From 379b917df8aa57de5c915c0fd84ffbd3377008e0 Mon Sep 17 00:00:00 2001 From: Christophe Fergeau Date: Tue, 20 Aug 2024 11:48:25 +0200 Subject: [PATCH] deps: Update golangci-lint to latest version Signed-off-by: Christophe Fergeau --- tools/go.mod | 174 +- tools/go.sum | 446 +- .../github.com/Abirdcfly/dupword/dupword.go | 4 +- .../Antonboom/nilnil/pkg/analyzer/analyzer.go | 136 +- .../Antonboom/nilnil/pkg/analyzer/config.go | 28 +- .../testifylint/analyzer/analyzer.go | 88 +- .../testifylint/analyzer/checkers_factory.go | 41 +- .../internal/analysisutil/object.go | 2 +- .../internal/checkers/blank_import.go | 69 + .../internal/checkers/bool_compare.go | 149 +- .../internal/checkers/call_meta.go | 133 + .../testifylint/internal/checkers/checker.go | 36 - .../internal/checkers/checkers_registry.go | 10 +- .../testifylint/internal/checkers/compares.go | 52 +- .../testifylint/internal/checkers/empty.go | 123 +- .../internal/checkers/error_is_as.go | 70 +- .../internal/checkers/error_nil.go | 55 +- .../internal/checkers/expected_actual.go | 117 +- .../internal/checkers/float_compare.go | 53 +- .../internal/checkers/formatter.go | 187 + .../internal/checkers/go_require.go | 345 + .../testifylint/internal/checkers/helpers.go | 43 + .../internal/checkers/helpers_basic_type.go | 113 + .../internal/checkers/helpers_bool.go | 33 + .../internal/checkers/helpers_comparison.go | 68 + .../internal/checkers/helpers_context.go | 126 + .../{diagnostic.go => helpers_diagnostic.go} | 20 + .../internal/checkers/helpers_error.go | 42 + .../internal/checkers/helpers_format.go | 26 + .../internal/checkers/helpers_http.go | 35 + .../internal/checkers/helpers_interface.go | 48 + .../internal/checkers/helpers_len.go | 55 + .../internal/checkers/helpers_naming.go | 26 + .../internal/checkers/helpers_nil.go | 18 + .../internal/checkers/helpers_suite.go | 40 + .../internal/checkers/helpers_testing.go | 36 + .../testifylint/internal/checkers/len.go | 42 +- .../internal/checkers/negative_postive.go | 175 + .../internal/checkers/nil_compare.go | 56 + .../internal/checkers/printf}/LICENSE | 2 +- .../internal/checkers/printf/doc.go | 6 + .../internal/checkers/printf/printf.go | 559 + .../internal/checkers/require_error.go | 253 +- .../checkers/suite_broken_parallel.go | 89 + .../internal/checkers/suite_dont_use_pkg.go | 20 +- .../checkers/suite_extra_assert_call.go | 6 +- .../internal/checkers/suite_subtest_run.go | 60 + .../internal/checkers/suite_thelper.go | 69 +- .../internal/checkers/useless_assert.go | 88 + .../testifylint/internal/config/config.go | 115 +- .../internal/config/flag_value_types.go | 9 + .../testifylint/internal/testify/const.go | 4 + .../github.com/BurntSushi/toml/README.md | 2 +- .../github.com/BurntSushi/toml/decode.go | 101 +- .../BurntSushi/toml/decode_go116.go | 19 - .../github.com/BurntSushi/toml/deprecated.go | 12 +- .../vendor/github.com/BurntSushi/toml/doc.go | 3 - .../github.com/BurntSushi/toml/encode.go | 45 +- .../github.com/BurntSushi/toml/error.go | 164 +- .../vendor/github.com/BurntSushi/toml/lex.go | 56 +- .../vendor/github.com/BurntSushi/toml/meta.go | 49 +- .../github.com/BurntSushi/toml/parse.go | 283 +- .../github.com/BurntSushi/toml/type_fields.go | 8 +- .../github.com/BurntSushi/toml/type_toml.go | 11 +- .../fatcontext}/LICENSE | 2 +- .../fatcontext/pkg/analyzer/analyzer.go | 195 + .../go-exhaustruct/v3/analyzer/analyzer.go | 120 +- .../v3/internal/comment/cache.go | 35 + .../v3/internal/comment/directive.go | 28 + .../v3/internal/structure/fields-cache.go | 35 + .../{fields/struct.go => structure/fields.go} | 43 +- .../github.com/Masterminds/semver/.travis.yml | 29 - .../Masterminds/semver/CHANGELOG.md | 109 - .../github.com/Masterminds/semver/Makefile | 36 - .../github.com/Masterminds/semver/README.md | 194 - .../Masterminds/semver/appveyor.yml | 44 - .../Masterminds/semver/constraints.go | 423 - .../github.com/Masterminds/semver/doc.go | 115 - .../Masterminds/semver/v3/.gitignore | 1 + .../Masterminds/semver/v3/.golangci.yml | 27 + .../Masterminds/semver/v3/CHANGELOG.md | 214 + .../Masterminds/semver/{ => v3}/LICENSE.txt | 0 .../github.com/Masterminds/semver/v3/Makefile | 30 + .../Masterminds/semver/v3/README.md | 258 + .../Masterminds/semver/v3/SECURITY.md | 19 + .../Masterminds/semver/{ => v3}/collection.go | 0 .../Masterminds/semver/v3/constraints.go | 594 + .../github.com/Masterminds/semver/v3/doc.go | 184 + .../Masterminds/semver/{ => v3}/version.go | 288 +- .../Masterminds/semver/version_fuzz.go | 10 - .../OpenPeeDeeP/depguard/v2/.gitignore | 1 + .../OpenPeeDeeP/depguard/v2/README.md | 25 +- .../OpenPeeDeeP/depguard/v2/settings.go | 53 +- .../alecthomas/go-check-sumtype/decl.go | 1 + .../alecthomas/go-check-sumtype/def.go | 16 + .../bombsimon/wsl/{v3 => v4}/.gitignore | 2 + .../bombsimon/wsl/{v3 => v4}/.golangci.yml | 22 +- .../bombsimon/wsl/{v3 => v4}/LICENSE | 0 .../bombsimon/wsl/{v3 => v4}/README.md | 84 +- .../github.com/bombsimon/wsl/v4/analyzer.go | 148 + .../bombsimon/wsl/{v3 => v4}/wsl.go | 754 +- .../butuzov/ireturn/analyzer/analyzer.go | 79 +- .../ireturn/analyzer/internal/types/iface.go | 11 +- .../butuzov/ireturn/analyzer/std.go | 3 + .../butuzov/ireturn/analyzer/typeparams.go | 38 - tools/vendor/github.com/butuzov/mirror/.act | 2 - .../butuzov/mirror/.goreleaser.yaml | 41 +- .../github.com/butuzov/mirror/MIRROR_FUNCS.md | 213 +- .../vendor/github.com/butuzov/mirror/Makefile | 135 +- .../github.com/butuzov/mirror/Taskfile.yml | 95 +- .../butuzov/mirror/checkers_bufio.go | 20 +- .../butuzov/mirror/checkers_bytes.go | 47 +- .../butuzov/mirror/checkers_httptest.go | 4 +- .../butuzov/mirror/checkers_maphash.go | 4 +- .../github.com/butuzov/mirror/checkers_os.go | 4 +- .../butuzov/mirror/checkers_regexp.go | 24 +- .../butuzov/mirror/checkers_strings.go | 49 +- .../butuzov/mirror/checkers_utf8.go | 20 +- .../mirror/internal/checker/violation.go | 11 +- .../github.com/butuzov/mirror/readme.md | 62 +- .../perfsprint/analyzer/analyzer.go | 328 +- .../ccojocar/zxcvbn-go/match/match.go | 3 +- .../ccojocar/zxcvbn-go/renovate.json | 25 + .../ccojocar/zxcvbn-go/scoring/scoring.go | 3 +- .../github.com/ckaznocha/intrange/.gitignore | 191 + .../ckaznocha/intrange/.golangci.yml | 99 + .../ckaznocha/intrange/CONTRIBUTING.md | 25 + .../intrange}/LICENSE | 16 +- .../github.com/ckaznocha/intrange/README.md | 90 + .../github.com/ckaznocha/intrange/SECURITY.md | 5 + .../github.com/ckaznocha/intrange/go.work | 6 + .../github.com/ckaznocha/intrange/intrange.go | 388 + .../daixiang0/gci/pkg/config/config.go | 34 +- .../daixiang0/gci/pkg/gci/testdata.go | 55 +- .../daixiang0/gci/pkg/parse/parse.go | 3 + .../daixiang0/gci/pkg/section/alias.go | 25 + .../daixiang0/gci/pkg/section/local_module.go | 59 + .../daixiang0/gci/pkg/section/parser.go | 5 + .../gci/pkg/section/standard_list.go | 6 +- .../gci/pkg/specificity/local_module.go | 15 + .../gci/pkg/specificity/specificity.go | 11 +- .../denis-tingaikin/go-header/.go-header.yml | 2 +- .../denis-tingaikin/go-header/README.md | 4 +- .../denis-tingaikin/go-header/analyzer.go | 134 +- .../denis-tingaikin/go-header/config.go | 10 +- .../denis-tingaikin/go-header/issue.go | 21 +- .../denis-tingaikin/go-header/value.go | 34 +- .../esimonov/ifshort/pkg/analyzer/analyzer.go | 280 - .../ifshort/pkg/analyzer/occurrences.go | 268 - .../github.com/ettle/strcase/.golangci.yml | 8 +- .../github.com/ettle/strcase/.readme.tmpl | 8 +- .../vendor/github.com/ettle/strcase/Makefile | 9 +- .../vendor/github.com/ettle/strcase/README.md | 143 +- .../vendor/github.com/ettle/strcase/assert.go | 24 + .../vendor/github.com/ettle/strcase/caser.go | 16 +- .../github.com/ettle/strcase/convert.go | 29 +- tools/vendor/github.com/ettle/strcase/doc.go | 181 +- .../vendor/github.com/ettle/strcase/split.go | 1 + tools/vendor/github.com/fatih/color/color.go | 61 +- .../nonamedreturns/analyzer/analyzer.go | 5 + .../github.com/ghostiam/protogetter/Makefile | 2 +- .../ghostiam/protogetter/processor.go | 137 +- .../ghostiam/protogetter/protogetter.go | 130 +- .../checkers/commentFormatting_checker.go | 16 +- .../checkers/commentedOutCode_checker.go | 11 +- .../go-critic/checkers/dupImports_checker.go | 2 +- .../go-critic/checkers/flagName_checker.go | 6 +- .../go-critic/checkers/hugeParam_checker.go | 20 + .../checkers/internal/lintutil/astflow.go | 2 +- .../go-critic/checkers/mapKey_checker.go | 2 +- .../go-critic/checkers/rulesdata/rulesdata.go | 1325 +- .../go-critic/checkers/typeUnparen_checker.go | 2 +- .../go-critic/checkers/unlambda_checker.go | 19 +- .../checkers/unnecessaryDefer_checker.go | 2 +- .../go-critic/go-critic/checkers/utils.go | 4 +- .../go-toolsmith/astequal/astequal.go | 28 +- .../github.com/go-toolsmith/astequal/diff.go | 23 + .../go-viper/mapstructure/v2/.editorconfig | 18 + .../go-viper/mapstructure/v2/.envrc | 4 + .../go-viper/mapstructure/v2/.gitignore | 6 + .../go-viper/mapstructure/v2/.golangci.yaml | 23 + .../go-viper/mapstructure/v2/CHANGELOG.md | 104 + .../go-viper/mapstructure/v2/LICENSE | 21 + .../go-viper/mapstructure/v2/README.md | 80 + .../go-viper/mapstructure/v2/decode_hooks.go | 577 + .../go-viper/mapstructure/v2/flake.lock | 472 + .../go-viper/mapstructure/v2/flake.nix | 39 + .../mapstructure/v2/internal/errors/errors.go | 11 + .../mapstructure/v2/internal/errors/join.go | 9 + .../v2/internal/errors/join_go1_19.go | 61 + .../go-viper/mapstructure/v2/mapstructure.go | 1576 ++ .../mapstructure/v2/reflect_go1_19.go | 44 + .../mapstructure/v2/reflect_go1_20.go | 10 + .../github.com/gofrs/flock/.golangci.yml | 114 + .../vendor/github.com/gofrs/flock/.travis.yml | 10 - tools/vendor/github.com/gofrs/flock/LICENSE | 1 + tools/vendor/github.com/gofrs/flock/Makefile | 15 + tools/vendor/github.com/gofrs/flock/README.md | 32 +- .../vendor/github.com/gofrs/flock/SECURITY.md | 21 + .../github.com/gofrs/flock/appveyor.yml | 25 - tools/vendor/github.com/gofrs/flock/build.sh | 18 + tools/vendor/github.com/gofrs/flock/flock.go | 110 +- .../github.com/gofrs/flock/flock_aix.go | 281 - .../github.com/gofrs/flock/flock_others.go | 40 + .../github.com/gofrs/flock/flock_unix.go | 179 +- .../gofrs/flock/flock_unix_fcntl.go | 393 + .../github.com/gofrs/flock/flock_winapi.go | 76 - .../github.com/gofrs/flock/flock_windows.go | 122 +- .../check/cmd/structcheck/structcheck.go | 193 - .../golangci/check/cmd/varcheck/varcheck.go | 163 - .../github.com/golangci/go-misc/LICENSE | 27 - .../golangci/go-misc/deadcode/README.md | 18 - .../golangci/go-misc/deadcode/deadcode.go | 138 - .../golangci-lint/cmd/golangci-lint/main.go | 64 +- .../cmd/golangci-lint/plugins.go | 3 + .../golangci-lint/pkg/commands/cache.go | 52 +- .../golangci-lint/pkg/commands/config.go | 111 +- .../pkg/commands/config_verify.go | 180 + .../golangci-lint/pkg/commands/custom.go | 79 + .../golangci-lint/pkg/commands/executor.go | 253 - .../golangci-lint/pkg/commands/flagsets.go | 146 + .../golangci-lint/pkg/commands/help.go | 126 +- .../pkg/commands/internal/builder.go | 250 + .../pkg/commands/internal/configuration.go | 140 + .../pkg/commands/internal/imports.go | 69 + .../pkg/commands/internal/vibra.go | 59 + .../golangci-lint/pkg/commands/linters.go | 88 +- .../golangci-lint/pkg/commands/root.go | 247 +- .../golangci-lint/pkg/commands/run.go | 898 +- .../golangci-lint/pkg/commands/version.go | 119 +- .../golangci-lint/pkg/config/config.go | 67 +- .../golangci-lint/pkg/config/issues.go | 103 +- .../golangci-lint/pkg/config/linters.go | 54 + .../pkg/config/linters_settings.go | 461 +- .../golangci-lint/pkg/config/loader.go | 490 + .../golangci-lint/pkg/config/output.go | 102 +- .../golangci-lint/pkg/config/reader.go | 248 - .../golangci/golangci-lint/pkg/config/run.go | 51 +- .../golangci-lint/pkg/config/severity.go | 23 + .../golangci-lint/pkg/fsutils/fsutils.go | 18 +- .../pkg/{golinters => }/goanalysis/issue.go | 5 +- .../pkg/{golinters => }/goanalysis/linter.go | 4 +- .../{golinters => }/goanalysis/load/guard.go | 0 .../{golinters => }/goanalysis/metalinter.go | 8 +- .../pkgerrors}/errors.go | 26 +- .../pkgerrors/extract.go} | 6 +- .../pkgerrors/parse.go} | 23 +- .../pkg/{golinters => }/goanalysis/runner.go | 36 +- .../goanalysis/runner_action.go | 14 +- .../goanalysis/runner_facts.go | 0 .../goanalysis/runner_loadingpackage.go | 2 +- .../pkg/{golinters => }/goanalysis/runners.go | 36 +- .../golinters/{ => asasalint}/asasalint.go | 9 +- .../golangci-lint/pkg/golinters/asciicheck.go | 17 - .../pkg/golinters/asciicheck/asciicheck.go | 19 + .../pkg/golinters/{ => bidichk}/bidichk.go | 8 +- .../golinters/{ => bodyclose}/bodyclose.go | 12 +- .../canonicalheader/canonicalheader.go | 19 + .../golangci-lint/pkg/golinters/commons.go | 6 - .../{ => containedctx}/containedctx.go | 6 +- .../{ => contextcheck}/contextcheck.go | 6 +- .../pkg/golinters/copyloopvar/copyloopvar.go | 29 + .../pkg/golinters/{ => cyclop}/cyclop.go | 10 +- .../golangci-lint/pkg/golinters/deadcode.go | 61 - .../pkg/golinters/{ => decorder}/decorder.go | 6 +- .../pkg/golinters/{ => depguard}/depguard.go | 11 +- .../pkg/golinters/{ => dogsled}/dogsled.go | 15 +- .../pkg/golinters/{ => dupl}/dupl.go | 20 +- .../pkg/golinters/{ => dupword}/dupword.go | 6 +- .../{ => durationcheck}/durationcheck.go | 6 +- .../{goerr113.go => err113/err113.go} | 12 +- .../pkg/golinters/{ => errcheck}/errcheck.go | 18 +- .../golinters/{ => errchkjson}/errchkjson.go | 12 +- .../golangci-lint/pkg/golinters/errname.go | 17 - .../pkg/golinters/errname/errname.go | 19 + .../golangci-lint/pkg/golinters/errorlint.go | 32 - .../pkg/golinters/errorlint/errorlint.go | 54 + .../{ => execinquery}/execinquery.go | 6 +- .../golinters/{ => exhaustive}/exhaustive.go | 7 +- .../pkg/golinters/exhaustivestruct.go | 31 - .../{ => exhaustruct}/exhaustruct.go | 9 +- .../{ => exportloopref}/exportloopref.go | 6 +- .../fatcontext.go} | 8 +- .../golinters/{ => forbidigo}/forbidigo.go | 17 +- .../{ => forcetypeassert}/forcetypeassert.go | 6 +- .../pkg/golinters/{ => funlen}/funlen.go | 15 +- .../pkg/golinters/{ => gci}/gci.go | 143 +- .../pkg/golinters/ginkgolinter.go | 34 - .../golinters/ginkgolinter/ginkgolinter.go | 39 + .../pkg/golinters/goanalysis/adapters.go | 41 - .../gocheckcompilerdirectives.go | 6 +- .../pkg/golinters/gochecknoglobals.go | 29 - .../gochecknoglobals/gochecknoglobals.go | 26 + .../{ => gochecknoinits}/gochecknoinits.go | 21 +- .../{ => gochecksumtype}/gochecksumtype.go | 16 +- .../pkg/golinters/{ => gocognit}/gocognit.go | 16 +- .../pkg/golinters/{ => goconst}/goconst.go | 21 +- .../golangci-lint/pkg/golinters/gocritic.go | 641 - .../pkg/golinters/gocritic/gocritic.go | 590 + .../pkg/golinters/{ => gocyclo}/gocyclo.go | 18 +- .../pkg/golinters/{ => godot}/godot.go | 17 +- .../pkg/golinters/{ => godox}/godox.go | 15 +- .../pkg/golinters/{ => gofmt}/gofmt.go | 29 +- .../pkg/golinters/{ => gofumpt}/gofumpt.go | 27 +- .../pkg/golinters/{ => goheader}/goheader.go | 25 +- .../golinters/{ => goimports}/goimports.go | 27 +- .../golangci-lint/pkg/golinters/golint.go | 84 - .../golangci-lint/pkg/golinters/gomnd.go | 45 - .../{ => gomoddirectives}/gomoddirectives.go | 15 +- .../golinters/{ => gomodguard}/gomodguard.go | 20 +- .../pkg/golinters/goprintffuncname.go | 17 - .../goprintffuncname/goprintffuncname.go | 19 + .../pkg/golinters/{ => gosec}/gosec.go | 30 +- .../golangci-lint/pkg/golinters/gosimple.go | 21 - .../pkg/golinters/gosimple/gosimple.go | 22 + .../{ => gosmopolitan}/gosmopolitan.go | 6 +- .../pkg/golinters/{ => govet}/govet.go | 84 +- .../pkg/golinters/{ => grouper}/grouper.go | 16 +- .../golangci-lint/pkg/golinters/ifshort.go | 28 - .../pkg/golinters/{ => importas}/importas.go | 10 +- .../pkg/golinters/inamedparam.go | 19 - .../pkg/golinters/inamedparam/inamedparam.go | 30 + .../{ => ineffassign}/ineffassign.go | 12 +- .../{ => interfacebloat}/interfacebloat.go | 6 +- .../golangci-lint/pkg/golinters/interfacer.go | 82 - .../pkg/golinters/internal/commons.go | 6 + .../{gofmt_common.go => internal/diff.go} | 39 +- .../{ => internal}/staticcheck_common.go | 12 +- .../pkg/golinters/{ => internal}/util.go | 14 +- .../pkg/golinters/intrange/intrange.go | 19 + .../pkg/golinters/{ => ireturn}/ireturn.go | 11 +- .../pkg/golinters/{ => lll}/lll.go | 29 +- .../{ => loggercheck}/loggercheck.go | 6 +- .../pkg/golinters/{ => maintidx}/maintidx.go | 6 +- .../pkg/golinters/{ => makezero}/makezero.go | 15 +- .../golangci-lint/pkg/golinters/maligned.go | 74 - .../pkg/golinters/{ => mirror}/mirror.go | 8 +- .../pkg/golinters/{ => misspell}/misspell.go | 86 +- .../golangci-lint/pkg/golinters/mnd/mnd.go | 63 + .../pkg/golinters/{ => musttag}/musttag.go | 8 +- .../golangci-lint/pkg/golinters/nakedret.go | 27 - .../pkg/golinters/nakedret/nakedret.go | 25 + .../pkg/golinters/{ => nestif}/nestif.go | 13 +- .../pkg/golinters/{ => nilerr}/nilerr.go | 6 +- .../pkg/golinters/{ => nilnil}/nilnil.go | 6 +- .../pkg/golinters/{ => nlreturn}/nlreturn.go | 6 +- .../golangci-lint/pkg/golinters/noctx.go | 17 - .../pkg/golinters/noctx/noctx.go | 19 + .../golangci-lint/pkg/golinters/nolintlint.go | 105 - .../nolintlint/{ => internal}/README.md | 6 +- .../nolintlint/internal/nolintlint.go | 304 + .../pkg/golinters/nolintlint/nolintlint.go | 350 +- .../{ => nonamedreturns}/nonamedreturns.go | 6 +- .../pkg/golinters/nosnakecase.go | 19 - .../nosprintfhostport.go | 6 +- .../pkg/golinters/paralleltest.go | 30 - .../golinters/paralleltest/paralleltest.go | 34 + .../pkg/golinters/perfsprint/perfsprint.go | 32 + .../pkg/golinters/{ => prealloc}/prealloc.go | 18 +- .../{ => predeclared}/predeclared.go | 6 +- .../golinters/{ => promlinter}/promlinter.go | 14 +- .../{ => protogetter}/protogetter.go | 25 +- .../pkg/golinters/{ => reassign}/reassign.go | 6 +- .../pkg/golinters/{ => revive}/revive.go | 99 +- .../pkg/golinters/rowserrcheck.go | 25 - .../golinters/rowserrcheck/rowserrcheck.go | 25 + .../golangci-lint/pkg/golinters/scopelint.go | 190 - .../pkg/golinters/{ => sloglint}/sloglint.go | 12 +- .../pkg/golinters/spancheck/spancheck.go | 33 + .../pkg/golinters/sqlclosecheck.go | 19 - .../golinters/sqlclosecheck/sqlclosecheck.go | 19 + .../{ => staticcheck}/staticcheck.go | 11 +- .../pkg/golinters/structcheck.go | 71 - .../golinters/{ => stylecheck}/stylecheck.go | 13 +- .../pkg/golinters/{ => tagalign}/tagalign.go | 6 +- .../{ => tagliatelle}/tagliatelle.go | 6 +- .../pkg/golinters/{ => tenv}/tenv.go | 6 +- .../testableexamples.go | 6 +- .../pkg/golinters/testifylint.go | 36 - .../pkg/golinters/testifylint/testifylint.go | 51 + .../{ => testpackage}/testpackage.go | 8 +- .../pkg/golinters/{ => thelper}/thelper.go | 19 +- .../golangci-lint/pkg/golinters/tparallel.go | 17 - .../pkg/golinters/tparallel/tparallel.go | 18 + .../golangci-lint/pkg/golinters/typecheck.go | 4 +- .../golinters/{ => unconvert}/unconvert.go | 35 +- .../pkg/golinters/{ => unparam}/unparam.go | 14 +- .../pkg/golinters/{ => unused}/unused.go | 31 +- .../{ => usestdlibvars}/usestdlibvars.go | 6 +- .../golangci-lint/pkg/golinters/varcheck.go | 72 - .../golinters/{ => varnamelen}/varnamelen.go | 6 +- .../pkg/golinters/wastedassign.go | 17 - .../golinters/wastedassign/wastedassign.go | 19 + .../golangci-lint/pkg/golinters/whitespace.go | 108 - .../pkg/golinters/whitespace/whitespace.go | 102 + .../golinters/{ => wrapcheck}/wrapcheck.go | 10 +- .../golangci-lint/pkg/golinters/wsl.go | 89 - .../golangci-lint/pkg/golinters/wsl/wsl.go | 40 + .../pkg/golinters/zerologlint.go | 17 - .../pkg/golinters/zerologlint/zerologlint.go | 19 + .../golangci/golangci-lint/pkg/goutil/env.go | 15 +- .../golangci-lint/pkg/lint/context.go | 64 + .../golangci-lint/pkg/lint/linter/config.go | 47 +- .../golangci-lint/pkg/lint/linter/context.go | 3 +- .../golangci-lint/pkg/lint/linter/linter.go | 46 +- .../pkg/lint/lintersdb/builder_linter.go | 841 + .../pkg/lint/lintersdb/builder_plugin_go.go | 138 + .../lint/lintersdb/builder_plugin_module.go | 85 + .../pkg/lint/lintersdb/custom_linters.go | 131 - .../pkg/lint/lintersdb/enabled_set.go | 223 - .../pkg/lint/lintersdb/manager.go | 1169 +- .../pkg/lint/lintersdb/validator.go | 110 +- .../pkg/lint/{load.go => package.go} | 361 +- .../golangci/golangci-lint/pkg/lint/runner.go | 233 +- .../golangci-lint/pkg/logutils/logutils.go | 12 + .../golangci-lint/pkg/logutils/mock.go | 55 +- .../golangci-lint/pkg/logutils/out.go | 6 +- .../golangci-lint/pkg/logutils/stderr_log.go | 2 +- .../golangci-lint/pkg/packages/skip.go | 25 - .../golangci-lint/pkg/printers/checkstyle.go | 6 +- .../printers/{github.go => githubaction.go} | 34 +- .../golangci-lint/pkg/printers/json.go | 2 +- .../golangci-lint/pkg/printers/junitxml.go | 6 +- .../golangci-lint/pkg/printers/printer.go | 138 +- .../golangci-lint/pkg/printers/sarif.go | 117 + .../golangci-lint/pkg/printers/tab.go | 12 +- .../golangci-lint/pkg/printers/teamcity.go | 14 +- .../golangci-lint/pkg/printers/text.go | 24 +- .../golangci-lint/pkg/result/issue.go | 4 +- .../processors/autogenerated_exclude.go | 153 +- .../pkg/result/processors/base_rule.go | 10 +- .../pkg/result/processors/cgo.go | 56 +- .../pkg/result/processors/diff.go | 36 +- .../pkg/result/processors/exclude.go | 58 +- .../pkg/result/processors/exclude_rules.go | 109 +- .../result/processors/filename_unadjuster.go | 116 +- .../pkg/result/processors/fixer.go | 82 +- .../result/processors/identifier_marker.go | 105 +- .../pkg/result/processors/invalid_issue.go | 60 + .../pkg/result/processors/issues.go | 35 +- .../pkg/result/processors/max_from_linter.go | 33 +- .../processors/max_per_file_from_linter.go | 48 +- .../pkg/result/processors/max_same_issues.go | 32 +- .../pkg/result/processors/nolint.go | 217 +- .../pkg/result/processors/path_prefixer.go | 4 +- .../pkg/result/processors/path_prettifier.go | 36 +- .../pkg/result/processors/path_shortener.go | 23 +- .../pkg/result/processors/processor.go | 2 + .../pkg/result/processors/severity.go | 116 + .../pkg/result/processors/severity_rules.go | 108 - .../pkg/result/processors/skip_dirs.go | 86 +- .../pkg/result/processors/skip_files.go | 17 +- .../pkg/result/processors/sort_results.go | 221 +- .../pkg/result/processors/source_code.go | 43 +- .../pkg/result/processors/uniq_by_line.go | 77 +- .../github.com/golangci/lint-1/.travis.yml | 19 - .../golangci/lint-1/CONTRIBUTING.md | 15 - .../vendor/github.com/golangci/lint-1/LICENSE | 27 - .../github.com/golangci/lint-1/README.md | 88 - .../vendor/github.com/golangci/lint-1/lint.go | 1655 -- .../github.com/golangci/maligned/README | 7 - .../github.com/golangci/maligned/maligned.go | 253 - .../golangci/misspell/.golangci.yml | 4 +- .../golangci/misspell/.pre-commit-hooks.yaml | 8 + .../github.com/golangci/misspell/Dockerfile | 2 +- .../github.com/golangci/misspell/Makefile | 2 +- .../github.com/golangci/misspell/README.md | 253 +- .../golangci/misspell/goreleaser.yml | 15 +- .../golangci/misspell/install-misspell.sh | 244 +- .../github.com/golangci/misspell/mime.go | 15 +- .../github.com/golangci/misspell/notwords.go | 27 +- .../github.com/golangci/misspell/replace.go | 12 +- .../golangci/misspell/stringreplacer.go | 23 +- .../github.com/golangci/misspell/url.go | 2 +- .../github.com/golangci/modinfo/.gitignore | 1 + .../github.com/golangci/modinfo/.golangci.yml | 157 + .../github.com/golangci/modinfo/LICENSE | 674 + .../github.com/golangci/modinfo/Makefile | 12 + .../github.com/golangci/modinfo/module.go | 157 + .../github.com/golangci/modinfo/readme.md | 73 + .../{check => plugin-module-register}/LICENSE | 16 +- .../register/register.go | 73 + .../github.com/golangci/revgrep/.golangci.yml | 4 +- .../github.com/golangci/revgrep/revgrep.go | 82 +- .../github.com/golangci/unconvert/README | 36 - .../github.com/golangci/unconvert/README.md | 6 + .../github.com/golangci/unconvert/golangci.go | 78 + .../golangci/unconvert/unconvert.go | 259 +- .../github.com/hashicorp/errwrap/LICENSE | 354 - .../github.com/hashicorp/errwrap/README.md | 89 - .../github.com/hashicorp/errwrap/errwrap.go | 169 - .../hashicorp/go-multierror/LICENSE | 353 - .../hashicorp/go-multierror/Makefile | 31 - .../hashicorp/go-multierror/README.md | 150 - .../hashicorp/go-multierror/append.go | 43 - .../hashicorp/go-multierror/flatten.go | 26 - .../hashicorp/go-multierror/format.go | 27 - .../hashicorp/go-multierror/group.go | 38 - .../hashicorp/go-multierror/multierror.go | 121 - .../hashicorp/go-multierror/prefix.go | 37 - .../hashicorp/go-multierror/sort.go | 16 - .../hashicorp/go-version/CHANGELOG.md | 19 + .../github.com/hashicorp/go-version/LICENSE | 2 + .../github.com/hashicorp/go-version/README.md | 2 +- .../hashicorp/go-version/constraint.go | 6 +- .../hashicorp/go-version/version.go | 46 +- .../go-version/version_collection.go | 3 + .../github.com/jgautheron/goconst/.gitignore | 2 - .../github.com/jgautheron/goconst/README.md | 1 + .../github.com/jgautheron/goconst/api.go | 2 + .../github.com/jgautheron/goconst/parser.go | 23 +- .../github.com/jgautheron/goconst/visitor.go | 4 + .../go-spancheck}/.gitignore | 4 + .../jjti/go-spancheck/.golangci.yml | 103 + .../jjti/go-spancheck/CONTRIBUTING.md | 51 + .../ifshort => jjti/go-spancheck}/LICENSE | 2 +- .../github.com/jjti/go-spancheck/Makefile | 27 + .../github.com/jjti/go-spancheck/README.md | 268 + .../github.com/jjti/go-spancheck/config.go | 223 + .../github.com/jjti/go-spancheck/doc.go | 37 + .../github.com/jjti/go-spancheck/go.work | 8 + .../github.com/jjti/go-spancheck/go.work.sum | 4 + .../github.com/jjti/go-spancheck/spancheck.go | 466 + .../karamaru-alpha/copyloopvar/.gitignore | 2 + .../copyloopvar}/LICENSE | 2 +- .../karamaru-alpha/copyloopvar/README.md | 27 + .../karamaru-alpha/copyloopvar/copyloopvar.go | 133 + .../kisielk/errcheck/errcheck/analyzer.go | 6 +- .../kisielk/errcheck/errcheck/errcheck.go | 6 +- .../kisielk/errcheck/errcheck/excludes.go | 80 +- .../github.com/kisielk/gotool/.travis.yml | 23 - tools/vendor/github.com/kisielk/gotool/LEGAL | 32 - .../vendor/github.com/kisielk/gotool/LICENSE | 20 - .../github.com/kisielk/gotool/README.md | 6 - .../vendor/github.com/kisielk/gotool/go13.go | 15 - .../github.com/kisielk/gotool/go14-15.go | 15 - .../github.com/kisielk/gotool/go16-18.go | 15 - .../kisielk/gotool/internal/load/path.go | 27 - .../kisielk/gotool/internal/load/pkg.go | 25 - .../kisielk/gotool/internal/load/search.go | 354 - .../vendor/github.com/kisielk/gotool/match.go | 56 - .../github.com/kisielk/gotool/match18.go | 317 - .../vendor/github.com/kisielk/gotool/tool.go | 48 - .../kkHAIKE/contextcheck/.gitignore | 2 + .../github.com/kkHAIKE/contextcheck/Makefile | 14 +- .../github.com/kkHAIKE/contextcheck/README.md | 10 +- .../kkHAIKE/contextcheck/contextcheck.go | 68 +- .../pkg/paralleltest/paralleltest.go | 59 +- .../lasiar/canonicalheader/.gitignore | 1 + .../lasiar/canonicalheader/.golangci.yaml | 802 + .../lasiar/canonicalheader/.goreleaser.yaml | 18 + .../github.com/lasiar/canonicalheader/LICENCE | 21 + .../lasiar/canonicalheader/README.md | 77 + .../lasiar/canonicalheader/analyzer.go | 264 + .../lasiar/canonicalheader/constant_string.go | 50 + .../lasiar/canonicalheader/initialism.go | 75 + .../lasiar/canonicalheader/literal_string.go | 80 + .../lasiar/canonicalheader/makefile | 12 + .../ldez/gomoddirectives/.golangci.yml | 38 +- .../github.com/ldez/gomoddirectives/Makefile | 2 +- .../github.com/ldez/gomoddirectives/module.go | 2 +- .../grouper/pkg/analyzer/analyzer.go | 4 +- .../github.com/macabu/inamedparam/.gitignore | 1 + .../macabu/inamedparam/.golangci.yml | 33 + .../github.com/macabu/inamedparam/README.md | 22 +- .../macabu/inamedparam/inamedparam.go | 33 +- .../github.com/mattn/go-isatty/isatty_bsd.go | 3 +- .../mattn/go-isatty/isatty_others.go | 5 +- .../mattn/go-isatty/isatty_tcgets.go | 3 +- .../exhaustivestruct/pkg/analyzer/analyzer.go | 187 - .../mgechev/revive/config/config.go | 23 +- .../mgechev/revive/formatter/checkstyle.go | 4 +- .../mgechev/revive/formatter/default.go | 6 +- .../mgechev/revive/formatter/doc.go | 2 + .../mgechev/revive/formatter/friendly.go | 46 +- .../mgechev/revive/formatter/ndjson.go | 7 +- .../mgechev/revive/formatter/plain.go | 6 +- .../mgechev/revive/formatter/unix.go | 9 +- .../github.com/mgechev/revive/lint/config.go | 12 +- .../github.com/mgechev/revive/lint/doc.go | 2 + .../github.com/mgechev/revive/lint/linter.go | 95 +- .../github.com/mgechev/revive/lint/package.go | 14 +- .../github.com/mgechev/revive/lint/utils.go | 11 +- .../mgechev/revive/rule/add-constant.go | 68 +- .../mgechev/revive/rule/comment-spacings.go | 15 +- .../mgechev/revive/rule/comments-density.go | 95 + .../mgechev/revive/rule/confusing-naming.go | 29 +- .../revive/rule/constant-logical-expr.go | 8 +- .../revive/rule/context-as-argument.go | 2 +- .../mgechev/revive/rule/datarace.go | 12 +- .../github.com/mgechev/revive/rule/defer.go | 4 +- .../github.com/mgechev/revive/rule/doc.go | 2 + .../mgechev/revive/rule/dot-imports.go | 65 +- .../mgechev/revive/rule/early-return.go | 2 +- .../mgechev/revive/rule/enforce-map-style.go | 6 +- .../rule/enforce-repeated-arg-type-style.go | 191 + .../revive/rule/enforce-slice-style.go | 214 + .../mgechev/revive/rule/flag-param.go | 2 +- .../mgechev/revive/rule/function-length.go | 2 +- .../revive/rule/import-alias-naming.go | 79 +- ...orts-blacklist.go => imports-blocklist.go} | 36 +- .../mgechev/revive/rule/indent-error-flow.go | 2 +- .../revive/rule/max-control-nesting.go | 128 + .../revive/rule/modifies-value-receiver.go | 7 +- .../revive/rule/optimize-operands-order.go | 17 +- .../mgechev/revive/rule/package-comments.go | 12 +- .../mgechev/revive/rule/range-val-address.go | 4 + .../revive/rule/range-val-in-closure.go | 4 + .../mgechev/revive/rule/string-format.go | 6 +- .../mgechev/revive/rule/struct-tag.go | 2 +- .../mgechev/revive/rule/superfluous-else.go | 2 +- .../revive/rule/unconditional-recursion.go | 32 +- .../mgechev/revive/rule/unhandled-error.go | 2 +- .../mgechev/revive/rule/unused-param.go | 78 +- .../mgechev/revive/rule/unused-receiver.go | 4 +- .../github.com/mgechev/revive/rule/utils.go | 18 +- .../mgechev/revive/rule/var-naming.go | 73 +- .../moricho/tparallel/.goreleaser.yaml | 18 +- .../github.com/moricho/tparallel/README.md | 2 +- .../github.com/moricho/tparallel/testmap.go | 4 + .../nishanths/exhaustive/comment.go | 39 +- .../nishanths/exhaustive/comment_go121.go | 11 + .../nishanths/exhaustive/comment_pre_go121.go | 27 + .../github.com/nishanths/exhaustive/doc.go | 5 +- .../nishanths/exhaustive/exhaustive.go | 5 + .../github.com/nishanths/exhaustive/switch.go | 75 +- .../github.com/nunnatsa/ginkgolinter/Makefile | 5 +- .../nunnatsa/ginkgolinter/README.md | 156 +- .../nunnatsa/ginkgolinter/analyzer.go | 58 + .../github.com/nunnatsa/ginkgolinter/doc.go | 99 + .../{ => internal}/ginkgohandler/handler.go | 40 +- .../{ => internal}/gomegahandler/handler.go | 13 +- .../internal/interfaces/interfaces.go | 76 + .../internal/intervals/intervals.go | 285 + .../internal/reports/report-builder.go | 98 + .../reverseassertion/reverse_assertion.go | 0 .../{ => linter}/ginkgo_linter.go | 807 +- .../nunnatsa/ginkgolinter/types/config.go | 41 +- .../pelletier/go-toml/v2/.gitignore | 3 +- .../pelletier/go-toml/v2/.goreleaser.yaml | 3 + .../pelletier/go-toml/v2/CONTRIBUTING.md | 31 +- .../github.com/pelletier/go-toml/v2/LICENSE | 3 +- .../github.com/pelletier/go-toml/v2/README.md | 172 +- .../pelletier/go-toml/v2/SECURITY.md | 3 - .../github.com/pelletier/go-toml/v2/ci.sh | 23 +- .../github.com/pelletier/go-toml/v2/decode.go | 90 +- .../github.com/pelletier/go-toml/v2/errors.go | 32 +- .../go-toml/v2/internal/ast/builder.go | 51 - .../go-toml/v2/internal/characters/ascii.go | 42 + .../v2/{ => internal/characters}/utf8.go | 53 +- .../go-toml/v2/internal/tracker/key.go | 12 +- .../go-toml/v2/internal/tracker/seen.go | 90 +- .../pelletier/go-toml/v2/localtime.go | 6 +- .../pelletier/go-toml/v2/marshaler.go | 109 +- .../github.com/pelletier/go-toml/v2/strict.go | 34 +- .../github.com/pelletier/go-toml/v2/types.go | 10 +- .../pelletier/go-toml/v2/unmarshaler.go | 260 +- .../v2/{internal/ast => unstable}/ast.go | 68 +- .../pelletier/go-toml/v2/unstable/builder.go | 71 + .../pelletier/go-toml/v2/unstable/doc.go | 3 + .../v2/{internal/ast => unstable}/kind.go | 12 +- .../go-toml/v2/{ => unstable}/parser.go | 421 +- .../go-toml/v2/{ => unstable}/scanner.go | 51 +- .../go-toml/v2/unstable/unmarshaler.go | 7 + .../go-errorlint/errorlint/allowed.go | 183 +- .../go-errorlint/errorlint/analysis.go | 35 +- .../polyfloyd/go-errorlint/errorlint/lint.go | 61 +- .../go-errorlint/errorlint/options.go | 15 + .../go-errorlint/errorlint/printf.go | 17 - .../quasilyte/go-ruleguard/dsl/LICENSE | 29 + .../quasilyte/go-ruleguard/dsl/bundle.go | 19 + .../quasilyte/go-ruleguard/dsl/do.go | 19 + .../quasilyte/go-ruleguard/dsl/dsl.go | 361 + .../quasilyte/go-ruleguard/dsl/filter.go | 24 + .../quasilyte/go-ruleguard/dsl/internal.go | 6 + .../quasilyte/go-ruleguard/dsl/types/ext.go | 21 + .../go-ruleguard/dsl/types/type_impl.go | 17 + .../quasilyte/go-ruleguard/dsl/types/types.go | 68 + .../go-ruleguard/ruleguard/ir_loader.go | 2 +- .../ruleguard/textmatch/textmatch.go | 2 +- .../quasilyte/go-ruleguard/ruleguard/utils.go | 2 +- .../ryancurrah/gomodguard/.golangci.yml | 128 +- .../ryancurrah/gomodguard/.goreleaser.yml | 8 + .../github.com/ryancurrah/gomodguard/Makefile | 4 +- .../ryancurrah/gomodguard/README.md | 2 +- .../ryancurrah/gomodguard/blocked.go | 16 +- .../ryancurrah/gomodguard/processor.go | 39 +- .../github.com/ryancurrah/gomodguard/tools.go | 5 - .../santhosh-tekuri/jsonschema/v5/.gitignore | 4 + .../santhosh-tekuri/jsonschema/v5/.gitmodules | 3 + .../santhosh-tekuri/jsonschema/v5/LICENSE | 175 + .../santhosh-tekuri/jsonschema/v5/README.md | 220 + .../santhosh-tekuri/jsonschema/v5/compiler.go | 812 + .../santhosh-tekuri/jsonschema/v5/content.go | 29 + .../santhosh-tekuri/jsonschema/v5/doc.go | 49 + .../santhosh-tekuri/jsonschema/v5/draft.go | 1454 ++ .../santhosh-tekuri/jsonschema/v5/errors.go | 129 + .../jsonschema/v5/extension.go | 116 + .../santhosh-tekuri/jsonschema/v5/format.go | 567 + .../jsonschema/v5/httploader/httploader.go | 38 + .../santhosh-tekuri/jsonschema/v5/loader.go | 60 + .../santhosh-tekuri/jsonschema/v5/output.go | 77 + .../santhosh-tekuri/jsonschema/v5/resource.go | 280 + .../santhosh-tekuri/jsonschema/v5/schema.go | 900 + .../usestdlibvars/pkg/analyzer/analyzer.go | 76 +- .../securego/gosec/v2/.goreleaser.yml | 1 + .../github.com/securego/gosec/v2/Makefile | 4 +- .../github.com/securego/gosec/v2/README.md | 22 +- .../github.com/securego/gosec/v2/action.yml | 2 +- .../github.com/securego/gosec/v2/analyzer.go | 49 +- .../github.com/securego/gosec/v2/helpers.go | 52 +- .../securego/gosec/v2/import_tracker.go | 8 + .../securego/gosec/v2/rules/fileperms.go | 14 +- .../gosec/v2/rules/hardcoded_credentials.go | 4 - .../gosec/v2/rules/implicit_aliasing.go | 6 + .../securego/gosec/v2/rules/rand.go | 24 +- .../securego/gosec/v2/rules/readfile.go | 1 + .../sivchari/nosnakecase/.golangci.yml | 40 - .../github.com/sivchari/nosnakecase/README.md | 224 - .../sivchari/nosnakecase/nosnakecase.go | 63 - .../vendor/github.com/sivchari/tenv/README.md | 12 +- tools/vendor/github.com/sivchari/tenv/tenv.go | 33 +- .../vendor/github.com/spf13/afero/.travis.yml | 26 - tools/vendor/github.com/spf13/afero/README.md | 2 +- tools/vendor/github.com/spf13/afero/afero.go | 6 +- .../github.com/spf13/afero/appveyor.yml | 9 +- .../vendor/github.com/spf13/afero/basepath.go | 13 +- .../github.com/spf13/afero/const_bsds.go | 3 +- .../github.com/spf13/afero/const_win_unix.go | 8 +- .../github.com/spf13/afero/copyOnWriteFs.go | 9 +- tools/vendor/github.com/spf13/afero/httpFs.go | 2 +- .../spf13/afero/internal/common/adapters.go | 27 + tools/vendor/github.com/spf13/afero/iofs.go | 38 +- tools/vendor/github.com/spf13/afero/ioutil.go | 19 +- .../vendor/github.com/spf13/afero/mem/file.go | 37 +- tools/vendor/github.com/spf13/afero/memmap.go | 73 +- .../vendor/github.com/spf13/afero/regexpfs.go | 1 - .../vendor/github.com/spf13/afero/symlink.go | 6 +- .../github.com/spf13/afero/unionFile.go | 9 +- tools/vendor/github.com/spf13/afero/util.go | 17 +- .../github.com/spf13/cobra/.golangci.yml | 29 +- tools/vendor/github.com/spf13/cobra/README.md | 8 +- .../github.com/spf13/cobra/active_help.go | 13 +- .../github.com/spf13/cobra/active_help.md | 157 - tools/vendor/github.com/spf13/cobra/args.go | 4 +- .../spf13/cobra/bash_completions.go | 27 +- .../spf13/cobra/bash_completions.md | 93 - .../spf13/cobra/bash_completionsV2.go | 2 +- tools/vendor/github.com/spf13/cobra/cobra.go | 15 +- .../vendor/github.com/spf13/cobra/command.go | 118 +- .../github.com/spf13/cobra/completions.go | 91 +- .../spf13/cobra/fish_completions.go | 2 +- .../spf13/cobra/fish_completions.md | 4 - .../github.com/spf13/cobra/flag_groups.go | 86 +- .../spf13/cobra/powershell_completions.go | 10 +- .../spf13/cobra/powershell_completions.md | 3 - .../spf13/cobra/projects_using_cobra.md | 64 - .../spf13/cobra/shell_completions.md | 576 - .../github.com/spf13/cobra/user_guide.md | 726 - .../github.com/spf13/cobra/zsh_completions.md | 48 - .../vendor/github.com/stretchr/objx/README.md | 8 +- .../github.com/stretchr/objx/Taskfile.yml | 5 +- .../github.com/stretchr/objx/accessors.go | 24 +- .../github.com/stretchr/objx/conversions.go | 4 +- tools/vendor/github.com/stretchr/objx/doc.go | 44 +- tools/vendor/github.com/stretchr/objx/map.go | 9 +- .../testify/assert/assertion_compare.go | 28 +- .../assert/assertion_compare_can_convert.go | 16 - .../assert/assertion_compare_legacy.go | 16 - .../testify/assert/assertion_format.go | 32 +- .../testify/assert/assertion_forward.go | 59 +- .../stretchr/testify/assert/assertions.go | 207 +- .../testify/assert/http_assertions.go | 27 +- .../github.com/stretchr/testify/mock/mock.go | 129 +- .../t-yuki/gocover-cobertura/.travis.yml | 12 - .../t-yuki/gocover-cobertura/README.md | 35 - .../t-yuki/gocover-cobertura/cobertura.go | 178 - .../gocover-cobertura/gocover-cobertura.go | 176 - .../t-yuki/gocover-cobertura/profile.go | 202 - .../github.com/tetafro/godot/.golangci.yml | 50 +- .../vendor/github.com/tetafro/godot/checks.go | 186 +- .../github.com/tetafro/godot/getters.go | 24 +- .../vendor/github.com/tetafro/godot/godot.go | 25 +- .../wrapcheck/v2/wrapcheck/wrapcheck.go | 24 + .../github.com/ultraware/whitespace/README.md | 4 +- .../github.com/ultraware/whitespace/main.go | 162 - .../ultraware/whitespace/whitespace.go | 307 + .../github.com/uudashr/gocognit/README.md | 6 +- .../yeya24/promlinter/promlinter.go | 237 +- .../ykadowak/zerologlint/.goreleaser.yaml | 7 - .../ykadowak/zerologlint/zerologlint.go | 102 +- .../gitlab.com/bosi/decorder/.gitlab-ci.yml | 8 +- .../musttag/.golangci.yml | 0 .../musttag/.goreleaser.yml | 9 - .../musttag/LICENSE | 0 tools/vendor/go-simpler.org/musttag/Makefile | 28 + tools/vendor/go-simpler.org/musttag/README.md | 102 + .../vendor/go-simpler.org/musttag/builtins.go | 133 + .../vendor/go-simpler.org/musttag/musttag.go | 282 + tools/vendor/go-simpler.org/musttag/utils.go | 49 + tools/vendor/go-simpler.org/sloglint/Makefile | 28 + .../vendor/go-simpler.org/sloglint/README.md | 130 +- .../go-simpler.org/sloglint/sloglint.go | 394 +- tools/vendor/go.tmz.dev/musttag/README.md | 106 - tools/vendor/go.tmz.dev/musttag/builtins.go | 67 - tools/vendor/go.tmz.dev/musttag/musttag.go | 259 - tools/vendor/go.tmz.dev/musttag/utils.go | 57 - tools/vendor/go.uber.org/automaxprocs/LICENSE | 19 + .../automaxprocs/internal/cgroups/cgroup.go | 79 + .../automaxprocs/internal/cgroups/cgroups.go | 118 + .../automaxprocs/internal/cgroups/cgroups2.go | 176 + .../automaxprocs/internal/cgroups/doc.go | 23 + .../automaxprocs/internal/cgroups/errors.go | 52 + .../internal/cgroups/mountpoint.go | 171 + .../automaxprocs/internal/cgroups/subsys.go | 103 + .../internal/runtime/cpu_quota_linux.go | 71 + .../internal/runtime/cpu_quota_unsupported.go | 31 + .../automaxprocs/internal/runtime/runtime.go | 33 + .../automaxprocs/maxprocs/maxprocs.go | 130 + .../automaxprocs/maxprocs/version.go | 24 + tools/vendor/golang.org/x/exp/maps/maps.go | 94 + tools/vendor/golang.org/x/exp/slices/cmp.go | 44 + .../vendor/golang.org/x/exp/slices/slices.go | 353 +- tools/vendor/golang.org/x/exp/slices/sort.go | 115 +- .../slices/{zsortfunc.go => zsortanyfunc.go} | 154 +- .../golang.org/x/exp/slices/zsortordered.go | 34 +- .../x/exp/typeparams/typeparams_go117.go | 1 - .../x/exp/typeparams/typeparams_go118.go | 1 - tools/vendor/golang.org/x/mod/LICENSE | 4 +- tools/vendor/golang.org/x/mod/modfile/read.go | 9 +- tools/vendor/golang.org/x/mod/modfile/rule.go | 203 +- tools/vendor/golang.org/x/mod/modfile/work.go | 54 +- tools/vendor/golang.org/x/sync/LICENSE | 4 +- .../golang.org/x/sync/errgroup/errgroup.go | 3 + .../golang.org/x/sync/errgroup/go120.go | 1 - .../golang.org/x/sync/errgroup/pre_go120.go | 1 - .../golang.org/x/sync/semaphore/semaphore.go | 42 +- tools/vendor/golang.org/x/sys/LICENSE | 4 +- .../golang.org/x/sys/execabs/execabs.go | 102 - .../golang.org/x/sys/execabs/execabs_go118.go | 18 - .../golang.org/x/sys/execabs/execabs_go119.go | 21 - tools/vendor/golang.org/x/sys/unix/aliases.go | 4 +- .../golang.org/x/sys/unix/asm_aix_ppc64.s | 1 - .../golang.org/x/sys/unix/asm_bsd_386.s | 2 - .../golang.org/x/sys/unix/asm_bsd_amd64.s | 2 - .../golang.org/x/sys/unix/asm_bsd_arm.s | 2 - .../golang.org/x/sys/unix/asm_bsd_arm64.s | 2 - .../golang.org/x/sys/unix/asm_bsd_ppc64.s | 2 - .../golang.org/x/sys/unix/asm_bsd_riscv64.s | 2 - .../golang.org/x/sys/unix/asm_linux_386.s | 1 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 1 - .../golang.org/x/sys/unix/asm_linux_arm.s | 1 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 3 - .../golang.org/x/sys/unix/asm_linux_loong64.s | 3 - .../golang.org/x/sys/unix/asm_linux_mips64x.s | 3 - .../golang.org/x/sys/unix/asm_linux_mipsx.s | 3 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 3 - .../golang.org/x/sys/unix/asm_linux_riscv64.s | 2 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 3 - .../x/sys/unix/asm_openbsd_mips64.s | 1 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 1 - .../golang.org/x/sys/unix/asm_zos_s390x.s | 668 +- .../golang.org/x/sys/unix/bpxsvc_zos.go | 657 + .../vendor/golang.org/x/sys/unix/bpxsvc_zos.s | 192 + .../golang.org/x/sys/unix/cap_freebsd.go | 1 - .../vendor/golang.org/x/sys/unix/constants.go | 1 - .../golang.org/x/sys/unix/dev_aix_ppc.go | 1 - .../golang.org/x/sys/unix/dev_aix_ppc64.go | 1 - tools/vendor/golang.org/x/sys/unix/dev_zos.go | 1 - tools/vendor/golang.org/x/sys/unix/dirent.go | 1 - .../golang.org/x/sys/unix/endian_big.go | 1 - .../golang.org/x/sys/unix/endian_little.go | 1 - .../vendor/golang.org/x/sys/unix/env_unix.go | 1 - .../vendor/golang.org/x/sys/unix/epoll_zos.go | 221 - tools/vendor/golang.org/x/sys/unix/fcntl.go | 3 +- .../x/sys/unix/fcntl_linux_32bit.go | 1 - tools/vendor/golang.org/x/sys/unix/fdset.go | 1 - .../golang.org/x/sys/unix/fstatfs_zos.go | 164 - tools/vendor/golang.org/x/sys/unix/gccgo.go | 1 - tools/vendor/golang.org/x/sys/unix/gccgo_c.c | 1 - .../x/sys/unix/gccgo_linux_amd64.go | 1 - .../golang.org/x/sys/unix/ifreq_linux.go | 1 - .../golang.org/x/sys/unix/ioctl_linux.go | 5 + .../golang.org/x/sys/unix/ioctl_signed.go | 1 - .../golang.org/x/sys/unix/ioctl_unsigned.go | 1 - .../vendor/golang.org/x/sys/unix/ioctl_zos.go | 1 - .../vendor/golang.org/x/sys/unix/mkerrors.sh | 46 +- .../golang.org/x/sys/unix/mmap_nomremap.go | 3 +- tools/vendor/golang.org/x/sys/unix/mremap.go | 6 +- .../golang.org/x/sys/unix/pagesize_unix.go | 3 +- .../golang.org/x/sys/unix/pledge_openbsd.go | 92 +- .../golang.org/x/sys/unix/ptrace_darwin.go | 1 - .../golang.org/x/sys/unix/ptrace_ios.go | 1 - tools/vendor/golang.org/x/sys/unix/race.go | 1 - tools/vendor/golang.org/x/sys/unix/race0.go | 1 - .../x/sys/unix/readdirent_getdents.go | 1 - .../x/sys/unix/readdirent_getdirentries.go | 3 +- .../golang.org/x/sys/unix/sockcmsg_unix.go | 1 - .../x/sys/unix/sockcmsg_unix_other.go | 1 - .../golang.org/x/sys/unix/sockcmsg_zos.go | 58 + .../golang.org/x/sys/unix/symaddr_zos_s390x.s | 75 + tools/vendor/golang.org/x/sys/unix/syscall.go | 1 - .../golang.org/x/sys/unix/syscall_aix.go | 4 +- .../golang.org/x/sys/unix/syscall_aix_ppc.go | 1 - .../x/sys/unix/syscall_aix_ppc64.go | 1 - .../golang.org/x/sys/unix/syscall_bsd.go | 3 +- .../golang.org/x/sys/unix/syscall_darwin.go | 24 + .../x/sys/unix/syscall_darwin_amd64.go | 1 - .../x/sys/unix/syscall_darwin_arm64.go | 1 - .../x/sys/unix/syscall_darwin_libSystem.go | 3 +- .../x/sys/unix/syscall_dragonfly_amd64.go | 1 - .../golang.org/x/sys/unix/syscall_freebsd.go | 12 +- .../x/sys/unix/syscall_freebsd_386.go | 1 - .../x/sys/unix/syscall_freebsd_amd64.go | 1 - .../x/sys/unix/syscall_freebsd_arm.go | 1 - .../x/sys/unix/syscall_freebsd_arm64.go | 1 - .../x/sys/unix/syscall_freebsd_riscv64.go | 1 - .../golang.org/x/sys/unix/syscall_hurd.go | 1 - .../golang.org/x/sys/unix/syscall_hurd_386.go | 1 - .../golang.org/x/sys/unix/syscall_illumos.go | 1 - .../golang.org/x/sys/unix/syscall_linux.go | 133 +- .../x/sys/unix/syscall_linux_386.go | 1 - .../x/sys/unix/syscall_linux_alarm.go | 2 - .../x/sys/unix/syscall_linux_amd64.go | 1 - .../x/sys/unix/syscall_linux_amd64_gc.go | 1 - .../x/sys/unix/syscall_linux_arm.go | 1 - .../x/sys/unix/syscall_linux_arm64.go | 1 - .../golang.org/x/sys/unix/syscall_linux_gc.go | 1 - .../x/sys/unix/syscall_linux_gc_386.go | 1 - .../x/sys/unix/syscall_linux_gc_arm.go | 1 - .../x/sys/unix/syscall_linux_gccgo_386.go | 1 - .../x/sys/unix/syscall_linux_gccgo_arm.go | 1 - .../x/sys/unix/syscall_linux_loong64.go | 1 - .../x/sys/unix/syscall_linux_mips64x.go | 2 - .../x/sys/unix/syscall_linux_mipsx.go | 2 - .../x/sys/unix/syscall_linux_ppc.go | 1 - .../x/sys/unix/syscall_linux_ppc64x.go | 2 - .../x/sys/unix/syscall_linux_riscv64.go | 1 - .../x/sys/unix/syscall_linux_s390x.go | 1 - .../x/sys/unix/syscall_linux_sparc64.go | 1 - .../x/sys/unix/syscall_netbsd_386.go | 1 - .../x/sys/unix/syscall_netbsd_amd64.go | 1 - .../x/sys/unix/syscall_netbsd_arm.go | 1 - .../x/sys/unix/syscall_netbsd_arm64.go | 1 - .../golang.org/x/sys/unix/syscall_openbsd.go | 29 +- .../x/sys/unix/syscall_openbsd_386.go | 1 - .../x/sys/unix/syscall_openbsd_amd64.go | 1 - .../x/sys/unix/syscall_openbsd_arm.go | 1 - .../x/sys/unix/syscall_openbsd_arm64.go | 1 - .../x/sys/unix/syscall_openbsd_libc.go | 1 - .../x/sys/unix/syscall_openbsd_ppc64.go | 1 - .../x/sys/unix/syscall_openbsd_riscv64.go | 1 - .../golang.org/x/sys/unix/syscall_solaris.go | 5 +- .../x/sys/unix/syscall_solaris_amd64.go | 1 - .../golang.org/x/sys/unix/syscall_unix.go | 10 +- .../golang.org/x/sys/unix/syscall_unix_gc.go | 2 - .../x/sys/unix/syscall_unix_gc_ppc64x.go | 3 - .../x/sys/unix/syscall_zos_s390x.go | 1512 +- .../golang.org/x/sys/unix/sysvshm_linux.go | 1 - .../golang.org/x/sys/unix/sysvshm_unix.go | 3 +- .../x/sys/unix/sysvshm_unix_other.go | 3 +- .../golang.org/x/sys/unix/timestruct.go | 1 - .../golang.org/x/sys/unix/unveil_openbsd.go | 41 +- .../vendor/golang.org/x/sys/unix/xattr_bsd.go | 1 - .../golang.org/x/sys/unix/zerrors_aix_ppc.go | 1 - .../x/sys/unix/zerrors_aix_ppc64.go | 1 - .../x/sys/unix/zerrors_darwin_amd64.go | 6 +- .../x/sys/unix/zerrors_darwin_arm64.go | 6 +- .../x/sys/unix/zerrors_dragonfly_amd64.go | 1 - .../x/sys/unix/zerrors_freebsd_386.go | 1 - .../x/sys/unix/zerrors_freebsd_amd64.go | 1 - .../x/sys/unix/zerrors_freebsd_arm.go | 1 - .../x/sys/unix/zerrors_freebsd_arm64.go | 1 - .../x/sys/unix/zerrors_freebsd_riscv64.go | 1 - .../golang.org/x/sys/unix/zerrors_linux.go | 169 +- .../x/sys/unix/zerrors_linux_386.go | 7 +- .../x/sys/unix/zerrors_linux_amd64.go | 7 +- .../x/sys/unix/zerrors_linux_arm.go | 6 +- .../x/sys/unix/zerrors_linux_arm64.go | 7 +- .../x/sys/unix/zerrors_linux_loong64.go | 7 +- .../x/sys/unix/zerrors_linux_mips.go | 6 +- .../x/sys/unix/zerrors_linux_mips64.go | 6 +- .../x/sys/unix/zerrors_linux_mips64le.go | 6 +- .../x/sys/unix/zerrors_linux_mipsle.go | 6 +- .../x/sys/unix/zerrors_linux_ppc.go | 6 +- .../x/sys/unix/zerrors_linux_ppc64.go | 6 +- .../x/sys/unix/zerrors_linux_ppc64le.go | 6 +- .../x/sys/unix/zerrors_linux_riscv64.go | 9 +- .../x/sys/unix/zerrors_linux_s390x.go | 6 +- .../x/sys/unix/zerrors_linux_sparc64.go | 6 +- .../x/sys/unix/zerrors_netbsd_386.go | 1 - .../x/sys/unix/zerrors_netbsd_amd64.go | 1 - .../x/sys/unix/zerrors_netbsd_arm.go | 1 - .../x/sys/unix/zerrors_netbsd_arm64.go | 1 - .../x/sys/unix/zerrors_openbsd_386.go | 1 - .../x/sys/unix/zerrors_openbsd_amd64.go | 1 - .../x/sys/unix/zerrors_openbsd_arm.go | 1 - .../x/sys/unix/zerrors_openbsd_arm64.go | 1 - .../x/sys/unix/zerrors_openbsd_mips64.go | 1 - .../x/sys/unix/zerrors_openbsd_ppc64.go | 1 - .../x/sys/unix/zerrors_openbsd_riscv64.go | 1 - .../x/sys/unix/zerrors_solaris_amd64.go | 1 - .../x/sys/unix/zerrors_zos_s390x.go | 234 +- .../x/sys/unix/zptrace_armnn_linux.go | 2 - .../x/sys/unix/zptrace_mipsnn_linux.go | 2 - .../x/sys/unix/zptrace_mipsnnle_linux.go | 2 - .../x/sys/unix/zptrace_x86_linux.go | 2 - .../x/sys/unix/zsymaddr_zos_s390x.s | 364 + .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1 - .../x/sys/unix/zsyscall_aix_ppc64.go | 1 - .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 1 - .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 1 - .../x/sys/unix/zsyscall_darwin_amd64.go | 82 +- .../x/sys/unix/zsyscall_darwin_amd64.s | 20 + .../x/sys/unix/zsyscall_darwin_arm64.go | 82 +- .../x/sys/unix/zsyscall_darwin_arm64.s | 20 + .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1 - .../x/sys/unix/zsyscall_freebsd_386.go | 1 - .../x/sys/unix/zsyscall_freebsd_amd64.go | 1 - .../x/sys/unix/zsyscall_freebsd_arm.go | 1 - .../x/sys/unix/zsyscall_freebsd_arm64.go | 1 - .../x/sys/unix/zsyscall_freebsd_riscv64.go | 1 - .../x/sys/unix/zsyscall_illumos_amd64.go | 1 - .../golang.org/x/sys/unix/zsyscall_linux.go | 52 +- .../x/sys/unix/zsyscall_linux_386.go | 1 - .../x/sys/unix/zsyscall_linux_amd64.go | 1 - .../x/sys/unix/zsyscall_linux_arm.go | 1 - .../x/sys/unix/zsyscall_linux_arm64.go | 1 - .../x/sys/unix/zsyscall_linux_loong64.go | 1 - .../x/sys/unix/zsyscall_linux_mips.go | 1 - .../x/sys/unix/zsyscall_linux_mips64.go | 1 - .../x/sys/unix/zsyscall_linux_mips64le.go | 1 - .../x/sys/unix/zsyscall_linux_mipsle.go | 1 - .../x/sys/unix/zsyscall_linux_ppc.go | 1 - .../x/sys/unix/zsyscall_linux_ppc64.go | 1 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 1 - .../x/sys/unix/zsyscall_linux_riscv64.go | 1 - .../x/sys/unix/zsyscall_linux_s390x.go | 1 - .../x/sys/unix/zsyscall_linux_sparc64.go | 1 - .../x/sys/unix/zsyscall_netbsd_386.go | 1 - .../x/sys/unix/zsyscall_netbsd_amd64.go | 1 - .../x/sys/unix/zsyscall_netbsd_arm.go | 1 - .../x/sys/unix/zsyscall_netbsd_arm64.go | 1 - .../x/sys/unix/zsyscall_openbsd_386.go | 94 +- .../x/sys/unix/zsyscall_openbsd_386.s | 25 + .../x/sys/unix/zsyscall_openbsd_amd64.go | 94 +- .../x/sys/unix/zsyscall_openbsd_amd64.s | 25 + .../x/sys/unix/zsyscall_openbsd_arm.go | 94 +- .../x/sys/unix/zsyscall_openbsd_arm.s | 25 + .../x/sys/unix/zsyscall_openbsd_arm64.go | 94 +- .../x/sys/unix/zsyscall_openbsd_arm64.s | 25 + .../x/sys/unix/zsyscall_openbsd_mips64.go | 94 +- .../x/sys/unix/zsyscall_openbsd_mips64.s | 25 + .../x/sys/unix/zsyscall_openbsd_ppc64.go | 94 +- .../x/sys/unix/zsyscall_openbsd_ppc64.s | 30 + .../x/sys/unix/zsyscall_openbsd_riscv64.go | 94 +- .../x/sys/unix/zsyscall_openbsd_riscv64.s | 25 + .../x/sys/unix/zsyscall_solaris_amd64.go | 1 - .../x/sys/unix/zsyscall_zos_s390x.go | 3114 ++- .../x/sys/unix/zsysctl_openbsd_386.go | 1 - .../x/sys/unix/zsysctl_openbsd_amd64.go | 1 - .../x/sys/unix/zsysctl_openbsd_arm.go | 1 - .../x/sys/unix/zsysctl_openbsd_arm64.go | 1 - .../x/sys/unix/zsysctl_openbsd_mips64.go | 1 - .../x/sys/unix/zsysctl_openbsd_ppc64.go | 1 - .../x/sys/unix/zsysctl_openbsd_riscv64.go | 1 - .../x/sys/unix/zsysnum_darwin_amd64.go | 1 - .../x/sys/unix/zsysnum_darwin_arm64.go | 1 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 1 - .../x/sys/unix/zsysnum_freebsd_386.go | 1 - .../x/sys/unix/zsysnum_freebsd_amd64.go | 1 - .../x/sys/unix/zsysnum_freebsd_arm.go | 1 - .../x/sys/unix/zsysnum_freebsd_arm64.go | 1 - .../x/sys/unix/zsysnum_freebsd_riscv64.go | 1 - .../x/sys/unix/zsysnum_linux_386.go | 12 +- .../x/sys/unix/zsysnum_linux_amd64.go | 12 +- .../x/sys/unix/zsysnum_linux_arm.go | 12 +- .../x/sys/unix/zsysnum_linux_arm64.go | 12 +- .../x/sys/unix/zsysnum_linux_loong64.go | 12 +- .../x/sys/unix/zsysnum_linux_mips.go | 12 +- .../x/sys/unix/zsysnum_linux_mips64.go | 12 +- .../x/sys/unix/zsysnum_linux_mips64le.go | 12 +- .../x/sys/unix/zsysnum_linux_mipsle.go | 12 +- .../x/sys/unix/zsysnum_linux_ppc.go | 12 +- .../x/sys/unix/zsysnum_linux_ppc64.go | 12 +- .../x/sys/unix/zsysnum_linux_ppc64le.go | 12 +- .../x/sys/unix/zsysnum_linux_riscv64.go | 12 +- .../x/sys/unix/zsysnum_linux_s390x.go | 12 +- .../x/sys/unix/zsysnum_linux_sparc64.go | 12 +- .../x/sys/unix/zsysnum_netbsd_386.go | 1 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 1 - .../x/sys/unix/zsysnum_netbsd_arm.go | 1 - .../x/sys/unix/zsysnum_netbsd_arm64.go | 1 - .../x/sys/unix/zsysnum_openbsd_386.go | 1 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 1 - .../x/sys/unix/zsysnum_openbsd_arm.go | 1 - .../x/sys/unix/zsysnum_openbsd_arm64.go | 1 - .../x/sys/unix/zsysnum_openbsd_mips64.go | 1 - .../x/sys/unix/zsysnum_openbsd_ppc64.go | 1 - .../x/sys/unix/zsysnum_openbsd_riscv64.go | 1 - .../x/sys/unix/zsysnum_zos_s390x.go | 5508 ++--- .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 1 - .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 1 - .../x/sys/unix/ztypes_darwin_amd64.go | 1 - .../x/sys/unix/ztypes_darwin_arm64.go | 1 - .../x/sys/unix/ztypes_dragonfly_amd64.go | 1 - .../x/sys/unix/ztypes_freebsd_386.go | 1 - .../x/sys/unix/ztypes_freebsd_amd64.go | 1 - .../x/sys/unix/ztypes_freebsd_arm.go | 1 - .../x/sys/unix/ztypes_freebsd_arm64.go | 1 - .../x/sys/unix/ztypes_freebsd_riscv64.go | 1 - .../golang.org/x/sys/unix/ztypes_linux.go | 292 +- .../golang.org/x/sys/unix/ztypes_linux_386.go | 9 - .../x/sys/unix/ztypes_linux_amd64.go | 10 - .../golang.org/x/sys/unix/ztypes_linux_arm.go | 10 - .../x/sys/unix/ztypes_linux_arm64.go | 10 - .../x/sys/unix/ztypes_linux_loong64.go | 10 - .../x/sys/unix/ztypes_linux_mips.go | 10 - .../x/sys/unix/ztypes_linux_mips64.go | 10 - .../x/sys/unix/ztypes_linux_mips64le.go | 10 - .../x/sys/unix/ztypes_linux_mipsle.go | 10 - .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 10 - .../x/sys/unix/ztypes_linux_ppc64.go | 10 - .../x/sys/unix/ztypes_linux_ppc64le.go | 10 - .../x/sys/unix/ztypes_linux_riscv64.go | 10 - .../x/sys/unix/ztypes_linux_s390x.go | 10 - .../x/sys/unix/ztypes_linux_sparc64.go | 10 - .../x/sys/unix/ztypes_netbsd_386.go | 1 - .../x/sys/unix/ztypes_netbsd_amd64.go | 1 - .../x/sys/unix/ztypes_netbsd_arm.go | 1 - .../x/sys/unix/ztypes_netbsd_arm64.go | 1 - .../x/sys/unix/ztypes_openbsd_386.go | 1 - .../x/sys/unix/ztypes_openbsd_amd64.go | 1 - .../x/sys/unix/ztypes_openbsd_arm.go | 1 - .../x/sys/unix/ztypes_openbsd_arm64.go | 1 - .../x/sys/unix/ztypes_openbsd_mips64.go | 1 - .../x/sys/unix/ztypes_openbsd_ppc64.go | 1 - .../x/sys/unix/ztypes_openbsd_riscv64.go | 1 - .../x/sys/unix/ztypes_solaris_amd64.go | 1 - .../golang.org/x/sys/unix/ztypes_zos_s390x.go | 147 +- .../golang.org/x/sys/windows/aliases.go | 3 +- tools/vendor/golang.org/x/sys/windows/empty.s | 9 - .../golang.org/x/sys/windows/env_windows.go | 17 +- .../golang.org/x/sys/windows/eventlog.go | 1 - .../golang.org/x/sys/windows/mksyscall.go | 1 - tools/vendor/golang.org/x/sys/windows/race.go | 1 - .../vendor/golang.org/x/sys/windows/race0.go | 1 - .../x/sys/windows/security_windows.go | 25 +- .../golang.org/x/sys/windows/service.go | 1 - tools/vendor/golang.org/x/sys/windows/str.go | 1 - .../golang.org/x/sys/windows/syscall.go | 1 - .../x/sys/windows/syscall_windows.go | 104 +- .../golang.org/x/sys/windows/types_windows.go | 79 +- .../x/sys/windows/zsyscall_windows.go | 196 + .../x/text/unicode/norm/tables10.0.0.go | 1 - .../x/text/unicode/norm/tables11.0.0.go | 1 - .../x/text/unicode/norm/tables12.0.0.go | 1 - .../x/text/unicode/norm/tables13.0.0.go | 1 - .../x/text/unicode/norm/tables15.0.0.go | 1 - .../x/text/unicode/norm/tables9.0.0.go | 1 - .../golang.org/x/text/width/tables10.0.0.go | 1 - .../golang.org/x/text/width/tables11.0.0.go | 1 - .../golang.org/x/text/width/tables12.0.0.go | 1 - .../golang.org/x/text/width/tables13.0.0.go | 1 - .../golang.org/x/text/width/tables15.0.0.go | 1 - .../golang.org/x/text/width/tables9.0.0.go | 1 - tools/vendor/golang.org/x/tools/LICENSE | 4 +- .../x/tools/go/analysis/analysis.go | 24 +- .../x/tools/go/analysis/diagnostic.go | 33 +- .../golang.org/x/tools/go/analysis/doc.go | 30 +- .../go/analysis/passes/appends/appends.go | 10 +- .../analysis/passes/asmdecl/arches_go118.go | 12 - .../analysis/passes/asmdecl/arches_go119.go | 14 - .../go/analysis/passes/asmdecl/asmdecl.go | 5 +- .../tools/go/analysis/passes/assign/assign.go | 3 +- .../tools/go/analysis/passes/atomic/atomic.go | 16 +- .../passes/atomicalign/atomicalign.go | 32 +- .../x/tools/go/analysis/passes/bools/bools.go | 49 +- .../go/analysis/passes/buildssa/buildssa.go | 30 +- .../go/analysis/passes/buildtag/buildtag.go | 58 +- .../analysis/passes/buildtag/buildtag_old.go | 174 - .../go/analysis/passes/cgocall/cgocall.go | 3 +- .../go/analysis/passes/composite/composite.go | 28 +- .../go/analysis/passes/copylock/copylock.go | 19 +- .../passes/deepequalerrors/deepequalerrors.go | 10 +- .../tools/go/analysis/passes/defers/defers.go | 4 +- .../go/analysis/passes/directive/directive.go | 11 +- .../go/analysis/passes/errorsas/errorsas.go | 10 +- .../passes/fieldalignment/fieldalignment.go | 9 + .../passes/framepointer/framepointer.go | 2 +- .../passes/httpresponse/httpresponse.go | 21 +- .../passes/ifaceassert/ifaceassert.go | 8 +- .../passes/ifaceassert/parameterized.go | 113 - .../passes/internal/analysisutil/util.go | 70 +- .../go/analysis/passes/loopclosure/doc.go | 13 +- .../passes/loopclosure/loopclosure.go | 38 +- .../analysis/passes/lostcancel/lostcancel.go | 13 +- .../go/analysis/passes/nilfunc/nilfunc.go | 2 +- .../x/tools/go/analysis/passes/nilness/doc.go | 27 + .../go/analysis/passes/nilness/nilness.go | 176 +- .../x/tools/go/analysis/passes/printf/doc.go | 72 +- .../tools/go/analysis/passes/printf/printf.go | 119 +- .../tools/go/analysis/passes/printf/types.go | 5 +- .../reflectvaluecompare.go | 13 +- .../x/tools/go/analysis/passes/shift/shift.go | 8 +- .../x/tools/go/analysis/passes/slog/slog.go | 58 +- .../go/analysis/passes/sortslice/analyzer.go | 9 +- .../analysis/passes/stringintconv/string.go | 105 +- .../analysis/passes/testinggoroutine/doc.go | 2 +- .../testinggoroutine/testinggoroutine.go | 278 +- .../analysis/passes/testinggoroutine/util.go | 96 + .../x/tools/go/analysis/passes/tests/tests.go | 41 +- .../analysis/passes/timeformat/timeformat.go | 23 +- .../go/analysis/passes/unmarshal/unmarshal.go | 12 +- .../go/analysis/passes/unsafeptr/unsafeptr.go | 21 +- .../passes/unusedresult/unusedresult.go | 24 +- .../passes/unusedwrite/unusedwrite.go | 31 +- .../x/tools/go/analysis/validate.go | 2 + .../x/tools/go/ast/astutil/enclosing.go | 32 +- .../x/tools/go/ast/astutil/rewrite.go | 8 +- .../golang.org/x/tools/go/ast/astutil/util.go | 1 + .../x/tools/go/ast/inspector/typeof.go | 4 +- .../golang.org/x/tools/go/buildutil/tags.go | 42 +- .../golang.org/x/tools/go/cfg/builder.go | 86 +- tools/vendor/golang.org/x/tools/go/cfg/cfg.go | 120 +- .../x/tools/go/gcexportdata/gcexportdata.go | 2 +- .../golang.org/x/tools/go/internal/cgo/cgo.go | 3 +- .../x/tools/go/internal/cgo/cgo_pkgconfig.go | 7 +- .../tools/go/internal/packagesdriver/sizes.go | 48 - .../golang.org/x/tools/go/loader/loader.go | 5 +- .../golang.org/x/tools/go/packages/doc.go | 52 +- .../x/tools/go/packages/external.go | 101 +- .../golang.org/x/tools/go/packages/golist.go | 237 +- .../x/tools/go/packages/golist_overlay.go | 492 - .../x/tools/go/packages/packages.go | 476 +- .../golang.org/x/tools/go/packages/visit.go | 9 + .../golang.org/x/tools/go/ssa/builder.go | 1556 +- .../vendor/golang.org/x/tools/go/ssa/const.go | 9 +- .../golang.org/x/tools/go/ssa/coretype.go | 14 +- .../golang.org/x/tools/go/ssa/create.go | 201 +- tools/vendor/golang.org/x/tools/go/ssa/doc.go | 40 +- tools/vendor/golang.org/x/tools/go/ssa/dom.go | 31 +- .../vendor/golang.org/x/tools/go/ssa/emit.go | 145 +- .../vendor/golang.org/x/tools/go/ssa/func.go | 359 +- .../golang.org/x/tools/go/ssa/identical.go | 12 - .../golang.org/x/tools/go/ssa/identical_17.go | 12 - .../golang.org/x/tools/go/ssa/instantiate.go | 196 +- .../vendor/golang.org/x/tools/go/ssa/lift.go | 63 +- .../golang.org/x/tools/go/ssa/lvalue.go | 4 +- .../golang.org/x/tools/go/ssa/methods.go | 404 +- .../vendor/golang.org/x/tools/go/ssa/print.go | 17 +- .../golang.org/x/tools/go/ssa/sanity.go | 21 +- .../golang.org/x/tools/go/ssa/source.go | 43 +- tools/vendor/golang.org/x/tools/go/ssa/ssa.go | 196 +- .../golang.org/x/tools/go/ssa/ssautil/load.go | 65 +- .../x/tools/go/ssa/ssautil/visit.go | 143 +- .../vendor/golang.org/x/tools/go/ssa/subst.go | 387 +- .../vendor/golang.org/x/tools/go/ssa/task.go | 103 + .../vendor/golang.org/x/tools/go/ssa/util.go | 170 +- .../golang.org/x/tools/go/ssa/util_go120.go | 17 + .../golang.org/x/tools/go/ssa/wrappers.go | 214 +- .../x/tools/go/types/objectpath/objectpath.go | 237 +- .../x/tools/go/types/typeutil/callee.go | 2 +- .../x/tools/go/types/typeutil/map.go | 49 +- .../tools/go/types/typeutil/methodsetcache.go | 6 +- .../x/tools/go/types/typeutil/ui.go | 8 +- .../x/tools/internal/aliases/aliases.go | 32 + .../x/tools/internal/aliases/aliases_go121.go | 35 + .../x/tools/internal/aliases/aliases_go122.go | 99 + .../internal/analysisinternal/analysis.go | 513 + .../analysisinternal}/extractdoc.go | 2 +- .../x/tools/internal/event/keys/util.go | 21 + .../x/tools/internal/event/tag/tag.go | 59 - .../x/tools/internal/fastwalk/fastwalk.go | 196 - .../internal/fastwalk/fastwalk_darwin.go | 119 - .../fastwalk/fastwalk_dirent_fileno.go | 14 - .../internal/fastwalk/fastwalk_dirent_ino.go | 15 - .../fastwalk/fastwalk_dirent_namlen_bsd.go | 14 - .../fastwalk/fastwalk_dirent_namlen_linux.go | 29 - .../internal/fastwalk/fastwalk_portable.go | 41 - .../tools/internal/fastwalk/fastwalk_unix.go | 153 - .../x/tools/internal/gcimporter/gcimporter.go | 7 - .../x/tools/internal/gcimporter/iexport.go | 64 +- .../x/tools/internal/gcimporter/iimport.go | 113 +- .../internal/gcimporter/support_go117.go | 16 - .../internal/gcimporter/support_go118.go | 3 - .../x/tools/internal/gcimporter/unified_no.go | 4 +- .../tools/internal/gcimporter/unified_yes.go | 4 +- .../x/tools/internal/gcimporter/ureader_no.go | 19 - .../tools/internal/gcimporter/ureader_yes.go | 10 +- .../x/tools/internal/gocommand/invoke.go | 153 +- .../x/tools/internal/gocommand/vendor.go | 54 + .../x/tools/internal/gopathwalk/walk.go | 289 +- .../x/tools/internal/imports/fix.go | 664 +- .../x/tools/internal/imports/imports.go | 6 +- .../x/tools/internal/imports/mod.go | 356 +- .../x/tools/internal/imports/mod_cache.go | 119 +- .../x/tools/internal/imports/sortimports.go | 2 +- .../x/tools/internal/imports/zstdlib.go | 11345 ---------- .../internal/packagesinternal/packages.go | 8 - .../x/tools/internal/stdlib/manifest.go | 17431 ++++++++++++++++ .../x/tools/internal/stdlib/stdlib.go | 97 + .../internal/tokeninternal/tokeninternal.go | 28 +- .../x/tools/internal/typeparams/common.go | 104 +- .../x/tools/internal/typeparams/coretype.go | 50 +- .../internal/typeparams/enabled_go117.go | 12 - .../internal/typeparams/enabled_go118.go | 15 - .../typeparams/free.go} | 69 +- .../x/tools/internal/typeparams/normalize.go | 20 +- .../internal/typeparams/typeparams_go117.go | 197 - .../internal/typeparams/typeparams_go118.go | 151 - .../tools/internal/typesinternal/errorcode.go | 6 +- .../internal/typesinternal/objectpath.go | 24 - .../x/tools/internal/typesinternal/recv.go | 43 + .../x/tools/internal/typesinternal/toonew.go | 89 + .../x/tools/internal/typesinternal/types.go | 15 +- .../tools/internal/typesinternal/types_118.go | 19 - .../x/tools/internal/versions/constraint.go | 13 + .../internal/versions/constraint_go121.go | 14 + .../x/tools/internal/versions/features.go | 43 + .../x/tools/internal/versions/gover.go | 172 + .../x/tools/internal/versions/toolchain.go | 14 + .../internal/versions/toolchain_go119.go | 14 + .../internal/versions/toolchain_go120.go | 14 + .../internal/versions/toolchain_go121.go | 14 + .../x/tools/internal/versions/types.go | 19 + .../x/tools/internal/versions/types_go121.go | 30 + .../x/tools/internal/versions/types_go122.go | 41 + .../x/tools/internal/versions/versions.go | 57 + .../go/tools/analysis/callcheck/callcheck.go | 161 + .../honnef.co/go/tools/analysis/code/code.go | 260 +- .../tools/analysis/facts/nilness/nilness.go | 9 +- .../honnef.co/go/tools/analysis/lint/lint.go | 110 +- .../go/tools/analysis/report/report.go | 42 +- .../honnef.co/go/tools/config/example.conf | 2 +- .../honnef.co/go/tools/go/ast/astutil/util.go | 111 + .../vendor/honnef.co/go/tools/go/ir/UPSTREAM | 2 +- .../honnef.co/go/tools/go/ir/builder.go | 1095 +- .../vendor/honnef.co/go/tools/go/ir/const.go | 54 +- .../vendor/honnef.co/go/tools/go/ir/create.go | 84 +- tools/vendor/honnef.co/go/tools/go/ir/doc.go | 5 +- tools/vendor/honnef.co/go/tools/go/ir/dom.go | 4 +- tools/vendor/honnef.co/go/tools/go/ir/emit.go | 229 +- tools/vendor/honnef.co/go/tools/go/ir/func.go | 327 +- tools/vendor/honnef.co/go/tools/go/ir/html.go | 3 + .../honnef.co/go/tools/go/ir/irutil/load.go | 14 +- tools/vendor/honnef.co/go/tools/go/ir/lift.go | 110 +- .../vendor/honnef.co/go/tools/go/ir/lvalue.go | 34 + .../honnef.co/go/tools/go/ir/methods.go | 7 +- .../vendor/honnef.co/go/tools/go/ir/print.go | 34 +- .../vendor/honnef.co/go/tools/go/ir/sanity.go | 16 +- .../vendor/honnef.co/go/tools/go/ir/source.go | 4 +- tools/vendor/honnef.co/go/tools/go/ir/ssa.go | 156 +- tools/vendor/honnef.co/go/tools/go/ir/util.go | 18 +- .../honnef.co/go/tools/go/ir/wrappers.go | 112 +- .../go/tools/go/types/typeutil/ext.go | 9 + .../go/tools/go/types/typeutil/util.go | 84 +- .../tools/internal/passes/buildir/buildir.go | 2 +- .../go/tools/internal/sharedcheck/lint.go | 4 +- .../honnef.co/go/tools/knowledge/arg.go | 112 +- .../go/tools/knowledge/deprecated.go | 392 +- .../honnef.co/go/tools/knowledge/targets.go | 38 + .../honnef.co/go/tools/pattern/match.go | 27 +- .../honnef.co/go/tools/simple/analysis.go | 221 +- tools/vendor/honnef.co/go/tools/simple/doc.go | 467 +- .../vendor/honnef.co/go/tools/simple/lint.go | 2192 -- .../honnef.co/go/tools/simple/s1000/s1000.go | 71 + .../honnef.co/go/tools/simple/s1001/s1001.go | 197 + .../honnef.co/go/tools/simple/s1002/s1002.go | 88 + .../honnef.co/go/tools/simple/s1003/s1003.go | 118 + .../honnef.co/go/tools/simple/s1004/s1004.go | 72 + .../honnef.co/go/tools/simple/s1005/s1005.go | 108 + .../honnef.co/go/tools/simple/s1006/s1006.go | 46 + .../honnef.co/go/tools/simple/s1007/s1007.go | 93 + .../honnef.co/go/tools/simple/s1008/s1008.go | 148 + .../honnef.co/go/tools/simple/s1009/s1009.go | 185 + .../honnef.co/go/tools/simple/s1010/s1010.go | 48 + .../honnef.co/go/tools/simple/s1011/s1011.go | 144 + .../honnef.co/go/tools/simple/s1012/s1012.go | 51 + .../honnef.co/go/tools/simple/s1016/s1016.go | 189 + .../honnef.co/go/tools/simple/s1017/s1017.go | 239 + .../honnef.co/go/tools/simple/s1018/s1018.go | 84 + .../honnef.co/go/tools/simple/s1019/s1019.go | 71 + .../honnef.co/go/tools/simple/s1020/s1020.go | 86 + .../honnef.co/go/tools/simple/s1021/s1021.go | 118 + .../honnef.co/go/tools/simple/s1023/s1023.go | 79 + .../honnef.co/go/tools/simple/s1024/s1024.go | 59 + .../honnef.co/go/tools/simple/s1025/s1025.go | 158 + .../honnef.co/go/tools/simple/s1028/s1028.go | 50 + .../honnef.co/go/tools/simple/s1029/s1029.go | 31 + .../honnef.co/go/tools/simple/s1030/s1030.go | 83 + .../honnef.co/go/tools/simple/s1031/s1031.go | 79 + .../honnef.co/go/tools/simple/s1032/s1032.go | 128 + .../honnef.co/go/tools/simple/s1033/s1033.go | 55 + .../honnef.co/go/tools/simple/s1034/s1034.go | 119 + .../honnef.co/go/tools/simple/s1035/s1035.go | 56 + .../honnef.co/go/tools/simple/s1036/s1036.go | 92 + .../honnef.co/go/tools/simple/s1037/s1037.go | 59 + .../honnef.co/go/tools/simple/s1038/s1038.go | 188 + .../honnef.co/go/tools/simple/s1039/s1039.go | 71 + .../honnef.co/go/tools/simple/s1040/s1040.go | 73 + .../go/tools/staticcheck/analysis.go | 516 +- .../go/tools/staticcheck/buildtag.go | 21 - .../honnef.co/go/tools/staticcheck/doc.go | 1301 +- .../staticcheck/fakereflect/fakereflect.go | 2 +- .../go/tools/staticcheck/fakexml/marshal.go | 16 +- .../go/tools/staticcheck/fakexml/typeinfo.go | 5 +- .../honnef.co/go/tools/staticcheck/lint.go | 5237 ----- .../honnef.co/go/tools/staticcheck/rules.go | 294 - .../go/tools/staticcheck/sa1000/sa1000.go | 46 + .../go/tools/staticcheck/sa1001/sa1001.go | 76 + .../go/tools/staticcheck/sa1002/sa1002.go | 45 + .../go/tools/staticcheck/sa1003/sa1003.go | 92 + .../go/tools/staticcheck/sa1004/sa1004.go | 78 + .../go/tools/staticcheck/sa1005/sa1005.go | 68 + .../go/tools/staticcheck/sa1006/sa1006.go | 107 + .../go/tools/staticcheck/sa1007/sa1007.go | 43 + .../go/tools/staticcheck/sa1008/sa1008.go | 111 + .../go/tools/staticcheck/sa1010/sa1010.go | 53 + .../go/tools/staticcheck/sa1011/sa1011.go | 47 + .../go/tools/staticcheck/sa1012/sa1012.go | 72 + .../go/tools/staticcheck/sa1013/sa1013.go | 50 + .../go/tools/staticcheck/sa1014/sa1014.go | 52 + .../go/tools/staticcheck/sa1015/sa1015.go | 69 + .../go/tools/staticcheck/sa1016/sa1016.go | 112 + .../go/tools/staticcheck/sa1017/sa1017.go | 64 + .../go/tools/staticcheck/sa1018/sa1018.go | 47 + .../go/tools/staticcheck/sa1019/sa1019.go | 212 + .../go/tools/staticcheck/sa1020/sa1020.go | 94 + .../go/tools/staticcheck/sa1021/sa1021.go | 49 + .../go/tools/staticcheck/sa1023/sa1023.go | 72 + .../go/tools/staticcheck/sa1024/sa1024.go | 75 + .../go/tools/staticcheck/sa1025/sa1025.go | 92 + .../go/tools/staticcheck/sa1026/sa1026.go | 77 + .../go/tools/staticcheck/sa1027/sa1027.go | 76 + .../go/tools/staticcheck/sa1028/sa1028.go | 57 + .../go/tools/staticcheck/sa1029/sa1029.go | 61 + .../go/tools/staticcheck/sa1030/sa1030.go | 134 + .../go/tools/staticcheck/sa1031/sa1031.go | 81 + .../go/tools/staticcheck/sa1032/sa1032.go | 79 + .../go/tools/staticcheck/sa2000/sa2000.go | 48 + .../go/tools/staticcheck/sa2001/sa2001.go | 111 + .../go/tools/staticcheck/sa2002/sa2002.go | 93 + .../go/tools/staticcheck/sa2003/sa2003.go | 87 + .../go/tools/staticcheck/sa3000/sa3000.go | 118 + .../go/tools/staticcheck/sa3001/sa3001.go | 55 + .../go/tools/staticcheck/sa4000/sa4000.go | 146 + .../go/tools/staticcheck/sa4001/sa4001.go | 52 + .../go/tools/staticcheck/sa4003/sa4003.go | 159 + .../go/tools/staticcheck/sa4004/sa4004.go | 159 + .../go/tools/staticcheck/sa4005/sa4005.go | 138 + .../go/tools/staticcheck/sa4006/sa4006.go | 155 + .../go/tools/staticcheck/sa4008/sa4008.go | 114 + .../go/tools/staticcheck/sa4009/sa4009.go | 106 + .../go/tools/staticcheck/sa4010/sa4010.go | 216 + .../go/tools/staticcheck/sa4011/sa4011.go | 88 + .../go/tools/staticcheck/sa4012/sa4012.go | 51 + .../go/tools/staticcheck/sa4013/sa4013.go | 44 + .../go/tools/staticcheck/sa4014/sa4014.go | 78 + .../go/tools/staticcheck/sa4015/sa4015.go | 56 + .../go/tools/staticcheck/sa4016/sa4016.go | 116 + .../go/tools/staticcheck/sa4017/sa4017.go | 87 + .../go/tools/staticcheck/sa4018/sa4018.go | 61 + .../go/tools/staticcheck/sa4019/sa4019.go | 82 + .../go/tools/staticcheck/sa4020/sa4020.go | 172 + .../go/tools/staticcheck/sa4021/sa4021.go | 44 + .../go/tools/staticcheck/sa4022/sa4022.go | 48 + .../go/tools/staticcheck/sa4023/sa4023.go | 205 + .../go/tools/staticcheck/sa4024/sa4024.go | 66 + .../go/tools/staticcheck/sa4025/sa4025.go | 77 + .../go/tools/staticcheck/sa4026/sa4026.go | 87 + .../go/tools/staticcheck/sa4027/sa4027.go | 64 + .../go/tools/staticcheck/sa4028/sa4028.go | 43 + .../go/tools/staticcheck/sa4029/sa4029.go | 87 + .../go/tools/staticcheck/sa4030/sa4030.go | 64 + .../go/tools/staticcheck/sa4031/sa4031.go | 162 + .../go/tools/staticcheck/sa4032/sa4032.go | 218 + .../go/tools/staticcheck/sa5000/sa5000.go | 49 + .../go/tools/staticcheck/sa5001/sa5001.go | 109 + .../go/tools/staticcheck/sa5002/sa5002.go | 74 + .../go/tools/staticcheck/sa5003/sa5003.go | 74 + .../go/tools/staticcheck/sa5004/sa5004.go | 55 + .../go/tools/staticcheck/sa5005/sa5005.go | 90 + .../go/tools/staticcheck/sa5007/sa5007.go | 77 + .../go/tools/staticcheck/sa5008/sa5008.go | 179 + .../staticcheck/{ => sa5008}/structtag.go | 2 +- .../go/tools/staticcheck/sa5009/sa5009.go | 409 + .../go/tools/staticcheck/sa5010/sa5010.go | 106 + .../go/tools/staticcheck/sa5011/sa5011.go | 221 + .../go/tools/staticcheck/sa5012/sa5012.go | 286 + .../go/tools/staticcheck/sa6000/sa6000.go | 57 + .../go/tools/staticcheck/sa6001/sa6001.go | 124 + .../go/tools/staticcheck/sa6002/sa6002.go | 52 + .../go/tools/staticcheck/sa6003/sa6003.go | 42 + .../go/tools/staticcheck/sa6005/sa6005.go | 80 + .../go/tools/staticcheck/sa6006/sa6006.go | 53 + .../go/tools/staticcheck/sa9001/sa9001.go | 69 + .../go/tools/staticcheck/sa9002/sa9002.go | 63 + .../go/tools/staticcheck/sa9003/sa9003.go | 62 + .../go/tools/staticcheck/sa9004/sa9004.go | 183 + .../go/tools/staticcheck/sa9005/sa9005.go | 94 + .../go/tools/staticcheck/sa9006/sa9006.go | 106 + .../go/tools/staticcheck/sa9007/sa9007.go | 114 + .../go/tools/staticcheck/sa9008/sa9008.go | 130 + .../go/tools/staticcheck/sa9009/sa9009.go | 68 + .../honnef.co/go/tools/stylecheck/analysis.go | 118 +- .../honnef.co/go/tools/stylecheck/doc.go | 256 +- .../honnef.co/go/tools/stylecheck/lint.go | 990 - .../go/tools/stylecheck/st1000/st1000.go | 83 + .../go/tools/stylecheck/st1001/st1001.go | 71 + .../stylecheck/{names.go => st1003/st1003.go} | 35 +- .../go/tools/stylecheck/st1005/st1005.go | 130 + .../go/tools/stylecheck/st1006/st1006.go | 65 + .../go/tools/stylecheck/st1008/st1008.go | 58 + .../go/tools/stylecheck/st1011/st1011.go | 88 + .../go/tools/stylecheck/st1012/st1012.go | 68 + .../go/tools/stylecheck/st1013/st1013.go | 151 + .../go/tools/stylecheck/st1015/st1015.go | 77 + .../go/tools/stylecheck/st1016/st1016.go | 74 + .../go/tools/stylecheck/st1017/st1017.go | 52 + .../go/tools/stylecheck/st1018/st1018.go | 157 + .../go/tools/stylecheck/st1019/st1019.go | 78 + .../go/tools/stylecheck/st1020/st1020.go | 101 + .../go/tools/stylecheck/st1021/st1021.go | 124 + .../go/tools/stylecheck/st1022/st1022.go | 105 + .../go/tools/stylecheck/st1023/st1023.go | 22 + .../honnef.co/go/tools/unused/implements.go | 73 +- .../honnef.co/go/tools/unused/unused.go | 27 +- tools/vendor/modules.txt | 596 +- .../vendor/mvdan.cc/gofumpt/format/format.go | 65 +- .../internal/govendor/go/doc/comment/print.go | 2 - .../internal/govendor/go/doc/comment/std.go | 3 + .../internal/govendor/go/printer/comment.go | 7 +- .../internal/govendor/go/printer/printer.go | 20 +- tools/vendor/mvdan.cc/interfacer/LICENSE | 27 - .../vendor/mvdan.cc/interfacer/check/cache.go | 50 - .../vendor/mvdan.cc/interfacer/check/check.go | 462 - .../vendor/mvdan.cc/interfacer/check/types.go | 170 - tools/vendor/mvdan.cc/lint/.travis.yml | 7 - tools/vendor/mvdan.cc/lint/LICENSE | 27 - tools/vendor/mvdan.cc/lint/README.md | 27 - tools/vendor/mvdan.cc/lint/lint.go | 28 - tools/vendor/mvdan.cc/unparam/check/check.go | 13 +- 1543 files changed, 96077 insertions(+), 59224 deletions(-) create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/blank_import.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/call_meta.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/formatter.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/go_require.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_basic_type.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_bool.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_comparison.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_context.go rename tools/vendor/github.com/Antonboom/testifylint/internal/checkers/{diagnostic.go => helpers_diagnostic.go} (70%) create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_error.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_format.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_http.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_interface.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_len.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_naming.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_nil.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_suite.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_testing.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/negative_postive.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/nil_compare.go rename tools/vendor/github.com/{golangci/maligned => Antonboom/testifylint/internal/checkers/printf}/LICENSE (96%) create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/doc.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/printf.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_broken_parallel.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_subtest_run.go create mode 100644 tools/vendor/github.com/Antonboom/testifylint/internal/checkers/useless_assert.go delete mode 100644 tools/vendor/github.com/BurntSushi/toml/decode_go116.go rename tools/vendor/github.com/{mbilski/exhaustivestruct => Crocmagnon/fatcontext}/LICENSE (96%) create mode 100644 tools/vendor/github.com/Crocmagnon/fatcontext/pkg/analyzer/analyzer.go create mode 100644 tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/cache.go create mode 100644 tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/directive.go create mode 100644 tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure/fields-cache.go rename tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/{fields/struct.go => structure/fields.go} (64%) delete mode 100644 tools/vendor/github.com/Masterminds/semver/.travis.yml delete mode 100644 tools/vendor/github.com/Masterminds/semver/CHANGELOG.md delete mode 100644 tools/vendor/github.com/Masterminds/semver/Makefile delete mode 100644 tools/vendor/github.com/Masterminds/semver/README.md delete mode 100644 tools/vendor/github.com/Masterminds/semver/appveyor.yml delete mode 100644 tools/vendor/github.com/Masterminds/semver/constraints.go delete mode 100644 tools/vendor/github.com/Masterminds/semver/doc.go create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/.gitignore create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/.golangci.yml create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md rename tools/vendor/github.com/Masterminds/semver/{ => v3}/LICENSE.txt (100%) create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/Makefile create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/README.md create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/SECURITY.md rename tools/vendor/github.com/Masterminds/semver/{ => v3}/collection.go (100%) create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/constraints.go create mode 100644 tools/vendor/github.com/Masterminds/semver/v3/doc.go rename tools/vendor/github.com/Masterminds/semver/{ => v3}/version.go (55%) delete mode 100644 tools/vendor/github.com/Masterminds/semver/version_fuzz.go rename tools/vendor/github.com/bombsimon/wsl/{v3 => v4}/.gitignore (99%) rename tools/vendor/github.com/bombsimon/wsl/{v3 => v4}/.golangci.yml (81%) rename tools/vendor/github.com/bombsimon/wsl/{v3 => v4}/LICENSE (100%) rename tools/vendor/github.com/bombsimon/wsl/{v3 => v4}/README.md (69%) create mode 100644 tools/vendor/github.com/bombsimon/wsl/v4/analyzer.go rename tools/vendor/github.com/bombsimon/wsl/{v3 => v4}/wsl.go (63%) delete mode 100644 tools/vendor/github.com/butuzov/ireturn/analyzer/typeparams.go delete mode 100644 tools/vendor/github.com/butuzov/mirror/.act create mode 100644 tools/vendor/github.com/ccojocar/zxcvbn-go/renovate.json create mode 100644 tools/vendor/github.com/ckaznocha/intrange/.gitignore create mode 100644 tools/vendor/github.com/ckaznocha/intrange/.golangci.yml create mode 100644 tools/vendor/github.com/ckaznocha/intrange/CONTRIBUTING.md rename tools/vendor/github.com/{t-yuki/gocover-cobertura => ckaznocha/intrange}/LICENSE (60%) create mode 100644 tools/vendor/github.com/ckaznocha/intrange/README.md create mode 100644 tools/vendor/github.com/ckaznocha/intrange/SECURITY.md create mode 100644 tools/vendor/github.com/ckaznocha/intrange/go.work create mode 100644 tools/vendor/github.com/ckaznocha/intrange/intrange.go create mode 100644 tools/vendor/github.com/daixiang0/gci/pkg/section/alias.go create mode 100644 tools/vendor/github.com/daixiang0/gci/pkg/section/local_module.go create mode 100644 tools/vendor/github.com/daixiang0/gci/pkg/specificity/local_module.go delete mode 100644 tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/analyzer.go delete mode 100644 tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/occurrences.go create mode 100644 tools/vendor/github.com/ettle/strcase/assert.go create mode 100644 tools/vendor/github.com/go-toolsmith/astequal/diff.go create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/.editorconfig create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/.envrc create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/.gitignore create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/.golangci.yaml create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/CHANGELOG.md create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/LICENSE create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/README.md create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/flake.lock create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/flake.nix create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/errors.go create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join.go create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join_go1_19.go create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_19.go create mode 100644 tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_20.go create mode 100644 tools/vendor/github.com/gofrs/flock/.golangci.yml delete mode 100644 tools/vendor/github.com/gofrs/flock/.travis.yml create mode 100644 tools/vendor/github.com/gofrs/flock/Makefile create mode 100644 tools/vendor/github.com/gofrs/flock/SECURITY.md delete mode 100644 tools/vendor/github.com/gofrs/flock/appveyor.yml create mode 100644 tools/vendor/github.com/gofrs/flock/build.sh delete mode 100644 tools/vendor/github.com/gofrs/flock/flock_aix.go create mode 100644 tools/vendor/github.com/gofrs/flock/flock_others.go create mode 100644 tools/vendor/github.com/gofrs/flock/flock_unix_fcntl.go delete mode 100644 tools/vendor/github.com/gofrs/flock/flock_winapi.go delete mode 100644 tools/vendor/github.com/golangci/check/cmd/structcheck/structcheck.go delete mode 100644 tools/vendor/github.com/golangci/check/cmd/varcheck/varcheck.go delete mode 100644 tools/vendor/github.com/golangci/go-misc/LICENSE delete mode 100644 tools/vendor/github.com/golangci/go-misc/deadcode/README.md delete mode 100644 tools/vendor/github.com/golangci/go-misc/deadcode/deadcode.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/plugins.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config_verify.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/custom.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/flagsets.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/builder.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/configuration.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/imports.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/vibra.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/config/loader.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/issue.go (81%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/linter.go (97%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/load/guard.go (100%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/metalinter.go (92%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters/goanalysis => goanalysis/pkgerrors}/errors.go (60%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{packages/util.go => goanalysis/pkgerrors/extract.go} (93%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{packages/errors.go => goanalysis/pkgerrors/parse.go} (53%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/runner.go (92%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/runner_action.go (97%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/runner_facts.go (100%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/runner_loadingpackage.go (99%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/{golinters => }/goanalysis/runners.go (88%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => asasalint}/asasalint.go (65%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck/asciicheck.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => bidichk}/bidichk.go (88%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => bodyclose}/bodyclose.go (57%) create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/canonicalheader/canonicalheader.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/commons.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => containedctx}/containedctx.go (66%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => contextcheck}/contextcheck.go (79%) create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/copyloopvar/copyloopvar.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => cyclop}/cyclop.go (78%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/deadcode.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => decorder}/decorder.go (89%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => depguard}/depguard.go (82%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => dogsled}/dogsled.go (88%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => dupl}/dupl.go (84%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => dupword}/dupword.go (78%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => durationcheck}/durationcheck.go (66%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{goerr113.go => err113/err113.go} (55%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => errcheck}/errcheck.go (94%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => errchkjson}/errchkjson.go (59%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname/errname.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint/errorlint.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => execinquery}/execinquery.go (66%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => exhaustive}/exhaustive.go (82%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustivestruct.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => exhaustruct}/exhaustruct.go (63%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => exportloopref}/exportloopref.go (66%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{perfsprint.go => fatcontext/fatcontext.go} (54%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => forbidigo}/forbidigo.go (88%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => forcetypeassert}/forcetypeassert.go (68%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => funlen}/funlen.go (85%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gci}/gci.go (53%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter/ginkgolinter.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/adapters.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gocheckcompilerdirectives}/gocheckcompilerdirectives.go (67%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals/gochecknoglobals.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gochecknoinits}/gochecknoinits.go (74%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gochecksumtype}/gochecksumtype.go (82%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gocognit}/gocognit.go (82%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => goconst}/goconst.go (80%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic/gocritic.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gocyclo}/gocyclo.go (80%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => godot}/godot.go (84%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => godox}/godox.go (85%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gofmt}/gofmt.go (72%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gofumpt}/gofumpt.go (81%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => goheader}/goheader.go (80%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => goimports}/goimports.go (71%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/golint.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomnd.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gomoddirectives}/gomoddirectives.go (80%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gomodguard}/gomodguard.go (83%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname/goprintffuncname.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gosec}/gosec.go (90%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple/gosimple.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => gosmopolitan}/gosmopolitan.go (79%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => govet}/govet.go (77%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => grouper}/grouper.go (74%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ifshort.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => importas}/importas.go (88%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam/inamedparam.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => ineffassign}/ineffassign.go (57%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => interfacebloat}/interfacebloat.go (74%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacer.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/commons.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{gofmt_common.go => internal/diff.go} (85%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => internal}/staticcheck_common.go (92%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => internal}/util.go (66%) create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/intrange/intrange.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => ireturn}/ireturn.go (61%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => lll}/lll.go (82%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => loggercheck}/loggercheck.go (84%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => maintidx}/maintidx.go (76%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => makezero}/makezero.go (85%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maligned.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => mirror}/mirror.go (91%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => misspell}/misspell.go (55%) create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mnd/mnd.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => musttag}/musttag.go (72%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret/nakedret.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => nestif}/nestif.go (87%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => nilerr}/nilerr.go (72%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => nilnil}/nilnil.go (77%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => nlreturn}/nlreturn.go (77%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx/noctx.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/{ => internal}/README.md (81%) create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal/nolintlint.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => nonamedreturns}/nonamedreturns.go (74%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosnakecase.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => nosprintfhostport}/nosprintfhostport.go (66%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest/paralleltest.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/perfsprint/perfsprint.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => prealloc}/prealloc.go (76%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => predeclared}/predeclared.go (76%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => promlinter}/promlinter.go (85%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => protogetter}/protogetter.go (63%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => reassign}/reassign.go (78%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => revive}/revive.go (77%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck/rowserrcheck.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/scopelint.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => sloglint}/sloglint.go (57%) create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/spancheck/spancheck.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck/sqlclosecheck.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => staticcheck}/staticcheck.go (53%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/structcheck.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => stylecheck}/stylecheck.go (61%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => tagalign}/tagalign.go (92%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => tagliatelle}/tagliatelle.go (77%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => tenv}/tenv.go (74%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => testableexamples}/testableexamples.go (68%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint/testifylint.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => testpackage}/testpackage.go (74%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => thelper}/thelper.go (74%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel/tparallel.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => unconvert}/unconvert.go (58%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => unparam}/unparam.go (88%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => unused}/unused.go (74%) rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => usestdlibvars}/usestdlibvars.go (87%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varcheck.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => varnamelen}/varnamelen.go (89%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign/wastedassign.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace/whitespace.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/{ => wrapcheck}/wrapcheck.go (78%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl/wsl.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint/zerologlint.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/lint/context.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_linter.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_go.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_module.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/custom_linters.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/lint/{load.go => package.go} (52%) delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/packages/skip.go rename tools/vendor/github.com/golangci/golangci-lint/pkg/printers/{github.go => githubaction.go} (66%) create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/printers/sarif.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/invalid_issue.go create mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity.go delete mode 100644 tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity_rules.go delete mode 100644 tools/vendor/github.com/golangci/lint-1/.travis.yml delete mode 100644 tools/vendor/github.com/golangci/lint-1/CONTRIBUTING.md delete mode 100644 tools/vendor/github.com/golangci/lint-1/LICENSE delete mode 100644 tools/vendor/github.com/golangci/lint-1/README.md delete mode 100644 tools/vendor/github.com/golangci/lint-1/lint.go delete mode 100644 tools/vendor/github.com/golangci/maligned/README delete mode 100644 tools/vendor/github.com/golangci/maligned/maligned.go create mode 100644 tools/vendor/github.com/golangci/misspell/.pre-commit-hooks.yaml create mode 100644 tools/vendor/github.com/golangci/modinfo/.gitignore create mode 100644 tools/vendor/github.com/golangci/modinfo/.golangci.yml create mode 100644 tools/vendor/github.com/golangci/modinfo/LICENSE create mode 100644 tools/vendor/github.com/golangci/modinfo/Makefile create mode 100644 tools/vendor/github.com/golangci/modinfo/module.go create mode 100644 tools/vendor/github.com/golangci/modinfo/readme.md rename tools/vendor/github.com/golangci/{check => plugin-module-register}/LICENSE (98%) create mode 100644 tools/vendor/github.com/golangci/plugin-module-register/register/register.go delete mode 100644 tools/vendor/github.com/golangci/unconvert/README create mode 100644 tools/vendor/github.com/golangci/unconvert/README.md create mode 100644 tools/vendor/github.com/golangci/unconvert/golangci.go delete mode 100644 tools/vendor/github.com/hashicorp/errwrap/LICENSE delete mode 100644 tools/vendor/github.com/hashicorp/errwrap/README.md delete mode 100644 tools/vendor/github.com/hashicorp/errwrap/errwrap.go delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/LICENSE delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/Makefile delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/README.md delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/append.go delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/flatten.go delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/format.go delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/group.go delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/multierror.go delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/prefix.go delete mode 100644 tools/vendor/github.com/hashicorp/go-multierror/sort.go delete mode 100644 tools/vendor/github.com/jgautheron/goconst/.gitignore rename tools/vendor/github.com/{sivchari/nosnakecase => jjti/go-spancheck}/.gitignore (59%) create mode 100644 tools/vendor/github.com/jjti/go-spancheck/.golangci.yml create mode 100644 tools/vendor/github.com/jjti/go-spancheck/CONTRIBUTING.md rename tools/vendor/github.com/{esimonov/ifshort => jjti/go-spancheck}/LICENSE (96%) create mode 100644 tools/vendor/github.com/jjti/go-spancheck/Makefile create mode 100644 tools/vendor/github.com/jjti/go-spancheck/README.md create mode 100644 tools/vendor/github.com/jjti/go-spancheck/config.go create mode 100644 tools/vendor/github.com/jjti/go-spancheck/doc.go create mode 100644 tools/vendor/github.com/jjti/go-spancheck/go.work create mode 100644 tools/vendor/github.com/jjti/go-spancheck/go.work.sum create mode 100644 tools/vendor/github.com/jjti/go-spancheck/spancheck.go create mode 100644 tools/vendor/github.com/karamaru-alpha/copyloopvar/.gitignore rename tools/vendor/github.com/{sivchari/nosnakecase => karamaru-alpha/copyloopvar}/LICENSE (96%) create mode 100644 tools/vendor/github.com/karamaru-alpha/copyloopvar/README.md create mode 100644 tools/vendor/github.com/karamaru-alpha/copyloopvar/copyloopvar.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/.travis.yml delete mode 100644 tools/vendor/github.com/kisielk/gotool/LEGAL delete mode 100644 tools/vendor/github.com/kisielk/gotool/LICENSE delete mode 100644 tools/vendor/github.com/kisielk/gotool/README.md delete mode 100644 tools/vendor/github.com/kisielk/gotool/go13.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/go14-15.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/go16-18.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/internal/load/path.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/internal/load/pkg.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/internal/load/search.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/match.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/match18.go delete mode 100644 tools/vendor/github.com/kisielk/gotool/tool.go create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/.gitignore create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/.golangci.yaml create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/.goreleaser.yaml create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/LICENCE create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/README.md create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/analyzer.go create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/constant_string.go create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/initialism.go create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/literal_string.go create mode 100644 tools/vendor/github.com/lasiar/canonicalheader/makefile create mode 100644 tools/vendor/github.com/macabu/inamedparam/.golangci.yml delete mode 100644 tools/vendor/github.com/mbilski/exhaustivestruct/pkg/analyzer/analyzer.go create mode 100644 tools/vendor/github.com/mgechev/revive/formatter/doc.go create mode 100644 tools/vendor/github.com/mgechev/revive/lint/doc.go create mode 100644 tools/vendor/github.com/mgechev/revive/rule/comments-density.go create mode 100644 tools/vendor/github.com/mgechev/revive/rule/doc.go create mode 100644 tools/vendor/github.com/mgechev/revive/rule/enforce-repeated-arg-type-style.go create mode 100644 tools/vendor/github.com/mgechev/revive/rule/enforce-slice-style.go rename tools/vendor/github.com/mgechev/revive/rule/{imports-blacklist.go => imports-blocklist.go} (50%) create mode 100644 tools/vendor/github.com/mgechev/revive/rule/max-control-nesting.go create mode 100644 tools/vendor/github.com/nishanths/exhaustive/comment_go121.go create mode 100644 tools/vendor/github.com/nishanths/exhaustive/comment_pre_go121.go create mode 100644 tools/vendor/github.com/nunnatsa/ginkgolinter/analyzer.go create mode 100644 tools/vendor/github.com/nunnatsa/ginkgolinter/doc.go rename tools/vendor/github.com/nunnatsa/ginkgolinter/{ => internal}/ginkgohandler/handler.go (72%) rename tools/vendor/github.com/nunnatsa/ginkgolinter/{ => internal}/gomegahandler/handler.go (96%) create mode 100644 tools/vendor/github.com/nunnatsa/ginkgolinter/internal/interfaces/interfaces.go create mode 100644 tools/vendor/github.com/nunnatsa/ginkgolinter/internal/intervals/intervals.go create mode 100644 tools/vendor/github.com/nunnatsa/ginkgolinter/internal/reports/report-builder.go rename tools/vendor/github.com/nunnatsa/ginkgolinter/{ => internal}/reverseassertion/reverse_assertion.go (100%) rename tools/vendor/github.com/nunnatsa/ginkgolinter/{ => linter}/ginkgo_linter.go (59%) delete mode 100644 tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/builder.go create mode 100644 tools/vendor/github.com/pelletier/go-toml/v2/internal/characters/ascii.go rename tools/vendor/github.com/pelletier/go-toml/v2/{ => internal/characters}/utf8.go (87%) rename tools/vendor/github.com/pelletier/go-toml/v2/{internal/ast => unstable}/ast.go (60%) create mode 100644 tools/vendor/github.com/pelletier/go-toml/v2/unstable/builder.go create mode 100644 tools/vendor/github.com/pelletier/go-toml/v2/unstable/doc.go rename tools/vendor/github.com/pelletier/go-toml/v2/{internal/ast => unstable}/kind.go (81%) rename tools/vendor/github.com/pelletier/go-toml/v2/{ => unstable}/parser.go (62%) rename tools/vendor/github.com/pelletier/go-toml/v2/{ => unstable}/scanner.go (79%) create mode 100644 tools/vendor/github.com/pelletier/go-toml/v2/unstable/unmarshaler.go create mode 100644 tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/options.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/LICENSE create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/bundle.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/do.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/dsl.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/filter.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/internal.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/ext.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/type_impl.go create mode 100644 tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/types.go delete mode 100644 tools/vendor/github.com/ryancurrah/gomodguard/tools.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitignore create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitmodules create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/LICENSE create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/README.md create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/compiler.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/content.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/doc.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/draft.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/errors.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/extension.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/format.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/httploader/httploader.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/loader.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/output.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/resource.go create mode 100644 tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/schema.go delete mode 100644 tools/vendor/github.com/sivchari/nosnakecase/.golangci.yml delete mode 100644 tools/vendor/github.com/sivchari/nosnakecase/README.md delete mode 100644 tools/vendor/github.com/sivchari/nosnakecase/nosnakecase.go delete mode 100644 tools/vendor/github.com/spf13/afero/.travis.yml create mode 100644 tools/vendor/github.com/spf13/afero/internal/common/adapters.go delete mode 100644 tools/vendor/github.com/spf13/cobra/active_help.md delete mode 100644 tools/vendor/github.com/spf13/cobra/bash_completions.md delete mode 100644 tools/vendor/github.com/spf13/cobra/fish_completions.md delete mode 100644 tools/vendor/github.com/spf13/cobra/powershell_completions.md delete mode 100644 tools/vendor/github.com/spf13/cobra/projects_using_cobra.md delete mode 100644 tools/vendor/github.com/spf13/cobra/shell_completions.md delete mode 100644 tools/vendor/github.com/spf13/cobra/user_guide.md delete mode 100644 tools/vendor/github.com/spf13/cobra/zsh_completions.md delete mode 100644 tools/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go delete mode 100644 tools/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go delete mode 100644 tools/vendor/github.com/t-yuki/gocover-cobertura/.travis.yml delete mode 100644 tools/vendor/github.com/t-yuki/gocover-cobertura/README.md delete mode 100644 tools/vendor/github.com/t-yuki/gocover-cobertura/cobertura.go delete mode 100644 tools/vendor/github.com/t-yuki/gocover-cobertura/gocover-cobertura.go delete mode 100644 tools/vendor/github.com/t-yuki/gocover-cobertura/profile.go delete mode 100644 tools/vendor/github.com/ultraware/whitespace/main.go create mode 100644 tools/vendor/github.com/ultraware/whitespace/whitespace.go rename tools/vendor/{go.tmz.dev => go-simpler.org}/musttag/.golangci.yml (100%) rename tools/vendor/{go.tmz.dev => go-simpler.org}/musttag/.goreleaser.yml (55%) rename tools/vendor/{go.tmz.dev => go-simpler.org}/musttag/LICENSE (100%) create mode 100644 tools/vendor/go-simpler.org/musttag/Makefile create mode 100644 tools/vendor/go-simpler.org/musttag/README.md create mode 100644 tools/vendor/go-simpler.org/musttag/builtins.go create mode 100644 tools/vendor/go-simpler.org/musttag/musttag.go create mode 100644 tools/vendor/go-simpler.org/musttag/utils.go create mode 100644 tools/vendor/go-simpler.org/sloglint/Makefile delete mode 100644 tools/vendor/go.tmz.dev/musttag/README.md delete mode 100644 tools/vendor/go.tmz.dev/musttag/builtins.go delete mode 100644 tools/vendor/go.tmz.dev/musttag/musttag.go delete mode 100644 tools/vendor/go.tmz.dev/musttag/utils.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/LICENSE create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroup.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups2.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/cgroups/doc.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/cgroups/errors.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/cgroups/mountpoint.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/cgroups/subsys.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_linux.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_unsupported.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/internal/runtime/runtime.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/maxprocs/maxprocs.go create mode 100644 tools/vendor/go.uber.org/automaxprocs/maxprocs/version.go create mode 100644 tools/vendor/golang.org/x/exp/maps/maps.go create mode 100644 tools/vendor/golang.org/x/exp/slices/cmp.go rename tools/vendor/golang.org/x/exp/slices/{zsortfunc.go => zsortanyfunc.go} (64%) delete mode 100644 tools/vendor/golang.org/x/sys/execabs/execabs.go delete mode 100644 tools/vendor/golang.org/x/sys/execabs/execabs_go118.go delete mode 100644 tools/vendor/golang.org/x/sys/execabs/execabs_go119.go create mode 100644 tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.go create mode 100644 tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.s delete mode 100644 tools/vendor/golang.org/x/sys/unix/epoll_zos.go delete mode 100644 tools/vendor/golang.org/x/sys/unix/fstatfs_zos.go create mode 100644 tools/vendor/golang.org/x/sys/unix/sockcmsg_zos.go create mode 100644 tools/vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s create mode 100644 tools/vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s delete mode 100644 tools/vendor/golang.org/x/sys/windows/empty.s delete mode 100644 tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go118.go delete mode 100644 tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go119.go delete mode 100644 tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag_old.go delete mode 100644 tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/parameterized.go create mode 100644 tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/util.go delete mode 100644 tools/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go delete mode 100644 tools/vendor/golang.org/x/tools/go/ssa/identical.go delete mode 100644 tools/vendor/golang.org/x/tools/go/ssa/identical_17.go create mode 100644 tools/vendor/golang.org/x/tools/go/ssa/task.go create mode 100644 tools/vendor/golang.org/x/tools/go/ssa/util_go120.go create mode 100644 tools/vendor/golang.org/x/tools/internal/aliases/aliases.go create mode 100644 tools/vendor/golang.org/x/tools/internal/aliases/aliases_go121.go create mode 100644 tools/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go create mode 100644 tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go rename tools/vendor/golang.org/x/tools/{go/analysis/passes/internal/analysisutil => internal/analysisinternal}/extractdoc.go (99%) create mode 100644 tools/vendor/golang.org/x/tools/internal/event/keys/util.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/event/tag/tag.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_darwin.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_fileno.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_ino.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_bsd.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_linux.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_unix.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/gcimporter/support_go117.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_no.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go create mode 100644 tools/vendor/golang.org/x/tools/internal/stdlib/manifest.go create mode 100644 tools/vendor/golang.org/x/tools/internal/stdlib/stdlib.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go117.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go118.go rename tools/vendor/golang.org/x/tools/{go/ssa/parameterized.go => internal/typeparams/free.go} (52%) delete mode 100644 tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/typesinternal/objectpath.go create mode 100644 tools/vendor/golang.org/x/tools/internal/typesinternal/recv.go create mode 100644 tools/vendor/golang.org/x/tools/internal/typesinternal/toonew.go delete mode 100644 tools/vendor/golang.org/x/tools/internal/typesinternal/types_118.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/constraint.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/constraint_go121.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/features.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/gover.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/toolchain.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/toolchain_go119.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/toolchain_go120.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/toolchain_go121.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/types.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/types_go121.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/types_go122.go create mode 100644 tools/vendor/golang.org/x/tools/internal/versions/versions.go create mode 100644 tools/vendor/honnef.co/go/tools/analysis/callcheck/callcheck.go create mode 100644 tools/vendor/honnef.co/go/tools/knowledge/targets.go delete mode 100644 tools/vendor/honnef.co/go/tools/simple/lint.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1000/s1000.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1001/s1001.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1002/s1002.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1003/s1003.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1004/s1004.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1005/s1005.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1006/s1006.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1007/s1007.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1008/s1008.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1009/s1009.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1010/s1010.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1011/s1011.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1012/s1012.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1016/s1016.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1017/s1017.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1018/s1018.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1019/s1019.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1020/s1020.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1021/s1021.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1023/s1023.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1024/s1024.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1025/s1025.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1028/s1028.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1029/s1029.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1030/s1030.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1031/s1031.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1032/s1032.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1033/s1033.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1034/s1034.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1035/s1035.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1036/s1036.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1037/s1037.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1038/s1038.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1039/s1039.go create mode 100644 tools/vendor/honnef.co/go/tools/simple/s1040/s1040.go delete mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/buildtag.go delete mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/lint.go delete mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/rules.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1000/sa1000.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1001/sa1001.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1002/sa1002.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1003/sa1003.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1004/sa1004.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1005/sa1005.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1006/sa1006.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1007/sa1007.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1008/sa1008.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1010/sa1010.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1011/sa1011.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1012/sa1012.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1013/sa1013.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1014/sa1014.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1015/sa1015.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1016/sa1016.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1017/sa1017.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1018/sa1018.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1019/sa1019.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1020/sa1020.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1021/sa1021.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1023/sa1023.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1024/sa1024.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1025/sa1025.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1026/sa1026.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1027/sa1027.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1028/sa1028.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1029/sa1029.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1030/sa1030.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1031/sa1031.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa1032/sa1032.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa2000/sa2000.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa2001/sa2001.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa2002/sa2002.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa2003/sa2003.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa3000/sa3000.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa3001/sa3001.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4000/sa4000.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4001/sa4001.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4003/sa4003.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4004/sa4004.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4005/sa4005.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4006/sa4006.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4008/sa4008.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4009/sa4009.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4010/sa4010.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4011/sa4011.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4012/sa4012.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4013/sa4013.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4014/sa4014.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4015/sa4015.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4016/sa4016.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4017/sa4017.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4018/sa4018.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4019/sa4019.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4020/sa4020.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4021/sa4021.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4022/sa4022.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4023/sa4023.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4024/sa4024.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4025/sa4025.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4026/sa4026.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4027/sa4027.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4028/sa4028.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4029/sa4029.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4030/sa4030.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4031/sa4031.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa4032/sa4032.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5000/sa5000.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5001/sa5001.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5002/sa5002.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5003/sa5003.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5004/sa5004.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5005/sa5005.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5007/sa5007.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5008/sa5008.go rename tools/vendor/honnef.co/go/tools/staticcheck/{ => sa5008}/structtag.go (98%) create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5009/sa5009.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5010/sa5010.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5011/sa5011.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa5012/sa5012.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa6000/sa6000.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa6001/sa6001.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa6002/sa6002.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa6003/sa6003.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa6005/sa6005.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa6006/sa6006.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9001/sa9001.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9002/sa9002.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9003/sa9003.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9004/sa9004.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9005/sa9005.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9006/sa9006.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9007/sa9007.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9008/sa9008.go create mode 100644 tools/vendor/honnef.co/go/tools/staticcheck/sa9009/sa9009.go delete mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/lint.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1000/st1000.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1001/st1001.go rename tools/vendor/honnef.co/go/tools/stylecheck/{names.go => st1003/st1003.go} (88%) create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1005/st1005.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1006/st1006.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1008/st1008.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1011/st1011.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1012/st1012.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1013/st1013.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1015/st1015.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1016/st1016.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1017/st1017.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1018/st1018.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1019/st1019.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1020/st1020.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1021/st1021.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1022/st1022.go create mode 100644 tools/vendor/honnef.co/go/tools/stylecheck/st1023/st1023.go delete mode 100644 tools/vendor/mvdan.cc/interfacer/LICENSE delete mode 100644 tools/vendor/mvdan.cc/interfacer/check/cache.go delete mode 100644 tools/vendor/mvdan.cc/interfacer/check/check.go delete mode 100644 tools/vendor/mvdan.cc/interfacer/check/types.go delete mode 100644 tools/vendor/mvdan.cc/lint/.travis.yml delete mode 100644 tools/vendor/mvdan.cc/lint/LICENSE delete mode 100644 tools/vendor/mvdan.cc/lint/README.md delete mode 100644 tools/vendor/mvdan.cc/lint/lint.go diff --git a/tools/go.mod b/tools/go.mod index 91abf8026..ce4d7277f 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -1,27 +1,28 @@ module github.com/containers/gvisor-tap-vsock/tools -go 1.20 +go 1.22.1 require ( - github.com/golangci/golangci-lint v1.55.2 + github.com/golangci/golangci-lint v1.60.1 github.com/randall77/makefat v0.0.0-20210315173500-7ddd0e42c844 ) require ( 4d63.com/gocheckcompilerdirectives v1.2.1 // indirect 4d63.com/gochecknoglobals v0.2.1 // indirect - github.com/4meepo/tagalign v1.3.3 // indirect - github.com/Abirdcfly/dupword v0.0.13 // indirect - github.com/Antonboom/errname v0.1.12 // indirect - github.com/Antonboom/nilnil v0.1.7 // indirect - github.com/Antonboom/testifylint v0.2.3 // indirect - github.com/BurntSushi/toml v1.3.2 // indirect + github.com/4meepo/tagalign v1.3.4 // indirect + github.com/Abirdcfly/dupword v0.0.14 // indirect + github.com/Antonboom/errname v0.1.13 // indirect + github.com/Antonboom/nilnil v0.1.9 // indirect + github.com/Antonboom/testifylint v1.4.3 // indirect + github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c // indirect + github.com/Crocmagnon/fatcontext v0.4.0 // indirect github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 // indirect - github.com/GaijinEntertainment/go-exhaustruct/v3 v3.1.0 // indirect - github.com/Masterminds/semver v1.5.0 // indirect - github.com/OpenPeeDeeP/depguard/v2 v2.1.0 // indirect - github.com/alecthomas/go-check-sumtype v0.1.3 // indirect - github.com/alexkohler/nakedret/v2 v2.0.2 // indirect + github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.0 // indirect + github.com/Masterminds/semver/v3 v3.2.1 // indirect + github.com/OpenPeeDeeP/depguard/v2 v2.2.0 // indirect + github.com/alecthomas/go-check-sumtype v0.1.4 // indirect + github.com/alexkohler/nakedret/v2 v2.0.4 // indirect github.com/alexkohler/prealloc v1.0.0 // indirect github.com/alingse/asasalint v0.0.11 // indirect github.com/ashanbrown/forbidigo v1.6.0 // indirect @@ -29,164 +30,161 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/bkielbasa/cyclop v1.2.1 // indirect github.com/blizzy78/varnamelen v0.8.0 // indirect - github.com/bombsimon/wsl/v3 v3.4.0 // indirect + github.com/bombsimon/wsl/v4 v4.4.1 // indirect github.com/breml/bidichk v0.2.7 // indirect github.com/breml/errchkjson v0.3.6 // indirect - github.com/butuzov/ireturn v0.2.2 // indirect - github.com/butuzov/mirror v1.1.0 // indirect - github.com/catenacyber/perfsprint v0.2.0 // indirect - github.com/ccojocar/zxcvbn-go v1.0.1 // indirect + github.com/butuzov/ireturn v0.3.0 // indirect + github.com/butuzov/mirror v1.2.0 // indirect + github.com/catenacyber/perfsprint v0.7.1 // indirect + github.com/ccojocar/zxcvbn-go v1.0.2 // indirect github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/charithe/durationcheck v0.0.10 // indirect github.com/chavacava/garif v0.1.0 // indirect + github.com/ckaznocha/intrange v0.1.2 // indirect github.com/curioswitch/go-reassign v0.2.0 // indirect - github.com/daixiang0/gci v0.11.2 // indirect + github.com/daixiang0/gci v0.13.4 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/denis-tingaikin/go-header v0.4.3 // indirect - github.com/esimonov/ifshort v1.0.4 // indirect - github.com/ettle/strcase v0.1.1 // indirect - github.com/fatih/color v1.15.0 // indirect + github.com/denis-tingaikin/go-header v0.5.0 // indirect + github.com/ettle/strcase v0.2.0 // indirect + github.com/fatih/color v1.17.0 // indirect github.com/fatih/structtag v1.2.0 // indirect - github.com/firefart/nonamedreturns v1.0.4 // indirect + github.com/firefart/nonamedreturns v1.0.5 // indirect github.com/fsnotify/fsnotify v1.5.4 // indirect github.com/fzipp/gocyclo v0.6.0 // indirect - github.com/ghostiam/protogetter v0.2.3 // indirect - github.com/go-critic/go-critic v0.9.0 // indirect + github.com/ghostiam/protogetter v0.3.6 // indirect + github.com/go-critic/go-critic v0.11.4 // indirect github.com/go-toolsmith/astcast v1.1.0 // indirect github.com/go-toolsmith/astcopy v1.1.0 // indirect - github.com/go-toolsmith/astequal v1.1.0 // indirect + github.com/go-toolsmith/astequal v1.2.0 // indirect github.com/go-toolsmith/astfmt v1.1.0 // indirect github.com/go-toolsmith/astp v1.1.0 // indirect github.com/go-toolsmith/strparse v1.1.0 // indirect github.com/go-toolsmith/typep v1.1.0 // indirect + github.com/go-viper/mapstructure/v2 v2.0.0 // indirect github.com/go-xmlfmt/xmlfmt v1.1.2 // indirect github.com/gobwas/glob v0.2.3 // indirect - github.com/gofrs/flock v0.8.1 // indirect - github.com/golang/protobuf v1.5.2 // indirect - github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 // indirect + github.com/gofrs/flock v0.12.1 // indirect + github.com/golang/protobuf v1.5.3 // indirect github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a // indirect - github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe // indirect github.com/golangci/gofmt v0.0.0-20231018234816-f50ced29576e // indirect - github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 // indirect - github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca // indirect - github.com/golangci/misspell v0.4.1 // indirect - github.com/golangci/revgrep v0.5.2 // indirect - github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 // indirect + github.com/golangci/misspell v0.6.0 // indirect + github.com/golangci/modinfo v0.3.4 // indirect + github.com/golangci/plugin-module-register v0.1.1 // indirect + github.com/golangci/revgrep v0.5.3 // indirect + github.com/golangci/unconvert v0.0.0-20240309020433-c5143eacb3ed // indirect github.com/google/go-cmp v0.6.0 // indirect - github.com/gordonklaus/ineffassign v0.0.0-20230610083614-0e73809eb601 // indirect + github.com/gordonklaus/ineffassign v0.1.0 // indirect github.com/gostaticanalysis/analysisutil v0.7.1 // indirect github.com/gostaticanalysis/comment v1.4.2 // indirect github.com/gostaticanalysis/forcetypeassert v0.1.0 // indirect github.com/gostaticanalysis/nilerr v0.1.1 // indirect - github.com/hashicorp/errwrap v1.0.0 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-version v1.6.0 // indirect + github.com/hashicorp/go-version v1.7.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/jgautheron/goconst v1.6.0 // indirect + github.com/jgautheron/goconst v1.7.1 // indirect github.com/jingyugao/rowserrcheck v1.1.1 // indirect github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af // indirect + github.com/jjti/go-spancheck v0.6.2 // indirect github.com/julz/importas v0.1.0 // indirect - github.com/kisielk/errcheck v1.6.3 // indirect - github.com/kisielk/gotool v1.0.0 // indirect - github.com/kkHAIKE/contextcheck v1.1.4 // indirect + github.com/karamaru-alpha/copyloopvar v1.1.0 // indirect + github.com/kisielk/errcheck v1.7.0 // indirect + github.com/kkHAIKE/contextcheck v1.1.5 // indirect github.com/kulti/thelper v0.6.3 // indirect - github.com/kunwardeep/paralleltest v1.0.8 // indirect + github.com/kunwardeep/paralleltest v1.0.10 // indirect github.com/kyoh86/exportloopref v0.1.11 // indirect - github.com/ldez/gomoddirectives v0.2.3 // indirect + github.com/lasiar/canonicalheader v1.1.1 // indirect + github.com/ldez/gomoddirectives v0.2.4 // indirect github.com/ldez/tagliatelle v0.5.0 // indirect - github.com/leonklingele/grouper v1.1.1 // indirect + github.com/leonklingele/grouper v1.1.2 // indirect github.com/lufeee/execinquery v1.2.1 // indirect - github.com/macabu/inamedparam v0.1.2 // indirect + github.com/macabu/inamedparam v0.1.3 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/maratori/testableexamples v1.0.0 // indirect github.com/maratori/testpackage v1.1.1 // indirect github.com/matoous/godox v0.0.0-20230222163458-006bad1f9d26 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.17 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.9 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect - github.com/mbilski/exhaustivestruct v1.2.0 // indirect - github.com/mgechev/revive v1.3.4 // indirect + github.com/mgechev/revive v1.3.9 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect - github.com/moricho/tparallel v0.3.1 // indirect + github.com/moricho/tparallel v0.3.2 // indirect github.com/nakabonne/nestif v0.3.1 // indirect - github.com/nishanths/exhaustive v0.11.0 // indirect + github.com/nishanths/exhaustive v0.12.0 // indirect github.com/nishanths/predeclared v0.2.2 // indirect - github.com/nunnatsa/ginkgolinter v0.14.1 // indirect + github.com/nunnatsa/ginkgolinter v0.16.2 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pelletier/go-toml v1.9.5 // indirect - github.com/pelletier/go-toml/v2 v2.0.5 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/polyfloyd/go-errorlint v1.4.5 // indirect + github.com/polyfloyd/go-errorlint v1.6.0 // indirect github.com/prometheus/client_golang v1.12.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.32.1 // indirect github.com/prometheus/procfs v0.7.3 // indirect - github.com/quasilyte/go-ruleguard v0.4.0 // indirect + github.com/quasilyte/go-ruleguard v0.4.2 // indirect + github.com/quasilyte/go-ruleguard/dsl v0.3.22 // indirect github.com/quasilyte/gogrep v0.5.0 // indirect github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect - github.com/ryancurrah/gomodguard v1.3.0 // indirect + github.com/ryancurrah/gomodguard v1.3.3 // indirect github.com/ryanrolds/sqlclosecheck v0.5.1 // indirect github.com/sanposhiho/wastedassign/v2 v2.0.7 // indirect + github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 // indirect github.com/sashamelentyev/interfacebloat v1.1.0 // indirect - github.com/sashamelentyev/usestdlibvars v1.24.0 // indirect - github.com/securego/gosec/v2 v2.18.2 // indirect + github.com/sashamelentyev/usestdlibvars v1.27.0 // indirect + github.com/securego/gosec/v2 v2.20.1-0.20240525090044-5f0084eb01a9 // indirect github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sivchari/containedctx v1.0.3 // indirect - github.com/sivchari/nosnakecase v1.7.0 // indirect - github.com/sivchari/tenv v1.7.1 // indirect + github.com/sivchari/tenv v1.10.0 // indirect github.com/sonatard/noctx v0.0.2 // indirect github.com/sourcegraph/go-diff v0.7.0 // indirect - github.com/spf13/afero v1.8.2 // indirect + github.com/spf13/afero v1.11.0 // indirect github.com/spf13/cast v1.5.0 // indirect - github.com/spf13/cobra v1.7.0 // indirect + github.com/spf13/cobra v1.8.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/viper v1.12.0 // indirect github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect github.com/stbenjam/no-sprintf-host-port v0.1.1 // indirect - github.com/stretchr/objx v0.5.0 // indirect - github.com/stretchr/testify v1.8.4 // indirect + github.com/stretchr/objx v0.5.2 // indirect + github.com/stretchr/testify v1.9.0 // indirect github.com/subosito/gotenv v1.4.1 // indirect - github.com/t-yuki/gocover-cobertura v0.0.0-20180217150009-aaee18c8195c // indirect github.com/tdakkota/asciicheck v0.2.0 // indirect - github.com/tetafro/godot v1.4.15 // indirect + github.com/tetafro/godot v1.4.16 // indirect github.com/timakin/bodyclose v0.0.0-20230421092635-574207250966 // indirect github.com/timonwong/loggercheck v0.9.4 // indirect - github.com/tomarrell/wrapcheck/v2 v2.8.1 // indirect + github.com/tomarrell/wrapcheck/v2 v2.8.3 // indirect github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect github.com/ultraware/funlen v0.1.0 // indirect - github.com/ultraware/whitespace v0.0.5 // indirect - github.com/uudashr/gocognit v1.1.2 // indirect + github.com/ultraware/whitespace v0.1.1 // indirect + github.com/uudashr/gocognit v1.1.3 // indirect github.com/xen0n/gosmopolitan v1.2.2 // indirect github.com/yagipy/maintidx v1.0.0 // indirect - github.com/yeya24/promlinter v0.2.0 // indirect - github.com/ykadowak/zerologlint v0.1.3 // indirect - gitlab.com/bosi/decorder v0.4.1 // indirect - go-simpler.org/sloglint v0.1.2 // indirect - go.tmz.dev/musttag v0.7.2 // indirect + github.com/yeya24/promlinter v0.3.0 // indirect + github.com/ykadowak/zerologlint v0.1.5 // indirect + gitlab.com/bosi/decorder v0.4.2 // indirect + go-simpler.org/musttag v0.12.2 // indirect + go-simpler.org/sloglint v0.7.2 // indirect go.uber.org/atomic v1.7.0 // indirect + go.uber.org/automaxprocs v1.5.3 // indirect go.uber.org/multierr v1.6.0 // indirect go.uber.org/zap v1.24.0 // indirect - golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea // indirect - golang.org/x/exp/typeparams v0.0.0-20230307190834-24139beb5833 // indirect - golang.org/x/mod v0.13.0 // indirect - golang.org/x/sync v0.4.0 // indirect - golang.org/x/sys v0.13.0 // indirect - golang.org/x/text v0.13.0 // indirect - golang.org/x/tools v0.14.0 // indirect + golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc // indirect + golang.org/x/exp/typeparams v0.0.0-20240314144324-c7f7c6466f7f // indirect + golang.org/x/mod v0.20.0 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.23.0 // indirect + golang.org/x/text v0.15.0 // indirect + golang.org/x/tools v0.24.0 // indirect google.golang.org/protobuf v1.33.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - honnef.co/go/tools v0.4.6 // indirect - mvdan.cc/gofumpt v0.5.0 // indirect - mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed // indirect - mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b // indirect - mvdan.cc/unparam v0.0.0-20221223090309-7455f1af531d // indirect + honnef.co/go/tools v0.5.0 // indirect + mvdan.cc/gofumpt v0.6.0 // indirect + mvdan.cc/unparam v0.0.0-20240528143540-8a5130ca722f // indirect ) diff --git a/tools/go.sum b/tools/go.sum index 4cc2d73ed..30fe76210 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -7,7 +7,6 @@ cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= @@ -18,9 +17,6 @@ cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKV cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= -cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= @@ -38,41 +34,44 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeo cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/4meepo/tagalign v1.3.3 h1:ZsOxcwGD/jP4U/aw7qeWu58i7dwYemfy5Y+IF1ACoNw= -github.com/4meepo/tagalign v1.3.3/go.mod h1:Q9c1rYMZJc9dPRkbQPpcBNCLEmY2njbAsXhQOZFE2dE= -github.com/Abirdcfly/dupword v0.0.13 h1:SMS17YXypwP000fA7Lr+kfyBQyW14tTT+nRv9ASwUUo= -github.com/Abirdcfly/dupword v0.0.13/go.mod h1:Ut6Ue2KgF/kCOawpW4LnExT+xZLQviJPE4klBPMK/5Y= -github.com/Antonboom/errname v0.1.12 h1:oh9ak2zUtsLp5oaEd/erjB4GPu9w19NyoIskZClDcQY= -github.com/Antonboom/errname v0.1.12/go.mod h1:bK7todrzvlaZoQagP1orKzWXv59X/x0W0Io2XT1Ssro= -github.com/Antonboom/nilnil v0.1.7 h1:ofgL+BA7vlA1K2wNQOsHzLJ2Pw5B5DpWRLdDAVvvTow= -github.com/Antonboom/nilnil v0.1.7/go.mod h1:TP+ScQWVEq0eSIxqU8CbdT5DFWoHp0MbP+KMUO1BKYQ= -github.com/Antonboom/testifylint v0.2.3 h1:MFq9zyL+rIVpsvLX4vDPLojgN7qODzWsrnftNX2Qh60= -github.com/Antonboom/testifylint v0.2.3/go.mod h1:IYaXaOX9NbfAyO+Y04nfjGI8wDemC1rUyM/cYolz018= +github.com/4meepo/tagalign v1.3.4 h1:P51VcvBnf04YkHzjfclN6BbsopfJR5rxs1n+5zHt+w8= +github.com/4meepo/tagalign v1.3.4/go.mod h1:M+pnkHH2vG8+qhE5bVc/zeP7HS/j910Fwa9TUSyZVI0= +github.com/Abirdcfly/dupword v0.0.14 h1:3U4ulkc8EUo+CaT105/GJ1BQwtgyj6+VaBVbAX11Ba8= +github.com/Abirdcfly/dupword v0.0.14/go.mod h1:VKDAbxdY8YbKUByLGg8EETzYSuC4crm9WwI6Y3S0cLI= +github.com/Antonboom/errname v0.1.13 h1:JHICqsewj/fNckzrfVSe+T33svwQxmjC+1ntDsHOVvM= +github.com/Antonboom/errname v0.1.13/go.mod h1:uWyefRYRN54lBg6HseYCFhs6Qjcy41Y3Jl/dVhA87Ns= +github.com/Antonboom/nilnil v0.1.9 h1:eKFMejSxPSA9eLSensFmjW2XTgTwJMjZ8hUHtV4s/SQ= +github.com/Antonboom/nilnil v0.1.9/go.mod h1:iGe2rYwCq5/Me1khrysB4nwI7swQvjclR8/YRPl5ihQ= +github.com/Antonboom/testifylint v1.4.3 h1:ohMt6AHuHgttaQ1xb6SSnxCeK4/rnK7KKzbvs7DmEck= +github.com/Antonboom/testifylint v1.4.3/go.mod h1:+8Q9+AOLsz5ZiQiiYujJKs9mNz398+M6UgslP4qgJLA= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= -github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c h1:pxW6RcqyfI9/kWtOwnv/G+AzdKuy2ZrqINhenH4HyNs= +github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/Crocmagnon/fatcontext v0.4.0 h1:4ykozu23YHA0JB6+thiuEv7iT6xq995qS1vcuWZq0tg= +github.com/Crocmagnon/fatcontext v0.4.0/go.mod h1:ZtWrXkgyfsYPzS6K3O88va6t2GEglG93vnII/F94WC0= github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 h1:sHglBQTwgx+rWPdisA5ynNEsoARbiCBOyGcJM4/OzsM= github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs= -github.com/GaijinEntertainment/go-exhaustruct/v3 v3.1.0 h1:3ZBs7LAezy8gh0uECsA6CGU43FF3zsx5f4eah5FxTMA= -github.com/GaijinEntertainment/go-exhaustruct/v3 v3.1.0/go.mod h1:rZLTje5A9kFBe0pzhpe2TdhRniBF++PRHQuRpR8esVc= -github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= -github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/OpenPeeDeeP/depguard/v2 v2.1.0 h1:aQl70G173h/GZYhWf36aE5H0KaujXfVMnn/f1kSDVYY= -github.com/OpenPeeDeeP/depguard/v2 v2.1.0/go.mod h1:PUBgk35fX4i7JDmwzlJwJ+GMe6NfO1723wmJMgPThNQ= +github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.0 h1:/fTUt5vmbkAcMBt4YQiuC23cV0kEsN1MVMNqeOW43cU= +github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.0/go.mod h1:ONJg5sxcbsdQQ4pOW8TGdTidT2TMAUy/2Xhr8mrYaao= +github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= +github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= +github.com/OpenPeeDeeP/depguard/v2 v2.2.0 h1:vDfG60vDtIuf0MEOhmLlLLSzqaRM8EMcgJPdp74zmpA= +github.com/OpenPeeDeeP/depguard/v2 v2.2.0/go.mod h1:CIzddKRvLBC4Au5aYP/i3nyaWQ+ClszLIuVocRiCYFQ= github.com/alecthomas/assert/v2 v2.2.2 h1:Z/iVC0xZfWTaFNE6bA3z07T86hd45Xe2eLt6WVy2bbk= -github.com/alecthomas/go-check-sumtype v0.1.3 h1:M+tqMxB68hcgccRXBMVCPI4UJ+QUfdSx0xdbypKCqA8= -github.com/alecthomas/go-check-sumtype v0.1.3/go.mod h1:WyYPfhfkdhyrdaligV6svFopZV8Lqdzn5pyVBaV6jhQ= +github.com/alecthomas/assert/v2 v2.2.2/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= +github.com/alecthomas/go-check-sumtype v0.1.4 h1:WCvlB3l5Vq5dZQTFmodqL2g68uHiSwwlWcT5a2FGK0c= +github.com/alecthomas/go-check-sumtype v0.1.4/go.mod h1:WyYPfhfkdhyrdaligV6svFopZV8Lqdzn5pyVBaV6jhQ= github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk= +github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/alexkohler/nakedret/v2 v2.0.2 h1:qnXuZNvv3/AxkAb22q/sEsEpcA99YxLFACDtEw9TPxE= -github.com/alexkohler/nakedret/v2 v2.0.2/go.mod h1:2b8Gkk0GsOrqQv/gPWjNLDSKwG8I5moSXG1K4VIBcTQ= +github.com/alexkohler/nakedret/v2 v2.0.4 h1:yZuKmjqGi0pSmjGpOC016LtPJysIL0WEUiaXW5SUnNg= +github.com/alexkohler/nakedret/v2 v2.0.4/go.mod h1:bF5i0zF2Wo2o4X4USt9ntUWve6JbFv02Ff4vlkmS/VU= github.com/alexkohler/prealloc v1.0.0 h1:Hbq0/3fJPQhNkN0dR95AVrr6R7tou91y0uHG5pOcUuw= github.com/alexkohler/prealloc v1.0.0/go.mod h1:VetnK3dIgFBBKmg0YnD9F9x6Icjd+9cvfHR56wJVlKE= github.com/alingse/asasalint v0.0.11 h1:SFwnQXJ49Kx/1GghOFz1XGqHYKp21Kq1nHad/0WQRnw= @@ -82,6 +81,7 @@ github.com/ashanbrown/forbidigo v1.6.0/go.mod h1:Y8j9jy9ZYAEHXdu723cUlraTqbzjKF1 github.com/ashanbrown/makezero v1.1.1 h1:iCQ87C0V0vSyO+M9E/FZYbu65auqH0lnsOkf5FcB28s= github.com/ashanbrown/makezero v1.1.1/go.mod h1:i1bJLCRSCHOcOa9Y6MyF2FTfMZMFdHvxKHxgO5Z1axI= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -90,20 +90,20 @@ github.com/bkielbasa/cyclop v1.2.1 h1:AeF71HZDob1P2/pRm1so9cd1alZnrpyc4q2uP2l0gJ github.com/bkielbasa/cyclop v1.2.1/go.mod h1:K/dT/M0FPAiYjBgQGau7tz+3TMh4FWAEqlMhzFWCrgM= github.com/blizzy78/varnamelen v0.8.0 h1:oqSblyuQvFsW1hbBHh1zfwrKe3kcSj0rnXkKzsQ089M= github.com/blizzy78/varnamelen v0.8.0/go.mod h1:V9TzQZ4fLJ1DSrjVDfl89H7aMnTvKkApdHeyESmyR7k= -github.com/bombsimon/wsl/v3 v3.4.0 h1:RkSxjT3tmlptwfgEgTgU+KYKLI35p/tviNXNXiL2aNU= -github.com/bombsimon/wsl/v3 v3.4.0/go.mod h1:KkIB+TXkqy6MvK9BDZVbZxKNYsE1/oLRJbIFtf14qqo= +github.com/bombsimon/wsl/v4 v4.4.1 h1:jfUaCkN+aUpobrMO24zwyAMwMAV5eSziCkOKEauOLdw= +github.com/bombsimon/wsl/v4 v4.4.1/go.mod h1:Xu/kDxGZTofQcDGCtQe9KCzhHphIe0fDuyWTxER9Feo= github.com/breml/bidichk v0.2.7 h1:dAkKQPLl/Qrk7hnP6P+E0xOodrq8Us7+U0o4UBOAlQY= github.com/breml/bidichk v0.2.7/go.mod h1:YodjipAGI9fGcYM7II6wFvGhdMYsC5pHDlGzqvEW3tQ= github.com/breml/errchkjson v0.3.6 h1:VLhVkqSBH96AvXEyclMR37rZslRrY2kcyq+31HCsVrA= github.com/breml/errchkjson v0.3.6/go.mod h1:jhSDoFheAF2RSDOlCfhHO9KqhZgAYLyvHe7bRCX8f/U= -github.com/butuzov/ireturn v0.2.2 h1:jWI36dxXwVrI+RnXDwux2IZOewpmfv930OuIRfaBUJ0= -github.com/butuzov/ireturn v0.2.2/go.mod h1:RfGHUvvAuFFxoHKf4Z8Yxuh6OjlCw1KvR2zM1NFHeBk= -github.com/butuzov/mirror v1.1.0 h1:ZqX54gBVMXu78QLoiqdwpl2mgmoOJTk7s4p4o+0avZI= -github.com/butuzov/mirror v1.1.0/go.mod h1:8Q0BdQU6rC6WILDiBM60DBfvV78OLJmMmixe7GF45AE= -github.com/catenacyber/perfsprint v0.2.0 h1:azOocHLscPjqXVJ7Mf14Zjlkn4uNua0+Hcg1wTR6vUo= -github.com/catenacyber/perfsprint v0.2.0/go.mod h1:/wclWYompEyjUD2FuIIDVKNkqz7IgBIWXIH3V0Zol50= -github.com/ccojocar/zxcvbn-go v1.0.1 h1:+sxrANSCj6CdadkcMnvde/GWU1vZiiXRbqYSCalV4/4= -github.com/ccojocar/zxcvbn-go v1.0.1/go.mod h1:g1qkXtUSvHP8lhHp5GrSmTz6uWALGRMQdw6Qnz/hi60= +github.com/butuzov/ireturn v0.3.0 h1:hTjMqWw3y5JC3kpnC5vXmFJAWI/m31jaCYQqzkS6PL0= +github.com/butuzov/ireturn v0.3.0/go.mod h1:A09nIiwiqzN/IoVo9ogpa0Hzi9fex1kd9PSD6edP5ZA= +github.com/butuzov/mirror v1.2.0 h1:9YVK1qIjNspaqWutSv8gsge2e/Xpq1eqEkslEUHy5cs= +github.com/butuzov/mirror v1.2.0/go.mod h1:DqZZDtzm42wIAIyHXeN8W/qb1EPlb9Qn/if9icBOpdQ= +github.com/catenacyber/perfsprint v0.7.1 h1:PGW5G/Kxn+YrN04cRAZKC+ZuvlVwolYMrIyyTJ/rMmc= +github.com/catenacyber/perfsprint v0.7.1/go.mod h1:/wclWYompEyjUD2FuIIDVKNkqz7IgBIWXIH3V0Zol50= +github.com/ccojocar/zxcvbn-go v1.0.2 h1:na/czXU8RrhXO4EZme6eQJLR4PzcGsahsBOAwU6I3Vg= +github.com/ccojocar/zxcvbn-go v1.0.2/go.mod h1:g1qkXtUSvHP8lhHp5GrSmTz6uWALGRMQdw6Qnz/hi60= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= @@ -115,45 +115,42 @@ github.com/chavacava/garif v0.1.0/go.mod h1:XMyYCkEL58DF0oyW4qDjjnPWONs2HBqYKI+U github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/ckaznocha/intrange v0.1.2 h1:3Y4JAxcMntgb/wABQ6e8Q8leMd26JbX2790lIss9MTI= +github.com/ckaznocha/intrange v0.1.2/go.mod h1:RWffCw/vKBwHeOEwWdCikAtY0q4gGt8VhJZEEA5n+RE= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/curioswitch/go-reassign v0.2.0 h1:G9UZyOcpk/d7Gd6mqYgd8XYWFMw/znxwGDUstnC9DIo= github.com/curioswitch/go-reassign v0.2.0/go.mod h1:x6OpXuWvgfQaMGks2BZybTngWjT84hqJfKoO8Tt/Roc= -github.com/daixiang0/gci v0.11.2 h1:Oji+oPsp3bQ6bNNgX30NBAVT18P4uBH4sRZnlOlTj7Y= -github.com/daixiang0/gci v0.11.2/go.mod h1:xtHP9N7AHdNvtRNfcx9gwTDfw7FRJx4bZUsiEfiNNAI= +github.com/daixiang0/gci v0.13.4 h1:61UGkmpoAcxHM2hhNkZEf5SzwQtWJXTSws7jaPyqwlw= +github.com/daixiang0/gci v0.13.4/go.mod h1:12etP2OniiIdP4q+kjUGrC/rUagga7ODbqsom5Eo5Yk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/denis-tingaikin/go-header v0.4.3 h1:tEaZKAlqql6SKCY++utLmkPLd6K8IBM20Ha7UVm+mtU= -github.com/denis-tingaikin/go-header v0.4.3/go.mod h1:0wOCWuN71D5qIgE2nz9KrKmuYBAC2Mra5RassOIQ2/c= +github.com/denis-tingaikin/go-header v0.5.0 h1:SRdnP5ZKvcO9KKRP1KJrhFR3RrlGuD+42t4429eC9k8= +github.com/denis-tingaikin/go-header v0.5.0/go.mod h1:mMenU5bWrok6Wl2UsZjy+1okegmwQ3UgWl4V1D8gjlY= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/esimonov/ifshort v1.0.4 h1:6SID4yGWfRae/M7hkVDVVyppy8q/v9OuxNdmjLQStBA= -github.com/esimonov/ifshort v1.0.4/go.mod h1:Pe8zjlRrJ80+q2CxHLfEOfTwxCZ4O+MuhcHcfgNWTk0= -github.com/ettle/strcase v0.1.1 h1:htFueZyVeE1XNnMEfbqp5r67qAN/4r6ya1ysq8Q+Zcw= -github.com/ettle/strcase v0.1.1/go.mod h1:hzDLsPC7/lwKyBOywSHEP89nt2pDgdy+No1NBA9o9VY= -github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= -github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= +github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= +github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= +github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4= +github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI= github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4= github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= -github.com/firefart/nonamedreturns v1.0.4 h1:abzI1p7mAEPYuR4A+VLKn4eNDOycjYo2phmY9sfv40Y= -github.com/firefart/nonamedreturns v1.0.4/go.mod h1:TDhe/tjI1BXo48CmYbUduTV7BdIga8MAO/xbKdcVsGI= -github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= +github.com/firefart/nonamedreturns v1.0.5 h1:tM+Me2ZaXs8tfdDw3X6DOX++wMCOqzYUho6tUTYIdRA= +github.com/firefart/nonamedreturns v1.0.5/go.mod h1:gHJjDqhGM4WyPt639SOZs+G89Ko7QKH5R5BhnO6xJhw= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo= github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= -github.com/ghostiam/protogetter v0.2.3 h1:qdv2pzo3BpLqezwqfGDLZ+nHEYmc5bUpIdsMbBVwMjw= -github.com/ghostiam/protogetter v0.2.3/go.mod h1:KmNLOsy1v04hKbvZs8EfGI1fk39AgTdRDxWNYPfXVc4= -github.com/go-critic/go-critic v0.9.0 h1:Pmys9qvU3pSML/3GEQ2Xd9RZ/ip+aXHKILuxczKGV/U= -github.com/go-critic/go-critic v0.9.0/go.mod h1:5P8tdXL7m/6qnyG6oRAlYLORvoXH0WDypYgAEmagT40= +github.com/ghostiam/protogetter v0.3.6 h1:R7qEWaSgFCsy20yYHNIJsU9ZOb8TziSRRxuAOTVKeOk= +github.com/ghostiam/protogetter v0.3.6/go.mod h1:7lpeDnEJ1ZjL/YtyoN99ljO4z0pd3H0d18/t2dPBxHw= +github.com/go-critic/go-critic v0.11.4 h1:O7kGOCx0NDIni4czrkRIXTnit0mkyKOCePh3My6OyEU= +github.com/go-critic/go-critic v0.11.4/go.mod h1:2QAdo4iuLik5S9YG0rT4wcZ8QxwHYkrr6/2MWAiv/vc= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -163,32 +160,38 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/go-toolsmith/astcast v1.1.0 h1:+JN9xZV1A+Re+95pgnMgDboWNVnIMMQXwfBwLRPgSC8= github.com/go-toolsmith/astcast v1.1.0/go.mod h1:qdcuFWeGGS2xX5bLM/c3U9lewg7+Zu4mr+xPwZIB4ZU= github.com/go-toolsmith/astcopy v1.1.0 h1:YGwBN0WM+ekI/6SS6+52zLDEf8Yvp3n2seZITCUBt5s= github.com/go-toolsmith/astcopy v1.1.0/go.mod h1:hXM6gan18VA1T/daUEHCFcYiW8Ai1tIwIzHY6srfEAw= github.com/go-toolsmith/astequal v1.0.3/go.mod h1:9Ai4UglvtR+4up+bAD4+hCj7iTo4m/OXVTSLnCyTAx4= -github.com/go-toolsmith/astequal v1.1.0 h1:kHKm1AWqClYn15R0K1KKE4RG614D46n+nqUQ06E1dTw= github.com/go-toolsmith/astequal v1.1.0/go.mod h1:sedf7VIdCL22LD8qIvv7Nn9MuWJruQA/ysswh64lffQ= +github.com/go-toolsmith/astequal v1.2.0 h1:3Fs3CYZ1k9Vo4FzFhwwewC3CHISHDnVUPC4x0bI2+Cw= +github.com/go-toolsmith/astequal v1.2.0/go.mod h1:c8NZ3+kSFtFY/8lPso4v8LuJjdJiUFVnSuU3s0qrrDY= github.com/go-toolsmith/astfmt v1.1.0 h1:iJVPDPp6/7AaeLJEruMsBUlOYCmvg0MoCfJprsOmcco= github.com/go-toolsmith/astfmt v1.1.0/go.mod h1:OrcLlRwu0CuiIBp/8b5PYF9ktGVZUjlNMV634mhwuQ4= github.com/go-toolsmith/astp v1.1.0 h1:dXPuCl6u2llURjdPLLDxJeZInAeZ0/eZwFJmqZMnpQA= github.com/go-toolsmith/astp v1.1.0/go.mod h1:0T1xFGz9hicKs8Z5MfAqSUitoUYS30pDMsRVIDHs8CA= github.com/go-toolsmith/pkgload v1.2.2 h1:0CtmHq/02QhxcF7E9N5LIFcYFsMR5rdovfqTtRKkgIk= +github.com/go-toolsmith/pkgload v1.2.2/go.mod h1:R2hxLNRKuAsiXCo2i5J6ZQPhnPMOVtU+f0arbFPWCus= github.com/go-toolsmith/strparse v1.0.0/go.mod h1:YI2nUKP9YGZnL/L1/DLFBfixrcjslWct4wyljWhSRy8= github.com/go-toolsmith/strparse v1.1.0 h1:GAioeZUK9TGxnLS+qfdqNbA4z0SSm5zVNtCQiyP2Bvw= github.com/go-toolsmith/strparse v1.1.0/go.mod h1:7ksGy58fsaQkGQlY8WVoBFNyEPMGuJin1rfoPS4lBSQ= github.com/go-toolsmith/typep v1.1.0 h1:fIRYDyF+JywLfqzyhdiHzRop/GQDxxNhLGQ6gFUNHus= github.com/go-toolsmith/typep v1.1.0/go.mod h1:fVIw+7zjdsMxDA3ITWnH1yOiw1rnTQKCsF/sk2H/qig= +github.com/go-viper/mapstructure/v2 v2.0.0 h1:dhn8MZ1gZ0mzeodTG3jt5Vj/o87xZKuNAprG2mQfMfc= +github.com/go-viper/mapstructure/v2 v2.0.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/go-xmlfmt/xmlfmt v1.1.2 h1:Nea7b4icn8s57fTx1M5AI4qQT5HEM3rVUO8MuE6g80U= github.com/go-xmlfmt/xmlfmt v1.1.2/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= -github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= +github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= +github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -216,28 +219,25 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 h1:23T5iq8rbUYlhpt5DB4XJkc6BU31uODLD1o1gKvZmD0= -github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2/go.mod h1:k9Qvh+8juN+UKMCS/3jFtGICgW8O96FVaZsaxdzDkR4= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a h1:w8hkcTqaFpzKqonE9uMCefW1WDie15eSP/4MssdenaM= github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a/go.mod h1:ryS0uhF+x9jgbj/N71xsEqODy9BN81/GonCZiOzirOk= -github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe h1:6RGUuS7EGotKx6J5HIP8ZtyMdiDscjMLfRBSPuzVVeo= -github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe/go.mod h1:gjqyPShc/m8pEMpk0a3SeagVb0kaqvhscv+i9jI5ZhQ= github.com/golangci/gofmt v0.0.0-20231018234816-f50ced29576e h1:ULcKCDV1LOZPFxGZaA6TlQbiM3J2GCPnkx/bGF6sX/g= github.com/golangci/gofmt v0.0.0-20231018234816-f50ced29576e/go.mod h1:Pm5KhLPA8gSnQwrQ6ukebRcapGb/BG9iUkdaiCcGHJM= -github.com/golangci/golangci-lint v1.55.2 h1:yllEIsSJ7MtlDBwDJ9IMBkyEUz2fYE0b5B8IUgO1oP8= -github.com/golangci/golangci-lint v1.55.2/go.mod h1:H60CZ0fuqoTwlTvnbyjhpZPWp7KmsjwV2yupIMiMXbM= -github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 h1:MfyDlzVjl1hoaPzPD4Gpb/QgoRfSBR0jdhwGyAWwMSA= -github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= -github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca h1:kNY3/svz5T29MYHubXix4aDDuE3RWHkPvopM/EDv/MA= -github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca/go.mod h1:tvlJhZqDe4LMs4ZHD0oMUlt9G2LWuDGoisJTBzLMV9o= -github.com/golangci/misspell v0.4.1 h1:+y73iSicVy2PqyX7kmUefHusENlrP9YwuHZHPLGQj/g= -github.com/golangci/misspell v0.4.1/go.mod h1:9mAN1quEo3DlpbaIKKyEvRxK1pwqR9s/Sea1bJCtlNI= -github.com/golangci/revgrep v0.5.2 h1:EndcWoRhcnfj2NHQ+28hyuXpLMF+dQmCN+YaeeIl4FU= -github.com/golangci/revgrep v0.5.2/go.mod h1:bjAMA+Sh/QUfTDcHzxfyHxr4xKvllVr/0sCv2e7jJHA= -github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 h1:zwtduBRr5SSWhqsYNgcuWO2kFlpdOZbP0+yRjmvPGys= -github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4/go.mod h1:Izgrg8RkN3rCIMLGE9CyYmU9pY2Jer6DgANEnZ/L/cQ= +github.com/golangci/golangci-lint v1.60.1 h1:DRKNqNTQRLBJZ1il5u4fvgLQCjQc7QFs0DbhksJtVJE= +github.com/golangci/golangci-lint v1.60.1/go.mod h1:jDIPN1rYaIA+ijp9OZcUmUCoQOtZ76pOlFbi15FlLJY= +github.com/golangci/misspell v0.6.0 h1:JCle2HUTNWirNlDIAUO44hUsKhOFqGPoC4LZxlaSXDs= +github.com/golangci/misspell v0.6.0/go.mod h1:keMNyY6R9isGaSAu+4Q8NMBwMPkh15Gtc8UCVoDtAWo= +github.com/golangci/modinfo v0.3.4 h1:oU5huX3fbxqQXdfspamej74DFX0kyGLkw1ppvXoJ8GA= +github.com/golangci/modinfo v0.3.4/go.mod h1:wytF1M5xl9u0ij8YSvhkEVPP3M5Mc7XLl1pxH3B2aUM= +github.com/golangci/plugin-module-register v0.1.1 h1:TCmesur25LnyJkpsVrupv1Cdzo+2f7zX0H6Jkw1Ol6c= +github.com/golangci/plugin-module-register v0.1.1/go.mod h1:TTpqoB6KkwOJMV8u7+NyXMrkwwESJLOkfl9TxR1DGFc= +github.com/golangci/revgrep v0.5.3 h1:3tL7c1XBMtWHHqVpS5ChmiAAoe4PF/d5+ULzV9sLAzs= +github.com/golangci/revgrep v0.5.3/go.mod h1:U4R/s9dlXZsg8uJmaR1GrloUr14D7qDl8gi2iPXJH8k= +github.com/golangci/unconvert v0.0.0-20240309020433-c5143eacb3ed h1:IURFTjxeTfNFP0hTEi1YKjB/ub8zkpaOqFFMApi2EAs= +github.com/golangci/unconvert v0.0.0-20240309020433-c5143eacb3ed/go.mod h1:XLXN8bNw4CGRPaqgl3bv/lhz7bsGPh4/xSaMTbo2vkQ= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= @@ -257,7 +257,6 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= @@ -265,17 +264,13 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE= +github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6 h1:k7nVchz72niMH6YLQNvHSdIE7iqsQxK1P41mySCvssg= +github.com/google/pprof v0.0.0-20240424215950-a892ee059fd6/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= -github.com/gordonklaus/ineffassign v0.0.0-20230610083614-0e73809eb601 h1:mrEEilTAUmaAORhssPPkxj84TsHrPMLBGW2Z4SoTxm8= -github.com/gordonklaus/ineffassign v0.0.0-20230610083614-0e73809eb601/go.mod h1:Qcp2HIAYhR7mNUVSIxZww3Guk4it82ghYcEXIAk+QT0= +github.com/gordonklaus/ineffassign v0.1.0 h1:y2Gd/9I7MdY1oEIt+n+rowjBNDcLQq3RsH5hwJd0f9s= +github.com/gordonklaus/ineffassign v0.1.0/go.mod h1:Qcp2HIAYhR7mNUVSIxZww3Guk4it82ghYcEXIAk+QT0= github.com/gostaticanalysis/analysisutil v0.7.1 h1:ZMCjoue3DtDWQ5WyU16YbjbQEQ3VuzwxALrpYd+HeKk= github.com/gostaticanalysis/analysisutil v0.7.1/go.mod h1:v21E3hY37WKMGSnbsw2S/ojApNWb6C1//mXO48CXbVc= github.com/gostaticanalysis/comment v1.4.1/go.mod h1:ih6ZxzTHLdadaiSnF5WY3dxUoXfXAlTaRzuaNDlSado= @@ -287,13 +282,10 @@ github.com/gostaticanalysis/nilerr v0.1.1 h1:ThE+hJP0fEp4zWLkWHWcRyI2Od0p7DlgYG3 github.com/gostaticanalysis/nilerr v0.1.1/go.mod h1:wZYb6YI5YAxxq0i1+VJbY0s2YONW0HU0GPE3+5PWN4A= github.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M= github.com/gostaticanalysis/testutil v0.4.0 h1:nhdCmubdmDF6VEatUNjgUZBJKWRqugoISdUv3PPQgHY= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/gostaticanalysis/testutil v0.4.0/go.mod h1:bLIoPefWXrRi/ssLFWX1dx7Repi5x3CuviD3dgAZaBU= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= -github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY= +github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= @@ -301,15 +293,16 @@ github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jgautheron/goconst v1.6.0 h1:gbMLWKRMkzAc6kYsQL6/TxaoBUg3Jm9LSF/Ih1ADWGA= -github.com/jgautheron/goconst v1.6.0/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= +github.com/jgautheron/goconst v1.7.1 h1:VpdAG7Ca7yvvJk5n8dMwQhfEZJh95kl/Hl9S1OI5Jkk= +github.com/jgautheron/goconst v1.7.1/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= github.com/jingyugao/rowserrcheck v1.1.1 h1:zibz55j/MJtLsjP1OF4bSdgXxwL1b+Vn7Tjzq7gFzUs= github.com/jingyugao/rowserrcheck v1.1.1/go.mod h1:4yvlZSDb3IyDTUZJUmpZfm2Hwok+Dtp+nu2qOq+er9c= github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af h1:KA9BjwUk7KlCh6S9EAGWBt1oExIUv9WyNCiRz5amv48= github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af/go.mod h1:HEWGJkRDzjJY2sqdDwxccsGicWEf9BQOZsq2tV+xzM0= +github.com/jjti/go-spancheck v0.6.2 h1:iYtoxqPMzHUPp7St+5yA8+cONdyXD3ug6KK15n7Pklk= +github.com/jjti/go-spancheck v0.6.2/go.mod h1:+X7lvIrR5ZdUTkxFYqzJ0abr8Sb5LOo80uOhWNqIrYA= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -321,37 +314,41 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/julz/importas v0.1.0 h1:F78HnrsjY3cR7j0etXy5+TU1Zuy7Xt08X/1aJnH5xXY= github.com/julz/importas v0.1.0/go.mod h1:oSFU2R4XK/P7kNBrnL/FEQlDGN1/6WoxXEjSSXO0DV0= -github.com/kisielk/errcheck v1.6.3 h1:dEKh+GLHcWm2oN34nMvDzn1sqI0i0WxPvrgiJA5JuM8= -github.com/kisielk/errcheck v1.6.3/go.mod h1:nXw/i/MfnvRHqXa7XXmQMUB0oNFGuBrNI8d8NLy0LPw= -github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= +github.com/karamaru-alpha/copyloopvar v1.1.0 h1:x7gNyKcC2vRBO1H2Mks5u1VxQtYvFiym7fCjIP8RPos= +github.com/karamaru-alpha/copyloopvar v1.1.0/go.mod h1:u7CIfztblY0jZLOQZgH3oYsJzpC2A7S6u/lfgSXHy0k= +github.com/kisielk/errcheck v1.7.0 h1:+SbscKmWJ5mOK/bO1zS60F5I9WwZDWOfRsC4RwfwRV0= +github.com/kisielk/errcheck v1.7.0/go.mod h1:1kLL+jV4e+CFfueBmI1dSK2ADDyQnlrnrY/FqKluHJQ= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/kkHAIKE/contextcheck v1.1.4 h1:B6zAaLhOEEcjvUgIYEqystmnFk1Oemn8bvJhbt0GMb8= -github.com/kkHAIKE/contextcheck v1.1.4/go.mod h1:1+i/gWqokIa+dm31mqGLZhZJ7Uh44DJGZVmr6QRBNJg= +github.com/kkHAIKE/contextcheck v1.1.5 h1:CdnJh63tcDe53vG+RebdpdXJTc9atMgGqdx8LXxiilg= +github.com/kkHAIKE/contextcheck v1.1.5/go.mod h1:O930cpht4xb1YQpK+1+AgoM3mFsvxr7uyFptcnWTYUA= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kulti/thelper v0.6.3 h1:ElhKf+AlItIu+xGnI990no4cE2+XaSu1ULymV2Yulxs= github.com/kulti/thelper v0.6.3/go.mod h1:DsqKShOvP40epevkFrvIwkCMNYxMeTNjdWL4dqWHZ6I= -github.com/kunwardeep/paralleltest v1.0.8 h1:Ul2KsqtzFxTlSU7IP0JusWlLiNqQaloB9vguyjbE558= -github.com/kunwardeep/paralleltest v1.0.8/go.mod h1:2C7s65hONVqY7Q5Efj5aLzRCNLjw2h4eMc9EcypGjcY= +github.com/kunwardeep/paralleltest v1.0.10 h1:wrodoaKYzS2mdNVnc4/w31YaXFtsc21PCTdvWJ/lDDs= +github.com/kunwardeep/paralleltest v1.0.10/go.mod h1:2C7s65hONVqY7Q5Efj5aLzRCNLjw2h4eMc9EcypGjcY= github.com/kyoh86/exportloopref v0.1.11 h1:1Z0bcmTypkL3Q4k+IDHMWTcnCliEZcaPiIe0/ymEyhQ= github.com/kyoh86/exportloopref v0.1.11/go.mod h1:qkV4UF1zGl6EkF1ox8L5t9SwyeBAZ3qLMd6up458uqA= -github.com/ldez/gomoddirectives v0.2.3 h1:y7MBaisZVDYmKvt9/l1mjNCiSA1BVn34U0ObUcJwlhA= -github.com/ldez/gomoddirectives v0.2.3/go.mod h1:cpgBogWITnCfRq2qGoDkKMEVSaarhdBr6g8G04uz6d0= +github.com/lasiar/canonicalheader v1.1.1 h1:wC+dY9ZfiqiPwAexUApFush/csSPXeIi4QqyxXmng8I= +github.com/lasiar/canonicalheader v1.1.1/go.mod h1:cXkb3Dlk6XXy+8MVQnF23CYKWlyA7kfQhSw2CcZtZb0= +github.com/ldez/gomoddirectives v0.2.4 h1:j3YjBIjEBbqZ0NKtBNzr8rtMHTOrLPeiwTkfUJZ3alg= +github.com/ldez/gomoddirectives v0.2.4/go.mod h1:oWu9i62VcQDYp9EQ0ONTfqLNh+mDLWWDO+SO0qSQw5g= github.com/ldez/tagliatelle v0.5.0 h1:epgfuYt9v0CG3fms0pEgIMNPuFf/LpPIfjk4kyqSioo= github.com/ldez/tagliatelle v0.5.0/go.mod h1:rj1HmWiL1MiKQuOONhd09iySTEkUuE/8+5jtPYz9xa4= -github.com/leonklingele/grouper v1.1.1 h1:suWXRU57D4/Enn6pXR0QVqqWWrnJ9Osrz+5rjt8ivzU= -github.com/leonklingele/grouper v1.1.1/go.mod h1:uk3I3uDfi9B6PeUjsCKi6ndcf63Uy7snXgR4yDYQVDY= +github.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY= +github.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA= github.com/lufeee/execinquery v1.2.1 h1:hf0Ems4SHcUGBxpGN7Jz78z1ppVkP/837ZlETPCEtOM= github.com/lufeee/execinquery v1.2.1/go.mod h1:EC7DrEKView09ocscGHC+apXMIaorh4xqSxS/dy8SbM= -github.com/macabu/inamedparam v0.1.2 h1:RR5cnayM6Q7cDhQol32DE2BGAPGMnffJ31LFE+UklaU= -github.com/macabu/inamedparam v0.1.2/go.mod h1:Xg25QvY7IBRl1KLPV9Rbml8JOMZtF/iAkNkmV7eQgjw= +github.com/macabu/inamedparam v0.1.3 h1:2tk/phHkMlEL/1GNe/Yf6kkR/hkcUdAEY3L0hjYV1Mk= +github.com/macabu/inamedparam v0.1.3/go.mod h1:93FLICAIk/quk7eaPPQvbzihUdn/QkGDwIZEoLtpH6I= github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/maratori/testableexamples v1.0.0 h1:dU5alXRrD8WKSjOUnmJZuzdxWOEQ57+7s93SLMxb2vI= @@ -365,16 +362,14 @@ github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwM github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= -github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/mbilski/exhaustivestruct v1.2.0 h1:wCBmUnSYufAHO6J4AVWY6ff+oxWxsVFrwgOdMUQePUo= -github.com/mbilski/exhaustivestruct v1.2.0/go.mod h1:OeTBVxQWoEmB2J2JCHmXWPJ0aksxSUOUy+nvtVEfzXc= -github.com/mgechev/revive v1.3.4 h1:k/tO3XTaWY4DEHal9tWBkkUMJYO/dLDVyMmAQxmIMDc= -github.com/mgechev/revive v1.3.4/go.mod h1:W+pZCMu9qj8Uhfs1iJMQsEFLRozUfvwFwqVvRbSNLVw= +github.com/mgechev/revive v1.3.9 h1:18Y3R4a2USSBF+QZKFQwVkBROUda7uoBlkEuBD+YD1A= +github.com/mgechev/revive v1.3.9/go.mod h1:+uxEIr5UH0TjXWHTno3xh4u7eg6jDpXKzQccA9UGhHU= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= @@ -384,42 +379,45 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/moricho/tparallel v0.3.1 h1:fQKD4U1wRMAYNngDonW5XupoB/ZGJHdpzrWqgyg9krA= -github.com/moricho/tparallel v0.3.1/go.mod h1:leENX2cUv7Sv2qDgdi0D0fCftN8fRC67Bcn8pqzeYNI= +github.com/moricho/tparallel v0.3.2 h1:odr8aZVFA3NZrNybggMkYO3rgPRcqjeQUlBBFVxKHTI= +github.com/moricho/tparallel v0.3.2/go.mod h1:OQ+K3b4Ln3l2TZveGCywybl68glfLEwFGqvnjok8b+U= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/nakabonne/nestif v0.3.1 h1:wm28nZjhQY5HyYPx+weN3Q65k6ilSBxDb8v5S81B81U= github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= -github.com/nishanths/exhaustive v0.11.0 h1:T3I8nUGhl/Cwu5Z2hfc92l0e04D2GEW6e0l8pzda2l0= -github.com/nishanths/exhaustive v0.11.0/go.mod h1:RqwDsZ1xY0dNdqHho2z6X+bgzizwbLYOWnZbbl2wLB4= +github.com/nishanths/exhaustive v0.12.0 h1:vIY9sALmw6T/yxiASewa4TQcFsVYZQQRUQJhKRf3Swg= +github.com/nishanths/exhaustive v0.12.0/go.mod h1:mEZ95wPIZW+x8kC4TgC+9YCUgiST7ecevsVDTgc2obs= github.com/nishanths/predeclared v0.2.2 h1:V2EPdZPliZymNAn79T8RkNApBjMmVKh5XRpLm/w98Vk= github.com/nishanths/predeclared v0.2.2/go.mod h1:RROzoN6TnGQupbC+lqggsOlcgysk3LMK/HI84Mp280c= -github.com/nunnatsa/ginkgolinter v0.14.1 h1:khx0CqR5U4ghsscjJ+lZVthp3zjIFytRXPTaQ/TMiyA= -github.com/nunnatsa/ginkgolinter v0.14.1/go.mod h1:nY0pafUSst7v7F637e7fymaMlQqI9c0Wka2fGsDkzWg= +github.com/nunnatsa/ginkgolinter v0.16.2 h1:8iLqHIZvN4fTLDC0Ke9tbSZVcyVHoBs0HIbnVSxfHJk= +github.com/nunnatsa/ginkgolinter v0.16.2/go.mod h1:4tWRinDN1FeJgU+iJANW/kz7xKN5nYRAOfJDQUS9dOQ= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onsi/ginkgo/v2 v2.13.0 h1:0jY9lJquiL8fcf3M4LAXN5aMlS/b2BV86HFFPCPMgE4= -github.com/onsi/gomega v1.28.1 h1:MijcGUbfYuznzK/5R4CPNoUP/9Xvuo20sXfEm6XxoTA= +github.com/onsi/ginkgo/v2 v2.17.3 h1:oJcvKpIb7/8uLpDDtnQuf18xVnwKp8DTD7DQ6gTd/MU= +github.com/onsi/ginkgo/v2 v2.17.3/go.mod h1:nP2DPOQoNsQmsVyv5rDA8JkXQoCs6goXIvr/PRJ1eCc= +github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= +github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw= -github.com/otiai10/copy v1.11.0 h1:OKBD80J/mLBrwnzXqGtFCzprFSGioo30JcmR4APsNwc= +github.com/otiai10/copy v1.14.0 h1:dCI/t1iTdYGtkvCuBG2BgR6KZa83PTclw4U5n2wAllU= +github.com/otiai10/copy v1.14.0/go.mod h1:ECfuL02W+/FkTWZWgQqXPWZgW9oeKCSQ5qVfSc4qc4w= github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= github.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pelletier/go-toml/v2 v2.0.5 h1:ipoSadvV8oGUjnUbMub59IDPPwfxF694nG/jwbMiyQg= -github.com/pelletier/go-toml/v2 v2.0.5/go.mod h1:OMHamSCAODeSsVrwwvcJOaoN0LIUIaFVNZzmWyNfXas= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/polyfloyd/go-errorlint v1.4.5 h1:70YWmMy4FgRHehGNOUask3HtSFSOLKgmDn7ryNe7LqI= -github.com/polyfloyd/go-errorlint v1.4.5/go.mod h1:sIZEbFoDOCnTYYZoVkjc4hTnM459tuWA9H/EkdXwsKk= +github.com/polyfloyd/go-errorlint v1.6.0 h1:tftWV9DE7txiFzPpztTAwyoRLKNj9gpVm2cg8/OwcYY= +github.com/polyfloyd/go-errorlint v1.6.0/go.mod h1:HR7u8wuP1kb1NeN1zqTd1ZMlqUKPPHF+Id4vIPvDqVw= +github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= +github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= @@ -442,8 +440,10 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/quasilyte/go-ruleguard v0.4.0 h1:DyM6r+TKL+xbKB4Nm7Afd1IQh9kEUKQs2pboWGKtvQo= -github.com/quasilyte/go-ruleguard v0.4.0/go.mod h1:Eu76Z/R8IXtViWUIHkE3p8gdH3/PKk1eh3YGfaEof10= +github.com/quasilyte/go-ruleguard v0.4.2 h1:htXcXDK6/rO12kiTHKfHuqR4kr3Y4M0J0rOL6CH/BYs= +github.com/quasilyte/go-ruleguard v0.4.2/go.mod h1:GJLgqsLeo4qgavUoL8JeGFNS7qcisx3awV/w9eWTmNI= +github.com/quasilyte/go-ruleguard/dsl v0.3.22 h1:wd8zkOhSNr+I+8Qeciml08ivDt1pSXe60+5DqOpCjPE= +github.com/quasilyte/go-ruleguard/dsl v0.3.22/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= github.com/quasilyte/gogrep v0.5.0 h1:eTKODPXbI8ffJMN+W2aE0+oL0z/nh8/5eNdiO34SOAo= github.com/quasilyte/gogrep v0.5.0/go.mod h1:Cm9lpz9NZjEoL1tgZ2OgeUKPIxL1meE7eo60Z6Sk+Ng= github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 h1:TCg2WBOl980XxGFEZSS6KlBGIV0diGdySzxATTWoqaU= @@ -453,20 +453,23 @@ github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567/go.mod h1:DWNGW8 github.com/randall77/makefat v0.0.0-20210315173500-7ddd0e42c844 h1:GranzK4hv1/pqTIhMTXt2X8MmMOuH3hMeUR0o9SP5yc= github.com/randall77/makefat v0.0.0-20210315173500-7ddd0e42c844/go.mod h1:T1TLSfyWVBRXVGzWd0o9BI4kfoO9InEgfQe4NV3mLz8= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryancurrah/gomodguard v1.3.0 h1:q15RT/pd6UggBXVBuLps8BXRvl5GPBcwVA7BJHMLuTw= -github.com/ryancurrah/gomodguard v1.3.0/go.mod h1:ggBxb3luypPEzqVtq33ee7YSN35V28XeGnid8dnni50= +github.com/ryancurrah/gomodguard v1.3.3 h1:eiSQdJVNr9KTNxY2Niij8UReSwR8Xrte3exBrAZfqpg= +github.com/ryancurrah/gomodguard v1.3.3/go.mod h1:rsKQjj4l3LXe8N344Ow7agAy5p9yjsWOtRzUMYmA0QY= github.com/ryanrolds/sqlclosecheck v0.5.1 h1:dibWW826u0P8jNLsLN+En7+RqWWTYrjCB9fJfSfdyCU= github.com/ryanrolds/sqlclosecheck v0.5.1/go.mod h1:2g3dUjoS6AL4huFdv6wn55WpLIDjY7ZgUR4J8HOO/XQ= github.com/sanposhiho/wastedassign/v2 v2.0.7 h1:J+6nrY4VW+gC9xFzUc+XjPD3g3wF3je/NsJFwFK7Uxc= github.com/sanposhiho/wastedassign/v2 v2.0.7/go.mod h1:KyZ0MWTwxxBmfwn33zh3k1dmsbF2ud9pAAGfoLfjhtI= +github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 h1:lZUw3E0/J3roVtGQ+SCrUrg3ON6NgVqpn3+iol9aGu4= +github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY= github.com/sashamelentyev/interfacebloat v1.1.0 h1:xdRdJp0irL086OyW1H/RTZTr1h/tMEOsumirXcOJqAw= github.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84dxiN1iBi9+G8zZIhPVoNjQ= -github.com/sashamelentyev/usestdlibvars v1.24.0 h1:MKNzmXtGh5N0y74Z/CIaJh4GlB364l0K1RUT08WSWAc= -github.com/sashamelentyev/usestdlibvars v1.24.0/go.mod h1:9cYkq+gYJ+a5W2RPdhfaSCnTVUC1OQP/bSiiBhq3OZE= -github.com/securego/gosec/v2 v2.18.2 h1:DkDt3wCiOtAHf1XkiXZBhQ6m6mK/b9T/wD257R3/c+I= -github.com/securego/gosec/v2 v2.18.2/go.mod h1:xUuqSF6i0So56Y2wwohWAmB07EdBkUN6crbLlHwbyJs= +github.com/sashamelentyev/usestdlibvars v1.27.0 h1:t/3jZpSXtRPRf2xr0m63i32ZrusyurIGT9E5wAvXQnI= +github.com/sashamelentyev/usestdlibvars v1.27.0/go.mod h1:9nl0jgOfHKWNFS43Ojw0i7aRoS4j6EBye3YBhmAIRF8= +github.com/securego/gosec/v2 v2.20.1-0.20240525090044-5f0084eb01a9 h1:rnO6Zp1YMQwv8AyxzuwsVohljJgp4L0ZqiCgtACsPsc= +github.com/securego/gosec/v2 v2.20.1-0.20240525090044-5f0084eb01a9/go.mod h1:dg7lPlu/xK/Ut9SedURCoZbVCR4yC7fM65DtH9/CDHs= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c h1:W65qqJCIOVP4jpqPQ0YvHYKwcMEMVWIzWC5iNQQfBTU= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAxekIXwN8qQyfc5gl2NlkB3CQlkizAbOkeBs= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= @@ -478,20 +481,18 @@ github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sivchari/containedctx v1.0.3 h1:x+etemjbsh2fB5ewm5FeLNi5bUjK0V8n0RB+Wwfd0XE= github.com/sivchari/containedctx v1.0.3/go.mod h1:c1RDvCbnJLtH4lLcYD/GqwiBSSf4F5Qk0xld2rBqzJ4= -github.com/sivchari/nosnakecase v1.7.0 h1:7QkpWIRMe8x25gckkFd2A5Pi6Ymo0qgr4JrhGt95do8= -github.com/sivchari/nosnakecase v1.7.0/go.mod h1:CwDzrzPea40/GB6uynrNLiorAlgFRvRbFSgJx2Gs+QY= -github.com/sivchari/tenv v1.7.1 h1:PSpuD4bu6fSmtWMxSGWcvqUUgIn7k3yOJhOIzVWn8Ak= -github.com/sivchari/tenv v1.7.1/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= +github.com/sivchari/tenv v1.10.0 h1:g/hzMA+dBCKqGXgW8AV/1xIWhAvDrx0zFKNR48NFMg0= +github.com/sivchari/tenv v1.10.0/go.mod h1:tdY24masnVoZFxYrHv/nD6Tc8FbkEtAQEEziXpyMgqY= github.com/sonatard/noctx v0.0.2 h1:L7Dz4De2zDQhW8S0t+KUjY0MAQJd6SgVwhzNIc4ok00= github.com/sonatard/noctx v0.0.2/go.mod h1:kzFz+CzWSjQ2OzIm46uJZoXuBpa2+0y3T36U18dWqIo= github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= github.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= -github.com/spf13/afero v1.8.2 h1:xehSyVa0YnHWsJ49JFljMpg1HX19V6NDZ1fkm1Xznbo= -github.com/spf13/afero v1.8.2/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= +github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= @@ -505,8 +506,9 @@ github.com/stbenjam/no-sprintf-host-port v0.1.1/go.mod h1:TLhvtIvONRzdmkFiio4O8L github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -514,42 +516,41 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= -github.com/t-yuki/gocover-cobertura v0.0.0-20180217150009-aaee18c8195c h1:+aPplBwWcHBo6q9xrfWdMrT9o4kltkmmvpemgIjep/8= -github.com/t-yuki/gocover-cobertura v0.0.0-20180217150009-aaee18c8195c/go.mod h1:SbErYREK7xXdsRiigaQiQkI9McGRzYMvlKYaP3Nimdk= github.com/tdakkota/asciicheck v0.2.0 h1:o8jvnUANo0qXtnslk2d3nMKTFNlOnJjRrNcj0j9qkHM= github.com/tdakkota/asciicheck v0.2.0/go.mod h1:Qb7Y9EgjCLJGup51gDHFzbI08/gbGhL/UVhYIPWG2rg= github.com/tenntenn/modver v1.0.1 h1:2klLppGhDgzJrScMpkj9Ujy3rXPUspSjAcev9tSEBgA= github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3 h1:f+jULpRQGxTSkNYKJ51yaw6ChIqO+Je8UqsTKN/cDag= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY= -github.com/tetafro/godot v1.4.15 h1:QzdIs+XB8q+U1WmQEWKHQbKmCw06QuQM7gLx/dky2RM= -github.com/tetafro/godot v1.4.15/go.mod h1:2oVxTBSftRTh4+MVfUaUXR6bn2GDXCaMcOG4Dk3rfio= +github.com/tetafro/godot v1.4.16 h1:4ChfhveiNLk4NveAZ9Pu2AN8QZ2nkUGFuadM9lrr5D0= +github.com/tetafro/godot v1.4.16/go.mod h1:2oVxTBSftRTh4+MVfUaUXR6bn2GDXCaMcOG4Dk3rfio= github.com/timakin/bodyclose v0.0.0-20230421092635-574207250966 h1:quvGphlmUVU+nhpFa4gg4yJyTRJ13reZMDHrKwYw53M= github.com/timakin/bodyclose v0.0.0-20230421092635-574207250966/go.mod h1:27bSVNWSBOHm+qRp1T9qzaIpsWEP6TbUnei/43HK+PQ= github.com/timonwong/loggercheck v0.9.4 h1:HKKhqrjcVj8sxL7K77beXh0adEm6DLjV/QOGeMXEVi4= github.com/timonwong/loggercheck v0.9.4/go.mod h1:caz4zlPcgvpEkXgVnAJGowHAMW2NwHaNlpS8xDbVhTg= -github.com/tomarrell/wrapcheck/v2 v2.8.1 h1:HxSqDSN0sAt0yJYsrcYVoEeyM4aI9yAm3KQpIXDJRhQ= -github.com/tomarrell/wrapcheck/v2 v2.8.1/go.mod h1:/n2Q3NZ4XFT50ho6Hbxg+RV1uyo2Uow/Vdm9NQcl5SE= +github.com/tomarrell/wrapcheck/v2 v2.8.3 h1:5ov+Cbhlgi7s/a42BprYoxsr73CbdMUTzE3bRDFASUs= +github.com/tomarrell/wrapcheck/v2 v2.8.3/go.mod h1:g9vNIyhb5/9TQgumxQyOEqDHsmGYcGsVMOx/xGkqdMo= github.com/tommy-muehle/go-mnd/v2 v2.5.1 h1:NowYhSdyE/1zwK9QCLeRb6USWdoif80Ie+v+yU8u1Zw= github.com/tommy-muehle/go-mnd/v2 v2.5.1/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= github.com/ultraware/funlen v0.1.0 h1:BuqclbkY6pO+cvxoq7OsktIXZpgBSkYTQtmwhAK81vI= github.com/ultraware/funlen v0.1.0/go.mod h1:XJqmOQja6DpxarLj6Jj1U7JuoS8PvL4nEqDaQhy22p4= -github.com/ultraware/whitespace v0.0.5 h1:hh+/cpIcopyMYbZNVov9iSxvJU3OYQg78Sfaqzi/CzI= -github.com/ultraware/whitespace v0.0.5/go.mod h1:aVMh/gQve5Maj9hQ/hg+F75lr/X5A89uZnzAmWSineA= -github.com/uudashr/gocognit v1.1.2 h1:l6BAEKJqQH2UpKAPKdMfZf5kE4W/2xk8pfU1OVLvniI= -github.com/uudashr/gocognit v1.1.2/go.mod h1:aAVdLURqcanke8h3vg35BC++eseDm66Z7KmchI5et4k= +github.com/ultraware/whitespace v0.1.1 h1:bTPOGejYFulW3PkcrqkeQwOd6NKOOXvmGD9bo/Gk8VQ= +github.com/ultraware/whitespace v0.1.1/go.mod h1:XcP1RLD81eV4BW8UhQlpaR+SDc2givTvyI8a586WjW8= +github.com/uudashr/gocognit v1.1.3 h1:l+a111VcDbKfynh+airAy/DJQKaXh2m9vkoysMPSZyM= +github.com/uudashr/gocognit v1.1.3/go.mod h1:aKH8/e8xbTRBwjbCkwZ8qt4l2EpKXl31KMHgSS+lZ2U= github.com/xen0n/gosmopolitan v1.2.2 h1:/p2KTnMzwRexIW8GlKawsTWOxn7UHA+jCMF/V8HHtvU= github.com/xen0n/gosmopolitan v1.2.2/go.mod h1:7XX7Mj61uLYrj0qmeN0zi7XDon9JRAEhYQqAPLVNTeg= github.com/yagipy/maintidx v1.0.0 h1:h5NvIsCz+nRDapQ0exNv4aJ0yXSI0420omVANTv3GJM= github.com/yagipy/maintidx v1.0.0/go.mod h1:0qNf/I/CCZXSMhsRsrEPDZ+DkekpKLXAJfsTACwgXLk= -github.com/yeya24/promlinter v0.2.0 h1:xFKDQ82orCU5jQujdaD8stOHiv8UN68BSdn2a8u8Y3o= -github.com/yeya24/promlinter v0.2.0/go.mod h1:u54lkmBOZrpEbQQ6gox2zWKKLKu2SGe+2KOiextY+IA= -github.com/ykadowak/zerologlint v0.1.3 h1:TLy1dTW3Nuc+YE3bYRPToG1Q9Ej78b5UUN6bjbGdxPE= -github.com/ykadowak/zerologlint v0.1.3/go.mod h1:KaUskqF3e/v59oPmdq1U1DnKcuHokl2/K1U4pmIELKg= +github.com/yeya24/promlinter v0.3.0 h1:JVDbMp08lVCP7Y6NP3qHroGAO6z2yGKQtS5JsjqtoFs= +github.com/yeya24/promlinter v0.3.0/go.mod h1:cDfJQQYv9uYciW60QT0eeHlFodotkYZlL+YcPQN+mW4= +github.com/ykadowak/zerologlint v0.1.5 h1:Gy/fMz1dFQN9JZTPjv1hxEk+sRWm05row04Yoolgdiw= +github.com/ykadowak/zerologlint v0.1.5/go.mod h1:KaUskqF3e/v59oPmdq1U1DnKcuHokl2/K1U4pmIELKg= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -557,22 +558,25 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -gitlab.com/bosi/decorder v0.4.1 h1:VdsdfxhstabyhZovHafFw+9eJ6eU0d2CkFNJcZz/NU4= -gitlab.com/bosi/decorder v0.4.1/go.mod h1:jecSqWUew6Yle1pCr2eLWTensJMmsxHsBwt+PVbkAqA= -go-simpler.org/assert v0.6.0 h1:QxSrXa4oRuo/1eHMXSBFHKvJIpWABayzKldqZyugG7E= -go-simpler.org/sloglint v0.1.2 h1:IjdhF8NPxyn0Ckn2+fuIof7ntSnVUAqBFcQRrnG9AiM= -go-simpler.org/sloglint v0.1.2/go.mod h1:2LL+QImPfTslD5muNPydAEYmpXIj6o/WYcqnJjLi4o4= +gitlab.com/bosi/decorder v0.4.2 h1:qbQaV3zgwnBZ4zPMhGLW4KZe7A7NwxEhJx39R3shffo= +gitlab.com/bosi/decorder v0.4.2/go.mod h1:muuhHoaJkA9QLcYHq4Mj8FJUwDZ+EirSHRiaTcTf6T8= +go-simpler.org/assert v0.9.0 h1:PfpmcSvL7yAnWyChSjOz6Sp6m9j5lyK8Ok9pEL31YkQ= +go-simpler.org/assert v0.9.0/go.mod h1:74Eqh5eI6vCK6Y5l3PI8ZYFXG4Sa+tkr70OIPJAUr28= +go-simpler.org/musttag v0.12.2 h1:J7lRc2ysXOq7eM8rwaTYnNrHd5JwjppzB6mScysB2Cs= +go-simpler.org/musttag v0.12.2/go.mod h1:uN1DVIasMTQKk6XSik7yrJoEysGtR2GRqvWnI9S7TYM= +go-simpler.org/sloglint v0.7.2 h1:Wc9Em/Zeuu7JYpl+oKoYOsQSy2X560aVueCW/m6IijY= +go-simpler.org/sloglint v0.7.2/go.mod h1:US+9C80ppl7VsThQclkM7BkCHQAzuz8kHLsW3ppuluo= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= -go.tmz.dev/musttag v0.7.2 h1:1J6S9ipDbalBSODNT5jCep8dhZyMr4ttnjQagmGYR5s= -go.tmz.dev/musttag v0.7.2/go.mod h1:m6q5NiiSKMnQYokefa2xGoyoXnrswCbJ0AWYzf4Zs28= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/automaxprocs v1.5.3 h1:kWazyxZUrS3Gs4qUpbwo5kEIMGe/DAvi5Z4tl2NW4j8= +go.uber.org/automaxprocs v1.5.3/go.mod h1:eRbA25aqJrxAbsLO0xy5jVwPt7FQnRgjW+efnwa1WM0= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= +go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= @@ -583,9 +587,7 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -597,12 +599,12 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea h1:vLCWI/yYrdEHyN2JzIzPO3aaQJHQdp89IZBA/+azVC4= -golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= +golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc h1:ao2WRsKSzW6KuUY9IWPwWahcHCgR0s52IfwutMfEbdM= +golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI= golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/exp/typeparams v0.0.0-20230203172020-98cc5a0785f9/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= -golang.org/x/exp/typeparams v0.0.0-20230307190834-24139beb5833 h1:jWGQJV4niP+CCmFW9ekjA9Zx8vYORzOUH2/Nl5WPuLQ= -golang.org/x/exp/typeparams v0.0.0-20230307190834-24139beb5833/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= +golang.org/x/exp/typeparams v0.0.0-20240314144324-c7f7c6466f7f h1:phY1HzDcf18Aq9A8KkmRtY9WvOFIxN8wgfvy6Zm1DV8= +golang.org/x/exp/typeparams v0.0.0-20240314144324-c7f7c6466f7f/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -615,7 +617,6 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -624,7 +625,6 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= @@ -633,8 +633,8 @@ golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91 golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY= -golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= +golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -664,9 +664,6 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -676,16 +673,13 @@ golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -700,8 +694,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ= -golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 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= @@ -733,17 +727,12 @@ golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -752,7 +741,6 @@ golang.org/x/sys v0.0.0-20211105183446-c75c47738b0c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220702020025-31831981b65f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -760,8 +748,9 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= -golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= +golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -773,14 +762,13 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -831,14 +819,7 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200820010801-b793a1359eac/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201001104356-43ebab892c4c/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201023174141-c8cfbd0f21e6/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.1-0.20210205202024-ef80cdb6ec6d/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU= golang.org/x/tools v0.1.1-0.20210302220138-2ac05c832e1a/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU= @@ -846,14 +827,13 @@ golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= -golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA= golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= golang.org/x/tools v0.5.0/go.mod h1:N+Kgy78s5I24c24dU8OfWNEotWjutIs8SnJvn5IDq+k= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc= -golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -874,16 +854,12 @@ google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0M google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= -google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= -google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -913,13 +889,6 @@ google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7Fc google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -932,10 +901,6 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= -google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -954,7 +919,8 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= @@ -975,16 +941,12 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.4.6 h1:oFEHCKeID7to/3autwsWfnuv69j3NsfcXbvJKuIcep8= -honnef.co/go/tools v0.4.6/go.mod h1:+rnGS1THNh8zMwnd2oVOTL9QF6vmfyG6ZXBULae2uc0= -mvdan.cc/gofumpt v0.5.0 h1:0EQ+Z56k8tXjj/6TQD25BFNKQXpCvT0rnansIc7Ug5E= -mvdan.cc/gofumpt v0.5.0/go.mod h1:HBeVDtMKRZpXyxFciAirzdKklDlGu8aAy1wEbH5Y9js= -mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed h1:WX1yoOaKQfddO/mLzdV4wptyWgoH/6hwLs7QHTixo0I= -mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed/go.mod h1:Xkxe497xwlCKkIaQYRfC7CSLworTXY9RMqwhhCm+8Nc= -mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b h1:DxJ5nJdkhDlLok9K6qO+5290kphDJbHOQO1DFFFTeBo= -mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jCoyKnw3vv5biOc3JnIcYfL4= -mvdan.cc/unparam v0.0.0-20221223090309-7455f1af531d h1:3rvTIIM22r9pvXk+q3swxUQAQOxksVMGK7sml4nG57w= -mvdan.cc/unparam v0.0.0-20221223090309-7455f1af531d/go.mod h1:IeHQjmn6TOD+e4Z3RFiZMMsLVL+A96Nvptar8Fj71is= +honnef.co/go/tools v0.5.0 h1:29uoiIormS3Z6R+t56STz/oI4v+mB51TSmEOdJPgRnE= +honnef.co/go/tools v0.5.0/go.mod h1:e9irvo83WDG9/irijV44wr3tbhcFeRnfpVlRqVwpzMs= +mvdan.cc/gofumpt v0.6.0 h1:G3QvahNDmpD+Aek/bNOLrFR2XC6ZAdo62dZu65gmwGo= +mvdan.cc/gofumpt v0.6.0/go.mod h1:4L0wf+kgIPZtcCWXynNS2e6bhmj73umwnuXSZarixzA= +mvdan.cc/unparam v0.0.0-20240528143540-8a5130ca722f h1:lMpcwN6GxNbWtbpI1+xzFLSW8XzX0u72NttUGVFjO3U= +mvdan.cc/unparam v0.0.0-20240528143540-8a5130ca722f/go.mod h1:RSLa7mKKCNeTTMHBw5Hsy2rfJmd6O2ivt9Dw9ZqCQpQ= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/tools/vendor/github.com/Abirdcfly/dupword/dupword.go b/tools/vendor/github.com/Abirdcfly/dupword/dupword.go index c291eab52..9a78fb6cc 100644 --- a/tools/vendor/github.com/Abirdcfly/dupword/dupword.go +++ b/tools/vendor/github.com/Abirdcfly/dupword/dupword.go @@ -75,7 +75,7 @@ type ignore struct { } func (a *ignore) String() string { - t := make([]string,0, len(ignoreWord)) + t := make([]string, 0, len(ignoreWord)) for k := range ignoreWord { t = append(t, k) } @@ -83,7 +83,7 @@ func (a *ignore) String() string { } func (a *ignore) Set(w string) error { - for _, k := range strings.Split(w, ","){ + for _, k := range strings.Split(w, ",") { ignoreWord[k] = true } return nil diff --git a/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/analyzer.go b/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/analyzer.go index e980db546..5646ee909 100644 --- a/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/analyzer.go +++ b/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/analyzer.go @@ -2,6 +2,9 @@ package analyzer import ( "go/ast" + "go/token" + "go/types" + "strconv" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" @@ -40,29 +43,15 @@ func newNilNil() *nilNil { } } -var ( - types = []ast.Node{(*ast.TypeSpec)(nil)} - - funcAndReturns = []ast.Node{ - (*ast.FuncDecl)(nil), - (*ast.FuncLit)(nil), - (*ast.ReturnStmt)(nil), - } -) - -type typeSpecByName map[string]typer +var funcAndReturns = []ast.Node{ + (*ast.FuncDecl)(nil), + (*ast.FuncLit)(nil), + (*ast.ReturnStmt)(nil), +} func (n *nilNil) run(pass *analysis.Pass) (interface{}, error) { insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) - typeSpecs := typeSpecByName{ - "any": newTyper(new(ast.InterfaceType)), - } - insp.Preorder(types, func(node ast.Node) { - t := node.(*ast.TypeSpec) - typeSpecs[t.Name.Name] = newTyper(t.Type) - }) - var fs funcTypeStack insp.Nodes(funcAndReturns, func(node ast.Node, push bool) (proceed bool) { switch v := node.(type) { @@ -87,13 +76,32 @@ func (n *nilNil) run(pass *analysis.Pass) (interface{}, error) { return false } - fRes1, fRes2 := ft.Results.List[0], ft.Results.List[1] - if !(n.isDangerNilField(fRes1, typeSpecs) && n.isErrorField(fRes2)) { + fRes1Type := pass.TypesInfo.TypeOf(ft.Results.List[0].Type) + if fRes1Type == nil { return false } - rRes1, rRes2 := v.Results[0], v.Results[1] - if isNil(rRes1) && isNil(rRes2) { + fRes2Type := pass.TypesInfo.TypeOf(ft.Results.List[1].Type) + if fRes2Type == nil { + return false + } + + ok, zv := n.isDangerNilType(fRes1Type) + if !(ok && isErrorType(fRes2Type)) { + return false + } + + retVal, retErr := v.Results[0], v.Results[1] + + var needWarn bool + switch zv { + case zeroValueNil: + needWarn = isNil(pass, retVal) && isNil(pass, retErr) + case zeroValueZero: + needWarn = isZero(retVal) && isNil(pass, retErr) + } + + if needWarn { pass.Reportf(v.Pos(), reportMsg) } } @@ -104,55 +112,73 @@ func (n *nilNil) run(pass *analysis.Pass) (interface{}, error) { return nil, nil //nolint:nilnil } -func (n *nilNil) isDangerNilField(f *ast.Field, typeSpecs typeSpecByName) bool { - return n.isDangerNilType(f.Type, typeSpecs) -} +type zeroValue int -func (n *nilNil) isDangerNilType(t ast.Expr, typeSpecs typeSpecByName) bool { +const ( + zeroValueNil = iota + 1 + zeroValueZero +) + +func (n *nilNil) isDangerNilType(t types.Type) (bool, zeroValue) { switch v := t.(type) { - case *ast.StarExpr: - return n.checkedTypes.Contains(ptrType) + case *types.Pointer: + return n.checkedTypes.Contains(ptrType), zeroValueNil - case *ast.FuncType: - return n.checkedTypes.Contains(funcType) + case *types.Signature: + return n.checkedTypes.Contains(funcType), zeroValueNil - case *ast.InterfaceType: - return n.checkedTypes.Contains(ifaceType) + case *types.Interface: + return n.checkedTypes.Contains(ifaceType), zeroValueNil - case *ast.MapType: - return n.checkedTypes.Contains(mapType) + case *types.Map: + return n.checkedTypes.Contains(mapType), zeroValueNil - case *ast.ChanType: - return n.checkedTypes.Contains(chanType) + case *types.Chan: + return n.checkedTypes.Contains(chanType), zeroValueNil - case *ast.Ident: - if t, ok := typeSpecs[v.Name]; ok { - return n.isDangerNilType(t.Type(), typeSpecs) + case *types.Basic: + if v.Kind() == types.Uintptr { + return n.checkedTypes.Contains(uintptrType), zeroValueZero + } + if v.Kind() == types.UnsafePointer { + return n.checkedTypes.Contains(unsafeptrType), zeroValueNil } + + case *types.Named: + return n.isDangerNilType(v.Underlying()) } - return false + return false, 0 } -func (n *nilNil) isErrorField(f *ast.Field) bool { - return isIdent(f.Type, "error") -} +var errorIface = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) -func isNil(e ast.Expr) bool { - return isIdent(e, "nil") +func isErrorType(t types.Type) bool { + _, ok := t.Underlying().(*types.Interface) + return ok && types.Implements(t, errorIface) } -func isIdent(n ast.Node, name string) bool { - i, ok := n.(*ast.Ident) +func isNil(pass *analysis.Pass, e ast.Expr) bool { + i, ok := e.(*ast.Ident) if !ok { return false } - return i.Name == name -} -type typer interface { - Type() ast.Expr + _, ok = pass.TypesInfo.ObjectOf(i).(*types.Nil) + return ok } -func newTyper(t ast.Expr) typer { return typerImpl{t: t} } // -type typerImpl struct{ t ast.Expr } // -func (ti typerImpl) Type() ast.Expr { return ti.t } +func isZero(e ast.Expr) bool { + bl, ok := e.(*ast.BasicLit) + if !ok { + return false + } + if bl.Kind != token.INT { + return false + } + + v, err := strconv.ParseInt(bl.Value, 0, 64) + if err != nil { + return false + } + return v == 0 +} diff --git a/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/config.go b/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/config.go index 520b813a5..c9b8e3eed 100644 --- a/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/config.go +++ b/tools/vendor/github.com/Antonboom/nilnil/pkg/analyzer/config.go @@ -8,11 +8,13 @@ import ( func newDefaultCheckedTypes() checkedTypes { return checkedTypes{ - ptrType: struct{}{}, - funcType: struct{}{}, - ifaceType: struct{}{}, - mapType: struct{}{}, - chanType: struct{}{}, + ptrType: {}, + funcType: {}, + ifaceType: {}, + mapType: {}, + chanType: {}, + uintptrType: {}, + unsafeptrType: {}, } } @@ -25,15 +27,15 @@ func (t typeName) S() string { } const ( - ptrType typeName = "ptr" - funcType typeName = "func" - ifaceType typeName = "iface" - mapType typeName = "map" - chanType typeName = "chan" + ptrType typeName = "ptr" + funcType typeName = "func" + ifaceType typeName = "iface" + mapType typeName = "map" + chanType typeName = "chan" + uintptrType typeName = "uintptr" + unsafeptrType typeName = "unsafeptr" ) -var knownTypes = []typeName{ptrType, funcType, ifaceType, mapType, chanType} - type checkedTypes map[typeName]struct{} func (c checkedTypes) Contains(t typeName) bool { @@ -60,7 +62,7 @@ func (c checkedTypes) Set(s string) error { c.disableAll() for _, t := range types { switch tt := typeName(t); tt { - case ptrType, funcType, ifaceType, mapType, chanType: + case ptrType, funcType, ifaceType, mapType, chanType, uintptrType, unsafeptrType: c[tt] = struct{}{} default: return fmt.Errorf("unknown checked type name %q (see help)", t) diff --git a/tools/vendor/github.com/Antonboom/testifylint/analyzer/analyzer.go b/tools/vendor/github.com/Antonboom/testifylint/analyzer/analyzer.go index c0b98f83c..a9e41b0a8 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/analyzer/analyzer.go +++ b/tools/vendor/github.com/Antonboom/testifylint/analyzer/analyzer.go @@ -3,8 +3,6 @@ package analyzer import ( "fmt" "go/ast" - "go/types" - "strings" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/ast/inspector" @@ -21,7 +19,7 @@ const ( url = "https://github.com/antonboom/" + name ) -// New returns new instance of testifylint analyzer. +// New returns a new instance of testifylint analyzer. func New() *analysis.Analyzer { cfg := config.NewDefault() @@ -79,58 +77,11 @@ func (tl *testifyLint) run(pass *analysis.Pass) (any, error) { } func (tl *testifyLint) regularCheck(pass *analysis.Pass, ce *ast.CallExpr) { - se, ok := ce.Fun.(*ast.SelectorExpr) - if !ok || se.Sel == nil { - return - } - fnName := se.Sel.Name - - initiatorPkg, isPkgCall := func() (*types.Package, bool) { - // Examples: - // s.Assert -> method of *suite.Suite -> package suite ("vendor/github.com/stretchr/testify/suite") - // s.Assert().Equal -> method of *assert.Assertions -> package assert ("vendor/github.com/stretchr/testify/assert") - // s.Equal -> method of *assert.Assertions -> package assert ("vendor/github.com/stretchr/testify/assert") - // reqObj.Falsef -> method of *require.Assertions -> package require ("vendor/github.com/stretchr/testify/require") - if sel, ok := pass.TypesInfo.Selections[se]; ok { - return sel.Obj().Pkg(), false - } - - // Examples: - // assert.False -> assert -> package assert ("vendor/github.com/stretchr/testify/assert") - // require.NotEqualf -> require -> package require ("vendor/github.com/stretchr/testify/require") - if id, ok := se.X.(*ast.Ident); ok { - if selObj := pass.TypesInfo.ObjectOf(id); selObj != nil { - if pkg, ok := selObj.(*types.PkgName); ok { - return pkg.Imported(), true - } - } - } - return nil, false - }() - if initiatorPkg == nil { + call := checkers.NewCallMeta(pass, ce) + if nil == call { return } - isAssert := analysisutil.IsPkg(initiatorPkg, testify.AssertPkgName, testify.AssertPkgPath) - isRequire := analysisutil.IsPkg(initiatorPkg, testify.RequirePkgName, testify.RequirePkgPath) - if !(isAssert || isRequire) { - return - } - - call := &checkers.CallMeta{ - Range: ce, - IsPkg: isPkgCall, - IsAssert: isAssert, - Selector: se, - SelectorXStr: analysisutil.NodeString(pass.Fset, se.X), - Fn: checkers.FnMeta{ - Range: se.Sel, - Name: fnName, - IsFmt: strings.HasSuffix(fnName, "f"), - }, - Args: trimTArg(pass, isAssert, ce.Args), - ArgsRaw: ce.Args, - } for _, ch := range tl.regularCheckers { if d := ch.Check(pass, call); d != nil { pass.Report(*d) @@ -140,36 +91,3 @@ func (tl *testifyLint) regularCheck(pass *analysis.Pass, ce *ast.CallExpr) { } } } - -func trimTArg(pass *analysis.Pass, isAssert bool, args []ast.Expr) []ast.Expr { - if len(args) == 0 { - return args - } - - if isTestingTPtr(pass, isAssert, args[0]) { - return args[1:] - } - return args -} - -func isTestingTPtr(pass *analysis.Pass, isAssert bool, arg ast.Expr) bool { - pkgPath := testify.RequirePkgPath - if isAssert { - pkgPath = testify.AssertPkgPath - } - - testingInterfaceObj := analysisutil.ObjectOf(pass.Pkg, pkgPath, "TestingT") - if testingInterfaceObj == nil { - return false - } - - argType := pass.TypesInfo.TypeOf(arg) - if argType == nil { - return false - } - - return types.Implements( - argType, - testingInterfaceObj.Type().Underlying().(*types.Interface), - ) -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/analyzer/checkers_factory.go b/tools/vendor/github.com/Antonboom/testifylint/analyzer/checkers_factory.go index e87e35e50..df04dfdc5 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/analyzer/checkers_factory.go +++ b/tools/vendor/github.com/Antonboom/testifylint/analyzer/checkers_factory.go @@ -9,14 +9,34 @@ import ( // newCheckers accepts linter config and returns slices of enabled checkers sorted by priority. func newCheckers(cfg config.Config) ([]checkers.RegularChecker, []checkers.AdvancedChecker, error) { - enabledCheckers := cfg.EnabledCheckers - if len(enabledCheckers) == 0 { - enabledCheckers = checkers.EnabledByDefault() + if err := cfg.Validate(); err != nil { + return nil, nil, err } + + enabledCheckersSet := make(map[string]struct{}) + if cfg.EnableAll { - enabledCheckers = checkers.All() + for _, checker := range checkers.All() { + enabledCheckersSet[checker] = struct{}{} + } + } else if !cfg.DisableAll { + for _, checker := range checkers.EnabledByDefault() { + enabledCheckersSet[checker] = struct{}{} + } } + for _, checker := range cfg.EnabledCheckers { + enabledCheckersSet[checker] = struct{}{} + } + + for _, checker := range cfg.DisabledCheckers { + delete(enabledCheckersSet, checker) + } + + enabledCheckers := make([]string, 0, len(enabledCheckersSet)) + for v := range enabledCheckersSet { + enabledCheckers = append(enabledCheckers, v) + } checkers.SortByPriority(enabledCheckers) regularCheckers := make([]checkers.RegularChecker, 0, len(enabledCheckers)) @@ -29,9 +49,22 @@ func newCheckers(cfg config.Config) ([]checkers.RegularChecker, []checkers.Advan } switch c := ch.(type) { + case *checkers.BoolCompare: + c.SetIgnoreCustomTypes(cfg.BoolCompare.IgnoreCustomTypes) + case *checkers.ExpectedActual: c.SetExpVarPattern(cfg.ExpectedActual.ExpVarPattern.Regexp) + case *checkers.Formatter: + c.SetCheckFormatString(cfg.Formatter.CheckFormatString) + c.SetRequireFFuncs(cfg.Formatter.RequireFFuncs) + + case *checkers.GoRequire: + c.SetIgnoreHTTPHandlers(cfg.GoRequire.IgnoreHTTPHandlers) + + case *checkers.RequireError: + c.SetFnPattern(cfg.RequireError.FnPattern.Regexp) + case *checkers.SuiteExtraAssertCall: c.SetMode(cfg.SuiteExtraAssertCall.Mode) } diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/analysisutil/object.go b/tools/vendor/github.com/Antonboom/testifylint/internal/analysisutil/object.go index e01fba5c1..4e0346d2b 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/analysisutil/object.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/analysisutil/object.go @@ -30,5 +30,5 @@ func IsObj(typesInfo *types.Info, expr ast.Expr, expected types.Object) bool { } obj := typesInfo.ObjectOf(id) - return obj.Id() == expected.Id() + return obj == expected } diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/blank_import.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/blank_import.go new file mode 100644 index 000000000..403691e27 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/blank_import.go @@ -0,0 +1,69 @@ +package checkers + +import ( + "fmt" + "strconv" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ast/inspector" + + "github.com/Antonboom/testifylint/internal/testify" +) + +// BlankImport detects useless blank imports of testify's packages. +// These imports are useless since testify doesn't do any magic with init() function. +// +// The checker detects situations like +// +// import ( +// "testing" +// +// _ "github.com/stretchr/testify" +// _ "github.com/stretchr/testify/assert" +// _ "github.com/stretchr/testify/http" +// _ "github.com/stretchr/testify/mock" +// _ "github.com/stretchr/testify/require" +// _ "github.com/stretchr/testify/suite" +// ) +// +// and requires +// +// import ( +// "testing" +// ) +type BlankImport struct{} + +// NewBlankImport constructs BlankImport checker. +func NewBlankImport() BlankImport { return BlankImport{} } +func (BlankImport) Name() string { return "blank-import" } + +func (checker BlankImport) Check(pass *analysis.Pass, _ *inspector.Inspector) (diagnostics []analysis.Diagnostic) { + for _, file := range pass.Files { + for _, imp := range file.Imports { + if imp.Name == nil || imp.Name.Name != "_" { + continue + } + + pkg, err := strconv.Unquote(imp.Path.Value) + if err != nil { + continue + } + if _, ok := packagesNotIntendedForBlankImport[pkg]; !ok { + continue + } + + msg := fmt.Sprintf("avoid blank import of %s as it does nothing", pkg) + diagnostics = append(diagnostics, *newDiagnostic(checker.Name(), imp, msg, nil)) + } + } + return diagnostics +} + +var packagesNotIntendedForBlankImport = map[string]struct{}{ + testify.ModulePath: {}, + testify.AssertPkgPath: {}, + testify.HTTPPkgPath: {}, + testify.MockPkgPath: {}, + testify.RequirePkgPath: {}, + testify.SuitePkgPath: {}, +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/bool_compare.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/bool_compare.go index 8245ab58e..d125c43f9 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/bool_compare.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/bool_compare.go @@ -3,7 +3,6 @@ package checkers import ( "go/ast" "go/token" - "go/types" "golang.org/x/tools/go/analysis" @@ -13,7 +12,10 @@ import ( // BoolCompare detects situations like // // assert.Equal(t, false, result) -// assert.NotEqual(t, result, true) +// assert.EqualValues(t, false, result) +// assert.Exactly(t, false, result) +// assert.NotEqual(t, true, result) +// assert.NotEqualValues(t, true, result) // assert.False(t, !result) // assert.True(t, result == true) // ... @@ -22,14 +24,31 @@ import ( // // assert.False(t, result) // assert.True(t, result) -type BoolCompare struct{} // +type BoolCompare struct { + ignoreCustomTypes bool +} // NewBoolCompare constructs BoolCompare checker. -func NewBoolCompare() BoolCompare { return BoolCompare{} } -func (BoolCompare) Name() string { return "bool-compare" } +func NewBoolCompare() *BoolCompare { return new(BoolCompare) } +func (BoolCompare) Name() string { return "bool-compare" } + +func (checker *BoolCompare) SetIgnoreCustomTypes(v bool) *BoolCompare { + checker.ignoreCustomTypes = v + return checker +} func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { - newUseFnDiagnostic := func(proposed string, survivingArg ast.Node, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { + newBoolCast := func(e ast.Expr) ast.Expr { + return &ast.CallExpr{Fun: &ast.Ident{Name: "bool"}, Args: []ast.Expr{e}} + } + + newUseFnDiagnostic := func(proposed string, survivingArg ast.Expr, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { + if !isBuiltinBool(pass, survivingArg) { + if checker.ignoreCustomTypes { + return nil + } + survivingArg = newBoolCast(survivingArg) + } return newUseFunctionDiagnostic(checker.Name(), call, proposed, newSuggestedFuncReplacement(call, proposed, analysis.TextEdit{ Pos: replaceStart, @@ -39,15 +58,21 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. ) } - newUseTrueDiagnostic := func(survivingArg ast.Node, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { + newUseTrueDiagnostic := func(survivingArg ast.Expr, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { return newUseFnDiagnostic("True", survivingArg, replaceStart, replaceEnd) } - newUseFalseDiagnostic := func(survivingArg ast.Node, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { + newUseFalseDiagnostic := func(survivingArg ast.Expr, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { return newUseFnDiagnostic("False", survivingArg, replaceStart, replaceEnd) } - newNeedSimplifyDiagnostic := func(survivingArg ast.Node, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { + newNeedSimplifyDiagnostic := func(survivingArg ast.Expr, replaceStart, replaceEnd token.Pos) *analysis.Diagnostic { + if !isBuiltinBool(pass, survivingArg) { + if checker.ignoreCustomTypes { + return nil + } + survivingArg = newBoolCast(survivingArg) + } return newDiagnostic(checker.Name(), call, "need to simplify the assertion", &analysis.SuggestedFix{ Message: "Simplify the assertion", @@ -60,32 +85,54 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. ) } - switch call.Fn.Name { - case "Equal", "Equalf": + switch call.Fn.NameFTrimmed { + case "Equal", "EqualValues", "Exactly": if len(call.Args) < 2 { return nil } arg1, arg2 := call.Args[0], call.Args[1] + if anyCondSatisfaction(pass, isEmptyInterface, arg1, arg2) { + return nil + } + if anyCondSatisfaction(pass, isBoolOverride, arg1, arg2) { + return nil + } + t1, t2 := isUntypedTrue(pass, arg1), isUntypedTrue(pass, arg2) f1, f2 := isUntypedFalse(pass, arg1), isUntypedFalse(pass, arg2) switch { case xor(t1, t2): survivingArg, _ := anyVal([]bool{t1, t2}, arg2, arg1) + if call.Fn.NameFTrimmed == "Exactly" && !isBuiltinBool(pass, survivingArg) { + // NOTE(a.telyshev): `Exactly` assumes no type casting. + return nil + } return newUseTrueDiagnostic(survivingArg, arg1.Pos(), arg2.End()) case xor(f1, f2): survivingArg, _ := anyVal([]bool{f1, f2}, arg2, arg1) + if call.Fn.NameFTrimmed == "Exactly" && !isBuiltinBool(pass, survivingArg) { + // NOTE(a.telyshev): `Exactly` assumes no type casting. + return nil + } return newUseFalseDiagnostic(survivingArg, arg1.Pos(), arg2.End()) } - case "NotEqual", "NotEqualf": + case "NotEqual", "NotEqualValues": if len(call.Args) < 2 { return nil } arg1, arg2 := call.Args[0], call.Args[1] + if anyCondSatisfaction(pass, isEmptyInterface, arg1, arg2) { + return nil + } + if anyCondSatisfaction(pass, isBoolOverride, arg1, arg2) { + return nil + } + t1, t2 := isUntypedTrue(pass, arg1), isUntypedTrue(pass, arg2) f1, f2 := isUntypedFalse(pass, arg1), isUntypedFalse(pass, arg2) @@ -99,7 +146,7 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. return newUseTrueDiagnostic(survivingArg, arg1.Pos(), arg2.End()) } - case "True", "Truef": + case "True": if len(call.Args) < 1 { return nil } @@ -109,7 +156,8 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. arg1, ok1 := isComparisonWithTrue(pass, expr, token.EQL) arg2, ok2 := isComparisonWithFalse(pass, expr, token.NEQ) - if survivingArg, ok := anyVal([]bool{ok1, ok2}, arg1, arg2); ok { + survivingArg, ok := anyVal([]bool{ok1, ok2}, arg1, arg2) + if ok && !isEmptyInterface(pass, survivingArg) { return newNeedSimplifyDiagnostic(survivingArg, expr.Pos(), expr.End()) } } @@ -119,12 +167,13 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. arg2, ok2 := isComparisonWithFalse(pass, expr, token.EQL) arg3, ok3 := isNegation(expr) - if survivingArg, ok := anyVal([]bool{ok1, ok2, ok3}, arg1, arg2, arg3); ok { + survivingArg, ok := anyVal([]bool{ok1, ok2, ok3}, arg1, arg2, arg3) + if ok && !isEmptyInterface(pass, survivingArg) { return newUseFalseDiagnostic(survivingArg, expr.Pos(), expr.End()) } } - case "False", "Falsef": + case "False": if len(call.Args) < 1 { return nil } @@ -134,7 +183,8 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. arg1, ok1 := isComparisonWithTrue(pass, expr, token.EQL) arg2, ok2 := isComparisonWithFalse(pass, expr, token.NEQ) - if survivingArg, ok := anyVal([]bool{ok1, ok2}, arg1, arg2); ok { + survivingArg, ok := anyVal([]bool{ok1, ok2}, arg1, arg2) + if ok && !isEmptyInterface(pass, survivingArg) { return newNeedSimplifyDiagnostic(survivingArg, expr.Pos(), expr.End()) } } @@ -144,7 +194,8 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. arg2, ok2 := isComparisonWithFalse(pass, expr, token.EQL) arg3, ok3 := isNegation(expr) - if survivingArg, ok := anyVal([]bool{ok1, ok2, ok3}, arg1, arg2, arg3); ok { + survivingArg, ok := anyVal([]bool{ok1, ok2, ok3}, arg1, arg2, arg3) + if ok && !isEmptyInterface(pass, survivingArg) { return newUseTrueDiagnostic(survivingArg, expr.Pos(), expr.End()) } } @@ -152,48 +203,6 @@ func (checker BoolCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis. return nil } -var ( - falseObj = types.Universe.Lookup("false") - trueObj = types.Universe.Lookup("true") -) - -func isUntypedTrue(pass *analysis.Pass, e ast.Expr) bool { - return analysisutil.IsObj(pass.TypesInfo, e, trueObj) -} - -func isUntypedFalse(pass *analysis.Pass, e ast.Expr) bool { - return analysisutil.IsObj(pass.TypesInfo, e, falseObj) -} - -func isComparisonWithTrue(pass *analysis.Pass, e ast.Expr, op token.Token) (ast.Expr, bool) { - return isComparisonWith(pass, e, isUntypedTrue, op) -} - -func isComparisonWithFalse(pass *analysis.Pass, e ast.Expr, op token.Token) (ast.Expr, bool) { - return isComparisonWith(pass, e, isUntypedFalse, op) -} - -type predicate func(pass *analysis.Pass, e ast.Expr) bool - -func isComparisonWith(pass *analysis.Pass, e ast.Expr, predicate predicate, op token.Token) (ast.Expr, bool) { - be, ok := e.(*ast.BinaryExpr) - if !ok { - return nil, false - } - if be.Op != op { - return nil, false - } - - t1, t2 := predicate(pass, be.X), predicate(pass, be.Y) - if xor(t1, t2) { - if t1 { - return be.Y, true - } - return be.X, true - } - return nil, false -} - func isNegation(e ast.Expr) (ast.Expr, bool) { ue, ok := e.(*ast.UnaryExpr) if !ok { @@ -201,23 +210,3 @@ func isNegation(e ast.Expr) (ast.Expr, bool) { } return ue.X, ue.Op == token.NOT } - -func xor(a, b bool) bool { - return a != b -} - -// anyVal returns the first value[i] for which bools[i] is true. -func anyVal[T any](bools []bool, vals ...T) (T, bool) { - if len(bools) != len(vals) { - panic("inconsistent usage of valOr") //nolint:forbidigo // Does not depend on the code being analyzed. - } - - for i, b := range bools { - if b { - return vals[i], true - } - } - - var _default T - return _default, false -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/call_meta.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/call_meta.go new file mode 100644 index 000000000..96b5b19b0 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/call_meta.go @@ -0,0 +1,133 @@ +package checkers + +import ( + "go/ast" + "go/types" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/types/typeutil" + + "github.com/Antonboom/testifylint/internal/analysisutil" + "github.com/Antonboom/testifylint/internal/testify" +) + +// CallMeta stores meta info about assertion function/method call, for example +// +// assert.Equal(t, 42, result, "helpful comment") +type CallMeta struct { + // Call stores the original AST call expression. + Call *ast.CallExpr + // Range contains start and end position of assertion call. + analysis.Range + // IsPkg true if this is package (not object) call. + IsPkg bool + // IsAssert true if this is "testify/assert" package (or object) call. + IsAssert bool + // Selector is the AST expression of "assert.Equal". + Selector *ast.SelectorExpr + // SelectorXStr is a string representation of Selector's left part – value before point, e.g. "assert". + SelectorXStr string + // Fn stores meta info about assertion function itself. + Fn FnMeta + // Args stores assertion call arguments but without `t *testing.T` argument. + // E.g [42, result, "helpful comment"]. + Args []ast.Expr + // ArgsRaw stores assertion call initial arguments. + // E.g [t, 42, result, "helpful comment"]. + ArgsRaw []ast.Expr +} + +func (c CallMeta) String() string { + return c.SelectorXStr + "." + c.Fn.Name +} + +// FnMeta stores meta info about assertion function itself, for example "Equal". +type FnMeta struct { + // Range contains start and end position of function Name. + analysis.Range + // Name is a function name. + Name string + // NameFTrimmed is a function name without "f" suffix. + NameFTrimmed string + // IsFmt is true if function is formatted, e.g. "Equalf". + IsFmt bool + // Signature represents assertion signature. + Signature *types.Signature +} + +// NewCallMeta returns meta information about testify assertion call. +// Returns nil if ast.CallExpr is not testify call. +func NewCallMeta(pass *analysis.Pass, ce *ast.CallExpr) *CallMeta { + se, ok := ce.Fun.(*ast.SelectorExpr) + if !ok || se.Sel == nil { + return nil + } + fnName := se.Sel.Name + + initiatorPkg, isPkgCall := func() (*types.Package, bool) { + // Examples: + // s.Assert -> method of *suite.Suite -> package suite ("vendor/github.com/stretchr/testify/suite") + // s.Assert().Equal -> method of *assert.Assertions -> package assert ("vendor/github.com/stretchr/testify/assert") + // s.Equal -> method of *assert.Assertions -> package assert ("vendor/github.com/stretchr/testify/assert") + // reqObj.Falsef -> method of *require.Assertions -> package require ("vendor/github.com/stretchr/testify/require") + if sel, isSel := pass.TypesInfo.Selections[se]; isSel { + return sel.Obj().Pkg(), false + } + + // Examples: + // assert.False -> assert -> package assert ("vendor/github.com/stretchr/testify/assert") + // require.NotEqualf -> require -> package require ("vendor/github.com/stretchr/testify/require") + if id, isIdent := se.X.(*ast.Ident); isIdent { + if selObj := pass.TypesInfo.ObjectOf(id); selObj != nil { + if pkg, isPkgName := selObj.(*types.PkgName); isPkgName { + return pkg.Imported(), true + } + } + } + return nil, false + }() + if initiatorPkg == nil { + return nil + } + + isAssert := analysisutil.IsPkg(initiatorPkg, testify.AssertPkgName, testify.AssertPkgPath) + isRequire := analysisutil.IsPkg(initiatorPkg, testify.RequirePkgName, testify.RequirePkgPath) + if !(isAssert || isRequire) { + return nil + } + + funcObj, ok := typeutil.Callee(pass.TypesInfo, ce).(*types.Func) + if !ok { + return nil + } + + return &CallMeta{ + Call: ce, + Range: ce, + IsPkg: isPkgCall, + IsAssert: isAssert, + Selector: se, + SelectorXStr: analysisutil.NodeString(pass.Fset, se.X), + Fn: FnMeta{ + Range: se.Sel, + Name: fnName, + NameFTrimmed: strings.TrimSuffix(fnName, "f"), + IsFmt: strings.HasSuffix(fnName, "f"), + Signature: funcObj.Type().(*types.Signature), // NOTE(a.telyshev): Func's Type() is always a *Signature. + }, + Args: trimTArg(pass, ce.Args), + ArgsRaw: ce.Args, + } +} + +func trimTArg(pass *analysis.Pass, args []ast.Expr) []ast.Expr { + if len(args) == 0 { + return args + } + + if implementsTestingT(pass, args[0]) { + return args[1:] + } + return args +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checker.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checker.go index f3249dc3c..ac23af6f6 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checker.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checker.go @@ -1,46 +1,10 @@ package checkers import ( - "go/ast" - "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/ast/inspector" ) -// CallMeta stores meta info about assertion function/method call, for example -// -// assert.Equal(t, 42, result, "helpful comment") -type CallMeta struct { - // Range contains start and end position of assertion call. - analysis.Range - // IsPkg true if this is package (not object) call. - IsPkg bool - // IsAssert true if this is "testify/assert" package (or object) call. - IsAssert bool - // Selector is the AST expression of "assert.Equal". - Selector *ast.SelectorExpr - // SelectorXStr is a string representation of Selector's left part – value before point, e.g. "assert". - SelectorXStr string - // Fn stores meta info about assertion function itself. - Fn FnMeta - // Args stores assertion call arguments but without `t *testing.T` argument. - // E.g [42, result, "helpful comment"]. - Args []ast.Expr - // ArgsRaw stores assertion call initial arguments. - // E.g [t, 42, result, "helpful comment"]. - ArgsRaw []ast.Expr -} - -// FnMeta stores meta info about assertion function itself, for example "Equal". -type FnMeta struct { - // Range contains start and end position of function Name. - analysis.Range - // Name is a function name. - Name string - // IsFmt is true if function is formatted, e.g. "Equalf". - IsFmt bool -} - // Checker describes named checker. type Checker interface { Name() string diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checkers_registry.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checkers_registry.go index 47eaafb76..17c7d14ee 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checkers_registry.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/checkers_registry.go @@ -11,14 +11,22 @@ var registry = checkersRegistry{ {factory: asCheckerFactory(NewBoolCompare), enabledByDefault: true}, {factory: asCheckerFactory(NewEmpty), enabledByDefault: true}, {factory: asCheckerFactory(NewLen), enabledByDefault: true}, + {factory: asCheckerFactory(NewNegativePositive), enabledByDefault: true}, {factory: asCheckerFactory(NewCompares), enabledByDefault: true}, {factory: asCheckerFactory(NewErrorNil), enabledByDefault: true}, + {factory: asCheckerFactory(NewNilCompare), enabledByDefault: true}, {factory: asCheckerFactory(NewErrorIsAs), enabledByDefault: true}, - {factory: asCheckerFactory(NewRequireError), enabledByDefault: true}, {factory: asCheckerFactory(NewExpectedActual), enabledByDefault: true}, {factory: asCheckerFactory(NewSuiteExtraAssertCall), enabledByDefault: true}, {factory: asCheckerFactory(NewSuiteDontUsePkg), enabledByDefault: true}, + {factory: asCheckerFactory(NewUselessAssert), enabledByDefault: true}, + {factory: asCheckerFactory(NewFormatter), enabledByDefault: true}, // Advanced checkers. + {factory: asCheckerFactory(NewBlankImport), enabledByDefault: true}, + {factory: asCheckerFactory(NewGoRequire), enabledByDefault: true}, + {factory: asCheckerFactory(NewRequireError), enabledByDefault: true}, + {factory: asCheckerFactory(NewSuiteBrokenParallel), enabledByDefault: true}, + {factory: asCheckerFactory(NewSuiteSubtestRun), enabledByDefault: true}, {factory: asCheckerFactory(NewSuiteTHelper), enabledByDefault: false}, } diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/compares.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/compares.go index afc829f97..bdde03d95 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/compares.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/compares.go @@ -1,13 +1,10 @@ package checkers import ( - "bytes" "go/ast" "go/token" "golang.org/x/tools/go/analysis" - - "github.com/Antonboom/testifylint/internal/analysisutil" ) // Compares detects situations like @@ -18,6 +15,7 @@ import ( // assert.True(t, a >= b) // assert.True(t, a < b) // assert.True(t, a <= b) +// assert.False(t, a == b) // ... // // and requires @@ -28,6 +26,9 @@ import ( // assert.GreaterOrEqual(t, a, b) // assert.Less(t, a, b) // assert.LessOrEqual(t, a, b) +// +// If `a` and `b` are pointers then `assert.Same`/`NotSame` is required instead, +// due to the inappropriate recursive nature of `assert.Equal` (based on `reflect.DeepEqual`). type Compares struct{} // NewCompares constructs Compares checker. @@ -46,26 +47,37 @@ func (checker Compares) Check(pass *analysis.Pass, call *CallMeta) *analysis.Dia var tokenToProposedFn map[token.Token]string - switch call.Fn.Name { - case "True", "Truef": + switch call.Fn.NameFTrimmed { + case "True": tokenToProposedFn = tokenToProposedFnInsteadOfTrue - case "False", "Falsef": + case "False": tokenToProposedFn = tokenToProposedFnInsteadOfFalse default: return nil } - if proposedFn, ok := tokenToProposedFn[be.Op]; ok { - a, b := be.X, be.Y - return newUseFunctionDiagnostic(checker.Name(), call, proposedFn, - newSuggestedFuncReplacement(call, proposedFn, analysis.TextEdit{ - Pos: be.X.Pos(), - End: be.Y.End(), - NewText: formatAsCallArgs(pass, a, b), - }), - ) + proposedFn, ok := tokenToProposedFn[be.Op] + if !ok { + return nil } - return nil + + if isPointer(pass, be.X) && isPointer(pass, be.Y) { + switch proposedFn { + case "Equal": + proposedFn = "Same" + case "NotEqual": + proposedFn = "NotSame" + } + } + + a, b := be.X, be.Y + return newUseFunctionDiagnostic(checker.Name(), call, proposedFn, + newSuggestedFuncReplacement(call, proposedFn, analysis.TextEdit{ + Pos: be.X.Pos(), + End: be.Y.End(), + NewText: formatAsCallArgs(pass, a, b), + }), + ) } var tokenToProposedFnInsteadOfTrue = map[token.Token]string{ @@ -85,11 +97,3 @@ var tokenToProposedFnInsteadOfFalse = map[token.Token]string{ token.LSS: "GreaterOrEqual", token.LEQ: "Greater", } - -// formatAsCallArgs joins a and b and return bytes like `a, b`. -func formatAsCallArgs(pass *analysis.Pass, a, b ast.Node) []byte { - return bytes.Join([][]byte{ - analysisutil.NodeBytes(pass.Fset, a), - analysisutil.NodeBytes(pass.Fset, b), - }, []byte(", ")) -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/empty.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/empty.go index 79c64205f..eafecb678 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/empty.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/empty.go @@ -1,10 +1,8 @@ package checkers import ( - "fmt" "go/ast" "go/token" - "go/types" "golang.org/x/tools/go/analysis" @@ -15,9 +13,24 @@ import ( // // assert.Len(t, arr, 0) // assert.Equal(t, 0, len(arr)) +// assert.EqualValues(t, 0, len(arr)) +// assert.Exactly(t, 0, len(arr)) +// assert.LessOrEqual(t, len(arr), 0) +// assert.GreaterOrEqual(t, 0, len(arr)) +// assert.Less(t, len(arr), 0) +// assert.Greater(t, 0, len(arr)) +// assert.Less(t, len(arr), 1) +// assert.Greater(t, 1, len(arr)) +// assert.Zero(t, len(arr)) +// assert.Empty(t, len(arr)) +// // assert.NotEqual(t, 0, len(arr)) -// assert.GreaterOrEqual(t, len(arr), 1) -// ... +// assert.NotEqualValues(t, 0, len(arr)) +// assert.Less(t, 0, len(arr)) +// assert.Greater(t, len(arr), 0) +// assert.Positive(t, len(arr)) +// assert.NotZero(t, len(arr)) +// assert.NotEmpty(t, len(arr)) // // and requires // @@ -48,18 +61,31 @@ func (checker Empty) checkEmpty(pass *analysis.Pass, call *CallMeta) *analysis.D ) } + if len(call.Args) == 0 { + return nil + } + + a := call.Args[0] + switch call.Fn.NameFTrimmed { + case "Zero", "Empty": + lenArg, ok := isBuiltinLenCall(pass, a) + if ok { + return newUseEmptyDiagnostic(a.Pos(), a.End(), lenArg) + } + } + if len(call.Args) < 2 { return nil } - a, b := call.Args[0], call.Args[1] + b := call.Args[1] - switch call.Fn.Name { - case "Len", "Lenf": + switch call.Fn.NameFTrimmed { + case "Len": if isZero(b) { return newUseEmptyDiagnostic(a.Pos(), b.End(), a) } - case "Equal", "Equalf": + case "Equal", "EqualValues", "Exactly": arg1, ok1 := isLenCallAndZero(pass, a, b) arg2, ok2 := isLenCallAndZero(pass, b, a) @@ -67,23 +93,23 @@ func (checker Empty) checkEmpty(pass *analysis.Pass, call *CallMeta) *analysis.D return newUseEmptyDiagnostic(a.Pos(), b.End(), lenArg) } - case "LessOrEqual", "LessOrEqualf": + case "LessOrEqual": if lenArg, ok := isBuiltinLenCall(pass, a); ok && isZero(b) { return newUseEmptyDiagnostic(a.Pos(), b.End(), lenArg) } - case "GreaterOrEqual", "GreaterOrEqualf": + case "GreaterOrEqual": if lenArg, ok := isBuiltinLenCall(pass, b); ok && isZero(a) { return newUseEmptyDiagnostic(a.Pos(), b.End(), lenArg) } - case "Less", "Lessf": - if lenArg, ok := isBuiltinLenCall(pass, a); ok && isOne(b) { + case "Less": + if lenArg, ok := isBuiltinLenCall(pass, a); ok && (isOne(b) || isZero(b)) { return newUseEmptyDiagnostic(a.Pos(), b.End(), lenArg) } - case "Greater", "Greaterf": - if lenArg, ok := isBuiltinLenCall(pass, b); ok && isOne(a) { + case "Greater": + if lenArg, ok := isBuiltinLenCall(pass, b); ok && (isOne(a) || isZero(a)) { return newUseEmptyDiagnostic(a.Pos(), b.End(), lenArg) } } @@ -102,13 +128,26 @@ func (checker Empty) checkNotEmpty(pass *analysis.Pass, call *CallMeta) *analysi ) } + if len(call.Args) == 0 { + return nil + } + + a := call.Args[0] + switch call.Fn.NameFTrimmed { + case "NotZero", "NotEmpty", "Positive": + lenArg, ok := isBuiltinLenCall(pass, a) + if ok { + return newUseNotEmptyDiagnostic(a.Pos(), a.End(), lenArg) + } + } + if len(call.Args) < 2 { return nil } - a, b := call.Args[0], call.Args[1] + b := call.Args[1] - switch call.Fn.Name { - case "NotEqual", "NotEqualf": + switch call.Fn.NameFTrimmed { + case "NotEqual", "NotEqualValues": arg1, ok1 := isLenCallAndZero(pass, a, b) arg2, ok2 := isLenCallAndZero(pass, b, a) @@ -116,57 +155,15 @@ func (checker Empty) checkNotEmpty(pass *analysis.Pass, call *CallMeta) *analysi return newUseNotEmptyDiagnostic(a.Pos(), b.End(), lenArg) } - case "Greater", "Greaterf": - if lenArg, ok := isBuiltinLenCall(pass, a); ok && isZero(b) || isOne(b) { - return newUseNotEmptyDiagnostic(a.Pos(), b.End(), lenArg) - } - - case "Less", "Lessf": - if lenArg, ok := isBuiltinLenCall(pass, b); ok && isZero(a) || isOne(a) { - return newUseNotEmptyDiagnostic(a.Pos(), b.End(), lenArg) - } - - case "GreaterOrEqual", "GreaterOrEqualf": - if lenArg, ok := isBuiltinLenCall(pass, a); ok && isOne(b) { + case "Less": + if lenArg, ok := isBuiltinLenCall(pass, b); ok && isZero(a) { return newUseNotEmptyDiagnostic(a.Pos(), b.End(), lenArg) } - case "LessOrEqual", "LessOrEqualf": - if lenArg, ok := isBuiltinLenCall(pass, b); ok && isOne(a) { + case "Greater": + if lenArg, ok := isBuiltinLenCall(pass, a); ok && isZero(b) { return newUseNotEmptyDiagnostic(a.Pos(), b.End(), lenArg) } } return nil } - -var lenObj = types.Universe.Lookup("len") - -func isLenCallAndZero(pass *analysis.Pass, a, b ast.Expr) (ast.Expr, bool) { - lenArg, ok := isBuiltinLenCall(pass, a) - return lenArg, ok && isZero(b) -} - -func isBuiltinLenCall(pass *analysis.Pass, e ast.Expr) (ast.Expr, bool) { - ce, ok := e.(*ast.CallExpr) - if !ok { - return nil, false - } - - if analysisutil.IsObj(pass.TypesInfo, ce.Fun, lenObj) && len(ce.Args) == 1 { - return ce.Args[0], true - } - return nil, false -} - -func isZero(e ast.Expr) bool { - return isIntNumber(e, 0) -} - -func isOne(e ast.Expr) bool { - return isIntNumber(e, 1) -} - -func isIntNumber(e ast.Expr, v int) bool { - bl, ok := e.(*ast.BasicLit) - return ok && bl.Kind == token.INT && bl.Value == fmt.Sprintf("%d", v) -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_is_as.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_is_as.go index e6abd0ba4..ab92c2ec0 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_is_as.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_is_as.go @@ -3,10 +3,9 @@ package checkers import ( "fmt" "go/ast" + "go/types" "golang.org/x/tools/go/analysis" - - "github.com/Antonboom/testifylint/internal/analysisutil" ) // ErrorIsAs detects situations like @@ -22,6 +21,8 @@ import ( // assert.ErrorIs(t, err, errSentinel) // assert.NotErrorIs(t, err, errSentinel) // assert.ErrorAs(t, err, &target) +// +// Also ErrorIsAs repeats go vet's "errorsas" check logic. type ErrorIsAs struct{} // NewErrorIsAs constructs ErrorIsAs checker. @@ -29,22 +30,22 @@ func NewErrorIsAs() ErrorIsAs { return ErrorIsAs{} } func (ErrorIsAs) Name() string { return "error-is-as" } func (checker ErrorIsAs) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { - switch call.Fn.Name { - case "Error", "Errorf": + switch call.Fn.NameFTrimmed { + case "Error": if len(call.Args) >= 2 && isError(pass, call.Args[1]) { const proposed = "ErrorIs" msg := fmt.Sprintf("invalid usage of %[1]s.Error, use %[1]s.%[2]s instead", call.SelectorXStr, proposed) return newDiagnostic(checker.Name(), call, msg, newSuggestedFuncReplacement(call, proposed)) } - case "NoError", "NoErrorf": + case "NoError": if len(call.Args) >= 2 && isError(pass, call.Args[1]) { const proposed = "NotErrorIs" msg := fmt.Sprintf("invalid usage of %[1]s.NoError, use %[1]s.%[2]s instead", call.SelectorXStr, proposed) return newDiagnostic(checker.Name(), call, msg, newSuggestedFuncReplacement(call, proposed)) } - case "True", "Truef": + case "True": if len(call.Args) < 1 { return nil } @@ -74,7 +75,7 @@ func (checker ErrorIsAs) Check(pass *analysis.Pass, call *CallMeta) *analysis.Di ) } - case "False", "Falsef": + case "False": if len(call.Args) < 1 { return nil } @@ -97,28 +98,45 @@ func (checker ErrorIsAs) Check(pass *analysis.Pass, call *CallMeta) *analysis.Di }), ) } - } - return nil -} -func isErrorsIsCall(pass *analysis.Pass, ce *ast.CallExpr) bool { - return isErrorsPkgFnCall(pass, ce, "Is") -} + case "ErrorAs": + if len(call.Args) < 2 { + return nil + } -func isErrorsAsCall(pass *analysis.Pass, ce *ast.CallExpr) bool { - return isErrorsPkgFnCall(pass, ce, "As") -} + // NOTE(a.telyshev): Logic below must be consistent with + // https://cs.opensource.google/go/x/tools/+/master:go/analysis/passes/errorsas/errorsas.go -func isErrorsPkgFnCall(pass *analysis.Pass, ce *ast.CallExpr, fn string) bool { - se, ok := ce.Fun.(*ast.SelectorExpr) - if !ok { - return false - } + var ( + defaultReport = fmt.Sprintf("second argument to %s must be a non-nil pointer to either a type that implements error, or to any interface type", call) //nolint:lll + errorPtrReport = fmt.Sprintf("second argument to %s should not be *error", call) + ) - errorsIsObj := analysisutil.ObjectOf(pass.Pkg, "errors", fn) - if errorsIsObj == nil { - return false - } + target := call.Args[1] - return analysisutil.IsObj(pass.TypesInfo, se.Sel, errorsIsObj) + if isEmptyInterface(pass, target) { + // `any` interface case. It is always allowed, since it often indicates + // a value forwarded from another source. + return nil + } + + tv, ok := pass.TypesInfo.Types[target] + if !ok { + return nil + } + + pt, ok := tv.Type.Underlying().(*types.Pointer) + if !ok { + return newDiagnostic(checker.Name(), call, defaultReport, nil) + } + if pt.Elem() == errorType { + return newDiagnostic(checker.Name(), call, errorPtrReport, nil) + } + + _, isInterface := pt.Elem().Underlying().(*types.Interface) + if !isInterface && !types.Implements(pt.Elem(), errorIface) { + return newDiagnostic(checker.Name(), call, defaultReport, nil) + } + } + return nil } diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_nil.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_nil.go index b45629a48..1e56d222a 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_nil.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/error_nil.go @@ -3,7 +3,6 @@ package checkers import ( "go/ast" "go/token" - "go/types" "golang.org/x/tools/go/analysis" @@ -14,8 +13,14 @@ import ( // // assert.Nil(t, err) // assert.NotNil(t, err) -// assert.Equal(t, err, nil) -// assert.NotEqual(t, err, nil) +// assert.Equal(t, nil, err) +// assert.EqualValues(t, nil, err) +// assert.Exactly(t, nil, err) +// assert.ErrorIs(t, err, nil) +// +// assert.NotEqual(t, nil, err) +// assert.NotEqualValues(t, nil, err) +// assert.NotErrorIs(t, err, nil) // // and requires // @@ -34,40 +39,40 @@ func (checker ErrorNil) Check(pass *analysis.Pass, call *CallMeta) *analysis.Dia ) proposedFn, survivingArg, replacementEndPos := func() (string, ast.Expr, token.Pos) { - switch call.Fn.Name { - case "NotNil", "NotNilf": + switch call.Fn.NameFTrimmed { + case "Nil": if len(call.Args) >= 1 && isError(pass, call.Args[0]) { - return errorFn, call.Args[0], call.Args[0].End() + return noErrorFn, call.Args[0], call.Args[0].End() } - case "Nil", "Nilf": + case "NotNil": if len(call.Args) >= 1 && isError(pass, call.Args[0]) { - return noErrorFn, call.Args[0], call.Args[0].End() + return errorFn, call.Args[0], call.Args[0].End() } - case "Equal", "Equalf": + case "Equal", "EqualValues", "Exactly", "ErrorIs": if len(call.Args) < 2 { return "", nil, token.NoPos } a, b := call.Args[0], call.Args[1] switch { - case isError(pass, a) && isNil(pass, b): + case isError(pass, a) && isNil(b): return noErrorFn, a, b.End() - case isNil(pass, a) && isError(pass, b): + case isNil(a) && isError(pass, b): return noErrorFn, b, b.End() } - case "NotEqual", "NotEqualf": + case "NotEqual", "NotEqualValues", "NotErrorIs": if len(call.Args) < 2 { return "", nil, token.NoPos } a, b := call.Args[0], call.Args[1] switch { - case isError(pass, a) && isNil(pass, b): + case isError(pass, a) && isNil(b): return errorFn, a, b.End() - case isNil(pass, a) && isError(pass, b): + case isNil(a) && isError(pass, b): return errorFn, b, b.End() } } @@ -85,25 +90,3 @@ func (checker ErrorNil) Check(pass *analysis.Pass, call *CallMeta) *analysis.Dia } return nil } - -var errIface = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) - -func isError(pass *analysis.Pass, expr ast.Expr) bool { - t := pass.TypesInfo.TypeOf(expr) - if t == nil { - return false - } - - _, ok := t.Underlying().(*types.Interface) - return ok && types.Implements(t, errIface) -} - -func isNil(pass *analysis.Pass, expr ast.Expr) bool { - t := pass.TypesInfo.TypeOf(expr) - if t == nil { - return false - } - - b, ok := t.(*types.Basic) - return ok && b.Kind()&types.UntypedNil > 0 -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/expected_actual.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/expected_actual.go index ff8243980..77784dc7b 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/expected_actual.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/expected_actual.go @@ -2,23 +2,44 @@ package checkers import ( "go/ast" - "go/types" + "go/token" "regexp" "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" ) // DefaultExpectedVarPattern matches variables with "expected" or "wanted" prefix or suffix in the name. var DefaultExpectedVarPattern = regexp.MustCompile( `(^(exp(ected)?|want(ed)?)([A-Z]\w*)?$)|(^(\w*[a-z])?(Exp(ected)?|Want(ed)?)$)`) -// ExpectedActual detects situation like +// ExpectedActual detects situations like // -// assert.NotEqual(t, result, "expected value") +// assert.Equal(t, result, expected) +// assert.EqualExportedValues(t, resultObj, User{Name: "Anton"}) +// assert.EqualValues(t, result, 42) +// assert.Exactly(t, result, int64(42)) +// assert.JSONEq(t, result, `{"version": 3}`) +// assert.InDelta(t, result, 42.42, 1.0) +// assert.InDeltaMapValues(t, result, map[string]float64{"score": 0.99}, 1.0) +// assert.InDeltaSlice(t, result, []float64{0.98, 0.99}, 1.0) +// assert.InEpsilon(t, result, 42.42, 0.0001) +// assert.InEpsilonSlice(t, result, []float64{0.9801, 0.9902}, 0.0001) +// assert.IsType(t, result, (*User)(nil)) +// assert.NotEqual(t, result, "expected") +// assert.NotEqualValues(t, result, "expected") +// assert.NotSame(t, resultPtr, &value) +// assert.Same(t, resultPtr, &value) +// assert.WithinDuration(t, resultTime, time.Date(2023, 01, 12, 11, 46, 33, 0, nil), time.Second) +// assert.YAMLEq(t, result, "version: '3'") // // and requires // -// assert.NotEqual(t, "expected value", result) +// assert.Equal(t, expected, result) +// assert.EqualExportedValues(t, User{Name: "Anton"}, resultObj) +// assert.EqualValues(t, 42, result) +// ... type ExpectedActual struct { expVarPattern *regexp.Regexp } @@ -38,9 +59,24 @@ func (checker *ExpectedActual) SetExpVarPattern(p *regexp.Regexp) *ExpectedActua } func (checker ExpectedActual) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { - switch call.Fn.Name { - case "Equal", "Equalf", "NotEqual", "NotEqualf", - "JSONEq", "JSONEqf", "YAMLEq", "YAMLEqf": + switch call.Fn.NameFTrimmed { + case "Equal", + "EqualExportedValues", + "EqualValues", + "Exactly", + "InDelta", + "InDeltaMapValues", + "InDeltaSlice", + "InEpsilon", + "InEpsilonSlice", + "IsType", + "JSONEq", + "NotEqual", + "NotEqualValues", + "NotSame", + "Same", + "WithinDuration", + "YAMLEq": default: return nil } @@ -73,19 +109,35 @@ func (checker ExpectedActual) isWrongExpectedActualOrder(pass *analysis.Pass, fi func (checker ExpectedActual) isExpectedValueCandidate(pass *analysis.Pass, expr ast.Expr) bool { switch v := expr.(type) { + case *ast.ParenExpr: + return checker.isExpectedValueCandidate(pass, v.X) + + case *ast.StarExpr: // *value + return checker.isExpectedValueCandidate(pass, v.X) + + case *ast.UnaryExpr: + return (v.Op == token.AND) && checker.isExpectedValueCandidate(pass, v.X) // &value + case *ast.CompositeLit: return true case *ast.CallExpr: - return isCastedBasicLitOrExpectedValue(v, checker.expVarPattern) || - isExpectedValueFactory(v, checker.expVarPattern) + return isParenExpr(v) || + isCastedBasicLitOrExpectedValue(v, checker.expVarPattern) || + isExpectedValueFactory(pass, v, checker.expVarPattern) } return isBasicLit(expr) || isUntypedConst(pass, expr) || isTypedConst(pass, expr) || - isIdentNamedAsExpected(checker.expVarPattern, expr) || - isStructFieldNamedAsExpected(checker.expVarPattern, expr) + isIdentNamedAfterPattern(checker.expVarPattern, expr) || + isStructVarNamedAfterPattern(checker.expVarPattern, expr) || + isStructFieldNamedAfterPattern(checker.expVarPattern, expr) +} + +func isParenExpr(ce *ast.CallExpr) bool { + _, ok := ce.Fun.(*ast.ParenExpr) + return ok } func isCastedBasicLitOrExpectedValue(ce *ast.CallExpr, pattern *regexp.Regexp) bool { @@ -106,51 +158,22 @@ func isCastedBasicLitOrExpectedValue(ce *ast.CallExpr, pattern *regexp.Regexp) b "int", "int8", "int16", "int32", "int64", "float32", "float64", "rune", "string": - return isBasicLit(ce.Args[0]) || isIdentNamedAsExpected(pattern, ce.Args[0]) + return isBasicLit(ce.Args[0]) || isIdentNamedAfterPattern(pattern, ce.Args[0]) } return false } -func isExpectedValueFactory(ce *ast.CallExpr, pattern *regexp.Regexp) bool { - if len(ce.Args) != 0 { - return false - } - +func isExpectedValueFactory(pass *analysis.Pass, ce *ast.CallExpr, pattern *regexp.Regexp) bool { switch fn := ce.Fun.(type) { case *ast.Ident: return pattern.MatchString(fn.Name) + case *ast.SelectorExpr: + timeDateFn := analysisutil.ObjectOf(pass.Pkg, "time", "Date") + if timeDateFn != nil && analysisutil.IsObj(pass.TypesInfo, fn.Sel, timeDateFn) { + return true + } return pattern.MatchString(fn.Sel.Name) } return false } - -func isBasicLit(e ast.Expr) bool { - _, ok := e.(*ast.BasicLit) - return ok -} - -func isUntypedConst(p *analysis.Pass, e ast.Expr) bool { - t := p.TypesInfo.TypeOf(e) - if t == nil { - return false - } - - b, ok := t.(*types.Basic) - return ok && b.Info()&types.IsUntyped > 0 -} - -func isTypedConst(p *analysis.Pass, e ast.Expr) bool { - tt, ok := p.TypesInfo.Types[e] - return ok && tt.IsValue() && tt.Value != nil -} - -func isIdentNamedAsExpected(pattern *regexp.Regexp, e ast.Expr) bool { - id, ok := e.(*ast.Ident) - return ok && pattern.MatchString(id.Name) -} - -func isStructFieldNamedAsExpected(pattern *regexp.Regexp, e ast.Expr) bool { - s, ok := e.(*ast.SelectorExpr) - return ok && isIdentNamedAsExpected(pattern, s.Sel) -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/float_compare.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/float_compare.go index 7d5b358b3..7436f9ca1 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/float_compare.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/float_compare.go @@ -1,22 +1,23 @@ package checkers import ( - "go/ast" + "fmt" "go/token" - "go/types" "golang.org/x/tools/go/analysis" ) -// FloatCompare detects situation like +// FloatCompare detects situations like // -// assert.Equal(t, 42.42, a) -// assert.True(t, a == 42.42) -// assert.False(t, a != 42.42) +// assert.Equal(t, 42.42, result) +// assert.EqualValues(t, 42.42, result) +// assert.Exactly(t, 42.42, result) +// assert.True(t, result == 42.42) +// assert.False(t, result != 42.42) // // and requires // -// assert.InEpsilon(t, 42.42, a, 0.0001) // Or assert.InDelta +// assert.InEpsilon(t, 42.42, result, 0.0001) // Or assert.InDelta type FloatCompare struct{} // NewFloatCompare constructs FloatCompare checker. @@ -25,39 +26,25 @@ func (FloatCompare) Name() string { return "float-compare" } func (checker FloatCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { invalid := func() bool { - switch call.Fn.Name { - case "Equal", "Equalf": - return len(call.Args) > 1 && isFloat(pass, call.Args[0]) && isFloat(pass, call.Args[1]) + switch call.Fn.NameFTrimmed { + case "Equal", "EqualValues", "Exactly": + return len(call.Args) > 1 && (isFloat(pass, call.Args[0]) || isFloat(pass, call.Args[1])) - case "True", "Truef": - return len(call.Args) > 0 && isFloatCompare(pass, call.Args[0], token.EQL) + case "True": + return len(call.Args) > 0 && isComparisonWithFloat(pass, call.Args[0], token.EQL) - case "False", "Falsef": - return len(call.Args) > 0 && isFloatCompare(pass, call.Args[0], token.NEQ) + case "False": + return len(call.Args) > 0 && isComparisonWithFloat(pass, call.Args[0], token.NEQ) } return false }() if invalid { - return newUseFunctionDiagnostic(checker.Name(), call, "InEpsilon (or InDelta)", nil) + format := "use %s.InEpsilon (or InDelta)" + if call.Fn.IsFmt { + format = "use %s.InEpsilonf (or InDeltaf)" + } + return newDiagnostic(checker.Name(), call, fmt.Sprintf(format, call.SelectorXStr), nil) } return nil } - -func isFloat(pass *analysis.Pass, expr ast.Expr) bool { - t := pass.TypesInfo.TypeOf(expr) - if t == nil { - return false - } - - bt, ok := t.Underlying().(*types.Basic) - return ok && (bt.Info()&types.IsFloat > 0) -} - -func isFloatCompare(p *analysis.Pass, e ast.Expr, op token.Token) bool { - be, ok := e.(*ast.BinaryExpr) - if !ok { - return false - } - return be.Op == op && (isFloat(p, be.X) || isFloat(p, be.Y)) -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/formatter.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/formatter.go new file mode 100644 index 000000000..3401bb097 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/formatter.go @@ -0,0 +1,187 @@ +package checkers + +import ( + "fmt" + "go/ast" + "go/types" + "strconv" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" + "github.com/Antonboom/testifylint/internal/checkers/printf" + "github.com/Antonboom/testifylint/internal/testify" +) + +// Formatter detects situations like +// +// assert.ElementsMatch(t, certConfig.Org, csr.Subject.Org, "organizations not equal") +// assert.Error(t, err, fmt.Sprintf("Profile %s should not be valid", test.profile)) +// assert.Errorf(t, err, fmt.Sprintf("test %s", test.testName)) +// assert.Truef(t, targetTs.Equal(ts), "the timestamp should be as expected (%s) but was %s", targetTs) +// ... +// +// and requires +// +// assert.ElementsMatchf(t, certConfig.Org, csr.Subject.Org, "organizations not equal") +// assert.Errorf(t, err, "Profile %s should not be valid", test.profile) +// assert.Errorf(t, err, "test %s", test.testName) +// assert.Truef(t, targetTs.Equal(ts), "the timestamp should be as expected (%s) but was %s", targetTs, ts) +type Formatter struct { + checkFormatString bool + requireFFuncs bool +} + +// NewFormatter constructs Formatter checker. +func NewFormatter() *Formatter { + return &Formatter{ + checkFormatString: true, + requireFFuncs: false, + } +} + +func (Formatter) Name() string { return "formatter" } + +func (checker *Formatter) SetCheckFormatString(v bool) *Formatter { + checker.checkFormatString = v + return checker +} + +func (checker *Formatter) SetRequireFFuncs(v bool) *Formatter { + checker.requireFFuncs = v + return checker +} + +func (checker Formatter) Check(pass *analysis.Pass, call *CallMeta) (result *analysis.Diagnostic) { + if call.Fn.IsFmt { + return checker.checkFmtAssertion(pass, call) + } + return checker.checkNotFmtAssertion(pass, call) +} + +func (checker Formatter) checkNotFmtAssertion(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { + msgAndArgsPos, ok := isPrintfLikeCall(pass, call, call.Fn.Signature) + if !ok { + return nil + } + + fFunc := call.Fn.Name + "f" + + if msgAndArgsPos == len(call.ArgsRaw)-1 { + msgAndArgs := call.ArgsRaw[msgAndArgsPos] + if args, ok := isFmtSprintfCall(pass, msgAndArgs); ok { + if checker.requireFFuncs { + msg := fmt.Sprintf("remove unnecessary fmt.Sprintf and use %s.%s", call.SelectorXStr, fFunc) + return newDiagnostic(checker.Name(), call, msg, + newSuggestedFuncReplacement(call, fFunc, analysis.TextEdit{ + Pos: msgAndArgs.Pos(), + End: msgAndArgs.End(), + NewText: formatAsCallArgs(pass, args...), + }), + ) + } + return newRemoveSprintfDiagnostic(pass, checker.Name(), call, msgAndArgs, args) + } + } + + if checker.requireFFuncs { + return newUseFunctionDiagnostic(checker.Name(), call, fFunc, newSuggestedFuncReplacement(call, fFunc)) + } + return nil +} + +func (checker Formatter) checkFmtAssertion(pass *analysis.Pass, call *CallMeta) (result *analysis.Diagnostic) { + formatPos := getMsgPosition(call.Fn.Signature) + if formatPos < 0 { + return nil + } + + msg := call.ArgsRaw[formatPos] + + if formatPos == len(call.ArgsRaw)-1 { + if args, ok := isFmtSprintfCall(pass, msg); ok { + return newRemoveSprintfDiagnostic(pass, checker.Name(), call, msg, args) + } + } + + if checker.checkFormatString { + report := pass.Report + defer func() { pass.Report = report }() + + pass.Report = func(d analysis.Diagnostic) { + result = newDiagnostic(checker.Name(), call, d.Message, nil) + } + + format, err := strconv.Unquote(analysisutil.NodeString(pass.Fset, msg)) + if err != nil { + return nil + } + printf.CheckPrintf(pass, call.Call, call.String(), format, formatPos) + } + return result +} + +func isPrintfLikeCall(pass *analysis.Pass, call *CallMeta, sig *types.Signature) (int, bool) { + msgAndArgsPos := getMsgAndArgsPosition(sig) + if msgAndArgsPos < 0 { + return -1, false + } + + fmtFn := analysisutil.ObjectOf(pass.Pkg, testify.AssertPkgPath, call.Fn.Name+"f") + if fmtFn == nil { + // NOTE(a.telyshev): No formatted analogue of assertion. + return -1, false + } + + return msgAndArgsPos, len(call.ArgsRaw) > msgAndArgsPos +} + +func getMsgAndArgsPosition(sig *types.Signature) int { + params := sig.Params() + if params.Len() < 1 { + return -1 + } + + lastIdx := params.Len() - 1 + lastParam := params.At(lastIdx) + + _, isSlice := lastParam.Type().(*types.Slice) + if lastParam.Name() == "msgAndArgs" && isSlice { + return lastIdx + } + return -1 +} + +func getMsgPosition(sig *types.Signature) int { + for i := 0; i < sig.Params().Len(); i++ { + param := sig.Params().At(i) + + if b, ok := param.Type().(*types.Basic); ok && b.Kind() == types.String && param.Name() == "msg" { + return i + } + } + return -1 +} + +func isFmtSprintfCall(pass *analysis.Pass, expr ast.Expr) ([]ast.Expr, bool) { + ce, ok := expr.(*ast.CallExpr) + if !ok { + return nil, false + } + + se, ok := ce.Fun.(*ast.SelectorExpr) + if !ok { + return nil, false + } + + sprintfObj := analysisutil.ObjectOf(pass.Pkg, "fmt", "Sprintf") + if sprintfObj == nil { + return nil, false + } + + if !analysisutil.IsObj(pass.TypesInfo, se.Sel, sprintfObj) { + return nil, false + } + + return ce.Args, true +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/go_require.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/go_require.go new file mode 100644 index 000000000..060c96033 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/go_require.go @@ -0,0 +1,345 @@ +package checkers + +import ( + "fmt" + "go/ast" + "go/types" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ast/inspector" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +const ( + goRequireFnReportFormat = "%s contains assertions that must only be used in the goroutine running the test function" + goRequireCallReportFormat = "%s must only be used in the goroutine running the test function" + goRequireHTTPHandlerReportFormat = "do not use %s in http handlers" +) + +// GoRequire takes idea from go vet's "testinggoroutine" check +// and detects usage of require package's functions or assert.FailNow in the non-test goroutines +// +// go func() { +// conn, err = lis.Accept() +// require.NoError(t, err) +// +// if assert.Error(err) { +// assert.FailNow(t, msg) +// } +// }() +type GoRequire struct { + ignoreHTTPHandlers bool +} + +// NewGoRequire constructs GoRequire checker. +func NewGoRequire() *GoRequire { return new(GoRequire) } +func (GoRequire) Name() string { return "go-require" } + +func (checker *GoRequire) SetIgnoreHTTPHandlers(v bool) *GoRequire { + checker.ignoreHTTPHandlers = v + return checker +} + +// Check should be consistent with +// https://cs.opensource.google/go/x/tools/+/master:go/analysis/passes/testinggoroutine/testinggoroutine.go +// +// But due to the fact that the Check covers cases missed by go vet, +// the implementation turned out to be terribly complicated. +// +// In simple words, the algorithm is as follows: +// - we walk along the call tree and store the status, whether we are in the test goroutine or not; +// - if we are in a test goroutine, then require is allowed, otherwise not; +// - when we encounter the launch of a subtest or `go` statement, the status changes; +// - in order to correctly handle the return to the correct status when exiting the current function, +// we have to store a stack of statuses (inGoroutineRunningTestFunc). +// +// Other test functions called in the test function are also analyzed to make a verdict about the current function. +// This leads to recursion, which the cache of processed functions (processedFuncs) helps reduce the impact of. +// Also, because of this, we have to pre-collect a list of test function declarations (testsDecls). +func (checker GoRequire) Check(pass *analysis.Pass, inspector *inspector.Inspector) (diagnostics []analysis.Diagnostic) { + testsDecls := make(funcDeclarations) + inspector.Preorder([]ast.Node{(*ast.FuncDecl)(nil)}, func(node ast.Node) { + fd := node.(*ast.FuncDecl) + + if isTestingFuncOrMethod(pass, fd) { + if tf, ok := pass.TypesInfo.ObjectOf(fd.Name).(*types.Func); ok { + testsDecls[tf] = fd + } + } + }) + + var inGoroutineRunningTestFunc boolStack + processedFuncs := make(map[*ast.FuncDecl]goRequireVerdict) + + nodesFilter := []ast.Node{ + (*ast.FuncDecl)(nil), + (*ast.FuncType)(nil), + (*ast.GoStmt)(nil), + (*ast.CallExpr)(nil), + } + inspector.Nodes(nodesFilter, func(node ast.Node, push bool) bool { + if fd, ok := node.(*ast.FuncDecl); ok { + if !isTestingFuncOrMethod(pass, fd) { + return false + } + + if push { + inGoroutineRunningTestFunc.Push(true) + } else { + inGoroutineRunningTestFunc.Pop() + } + return true + } + + if ft, ok := node.(*ast.FuncType); ok { + if !isTestingAnonymousFunc(pass, ft) { + return false + } + + if push { + inGoroutineRunningTestFunc.Push(true) + } else { + inGoroutineRunningTestFunc.Pop() + } + return true + } + + if _, ok := node.(*ast.GoStmt); ok { + if push { + inGoroutineRunningTestFunc.Push(false) + } else { + inGoroutineRunningTestFunc.Pop() + } + return true + } + + ce := node.(*ast.CallExpr) + if isSubTestRun(pass, ce) { + if push { + // t.Run spawns the new testing goroutine and declines + // possible warnings from previous "simple" goroutine. + inGoroutineRunningTestFunc.Push(true) + } else { + inGoroutineRunningTestFunc.Pop() + } + return true + } + + if !push { + return false + } + if inGoroutineRunningTestFunc.Len() == 0 { + // Insufficient info. + return true + } + if inGoroutineRunningTestFunc.Last() { + // We are in testing goroutine and can skip any assertion checks. + return true + } + + testifyCall := NewCallMeta(pass, ce) + if testifyCall != nil { + switch checker.checkCall(testifyCall) { + case goRequireVerdictRequire: + d := newDiagnostic(checker.Name(), testifyCall, fmt.Sprintf(goRequireCallReportFormat, "require"), nil) + diagnostics = append(diagnostics, *d) + + case goRequireVerdictAssertFailNow: + d := newDiagnostic(checker.Name(), testifyCall, fmt.Sprintf(goRequireCallReportFormat, testifyCall), nil) + diagnostics = append(diagnostics, *d) + + case goRequireVerdictNoExit: + } + return false + } + + // Case of nested function call. + { + calledFd := testsDecls.Get(pass, ce) + if calledFd == nil { + return true + } + + if v := checker.checkFunc(pass, calledFd, testsDecls, processedFuncs); v != goRequireVerdictNoExit { + caller := analysisutil.NodeString(pass.Fset, ce.Fun) + d := newDiagnostic(checker.Name(), ce, fmt.Sprintf(goRequireFnReportFormat, caller), nil) + diagnostics = append(diagnostics, *d) + } + } + return true + }) + + if !checker.ignoreHTTPHandlers { + diagnostics = append(diagnostics, checker.checkHTTPHandlers(pass, inspector)...) + } + + return diagnostics +} + +func (checker GoRequire) checkHTTPHandlers(pass *analysis.Pass, insp *inspector.Inspector) (diagnostics []analysis.Diagnostic) { + insp.WithStack([]ast.Node{(*ast.CallExpr)(nil)}, func(node ast.Node, push bool, stack []ast.Node) bool { + if !push { + return false + } + if len(stack) < 3 { + return true + } + + fID := findSurroundingFunc(pass, stack) + if fID == nil || !fID.meta.isHTTPHandler { + return true + } + + testifyCall := NewCallMeta(pass, node.(*ast.CallExpr)) + if testifyCall == nil { + return true + } + + switch checker.checkCall(testifyCall) { + case goRequireVerdictRequire: + d := newDiagnostic(checker.Name(), testifyCall, fmt.Sprintf(goRequireHTTPHandlerReportFormat, "require"), nil) + diagnostics = append(diagnostics, *d) + + case goRequireVerdictAssertFailNow: + d := newDiagnostic(checker.Name(), testifyCall, fmt.Sprintf(goRequireHTTPHandlerReportFormat, testifyCall), nil) + diagnostics = append(diagnostics, *d) + + case goRequireVerdictNoExit: + } + return false + }) + return diagnostics +} + +func (checker GoRequire) checkFunc( + pass *analysis.Pass, + fd *ast.FuncDecl, + testsDecls funcDeclarations, + processedFuncs map[*ast.FuncDecl]goRequireVerdict, +) (result goRequireVerdict) { + if v, ok := processedFuncs[fd]; ok { + return v + } + + ast.Inspect(fd, func(node ast.Node) bool { + if result != goRequireVerdictNoExit { + return false + } + + if _, ok := node.(*ast.GoStmt); ok { + return false + } + + ce, ok := node.(*ast.CallExpr) + if !ok { + return true + } + + testifyCall := NewCallMeta(pass, ce) + if testifyCall != nil { + if v := checker.checkCall(testifyCall); v != goRequireVerdictNoExit { + result, processedFuncs[fd] = v, v + } + return false + } + + // Case of nested function call. + { + calledFd := testsDecls.Get(pass, ce) + if calledFd == nil { + return true + } + if calledFd == fd { + // Recursion. + return true + } + + if v := checker.checkFunc(pass, calledFd, testsDecls, processedFuncs); v != goRequireVerdictNoExit { + result = v + return false + } + return true + } + }) + + return result +} + +type goRequireVerdict int + +const ( + goRequireVerdictNoExit goRequireVerdict = iota + goRequireVerdictRequire + goRequireVerdictAssertFailNow +) + +func (checker GoRequire) checkCall(call *CallMeta) goRequireVerdict { + if !call.IsAssert { + return goRequireVerdictRequire + } + if call.Fn.NameFTrimmed == "FailNow" { + return goRequireVerdictAssertFailNow + } + return goRequireVerdictNoExit +} + +type funcDeclarations map[*types.Func]*ast.FuncDecl + +// Get returns the declaration of a called function or method. +// Currently, only static calls within the same package are supported, otherwise returns nil. +func (fd funcDeclarations) Get(pass *analysis.Pass, ce *ast.CallExpr) *ast.FuncDecl { + var obj types.Object + + switch fun := ce.Fun.(type) { + case *ast.SelectorExpr: + obj = pass.TypesInfo.ObjectOf(fun.Sel) + + case *ast.Ident: + obj = pass.TypesInfo.ObjectOf(fun) + + case *ast.IndexExpr: + if id, ok := fun.X.(*ast.Ident); ok { + obj = pass.TypesInfo.ObjectOf(id) + } + + case *ast.IndexListExpr: + if id, ok := fun.X.(*ast.Ident); ok { + obj = pass.TypesInfo.ObjectOf(id) + } + } + + if tf, ok := obj.(*types.Func); ok { + return fd[tf] + } + return nil +} + +type boolStack []bool + +func (s boolStack) Len() int { + return len(s) +} + +func (s *boolStack) Push(v bool) { + *s = append(*s, v) +} + +func (s *boolStack) Pop() bool { + n := len(*s) + if n == 0 { + return false + } + + last := (*s)[n-1] + *s = (*s)[:n-1] + return last +} + +func (s boolStack) Last() bool { + n := len(s) + if n == 0 { + return false + } + return s[n-1] +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers.go new file mode 100644 index 000000000..4e4735269 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers.go @@ -0,0 +1,43 @@ +package checkers + +import ( + "go/ast" + + "golang.org/x/tools/go/analysis" +) + +func xor(a, b bool) bool { + return a != b +} + +// anyVal returns the first value[i] for which bools[i] is true. +func anyVal[T any](bools []bool, vals ...T) (T, bool) { + if len(bools) != len(vals) { + panic("inconsistent usage of valOr") //nolint:forbidigo // Does not depend on the code being analyzed. + } + + for i, b := range bools { + if b { + return vals[i], true + } + } + + var _default T + return _default, false +} + +func anyCondSatisfaction(pass *analysis.Pass, p predicate, vals ...ast.Expr) bool { + for _, v := range vals { + if p(pass, v) { + return true + } + } + return false +} + +// p transforms simple is-function in a predicate. +func p(fn func(e ast.Expr) bool) predicate { + return func(_ *analysis.Pass, e ast.Expr) bool { + return fn(e) + } +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_basic_type.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_basic_type.go new file mode 100644 index 000000000..432a3032c --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_basic_type.go @@ -0,0 +1,113 @@ +package checkers + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + + "golang.org/x/tools/go/analysis" +) + +func isZero(e ast.Expr) bool { return isIntNumber(e, 0) } + +func isOne(e ast.Expr) bool { return isIntNumber(e, 1) } + +func isAnyZero(e ast.Expr) bool { + return isIntNumber(e, 0) || isTypedSignedIntNumber(e, 0) || isTypedUnsignedIntNumber(e, 0) +} + +func isNotAnyZero(e ast.Expr) bool { + return !isAnyZero(e) +} + +func isZeroOrSignedZero(e ast.Expr) bool { + return isIntNumber(e, 0) || isTypedSignedIntNumber(e, 0) +} + +func isSignedNotZero(pass *analysis.Pass, e ast.Expr) bool { + return !isUnsigned(pass, e) && !isZeroOrSignedZero(e) +} + +func isTypedSignedIntNumber(e ast.Expr, v int) bool { + return isTypedIntNumber(e, v, "int", "int8", "int16", "int32", "int64") +} + +func isTypedUnsignedIntNumber(e ast.Expr, v int) bool { + return isTypedIntNumber(e, v, "uint", "uint8", "uint16", "uint32", "uint64") +} + +func isTypedIntNumber(e ast.Expr, v int, types ...string) bool { + ce, ok := e.(*ast.CallExpr) + if !ok || len(ce.Args) != 1 { + return false + } + + fn, ok := ce.Fun.(*ast.Ident) + if !ok { + return false + } + + for _, t := range types { + if fn.Name == t { + return isIntNumber(ce.Args[0], v) + } + } + return false +} + +func isIntNumber(e ast.Expr, v int) bool { + bl, ok := e.(*ast.BasicLit) + return ok && bl.Kind == token.INT && bl.Value == fmt.Sprintf("%d", v) +} + +func isBasicLit(e ast.Expr) bool { + _, ok := e.(*ast.BasicLit) + return ok +} + +func isIntBasicLit(e ast.Expr) bool { + bl, ok := e.(*ast.BasicLit) + return ok && bl.Kind == token.INT +} + +func isUntypedConst(pass *analysis.Pass, e ast.Expr) bool { + return isUnderlying(pass, e, types.IsUntyped) +} + +func isTypedConst(pass *analysis.Pass, e ast.Expr) bool { + tt, ok := pass.TypesInfo.Types[e] + return ok && tt.IsValue() && tt.Value != nil +} + +func isFloat(pass *analysis.Pass, e ast.Expr) bool { + return isUnderlying(pass, e, types.IsFloat) +} + +func isUnsigned(pass *analysis.Pass, e ast.Expr) bool { + return isUnderlying(pass, e, types.IsUnsigned) +} + +func isUnderlying(pass *analysis.Pass, e ast.Expr, flag types.BasicInfo) bool { + t := pass.TypesInfo.TypeOf(e) + if t == nil { + return false + } + + bt, ok := t.Underlying().(*types.Basic) + return ok && (bt.Info()&flag > 0) +} + +func isPointer(pass *analysis.Pass, e ast.Expr) bool { + _, ok := pass.TypesInfo.TypeOf(e).(*types.Pointer) + return ok +} + +// untype returns v from type(v) expression or v itself if there is no type cast. +func untype(e ast.Expr) ast.Expr { + ce, ok := e.(*ast.CallExpr) + if !ok || len(ce.Args) != 1 { + return e + } + return ce.Args[0] +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_bool.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_bool.go new file mode 100644 index 000000000..13e579a2b --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_bool.go @@ -0,0 +1,33 @@ +package checkers + +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +var ( + falseObj = types.Universe.Lookup("false") + trueObj = types.Universe.Lookup("true") +) + +func isUntypedTrue(pass *analysis.Pass, e ast.Expr) bool { + return analysisutil.IsObj(pass.TypesInfo, e, trueObj) +} + +func isUntypedFalse(pass *analysis.Pass, e ast.Expr) bool { + return analysisutil.IsObj(pass.TypesInfo, e, falseObj) +} + +func isBuiltinBool(pass *analysis.Pass, e ast.Expr) bool { + basicType, ok := pass.TypesInfo.TypeOf(e).(*types.Basic) + return ok && basicType.Kind() == types.Bool +} + +func isBoolOverride(pass *analysis.Pass, e ast.Expr) bool { + namedType, ok := pass.TypesInfo.TypeOf(e).(*types.Named) + return ok && namedType.Obj().Name() == "bool" +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_comparison.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_comparison.go new file mode 100644 index 000000000..ac11d7399 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_comparison.go @@ -0,0 +1,68 @@ +package checkers + +import ( + "go/ast" + "go/token" + + "golang.org/x/tools/go/analysis" +) + +func isComparisonWithFloat(p *analysis.Pass, e ast.Expr, op token.Token) bool { + be, ok := e.(*ast.BinaryExpr) + if !ok { + return false + } + return be.Op == op && (isFloat(p, be.X) || isFloat(p, be.Y)) +} + +func isComparisonWithTrue(pass *analysis.Pass, e ast.Expr, op token.Token) (ast.Expr, bool) { + return isComparisonWith(pass, e, isUntypedTrue, op) +} + +func isComparisonWithFalse(pass *analysis.Pass, e ast.Expr, op token.Token) (ast.Expr, bool) { + return isComparisonWith(pass, e, isUntypedFalse, op) +} + +type predicate func(pass *analysis.Pass, e ast.Expr) bool + +func isComparisonWith( + pass *analysis.Pass, + e ast.Expr, + predicate predicate, + op token.Token, +) (ast.Expr, bool) { + be, ok := e.(*ast.BinaryExpr) + if !ok { + return nil, false + } + if be.Op != op { + return nil, false + } + + t1, t2 := predicate(pass, be.X), predicate(pass, be.Y) + if xor(t1, t2) { + if t1 { + return be.Y, true + } + return be.X, true + } + return nil, false +} + +func isStrictComparisonWith( + pass *analysis.Pass, + e ast.Expr, + lhs predicate, + op token.Token, + rhs predicate, +) (ast.Expr, ast.Expr, bool) { + be, ok := e.(*ast.BinaryExpr) + if !ok { + return nil, nil, false + } + + if be.Op == op && lhs(pass, be.X) && rhs(pass, be.Y) { + return be.X, be.Y, true + } + return nil, nil, false +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_context.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_context.go new file mode 100644 index 000000000..e8505fad0 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_context.go @@ -0,0 +1,126 @@ +package checkers + +import ( + "fmt" + "go/ast" + "go/token" + + "golang.org/x/tools/go/analysis" +) + +type funcID struct { + pos token.Pos + posStr string + name string + meta funcMeta +} + +type funcMeta struct { + isTestCleanup bool + isGoroutine bool + isHTTPHandler bool +} + +func (id funcID) String() string { + return fmt.Sprintf("%s at %s", id.name, id.posStr) +} + +func findSurroundingFunc(pass *analysis.Pass, stack []ast.Node) *funcID { + for i := len(stack) - 2; i >= 0; i-- { + var fType *ast.FuncType + var fName string + var isTestCleanup bool + var isGoroutine bool + var isHTTPHandler bool + + switch fd := stack[i].(type) { + case *ast.FuncDecl: + fType, fName = fd.Type, fd.Name.Name + + if isSuiteMethod(pass, fd) { + if ident := fd.Name; ident != nil && isSuiteAfterTestMethod(ident.Name) { + isTestCleanup = true + } + } + + if mimicHTTPHandler(pass, fd.Type) { + isHTTPHandler = true + } + + case *ast.FuncLit: + fType, fName = fd.Type, "anonymous" + + if mimicHTTPHandler(pass, fType) { + isHTTPHandler = true + } + + if i >= 2 { //nolint:nestif + if ce, ok := stack[i-1].(*ast.CallExpr); ok { + if se, ok := ce.Fun.(*ast.SelectorExpr); ok { + isTestCleanup = implementsTestingT(pass, se.X) && se.Sel != nil && (se.Sel.Name == "Cleanup") + } + + if _, ok := stack[i-2].(*ast.GoStmt); ok { + isGoroutine = true + } + } + } + + default: + continue + } + + return &funcID{ + pos: fType.Pos(), + posStr: pass.Fset.Position(fType.Pos()).String(), + name: fName, + meta: funcMeta{ + isTestCleanup: isTestCleanup, + isGoroutine: isGoroutine, + isHTTPHandler: isHTTPHandler, + }, + } + } + return nil +} + +func findNearestNode[T ast.Node](stack []ast.Node) (v T) { + v, _ = findNearestNodeWithIdx[T](stack) + return +} + +func findNearestNodeWithIdx[T ast.Node](stack []ast.Node) (v T, index int) { + for i := len(stack) - 2; i >= 0; i-- { + if n, ok := stack[i].(T); ok { + return n, i + } + } + return +} + +func fnContainsAssertions(pass *analysis.Pass, fn *ast.FuncDecl) bool { + if fn.Body == nil { + return false + } + + for _, s := range fn.Body.List { + if isAssertionStmt(pass, s) { + return true + } + } + return false +} + +func isAssertionStmt(pass *analysis.Pass, stmt ast.Stmt) bool { + expr, ok := stmt.(*ast.ExprStmt) + if !ok { + return false + } + + ce, ok := expr.X.(*ast.CallExpr) + if !ok { + return false + } + + return NewCallMeta(pass, ce) != nil +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/diagnostic.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_diagnostic.go similarity index 70% rename from tools/vendor/github.com/Antonboom/testifylint/internal/checkers/diagnostic.go rename to tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_diagnostic.go index 4ab69c69b..3ae88a560 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/diagnostic.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_diagnostic.go @@ -2,6 +2,7 @@ package checkers import ( "fmt" + "go/ast" "golang.org/x/tools/go/analysis" ) @@ -21,6 +22,25 @@ func newUseFunctionDiagnostic( return newDiagnostic(checker, call, msg, fix) } +func newRemoveSprintfDiagnostic( + pass *analysis.Pass, + checker string, + call *CallMeta, + sprintfPos analysis.Range, + sprintfArgs []ast.Expr, +) *analysis.Diagnostic { + return newDiagnostic(checker, call, "remove unnecessary fmt.Sprintf", &analysis.SuggestedFix{ + Message: "Remove `fmt.Sprintf`", + TextEdits: []analysis.TextEdit{ + { + Pos: sprintfPos.Pos(), + End: sprintfPos.End(), + NewText: formatAsCallArgs(pass, sprintfArgs...), + }, + }, + }) +} + func newDiagnostic( checker string, rng analysis.Range, diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_error.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_error.go new file mode 100644 index 000000000..55cd5fd05 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_error.go @@ -0,0 +1,42 @@ +package checkers + +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +var ( + errorObj = types.Universe.Lookup("error") + errorType = errorObj.Type() + errorIface = errorType.Underlying().(*types.Interface) +) + +func isError(pass *analysis.Pass, expr ast.Expr) bool { + return pass.TypesInfo.TypeOf(expr) == errorType +} + +func isErrorsIsCall(pass *analysis.Pass, ce *ast.CallExpr) bool { + return isErrorsPkgFnCall(pass, ce, "Is") +} + +func isErrorsAsCall(pass *analysis.Pass, ce *ast.CallExpr) bool { + return isErrorsPkgFnCall(pass, ce, "As") +} + +func isErrorsPkgFnCall(pass *analysis.Pass, ce *ast.CallExpr, fn string) bool { + se, ok := ce.Fun.(*ast.SelectorExpr) + if !ok { + return false + } + + errorsIsObj := analysisutil.ObjectOf(pass.Pkg, "errors", fn) + if errorsIsObj == nil { + return false + } + + return analysisutil.IsObj(pass.TypesInfo, se.Sel, errorsIsObj) +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_format.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_format.go new file mode 100644 index 000000000..765fce527 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_format.go @@ -0,0 +1,26 @@ +package checkers + +import ( + "bytes" + "go/ast" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +// formatAsCallArgs joins a, b and c and returns bytes like `a, b, c`. +func formatAsCallArgs(pass *analysis.Pass, args ...ast.Expr) []byte { + if len(args) == 0 { + return []byte("") + } + + var buf bytes.Buffer + for i, arg := range args { + buf.Write(analysisutil.NodeBytes(pass.Fset, arg)) + if i != len(args)-1 { + buf.WriteString(", ") + } + } + return buf.Bytes() +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_http.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_http.go new file mode 100644 index 000000000..9dabb02a9 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_http.go @@ -0,0 +1,35 @@ +package checkers + +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +func mimicHTTPHandler(pass *analysis.Pass, fType *ast.FuncType) bool { + httpHandlerFuncObj := analysisutil.ObjectOf(pass.Pkg, "net/http", "HandlerFunc") + if httpHandlerFuncObj == nil { + return false + } + + sig, ok := httpHandlerFuncObj.Type().Underlying().(*types.Signature) + if !ok { + return false + } + + if len(fType.Params.List) != sig.Params().Len() { + return false + } + + for i := 0; i < sig.Params().Len(); i++ { + lhs := sig.Params().At(i).Type() + rhs := pass.TypesInfo.TypeOf(fType.Params.List[i].Type) + if !types.Identical(lhs, rhs) { + return false + } + } + return true +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_interface.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_interface.go new file mode 100644 index 000000000..b0c0d1302 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_interface.go @@ -0,0 +1,48 @@ +package checkers + +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" + "github.com/Antonboom/testifylint/internal/testify" +) + +func isEmptyInterface(pass *analysis.Pass, expr ast.Expr) bool { + t, ok := pass.TypesInfo.Types[expr] + if !ok { + return false + } + + iface, ok := t.Type.Underlying().(*types.Interface) + return ok && iface.NumMethods() == 0 +} + +func implementsTestifySuite(pass *analysis.Pass, e ast.Expr) bool { + suiteIfaceObj := analysisutil.ObjectOf(pass.Pkg, testify.SuitePkgPath, "TestingSuite") + return (suiteIfaceObj != nil) && implements(pass, e, suiteIfaceObj) +} + +func implementsTestingT(pass *analysis.Pass, e ast.Expr) bool { + return implementsAssertTestingT(pass, e) || implementsRequireTestingT(pass, e) +} + +func implementsAssertTestingT(pass *analysis.Pass, e ast.Expr) bool { + assertTestingTObj := analysisutil.ObjectOf(pass.Pkg, testify.AssertPkgPath, "TestingT") + return (assertTestingTObj != nil) && implements(pass, e, assertTestingTObj) +} + +func implementsRequireTestingT(pass *analysis.Pass, e ast.Expr) bool { + requireTestingTObj := analysisutil.ObjectOf(pass.Pkg, testify.RequirePkgPath, "TestingT") + return (requireTestingTObj != nil) && implements(pass, e, requireTestingTObj) +} + +func implements(pass *analysis.Pass, e ast.Expr, ifaceObj types.Object) bool { + t := pass.TypesInfo.TypeOf(e) + if t == nil { + return false + } + return types.Implements(t, ifaceObj.Type().Underlying().(*types.Interface)) +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_len.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_len.go new file mode 100644 index 000000000..904950ff3 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_len.go @@ -0,0 +1,55 @@ +package checkers + +import ( + "go/ast" + "go/token" + "go/types" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +var lenObj = types.Universe.Lookup("len") + +func isLenEquality(pass *analysis.Pass, e ast.Expr) (ast.Expr, ast.Expr, bool) { + be, ok := e.(*ast.BinaryExpr) + if !ok { + return nil, nil, false + } + + if be.Op != token.EQL { + return nil, nil, false + } + return xorLenCall(pass, be.X, be.Y) +} + +func xorLenCall(pass *analysis.Pass, a, b ast.Expr) (lenArg ast.Expr, expectedLen ast.Expr, ok bool) { + arg1, ok1 := isBuiltinLenCall(pass, a) + arg2, ok2 := isBuiltinLenCall(pass, b) + + if xor(ok1, ok2) { + if ok1 { + return arg1, b, true + } + return arg2, a, true + } + return nil, nil, false +} + +func isLenCallAndZero(pass *analysis.Pass, a, b ast.Expr) (ast.Expr, bool) { + lenArg, ok := isBuiltinLenCall(pass, a) + return lenArg, ok && isZero(b) +} + +func isBuiltinLenCall(pass *analysis.Pass, e ast.Expr) (ast.Expr, bool) { + ce, ok := e.(*ast.CallExpr) + if !ok { + return nil, false + } + + if analysisutil.IsObj(pass.TypesInfo, ce.Fun, lenObj) && len(ce.Args) == 1 { + return ce.Args[0], true + } + return nil, false +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_naming.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_naming.go new file mode 100644 index 000000000..1d92e3e81 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_naming.go @@ -0,0 +1,26 @@ +package checkers + +import ( + "go/ast" + "regexp" +) + +func isStructVarNamedAfterPattern(pattern *regexp.Regexp, e ast.Expr) bool { + s, ok := e.(*ast.SelectorExpr) + return ok && isIdentNamedAfterPattern(pattern, s.X) +} + +func isStructFieldNamedAfterPattern(pattern *regexp.Regexp, e ast.Expr) bool { + s, ok := e.(*ast.SelectorExpr) + return ok && isIdentNamedAfterPattern(pattern, s.Sel) +} + +func isIdentNamedAfterPattern(pattern *regexp.Regexp, e ast.Expr) bool { + id, ok := e.(*ast.Ident) + return ok && pattern.MatchString(id.Name) +} + +func isIdentWithName(name string, e ast.Expr) bool { + id, ok := e.(*ast.Ident) + return ok && id.Name == name +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_nil.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_nil.go new file mode 100644 index 000000000..112fca38e --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_nil.go @@ -0,0 +1,18 @@ +package checkers + +import "go/ast" + +func xorNil(first, second ast.Expr) (ast.Expr, bool) { + a, b := isNil(first), isNil(second) + if xor(a, b) { + if a { + return second, true + } + return first, true + } + return nil, false +} + +func isNil(expr ast.Expr) bool { + return isIdentWithName("nil", expr) +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_suite.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_suite.go new file mode 100644 index 000000000..9f39d4653 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_suite.go @@ -0,0 +1,40 @@ +package checkers + +import ( + "go/ast" + "strings" + + "golang.org/x/tools/go/analysis" +) + +func isSuiteMethod(pass *analysis.Pass, fDecl *ast.FuncDecl) bool { + if fDecl.Recv == nil || len(fDecl.Recv.List) != 1 { + return false + } + + rcv := fDecl.Recv.List[0] + return implementsTestifySuite(pass, rcv.Type) +} + +func isSuiteTestMethod(name string) bool { + return strings.HasPrefix(name, "Test") +} + +func isSuiteServiceMethod(name string) bool { + // https://github.com/stretchr/testify/blob/master/suite/interfaces.go + switch name { + case "T", "SetT", "SetS", "SetupSuite", "SetupTest", "TearDownSuite", "TearDownTest", + "BeforeTest", "AfterTest", "HandleStats", "SetupSubTest", "TearDownSubTest": + return true + } + return false +} + +func isSuiteAfterTestMethod(name string) bool { + // https://github.com/stretchr/testify/blob/master/suite/interfaces.go + switch name { + case "TearDownSuite", "TearDownTest", "AfterTest", "HandleStats", "TearDownSubTest": + return true + } + return false +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_testing.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_testing.go new file mode 100644 index 000000000..5c28ec883 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/helpers_testing.go @@ -0,0 +1,36 @@ +package checkers + +import ( + "go/ast" + + "golang.org/x/tools/go/analysis" +) + +func isSubTestRun(pass *analysis.Pass, ce *ast.CallExpr) bool { + se, ok := ce.Fun.(*ast.SelectorExpr) + if !ok || se.Sel == nil { + return false + } + return (implementsTestingT(pass, se.X) || implementsTestifySuite(pass, se.X)) && se.Sel.Name == "Run" +} + +func isTestingFuncOrMethod(pass *analysis.Pass, fd *ast.FuncDecl) bool { + return hasTestingTParam(pass, fd.Type) || isSuiteMethod(pass, fd) +} + +func isTestingAnonymousFunc(pass *analysis.Pass, ft *ast.FuncType) bool { + return hasTestingTParam(pass, ft) +} + +func hasTestingTParam(pass *analysis.Pass, ft *ast.FuncType) bool { + if ft == nil || ft.Params == nil { + return false + } + + for _, param := range ft.Params.List { + if implementsTestingT(pass, param.Type) { + return true + } + } + return false +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/len.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/len.go index f10412f63..47330568c 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/len.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/len.go @@ -1,15 +1,14 @@ package checkers import ( - "go/ast" - "go/token" - "golang.org/x/tools/go/analysis" ) // Len detects situations like // // assert.Equal(t, 3, len(arr)) +// assert.EqualValues(t, 3, len(arr)) +// assert.Exactly(t, 3, len(arr)) // assert.True(t, len(arr) == 3) // // and requires @@ -24,14 +23,18 @@ func (Len) Name() string { return "len" } func (checker Len) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { const proposedFn = "Len" - switch call.Fn.Name { - case "Equal", "Equalf": + switch call.Fn.NameFTrimmed { + case "Equal", "EqualValues", "Exactly": if len(call.Args) < 2 { return nil } a, b := call.Args[0], call.Args[1] if lenArg, expectedLen, ok := xorLenCall(pass, a, b); ok { + if expectedLen == b && !isIntBasicLit(expectedLen) { + // https://github.com/Antonboom/testifylint/issues/9 + return nil + } return newUseFunctionDiagnostic(checker.Name(), call, proposedFn, newSuggestedFuncReplacement(call, proposedFn, analysis.TextEdit{ Pos: a.Pos(), @@ -41,13 +44,13 @@ func (checker Len) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnost ) } - case "True", "Truef": + case "True": if len(call.Args) < 1 { return nil } expr := call.Args[0] - if lenArg, expectedLen, ok := isLenEquality(pass, expr); ok { + if lenArg, expectedLen, ok := isLenEquality(pass, expr); ok && isIntBasicLit(expectedLen) { return newUseFunctionDiagnostic(checker.Name(), call, proposedFn, newSuggestedFuncReplacement(call, proposedFn, analysis.TextEdit{ Pos: expr.Pos(), @@ -59,28 +62,3 @@ func (checker Len) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnost } return nil } - -func xorLenCall(pass *analysis.Pass, a, b ast.Expr) (lenArg ast.Expr, expectedLen ast.Expr, ok bool) { - arg1, ok1 := isBuiltinLenCall(pass, a) - arg2, ok2 := isBuiltinLenCall(pass, b) - - if xor(ok1, ok2) { - if ok1 { - return arg1, b, true - } - return arg2, a, true - } - return nil, nil, false -} - -func isLenEquality(pass *analysis.Pass, e ast.Expr) (ast.Expr, ast.Expr, bool) { - be, ok := e.(*ast.BinaryExpr) - if !ok { - return nil, nil, false - } - - if be.Op != token.EQL { - return nil, nil, false - } - return xorLenCall(pass, be.X, be.Y) -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/negative_postive.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/negative_postive.go new file mode 100644 index 000000000..274021f67 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/negative_postive.go @@ -0,0 +1,175 @@ +package checkers + +import ( + "go/ast" + "go/token" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +// NegativePositive detects situations like +// +// assert.Less(t, a, 0) +// assert.Greater(t, 0, a) +// assert.True(t, a < 0) +// assert.True(t, 0 > a) +// assert.False(t, a >= 0) +// assert.False(t, 0 <= a) +// +// assert.Greater(t, a, 0) +// assert.Less(t, 0, a) +// assert.True(t, a > 0) +// assert.True(t, 0 < a) +// assert.False(t, a <= 0) +// assert.False(t, 0 >= a) +// +// and requires +// +// assert.Negative(t, value) +// assert.Positive(t, value) +// +// Typed zeros (like `int8(0)`, ..., `uint64(0)`) are also supported. +type NegativePositive struct{} + +// NewNegativePositive constructs NegativePositive checker. +func NewNegativePositive() NegativePositive { return NegativePositive{} } +func (NegativePositive) Name() string { return "negative-positive" } + +func (checker NegativePositive) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { + if d := checker.checkNegative(pass, call); d != nil { + return d + } + return checker.checkPositive(pass, call) +} + +func (checker NegativePositive) checkNegative(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { + newUseNegativeDiagnostic := func(replaceStart, replaceEnd token.Pos, replaceWith ast.Expr) *analysis.Diagnostic { + const proposed = "Negative" + return newUseFunctionDiagnostic(checker.Name(), call, proposed, + newSuggestedFuncReplacement(call, proposed, analysis.TextEdit{ + Pos: replaceStart, + End: replaceEnd, + NewText: analysisutil.NodeBytes(pass.Fset, replaceWith), + }), + ) + } + + // NOTE(a.telyshev): We ignore uint-asserts as being no sense for assert.Negative. + + switch call.Fn.NameFTrimmed { + case "Less": + if len(call.Args) < 2 { + return nil + } + a, b := call.Args[0], call.Args[1] + + if isSignedNotZero(pass, a) && isZeroOrSignedZero(b) { + return newUseNegativeDiagnostic(a.Pos(), b.End(), untype(a)) + } + + case "Greater": + if len(call.Args) < 2 { + return nil + } + a, b := call.Args[0], call.Args[1] + + if isZeroOrSignedZero(a) && isSignedNotZero(pass, b) { + return newUseNegativeDiagnostic(a.Pos(), b.End(), untype(b)) + } + + case "True": + if len(call.Args) < 1 { + return nil + } + expr := call.Args[0] + + a, _, ok1 := isStrictComparisonWith(pass, expr, isSignedNotZero, token.LSS, p(isZeroOrSignedZero)) // a < 0 + _, b, ok2 := isStrictComparisonWith(pass, expr, p(isZeroOrSignedZero), token.GTR, isSignedNotZero) // 0 > a + + survivingArg, ok := anyVal([]bool{ok1, ok2}, a, b) + if ok { + return newUseNegativeDiagnostic(expr.Pos(), expr.End(), untype(survivingArg)) + } + + case "False": + if len(call.Args) < 1 { + return nil + } + expr := call.Args[0] + + a, _, ok1 := isStrictComparisonWith(pass, expr, isSignedNotZero, token.GEQ, p(isZeroOrSignedZero)) // a >= 0 + _, b, ok2 := isStrictComparisonWith(pass, expr, p(isZeroOrSignedZero), token.LEQ, isSignedNotZero) // 0 <= a + + survivingArg, ok := anyVal([]bool{ok1, ok2}, a, b) + if ok { + return newUseNegativeDiagnostic(expr.Pos(), expr.End(), untype(survivingArg)) + } + } + return nil +} + +func (checker NegativePositive) checkPositive(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { + newUsePositiveDiagnostic := func(replaceStart, replaceEnd token.Pos, replaceWith ast.Expr) *analysis.Diagnostic { + const proposed = "Positive" + return newUseFunctionDiagnostic(checker.Name(), call, proposed, + newSuggestedFuncReplacement(call, proposed, analysis.TextEdit{ + Pos: replaceStart, + End: replaceEnd, + NewText: analysisutil.NodeBytes(pass.Fset, replaceWith), + }), + ) + } + + switch call.Fn.NameFTrimmed { + case "Greater": + if len(call.Args) < 2 { + return nil + } + a, b := call.Args[0], call.Args[1] + + if isNotAnyZero(a) && isAnyZero(b) { + return newUsePositiveDiagnostic(a.Pos(), b.End(), untype(a)) + } + + case "Less": + if len(call.Args) < 2 { + return nil + } + a, b := call.Args[0], call.Args[1] + + if isAnyZero(a) && isNotAnyZero(b) { + return newUsePositiveDiagnostic(a.Pos(), b.End(), untype(b)) + } + + case "True": + if len(call.Args) < 1 { + return nil + } + expr := call.Args[0] + + a, _, ok1 := isStrictComparisonWith(pass, expr, p(isNotAnyZero), token.GTR, p(isAnyZero)) // a > 0 + _, b, ok2 := isStrictComparisonWith(pass, expr, p(isAnyZero), token.LSS, p(isNotAnyZero)) // 0 < a + + survivingArg, ok := anyVal([]bool{ok1, ok2}, a, b) + if ok { + return newUsePositiveDiagnostic(expr.Pos(), expr.End(), untype(survivingArg)) + } + + case "False": + if len(call.Args) < 1 { + return nil + } + expr := call.Args[0] + + a, _, ok1 := isStrictComparisonWith(pass, expr, p(isNotAnyZero), token.LEQ, p(isAnyZero)) // a <= 0 + _, b, ok2 := isStrictComparisonWith(pass, expr, p(isAnyZero), token.GEQ, p(isNotAnyZero)) // 0 >= a + + survivingArg, ok := anyVal([]bool{ok1, ok2}, a, b) + if ok { + return newUsePositiveDiagnostic(expr.Pos(), expr.End(), untype(survivingArg)) + } + } + return nil +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/nil_compare.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/nil_compare.go new file mode 100644 index 000000000..47c4a7383 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/nil_compare.go @@ -0,0 +1,56 @@ +package checkers + +import ( + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +// NilCompare detects situations like +// +// assert.Equal(t, nil, value) +// assert.EqualValues(t, nil, value) +// assert.Exactly(t, nil, value) +// +// assert.NotEqual(t, nil, value) +// assert.NotEqualValues(t, nil, value) +// +// and requires +// +// assert.Nil(t, value) +// assert.NotNil(t, value) +type NilCompare struct{} + +// NewNilCompare constructs NilCompare checker. +func NewNilCompare() NilCompare { return NilCompare{} } +func (NilCompare) Name() string { return "nil-compare" } + +func (checker NilCompare) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { + if len(call.Args) < 2 { + return nil + } + + survivingArg, ok := xorNil(call.Args[0], call.Args[1]) + if !ok { + return nil + } + + var proposedFn string + + switch call.Fn.NameFTrimmed { + case "Equal", "EqualValues", "Exactly": + proposedFn = "Nil" + case "NotEqual", "NotEqualValues": + proposedFn = "NotNil" + default: + return nil + } + + return newUseFunctionDiagnostic(checker.Name(), call, proposedFn, + newSuggestedFuncReplacement(call, proposedFn, analysis.TextEdit{ + Pos: call.Args[0].Pos(), + End: call.Args[1].End(), + NewText: analysisutil.NodeBytes(pass.Fset, survivingArg), + }), + ) +} diff --git a/tools/vendor/github.com/golangci/maligned/LICENSE b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/LICENSE similarity index 96% rename from tools/vendor/github.com/golangci/maligned/LICENSE rename to tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/LICENSE index 744875676..6a66aea5e 100644 --- a/tools/vendor/github.com/golangci/maligned/LICENSE +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. +Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/doc.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/doc.go new file mode 100644 index 000000000..09cd23993 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/doc.go @@ -0,0 +1,6 @@ +// Package printf is a patched fork of +// https://github.com/golang/tools/blob/b6235391adb3b7f8bcfc4df81055e8f023de2688/go/analysis/passes/printf/printf.go#L538 +// +// Initial discussion: +// https://go-review.googlesource.com/c/tools/+/580555/comments/dfe3ef96_b1b815d5 +package printf diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/printf.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/printf.go new file mode 100644 index 000000000..cfb47b542 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/printf/printf.go @@ -0,0 +1,559 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package printf + +import ( + "bytes" + "fmt" + "go/ast" + "go/token" + "go/types" + "strconv" + "strings" + "unicode/utf8" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +// CheckPrintf checks a call to a formatted print routine such as Printf. +func CheckPrintf( + pass *analysis.Pass, + call *ast.CallExpr, + fnName string, + format string, + formatIdx int, +) { + firstArg := formatIdx + 1 // Arguments are immediately after format string. + if !strings.Contains(format, "%") { + if len(call.Args) > firstArg { + pass.Reportf(call.Lparen, "%s call has arguments but no formatting directives", fnName) + } + return + } + // Hard part: check formats against args. + argNum := firstArg + maxArgNum := firstArg + anyIndex := false + for i, w := 0, 0; i < len(format); i += w { + w = 1 + if format[i] != '%' { + continue + } + state := parsePrintfVerb(pass, call, fnName, format[i:], firstArg, argNum) + if state == nil { + return + } + w = len(state.format) + if !okPrintfArg(pass, call, state) { // One error per format is enough. + return + } + if state.hasIndex { + anyIndex = true + } + if state.verb == 'w' { + pass.Reportf(call.Pos(), "%s does not support error-wrapping directive %%w", state.name) + return + } + if len(state.argNums) > 0 { + // Continue with the next sequential argument. + argNum = state.argNums[len(state.argNums)-1] + 1 + } + for _, n := range state.argNums { + if n >= maxArgNum { + maxArgNum = n + 1 + } + } + } + // Dotdotdot is hard. + if call.Ellipsis.IsValid() && maxArgNum >= len(call.Args)-1 { + return + } + // If any formats are indexed, extra arguments are ignored. + if anyIndex { + return + } + // There should be no leftover arguments. + if maxArgNum != len(call.Args) { + expect := maxArgNum - firstArg + numArgs := len(call.Args) - firstArg + pass.ReportRangef(call, "%s call needs %v but has %v", fnName, count(expect, "arg"), count(numArgs, "arg")) + } +} + +// formatState holds the parsed representation of a printf directive such as "%3.*[4]d". +// It is constructed by parsePrintfVerb. +type formatState struct { + verb rune // the format verb: 'd' for "%d" + format string // the full format directive from % through verb, "%.3d". + name string // Printf, Sprintf etc. + flags []byte // the list of # + etc. + argNums []int // the successive argument numbers that are consumed, adjusted to refer to actual arg in call + firstArg int // Index of first argument after the format in the Printf call. + // Used only during parse. + pass *analysis.Pass + call *ast.CallExpr + argNum int // Which argument we're expecting to format now. + hasIndex bool // Whether the argument is indexed. + indexPending bool // Whether we have an indexed argument that has not resolved. + nbytes int // number of bytes of the format string consumed. +} + +// parseFlags accepts any printf flags. +func (s *formatState) parseFlags() { + for s.nbytes < len(s.format) { + switch c := s.format[s.nbytes]; c { + case '#', '0', '+', '-', ' ': + s.flags = append(s.flags, c) + s.nbytes++ + default: + return + } + } +} + +// scanNum advances through a decimal number if present. +func (s *formatState) scanNum() { + for ; s.nbytes < len(s.format); s.nbytes++ { + c := s.format[s.nbytes] + if c < '0' || '9' < c { + return + } + } +} + +// parseIndex scans an index expression. It returns false if there is a syntax error. +func (s *formatState) parseIndex() bool { + if s.nbytes == len(s.format) || s.format[s.nbytes] != '[' { + return true + } + // Argument index present. + s.nbytes++ // skip '[' + start := s.nbytes + s.scanNum() + ok := true + if s.nbytes == len(s.format) || s.nbytes == start || s.format[s.nbytes] != ']' { + ok = false // syntax error is either missing "]" or invalid index. + s.nbytes = strings.Index(s.format[start:], "]") + if s.nbytes < 0 { + s.pass.ReportRangef(s.call, "%s format %s is missing closing ]", s.name, s.format) + return false + } + s.nbytes += start + } + arg32, err := strconv.ParseInt(s.format[start:s.nbytes], 10, 32) + if err != nil || !ok || arg32 <= 0 || arg32 > int64(len(s.call.Args)-s.firstArg) { + s.pass.ReportRangef(s.call, "%s format has invalid argument index [%s]", s.name, s.format[start:s.nbytes]) + return false + } + s.nbytes++ // skip ']' + arg := int(arg32) + arg += s.firstArg - 1 // We want to zero-index the actual arguments. + s.argNum = arg + s.hasIndex = true + s.indexPending = true + return true +} + +// parseNum scans a width or precision (or *). It returns false if there's a bad index expression. +func (s *formatState) parseNum() bool { + if s.nbytes < len(s.format) && s.format[s.nbytes] == '*' { + if s.indexPending { // Absorb it. + s.indexPending = false + } + s.nbytes++ + s.argNums = append(s.argNums, s.argNum) + s.argNum++ + } else { + s.scanNum() + } + return true +} + +// parsePrecision scans for a precision. It returns false if there's a bad index expression. +func (s *formatState) parsePrecision() bool { + // If there's a period, there may be a precision. + if s.nbytes < len(s.format) && s.format[s.nbytes] == '.' { + s.flags = append(s.flags, '.') // Treat precision as a flag. + s.nbytes++ + if !s.parseIndex() { + return false + } + if !s.parseNum() { + return false + } + } + return true +} + +// isFormatter reports whether t could satisfy fmt.Formatter. +// The only interface method to look for is "Format(State, rune)". +func isFormatter(typ types.Type) bool { + // If the type is an interface, the value it holds might satisfy fmt.Formatter. + if _, ok := typ.Underlying().(*types.Interface); ok { + // Don't assume type parameters could be formatters. With the greater + // expressiveness of constraint interface syntax we expect more type safety + // when using type parameters. + if !isTypeParam(typ) { + return true + } + } + obj, _, _ := types.LookupFieldOrMethod(typ, false, nil, "Format") + fn, ok := obj.(*types.Func) + if !ok { + return false + } + sig := fn.Type().(*types.Signature) + return sig.Params().Len() == 2 && + sig.Results().Len() == 0 && + isNamedType(sig.Params().At(0).Type(), "fmt", "State") && + types.Identical(sig.Params().At(1).Type(), types.Typ[types.Rune]) +} + +// isTypeParam reports whether t is a type parameter. +func isTypeParam(t types.Type) bool { + _, ok := t.(*types.TypeParam) + return ok +} + +// isNamedType reports whether t is the named type with the given package path +// and one of the given names. +// This function avoids allocating the concatenation of "pkg.Name", +// which is important for the performance of syntax matching. +func isNamedType(t types.Type, pkgPath string, names ...string) bool { + n, ok := t.(*types.Named) + if !ok { + return false + } + obj := n.Obj() + if obj == nil || obj.Pkg() == nil || obj.Pkg().Path() != pkgPath { + return false + } + name := obj.Name() + for _, n := range names { + if name == n { + return true + } + } + return false +} + +// parsePrintfVerb looks the formatting directive that begins the format string +// and returns a formatState that encodes what the directive wants, without looking +// at the actual arguments present in the call. The result is nil if there is an error. +func parsePrintfVerb(pass *analysis.Pass, call *ast.CallExpr, name, format string, firstArg, argNum int) *formatState { + state := &formatState{ + format: format, + name: name, + flags: make([]byte, 0, 5), + argNum: argNum, + argNums: make([]int, 0, 1), + nbytes: 1, // There's guaranteed to be a percent sign. + firstArg: firstArg, + pass: pass, + call: call, + } + // There may be flags. + state.parseFlags() + // There may be an index. + if !state.parseIndex() { + return nil + } + // There may be a width. + if !state.parseNum() { + return nil + } + // There may be a precision. + if !state.parsePrecision() { + return nil + } + // Now a verb, possibly prefixed by an index (which we may already have). + if !state.indexPending && !state.parseIndex() { + return nil + } + if state.nbytes == len(state.format) { + pass.ReportRangef(call.Fun, "%s format %s is missing verb at end of string", name, state.format) + return nil + } + verb, w := utf8.DecodeRuneInString(state.format[state.nbytes:]) + state.verb = verb + state.nbytes += w + if verb != '%' { + state.argNums = append(state.argNums, state.argNum) + } + state.format = state.format[:state.nbytes] + return state +} + +// printfArgType encodes the types of expressions a printf verb accepts. It is a bitmask. +type printfArgType int + +const ( + argBool printfArgType = 1 << iota + argInt + argRune + argString + argFloat + argComplex + argPointer + argError + anyType printfArgType = ^0 +) + +type printVerb struct { + verb rune // User may provide verb through Formatter; could be a rune. + flags string // known flags are all ASCII + typ printfArgType +} + +// Common flag sets for printf verbs. +const ( + noFlag = "" + numFlag = " -+.0" + sharpNumFlag = " -+.0#" + allFlags = " -+.0#" +) + +// printVerbs identifies which flags are known to printf for each verb. +var printVerbs = []printVerb{ + // '-' is a width modifier, always valid. + // '.' is a precision for float, max width for strings. + // '+' is required sign for numbers, Go format for %v. + // '#' is alternate format for several verbs. + // ' ' is spacer for numbers + {'%', noFlag, 0}, + {'b', sharpNumFlag, argInt | argFloat | argComplex | argPointer}, + {'c', "-", argRune | argInt}, + {'d', numFlag, argInt | argPointer}, + {'e', sharpNumFlag, argFloat | argComplex}, + {'E', sharpNumFlag, argFloat | argComplex}, + {'f', sharpNumFlag, argFloat | argComplex}, + {'F', sharpNumFlag, argFloat | argComplex}, + {'g', sharpNumFlag, argFloat | argComplex}, + {'G', sharpNumFlag, argFloat | argComplex}, + {'o', sharpNumFlag, argInt | argPointer}, + {'O', sharpNumFlag, argInt | argPointer}, + {'p', "-#", argPointer}, + {'q', " -+.0#", argRune | argInt | argString}, + {'s', " -+.0", argString}, + {'t', "-", argBool}, + {'T', "-", anyType}, + {'U', "-#", argRune | argInt}, + {'v', allFlags, anyType}, + {'w', allFlags, argError}, + {'x', sharpNumFlag, argRune | argInt | argString | argPointer | argFloat | argComplex}, + {'X', sharpNumFlag, argRune | argInt | argString | argPointer | argFloat | argComplex}, +} + +// okPrintfArg compares the formatState to the arguments actually present, +// reporting any discrepancies it can discern. If the final argument is ellipsissed, +// there's little it can do for that. +func okPrintfArg(pass *analysis.Pass, call *ast.CallExpr, state *formatState) (ok bool) { + var v printVerb + found := false + // Linear scan is fast enough for a small list. + for _, v = range printVerbs { + if v.verb == state.verb { + found = true + break + } + } + + // Could current arg implement fmt.Formatter? + // Skip check for the %w verb, which requires an error. + formatter := false + if v.typ != argError && state.argNum < len(call.Args) { + if tv, ok := pass.TypesInfo.Types[call.Args[state.argNum]]; ok { + formatter = isFormatter(tv.Type) + } + } + + if !formatter { + if !found { + pass.ReportRangef(call, "%s format %s has unknown verb %c", state.name, state.format, state.verb) + return false + } + for _, flag := range state.flags { + // TODO: Disable complaint about '0' for Go 1.10. To be fixed properly in 1.11. + // See issues 23598 and 23605. + if flag == '0' { + continue + } + if !strings.ContainsRune(v.flags, rune(flag)) { + pass.ReportRangef(call, "%s format %s has unrecognized flag %c", state.name, state.format, flag) + return false + } + } + } + // Verb is good. If len(state.argNums)>trueArgs, we have something like %.*s and all + // but the final arg must be an integer. + trueArgs := 1 + if state.verb == '%' { + trueArgs = 0 + } + nargs := len(state.argNums) + for i := 0; i < nargs-trueArgs; i++ { + if !argCanBeChecked(pass, call, i, state) { + return + } + // NOTE(a.telyshev): `matchArgType` leads to a lot of "golang.org/x/tools/internal" code. + /* + argNum := state.argNums[i] + arg := call.Args[argNum] + + if reason, ok := matchArgType(pass, argInt, arg); !ok { + details := "" + if reason != "" { + details = " (" + reason + ")" + } + pass.ReportRangef(call, "%s format %s uses non-int %s%s as argument of *", state.name, state.format, analysisutil.Format(pass.Fset, arg), details) + return false + } + */ + } + + if state.verb == '%' || formatter { + return true + } + argNum := state.argNums[len(state.argNums)-1] + if !argCanBeChecked(pass, call, len(state.argNums)-1, state) { + return false + } + arg := call.Args[argNum] + if isFunctionValue(pass, arg) && state.verb != 'p' && state.verb != 'T' { + pass.ReportRangef(call, "%s format %s arg %s is a func value, not called", state.name, state.format, analysisutil.NodeString(pass.Fset, arg)) + return false + } + // NOTE(a.telyshev): `matchArgType` leads to a lot of "golang.org/x/tools/internal" code. + /* + if reason, ok := matchArgType(pass, v.typ, arg); !ok { + typeString := "" + if typ := pass.TypesInfo.Types[arg].Type; typ != nil { + typeString = typ.String() + } + details := "" + if reason != "" { + details = " (" + reason + ")" + } + pass.ReportRangef(call, "%s format %s has arg %s of wrong type %s%s", state.name, state.format, analysisutil.Format(pass.Fset, arg), typeString, details) + return false + } + */ + if v.typ&argString != 0 && v.verb != 'T' && !bytes.Contains(state.flags, []byte{'#'}) { + if methodName, ok := recursiveStringer(pass, arg); ok { + pass.ReportRangef(call, "%s format %s with arg %s causes recursive %s method call", state.name, state.format, analysisutil.NodeString(pass.Fset, arg), methodName) + return false + } + } + return true +} + +// recursiveStringer reports whether the argument e is a potential +// recursive call to stringer or is an error, such as t and &t in these examples: +// +// func (t *T) String() string { printf("%s", t) } +// func (t T) Error() string { printf("%s", t) } +// func (t T) String() string { printf("%s", &t) } +func recursiveStringer(pass *analysis.Pass, e ast.Expr) (string, bool) { + typ := pass.TypesInfo.Types[e].Type + + // It's unlikely to be a recursive stringer if it has a Format method. + if isFormatter(typ) { + return "", false + } + + // Does e allow e.String() or e.Error()? + strObj, _, _ := types.LookupFieldOrMethod(typ, false, pass.Pkg, "String") + strMethod, strOk := strObj.(*types.Func) + errObj, _, _ := types.LookupFieldOrMethod(typ, false, pass.Pkg, "Error") + errMethod, errOk := errObj.(*types.Func) + if !strOk && !errOk { + return "", false + } + + // inScope returns true if e is in the scope of f. + inScope := func(e ast.Expr, f *types.Func) bool { + return f.Scope() != nil && f.Scope().Contains(e.Pos()) + } + + // Is the expression e within the body of that String or Error method? + var method *types.Func + if strOk && strMethod.Pkg() == pass.Pkg && inScope(e, strMethod) { + method = strMethod + } else if errOk && errMethod.Pkg() == pass.Pkg && inScope(e, errMethod) { + method = errMethod + } else { + return "", false + } + + sig := method.Type().(*types.Signature) + if !isStringer(sig) { + return "", false + } + + // Is it the receiver r, or &r? + if u, ok := e.(*ast.UnaryExpr); ok && u.Op == token.AND { + e = u.X // strip off & from &r + } + if id, ok := e.(*ast.Ident); ok { + if pass.TypesInfo.Uses[id] == sig.Recv() { + return method.FullName(), true + } + } + return "", false +} + +// isStringer reports whether the method signature matches the String() definition in fmt.Stringer. +func isStringer(sig *types.Signature) bool { + return sig.Params().Len() == 0 && + sig.Results().Len() == 1 && + sig.Results().At(0).Type() == types.Typ[types.String] +} + +// isFunctionValue reports whether the expression is a function as opposed to a function call. +// It is almost always a mistake to print a function value. +func isFunctionValue(pass *analysis.Pass, e ast.Expr) bool { + if typ := pass.TypesInfo.Types[e].Type; typ != nil { + // Don't call Underlying: a named func type with a String method is ok. + // TODO(adonovan): it would be more precise to check isStringer. + _, ok := typ.(*types.Signature) + return ok + } + return false +} + +// argCanBeChecked reports whether the specified argument is statically present; +// it may be beyond the list of arguments or in a terminal slice... argument, which +// means we can't see it. +func argCanBeChecked(pass *analysis.Pass, call *ast.CallExpr, formatArg int, state *formatState) bool { + argNum := state.argNums[formatArg] + if argNum <= 0 { + return false + } + if argNum < len(call.Args)-1 { + return true // Always OK. + } + if call.Ellipsis.IsValid() { + return false // We just can't tell; there could be many more arguments. + } + if argNum < len(call.Args) { + return true + } + // There are bad indexes in the format or there are fewer arguments than the format needs. + // This is the argument number relative to the format: Printf("%s", "hi") will give 1 for the "hi". + arg := argNum - state.firstArg + 1 // People think of arguments as 1-indexed. + pass.ReportRangef(call, "%s format %s reads arg #%d, but call has %v", state.name, state.format, arg, count(len(call.Args)-state.firstArg, "arg")) + return false +} + +// count(n, what) returns "1 what" or "N whats" +// (assuming the plural of what is whats). +func count(n int, what string) string { + if n == 1 { + return "1 " + what + } + return fmt.Sprintf("%d %ss", n, what) +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/require_error.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/require_error.go index 2da71ed81..4303828fd 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/require_error.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/require_error.go @@ -1,35 +1,250 @@ package checkers -import "golang.org/x/tools/go/analysis" +import ( + "go/ast" + "regexp" -// RequireError detects situations like + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ast/inspector" +) + +const requireErrorReport = "for error assertions use require" + +// RequireError detects error assertions like // +// assert.Error(t, err) // s.Error(err), s.Assert().Error(err) +// assert.ErrorIs(t, err, io.EOF) +// assert.ErrorAs(t, err, &target) +// assert.EqualError(t, err, "end of file") +// assert.ErrorContains(t, err, "end of file") // assert.NoError(t, err) -// s.ErrorIs(err, io.EOF) -// s.Assert().Error(err) +// assert.NotErrorIs(t, err, io.EOF) // // and requires // -// require.NoError(t, err) -// s.Require().ErrorIs(err, io.EOF) -// s.Require().Error(err) -type RequireError struct{} +// require.Error(t, err) // s.Require().Error(err), s.Require().Error(err) +// require.ErrorIs(t, err, io.EOF) +// require.ErrorAs(t, err, &target) +// ... +// +// RequireError ignores: +// - assertions in the `if` condition; +// - assertions in the bool expression; +// - the entire `if-else[-if]` block, if there is an assertion in any `if` condition; +// - the last assertion in the block, if there are no methods/functions calls after it; +// - assertions in an explicit goroutine (including `http.Handler`); +// - assertions in an explicit testing cleanup function or suite teardown methods; +// - sequence of NoError assertions. +type RequireError struct { + fnPattern *regexp.Regexp +} // NewRequireError constructs RequireError checker. -func NewRequireError() RequireError { return RequireError{} } -func (RequireError) Name() string { return "require-error" } +func NewRequireError() *RequireError { return new(RequireError) } +func (RequireError) Name() string { return "require-error" } + +func (checker *RequireError) SetFnPattern(p *regexp.Regexp) *RequireError { + if p != nil { + checker.fnPattern = p + } + return checker +} + +func (checker RequireError) Check(pass *analysis.Pass, inspector *inspector.Inspector) []analysis.Diagnostic { + callsByFunc := make(map[funcID][]*callMeta) + + // Stage 1. Collect meta information about any calls inside functions. + + inspector.WithStack([]ast.Node{(*ast.CallExpr)(nil)}, func(node ast.Node, push bool, stack []ast.Node) bool { + if !push { + return false + } + if len(stack) < 3 { + return true + } + + fID := findSurroundingFunc(pass, stack) + if fID == nil { + return true + } + + _, prevIsIfStmt := stack[len(stack)-2].(*ast.IfStmt) + _, prevIsAssignStmt := stack[len(stack)-2].(*ast.AssignStmt) + _, prevPrevIsIfStmt := stack[len(stack)-3].(*ast.IfStmt) + inIfCond := prevIsIfStmt || (prevPrevIsIfStmt && prevIsAssignStmt) -func (checker RequireError) Check(_ *analysis.Pass, call *CallMeta) *analysis.Diagnostic { - if !call.IsAssert { - return nil + _, inBoolExpr := stack[len(stack)-2].(*ast.BinaryExpr) + + callExpr := node.(*ast.CallExpr) + testifyCall := NewCallMeta(pass, callExpr) + + call := &callMeta{ + call: callExpr, + testifyCall: testifyCall, + rootIf: findRootIf(stack), + parentIf: findNearestNode[*ast.IfStmt](stack), + parentBlock: findNearestNode[*ast.BlockStmt](stack), + inIfCond: inIfCond, + inBoolExpr: inBoolExpr, + inNoErrorSeq: false, // Will be filled in below. + } + + callsByFunc[*fID] = append(callsByFunc[*fID], call) + return testifyCall == nil // Do not support asserts in asserts. + }) + + // Stage 2. Analyze calls and block context. + + var diagnostics []analysis.Diagnostic + + callsByBlock := map[*ast.BlockStmt][]*callMeta{} + for _, calls := range callsByFunc { + for _, c := range calls { + if b := c.parentBlock; b != nil { + callsByBlock[b] = append(callsByBlock[b], c) + } + } } - const msg = "for error assertions use require" + markCallsInNoErrorSequence(callsByBlock) - switch call.Fn.Name { - case "Error", "ErrorIs", "ErrorAs", "EqualError", "ErrorContains", "NoError", "NotErrorIs", - "Errorf", "ErrorIsf", "ErrorAsf", "EqualErrorf", "ErrorContainsf", "NoErrorf", "NotErrorIsf": - return newDiagnostic(checker.Name(), call, msg, nil) + for funcInfo, calls := range callsByFunc { + for i, c := range calls { + if m := funcInfo.meta; m.isTestCleanup || m.isGoroutine || m.isHTTPHandler { + continue + } + + if c.testifyCall == nil { + continue + } + if !c.testifyCall.IsAssert { + continue + } + switch c.testifyCall.Fn.NameFTrimmed { + default: + continue + case "Error", "ErrorIs", "ErrorAs", "EqualError", "ErrorContains", "NoError", "NotErrorIs": + } + + if needToSkipBasedOnContext(c, i, calls, callsByBlock) { + continue + } + if p := checker.fnPattern; p != nil && !p.MatchString(c.testifyCall.Fn.Name) { + continue + } + + diagnostics = append(diagnostics, + *newDiagnostic(checker.Name(), c.testifyCall, requireErrorReport, nil)) + } } - return nil + + return diagnostics +} + +func needToSkipBasedOnContext( + currCall *callMeta, + currCallIndex int, + otherCalls []*callMeta, + callsByBlock map[*ast.BlockStmt][]*callMeta, +) bool { + if currCall.inIfCond || currCall.inBoolExpr || currCall.inNoErrorSeq { + return true + } + + if currCall.rootIf != nil { + for _, rootCall := range otherCalls { + if (rootCall.rootIf == currCall.rootIf) && rootCall.inIfCond { + // Skip assertions in the entire if-else[-if] block, if some of "if condition" contains assertion. + return true + } + } + } + + block := currCall.parentBlock + blockCalls := callsByBlock[block] + isLastCallInBlock := blockCalls[len(blockCalls)-1] == currCall + + noCallsAfter := true + + _, blockEndWithReturn := block.List[len(block.List)-1].(*ast.ReturnStmt) + if !blockEndWithReturn { + for i := currCallIndex + 1; i < len(otherCalls); i++ { + nextCall := otherCalls[i] + nextCallInElseBlock := false + + if pIf := currCall.parentIf; pIf != nil && pIf.Else != nil { + ast.Inspect(pIf.Else, func(n ast.Node) bool { + if n == nextCall.call { + nextCallInElseBlock = true + return false + } + return true + }) + } + + if !nextCallInElseBlock { + noCallsAfter = false + break + } + } + } + + // Skip assertion if this is the last operation in the test. + return isLastCallInBlock && noCallsAfter +} + +func findRootIf(stack []ast.Node) *ast.IfStmt { + nearestIf, i := findNearestNodeWithIdx[*ast.IfStmt](stack) + for ; i > 0; i-- { + parent, ok := stack[i-1].(*ast.IfStmt) + if ok { + nearestIf = parent + } else { + break + } + } + return nearestIf +} + +func markCallsInNoErrorSequence(callsByBlock map[*ast.BlockStmt][]*callMeta) { + for _, calls := range callsByBlock { + for i, c := range calls { + if c.testifyCall == nil { + continue + } + + var prevIsNoError bool + if i > 0 { + if prev := calls[i-1].testifyCall; prev != nil { + prevIsNoError = isNoErrorAssertion(prev.Fn.Name) + } + } + + var nextIsNoError bool + if i < len(calls)-1 { + if next := calls[i+1].testifyCall; next != nil { + nextIsNoError = isNoErrorAssertion(next.Fn.Name) + } + } + + if isNoErrorAssertion(c.testifyCall.Fn.Name) && (prevIsNoError || nextIsNoError) { + calls[i].inNoErrorSeq = true + } + } + } +} + +type callMeta struct { + call *ast.CallExpr + testifyCall *CallMeta + rootIf *ast.IfStmt // The root `if` in if-else[-if] chain. + parentIf *ast.IfStmt // The nearest `if`, can be equal with rootIf. + parentBlock *ast.BlockStmt + inIfCond bool // True for code like `if assert.ErrorAs(t, err, &target) {`. + inBoolExpr bool // True for code like `assert.Error(t, err) && assert.ErrorContains(t, err, "value")` + inNoErrorSeq bool // True for sequence of `assert.NoError` assertions. +} + +func isNoErrorAssertion(fnName string) bool { + return (fnName == "NoError") || (fnName == "NoErrorf") } diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_broken_parallel.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_broken_parallel.go new file mode 100644 index 000000000..f830fd2a5 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_broken_parallel.go @@ -0,0 +1,89 @@ +package checkers + +import ( + "fmt" + "go/ast" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ast/inspector" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +// SuiteBrokenParallel detects unsupported t.Parallel() call in suite tests +// +// func (s *MySuite) SetupTest() { +// s.T().Parallel() +// } +// +// // And other hooks... +// +// func (s *MySuite) TestSomething() { +// s.T().Parallel() +// +// for _, tt := range cases { +// s.Run(tt.name, func() { +// s.T().Parallel() +// }) +// +// s.T().Run(tt.name, func(t *testing.T) { +// t.Parallel() +// }) +// } +// } +type SuiteBrokenParallel struct{} + +// NewSuiteBrokenParallel constructs SuiteBrokenParallel checker. +func NewSuiteBrokenParallel() SuiteBrokenParallel { return SuiteBrokenParallel{} } +func (SuiteBrokenParallel) Name() string { return "suite-broken-parallel" } + +func (checker SuiteBrokenParallel) Check(pass *analysis.Pass, insp *inspector.Inspector) (diagnostics []analysis.Diagnostic) { + const report = "testify v1 does not support suite's parallel tests and subtests" + + insp.WithStack([]ast.Node{(*ast.CallExpr)(nil)}, func(node ast.Node, push bool, stack []ast.Node) bool { + if !push { + return false + } + ce := node.(*ast.CallExpr) + + se, ok := ce.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + if !isIdentWithName("Parallel", se.Sel) { + return true + } + if !implementsTestingT(pass, se.X) { + return true + } + + for i := len(stack) - 2; i >= 0; i-- { + fd, ok := stack[i].(*ast.FuncDecl) + if !ok { + continue + } + + if !isSuiteMethod(pass, fd) { + continue + } + + nextLine := pass.Fset.Position(ce.Pos()).Line + 1 + d := newDiagnostic(checker.Name(), ce, report, &analysis.SuggestedFix{ + Message: fmt.Sprintf("Remove `%s` call", analysisutil.NodeString(pass.Fset, ce)), + TextEdits: []analysis.TextEdit{ + { + Pos: ce.Pos(), + End: pass.Fset.File(ce.Pos()).LineStart(nextLine), + NewText: []byte(""), + }, + }, + }) + + diagnostics = append(diagnostics, *d) + return false + } + + return true + }) + return diagnostics +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_dont_use_pkg.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_dont_use_pkg.go index bf84f6378..6150ae78d 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_dont_use_pkg.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_dont_use_pkg.go @@ -3,15 +3,11 @@ package checkers import ( "fmt" "go/ast" - "go/types" "golang.org/x/tools/go/analysis" - - "github.com/Antonboom/testifylint/internal/analysisutil" - "github.com/Antonboom/testifylint/internal/testify" ) -// SuiteDontUsePkg detects situation like +// SuiteDontUsePkg detects situations like // // func (s *MySuite) TestSomething() { // assert.Equal(s.T(), 42, value) @@ -47,7 +43,7 @@ func (checker SuiteDontUsePkg) Check(pass *analysis.Pass, call *CallMeta) *analy if !ok { return nil } - if se.X == nil || !implementsTestifySuiteIface(pass, se.X) { + if se.X == nil || !implementsTestifySuite(pass, se.X) { return nil } if se.Sel == nil || se.Sel.Name != "T" { @@ -82,15 +78,3 @@ func (checker SuiteDontUsePkg) Check(pass *analysis.Pass, call *CallMeta) *analy }, }) } - -func implementsTestifySuiteIface(pass *analysis.Pass, rcv ast.Expr) bool { - suiteIface := analysisutil.ObjectOf(pass.Pkg, testify.SuitePkgPath, "TestingSuite") - if suiteIface == nil { - return false - } - - return types.Implements( - pass.TypesInfo.TypeOf(rcv), - suiteIface.Type().Underlying().(*types.Interface), - ) -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_extra_assert_call.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_extra_assert_call.go index 791488b65..9adfe5190 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_extra_assert_call.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_extra_assert_call.go @@ -19,7 +19,7 @@ const ( const DefaultSuiteExtraAssertCallMode = SuiteExtraAssertCallModeRemove -// SuiteExtraAssertCall detects situation like +// SuiteExtraAssertCall detects situations like // // func (s *MySuite) TestSomething() { // s.Assert().Equal(42, value) @@ -56,7 +56,7 @@ func (checker SuiteExtraAssertCall) Check(pass *analysis.Pass, call *CallMeta) * switch checker.mode { case SuiteExtraAssertCallModeRequire: x, ok := call.Selector.X.(*ast.Ident) // s.True - if !ok || x == nil || !implementsTestifySuiteIface(pass, x) { + if !ok || x == nil || !implementsTestifySuite(pass, x) { return nil } @@ -77,7 +77,7 @@ func (checker SuiteExtraAssertCall) Check(pass *analysis.Pass, call *CallMeta) * } se, ok := x.Fun.(*ast.SelectorExpr) - if !ok || se == nil || !implementsTestifySuiteIface(pass, se.X) { + if !ok || se == nil || !implementsTestifySuite(pass, se.X) { return nil } if se.Sel == nil || se.Sel.Name != "Assert" { diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_subtest_run.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_subtest_run.go new file mode 100644 index 000000000..67d9c252b --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_subtest_run.go @@ -0,0 +1,60 @@ +package checkers + +import ( + "fmt" + "go/ast" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ast/inspector" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +// SuiteSubtestRun detects situations like +// +// s.T().Run("subtest", func(t *testing.T) { +// assert.Equal(t, 42, result) +// }) +// +// and requires +// +// s.Run("subtest", func() { +// s.Equal(42, result) +// }) +type SuiteSubtestRun struct{} + +// NewSuiteSubtestRun constructs SuiteSubtestRun checker. +func NewSuiteSubtestRun() SuiteSubtestRun { return SuiteSubtestRun{} } +func (SuiteSubtestRun) Name() string { return "suite-subtest-run" } + +func (checker SuiteSubtestRun) Check(pass *analysis.Pass, insp *inspector.Inspector) (diagnostics []analysis.Diagnostic) { + insp.Preorder([]ast.Node{(*ast.CallExpr)(nil)}, func(node ast.Node) { + ce := node.(*ast.CallExpr) // s.T().Run + + se, ok := ce.Fun.(*ast.SelectorExpr) // s.T() + .Run + if !ok { + return + } + if !isIdentWithName("Run", se.Sel) { + return + } + + tCall, ok := se.X.(*ast.CallExpr) // s.T() + if !ok { + return + } + tCallSel, ok := tCall.Fun.(*ast.SelectorExpr) // s + .T() + if !ok { + return + } + if !isIdentWithName("T", tCallSel.Sel) { + return + } + + if implementsTestifySuite(pass, tCallSel.X) && implementsTestingT(pass, tCall) { + msg := fmt.Sprintf("use %s.Run to run subtest", analysisutil.NodeString(pass.Fset, tCallSel.X)) + diagnostics = append(diagnostics, *newDiagnostic(checker.Name(), ce, msg, nil)) + } + }) + return diagnostics +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_thelper.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_thelper.go index 5cadc93ad..59455290d 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_thelper.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/suite_thelper.go @@ -3,13 +3,11 @@ package checkers import ( "fmt" "go/ast" - "strings" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/ast/inspector" "github.com/Antonboom/testifylint/internal/analysisutil" - "github.com/Antonboom/testifylint/internal/testify" ) // SuiteTHelper requires t.Helper() call in suite helpers: @@ -27,15 +25,15 @@ func (SuiteTHelper) Name() string { return "suite-thelper" } func (checker SuiteTHelper) Check(pass *analysis.Pass, inspector *inspector.Inspector) (diagnostics []analysis.Diagnostic) { inspector.Preorder([]ast.Node{(*ast.FuncDecl)(nil)}, func(node ast.Node) { fd := node.(*ast.FuncDecl) - if !isTestifySuiteMethod(pass, fd) { + if !isSuiteMethod(pass, fd) { return } - if ident := fd.Name; ident == nil || isTestMethod(ident.Name) || isServiceMethod(ident.Name) { + if ident := fd.Name; ident == nil || isSuiteTestMethod(ident.Name) || isSuiteServiceMethod(ident.Name) { return } - if !containsSuiteAssertions(pass, fd) { + if !fnContainsAssertions(pass, fd) { return } @@ -67,64 +65,3 @@ func (checker SuiteTHelper) Check(pass *analysis.Pass, inspector *inspector.Insp }) return diagnostics } - -func isTestifySuiteMethod(pass *analysis.Pass, fDecl *ast.FuncDecl) bool { - if fDecl.Recv == nil || len(fDecl.Recv.List) != 1 { - return false - } - - rcv := fDecl.Recv.List[0] - return implementsTestifySuiteIface(pass, rcv.Type) -} - -func isTestMethod(name string) bool { - return strings.HasPrefix(name, "Test") -} - -func isServiceMethod(name string) bool { - // https://github.com/stretchr/testify/blob/master/suite/interfaces.go - switch name { - case "T", "SetT", "SetS", "SetupSuite", "SetupTest", "TearDownSuite", "TearDownTest", - "BeforeTest", "AfterTest", "HandleStats", "SetupSubTest", "TearDownSubTest": - return true - } - return false -} - -func containsSuiteAssertions(pass *analysis.Pass, fn *ast.FuncDecl) bool { - if fn.Body == nil { - return false - } - - for _, s := range fn.Body.List { - if isSuiteAssertion(pass, s) { - return true - } - } - return false -} - -func isSuiteAssertion(pass *analysis.Pass, stmt ast.Stmt) bool { - expr, ok := stmt.(*ast.ExprStmt) - if !ok { - return false - } - - ce, ok := expr.X.(*ast.CallExpr) - if !ok { - return false - } - - se, ok := ce.Fun.(*ast.SelectorExpr) - if !ok || se.Sel == nil { - return false - } - - if sel, ok := pass.TypesInfo.Selections[se]; ok { - pkg := sel.Obj().Pkg() - isAssert := analysisutil.IsPkg(pkg, testify.AssertPkgName, testify.AssertPkgPath) - isRequire := analysisutil.IsPkg(pkg, testify.RequirePkgName, testify.RequirePkgPath) - return isAssert || isRequire - } - return false -} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/useless_assert.go b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/useless_assert.go new file mode 100644 index 000000000..6f206d095 --- /dev/null +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/checkers/useless_assert.go @@ -0,0 +1,88 @@ +package checkers + +import ( + "go/ast" + + "golang.org/x/tools/go/analysis" + + "github.com/Antonboom/testifylint/internal/analysisutil" +) + +// UselessAssert detects useless asserts like +// +// 1) Asserting of the same variable +// +// assert.Equal(t, tt.value, tt.value) +// assert.ElementsMatch(t, users, users) +// ... +// assert.True(t, num > num) +// assert.False(t, num == num) +// +// 2) Open for contribution... +type UselessAssert struct{} + +// NewUselessAssert constructs UselessAssert checker. +func NewUselessAssert() UselessAssert { return UselessAssert{} } +func (UselessAssert) Name() string { return "useless-assert" } + +func (checker UselessAssert) Check(pass *analysis.Pass, call *CallMeta) *analysis.Diagnostic { + var first, second ast.Node + + switch call.Fn.NameFTrimmed { + case + "Contains", + "ElementsMatch", + "Equal", + "EqualExportedValues", + "EqualValues", + "ErrorAs", + "ErrorIs", + "Exactly", + "Greater", + "GreaterOrEqual", + "Implements", + "InDelta", + "InDeltaMapValues", + "InDeltaSlice", + "InEpsilon", + "InEpsilonSlice", + "IsType", + "JSONEq", + "Less", + "LessOrEqual", + "NotEqual", + "NotEqualValues", + "NotErrorIs", + "NotRegexp", + "NotSame", + "NotSubset", + "Regexp", + "Same", + "Subset", + "WithinDuration", + "YAMLEq": + if len(call.Args) < 2 { + return nil + } + first, second = call.Args[0], call.Args[1] + + case "True", "False": + if len(call.Args) < 1 { + return nil + } + + be, ok := call.Args[0].(*ast.BinaryExpr) + if !ok { + return nil + } + first, second = be.X, be.Y + + default: + return nil + } + + if analysisutil.NodeString(pass.Fset, first) == analysisutil.NodeString(pass.Fset, second) { + return newDiagnostic(checker.Name(), call, "asserting of the same variable", nil) + } + return nil +} diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/config/config.go b/tools/vendor/github.com/Antonboom/testifylint/internal/config/config.go index 51f627008..a8812e6d0 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/config/config.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/config/config.go @@ -1,7 +1,9 @@ package config import ( + "errors" "flag" + "fmt" "github.com/Antonboom/testifylint/internal/checkers" ) @@ -9,11 +11,26 @@ import ( // NewDefault builds default testifylint config. func NewDefault() Config { return Config{ - EnableAll: false, - EnabledCheckers: checkers.EnabledByDefault(), + EnableAll: false, + DisabledCheckers: nil, + DisableAll: false, + EnabledCheckers: nil, + BoolCompare: BoolCompareConfig{ + IgnoreCustomTypes: false, + }, ExpectedActual: ExpectedActualConfig{ ExpVarPattern: RegexpValue{checkers.DefaultExpectedVarPattern}, }, + Formatter: FormatterConfig{ + CheckFormatString: true, + RequireFFuncs: false, + }, + GoRequire: GoRequireConfig{ + IgnoreHTTPHandlers: false, + }, + RequireError: RequireErrorConfig{ + FnPattern: RegexpValue{nil}, + }, SuiteExtraAssertCall: SuiteExtraAssertCallConfig{ Mode: checkers.DefaultSuiteExtraAssertCallMode, }, @@ -22,29 +39,113 @@ func NewDefault() Config { // Config implements testifylint configuration. type Config struct { - EnableAll bool - EnabledCheckers KnownCheckersValue + EnableAll bool + DisabledCheckers KnownCheckersValue + DisableAll bool + EnabledCheckers KnownCheckersValue + + BoolCompare BoolCompareConfig ExpectedActual ExpectedActualConfig + Formatter FormatterConfig + GoRequire GoRequireConfig + RequireError RequireErrorConfig SuiteExtraAssertCall SuiteExtraAssertCallConfig } +// BoolCompareConfig implements configuration of checkers.BoolCompare. +type BoolCompareConfig struct { + IgnoreCustomTypes bool +} + // ExpectedActualConfig implements configuration of checkers.ExpectedActual. type ExpectedActualConfig struct { ExpVarPattern RegexpValue } +// FormatterConfig implements configuration of checkers.Formatter. +type FormatterConfig struct { + CheckFormatString bool + RequireFFuncs bool +} + +// GoRequireConfig implements configuration of checkers.GoRequire. +type GoRequireConfig struct { + IgnoreHTTPHandlers bool +} + +// RequireErrorConfig implements configuration of checkers.RequireError. +type RequireErrorConfig struct { + FnPattern RegexpValue +} + // SuiteExtraAssertCallConfig implements configuration of checkers.SuiteExtraAssertCall. type SuiteExtraAssertCallConfig struct { Mode checkers.SuiteExtraAssertCallMode } +func (cfg Config) Validate() error { + if cfg.EnableAll { + if cfg.DisableAll { + return errors.New("enable-all and disable-all options must not be combined") + } + + if len(cfg.EnabledCheckers) != 0 { + return errors.New("enable-all and enable options must not be combined") + } + } + + if cfg.DisableAll { + if len(cfg.DisabledCheckers) != 0 { + return errors.New("disable-all and disable options must not be combined") + } + + if len(cfg.EnabledCheckers) == 0 { + return errors.New("all checkers were disabled, but no one checker was enabled: at least one must be enabled") + } + } + + for _, checker := range cfg.DisabledCheckers { + if cfg.EnabledCheckers.Contains(checker) { + return fmt.Errorf("checker %q disabled and enabled at one moment", checker) + } + } + + return nil +} + // BindToFlags binds Config fields to according flags. func BindToFlags(cfg *Config, fs *flag.FlagSet) { fs.BoolVar(&cfg.EnableAll, "enable-all", false, "enable all checkers") - fs.Var(&cfg.EnabledCheckers, "enable", "comma separated list of enabled checkers") - fs.Var(&cfg.ExpectedActual.ExpVarPattern, "expected-actual.pattern", "regexp for expected variable name") + fs.Var(&cfg.DisabledCheckers, "disable", "comma separated list of disabled checkers (to exclude from enabled by default)") + fs.BoolVar(&cfg.DisableAll, "disable-all", false, "disable all checkers") + fs.Var(&cfg.EnabledCheckers, "enable", "comma separated list of enabled checkers (in addition to enabled by default)") + + fs.BoolVar(&cfg.BoolCompare.IgnoreCustomTypes, + "bool-compare.ignore-custom-types", false, + "to ignore user defined types (over builtin bool)") + + fs.Var(&cfg.ExpectedActual.ExpVarPattern, + "expected-actual.pattern", + "regexp for expected variable name") + + fs.BoolVar(&cfg.Formatter.CheckFormatString, + "formatter.check-format-string", true, + "to enable go vet's printf checks") + fs.BoolVar(&cfg.Formatter.RequireFFuncs, + "formatter.require-f-funcs", false, + "to require f-assertions if format string is used") + + fs.BoolVar(&cfg.GoRequire.IgnoreHTTPHandlers, + "go-require.ignore-http-handlers", false, + "to ignore HTTP handlers (like http.HandlerFunc)") + + fs.Var(&cfg.RequireError.FnPattern, + "require-error.fn-pattern", + "regexp for error assertions that should only be analyzed") + fs.Var(NewEnumValue(suiteExtraAssertCallModeAsString, &cfg.SuiteExtraAssertCall.Mode), - "suite-extra-assert-call.mode", "to require or remove extra Assert() call") + "suite-extra-assert-call.mode", + "to require or remove extra Assert() call") } var suiteExtraAssertCallModeAsString = map[string]checkers.SuiteExtraAssertCallMode{ diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/config/flag_value_types.go b/tools/vendor/github.com/Antonboom/testifylint/internal/config/flag_value_types.go index 2f0ee978f..5b08ec47b 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/config/flag_value_types.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/config/flag_value_types.go @@ -35,6 +35,15 @@ func (kcv *KnownCheckersValue) Set(v string) error { return nil } +func (kcv KnownCheckersValue) Contains(v string) bool { + for _, checker := range kcv { + if checker == v { + return true + } + } + return false +} + // RegexpValue is a special wrapper for support of flag.FlagSet over regexp.Regexp. // Original regexp is available through RegexpValue.Regexp. type RegexpValue struct { diff --git a/tools/vendor/github.com/Antonboom/testifylint/internal/testify/const.go b/tools/vendor/github.com/Antonboom/testifylint/internal/testify/const.go index 45731aa97..3476e4040 100644 --- a/tools/vendor/github.com/Antonboom/testifylint/internal/testify/const.go +++ b/tools/vendor/github.com/Antonboom/testifylint/internal/testify/const.go @@ -4,10 +4,14 @@ const ( ModulePath = "github.com/stretchr/testify" AssertPkgName = "assert" + HTTPPkgName = "http" + MockPkgName = "mock" RequirePkgName = "require" SuitePkgName = "suite" AssertPkgPath = ModulePath + "/" + AssertPkgName + HTTPPkgPath = ModulePath + "/" + HTTPPkgName + MockPkgPath = ModulePath + "/" + MockPkgName RequirePkgPath = ModulePath + "/" + RequirePkgName SuitePkgPath = ModulePath + "/" + SuitePkgName ) diff --git a/tools/vendor/github.com/BurntSushi/toml/README.md b/tools/vendor/github.com/BurntSushi/toml/README.md index 3651cfa96..639e6c399 100644 --- a/tools/vendor/github.com/BurntSushi/toml/README.md +++ b/tools/vendor/github.com/BurntSushi/toml/README.md @@ -9,7 +9,7 @@ See the [releases page](https://github.com/BurntSushi/toml/releases) for a changelog; this information is also in the git tag annotations (e.g. `git show v0.4.0`). -This library requires Go 1.13 or newer; add it to your go.mod with: +This library requires Go 1.18 or newer; add it to your go.mod with: % go get github.com/BurntSushi/toml@latest diff --git a/tools/vendor/github.com/BurntSushi/toml/decode.go b/tools/vendor/github.com/BurntSushi/toml/decode.go index 4d38f3bfc..c05a0b7e5 100644 --- a/tools/vendor/github.com/BurntSushi/toml/decode.go +++ b/tools/vendor/github.com/BurntSushi/toml/decode.go @@ -6,7 +6,7 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" + "io/fs" "math" "os" "reflect" @@ -18,13 +18,13 @@ import ( // Unmarshaler is the interface implemented by objects that can unmarshal a // TOML description of themselves. type Unmarshaler interface { - UnmarshalTOML(interface{}) error + UnmarshalTOML(any) error } // Unmarshal decodes the contents of data in TOML format into a pointer v. // // See [Decoder] for a description of the decoding process. -func Unmarshal(data []byte, v interface{}) error { +func Unmarshal(data []byte, v any) error { _, err := NewDecoder(bytes.NewReader(data)).Decode(v) return err } @@ -32,12 +32,12 @@ func Unmarshal(data []byte, v interface{}) error { // Decode the TOML data in to the pointer v. // // See [Decoder] for a description of the decoding process. -func Decode(data string, v interface{}) (MetaData, error) { +func Decode(data string, v any) (MetaData, error) { return NewDecoder(strings.NewReader(data)).Decode(v) } // DecodeFile reads the contents of a file and decodes it with [Decode]. -func DecodeFile(path string, v interface{}) (MetaData, error) { +func DecodeFile(path string, v any) (MetaData, error) { fp, err := os.Open(path) if err != nil { return MetaData{}, err @@ -46,6 +46,17 @@ func DecodeFile(path string, v interface{}) (MetaData, error) { return NewDecoder(fp).Decode(v) } +// DecodeFS reads the contents of a file from [fs.FS] and decodes it with +// [Decode]. +func DecodeFS(fsys fs.FS, path string, v any) (MetaData, error) { + fp, err := fsys.Open(path) + if err != nil { + return MetaData{}, err + } + defer fp.Close() + return NewDecoder(fp).Decode(v) +} + // Primitive is a TOML value that hasn't been decoded into a Go value. // // This type can be used for any value, which will cause decoding to be delayed. @@ -58,7 +69,7 @@ func DecodeFile(path string, v interface{}) (MetaData, error) { // overhead of reflection. They can be useful when you don't know the exact type // of TOML data until runtime. type Primitive struct { - undecoded interface{} + undecoded any context Key } @@ -122,7 +133,7 @@ var ( ) // Decode TOML data in to the pointer `v`. -func (dec *Decoder) Decode(v interface{}) (MetaData, error) { +func (dec *Decoder) Decode(v any) (MetaData, error) { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { s := "%q" @@ -136,8 +147,8 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { return MetaData{}, fmt.Errorf("toml: cannot decode to nil value of %q", reflect.TypeOf(v)) } - // Check if this is a supported type: struct, map, interface{}, or something - // that implements UnmarshalTOML or UnmarshalText. + // Check if this is a supported type: struct, map, any, or something that + // implements UnmarshalTOML or UnmarshalText. rv = indirect(rv) rt := rv.Type() if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map && @@ -148,7 +159,7 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { // TODO: parser should read from io.Reader? Or at the very least, make it // read from []byte rather than string - data, err := ioutil.ReadAll(dec.r) + data, err := io.ReadAll(dec.r) if err != nil { return MetaData{}, err } @@ -179,7 +190,7 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { // will only reflect keys that were decoded. Namely, any keys hidden behind a // Primitive will be considered undecoded. Executing this method will update the // undecoded keys in the meta data. (See the example.) -func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { +func (md *MetaData) PrimitiveDecode(primValue Primitive, v any) error { md.context = primValue.context defer func() { md.context = nil }() return md.unify(primValue.undecoded, rvalue(v)) @@ -190,7 +201,7 @@ func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { // // Any type mismatch produces an error. Finding a type that we don't know // how to handle produces an unsupported type error. -func (md *MetaData) unify(data interface{}, rv reflect.Value) error { +func (md *MetaData) unify(data any, rv reflect.Value) error { // Special case. Look for a `Primitive` value. // TODO: #76 would make this superfluous after implemented. if rv.Type() == primitiveType { @@ -207,7 +218,11 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { rvi := rv.Interface() if v, ok := rvi.(Unmarshaler); ok { - return v.UnmarshalTOML(data) + err := v.UnmarshalTOML(data) + if err != nil { + return md.parseErr(err) + } + return nil } if v, ok := rvi.(encoding.TextUnmarshaler); ok { return md.unifyText(data, v) @@ -227,14 +242,6 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { return md.unifyInt(data, rv) } switch k { - case reflect.Ptr: - elem := reflect.New(rv.Type().Elem()) - err := md.unify(data, reflect.Indirect(elem)) - if err != nil { - return err - } - rv.Set(elem) - return nil case reflect.Struct: return md.unifyStruct(data, rv) case reflect.Map: @@ -258,14 +265,13 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { return md.e("unsupported type %s", rv.Kind()) } -func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { - tmap, ok := mapping.(map[string]interface{}) +func (md *MetaData) unifyStruct(mapping any, rv reflect.Value) error { + tmap, ok := mapping.(map[string]any) if !ok { if mapping == nil { return nil } - return md.e("type mismatch for %s: expected table but found %T", - rv.Type().String(), mapping) + return md.e("type mismatch for %s: expected table but found %s", rv.Type().String(), fmtType(mapping)) } for key, datum := range tmap { @@ -304,14 +310,14 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { return nil } -func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { +func (md *MetaData) unifyMap(mapping any, rv reflect.Value) error { keyType := rv.Type().Key().Kind() if keyType != reflect.String && keyType != reflect.Interface { return fmt.Errorf("toml: cannot decode to a map with non-string key type (%s in %q)", keyType, rv.Type()) } - tmap, ok := mapping.(map[string]interface{}) + tmap, ok := mapping.(map[string]any) if !ok { if tmap == nil { return nil @@ -347,7 +353,7 @@ func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { return nil } -func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { +func (md *MetaData) unifyArray(data any, rv reflect.Value) error { datav := reflect.ValueOf(data) if datav.Kind() != reflect.Slice { if !datav.IsValid() { @@ -361,7 +367,7 @@ func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { return md.unifySliceArray(datav, rv) } -func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error { +func (md *MetaData) unifySlice(data any, rv reflect.Value) error { datav := reflect.ValueOf(data) if datav.Kind() != reflect.Slice { if !datav.IsValid() { @@ -388,7 +394,7 @@ func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { return nil } -func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { +func (md *MetaData) unifyString(data any, rv reflect.Value) error { _, ok := rv.Interface().(json.Number) if ok { if i, ok := data.(int64); ok { @@ -408,7 +414,7 @@ func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { return md.badtype("string", data) } -func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { +func (md *MetaData) unifyFloat64(data any, rv reflect.Value) error { rvk := rv.Kind() if num, ok := data.(float64); ok { @@ -429,7 +435,7 @@ func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { if num, ok := data.(int64); ok { if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) || (rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) { - return md.parseErr(errParseRange{i: num, size: rvk.String()}) + return md.parseErr(errUnsafeFloat{i: num, size: rvk.String()}) } rv.SetFloat(float64(num)) return nil @@ -438,7 +444,7 @@ func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { return md.badtype("float", data) } -func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { +func (md *MetaData) unifyInt(data any, rv reflect.Value) error { _, ok := rv.Interface().(time.Duration) if ok { // Parse as string duration, and fall back to regular integer parsing @@ -481,7 +487,7 @@ func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { return nil } -func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { +func (md *MetaData) unifyBool(data any, rv reflect.Value) error { if b, ok := data.(bool); ok { rv.SetBool(b) return nil @@ -489,12 +495,12 @@ func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { return md.badtype("boolean", data) } -func (md *MetaData) unifyAnything(data interface{}, rv reflect.Value) error { +func (md *MetaData) unifyAnything(data any, rv reflect.Value) error { rv.Set(reflect.ValueOf(data)) return nil } -func (md *MetaData) unifyText(data interface{}, v encoding.TextUnmarshaler) error { +func (md *MetaData) unifyText(data any, v encoding.TextUnmarshaler) error { var s string switch sdata := data.(type) { case Marshaler: @@ -523,27 +529,29 @@ func (md *MetaData) unifyText(data interface{}, v encoding.TextUnmarshaler) erro return md.badtype("primitive (string-like)", data) } if err := v.UnmarshalText([]byte(s)); err != nil { - return err + return md.parseErr(err) } return nil } -func (md *MetaData) badtype(dst string, data interface{}) error { - return md.e("incompatible types: TOML value has type %T; destination has type %s", data, dst) +func (md *MetaData) badtype(dst string, data any) error { + return md.e("incompatible types: TOML value has type %s; destination has type %s", fmtType(data), dst) } func (md *MetaData) parseErr(err error) error { k := md.context.String() + d := string(md.data) return ParseError{ + Message: err.Error(), + err: err, LastKey: k, - Position: md.keyInfo[k].pos, + Position: md.keyInfo[k].pos.withCol(d), Line: md.keyInfo[k].pos.Line, - err: err, - input: string(md.data), + input: d, } } -func (md *MetaData) e(format string, args ...interface{}) error { +func (md *MetaData) e(format string, args ...any) error { f := "toml: " if len(md.context) > 0 { f = fmt.Sprintf("toml: (last key %q): ", md.context) @@ -556,7 +564,7 @@ func (md *MetaData) e(format string, args ...interface{}) error { } // rvalue returns a reflect.Value of `v`. All pointers are resolved. -func rvalue(v interface{}) reflect.Value { +func rvalue(v any) reflect.Value { return indirect(reflect.ValueOf(v)) } @@ -600,3 +608,8 @@ func isUnifiable(rv reflect.Value) bool { } return false } + +// fmt %T with "interface {}" replaced with "any", which is far more readable. +func fmtType(t any) string { + return strings.ReplaceAll(fmt.Sprintf("%T", t), "interface {}", "any") +} diff --git a/tools/vendor/github.com/BurntSushi/toml/decode_go116.go b/tools/vendor/github.com/BurntSushi/toml/decode_go116.go deleted file mode 100644 index 086d0b686..000000000 --- a/tools/vendor/github.com/BurntSushi/toml/decode_go116.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build go1.16 -// +build go1.16 - -package toml - -import ( - "io/fs" -) - -// DecodeFS reads the contents of a file from [fs.FS] and decodes it with -// [Decode]. -func DecodeFS(fsys fs.FS, path string, v interface{}) (MetaData, error) { - fp, err := fsys.Open(path) - if err != nil { - return MetaData{}, err - } - defer fp.Close() - return NewDecoder(fp).Decode(v) -} diff --git a/tools/vendor/github.com/BurntSushi/toml/deprecated.go b/tools/vendor/github.com/BurntSushi/toml/deprecated.go index b9e309717..155709a80 100644 --- a/tools/vendor/github.com/BurntSushi/toml/deprecated.go +++ b/tools/vendor/github.com/BurntSushi/toml/deprecated.go @@ -15,15 +15,15 @@ type TextMarshaler encoding.TextMarshaler // Deprecated: use encoding.TextUnmarshaler type TextUnmarshaler encoding.TextUnmarshaler +// DecodeReader is an alias for NewDecoder(r).Decode(v). +// +// Deprecated: use NewDecoder(reader).Decode(&value). +func DecodeReader(r io.Reader, v any) (MetaData, error) { return NewDecoder(r).Decode(v) } + // PrimitiveDecode is an alias for MetaData.PrimitiveDecode(). // // Deprecated: use MetaData.PrimitiveDecode. -func PrimitiveDecode(primValue Primitive, v interface{}) error { +func PrimitiveDecode(primValue Primitive, v any) error { md := MetaData{decoded: make(map[string]struct{})} return md.unify(primValue.undecoded, rvalue(v)) } - -// DecodeReader is an alias for NewDecoder(r).Decode(v). -// -// Deprecated: use NewDecoder(reader).Decode(&value). -func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { return NewDecoder(r).Decode(v) } diff --git a/tools/vendor/github.com/BurntSushi/toml/doc.go b/tools/vendor/github.com/BurntSushi/toml/doc.go index 81a7c0fe9..82c90a905 100644 --- a/tools/vendor/github.com/BurntSushi/toml/doc.go +++ b/tools/vendor/github.com/BurntSushi/toml/doc.go @@ -2,9 +2,6 @@ // // This package supports TOML v1.0.0, as specified at https://toml.io // -// There is also support for delaying decoding with the Primitive type, and -// querying the set of keys in a TOML document with the MetaData type. -// // The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator, // and can be used to verify if TOML document is valid. It can also be used to // print the type of each key. diff --git a/tools/vendor/github.com/BurntSushi/toml/encode.go b/tools/vendor/github.com/BurntSushi/toml/encode.go index 9cd25d757..73366c0d9 100644 --- a/tools/vendor/github.com/BurntSushi/toml/encode.go +++ b/tools/vendor/github.com/BurntSushi/toml/encode.go @@ -2,6 +2,7 @@ package toml import ( "bufio" + "bytes" "encoding" "encoding/json" "errors" @@ -76,6 +77,17 @@ type Marshaler interface { MarshalTOML() ([]byte, error) } +// Marshal returns a TOML representation of the Go value. +// +// See [Encoder] for a description of the encoding process. +func Marshal(v any) ([]byte, error) { + buff := new(bytes.Buffer) + if err := NewEncoder(buff).Encode(v); err != nil { + return nil, err + } + return buff.Bytes(), nil +} + // Encoder encodes a Go to a TOML document. // // The mapping between Go values and TOML values should be precisely the same as @@ -115,26 +127,21 @@ type Marshaler interface { // NOTE: only exported keys are encoded due to the use of reflection. Unexported // keys are silently discarded. type Encoder struct { - // String to use for a single indentation level; default is two spaces. - Indent string - + Indent string // string for a single indentation level; default is two spaces. + hasWritten bool // written any output to w yet? w *bufio.Writer - hasWritten bool // written any output to w yet? } // NewEncoder create a new Encoder. func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - w: bufio.NewWriter(w), - Indent: " ", - } + return &Encoder{w: bufio.NewWriter(w), Indent: " "} } // Encode writes a TOML representation of the Go value to the [Encoder]'s writer. // // An error is returned if the value given cannot be encoded to a valid TOML // document. -func (enc *Encoder) Encode(v interface{}) error { +func (enc *Encoder) Encode(v any) error { rv := eindirect(reflect.ValueOf(v)) err := enc.safeEncode(Key([]string{}), rv) if err != nil { @@ -280,18 +287,30 @@ func (enc *Encoder) eElement(rv reflect.Value) { case reflect.Float32: f := rv.Float() if math.IsNaN(f) { + if math.Signbit(f) { + enc.wf("-") + } enc.wf("nan") } else if math.IsInf(f, 0) { - enc.wf("%cinf", map[bool]byte{true: '-', false: '+'}[math.Signbit(f)]) + if math.Signbit(f) { + enc.wf("-") + } + enc.wf("inf") } else { enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 32))) } case reflect.Float64: f := rv.Float() if math.IsNaN(f) { + if math.Signbit(f) { + enc.wf("-") + } enc.wf("nan") } else if math.IsInf(f, 0) { - enc.wf("%cinf", map[bool]byte{true: '-', false: '+'}[math.Signbit(f)]) + if math.Signbit(f) { + enc.wf("-") + } + enc.wf("inf") } else { enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 64))) } @@ -304,7 +323,7 @@ func (enc *Encoder) eElement(rv reflect.Value) { case reflect.Interface: enc.eElement(rv.Elem()) default: - encPanic(fmt.Errorf("unexpected type: %T", rv.Interface())) + encPanic(fmt.Errorf("unexpected type: %s", fmtType(rv.Interface()))) } } @@ -712,7 +731,7 @@ func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) { } } -func (enc *Encoder) wf(format string, v ...interface{}) { +func (enc *Encoder) wf(format string, v ...any) { _, err := fmt.Fprintf(enc.w, format, v...) if err != nil { encPanic(err) diff --git a/tools/vendor/github.com/BurntSushi/toml/error.go b/tools/vendor/github.com/BurntSushi/toml/error.go index efd68865b..1dd523211 100644 --- a/tools/vendor/github.com/BurntSushi/toml/error.go +++ b/tools/vendor/github.com/BurntSushi/toml/error.go @@ -67,21 +67,36 @@ type ParseError struct { // Position of an error. type Position struct { Line int // Line number, starting at 1. + Col int // Error column, starting at 1. Start int // Start of error, as byte offset starting at 0. - Len int // Lenght in bytes. + Len int // Lenght of the error in bytes. } -func (pe ParseError) Error() string { - msg := pe.Message - if msg == "" { // Error from errorf() - msg = pe.err.Error() +func (p Position) withCol(tomlFile string) Position { + var ( + pos int + lines = strings.Split(tomlFile, "\n") + ) + for i := range lines { + ll := len(lines[i]) + 1 // +1 for the removed newline + if pos+ll >= p.Start { + p.Col = p.Start - pos + 1 + if p.Col < 1 { // Should never happen, but just in case. + p.Col = 1 + } + break + } + pos += ll } + return p +} +func (pe ParseError) Error() string { if pe.LastKey == "" { - return fmt.Sprintf("toml: line %d: %s", pe.Position.Line, msg) + return fmt.Sprintf("toml: line %d: %s", pe.Position.Line, pe.Message) } return fmt.Sprintf("toml: line %d (last key %q): %s", - pe.Position.Line, pe.LastKey, msg) + pe.Position.Line, pe.LastKey, pe.Message) } // ErrorWithPosition returns the error with detailed location context. @@ -92,35 +107,37 @@ func (pe ParseError) ErrorWithPosition() string { return pe.Error() } + // TODO: don't show control characters as literals? This may not show up + // well everywhere. + var ( lines = strings.Split(pe.input, "\n") - col = pe.column(lines) b = new(strings.Builder) ) - - msg := pe.Message - if msg == "" { - msg = pe.err.Error() - } - - // TODO: don't show control characters as literals? This may not show up - // well everywhere. - if pe.Position.Len == 1 { fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d:\n\n", - msg, pe.Position.Line, col+1) + pe.Message, pe.Position.Line, pe.Position.Col) } else { fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d-%d:\n\n", - msg, pe.Position.Line, col, col+pe.Position.Len) + pe.Message, pe.Position.Line, pe.Position.Col, pe.Position.Col+pe.Position.Len-1) } if pe.Position.Line > 2 { - fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, lines[pe.Position.Line-3]) + fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, expandTab(lines[pe.Position.Line-3])) } if pe.Position.Line > 1 { - fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, lines[pe.Position.Line-2]) + fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2])) } - fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, lines[pe.Position.Line-1]) - fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", col), strings.Repeat("^", pe.Position.Len)) + + /// Expand tabs, so that the ^^^s are at the correct position, but leave + /// "column 10-13" intact. Adjusting this to the visual column would be + /// better, but we don't know the tabsize of the user in their editor, which + /// can be 8, 4, 2, or something else. We can't know. So leaving it as the + /// character index is probably the "most correct". + expanded := expandTab(lines[pe.Position.Line-1]) + diff := len(expanded) - len(lines[pe.Position.Line-1]) + + fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, expanded) + fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", pe.Position.Col-1+diff), strings.Repeat("^", pe.Position.Len)) return b.String() } @@ -142,34 +159,47 @@ func (pe ParseError) ErrorWithUsage() string { return m } -func (pe ParseError) column(lines []string) int { - var pos, col int - for i := range lines { - ll := len(lines[i]) + 1 // +1 for the removed newline - if pos+ll >= pe.Position.Start { - col = pe.Position.Start - pos - if col < 0 { // Should never happen, but just in case. - col = 0 +func expandTab(s string) string { + var ( + b strings.Builder + l int + fill = func(n int) string { + b := make([]byte, n) + for i := range b { + b[i] = ' ' } - break + return string(b) + } + ) + b.Grow(len(s)) + for _, r := range s { + switch r { + case '\t': + tw := 8 - l%8 + b.WriteString(fill(tw)) + l += tw + default: + b.WriteRune(r) + l += 1 } - pos += ll } - - return col + return b.String() } type ( errLexControl struct{ r rune } errLexEscape struct{ r rune } errLexUTF8 struct{ b byte } - errLexInvalidNum struct{ v string } - errLexInvalidDate struct{ v string } + errParseDate struct{ v string } errLexInlineTableNL struct{} errLexStringNL struct{} errParseRange struct { - i interface{} // int or float - size string // "int64", "uint16", etc. + i any // int or float + size string // "int64", "uint16", etc. + } + errUnsafeFloat struct { + i interface{} // float32 or float64 + size string // "float32" or "float64" } errParseDuration struct{ d string } ) @@ -183,18 +213,20 @@ func (e errLexEscape) Error() string { return fmt.Sprintf(`invalid escape func (e errLexEscape) Usage() string { return usageEscape } func (e errLexUTF8) Error() string { return fmt.Sprintf("invalid UTF-8 byte: 0x%02x", e.b) } func (e errLexUTF8) Usage() string { return "" } -func (e errLexInvalidNum) Error() string { return fmt.Sprintf("invalid number: %q", e.v) } -func (e errLexInvalidNum) Usage() string { return "" } -func (e errLexInvalidDate) Error() string { return fmt.Sprintf("invalid date: %q", e.v) } -func (e errLexInvalidDate) Usage() string { return "" } +func (e errParseDate) Error() string { return fmt.Sprintf("invalid datetime: %q", e.v) } +func (e errParseDate) Usage() string { return usageDate } func (e errLexInlineTableNL) Error() string { return "newlines not allowed within inline tables" } func (e errLexInlineTableNL) Usage() string { return usageInlineNewline } func (e errLexStringNL) Error() string { return "strings cannot contain newlines" } func (e errLexStringNL) Usage() string { return usageStringNewline } func (e errParseRange) Error() string { return fmt.Sprintf("%v is out of range for %s", e.i, e.size) } func (e errParseRange) Usage() string { return usageIntOverflow } -func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) } -func (e errParseDuration) Usage() string { return usageDuration } +func (e errUnsafeFloat) Error() string { + return fmt.Sprintf("%v is out of the safe %s range", e.i, e.size) +} +func (e errUnsafeFloat) Usage() string { return usageUnsafeFloat } +func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) } +func (e errParseDuration) Usage() string { return usageDuration } const usageEscape = ` A '\' inside a "-delimited string is interpreted as an escape character. @@ -251,19 +283,35 @@ bug in the program that uses too small of an integer. The maximum and minimum values are: size │ lowest │ highest - ───────┼────────────────┼────────── + ───────┼────────────────┼────────────── int8 │ -128 │ 127 int16 │ -32,768 │ 32,767 int32 │ -2,147,483,648 │ 2,147,483,647 int64 │ -9.2 × 10¹⁷ │ 9.2 × 10¹⁷ uint8 │ 0 │ 255 - uint16 │ 0 │ 65535 - uint32 │ 0 │ 4294967295 + uint16 │ 0 │ 65,535 + uint32 │ 0 │ 4,294,967,295 uint64 │ 0 │ 1.8 × 10¹⁸ int refers to int32 on 32-bit systems and int64 on 64-bit systems. ` +const usageUnsafeFloat = ` +This number is outside of the "safe" range for floating point numbers; whole +(non-fractional) numbers outside the below range can not always be represented +accurately in a float, leading to some loss of accuracy. + +Explicitly mark a number as a fractional unit by adding ".0", which will incur +some loss of accuracy; for example: + + f = 2_000_000_000.0 + +Accuracy ranges: + + float32 = 16,777,215 + float64 = 9,007,199,254,740,991 +` + const usageDuration = ` A duration must be as "number", without any spaces. Valid units are: @@ -277,3 +325,23 @@ A duration must be as "number", without any spaces. Valid units are: You can combine multiple units; for example "5m10s" for 5 minutes and 10 seconds. ` + +const usageDate = ` +A TOML datetime must be in one of the following formats: + + 2006-01-02T15:04:05Z07:00 Date and time, with timezone. + 2006-01-02T15:04:05 Date and time, but without timezone. + 2006-01-02 Date without a time or timezone. + 15:04:05 Just a time, without any timezone. + +Seconds may optionally have a fraction, up to nanosecond precision: + + 15:04:05.123 + 15:04:05.856018510 +` + +// TOML 1.1: +// The seconds part in times is optional, and may be omitted: +// 2006-01-02T15:04Z07:00 +// 2006-01-02T15:04 +// 15:04 diff --git a/tools/vendor/github.com/BurntSushi/toml/lex.go b/tools/vendor/github.com/BurntSushi/toml/lex.go index 3545a6ad6..6878d9d69 100644 --- a/tools/vendor/github.com/BurntSushi/toml/lex.go +++ b/tools/vendor/github.com/BurntSushi/toml/lex.go @@ -17,6 +17,7 @@ const ( itemEOF itemText itemString + itemStringEsc itemRawString itemMultilineString itemRawMultilineString @@ -53,6 +54,7 @@ type lexer struct { state stateFn items chan item tomlNext bool + esc bool // Allow for backing up up to 4 runes. This is necessary because TOML // contains 3-rune tokens (""" and '''). @@ -164,7 +166,7 @@ func (lx *lexer) next() (r rune) { } r, w := utf8.DecodeRuneInString(lx.input[lx.pos:]) - if r == utf8.RuneError { + if r == utf8.RuneError && w == 1 { lx.error(errLexUTF8{lx.input[lx.pos]}) return utf8.RuneError } @@ -270,7 +272,7 @@ func (lx *lexer) errorPos(start, length int, err error) stateFn { } // errorf is like error, and creates a new error. -func (lx *lexer) errorf(format string, values ...interface{}) stateFn { +func (lx *lexer) errorf(format string, values ...any) stateFn { if lx.atEOF { pos := lx.getPos() pos.Line-- @@ -333,9 +335,7 @@ func lexTopEnd(lx *lexer) stateFn { lx.emit(itemEOF) return nil } - return lx.errorf( - "expected a top-level item to end with a newline, comment, or EOF, but got %q instead", - r) + return lx.errorf("expected a top-level item to end with a newline, comment, or EOF, but got %q instead", r) } // lexTable lexes the beginning of a table. Namely, it makes sure that @@ -492,6 +492,9 @@ func lexKeyEnd(lx *lexer) stateFn { lx.emit(itemKeyEnd) return lexSkip(lx, lexValue) default: + if r == '\n' { + return lx.errorPrevLine(fmt.Errorf("expected '.' or '=', but got %q instead", r)) + } return lx.errorf("expected '.' or '=', but got %q instead", r) } } @@ -560,6 +563,9 @@ func lexValue(lx *lexer) stateFn { if r == eof { return lx.errorf("unexpected EOF; expected value") } + if r == '\n' { + return lx.errorPrevLine(fmt.Errorf("expected value but found %q instead", r)) + } return lx.errorf("expected value but found %q instead", r) } @@ -698,7 +704,12 @@ func lexString(lx *lexer) stateFn { return lexStringEscape case r == '"': lx.backup() - lx.emit(itemString) + if lx.esc { + lx.esc = false + lx.emit(itemStringEsc) + } else { + lx.emit(itemString) + } lx.next() lx.ignore() return lx.pop() @@ -748,6 +759,7 @@ func lexMultilineString(lx *lexer) stateFn { lx.backup() /// backup: don't include the """ in the item. lx.backup() lx.backup() + lx.esc = false lx.emit(itemMultilineString) lx.next() /// Read over ''' again and discard it. lx.next() @@ -837,6 +849,7 @@ func lexMultilineStringEscape(lx *lexer) stateFn { } func lexStringEscape(lx *lexer) stateFn { + lx.esc = true r := lx.next() switch r { case 'e': @@ -879,10 +892,8 @@ func lexHexEscape(lx *lexer) stateFn { var r rune for i := 0; i < 2; i++ { r = lx.next() - if !isHexadecimal(r) { - return lx.errorf( - `expected two hexadecimal digits after '\x', but got %q instead`, - lx.current()) + if !isHex(r) { + return lx.errorf(`expected two hexadecimal digits after '\x', but got %q instead`, lx.current()) } } return lx.pop() @@ -892,10 +903,8 @@ func lexShortUnicodeEscape(lx *lexer) stateFn { var r rune for i := 0; i < 4; i++ { r = lx.next() - if !isHexadecimal(r) { - return lx.errorf( - `expected four hexadecimal digits after '\u', but got %q instead`, - lx.current()) + if !isHex(r) { + return lx.errorf(`expected four hexadecimal digits after '\u', but got %q instead`, lx.current()) } } return lx.pop() @@ -905,10 +914,8 @@ func lexLongUnicodeEscape(lx *lexer) stateFn { var r rune for i := 0; i < 8; i++ { r = lx.next() - if !isHexadecimal(r) { - return lx.errorf( - `expected eight hexadecimal digits after '\U', but got %q instead`, - lx.current()) + if !isHex(r) { + return lx.errorf(`expected eight hexadecimal digits after '\U', but got %q instead`, lx.current()) } } return lx.pop() @@ -975,7 +982,7 @@ func lexDatetime(lx *lexer) stateFn { // lexHexInteger consumes a hexadecimal integer after seeing the '0x' prefix. func lexHexInteger(lx *lexer) stateFn { r := lx.next() - if isHexadecimal(r) { + if isHex(r) { return lexHexInteger } switch r { @@ -1109,7 +1116,7 @@ func lexBaseNumberOrDate(lx *lexer) stateFn { return lexOctalInteger case 'x': r = lx.peek() - if !isHexadecimal(r) { + if !isHex(r) { lx.errorf("not a hexidecimal number: '%s%c'", lx.current(), r) } return lexHexInteger @@ -1207,7 +1214,7 @@ func (itype itemType) String() string { return "EOF" case itemText: return "Text" - case itemString, itemRawString, itemMultilineString, itemRawMultilineString: + case itemString, itemStringEsc, itemRawString, itemMultilineString, itemRawMultilineString: return "String" case itemBool: return "Bool" @@ -1240,7 +1247,7 @@ func (itype itemType) String() string { } func (item item) String() string { - return fmt.Sprintf("(%s, %s)", item.typ.String(), item.val) + return fmt.Sprintf("(%s, %s)", item.typ, item.val) } func isWhitespace(r rune) bool { return r == '\t' || r == ' ' } @@ -1256,10 +1263,7 @@ func isControl(r rune) bool { // Control characters except \t, \r, \n func isDigit(r rune) bool { return r >= '0' && r <= '9' } func isBinary(r rune) bool { return r == '0' || r == '1' } func isOctal(r rune) bool { return r >= '0' && r <= '7' } -func isHexadecimal(r rune) bool { - return (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F') -} - +func isHex(r rune) bool { return (r >= '0' && r <= '9') || (r|0x20 >= 'a' && r|0x20 <= 'f') } func isBareKeyChar(r rune, tomlNext bool) bool { if tomlNext { return (r >= 'A' && r <= 'Z') || diff --git a/tools/vendor/github.com/BurntSushi/toml/meta.go b/tools/vendor/github.com/BurntSushi/toml/meta.go index 2e78b24e9..e61453730 100644 --- a/tools/vendor/github.com/BurntSushi/toml/meta.go +++ b/tools/vendor/github.com/BurntSushi/toml/meta.go @@ -13,7 +13,7 @@ type MetaData struct { context Key // Used only during decoding. keyInfo map[string]keyInfo - mapping map[string]interface{} + mapping map[string]any keys []Key decoded map[string]struct{} data []byte // Input file; for errors. @@ -31,12 +31,12 @@ func (md *MetaData) IsDefined(key ...string) bool { } var ( - hash map[string]interface{} + hash map[string]any ok bool - hashOrVal interface{} = md.mapping + hashOrVal any = md.mapping ) for _, k := range key { - if hash, ok = hashOrVal.(map[string]interface{}); !ok { + if hash, ok = hashOrVal.(map[string]any); !ok { return false } if hashOrVal, ok = hash[k]; !ok { @@ -94,28 +94,55 @@ func (md *MetaData) Undecoded() []Key { type Key []string func (k Key) String() string { - ss := make([]string, len(k)) - for i := range k { - ss[i] = k.maybeQuoted(i) + // This is called quite often, so it's a bit funky to make it faster. + var b strings.Builder + b.Grow(len(k) * 25) +outer: + for i, kk := range k { + if i > 0 { + b.WriteByte('.') + } + if kk == "" { + b.WriteString(`""`) + } else { + for _, r := range kk { + // "Inline" isBareKeyChar + if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-') { + b.WriteByte('"') + b.WriteString(dblQuotedReplacer.Replace(kk)) + b.WriteByte('"') + continue outer + } + } + b.WriteString(kk) + } } - return strings.Join(ss, ".") + return b.String() } func (k Key) maybeQuoted(i int) string { if k[i] == "" { return `""` } - for _, c := range k[i] { - if !isBareKeyChar(c, false) { - return `"` + dblQuotedReplacer.Replace(k[i]) + `"` + for _, r := range k[i] { + if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' { + continue } + return `"` + dblQuotedReplacer.Replace(k[i]) + `"` } return k[i] } +// Like append(), but only increase the cap by 1. func (k Key) add(piece string) Key { + if cap(k) > len(k) { + return append(k, piece) + } newKey := make(Key, len(k)+1) copy(newKey, k) newKey[len(k)] = piece return newKey } + +func (k Key) parent() Key { return k[:len(k)-1] } // all except the last piece. +func (k Key) last() string { return k[len(k)-1] } // last piece of this key. diff --git a/tools/vendor/github.com/BurntSushi/toml/parse.go b/tools/vendor/github.com/BurntSushi/toml/parse.go index 9c1915369..3f2c090c8 100644 --- a/tools/vendor/github.com/BurntSushi/toml/parse.go +++ b/tools/vendor/github.com/BurntSushi/toml/parse.go @@ -2,6 +2,7 @@ package toml import ( "fmt" + "math" "os" "strconv" "strings" @@ -20,9 +21,9 @@ type parser struct { ordered []Key // List of keys in the order that they appear in the TOML data. - keyInfo map[string]keyInfo // Map keyname → info about the TOML key. - mapping map[string]interface{} // Map keyname → key value. - implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names"). + keyInfo map[string]keyInfo // Map keyname → info about the TOML key. + mapping map[string]any // Map keyname → key value. + implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names"). } type keyInfo struct { @@ -49,6 +50,7 @@ func parse(data string) (p *parser, err error) { // it anyway. if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { // UTF-16 data = data[2:] + //lint:ignore S1017 https://github.com/dominikh/go-tools/issues/1447 } else if strings.HasPrefix(data, "\xef\xbb\xbf") { // UTF-8 data = data[3:] } @@ -63,7 +65,7 @@ func parse(data string) (p *parser, err error) { if i := strings.IndexRune(data[:ex], 0); i > -1 { return nil, ParseError{ Message: "files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8", - Position: Position{Line: 1, Start: i, Len: 1}, + Position: Position{Line: 1, Col: 1, Start: i, Len: 1}, Line: 1, input: data, } @@ -71,7 +73,7 @@ func parse(data string) (p *parser, err error) { p = &parser{ keyInfo: make(map[string]keyInfo), - mapping: make(map[string]interface{}), + mapping: make(map[string]any), lx: lex(data, tomlNext), ordered: make([]Key, 0), implicits: make(map[string]struct{}), @@ -90,26 +92,27 @@ func parse(data string) (p *parser, err error) { func (p *parser) panicErr(it item, err error) { panic(ParseError{ + Message: err.Error(), err: err, - Position: it.pos, + Position: it.pos.withCol(p.lx.input), Line: it.pos.Len, LastKey: p.current(), }) } -func (p *parser) panicItemf(it item, format string, v ...interface{}) { +func (p *parser) panicItemf(it item, format string, v ...any) { panic(ParseError{ Message: fmt.Sprintf(format, v...), - Position: it.pos, + Position: it.pos.withCol(p.lx.input), Line: it.pos.Len, LastKey: p.current(), }) } -func (p *parser) panicf(format string, v ...interface{}) { +func (p *parser) panicf(format string, v ...any) { panic(ParseError{ Message: fmt.Sprintf(format, v...), - Position: p.pos, + Position: p.pos.withCol(p.lx.input), Line: p.pos.Line, LastKey: p.current(), }) @@ -121,10 +124,11 @@ func (p *parser) next() item { if it.typ == itemError { if it.err != nil { panic(ParseError{ - Position: it.pos, + Message: it.err.Error(), + err: it.err, + Position: it.pos.withCol(p.lx.input), Line: it.pos.Line, LastKey: p.current(), - err: it.err, }) } @@ -139,7 +143,7 @@ func (p *parser) nextPos() item { return it } -func (p *parser) bug(format string, v ...interface{}) { +func (p *parser) bug(format string, v ...any) { panic(fmt.Sprintf("BUG: "+format+"\n\n", v...)) } @@ -194,11 +198,11 @@ func (p *parser) topLevel(item item) { p.assertEqual(itemKeyEnd, k.typ) /// The current key is the last part. - p.currentKey = key[len(key)-1] + p.currentKey = key.last() /// All the other parts (if any) are the context; need to set each part /// as implicit. - context := key[:len(key)-1] + context := key.parent() for i := range context { p.addImplicitContext(append(p.context, context[i:i+1]...)) } @@ -207,7 +211,8 @@ func (p *parser) topLevel(item item) { /// Set value. vItem := p.next() val, typ := p.value(vItem, false) - p.set(p.currentKey, val, typ, vItem.pos) + p.setValue(p.currentKey, val) + p.setType(p.currentKey, typ, vItem.pos) /// Remove the context we added (preserving any context from [tbl] lines). p.context = outerContext @@ -222,7 +227,7 @@ func (p *parser) keyString(it item) string { switch it.typ { case itemText: return it.val - case itemString, itemMultilineString, + case itemString, itemStringEsc, itemMultilineString, itemRawString, itemRawMultilineString: s, _ := p.value(it, false) return s.(string) @@ -239,9 +244,11 @@ var datetimeRepl = strings.NewReplacer( // value translates an expected value from the lexer into a Go value wrapped // as an empty interface. -func (p *parser) value(it item, parentIsArray bool) (interface{}, tomlType) { +func (p *parser) value(it item, parentIsArray bool) (any, tomlType) { switch it.typ { case itemString: + return it.val, p.typeOfPrimitive(it) + case itemStringEsc: return p.replaceEscapes(it, it.val), p.typeOfPrimitive(it) case itemMultilineString: return p.replaceEscapes(it, p.stripEscapedNewlines(stripFirstNewline(it.val))), p.typeOfPrimitive(it) @@ -274,7 +281,7 @@ func (p *parser) value(it item, parentIsArray bool) (interface{}, tomlType) { panic("unreachable") } -func (p *parser) valueInteger(it item) (interface{}, tomlType) { +func (p *parser) valueInteger(it item) (any, tomlType) { if !numUnderscoresOK(it.val) { p.panicItemf(it, "Invalid integer %q: underscores must be surrounded by digits", it.val) } @@ -298,7 +305,7 @@ func (p *parser) valueInteger(it item) (interface{}, tomlType) { return num, p.typeOfPrimitive(it) } -func (p *parser) valueFloat(it item) (interface{}, tomlType) { +func (p *parser) valueFloat(it item) (any, tomlType) { parts := strings.FieldsFunc(it.val, func(r rune) bool { switch r { case '.', 'e', 'E': @@ -322,7 +329,9 @@ func (p *parser) valueFloat(it item) (interface{}, tomlType) { p.panicItemf(it, "Invalid float %q: '.' must be followed by one or more digits", it.val) } val := strings.Replace(it.val, "_", "", -1) - if val == "+nan" || val == "-nan" { // Go doesn't support this, but TOML spec does. + signbit := false + if val == "+nan" || val == "-nan" { + signbit = val == "-nan" val = "nan" } num, err := strconv.ParseFloat(val, 64) @@ -333,6 +342,9 @@ func (p *parser) valueFloat(it item) (interface{}, tomlType) { p.panicItemf(it, "Invalid float value: %q", it.val) } } + if signbit { + num = math.Copysign(num, -1) + } return num, p.typeOfPrimitive(it) } @@ -352,7 +364,7 @@ var dtTypes = []struct { {"15:04", internal.LocalTime, true}, } -func (p *parser) valueDatetime(it item) (interface{}, tomlType) { +func (p *parser) valueDatetime(it item) (any, tomlType) { it.val = datetimeRepl.Replace(it.val) var ( t time.Time @@ -365,26 +377,44 @@ func (p *parser) valueDatetime(it item) (interface{}, tomlType) { } t, err = time.ParseInLocation(dt.fmt, it.val, dt.zone) if err == nil { + if missingLeadingZero(it.val, dt.fmt) { + p.panicErr(it, errParseDate{it.val}) + } ok = true break } } if !ok { - p.panicItemf(it, "Invalid TOML Datetime: %q.", it.val) + p.panicErr(it, errParseDate{it.val}) } return t, p.typeOfPrimitive(it) } -func (p *parser) valueArray(it item) (interface{}, tomlType) { +// Go's time.Parse() will accept numbers without a leading zero; there isn't any +// way to require it. https://github.com/golang/go/issues/29911 +// +// Depend on the fact that the separators (- and :) should always be at the same +// location. +func missingLeadingZero(d, l string) bool { + for i, c := range []byte(l) { + if c == '.' || c == 'Z' { + return false + } + if (c < '0' || c > '9') && d[i] != c { + return true + } + } + return false +} + +func (p *parser) valueArray(it item) (any, tomlType) { p.setType(p.currentKey, tomlArray, it.pos) var ( - types []tomlType - - // Initialize to a non-nil empty slice. This makes it consistent with - // how S = [] decodes into a non-nil slice inside something like struct - // { S []string }. See #338 - array = []interface{}{} + // Initialize to a non-nil slice to make it consistent with how S = [] + // decodes into a non-nil slice inside something like struct { S + // []string }. See #338 + array = make([]any, 0, 2) ) for it = p.next(); it.typ != itemArrayEnd; it = p.next() { if it.typ == itemCommentStart { @@ -394,21 +424,20 @@ func (p *parser) valueArray(it item) (interface{}, tomlType) { val, typ := p.value(it, true) array = append(array, val) - types = append(types, typ) - // XXX: types isn't used here, we need it to record the accurate type + // XXX: type isn't used here, we need it to record the accurate type // information. // // Not entirely sure how to best store this; could use "key[0]", // "key[1]" notation, or maybe store it on the Array type? - _ = types + _ = typ } return array, tomlArray } -func (p *parser) valueInlineTable(it item, parentIsArray bool) (interface{}, tomlType) { +func (p *parser) valueInlineTable(it item, parentIsArray bool) (any, tomlType) { var ( - hash = make(map[string]interface{}) + topHash = make(map[string]any) outerContext = p.context outerKey = p.currentKey ) @@ -436,11 +465,11 @@ func (p *parser) valueInlineTable(it item, parentIsArray bool) (interface{}, tom p.assertEqual(itemKeyEnd, k.typ) /// The current key is the last part. - p.currentKey = key[len(key)-1] + p.currentKey = key.last() /// All the other parts (if any) are the context; need to set each part /// as implicit. - context := key[:len(key)-1] + context := key.parent() for i := range context { p.addImplicitContext(append(p.context, context[i:i+1]...)) } @@ -448,7 +477,21 @@ func (p *parser) valueInlineTable(it item, parentIsArray bool) (interface{}, tom /// Set the value. val, typ := p.value(p.next(), false) - p.set(p.currentKey, val, typ, it.pos) + p.setValue(p.currentKey, val) + p.setType(p.currentKey, typ, it.pos) + + hash := topHash + for _, c := range context { + h, ok := hash[c] + if !ok { + h = make(map[string]any) + hash[c] = h + } + hash, ok = h.(map[string]any) + if !ok { + p.panicf("%q is not a table", p.context) + } + } hash[p.currentKey] = val /// Restore context. @@ -456,7 +499,7 @@ func (p *parser) valueInlineTable(it item, parentIsArray bool) (interface{}, tom } p.context = outerContext p.currentKey = outerKey - return hash, tomlHash + return topHash, tomlHash } // numHasLeadingZero checks if this number has leading zeroes, allowing for '0', @@ -486,9 +529,9 @@ func numUnderscoresOK(s string) bool { } } - // isHexadecimal is a superset of all the permissable characters - // surrounding an underscore. - accept = isHexadecimal(r) + // isHexis a superset of all the permissable characters surrounding an + // underscore. + accept = isHex(r) } return accept } @@ -511,21 +554,19 @@ func numPeriodsOK(s string) bool { // Establishing the context also makes sure that the key isn't a duplicate, and // will create implicit hashes automatically. func (p *parser) addContext(key Key, array bool) { - var ok bool - - // Always start at the top level and drill down for our context. + /// Always start at the top level and drill down for our context. hashContext := p.mapping - keyContext := make(Key, 0) + keyContext := make(Key, 0, len(key)-1) - // We only need implicit hashes for key[0:-1] - for _, k := range key[0 : len(key)-1] { - _, ok = hashContext[k] + /// We only need implicit hashes for the parents. + for _, k := range key.parent() { + _, ok := hashContext[k] keyContext = append(keyContext, k) // No key? Make an implicit hash and move on. if !ok { p.addImplicit(keyContext) - hashContext[k] = make(map[string]interface{}) + hashContext[k] = make(map[string]any) } // If the hash context is actually an array of tables, then set @@ -534,9 +575,9 @@ func (p *parser) addContext(key Key, array bool) { // Otherwise, it better be a table, since this MUST be a key group (by // virtue of it not being the last element in a key). switch t := hashContext[k].(type) { - case []map[string]interface{}: + case []map[string]any: hashContext = t[len(t)-1] - case map[string]interface{}: + case map[string]any: hashContext = t default: p.panicf("Key '%s' was already created as a hash.", keyContext) @@ -547,39 +588,33 @@ func (p *parser) addContext(key Key, array bool) { if array { // If this is the first element for this array, then allocate a new // list of tables for it. - k := key[len(key)-1] + k := key.last() if _, ok := hashContext[k]; !ok { - hashContext[k] = make([]map[string]interface{}, 0, 4) + hashContext[k] = make([]map[string]any, 0, 4) } // Add a new table. But make sure the key hasn't already been used // for something else. - if hash, ok := hashContext[k].([]map[string]interface{}); ok { - hashContext[k] = append(hash, make(map[string]interface{})) + if hash, ok := hashContext[k].([]map[string]any); ok { + hashContext[k] = append(hash, make(map[string]any)) } else { p.panicf("Key '%s' was already created and cannot be used as an array.", key) } } else { - p.setValue(key[len(key)-1], make(map[string]interface{})) + p.setValue(key.last(), make(map[string]any)) } - p.context = append(p.context, key[len(key)-1]) -} - -// set calls setValue and setType. -func (p *parser) set(key string, val interface{}, typ tomlType, pos Position) { - p.setValue(key, val) - p.setType(key, typ, pos) + p.context = append(p.context, key.last()) } // setValue sets the given key to the given value in the current context. // It will make sure that the key hasn't already been defined, account for // implicit key groups. -func (p *parser) setValue(key string, value interface{}) { +func (p *parser) setValue(key string, value any) { var ( - tmpHash interface{} + tmpHash any ok bool hash = p.mapping - keyContext Key + keyContext = make(Key, 0, len(p.context)+1) ) for _, k := range p.context { keyContext = append(keyContext, k) @@ -587,11 +622,11 @@ func (p *parser) setValue(key string, value interface{}) { p.bug("Context for key '%s' has not been established.", keyContext) } switch t := tmpHash.(type) { - case []map[string]interface{}: + case []map[string]any: // The context is a table of hashes. Pick the most recent table // defined as the current hash. hash = t[len(t)-1] - case map[string]interface{}: + case map[string]any: hash = t default: p.panicf("Key '%s' has already been defined.", keyContext) @@ -618,9 +653,8 @@ func (p *parser) setValue(key string, value interface{}) { p.removeImplicit(keyContext) return } - - // Otherwise, we have a concrete key trying to override a previous - // key, which is *always* wrong. + // Otherwise, we have a concrete key trying to override a previous key, + // which is *always* wrong. p.panicf("Key '%s' has already been defined.", keyContext) } @@ -683,8 +717,11 @@ func stripFirstNewline(s string) string { // the next newline. After a line-ending backslash, all whitespace is removed // until the next non-whitespace character. func (p *parser) stripEscapedNewlines(s string) string { - var b strings.Builder - var i int + var ( + b strings.Builder + i int + ) + b.Grow(len(s)) for { ix := strings.Index(s[i:], `\`) if ix < 0 { @@ -714,9 +751,8 @@ func (p *parser) stripEscapedNewlines(s string) string { continue } if !strings.Contains(s[i:j], "\n") { - // This is not a line-ending backslash. - // (It's a bad escape sequence, but we can let - // replaceEscapes catch it.) + // This is not a line-ending backslash. (It's a bad escape sequence, + // but we can let replaceEscapes catch it.) i++ continue } @@ -727,79 +763,78 @@ func (p *parser) stripEscapedNewlines(s string) string { } func (p *parser) replaceEscapes(it item, str string) string { - replaced := make([]rune, 0, len(str)) - s := []byte(str) - r := 0 - for r < len(s) { - if s[r] != '\\' { - c, size := utf8.DecodeRune(s[r:]) - r += size - replaced = append(replaced, c) + var ( + b strings.Builder + skip = 0 + ) + b.Grow(len(str)) + for i, c := range str { + if skip > 0 { + skip-- continue } - r += 1 - if r >= len(s) { + if c != '\\' { + b.WriteRune(c) + continue + } + + if i >= len(str) { p.bug("Escape sequence at end of string.") return "" } - switch s[r] { + switch str[i+1] { default: - p.bug("Expected valid escape code after \\, but got %q.", s[r]) + p.bug("Expected valid escape code after \\, but got %q.", str[i+1]) case ' ', '\t': - p.panicItemf(it, "invalid escape: '\\%c'", s[r]) + p.panicItemf(it, "invalid escape: '\\%c'", str[i+1]) case 'b': - replaced = append(replaced, rune(0x0008)) - r += 1 + b.WriteByte(0x08) + skip = 1 case 't': - replaced = append(replaced, rune(0x0009)) - r += 1 + b.WriteByte(0x09) + skip = 1 case 'n': - replaced = append(replaced, rune(0x000A)) - r += 1 + b.WriteByte(0x0a) + skip = 1 case 'f': - replaced = append(replaced, rune(0x000C)) - r += 1 + b.WriteByte(0x0c) + skip = 1 case 'r': - replaced = append(replaced, rune(0x000D)) - r += 1 + b.WriteByte(0x0d) + skip = 1 case 'e': if p.tomlNext { - replaced = append(replaced, rune(0x001B)) - r += 1 + b.WriteByte(0x1b) + skip = 1 } case '"': - replaced = append(replaced, rune(0x0022)) - r += 1 + b.WriteByte(0x22) + skip = 1 case '\\': - replaced = append(replaced, rune(0x005C)) - r += 1 + b.WriteByte(0x5c) + skip = 1 + // The lexer guarantees the correct number of characters are present; + // don't need to check here. case 'x': if p.tomlNext { - escaped := p.asciiEscapeToUnicode(it, s[r+1:r+3]) - replaced = append(replaced, escaped) - r += 3 + escaped := p.asciiEscapeToUnicode(it, str[i+2:i+4]) + b.WriteRune(escaped) + skip = 3 } case 'u': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+5). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(it, s[r+1:r+5]) - replaced = append(replaced, escaped) - r += 5 + escaped := p.asciiEscapeToUnicode(it, str[i+2:i+6]) + b.WriteRune(escaped) + skip = 5 case 'U': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+9). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(it, s[r+1:r+9]) - replaced = append(replaced, escaped) - r += 9 + escaped := p.asciiEscapeToUnicode(it, str[i+2:i+10]) + b.WriteRune(escaped) + skip = 9 } } - return string(replaced) + return b.String() } -func (p *parser) asciiEscapeToUnicode(it item, bs []byte) rune { - s := string(bs) +func (p *parser) asciiEscapeToUnicode(it item, s string) rune { hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32) if err != nil { p.bug("Could not parse '%s' as a hexadecimal number, but the lexer claims it's OK: %s", s, err) diff --git a/tools/vendor/github.com/BurntSushi/toml/type_fields.go b/tools/vendor/github.com/BurntSushi/toml/type_fields.go index 254ca82e5..10c51f7ee 100644 --- a/tools/vendor/github.com/BurntSushi/toml/type_fields.go +++ b/tools/vendor/github.com/BurntSushi/toml/type_fields.go @@ -25,10 +25,8 @@ type field struct { // breaking ties with index sequence. type byName []field -func (x byName) Len() int { return len(x) } - +func (x byName) Len() int { return len(x) } func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - func (x byName) Less(i, j int) bool { if x[i].name != x[j].name { return x[i].name < x[j].name @@ -45,10 +43,8 @@ func (x byName) Less(i, j int) bool { // byIndex sorts field by index sequence. type byIndex []field -func (x byIndex) Len() int { return len(x) } - +func (x byIndex) Len() int { return len(x) } func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - func (x byIndex) Less(i, j int) bool { for k, xik := range x[i].index { if k >= len(x[j].index) { diff --git a/tools/vendor/github.com/BurntSushi/toml/type_toml.go b/tools/vendor/github.com/BurntSushi/toml/type_toml.go index 4e90d7737..1c090d331 100644 --- a/tools/vendor/github.com/BurntSushi/toml/type_toml.go +++ b/tools/vendor/github.com/BurntSushi/toml/type_toml.go @@ -22,13 +22,8 @@ func typeIsTable(t tomlType) bool { type tomlBaseType string -func (btype tomlBaseType) typeString() string { - return string(btype) -} - -func (btype tomlBaseType) String() string { - return btype.typeString() -} +func (btype tomlBaseType) typeString() string { return string(btype) } +func (btype tomlBaseType) String() string { return btype.typeString() } var ( tomlInteger tomlBaseType = "Integer" @@ -54,7 +49,7 @@ func (p *parser) typeOfPrimitive(lexItem item) tomlType { return tomlFloat case itemDatetime: return tomlDatetime - case itemString: + case itemString, itemStringEsc: return tomlString case itemMultilineString: return tomlString diff --git a/tools/vendor/github.com/mbilski/exhaustivestruct/LICENSE b/tools/vendor/github.com/Crocmagnon/fatcontext/LICENSE similarity index 96% rename from tools/vendor/github.com/mbilski/exhaustivestruct/LICENSE rename to tools/vendor/github.com/Crocmagnon/fatcontext/LICENSE index 893eb73b9..96f153ca4 100644 --- a/tools/vendor/github.com/mbilski/exhaustivestruct/LICENSE +++ b/tools/vendor/github.com/Crocmagnon/fatcontext/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2020 Mateusz Bilski +Copyright (c) 2024 Gabriel Augendre Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/tools/vendor/github.com/Crocmagnon/fatcontext/pkg/analyzer/analyzer.go b/tools/vendor/github.com/Crocmagnon/fatcontext/pkg/analyzer/analyzer.go new file mode 100644 index 000000000..c3be4e981 --- /dev/null +++ b/tools/vendor/github.com/Crocmagnon/fatcontext/pkg/analyzer/analyzer.go @@ -0,0 +1,195 @@ +package analyzer + +import ( + "bytes" + "errors" + "fmt" + "go/ast" + "go/printer" + "go/token" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var Analyzer = &analysis.Analyzer{ + Name: "fatcontext", + Doc: "detects nested contexts in loops", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, +} + +var errUnknown = errors.New("unknown node type") + +func run(pass *analysis.Pass) (interface{}, error) { + inspctr := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + nodeFilter := []ast.Node{ + (*ast.ForStmt)(nil), + (*ast.RangeStmt)(nil), + } + + inspctr.Preorder(nodeFilter, func(node ast.Node) { + body, err := getBody(node) + if err != nil { + return + } + + assignStmt := findNestedContext(pass, body, body.List) + if assignStmt == nil { + return + } + + suggestedStmt := ast.AssignStmt{ + Lhs: assignStmt.Lhs, + TokPos: assignStmt.TokPos, + Tok: token.DEFINE, + Rhs: assignStmt.Rhs, + } + suggested, err := render(pass.Fset, &suggestedStmt) + + var fixes []analysis.SuggestedFix + if err == nil { + fixes = append(fixes, analysis.SuggestedFix{ + Message: "replace `=` with `:=`", + TextEdits: []analysis.TextEdit{ + { + Pos: assignStmt.Pos(), + End: assignStmt.End(), + NewText: []byte(suggested), + }, + }, + }) + } + + pass.Report(analysis.Diagnostic{ + Pos: assignStmt.Pos(), + Message: "nested context in loop", + SuggestedFixes: fixes, + }) + + }) + + return nil, nil +} + +func getBody(node ast.Node) (*ast.BlockStmt, error) { + forStmt, ok := node.(*ast.ForStmt) + if ok { + return forStmt.Body, nil + } + + rangeStmt, ok := node.(*ast.RangeStmt) + if ok { + return rangeStmt.Body, nil + } + + return nil, errUnknown +} + +func findNestedContext(pass *analysis.Pass, block *ast.BlockStmt, stmts []ast.Stmt) *ast.AssignStmt { + for _, stmt := range stmts { + // Recurse if necessary + if inner, ok := stmt.(*ast.BlockStmt); ok { + found := findNestedContext(pass, inner, inner.List) + if found != nil { + return found + } + } + + if inner, ok := stmt.(*ast.IfStmt); ok { + found := findNestedContext(pass, inner.Body, inner.Body.List) + if found != nil { + return found + } + } + + if inner, ok := stmt.(*ast.SwitchStmt); ok { + found := findNestedContext(pass, inner.Body, inner.Body.List) + if found != nil { + return found + } + } + + if inner, ok := stmt.(*ast.CaseClause); ok { + found := findNestedContext(pass, block, inner.Body) + if found != nil { + return found + } + } + + if inner, ok := stmt.(*ast.SelectStmt); ok { + found := findNestedContext(pass, inner.Body, inner.Body.List) + if found != nil { + return found + } + } + + if inner, ok := stmt.(*ast.CommClause); ok { + found := findNestedContext(pass, block, inner.Body) + if found != nil { + return found + } + } + + // Actually check for nested context + assignStmt, ok := stmt.(*ast.AssignStmt) + if !ok { + continue + } + + t := pass.TypesInfo.TypeOf(assignStmt.Lhs[0]) + if t == nil { + continue + } + + if t.String() != "context.Context" { + continue + } + + if assignStmt.Tok == token.DEFINE { + break + } + + // allow assignment to non-pointer children of values defined within the loop + if lhs := getRootIdent(pass, assignStmt.Lhs[0]); lhs != nil { + if obj := pass.TypesInfo.ObjectOf(lhs); obj != nil { + if obj.Pos() >= block.Pos() && obj.Pos() < block.End() { + continue // definition is within the loop + } + } + } + + return assignStmt + } + + return nil +} + +func getRootIdent(pass *analysis.Pass, node ast.Node) *ast.Ident { + for { + switch n := node.(type) { + case *ast.Ident: + return n + case *ast.IndexExpr: + node = n.X + case *ast.SelectorExpr: + if sel, ok := pass.TypesInfo.Selections[n]; ok && sel.Indirect() { + return nil // indirected (pointer) roots don't imply a (safe) copy + } + node = n.X + default: + return nil + } + } +} + +// render returns the pretty-print of the given node +func render(fset *token.FileSet, x interface{}) (string, error) { + var buf bytes.Buffer + if err := printer.Fprint(&buf, fset, x); err != nil { + return "", fmt.Errorf("printing node: %w", err) + } + return buf.String(), nil +} diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/analyzer/analyzer.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/analyzer/analyzer.go index d0cd2d5bb..ec75fd409 100644 --- a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/analyzer/analyzer.go +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/analyzer/analyzer.go @@ -12,16 +12,17 @@ import ( "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" - "github.com/GaijinEntertainment/go-exhaustruct/v3/internal/fields" + "github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment" "github.com/GaijinEntertainment/go-exhaustruct/v3/internal/pattern" + "github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure" ) type analyzer struct { include pattern.List `exhaustruct:"optional"` exclude pattern.List `exhaustruct:"optional"` - fieldsCache map[types.Type]fields.StructFields - fieldsCacheMu sync.RWMutex `exhaustruct:"optional"` + structFields structure.FieldsCache `exhaustruct:"optional"` + comments comment.Cache `exhaustruct:"optional"` typeProcessingNeed map[string]bool typeProcessingNeedMu sync.RWMutex `exhaustruct:"optional"` @@ -29,8 +30,8 @@ type analyzer struct { func NewAnalyzer(include, exclude []string) (*analysis.Analyzer, error) { a := analyzer{ - fieldsCache: make(map[types.Type]fields.StructFields), typeProcessingNeed: make(map[string]bool), + comments: comment.Cache{}, } var err error @@ -74,12 +75,7 @@ Anonymous structs can be matched by '' alias. func (a *analyzer) run(pass *analysis.Pass) (any, error) { insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) //nolint:forcetypeassert - insp.WithStack( - []ast.Node{ - (*ast.CompositeLit)(nil), - }, - a.newVisitor(pass), - ) + insp.WithStack([]ast.Node{(*ast.CompositeLit)(nil)}, a.newVisitor(pass)) return nil, nil //nolint:nilnil } @@ -104,18 +100,18 @@ func (a *analyzer) newVisitor(pass *analysis.Pass) func(n ast.Node, push bool, s if len(lit.Elts) == 0 { if ret, ok := stackParentIsReturn(stack); ok { - if returnContainsNonNilError(pass, ret) { + if returnContainsNonNilError(pass, ret, n) { // it is okay to return uninitialized structure in case struct's direct parent is // a return statement containing non-nil error - // - // we're unable to check if returned error is custom, but at least we're able to - // cover str [error] type. return true } } } - pos, msg := a.processStruct(pass, lit, structTyp, typeInfo) + file := a.comments.Get(pass.Fset, stack[0].(*ast.File)) //nolint:forcetypeassert + rc := getCompositeLitRelatedComments(stack, file) + pos, msg := a.processStruct(pass, lit, structTyp, typeInfo, rc) + if pos != nil { pass.Reportf(*pos, msg) } @@ -124,6 +120,35 @@ func (a *analyzer) newVisitor(pass *analysis.Pass) func(n ast.Node, push bool, s } } +// getCompositeLitRelatedComments returns all comments that are related to checked node. We +// have to traverse the stack manually as ast do not associate comments with +// [ast.CompositeLit]. +func getCompositeLitRelatedComments(stack []ast.Node, cm ast.CommentMap) []*ast.CommentGroup { + comments := make([]*ast.CommentGroup, 0) + + for i := len(stack) - 1; i >= 0; i-- { + node := stack[i] + + switch node.(type) { + case *ast.CompositeLit, // stack[len(stack)-1] + *ast.ReturnStmt, // return ... + *ast.IndexExpr, // map[enum]...{...}[key] + *ast.CallExpr, // myfunc(map...) + *ast.UnaryExpr, // &map... + *ast.AssignStmt, // variable assignment (without var keyword) + *ast.DeclStmt, // var declaration, parent of *ast.GenDecl + *ast.GenDecl, // var declaration, parent of *ast.ValueSpec + *ast.ValueSpec: // var declaration + comments = append(comments, cm[node]...) + + default: + return comments + } + } + + return comments +} + func getStructType(pass *analysis.Pass, lit *ast.CompositeLit) (*types.Struct, *TypeInfo, bool) { switch typ := pass.TypesInfo.TypeOf(lit).(type) { case *types.Named: // named type @@ -156,17 +181,47 @@ func getStructType(pass *analysis.Pass, lit *ast.CompositeLit) (*types.Struct, * func stackParentIsReturn(stack []ast.Node) (*ast.ReturnStmt, bool) { // it is safe to skip boundary check, since stack always has at least one element - // - whole file. - ret, ok := stack[len(stack)-2].(*ast.ReturnStmt) + // we also have no reason to check the first element, since it is always a file + for i := len(stack) - 2; i > 0; i-- { + switch st := stack[i].(type) { + case *ast.ReturnStmt: + return st, true + + case *ast.UnaryExpr: + // in case we're dealing with pointers - it is still viable to check pointer's + // parent for return statement + continue + + default: + return nil, false + } + } - return ret, ok + return nil, false } -func returnContainsNonNilError(pass *analysis.Pass, ret *ast.ReturnStmt) bool { +// errorIface is a type that represents [error] interface and all types will be +// compared against. +var errorIface = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) + +func returnContainsNonNilError(pass *analysis.Pass, ret *ast.ReturnStmt, except ast.Node) bool { // errors are mostly located at the end of return statement, so we're starting // from the end. for i := len(ret.Results) - 1; i >= 0; i-- { - if pass.TypesInfo.TypeOf(ret.Results[i]).String() == "error" { + ri := ret.Results[i] + + // skip current node + if ri == except { + continue + } + + if un, ok := ri.(*ast.UnaryExpr); ok { + if un.X == except { + continue + } + } + + if types.Implements(pass.TypesInfo.TypeOf(ri), errorIface) { return true } } @@ -179,8 +234,15 @@ func (a *analyzer) processStruct( lit *ast.CompositeLit, structTyp *types.Struct, info *TypeInfo, + comments []*ast.CommentGroup, ) (*token.Pos, string) { - if !a.shouldProcessType(info) { + shouldProcess := a.shouldProcessType(info) + + if shouldProcess && comment.HasDirective(comments, comment.DirectiveIgnore) { + return nil, "" + } + + if !shouldProcess && !comment.HasDirective(comments, comment.DirectiveEnforce) { return nil, "" } @@ -233,24 +295,12 @@ func (a *analyzer) shouldProcessType(info *TypeInfo) bool { return res } -//revive:disable-next-line:unused-receiver func (a *analyzer) litSkippedFields( lit *ast.CompositeLit, typ *types.Struct, onlyExported bool, -) fields.StructFields { - a.fieldsCacheMu.RLock() - f, ok := a.fieldsCache[typ] - a.fieldsCacheMu.RUnlock() - - if !ok { - a.fieldsCacheMu.Lock() - f = fields.NewStructFields(typ) - a.fieldsCache[typ] = f - a.fieldsCacheMu.Unlock() - } - - return f.SkippedFields(lit, onlyExported) +) structure.Fields { + return a.structFields.Get(typ).Skipped(lit, onlyExported) } type TypeInfo struct { diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/cache.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/cache.go new file mode 100644 index 000000000..88edef638 --- /dev/null +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/cache.go @@ -0,0 +1,35 @@ +package comment + +import ( + "go/ast" + "go/token" + "sync" +) + +type Cache struct { + comments map[*ast.File]ast.CommentMap + mu sync.RWMutex +} + +// Get returns a comment map for a given file. In case if a comment map is not +// found, it creates a new one. +func (c *Cache) Get(fset *token.FileSet, f *ast.File) ast.CommentMap { + c.mu.RLock() + if cm, ok := c.comments[f]; ok { + c.mu.RUnlock() + return cm + } + c.mu.RUnlock() + + c.mu.Lock() + defer c.mu.Unlock() + + if c.comments == nil { + c.comments = make(map[*ast.File]ast.CommentMap) + } + + cm := ast.NewCommentMap(fset, f, f.Comments) + c.comments[f] = cm + + return cm +} diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/directive.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/directive.go new file mode 100644 index 000000000..a39a8076f --- /dev/null +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment/directive.go @@ -0,0 +1,28 @@ +package comment + +import ( + "go/ast" + "strings" +) + +type Directive string + +const ( + prefix = `//exhaustruct:` + DirectiveIgnore Directive = prefix + `ignore` + DirectiveEnforce Directive = prefix + `enforce` +) + +// HasDirective parses a directive from a given list of comments. +// If no directive is found, the second return value is `false`. +func HasDirective(comments []*ast.CommentGroup, expected Directive) bool { + for _, cg := range comments { + for _, commentLine := range cg.List { + if strings.HasPrefix(commentLine.Text, string(expected)) { + return true + } + } + } + + return false +} diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure/fields-cache.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure/fields-cache.go new file mode 100644 index 000000000..12a379692 --- /dev/null +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure/fields-cache.go @@ -0,0 +1,35 @@ +package structure + +import ( + "go/types" + "sync" +) + +type FieldsCache struct { + fields map[*types.Struct]Fields + mu sync.RWMutex +} + +// Get returns a struct fields for a given type. In case if a struct fields is +// not found, it creates a new one from type definition. +func (c *FieldsCache) Get(typ *types.Struct) Fields { + c.mu.RLock() + fields, ok := c.fields[typ] + c.mu.RUnlock() + + if ok { + return fields + } + + c.mu.Lock() + defer c.mu.Unlock() + + if c.fields == nil { + c.fields = make(map[*types.Struct]Fields) + } + + fields = NewFields(typ) + c.fields[typ] = fields + + return fields +} diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/fields/struct.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure/fields.go similarity index 64% rename from tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/fields/struct.go rename to tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure/fields.go index af2390e87..b6b1a48c8 100644 --- a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/fields/struct.go +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure/fields.go @@ -1,33 +1,34 @@ -package fields +package structure import ( "go/ast" "go/types" "reflect" + "strings" ) const ( - TagName = "exhaustruct" - OptionalTagValue = "optional" + tagName = "exhaustruct" + optionalTagValue = "optional" ) -type StructField struct { +type Field struct { Name string Exported bool Optional bool } -type StructFields []*StructField +type Fields []*Field -// NewStructFields creates a new [StructFields] from a given struct type. -// StructFields items are listed in order they appear in the struct. -func NewStructFields(strct *types.Struct) StructFields { - sf := make(StructFields, 0, strct.NumFields()) +// NewFields creates a new [Fields] from a given struct type. +// Fields items are listed in order they appear in the struct. +func NewFields(strct *types.Struct) Fields { + sf := make(Fields, 0, strct.NumFields()) for i := 0; i < strct.NumFields(); i++ { f := strct.Field(i) - sf = append(sf, &StructField{ + sf = append(sf, &Field{ Name: f.Name(), Exported: f.Exported(), Optional: HasOptionalTag(strct.Tag(i)), @@ -38,27 +39,29 @@ func NewStructFields(strct *types.Struct) StructFields { } func HasOptionalTag(tags string) bool { - return reflect.StructTag(tags).Get(TagName) == OptionalTagValue + return reflect.StructTag(tags).Get(tagName) == optionalTagValue } // String returns a comma-separated list of field names. -func (sf StructFields) String() (res string) { +func (sf Fields) String() string { + b := strings.Builder{} + for i := 0; i < len(sf); i++ { - if res != "" { - res += ", " + if b.Len() != 0 { + b.WriteString(", ") } - res += sf[i].Name + b.WriteString(sf[i].Name) } - return res + return b.String() } -// SkippedFields returns a list of fields that are not present in the given +// Skipped returns a list of fields that are not present in the given // literal, but expected to. // //revive:disable-next-line:cyclomatic -func (sf StructFields) SkippedFields(lit *ast.CompositeLit, onlyExported bool) StructFields { +func (sf Fields) Skipped(lit *ast.CompositeLit, onlyExported bool) Fields { if len(lit.Elts) != 0 && !isNamedLiteral(lit) { if len(lit.Elts) == len(sf) { return nil @@ -68,7 +71,7 @@ func (sf StructFields) SkippedFields(lit *ast.CompositeLit, onlyExported bool) S } em := sf.existenceMap() - res := make(StructFields, 0, len(sf)) + res := make(Fields, 0, len(sf)) for i := 0; i < len(lit.Elts); i++ { kv, ok := lit.Elts[i].(*ast.KeyValueExpr) @@ -99,7 +102,7 @@ func (sf StructFields) SkippedFields(lit *ast.CompositeLit, onlyExported bool) S return res } -func (sf StructFields) existenceMap() map[string]bool { +func (sf Fields) existenceMap() map[string]bool { m := make(map[string]bool, len(sf)) for i := 0; i < len(sf); i++ { diff --git a/tools/vendor/github.com/Masterminds/semver/.travis.yml b/tools/vendor/github.com/Masterminds/semver/.travis.yml deleted file mode 100644 index 096369d44..000000000 --- a/tools/vendor/github.com/Masterminds/semver/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -language: go - -go: - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - tip - -# Setting sudo access to false will let Travis CI use containers rather than -# VMs to run the tests. For more details see: -# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ -# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ -sudo: false - -script: - - make setup - - make test - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/06e3328629952dabe3e0 - on_success: change # options: [always|never|change] default: always - on_failure: always # options: [always|never|change] default: always - on_start: never # options: [always|never|change] default: always diff --git a/tools/vendor/github.com/Masterminds/semver/CHANGELOG.md b/tools/vendor/github.com/Masterminds/semver/CHANGELOG.md deleted file mode 100644 index e405c9a84..000000000 --- a/tools/vendor/github.com/Masterminds/semver/CHANGELOG.md +++ /dev/null @@ -1,109 +0,0 @@ -# 1.5.0 (2019-09-11) - -## Added - -- #103: Add basic fuzzing for `NewVersion()` (thanks @jesse-c) - -## Changed - -- #82: Clarify wildcard meaning in range constraints and update tests for it (thanks @greysteil) -- #83: Clarify caret operator range for pre-1.0.0 dependencies (thanks @greysteil) -- #72: Adding docs comment pointing to vert for a cli -- #71: Update the docs on pre-release comparator handling -- #89: Test with new go versions (thanks @thedevsaddam) -- #87: Added $ to ValidPrerelease for better validation (thanks @jeremycarroll) - -## Fixed - -- #78: Fix unchecked error in example code (thanks @ravron) -- #70: Fix the handling of pre-releases and the 0.0.0 release edge case -- #97: Fixed copyright file for proper display on GitHub -- #107: Fix handling prerelease when sorting alphanum and num -- #109: Fixed where Validate sometimes returns wrong message on error - -# 1.4.2 (2018-04-10) - -## Changed -- #72: Updated the docs to point to vert for a console appliaction -- #71: Update the docs on pre-release comparator handling - -## Fixed -- #70: Fix the handling of pre-releases and the 0.0.0 release edge case - -# 1.4.1 (2018-04-02) - -## Fixed -- Fixed #64: Fix pre-release precedence issue (thanks @uudashr) - -# 1.4.0 (2017-10-04) - -## Changed -- #61: Update NewVersion to parse ints with a 64bit int size (thanks @zknill) - -# 1.3.1 (2017-07-10) - -## Fixed -- Fixed #57: number comparisons in prerelease sometimes inaccurate - -# 1.3.0 (2017-05-02) - -## Added -- #45: Added json (un)marshaling support (thanks @mh-cbon) -- Stability marker. See https://masterminds.github.io/stability/ - -## Fixed -- #51: Fix handling of single digit tilde constraint (thanks @dgodd) - -## Changed -- #55: The godoc icon moved from png to svg - -# 1.2.3 (2017-04-03) - -## Fixed -- #46: Fixed 0.x.x and 0.0.x in constraints being treated as * - -# Release 1.2.2 (2016-12-13) - -## Fixed -- #34: Fixed issue where hyphen range was not working with pre-release parsing. - -# Release 1.2.1 (2016-11-28) - -## Fixed -- #24: Fixed edge case issue where constraint "> 0" does not handle "0.0.1-alpha" - properly. - -# Release 1.2.0 (2016-11-04) - -## Added -- #20: Added MustParse function for versions (thanks @adamreese) -- #15: Added increment methods on versions (thanks @mh-cbon) - -## Fixed -- Issue #21: Per the SemVer spec (section 9) a pre-release is unstable and - might not satisfy the intended compatibility. The change here ignores pre-releases - on constraint checks (e.g., ~ or ^) when a pre-release is not part of the - constraint. For example, `^1.2.3` will ignore pre-releases while - `^1.2.3-alpha` will include them. - -# Release 1.1.1 (2016-06-30) - -## Changed -- Issue #9: Speed up version comparison performance (thanks @sdboyer) -- Issue #8: Added benchmarks (thanks @sdboyer) -- Updated Go Report Card URL to new location -- Updated Readme to add code snippet formatting (thanks @mh-cbon) -- Updating tagging to v[SemVer] structure for compatibility with other tools. - -# Release 1.1.0 (2016-03-11) - -- Issue #2: Implemented validation to provide reasons a versions failed a - constraint. - -# Release 1.0.1 (2015-12-31) - -- Fixed #1: * constraint failing on valid versions. - -# Release 1.0.0 (2015-10-20) - -- Initial release diff --git a/tools/vendor/github.com/Masterminds/semver/Makefile b/tools/vendor/github.com/Masterminds/semver/Makefile deleted file mode 100644 index a7a1b4e36..000000000 --- a/tools/vendor/github.com/Masterminds/semver/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -.PHONY: setup -setup: - go get -u gopkg.in/alecthomas/gometalinter.v1 - gometalinter.v1 --install - -.PHONY: test -test: validate lint - @echo "==> Running tests" - go test -v - -.PHONY: validate -validate: - @echo "==> Running static validations" - @gometalinter.v1 \ - --disable-all \ - --enable deadcode \ - --severity deadcode:error \ - --enable gofmt \ - --enable gosimple \ - --enable ineffassign \ - --enable misspell \ - --enable vet \ - --tests \ - --vendor \ - --deadline 60s \ - ./... || exit_code=1 - -.PHONY: lint -lint: - @echo "==> Running linters" - @gometalinter.v1 \ - --disable-all \ - --enable golint \ - --vendor \ - --deadline 60s \ - ./... || : diff --git a/tools/vendor/github.com/Masterminds/semver/README.md b/tools/vendor/github.com/Masterminds/semver/README.md deleted file mode 100644 index 1b52d2f43..000000000 --- a/tools/vendor/github.com/Masterminds/semver/README.md +++ /dev/null @@ -1,194 +0,0 @@ -# SemVer - -The `semver` package provides the ability to work with [Semantic Versions](http://semver.org) in Go. Specifically it provides the ability to: - -* Parse semantic versions -* Sort semantic versions -* Check if a semantic version fits within a set of constraints -* Optionally work with a `v` prefix - -[![Stability: -Active](https://masterminds.github.io/stability/active.svg)](https://masterminds.github.io/stability/active.html) -[![Build Status](https://travis-ci.org/Masterminds/semver.svg)](https://travis-ci.org/Masterminds/semver) [![Build status](https://ci.appveyor.com/api/projects/status/jfk66lib7hb985k8/branch/master?svg=true&passingText=windows%20build%20passing&failingText=windows%20build%20failing)](https://ci.appveyor.com/project/mattfarina/semver/branch/master) [![GoDoc](https://godoc.org/github.com/Masterminds/semver?status.svg)](https://godoc.org/github.com/Masterminds/semver) [![Go Report Card](https://goreportcard.com/badge/github.com/Masterminds/semver)](https://goreportcard.com/report/github.com/Masterminds/semver) - -If you are looking for a command line tool for version comparisons please see -[vert](https://github.com/Masterminds/vert) which uses this library. - -## Parsing Semantic Versions - -To parse a semantic version use the `NewVersion` function. For example, - -```go - v, err := semver.NewVersion("1.2.3-beta.1+build345") -``` - -If there is an error the version wasn't parseable. The version object has methods -to get the parts of the version, compare it to other versions, convert the -version back into a string, and get the original string. For more details -please see the [documentation](https://godoc.org/github.com/Masterminds/semver). - -## Sorting Semantic Versions - -A set of versions can be sorted using the [`sort`](https://golang.org/pkg/sort/) -package from the standard library. For example, - -```go - raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} - vs := make([]*semver.Version, len(raw)) - for i, r := range raw { - v, err := semver.NewVersion(r) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - vs[i] = v - } - - sort.Sort(semver.Collection(vs)) -``` - -## Checking Version Constraints - -Checking a version against version constraints is one of the most featureful -parts of the package. - -```go - c, err := semver.NewConstraint(">= 1.2.3") - if err != nil { - // Handle constraint not being parseable. - } - - v, _ := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parseable. - } - // Check if the version meets the constraints. The a variable will be true. - a := c.Check(v) -``` - -## Basic Comparisons - -There are two elements to the comparisons. First, a comparison string is a list -of comma separated and comparisons. These are then separated by || separated or -comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a -comparison that's greater than or equal to 1.2 and less than 3.0.0 or is -greater than or equal to 4.2.3. - -The basic comparisons are: - -* `=`: equal (aliased to no operator) -* `!=`: not equal -* `>`: greater than -* `<`: less than -* `>=`: greater than or equal to -* `<=`: less than or equal to - -## Working With Pre-release Versions - -Pre-releases, for those not familiar with them, are used for software releases -prior to stable or generally available releases. Examples of pre-releases include -development, alpha, beta, and release candidate releases. A pre-release may be -a version such as `1.2.3-beta.1` while the stable release would be `1.2.3`. In the -order of precidence, pre-releases come before their associated releases. In this -example `1.2.3-beta.1 < 1.2.3`. - -According to the Semantic Version specification pre-releases may not be -API compliant with their release counterpart. It says, - -> A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. - -SemVer comparisons without a pre-release comparator will skip pre-release versions. -For example, `>=1.2.3` will skip pre-releases when looking at a list of releases -while `>=1.2.3-0` will evaluate and find pre-releases. - -The reason for the `0` as a pre-release version in the example comparison is -because pre-releases can only contain ASCII alphanumerics and hyphens (along with -`.` separators), per the spec. Sorting happens in ASCII sort order, again per the spec. The lowest character is a `0` in ASCII sort order (see an [ASCII Table](http://www.asciitable.com/)) - -Understanding ASCII sort ordering is important because A-Z comes before a-z. That -means `>=1.2.3-BETA` will return `1.2.3-alpha`. What you might expect from case -sensitivity doesn't apply here. This is due to ASCII sort ordering which is what -the spec specifies. - -## Hyphen Range Comparisons - -There are multiple methods to handle ranges and the first is hyphens ranges. -These look like: - -* `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` -* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` - -## Wildcards In Comparisons - -The `x`, `X`, and `*` characters can be used as a wildcard character. This works -for all comparison operators. When used on the `=` operator it falls -back to the pack level comparison (see tilde below). For example, - -* `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` -* `>= 1.2.x` is equivalent to `>= 1.2.0` -* `<= 2.x` is equivalent to `< 3` -* `*` is equivalent to `>= 0.0.0` - -## Tilde Range Comparisons (Patch) - -The tilde (`~`) comparison operator is for patch level ranges when a minor -version is specified and major level changes when the minor number is missing. -For example, - -* `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` -* `~1` is equivalent to `>= 1, < 2` -* `~2.3` is equivalent to `>= 2.3, < 2.4` -* `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` -* `~1.x` is equivalent to `>= 1, < 2` - -## Caret Range Comparisons (Major) - -The caret (`^`) comparison operator is for major level changes. This is useful -when comparisons of API versions as a major change is API breaking. For example, - -* `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` -* `^0.0.1` is equivalent to `>= 0.0.1, < 1.0.0` -* `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` -* `^2.3` is equivalent to `>= 2.3, < 3` -* `^2.x` is equivalent to `>= 2.0.0, < 3` - -# Validation - -In addition to testing a version against a constraint, a version can be validated -against a constraint. When validation fails a slice of errors containing why a -version didn't meet the constraint is returned. For example, - -```go - c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") - if err != nil { - // Handle constraint not being parseable. - } - - v, _ := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parseable. - } - - // Validate a version against a constraint. - a, msgs := c.Validate(v) - // a is false - for _, m := range msgs { - fmt.Println(m) - - // Loops over the errors which would read - // "1.3 is greater than 1.2.3" - // "1.3 is less than 1.4" - } -``` - -# Fuzzing - - [dvyukov/go-fuzz](https://github.com/dvyukov/go-fuzz) is used for fuzzing. - -1. `go-fuzz-build` -2. `go-fuzz -workdir=fuzz` - -# Contribute - -If you find an issue or want to contribute please file an [issue](https://github.com/Masterminds/semver/issues) -or [create a pull request](https://github.com/Masterminds/semver/pulls). diff --git a/tools/vendor/github.com/Masterminds/semver/appveyor.yml b/tools/vendor/github.com/Masterminds/semver/appveyor.yml deleted file mode 100644 index b2778df15..000000000 --- a/tools/vendor/github.com/Masterminds/semver/appveyor.yml +++ /dev/null @@ -1,44 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\Masterminds\semver -shallow_clone: true - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -install: - - go version - - go env - - go get -u gopkg.in/alecthomas/gometalinter.v1 - - set PATH=%PATH%;%GOPATH%\bin - - gometalinter.v1.exe --install - -build_script: - - go install -v ./... - -test_script: - - "gometalinter.v1 \ - --disable-all \ - --enable deadcode \ - --severity deadcode:error \ - --enable gofmt \ - --enable gosimple \ - --enable ineffassign \ - --enable misspell \ - --enable vet \ - --tests \ - --vendor \ - --deadline 60s \ - ./... || exit_code=1" - - "gometalinter.v1 \ - --disable-all \ - --enable golint \ - --vendor \ - --deadline 60s \ - ./... || :" - - go test -v - -deploy: off diff --git a/tools/vendor/github.com/Masterminds/semver/constraints.go b/tools/vendor/github.com/Masterminds/semver/constraints.go deleted file mode 100644 index b94b93413..000000000 --- a/tools/vendor/github.com/Masterminds/semver/constraints.go +++ /dev/null @@ -1,423 +0,0 @@ -package semver - -import ( - "errors" - "fmt" - "regexp" - "strings" -) - -// Constraints is one or more constraint that a semantic version can be -// checked against. -type Constraints struct { - constraints [][]*constraint -} - -// NewConstraint returns a Constraints instance that a Version instance can -// be checked against. If there is a parse error it will be returned. -func NewConstraint(c string) (*Constraints, error) { - - // Rewrite - ranges into a comparison operation. - c = rewriteRange(c) - - ors := strings.Split(c, "||") - or := make([][]*constraint, len(ors)) - for k, v := range ors { - cs := strings.Split(v, ",") - result := make([]*constraint, len(cs)) - for i, s := range cs { - pc, err := parseConstraint(s) - if err != nil { - return nil, err - } - - result[i] = pc - } - or[k] = result - } - - o := &Constraints{constraints: or} - return o, nil -} - -// Check tests if a version satisfies the constraints. -func (cs Constraints) Check(v *Version) bool { - // loop over the ORs and check the inner ANDs - for _, o := range cs.constraints { - joy := true - for _, c := range o { - if !c.check(v) { - joy = false - break - } - } - - if joy { - return true - } - } - - return false -} - -// Validate checks if a version satisfies a constraint. If not a slice of -// reasons for the failure are returned in addition to a bool. -func (cs Constraints) Validate(v *Version) (bool, []error) { - // loop over the ORs and check the inner ANDs - var e []error - - // Capture the prerelease message only once. When it happens the first time - // this var is marked - var prerelesase bool - for _, o := range cs.constraints { - joy := true - for _, c := range o { - // Before running the check handle the case there the version is - // a prerelease and the check is not searching for prereleases. - if c.con.pre == "" && v.pre != "" { - if !prerelesase { - em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - e = append(e, em) - prerelesase = true - } - joy = false - - } else { - - if !c.check(v) { - em := fmt.Errorf(c.msg, v, c.orig) - e = append(e, em) - joy = false - } - } - } - - if joy { - return true, []error{} - } - } - - return false, e -} - -var constraintOps map[string]cfunc -var constraintMsg map[string]string -var constraintRegex *regexp.Regexp - -func init() { - constraintOps = map[string]cfunc{ - "": constraintTildeOrEqual, - "=": constraintTildeOrEqual, - "!=": constraintNotEqual, - ">": constraintGreaterThan, - "<": constraintLessThan, - ">=": constraintGreaterThanEqual, - "=>": constraintGreaterThanEqual, - "<=": constraintLessThanEqual, - "=<": constraintLessThanEqual, - "~": constraintTilde, - "~>": constraintTilde, - "^": constraintCaret, - } - - constraintMsg = map[string]string{ - "": "%s is not equal to %s", - "=": "%s is not equal to %s", - "!=": "%s is equal to %s", - ">": "%s is less than or equal to %s", - "<": "%s is greater than or equal to %s", - ">=": "%s is less than %s", - "=>": "%s is less than %s", - "<=": "%s is greater than %s", - "=<": "%s is greater than %s", - "~": "%s does not have same major and minor version as %s", - "~>": "%s does not have same major and minor version as %s", - "^": "%s does not have same major version as %s", - } - - ops := make([]string, 0, len(constraintOps)) - for k := range constraintOps { - ops = append(ops, regexp.QuoteMeta(k)) - } - - constraintRegex = regexp.MustCompile(fmt.Sprintf( - `^\s*(%s)\s*(%s)\s*$`, - strings.Join(ops, "|"), - cvRegex)) - - constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( - `\s*(%s)\s+-\s+(%s)\s*`, - cvRegex, cvRegex)) -} - -// An individual constraint -type constraint struct { - // The callback function for the restraint. It performs the logic for - // the constraint. - function cfunc - - msg string - - // The version used in the constraint check. For example, if a constraint - // is '<= 2.0.0' the con a version instance representing 2.0.0. - con *Version - - // The original parsed version (e.g., 4.x from != 4.x) - orig string - - // When an x is used as part of the version (e.g., 1.x) - minorDirty bool - dirty bool - patchDirty bool -} - -// Check if a version meets the constraint -func (c *constraint) check(v *Version) bool { - return c.function(v, c) -} - -type cfunc func(v *Version, c *constraint) bool - -func parseConstraint(c string) (*constraint, error) { - m := constraintRegex.FindStringSubmatch(c) - if m == nil { - return nil, fmt.Errorf("improper constraint: %s", c) - } - - ver := m[2] - orig := ver - minorDirty := false - patchDirty := false - dirty := false - if isX(m[3]) { - ver = "0.0.0" - dirty = true - } else if isX(strings.TrimPrefix(m[4], ".")) || m[4] == "" { - minorDirty = true - dirty = true - ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) - } else if isX(strings.TrimPrefix(m[5], ".")) { - dirty = true - patchDirty = true - ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) - } - - con, err := NewVersion(ver) - if err != nil { - - // The constraintRegex should catch any regex parsing errors. So, - // we should never get here. - return nil, errors.New("constraint Parser Error") - } - - cs := &constraint{ - function: constraintOps[m[1]], - msg: constraintMsg[m[1]], - con: con, - orig: orig, - minorDirty: minorDirty, - patchDirty: patchDirty, - dirty: dirty, - } - return cs, nil -} - -// Constraint functions -func constraintNotEqual(v *Version, c *constraint) bool { - if c.dirty { - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if c.con.Major() != v.Major() { - return true - } - if c.con.Minor() != v.Minor() && !c.minorDirty { - return true - } else if c.minorDirty { - return false - } - - return false - } - - return !v.Equal(c.con) -} - -func constraintGreaterThan(v *Version, c *constraint) bool { - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - return v.Compare(c.con) == 1 -} - -func constraintLessThan(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if !c.dirty { - return v.Compare(c.con) < 0 - } - - if v.Major() > c.con.Major() { - return false - } else if v.Minor() > c.con.Minor() && !c.minorDirty { - return false - } - - return true -} - -func constraintGreaterThanEqual(v *Version, c *constraint) bool { - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - return v.Compare(c.con) >= 0 -} - -func constraintLessThanEqual(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if !c.dirty { - return v.Compare(c.con) <= 0 - } - - if v.Major() > c.con.Major() { - return false - } else if v.Minor() > c.con.Minor() && !c.minorDirty { - return false - } - - return true -} - -// ~*, ~>* --> >= 0.0.0 (any) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0 -func constraintTilde(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if v.LessThan(c.con) { - return false - } - - // ~0.0.0 is a special case where all constraints are accepted. It's - // equivalent to >= 0.0.0. - if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 && - !c.minorDirty && !c.patchDirty { - return true - } - - if v.Major() != c.con.Major() { - return false - } - - if v.Minor() != c.con.Minor() && !c.minorDirty { - return false - } - - return true -} - -// When there is a .x (dirty) status it automatically opts in to ~. Otherwise -// it's a straight = -func constraintTildeOrEqual(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if c.dirty { - c.msg = constraintMsg["~"] - return constraintTilde(v, c) - } - - return v.Equal(c.con) -} - -// ^* --> (any) -// ^2, ^2.x, ^2.x.x --> >=2.0.0, <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0, <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0, <2.0.0 -// ^1.2.3 --> >=1.2.3, <2.0.0 -// ^1.2.0 --> >=1.2.0, <2.0.0 -func constraintCaret(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if v.LessThan(c.con) { - return false - } - - if v.Major() != c.con.Major() { - return false - } - - return true -} - -var constraintRangeRegex *regexp.Regexp - -const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + - `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + - `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` - -func isX(x string) bool { - switch x { - case "x", "*", "X": - return true - default: - return false - } -} - -func rewriteRange(i string) string { - m := constraintRangeRegex.FindAllStringSubmatch(i, -1) - if m == nil { - return i - } - o := i - for _, v := range m { - t := fmt.Sprintf(">= %s, <= %s", v[1], v[11]) - o = strings.Replace(o, v[0], t, 1) - } - - return o -} diff --git a/tools/vendor/github.com/Masterminds/semver/doc.go b/tools/vendor/github.com/Masterminds/semver/doc.go deleted file mode 100644 index 6a6c24c6d..000000000 --- a/tools/vendor/github.com/Masterminds/semver/doc.go +++ /dev/null @@ -1,115 +0,0 @@ -/* -Package semver provides the ability to work with Semantic Versions (http://semver.org) in Go. - -Specifically it provides the ability to: - - * Parse semantic versions - * Sort semantic versions - * Check if a semantic version fits within a set of constraints - * Optionally work with a `v` prefix - -Parsing Semantic Versions - -To parse a semantic version use the `NewVersion` function. For example, - - v, err := semver.NewVersion("1.2.3-beta.1+build345") - -If there is an error the version wasn't parseable. The version object has methods -to get the parts of the version, compare it to other versions, convert the -version back into a string, and get the original string. For more details -please see the documentation at https://godoc.org/github.com/Masterminds/semver. - -Sorting Semantic Versions - -A set of versions can be sorted using the `sort` package from the standard library. -For example, - - raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} - vs := make([]*semver.Version, len(raw)) - for i, r := range raw { - v, err := semver.NewVersion(r) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - vs[i] = v - } - - sort.Sort(semver.Collection(vs)) - -Checking Version Constraints - -Checking a version against version constraints is one of the most featureful -parts of the package. - - c, err := semver.NewConstraint(">= 1.2.3") - if err != nil { - // Handle constraint not being parseable. - } - - v, err := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parseable. - } - // Check if the version meets the constraints. The a variable will be true. - a := c.Check(v) - -Basic Comparisons - -There are two elements to the comparisons. First, a comparison string is a list -of comma separated and comparisons. These are then separated by || separated or -comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a -comparison that's greater than or equal to 1.2 and less than 3.0.0 or is -greater than or equal to 4.2.3. - -The basic comparisons are: - - * `=`: equal (aliased to no operator) - * `!=`: not equal - * `>`: greater than - * `<`: less than - * `>=`: greater than or equal to - * `<=`: less than or equal to - -Hyphen Range Comparisons - -There are multiple methods to handle ranges and the first is hyphens ranges. -These look like: - - * `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` - * `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` - -Wildcards In Comparisons - -The `x`, `X`, and `*` characters can be used as a wildcard character. This works -for all comparison operators. When used on the `=` operator it falls -back to the pack level comparison (see tilde below). For example, - - * `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` - * `>= 1.2.x` is equivalent to `>= 1.2.0` - * `<= 2.x` is equivalent to `<= 3` - * `*` is equivalent to `>= 0.0.0` - -Tilde Range Comparisons (Patch) - -The tilde (`~`) comparison operator is for patch level ranges when a minor -version is specified and major level changes when the minor number is missing. -For example, - - * `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` - * `~1` is equivalent to `>= 1, < 2` - * `~2.3` is equivalent to `>= 2.3, < 2.4` - * `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` - * `~1.x` is equivalent to `>= 1, < 2` - -Caret Range Comparisons (Major) - -The caret (`^`) comparison operator is for major level changes. This is useful -when comparisons of API versions as a major change is API breaking. For example, - - * `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` - * `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` - * `^2.3` is equivalent to `>= 2.3, < 3` - * `^2.x` is equivalent to `>= 2.0.0, < 3` -*/ -package semver diff --git a/tools/vendor/github.com/Masterminds/semver/v3/.gitignore b/tools/vendor/github.com/Masterminds/semver/v3/.gitignore new file mode 100644 index 000000000..6b061e617 --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/.gitignore @@ -0,0 +1 @@ +_fuzz/ \ No newline at end of file diff --git a/tools/vendor/github.com/Masterminds/semver/v3/.golangci.yml b/tools/vendor/github.com/Masterminds/semver/v3/.golangci.yml new file mode 100644 index 000000000..fbc633259 --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/.golangci.yml @@ -0,0 +1,27 @@ +run: + deadline: 2m + +linters: + disable-all: true + enable: + - misspell + - govet + - staticcheck + - errcheck + - unparam + - ineffassign + - nakedret + - gocyclo + - dupl + - goimports + - revive + - gosec + - gosimple + - typecheck + - unused + +linters-settings: + gofmt: + simplify: true + dupl: + threshold: 600 diff --git a/tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md b/tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md new file mode 100644 index 000000000..f12626423 --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md @@ -0,0 +1,214 @@ +# Changelog + +## 3.2.0 (2022-11-28) + +### Added + +- #190: Added text marshaling and unmarshaling +- #167: Added JSON marshalling for constraints (thanks @SimonTheLeg) +- #173: Implement encoding.TextMarshaler and encoding.TextUnmarshaler on Version (thanks @MarkRosemaker) +- #179: Added New() version constructor (thanks @kazhuravlev) + +### Changed + +- #182/#183: Updated CI testing setup + +### Fixed + +- #186: Fixing issue where validation of constraint section gave false positives +- #176: Fix constraints check with *-0 (thanks @mtt0) +- #181: Fixed Caret operator (^) gives unexpected results when the minor version in constraint is 0 (thanks @arshchimni) +- #161: Fixed godoc (thanks @afirth) + +## 3.1.1 (2020-11-23) + +### Fixed + +- #158: Fixed issue with generated regex operation order that could cause problem + +## 3.1.0 (2020-04-15) + +### Added + +- #131: Add support for serializing/deserializing SQL (thanks @ryancurrah) + +### Changed + +- #148: More accurate validation messages on constraints + +## 3.0.3 (2019-12-13) + +### Fixed + +- #141: Fixed issue with <= comparison + +## 3.0.2 (2019-11-14) + +### Fixed + +- #134: Fixed broken constraint checking with ^0.0 (thanks @krmichelos) + +## 3.0.1 (2019-09-13) + +### Fixed + +- #125: Fixes issue with module path for v3 + +## 3.0.0 (2019-09-12) + +This is a major release of the semver package which includes API changes. The Go +API is compatible with ^1. The Go API was not changed because many people are using +`go get` without Go modules for their applications and API breaking changes cause +errors which we have or would need to support. + +The changes in this release are the handling based on the data passed into the +functions. These are described in the added and changed sections below. + +### Added + +- StrictNewVersion function. This is similar to NewVersion but will return an + error if the version passed in is not a strict semantic version. For example, + 1.2.3 would pass but v1.2.3 or 1.2 would fail because they are not strictly + speaking semantic versions. This function is faster, performs fewer operations, + and uses fewer allocations than NewVersion. +- Fuzzing has been performed on NewVersion, StrictNewVersion, and NewConstraint. + The Makefile contains the operations used. For more information on you can start + on Wikipedia at https://en.wikipedia.org/wiki/Fuzzing +- Now using Go modules + +### Changed + +- NewVersion has proper prerelease and metadata validation with error messages + to signal an issue with either of them +- ^ now operates using a similar set of rules to npm/js and Rust/Cargo. If the + version is >=1 the ^ ranges works the same as v1. For major versions of 0 the + rules have changed. The minor version is treated as the stable version unless + a patch is specified and then it is equivalent to =. One difference from npm/js + is that prereleases there are only to a specific version (e.g. 1.2.3). + Prereleases here look over multiple versions and follow semantic version + ordering rules. This pattern now follows along with the expected and requested + handling of this packaged by numerous users. + +## 1.5.0 (2019-09-11) + +### Added + +- #103: Add basic fuzzing for `NewVersion()` (thanks @jesse-c) + +### Changed + +- #82: Clarify wildcard meaning in range constraints and update tests for it (thanks @greysteil) +- #83: Clarify caret operator range for pre-1.0.0 dependencies (thanks @greysteil) +- #72: Adding docs comment pointing to vert for a cli +- #71: Update the docs on pre-release comparator handling +- #89: Test with new go versions (thanks @thedevsaddam) +- #87: Added $ to ValidPrerelease for better validation (thanks @jeremycarroll) + +### Fixed + +- #78: Fix unchecked error in example code (thanks @ravron) +- #70: Fix the handling of pre-releases and the 0.0.0 release edge case +- #97: Fixed copyright file for proper display on GitHub +- #107: Fix handling prerelease when sorting alphanum and num +- #109: Fixed where Validate sometimes returns wrong message on error + +## 1.4.2 (2018-04-10) + +### Changed + +- #72: Updated the docs to point to vert for a console appliaction +- #71: Update the docs on pre-release comparator handling + +### Fixed + +- #70: Fix the handling of pre-releases and the 0.0.0 release edge case + +## 1.4.1 (2018-04-02) + +### Fixed + +- Fixed #64: Fix pre-release precedence issue (thanks @uudashr) + +## 1.4.0 (2017-10-04) + +### Changed + +- #61: Update NewVersion to parse ints with a 64bit int size (thanks @zknill) + +## 1.3.1 (2017-07-10) + +### Fixed + +- Fixed #57: number comparisons in prerelease sometimes inaccurate + +## 1.3.0 (2017-05-02) + +### Added + +- #45: Added json (un)marshaling support (thanks @mh-cbon) +- Stability marker. See https://masterminds.github.io/stability/ + +### Fixed + +- #51: Fix handling of single digit tilde constraint (thanks @dgodd) + +### Changed + +- #55: The godoc icon moved from png to svg + +## 1.2.3 (2017-04-03) + +### Fixed + +- #46: Fixed 0.x.x and 0.0.x in constraints being treated as * + +## Release 1.2.2 (2016-12-13) + +### Fixed + +- #34: Fixed issue where hyphen range was not working with pre-release parsing. + +## Release 1.2.1 (2016-11-28) + +### Fixed + +- #24: Fixed edge case issue where constraint "> 0" does not handle "0.0.1-alpha" + properly. + +## Release 1.2.0 (2016-11-04) + +### Added + +- #20: Added MustParse function for versions (thanks @adamreese) +- #15: Added increment methods on versions (thanks @mh-cbon) + +### Fixed + +- Issue #21: Per the SemVer spec (section 9) a pre-release is unstable and + might not satisfy the intended compatibility. The change here ignores pre-releases + on constraint checks (e.g., ~ or ^) when a pre-release is not part of the + constraint. For example, `^1.2.3` will ignore pre-releases while + `^1.2.3-alpha` will include them. + +## Release 1.1.1 (2016-06-30) + +### Changed + +- Issue #9: Speed up version comparison performance (thanks @sdboyer) +- Issue #8: Added benchmarks (thanks @sdboyer) +- Updated Go Report Card URL to new location +- Updated Readme to add code snippet formatting (thanks @mh-cbon) +- Updating tagging to v[SemVer] structure for compatibility with other tools. + +## Release 1.1.0 (2016-03-11) + +- Issue #2: Implemented validation to provide reasons a versions failed a + constraint. + +## Release 1.0.1 (2015-12-31) + +- Fixed #1: * constraint failing on valid versions. + +## Release 1.0.0 (2015-10-20) + +- Initial release diff --git a/tools/vendor/github.com/Masterminds/semver/LICENSE.txt b/tools/vendor/github.com/Masterminds/semver/v3/LICENSE.txt similarity index 100% rename from tools/vendor/github.com/Masterminds/semver/LICENSE.txt rename to tools/vendor/github.com/Masterminds/semver/v3/LICENSE.txt diff --git a/tools/vendor/github.com/Masterminds/semver/v3/Makefile b/tools/vendor/github.com/Masterminds/semver/v3/Makefile new file mode 100644 index 000000000..0e7b5c713 --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/Makefile @@ -0,0 +1,30 @@ +GOPATH=$(shell go env GOPATH) +GOLANGCI_LINT=$(GOPATH)/bin/golangci-lint + +.PHONY: lint +lint: $(GOLANGCI_LINT) + @echo "==> Linting codebase" + @$(GOLANGCI_LINT) run + +.PHONY: test +test: + @echo "==> Running tests" + GO111MODULE=on go test -v + +.PHONY: test-cover +test-cover: + @echo "==> Running Tests with coverage" + GO111MODULE=on go test -cover . + +.PHONY: fuzz +fuzz: + @echo "==> Running Fuzz Tests" + go test -fuzz=FuzzNewVersion -fuzztime=15s . + go test -fuzz=FuzzStrictNewVersion -fuzztime=15s . + go test -fuzz=FuzzNewConstraint -fuzztime=15s . + +$(GOLANGCI_LINT): + # Install golangci-lint. The configuration for it is in the .golangci.yml + # file in the root of the repository + echo ${GOPATH} + curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.17.1 diff --git a/tools/vendor/github.com/Masterminds/semver/v3/README.md b/tools/vendor/github.com/Masterminds/semver/v3/README.md new file mode 100644 index 000000000..eab8cac3b --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/README.md @@ -0,0 +1,258 @@ +# SemVer + +The `semver` package provides the ability to work with [Semantic Versions](http://semver.org) in Go. Specifically it provides the ability to: + +* Parse semantic versions +* Sort semantic versions +* Check if a semantic version fits within a set of constraints +* Optionally work with a `v` prefix + +[![Stability: +Active](https://masterminds.github.io/stability/active.svg)](https://masterminds.github.io/stability/active.html) +[![](https://github.com/Masterminds/semver/workflows/Tests/badge.svg)](https://github.com/Masterminds/semver/actions) +[![GoDoc](https://img.shields.io/static/v1?label=godoc&message=reference&color=blue)](https://pkg.go.dev/github.com/Masterminds/semver/v3) +[![Go Report Card](https://goreportcard.com/badge/github.com/Masterminds/semver)](https://goreportcard.com/report/github.com/Masterminds/semver) + +If you are looking for a command line tool for version comparisons please see +[vert](https://github.com/Masterminds/vert) which uses this library. + +## Package Versions + +Note, import `github.com/github.com/Masterminds/semver/v3` to use the latest version. + +There are three major versions fo the `semver` package. + +* 3.x.x is the stable and active version. This version is focused on constraint + compatibility for range handling in other tools from other languages. It has + a similar API to the v1 releases. The development of this version is on the master + branch. The documentation for this version is below. +* 2.x was developed primarily for [dep](https://github.com/golang/dep). There are + no tagged releases and the development was performed by [@sdboyer](https://github.com/sdboyer). + There are API breaking changes from v1. This version lives on the [2.x branch](https://github.com/Masterminds/semver/tree/2.x). +* 1.x.x is the original release. It is no longer maintained. You should use the + v3 release instead. You can read the documentation for the 1.x.x release + [here](https://github.com/Masterminds/semver/blob/release-1/README.md). + +## Parsing Semantic Versions + +There are two functions that can parse semantic versions. The `StrictNewVersion` +function only parses valid version 2 semantic versions as outlined in the +specification. The `NewVersion` function attempts to coerce a version into a +semantic version and parse it. For example, if there is a leading v or a version +listed without all 3 parts (e.g. `v1.2`) it will attempt to coerce it into a valid +semantic version (e.g., 1.2.0). In both cases a `Version` object is returned +that can be sorted, compared, and used in constraints. + +When parsing a version an error is returned if there is an issue parsing the +version. For example, + + v, err := semver.NewVersion("1.2.3-beta.1+build345") + +The version object has methods to get the parts of the version, compare it to +other versions, convert the version back into a string, and get the original +string. Getting the original string is useful if the semantic version was coerced +into a valid form. + +## Sorting Semantic Versions + +A set of versions can be sorted using the `sort` package from the standard library. +For example, + +```go +raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} +vs := make([]*semver.Version, len(raw)) +for i, r := range raw { + v, err := semver.NewVersion(r) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + vs[i] = v +} + +sort.Sort(semver.Collection(vs)) +``` + +## Checking Version Constraints + +There are two methods for comparing versions. One uses comparison methods on +`Version` instances and the other uses `Constraints`. There are some important +differences to notes between these two methods of comparison. + +1. When two versions are compared using functions such as `Compare`, `LessThan`, + and others it will follow the specification and always include prereleases + within the comparison. It will provide an answer that is valid with the + comparison section of the spec at https://semver.org/#spec-item-11 +2. When constraint checking is used for checks or validation it will follow a + different set of rules that are common for ranges with tools like npm/js + and Rust/Cargo. This includes considering prereleases to be invalid if the + ranges does not include one. If you want to have it include pre-releases a + simple solution is to include `-0` in your range. +3. Constraint ranges can have some complex rules including the shorthand use of + ~ and ^. For more details on those see the options below. + +There are differences between the two methods or checking versions because the +comparison methods on `Version` follow the specification while comparison ranges +are not part of the specification. Different packages and tools have taken it +upon themselves to come up with range rules. This has resulted in differences. +For example, npm/js and Cargo/Rust follow similar patterns while PHP has a +different pattern for ^. The comparison features in this package follow the +npm/js and Cargo/Rust lead because applications using it have followed similar +patters with their versions. + +Checking a version against version constraints is one of the most featureful +parts of the package. + +```go +c, err := semver.NewConstraint(">= 1.2.3") +if err != nil { + // Handle constraint not being parsable. +} + +v, err := semver.NewVersion("1.3") +if err != nil { + // Handle version not being parsable. +} +// Check if the version meets the constraints. The a variable will be true. +a := c.Check(v) +``` + +### Basic Comparisons + +There are two elements to the comparisons. First, a comparison string is a list +of space or comma separated AND comparisons. These are then separated by || (OR) +comparisons. For example, `">= 1.2 < 3.0.0 || >= 4.2.3"` is looking for a +comparison that's greater than or equal to 1.2 and less than 3.0.0 or is +greater than or equal to 4.2.3. + +The basic comparisons are: + +* `=`: equal (aliased to no operator) +* `!=`: not equal +* `>`: greater than +* `<`: less than +* `>=`: greater than or equal to +* `<=`: less than or equal to + +### Working With Prerelease Versions + +Pre-releases, for those not familiar with them, are used for software releases +prior to stable or generally available releases. Examples of prereleases include +development, alpha, beta, and release candidate releases. A prerelease may be +a version such as `1.2.3-beta.1` while the stable release would be `1.2.3`. In the +order of precedence, prereleases come before their associated releases. In this +example `1.2.3-beta.1 < 1.2.3`. + +According to the Semantic Version specification prereleases may not be +API compliant with their release counterpart. It says, + +> A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. + +SemVer comparisons using constraints without a prerelease comparator will skip +prerelease versions. For example, `>=1.2.3` will skip prereleases when looking +at a list of releases while `>=1.2.3-0` will evaluate and find prereleases. + +The reason for the `0` as a pre-release version in the example comparison is +because pre-releases can only contain ASCII alphanumerics and hyphens (along with +`.` separators), per the spec. Sorting happens in ASCII sort order, again per the +spec. The lowest character is a `0` in ASCII sort order +(see an [ASCII Table](http://www.asciitable.com/)) + +Understanding ASCII sort ordering is important because A-Z comes before a-z. That +means `>=1.2.3-BETA` will return `1.2.3-alpha`. What you might expect from case +sensitivity doesn't apply here. This is due to ASCII sort ordering which is what +the spec specifies. + +### Hyphen Range Comparisons + +There are multiple methods to handle ranges and the first is hyphens ranges. +These look like: + +* `1.2 - 1.4.5` which is equivalent to `>= 1.2 <= 1.4.5` +* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4 <= 4.5` + +### Wildcards In Comparisons + +The `x`, `X`, and `*` characters can be used as a wildcard character. This works +for all comparison operators. When used on the `=` operator it falls +back to the patch level comparison (see tilde below). For example, + +* `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` +* `>= 1.2.x` is equivalent to `>= 1.2.0` +* `<= 2.x` is equivalent to `< 3` +* `*` is equivalent to `>= 0.0.0` + +### Tilde Range Comparisons (Patch) + +The tilde (`~`) comparison operator is for patch level ranges when a minor +version is specified and major level changes when the minor number is missing. +For example, + +* `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` +* `~1` is equivalent to `>= 1, < 2` +* `~2.3` is equivalent to `>= 2.3, < 2.4` +* `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` +* `~1.x` is equivalent to `>= 1, < 2` + +### Caret Range Comparisons (Major) + +The caret (`^`) comparison operator is for major level changes once a stable +(1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts +as the API stability level. This is useful when comparisons of API versions as a +major change is API breaking. For example, + +* `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` +* `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` +* `^2.3` is equivalent to `>= 2.3, < 3` +* `^2.x` is equivalent to `>= 2.0.0, < 3` +* `^0.2.3` is equivalent to `>=0.2.3 <0.3.0` +* `^0.2` is equivalent to `>=0.2.0 <0.3.0` +* `^0.0.3` is equivalent to `>=0.0.3 <0.0.4` +* `^0.0` is equivalent to `>=0.0.0 <0.1.0` +* `^0` is equivalent to `>=0.0.0 <1.0.0` + +## Validation + +In addition to testing a version against a constraint, a version can be validated +against a constraint. When validation fails a slice of errors containing why a +version didn't meet the constraint is returned. For example, + +```go +c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") +if err != nil { + // Handle constraint not being parseable. +} + +v, err := semver.NewVersion("1.3") +if err != nil { + // Handle version not being parseable. +} + +// Validate a version against a constraint. +a, msgs := c.Validate(v) +// a is false +for _, m := range msgs { + fmt.Println(m) + + // Loops over the errors which would read + // "1.3 is greater than 1.2.3" + // "1.3 is less than 1.4" +} +``` + +## Contribute + +If you find an issue or want to contribute please file an [issue](https://github.com/Masterminds/semver/issues) +or [create a pull request](https://github.com/Masterminds/semver/pulls). + +## Security + +Security is an important consideration for this project. The project currently +uses the following tools to help discover security issues: + +* [CodeQL](https://github.com/Masterminds/semver) +* [gosec](https://github.com/securego/gosec) +* Daily Fuzz testing + +If you believe you have found a security vulnerability you can privately disclose +it through the [GitHub security page](https://github.com/Masterminds/semver/security). diff --git a/tools/vendor/github.com/Masterminds/semver/v3/SECURITY.md b/tools/vendor/github.com/Masterminds/semver/v3/SECURITY.md new file mode 100644 index 000000000..a30a66b1f --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +## Supported Versions + +The following versions of semver are currently supported: + +| Version | Supported | +| ------- | ------------------ | +| 3.x | :white_check_mark: | +| 2.x | :x: | +| 1.x | :x: | + +Fixes are only released for the latest minor version in the form of a patch release. + +## Reporting a Vulnerability + +You can privately disclose a vulnerability through GitHubs +[private vulnerability reporting](https://github.com/Masterminds/semver/security/advisories) +mechanism. diff --git a/tools/vendor/github.com/Masterminds/semver/collection.go b/tools/vendor/github.com/Masterminds/semver/v3/collection.go similarity index 100% rename from tools/vendor/github.com/Masterminds/semver/collection.go rename to tools/vendor/github.com/Masterminds/semver/v3/collection.go diff --git a/tools/vendor/github.com/Masterminds/semver/v3/constraints.go b/tools/vendor/github.com/Masterminds/semver/v3/constraints.go new file mode 100644 index 000000000..8461c7ed9 --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/constraints.go @@ -0,0 +1,594 @@ +package semver + +import ( + "bytes" + "errors" + "fmt" + "regexp" + "strings" +) + +// Constraints is one or more constraint that a semantic version can be +// checked against. +type Constraints struct { + constraints [][]*constraint +} + +// NewConstraint returns a Constraints instance that a Version instance can +// be checked against. If there is a parse error it will be returned. +func NewConstraint(c string) (*Constraints, error) { + + // Rewrite - ranges into a comparison operation. + c = rewriteRange(c) + + ors := strings.Split(c, "||") + or := make([][]*constraint, len(ors)) + for k, v := range ors { + + // TODO: Find a way to validate and fetch all the constraints in a simpler form + + // Validate the segment + if !validConstraintRegex.MatchString(v) { + return nil, fmt.Errorf("improper constraint: %s", v) + } + + cs := findConstraintRegex.FindAllString(v, -1) + if cs == nil { + cs = append(cs, v) + } + result := make([]*constraint, len(cs)) + for i, s := range cs { + pc, err := parseConstraint(s) + if err != nil { + return nil, err + } + + result[i] = pc + } + or[k] = result + } + + o := &Constraints{constraints: or} + return o, nil +} + +// Check tests if a version satisfies the constraints. +func (cs Constraints) Check(v *Version) bool { + // TODO(mattfarina): For v4 of this library consolidate the Check and Validate + // functions as the underlying functions make that possible now. + // loop over the ORs and check the inner ANDs + for _, o := range cs.constraints { + joy := true + for _, c := range o { + if check, _ := c.check(v); !check { + joy = false + break + } + } + + if joy { + return true + } + } + + return false +} + +// Validate checks if a version satisfies a constraint. If not a slice of +// reasons for the failure are returned in addition to a bool. +func (cs Constraints) Validate(v *Version) (bool, []error) { + // loop over the ORs and check the inner ANDs + var e []error + + // Capture the prerelease message only once. When it happens the first time + // this var is marked + var prerelesase bool + for _, o := range cs.constraints { + joy := true + for _, c := range o { + // Before running the check handle the case there the version is + // a prerelease and the check is not searching for prereleases. + if c.con.pre == "" && v.pre != "" { + if !prerelesase { + em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + e = append(e, em) + prerelesase = true + } + joy = false + + } else { + + if _, err := c.check(v); err != nil { + e = append(e, err) + joy = false + } + } + } + + if joy { + return true, []error{} + } + } + + return false, e +} + +func (cs Constraints) String() string { + buf := make([]string, len(cs.constraints)) + var tmp bytes.Buffer + + for k, v := range cs.constraints { + tmp.Reset() + vlen := len(v) + for kk, c := range v { + tmp.WriteString(c.string()) + + // Space separate the AND conditions + if vlen > 1 && kk < vlen-1 { + tmp.WriteString(" ") + } + } + buf[k] = tmp.String() + } + + return strings.Join(buf, " || ") +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +func (cs *Constraints) UnmarshalText(text []byte) error { + temp, err := NewConstraint(string(text)) + if err != nil { + return err + } + + *cs = *temp + + return nil +} + +// MarshalText implements the encoding.TextMarshaler interface. +func (cs Constraints) MarshalText() ([]byte, error) { + return []byte(cs.String()), nil +} + +var constraintOps map[string]cfunc +var constraintRegex *regexp.Regexp +var constraintRangeRegex *regexp.Regexp + +// Used to find individual constraints within a multi-constraint string +var findConstraintRegex *regexp.Regexp + +// Used to validate an segment of ANDs is valid +var validConstraintRegex *regexp.Regexp + +const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + +func init() { + constraintOps = map[string]cfunc{ + "": constraintTildeOrEqual, + "=": constraintTildeOrEqual, + "!=": constraintNotEqual, + ">": constraintGreaterThan, + "<": constraintLessThan, + ">=": constraintGreaterThanEqual, + "=>": constraintGreaterThanEqual, + "<=": constraintLessThanEqual, + "=<": constraintLessThanEqual, + "~": constraintTilde, + "~>": constraintTilde, + "^": constraintCaret, + } + + ops := `=||!=|>|<|>=|=>|<=|=<|~|~>|\^` + + constraintRegex = regexp.MustCompile(fmt.Sprintf( + `^\s*(%s)\s*(%s)\s*$`, + ops, + cvRegex)) + + constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( + `\s*(%s)\s+-\s+(%s)\s*`, + cvRegex, cvRegex)) + + findConstraintRegex = regexp.MustCompile(fmt.Sprintf( + `(%s)\s*(%s)`, + ops, + cvRegex)) + + // The first time a constraint shows up will look slightly different from + // future times it shows up due to a leading space or comma in a given + // string. + validConstraintRegex = regexp.MustCompile(fmt.Sprintf( + `^(\s*(%s)\s*(%s)\s*)((?:\s+|,\s*)(%s)\s*(%s)\s*)*$`, + ops, + cvRegex, + ops, + cvRegex)) +} + +// An individual constraint +type constraint struct { + // The version used in the constraint check. For example, if a constraint + // is '<= 2.0.0' the con a version instance representing 2.0.0. + con *Version + + // The original parsed version (e.g., 4.x from != 4.x) + orig string + + // The original operator for the constraint + origfunc string + + // When an x is used as part of the version (e.g., 1.x) + minorDirty bool + dirty bool + patchDirty bool +} + +// Check if a version meets the constraint +func (c *constraint) check(v *Version) (bool, error) { + return constraintOps[c.origfunc](v, c) +} + +// String prints an individual constraint into a string +func (c *constraint) string() string { + return c.origfunc + c.orig +} + +type cfunc func(v *Version, c *constraint) (bool, error) + +func parseConstraint(c string) (*constraint, error) { + if len(c) > 0 { + m := constraintRegex.FindStringSubmatch(c) + if m == nil { + return nil, fmt.Errorf("improper constraint: %s", c) + } + + cs := &constraint{ + orig: m[2], + origfunc: m[1], + } + + ver := m[2] + minorDirty := false + patchDirty := false + dirty := false + if isX(m[3]) || m[3] == "" { + ver = fmt.Sprintf("0.0.0%s", m[6]) + dirty = true + } else if isX(strings.TrimPrefix(m[4], ".")) || m[4] == "" { + minorDirty = true + dirty = true + ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) + } else if isX(strings.TrimPrefix(m[5], ".")) || m[5] == "" { + dirty = true + patchDirty = true + ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) + } + + con, err := NewVersion(ver) + if err != nil { + + // The constraintRegex should catch any regex parsing errors. So, + // we should never get here. + return nil, errors.New("constraint Parser Error") + } + + cs.con = con + cs.minorDirty = minorDirty + cs.patchDirty = patchDirty + cs.dirty = dirty + + return cs, nil + } + + // The rest is the special case where an empty string was passed in which + // is equivalent to * or >=0.0.0 + con, err := StrictNewVersion("0.0.0") + if err != nil { + + // The constraintRegex should catch any regex parsing errors. So, + // we should never get here. + return nil, errors.New("constraint Parser Error") + } + + cs := &constraint{ + con: con, + orig: c, + origfunc: "", + minorDirty: false, + patchDirty: false, + dirty: true, + } + return cs, nil +} + +// Constraint functions +func constraintNotEqual(v *Version, c *constraint) (bool, error) { + if c.dirty { + + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + if c.con.Major() != v.Major() { + return true, nil + } + if c.con.Minor() != v.Minor() && !c.minorDirty { + return true, nil + } else if c.minorDirty { + return false, fmt.Errorf("%s is equal to %s", v, c.orig) + } else if c.con.Patch() != v.Patch() && !c.patchDirty { + return true, nil + } else if c.patchDirty { + // Need to handle prereleases if present + if v.Prerelease() != "" || c.con.Prerelease() != "" { + eq := comparePrerelease(v.Prerelease(), c.con.Prerelease()) != 0 + if eq { + return true, nil + } + return false, fmt.Errorf("%s is equal to %s", v, c.orig) + } + return false, fmt.Errorf("%s is equal to %s", v, c.orig) + } + } + + eq := v.Equal(c.con) + if eq { + return false, fmt.Errorf("%s is equal to %s", v, c.orig) + } + + return true, nil +} + +func constraintGreaterThan(v *Version, c *constraint) (bool, error) { + + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + var eq bool + + if !c.dirty { + eq = v.Compare(c.con) == 1 + if eq { + return true, nil + } + return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) + } + + if v.Major() > c.con.Major() { + return true, nil + } else if v.Major() < c.con.Major() { + return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) + } else if c.minorDirty { + // This is a range case such as >11. When the version is something like + // 11.1.0 is it not > 11. For that we would need 12 or higher + return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) + } else if c.patchDirty { + // This is for ranges such as >11.1. A version of 11.1.1 is not greater + // which one of 11.2.1 is greater + eq = v.Minor() > c.con.Minor() + if eq { + return true, nil + } + return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) + } + + // If we have gotten here we are not comparing pre-preleases and can use the + // Compare function to accomplish that. + eq = v.Compare(c.con) == 1 + if eq { + return true, nil + } + return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) +} + +func constraintLessThan(v *Version, c *constraint) (bool, error) { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + eq := v.Compare(c.con) < 0 + if eq { + return true, nil + } + return false, fmt.Errorf("%s is greater than or equal to %s", v, c.orig) +} + +func constraintGreaterThanEqual(v *Version, c *constraint) (bool, error) { + + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + eq := v.Compare(c.con) >= 0 + if eq { + return true, nil + } + return false, fmt.Errorf("%s is less than %s", v, c.orig) +} + +func constraintLessThanEqual(v *Version, c *constraint) (bool, error) { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + var eq bool + + if !c.dirty { + eq = v.Compare(c.con) <= 0 + if eq { + return true, nil + } + return false, fmt.Errorf("%s is greater than %s", v, c.orig) + } + + if v.Major() > c.con.Major() { + return false, fmt.Errorf("%s is greater than %s", v, c.orig) + } else if v.Major() == c.con.Major() && v.Minor() > c.con.Minor() && !c.minorDirty { + return false, fmt.Errorf("%s is greater than %s", v, c.orig) + } + + return true, nil +} + +// ~*, ~>* --> >= 0.0.0 (any) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0 +func constraintTilde(v *Version, c *constraint) (bool, error) { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + if v.LessThan(c.con) { + return false, fmt.Errorf("%s is less than %s", v, c.orig) + } + + // ~0.0.0 is a special case where all constraints are accepted. It's + // equivalent to >= 0.0.0. + if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 && + !c.minorDirty && !c.patchDirty { + return true, nil + } + + if v.Major() != c.con.Major() { + return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) + } + + if v.Minor() != c.con.Minor() && !c.minorDirty { + return false, fmt.Errorf("%s does not have same major and minor version as %s", v, c.orig) + } + + return true, nil +} + +// When there is a .x (dirty) status it automatically opts in to ~. Otherwise +// it's a straight = +func constraintTildeOrEqual(v *Version, c *constraint) (bool, error) { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + if c.dirty { + return constraintTilde(v, c) + } + + eq := v.Equal(c.con) + if eq { + return true, nil + } + + return false, fmt.Errorf("%s is not equal to %s", v, c.orig) +} + +// ^* --> (any) +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2 --> >=1.2.0 <2.0.0 +// ^1 --> >=1.0.0 <2.0.0 +// ^0.2.3 --> >=0.2.3 <0.3.0 +// ^0.2 --> >=0.2.0 <0.3.0 +// ^0.0.3 --> >=0.0.3 <0.0.4 +// ^0.0 --> >=0.0.0 <0.1.0 +// ^0 --> >=0.0.0 <1.0.0 +func constraintCaret(v *Version, c *constraint) (bool, error) { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + } + + // This less than handles prereleases + if v.LessThan(c.con) { + return false, fmt.Errorf("%s is less than %s", v, c.orig) + } + + var eq bool + + // ^ when the major > 0 is >=x.y.z < x+1 + if c.con.Major() > 0 || c.minorDirty { + + // ^ has to be within a major range for > 0. Everything less than was + // filtered out with the LessThan call above. This filters out those + // that greater but not within the same major range. + eq = v.Major() == c.con.Major() + if eq { + return true, nil + } + return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) + } + + // ^ when the major is 0 and minor > 0 is >=0.y.z < 0.y+1 + if c.con.Major() == 0 && v.Major() > 0 { + return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) + } + // If the con Minor is > 0 it is not dirty + if c.con.Minor() > 0 || c.patchDirty { + eq = v.Minor() == c.con.Minor() + if eq { + return true, nil + } + return false, fmt.Errorf("%s does not have same minor version as %s. Expected minor versions to match when constraint major version is 0", v, c.orig) + } + // ^ when the minor is 0 and minor > 0 is =0.0.z + if c.con.Minor() == 0 && v.Minor() > 0 { + return false, fmt.Errorf("%s does not have same minor version as %s", v, c.orig) + } + + // At this point the major is 0 and the minor is 0 and not dirty. The patch + // is not dirty so we need to check if they are equal. If they are not equal + eq = c.con.Patch() == v.Patch() + if eq { + return true, nil + } + return false, fmt.Errorf("%s does not equal %s. Expect version and constraint to equal when major and minor versions are 0", v, c.orig) +} + +func isX(x string) bool { + switch x { + case "x", "*", "X": + return true + default: + return false + } +} + +func rewriteRange(i string) string { + m := constraintRangeRegex.FindAllStringSubmatch(i, -1) + if m == nil { + return i + } + o := i + for _, v := range m { + t := fmt.Sprintf(">= %s, <= %s ", v[1], v[11]) + o = strings.Replace(o, v[0], t, 1) + } + + return o +} diff --git a/tools/vendor/github.com/Masterminds/semver/v3/doc.go b/tools/vendor/github.com/Masterminds/semver/v3/doc.go new file mode 100644 index 000000000..74f97caa5 --- /dev/null +++ b/tools/vendor/github.com/Masterminds/semver/v3/doc.go @@ -0,0 +1,184 @@ +/* +Package semver provides the ability to work with Semantic Versions (http://semver.org) in Go. + +Specifically it provides the ability to: + + - Parse semantic versions + - Sort semantic versions + - Check if a semantic version fits within a set of constraints + - Optionally work with a `v` prefix + +# Parsing Semantic Versions + +There are two functions that can parse semantic versions. The `StrictNewVersion` +function only parses valid version 2 semantic versions as outlined in the +specification. The `NewVersion` function attempts to coerce a version into a +semantic version and parse it. For example, if there is a leading v or a version +listed without all 3 parts (e.g. 1.2) it will attempt to coerce it into a valid +semantic version (e.g., 1.2.0). In both cases a `Version` object is returned +that can be sorted, compared, and used in constraints. + +When parsing a version an optional error can be returned if there is an issue +parsing the version. For example, + + v, err := semver.NewVersion("1.2.3-beta.1+b345") + +The version object has methods to get the parts of the version, compare it to +other versions, convert the version back into a string, and get the original +string. For more details please see the documentation +at https://godoc.org/github.com/Masterminds/semver. + +# Sorting Semantic Versions + +A set of versions can be sorted using the `sort` package from the standard library. +For example, + + raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} + vs := make([]*semver.Version, len(raw)) + for i, r := range raw { + v, err := semver.NewVersion(r) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + vs[i] = v + } + + sort.Sort(semver.Collection(vs)) + +# Checking Version Constraints and Comparing Versions + +There are two methods for comparing versions. One uses comparison methods on +`Version` instances and the other is using Constraints. There are some important +differences to notes between these two methods of comparison. + + 1. When two versions are compared using functions such as `Compare`, `LessThan`, + and others it will follow the specification and always include prereleases + within the comparison. It will provide an answer valid with the comparison + spec section at https://semver.org/#spec-item-11 + 2. When constraint checking is used for checks or validation it will follow a + different set of rules that are common for ranges with tools like npm/js + and Rust/Cargo. This includes considering prereleases to be invalid if the + ranges does not include on. If you want to have it include pre-releases a + simple solution is to include `-0` in your range. + 3. Constraint ranges can have some complex rules including the shorthard use of + ~ and ^. For more details on those see the options below. + +There are differences between the two methods or checking versions because the +comparison methods on `Version` follow the specification while comparison ranges +are not part of the specification. Different packages and tools have taken it +upon themselves to come up with range rules. This has resulted in differences. +For example, npm/js and Cargo/Rust follow similar patterns which PHP has a +different pattern for ^. The comparison features in this package follow the +npm/js and Cargo/Rust lead because applications using it have followed similar +patters with their versions. + +Checking a version against version constraints is one of the most featureful +parts of the package. + + c, err := semver.NewConstraint(">= 1.2.3") + if err != nil { + // Handle constraint not being parsable. + } + + v, err := semver.NewVersion("1.3") + if err != nil { + // Handle version not being parsable. + } + // Check if the version meets the constraints. The a variable will be true. + a := c.Check(v) + +# Basic Comparisons + +There are two elements to the comparisons. First, a comparison string is a list +of comma or space separated AND comparisons. These are then separated by || (OR) +comparisons. For example, `">= 1.2 < 3.0.0 || >= 4.2.3"` is looking for a +comparison that's greater than or equal to 1.2 and less than 3.0.0 or is +greater than or equal to 4.2.3. This can also be written as +`">= 1.2, < 3.0.0 || >= 4.2.3"` + +The basic comparisons are: + + - `=`: equal (aliased to no operator) + - `!=`: not equal + - `>`: greater than + - `<`: less than + - `>=`: greater than or equal to + - `<=`: less than or equal to + +# Hyphen Range Comparisons + +There are multiple methods to handle ranges and the first is hyphens ranges. +These look like: + + - `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` + - `2.3.4 - 4.5` which is equivalent to `>= 2.3.4 <= 4.5` + +# Wildcards In Comparisons + +The `x`, `X`, and `*` characters can be used as a wildcard character. This works +for all comparison operators. When used on the `=` operator it falls +back to the tilde operation. For example, + + - `1.2.x` is equivalent to `>= 1.2.0 < 1.3.0` + - `>= 1.2.x` is equivalent to `>= 1.2.0` + - `<= 2.x` is equivalent to `<= 3` + - `*` is equivalent to `>= 0.0.0` + +Tilde Range Comparisons (Patch) + +The tilde (`~`) comparison operator is for patch level ranges when a minor +version is specified and major level changes when the minor number is missing. +For example, + + - `~1.2.3` is equivalent to `>= 1.2.3 < 1.3.0` + - `~1` is equivalent to `>= 1, < 2` + - `~2.3` is equivalent to `>= 2.3 < 2.4` + - `~1.2.x` is equivalent to `>= 1.2.0 < 1.3.0` + - `~1.x` is equivalent to `>= 1 < 2` + +Caret Range Comparisons (Major) + +The caret (`^`) comparison operator is for major level changes once a stable +(1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts +as the API stability level. This is useful when comparisons of API versions as a +major change is API breaking. For example, + + - `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` + - `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` + - `^2.3` is equivalent to `>= 2.3, < 3` + - `^2.x` is equivalent to `>= 2.0.0, < 3` + - `^0.2.3` is equivalent to `>=0.2.3 <0.3.0` + - `^0.2` is equivalent to `>=0.2.0 <0.3.0` + - `^0.0.3` is equivalent to `>=0.0.3 <0.0.4` + - `^0.0` is equivalent to `>=0.0.0 <0.1.0` + - `^0` is equivalent to `>=0.0.0 <1.0.0` + +# Validation + +In addition to testing a version against a constraint, a version can be validated +against a constraint. When validation fails a slice of errors containing why a +version didn't meet the constraint is returned. For example, + + c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") + if err != nil { + // Handle constraint not being parseable. + } + + v, _ := semver.NewVersion("1.3") + if err != nil { + // Handle version not being parseable. + } + + // Validate a version against a constraint. + a, msgs := c.Validate(v) + // a is false + for _, m := range msgs { + fmt.Println(m) + + // Loops over the errors which would read + // "1.3 is greater than 1.2.3" + // "1.3 is less than 1.4" + } +*/ +package semver diff --git a/tools/vendor/github.com/Masterminds/semver/version.go b/tools/vendor/github.com/Masterminds/semver/v3/version.go similarity index 55% rename from tools/vendor/github.com/Masterminds/semver/version.go rename to tools/vendor/github.com/Masterminds/semver/v3/version.go index 400d4f934..7c4bed334 100644 --- a/tools/vendor/github.com/Masterminds/semver/version.go +++ b/tools/vendor/github.com/Masterminds/semver/v3/version.go @@ -2,6 +2,7 @@ package semver import ( "bytes" + "database/sql/driver" "encoding/json" "errors" "fmt" @@ -13,13 +14,23 @@ import ( // The compiled version of the regex created at init() is cached here so it // only needs to be created once. var versionRegex *regexp.Regexp -var validPrereleaseRegex *regexp.Regexp var ( // ErrInvalidSemVer is returned a version is found to be invalid when // being parsed. ErrInvalidSemVer = errors.New("Invalid Semantic Version") + // ErrEmptyString is returned when an empty string is passed in for parsing. + ErrEmptyString = errors.New("Version string empty") + + // ErrInvalidCharacters is returned when invalid characters are found as + // part of a version + ErrInvalidCharacters = errors.New("Invalid characters in version") + + // ErrSegmentStartsZero is returned when a version segment starts with 0. + // This is invalid in SemVer. + ErrSegmentStartsZero = errors.New("Version segment starts with 0") + // ErrInvalidMetadata is returned when the metadata is an invalid format ErrInvalidMetadata = errors.New("Invalid Metadata string") @@ -27,30 +38,123 @@ var ( ErrInvalidPrerelease = errors.New("Invalid Prerelease string") ) -// SemVerRegex is the regular expression used to parse a semantic version. -const SemVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` + +// semVerRegex is the regular expression used to parse a semantic version. +const semVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` -// ValidPrerelease is the regular expression which validates -// both prerelease and metadata values. -const ValidPrerelease string = `^([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*)$` - // Version represents a single semantic version. type Version struct { - major, minor, patch int64 + major, minor, patch uint64 pre string metadata string original string } func init() { - versionRegex = regexp.MustCompile("^" + SemVerRegex + "$") - validPrereleaseRegex = regexp.MustCompile(ValidPrerelease) + versionRegex = regexp.MustCompile("^" + semVerRegex + "$") +} + +const ( + num string = "0123456789" + allowed string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-" + num +) + +// StrictNewVersion parses a given version and returns an instance of Version or +// an error if unable to parse the version. Only parses valid semantic versions. +// Performs checking that can find errors within the version. +// If you want to coerce a version such as 1 or 1.2 and parse it as the 1.x +// releases of semver did, use the NewVersion() function. +func StrictNewVersion(v string) (*Version, error) { + // Parsing here does not use RegEx in order to increase performance and reduce + // allocations. + + if len(v) == 0 { + return nil, ErrEmptyString + } + + // Split the parts into [0]major, [1]minor, and [2]patch,prerelease,build + parts := strings.SplitN(v, ".", 3) + if len(parts) != 3 { + return nil, ErrInvalidSemVer + } + + sv := &Version{ + original: v, + } + + // check for prerelease or build metadata + var extra []string + if strings.ContainsAny(parts[2], "-+") { + // Start with the build metadata first as it needs to be on the right + extra = strings.SplitN(parts[2], "+", 2) + if len(extra) > 1 { + // build metadata found + sv.metadata = extra[1] + parts[2] = extra[0] + } + + extra = strings.SplitN(parts[2], "-", 2) + if len(extra) > 1 { + // prerelease found + sv.pre = extra[1] + parts[2] = extra[0] + } + } + + // Validate the number segments are valid. This includes only having positive + // numbers and no leading 0's. + for _, p := range parts { + if !containsOnly(p, num) { + return nil, ErrInvalidCharacters + } + + if len(p) > 1 && p[0] == '0' { + return nil, ErrSegmentStartsZero + } + } + + // Extract the major, minor, and patch elements onto the returned Version + var err error + sv.major, err = strconv.ParseUint(parts[0], 10, 64) + if err != nil { + return nil, err + } + + sv.minor, err = strconv.ParseUint(parts[1], 10, 64) + if err != nil { + return nil, err + } + + sv.patch, err = strconv.ParseUint(parts[2], 10, 64) + if err != nil { + return nil, err + } + + // No prerelease or build metadata found so returning now as a fastpath. + if sv.pre == "" && sv.metadata == "" { + return sv, nil + } + + if sv.pre != "" { + if err = validatePrerelease(sv.pre); err != nil { + return nil, err + } + } + + if sv.metadata != "" { + if err = validateMetadata(sv.metadata); err != nil { + return nil, err + } + } + + return sv, nil } // NewVersion parses a given version and returns an instance of Version or -// an error if unable to parse the version. +// an error if unable to parse the version. If the version is SemVer-ish it +// attempts to convert it to SemVer. If you want to validate it was a strict +// semantic version at parse time see StrictNewVersion(). func NewVersion(v string) (*Version, error) { m := versionRegex.FindStringSubmatch(v) if m == nil { @@ -63,36 +167,65 @@ func NewVersion(v string) (*Version, error) { original: v, } - var temp int64 - temp, err := strconv.ParseInt(m[1], 10, 64) + var err error + sv.major, err = strconv.ParseUint(m[1], 10, 64) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } - sv.major = temp if m[2] != "" { - temp, err = strconv.ParseInt(strings.TrimPrefix(m[2], "."), 10, 64) + sv.minor, err = strconv.ParseUint(strings.TrimPrefix(m[2], "."), 10, 64) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } - sv.minor = temp } else { sv.minor = 0 } if m[3] != "" { - temp, err = strconv.ParseInt(strings.TrimPrefix(m[3], "."), 10, 64) + sv.patch, err = strconv.ParseUint(strings.TrimPrefix(m[3], "."), 10, 64) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } - sv.patch = temp } else { sv.patch = 0 } + // Perform some basic due diligence on the extra parts to ensure they are + // valid. + + if sv.pre != "" { + if err = validatePrerelease(sv.pre); err != nil { + return nil, err + } + } + + if sv.metadata != "" { + if err = validateMetadata(sv.metadata); err != nil { + return nil, err + } + } + return sv, nil } +// New creates a new instance of Version with each of the parts passed in as +// arguments instead of parsing a version string. +func New(major, minor, patch uint64, pre, metadata string) *Version { + v := Version{ + major: major, + minor: minor, + patch: patch, + pre: pre, + metadata: metadata, + original: "", + } + + v.original = v.String() + + return &v +} + // MustParse parses a given version and panics on error. func MustParse(v string) *Version { sv, err := NewVersion(v) @@ -107,7 +240,7 @@ func MustParse(v string) *Version { // See the Original() method to retrieve the original value. Semantic Versions // don't contain a leading v per the spec. Instead it's optional on // implementation. -func (v *Version) String() string { +func (v Version) String() string { var buf bytes.Buffer fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch) @@ -127,33 +260,32 @@ func (v *Version) Original() string { } // Major returns the major version. -func (v *Version) Major() int64 { +func (v Version) Major() uint64 { return v.major } // Minor returns the minor version. -func (v *Version) Minor() int64 { +func (v Version) Minor() uint64 { return v.minor } // Patch returns the patch version. -func (v *Version) Patch() int64 { +func (v Version) Patch() uint64 { return v.patch } // Prerelease returns the pre-release version. -func (v *Version) Prerelease() string { +func (v Version) Prerelease() string { return v.pre } // Metadata returns the metadata on the version. -func (v *Version) Metadata() string { +func (v Version) Metadata() string { return v.metadata } // originalVPrefix returns the original 'v' prefix if any. -func (v *Version) originalVPrefix() string { - +func (v Version) originalVPrefix() string { // Note, only lowercase v is supported as a prefix by the parser. if v.original != "" && v.original[:1] == "v" { return v.original[:1] @@ -165,7 +297,7 @@ func (v *Version) originalVPrefix() string { // If the current version does not have prerelease/metadata information, // it unsets metadata and prerelease values, increments patch number. // If the current version has any of prerelease or metadata information, -// it unsets both values and keeps curent patch value +// it unsets both values and keeps current patch value func (v Version) IncPatch() Version { vNext := v // according to http://semver.org/#spec-item-9 @@ -217,11 +349,13 @@ func (v Version) IncMajor() Version { } // SetPrerelease defines the prerelease value. -// Value must not include the required 'hypen' prefix. +// Value must not include the required 'hyphen' prefix. func (v Version) SetPrerelease(prerelease string) (Version, error) { vNext := v - if len(prerelease) > 0 && !validPrereleaseRegex.MatchString(prerelease) { - return vNext, ErrInvalidPrerelease + if len(prerelease) > 0 { + if err := validatePrerelease(prerelease); err != nil { + return vNext, err + } } vNext.pre = prerelease vNext.original = v.originalVPrefix() + "" + vNext.String() @@ -232,8 +366,10 @@ func (v Version) SetPrerelease(prerelease string) (Version, error) { // Value must not include the required 'plus' prefix. func (v Version) SetMetadata(metadata string) (Version, error) { vNext := v - if len(metadata) > 0 && !validPrereleaseRegex.MatchString(metadata) { - return vNext, ErrInvalidMetadata + if len(metadata) > 0 { + if err := validateMetadata(metadata); err != nil { + return vNext, err + } } vNext.metadata = metadata vNext.original = v.originalVPrefix() + "" + vNext.String() @@ -261,7 +397,9 @@ func (v *Version) Equal(o *Version) bool { // the version smaller, equal, or larger than the other version. // // Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is -// lower than the version without a prerelease. +// lower than the version without a prerelease. Compare always takes into account +// prereleases. If you want to work with ranges using typical range syntaxes that +// skip prereleases if the range is not looking for them use constraints. func (v *Version) Compare(o *Version) int { // Compare the major, minor, and patch version for differences. If a // difference is found return the comparison. @@ -308,16 +446,54 @@ func (v *Version) UnmarshalJSON(b []byte) error { v.pre = temp.pre v.metadata = temp.metadata v.original = temp.original - temp = nil return nil } // MarshalJSON implements JSON.Marshaler interface. -func (v *Version) MarshalJSON() ([]byte, error) { +func (v Version) MarshalJSON() ([]byte, error) { return json.Marshal(v.String()) } -func compareSegment(v, o int64) int { +// UnmarshalText implements the encoding.TextUnmarshaler interface. +func (v *Version) UnmarshalText(text []byte) error { + temp, err := NewVersion(string(text)) + if err != nil { + return err + } + + *v = *temp + + return nil +} + +// MarshalText implements the encoding.TextMarshaler interface. +func (v Version) MarshalText() ([]byte, error) { + return []byte(v.String()), nil +} + +// Scan implements the SQL.Scanner interface. +func (v *Version) Scan(value interface{}) error { + var s string + s, _ = value.(string) + temp, err := NewVersion(s) + if err != nil { + return err + } + v.major = temp.major + v.minor = temp.minor + v.patch = temp.patch + v.pre = temp.pre + v.metadata = temp.metadata + v.original = temp.original + return nil +} + +// Value implements the Driver.Valuer interface. +func (v Version) Value() (driver.Value, error) { + return v.String(), nil +} + +func compareSegment(v, o uint64) int { if v < o { return -1 } @@ -329,7 +505,6 @@ func compareSegment(v, o int64) int { } func comparePrerelease(v, o string) int { - // split the prelease versions by their part. The separator, per the spec, // is a . sparts := strings.Split(v, ".") @@ -421,5 +596,44 @@ func comparePrePart(s, o string) int { return 1 } return -1 +} + +// Like strings.ContainsAny but does an only instead of any. +func containsOnly(s string, comp string) bool { + return strings.IndexFunc(s, func(r rune) bool { + return !strings.ContainsRune(comp, r) + }) == -1 +} + +// From the spec, "Identifiers MUST comprise only +// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. +// Numeric identifiers MUST NOT include leading zeroes.". These segments can +// be dot separated. +func validatePrerelease(p string) error { + eparts := strings.Split(p, ".") + for _, p := range eparts { + if containsOnly(p, num) { + if len(p) > 1 && p[0] == '0' { + return ErrSegmentStartsZero + } + } else if !containsOnly(p, allowed) { + return ErrInvalidPrerelease + } + } + return nil +} + +// From the spec, "Build metadata MAY be denoted by +// appending a plus sign and a series of dot separated identifiers immediately +// following the patch or pre-release version. Identifiers MUST comprise only +// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty." +func validateMetadata(m string) error { + eparts := strings.Split(m, ".") + for _, p := range eparts { + if !containsOnly(p, allowed) { + return ErrInvalidMetadata + } + } + return nil } diff --git a/tools/vendor/github.com/Masterminds/semver/version_fuzz.go b/tools/vendor/github.com/Masterminds/semver/version_fuzz.go deleted file mode 100644 index b42bcd62b..000000000 --- a/tools/vendor/github.com/Masterminds/semver/version_fuzz.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build gofuzz - -package semver - -func Fuzz(data []byte) int { - if _, err := NewVersion(string(data)); err != nil { - return 0 - } - return 1 -} diff --git a/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/.gitignore b/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/.gitignore index 97cca67c6..e189bdb22 100644 --- a/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/.gitignore +++ b/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/.gitignore @@ -12,3 +12,4 @@ *.out .idea +.null-ls*.go diff --git a/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/README.md b/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/README.md index 3de3f6317..2ccfa22c5 100644 --- a/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/README.md +++ b/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/README.md @@ -7,13 +7,12 @@ allow specific packages within a repository. ## Install ```bash -go get github.com/OpenPeeDeeP/depguard/v2 +go install github.com/OpenPeeDeeP/depguard@latest ``` ## Config -The Depguard binary looks for a file named `^\.?depguard\.(yaml|yml|json|toml)$` in the current -current working directory. Examples include (`.depguard.yml` or `depguard.toml`). +The Depguard binary looks for a file named `^\.?depguard\.(yaml|yml|json|toml)$` in the current working directory. Examples include (`.depguard.yml` or `depguard.toml`). The following is an example configuration file. @@ -24,6 +23,7 @@ The following is an example configuration file. "$all", "!$test" ], + "listMode": "Strict", "allow": [ "$gostd", "github.com/OpenPeeDeeP" @@ -36,6 +36,7 @@ The following is an example configuration file. "files": [ "$test" ], + "listMode": "Lax", "deny": { "github.com/stretchr/testify": "Please use standard library for tests" } @@ -48,6 +49,7 @@ the linter's output. - `files` - list of file globs that will match this list of settings to compare against - `allow` - list of allowed packages - `deny` - map of packages that are not allowed where the value is a suggestion += `listMode` - the mode to use for package matching Files are matched using [Globs](https://github.com/gobwas/glob). If the files list is empty, then all files will match that list. Prefixing a file @@ -67,6 +69,21 @@ A Prefix List just means that a package will match a value, if the value is a prefix of the package. Example `github.com/OpenPeeDeeP/depguard` package will match a value of `github.com/OpenPeeDeeP` but won't match `github.com/OpenPeeDeeP/depguard/v2`. +ListMode is used to determine the package matching priority. There are three +different modes; Original, Strict, and Lax. + +Original is the original way that the package was written to use. It is not recommended +to stay with this and is only here for backwards compatibility. + +Strict, at its roots, is everything is denied unless in allowed. + +Lax, at its roots, is everything is allowed unless it is denied. + +There are cases where a package can be matched in both the allow and denied lists. +You may allow a subpackage but deny the root or vice versa. The `settings_tests.go` file +has many scenarios listed out under `TestListImportAllowed`. These tests will stay +up to date as features are added. + ### Variables There are variable replacements for each type of list (file or package). This is @@ -74,7 +91,7 @@ to reduce repetition and tedious behaviors. #### File Variables -> you can still use and exclamation mark `!` in front of a variable to say not to +> you can still use an exclamation mark `!` in front of a variable to say not to use it. Example `!$test` will match any file that is not a go test file. - `$all` - matches all go files diff --git a/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/settings.go b/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/settings.go index 440f32985..311cacc88 100644 --- a/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/settings.go +++ b/tools/vendor/github.com/OpenPeeDeeP/depguard/v2/settings.go @@ -11,12 +11,22 @@ import ( ) type List struct { - Files []string `json:"files" yaml:"files" toml:"files" mapstructure:"files"` - Allow []string `json:"allow" yaml:"allow" toml:"allow" mapstructure:"allow"` - Deny map[string]string `json:"deny" yaml:"deny" toml:"deny" mapstructure:"deny"` + ListMode string `json:"listMode" yaml:"listMode" toml:"listMode" mapstructure:"listMode"` + Files []string `json:"files" yaml:"files" toml:"files" mapstructure:"files"` + Allow []string `json:"allow" yaml:"allow" toml:"allow" mapstructure:"allow"` + Deny map[string]string `json:"deny" yaml:"deny" toml:"deny" mapstructure:"deny"` } +type listMode int + +const ( + listModeOriginal listMode = iota + listModeStrict + listModeLax +) + type list struct { + listMode listMode name string files []glob.Glob negFiles []glob.Glob @@ -33,6 +43,20 @@ func (l *List) compile() (*list, error) { var errs utils.MultiError var err error + // Determine List Mode + switch strings.ToLower(l.ListMode) { + case "": + li.listMode = listModeOriginal + case "original": + li.listMode = listModeOriginal + case "strict": + li.listMode = listModeStrict + case "lax": + li.listMode = listModeLax + default: + errs = append(errs, fmt.Errorf("%s is not a known list mode", l.ListMode)) + } + // Compile Files for _, f := range l.Files { var negate bool @@ -113,16 +137,25 @@ func (l *list) fileMatch(fileName string) bool { } func (l *list) importAllowed(imp string) (bool, string) { - inAllowed := len(l.allow) == 0 - if !inAllowed { - inAllowed, _ = strInPrefixList(imp, l.allow) + inAllowed, aIdx := strInPrefixList(imp, l.allow) + inDenied, dIdx := strInPrefixList(imp, l.deny) + var allowed bool + switch l.listMode { + case listModeOriginal: + inAllowed = len(l.allow) == 0 || inAllowed + allowed = inAllowed && !inDenied + case listModeStrict: + allowed = inAllowed && (!inDenied || len(l.allow[aIdx]) > len(l.deny[dIdx])) + case listModeLax: + allowed = !inDenied || (inAllowed && len(l.allow[aIdx]) > len(l.deny[dIdx])) + default: + allowed = false } - inDenied, suggIdx := strInPrefixList(imp, l.deny) sugg := "" - if inDenied && suggIdx != -1 { - sugg = l.suggestions[suggIdx] + if !allowed && inDenied && dIdx != -1 { + sugg = l.suggestions[dIdx] } - return inAllowed && !inDenied, sugg + return allowed, sugg } type LinterSettings map[string]*List diff --git a/tools/vendor/github.com/alecthomas/go-check-sumtype/decl.go b/tools/vendor/github.com/alecthomas/go-check-sumtype/decl.go index ea2cd06df..9dec9eefd 100644 --- a/tools/vendor/github.com/alecthomas/go-check-sumtype/decl.go +++ b/tools/vendor/github.com/alecthomas/go-check-sumtype/decl.go @@ -57,6 +57,7 @@ func findSumTypeDecls(pkgs []*packages.Package) ([]sumTypeDecl, error) { } pos = pkg.Fset.Position(tspec.Pos()) decl := sumTypeDecl{Package: pkg, TypeName: tspec.Name.Name, Pos: pos} + debugf("found sum type decl: %s.%s", decl.Package.PkgPath, decl.TypeName) decls = append(decls, decl) break } diff --git a/tools/vendor/github.com/alecthomas/go-check-sumtype/def.go b/tools/vendor/github.com/alecthomas/go-check-sumtype/def.go index 811b98f98..24729ac01 100644 --- a/tools/vendor/github.com/alecthomas/go-check-sumtype/def.go +++ b/tools/vendor/github.com/alecthomas/go-check-sumtype/def.go @@ -1,11 +1,21 @@ package gochecksumtype import ( + "flag" "fmt" "go/token" "go/types" + "log" ) +var debug = flag.Bool("debug", false, "enable debug logging") + +func debugf(format string, args ...interface{}) { + if *debug { + log.Printf(format, args...) + } +} + // Error as returned by Run() type Error interface { error @@ -107,6 +117,7 @@ func newSumTypeDef(pkg *types.Package, decl sumTypeDecl) (*sumTypeDef, error) { Decl: decl, Ty: iface, } + debugf("searching for variants of %s.%s\n", pkg.Path(), decl.TypeName) for _, name := range pkg.Scope().Names() { obj, ok := pkg.Scope().Lookup(name).(*types.TypeName) if !ok { @@ -116,7 +127,12 @@ func newSumTypeDef(pkg *types.Package, decl sumTypeDecl) (*sumTypeDef, error) { if types.Identical(ty.Underlying(), iface) { continue } + // Skip generic types. + if named, ok := ty.(*types.Named); ok && named.TypeParams() != nil { + continue + } if types.Implements(ty, iface) || types.Implements(types.NewPointer(ty), iface) { + debugf(" found variant: %s.%s\n", pkg.Path(), obj.Name()) def.Variants = append(def.Variants, obj) } } diff --git a/tools/vendor/github.com/bombsimon/wsl/v3/.gitignore b/tools/vendor/github.com/bombsimon/wsl/v4/.gitignore similarity index 99% rename from tools/vendor/github.com/bombsimon/wsl/v3/.gitignore rename to tools/vendor/github.com/bombsimon/wsl/v4/.gitignore index 1c8eba613..b37c69481 100644 --- a/tools/vendor/github.com/bombsimon/wsl/v3/.gitignore +++ b/tools/vendor/github.com/bombsimon/wsl/v4/.gitignore @@ -68,3 +68,5 @@ tags # End of https://www.gitignore.io/api/go,vim,macos + +.idea/ diff --git a/tools/vendor/github.com/bombsimon/wsl/v3/.golangci.yml b/tools/vendor/github.com/bombsimon/wsl/v4/.golangci.yml similarity index 81% rename from tools/vendor/github.com/bombsimon/wsl/v3/.golangci.yml rename to tools/vendor/github.com/bombsimon/wsl/v4/.golangci.yml index 336ad4bc8..bde0ae54e 100644 --- a/tools/vendor/github.com/bombsimon/wsl/v3/.golangci.yml +++ b/tools/vendor/github.com/bombsimon/wsl/v4/.golangci.yml @@ -1,24 +1,25 @@ --- run: - deadline: 1m + timeout: 1m issues-exit-code: 1 tests: true - skip-dirs: - - vendor$ output: - format: colored-line-number print-issued-lines: false + sort-results: true + formats: + - format: colored-line-number linters-settings: gocognit: min-complexity: 10 depguard: - list-type: blacklist - include-go-root: false - packages: - - github.com/davecgh/go-spew/spew + rules: + main: + deny: + - pkg: "github.com/davecgh/go-spew/spew" + desc: not allowed misspell: locale: US @@ -39,6 +40,7 @@ linters: disable: - cyclop - deadcode + - depguard - dupl - dupword - exhaustivestruct @@ -62,13 +64,13 @@ linters: - nosnakecase - paralleltest - prealloc + - rowserrcheck - scopelint - structcheck - testpackage - varcheck - varnamelen - fast: false - + - wastedassign issues: exclude-use-default: true diff --git a/tools/vendor/github.com/bombsimon/wsl/v3/LICENSE b/tools/vendor/github.com/bombsimon/wsl/v4/LICENSE similarity index 100% rename from tools/vendor/github.com/bombsimon/wsl/v3/LICENSE rename to tools/vendor/github.com/bombsimon/wsl/v4/LICENSE diff --git a/tools/vendor/github.com/bombsimon/wsl/v3/README.md b/tools/vendor/github.com/bombsimon/wsl/v4/README.md similarity index 69% rename from tools/vendor/github.com/bombsimon/wsl/v3/README.md rename to tools/vendor/github.com/bombsimon/wsl/v4/README.md index 8ff74392b..c9c42341e 100644 --- a/tools/vendor/github.com/bombsimon/wsl/v3/README.md +++ b/tools/vendor/github.com/bombsimon/wsl/v4/README.md @@ -1,4 +1,4 @@ -# WSL - Whitespace Linter +# wsl - Whitespace Linter [![forthebadge](https://forthebadge.com/images/badges/made-with-go.svg)](https://forthebadge.com) [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) @@ -6,83 +6,58 @@ [![GitHub Actions](https://github.com/bombsimon/wsl/actions/workflows/go.yml/badge.svg)](https://github.com/bombsimon/wsl/actions/workflows/go.yml) [![Coverage Status](https://coveralls.io/repos/github/bombsimon/wsl/badge.svg?branch=master)](https://coveralls.io/github/bombsimon/wsl?branch=master) -WSL is a linter that enforces a very **non scientific** vision of how to make +`wsl` is a linter that enforces a very **non scientific** vision of how to make code more readable by enforcing empty lines at the right places. -I think too much code out there is to cuddly and a bit too warm for it's own -good, making it harder for other people to read and understand. The linter will -warn about newlines in and around blocks, in the beginning of files and other -places in the code. - -**I know this linter is aggressive** and a lot of projects I've tested it on -have failed miserably. For this linter to be useful at all I want to be open to -new ideas, configurations and discussions! Also note that some of the warnings -might be bugs or unintentional false positives so I would love an +**This linter is aggressive** and a lot of projects I've tested it on have +failed miserably. For this linter to be useful at all I want to be open to new +ideas, configurations and discussions! Also note that some of the warnings might +be bugs or unintentional false positives so I would love an [issue](https://github.com/bombsimon/wsl/issues/new) to fix, discuss, change or make something configurable! ## Installation -### By `go get` (local installation) - -You can do that by using: - ```sh -go get -u github.com/bombsimon/wsl/v3/cmd/... -``` - -### By golangci-lint (CI automation) +# Latest release +go install github.com/bombsimon/wsl/v4/cmd/wsl@latest -`wsl` is already integrated with -[golangci-lint](https://github.com/golangci/golangci-lint). Please refer to the -instructions there. +# Main branch +go install github.com/bombsimon/wsl/v4/cmd/wsl@master +``` ## Usage -How to use depends on how you install `wsl`. +> **Note**: This linter provides a fixer that can fix most issues with the +> `--fix` flag. However, currently `golangci-lint` [does not support suggested +> fixes](https://github.com/golangci/golangci-lint/issues/1779) so the `--fix` +> flag in `golangci-lint` will **not** work. -### With local binary - -The general command format for `wsl` is: +`wsl` uses the [analysis](https://pkg.go.dev/golang.org/x/tools/go/analysis) +package meaning it will operate on package level with the default analysis flags +and way of working. ```sh -$ wsl [flags] [files...] -$ wsl [flags] - -# Examples +wsl --help +wsl [flags] -$ wsl ./main.go -$ wsl --no-test ./main.go -$ wsl --allow-cuddle-declarations ./main.go -$ wsl --no-test --allow-cuddle-declaration ./main.go -$ wsl --no-test --allow-trailing-comment ./myProject/... +wsl --allow-cuddle-declarations --fix ./... ``` -The "..." wildcard is not used like other `go` commands but instead can only -be to a relative or absolute path. - -By default, the linter will run on `./...` which means all go files in the -current path and all subsequent paths, including test files. To disable linting -test files, use `-n` or `--no-test`. - -### By `golangci-lint` (CI automation) - -The recommended command is: +`wsl` is also integrated in [`golangci-lint`](https://golangci-lint.run) ```sh -golangci-lint run --disable-all --enable wsl +golangci-lint run --no-config --disable-all --enable wsl ``` -For more information, please refer to -[golangci-lint](https://github.com/golangci/golangci-lint)'s documentation. - ## Issues and configuration The linter suppers a few ways to configure it to satisfy more than one kind of code style. These settings could be set either with flags or with YAML configuration if used via `golangci-lint`. -The supported configuration can be found [in the documentation](doc/configuration.md). +The supported configuration can be found [in the +documentation](doc/configuration.md). Below are the available checklist for any hit from `wsl`. If you do not see any, feel free to raise an [issue](https://github.com/bombsimon/wsl/issues/new). @@ -106,14 +81,11 @@ feel free to raise an [issue](https://github.com/bombsimon/wsl/issues/new). * [For statements should only be cuddled with assignments used in the iteration](doc/rules.md#for-statements-should-only-be-cuddled-with-assignments-used-in-the-iteration) * [Go statements can only invoke functions assigned on line above](doc/rules.md#go-statements-can-only-invoke-functions-assigned-on-line-above) * [If statements should only be cuddled with assignments](doc/rules.md#if-statements-should-only-be-cuddled-with-assignments) -* [If statements should only be cuddled with assignments used in the if - statement - itself](doc/rules.md#if-statements-should-only-be-cuddled-with-assignments-used-in-the-if-statement-itself) +* [If statements should only be cuddled with assignments used in the if statement itself](doc/rules.md#if-statements-should-only-be-cuddled-with-assignments-used-in-the-if-statement-itself) * [If statements that check an error must be cuddled with the statement that assigned the error](doc/rules.md#if-statements-that-check-an-error-must-be-cuddled-with-the-statement-that-assigned-the-error) -* [Only cuddled expressions if assigning variable or using from line - above](doc/rules.md#only-cuddled-expressions-if-assigning-variable-or-using-from-line-above) +* [Only cuddled expressions if assigning variable or using from line above](doc/rules.md#only-cuddled-expressions-if-assigning-variable-or-using-from-line-above) * [Only one cuddle assignment allowed before defer statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-defer-statement) -* [Only one cuddle assginment allowed before for statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-for-statement) +* [Only one cuddle assignment allowed before for statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-for-statement) * [Only one cuddle assignment allowed before go statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-go-statement) * [Only one cuddle assignment allowed before if statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-if-statement) * [Only one cuddle assignment allowed before range statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-range-statement) diff --git a/tools/vendor/github.com/bombsimon/wsl/v4/analyzer.go b/tools/vendor/github.com/bombsimon/wsl/v4/analyzer.go new file mode 100644 index 000000000..46d5019a7 --- /dev/null +++ b/tools/vendor/github.com/bombsimon/wsl/v4/analyzer.go @@ -0,0 +1,148 @@ +package wsl + +import ( + "flag" + "go/ast" + "strings" + + "golang.org/x/tools/go/analysis" +) + +func NewAnalyzer(config *Configuration) *analysis.Analyzer { + wa := &wslAnalyzer{config: config} + + return &analysis.Analyzer{ + Name: "wsl", + Doc: "add or remove empty lines", + Flags: wa.flags(), + Run: wa.run, + RunDespiteErrors: true, + } +} + +func defaultConfig() *Configuration { + return &Configuration{ + AllowAssignAndAnythingCuddle: false, + AllowAssignAndCallCuddle: true, + AllowCuddleDeclaration: false, + AllowMultiLineAssignCuddle: true, + AllowSeparatedLeadingComment: false, + AllowTrailingComment: false, + ForceCuddleErrCheckAndAssign: false, + ForceExclusiveShortDeclarations: false, + StrictAppend: true, + IncludeGenerated: false, + AllowCuddleWithCalls: []string{"Lock", "RLock"}, + AllowCuddleWithRHS: []string{"Unlock", "RUnlock"}, + ErrorVariableNames: []string{"err"}, + ForceCaseTrailingWhitespaceLimit: 0, + } +} + +// wslAnalyzer is a wrapper around the configuration which is used to be able to +// set the configuration when creating the analyzer and later be able to update +// flags and running method. +type wslAnalyzer struct { + config *Configuration +} + +func (wa *wslAnalyzer) flags() flag.FlagSet { + flags := flag.NewFlagSet("", flag.ExitOnError) + + // If we have a configuration set we're not running from the command line so + // we don't use any flags. + if wa.config != nil { + return *flags + } + + wa.config = defaultConfig() + + flags.BoolVar(&wa.config.AllowAssignAndAnythingCuddle, "allow-assign-and-anything", false, "Allow assignments and anything to be cuddled") + flags.BoolVar(&wa.config.AllowAssignAndCallCuddle, "allow-assign-and-call", true, "Allow assignments and calls to be cuddled (if using same variable/type)") + flags.BoolVar(&wa.config.AllowCuddleDeclaration, "allow-cuddle-declarations", false, "Allow declarations to be cuddled") + flags.BoolVar(&wa.config.AllowMultiLineAssignCuddle, "allow-multi-line-assign", true, "Allow cuddling with multi line assignments") + flags.BoolVar(&wa.config.AllowSeparatedLeadingComment, "allow-separated-leading-comment", false, "Allow empty newlines in leading comments") + flags.BoolVar(&wa.config.AllowTrailingComment, "allow-trailing-comment", false, "Allow blocks to end with a comment") + flags.BoolVar(&wa.config.ForceCuddleErrCheckAndAssign, "force-err-cuddling", false, "Force cuddling of error checks with error var assignment") + flags.BoolVar(&wa.config.ForceExclusiveShortDeclarations, "force-short-decl-cuddling", false, "Force short declarations to cuddle by themselves") + flags.BoolVar(&wa.config.StrictAppend, "strict-append", true, "Strict rules for append") + flags.BoolVar(&wa.config.IncludeGenerated, "include-generated", false, "Include generated files") + flags.IntVar(&wa.config.ForceCaseTrailingWhitespaceLimit, "force-case-trailing-whitespace", 0, "Force newlines for case blocks > this number.") + + flags.Var(&multiStringValue{slicePtr: &wa.config.AllowCuddleWithCalls}, "allow-cuddle-with-calls", "Comma separated list of idents that can have cuddles after") + flags.Var(&multiStringValue{slicePtr: &wa.config.AllowCuddleWithRHS}, "allow-cuddle-with-rhs", "Comma separated list of idents that can have cuddles before") + flags.Var(&multiStringValue{slicePtr: &wa.config.ErrorVariableNames}, "error-variable-names", "Comma separated list of error variable names") + + return *flags +} + +func (wa *wslAnalyzer) run(pass *analysis.Pass) (interface{}, error) { + for _, file := range pass.Files { + if !wa.config.IncludeGenerated && ast.IsGenerated(file) { + continue + } + + filename := pass.Fset.PositionFor(file.Pos(), false).Filename + if !strings.HasSuffix(filename, ".go") { + continue + } + + processor := newProcessorWithConfig(file, pass.Fset, wa.config) + processor.parseAST() + + for pos, fix := range processor.result { + textEdits := []analysis.TextEdit{} + for _, f := range fix.fixRanges { + textEdits = append(textEdits, analysis.TextEdit{ + Pos: f.fixRangeStart, + End: f.fixRangeEnd, + NewText: []byte("\n"), + }) + } + + pass.Report(analysis.Diagnostic{ + Pos: pos, + Category: "whitespace", + Message: fix.reason, + SuggestedFixes: []analysis.SuggestedFix{ + { + TextEdits: textEdits, + }, + }, + }) + } + } + + //nolint:nilnil // A pass don't need to return anything. + return nil, nil +} + +// multiStringValue is a flag that supports multiple values. It's implemented to +// contain a pointer to a string slice that will be overwritten when the flag's +// `Set` method is called. +type multiStringValue struct { + slicePtr *[]string +} + +// Set implements the flag.Value interface and will overwrite the pointer to the +// slice with a new pointer after splitting the flag by comma. +func (m *multiStringValue) Set(value string) error { + s := []string{} + + for _, v := range strings.Split(value, ",") { + s = append(s, strings.TrimSpace(v)) + } + + *m.slicePtr = s + + return nil +} + +// Set implements the flag.Value interface. +func (m *multiStringValue) String() string { + if m.slicePtr == nil { + return "" + } + + return strings.Join(*m.slicePtr, ", ") +} diff --git a/tools/vendor/github.com/bombsimon/wsl/v3/wsl.go b/tools/vendor/github.com/bombsimon/wsl/v4/wsl.go similarity index 63% rename from tools/vendor/github.com/bombsimon/wsl/v3/wsl.go rename to tools/vendor/github.com/bombsimon/wsl/v4/wsl.go index 1b139c047..76f4abf61 100644 --- a/tools/vendor/github.com/bombsimon/wsl/v3/wsl.go +++ b/tools/vendor/github.com/bombsimon/wsl/v4/wsl.go @@ -3,45 +3,44 @@ package wsl import ( "fmt" "go/ast" - "go/parser" "go/token" - "os" "reflect" + "sort" "strings" ) // Error reason strings. const ( - reasonMustCuddleErrCheck = "if statements that check an error must be cuddled with the statement that assigned the error" - reasonOnlyCuddleIfWithAssign = "if statements should only be cuddled with assignments" - reasonOnlyOneCuddle = "only one cuddle assignment allowed before if statement" - reasonOnlyCuddleWithUsedAssign = "if statements should only be cuddled with assignments used in the if statement itself" - reasonOnlyCuddle2LineReturn = "return statements should not be cuddled if block has more than two lines" - reasonMultiLineBranchCuddle = "branch statements should not be cuddled if block has more than two lines" + reasonAnonSwitchCuddled = "anonymous switch statements should never be cuddled" reasonAppendCuddledWithoutUse = "append only allowed to cuddle with appended value" reasonAssignsCuddleAssign = "assignments should only be cuddled with other assignments" - reasonNeverCuddleDeclare = "declarations should never be cuddled" - reasonExpressionCuddledWithDeclOrRet = "expressions should not be cuddled with declarations or returns" - reasonExpressionCuddledWithBlock = "expressions should not be cuddled with blocks" - reasonExprCuddlingNonAssignedVar = "only cuddled expressions if assigning variable or using from line above" - reasonOneCuddleBeforeRange = "only one cuddle assignment allowed before range statement" - reasonRangeCuddledWithoutUse = "ranges should only be cuddled with assignments used in the iteration" - reasonOneCuddleBeforeDefer = "only one cuddle assignment allowed before defer statement" + reasonBlockEndsWithWS = "block should not end with a whitespace (or comment)" + reasonBlockStartsWithWS = "block should not start with a whitespace" + reasonCaseBlockTooCuddly = "case block should end with newline at this size" reasonDeferCuddledWithOtherVar = "defer statements should only be cuddled with expressions on same variable" - reasonForWithoutCondition = "for statement without condition should never be cuddled" - reasonForWithMoreThanOneCuddle = "only one cuddle assignment allowed before for statement" + reasonExprCuddlingNonAssignedVar = "only cuddled expressions if assigning variable or using from line above" + reasonExpressionCuddledWithBlock = "expressions should not be cuddled with blocks" + reasonExpressionCuddledWithDeclOrRet = "expressions should not be cuddled with declarations or returns" reasonForCuddledAssignWithoutUse = "for statements should only be cuddled with assignments used in the iteration" - reasonOneCuddleBeforeGo = "only one cuddle assignment allowed before go statement" + reasonForWithoutCondition = "for statement without condition should never be cuddled" reasonGoFuncWithoutAssign = "go statements can only invoke functions assigned on line above" - reasonSwitchManyCuddles = "only one cuddle assignment allowed before switch statement" - reasonAnonSwitchCuddled = "anonymous switch statements should never be cuddled" + reasonMultiLineBranchCuddle = "branch statements should not be cuddled if block has more than two lines" + reasonMustCuddleErrCheck = "if statements that check an error must be cuddled with the statement that assigned the error" + reasonNeverCuddleDeclare = "declarations should never be cuddled" + reasonOnlyCuddle2LineReturn = "return statements should not be cuddled if block has more than two lines" + reasonOnlyCuddleIfWithAssign = "if statements should only be cuddled with assignments" + reasonOnlyCuddleWithUsedAssign = "if statements should only be cuddled with assignments used in the if statement itself" + reasonOnlyOneCuddleBeforeDefer = "only one cuddle assignment allowed before defer statement" + reasonOnlyOneCuddleBeforeFor = "only one cuddle assignment allowed before for statement" + reasonOnlyOneCuddleBeforeGo = "only one cuddle assignment allowed before go statement" + reasonOnlyOneCuddleBeforeIf = "only one cuddle assignment allowed before if statement" + reasonOnlyOneCuddleBeforeRange = "only one cuddle assignment allowed before range statement" + reasonOnlyOneCuddleBeforeSwitch = "only one cuddle assignment allowed before switch statement" + reasonOnlyOneCuddleBeforeTypeSwitch = "only one cuddle assignment allowed before type switch statement" + reasonRangeCuddledWithoutUse = "ranges should only be cuddled with assignments used in the iteration" + reasonShortDeclNotExclusive = "short declaration should cuddle only with other short declarations" reasonSwitchCuddledWithoutUse = "switch statements should only be cuddled with variables switched" - reasonTypeSwitchTooCuddled = "only one cuddle assignment allowed before type switch statement" reasonTypeSwitchCuddledWithoutUse = "type switch statements should only be cuddled with variables switched" - reasonBlockStartsWithWS = "block should not start with a whitespace" - reasonBlockEndsWithWS = "block should not end with a whitespace (or comment)" - reasonCaseBlockTooCuddly = "case block should end with newline at this size" - reasonShortDeclNotExclusive = "short declaration should cuddle only with other short declarations" ) // Warning strings. @@ -54,6 +53,7 @@ const ( warnUnknownRHS = "UNKNOWN RHS" ) +// Configuration represents configurable settings for the linter. type Configuration struct { // StrictAppend will do strict checking when assigning from append (x = // append(x, y)). If this is set to true the append call must append either @@ -82,7 +82,7 @@ type Configuration struct { // x = AnotherAssign() AllowAssignAndCallCuddle bool - // AllowAssignAndCallCuddle allows assignments to be cuddled with anything. + // AllowAssignAndAnythingCuddle allows assignments to be cuddled with anything. // Example supported with this set to true: // if x == 1 { // x = 0 @@ -174,96 +174,47 @@ type Configuration struct { // // is not allowed. This logic overrides ForceCuddleErrCheckAndAssign among others. ForceExclusiveShortDeclarations bool -} -// DefaultConfig returns default configuration. -func DefaultConfig() Configuration { - return Configuration{ - StrictAppend: true, - AllowAssignAndCallCuddle: true, - AllowAssignAndAnythingCuddle: false, - AllowMultiLineAssignCuddle: true, - AllowTrailingComment: false, - AllowSeparatedLeadingComment: false, - ForceCuddleErrCheckAndAssign: false, - ForceExclusiveShortDeclarations: false, - ForceCaseTrailingWhitespaceLimit: 0, - AllowCuddleWithCalls: []string{"Lock", "RLock"}, - AllowCuddleWithRHS: []string{"Unlock", "RUnlock"}, - ErrorVariableNames: []string{"err"}, - } + // IncludeGenerated will include generated files in the analysis and report + // errors even for generated files. Can be useful when developing + // generators. + IncludeGenerated bool } -// Result represents the result of one error. -type Result struct { - FileName string - LineNumber int - Position token.Position - Reason string +// fix is a range to fixup. +type fix struct { + fixRangeStart token.Pos + fixRangeEnd token.Pos } -// String returns the filename, line number and reason of a Result. -func (r *Result) String() string { - return fmt.Sprintf("%s:%d: %s", r.FileName, r.LineNumber, r.Reason) +// result represents the result of one error. +type result struct { + fixRanges []fix + reason string } -type Processor struct { - config Configuration - result []Result - warnings []string - fileSet *token.FileSet +// processor is the type that keeps track of the file and fileset and holds the +// results from parsing the AST. +type processor struct { + config *Configuration file *ast.File + fileSet *token.FileSet + result map[token.Pos]result + warnings []string } -// NewProcessor will create a Processor. -// -//nolint:gocritic // It's fine to copy config struct -func NewProcessorWithConfig(cfg Configuration) *Processor { - return &Processor{ - result: []Result{}, - config: cfg, +// newProcessorWithConfig will create a Processor with the passed configuration. +func newProcessorWithConfig(file *ast.File, fileSet *token.FileSet, cfg *Configuration) *processor { + return &processor{ + config: cfg, + file: file, + fileSet: fileSet, + result: make(map[token.Pos]result), } } -// NewProcessor will create a Processor. -func NewProcessor() *Processor { - return NewProcessorWithConfig(DefaultConfig()) -} - -// ProcessFiles takes a string slice with file names (full paths) and lints -// them. -// -//nolint:gocritic // Don't want named returns -func (p *Processor) ProcessFiles(filenames []string) ([]Result, []string) { - for _, filename := range filenames { - data, err := os.ReadFile(filename) - if err != nil { - panic(err) - } - - p.process(filename, data) - } - - return p.result, p.warnings -} - -func (p *Processor) process(filename string, data []byte) { - fileSet := token.NewFileSet() - file, err := parser.ParseFile(fileSet, filename, data, parser.ParseComments) - // If the file is not parsable let's add a syntax error and move on. - if err != nil { - p.result = append(p.result, Result{ - FileName: filename, - LineNumber: 0, - Reason: fmt.Sprintf("invalid syntax, file cannot be linted (%s)", err.Error()), - }) - - return - } - - p.fileSet = fileSet - p.file = file - +// parseAST will parse the AST attached to the Processor instance. +func (p *processor) parseAST() { for _, d := range p.file.Decls { switch v := d.(type) { case *ast.FuncDecl: @@ -279,7 +230,7 @@ func (p *Processor) process(filename string, data []byte) { // parseBlockBody will parse any kind of block statements such as switch cases // and if statements. A list of Result is returned. -func (p *Processor) parseBlockBody(ident *ast.Ident, block *ast.BlockStmt) { +func (p *processor) parseBlockBody(ident *ast.Ident, block *ast.BlockStmt) { // Nothing to do if there's no value. if reflect.ValueOf(block).IsNil() { return @@ -294,7 +245,7 @@ func (p *Processor) parseBlockBody(ident *ast.Ident, block *ast.BlockStmt) { // parseBlockStatements will parse all the statements found in the body of a // node. A list of Result is returned. -func (p *Processor) parseBlockStatements(statements []ast.Stmt) { +func (p *processor) parseBlockStatements(statements []ast.Stmt) { for i, stmt := range statements { // Start by checking if this statement is another block (other than if, // for and range). This could be assignment to a function, defer or go @@ -380,14 +331,38 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { continue } - moreThanOneStatementAbove := func() bool { - if i < 2 { + nStatementsBefore := func(n int) bool { + if i < n { return false } - statementBeforePreviousStatement := statements[i-2] + for j := 1; j < n; j++ { + s1 := statements[i-j] + s2 := statements[i-(j+1)] + + if p.nodeStart(s1)-1 != p.nodeEnd(s2) { + return false + } + } + + return true + } + + nStatementsAfter := func(n int) bool { + if len(statements)-1 < i+n { + return false + } + + for j := 0; j < n; j++ { + s1 := statements[i+j] + s2 := statements[i+j+1] + + if p.nodeEnd(s1)+1 != p.nodeStart(s2) { + return false + } + } - return p.nodeStart(previousStatement)-1 == p.nodeEnd(statementBeforePreviousStatement) + return true } isLastStatementInBlockOfOnlyTwoLines := func() bool { @@ -413,9 +388,30 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { // it was and use *that* statement's position if p.config.ForceExclusiveShortDeclarations && cuddledWithLastStmt { if p.isShortDecl(stmt) && !p.isShortDecl(previousStatement) { - p.addError(stmt.Pos(), reasonShortDeclNotExclusive) + var reportNode ast.Node = previousStatement + + cm := ast.NewCommentMap(p.fileSet, stmt, p.file.Comments) + if cg, ok := cm[stmt]; ok && len(cg) > 0 { + for _, c := range cg { + if c.Pos() > previousStatement.End() && c.End() < stmt.Pos() { + reportNode = c + } + } + } + + p.addErrorRange( + stmt.Pos(), + reportNode.End(), + reportNode.End(), + reasonShortDeclNotExclusive, + ) } else if p.isShortDecl(previousStatement) && !p.isShortDecl(stmt) { - p.addError(previousStatement.Pos(), reasonShortDeclNotExclusive) + p.addErrorRange( + previousStatement.Pos(), + stmt.Pos(), + stmt.Pos(), + reasonShortDeclNotExclusive, + ) } } @@ -428,6 +424,31 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { } } + reportNewlineTwoLinesAbove := func(n1, n2 ast.Node, reason string) { + if atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) || + atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) { + // If both the assignment on the line above _and_ the assignment + // two lines above is part of line or first in block, add the + // newline as if non were. + _, isAssignmentTwoLinesAbove := statements[i-2].(*ast.AssignStmt) + assignedTwoLinesAbove := p.findLHS(statements[i-2]) + + if isAssignmentTwoLinesAbove && + (atLeastOneInListsMatch(rightAndLeftHandSide, assignedTwoLinesAbove) || + atLeastOneInListsMatch(assignedTwoLinesAbove, calledOrAssignedFirstInBlock)) { + p.addWhitespaceBeforeError(n1, reason) + } else { + // If the variable on the line above is allowed to be + // cuddled, break two lines above so we keep the proper + // cuddling. + p.addErrorRange(n1.Pos(), n2.Pos(), n2.Pos(), reason) + } + } else { + // If not, break here so we separate the cuddled variable. + p.addWhitespaceBeforeError(n1, reason) + } + } + switch t := stmt.(type) { case *ast.IfStmt: checkingErrInitializedInline := func() bool { @@ -460,7 +481,12 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { } if atLeastOneInListsMatch(assignedOnLineAbove, p.config.ErrorVariableNames) { - p.addError(t.Pos(), reasonMustCuddleErrCheck) + p.addErrorRange( + stmt.Pos(), + previousStatement.End(), + stmt.Pos(), + reasonMustCuddleErrCheck, + ) } } @@ -468,12 +494,12 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { } if len(assignedOnLineAbove) == 0 { - p.addError(t.Pos(), reasonOnlyCuddleIfWithAssign) + p.addWhitespaceBeforeError(t, reasonOnlyCuddleIfWithAssign) continue } - if moreThanOneStatementAbove() { - p.addError(t.Pos(), reasonOnlyOneCuddle) + if nStatementsBefore(2) { + reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeIf) continue } @@ -485,33 +511,34 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { continue } - p.addError(t.Pos(), reasonOnlyCuddleWithUsedAssign) + p.addWhitespaceBeforeError(t, reasonOnlyCuddleWithUsedAssign) case *ast.ReturnStmt: if isLastStatementInBlockOfOnlyTwoLines() { continue } - p.addError(t.Pos(), reasonOnlyCuddle2LineReturn) + p.addWhitespaceBeforeError(t, reasonOnlyCuddle2LineReturn) case *ast.BranchStmt: if isLastStatementInBlockOfOnlyTwoLines() { continue } - p.addError(t.Pos(), reasonMultiLineBranchCuddle) + p.addWhitespaceBeforeError(t, reasonMultiLineBranchCuddle) case *ast.AssignStmt: // append is usually an assignment but should not be allowed to be // cuddled with anything not appended. if len(rightHandSide) > 0 && rightHandSide[len(rightHandSide)-1] == "append" { if p.config.StrictAppend { if !atLeastOneInListsMatch(calledOrAssignedOnLineAbove, rightHandSide) { - p.addError(t.Pos(), reasonAppendCuddledWithoutUse) + p.addWhitespaceBeforeError(t, reasonAppendCuddledWithoutUse) } } continue } - if _, ok := previousStatement.(*ast.AssignStmt); ok { + switch previousStatement.(type) { + case *ast.AssignStmt, *ast.IncDecStmt: continue } @@ -535,10 +562,18 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { } } - p.addError(t.Pos(), reasonAssignsCuddleAssign) + p.addWhitespaceBeforeError(t, reasonAssignsCuddleAssign) + case *ast.IncDecStmt: + switch previousStatement.(type) { + case *ast.AssignStmt, *ast.IncDecStmt: + continue + } + + p.addWhitespaceBeforeError(t, reasonAssignsCuddleAssign) + case *ast.DeclStmt: if !p.config.AllowCuddleDeclaration { - p.addError(t.Pos(), reasonNeverCuddleDeclare) + p.addWhitespaceBeforeError(t, reasonNeverCuddleDeclare) } case *ast.ExprStmt: switch previousStatement.(type) { @@ -547,9 +582,9 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { continue } - p.addError(t.Pos(), reasonExpressionCuddledWithDeclOrRet) - case *ast.IfStmt, *ast.RangeStmt, *ast.SwitchStmt: - p.addError(t.Pos(), reasonExpressionCuddledWithBlock) + p.addWhitespaceBeforeError(t, reasonExpressionCuddledWithDeclOrRet) + case *ast.IfStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.ForStmt: + p.addWhitespaceBeforeError(t, reasonExpressionCuddledWithBlock) } // If the expression is called on a type or variable used or @@ -567,17 +602,17 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { // If we assigned variables on the line above but didn't use them in // this expression there should probably be a newline between them. if len(assignedOnLineAbove) > 0 && !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) { - p.addError(t.Pos(), reasonExprCuddlingNonAssignedVar) + p.addWhitespaceBeforeError(t, reasonExprCuddlingNonAssignedVar) } case *ast.RangeStmt: - if moreThanOneStatementAbove() { - p.addError(t.Pos(), reasonOneCuddleBeforeRange) + if nStatementsBefore(2) { + reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeRange) continue } if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) { if !atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) { - p.addError(t.Pos(), reasonRangeCuddledWithoutUse) + p.addWhitespaceBeforeError(t, reasonRangeCuddledWithoutUse) } } case *ast.DeferStmt: @@ -586,27 +621,38 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { continue } - // Special treatment of deferring body closes after error checking - // according to best practices. See - // https://github.com/bombsimon/wsl/issues/31 which links to - // discussion about error handling after HTTP requests. This is hard - // coded and very specific but for now this is to be seen as a - // special case. What this does is that it *only* allows a defer - // statement with `Close` on the right hand side to be cuddled with - // an if-statement to support this: - // resp, err := client.Do(req) - // if err != nil { - // return err - // } - // defer resp.Body.Close() - if _, ok := previousStatement.(*ast.IfStmt); ok { - if atLeastOneInListsMatch(rightHandSide, []string{"Close"}) { - continue + if nStatementsBefore(2) { + // We allow cuddling defer if the defer references something + // used two lines above. + // There are several reasons to why we do this. + // Originally there was a special use case only for "Close" + // + // https://github.com/bombsimon/wsl/issues/31 which links to + // resp, err := client.Do(req) + // if err != nil { + // return err + // } + // defer resp.Body.Close() + // + // After a discussion in a followup issue it makes sense to not + // only hard code `Close` but for anything that's referenced two + // statements above. + // + // https://github.com/bombsimon/wsl/issues/85 + // db, err := OpenDB() + // require.NoError(t, err) + // defer db.Close() + // + // All of this is only allowed if there's exactly three cuddled + // statements, otherwise the regular rules apply. + if !nStatementsBefore(3) && !nStatementsAfter(1) { + variablesTwoLinesAbove := append(p.findLHS(statements[i-2]), p.findRHS(statements[i-2])...) + if atLeastOneInListsMatch(rightHandSide, variablesTwoLinesAbove) { + continue + } } - } - if moreThanOneStatementAbove() { - p.addError(t.Pos(), reasonOneCuddleBeforeDefer) + reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeDefer) continue } @@ -620,7 +666,7 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { } // Allow use to cuddled defer func literals with usages on line - // abouve. Example: + // above. Example: // b := getB() // defer func() { // makesSenseToUse(b) @@ -638,18 +684,16 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { } if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) { - p.addError(t.Pos(), reasonDeferCuddledWithOtherVar) + p.addWhitespaceBeforeError(t, reasonDeferCuddledWithOtherVar) } case *ast.ForStmt: if len(rightAndLeftHandSide) == 0 { - p.addError(t.Pos(), reasonForWithoutCondition) - + p.addWhitespaceBeforeError(t, reasonForWithoutCondition) continue } - if moreThanOneStatementAbove() { - p.addError(t.Pos(), reasonForWithMoreThanOneCuddle) - + if nStatementsBefore(2) { + reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeFor) continue } @@ -658,7 +702,7 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { // first line in the block for details. if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) { if !atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) { - p.addError(t.Pos(), reasonForCuddledAssignWithoutUse) + p.addWhitespaceBeforeError(t, reasonForCuddledAssignWithoutUse) } } case *ast.GoStmt: @@ -666,9 +710,8 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { continue } - if moreThanOneStatementAbove() { - p.addError(t.Pos(), reasonOneCuddleBeforeGo) - + if nStatementsBefore(2) { + reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeGo) continue } @@ -689,26 +732,24 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { } if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) { - p.addError(t.Pos(), reasonGoFuncWithoutAssign) + p.addWhitespaceBeforeError(t, reasonGoFuncWithoutAssign) } case *ast.SwitchStmt: - if moreThanOneStatementAbove() { - p.addError(t.Pos(), reasonSwitchManyCuddles) - + if nStatementsBefore(2) { + reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeSwitch) continue } if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) { if len(rightAndLeftHandSide) == 0 { - p.addError(t.Pos(), reasonAnonSwitchCuddled) + p.addWhitespaceBeforeError(t, reasonAnonSwitchCuddled) } else { - p.addError(t.Pos(), reasonSwitchCuddledWithoutUse) + p.addWhitespaceBeforeError(t, reasonSwitchCuddledWithoutUse) } } case *ast.TypeSwitchStmt: - if moreThanOneStatementAbove() { - p.addError(t.Pos(), reasonTypeSwitchTooCuddled) - + if nStatementsBefore(2) { + reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeTypeSwitch) continue } @@ -717,11 +758,11 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { // Allow type assertion on variables used in the first case // immediately. if !atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) { - p.addError(t.Pos(), reasonTypeSwitchCuddledWithoutUse) + p.addWhitespaceBeforeError(t, reasonTypeSwitchCuddledWithoutUse) } } case *ast.CaseClause, *ast.CommClause: - // Case clauses will be checked by not allowing leading ot trailing + // Case clauses will be checked by not allowing leading of trailing // whitespaces within the block. There's nothing in the case itself // that may be cuddled. default: @@ -735,7 +776,7 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { // directly as the first argument inside a body. // The body will then be parsed as a *ast.BlockStmt (regular block) or as a list // of []ast.Stmt (case block). -func (p *Processor) firstBodyStatement(i int, allStmt []ast.Stmt) ast.Node { +func (p *processor) firstBodyStatement(i int, allStmt []ast.Stmt) ast.Node { stmt := allStmt[i] // Start by checking if the statement has a body (probably if-statement, @@ -766,7 +807,14 @@ func (p *Processor) firstBodyStatement(i int, allStmt []ast.Stmt) ast.Node { } } - p.parseBlockBody(nil, statementBodyContent) + // If statement bodies will be parsed already when finding block bodies. + // The reason is because if/else-if/else chains is nested in the AST + // where the else bit is a part of the if statement. Since if statements + // is the only statement that can be chained like this we exclude it + // from parsing it again here. + if _, ok := stmt.(*ast.IfStmt); !ok { + p.parseBlockBody(nil, statementBodyContent) + } case []ast.Stmt: // The Body field for an *ast.CaseClause or *ast.CommClause is of type // []ast.Stmt. We must check leading and trailing whitespaces and then @@ -791,7 +839,7 @@ func (p *Processor) firstBodyStatement(i int, allStmt []ast.Stmt) ast.Node { return firstBodyStatement } -func (p *Processor) findLHS(node ast.Node) []string { +func (p *processor) findLHS(node ast.Node) []string { var lhs []string if node == nil { @@ -850,7 +898,7 @@ func (p *Processor) findLHS(node ast.Node) []string { return lhs } -func (p *Processor) findRHS(node ast.Node) []string { +func (p *processor) findRHS(node ast.Node) []string { var rhs []string if node == nil { @@ -934,7 +982,7 @@ func (p *Processor) findRHS(node ast.Node) []string { return rhs } -func (p *Processor) isShortDecl(node ast.Node) bool { +func (p *processor) isShortDecl(node ast.Node) bool { if t, ok := node.(*ast.AssignStmt); ok { return t.Tok == token.DEFINE } @@ -942,16 +990,22 @@ func (p *Processor) isShortDecl(node ast.Node) bool { return false } -func (p *Processor) findBlockStmt(node ast.Node) []*ast.BlockStmt { +func (p *processor) findBlockStmt(node ast.Node) []*ast.BlockStmt { var blocks []*ast.BlockStmt switch t := node.(type) { + case *ast.BlockStmt: + return []*ast.BlockStmt{t} case *ast.AssignStmt: for _, x := range t.Rhs { blocks = append(blocks, p.findBlockStmt(x)...) } case *ast.CallExpr: blocks = append(blocks, p.findBlockStmt(t.Fun)...) + + for _, x := range t.Args { + blocks = append(blocks, p.findBlockStmt(x)...) + } case *ast.FuncLit: blocks = append(blocks, t.Body) case *ast.ExprStmt: @@ -964,6 +1018,8 @@ func (p *Processor) findBlockStmt(node ast.Node) []*ast.BlockStmt { blocks = append(blocks, p.findBlockStmt(t.Call)...) case *ast.GoStmt: blocks = append(blocks, p.findBlockStmt(t.Call)...) + case *ast.IfStmt: + blocks = append([]*ast.BlockStmt{t.Body}, p.findBlockStmt(t.Else)...) } return blocks @@ -1020,15 +1076,15 @@ func atLeastOneInListsMatch(listOne, listTwo []string) bool { // findLeadingAndTrailingWhitespaces will find leading and trailing whitespaces // in a node. The method takes comments in consideration which will make the // parser more gentle. -func (p *Processor) findLeadingAndTrailingWhitespaces(ident *ast.Ident, stmt, nextStatement ast.Node) { +func (p *processor) findLeadingAndTrailingWhitespaces(ident *ast.Ident, stmt, nextStatement ast.Node) { var ( - allowedLinesBeforeFirstStatement = 1 - commentMap = ast.NewCommentMap(p.fileSet, stmt, p.file.Comments) - blockStatements []ast.Stmt - blockStartLine int - blockEndLine int - blockStartPos token.Pos - blockEndPos token.Pos + commentMap = ast.NewCommentMap(p.fileSet, stmt, p.file.Comments) + blockStatements []ast.Stmt + blockStartLine int + blockEndLine int + blockStartPos token.Pos + blockEndPos token.Pos + isCase bool ) // Depending on the block type, get the statements in the block and where @@ -1041,9 +1097,11 @@ func (p *Processor) findLeadingAndTrailingWhitespaces(ident *ast.Ident, stmt, ne case *ast.CaseClause: blockStatements = t.Body blockStartPos = t.Colon + isCase = true case *ast.CommClause: blockStatements = t.Body blockStartPos = t.Colon + isCase = true default: p.addWarning(warnWSNodeTypeNotImplemented, stmt.Pos(), stmt) @@ -1055,8 +1113,8 @@ func (p *Processor) findLeadingAndTrailingWhitespaces(ident *ast.Ident, stmt, ne return } - blockStartLine = p.fileSet.Position(blockStartPos).Line - blockEndLine = p.fileSet.Position(blockEndPos).Line + blockStartLine = p.fileSet.PositionFor(blockStartPos, false).Line + blockEndLine = p.fileSet.PositionFor(blockEndPos, false).Line // No whitespace possible if LBrace and RBrace is on the same line. if blockStartLine == blockEndLine { @@ -1064,152 +1122,238 @@ func (p *Processor) findLeadingAndTrailingWhitespaces(ident *ast.Ident, stmt, ne } var ( - firstStatement = blockStatements[0] - lastStatement = blockStatements[len(blockStatements)-1] - seenCommentGroups = 0 + firstStatement = blockStatements[0] + lastStatement = blockStatements[len(blockStatements)-1] ) - // Get the comment related to the first statement, we do allow commends in + // Get the comment related to the first statement, we do allow comments in // the beginning of a block before the first statement. - if c, ok := commentMap[firstStatement]; ok { - for _, commentGroup := range c { - // If the comment group is on the same line as the block start - // (LBrace) we should not consider it. - if p.nodeStart(commentGroup) == blockStartLine { + var ( + openingNodePos = blockStartPos + 1 + lastLeadingComment ast.Node + ) + + var ( + firstStatementCommentGroups []*ast.CommentGroup + lastStatementCommentGroups []*ast.CommentGroup + ) + + if cg, ok := commentMap[firstStatement]; ok && !isCase { + firstStatementCommentGroups = cg + } else { + // TODO: Just like with trailing whitespaces comments in a case block is + // tied to the last token of the first statement. For now we iterate over + // all comments in the stmt and grab those that's after colon and before + // first statement. + for _, cg := range commentMap { + if len(cg) < 1 { continue } - // We only care about comments before our statement from the comment - // map. As soon as we hit comments after our statement let's break - // out! - if commentGroup.Pos() > firstStatement.Pos() { - break + // If we have comments and the last comment ends before the first + // statement and the node is after the colon, this must be the node + // mapped to comments. + for _, c := range cg { + if c.End() < firstStatement.Pos() && c.Pos() > blockStartPos { + firstStatementCommentGroups = append(firstStatementCommentGroups, c) + } } - // We store number of seen comment groups because we allow multiple - // groups with a newline between them; but if the first one has WS - // before it, we're not going to count it to force an error. - if p.config.AllowSeparatedLeadingComment { - cg := p.fileSet.Position(commentGroup.Pos()).Line + // And same if we have comments where the first comment is after the + // last statement but before the next statement (next case). As with + // the other things, if there is not next statement it's no next + // case and the logic will be handled when parsing the block. + if nextStatement == nil { + continue + } - if seenCommentGroups > 0 || cg == blockStartLine+1 { - seenCommentGroups++ + for _, c := range cg { + if c.Pos() > lastStatement.End() && c.End() < nextStatement.Pos() { + lastStatementCommentGroups = append(lastStatementCommentGroups, c) } - } else { - seenCommentGroups++ } + } + + // Since the comments come from a map they might not be ordered meaning + // that the last and first comment groups can be in the wrong order. We + // fix this by sorting all comments by pos after adding them all to the + // slice. + sort.Slice(firstStatementCommentGroups, func(i, j int) bool { + return firstStatementCommentGroups[i].Pos() < firstStatementCommentGroups[j].Pos() + }) + + sort.Slice(lastStatementCommentGroups, func(i, j int) bool { + return lastStatementCommentGroups[i].Pos() < lastStatementCommentGroups[j].Pos() + }) + } - // Support both /* multiline */ and //single line comments - for _, c := range commentGroup.List { - allowedLinesBeforeFirstStatement += len(strings.Split(c.Text, "\n")) + for _, commentGroup := range firstStatementCommentGroups { + // If the comment group is on the same line as the block start + // (LBrace) we should not consider it. + if p.nodeEnd(commentGroup) == blockStartLine { + openingNodePos = commentGroup.End() + continue + } + + // We only care about comments before our statement from the comment + // map. As soon as we hit comments after our statement let's break + // out! + if commentGroup.Pos() > firstStatement.Pos() { + break + } + + // We never allow leading whitespace for the first comment. + if lastLeadingComment == nil && p.nodeStart(commentGroup)-1 != blockStartLine { + p.addErrorRange( + openingNodePos, + openingNodePos, + commentGroup.Pos(), + reasonBlockStartsWithWS, + ) + } + + // If lastLeadingComment is set this is not the first comment so we + // should remove whitespace between them if we don't explicitly + // allow it. + if lastLeadingComment != nil && !p.config.AllowSeparatedLeadingComment { + if p.nodeStart(commentGroup)+1 != p.nodeEnd(lastLeadingComment) { + p.addErrorRange( + openingNodePos, + lastLeadingComment.End(), + commentGroup.Pos(), + reasonBlockStartsWithWS, + ) } } + + lastLeadingComment = commentGroup } - // If we allow separated comments, allow for a space after each group - if p.config.AllowSeparatedLeadingComment { - if seenCommentGroups > 1 { - allowedLinesBeforeFirstStatement += seenCommentGroups - 1 - } else if seenCommentGroups == 1 { - allowedLinesBeforeFirstStatement++ - } + lastNodePos := openingNodePos + if lastLeadingComment != nil { + lastNodePos = lastLeadingComment.End() + blockStartLine = p.nodeEnd(lastLeadingComment) } - // And now if the first statement is passed the number of allowed lines, - // then we had extra WS, possibly before the first comment group. - if p.nodeStart(firstStatement) > blockStartLine+allowedLinesBeforeFirstStatement { - p.addError( - blockStartPos, + // Check if we have a whitespace between the last node which can be the + // Lbrace, a comment on the same line or the last comment if we have + // comments inside the actual block and the first statement. This is never + // allowed. + if p.nodeStart(firstStatement)-1 != blockStartLine { + p.addErrorRange( + openingNodePos, + lastNodePos, + firstStatement.Pos(), reasonBlockStartsWithWS, ) } // If the blockEndLine is not 0 we're a regular block (not case). if blockEndLine != 0 { - if p.config.AllowTrailingComment { - if lastComment, ok := commentMap[lastStatement]; ok { - var ( - lastCommentGroup = lastComment[len(lastComment)-1] - lastCommentLine = lastCommentGroup.List[len(lastCommentGroup.List)-1] - countNewlines = 0 - ) + // We don't want to reject example functions since they have to end with + // a comment. + if isExampleFunc(ident) { + return + } - countNewlines += len(strings.Split(lastCommentLine.Text, "\n")) + var ( + lastNode ast.Node = lastStatement + trailingComments []ast.Node + ) - // No newlines between trailing comments and end of block. - if p.nodeStart(lastCommentLine)+countNewlines != blockEndLine-1 { - return + // Check if we have an comments _after_ the last statement and update + // the last node if so. + if c, ok := commentMap[lastStatement]; ok { + lastComment := c[len(c)-1] + if lastComment.Pos() > lastStatement.End() && lastComment.Pos() < stmt.End() { + lastNode = lastComment + } + } + + // TODO: This should be improved. + // The trailing comments are mapped to the last statement item which can + // be anything depending on what the last statement is. + // In `fmt.Println("hello")`, trailing comments will be mapped to + // `*ast.BasicLit` for the "hello" string. + // A short term improvement can be to cache this but for now we naively + // iterate over all items when we check a block. + for _, commentGroups := range commentMap { + for _, commentGroup := range commentGroups { + if commentGroup.Pos() < lastNode.End() || commentGroup.End() > stmt.End() { + continue } + + trailingComments = append(trailingComments, commentGroup) } } - if p.nodeEnd(lastStatement) != blockEndLine-1 && !isExampleFunc(ident) { - p.addError(blockEndPos, reasonBlockEndsWithWS) + // TODO: Should this be relaxed? + // Given the old code we only allowed trailing newline if it was + // directly tied to the last statement so for backwards compatibility + // we'll do the same. This means we fail all but the last whitespace + // even when allowing trailing comments. + for _, comment := range trailingComments { + if p.nodeStart(comment)-p.nodeEnd(lastNode) > 1 { + p.addErrorRange( + blockEndPos, + lastNode.End(), + comment.Pos(), + reasonBlockEndsWithWS, + ) + } + + lastNode = comment + } + + if !p.config.AllowTrailingComment && p.nodeEnd(stmt)-1 != p.nodeEnd(lastStatement) { + p.addErrorRange( + blockEndPos, + lastNode.End(), + stmt.End()-1, + reasonBlockEndsWithWS, + ) } return } + // Nothing to do if we're not looking for enforced newline. + if p.config.ForceCaseTrailingWhitespaceLimit == 0 { + return + } + // If we don't have any nextStatement the trailing whitespace will be // handled when parsing the switch. If we do have a next statement we can // see where it starts by getting it's colon position. We set the end of the // current case to the position of the next case. - switch n := nextStatement.(type) { - case *ast.CaseClause: - blockEndPos = n.Case - case *ast.CommClause: - blockEndPos = n.Case + switch nextStatement.(type) { + case *ast.CaseClause, *ast.CommClause: default: // No more cases return } - blockEndLine = p.fileSet.Position(blockEndPos).Line - 1 - - var ( - blockSize = blockEndLine - blockStartLine - caseTrailingCommentLines int - ) - - // TODO: I don't know what comments are bound to in cases. For regular - // blocks the last comment is bound to the last statement but for cases - // they are bound to the case clause expression. This will however get us all - // comments and depending on the case expression this gets tricky. - // - // To handle this I get the comment map from the current statement (the case - // itself) and iterate through all groups and all comment within all groups. - // I then get the comments after the last statement but before the next case - // clause and just map each line of comment that way. - for _, commentGroups := range commentMap { - for _, commentGroup := range commentGroups { - for _, comment := range commentGroup.List { - commentLine := p.fileSet.Position(comment.Pos()).Line - - // Ignore comments before the last statement. - if commentLine <= p.nodeStart(lastStatement) { - continue - } - - // Ignore comments after the end of this case. - if commentLine > blockEndLine { - continue - } - - // This allows /* multiline */ comments with newlines as well - // as regular (//) ones - caseTrailingCommentLines += len(strings.Split(comment.Text, "\n")) - } - } + var closingNode ast.Node = lastStatement + for _, commentGroup := range lastStatementCommentGroups { + // TODO: In future versions we might want to close the gaps between + // comments. However this is not currently reported in v3 so we + // won't add this for now. + // if p.nodeStart(commentGroup)-1 != p.nodeEnd(closingNode) {} + closingNode = commentGroup } - hasTrailingWhitespace := p.nodeEnd(lastStatement)+caseTrailingCommentLines != blockEndLine + totalRowsInCase := p.nodeEnd(closingNode) - blockStartLine + if totalRowsInCase < p.config.ForceCaseTrailingWhitespaceLimit { + return + } - // If the force trailing limit is configured and we don't end with a newline. - if p.config.ForceCaseTrailingWhitespaceLimit > 0 && !hasTrailingWhitespace { - // Check if the block size is too big to miss the newline. - if blockSize >= p.config.ForceCaseTrailingWhitespaceLimit { - p.addError(lastStatement.Pos(), reasonCaseBlockTooCuddly) - } + if p.nodeEnd(closingNode)+1 == p.nodeStart(nextStatement) { + p.addErrorRange( + closingNode.Pos(), + closingNode.End(), + closingNode.End(), + reasonCaseBlockTooCuddly, + ) } } @@ -1217,15 +1361,15 @@ func isExampleFunc(ident *ast.Ident) bool { return ident != nil && strings.HasPrefix(ident.Name, "Example") } -func (p *Processor) nodeStart(node ast.Node) int { - return p.fileSet.Position(node.Pos()).Line +func (p *processor) nodeStart(node ast.Node) int { + return p.fileSet.PositionFor(node.Pos(), false).Line } -func (p *Processor) nodeEnd(node ast.Node) int { - line := p.fileSet.Position(node.End()).Line +func (p *processor) nodeEnd(node ast.Node) int { + line := p.fileSet.PositionFor(node.End(), false).Line if isEmptyLabeledStmt(node) { - return p.fileSet.Position(node.Pos()).Line + return p.fileSet.PositionFor(node.Pos(), false).Line } return line @@ -1242,21 +1386,29 @@ func isEmptyLabeledStmt(node ast.Node) bool { return empty } -// Add an error for the file and line number for the current token.Pos with the -// given reason. -func (p *Processor) addError(pos token.Pos, reason string) { - position := p.fileSet.Position(pos) +func (p *processor) addWhitespaceBeforeError(node ast.Node, reason string) { + p.addErrorRange(node.Pos(), node.Pos(), node.Pos(), reason) +} + +func (p *processor) addErrorRange(reportAt, start, end token.Pos, reason string) { + report, ok := p.result[reportAt] + if !ok { + report = result{ + reason: reason, + fixRanges: []fix{}, + } + } - p.result = append(p.result, Result{ - FileName: position.Filename, - LineNumber: position.Line, - Position: position, - Reason: reason, + report.fixRanges = append(report.fixRanges, fix{ + fixRangeStart: start, + fixRangeEnd: end, }) + + p.result[reportAt] = report } -func (p *Processor) addWarning(w string, pos token.Pos, t interface{}) { - position := p.fileSet.Position(pos) +func (p *processor) addWarning(w string, pos token.Pos, t interface{}) { + position := p.fileSet.PositionFor(pos, false) p.warnings = append(p.warnings, fmt.Sprintf("%s:%d: %s (%T)", position.Filename, position.Line, w, t), diff --git a/tools/vendor/github.com/butuzov/ireturn/analyzer/analyzer.go b/tools/vendor/github.com/butuzov/ireturn/analyzer/analyzer.go index 21e5897b2..f68170fb3 100644 --- a/tools/vendor/github.com/butuzov/ireturn/analyzer/analyzer.go +++ b/tools/vendor/github.com/butuzov/ireturn/analyzer/analyzer.go @@ -4,6 +4,7 @@ import ( "flag" "go/ast" gotypes "go/types" + "runtime" "strings" "sync" @@ -22,10 +23,11 @@ type validator interface { } type analyzer struct { - once sync.Once - mu sync.RWMutex - handler validator - err error + once sync.Once + mu sync.RWMutex + handler validator + err error + diabledNolint bool found []analysis.Diagnostic } @@ -61,8 +63,7 @@ func (a *analyzer) run(pass *analysis.Pass) (interface{}, error) { } // 003. Is it allowed to be checked? - // TODO(butuzov): add inline comment - if hasDisallowDirective(f.Doc) { + if !a.diabledNolint && hasDisallowDirective(f.Doc) { return } @@ -70,7 +71,6 @@ func (a *analyzer) run(pass *analysis.Pass) (interface{}, error) { // 004. Filtering Results. for _, issue := range filterInterfaces(pass, f.Type, dotImportedStd) { - if a.handler.IsValid(issue) { continue } @@ -112,6 +112,13 @@ func (a *analyzer) readConfiguration(fs *flag.FlagSet) { return } + // First: checking nonolint directive + val := fs.Lookup("nonolint") + if val != nil { + a.diabledNolint = fs.Lookup("nonolint").Value.String() == "true" + } + + // Second: validators implementation next if validatorImpl, ok := cnf.(validator); ok { a.handler = validatorImpl return @@ -136,6 +143,7 @@ func flags() flag.FlagSet { set := flag.NewFlagSet("", flag.PanicOnError) set.String("allow", "", "accept-list of the comma-separated interfaces") set.String("reject", "", "reject-list of the comma-separated interfaces") + set.Bool("nonolint", false, "disable nolint checks") return *set } @@ -146,13 +154,10 @@ func filterInterfaces(p *analysis.Pass, ft *ast.FuncType, di map[string]struct{} return results } - tp := newTypeParams(ft.TypeParams) - for _, el := range ft.Results.List { switch v := el.Type.(type) { // ----- empty or anonymous interfaces case *ast.InterfaceType: - if len(v.Methods.List) == 0 { results = append(results, types.NewIssue("interface{}", types.EmptyInterface)) continue @@ -164,35 +169,65 @@ func filterInterfaces(p *analysis.Pass, ft *ast.FuncType, di map[string]struct{} case *ast.Ident: t1 := p.TypesInfo.TypeOf(el.Type) - if !gotypes.IsInterface(t1.Underlying()) { + val, ok := t1.Underlying().(*gotypes.Interface) + if !ok { continue } - word := t1.String() - // only build in interface is error - if obj := gotypes.Universe.Lookup(word); obj != nil { - results = append(results, types.NewIssue(obj.Name(), types.ErrorInterface)) + var ( + name = t1.String() + isNamed = strings.Contains(name, ".") + isEmpty = val.Empty() + ) + + // catching any + if isEmpty && name == "any" { + results = append(results, types.NewIssue(name, types.EmptyInterface)) + continue + } + + // NOTE: FIXED! + if name == "error" { + results = append(results, types.NewIssue(name, types.ErrorInterface)) continue } - // found in type params - if tp.In(word) { - results = append(results, types.NewIssue(word, types.Generic)) + if !isNamed { + + typeParams := val.String() + prefix, suffix := "interface{", "}" + if strings.HasPrefix(typeParams, prefix) { // nolint: gosimple + typeParams = typeParams[len(prefix):] + } + if strings.HasSuffix(typeParams, suffix) { + typeParams = typeParams[:len(typeParams)-1] + } + + goVersion := runtime.Version() + if strings.HasPrefix(goVersion, "go1.18") || strings.HasPrefix(goVersion, "go1.19") { + typeParams = strings.ReplaceAll(typeParams, "|", " | ") + } + + results = append(results, types.IFace{ + Name: name, + Type: types.Generic, + OfType: typeParams, + }) continue } // is it dot-imported package? // handling cases when stdlib package imported via "." dot-import if len(di) > 0 { - name := stdPkgInterface(word) - if _, ok := di[name]; ok { - results = append(results, types.NewIssue(word, types.NamedStdInterface)) + pkgName := stdPkgInterface(name) + if _, ok := di[pkgName]; ok { + results = append(results, types.NewIssue(name, types.NamedStdInterface)) continue } } - results = append(results, types.NewIssue(word, types.NamedInterface)) + results = append(results, types.NewIssue(name, types.NamedInterface)) // ------- standard library and 3rd party interfaces case *ast.SelectorExpr: diff --git a/tools/vendor/github.com/butuzov/ireturn/analyzer/internal/types/iface.go b/tools/vendor/github.com/butuzov/ireturn/analyzer/internal/types/iface.go index 13f19a3e2..5e576374d 100644 --- a/tools/vendor/github.com/butuzov/ireturn/analyzer/internal/types/iface.go +++ b/tools/vendor/github.com/butuzov/ireturn/analyzer/internal/types/iface.go @@ -14,6 +14,7 @@ type IFace struct { Pos token.Pos // Token Position FuncName string // + OfType string } func NewIssue(name string, interfaceType IType) IFace { @@ -30,11 +31,15 @@ func (i *IFace) Enrich(f *ast.FuncDecl) { } func (i IFace) String() string { - if i.Type == Generic { - return fmt.Sprintf("%s returns generic interface (%s)", i.FuncName, i.Name) + if i.Type != Generic { + return fmt.Sprintf("%s returns interface (%s)", i.FuncName, i.Name) } - return fmt.Sprintf("%s returns interface (%s)", i.FuncName, i.Name) + if i.OfType != "" { + return fmt.Sprintf("%s returns generic interface (%s) of type param %s", i.FuncName, i.Name, i.OfType) + } + + return fmt.Sprintf("%s returns generic interface (%s)", i.FuncName, i.Name) } func (i IFace) HashString() string { diff --git a/tools/vendor/github.com/butuzov/ireturn/analyzer/std.go b/tools/vendor/github.com/butuzov/ireturn/analyzer/std.go index 4c6c4e420..cac464612 100644 --- a/tools/vendor/github.com/butuzov/ireturn/analyzer/std.go +++ b/tools/vendor/github.com/butuzov/ireturn/analyzer/std.go @@ -197,4 +197,7 @@ var std = map[string]struct{}{ "maps": {}, "slices": {}, "testing/slogtest": {}, + // added in Go v1.22 in compare to v1.21 (docker image) + "go/version": {}, + "math/rand/v2": {}, } diff --git a/tools/vendor/github.com/butuzov/ireturn/analyzer/typeparams.go b/tools/vendor/github.com/butuzov/ireturn/analyzer/typeparams.go deleted file mode 100644 index 14193c355..000000000 --- a/tools/vendor/github.com/butuzov/ireturn/analyzer/typeparams.go +++ /dev/null @@ -1,38 +0,0 @@ -package analyzer - -import ( - "go/ast" -) - -type typeParams struct { - found []string -} - -func newTypeParams(fl *ast.FieldList) typeParams { - tp := typeParams{} - - if fl == nil { - return tp - } - - for _, el := range fl.List { - if el == nil { - continue - } - - for _, name := range el.Names { - tp.found = append(tp.found, name.Name) - } - } - - return tp -} - -func (tp typeParams) In(t string) bool { - for _, i := range tp.found { - if i == t { - return true - } - } - return false -} diff --git a/tools/vendor/github.com/butuzov/mirror/.act b/tools/vendor/github.com/butuzov/mirror/.act deleted file mode 100644 index 8182d703a..000000000 --- a/tools/vendor/github.com/butuzov/mirror/.act +++ /dev/null @@ -1,2 +0,0 @@ ---platform ubuntu-latest=butuzov/act-go:latest ---env DRY_RUN=1 diff --git a/tools/vendor/github.com/butuzov/mirror/.goreleaser.yaml b/tools/vendor/github.com/butuzov/mirror/.goreleaser.yaml index 11749ed2b..fa91fa97e 100644 --- a/tools/vendor/github.com/butuzov/mirror/.goreleaser.yaml +++ b/tools/vendor/github.com/butuzov/mirror/.goreleaser.yaml @@ -5,33 +5,17 @@ builds: - binary: mirror env: - CGO_ENABLED=0 + main: ./cmd/mirror/ + flags: + - -trimpath + ldflags: -s -w goos: - - darwin - linux + - darwin - windows goarch: - amd64 - - 386 - arm64 - - arm - goarm: - - 6 - ignore: - - goos: windows - goarm: 6 - - goos: windows - goarch: arm64 - - goos: linux - goarm: 6 - - goos: darwin - goarch: 386 - main: ./cmd/mirror/ - flags: - - -trimpath - ldflags: -s -w - -checksum: - name_template: 'checksums.txt' changelog: sort: asc @@ -45,14 +29,15 @@ changelog: - Merge pull request - Merge branch + +checksum: + name_template: 'checksums.txt' + + archives: - - name_template: '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}{{ if .Mips }}_{{ .Mips }}{{ end }}' - replacements: - darwin: darwin - linux: linux - windows: windows - 386: i386 - amd64: x86_64 + - format: tar.gz + name_template: >- + {{ .ProjectName }}_{{- tolower .Os }}_{{ .Arch }} format_overrides: - goos: windows format: zip diff --git a/tools/vendor/github.com/butuzov/mirror/MIRROR_FUNCS.md b/tools/vendor/github.com/butuzov/mirror/MIRROR_FUNCS.md index 776816e51..3dcc01e96 100644 --- a/tools/vendor/github.com/butuzov/mirror/MIRROR_FUNCS.md +++ b/tools/vendor/github.com/butuzov/mirror/MIRROR_FUNCS.md @@ -1,150 +1,201 @@ - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + -
func (b *bufio.Writer) WriteString(s string) (int, error) - func (b *bufio.Writer) Write(p []byte) (int, error) - func (b *bufio.Writer) WriteRune(r rune) (int, error) -
func (*bufio.Writer) Write([]byte) (int, error)func (*bufio.Writer) WriteString(string) (int, error)
func (*bufio.Writer) WriteRune(rune) (int, error)func (*bufio.Writer) WriteString(string) (int, error)
func (*bytes.Buffer) Write([]byte) (int, error)func (*bytes.Buffer) WriteString(string) (int, error)
func (*bytes.Buffer) WriteRune(rune) (int, error)func (*bytes.Buffer) WriteString(string) (int, error)
func bytes.Compare([]byte, []byte) intfunc strings.Compare(string, string) int
func bytes.Contains([]byte, []byte) boolfunc strings.Contains(string, string) bool
func bytes.ContainsAny([]byte, string) boolfunc strings.ContainsAny(string, string) bool
func bytes.ContainsRune([]byte, byte) boolfunc strings.ContainsRune(string, byte) bool
func bytes.Count([]byte, []byte) intfunc strings.Count(string, string) int
func bytes.EqualFold([]byte, []byte) boolfunc strings.EqualFold(string, string) bool
func bytes.HasPrefix([]byte, []byte) boolfunc strings.HasPrefix(string, string) bool
func bytes.HasSuffix([]byte, []byte) boolfunc strings.HasSuffix(string, string) bool
func bytes.Index([]byte, []byte) intfunc strings.Index(string, string) int
func bytes.IndexAny([]byte, string) intfunc strings.IndexAny(string, string) int
func bytes.IndexByte([]byte, byte) intfunc strings.IndexByte(string, byte) int
func bytes.IndexFunc([]byte, func(rune) bool) intfunc strings.IndexFunc(string, func(rune) bool) int
func (b *bytes.Buffer) WriteString(s string) (int, error) - func (b *bytes.Buffer) Write(p []byte) (int, error) - func (b *bytes.Buffer) WriteRune(r rune) (int, error) - func bytes.IndexRune([]byte, rune) intfunc strings.IndexRune(string, rune) int
func strings.Compare(a, b string) intfunc bytes.Compare(a, b []byte) intfunc bytes.LastIndex([]byte, []byte) intfunc strings.LastIndex(string, string) int
func strings.Contains(s, substr string) boolfunc bytes.Contains(b, subslice []byte) boolfunc bytes.LastIndexAny([]byte, string) intfunc strings.LastIndexAny(string, string) int
func strings.ContainsAny(s, chars string) boolfunc bytes.ContainsAny(b []byte, chars string) boolfunc bytes.LastIndexByte([]byte, byte) intfunc strings.LastIndexByte(string, byte) int
func strings.ContainsRune(s string, r rune) boolfunc bytes.ContainsRune(b []byte, r rune) boolfunc bytes.LastIndexFunc([]byte, func(rune) bool) intfunc strings.LastIndexFunc(string, func(rune) bool) int
func strings.Count(s, substr string) intfunc bytes.Count(s, sep []byte) intfunc bytes.NewBuffer([]byte) *bytes.Bufferfunc bytes.NewBufferString(string) *bytes.Buffer
func strings.EqualFold(s, t string) boolfunc bytes.EqualFold(s, t []byte) boolfunc (*httptest.ResponseRecorder) Write([]byte) (int, error)func (*httptest.ResponseRecorder) WriteString(string) (int, error)
func strings.HasPrefix(s, prefix string) boolfunc bytes.HasPrefix(s, prefix []byte) boolfunc (*maphash.Hash) Write([]byte) (int, error)func (*maphash.Hash) WriteString(string) (int, error)
func strings.HasSuffix(s, suffix string) boolfunc bytes.HasSuffix(s, suffix []byte) boolfunc (*os.File) Write([]byte) (int, error)func (*os.File) WriteString(string) (int, error)
func strings.Index(s, substr string) intfunc bytes.Index(s, sep []byte) intfunc regexp.Match(string, []byte) (bool, error)func regexp.MatchString(string, string) (bool, error)
func strings.IndexAny(s, chars string) intfunc bytes.IndexAny(s []byte, chars string) intfunc (*regexp.Regexp) FindAllIndex([]byte, int) [][]intfunc (*regexp.Regexp) FindAllStringIndex(string, int) [][]int
func strings.IndexByte(s string, c byte) intfunc bytes.IndexByte(b []byte, c byte) intfunc (*regexp.Regexp) FindAllSubmatchIndex([]byte, int) [][]intfunc (*regexp.Regexp) FindAllStringSubmatchIndex(string, int) [][]int
func strings.IndexFunc(s string, f func(rune) bool) intfunc bytes.IndexFunc(s []byte, f func(r rune) bool) intfunc (*regexp.Regexp) FindIndex([]byte) []intfunc (*regexp.Regexp) FindStringIndex(string) []int
func strings.IndexRune(s string, r rune) intfunc bytes.IndexRune(s []byte, r rune) intfunc (*regexp.Regexp) FindSubmatchIndex([]byte) []intfunc (*regexp.Regexp) FindStringSubmatchIndex(string) []int
func strings.LastIndex(s, sep string) intfunc bytes.LastIndex(s, sep []byte) intfunc (*regexp.Regexp) Match([]byte) boolfunc (*regexp.Regexp) MatchString(string) bool
func strings.LastIndexAny(s, chars string) intfunc bytes.LastIndexAny(s []byte, chars string) intfunc (*strings.Builder) Write([]byte) (int, error)func (*strings.Builder) WriteString(string) (int, error)
func strings.LastIndexByte(s string, c byte) intfunc bytes.LastIndexByte(s []byte, c byte) intfunc (*strings.Builder) WriteRune(rune) (int, error)func (*strings.Builder) WriteString(string) (int, error)
func strings.LastIndexFunc(s string, f func(rune) bool) intfunc bytes.LastIndexFunc(s []byte, f func(r rune) bool) intfunc strings.Compare(string) intfunc bytes.Compare([]byte) int
func bytes.NewBufferString(s string) *bytes.Bufferfunc bytes.NewBuffer(buf []byte *bytes.Bufferfunc strings.Contains(string) boolfunc bytes.Contains([]byte) bool
func (h *hash/maphash.Hash) WriteString(s string) (int, error)func (h *hash/maphash.Hash) Write(b []byte) (int, error)func strings.ContainsAny(string) boolfunc bytes.ContainsAny([]byte) bool
func (rw *net/http/httptest.ResponseRecorder) WriteString(str string) (int, error)func (rw *net/http/httptest.ResponseRecorder) Write(buf []byte) (int, error)func strings.ContainsRune(string) boolfunc bytes.ContainsRune([]byte) bool
func (f *os.File) WriteString(s string) (n int, err error)func (f *os.File) Write(b []byte) (n int, err error)func strings.EqualFold(string) boolfunc bytes.EqualFold([]byte) bool
func regexp.MatchString(pattern string, s string) (bool, error)func regexp.Match(pattern string, b []byte) (bool, error)func strings.HasPrefix(string) boolfunc bytes.HasPrefix([]byte) bool
func (re *regexp.Regexp) FindAllStringIndex(s string, n int) [][]intfunc (re *regexp.Regexp) FindAllIndex(b []byte, n int) [][]intfunc strings.HasSuffix(string) boolfunc bytes.HasSuffix([]byte) bool
func (re *regexp.Regexp) FindAllStringSubmatch(s string, n int) [][]stringfunc (re *regexp.Regexp) FindAllSubmatch(b []byte, n int) [][][]bytefunc strings.Index(string) intfunc bytes.Index([]byte) int
func (re *regexp.Regexp) FindStringIndex(s string) (loc []int)func (re *regexp.Regexp) FindIndex(b []byte) (loc []int)func strings.IndexFunc(string, func(r rune) bool) intfunc bytes.IndexFunc([]byte, func(r rune) bool) int
func (re *regexp.Regexp) FindStringSubmatchIndex(s string) []intfunc (re *regexp.Regexp) FindSubmatchIndex(b []byte) []intfunc strings.LastIndex(string) intfunc bytes.LastIndex([]byte) int
func (re *regexp.Regexp) MatchString(s string) boolfunc (re *regexp.Regexp) Match(b []byte) boolfunc strings.LastIndexAny(string) intfunc bytes.LastIndexAny([]byte) int
func (b *strings.Builder) WriteString(s string) error - func (b *strings.Builder) Write(p []byte) (int, error) - func (b *strings.Builder) WriteRune(r rune) (int, error) - func strings.LastIndexFunc(string, func(r rune) bool) intfunc bytes.LastIndexFunc([]byte, func(r rune) bool) int
func utf8.ValidString(s string) boolfunc utf8.Valid(p []byte) boolfunc utf8.DecodeLastRune([]byte) (rune, int)func utf8.DecodeLastRuneInString(string) (rune, int)
func utf8.FullRuneInString(s string) boolfunc utf8.FullRune(p []byte) boolfunc utf8.DecodeRune([]byte) (rune, int)func utf8.DecodeRuneInString(string) (rune, int)
func utf8.RuneCountInString(s string) (n int)func utf8.RuneCount(p []byte) intfunc utf8.FullRune([]byte) boolfunc utf8.FullRuneInString(string) bool
func utf8.DecodeLastRuneInString(s string) (rune, int)func utf8.DecodeLastRune(p []byte) (rune, int)func utf8.RuneCount([]byte) intfunc utf8.RuneCountInString(string) int
func utf8.DecodeRuneInString(s string) (une, int)func utf8.DecodeRune(p []byte) (rune, int)func utf8.Valid([]byte) boolfunc utf8.ValidString(string) bool
+ diff --git a/tools/vendor/github.com/butuzov/mirror/Makefile b/tools/vendor/github.com/butuzov/mirror/Makefile index b4b952b01..ac267208f 100644 --- a/tools/vendor/github.com/butuzov/mirror/Makefile +++ b/tools/vendor/github.com/butuzov/mirror/Makefile @@ -2,57 +2,130 @@ export PATH := $(PWD)/bin:$(PATH) # ./bin to $PATH export SHELL := bash # Default Shell -GOPKGS := $(shell go list ./... | grep -vE "(cmd|sandbox|testdata)" | tr -s '\n' ',' | sed 's/.\{1\}$$//' ) +define install_go_bin + @ which $(1) 2>&1 1>/dev/null || GOBIN=$(PWD)/bin go install $(2) +endef +.DEFAULT_GOAL := help -build: - @ go build -trimpath -ldflags="-w -s" \ - -o bin/mirror ./cmd/mirror/ +# Generate Artifacts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +generate: ## Generate Assets + $(MAKE) -build-race: - @ go build -race -trimpath -ldflags="-w -s" \ - -o bin/mirror ./cmd/mirror/ +generate-tests: ## Generates Assets at testdata + go run ./cmd/internal/tests/ "$(PWD)/testdata" -tests: - go test -v -count=1 -race \ +generate-mirror-table: ## Generate Asset MIRROR_FUNCS.md + go run ./cmd/internal/mirror-table/ > "$(PWD)/MIRROR_FUNCS.md" + + +# Build Artifacts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +build: ## Build binary + @ go build -trimpath -ldflags="-w -s" -o bin/mirror ./cmd/mirror/ + +build-race: ## Build binary with race flag + @ go build -race -trimpath -ldflags="-w -s" -o bin/mirror ./cmd/mirror/ + +install: ## Installs binary + @ go install -trimpath -v -ldflags="-w -s" ./cmd/mirror + +# Run Tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +tests: ## Run Tests (Summary) + @ go test -v -count=1 -race \ -failfast \ -parallel=2 \ -timeout=1m \ -covermode=atomic \ - -coverpkg=$(GOPKGS) -coverprofile=coverage.cov ./... + -coverprofile=coverage.cov ./... -tests-summary: - go test -v -count=1 -race \ +tests-summary: ## Run Tests, but shows summary +tests-summary: bin/tparse + @ go test -v -count=1 -race \ -failfast \ -parallel=2 \ -timeout=1m \ -covermode=atomic \ - -coverpkg=$(GOPKGS) -coverprofile=coverage.cov --json ./... | tparse -all + -coverprofile=coverage.cov --json ./... | tparse -all -test-generate: - go run ./cmd/internal/generate-tests/ "$(PWD)/testdata" +# Linter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +lints: ## Run golangci-lint +lints: bin/golangci-lint lints: - golangci-lint run --no-config ./... -D deadcode --skip-dirs "^(cmd|sandbox|testdata)" + golangci-lint run --no-config ./... --skip-dirs "^(cmd|testdata)" -cover: - go tool cover -html=coverage.cov +cover: ## Run Coverage + @ go tool cover -html=coverage.cov + +# Other ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +test-release: bin/goreleaser + goreleaser release --help + goreleaser release --skip=publish --skip=validate --clean + +# Install ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -install: - go install -trimpath -v -ldflags="-w -s" \ - ./cmd/mirror +bin/tparse: ## Installs tparse@v0.13.2 (if not exists) +bin/tparse: INSTALL_URL=github.com/mfridman/tparse@v0.13.2 +bin/tparse: + $(call install_go_bin, tparse, $(INSTALL_URL)) -funcs: - echo "" > "out/results.txt" - go list std | grep -v "vendor" | grep -v "internal" | \ - xargs -I {} sh -c 'go doc -all {} > out/$(basename {}).txt' +bin/golangci-lint: ## Installs golangci-lint@v1.55.2 (if not exists) +bin/golangci-lint: INSTALL_URL=github.com/golangci/golangci-lint@v1.55.2 +bin/golangci-lint: + $(call install_go_bin, golangci-lint, $(INSTALL_URL)) +bin/goreleaser: ## Installs goreleaser@v1.24.0 (if not exists) +bin/goreleaser: INSTALL_URL=github.com/goreleaser/goreleaser@v1.24.0 bin/goreleaser: - @curl -Ls https://github.com/goreleaser/goreleaser/releases/download/v1.17.2/goreleaser_Darwin_all.tar.gz | tar -zOxf - goreleaser > ./bin/goreleaser - chmod 0755 ./bin/goreleaser + $(call install_go_bin, goreleaser, $(INSTALL_URL)) -test-release: bin/goreleaser - goreleaser release --help - goreleaser release -f .goreleaser.yaml \ - --skip-validate --skip-publish --clean +# Help ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +help: dep-gawk + @ echo "==============================================================================" + @ echo " Makefile: github.com/butuzov/mirror " + @ echo "==============================================================================" + @ cat $(MAKEFILE_LIST) | \ + grep -E '^# ~~~ .*? [~]+$$|^[a-zA-Z0-9_-]+:.*?## .*$$' | \ + gawk '{if ( $$1=="#" ) { \ + match($$0, /^# ~~~ (.+?) [~]+$$/, a);\ + {print "\n", a[1], ""}\ + } else { \ + match($$0, /^([a-zA-Z/_-]+):.*?## (.*)$$/, a); \ + {printf " - \033[32m%-20s\033[0m %s\n", a[1], a[2]} \ + }}' + @ echo "" + + +# Helper Mehtods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +dep-gawk: + @ if [ -z "$(shell command -v gawk)" ]; then \ + if [ -x /usr/local/bin/brew ]; then $(MAKE) _brew_gawk_install; exit 0; fi; \ + if [ -x /usr/bin/apt-get ]; then $(MAKE) _ubuntu_gawk_install; exit 0; fi; \ + if [ -x /usr/bin/yum ]; then $(MAKE) _centos_gawk_install; exit 0; fi; \ + if [ -x /sbin/apk ]; then $(MAKE) _alpine_gawk_install; exit 0; fi; \ + echo "GNU Awk Required.";\ + exit 1; \ + fi + +_brew_gawk_install: + @ echo "Instaling gawk using brew... " + @ brew install gawk --quiet + @ echo "done" + +_ubuntu_gawk_install: + @ echo "Instaling gawk using apt-get... " + @ apt-get -q install gawk -y + @ echo "done" + +_alpine_gawk_install: + @ echo "Instaling gawk using yum... " + @ apk add --update --no-cache gawk + @ echo "done" + +_centos_gawk_install: + @ echo "Instaling gawk using yum... " + @ yum install -q -y gawk; + @ echo "done" diff --git a/tools/vendor/github.com/butuzov/mirror/Taskfile.yml b/tools/vendor/github.com/butuzov/mirror/Taskfile.yml index 26c9ba257..4bc7cfeda 100644 --- a/tools/vendor/github.com/butuzov/mirror/Taskfile.yml +++ b/tools/vendor/github.com/butuzov/mirror/Taskfile.yml @@ -1,28 +1,73 @@ version: '3' tasks: - default: - sources: - - "./**/*.go" - method: timestamp - cmds: - - clear - - make build - - make build-race - - task: lints - # - make test-generate - - task: tests - - cmd: go run ./cmd/mirror/ --with-tests --with-debug ./sandbox - ignore_error: true - - testcase: go test -v -failfast -count=1 -run "TestAll/{{ .Case }}" ./... - - tests: - cmds: - - cmd: make tests - ignore_error: true - - lints: - cmds: - - cmd: make lints - ignore_error: true + default: task --list-all + + # Continues Development ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + watcher: + desc: watcher + sources: + - ./**/*.go + method: timestamp + cmds: + - task: lints + - task: test-summary + - task: build-race + + # Generating assets ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + generate: + desc: Generate Assets + sources: + - ./checkers_*.go + - ./cmd/internal/**/*.go + method: timestamp + cmds: + - task generate-mirror-table + - task generate-tests + + generate-mirror-table: + desc: Generates Assets at testdata + cmd: make generate-mirror-table + + generate-tests: + desc: Generate Asset MIRROR_FUNCS.md + cmd: make generate-tests + + # Run Tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + tests: + desc: Run Tests + cmd: make tests + ignore_error: true + + test-summary: + desc: Run Tests (Summary) + cmd: make tests-summary + ignore_error: true + + testcase: go test -v -failfast -count=1 -run "TestAll/{{ .Case }}" ./... + + # Build Artifacts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + build: + desc: Build binary + cmd: make build + + build-race: + desc: Build binary with race flag + cmd: make build-race + + install: + desc: Install binary + cmd: make install + + # Linter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + lints: + cmd: make lints + + # Other + cover: + desc: Run Coverage + cmd: make cover + + test-release: + desc: Testing Release + cmd: make test-release diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_bufio.go b/tools/vendor/github.com/butuzov/mirror/checkers_bufio.go index 292ed269a..0985edad3 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_bufio.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_bufio.go @@ -15,7 +15,7 @@ var BufioMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `b := bufio.Writer{}`, Pattern: `Write($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*bufio.Writer).WriteString @@ -30,7 +30,7 @@ var BufioMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `b := bufio.Writer{}`, Pattern: `WriteString($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*bufio.Writer).WriteString -> (*bufio.Writer).WriteRune @@ -42,15 +42,11 @@ var BufioMethods = []checker.Violation{ Args: []int{0}, ArgsType: checker.Rune, AltCaller: "WriteRune", + + Generate: &checker.Generate{ + SkipGenerate: true, + Pattern: `WriteString($0)`, + Returns: []string{"int", "error"}, + }, }, - // { // (*bufio.Writer).WriteString -> (*bufio.Writer).WriteByte - // Targets: checker.Strings, - // Type: checker.Method, - // Package: "strings", - // Struct: "Builder", - // Caller: "WriteString", - // Args: []int{0}, - // ArgsType: checker.Byte, - // AltCaller: "WriteByte", // byte - // }, } diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_bytes.go b/tools/vendor/github.com/butuzov/mirror/checkers_bytes.go index c490a3784..b8819879c 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_bytes.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_bytes.go @@ -14,7 +14,7 @@ var ( Generate: &checker.Generate{ Pattern: `NewBuffer($0)`, - Returns: 1, + Returns: []string{"*bytes.Buffer"}, }, }, { // bytes.NewBufferString @@ -27,7 +27,7 @@ var ( Generate: &checker.Generate{ Pattern: `NewBufferString($0)`, - Returns: 1, + Returns: []string{"*bytes.Buffer"}, }, }, { // bytes.Compare: @@ -41,7 +41,7 @@ var ( Generate: &checker.Generate{ Pattern: `Compare($0, $1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.Contains: @@ -55,7 +55,7 @@ var ( Generate: &checker.Generate{ Pattern: `Contains($0, $1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // bytes.ContainsAny @@ -69,7 +69,7 @@ var ( Generate: &checker.Generate{ Pattern: `ContainsAny($0, "f")`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // bytes.ContainsRune @@ -83,7 +83,7 @@ var ( Generate: &checker.Generate{ Pattern: `ContainsRune($0, 'ф')`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // bytes.Count @@ -97,7 +97,7 @@ var ( Generate: &checker.Generate{ Pattern: `Count($0, $1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.EqualFold @@ -111,7 +111,7 @@ var ( Generate: &checker.Generate{ Pattern: `EqualFold($0, $1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, @@ -126,7 +126,7 @@ var ( Generate: &checker.Generate{ Pattern: `HasPrefix($0, $1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // bytes.HasSuffix @@ -140,7 +140,7 @@ var ( Generate: &checker.Generate{ Pattern: `HasSuffix($0, $1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // bytes.Index @@ -154,7 +154,7 @@ var ( Generate: &checker.Generate{ Pattern: `Index($0, $1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.IndexAny @@ -168,7 +168,7 @@ var ( Generate: &checker.Generate{ Pattern: `IndexAny($0, "f")`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.IndexByte @@ -182,7 +182,7 @@ var ( Generate: &checker.Generate{ Pattern: `IndexByte($0, 'f')`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.IndexFunc @@ -196,7 +196,7 @@ var ( Generate: &checker.Generate{ Pattern: `IndexFunc($0, func(rune) bool {return true })`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.IndexRune @@ -210,7 +210,7 @@ var ( Generate: &checker.Generate{ Pattern: `IndexRune($0, rune('ф'))`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.LastIndex @@ -224,7 +224,7 @@ var ( Generate: &checker.Generate{ Pattern: `LastIndex($0, $1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.LastIndexAny @@ -238,7 +238,7 @@ var ( Generate: &checker.Generate{ Pattern: `LastIndexAny($0, "ф")`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.LastIndexByte @@ -252,7 +252,7 @@ var ( Generate: &checker.Generate{ Pattern: `LastIndexByte($0, 'f')`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.LastIndexFunc @@ -266,7 +266,7 @@ var ( Generate: &checker.Generate{ Pattern: `LastIndexFunc($0, func(rune) bool {return true })`, - Returns: 1, + Returns: []string{"int"}, }, }, } @@ -284,7 +284,7 @@ var ( Generate: &checker.Generate{ PreCondition: `bb := bytes.Buffer{}`, Pattern: `Write($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*bytes.Buffer).WriteString @@ -299,7 +299,7 @@ var ( Generate: &checker.Generate{ PreCondition: `bb := bytes.Buffer{}`, Pattern: `WriteString($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*bytes.Buffer).WriteString -> (*bytes.Buffer).WriteRune @@ -311,6 +311,11 @@ var ( Args: []int{0}, ArgsType: checker.Rune, AltCaller: "WriteRune", + Generate: &checker.Generate{ + SkipGenerate: true, + Pattern: `WriteString($0)`, + Returns: []string{"int", "error"}, + }, }, // { // (*bytes.Buffer).WriteString -> (*bytes.Buffer).WriteByte // Targets: checker.Strings, diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_httptest.go b/tools/vendor/github.com/butuzov/mirror/checkers_httptest.go index ae6750930..c28bb1ade 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_httptest.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_httptest.go @@ -15,7 +15,7 @@ var HTTPTestMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `h := httptest.ResponseRecorder{}`, Pattern: `Write($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*net/http/httptest.ResponseRecorder).WriteString @@ -30,7 +30,7 @@ var HTTPTestMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `h := httptest.ResponseRecorder{}`, Pattern: `WriteString($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, } diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_maphash.go b/tools/vendor/github.com/butuzov/mirror/checkers_maphash.go index 4d184d2a9..0aa43ff7b 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_maphash.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_maphash.go @@ -15,7 +15,7 @@ var MaphashMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `h := maphash.Hash{}`, Pattern: `Write($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*hash/maphash).WriteString @@ -30,7 +30,7 @@ var MaphashMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `h := maphash.Hash{}`, Pattern: `WriteString($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, } diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_os.go b/tools/vendor/github.com/butuzov/mirror/checkers_os.go index 09f5a18e5..40973576b 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_os.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_os.go @@ -15,7 +15,7 @@ var OsFileMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `f := &os.File{}`, Pattern: `Write($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*os.File).WriteString @@ -30,7 +30,7 @@ var OsFileMethods = []checker.Violation{ Generate: &checker.Generate{ PreCondition: `f := &os.File{}`, Pattern: `WriteString($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, } diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_regexp.go b/tools/vendor/github.com/butuzov/mirror/checkers_regexp.go index 17175e028..2cd4dc9f8 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_regexp.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_regexp.go @@ -14,7 +14,7 @@ var ( Generate: &checker.Generate{ Pattern: `Match("foo", $0)`, - Returns: 2, + Returns: []string{"bool", "error"}, }, }, { // regexp.MatchString @@ -27,7 +27,7 @@ var ( Generate: &checker.Generate{ Pattern: `MatchString("foo", $0)`, - Returns: 2, + Returns: []string{"bool", "error"}, }, }, } @@ -45,7 +45,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `Match($0)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // (*regexp.Regexp).MatchString @@ -60,7 +60,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `MatchString($0)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // (*regexp.Regexp).FindAllIndex @@ -75,7 +75,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindAllIndex($0, 1)`, - Returns: 1, + Returns: []string{"[][]int"}, }, }, { // (*regexp.Regexp).FindAllStringIndex @@ -90,7 +90,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindAllStringIndex($0, 1)`, - Returns: 1, + Returns: []string{"[][]int"}, }, }, { // (*regexp.Regexp).FindAllSubmatchIndex @@ -105,7 +105,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindAllSubmatchIndex($0, 1)`, - Returns: 1, + Returns: []string{"[][]int"}, }, }, { // (*regexp.Regexp).FindAllStringSubmatchIndex @@ -120,7 +120,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindAllStringSubmatchIndex($0, 1)`, - Returns: 1, + Returns: []string{"[][]int"}, }, }, { // (*regexp.Regexp).FindIndex @@ -135,7 +135,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindIndex($0)`, - Returns: 1, + Returns: []string{"[]int"}, }, }, { // (*regexp.Regexp).FindStringIndex @@ -150,7 +150,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindStringIndex($0)`, - Returns: 1, + Returns: []string{"[]int"}, }, }, { // (*regexp.Regexp).FindSubmatchIndex @@ -165,7 +165,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindSubmatchIndex($0)`, - Returns: 1, + Returns: []string{"[]int"}, }, }, { // (*regexp.Regexp).FindStringSubmatchIndex @@ -180,7 +180,7 @@ var ( Generate: &checker.Generate{ PreCondition: `re := regexp.MustCompile(".*")`, Pattern: `FindStringSubmatchIndex($0)`, - Returns: 1, + Returns: []string{"[]int"}, }, }, } diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_strings.go b/tools/vendor/github.com/butuzov/mirror/checkers_strings.go index ead7e9cc7..3bd59a62f 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_strings.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_strings.go @@ -15,7 +15,7 @@ var ( Generate: &checker.Generate{ Pattern: `Compare($0,$1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // strings.Contains @@ -29,7 +29,7 @@ var ( Generate: &checker.Generate{ Pattern: `Contains($0,$1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // strings.ContainsAny @@ -43,7 +43,7 @@ var ( Generate: &checker.Generate{ Pattern: `ContainsAny($0,"foobar")`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // strings.ContainsRune @@ -57,7 +57,7 @@ var ( Generate: &checker.Generate{ Pattern: `ContainsRune($0,'ф')`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // strings.Count @@ -71,7 +71,7 @@ var ( Generate: &checker.Generate{ Pattern: `Count($0, $1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // strings.EqualFold @@ -85,7 +85,7 @@ var ( Generate: &checker.Generate{ Pattern: `EqualFold($0,$1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // strings.HasPrefix @@ -99,7 +99,7 @@ var ( Generate: &checker.Generate{ Pattern: `HasPrefix($0,$1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // strings.HasSuffix @@ -113,7 +113,7 @@ var ( Generate: &checker.Generate{ Pattern: `HasSuffix($0,$1)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // strings.Index @@ -127,7 +127,7 @@ var ( Generate: &checker.Generate{ Pattern: `Index($0,$1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // strings.IndexAny @@ -141,7 +141,7 @@ var ( Generate: &checker.Generate{ Pattern: `IndexAny($0, "f")`, - Returns: 1, + Returns: []string{"int"}, }, }, { // strings.IndexByte @@ -154,8 +154,8 @@ var ( AltCaller: "IndexByte", Generate: &checker.Generate{ - Pattern: `IndexByte($0, byte('f'))`, - Returns: 1, + Pattern: `IndexByte($0, 'f')`, + Returns: []string{"int"}, }, }, { // strings.IndexFunc @@ -168,8 +168,8 @@ var ( AltCaller: "IndexFunc", Generate: &checker.Generate{ - Pattern: `IndexFunc($0,func(r rune) bool { return true })`, - Returns: 1, + Pattern: `IndexFunc($0, func(r rune) bool { return true })`, + Returns: []string{"int"}, }, }, { // strings.IndexRune @@ -183,7 +183,7 @@ var ( Generate: &checker.Generate{ Pattern: `IndexRune($0, rune('ф'))`, - Returns: 1, + Returns: []string{"int"}, }, }, { // strings.LastIndex @@ -197,7 +197,7 @@ var ( Generate: &checker.Generate{ Pattern: `LastIndex($0,$1)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // strings.LastIndexAny @@ -211,7 +211,7 @@ var ( Generate: &checker.Generate{ Pattern: `LastIndexAny($0,"f")`, - Returns: 1, + Returns: []string{"int"}, }, }, { // strings.LastIndexByte @@ -224,8 +224,8 @@ var ( AltCaller: "LastIndexByte", Generate: &checker.Generate{ - Pattern: `LastIndexByte($0, byte('f'))`, - Returns: 1, + Pattern: `LastIndexByte($0, 'f')`, + Returns: []string{"int"}, }, }, { // strings.LastIndexFunc @@ -239,7 +239,7 @@ var ( Generate: &checker.Generate{ Pattern: `LastIndexFunc($0, func(r rune) bool { return true })`, - Returns: 1, + Returns: []string{"int"}, }, }, } @@ -257,7 +257,7 @@ var ( Generate: &checker.Generate{ PreCondition: `builder := strings.Builder{}`, Pattern: `Write($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*strings.Builder).WriteString @@ -272,7 +272,7 @@ var ( Generate: &checker.Generate{ PreCondition: `builder := strings.Builder{}`, Pattern: `WriteString($0)`, - Returns: 2, + Returns: []string{"int", "error"}, }, }, { // (*strings.Builder).WriteString -> (*strings.Builder).WriteRune @@ -284,6 +284,11 @@ var ( Args: []int{0}, ArgsType: checker.Rune, AltCaller: "WriteRune", + Generate: &checker.Generate{ + SkipGenerate: true, + Pattern: `WriteString($0)`, + Returns: []string{"int", "error"}, + }, }, // { // (*strings.Builder).WriteString -> (*strings.Builder).WriteByte // Targets: checker.Strings, diff --git a/tools/vendor/github.com/butuzov/mirror/checkers_utf8.go b/tools/vendor/github.com/butuzov/mirror/checkers_utf8.go index e7c4d5ba4..fd3010c37 100644 --- a/tools/vendor/github.com/butuzov/mirror/checkers_utf8.go +++ b/tools/vendor/github.com/butuzov/mirror/checkers_utf8.go @@ -13,7 +13,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `Valid($0)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // utf8.ValidString @@ -26,7 +26,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `ValidString($0)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // utf8.FullRune @@ -39,7 +39,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `FullRune($0)`, - Returns: 1, + Returns: []string{"bool"}, }, }, { // utf8.FullRuneInString @@ -52,7 +52,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `FullRuneInString($0)`, - Returns: 1, + Returns: []string{"bool"}, }, }, @@ -66,7 +66,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `RuneCount($0)`, - Returns: 1, + Returns: []string{"int"}, }, }, { // bytes.RuneCountInString @@ -79,7 +79,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `RuneCountInString($0)`, - Returns: 1, + Returns: []string{"int"}, }, }, @@ -93,7 +93,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `DecodeLastRune($0)`, - Returns: 2, + Returns: []string{"rune", "int"}, }, }, { // utf8.DecodeLastRuneInString @@ -106,7 +106,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `DecodeLastRuneInString($0)`, - Returns: 2, + Returns: []string{"rune", "int"}, }, }, { // utf8.DecodeRune @@ -119,7 +119,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `DecodeRune($0)`, - Returns: 2, + Returns: []string{"rune", "int"}, }, }, { // utf8.DecodeRuneInString @@ -132,7 +132,7 @@ var UTF8Functions = []checker.Violation{ Generate: &checker.Generate{ Pattern: `DecodeRuneInString($0)`, - Returns: 2, + Returns: []string{"rune", "int"}, }, }, } diff --git a/tools/vendor/github.com/butuzov/mirror/internal/checker/violation.go b/tools/vendor/github.com/butuzov/mirror/internal/checker/violation.go index 375d3c8e6..3d8acf141 100644 --- a/tools/vendor/github.com/butuzov/mirror/internal/checker/violation.go +++ b/tools/vendor/github.com/butuzov/mirror/internal/checker/violation.go @@ -52,9 +52,10 @@ type Violation struct { // Tests (generation) related struct. type Generate struct { - PreCondition string // Precondition we want to be generated - Pattern string // Generate pattern (for the `want` message) - Returns int // Expected to return n elements + SkipGenerate bool + PreCondition string // Precondition we want to be generated + Pattern string // Generate pattern (for the `want` message) + Returns []string // ReturnTypes as slice } func (v *Violation) With(base []byte, e *ast.CallExpr, args map[int]ast.Expr) *Violation { @@ -165,7 +166,7 @@ type GolangIssue struct { Original string } -// Issue inteanded to be used only with golangci-lint, bu you can use use it +// Issue intended to be used only within `golangci-lint`, bu you can use use it // alongside Diagnostic if you wish. func (v *Violation) Issue(fSet *token.FileSet) GolangIssue { issue := GolangIssue{ @@ -174,7 +175,7 @@ func (v *Violation) Issue(fSet *token.FileSet) GolangIssue { Message: v.Message(), } - // original expression (useful for debug & requied for replace) + // original expression (useful for debug & required for replace) var buf bytes.Buffer printer.Fprint(&buf, fSet, v.callExpr) issue.Original = buf.String() diff --git a/tools/vendor/github.com/butuzov/mirror/readme.md b/tools/vendor/github.com/butuzov/mirror/readme.md index fcfd1de11..f830ea72e 100644 --- a/tools/vendor/github.com/butuzov/mirror/readme.md +++ b/tools/vendor/github.com/butuzov/mirror/readme.md @@ -1,10 +1,7 @@ -# `mirror` [![Code Coverage](https://coveralls.io/repos/github/butuzov/mirror/badge.svg?branch=main)](https://coveralls.io/github/butuzov/mirror?branch=main) [![build status](https://github.com/butuzov/mirror/actions/workflows/main.yaml/badge.svg?branch=main)]() +# `mirror` [![Stand with Ukraine](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/badges/StandWithUkraine.svg)](https://u24.gov.ua/) [![Code Coverage](https://coveralls.io/repos/github/butuzov/mirror/badge.svg?branch=main)](https://coveralls.io/github/butuzov/mirror?branch=main) [![build status](https://github.com/butuzov/mirror/actions/workflows/main.yaml/badge.svg?branch=main)]() `mirror` suggests use of alternative functions/methods in order to gain performance boosts by avoiding unnecessary `[]byte/string` conversion calls. See [MIRROR_FUNCS.md](MIRROR_FUNCS.md) list of mirror functions you can use in go's stdlib. -## 🇺🇦 PLEASE HELP ME 🇺🇦 -Fundrise for scout drone **DJI Matrice 30T** for my squad (Ukrainian Forces). See more details at [butuzov/README.md](https://github.com/butuzov/butuzov/) - ## Linter Use Cases ### `github.com/argoproj/argo-cd` @@ -35,6 +32,10 @@ func IsValidHostname(hostname string, fqdn bool) bool { go install github.com/butuzov/mirror/cmd/mirror@latest ``` +### `golangci-lint` +`golangci-lint` supports `mirror` since `v1.53.0` + + ## How to use You run `mirror` with [`go vet`](https://pkg.go.dev/cmd/vet): @@ -55,6 +56,59 @@ mirror ./... /air/runner/util.go:173:14: avoid allocations with (*os.File).WriteString ``` +With [`golangci-lint`](https://github.com/golangci/golangci-lint) + +``` +golangci-lint run --no-config --disable-all -Emirror +# github.com/argoproj/argo-cd +test/e2e/fixture/app/actions.go:83:11: avoid allocations with (*os.File).WriteString (mirror) + _, err = tmpFile.Write([]byte(data)) + ^ +server/server.go:1166:9: avoid allocations with (*regexp.Regexp).MatchString (mirror) + return mainJsBundleRegex.Match([]byte(filename)) + ^ +server/account/account.go:91:6: avoid allocations with (*regexp.Regexp).MatchString (mirror) + if !validPasswordRegexp.Match([]byte(q.NewPassword)) { + ^ +server/badge/badge.go:52:20: avoid allocations with (*regexp.Regexp).FindAllStringSubmatchIndex (mirror) + for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) { + ^ +util/cert/cert.go:82:10: avoid allocations with (*regexp.Regexp).MatchString (mirror) + return validHostNameRegexp.Match([]byte(hostname)) || validIPv6Regexp.Match([]byte(hostname)) +``` + ## Command line - You can add checks for `_test.go` files with cli option `--with-tests` + +### `golangci-lint` + With `golangci-lint` tests are checked by default and can be can be turned off by using the regular `golangci-lint` ways to do it: + + - flag `--tests` (e.g. `--tests=false`) + - flag `--skip-files` (e.g. `--skip-files="_test.go"`) + - yaml confguration `run.skip-files`: + ```yaml + run: + skip-files: + - '(.+)_test\.go' + ``` + - yaml confguration `issues.exclude-rules`: + ```yaml + issues: + exclude-rules: + - path: '(.+)_test\.go' + linters: + - mirror + ``` + + +## Contributing + +```shell +# Update Assets (testdata/(strings|bytes|os|utf8|maphash|regexp|bufio).go) +(task|make) generated +# Run Tests +(task|make) tests +# Lint Code +(task|make) lints +``` diff --git a/tools/vendor/github.com/catenacyber/perfsprint/analyzer/analyzer.go b/tools/vendor/github.com/catenacyber/perfsprint/analyzer/analyzer.go index 69087802a..543b4bdbc 100644 --- a/tools/vendor/github.com/catenacyber/perfsprint/analyzer/analyzer.go +++ b/tools/vendor/github.com/catenacyber/perfsprint/analyzer/analyzer.go @@ -6,7 +6,9 @@ import ( "go/format" "go/token" "go/types" + "sort" "strconv" + "strings" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" @@ -14,24 +16,72 @@ import ( "golang.org/x/tools/go/analysis" ) -var Analyzer = &analysis.Analyzer{ - Name: "perfsprint", - Doc: "Checks that fmt.Sprintf can be replaced with a faster alternative.", - Run: run, - Requires: []*analysis.Analyzer{inspect.Analyzer}, +type perfSprint struct { + intConv bool + errError bool + errorf bool + sprintf1 bool + fiximports bool + strconcat bool } -func run(pass *analysis.Pass) (interface{}, error) { - var fmtSprintObj, fmtSprintfObj types.Object +func newPerfSprint() *perfSprint { + return &perfSprint{ + intConv: true, + errError: false, + errorf: true, + sprintf1: true, + fiximports: true, + strconcat: true, + } +} + +func New() *analysis.Analyzer { + n := newPerfSprint() + r := &analysis.Analyzer{ + Name: "perfsprint", + Doc: "Checks that fmt.Sprintf can be replaced with a faster alternative.", + Run: n.run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + } + r.Flags.BoolVar(&n.intConv, "int-conversion", true, "optimizes even if it requires an int or uint type cast") + r.Flags.BoolVar(&n.errError, "err-error", false, "optimizes into err.Error() even if it is only equivalent for non-nil errors") + r.Flags.BoolVar(&n.errorf, "errorf", true, "optimizes fmt.Errorf") + r.Flags.BoolVar(&n.sprintf1, "sprintf1", true, "optimizes fmt.Sprintf with only one argument") + r.Flags.BoolVar(&n.fiximports, "fiximports", true, "fix needed imports from other fixes") + r.Flags.BoolVar(&n.strconcat, "strconcat", true, "optimizes into strings concatenation") + return r +} + +// true if verb is a format string that could be replaced with concatenation. +func isConcatable(verb string) bool { + hasPrefix := + (strings.HasPrefix(verb, "%s") && !strings.Contains(verb, "%[1]s")) || + (strings.HasPrefix(verb, "%[1]s") && !strings.Contains(verb, "%s")) + hasSuffix := + (strings.HasSuffix(verb, "%s") && !strings.Contains(verb, "%[1]s")) || + (strings.HasSuffix(verb, "%[1]s") && !strings.Contains(verb, "%s")) + + if strings.Count(verb, "%[1]s") > 1 { + return false + } + return (hasPrefix || hasSuffix) && !(hasPrefix && hasSuffix) +} + +func (n *perfSprint) run(pass *analysis.Pass) (interface{}, error) { + var fmtSprintObj, fmtSprintfObj, fmtErrorfObj types.Object for _, pkg := range pass.Pkg.Imports() { if pkg.Path() == "fmt" { fmtSprintObj = pkg.Scope().Lookup("Sprint") fmtSprintfObj = pkg.Scope().Lookup("Sprintf") + fmtErrorfObj = pkg.Scope().Lookup("Errorf") } } - if fmtSprintfObj == nil { + if fmtSprintfObj == nil && fmtSprintObj == nil && fmtErrorfObj == nil { return nil, nil } + removedFmtUsages := make(map[string]int) + neededPackages := make(map[string]map[string]bool) insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) nodeFilter := []ast.Node{ @@ -52,11 +102,29 @@ func run(pass *analysis.Pass) (interface{}, error) { err error ) switch { + case calledObj == fmtErrorfObj && len(call.Args) == 1: + if n.errorf { + fn = "fmt.Errorf" + verb = "%s" + value = call.Args[0] + } else { + return + } + case calledObj == fmtSprintObj && len(call.Args) == 1: fn = "fmt.Sprint" verb = "%v" value = call.Args[0] + case calledObj == fmtSprintfObj && len(call.Args) == 1: + if n.sprintf1 { + fn = "fmt.Sprintf" + verb = "%s" + value = call.Args[0] + } else { + return + } + case calledObj == fmtSprintfObj && len(call.Args) == 2: verbLit, ok := call.Args[0].(*ast.BasicLit) if !ok { @@ -67,6 +135,10 @@ func run(pass *analysis.Pass) (interface{}, error) { // Probably unreachable. return } + // one single explicit arg is simplified + if strings.HasPrefix(verb, "%[1]") { + verb = "%" + verb[4:] + } fn = "fmt.Sprintf" value = call.Args[1] @@ -77,6 +149,9 @@ func run(pass *analysis.Pass) (interface{}, error) { switch verb { default: + if fn == "fmt.Sprintf" && isConcatable(verb) && n.strconcat { + break + } return case "%d", "%v", "%x", "%t", "%s": } @@ -88,24 +163,52 @@ func run(pass *analysis.Pass) (interface{}, error) { var d *analysis.Diagnostic switch { case isBasicType(valueType, types.String) && oneOf(verb, "%v", "%s"): - d = &analysis.Diagnostic{ - Pos: call.Pos(), - End: call.End(), - Message: fn + " can be replaced with just using the string", - SuggestedFixes: []analysis.SuggestedFix{ - { - Message: "Just use string value", - TextEdits: []analysis.TextEdit{{ - Pos: call.Pos(), - End: call.End(), - NewText: []byte(formatNode(pass.Fset, value)), - }}, + fname := pass.Fset.File(call.Pos()).Name() + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + removedFmtUsages[fname]++ + if fn == "fmt.Errorf" { + neededPackages[fname]["errors"] = true + d = &analysis.Diagnostic{ + Pos: call.Pos(), + End: call.End(), + Message: fn + " can be replaced with errors.New", + SuggestedFixes: []analysis.SuggestedFix{ + { + Message: "Use errors.New", + TextEdits: []analysis.TextEdit{{ + Pos: call.Pos(), + End: value.Pos(), + NewText: []byte("errors.New("), + }}, + }, }, - }, + } + } else { + d = &analysis.Diagnostic{ + Pos: call.Pos(), + End: call.End(), + Message: fn + " can be replaced with just using the string", + SuggestedFixes: []analysis.SuggestedFix{ + { + Message: "Just use string value", + TextEdits: []analysis.TextEdit{{ + Pos: call.Pos(), + End: call.End(), + NewText: []byte(formatNode(pass.Fset, value)), + }}, + }, + }, + } } - - case types.Implements(valueType, errIface) && oneOf(verb, "%v", "%s"): + case types.Implements(valueType, errIface) && oneOf(verb, "%v", "%s") && n.errError: + // known false positive if this error is nil + // fmt.Sprint(nil) does not panic like nil.Error() does errMethodCall := formatNode(pass.Fset, value) + ".Error()" + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -123,6 +226,13 @@ func run(pass *analysis.Pass) (interface{}, error) { } case isBasicType(valueType, types.Bool) && oneOf(verb, "%v", "%t"): + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["strconv"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -145,6 +255,13 @@ func run(pass *analysis.Pass) (interface{}, error) { return } + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["encoding/hex"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -168,6 +285,13 @@ func run(pass *analysis.Pass) (interface{}, error) { }, } case isSlice && isBasicType(s.Elem(), types.Uint8) && oneOf(verb, "%x"): + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["encoding/hex"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -184,7 +308,14 @@ func run(pass *analysis.Pass) (interface{}, error) { }, } - case isBasicType(valueType, types.Int8, types.Int16, types.Int32) && oneOf(verb, "%v", "%d"): + case isBasicType(valueType, types.Int8, types.Int16, types.Int32) && oneOf(verb, "%v", "%d") && n.intConv: + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["strconv"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -208,6 +339,13 @@ func run(pass *analysis.Pass) (interface{}, error) { }, } case isBasicType(valueType, types.Int) && oneOf(verb, "%v", "%d"): + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["strconv"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -224,6 +362,13 @@ func run(pass *analysis.Pass) (interface{}, error) { }, } case isBasicType(valueType, types.Int64) && oneOf(verb, "%v", "%d"): + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["strconv"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -247,7 +392,18 @@ func run(pass *analysis.Pass) (interface{}, error) { }, } - case isBasicType(valueType, types.Uint8, types.Uint16, types.Uint32, types.Uint) && oneOf(verb, "%v", "%d"): + case isBasicType(valueType, types.Uint8, types.Uint16, types.Uint32, types.Uint) && oneOf(verb, "%v", "%d", "%x") && n.intConv: + base := []byte("), 10") + if verb == "%x" { + base = []byte("), 16") + } + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["strconv"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -264,13 +420,24 @@ func run(pass *analysis.Pass) (interface{}, error) { { Pos: value.End(), End: value.End(), - NewText: []byte("), 10"), + NewText: base, }, }, }, }, } - case isBasicType(valueType, types.Uint64) && oneOf(verb, "%v", "%d"): + case isBasicType(valueType, types.Uint64) && oneOf(verb, "%v", "%d", "%x"): + base := []byte(", 10") + if verb == "%x" { + base = []byte(", 16") + } + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + _, ok := neededPackages[fname] + if !ok { + neededPackages[fname] = make(map[string]bool) + } + neededPackages[fname]["strconv"] = true d = &analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), @@ -287,20 +454,123 @@ func run(pass *analysis.Pass) (interface{}, error) { { Pos: value.End(), End: value.End(), - NewText: []byte(", 10"), + NewText: base, }, }, }, }, } + case isBasicType(valueType, types.String) && fn == "fmt.Sprintf" && isConcatable(verb): + var fix string + if strings.HasSuffix(verb, "%s") { + fix = strconv.Quote(verb[:len(verb)-2]) + "+" + formatNode(pass.Fset, value) + } else if strings.HasSuffix(verb, "%[1]s") { + fix = strconv.Quote(verb[:len(verb)-5]) + "+" + formatNode(pass.Fset, value) + } else if strings.HasPrefix(verb, "%s") { + fix = formatNode(pass.Fset, value) + "+" + strconv.Quote(verb[2:]) + } else { + fix = formatNode(pass.Fset, value) + "+" + strconv.Quote(verb[5:]) + } + fname := pass.Fset.File(call.Pos()).Name() + removedFmtUsages[fname]++ + d = &analysis.Diagnostic{ + Pos: call.Pos(), + End: call.End(), + Message: fn + " can be replaced with string concatenation", + SuggestedFixes: []analysis.SuggestedFix{ + { + Message: "Use string concatenation", + TextEdits: []analysis.TextEdit{{ + Pos: call.Pos(), + End: call.End(), + NewText: []byte(fix), + }}, + }, + }, + } } if d != nil { - // Need to run goimports to fix using of fmt, strconv or encoding/hex afterwards. pass.Report(*d) } }) + if len(removedFmtUsages) > 0 && n.fiximports { + for _, pkg := range pass.Pkg.Imports() { + if pkg.Path() == "fmt" { + insp = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + nodeFilter = []ast.Node{ + (*ast.SelectorExpr)(nil), + } + insp.Preorder(nodeFilter, func(node ast.Node) { + selec := node.(*ast.SelectorExpr) + selecok, ok := selec.X.(*ast.Ident) + if ok { + pkgname, ok := pass.TypesInfo.ObjectOf(selecok).(*types.PkgName) + if ok && pkgname.Name() == pkg.Name() { + fname := pass.Fset.File(pkgname.Pos()).Name() + removedFmtUsages[fname]-- + } + } + }) + } else if pkg.Path() == "errors" || pkg.Path() == "strconv" || pkg.Path() == "encoding/hex" { + insp = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + nodeFilter = []ast.Node{ + (*ast.ImportSpec)(nil), + } + insp.Preorder(nodeFilter, func(node ast.Node) { + gd := node.(*ast.ImportSpec) + if gd.Path.Value == strconv.Quote(pkg.Path()) { + fname := pass.Fset.File(gd.Pos()).Name() + _, ok := neededPackages[fname] + if ok { + delete(neededPackages[fname], pkg.Path()) + } + } + }) + } + } + insp = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + nodeFilter = []ast.Node{ + (*ast.ImportSpec)(nil), + } + insp.Preorder(nodeFilter, func(node ast.Node) { + gd := node.(*ast.ImportSpec) + if gd.Path.Value == `"fmt"` { + fix := "" + fname := pass.Fset.File(gd.Pos()).Name() + if removedFmtUsages[fname] < 0 { + fix += `"fmt"` + if len(neededPackages[fname]) == 0 { + return + } + } + keys := make([]string, 0, len(neededPackages[fname])) + for k := range neededPackages[fname] { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + fix = fix + "\n\t\"" + k + `"` + } + pass.Report(analysis.Diagnostic{ + Pos: gd.Pos(), + End: gd.End(), + Message: "Fix imports", + SuggestedFixes: []analysis.SuggestedFix{ + { + Message: "Fix imports", + TextEdits: []analysis.TextEdit{{ + Pos: gd.Pos(), + End: gd.End(), + NewText: []byte(fix), + }}, + }, + }}) + } + }) + } + return nil, nil } diff --git a/tools/vendor/github.com/ccojocar/zxcvbn-go/match/match.go b/tools/vendor/github.com/ccojocar/zxcvbn-go/match/match.go index 998dde111..da3e894ec 100644 --- a/tools/vendor/github.com/ccojocar/zxcvbn-go/match/match.go +++ b/tools/vendor/github.com/ccojocar/zxcvbn-go/match/match.go @@ -16,9 +16,8 @@ func (s Matches) Less(i, j int) bool { return true } else if s[i].I == s[j].I { return s[i].J < s[j].J - } else { - return false } + return false } // Match represents different matches diff --git a/tools/vendor/github.com/ccojocar/zxcvbn-go/renovate.json b/tools/vendor/github.com/ccojocar/zxcvbn-go/renovate.json new file mode 100644 index 000000000..58ee1e0ea --- /dev/null +++ b/tools/vendor/github.com/ccojocar/zxcvbn-go/renovate.json @@ -0,0 +1,25 @@ +{ + "dependencyDashboard": true, + "dependencyDashboardTitle" : "Renovate(bot) : dependency dashboard", + "vulnerabilityAlerts": { + "enabled": true + }, + "extends": [ + ":preserveSemverRanges", + "group:all", + "schedule:weekly" + ], + "lockFileMaintenance": { + "commitMessageAction": "Update", + "enabled": true, + "extends": [ + "group:all", + "schedule:weekly" + ] + }, + "postUpdateOptions": [ + "gomodTidy", + "gomodUpdateImportPaths" + ], + "separateMajorMinor": false +} diff --git a/tools/vendor/github.com/ccojocar/zxcvbn-go/scoring/scoring.go b/tools/vendor/github.com/ccojocar/zxcvbn-go/scoring/scoring.go index dbe331884..f25606a8d 100644 --- a/tools/vendor/github.com/ccojocar/zxcvbn-go/scoring/scoring.go +++ b/tools/vendor/github.com/ccojocar/zxcvbn-go/scoring/scoring.go @@ -161,9 +161,8 @@ func displayTime(seconds float64) string { return fmt.Sprintf(formater, (1 + math.Ceil(seconds/month)), "months") } else if seconds < century { return fmt.Sprintf(formater, (1 + math.Ceil(seconds/century)), "years") - } else { - return "centuries" } + return "centuries" } func crackTimeToScore(seconds float64) int { diff --git a/tools/vendor/github.com/ckaznocha/intrange/.gitignore b/tools/vendor/github.com/ckaznocha/intrange/.gitignore new file mode 100644 index 000000000..cfcb676e1 --- /dev/null +++ b/tools/vendor/github.com/ckaznocha/intrange/.gitignore @@ -0,0 +1,191 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +go.work.sum + +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* diff --git a/tools/vendor/github.com/ckaznocha/intrange/.golangci.yml b/tools/vendor/github.com/ckaznocha/intrange/.golangci.yml new file mode 100644 index 000000000..2ad830d1b --- /dev/null +++ b/tools/vendor/github.com/ckaznocha/intrange/.golangci.yml @@ -0,0 +1,99 @@ +linters-settings: + gci: + local-prefixes: github.com/ckaznocha/intrange + gocritic: + enabled-tags: + - diagnostic + - experimental + - opinionated + - performance + - style + goimports: + local-prefixes: github.com/ckaznocha/intrange + golint: + min-confidence: 0 + govet: + check-shadowing: true + enable: + - asmdecl + - assign + - atomic + - atomicalign + - bools + - buildtag + - cgocall + - composite + - copylock + - deepequalerrors + - errorsas + - fieldalignment + - findcall + - framepointer + - httpresponse + - ifaceassert + - loopclosure + - lostcancel + - nilfunc + - nilness + - printf + - shadow + - shift + - sortslice + - stdmethods + - stringintconv + - structtag + - testinggoroutine + - tests + - unmarshal + - unreachable + - unsafeptr + - unusedresult + misspell: + locale: US +linters: + disable-all: true + enable: + - asciicheck + - dupl + - errcheck + - errorlint + - exportloopref + - gci + - gochecknoinits + - goconst + - gocritic + - godot + - godox + - goerr113 + - gofmt + - gofumpt + - goimports + - gomnd + - goprintffuncname + - gosec + - gosimple + - govet + - ineffassign + - lll + - misspell + - nakedret + - nestif + - nilerr + - nlreturn + - noctx + - nolintlint + - prealloc + - predeclared + - revive + - rowserrcheck + - staticcheck + - stylecheck + - typecheck + - unconvert + - unused + - wastedassign + - whitespace + - wsl +run: + skip-dirs: + - testdata/ diff --git a/tools/vendor/github.com/ckaznocha/intrange/CONTRIBUTING.md b/tools/vendor/github.com/ckaznocha/intrange/CONTRIBUTING.md new file mode 100644 index 000000000..541cf2c54 --- /dev/null +++ b/tools/vendor/github.com/ckaznocha/intrange/CONTRIBUTING.md @@ -0,0 +1,25 @@ +# Contributing +Enhancements or fixes are welcome + +## Issues +Check if a ticket for your issue already exists in GitHub issues. If you don't +find a ticket submit a new one. + +## Pull Requests +1. Fork the repo +1. Make your changes. +1. Commit and push the to your fork. + 1. Extra credit if you squash your commits first. +1. Submit a pull request. + +### Style +- Your code should pass golint. +- Follow the existing conventions. + +### Tests +- If you add any functionality be sure to also add a test for it. +- All regressions need to pass before your pull can be accepted + +## License +By contributing to intrange you agree that your contributions will be +licensed under its MIT license. diff --git a/tools/vendor/github.com/t-yuki/gocover-cobertura/LICENSE b/tools/vendor/github.com/ckaznocha/intrange/LICENSE similarity index 60% rename from tools/vendor/github.com/t-yuki/gocover-cobertura/LICENSE rename to tools/vendor/github.com/ckaznocha/intrange/LICENSE index 7ec1b3d85..b68bde54b 100644 --- a/tools/vendor/github.com/t-yuki/gocover-cobertura/LICENSE +++ b/tools/vendor/github.com/ckaznocha/intrange/LICENSE @@ -1,11 +1,13 @@ -Copyright (c) 2013 Yukinari Toyota +The MIT License (MIT) -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: +Copyright (c) 2024 Clifton Kaznocha + +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. diff --git a/tools/vendor/github.com/ckaznocha/intrange/README.md b/tools/vendor/github.com/ckaznocha/intrange/README.md new file mode 100644 index 000000000..9cac46220 --- /dev/null +++ b/tools/vendor/github.com/ckaznocha/intrange/README.md @@ -0,0 +1,90 @@ +# intrange + +[![Build Status](https://github.com/ckaznocha/intrange/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ckaznocha/intrange/actions/workflows/ci.yml) +[![Release](http://img.shields.io/github/release/ckaznocha/intrange.svg)](https://github.com/ckaznocha/intrange/releases/latest) +[![GoDoc](https://godoc.org/github.com/ckaznocha/intrange?status.svg)](https://godoc.org/github.com/ckaznocha/intrange) + +intrange is a program for checking for loops that could use the [Go 1.22](https://go.dev/ref/spec#Go_1.22) integer +range feature. + +## Installation + +```bash +go install github.com/ckaznocha/intrange/cmd/intrange@latest +``` + +## Usage + +```bash +go vet -vettool=$(which intrange) ./... +``` + +## Examples + +### A loop that uses the value of the loop variable + +```go +package main + +import "fmt" + +func main() { + for i := 0; i < 10; i++ { + fmt.Println(i) + } +} +``` + +Running `intrange` on the above code will produce the following output: + +```bash +main.go:5:2: for loop can be changed to use an integer range (Go 1.22+) +``` + +The loop can be rewritten as: + +```go +package main + +import "fmt" + +func main() { + for i := range 10 { + fmt.Println(i) + } +} +``` + +### A loop that does not use the value of the loop variable + +```go +package main + +import "fmt" + +func main() { + for i := 0; i < 10; i++ { + fmt.Println("Hello again!") + } +} +``` + +Running `intrange` on the above code will produce the following output: + +```bash +main.go:5:2: for loop can be changed to use an integer range (Go 1.22+) +``` + +The loop can be rewritten as: + +```go +package main + +import "fmt" + +func main() { + for range 10 { + fmt.Println("Hello again!") + } +} +``` diff --git a/tools/vendor/github.com/ckaznocha/intrange/SECURITY.md b/tools/vendor/github.com/ckaznocha/intrange/SECURITY.md new file mode 100644 index 000000000..e2c44c4e2 --- /dev/null +++ b/tools/vendor/github.com/ckaznocha/intrange/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +Please open a [github issue](https://github.com/ckaznocha/intrange/issues) diff --git a/tools/vendor/github.com/ckaznocha/intrange/go.work b/tools/vendor/github.com/ckaznocha/intrange/go.work new file mode 100644 index 000000000..f41a04a2f --- /dev/null +++ b/tools/vendor/github.com/ckaznocha/intrange/go.work @@ -0,0 +1,6 @@ +go 1.22.0 + +use ( + . + ./testdata +) diff --git a/tools/vendor/github.com/ckaznocha/intrange/intrange.go b/tools/vendor/github.com/ckaznocha/intrange/intrange.go new file mode 100644 index 000000000..fac4e3dea --- /dev/null +++ b/tools/vendor/github.com/ckaznocha/intrange/intrange.go @@ -0,0 +1,388 @@ +package intrange + +import ( + "errors" + "fmt" + "go/ast" + "go/token" + "strconv" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var ( + Analyzer = &analysis.Analyzer{ + Name: "intrange", + Doc: "intrange is a linter to find places where for loops could make use of an integer range.", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + } + + errFailedAnalysis = errors.New("failed analysis") +) + +const msg = "for loop can be changed to use an integer range (Go 1.22+)" + +func run(pass *analysis.Pass) (any, error) { + result, ok := pass.ResultOf[inspect.Analyzer] + if !ok { + return nil, fmt.Errorf( + "%w: %s", + errFailedAnalysis, + inspect.Analyzer.Name, + ) + } + + resultInspector, ok := result.(*inspector.Inspector) + if !ok { + return nil, fmt.Errorf( + "%w: %s", + errFailedAnalysis, + inspect.Analyzer.Name, + ) + } + + resultInspector.Preorder([]ast.Node{(*ast.ForStmt)(nil)}, check(pass)) + + return nil, nil +} + +func check(pass *analysis.Pass) func(node ast.Node) { + return func(node ast.Node) { + forStmt, ok := node.(*ast.ForStmt) + if !ok { + return + } + + if forStmt.Init == nil || forStmt.Cond == nil || forStmt.Post == nil { + return + } + + // i := 0;; + init, ok := forStmt.Init.(*ast.AssignStmt) + if !ok { + return + } + + if len(init.Lhs) != 1 || len(init.Rhs) != 1 { + return + } + + initIdent, ok := init.Lhs[0].(*ast.Ident) + if !ok { + return + } + + if !compareNumberLit(init.Rhs[0], 0) { + return + } + + cond, ok := forStmt.Cond.(*ast.BinaryExpr) + if !ok { + return + } + + var nExpr ast.Expr + + switch cond.Op { + case token.LSS: // ;i < n; + if isBenchmark(cond.Y) { + return + } + + nExpr = findNExpr(cond.Y) + + x, ok := cond.X.(*ast.Ident) + if !ok { + return + } + + if x.Name != initIdent.Name { + return + } + case token.GTR: // ;n > i; + if isBenchmark(cond.X) { + return + } + + nExpr = findNExpr(cond.X) + + y, ok := cond.Y.(*ast.Ident) + if !ok { + return + } + + if y.Name != initIdent.Name { + return + } + default: + return + } + + switch post := forStmt.Post.(type) { + case *ast.IncDecStmt: // ;;i++ + if post.Tok != token.INC { + return + } + + ident, ok := post.X.(*ast.Ident) + if !ok { + return + } + + if ident.Name != initIdent.Name { + return + } + case *ast.AssignStmt: + switch post.Tok { + case token.ADD_ASSIGN: // ;;i += 1 + if len(post.Lhs) != 1 { + return + } + + ident, ok := post.Lhs[0].(*ast.Ident) + if !ok { + return + } + + if ident.Name != initIdent.Name { + return + } + + if len(post.Rhs) != 1 { + return + } + + if !compareNumberLit(post.Rhs[0], 1) { + return + } + case token.ASSIGN: // ;;i = i + 1 && ;;i = 1 + i + if len(post.Lhs) != 1 || len(post.Rhs) != 1 { + return + } + + ident, ok := post.Lhs[0].(*ast.Ident) + if !ok { + return + } + + if ident.Name != initIdent.Name { + return + } + + bin, ok := post.Rhs[0].(*ast.BinaryExpr) + if !ok { + return + } + + if bin.Op != token.ADD { + return + } + + switch x := bin.X.(type) { + case *ast.Ident: // ;;i = i + 1 + if x.Name != initIdent.Name { + return + } + + if !compareNumberLit(bin.Y, 1) { + return + } + case *ast.BasicLit: // ;;i = 1 + i + if !compareNumberLit(x, 1) { + return + } + + ident, ok := bin.Y.(*ast.Ident) + if !ok { + return + } + + if ident.Name != initIdent.Name { + return + } + default: + return + } + default: + return + } + default: + return + } + + bc := &bodyChecker{ + initIdent: initIdent, + nExpr: nExpr, + } + + ast.Inspect(forStmt.Body, bc.check) + + if bc.modified { + return + } + + pass.Report(analysis.Diagnostic{ + Pos: forStmt.Pos(), + Message: msg, + }) + } +} + +func findNExpr(expr ast.Expr) ast.Expr { + switch e := expr.(type) { + case *ast.CallExpr: + if fun, ok := e.Fun.(*ast.Ident); ok && fun.Name == "len" && len(e.Args) == 1 { + return findNExpr(e.Args[0]) + } + + return nil + case *ast.BasicLit: + return nil + case *ast.Ident: + return e + case *ast.SelectorExpr: + return e + case *ast.IndexExpr: + return e + default: + return nil + } +} + +func isBenchmark(expr ast.Expr) bool { + selectorExpr, ok := expr.(*ast.SelectorExpr) + if !ok { + return false + } + + if selectorExpr.Sel.Name != "N" { + return false + } + + ident, ok := selectorExpr.X.(*ast.Ident) + if !ok { + return false + } + + if ident.Name == "b" { + return true + } + + return false +} + +func identEqual(a, b ast.Expr) bool { + if a == nil || b == nil { + return false + } + + switch aT := a.(type) { + case *ast.Ident: + identB, ok := b.(*ast.Ident) + if !ok { + return false + } + + return aT.Name == identB.Name + case *ast.SelectorExpr: + selectorB, ok := b.(*ast.SelectorExpr) + if !ok { + return false + } + + return identEqual(aT.Sel, selectorB.Sel) && identEqual(aT.X, selectorB.X) + case *ast.IndexExpr: + indexB, ok := b.(*ast.IndexExpr) + if ok { + return identEqual(aT.X, indexB.X) && identEqual(aT.Index, indexB.Index) + } + + return identEqual(aT.X, b) + case *ast.BasicLit: + litB, ok := b.(*ast.BasicLit) + if !ok { + return false + } + + return aT.Value == litB.Value + default: + return false + } +} + +type bodyChecker struct { + initIdent *ast.Ident + nExpr ast.Expr + modified bool +} + +func (b *bodyChecker) check(n ast.Node) bool { + switch stmt := n.(type) { + case *ast.AssignStmt: + for _, lhs := range stmt.Lhs { + if identEqual(lhs, b.initIdent) || identEqual(lhs, b.nExpr) { + b.modified = true + + return false + } + } + case *ast.IncDecStmt: + if identEqual(stmt.X, b.initIdent) || identEqual(stmt.X, b.nExpr) { + b.modified = true + + return false + } + } + + return true +} + +func compareNumberLit(exp ast.Expr, val int) bool { + switch lit := exp.(type) { + case *ast.BasicLit: + if lit.Kind != token.INT { + return false + } + + n := strconv.Itoa(val) + + switch lit.Value { + case n, "0x" + n, "0X" + n: + return true + default: + return false + } + case *ast.CallExpr: + switch fun := lit.Fun.(type) { + case *ast.Ident: + switch fun.Name { + case + "int", + "int8", + "int16", + "int32", + "int64", + "uint", + "uint8", + "uint16", + "uint32", + "uint64": + default: + return false + } + default: + return false + } + + if len(lit.Args) != 1 { + return false + } + + return compareNumberLit(lit.Args[0], val) + default: + return false + } +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/config/config.go b/tools/vendor/github.com/daixiang0/gci/pkg/config/config.go index 98513c056..cc43f2fa0 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/config/config.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/config/config.go @@ -10,11 +10,13 @@ import ( ) var defaultOrder = map[string]int{ - section.StandardType: 0, - section.DefaultType: 1, - section.CustomType: 2, - section.BlankType: 3, - section.DotType: 4, + section.StandardType: 0, + section.DefaultType: 1, + section.CustomType: 2, + section.BlankType: 3, + section.DotType: 4, + section.AliasType: 5, + section.LocalModuleType: 6, } type BoolConfig struct { @@ -36,6 +38,10 @@ type YamlConfig struct { Cfg BoolConfig `yaml:",inline"` SectionStrings []string `yaml:"sections"` SectionSeparatorStrings []string `yaml:"sectionseparators"` + + // Since history issue, Golangci-lint needs Analyzer to run and GCI add an Analyzer layer to integrate. + // The ModPath param is only from analyzer.go, no need to set it in all other places. + ModPath string `yaml:"-"` } func (g YamlConfig) Parse() (*Config, error) { @@ -48,6 +54,9 @@ func (g YamlConfig) Parse() (*Config, error) { if sections == nil { sections = section.DefaultSections() } + if err := configureSections(sections, g.ModPath); err != nil { + return nil, err + } // if default order sorted sections if !g.Cfg.CustomOrder { @@ -87,3 +96,18 @@ func ParseConfig(in string) (*Config, error) { return gciCfg, nil } + +// configureSections now only do golang module path finding. +// Since history issue, Golangci-lint needs Analyzer to run and GCI add an Analyzer layer to integrate. +// The path param is from analyzer.go, in all other places should pass empty string. +func configureSections(sections section.SectionList, path string) error { + for _, sec := range sections { + switch s := sec.(type) { + case *section.LocalModule: + if err := s.Configure(path); err != nil { + return err + } + } + } + return nil +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/testdata.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/testdata.go index a48ce356c..866ae84c4 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/testdata.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/gci/testdata.go @@ -421,7 +421,7 @@ import ( `, }, { - "comment-whithout-whitespace", + "comment-without-whitespace", commonConfig, @@ -1240,6 +1240,59 @@ import ( "github.com/daixiang0/gci" "github.com/daixiang0/gci/subtest" ) +`, + }, + { + "alias", + + `sections: + - Standard + - Default + - Alias +`, + `package main + +import ( + testing "github.com/daixiang0/test" + "fmt" + + g "github.com/golang" + + "github.com/daixiang0/gci" + "github.com/daixiang0/gci/subtest" +) +`, + `package main + +import ( + "fmt" + + "github.com/daixiang0/gci" + "github.com/daixiang0/gci/subtest" + + testing "github.com/daixiang0/test" + g "github.com/golang" +) +`, + }, + { + "no-trailing-newline", + + `sections: + - Standard +`, + `package main + +import ( + "net" + "fmt" +)`, + `package main + +import ( + "fmt" + "net" +) `, }, } diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/parse/parse.go b/tools/vendor/github.com/daixiang0/gci/pkg/parse/parse.go index 33d6e1705..e8532f850 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/parse/parse.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/parse/parse.go @@ -111,6 +111,9 @@ func ParseFile(src []byte, filename string) (ImportList, int, int, int, int, err headEnd = int(decl.Pos()) - 1 } tailStart = int(decl.End()) + if tailStart > len(src) { + tailStart = len(src) + } for _, spec := range genDecl.Specs { imp := spec.(*ast.ImportSpec) diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/alias.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/alias.go new file mode 100644 index 000000000..423e96acf --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/alias.go @@ -0,0 +1,25 @@ +package section + +import ( + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +type Alias struct{} + +const AliasType = "alias" + +func (b Alias) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + if spec.Name != "." && spec.Name != "_" && spec.Name != "" { + return specificity.NameMatch{} + } + return specificity.MisMatch{} +} + +func (b Alias) String() string { + return AliasType +} + +func (b Alias) Type() string { + return AliasType +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/local_module.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/local_module.go new file mode 100644 index 000000000..50f41e501 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/local_module.go @@ -0,0 +1,59 @@ +package section + +import ( + "fmt" + "os" + "strings" + + "golang.org/x/mod/modfile" + + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +const LocalModuleType = "localmodule" + +type LocalModule struct { + Path string +} + +func (m *LocalModule) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + if spec.Path == m.Path || strings.HasPrefix(spec.Path, m.Path+"/") { + return specificity.LocalModule{} + } + + return specificity.MisMatch{} +} + +func (m *LocalModule) String() string { + return LocalModuleType +} + +func (m *LocalModule) Type() string { + return LocalModuleType +} + +// Configure configures the module section by finding the module +// for the current path +func (m *LocalModule) Configure(path string) error { + if path != "" { + m.Path = path + } else { + path, err := findLocalModule() + if err != nil { + return fmt.Errorf("finding local modules for `localModule` configuration: %w", err) + } + m.Path = path + } + + return nil +} + +func findLocalModule() (string, error) { + b, err := os.ReadFile("go.mod") + if err != nil { + return "", fmt.Errorf("reading go.mod: %w", err) + } + + return modfile.ModulePath(b), nil +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/parser.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/parser.go index 9834dcd13..62ed1582a 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/section/parser.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/parser.go @@ -33,6 +33,11 @@ func Parse(data []string) (SectionList, error) { list = append(list, Dot{}) } else if s == "blank" { list = append(list, Blank{}) + } else if s == "alias" { + list = append(list, Alias{}) + } else if s == "localmodule" { + // pointer because we need to mutate the section at configuration time + list = append(list, &LocalModule{}) } else { errString += fmt.Sprintf(" %s", s) } diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/standard_list.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/standard_list.go index 05e799939..a2cd0a6dd 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/section/standard_list.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/standard_list.go @@ -1,6 +1,6 @@ package section -// Code generated based on go1.21.0 X:arenas. DO NOT EDIT. +// Code generated based on go1.22.0 X:boringcrypto,arenas. DO NOT EDIT. var standardPackages = map[string]struct{}{ "archive/tar": {}, @@ -20,6 +20,7 @@ var standardPackages = map[string]struct{}{ "context": {}, "crypto": {}, "crypto/aes": {}, + "crypto/boring": {}, "crypto/cipher": {}, "crypto/des": {}, "crypto/dsa": {}, @@ -37,6 +38,7 @@ var standardPackages = map[string]struct{}{ "crypto/sha512": {}, "crypto/subtle": {}, "crypto/tls": {}, + "crypto/tls/fipsonly": {}, "crypto/x509": {}, "crypto/x509/pkix": {}, "database/sql": {}, @@ -78,6 +80,7 @@ var standardPackages = map[string]struct{}{ "go/scanner": {}, "go/token": {}, "go/types": {}, + "go/version": {}, "hash": {}, "hash/adler32": {}, "hash/crc32": {}, @@ -106,6 +109,7 @@ var standardPackages = map[string]struct{}{ "math/bits": {}, "math/cmplx": {}, "math/rand": {}, + "math/rand/v2": {}, "mime": {}, "mime/multipart": {}, "mime/quotedprintable": {}, diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/specificity/local_module.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/local_module.go new file mode 100644 index 000000000..ae482fec4 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/local_module.go @@ -0,0 +1,15 @@ +package specificity + +type LocalModule struct{} + +func (m LocalModule) IsMoreSpecific(than MatchSpecificity) bool { + return isMoreSpecific(m, than) +} + +func (m LocalModule) Equal(to MatchSpecificity) bool { + return equalSpecificity(m, to) +} + +func (LocalModule) class() specificityClass { + return LocalModuleClass +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/specificity/specificity.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/specificity.go index 842da1857..4a188b3bb 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/specificity/specificity.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/specificity.go @@ -3,11 +3,12 @@ package specificity type specificityClass int const ( - MisMatchClass = 0 - DefaultClass = 10 - StandardClass = 20 - MatchClass = 30 - NameClass = 40 + MisMatchClass = 0 + DefaultClass = 10 + StandardClass = 20 + MatchClass = 30 + NameClass = 40 + LocalModuleClass = 50 ) // MatchSpecificity is used to determine which section matches an import best diff --git a/tools/vendor/github.com/denis-tingaikin/go-header/.go-header.yml b/tools/vendor/github.com/denis-tingaikin/go-header/.go-header.yml index 3f87c8798..3aa6d060d 100644 --- a/tools/vendor/github.com/denis-tingaikin/go-header/.go-header.yml +++ b/tools/vendor/github.com/denis-tingaikin/go-header/.go-header.yml @@ -1,6 +1,6 @@ values: regexp: - copyright-holder: Copyright \(c\) {{year-range}} Denis Tingaikin + copyright-holder: Copyright \(c\) {{mod-year-range}} Denis Tingaikin template: | {{copyright-holder}} diff --git a/tools/vendor/github.com/denis-tingaikin/go-header/README.md b/tools/vendor/github.com/denis-tingaikin/go-header/README.md index c2044ec96..fcddad1fa 100644 --- a/tools/vendor/github.com/denis-tingaikin/go-header/README.md +++ b/tools/vendor/github.com/denis-tingaikin/go-header/README.md @@ -8,7 +8,7 @@ Go source code linter providing checks for license headers. For installation you can simply use `go get`. ```bash -go get github.com/denis-tingaikin/go-header/cmd/go-header +go install github.com/denis-tingaikin/go-header/cmd/go-header ``` ## Configuration @@ -38,6 +38,8 @@ values: ## Bult-in values +- **MOD-YEAR** - Returns the year when the file was modified. +- **MOD-YEAR-RANGE** - Returns a year-range where the range starts from the year when the file was modified. - **YEAR** - Expects current year. Example header value: `2020`. Example of template using: `{{YEAR}}` or `{{year}}`. - **YEAR-RANGE** - Expects any valid year interval or current year. Example header value: `2020` or `2000-2020`. Example of template using: `{{year-range}}` or `{{YEAR-RANGE}}`. diff --git a/tools/vendor/github.com/denis-tingaikin/go-header/analyzer.go b/tools/vendor/github.com/denis-tingaikin/go-header/analyzer.go index 785a02e79..c6b361f01 100644 --- a/tools/vendor/github.com/denis-tingaikin/go-header/analyzer.go +++ b/tools/vendor/github.com/denis-tingaikin/go-header/analyzer.go @@ -1,4 +1,4 @@ -// Copyright (c) 2020-2022 Denis Tingaikin +// Copyright (c) 2020-2024 Denis Tingaikin // // SPDX-License-Identifier: Apache-2.0 // @@ -52,15 +52,31 @@ type Analyzer struct { template string } -func (a *Analyzer) Analyze(target *Target) Issue { +func (a *Analyzer) processPerTargetValues(target *Target) error { + a.values["mod-year"] = a.values["year"] + a.values["mod-year-range"] = a.values["year-range"] + if t, err := target.ModTime(); err == nil { + a.values["mod-year"] = &ConstValue{RawValue: fmt.Sprint(t.Year())} + a.values["mod-year-range"] = &RegexpValue{RawValue: `((20\d\d\-{{mod-year}})|({{mod-year}}))`} + } + + for _, v := range a.values { + if err := v.Calculate(a.values); err != nil { + return err + } + } + return nil +} + +func (a *Analyzer) Analyze(target *Target) (i Issue) { if a.template == "" { return NewIssue("Missed template for check") } - if t, err := target.ModTime(); err == nil { - if t.Year() != time.Now().Year() { - return nil - } + + if err := a.processPerTargetValues(target); err != nil { + return &issue{msg: err.Error()} } + file := target.File var header string var offset = Location{ @@ -74,6 +90,16 @@ func (a *Analyzer) Analyze(target *Target) Issue { offset.Position += 3 } } + defer func() { + if i == nil { + return + } + fix, ok := a.generateFix(i, file, header) + if !ok { + return + } + i = NewIssueWithFix(i.Message(), i.Location(), fix) + }() header = strings.TrimSpace(header) if header == "" { return NewIssue("Missed header for check") @@ -132,15 +158,99 @@ func (a *Analyzer) readField(reader *Reader) string { } func New(options ...Option) *Analyzer { - a := &Analyzer{} + a := &Analyzer{values: make(map[string]Value)} for _, o := range options { o.apply(a) } - for _, v := range a.values { - err := v.Calculate(a.values) - if err != nil { - panic(err.Error()) + return a +} + +func (a *Analyzer) generateFix(i Issue, file *ast.File, header string) (Fix, bool) { + var expect string + t := NewReader(a.template) + for !t.Done() { + ch := t.Peek() + if ch == '{' { + f := a.values[a.readField(t)] + if f == nil { + return Fix{}, false + } + if f.Calculate(a.values) != nil { + return Fix{}, false + } + expect += f.Get() + continue } + + expect += string(ch) + t.Next() } - return a + + fix := Fix{Expected: strings.Split(expect, "\n")} + if !(len(file.Comments) > 0 && file.Comments[0].Pos() < file.Package) { + for i := range fix.Expected { + fix.Expected[i] = "// " + fix.Expected[i] + } + return fix, true + } + + actual := file.Comments[0].List[0].Text + if !strings.HasPrefix(actual, "/*") { + for i := range fix.Expected { + fix.Expected[i] = "// " + fix.Expected[i] + } + for _, c := range file.Comments[0].List { + fix.Actual = append(fix.Actual, c.Text) + } + i = NewIssueWithFix(i.Message(), i.Location(), fix) + return fix, true + } + + gets := func(i int, end bool) string { + if i < 0 { + return header + } + if end { + return header[i+1:] + } + return header[:i] + } + start := strings.Index(actual, gets(strings.IndexByte(header, '\n'), false)) + if start < 0 { + return Fix{}, false // Should be impossible + } + nl := strings.LastIndexByte(actual[:start], '\n') + if nl >= 0 { + fix.Actual = strings.Split(actual[:nl], "\n") + fix.Expected = append(fix.Actual, fix.Expected...) + actual = actual[nl+1:] + start -= nl + 1 + } + + prefix := actual[:start] + if nl < 0 { + fix.Expected[0] = prefix + fix.Expected[0] + } else { + n := len(fix.Actual) + for i := range fix.Expected[n:] { + fix.Expected[n+i] = prefix + fix.Expected[n+i] + } + } + + last := gets(strings.LastIndexByte(header, '\n'), true) + end := strings.Index(actual, last) + if end < 0 { + return Fix{}, false // Should be impossible + } + + trailing := actual[end+len(last):] + if i := strings.IndexRune(trailing, '\n'); i < 0 { + fix.Expected[len(fix.Expected)-1] += trailing + } else { + fix.Expected[len(fix.Expected)-1] += trailing[:i] + fix.Expected = append(fix.Expected, strings.Split(trailing[i+1:], "\n")...) + } + + fix.Actual = append(fix.Actual, strings.Split(actual, "\n")...) + return fix, true } diff --git a/tools/vendor/github.com/denis-tingaikin/go-header/config.go b/tools/vendor/github.com/denis-tingaikin/go-header/config.go index 9576b949f..c881b63ac 100644 --- a/tools/vendor/github.com/denis-tingaikin/go-header/config.go +++ b/tools/vendor/github.com/denis-tingaikin/go-header/config.go @@ -1,4 +1,4 @@ -// Copyright (c) 2020-2022 Denis Tingaikin +// Copyright (c) 2020-2024 Denis Tingaikin // // SPDX-License-Identifier: Apache-2.0 // @@ -19,7 +19,7 @@ package goheader import ( "errors" "fmt" - "io/ioutil" + "os" "strings" "time" @@ -40,7 +40,7 @@ func (c *Configuration) builtInValues() map[string]Value { var result = make(map[string]Value) year := fmt.Sprint(time.Now().Year()) result["year-range"] = &RegexpValue{ - RawValue: strings.ReplaceAll(`((20\d\d\-YEAR)|(YEAR))`, "YEAR", year), + RawValue: `((20\d\d\-{{YEAR}})|({{YEAR}}))`, } result["year"] = &ConstValue{ RawValue: year, @@ -82,7 +82,7 @@ func (c *Configuration) GetTemplate() (string, error) { if c.TemplatePath == "" { return "", errors.New("template has not passed") } - if b, err := ioutil.ReadFile(c.TemplatePath); err != nil { + if b, err := os.ReadFile(c.TemplatePath); err != nil { return "", err } else { c.Template = strings.TrimSpace(string(b)) @@ -91,7 +91,7 @@ func (c *Configuration) GetTemplate() (string, error) { } func (c *Configuration) Parse(p string) error { - b, err := ioutil.ReadFile(p) + b, err := os.ReadFile(p) if err != nil { return err } diff --git a/tools/vendor/github.com/denis-tingaikin/go-header/issue.go b/tools/vendor/github.com/denis-tingaikin/go-header/issue.go index 0ada0d62c..e92279793 100644 --- a/tools/vendor/github.com/denis-tingaikin/go-header/issue.go +++ b/tools/vendor/github.com/denis-tingaikin/go-header/issue.go @@ -1,4 +1,4 @@ -// Copyright (c) 2020-2022 Denis Tingaikin +// Copyright (c) 2020-2024 Denis Tingaikin // // SPDX-License-Identifier: Apache-2.0 // @@ -19,11 +19,18 @@ package goheader type Issue interface { Location() Location Message() string + Fix() *Fix } type issue struct { msg string location Location + fix *Fix +} + +type Fix struct { + Actual []string + Expected []string } func (i *issue) Location() Location { @@ -34,6 +41,10 @@ func (i *issue) Message() string { return i.msg } +func (i *issue) Fix() *Fix { + return i.fix +} + func NewIssueWithLocation(msg string, location Location) Issue { return &issue{ msg: msg, @@ -41,6 +52,14 @@ func NewIssueWithLocation(msg string, location Location) Issue { } } +func NewIssueWithFix(msg string, location Location, fix Fix) Issue { + return &issue{ + msg: msg, + location: location, + fix: &fix, + } +} + func NewIssue(msg string) Issue { return &issue{ msg: msg, diff --git a/tools/vendor/github.com/denis-tingaikin/go-header/value.go b/tools/vendor/github.com/denis-tingaikin/go-header/value.go index dcb206d35..706a84f18 100644 --- a/tools/vendor/github.com/denis-tingaikin/go-header/value.go +++ b/tools/vendor/github.com/denis-tingaikin/go-header/value.go @@ -1,4 +1,4 @@ -// Copyright (c) 2020-2022 Denis Tingaikin +// Copyright (c) 2020-2024 Denis Tingaikin // // SPDX-License-Identifier: Apache-2.0 // @@ -26,6 +26,7 @@ import ( type Calculable interface { Calculate(map[string]Value) error Get() string + Raw() string } type Value interface { @@ -35,7 +36,7 @@ type Value interface { func calculateValue(calculable Calculable, values map[string]Value) (string, error) { sb := strings.Builder{} - r := calculable.Get() + r := calculable.Raw() var endIndex int var startIndex int for startIndex = strings.Index(r, "{{"); startIndex >= 0; startIndex = strings.Index(r, "{{") { @@ -61,7 +62,7 @@ func calculateValue(calculable Calculable, values map[string]Value) (string, err } type ConstValue struct { - RawValue string + RawValue, Value string } func (c *ConstValue) Calculate(values map[string]Value) error { @@ -69,14 +70,25 @@ func (c *ConstValue) Calculate(values map[string]Value) error { if err != nil { return err } - c.RawValue = v + c.Value = v return nil } +func (c *ConstValue) Raw() string { + return c.RawValue +} + func (c *ConstValue) Get() string { + if c.Value != "" { + return c.Value + } return c.RawValue } +func (c *ConstValue) String() string { + return c.Get() +} + func (c *ConstValue) Read(s *Reader) Issue { l := s.Location() p := s.Position() @@ -94,7 +106,7 @@ func (c *ConstValue) Read(s *Reader) Issue { } type RegexpValue struct { - RawValue string + RawValue, Value string } func (r *RegexpValue) Calculate(values map[string]Value) error { @@ -102,14 +114,24 @@ func (r *RegexpValue) Calculate(values map[string]Value) error { if err != nil { return err } - r.RawValue = v + r.Value = v return nil } +func (r *RegexpValue) Raw() string { + return r.RawValue +} func (r *RegexpValue) Get() string { + if r.Value != "" { + return r.Value + } return r.RawValue } +func (r *RegexpValue) String() string { + return r.Get() +} + func (r *RegexpValue) Read(s *Reader) Issue { l := s.Location() p := regexp.MustCompile(r.Get()) diff --git a/tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/analyzer.go b/tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/analyzer.go deleted file mode 100644 index b2d06881d..000000000 --- a/tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/analyzer.go +++ /dev/null @@ -1,280 +0,0 @@ -package analyzer - -import ( - "go/ast" - "go/token" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" - "golang.org/x/tools/go/ast/inspector" -) - -var maxDeclChars, maxDeclLines int - -const ( - maxDeclLinesUsage = `maximum length of variable declaration measured in number of lines, after which the linter won't suggest using short syntax. -Has precedence over max-decl-chars.` - maxDeclCharsUsage = `maximum length of variable declaration measured in number of characters, after which the linter won't suggest using short syntax.` -) - -func init() { - Analyzer.Flags.IntVar(&maxDeclLines, "max-decl-lines", 1, maxDeclLinesUsage) - Analyzer.Flags.IntVar(&maxDeclChars, "max-decl-chars", 30, maxDeclCharsUsage) -} - -// Analyzer is an analysis.Analyzer instance for ifshort linter. -var Analyzer = &analysis.Analyzer{ - Name: "ifshort", - Doc: "Checks that your code uses short syntax for if-statements whenever possible.", - Run: run, - Requires: []*analysis.Analyzer{inspect.Analyzer}, -} - -func run(pass *analysis.Pass) (interface{}, error) { - inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) - nodeFilter := []ast.Node{ - (*ast.FuncDecl)(nil), - } - - inspector.Preorder(nodeFilter, func(node ast.Node) { - fdecl := node.(*ast.FuncDecl) - - /*if fdecl.Name.Name != "notUsed_BinaryExpressionInIndex_OK" { - return - }*/ - - if fdecl == nil || fdecl.Body == nil { - return - } - - candidates := getNamedOccurrenceMap(fdecl, pass) - - for _, stmt := range fdecl.Body.List { - candidates.checkStatement(stmt, token.NoPos) - } - - for varName := range candidates { - for marker, occ := range candidates[varName] { - // If two or more vars with the same scope marker - skip them. - if candidates.isFoundByScopeMarker(marker) { - continue - } - - pass.Reportf(occ.declarationPos, - "variable '%s' is only used in the if-statement (%s); consider using short syntax", - varName, pass.Fset.Position(occ.ifStmtPos)) - } - } - }) - return nil, nil -} - -func (nom namedOccurrenceMap) checkStatement(stmt ast.Stmt, ifPos token.Pos) { - switch v := stmt.(type) { - case *ast.AssignStmt: - for _, el := range v.Rhs { - nom.checkExpression(el, ifPos) - } - if isAssign(v.Tok) { - for _, el := range v.Lhs { - nom.checkExpression(el, ifPos) - } - } - case *ast.DeferStmt: - for _, a := range v.Call.Args { - nom.checkExpression(a, ifPos) - } - case *ast.ExprStmt: - switch v.X.(type) { - case *ast.CallExpr, *ast.UnaryExpr: - nom.checkExpression(v.X, ifPos) - } - case *ast.ForStmt: - for _, el := range v.Body.List { - nom.checkStatement(el, ifPos) - } - - if bexpr, ok := v.Cond.(*ast.BinaryExpr); ok { - nom.checkExpression(bexpr.X, ifPos) - nom.checkExpression(bexpr.Y, ifPos) - } - - nom.checkStatement(v.Post, ifPos) - case *ast.GoStmt: - for _, a := range v.Call.Args { - nom.checkExpression(a, ifPos) - } - case *ast.IfStmt: - for _, el := range v.Body.List { - nom.checkStatement(el, v.If) - } - if elseBlock, ok := v.Else.(*ast.BlockStmt); ok { - for _, el := range elseBlock.List { - nom.checkStatement(el, v.If) - } - } - - switch cond := v.Cond.(type) { - case *ast.UnaryExpr: - nom.checkExpression(cond.X, v.If) - case *ast.BinaryExpr: - nom.checkExpression(cond.X, v.If) - nom.checkExpression(cond.Y, v.If) - case *ast.CallExpr: - nom.checkExpression(cond, v.If) - } - - if init, ok := v.Init.(*ast.AssignStmt); ok { - for _, e := range init.Rhs { - nom.checkExpression(e, v.If) - } - } - case *ast.IncDecStmt: - nom.checkExpression(v.X, ifPos) - case *ast.RangeStmt: - nom.checkExpression(v.X, ifPos) - if v.Body != nil { - for _, e := range v.Body.List { - nom.checkStatement(e, ifPos) - } - } - case *ast.ReturnStmt: - for _, r := range v.Results { - nom.checkExpression(r, ifPos) - } - case *ast.SendStmt: - nom.checkExpression(v.Chan, ifPos) - nom.checkExpression(v.Value, ifPos) - case *ast.SwitchStmt: - nom.checkExpression(v.Tag, ifPos) - - for _, el := range v.Body.List { - clauses, ok := el.(*ast.CaseClause) - if !ok { - continue - } - - for _, c := range clauses.List { - switch v := c.(type) { - case *ast.BinaryExpr: - nom.checkExpression(v.X, ifPos) - nom.checkExpression(v.Y, ifPos) - case *ast.Ident: - nom.checkExpression(v, ifPos) - } - } - - for _, c := range clauses.Body { - switch v := c.(type) { - case *ast.AssignStmt: - for _, el := range v.Lhs { - nom.checkExpression(el, ifPos) - } - for _, el := range v.Rhs { - nom.checkExpression(el, ifPos) - } - case *ast.ExprStmt: - nom.checkExpression(v.X, ifPos) - } - } - } - case *ast.SelectStmt: - for _, el := range v.Body.List { - clause := el.(*ast.CommClause) - - nom.checkStatement(clause.Comm, ifPos) - - for _, c := range clause.Body { - switch v := c.(type) { - case *ast.AssignStmt: - for _, el := range v.Lhs { - nom.checkExpression(el, ifPos) - } - for _, el := range v.Rhs { - nom.checkExpression(el, ifPos) - } - case *ast.ExprStmt: - nom.checkExpression(v.X, ifPos) - } - } - } - case *ast.LabeledStmt: - nom.checkStatement(v.Stmt, ifPos) - } -} - -func (nom namedOccurrenceMap) checkExpression(candidate ast.Expr, ifPos token.Pos) { - switch v := candidate.(type) { - case *ast.BinaryExpr: - nom.checkExpression(v.X, ifPos) - nom.checkExpression(v.Y, ifPos) - case *ast.CallExpr: - for _, arg := range v.Args { - nom.checkExpression(arg, ifPos) - } - nom.checkExpression(v.Fun, ifPos) - if fun, ok := v.Fun.(*ast.SelectorExpr); ok { - nom.checkExpression(fun.X, ifPos) - } - case *ast.CompositeLit: - for _, el := range v.Elts { - switch v := el.(type) { - case *ast.Ident, *ast.CompositeLit: - nom.checkExpression(v, ifPos) - case *ast.KeyValueExpr: - nom.checkExpression(v.Key, ifPos) - nom.checkExpression(v.Value, ifPos) - case *ast.SelectorExpr: - nom.checkExpression(v.X, ifPos) - } - } - case *ast.FuncLit: - for _, el := range v.Body.List { - nom.checkStatement(el, ifPos) - } - case *ast.Ident: - if _, ok := nom[v.Name]; !ok || nom[v.Name].isEmponymousKey(ifPos) { - return - } - - scopeMarker1 := nom[v.Name].getScopeMarkerForPosition(v.Pos()) - - delete(nom[v.Name], scopeMarker1) - - for k := range nom { - for scopeMarker2 := range nom[k] { - if scopeMarker1 == scopeMarker2 { - delete(nom[k], scopeMarker2) - } - } - } - case *ast.StarExpr: - nom.checkExpression(v.X, ifPos) - case *ast.IndexExpr: - nom.checkExpression(v.X, ifPos) - switch index := v.Index.(type) { - case *ast.BinaryExpr: - nom.checkExpression(index.X, ifPos) - case *ast.Ident: - nom.checkExpression(index, ifPos) - } - case *ast.SelectorExpr: - nom.checkExpression(v.X, ifPos) - case *ast.SliceExpr: - nom.checkExpression(v.High, ifPos) - nom.checkExpression(v.Low, ifPos) - nom.checkExpression(v.X, ifPos) - case *ast.TypeAssertExpr: - nom.checkExpression(v.X, ifPos) - case *ast.UnaryExpr: - nom.checkExpression(v.X, ifPos) - } -} - -func isAssign(tok token.Token) bool { - return (tok == token.ASSIGN || - tok == token.ADD_ASSIGN || tok == token.SUB_ASSIGN || - tok == token.MUL_ASSIGN || tok == token.QUO_ASSIGN || tok == token.REM_ASSIGN || - tok == token.AND_ASSIGN || tok == token.OR_ASSIGN || tok == token.XOR_ASSIGN || tok == token.AND_NOT_ASSIGN || - tok == token.SHL_ASSIGN || tok == token.SHR_ASSIGN) -} diff --git a/tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/occurrences.go b/tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/occurrences.go deleted file mode 100644 index 0d3793a57..000000000 --- a/tools/vendor/github.com/esimonov/ifshort/pkg/analyzer/occurrences.go +++ /dev/null @@ -1,268 +0,0 @@ -package analyzer - -import ( - "go/ast" - "go/token" - "time" - - "golang.org/x/tools/go/analysis" -) - -// occurrence is a variable occurrence. -type occurrence struct { - declarationPos token.Pos - ifStmtPos token.Pos -} - -func (occ *occurrence) isComplete() bool { - return occ.ifStmtPos != token.NoPos && occ.declarationPos != token.NoPos -} - -// scopeMarkeredOccurences is a map of scope markers to variable occurrences. -type scopeMarkeredOccurences map[int64]occurrence - -func (smo scopeMarkeredOccurences) getGreatestMarker() int64 { - var maxScopeMarker int64 - - for marker := range smo { - if marker > maxScopeMarker { - maxScopeMarker = marker - } - } - return maxScopeMarker -} - -// find scope marker of the greatest token.Pos that is smaller than provided. -func (smo scopeMarkeredOccurences) getScopeMarkerForPosition(pos token.Pos) int64 { - var m int64 - var foundPos token.Pos - - for marker, occ := range smo { - if occ.declarationPos < pos && occ.declarationPos >= foundPos { - m = marker - foundPos = occ.declarationPos - } - } - return m -} - -func (smo scopeMarkeredOccurences) isEmponymousKey(pos token.Pos) bool { - if pos == token.NoPos { - return false - } - - for _, occ := range smo { - if occ.ifStmtPos == pos { - return true - } - } - return false -} - -// namedOccurrenceMap is a map of variable names to scopeMarkeredOccurences. -type namedOccurrenceMap map[string]scopeMarkeredOccurences - -func getNamedOccurrenceMap(fdecl *ast.FuncDecl, pass *analysis.Pass) namedOccurrenceMap { - nom := namedOccurrenceMap(map[string]scopeMarkeredOccurences{}) - - if fdecl == nil || fdecl.Body == nil { - return nom - } - - for _, stmt := range fdecl.Body.List { - switch v := stmt.(type) { - case *ast.AssignStmt: - nom.addFromAssignment(pass, v) - case *ast.IfStmt: - nom.addFromCondition(v) - nom.addFromIfClause(v) - nom.addFromElseClause(v) - } - } - - candidates := namedOccurrenceMap(map[string]scopeMarkeredOccurences{}) - - for varName, markeredOccs := range nom { - for marker, occ := range markeredOccs { - if !occ.isComplete() && !nom.isFoundByScopeMarker(marker) { - continue - } - if _, ok := candidates[varName]; !ok { - candidates[varName] = scopeMarkeredOccurences{ - marker: occ, - } - } else { - candidates[varName][marker] = occ - } - } - } - return candidates -} - -func (nom namedOccurrenceMap) isFoundByScopeMarker(scopeMarker int64) bool { - var i int - - for _, markeredOccs := range nom { - for marker := range markeredOccs { - if marker == scopeMarker { - i++ - } - } - } - return i >= 2 -} - -func (nom namedOccurrenceMap) addFromAssignment(pass *analysis.Pass, assignment *ast.AssignStmt) { - if assignment.Tok != token.DEFINE { - return - } - - scopeMarker := time.Now().UnixNano() - - for i, el := range assignment.Lhs { - ident, ok := el.(*ast.Ident) - if !ok { - continue - } - - if ident.Name == "_" || ident.Obj == nil || isUnshortenableAssignment(ident.Obj.Decl) { - continue - } - - if markeredOccs, ok := nom[ident.Name]; ok { - markeredOccs[scopeMarker] = occurrence{ - declarationPos: ident.Pos(), - } - nom[ident.Name] = markeredOccs - } else { - newOcc := occurrence{} - if areFlagSettingsSatisfied(pass, assignment, i) { - newOcc.declarationPos = ident.Pos() - } - nom[ident.Name] = scopeMarkeredOccurences{scopeMarker: newOcc} - } - } -} - -func isUnshortenableAssignment(decl interface{}) bool { - assign, ok := decl.(*ast.AssignStmt) - if !ok { - return false - } - - for _, el := range assign.Rhs { - u, ok := el.(*ast.UnaryExpr) - if !ok { - continue - } - - if u.Op == token.AND { - if _, ok := u.X.(*ast.CompositeLit); ok { - return true - } - } - } - return false -} - -func areFlagSettingsSatisfied(pass *analysis.Pass, assignment *ast.AssignStmt, i int) bool { - lh := assignment.Lhs[i] - rh := assignment.Rhs[len(assignment.Rhs)-1] - - if len(assignment.Rhs) == len(assignment.Lhs) { - rh = assignment.Rhs[i] - } - - if pass.Fset.Position(rh.End()).Line-pass.Fset.Position(rh.Pos()).Line > maxDeclLines { - return false - } - if int(rh.End()-lh.Pos()) > maxDeclChars { - return false - } - return true -} - -func (nom namedOccurrenceMap) addFromCondition(stmt *ast.IfStmt) { - switch v := stmt.Cond.(type) { - case *ast.BinaryExpr: - for _, v := range [2]ast.Expr{v.X, v.Y} { - switch e := v.(type) { - case *ast.CallExpr: - nom.addFromCallExpr(stmt.If, e) - case *ast.Ident: - nom.addFromIdent(stmt.If, e) - case *ast.SelectorExpr: - nom.addFromIdent(stmt.If, e.X) - } - } - case *ast.CallExpr: - for _, a := range v.Args { - switch e := a.(type) { - case *ast.Ident: - nom.addFromIdent(stmt.If, e) - case *ast.CallExpr: - nom.addFromCallExpr(stmt.If, e) - } - } - case *ast.Ident: - nom.addFromIdent(stmt.If, v) - case *ast.UnaryExpr: - switch e := v.X.(type) { - case *ast.Ident: - nom.addFromIdent(stmt.If, e) - case *ast.SelectorExpr: - nom.addFromIdent(stmt.If, e.X) - } - } -} - -func (nom namedOccurrenceMap) addFromIfClause(stmt *ast.IfStmt) { - nom.addFromBlockStmt(stmt.Body, stmt.If) -} - -func (nom namedOccurrenceMap) addFromElseClause(stmt *ast.IfStmt) { - nom.addFromBlockStmt(stmt.Else, stmt.If) -} - -func (nom namedOccurrenceMap) addFromBlockStmt(stmt ast.Stmt, ifPos token.Pos) { - blockStmt, ok := stmt.(*ast.BlockStmt) - if !ok { - return - } - - for _, el := range blockStmt.List { - exptStmt, ok := el.(*ast.ExprStmt) - if !ok { - continue - } - - if callExpr, ok := exptStmt.X.(*ast.CallExpr); ok { - nom.addFromCallExpr(ifPos, callExpr) - } - } -} - -func (nom namedOccurrenceMap) addFromCallExpr(ifPos token.Pos, callExpr *ast.CallExpr) { - for _, arg := range callExpr.Args { - nom.addFromIdent(ifPos, arg) - } -} - -func (nom namedOccurrenceMap) addFromIdent(ifPos token.Pos, v ast.Expr) { - ident, ok := v.(*ast.Ident) - if !ok { - return - } - - if markeredOccs, ok := nom[ident.Name]; ok { - marker := nom[ident.Name].getGreatestMarker() - - occ := markeredOccs[marker] - if occ.isComplete() { - return - } - - occ.ifStmtPos = ifPos - nom[ident.Name][marker] = occ - } -} diff --git a/tools/vendor/github.com/ettle/strcase/.golangci.yml b/tools/vendor/github.com/ettle/strcase/.golangci.yml index 4d31fcc5b..b7ce85d42 100644 --- a/tools/vendor/github.com/ettle/strcase/.golangci.yml +++ b/tools/vendor/github.com/ettle/strcase/.golangci.yml @@ -14,8 +14,6 @@ linters-settings: - ifElseChain - whyNoLint - wrapperFunc - golint: - min-confidence: 0.5 govet: check-shadowing: true lll: @@ -37,7 +35,6 @@ linters: disable-all: true enable: - bodyclose - - deadcode - depguard - dogsled - dupl @@ -47,26 +44,23 @@ linters: - gocyclo - gofmt - goimports - - golint - goprintffuncname - gosec - gosimple - govet - ineffassign - - interfacer - lll - misspell - nakedret - nolintlint + - revive - rowserrcheck - staticcheck - - structcheck - stylecheck - typecheck - unconvert - unparam - unused - - varcheck - whitespace # don't enable: diff --git a/tools/vendor/github.com/ettle/strcase/.readme.tmpl b/tools/vendor/github.com/ettle/strcase/.readme.tmpl index 135765c40..4d7a894f0 100644 --- a/tools/vendor/github.com/ettle/strcase/.readme.tmpl +++ b/tools/vendor/github.com/ettle/strcase/.readme.tmpl @@ -16,10 +16,10 @@ Convert strings to `snake_case`, `camelCase`, `PascalCase`, `kebab-case` and mor ## Index{{if .Consts}} * [Constants](#pkg-constants){{end}}{{if .Vars}} * [Variables](#pkg-variables){{end}}{{- range .Funcs -}}{{$name_html := html .Name}} -* [{{node_html $ .Decl false | sanitize}}](#{{$name_html}}){{- end}}{{- range .Types}}{{$tname_html := html .Name}} -* [type {{$tname_html}}](#{{$tname_html}}){{- range .Funcs}}{{$name_html := html .Name}} - * [{{node_html $ .Decl false | sanitize}}](#{{$name_html}}){{- end}}{{- range .Methods}}{{$name_html := html .Name}} - * [{{node_html $ .Decl false | sanitize}}](#{{$tname_html}}.{{$name_html}}){{- end}}{{- end}}{{- if $.Notes}}{{- range $marker, $item := $.Notes}} +* [{{node_html $ .Decl false | sanitize}}](#func-{{$name_html}}){{- end}}{{- range .Types}}{{$tname_html := html .Name}} +* [type {{$tname_html}}](#type-{{$tname_html}}){{- range .Funcs}}{{$name_html := html .Name}} + * [{{node_html $ .Decl false | sanitize}}](#func-{{$name_html}}){{- end}}{{- range .Methods}}{{$name_html := html .Name}} + * [{{node_html $ .Decl false | sanitize}}](#type-{{$tname_html}}.{{$name_html}}){{- end}}{{- end}}{{- if $.Notes}}{{- range $marker, $item := $.Notes}} * [{{noteTitle $marker | html}}s](#pkg-note-{{$marker}}){{end}}{{end}} {{if $.Examples}} #### Examples{{- range $.Examples}} diff --git a/tools/vendor/github.com/ettle/strcase/Makefile b/tools/vendor/github.com/ettle/strcase/Makefile index 462f8b473..ac98b4aa5 100644 --- a/tools/vendor/github.com/ettle/strcase/Makefile +++ b/tools/vendor/github.com/ettle/strcase/Makefile @@ -1,16 +1,19 @@ .PHONY: benchmark docs lint test docs: - which godoc2ghmd || ( go get github.com/DevotedHealth/godoc2ghmd && go mod tidy ) + which godoc2ghmd || go get github.com/DevotedHealth/godoc2ghmd godoc2ghmd -template .readme.tmpl github.com/ettle/strcase > README.md + go mod tidy test: go test -cover ./... lint: - which golangci-lint || ( go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.27.0 && go mod tidy ) + which golangci-lint || go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.50.1 golangci-lint run golangci-lint run benchmark/*.go + go mod tidy benchmark: - cd benchmark && go test -bench=. -test.benchmem && go mod tidy + cd benchmark && go test -bench=. -test.benchmem + go mod tidy diff --git a/tools/vendor/github.com/ettle/strcase/README.md b/tools/vendor/github.com/ettle/strcase/README.md index ee165e3e5..a984da80d 100644 --- a/tools/vendor/github.com/ettle/strcase/README.md +++ b/tools/vendor/github.com/ettle/strcase/README.md @@ -32,21 +32,24 @@ Example usage strcase.ToSnake("FOOBar") // foo_bar // Support Go initialisms - strcase.ToGoCamel("http_response") // HTTPResponse + strcase.ToGoPascal("http_response") // HTTPResponse // Specify case and delimiter strcase.ToCase("HelloWorld", strcase.UpperCase, '.') // HELLO.WORLD -### Why this package +## Why this package + String strcase is pretty straight forward and there are a number of methods to do it. This package is fully featured, more customizable, better tested, and -faster* than other packages and what you would probably whip up yourself. +faster than other packages and what you would probably whip up yourself. ### Unicode support + We work for with unicode strings and pay very little performance penalty for it as we optimized for the common use case of ASCII only strings. ### Customization + You can create a custom caser that changes the behavior to what you want. This customization also reduces the pressure for us to change the default behavior which means that things are more stable for everyone involved. The goal is to @@ -71,19 +74,22 @@ make the common path easy and fast, while making the uncommon path possible. assert.Equal(t, "http_200", c.ToSnake("http200")) ### Initialism support + By default, we use the golint intialisms list. You can customize and override the initialisms if you wish to add additional ones, such as "SSL" or "CMS" or domain specific ones to your industry. - ToGoCamel("http_response") // HTTPResponse + ToGoPascal("http_response") // HTTPResponse ToGoSnake("http_response") // HTTP_response ### Test coverage + We have a wide ranging test suite to make sure that we understand our behavior. Test coverage isn't everything, but we aim for 100% coverage. ### Fast + Optimized to reduce memory allocations with Builder. Benchmarked and optimized around common cases. @@ -96,56 +102,57 @@ Hopefully I was fair to each library and happy to rerun benchmarks differently or reword my commentary based on suggestions or updates. - // This package - // Go intialisms and custom casers are slower - BenchmarkToTitle-4 992491 1559 ns/op 32 B/op 1 allocs/op - BenchmarkToSnake-4 1000000 1475 ns/op 32 B/op 1 allocs/op - BenchmarkToSNAKE-4 1000000 1609 ns/op 32 B/op 1 allocs/op - BenchmarkToGoSnake-4 275010 3697 ns/op 44 B/op 4 allocs/op - BenchmarkToCustomCaser-4 342704 4191 ns/op 56 B/op 4 allocs/op + // This package - faster then almost all libraries + // Initialisms are more complicated and slightly slower, but still fast + BenchmarkToTitle-96 9617142 125.7 ns/op 16 B/op 1 allocs/op + BenchmarkToSnake-96 10659919 120.7 ns/op 16 B/op 1 allocs/op + BenchmarkToSNAKE-96 9018282 126.4 ns/op 16 B/op 1 allocs/op + BenchmarkToGoSnake-96 4903687 254.5 ns/op 26 B/op 4 allocs/op + BenchmarkToCustomCaser-96 4434489 265.0 ns/op 28 B/op 4 allocs/op // Segment has very fast snake case and camel case libraries // No features or customization, but very very fast - BenchmarkSegment-4 1303809 938 ns/op 16 B/op 1 allocs/op + BenchmarkSegment-96 33625734 35.54 ns/op 16 B/op 1 allocs/op - // Stdlib strings.Title for comparison, even though it only splits on spaces - BenchmarkToTitleStrings-4 1213467 1164 ns/op 16 B/op 1 allocs/op + // Iancoleman has gotten some performance improvements, but remains + // without unicode support and lacks fine-grained customization + BenchmarkToSnakeIan-96 13141522 92.99 ns/op 16 B/op 1 allocs/op + + // Stdlib strings.Title is deprecated; using golang.org/x.text + BenchmarkGolangOrgXTextCases-96 4665676 262.5 ns/op 272 B/op 2 allocs/op // Other libraries or code snippets // - Most are slower, by up to an order of magnitude - // - None support initialisms or customization + // - No support for initialisms or customization // - Some generate only camelCase or snake_case // - Many lack unicode support - BenchmarkToSnakeStoewer-4 973200 2075 ns/op 64 B/op 2 allocs/op + BenchmarkToSnakeStoewer-96 8095468 148.9 ns/op 64 B/op 2 allocs/op // Copying small rune arrays is slow - BenchmarkToSnakeSiongui-4 264315 4229 ns/op 48 B/op 10 allocs/op - BenchmarkGoValidator-4 206811 5152 ns/op 184 B/op 9 allocs/op + BenchmarkToSnakeSiongui-96 2912593 401.7 ns/op 112 B/op 19 allocs/op + BenchmarkGoValidator-96 3493800 342.6 ns/op 184 B/op 9 allocs/op // String alloction is slow - BenchmarkToSnakeFatih-4 82675 12280 ns/op 392 B/op 26 allocs/op - BenchmarkToSnakeIanColeman-4 83276 13903 ns/op 145 B/op 13 allocs/op + BenchmarkToSnakeFatih-96 1282648 945.1 ns/op 616 B/op 26 allocs/op // Regexp is slow - BenchmarkToSnakeGolangPrograms-4 74448 18586 ns/op 176 B/op 11 allocs/op + BenchmarkToSnakeGolangPrograms-96 778674 1495 ns/op 227 B/op 11 allocs/op // These results aren't a surprise - my initial version of this library was // painfully slow. I think most of us, without spending some time with // profilers and benchmarks, would write also something on the slower side. -### Why not this package +### Zero dependencies + +That's right - zero. We only import the Go standard library. No hassles with +dependencies, licensing, security alerts. + +## Why not this package + If every nanosecond matters and this is used in a tight loop, use segment.io's libraries (https://github.com/segmentio/go-snakecase and https://github.com/segmentio/go-camelcase). They lack features, but make up for -it by being blazing fast. Alternatively, if you need your code to work slightly -differently, fork them and tailor it for your use case. - -If you don't like having external imports, I get it. This package only imports -packages for testing, otherwise it only uses the standard library. If that's -not enough, you can use this repo as the foundation for your own. MIT Licensed. +it by being blazing fast. -This package is still relatively new and while I've used it for a while -personally, it doesn't have the miles that other packages do. I've tested this -code agains't their test cases to make sure that there aren't any surprises. +## Migrating from other packages -### Migrating from other packages If you are migrating from from another package, you may find slight differences in output. To reduce the delta, you may find it helpful to use the following custom casers to mimic the behavior of the other package. @@ -161,32 +168,32 @@ custom casers to mimic the behavior of the other package. ## Index -* [func ToCamel(s string) string](#ToCamel) -* [func ToCase(s string, wordCase WordCase, delimiter rune) string](#ToCase) -* [func ToGoCamel(s string) string](#ToGoCamel) -* [func ToGoCase(s string, wordCase WordCase, delimiter rune) string](#ToGoCase) -* [func ToGoKebab(s string) string](#ToGoKebab) -* [func ToGoPascal(s string) string](#ToGoPascal) -* [func ToGoSnake(s string) string](#ToGoSnake) -* [func ToKEBAB(s string) string](#ToKEBAB) -* [func ToKebab(s string) string](#ToKebab) -* [func ToPascal(s string) string](#ToPascal) -* [func ToSNAKE(s string) string](#ToSNAKE) -* [func ToSnake(s string) string](#ToSnake) -* [type Caser](#Caser) - * [func NewCaser(goInitialisms bool, initialismOverrides map[string]bool, splitFn SplitFn) *Caser](#NewCaser) - * [func (c *Caser) ToCamel(s string) string](#Caser.ToCamel) - * [func (c *Caser) ToCase(s string, wordCase WordCase, delimiter rune) string](#Caser.ToCase) - * [func (c *Caser) ToKEBAB(s string) string](#Caser.ToKEBAB) - * [func (c *Caser) ToKebab(s string) string](#Caser.ToKebab) - * [func (c *Caser) ToPascal(s string) string](#Caser.ToPascal) - * [func (c *Caser) ToSNAKE(s string) string](#Caser.ToSNAKE) - * [func (c *Caser) ToSnake(s string) string](#Caser.ToSnake) -* [type SplitAction](#SplitAction) -* [type SplitFn](#SplitFn) - * [func NewSplitFn(delimiters []rune, splitOptions ...SplitOption) SplitFn](#NewSplitFn) -* [type SplitOption](#SplitOption) -* [type WordCase](#WordCase) +* [func ToCamel(s string) string](#func-ToCamel) +* [func ToCase(s string, wordCase WordCase, delimiter rune) string](#func-ToCase) +* [func ToGoCamel(s string) string](#func-ToGoCamel) +* [func ToGoCase(s string, wordCase WordCase, delimiter rune) string](#func-ToGoCase) +* [func ToGoKebab(s string) string](#func-ToGoKebab) +* [func ToGoPascal(s string) string](#func-ToGoPascal) +* [func ToGoSnake(s string) string](#func-ToGoSnake) +* [func ToKEBAB(s string) string](#func-ToKEBAB) +* [func ToKebab(s string) string](#func-ToKebab) +* [func ToPascal(s string) string](#func-ToPascal) +* [func ToSNAKE(s string) string](#func-ToSNAKE) +* [func ToSnake(s string) string](#func-ToSnake) +* [type Caser](#type-Caser) + * [func NewCaser(goInitialisms bool, initialismOverrides map[string]bool, splitFn SplitFn) *Caser](#func-NewCaser) + * [func (c *Caser) ToCamel(s string) string](#type-Caser.ToCamel) + * [func (c *Caser) ToCase(s string, wordCase WordCase, delimiter rune) string](#type-Caser.ToCase) + * [func (c *Caser) ToKEBAB(s string) string](#type-Caser.ToKEBAB) + * [func (c *Caser) ToKebab(s string) string](#type-Caser.ToKebab) + * [func (c *Caser) ToPascal(s string) string](#type-Caser.ToPascal) + * [func (c *Caser) ToSNAKE(s string) string](#type-Caser.ToSNAKE) + * [func (c *Caser) ToSnake(s string) string](#type-Caser.ToSnake) +* [type SplitAction](#type-SplitAction) +* [type SplitFn](#type-SplitFn) + * [func NewSplitFn(delimiters []rune, splitOptions ...SplitOption) SplitFn](#func-NewSplitFn) +* [type SplitOption](#type-SplitOption) +* [type WordCase](#type-WordCase) @@ -201,7 +208,7 @@ Also known as lowerCamelCase or mixedCase. -## func [ToCase](./strcase.go#L70) +## func [ToCase](./strcase.go#L72) ``` go func ToCase(s string, wordCase WordCase, delimiter rune) string ``` @@ -209,18 +216,20 @@ ToCase returns words in given case and delimiter. -## func [ToGoCamel](./strcase.go#L65) +## func [ToGoCamel](./strcase.go#L67) ``` go func ToGoCamel(s string) string ``` ToGoCamel returns words in camelCase (capitalized words concatenated together, with first word lower case). Also known as lowerCamelCase or mixedCase. -Respects Go's common initialisms (e.g. httpResponse -> HTTPResponse). +Respects Go's common initialisms, but first word remains lowercased which is +important for code generator use cases (e.g. toJson -> toJSON, httpResponse +-> httpResponse). -## func [ToGoCase](./strcase.go#L77) +## func [ToGoCase](./strcase.go#L79) ``` go func ToGoCase(s string, wordCase WordCase, delimiter rune) string ``` @@ -415,7 +424,7 @@ ToSnake returns words in snake_case (lower case words with underscores). -## type [SplitAction](./split.go#L110) +## type [SplitAction](./split.go#L111) ``` go type SplitAction int ``` @@ -457,7 +466,7 @@ SplitFn defines how to split a string into words -### func [NewSplitFn](./split.go#L14-L17) +### func [NewSplitFn](./split.go#L15-L18) ``` go func NewSplitFn( delimiters []rune, @@ -469,13 +478,12 @@ NewSplitFn returns a SplitFn based on the options provided. NewSplitFn covers the majority of common options that other strcase libraries provide and should allow you to simply create a custom caser. For more complicated use cases, feel free to write your own SplitFn -nolint:gocyclo -## type [SplitOption](./split.go#L93) +## type [SplitOption](./split.go#L94) ``` go type SplitOption int ``` @@ -524,6 +532,9 @@ const ( // TitleCase - Only first letter upper cased (Example) TitleCase // CamelCase - TitleCase except lower case first word (exampleText) + // Notably, even if the first word is an initialism, it will be lower + // cased. This is important for code generators where capital letters + // mean exported functions. i.e. jsonString(), not JSONString() CamelCase ) ``` diff --git a/tools/vendor/github.com/ettle/strcase/assert.go b/tools/vendor/github.com/ettle/strcase/assert.go new file mode 100644 index 000000000..09344e40f --- /dev/null +++ b/tools/vendor/github.com/ettle/strcase/assert.go @@ -0,0 +1,24 @@ +package strcase + +// We use a lightweight replacement for testify/assert to reduce dependencies + +// testingT interface allows us to test our assert functions +type testingT interface { + Logf(format string, args ...interface{}) + Fail() +} + +// assertTrue will fail if the value is not true +func assertTrue(t testingT, value bool) { + if !value { + t.Fail() + } +} + +// assertEqual will fail if the two strings are not equal +func assertEqual(t testingT, expected, actual string) { + if expected != actual { + t.Logf("Expected: %s Actual: %s", expected, actual) + t.Fail() + } +} diff --git a/tools/vendor/github.com/ettle/strcase/caser.go b/tools/vendor/github.com/ettle/strcase/caser.go index 891a67189..2e7eb955b 100644 --- a/tools/vendor/github.com/ettle/strcase/caser.go +++ b/tools/vendor/github.com/ettle/strcase/caser.go @@ -10,17 +10,17 @@ type Caser struct { // // A Caser should be created when you want fine grained control over how the words are split. // -// Notes on function arguments +// Notes on function arguments // -// goInitialisms: Whether to use Golint's intialisms +// goInitialisms: Whether to use Golint's intialisms // -// initialismOverrides: A mapping of extra initialisms -// Keys must be in ALL CAPS. Merged with Golint's if goInitialisms is set. -// Setting a key to false will override Golint's. +// initialismOverrides: A mapping of extra initialisms +// Keys must be in ALL CAPS. Merged with Golint's if goInitialisms is set. +// Setting a key to false will override Golint's. // -// splitFn: How to separate words -// Override the default split function. Consider using NewSplitFn to -// configure one instead of writing your own. +// splitFn: How to separate words +// Override the default split function. Consider using NewSplitFn to +// configure one instead of writing your own. func NewCaser(goInitialisms bool, initialismOverrides map[string]bool, splitFn SplitFn) *Caser { c := &Caser{ initialisms: golintInitialisms, diff --git a/tools/vendor/github.com/ettle/strcase/convert.go b/tools/vendor/github.com/ettle/strcase/convert.go index 70fedb144..cb901d079 100644 --- a/tools/vendor/github.com/ettle/strcase/convert.go +++ b/tools/vendor/github.com/ettle/strcase/convert.go @@ -29,6 +29,7 @@ const ( // Case 2: UpperCase words, which don't need to support initialisms since everything is in upper case // convertWithoutInitialims only works for to UpperCase and LowerCase +// //nolint:gocyclo func convertWithoutInitialisms(input string, delimiter rune, wordCase WordCase) string { input = strings.TrimSpace(input) @@ -38,7 +39,7 @@ func convertWithoutInitialisms(input string, delimiter rune, wordCase WordCase) } var b strings.Builder - b.Grow(len(input) * 2) // In case we need to write delimiters where they weren't before + b.Grow(len(input) + 4) // In case we need to write delimiters where they weren't before var prev, curr rune next := runes[0] // 0 length will have already returned so safe to index @@ -90,13 +91,14 @@ func convertWithoutInitialisms(input string, delimiter rune, wordCase WordCase) // Must be original case b.WriteRune(curr) } - inWord = inWord || true + inWord = true } return b.String() } // convertWithGoInitialisms changes a input string to a certain case with a // delimiter, respecting go initialisms but not skip runes +// //nolint:gocyclo func convertWithGoInitialisms(input string, delimiter rune, wordCase WordCase) string { input = strings.TrimSpace(input) @@ -106,7 +108,7 @@ func convertWithGoInitialisms(input string, delimiter rune, wordCase WordCase) s } var b strings.Builder - b.Grow(len(input) * 2) // In case we need to write delimiters where they weren't before + b.Grow(len(input) + 4) // In case we need to write delimiters where they weren't before firstWord := true @@ -122,10 +124,15 @@ func convertWithGoInitialisms(input string, delimiter rune, wordCase WordCase) s // Don't bother with initialisms if the word is longer than 5 // A quick proxy to avoid the extra memory allocations if end-start <= 5 { - key := strings.ToUpper(string(runes[start:end])) - if golintInitialisms[key] { + var word strings.Builder + word.Grow(end - start) + for i := start; i < end; i++ { + word.WriteRune(toUpper(runes[i])) + } + w := word.String() + if golintInitialisms[w] { if !firstWord || wordCase != CamelCase { - b.WriteString(key) + b.WriteString(w) firstWord = false return } @@ -188,6 +195,7 @@ func convertWithGoInitialisms(input string, delimiter rune, wordCase WordCase) s // convert changes a input string to a certain case with a delimiter, // respecting arbitrary initialisms and skip characters +// //nolint:gocyclo func convert(input string, fn SplitFn, delimiter rune, wordCase WordCase, initialisms map[string]bool) string { @@ -198,7 +206,7 @@ func convert(input string, fn SplitFn, delimiter rune, wordCase WordCase, } var b strings.Builder - b.Grow(len(input) * 2) // In case we need to write delimiters where they weren't before + b.Grow(len(input) + 4) // In case we need to write delimiters where they weren't before firstWord := true var skipIndexes []int @@ -221,13 +229,14 @@ func convert(input string, fn SplitFn, delimiter rune, wordCase WordCase, // I'm open to it if there is a use case if initialisms != nil { var word strings.Builder + word.Grow(end - start) for i := start; i < end; i++ { word.WriteRune(toUpper(runes[i])) } - key := word.String() - if initialisms[key] { + w := word.String() + if initialisms[w] { if !firstWord || wordCase != CamelCase { - b.WriteString(key) + b.WriteString(w) firstWord = false return } diff --git a/tools/vendor/github.com/ettle/strcase/doc.go b/tools/vendor/github.com/ettle/strcase/doc.go index b898a4e45..c3bf14a8f 100644 --- a/tools/vendor/github.com/ettle/strcase/doc.go +++ b/tools/vendor/github.com/ettle/strcase/doc.go @@ -2,78 +2,78 @@ Package strcase is a package for converting strings into various word cases (e.g. snake_case, camelCase) - go get -u github.com/ettle/strcase + go get -u github.com/ettle/strcase Example usage - strcase.ToSnake("Hello World") // hello_world - strcase.ToSNAKE("Hello World") // HELLO_WORLD + strcase.ToSnake("Hello World") // hello_world + strcase.ToSNAKE("Hello World") // HELLO_WORLD - strcase.ToKebab("helloWorld") // hello-world - strcase.ToKEBAB("helloWorld") // HELLO-WORLD + strcase.ToKebab("helloWorld") // hello-world + strcase.ToKEBAB("helloWorld") // HELLO-WORLD - strcase.ToPascal("hello-world") // HelloWorld - strcase.ToCamel("hello-world") // helloWorld + strcase.ToPascal("hello-world") // HelloWorld + strcase.ToCamel("hello-world") // helloWorld - // Handle odd cases - strcase.ToSnake("FOOBar") // foo_bar + // Handle odd cases + strcase.ToSnake("FOOBar") // foo_bar - // Support Go initialisms - strcase.ToGoPascal("http_response") // HTTPResponse + // Support Go initialisms + strcase.ToGoPascal("http_response") // HTTPResponse - // Specify case and delimiter - strcase.ToCase("HelloWorld", strcase.UpperCase, '.') // HELLO.WORLD + // Specify case and delimiter + strcase.ToCase("HelloWorld", strcase.UpperCase, '.') // HELLO.WORLD -Why this package +## Why this package String strcase is pretty straight forward and there are a number of methods to do it. This package is fully featured, more customizable, better tested, and -faster* than other packages and what you would probably whip up yourself. +faster than other packages and what you would probably whip up yourself. -Unicode support +### Unicode support We work for with unicode strings and pay very little performance penalty for it as we optimized for the common use case of ASCII only strings. -Customization +### Customization You can create a custom caser that changes the behavior to what you want. This customization also reduces the pressure for us to change the default behavior which means that things are more stable for everyone involved. The goal is to make the common path easy and fast, while making the uncommon path possible. - c := NewCaser( - // Use Go's default initialisms e.g. ID, HTML - true, - // Override initialisms (e.g. don't initialize HTML but initialize SSL - map[string]bool{"SSL": true, "HTML": false}, - // Write your own custom SplitFn - // - NewSplitFn( - []rune{'*', '.', ','}, - SplitCase, - SplitAcronym, - PreserveNumberFormatting, - SplitBeforeNumber, - SplitAfterNumber, - )) - assert.Equal(t, "http_200", c.ToSnake("http200")) - -Initialism support + c := NewCaser( + // Use Go's default initialisms e.g. ID, HTML + true, + // Override initialisms (e.g. don't initialize HTML but initialize SSL + map[string]bool{"SSL": true, "HTML": false}, + // Write your own custom SplitFn + // + NewSplitFn( + []rune{'*', '.', ','}, + SplitCase, + SplitAcronym, + PreserveNumberFormatting, + SplitBeforeNumber, + SplitAfterNumber, + )) + assert.Equal(t, "http_200", c.ToSnake("http200")) + +### Initialism support By default, we use the golint intialisms list. You can customize and override the initialisms if you wish to add additional ones, such as "SSL" or "CMS" or domain specific ones to your industry. - ToGoPascal("http_response") // HTTPResponse - ToGoSnake("http_response") // HTTP_response + ToGoPascal("http_response") // HTTPResponse + ToGoSnake("http_response") // HTTP_response -Test coverage +### Test coverage We have a wide ranging test suite to make sure that we understand our behavior. Test coverage isn't everything, but we aim for 100% coverage. -Fast +### Fast Optimized to reduce memory allocations with Builder. Benchmarked and optimized around common cases. @@ -86,70 +86,65 @@ common cases have a large performance impact. Hopefully I was fair to each library and happy to rerun benchmarks differently or reword my commentary based on suggestions or updates. - // This package - faster then almost all libraries - // Initialisms are more complicated and slightly slower, but still faster then other libraries that do less - BenchmarkToTitle-4 7821166 221 ns/op 32 B/op 1 allocs/op - BenchmarkToSnake-4 9378589 202 ns/op 32 B/op 1 allocs/op - BenchmarkToSNAKE-4 6174453 223 ns/op 32 B/op 1 allocs/op - BenchmarkToGoSnake-4 3114266 434 ns/op 44 B/op 4 allocs/op - BenchmarkToCustomCaser-4 2973855 448 ns/op 56 B/op 4 allocs/op - - // Segment has very fast snake case and camel case libraries - // No features or customization, but very very fast - BenchmarkSegment-4 24003495 64.9 ns/op 16 B/op 1 allocs/op - - // Stdlib strings.Title for comparison, even though it only splits on spaces - BenchmarkToTitleStrings-4 11259376 161 ns/op 16 B/op 1 allocs/op - - // Other libraries or code snippets - // - Most are slower, by up to an order of magnitude - // - None support initialisms or customization - // - Some generate only camelCase or snake_case - // - Many lack unicode support - BenchmarkToSnakeStoewer-4 7103268 297 ns/op 64 B/op 2 allocs/op - // Copying small rune arrays is slow - BenchmarkToSnakeSiongui-4 3710768 413 ns/op 48 B/op 10 allocs/op - BenchmarkGoValidator-4 2416479 1049 ns/op 184 B/op 9 allocs/op - // String alloction is slow - BenchmarkToSnakeFatih-4 1000000 2407 ns/op 624 B/op 26 allocs/op - BenchmarkToSnakeIanColeman-4 1005766 1426 ns/op 160 B/op 13 allocs/op - // Regexp is slow - BenchmarkToSnakeGolangPrograms-4 614689 2237 ns/op 225 B/op 11 allocs/op - - - - // These results aren't a surprise - my initial version of this library was - // painfully slow. I think most of us, without spending some time with - // profilers and benchmarks, would write also something on the slower side. - - -Why not this package + // This package - faster then almost all libraries + // Initialisms are more complicated and slightly slower, but still fast + BenchmarkToTitle-96 9617142 125.7 ns/op 16 B/op 1 allocs/op + BenchmarkToSnake-96 10659919 120.7 ns/op 16 B/op 1 allocs/op + BenchmarkToSNAKE-96 9018282 126.4 ns/op 16 B/op 1 allocs/op + BenchmarkToGoSnake-96 4903687 254.5 ns/op 26 B/op 4 allocs/op + BenchmarkToCustomCaser-96 4434489 265.0 ns/op 28 B/op 4 allocs/op + + // Segment has very fast snake case and camel case libraries + // No features or customization, but very very fast + BenchmarkSegment-96 33625734 35.54 ns/op 16 B/op 1 allocs/op + + // Iancoleman has gotten some performance improvements, but remains + // without unicode support and lacks fine-grained customization + BenchmarkToSnakeIan-96 13141522 92.99 ns/op 16 B/op 1 allocs/op + + // Stdlib strings.Title is deprecated; using golang.org/x.text + BenchmarkGolangOrgXTextCases-96 4665676 262.5 ns/op 272 B/op 2 allocs/op + + // Other libraries or code snippets + // - Most are slower, by up to an order of magnitude + // - No support for initialisms or customization + // - Some generate only camelCase or snake_case + // - Many lack unicode support + BenchmarkToSnakeStoewer-96 8095468 148.9 ns/op 64 B/op 2 allocs/op + // Copying small rune arrays is slow + BenchmarkToSnakeSiongui-96 2912593 401.7 ns/op 112 B/op 19 allocs/op + BenchmarkGoValidator-96 3493800 342.6 ns/op 184 B/op 9 allocs/op + // String alloction is slow + BenchmarkToSnakeFatih-96 1282648 945.1 ns/op 616 B/op 26 allocs/op + // Regexp is slow + BenchmarkToSnakeGolangPrograms-96 778674 1495 ns/op 227 B/op 11 allocs/op + + // These results aren't a surprise - my initial version of this library was + // painfully slow. I think most of us, without spending some time with + // profilers and benchmarks, would write also something on the slower side. + +### Zero dependencies + +That's right - zero. We only import the Go standard library. No hassles with +dependencies, licensing, security alerts. + +## Why not this package If every nanosecond matters and this is used in a tight loop, use segment.io's libraries (https://github.com/segmentio/go-snakecase and https://github.com/segmentio/go-camelcase). They lack features, but make up for -it by being blazing fast. Alternatively, if you need your code to work slightly -differently, fork them and tailor it for your use case. - -If you don't like having external imports, I get it. This package only imports -packages for testing, otherwise it only uses the standard library. If that's -not enough, you can use this repo as the foundation for your own. MIT Licensed. +it by being blazing fast. -This package is still relatively new and while I've used it for a while -personally, it doesn't have the miles that other packages do. I've tested this -code agains't their test cases to make sure that there aren't any surprises. - -Migrating from other packages +## Migrating from other packages If you are migrating from from another package, you may find slight differences in output. To reduce the delta, you may find it helpful to use the following custom casers to mimic the behavior of the other package. - // From https://github.com/iancoleman/strcase - var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-', '.'}, SplitCase, SplitAcronym, SplitBeforeNumber)) - - // From https://github.com/stoewer/go-strcase - var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-'}, SplitCase), SplitAcronym) + // From https://github.com/iancoleman/strcase + var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-', '.'}, SplitCase, SplitAcronym, SplitBeforeNumber)) + // From https://github.com/stoewer/go-strcase + var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-'}, SplitCase), SplitAcronym) */ package strcase diff --git a/tools/vendor/github.com/ettle/strcase/split.go b/tools/vendor/github.com/ettle/strcase/split.go index 84381106b..32bc29759 100644 --- a/tools/vendor/github.com/ettle/strcase/split.go +++ b/tools/vendor/github.com/ettle/strcase/split.go @@ -10,6 +10,7 @@ type SplitFn func(prev, curr, next rune) SplitAction // NewSplitFn covers the majority of common options that other strcase // libraries provide and should allow you to simply create a custom caser. // For more complicated use cases, feel free to write your own SplitFn +// //nolint:gocyclo func NewSplitFn( delimiters []rune, diff --git a/tools/vendor/github.com/fatih/color/color.go b/tools/vendor/github.com/fatih/color/color.go index 889f9e77b..81094e87c 100644 --- a/tools/vendor/github.com/fatih/color/color.go +++ b/tools/vendor/github.com/fatih/color/color.go @@ -65,6 +65,29 @@ const ( CrossedOut ) +const ( + ResetBold Attribute = iota + 22 + ResetItalic + ResetUnderline + ResetBlinking + _ + ResetReversed + ResetConcealed + ResetCrossedOut +) + +var mapResetAttributes map[Attribute]Attribute = map[Attribute]Attribute{ + Bold: ResetBold, + Faint: ResetBold, + Italic: ResetItalic, + Underline: ResetUnderline, + BlinkSlow: ResetBlinking, + BlinkRapid: ResetBlinking, + ReverseVideo: ResetReversed, + Concealed: ResetConcealed, + CrossedOut: ResetCrossedOut, +} + // Foreground text colors const ( FgBlack Attribute = iota + 30 @@ -246,10 +269,7 @@ func (c *Color) Printf(format string, a ...interface{}) (n int, err error) { // On Windows, users should wrap w with colorable.NewColorable() if w is of // type *os.File. func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - c.SetWriter(w) - defer c.UnsetWriter(w) - - return fmt.Fprintln(w, a...) + return fmt.Fprintln(w, c.wrap(sprintln(a...))) } // Println formats using the default formats for its operands and writes to @@ -258,10 +278,7 @@ func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { // encountered. This is the standard fmt.Print() method wrapped with the given // color. func (c *Color) Println(a ...interface{}) (n int, err error) { - c.Set() - defer c.unset() - - return fmt.Fprintln(Output, a...) + return fmt.Fprintln(Output, c.wrap(sprintln(a...))) } // Sprint is just like Print, but returns a string instead of printing it. @@ -271,7 +288,7 @@ func (c *Color) Sprint(a ...interface{}) string { // Sprintln is just like Println, but returns a string instead of printing it. func (c *Color) Sprintln(a ...interface{}) string { - return c.wrap(fmt.Sprintln(a...)) + return c.wrap(sprintln(a...)) + "\n" } // Sprintf is just like Printf, but returns a string instead of printing it. @@ -353,7 +370,7 @@ func (c *Color) SprintfFunc() func(format string, a ...interface{}) string { // string. Windows users should use this in conjunction with color.Output. func (c *Color) SprintlnFunc() func(a ...interface{}) string { return func(a ...interface{}) string { - return c.wrap(fmt.Sprintln(a...)) + return c.wrap(sprintln(a...)) + "\n" } } @@ -383,7 +400,18 @@ func (c *Color) format() string { } func (c *Color) unformat() string { - return fmt.Sprintf("%s[%dm", escape, Reset) + //return fmt.Sprintf("%s[%dm", escape, Reset) + //for each element in sequence let's use the speficic reset escape, ou the generic one if not found + format := make([]string, len(c.params)) + for i, v := range c.params { + format[i] = strconv.Itoa(int(Reset)) + ra, ok := mapResetAttributes[v] + if ok { + format[i] = strconv.Itoa(int(ra)) + } + } + + return fmt.Sprintf("%s[%sm", escape, strings.Join(format, ";")) } // DisableColor disables the color output. Useful to not change any existing @@ -411,6 +439,12 @@ func (c *Color) isNoColorSet() bool { // Equals returns a boolean value indicating whether two colors are equal. func (c *Color) Equals(c2 *Color) bool { + if c == nil && c2 == nil { + return true + } + if c == nil || c2 == nil { + return false + } if len(c.params) != len(c2.params) { return false } @@ -614,3 +648,8 @@ func HiCyanString(format string, a ...interface{}) string { return colorString(f func HiWhiteString(format string, a ...interface{}) string { return colorString(format, FgHiWhite, a...) } + +// sprintln is a helper function to format a string with fmt.Sprintln and trim the trailing newline. +func sprintln(a ...interface{}) string { + return strings.TrimSuffix(fmt.Sprintln(a...), "\n") +} diff --git a/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go b/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go index 6ad97ab49..ecd4915a8 100644 --- a/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go +++ b/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go @@ -53,6 +53,11 @@ func run(pass *analysis.Pass) (interface{}, error) { return } + // Function without body, ex: https://github.com/golang/go/blob/master/src/internal/syscall/unix/net.go + if funcBody == nil { + return + } + // no return values if funcResults == nil { return diff --git a/tools/vendor/github.com/ghostiam/protogetter/Makefile b/tools/vendor/github.com/ghostiam/protogetter/Makefile index af4b62bdf..4c2a62af1 100644 --- a/tools/vendor/github.com/ghostiam/protogetter/Makefile +++ b/tools/vendor/github.com/ghostiam/protogetter/Makefile @@ -1,6 +1,6 @@ .PHONY: test test: - cd testdata && make vendor + $(MAKE) -C testdata vendor go test -v ./... .PHONY: install diff --git a/tools/vendor/github.com/ghostiam/protogetter/processor.go b/tools/vendor/github.com/ghostiam/protogetter/processor.go index 445f136b8..eca82939d 100644 --- a/tools/vendor/github.com/ghostiam/protogetter/processor.go +++ b/tools/vendor/github.com/ghostiam/protogetter/processor.go @@ -12,16 +12,18 @@ import ( type processor struct { info *types.Info filter *PosFilter + cfg *Config to strings.Builder from strings.Builder err error } -func Process(info *types.Info, filter *PosFilter, n ast.Node) (*Result, error) { +func Process(info *types.Info, filter *PosFilter, n ast.Node, cfg *Config) (*Result, error) { p := &processor{ info: info, filter: filter, + cfg: cfg, } return p.process(n) @@ -31,8 +33,12 @@ func (c *processor) process(n ast.Node) (*Result, error) { switch x := n.(type) { case *ast.AssignStmt: // Skip any assignment to the field. - for _, lhs := range x.Lhs { - c.filter.AddPos(lhs.Pos()) + for _, s := range x.Lhs { + c.filter.AddPos(s.Pos()) + + if se, ok := s.(*ast.StarExpr); ok { + c.filter.AddPos(se.X.Pos()) + } } case *ast.IncDecStmt: @@ -47,6 +53,14 @@ func (c *processor) process(n ast.Node) (*Result, error) { } case *ast.CallExpr: + if !c.cfg.ReplaceFirstArgInAppend && len(x.Args) > 0 { + if v, ok := x.Fun.(*ast.Ident); ok && v.Name == "append" { + // Skip first argument of append function. + c.filter.AddPos(x.Args[0].Pos()) + break + } + } + f, ok := x.Fun.(*ast.SelectorExpr) if !ok { return &Result{}, nil @@ -66,6 +80,67 @@ func (c *processor) process(n ast.Node) (*Result, error) { c.processInner(x) + case *ast.StarExpr: + f, ok := x.X.(*ast.SelectorExpr) + if !ok { + return &Result{}, nil + } + + if !isProtoMessage(c.info, f.X) { + return &Result{}, nil + } + + // proto2 generates fields as pointers. Hence, the indirection + // must be removed when generating the fix for the case. + // The `*` is retained in `c.from`, but excluded from the fix + // present in the `c.to`. + c.writeFrom("*") + c.processInner(x.X) + + case *ast.BinaryExpr: + // Check if the expression is a comparison. + if x.Op != token.EQL && x.Op != token.NEQ { + return &Result{}, nil + } + + // Check if one of the operands is nil. + + xIdent, xOk := x.X.(*ast.Ident) + yIdent, yOk := x.Y.(*ast.Ident) + + xIsNil := xOk && xIdent.Name == "nil" + yIsNil := yOk && yIdent.Name == "nil" + + if !xIsNil && !yIsNil { + return &Result{}, nil + } + + // Extract the non-nil operand for further checks + + var expr ast.Expr + if xIsNil { + expr = x.Y + } else { + expr = x.X + } + + se, ok := expr.(*ast.SelectorExpr) + if !ok { + return &Result{}, nil + } + + if !isProtoMessage(c.info, se.X) { + return &Result{}, nil + } + + // Check if the Getter function of the protobuf message returns a pointer. + hasPointer, ok := getterResultHasPointer(c.info, se.X, se.Sel.Name) + if !ok || hasPointer { + return &Result{}, nil + } + + c.filter.AddPos(x.X.Pos()) + default: return nil, fmt.Errorf("not implemented for type: %s (%s)", reflect.TypeOf(x), formatNode(n)) } @@ -143,10 +218,8 @@ func (c *processor) processInner(expr ast.Expr) { c.write("*") c.processInner(x.X) - case *ast.CompositeLit: - c.write(formatNode(x)) - - case *ast.TypeAssertExpr: + case *ast.CompositeLit, *ast.TypeAssertExpr, *ast.ArrayType, *ast.FuncLit: + // Process the node as is. c.write(formatNode(x)) default: @@ -204,14 +277,14 @@ func isProtoMessage(info *types.Info, expr ast.Expr) bool { return false } -func methodIsExists(info *types.Info, x ast.Expr, name string) bool { +func typesNamed(info *types.Info, x ast.Expr) (*types.Named, bool) { if info == nil { - return false + return nil, false } t := info.TypeOf(x) if t == nil { - return false + return nil, false } ptr, ok := t.Underlying().(*types.Pointer) @@ -220,6 +293,15 @@ func methodIsExists(info *types.Info, x ast.Expr, name string) bool { } named, ok := t.(*types.Named) + if !ok { + return nil, false + } + + return named, true +} + +func methodIsExists(info *types.Info, x ast.Expr, name string) bool { + named, ok := typesNamed(info, x) if !ok { return false } @@ -232,3 +314,38 @@ func methodIsExists(info *types.Info, x ast.Expr, name string) bool { return false } + +func getterResultHasPointer(info *types.Info, x ast.Expr, name string) (hasPointer, ok bool) { + named, ok := typesNamed(info, x) + if !ok { + return false, false + } + + for i := 0; i < named.NumMethods(); i++ { + method := named.Method(i) + if method.Name() != "Get"+name { + continue + } + + var sig *types.Signature + sig, ok = method.Type().(*types.Signature) + if !ok { + return false, false + } + + results := sig.Results() + if results.Len() == 0 { + return false, false + } + + firstType := results.At(0) + _, ok = firstType.Type().(*types.Pointer) + if !ok { + return false, true + } + + return true, true + } + + return false, false +} diff --git a/tools/vendor/github.com/ghostiam/protogetter/protogetter.go b/tools/vendor/github.com/ghostiam/protogetter/protogetter.go index 80a829672..31eee8572 100644 --- a/tools/vendor/github.com/ghostiam/protogetter/protogetter.go +++ b/tools/vendor/github.com/ghostiam/protogetter/protogetter.go @@ -2,13 +2,16 @@ package protogetter import ( "bytes" + "flag" "fmt" "go/ast" "go/format" "go/token" "log" + "path/filepath" "strings" + "github.com/gobwas/glob" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/ast/inspector" ) @@ -22,34 +25,101 @@ const ( const msgFormat = "avoid direct access to proto field %s, use %s instead" -func NewAnalyzer() *analysis.Analyzer { +func NewAnalyzer(cfg *Config) *analysis.Analyzer { + if cfg == nil { + cfg = &Config{} + } + return &analysis.Analyzer{ - Name: "protogetter", - Doc: "Reports direct reads from proto message fields when getters should be used", + Name: "protogetter", + Doc: "Reports direct reads from proto message fields when getters should be used", + Flags: flags(cfg), Run: func(pass *analysis.Pass) (any, error) { - Run(pass, StandaloneMode) - return nil, nil + _, err := Run(pass, cfg) + return nil, err }, } } -func Run(pass *analysis.Pass, mode Mode) []Issue { +func flags(opts *Config) flag.FlagSet { + fs := flag.NewFlagSet("protogetter", flag.ContinueOnError) + + fs.Func("skip-generated-by", "skip files generated with the given prefixes", func(s string) error { + for _, prefix := range strings.Split(s, ",") { + opts.SkipGeneratedBy = append(opts.SkipGeneratedBy, prefix) + } + return nil + }) + fs.Func("skip-files", "skip files with the given glob patterns", func(s string) error { + for _, pattern := range strings.Split(s, ",") { + opts.SkipFiles = append(opts.SkipFiles, pattern) + } + return nil + }) + fs.BoolVar(&opts.SkipAnyGenerated, "skip-any-generated", false, "skip any generated files") + + return *fs +} + +type Config struct { + Mode Mode // Zero value is StandaloneMode. + SkipGeneratedBy []string + SkipFiles []string + SkipAnyGenerated bool + ReplaceFirstArgInAppend bool +} + +func Run(pass *analysis.Pass, cfg *Config) ([]Issue, error) { + skipGeneratedBy := make([]string, 0, len(cfg.SkipGeneratedBy)+3) + // Always skip files generated by protoc-gen-go, protoc-gen-go-grpc and protoc-gen-grpc-gateway. + skipGeneratedBy = append(skipGeneratedBy, "protoc-gen-go", "protoc-gen-go-grpc", "protoc-gen-grpc-gateway") + for _, s := range cfg.SkipGeneratedBy { + s = strings.TrimSpace(s) + if s == "" { + continue + } + skipGeneratedBy = append(skipGeneratedBy, s) + } + + skipFilesGlobPatterns := make([]glob.Glob, 0, len(cfg.SkipFiles)) + for _, s := range cfg.SkipFiles { + s = strings.TrimSpace(s) + if s == "" { + continue + } + + compile, err := glob.Compile(s) + if err != nil { + return nil, fmt.Errorf("invalid glob pattern: %w", err) + } + + skipFilesGlobPatterns = append(skipFilesGlobPatterns, compile) + } + nodeTypes := []ast.Node{ (*ast.AssignStmt)(nil), + (*ast.BinaryExpr)(nil), (*ast.CallExpr)(nil), (*ast.SelectorExpr)(nil), + (*ast.StarExpr)(nil), (*ast.IncDecStmt)(nil), (*ast.UnaryExpr)(nil), } - // Skip protoc-generated files. + // Skip filtered files. var files []*ast.File for _, f := range pass.Files { - if !isProtocGeneratedFile(f) { - files = append(files, f) + if skipGeneratedFile(f, skipGeneratedBy, cfg.SkipAnyGenerated) { + continue + } - // ast.Print(pass.Fset, f) + if skipFilesByGlob(pass.Fset.File(f.Pos()).Name(), skipFilesGlobPatterns) { + continue } + + files = append(files, f) + + // ast.Print(pass.Fset, f) } ins := inspector.New(files) @@ -58,12 +128,12 @@ func Run(pass *analysis.Pass, mode Mode) []Issue { filter := NewPosFilter() ins.Preorder(nodeTypes, func(node ast.Node) { - report := analyse(pass, filter, node) + report := analyse(pass, filter, node, cfg) if report == nil { return } - switch mode { + switch cfg.Mode { case StandaloneMode: pass.Report(report.ToDiagReport()) case GolangciLintMode: @@ -71,10 +141,10 @@ func Run(pass *analysis.Pass, mode Mode) []Issue { } }) - return issues + return issues, nil } -func analyse(pass *analysis.Pass, filter *PosFilter, n ast.Node) *Report { +func analyse(pass *analysis.Pass, filter *PosFilter, n ast.Node, cfg *Config) *Report { // fmt.Printf("\n>>> check: %s\n", formatNode(n)) // ast.Print(pass.Fset, n) if filter.IsFiltered(n.Pos()) { @@ -82,7 +152,7 @@ func analyse(pass *analysis.Pass, filter *PosFilter, n ast.Node) *Report { return nil } - result, err := Process(pass.TypesInfo, filter, n) + result, err := Process(pass.TypesInfo, filter, n, cfg) if err != nil { pass.Report(analysis.Diagnostic{ Pos: n.Pos(), @@ -168,8 +238,34 @@ func (r *Report) ToIssue(fset *token.FileSet) Issue { } } -func isProtocGeneratedFile(f *ast.File) bool { - return len(f.Comments) > 0 && strings.HasPrefix(f.Comments[0].Text(), "Code generated by protoc-gen-go") +func skipGeneratedFile(f *ast.File, prefixes []string, skipAny bool) bool { + if len(f.Comments) == 0 { + return false + } + firstComment := f.Comments[0].Text() + + // https://golang.org/s/generatedcode + if skipAny && strings.HasPrefix(firstComment, "Code generated") { + return true + } + + for _, prefix := range prefixes { + if strings.HasPrefix(firstComment, "Code generated by "+prefix) { + return true + } + } + + return false +} + +func skipFilesByGlob(filename string, patterns []glob.Glob) bool { + for _, pattern := range patterns { + if pattern.Match(filename) || pattern.Match(filepath.Base(filename)) { + return true + } + } + + return false } func formatNode(node ast.Node) string { diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go index 5a9564a0f..b834158ec 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go @@ -27,12 +27,16 @@ func init() { "//nolint", } parts := []string{ - "//go:generate ", // e.g.: go:generate value - "//line /", // e.g.: line /path/to/file:123 - "//nolint ", // e.g.: nolint - "//noinspection ", // e.g.: noinspection ALL, some GoLand and friends versions - "//export ", // e.g.: export Foo - "///", // e.g.: vertical breaker ///////////// + "//go:generate ", // e.g.: go:generate value + "//line /", // e.g.: line /path/to/file:123 + "//nolint ", // e.g.: nolint + "//noinspection ", // e.g.: noinspection ALL, some GoLand and friends versions + "//region", // e.g.: region awawa, used by GoLand and friends for custom folding + "//endregion", // e.g.: endregion awawa or endregion, closes GoLand regions + "// or , used by VSCode for custom folding + "//", // e.g.: , closes VSCode regions + "//export ", // e.g.: export Foo + "///", // e.g.: vertical breaker ///////////// "//+", "//#", "//-", diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go index 402ba3306..8595b7951 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go @@ -6,6 +6,7 @@ import ( "go/token" "regexp" "strings" + "unicode/utf8" "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/linter" @@ -18,6 +19,12 @@ func init() { info.Name = "commentedOutCode" info.Tags = []string{linter.DiagnosticTag, linter.ExperimentalTag} info.Summary = "Detects commented-out code inside function bodies" + info.Params = linter.CheckerParams{ + "minLength": { + Value: 15, + Usage: "min length of the comment that triggers a warning", + }, + } info.Before = ` // fmt.Println("Debugging hard") foo(1, 2)` @@ -27,6 +34,7 @@ foo(1, 2)` return astwalk.WalkerForLocalComment(&commentedOutCodeChecker{ ctx: ctx, notQuiteFuncCall: regexp.MustCompile(`\w+\s+\([^)]*\)\s*$`), + minLength: info.Params.Int("minLength"), }), nil }) } @@ -37,6 +45,7 @@ type commentedOutCodeChecker struct { fn *ast.FuncDecl notQuiteFuncCall *regexp.Regexp + minLength int } func (c *commentedOutCodeChecker) EnterFunc(fn *ast.FuncDecl) bool { @@ -69,7 +78,7 @@ func (c *commentedOutCodeChecker) VisitLocalComment(cg *ast.CommentGroup) { // Some very short comment that can be skipped. // Usually triggering on these results in false positive. // Unless there is a very popular call like print/println. - cond := len(s) < len("quite too short") && + cond := utf8.RuneCountInString(s) < c.minLength && !strings.Contains(s, "print") && !strings.Contains(s, "fmt.") && !strings.Contains(s, "log.") diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go index 19079871f..ed674eb85 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go @@ -15,7 +15,7 @@ func init() { info.Before = ` import ( "fmt" - priting "fmt" // Imported the second time + printing "fmt" // Imported the second time )` info.After = ` import( diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go index 98b76e261..701066860 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go @@ -64,7 +64,7 @@ func (c *flagNameChecker) checkFlagName(call *ast.CallExpr, arg ast.Expr) { case name == "": c.warnEmpty(call) case strings.HasPrefix(name, "-"): - c.warnHypenPrefix(call, name) + c.warnHyphenPrefix(call, name) case strings.Contains(name, "="): c.warnEq(call, name) case strings.Contains(name, " "): @@ -76,8 +76,8 @@ func (c *flagNameChecker) warnEmpty(cause ast.Node) { c.ctx.Warn(cause, "empty flag name") } -func (c *flagNameChecker) warnHypenPrefix(cause ast.Node, name string) { - c.ctx.Warn(cause, "flag name %q should not start with a hypen", name) +func (c *flagNameChecker) warnHyphenPrefix(cause ast.Node, name string) { + c.ctx.Warn(cause, "flag name %q should not start with a hyphen", name) } func (c *flagNameChecker) warnEq(cause ast.Node, name string) { diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go index 3b7f1d12b..7b7a3c538 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go @@ -5,6 +5,8 @@ import ( "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/linter" + + "github.com/go-toolsmith/astcast" ) func init() { @@ -39,12 +41,30 @@ type hugeParamChecker struct { func (c *hugeParamChecker) VisitFuncDecl(decl *ast.FuncDecl) { // TODO(quasilyte): maybe it's worthwhile to permit skipping // test files for this checker? + if c.isImplementStringer(decl) { + return + } + if decl.Recv != nil { c.checkParams(decl.Recv.List) } c.checkParams(decl.Type.Params.List) } +// isImplementStringer check method signature is: String() string. +func (*hugeParamChecker) isImplementStringer(decl *ast.FuncDecl) bool { + if decl.Recv != nil && + decl.Name.Name == "String" && + decl.Type != nil && + len(decl.Type.Params.List) == 0 && + len(decl.Type.Results.List) == 1 && + astcast.ToIdent(decl.Type.Results.List[0].Type).Name == "string" { + return true + } + + return false +} + func (c *hugeParamChecker) checkParams(params []*ast.Field) { for _, p := range params { for _, id := range p.Names { diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/internal/lintutil/astflow.go b/tools/vendor/github.com/go-critic/go-critic/checkers/internal/lintutil/astflow.go index 63d181e5e..f64907d69 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/internal/lintutil/astflow.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/internal/lintutil/astflow.go @@ -18,7 +18,7 @@ import ( // // If proven really useful, can be moved to go-toolsmith library. -// IsImmutable reports whether n can be midified through any operation. +// IsImmutable reports whether n can be modified through any operation. func IsImmutable(info *types.Info, n ast.Expr) bool { if astp.IsBasicLit(n) { return true diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go index ebc61c12a..2885dc725 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go @@ -117,7 +117,7 @@ func (c *mapKeyChecker) checkWhitespace(lit *ast.CompositeLit) { } func (c *mapKeyChecker) warnWhitespace(key ast.Node) { - c.ctx.Warn(key, "suspucious whitespace in %s key", key) + c.ctx.Warn(key, "suspicious whitespace in %s key", key) } func (c *mapKeyChecker) warnDupKey(key ast.Node) { diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/rulesdata/rulesdata.go b/tools/vendor/github.com/go-critic/go-critic/checkers/rulesdata/rulesdata.go index 503118c7e..4ab31076f 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/rulesdata/rulesdata.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/rulesdata/rulesdata.go @@ -363,7 +363,7 @@ var PrecompiledRules = &ir.File{ Line: 114, Name: "sloppyLen", MatcherName: "m", - DocTags: []string{"style"}, + DocTags: []string{"diagnostic"}, DocSummary: "Detects usage of `len` when result is obvious or doesn't make sense", DocBefore: "len(arr) <= 0", DocAfter: "len(arr) == 0", @@ -493,21 +493,45 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 164, - SyntaxPatterns: []ir.PatternString{{Line: 164, Value: "len($s) == 0"}}, + Line: 163, + SyntaxPatterns: []ir.PatternString{{Line: 163, Value: "len($s) > 0"}}, + ReportTemplate: "replace `$$` with `$s != \"\"`", + WhereExpr: ir.FilterExpr{ + Line: 164, + Op: ir.FilterVarTypeIsOp, + Src: "m[\"s\"].Type.Is(`string`)", + Value: "s", + Args: []ir.FilterExpr{{Line: 164, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + }, + }, + { + Line: 167, + SyntaxPatterns: []ir.PatternString{{Line: 167, Value: "len($s) == 0"}}, + ReportTemplate: "replace `$$` with `$s == \"\"`", + WhereExpr: ir.FilterExpr{ + Line: 168, + Op: ir.FilterVarTypeIsOp, + Src: "m[\"s\"].Type.Is(`string`)", + Value: "s", + Args: []ir.FilterExpr{{Line: 168, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + }, + }, + { + Line: 170, + SyntaxPatterns: []ir.PatternString{{Line: 170, Value: "len($s) <= 0"}}, ReportTemplate: "replace `$$` with `$s == \"\"`", WhereExpr: ir.FilterExpr{ - Line: 165, + Line: 171, Op: ir.FilterVarTypeIsOp, Src: "m[\"s\"].Type.Is(`string`)", Value: "s", - Args: []ir.FilterExpr{{Line: 165, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + Args: []ir.FilterExpr{{Line: 171, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, }, }, }, }, { - Line: 173, + Line: 179, Name: "stringXbytes", MatcherName: "m", DocTags: []string{"performance"}, @@ -516,180 +540,180 @@ var PrecompiledRules = &ir.File{ DocAfter: "copy(b, s)", Rules: []ir.Rule{ { - Line: 174, - SyntaxPatterns: []ir.PatternString{{Line: 174, Value: "copy($_, []byte($s))"}}, + Line: 180, + SyntaxPatterns: []ir.PatternString{{Line: 180, Value: "copy($_, []byte($s))"}}, ReportTemplate: "can simplify `[]byte($s)` to `$s`", }, { - Line: 176, - SyntaxPatterns: []ir.PatternString{{Line: 176, Value: "string($b) == \"\""}}, + Line: 182, + SyntaxPatterns: []ir.PatternString{{Line: 182, Value: "string($b) == \"\""}}, ReportTemplate: "suggestion: len($b) == 0", SuggestTemplate: "len($b) == 0", WhereExpr: ir.FilterExpr{ - Line: 176, + Line: 182, Op: ir.FilterVarTypeIsOp, Src: "m[\"b\"].Type.Is(`[]byte`)", Value: "b", - Args: []ir.FilterExpr{{Line: 176, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, + Args: []ir.FilterExpr{{Line: 182, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, }, }, { - Line: 177, - SyntaxPatterns: []ir.PatternString{{Line: 177, Value: "string($b) != \"\""}}, + Line: 183, + SyntaxPatterns: []ir.PatternString{{Line: 183, Value: "string($b) != \"\""}}, ReportTemplate: "suggestion: len($b) != 0", SuggestTemplate: "len($b) != 0", WhereExpr: ir.FilterExpr{ - Line: 177, + Line: 183, Op: ir.FilterVarTypeIsOp, Src: "m[\"b\"].Type.Is(`[]byte`)", Value: "b", - Args: []ir.FilterExpr{{Line: 177, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, + Args: []ir.FilterExpr{{Line: 183, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, }, }, { - Line: 179, - SyntaxPatterns: []ir.PatternString{{Line: 179, Value: "len(string($b))"}}, + Line: 185, + SyntaxPatterns: []ir.PatternString{{Line: 185, Value: "len(string($b))"}}, ReportTemplate: "suggestion: len($b)", SuggestTemplate: "len($b)", WhereExpr: ir.FilterExpr{ - Line: 179, + Line: 185, Op: ir.FilterVarTypeIsOp, Src: "m[\"b\"].Type.Is(`[]byte`)", Value: "b", - Args: []ir.FilterExpr{{Line: 179, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, + Args: []ir.FilterExpr{{Line: 185, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, }, }, { - Line: 181, - SyntaxPatterns: []ir.PatternString{{Line: 181, Value: "string($x) == string($y)"}}, + Line: 187, + SyntaxPatterns: []ir.PatternString{{Line: 187, Value: "string($x) == string($y)"}}, ReportTemplate: "suggestion: bytes.Equal($x, $y)", SuggestTemplate: "bytes.Equal($x, $y)", WhereExpr: ir.FilterExpr{ - Line: 182, + Line: 188, Op: ir.FilterAndOp, Src: "m[\"x\"].Type.Is(`[]byte`) && m[\"y\"].Type.Is(`[]byte`)", Args: []ir.FilterExpr{ { - Line: 182, + Line: 188, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]byte`)", Value: "x", - Args: []ir.FilterExpr{{Line: 182, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, + Args: []ir.FilterExpr{{Line: 188, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, }, { - Line: 182, + Line: 188, Op: ir.FilterVarTypeIsOp, Src: "m[\"y\"].Type.Is(`[]byte`)", Value: "y", - Args: []ir.FilterExpr{{Line: 182, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, + Args: []ir.FilterExpr{{Line: 188, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, }, }, }, }, { - Line: 185, - SyntaxPatterns: []ir.PatternString{{Line: 185, Value: "string($x) != string($y)"}}, + Line: 191, + SyntaxPatterns: []ir.PatternString{{Line: 191, Value: "string($x) != string($y)"}}, ReportTemplate: "suggestion: !bytes.Equal($x, $y)", SuggestTemplate: "!bytes.Equal($x, $y)", WhereExpr: ir.FilterExpr{ - Line: 186, + Line: 192, Op: ir.FilterAndOp, Src: "m[\"x\"].Type.Is(`[]byte`) && m[\"y\"].Type.Is(`[]byte`)", Args: []ir.FilterExpr{ { - Line: 186, + Line: 192, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]byte`)", Value: "x", - Args: []ir.FilterExpr{{Line: 186, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, + Args: []ir.FilterExpr{{Line: 192, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, }, { - Line: 186, + Line: 192, Op: ir.FilterVarTypeIsOp, Src: "m[\"y\"].Type.Is(`[]byte`)", Value: "y", - Args: []ir.FilterExpr{{Line: 186, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, + Args: []ir.FilterExpr{{Line: 192, Op: ir.FilterStringOp, Src: "`[]byte`", Value: "[]byte"}}, }, }, }, }, { - Line: 189, - SyntaxPatterns: []ir.PatternString{{Line: 189, Value: "$re.Match([]byte($s))"}}, + Line: 195, + SyntaxPatterns: []ir.PatternString{{Line: 195, Value: "$re.Match([]byte($s))"}}, ReportTemplate: "suggestion: $re.MatchString($s)", SuggestTemplate: "$re.MatchString($s)", WhereExpr: ir.FilterExpr{ - Line: 190, + Line: 196, Op: ir.FilterAndOp, Src: "m[\"re\"].Type.Is(`*regexp.Regexp`) && m[\"s\"].Type.Is(`string`)", Args: []ir.FilterExpr{ { - Line: 190, + Line: 196, Op: ir.FilterVarTypeIsOp, Src: "m[\"re\"].Type.Is(`*regexp.Regexp`)", Value: "re", - Args: []ir.FilterExpr{{Line: 190, Op: ir.FilterStringOp, Src: "`*regexp.Regexp`", Value: "*regexp.Regexp"}}, + Args: []ir.FilterExpr{{Line: 196, Op: ir.FilterStringOp, Src: "`*regexp.Regexp`", Value: "*regexp.Regexp"}}, }, { - Line: 190, + Line: 196, Op: ir.FilterVarTypeIsOp, Src: "m[\"s\"].Type.Is(`string`)", Value: "s", - Args: []ir.FilterExpr{{Line: 190, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + Args: []ir.FilterExpr{{Line: 196, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, }, }, }, }, { - Line: 193, - SyntaxPatterns: []ir.PatternString{{Line: 193, Value: "$re.FindIndex([]byte($s))"}}, + Line: 199, + SyntaxPatterns: []ir.PatternString{{Line: 199, Value: "$re.FindIndex([]byte($s))"}}, ReportTemplate: "suggestion: $re.FindStringIndex($s)", SuggestTemplate: "$re.FindStringIndex($s)", WhereExpr: ir.FilterExpr{ - Line: 194, + Line: 200, Op: ir.FilterAndOp, Src: "m[\"re\"].Type.Is(`*regexp.Regexp`) && m[\"s\"].Type.Is(`string`)", Args: []ir.FilterExpr{ { - Line: 194, + Line: 200, Op: ir.FilterVarTypeIsOp, Src: "m[\"re\"].Type.Is(`*regexp.Regexp`)", Value: "re", - Args: []ir.FilterExpr{{Line: 194, Op: ir.FilterStringOp, Src: "`*regexp.Regexp`", Value: "*regexp.Regexp"}}, + Args: []ir.FilterExpr{{Line: 200, Op: ir.FilterStringOp, Src: "`*regexp.Regexp`", Value: "*regexp.Regexp"}}, }, { - Line: 194, + Line: 200, Op: ir.FilterVarTypeIsOp, Src: "m[\"s\"].Type.Is(`string`)", Value: "s", - Args: []ir.FilterExpr{{Line: 194, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + Args: []ir.FilterExpr{{Line: 200, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, }, }, }, }, { - Line: 197, - SyntaxPatterns: []ir.PatternString{{Line: 197, Value: "$re.FindAllIndex([]byte($s), $n)"}}, + Line: 203, + SyntaxPatterns: []ir.PatternString{{Line: 203, Value: "$re.FindAllIndex([]byte($s), $n)"}}, ReportTemplate: "suggestion: $re.FindAllStringIndex($s, $n)", SuggestTemplate: "$re.FindAllStringIndex($s, $n)", WhereExpr: ir.FilterExpr{ - Line: 198, + Line: 204, Op: ir.FilterAndOp, Src: "m[\"re\"].Type.Is(`*regexp.Regexp`) && m[\"s\"].Type.Is(`string`)", Args: []ir.FilterExpr{ { - Line: 198, + Line: 204, Op: ir.FilterVarTypeIsOp, Src: "m[\"re\"].Type.Is(`*regexp.Regexp`)", Value: "re", - Args: []ir.FilterExpr{{Line: 198, Op: ir.FilterStringOp, Src: "`*regexp.Regexp`", Value: "*regexp.Regexp"}}, + Args: []ir.FilterExpr{{Line: 204, Op: ir.FilterStringOp, Src: "`*regexp.Regexp`", Value: "*regexp.Regexp"}}, }, { - Line: 198, + Line: 204, Op: ir.FilterVarTypeIsOp, Src: "m[\"s\"].Type.Is(`string`)", Value: "s", - Args: []ir.FilterExpr{{Line: 198, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + Args: []ir.FilterExpr{{Line: 204, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, }, }, }, @@ -697,7 +721,7 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 207, + Line: 213, Name: "indexAlloc", MatcherName: "m", DocTags: []string{"performance"}, @@ -706,22 +730,22 @@ var PrecompiledRules = &ir.File{ DocAfter: "bytes.Index(x, []byte(y))", DocNote: "See Go issue for details: https://github.com/golang/go/issues/25864", Rules: []ir.Rule{{ - Line: 208, - SyntaxPatterns: []ir.PatternString{{Line: 208, Value: "strings.Index(string($x), $y)"}}, + Line: 214, + SyntaxPatterns: []ir.PatternString{{Line: 214, Value: "strings.Index(string($x), $y)"}}, ReportTemplate: "consider replacing $$ with bytes.Index($x, []byte($y))", WhereExpr: ir.FilterExpr{ - Line: 209, + Line: 215, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"y\"].Pure", Args: []ir.FilterExpr{ - {Line: 209, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, - {Line: 209, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, + {Line: 215, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + {Line: 215, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, }, }, }}, }, { - Line: 217, + Line: 223, Name: "wrapperFunc", MatcherName: "m", DocTags: []string{"style"}, @@ -730,169 +754,169 @@ var PrecompiledRules = &ir.File{ DocAfter: "wg.Done()", Rules: []ir.Rule{ { - Line: 218, - SyntaxPatterns: []ir.PatternString{{Line: 218, Value: "$wg.Add(-1)"}}, + Line: 224, + SyntaxPatterns: []ir.PatternString{{Line: 224, Value: "$wg.Add(-1)"}}, ReportTemplate: "use WaitGroup.Done method in `$$`", WhereExpr: ir.FilterExpr{ - Line: 219, + Line: 225, Op: ir.FilterVarTypeIsOp, Src: "m[\"wg\"].Type.Is(`sync.WaitGroup`)", Value: "wg", - Args: []ir.FilterExpr{{Line: 219, Op: ir.FilterStringOp, Src: "`sync.WaitGroup`", Value: "sync.WaitGroup"}}, + Args: []ir.FilterExpr{{Line: 225, Op: ir.FilterStringOp, Src: "`sync.WaitGroup`", Value: "sync.WaitGroup"}}, }, }, { - Line: 222, - SyntaxPatterns: []ir.PatternString{{Line: 222, Value: "$buf.Truncate(0)"}}, + Line: 228, + SyntaxPatterns: []ir.PatternString{{Line: 228, Value: "$buf.Truncate(0)"}}, ReportTemplate: "use Buffer.Reset method in `$$`", WhereExpr: ir.FilterExpr{ - Line: 223, + Line: 229, Op: ir.FilterVarTypeIsOp, Src: "m[\"buf\"].Type.Is(`bytes.Buffer`)", Value: "buf", - Args: []ir.FilterExpr{{Line: 223, Op: ir.FilterStringOp, Src: "`bytes.Buffer`", Value: "bytes.Buffer"}}, + Args: []ir.FilterExpr{{Line: 229, Op: ir.FilterStringOp, Src: "`bytes.Buffer`", Value: "bytes.Buffer"}}, }, }, { - Line: 226, - SyntaxPatterns: []ir.PatternString{{Line: 226, Value: "http.HandlerFunc(http.NotFound)"}}, + Line: 232, + SyntaxPatterns: []ir.PatternString{{Line: 232, Value: "http.HandlerFunc(http.NotFound)"}}, ReportTemplate: "use http.NotFoundHandler method in `$$`", }, { - Line: 228, - SyntaxPatterns: []ir.PatternString{{Line: 228, Value: "strings.SplitN($_, $_, -1)"}}, + Line: 234, + SyntaxPatterns: []ir.PatternString{{Line: 234, Value: "strings.SplitN($_, $_, -1)"}}, ReportTemplate: "use strings.Split method in `$$`", }, { - Line: 229, - SyntaxPatterns: []ir.PatternString{{Line: 229, Value: "strings.Replace($_, $_, $_, -1)"}}, + Line: 235, + SyntaxPatterns: []ir.PatternString{{Line: 235, Value: "strings.Replace($_, $_, $_, -1)"}}, ReportTemplate: "use strings.ReplaceAll method in `$$`", }, { - Line: 230, - SyntaxPatterns: []ir.PatternString{{Line: 230, Value: "strings.Map(unicode.ToTitle, $_)"}}, + Line: 236, + SyntaxPatterns: []ir.PatternString{{Line: 236, Value: "strings.Map(unicode.ToTitle, $_)"}}, ReportTemplate: "use strings.ToTitle method in `$$`", }, { - Line: 231, + Line: 237, SyntaxPatterns: []ir.PatternString{ - {Line: 231, Value: "strings.Index($s1, $s2) >= 0"}, - {Line: 231, Value: "strings.Index($s1, $s2) != -1"}, + {Line: 237, Value: "strings.Index($s1, $s2) >= 0"}, + {Line: 237, Value: "strings.Index($s1, $s2) != -1"}, }, ReportTemplate: "suggestion: strings.Contains($s1, $s2)", SuggestTemplate: "strings.Contains($s1, $s2)", }, { - Line: 232, + Line: 238, SyntaxPatterns: []ir.PatternString{ - {Line: 232, Value: "strings.IndexAny($s1, $s2) >= 0"}, - {Line: 232, Value: "strings.IndexAny($s1, $s2) != -1"}, + {Line: 238, Value: "strings.IndexAny($s1, $s2) >= 0"}, + {Line: 238, Value: "strings.IndexAny($s1, $s2) != -1"}, }, ReportTemplate: "suggestion: strings.ContainsAny($s1, $s2)", SuggestTemplate: "strings.ContainsAny($s1, $s2)", }, { - Line: 233, + Line: 239, SyntaxPatterns: []ir.PatternString{ - {Line: 233, Value: "strings.IndexRune($s1, $s2) >= 0"}, - {Line: 233, Value: "strings.IndexRune($s1, $s2) != -1"}, + {Line: 239, Value: "strings.IndexRune($s1, $s2) >= 0"}, + {Line: 239, Value: "strings.IndexRune($s1, $s2) != -1"}, }, ReportTemplate: "suggestion: strings.ContainsRune($s1, $s2)", SuggestTemplate: "strings.ContainsRune($s1, $s2)", }, { - Line: 235, + Line: 241, SyntaxPatterns: []ir.PatternString{ - {Line: 235, Value: "$i := strings.Index($s, $sep); $*_; $x, $y = $s[:$i], $s[$i+1:]"}, - {Line: 236, Value: "$i := strings.Index($s, $sep); $*_; $x = $s[:$i]; $*_; $y = $s[$i+1:]"}, + {Line: 241, Value: "$i := strings.Index($s, $sep); $*_; $x, $y = $s[:$i], $s[$i+1:]"}, + {Line: 242, Value: "$i := strings.Index($s, $sep); $*_; $x = $s[:$i]; $*_; $y = $s[$i+1:]"}, }, ReportTemplate: "suggestion: $x, $y, _ = strings.Cut($s, $sep)", SuggestTemplate: "$x, $y, _ = strings.Cut($s, $sep)", WhereExpr: ir.FilterExpr{ - Line: 237, + Line: 243, Op: ir.FilterGoVersionGreaterEqThanOp, Src: "m.GoVersion().GreaterEqThan(\"1.18\")", Value: "1.18", }, }, { - Line: 240, + Line: 246, SyntaxPatterns: []ir.PatternString{ - {Line: 241, Value: "if $i := strings.Index($s, $sep); $i != -1 { $*_; $x, $y = $s[:$i], $s[$i+1:]; $*_ }"}, - {Line: 242, Value: "if $i := strings.Index($s, $sep); $i != -1 { $*_; $x = $s[:$i]; $*_; $y = $s[$i+1:]; $*_ }"}, - {Line: 243, Value: "if $i := strings.Index($s, $sep); $i >= 0 { $*_; $x, $y = $s[:$i], $s[$i+1:]; $*_ }"}, - {Line: 244, Value: "if $i := strings.Index($s, $sep); $i >= 0 { $*_; $x = $s[:$i]; $*_; $y = $s[$i+1:]; $*_ }"}, + {Line: 247, Value: "if $i := strings.Index($s, $sep); $i != -1 { $*_; $x, $y = $s[:$i], $s[$i+1:]; $*_ }"}, + {Line: 248, Value: "if $i := strings.Index($s, $sep); $i != -1 { $*_; $x = $s[:$i]; $*_; $y = $s[$i+1:]; $*_ }"}, + {Line: 249, Value: "if $i := strings.Index($s, $sep); $i >= 0 { $*_; $x, $y = $s[:$i], $s[$i+1:]; $*_ }"}, + {Line: 250, Value: "if $i := strings.Index($s, $sep); $i >= 0 { $*_; $x = $s[:$i]; $*_; $y = $s[$i+1:]; $*_ }"}, }, ReportTemplate: "suggestion: if $x, $y, ok = strings.Cut($s, $sep); ok { ... }", SuggestTemplate: "if $x, $y, ok = strings.Cut($s, $sep); ok { ... }", WhereExpr: ir.FilterExpr{ - Line: 245, + Line: 251, Op: ir.FilterGoVersionGreaterEqThanOp, Src: "m.GoVersion().GreaterEqThan(\"1.18\")", Value: "1.18", }, }, { - Line: 248, - SyntaxPatterns: []ir.PatternString{{Line: 248, Value: "bytes.SplitN(b, []byte(\".\"), -1)"}}, + Line: 254, + SyntaxPatterns: []ir.PatternString{{Line: 254, Value: "bytes.SplitN(b, []byte(\".\"), -1)"}}, ReportTemplate: "use bytes.Split method in `$$`", }, { - Line: 249, - SyntaxPatterns: []ir.PatternString{{Line: 249, Value: "bytes.Replace($_, $_, $_, -1)"}}, + Line: 255, + SyntaxPatterns: []ir.PatternString{{Line: 255, Value: "bytes.Replace($_, $_, $_, -1)"}}, ReportTemplate: "use bytes.ReplaceAll method in `$$`", }, { - Line: 250, - SyntaxPatterns: []ir.PatternString{{Line: 250, Value: "bytes.Map(unicode.ToUpper, $_)"}}, + Line: 256, + SyntaxPatterns: []ir.PatternString{{Line: 256, Value: "bytes.Map(unicode.ToUpper, $_)"}}, ReportTemplate: "use bytes.ToUpper method in `$$`", }, { - Line: 251, - SyntaxPatterns: []ir.PatternString{{Line: 251, Value: "bytes.Map(unicode.ToLower, $_)"}}, + Line: 257, + SyntaxPatterns: []ir.PatternString{{Line: 257, Value: "bytes.Map(unicode.ToLower, $_)"}}, ReportTemplate: "use bytes.ToLower method in `$$`", }, { - Line: 252, - SyntaxPatterns: []ir.PatternString{{Line: 252, Value: "bytes.Map(unicode.ToTitle, $_)"}}, + Line: 258, + SyntaxPatterns: []ir.PatternString{{Line: 258, Value: "bytes.Map(unicode.ToTitle, $_)"}}, ReportTemplate: "use bytes.ToTitle method in `$$`", }, { - Line: 253, + Line: 259, SyntaxPatterns: []ir.PatternString{ - {Line: 253, Value: "bytes.Index($b1, $b2) >= 0"}, - {Line: 253, Value: "bytes.Index($b1, $b2) != -1"}, + {Line: 259, Value: "bytes.Index($b1, $b2) >= 0"}, + {Line: 259, Value: "bytes.Index($b1, $b2) != -1"}, }, ReportTemplate: "suggestion: bytes.Contains($b1, $b2)", SuggestTemplate: "bytes.Contains($b1, $b2)", }, { - Line: 254, + Line: 260, SyntaxPatterns: []ir.PatternString{ - {Line: 254, Value: "bytes.IndexAny($b1, $b2) >= 0"}, - {Line: 254, Value: "bytes.IndexAny($b1, $b2) != -1"}, + {Line: 260, Value: "bytes.IndexAny($b1, $b2) >= 0"}, + {Line: 260, Value: "bytes.IndexAny($b1, $b2) != -1"}, }, ReportTemplate: "suggestion: bytes.ContainsAny($b1, $b2)", SuggestTemplate: "bytes.ContainsAny($b1, $b2)", }, { - Line: 255, + Line: 261, SyntaxPatterns: []ir.PatternString{ - {Line: 255, Value: "bytes.IndexRune($b1, $b2) >= 0"}, - {Line: 255, Value: "bytes.IndexRune($b1, $b2) != -1"}, + {Line: 261, Value: "bytes.IndexRune($b1, $b2) >= 0"}, + {Line: 261, Value: "bytes.IndexRune($b1, $b2) != -1"}, }, ReportTemplate: "suggestion: bytes.ContainsRune($b1, $b2)", SuggestTemplate: "bytes.ContainsRune($b1, $b2)", }, { - Line: 257, - SyntaxPatterns: []ir.PatternString{{Line: 257, Value: "draw.DrawMask($_, $_, $_, $_, nil, image.Point{}, $_)"}}, + Line: 263, + SyntaxPatterns: []ir.PatternString{{Line: 263, Value: "draw.DrawMask($_, $_, $_, $_, nil, image.Point{}, $_)"}}, ReportTemplate: "use draw.Draw method in `$$`", }, }, }, { - Line: 265, + Line: 271, Name: "regexpMust", MatcherName: "m", DocTags: []string{"style"}, @@ -901,22 +925,22 @@ var PrecompiledRules = &ir.File{ DocAfter: "re := regexp.MustCompile(\"const pattern\")", Rules: []ir.Rule{ { - Line: 266, - SyntaxPatterns: []ir.PatternString{{Line: 266, Value: "regexp.Compile($pat)"}}, + Line: 272, + SyntaxPatterns: []ir.PatternString{{Line: 272, Value: "regexp.Compile($pat)"}}, ReportTemplate: "for const patterns like $pat, use regexp.MustCompile", WhereExpr: ir.FilterExpr{ - Line: 267, + Line: 273, Op: ir.FilterVarConstOp, Src: "m[\"pat\"].Const", Value: "pat", }, }, { - Line: 270, - SyntaxPatterns: []ir.PatternString{{Line: 270, Value: "regexp.CompilePOSIX($pat)"}}, + Line: 276, + SyntaxPatterns: []ir.PatternString{{Line: 276, Value: "regexp.CompilePOSIX($pat)"}}, ReportTemplate: "for const patterns like $pat, use regexp.MustCompilePOSIX", WhereExpr: ir.FilterExpr{ - Line: 271, + Line: 277, Op: ir.FilterVarConstOp, Src: "m[\"pat\"].Const", Value: "pat", @@ -925,7 +949,7 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 279, + Line: 285, Name: "badCall", MatcherName: "m", DocTags: []string{"diagnostic"}, @@ -934,22 +958,22 @@ var PrecompiledRules = &ir.File{ DocAfter: "strings.Replace(s, from, to, -1)", Rules: []ir.Rule{ { - Line: 280, - SyntaxPatterns: []ir.PatternString{{Line: 280, Value: "strings.Replace($_, $_, $_, $zero)"}}, + Line: 286, + SyntaxPatterns: []ir.PatternString{{Line: 286, Value: "strings.Replace($_, $_, $_, $zero)"}}, ReportTemplate: "suspicious arg 0, probably meant -1", WhereExpr: ir.FilterExpr{ - Line: 281, + Line: 287, Op: ir.FilterEqOp, Src: "m[\"zero\"].Value.Int() == 0", Args: []ir.FilterExpr{ { - Line: 281, + Line: 287, Op: ir.FilterVarValueIntOp, Src: "m[\"zero\"].Value.Int()", Value: "zero", }, { - Line: 281, + Line: 287, Op: ir.FilterIntOp, Src: "0", Value: int64(0), @@ -959,22 +983,22 @@ var PrecompiledRules = &ir.File{ LocationVar: "zero", }, { - Line: 283, - SyntaxPatterns: []ir.PatternString{{Line: 283, Value: "bytes.Replace($_, $_, $_, $zero)"}}, + Line: 289, + SyntaxPatterns: []ir.PatternString{{Line: 289, Value: "bytes.Replace($_, $_, $_, $zero)"}}, ReportTemplate: "suspicious arg 0, probably meant -1", WhereExpr: ir.FilterExpr{ - Line: 284, + Line: 290, Op: ir.FilterEqOp, Src: "m[\"zero\"].Value.Int() == 0", Args: []ir.FilterExpr{ { - Line: 284, + Line: 290, Op: ir.FilterVarValueIntOp, Src: "m[\"zero\"].Value.Int()", Value: "zero", }, { - Line: 284, + Line: 290, Op: ir.FilterIntOp, Src: "0", Value: int64(0), @@ -984,22 +1008,22 @@ var PrecompiledRules = &ir.File{ LocationVar: "zero", }, { - Line: 287, - SyntaxPatterns: []ir.PatternString{{Line: 287, Value: "strings.SplitN($_, $_, $zero)"}}, + Line: 293, + SyntaxPatterns: []ir.PatternString{{Line: 293, Value: "strings.SplitN($_, $_, $zero)"}}, ReportTemplate: "suspicious arg 0, probably meant -1", WhereExpr: ir.FilterExpr{ - Line: 288, + Line: 294, Op: ir.FilterEqOp, Src: "m[\"zero\"].Value.Int() == 0", Args: []ir.FilterExpr{ { - Line: 288, + Line: 294, Op: ir.FilterVarValueIntOp, Src: "m[\"zero\"].Value.Int()", Value: "zero", }, { - Line: 288, + Line: 294, Op: ir.FilterIntOp, Src: "0", Value: int64(0), @@ -1009,22 +1033,22 @@ var PrecompiledRules = &ir.File{ LocationVar: "zero", }, { - Line: 290, - SyntaxPatterns: []ir.PatternString{{Line: 290, Value: "bytes.SplitN($_, $_, $zero)"}}, + Line: 296, + SyntaxPatterns: []ir.PatternString{{Line: 296, Value: "bytes.SplitN($_, $_, $zero)"}}, ReportTemplate: "suspicious arg 0, probably meant -1", WhereExpr: ir.FilterExpr{ - Line: 291, + Line: 297, Op: ir.FilterEqOp, Src: "m[\"zero\"].Value.Int() == 0", Args: []ir.FilterExpr{ { - Line: 291, + Line: 297, Op: ir.FilterVarValueIntOp, Src: "m[\"zero\"].Value.Int()", Value: "zero", }, { - Line: 291, + Line: 297, Op: ir.FilterIntOp, Src: "0", Value: int64(0), @@ -1034,19 +1058,19 @@ var PrecompiledRules = &ir.File{ LocationVar: "zero", }, { - Line: 294, - SyntaxPatterns: []ir.PatternString{{Line: 294, Value: "append($_)"}}, + Line: 300, + SyntaxPatterns: []ir.PatternString{{Line: 300, Value: "append($_)"}}, ReportTemplate: "no-op append call, probably missing arguments", }, { - Line: 296, - SyntaxPatterns: []ir.PatternString{{Line: 296, Value: "filepath.Join($_)"}}, + Line: 302, + SyntaxPatterns: []ir.PatternString{{Line: 302, Value: "filepath.Join($_)"}}, ReportTemplate: "suspicious Join on 1 argument", }, }, }, { - Line: 303, + Line: 309, Name: "assignOp", MatcherName: "m", DocTags: []string{"style"}, @@ -1055,87 +1079,87 @@ var PrecompiledRules = &ir.File{ DocAfter: "x *= 2", Rules: []ir.Rule{ { - Line: 304, - SyntaxPatterns: []ir.PatternString{{Line: 304, Value: "$x = $x + 1"}}, + Line: 310, + SyntaxPatterns: []ir.PatternString{{Line: 310, Value: "$x = $x + 1"}}, ReportTemplate: "replace `$$` with `$x++`", - WhereExpr: ir.FilterExpr{Line: 304, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 310, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 305, - SyntaxPatterns: []ir.PatternString{{Line: 305, Value: "$x = $x - 1"}}, + Line: 311, + SyntaxPatterns: []ir.PatternString{{Line: 311, Value: "$x = $x - 1"}}, ReportTemplate: "replace `$$` with `$x--`", - WhereExpr: ir.FilterExpr{Line: 305, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 311, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 307, - SyntaxPatterns: []ir.PatternString{{Line: 307, Value: "$x = $x + $y"}}, + Line: 313, + SyntaxPatterns: []ir.PatternString{{Line: 313, Value: "$x = $x + $y"}}, ReportTemplate: "replace `$$` with `$x += $y`", - WhereExpr: ir.FilterExpr{Line: 307, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 313, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 308, - SyntaxPatterns: []ir.PatternString{{Line: 308, Value: "$x = $x - $y"}}, + Line: 314, + SyntaxPatterns: []ir.PatternString{{Line: 314, Value: "$x = $x - $y"}}, ReportTemplate: "replace `$$` with `$x -= $y`", - WhereExpr: ir.FilterExpr{Line: 308, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 314, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 310, - SyntaxPatterns: []ir.PatternString{{Line: 310, Value: "$x = $x * $y"}}, + Line: 316, + SyntaxPatterns: []ir.PatternString{{Line: 316, Value: "$x = $x * $y"}}, ReportTemplate: "replace `$$` with `$x *= $y`", - WhereExpr: ir.FilterExpr{Line: 310, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 316, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 311, - SyntaxPatterns: []ir.PatternString{{Line: 311, Value: "$x = $x / $y"}}, + Line: 317, + SyntaxPatterns: []ir.PatternString{{Line: 317, Value: "$x = $x / $y"}}, ReportTemplate: "replace `$$` with `$x /= $y`", - WhereExpr: ir.FilterExpr{Line: 311, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 317, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 312, - SyntaxPatterns: []ir.PatternString{{Line: 312, Value: "$x = $x % $y"}}, + Line: 318, + SyntaxPatterns: []ir.PatternString{{Line: 318, Value: "$x = $x % $y"}}, ReportTemplate: "replace `$$` with `$x %= $y`", - WhereExpr: ir.FilterExpr{Line: 312, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 318, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 313, - SyntaxPatterns: []ir.PatternString{{Line: 313, Value: "$x = $x & $y"}}, + Line: 319, + SyntaxPatterns: []ir.PatternString{{Line: 319, Value: "$x = $x & $y"}}, ReportTemplate: "replace `$$` with `$x &= $y`", - WhereExpr: ir.FilterExpr{Line: 313, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 319, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 314, - SyntaxPatterns: []ir.PatternString{{Line: 314, Value: "$x = $x | $y"}}, + Line: 320, + SyntaxPatterns: []ir.PatternString{{Line: 320, Value: "$x = $x | $y"}}, ReportTemplate: "replace `$$` with `$x |= $y`", - WhereExpr: ir.FilterExpr{Line: 314, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 320, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 315, - SyntaxPatterns: []ir.PatternString{{Line: 315, Value: "$x = $x ^ $y"}}, + Line: 321, + SyntaxPatterns: []ir.PatternString{{Line: 321, Value: "$x = $x ^ $y"}}, ReportTemplate: "replace `$$` with `$x ^= $y`", - WhereExpr: ir.FilterExpr{Line: 315, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 321, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 316, - SyntaxPatterns: []ir.PatternString{{Line: 316, Value: "$x = $x << $y"}}, + Line: 322, + SyntaxPatterns: []ir.PatternString{{Line: 322, Value: "$x = $x << $y"}}, ReportTemplate: "replace `$$` with `$x <<= $y`", - WhereExpr: ir.FilterExpr{Line: 316, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 322, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 317, - SyntaxPatterns: []ir.PatternString{{Line: 317, Value: "$x = $x >> $y"}}, + Line: 323, + SyntaxPatterns: []ir.PatternString{{Line: 323, Value: "$x = $x >> $y"}}, ReportTemplate: "replace `$$` with `$x >>= $y`", - WhereExpr: ir.FilterExpr{Line: 317, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 323, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 318, - SyntaxPatterns: []ir.PatternString{{Line: 318, Value: "$x = $x &^ $y"}}, + Line: 324, + SyntaxPatterns: []ir.PatternString{{Line: 324, Value: "$x = $x &^ $y"}}, ReportTemplate: "replace `$$` with `$x &^= $y`", - WhereExpr: ir.FilterExpr{Line: 318, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 324, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, }, }, { - Line: 325, + Line: 331, Name: "preferWriteByte", MatcherName: "m", DocTags: []string{"performance", "experimental", "opinionated"}, @@ -1143,45 +1167,45 @@ var PrecompiledRules = &ir.File{ DocBefore: "w.WriteRune('\\n')", DocAfter: "w.WriteByte('\\n')", Rules: []ir.Rule{{ - Line: 329, - SyntaxPatterns: []ir.PatternString{{Line: 329, Value: "$w.WriteRune($c)"}}, + Line: 335, + SyntaxPatterns: []ir.PatternString{{Line: 335, Value: "$w.WriteRune($c)"}}, ReportTemplate: "consider writing single byte rune $c with $w.WriteByte($c)", WhereExpr: ir.FilterExpr{ - Line: 330, + Line: 336, Op: ir.FilterAndOp, Src: "m[\"w\"].Type.Implements(\"io.ByteWriter\") && (m[\"c\"].Const && m[\"c\"].Value.Int() < runeSelf)", Args: []ir.FilterExpr{ { - Line: 330, + Line: 336, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.ByteWriter\")", Value: "w", - Args: []ir.FilterExpr{{Line: 330, Op: ir.FilterStringOp, Src: "\"io.ByteWriter\"", Value: "io.ByteWriter"}}, + Args: []ir.FilterExpr{{Line: 336, Op: ir.FilterStringOp, Src: "\"io.ByteWriter\"", Value: "io.ByteWriter"}}, }, { - Line: 330, + Line: 336, Op: ir.FilterAndOp, Src: "(m[\"c\"].Const && m[\"c\"].Value.Int() < runeSelf)", Args: []ir.FilterExpr{ { - Line: 330, + Line: 336, Op: ir.FilterVarConstOp, Src: "m[\"c\"].Const", Value: "c", }, { - Line: 330, + Line: 336, Op: ir.FilterLtOp, Src: "m[\"c\"].Value.Int() < runeSelf", Args: []ir.FilterExpr{ { - Line: 330, + Line: 336, Op: ir.FilterVarValueIntOp, Src: "m[\"c\"].Value.Int()", Value: "c", }, { - Line: 330, + Line: 336, Op: ir.FilterIntOp, Src: "runeSelf", Value: int64(128), @@ -1195,7 +1219,7 @@ var PrecompiledRules = &ir.File{ }}, }, { - Line: 338, + Line: 344, Name: "preferFprint", MatcherName: "m", DocTags: []string{"performance", "experimental"}, @@ -1204,139 +1228,139 @@ var PrecompiledRules = &ir.File{ DocAfter: "fmt.Fprintf(w, \"%x\", 10)", Rules: []ir.Rule{ { - Line: 339, - SyntaxPatterns: []ir.PatternString{{Line: 339, Value: "$w.Write([]byte(fmt.Sprint($*args)))"}}, + Line: 345, + SyntaxPatterns: []ir.PatternString{{Line: 345, Value: "$w.Write([]byte(fmt.Sprint($*args)))"}}, ReportTemplate: "fmt.Fprint($w, $args) should be preferred to the $$", SuggestTemplate: "fmt.Fprint($w, $args)", WhereExpr: ir.FilterExpr{ - Line: 340, + Line: 346, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\")", Value: "w", - Args: []ir.FilterExpr{{Line: 340, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, + Args: []ir.FilterExpr{{Line: 346, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, }, }, { - Line: 344, - SyntaxPatterns: []ir.PatternString{{Line: 344, Value: "$w.Write([]byte(fmt.Sprintf($*args)))"}}, + Line: 350, + SyntaxPatterns: []ir.PatternString{{Line: 350, Value: "$w.Write([]byte(fmt.Sprintf($*args)))"}}, ReportTemplate: "fmt.Fprintf($w, $args) should be preferred to the $$", SuggestTemplate: "fmt.Fprintf($w, $args)", WhereExpr: ir.FilterExpr{ - Line: 345, + Line: 351, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\")", Value: "w", - Args: []ir.FilterExpr{{Line: 345, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, + Args: []ir.FilterExpr{{Line: 351, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, }, }, { - Line: 349, - SyntaxPatterns: []ir.PatternString{{Line: 349, Value: "$w.Write([]byte(fmt.Sprintln($*args)))"}}, + Line: 355, + SyntaxPatterns: []ir.PatternString{{Line: 355, Value: "$w.Write([]byte(fmt.Sprintln($*args)))"}}, ReportTemplate: "fmt.Fprintln($w, $args) should be preferred to the $$", SuggestTemplate: "fmt.Fprintln($w, $args)", WhereExpr: ir.FilterExpr{ - Line: 350, + Line: 356, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\")", Value: "w", - Args: []ir.FilterExpr{{Line: 350, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, + Args: []ir.FilterExpr{{Line: 356, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, }, }, { - Line: 354, - SyntaxPatterns: []ir.PatternString{{Line: 354, Value: "io.WriteString($w, fmt.Sprint($*args))"}}, + Line: 360, + SyntaxPatterns: []ir.PatternString{{Line: 360, Value: "io.WriteString($w, fmt.Sprint($*args))"}}, ReportTemplate: "suggestion: fmt.Fprint($w, $args)", SuggestTemplate: "fmt.Fprint($w, $args)", }, { - Line: 355, - SyntaxPatterns: []ir.PatternString{{Line: 355, Value: "io.WriteString($w, fmt.Sprintf($*args))"}}, + Line: 361, + SyntaxPatterns: []ir.PatternString{{Line: 361, Value: "io.WriteString($w, fmt.Sprintf($*args))"}}, ReportTemplate: "suggestion: fmt.Fprintf($w, $args)", SuggestTemplate: "fmt.Fprintf($w, $args)", }, { - Line: 356, - SyntaxPatterns: []ir.PatternString{{Line: 356, Value: "io.WriteString($w, fmt.Sprintln($*args))"}}, + Line: 362, + SyntaxPatterns: []ir.PatternString{{Line: 362, Value: "io.WriteString($w, fmt.Sprintln($*args))"}}, ReportTemplate: "suggestion: fmt.Fprintln($w, $args)", SuggestTemplate: "fmt.Fprintln($w, $args)", }, { - Line: 358, - SyntaxPatterns: []ir.PatternString{{Line: 358, Value: "$w.WriteString(fmt.Sprint($*args))"}}, + Line: 364, + SyntaxPatterns: []ir.PatternString{{Line: 364, Value: "$w.WriteString(fmt.Sprint($*args))"}}, ReportTemplate: "suggestion: fmt.Fprint($w, $args)", SuggestTemplate: "fmt.Fprint($w, $args)", WhereExpr: ir.FilterExpr{ - Line: 359, + Line: 365, Op: ir.FilterAndOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\") && m[\"w\"].Type.Implements(\"io.StringWriter\")", Args: []ir.FilterExpr{ { - Line: 359, + Line: 365, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\")", Value: "w", - Args: []ir.FilterExpr{{Line: 359, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, + Args: []ir.FilterExpr{{Line: 365, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, }, { - Line: 359, + Line: 365, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.StringWriter\")", Value: "w", - Args: []ir.FilterExpr{{Line: 359, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, + Args: []ir.FilterExpr{{Line: 365, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, }, }, }, }, { - Line: 361, - SyntaxPatterns: []ir.PatternString{{Line: 361, Value: "$w.WriteString(fmt.Sprintf($*args))"}}, + Line: 367, + SyntaxPatterns: []ir.PatternString{{Line: 367, Value: "$w.WriteString(fmt.Sprintf($*args))"}}, ReportTemplate: "suggestion: fmt.Fprintf($w, $args)", SuggestTemplate: "fmt.Fprintf($w, $args)", WhereExpr: ir.FilterExpr{ - Line: 362, + Line: 368, Op: ir.FilterAndOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\") && m[\"w\"].Type.Implements(\"io.StringWriter\")", Args: []ir.FilterExpr{ { - Line: 362, + Line: 368, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\")", Value: "w", - Args: []ir.FilterExpr{{Line: 362, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, + Args: []ir.FilterExpr{{Line: 368, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, }, { - Line: 362, + Line: 368, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.StringWriter\")", Value: "w", - Args: []ir.FilterExpr{{Line: 362, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, + Args: []ir.FilterExpr{{Line: 368, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, }, }, }, }, { - Line: 364, - SyntaxPatterns: []ir.PatternString{{Line: 364, Value: "$w.WriteString(fmt.Sprintln($*args))"}}, + Line: 370, + SyntaxPatterns: []ir.PatternString{{Line: 370, Value: "$w.WriteString(fmt.Sprintln($*args))"}}, ReportTemplate: "suggestion: fmt.Fprintln($w, $args)", SuggestTemplate: "fmt.Fprintln($w, $args)", WhereExpr: ir.FilterExpr{ - Line: 365, + Line: 371, Op: ir.FilterAndOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\") && m[\"w\"].Type.Implements(\"io.StringWriter\")", Args: []ir.FilterExpr{ { - Line: 365, + Line: 371, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.Writer\")", Value: "w", - Args: []ir.FilterExpr{{Line: 365, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, + Args: []ir.FilterExpr{{Line: 371, Op: ir.FilterStringOp, Src: "\"io.Writer\"", Value: "io.Writer"}}, }, { - Line: 365, + Line: 371, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.StringWriter\")", Value: "w", - Args: []ir.FilterExpr{{Line: 365, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, + Args: []ir.FilterExpr{{Line: 371, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, }, }, }, @@ -1344,7 +1368,7 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 373, + Line: 379, Name: "dupArg", MatcherName: "m", DocTags: []string{"diagnostic"}, @@ -1353,62 +1377,62 @@ var PrecompiledRules = &ir.File{ DocAfter: "copy(dst, src)", Rules: []ir.Rule{ { - Line: 374, + Line: 380, SyntaxPatterns: []ir.PatternString{ - {Line: 374, Value: "$x.Equal($x)"}, - {Line: 374, Value: "$x.Equals($x)"}, - {Line: 374, Value: "$x.Compare($x)"}, - {Line: 374, Value: "$x.Cmp($x)"}, + {Line: 380, Value: "$x.Equal($x)"}, + {Line: 380, Value: "$x.Equals($x)"}, + {Line: 380, Value: "$x.Compare($x)"}, + {Line: 380, Value: "$x.Cmp($x)"}, }, ReportTemplate: "suspicious method call with the same argument and receiver", - WhereExpr: ir.FilterExpr{Line: 375, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 381, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, { - Line: 378, + Line: 384, SyntaxPatterns: []ir.PatternString{ - {Line: 378, Value: "copy($x, $x)"}, - {Line: 379, Value: "math.Max($x, $x)"}, - {Line: 380, Value: "math.Min($x, $x)"}, - {Line: 381, Value: "reflect.Copy($x, $x)"}, - {Line: 382, Value: "reflect.DeepEqual($x, $x)"}, - {Line: 383, Value: "strings.Contains($x, $x)"}, - {Line: 384, Value: "strings.Compare($x, $x)"}, - {Line: 385, Value: "strings.EqualFold($x, $x)"}, - {Line: 386, Value: "strings.HasPrefix($x, $x)"}, - {Line: 387, Value: "strings.HasSuffix($x, $x)"}, - {Line: 388, Value: "strings.Index($x, $x)"}, - {Line: 389, Value: "strings.LastIndex($x, $x)"}, - {Line: 390, Value: "strings.Split($x, $x)"}, - {Line: 391, Value: "strings.SplitAfter($x, $x)"}, - {Line: 392, Value: "strings.SplitAfterN($x, $x, $_)"}, - {Line: 393, Value: "strings.SplitN($x, $x, $_)"}, - {Line: 394, Value: "strings.Replace($_, $x, $x, $_)"}, - {Line: 395, Value: "strings.ReplaceAll($_, $x, $x)"}, - {Line: 396, Value: "bytes.Contains($x, $x)"}, - {Line: 397, Value: "bytes.Compare($x, $x)"}, - {Line: 398, Value: "bytes.Equal($x, $x)"}, - {Line: 399, Value: "bytes.EqualFold($x, $x)"}, - {Line: 400, Value: "bytes.HasPrefix($x, $x)"}, - {Line: 401, Value: "bytes.HasSuffix($x, $x)"}, - {Line: 402, Value: "bytes.Index($x, $x)"}, - {Line: 403, Value: "bytes.LastIndex($x, $x)"}, - {Line: 404, Value: "bytes.Split($x, $x)"}, - {Line: 405, Value: "bytes.SplitAfter($x, $x)"}, - {Line: 406, Value: "bytes.SplitAfterN($x, $x, $_)"}, - {Line: 407, Value: "bytes.SplitN($x, $x, $_)"}, - {Line: 408, Value: "bytes.Replace($_, $x, $x, $_)"}, - {Line: 409, Value: "bytes.ReplaceAll($_, $x, $x)"}, - {Line: 410, Value: "types.Identical($x, $x)"}, - {Line: 411, Value: "types.IdenticalIgnoreTags($x, $x)"}, - {Line: 412, Value: "draw.Draw($x, $_, $x, $_, $_)"}, + {Line: 384, Value: "copy($x, $x)"}, + {Line: 385, Value: "math.Max($x, $x)"}, + {Line: 386, Value: "math.Min($x, $x)"}, + {Line: 387, Value: "reflect.Copy($x, $x)"}, + {Line: 388, Value: "reflect.DeepEqual($x, $x)"}, + {Line: 389, Value: "strings.Contains($x, $x)"}, + {Line: 390, Value: "strings.Compare($x, $x)"}, + {Line: 391, Value: "strings.EqualFold($x, $x)"}, + {Line: 392, Value: "strings.HasPrefix($x, $x)"}, + {Line: 393, Value: "strings.HasSuffix($x, $x)"}, + {Line: 394, Value: "strings.Index($x, $x)"}, + {Line: 395, Value: "strings.LastIndex($x, $x)"}, + {Line: 396, Value: "strings.Split($x, $x)"}, + {Line: 397, Value: "strings.SplitAfter($x, $x)"}, + {Line: 398, Value: "strings.SplitAfterN($x, $x, $_)"}, + {Line: 399, Value: "strings.SplitN($x, $x, $_)"}, + {Line: 400, Value: "strings.Replace($_, $x, $x, $_)"}, + {Line: 401, Value: "strings.ReplaceAll($_, $x, $x)"}, + {Line: 402, Value: "bytes.Contains($x, $x)"}, + {Line: 403, Value: "bytes.Compare($x, $x)"}, + {Line: 404, Value: "bytes.Equal($x, $x)"}, + {Line: 405, Value: "bytes.EqualFold($x, $x)"}, + {Line: 406, Value: "bytes.HasPrefix($x, $x)"}, + {Line: 407, Value: "bytes.HasSuffix($x, $x)"}, + {Line: 408, Value: "bytes.Index($x, $x)"}, + {Line: 409, Value: "bytes.LastIndex($x, $x)"}, + {Line: 410, Value: "bytes.Split($x, $x)"}, + {Line: 411, Value: "bytes.SplitAfter($x, $x)"}, + {Line: 412, Value: "bytes.SplitAfterN($x, $x, $_)"}, + {Line: 413, Value: "bytes.SplitN($x, $x, $_)"}, + {Line: 414, Value: "bytes.Replace($_, $x, $x, $_)"}, + {Line: 415, Value: "bytes.ReplaceAll($_, $x, $x)"}, + {Line: 416, Value: "types.Identical($x, $x)"}, + {Line: 417, Value: "types.IdenticalIgnoreTags($x, $x)"}, + {Line: 418, Value: "draw.Draw($x, $_, $x, $_, $_)"}, }, ReportTemplate: "suspicious duplicated args in $$", - WhereExpr: ir.FilterExpr{Line: 413, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + WhereExpr: ir.FilterExpr{Line: 419, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, }, }, }, { - Line: 421, + Line: 427, Name: "returnAfterHttpError", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -1416,14 +1440,14 @@ var PrecompiledRules = &ir.File{ DocBefore: "if err != nil { http.Error(...); }", DocAfter: "if err != nil { http.Error(...); return; }", Rules: []ir.Rule{{ - Line: 422, - SyntaxPatterns: []ir.PatternString{{Line: 422, Value: "if $_ { $*_; http.Error($w, $err, $code) }"}}, + Line: 428, + SyntaxPatterns: []ir.PatternString{{Line: 428, Value: "if $_ { $*_; http.Error($w, $err, $code) }"}}, ReportTemplate: "Possibly return is missed after the http.Error call", LocationVar: "w", }}, }, { - Line: 431, + Line: 437, Name: "preferFilepathJoin", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -1431,35 +1455,35 @@ var PrecompiledRules = &ir.File{ DocBefore: "x + string(os.PathSeparator) + y", DocAfter: "filepath.Join(x, y)", Rules: []ir.Rule{{ - Line: 432, - SyntaxPatterns: []ir.PatternString{{Line: 432, Value: "$x + string(os.PathSeparator) + $y"}}, + Line: 438, + SyntaxPatterns: []ir.PatternString{{Line: 438, Value: "$x + string(os.PathSeparator) + $y"}}, ReportTemplate: "filepath.Join($x, $y) should be preferred to the $$", SuggestTemplate: "filepath.Join($x, $y)", WhereExpr: ir.FilterExpr{ - Line: 433, + Line: 439, Op: ir.FilterAndOp, Src: "m[\"x\"].Type.Is(`string`) && m[\"y\"].Type.Is(`string`)", Args: []ir.FilterExpr{ { - Line: 433, + Line: 439, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`string`)", Value: "x", - Args: []ir.FilterExpr{{Line: 433, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + Args: []ir.FilterExpr{{Line: 439, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, }, { - Line: 433, + Line: 439, Op: ir.FilterVarTypeIsOp, Src: "m[\"y\"].Type.Is(`string`)", Value: "y", - Args: []ir.FilterExpr{{Line: 433, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + Args: []ir.FilterExpr{{Line: 439, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, }, }, }, }}, }, { - Line: 442, + Line: 448, Name: "preferStringWriter", MatcherName: "m", DocTags: []string{"performance", "experimental"}, @@ -1468,35 +1492,35 @@ var PrecompiledRules = &ir.File{ DocAfter: "w.WriteString(\"foo\")", Rules: []ir.Rule{ { - Line: 443, - SyntaxPatterns: []ir.PatternString{{Line: 443, Value: "$w.Write([]byte($s))"}}, + Line: 449, + SyntaxPatterns: []ir.PatternString{{Line: 449, Value: "$w.Write([]byte($s))"}}, ReportTemplate: "$w.WriteString($s) should be preferred to the $$", SuggestTemplate: "$w.WriteString($s)", WhereExpr: ir.FilterExpr{ - Line: 444, + Line: 450, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.StringWriter\")", Value: "w", - Args: []ir.FilterExpr{{Line: 444, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, + Args: []ir.FilterExpr{{Line: 450, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, }, }, { - Line: 448, - SyntaxPatterns: []ir.PatternString{{Line: 448, Value: "io.WriteString($w, $s)"}}, + Line: 454, + SyntaxPatterns: []ir.PatternString{{Line: 454, Value: "io.WriteString($w, $s)"}}, ReportTemplate: "$w.WriteString($s) should be preferred to the $$", SuggestTemplate: "$w.WriteString($s)", WhereExpr: ir.FilterExpr{ - Line: 449, + Line: 455, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"w\"].Type.Implements(\"io.StringWriter\")", Value: "w", - Args: []ir.FilterExpr{{Line: 449, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, + Args: []ir.FilterExpr{{Line: 455, Op: ir.FilterStringOp, Src: "\"io.StringWriter\"", Value: "io.StringWriter"}}, }, }, }, }, { - Line: 458, + Line: 464, Name: "sliceClear", MatcherName: "m", DocTags: []string{"performance", "experimental"}, @@ -1504,22 +1528,22 @@ var PrecompiledRules = &ir.File{ DocBefore: "for i := 0; i < len(buf); i++ { buf[i] = 0 }", DocAfter: "for i := range buf { buf[i] = 0 }", Rules: []ir.Rule{{ - Line: 459, - SyntaxPatterns: []ir.PatternString{{Line: 459, Value: "for $i := 0; $i < len($xs); $i++ { $xs[$i] = $zero }"}}, + Line: 465, + SyntaxPatterns: []ir.PatternString{{Line: 465, Value: "for $i := 0; $i < len($xs); $i++ { $xs[$i] = $zero }"}}, ReportTemplate: "rewrite as for-range so compiler can recognize this pattern", WhereExpr: ir.FilterExpr{ - Line: 460, + Line: 466, Op: ir.FilterEqOp, Src: "m[\"zero\"].Value.Int() == 0", Args: []ir.FilterExpr{ { - Line: 460, + Line: 466, Op: ir.FilterVarValueIntOp, Src: "m[\"zero\"].Value.Int()", Value: "zero", }, { - Line: 460, + Line: 466, Op: ir.FilterIntOp, Src: "0", Value: int64(0), @@ -1529,7 +1553,7 @@ var PrecompiledRules = &ir.File{ }}, }, { - Line: 468, + Line: 474, Name: "syncMapLoadAndDelete", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -1537,33 +1561,33 @@ var PrecompiledRules = &ir.File{ DocBefore: "v, ok := m.Load(k); if ok { m.Delete($k); f(v); }", DocAfter: "v, deleted := m.LoadAndDelete(k); if deleted { f(v) }", Rules: []ir.Rule{{ - Line: 469, - SyntaxPatterns: []ir.PatternString{{Line: 469, Value: "$_, $ok := $m.Load($k); if $ok { $m.Delete($k); $*_ }"}}, + Line: 475, + SyntaxPatterns: []ir.PatternString{{Line: 475, Value: "$_, $ok := $m.Load($k); if $ok { $m.Delete($k); $*_ }"}}, ReportTemplate: "use $m.LoadAndDelete to perform load+delete operations atomically", WhereExpr: ir.FilterExpr{ - Line: 470, + Line: 476, Op: ir.FilterAndOp, Src: "m.GoVersion().GreaterEqThan(\"1.15\") &&\n\tm[\"m\"].Type.Is(`*sync.Map`)", Args: []ir.FilterExpr{ { - Line: 470, + Line: 476, Op: ir.FilterGoVersionGreaterEqThanOp, Src: "m.GoVersion().GreaterEqThan(\"1.15\")", Value: "1.15", }, { - Line: 471, + Line: 477, Op: ir.FilterVarTypeIsOp, Src: "m[\"m\"].Type.Is(`*sync.Map`)", Value: "m", - Args: []ir.FilterExpr{{Line: 471, Op: ir.FilterStringOp, Src: "`*sync.Map`", Value: "*sync.Map"}}, + Args: []ir.FilterExpr{{Line: 477, Op: ir.FilterStringOp, Src: "`*sync.Map`", Value: "*sync.Map"}}, }, }, }, }}, }, { - Line: 479, + Line: 485, Name: "sprintfQuotedString", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -1571,34 +1595,34 @@ var PrecompiledRules = &ir.File{ DocBefore: "fmt.Sprintf(`\"%s\"`, s)", DocAfter: "fmt.Sprintf(`%q`, s)", Rules: []ir.Rule{{ - Line: 480, - SyntaxPatterns: []ir.PatternString{{Line: 480, Value: "fmt.Sprintf($s, $*_)"}}, + Line: 486, + SyntaxPatterns: []ir.PatternString{{Line: 486, Value: "fmt.Sprintf($s, $*_)"}}, ReportTemplate: "use %q instead of \"%s\" for quoted strings", WhereExpr: ir.FilterExpr{ - Line: 481, + Line: 487, Op: ir.FilterOrOp, Src: "m[\"s\"].Text.Matches(\"^`.*\\\"%s\\\".*`$\") ||\n\tm[\"s\"].Text.Matches(`^\".*\\\\\"%s\\\\\".*\"$`)", Args: []ir.FilterExpr{ { - Line: 481, + Line: 487, Op: ir.FilterVarTextMatchesOp, Src: "m[\"s\"].Text.Matches(\"^`.*\\\"%s\\\".*`$\")", Value: "s", - Args: []ir.FilterExpr{{Line: 481, Op: ir.FilterStringOp, Src: "\"^`.*\\\"%s\\\".*`$\"", Value: "^`.*\"%s\".*`$"}}, + Args: []ir.FilterExpr{{Line: 487, Op: ir.FilterStringOp, Src: "\"^`.*\\\"%s\\\".*`$\"", Value: "^`.*\"%s\".*`$"}}, }, { - Line: 482, + Line: 488, Op: ir.FilterVarTextMatchesOp, Src: "m[\"s\"].Text.Matches(`^\".*\\\\\"%s\\\\\".*\"$`)", Value: "s", - Args: []ir.FilterExpr{{Line: 482, Op: ir.FilterStringOp, Src: "`^\".*\\\\\"%s\\\\\".*\"$`", Value: "^\".*\\\\\"%s\\\\\".*\"$"}}, + Args: []ir.FilterExpr{{Line: 488, Op: ir.FilterStringOp, Src: "`^\".*\\\\\"%s\\\\\".*\"$`", Value: "^\".*\\\\\"%s\\\\\".*\"$"}}, }, }, }, }}, }, { - Line: 490, + Line: 496, Name: "offBy1", MatcherName: "m", DocTags: []string{"diagnostic"}, @@ -1607,80 +1631,80 @@ var PrecompiledRules = &ir.File{ DocAfter: "xs[len(xs)-1]", Rules: []ir.Rule{ { - Line: 491, - SyntaxPatterns: []ir.PatternString{{Line: 491, Value: "$x[len($x)]"}}, + Line: 497, + SyntaxPatterns: []ir.PatternString{{Line: 497, Value: "$x[len($x)]"}}, ReportTemplate: "index expr always panics; maybe you wanted $x[len($x)-1]?", SuggestTemplate: "$x[len($x)-1]", WhereExpr: ir.FilterExpr{ - Line: 492, + Line: 498, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"x\"].Type.Is(`[]$_`)", Args: []ir.FilterExpr{ - {Line: 492, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + {Line: 498, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, { - Line: 492, + Line: 498, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]$_`)", Value: "x", - Args: []ir.FilterExpr{{Line: 492, Op: ir.FilterStringOp, Src: "`[]$_`", Value: "[]$_"}}, + Args: []ir.FilterExpr{{Line: 498, Op: ir.FilterStringOp, Src: "`[]$_`", Value: "[]$_"}}, }, }, }, }, { - Line: 499, + Line: 505, SyntaxPatterns: []ir.PatternString{ - {Line: 500, Value: "$i := strings.Index($s, $_); $_ := $slicing[$i:]"}, - {Line: 501, Value: "$i := strings.Index($s, $_); $_ = $slicing[$i:]"}, - {Line: 502, Value: "$i := bytes.Index($s, $_); $_ := $slicing[$i:]"}, - {Line: 503, Value: "$i := bytes.Index($s, $_); $_ = $slicing[$i:]"}, + {Line: 506, Value: "$i := strings.Index($s, $_); $_ := $slicing[$i:]"}, + {Line: 507, Value: "$i := strings.Index($s, $_); $_ = $slicing[$i:]"}, + {Line: 508, Value: "$i := bytes.Index($s, $_); $_ := $slicing[$i:]"}, + {Line: 509, Value: "$i := bytes.Index($s, $_); $_ = $slicing[$i:]"}, }, ReportTemplate: "Index() can return -1; maybe you wanted to do $s[$i+1:]", WhereExpr: ir.FilterExpr{ - Line: 504, + Line: 510, Op: ir.FilterEqOp, Src: "m[\"s\"].Text == m[\"slicing\"].Text", Args: []ir.FilterExpr{ - {Line: 504, Op: ir.FilterVarTextOp, Src: "m[\"s\"].Text", Value: "s"}, - {Line: 504, Op: ir.FilterVarTextOp, Src: "m[\"slicing\"].Text", Value: "slicing"}, + {Line: 510, Op: ir.FilterVarTextOp, Src: "m[\"s\"].Text", Value: "s"}, + {Line: 510, Op: ir.FilterVarTextOp, Src: "m[\"slicing\"].Text", Value: "slicing"}, }, }, LocationVar: "slicing", }, { - Line: 508, + Line: 514, SyntaxPatterns: []ir.PatternString{ - {Line: 509, Value: "$i := strings.Index($s, $_); $_ := $slicing[:$i]"}, - {Line: 510, Value: "$i := strings.Index($s, $_); $_ = $slicing[:$i]"}, - {Line: 511, Value: "$i := bytes.Index($s, $_); $_ := $slicing[:$i]"}, - {Line: 512, Value: "$i := bytes.Index($s, $_); $_ = $slicing[:$i]"}, + {Line: 515, Value: "$i := strings.Index($s, $_); $_ := $slicing[:$i]"}, + {Line: 516, Value: "$i := strings.Index($s, $_); $_ = $slicing[:$i]"}, + {Line: 517, Value: "$i := bytes.Index($s, $_); $_ := $slicing[:$i]"}, + {Line: 518, Value: "$i := bytes.Index($s, $_); $_ = $slicing[:$i]"}, }, ReportTemplate: "Index() can return -1; maybe you wanted to do $s[:$i+1]", WhereExpr: ir.FilterExpr{ - Line: 513, + Line: 519, Op: ir.FilterEqOp, Src: "m[\"s\"].Text == m[\"slicing\"].Text", Args: []ir.FilterExpr{ - {Line: 513, Op: ir.FilterVarTextOp, Src: "m[\"s\"].Text", Value: "s"}, - {Line: 513, Op: ir.FilterVarTextOp, Src: "m[\"slicing\"].Text", Value: "slicing"}, + {Line: 519, Op: ir.FilterVarTextOp, Src: "m[\"s\"].Text", Value: "s"}, + {Line: 519, Op: ir.FilterVarTextOp, Src: "m[\"slicing\"].Text", Value: "slicing"}, }, }, LocationVar: "slicing", }, { - Line: 517, + Line: 523, SyntaxPatterns: []ir.PatternString{ - {Line: 518, Value: "$s[strings.Index($s, $_):]"}, - {Line: 519, Value: "$s[:strings.Index($s, $_)]"}, - {Line: 520, Value: "$s[bytes.Index($s, $_):]"}, - {Line: 521, Value: "$s[:bytes.Index($s, $_)]"}, + {Line: 524, Value: "$s[strings.Index($s, $_):]"}, + {Line: 525, Value: "$s[:strings.Index($s, $_)]"}, + {Line: 526, Value: "$s[bytes.Index($s, $_):]"}, + {Line: 527, Value: "$s[:bytes.Index($s, $_)]"}, }, ReportTemplate: "Index() can return -1; maybe you wanted to do Index()+1", }, }, }, { - Line: 529, + Line: 535, Name: "unslice", MatcherName: "m", DocTags: []string{"style"}, @@ -1688,35 +1712,35 @@ var PrecompiledRules = &ir.File{ DocBefore: "copy(b[:], values...)", DocAfter: "copy(b, values...)", Rules: []ir.Rule{{ - Line: 530, - SyntaxPatterns: []ir.PatternString{{Line: 530, Value: "$s[:]"}}, + Line: 536, + SyntaxPatterns: []ir.PatternString{{Line: 536, Value: "$s[:]"}}, ReportTemplate: "could simplify $$ to $s", SuggestTemplate: "$s", WhereExpr: ir.FilterExpr{ - Line: 531, + Line: 537, Op: ir.FilterOrOp, Src: "m[\"s\"].Type.Is(`string`) || m[\"s\"].Type.Is(`[]$_`)", Args: []ir.FilterExpr{ { - Line: 531, + Line: 537, Op: ir.FilterVarTypeIsOp, Src: "m[\"s\"].Type.Is(`string`)", Value: "s", - Args: []ir.FilterExpr{{Line: 531, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, + Args: []ir.FilterExpr{{Line: 537, Op: ir.FilterStringOp, Src: "`string`", Value: "string"}}, }, { - Line: 531, + Line: 537, Op: ir.FilterVarTypeIsOp, Src: "m[\"s\"].Type.Is(`[]$_`)", Value: "s", - Args: []ir.FilterExpr{{Line: 531, Op: ir.FilterStringOp, Src: "`[]$_`", Value: "[]$_"}}, + Args: []ir.FilterExpr{{Line: 537, Op: ir.FilterStringOp, Src: "`[]$_`", Value: "[]$_"}}, }, }, }, }}, }, { - Line: 540, + Line: 546, Name: "yodaStyleExpr", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -1725,105 +1749,105 @@ var PrecompiledRules = &ir.File{ DocAfter: "return ptr != nil", Rules: []ir.Rule{ { - Line: 541, - SyntaxPatterns: []ir.PatternString{{Line: 541, Value: "$constval != $x"}}, + Line: 547, + SyntaxPatterns: []ir.PatternString{{Line: 547, Value: "$constval != $x"}}, ReportTemplate: "consider to change order in expression to $x != $constval", WhereExpr: ir.FilterExpr{ - Line: 541, + Line: 547, Op: ir.FilterAndOp, Src: "m[\"constval\"].Node.Is(`BasicLit`) && !m[\"x\"].Node.Is(`BasicLit`)", Args: []ir.FilterExpr{ { - Line: 541, + Line: 547, Op: ir.FilterVarNodeIsOp, Src: "m[\"constval\"].Node.Is(`BasicLit`)", Value: "constval", - Args: []ir.FilterExpr{{Line: 541, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, + Args: []ir.FilterExpr{{Line: 547, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, }, { - Line: 541, + Line: 547, Op: ir.FilterNotOp, Src: "!m[\"x\"].Node.Is(`BasicLit`)", Args: []ir.FilterExpr{{ - Line: 541, + Line: 547, Op: ir.FilterVarNodeIsOp, Src: "m[\"x\"].Node.Is(`BasicLit`)", Value: "x", - Args: []ir.FilterExpr{{Line: 541, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, + Args: []ir.FilterExpr{{Line: 547, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, }}, }, }, }, }, { - Line: 543, - SyntaxPatterns: []ir.PatternString{{Line: 543, Value: "$constval == $x"}}, + Line: 549, + SyntaxPatterns: []ir.PatternString{{Line: 549, Value: "$constval == $x"}}, ReportTemplate: "consider to change order in expression to $x == $constval", WhereExpr: ir.FilterExpr{ - Line: 543, + Line: 549, Op: ir.FilterAndOp, Src: "m[\"constval\"].Node.Is(`BasicLit`) && !m[\"x\"].Node.Is(`BasicLit`)", Args: []ir.FilterExpr{ { - Line: 543, + Line: 549, Op: ir.FilterVarNodeIsOp, Src: "m[\"constval\"].Node.Is(`BasicLit`)", Value: "constval", - Args: []ir.FilterExpr{{Line: 543, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, + Args: []ir.FilterExpr{{Line: 549, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, }, { - Line: 543, + Line: 549, Op: ir.FilterNotOp, Src: "!m[\"x\"].Node.Is(`BasicLit`)", Args: []ir.FilterExpr{{ - Line: 543, + Line: 549, Op: ir.FilterVarNodeIsOp, Src: "m[\"x\"].Node.Is(`BasicLit`)", Value: "x", - Args: []ir.FilterExpr{{Line: 543, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, + Args: []ir.FilterExpr{{Line: 549, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, }}, }, }, }, }, { - Line: 546, - SyntaxPatterns: []ir.PatternString{{Line: 546, Value: "nil != $x"}}, + Line: 552, + SyntaxPatterns: []ir.PatternString{{Line: 552, Value: "nil != $x"}}, ReportTemplate: "consider to change order in expression to $x != nil", WhereExpr: ir.FilterExpr{ - Line: 546, + Line: 552, Op: ir.FilterNotOp, Src: "!m[\"x\"].Node.Is(`BasicLit`)", Args: []ir.FilterExpr{{ - Line: 546, + Line: 552, Op: ir.FilterVarNodeIsOp, Src: "m[\"x\"].Node.Is(`BasicLit`)", Value: "x", - Args: []ir.FilterExpr{{Line: 546, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, + Args: []ir.FilterExpr{{Line: 552, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, }}, }, }, { - Line: 548, - SyntaxPatterns: []ir.PatternString{{Line: 548, Value: "nil == $x"}}, + Line: 554, + SyntaxPatterns: []ir.PatternString{{Line: 554, Value: "nil == $x"}}, ReportTemplate: "consider to change order in expression to $x == nil", WhereExpr: ir.FilterExpr{ - Line: 548, + Line: 554, Op: ir.FilterNotOp, Src: "!m[\"x\"].Node.Is(`BasicLit`)", Args: []ir.FilterExpr{{ - Line: 548, + Line: 554, Op: ir.FilterVarNodeIsOp, Src: "m[\"x\"].Node.Is(`BasicLit`)", Value: "x", - Args: []ir.FilterExpr{{Line: 548, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, + Args: []ir.FilterExpr{{Line: 554, Op: ir.FilterStringOp, Src: "`BasicLit`", Value: "BasicLit"}}, }}, }, }, }, }, { - Line: 556, + Line: 562, Name: "equalFold", MatcherName: "m", DocTags: []string{"performance", "experimental"}, @@ -1832,114 +1856,114 @@ var PrecompiledRules = &ir.File{ DocAfter: "strings.EqualFold(x, y)", Rules: []ir.Rule{ { - Line: 565, + Line: 571, SyntaxPatterns: []ir.PatternString{ - {Line: 566, Value: "strings.ToLower($x) == $y"}, - {Line: 567, Value: "strings.ToLower($x) == strings.ToLower($y)"}, - {Line: 568, Value: "$x == strings.ToLower($y)"}, - {Line: 569, Value: "strings.ToUpper($x) == $y"}, - {Line: 570, Value: "strings.ToUpper($x) == strings.ToUpper($y)"}, - {Line: 571, Value: "$x == strings.ToUpper($y)"}, + {Line: 572, Value: "strings.ToLower($x) == $y"}, + {Line: 573, Value: "strings.ToLower($x) == strings.ToLower($y)"}, + {Line: 574, Value: "$x == strings.ToLower($y)"}, + {Line: 575, Value: "strings.ToUpper($x) == $y"}, + {Line: 576, Value: "strings.ToUpper($x) == strings.ToUpper($y)"}, + {Line: 577, Value: "$x == strings.ToUpper($y)"}, }, ReportTemplate: "consider replacing with strings.EqualFold($x, $y)", SuggestTemplate: "strings.EqualFold($x, $y)", WhereExpr: ir.FilterExpr{ - Line: 572, + Line: 578, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"y\"].Pure && m[\"x\"].Text != m[\"y\"].Text", Args: []ir.FilterExpr{ { - Line: 572, + Line: 578, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"y\"].Pure", Args: []ir.FilterExpr{ - {Line: 572, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, - {Line: 572, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, + {Line: 578, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + {Line: 578, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, }, }, { - Line: 572, + Line: 578, Op: ir.FilterNeqOp, Src: "m[\"x\"].Text != m[\"y\"].Text", Args: []ir.FilterExpr{ - {Line: 572, Op: ir.FilterVarTextOp, Src: "m[\"x\"].Text", Value: "x"}, - {Line: 572, Op: ir.FilterVarTextOp, Src: "m[\"y\"].Text", Value: "y"}, + {Line: 578, Op: ir.FilterVarTextOp, Src: "m[\"x\"].Text", Value: "x"}, + {Line: 578, Op: ir.FilterVarTextOp, Src: "m[\"y\"].Text", Value: "y"}, }, }, }, }, }, { - Line: 577, + Line: 583, SyntaxPatterns: []ir.PatternString{ - {Line: 578, Value: "strings.ToLower($x) != $y"}, - {Line: 579, Value: "strings.ToLower($x) != strings.ToLower($y)"}, - {Line: 580, Value: "$x != strings.ToLower($y)"}, - {Line: 581, Value: "strings.ToUpper($x) != $y"}, - {Line: 582, Value: "strings.ToUpper($x) != strings.ToUpper($y)"}, - {Line: 583, Value: "$x != strings.ToUpper($y)"}, + {Line: 584, Value: "strings.ToLower($x) != $y"}, + {Line: 585, Value: "strings.ToLower($x) != strings.ToLower($y)"}, + {Line: 586, Value: "$x != strings.ToLower($y)"}, + {Line: 587, Value: "strings.ToUpper($x) != $y"}, + {Line: 588, Value: "strings.ToUpper($x) != strings.ToUpper($y)"}, + {Line: 589, Value: "$x != strings.ToUpper($y)"}, }, ReportTemplate: "consider replacing with !strings.EqualFold($x, $y)", SuggestTemplate: "!strings.EqualFold($x, $y)", WhereExpr: ir.FilterExpr{ - Line: 584, + Line: 590, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"y\"].Pure && m[\"x\"].Text != m[\"y\"].Text", Args: []ir.FilterExpr{ { - Line: 584, + Line: 590, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"y\"].Pure", Args: []ir.FilterExpr{ - {Line: 584, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, - {Line: 584, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, + {Line: 590, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + {Line: 590, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, }, }, { - Line: 584, + Line: 590, Op: ir.FilterNeqOp, Src: "m[\"x\"].Text != m[\"y\"].Text", Args: []ir.FilterExpr{ - {Line: 584, Op: ir.FilterVarTextOp, Src: "m[\"x\"].Text", Value: "x"}, - {Line: 584, Op: ir.FilterVarTextOp, Src: "m[\"y\"].Text", Value: "y"}, + {Line: 590, Op: ir.FilterVarTextOp, Src: "m[\"x\"].Text", Value: "x"}, + {Line: 590, Op: ir.FilterVarTextOp, Src: "m[\"y\"].Text", Value: "y"}, }, }, }, }, }, { - Line: 589, + Line: 595, SyntaxPatterns: []ir.PatternString{ - {Line: 590, Value: "bytes.Equal(bytes.ToLower($x), $y)"}, - {Line: 591, Value: "bytes.Equal(bytes.ToLower($x), bytes.ToLower($y))"}, - {Line: 592, Value: "bytes.Equal($x, bytes.ToLower($y))"}, - {Line: 593, Value: "bytes.Equal(bytes.ToUpper($x), $y)"}, - {Line: 594, Value: "bytes.Equal(bytes.ToUpper($x), bytes.ToUpper($y))"}, - {Line: 595, Value: "bytes.Equal($x, bytes.ToUpper($y))"}, + {Line: 596, Value: "bytes.Equal(bytes.ToLower($x), $y)"}, + {Line: 597, Value: "bytes.Equal(bytes.ToLower($x), bytes.ToLower($y))"}, + {Line: 598, Value: "bytes.Equal($x, bytes.ToLower($y))"}, + {Line: 599, Value: "bytes.Equal(bytes.ToUpper($x), $y)"}, + {Line: 600, Value: "bytes.Equal(bytes.ToUpper($x), bytes.ToUpper($y))"}, + {Line: 601, Value: "bytes.Equal($x, bytes.ToUpper($y))"}, }, ReportTemplate: "consider replacing with bytes.EqualFold($x, $y)", SuggestTemplate: "bytes.EqualFold($x, $y)", WhereExpr: ir.FilterExpr{ - Line: 596, + Line: 602, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"y\"].Pure && m[\"x\"].Text != m[\"y\"].Text", Args: []ir.FilterExpr{ { - Line: 596, + Line: 602, Op: ir.FilterAndOp, Src: "m[\"x\"].Pure && m[\"y\"].Pure", Args: []ir.FilterExpr{ - {Line: 596, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, - {Line: 596, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, + {Line: 602, Op: ir.FilterVarPureOp, Src: "m[\"x\"].Pure", Value: "x"}, + {Line: 602, Op: ir.FilterVarPureOp, Src: "m[\"y\"].Pure", Value: "y"}, }, }, { - Line: 596, + Line: 602, Op: ir.FilterNeqOp, Src: "m[\"x\"].Text != m[\"y\"].Text", Args: []ir.FilterExpr{ - {Line: 596, Op: ir.FilterVarTextOp, Src: "m[\"x\"].Text", Value: "x"}, - {Line: 596, Op: ir.FilterVarTextOp, Src: "m[\"y\"].Text", Value: "y"}, + {Line: 602, Op: ir.FilterVarTextOp, Src: "m[\"x\"].Text", Value: "x"}, + {Line: 602, Op: ir.FilterVarTextOp, Src: "m[\"y\"].Text", Value: "y"}, }, }, }, @@ -1948,7 +1972,7 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 605, + Line: 611, Name: "argOrder", MatcherName: "m", DocTags: []string{"diagnostic"}, @@ -1956,45 +1980,45 @@ var PrecompiledRules = &ir.File{ DocBefore: "strings.HasPrefix(\"#\", userpass)", DocAfter: "strings.HasPrefix(userpass, \"#\")", Rules: []ir.Rule{{ - Line: 606, + Line: 612, SyntaxPatterns: []ir.PatternString{ - {Line: 607, Value: "strings.HasPrefix($lit, $s)"}, - {Line: 608, Value: "bytes.HasPrefix($lit, $s)"}, - {Line: 609, Value: "strings.HasSuffix($lit, $s)"}, - {Line: 610, Value: "bytes.HasSuffix($lit, $s)"}, - {Line: 611, Value: "strings.Contains($lit, $s)"}, - {Line: 612, Value: "bytes.Contains($lit, $s)"}, - {Line: 613, Value: "strings.TrimPrefix($lit, $s)"}, - {Line: 614, Value: "bytes.TrimPrefix($lit, $s)"}, - {Line: 615, Value: "strings.TrimSuffix($lit, $s)"}, - {Line: 616, Value: "bytes.TrimSuffix($lit, $s)"}, - {Line: 617, Value: "strings.Split($lit, $s)"}, - {Line: 618, Value: "bytes.Split($lit, $s)"}, + {Line: 613, Value: "strings.HasPrefix($lit, $s)"}, + {Line: 614, Value: "bytes.HasPrefix($lit, $s)"}, + {Line: 615, Value: "strings.HasSuffix($lit, $s)"}, + {Line: 616, Value: "bytes.HasSuffix($lit, $s)"}, + {Line: 617, Value: "strings.Contains($lit, $s)"}, + {Line: 618, Value: "bytes.Contains($lit, $s)"}, + {Line: 619, Value: "strings.TrimPrefix($lit, $s)"}, + {Line: 620, Value: "bytes.TrimPrefix($lit, $s)"}, + {Line: 621, Value: "strings.TrimSuffix($lit, $s)"}, + {Line: 622, Value: "bytes.TrimSuffix($lit, $s)"}, + {Line: 623, Value: "strings.Split($lit, $s)"}, + {Line: 624, Value: "bytes.Split($lit, $s)"}, }, ReportTemplate: "$lit and $s arguments order looks reversed", WhereExpr: ir.FilterExpr{ - Line: 619, + Line: 625, Op: ir.FilterAndOp, Src: "(m[\"lit\"].Const || m[\"lit\"].ConstSlice) &&\n\t!(m[\"s\"].Const || m[\"s\"].ConstSlice) &&\n\t!m[\"lit\"].Node.Is(`Ident`)", Args: []ir.FilterExpr{ { - Line: 619, + Line: 625, Op: ir.FilterAndOp, Src: "(m[\"lit\"].Const || m[\"lit\"].ConstSlice) &&\n\t!(m[\"s\"].Const || m[\"s\"].ConstSlice)", Args: []ir.FilterExpr{ { - Line: 619, + Line: 625, Op: ir.FilterOrOp, Src: "(m[\"lit\"].Const || m[\"lit\"].ConstSlice)", Args: []ir.FilterExpr{ { - Line: 619, + Line: 625, Op: ir.FilterVarConstOp, Src: "m[\"lit\"].Const", Value: "lit", }, { - Line: 619, + Line: 625, Op: ir.FilterVarConstSliceOp, Src: "m[\"lit\"].ConstSlice", Value: "lit", @@ -2002,22 +2026,22 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 620, + Line: 626, Op: ir.FilterNotOp, Src: "!(m[\"s\"].Const || m[\"s\"].ConstSlice)", Args: []ir.FilterExpr{{ - Line: 620, + Line: 626, Op: ir.FilterOrOp, Src: "(m[\"s\"].Const || m[\"s\"].ConstSlice)", Args: []ir.FilterExpr{ { - Line: 620, + Line: 626, Op: ir.FilterVarConstOp, Src: "m[\"s\"].Const", Value: "s", }, { - Line: 620, + Line: 626, Op: ir.FilterVarConstSliceOp, Src: "m[\"s\"].ConstSlice", Value: "s", @@ -2028,15 +2052,15 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 621, + Line: 627, Op: ir.FilterNotOp, Src: "!m[\"lit\"].Node.Is(`Ident`)", Args: []ir.FilterExpr{{ - Line: 621, + Line: 627, Op: ir.FilterVarNodeIsOp, Src: "m[\"lit\"].Node.Is(`Ident`)", Value: "lit", - Args: []ir.FilterExpr{{Line: 621, Op: ir.FilterStringOp, Src: "`Ident`", Value: "Ident"}}, + Args: []ir.FilterExpr{{Line: 627, Op: ir.FilterStringOp, Src: "`Ident`", Value: "Ident"}}, }}, }, }, @@ -2044,7 +2068,7 @@ var PrecompiledRules = &ir.File{ }}, }, { - Line: 629, + Line: 635, Name: "stringConcatSimplify", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -2053,27 +2077,27 @@ var PrecompiledRules = &ir.File{ DocAfter: "x + \"_\" + y", Rules: []ir.Rule{ { - Line: 630, - SyntaxPatterns: []ir.PatternString{{Line: 630, Value: "strings.Join([]string{$x, $y}, \"\")"}}, + Line: 636, + SyntaxPatterns: []ir.PatternString{{Line: 636, Value: "strings.Join([]string{$x, $y}, \"\")"}}, ReportTemplate: "suggestion: $x + $y", SuggestTemplate: "$x + $y", }, { - Line: 631, - SyntaxPatterns: []ir.PatternString{{Line: 631, Value: "strings.Join([]string{$x, $y, $z}, \"\")"}}, + Line: 637, + SyntaxPatterns: []ir.PatternString{{Line: 637, Value: "strings.Join([]string{$x, $y, $z}, \"\")"}}, ReportTemplate: "suggestion: $x + $y + $z", SuggestTemplate: "$x + $y + $z", }, { - Line: 632, - SyntaxPatterns: []ir.PatternString{{Line: 632, Value: "strings.Join([]string{$x, $y}, $glue)"}}, + Line: 638, + SyntaxPatterns: []ir.PatternString{{Line: 638, Value: "strings.Join([]string{$x, $y}, $glue)"}}, ReportTemplate: "suggestion: $x + $glue + $y", SuggestTemplate: "$x + $glue + $y", }, }, }, { - Line: 639, + Line: 645, Name: "timeExprSimplify", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -2082,39 +2106,39 @@ var PrecompiledRules = &ir.File{ DocAfter: "t.UnixMilli()", Rules: []ir.Rule{ { - Line: 644, - SyntaxPatterns: []ir.PatternString{{Line: 644, Value: "$t.Unix() / 1000"}}, + Line: 650, + SyntaxPatterns: []ir.PatternString{{Line: 650, Value: "$t.Unix() / 1000"}}, ReportTemplate: "use $t.UnixMilli() instead of $$", SuggestTemplate: "$t.UnixMilli()", WhereExpr: ir.FilterExpr{ - Line: 645, + Line: 651, Op: ir.FilterAndOp, Src: "m.GoVersion().GreaterEqThan(\"1.17\") && isTime(m[\"t\"])", Args: []ir.FilterExpr{ { - Line: 645, + Line: 651, Op: ir.FilterGoVersionGreaterEqThanOp, Src: "m.GoVersion().GreaterEqThan(\"1.17\")", Value: "1.17", }, { - Line: 645, + Line: 651, Op: ir.FilterOrOp, Src: "isTime(m[\"t\"])", Args: []ir.FilterExpr{ { - Line: 645, + Line: 651, Op: ir.FilterVarTypeIsOp, Src: "m[\"t\"].Type.Is(`time.Time`)", Value: "t", - Args: []ir.FilterExpr{{Line: 641, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, + Args: []ir.FilterExpr{{Line: 647, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, }, { - Line: 645, + Line: 651, Op: ir.FilterVarTypeIsOp, Src: "m[\"t\"].Type.Is(`*time.Time`)", Value: "t", - Args: []ir.FilterExpr{{Line: 641, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, + Args: []ir.FilterExpr{{Line: 647, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, }, }, }, @@ -2122,39 +2146,39 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 649, - SyntaxPatterns: []ir.PatternString{{Line: 649, Value: "$t.UnixNano() * 1000"}}, + Line: 655, + SyntaxPatterns: []ir.PatternString{{Line: 655, Value: "$t.UnixNano() * 1000"}}, ReportTemplate: "use $t.UnixMicro() instead of $$", SuggestTemplate: "$t.UnixMicro()", WhereExpr: ir.FilterExpr{ - Line: 650, + Line: 656, Op: ir.FilterAndOp, Src: "m.GoVersion().GreaterEqThan(\"1.17\") && isTime(m[\"t\"])", Args: []ir.FilterExpr{ { - Line: 650, + Line: 656, Op: ir.FilterGoVersionGreaterEqThanOp, Src: "m.GoVersion().GreaterEqThan(\"1.17\")", Value: "1.17", }, { - Line: 650, + Line: 656, Op: ir.FilterOrOp, Src: "isTime(m[\"t\"])", Args: []ir.FilterExpr{ { - Line: 650, + Line: 656, Op: ir.FilterVarTypeIsOp, Src: "m[\"t\"].Type.Is(`time.Time`)", Value: "t", - Args: []ir.FilterExpr{{Line: 641, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, + Args: []ir.FilterExpr{{Line: 647, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, }, { - Line: 650, + Line: 656, Op: ir.FilterVarTypeIsOp, Src: "m[\"t\"].Type.Is(`*time.Time`)", Value: "t", - Args: []ir.FilterExpr{{Line: 641, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, + Args: []ir.FilterExpr{{Line: 647, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, }, }, }, @@ -2164,72 +2188,7 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 659, - Name: "timeCmpSimplify", - MatcherName: "m", - DocTags: []string{"style", "experimental"}, - DocSummary: "Detects Before/After call of time.Time that can be simplified", - DocBefore: "!t.Before(tt)", - DocAfter: "t.After(tt)", - Rules: []ir.Rule{ - { - Line: 664, - SyntaxPatterns: []ir.PatternString{{Line: 664, Value: "!$t.Before($tt)"}}, - ReportTemplate: "suggestion: $t.After($tt)", - SuggestTemplate: "$t.After($tt)", - WhereExpr: ir.FilterExpr{ - Line: 665, - Op: ir.FilterOrOp, - Src: "isTime(m[\"t\"])", - Args: []ir.FilterExpr{ - { - Line: 665, - Op: ir.FilterVarTypeIsOp, - Src: "m[\"t\"].Type.Is(`time.Time`)", - Value: "t", - Args: []ir.FilterExpr{{Line: 661, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, - }, - { - Line: 665, - Op: ir.FilterVarTypeIsOp, - Src: "m[\"t\"].Type.Is(`*time.Time`)", - Value: "t", - Args: []ir.FilterExpr{{Line: 661, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, - }, - }, - }, - }, - { - Line: 668, - SyntaxPatterns: []ir.PatternString{{Line: 668, Value: "!$t.After($tt)"}}, - ReportTemplate: "suggestion: $t.Before($tt)", - SuggestTemplate: "$t.Before($tt)", - WhereExpr: ir.FilterExpr{ - Line: 669, - Op: ir.FilterOrOp, - Src: "isTime(m[\"t\"])", - Args: []ir.FilterExpr{ - { - Line: 669, - Op: ir.FilterVarTypeIsOp, - Src: "m[\"t\"].Type.Is(`time.Time`)", - Value: "t", - Args: []ir.FilterExpr{{Line: 661, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, - }, - { - Line: 669, - Op: ir.FilterVarTypeIsOp, - Src: "m[\"t\"].Type.Is(`*time.Time`)", - Value: "t", - Args: []ir.FilterExpr{{Line: 661, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, - }, - }, - }, - }, - }, - }, - { - Line: 677, + Line: 665, Name: "exposedSyncMutex", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -2238,57 +2197,57 @@ var PrecompiledRules = &ir.File{ DocAfter: "type Foo struct{ ...; mu sync.Mutex; ... }", Rules: []ir.Rule{ { - Line: 682, - SyntaxPatterns: []ir.PatternString{{Line: 682, Value: "type $x struct { $*_; sync.Mutex; $*_ }"}}, + Line: 670, + SyntaxPatterns: []ir.PatternString{{Line: 670, Value: "type $x struct { $*_; sync.Mutex; $*_ }"}}, ReportTemplate: "don't embed sync.Mutex", WhereExpr: ir.FilterExpr{ - Line: 683, + Line: 671, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 679, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 667, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, { - Line: 686, - SyntaxPatterns: []ir.PatternString{{Line: 686, Value: "type $x struct { $*_; *sync.Mutex; $*_ }"}}, + Line: 674, + SyntaxPatterns: []ir.PatternString{{Line: 674, Value: "type $x struct { $*_; *sync.Mutex; $*_ }"}}, ReportTemplate: "don't embed *sync.Mutex", WhereExpr: ir.FilterExpr{ - Line: 687, + Line: 675, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 679, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 667, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, { - Line: 690, - SyntaxPatterns: []ir.PatternString{{Line: 690, Value: "type $x struct { $*_; sync.RWMutex; $*_ }"}}, + Line: 678, + SyntaxPatterns: []ir.PatternString{{Line: 678, Value: "type $x struct { $*_; sync.RWMutex; $*_ }"}}, ReportTemplate: "don't embed sync.RWMutex", WhereExpr: ir.FilterExpr{ - Line: 691, + Line: 679, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 679, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 667, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, { - Line: 694, - SyntaxPatterns: []ir.PatternString{{Line: 694, Value: "type $x struct { $*_; *sync.RWMutex; $*_ }"}}, + Line: 682, + SyntaxPatterns: []ir.PatternString{{Line: 682, Value: "type $x struct { $*_; *sync.RWMutex; $*_ }"}}, ReportTemplate: "don't embed *sync.RWMutex", WhereExpr: ir.FilterExpr{ - Line: 695, + Line: 683, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 679, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 667, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, }, }, { - Line: 703, + Line: 691, Name: "badSorting", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2297,83 +2256,83 @@ var PrecompiledRules = &ir.File{ DocAfter: "sort.Strings(xs)", Rules: []ir.Rule{ { - Line: 704, - SyntaxPatterns: []ir.PatternString{{Line: 704, Value: "$x = sort.IntSlice($x)"}}, + Line: 692, + SyntaxPatterns: []ir.PatternString{{Line: 692, Value: "$x = sort.IntSlice($x)"}}, ReportTemplate: "suspicious sort.IntSlice usage, maybe sort.Ints was intended?", SuggestTemplate: "sort.Ints($x)", WhereExpr: ir.FilterExpr{ - Line: 705, + Line: 693, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]int`)", Value: "x", - Args: []ir.FilterExpr{{Line: 705, Op: ir.FilterStringOp, Src: "`[]int`", Value: "[]int"}}, + Args: []ir.FilterExpr{{Line: 693, Op: ir.FilterStringOp, Src: "`[]int`", Value: "[]int"}}, }, }, { - Line: 709, - SyntaxPatterns: []ir.PatternString{{Line: 709, Value: "$x = sort.Float64Slice($x)"}}, + Line: 697, + SyntaxPatterns: []ir.PatternString{{Line: 697, Value: "$x = sort.Float64Slice($x)"}}, ReportTemplate: "suspicious sort.Float64s usage, maybe sort.Float64s was intended?", SuggestTemplate: "sort.Float64s($x)", WhereExpr: ir.FilterExpr{ - Line: 710, + Line: 698, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]float64`)", Value: "x", - Args: []ir.FilterExpr{{Line: 710, Op: ir.FilterStringOp, Src: "`[]float64`", Value: "[]float64"}}, + Args: []ir.FilterExpr{{Line: 698, Op: ir.FilterStringOp, Src: "`[]float64`", Value: "[]float64"}}, }, }, { - Line: 714, - SyntaxPatterns: []ir.PatternString{{Line: 714, Value: "$x = sort.StringSlice($x)"}}, + Line: 702, + SyntaxPatterns: []ir.PatternString{{Line: 702, Value: "$x = sort.StringSlice($x)"}}, ReportTemplate: "suspicious sort.StringSlice usage, maybe sort.Strings was intended?", SuggestTemplate: "sort.Strings($x)", WhereExpr: ir.FilterExpr{ - Line: 715, + Line: 703, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]string`)", Value: "x", - Args: []ir.FilterExpr{{Line: 715, Op: ir.FilterStringOp, Src: "`[]string`", Value: "[]string"}}, + Args: []ir.FilterExpr{{Line: 703, Op: ir.FilterStringOp, Src: "`[]string`", Value: "[]string"}}, }, }, }, }, { - Line: 724, + Line: 712, Name: "externalErrorReassign", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, - DocSummary: "Detects suspicious reassigment of error from another package", + DocSummary: "Detects suspicious reassignment of error from another package", DocBefore: "io.EOF = nil", DocAfter: "/* don't do it */", Rules: []ir.Rule{{ - Line: 725, - SyntaxPatterns: []ir.PatternString{{Line: 725, Value: "$pkg.$err = $x"}}, - ReportTemplate: "suspicious reassigment of error from another package", + Line: 713, + SyntaxPatterns: []ir.PatternString{{Line: 713, Value: "$pkg.$err = $x"}}, + ReportTemplate: "suspicious reassignment of error from another package", WhereExpr: ir.FilterExpr{ - Line: 726, + Line: 714, Op: ir.FilterAndOp, Src: "m[\"err\"].Type.Is(`error`) && m[\"pkg\"].Object.Is(`PkgName`)", Args: []ir.FilterExpr{ { - Line: 726, + Line: 714, Op: ir.FilterVarTypeIsOp, Src: "m[\"err\"].Type.Is(`error`)", Value: "err", - Args: []ir.FilterExpr{{Line: 726, Op: ir.FilterStringOp, Src: "`error`", Value: "error"}}, + Args: []ir.FilterExpr{{Line: 714, Op: ir.FilterStringOp, Src: "`error`", Value: "error"}}, }, { - Line: 726, + Line: 714, Op: ir.FilterVarObjectIsOp, Src: "m[\"pkg\"].Object.Is(`PkgName`)", Value: "pkg", - Args: []ir.FilterExpr{{Line: 726, Op: ir.FilterStringOp, Src: "`PkgName`", Value: "PkgName"}}, + Args: []ir.FilterExpr{{Line: 714, Op: ir.FilterStringOp, Src: "`PkgName`", Value: "PkgName"}}, }, }, }, }}, }, { - Line: 734, + Line: 722, Name: "emptyDecl", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2382,24 +2341,24 @@ var PrecompiledRules = &ir.File{ DocAfter: "/* nothing */", Rules: []ir.Rule{ { - Line: 735, - SyntaxPatterns: []ir.PatternString{{Line: 735, Value: "var()"}}, + Line: 723, + SyntaxPatterns: []ir.PatternString{{Line: 723, Value: "var()"}}, ReportTemplate: "empty var() block", }, { - Line: 736, - SyntaxPatterns: []ir.PatternString{{Line: 736, Value: "const()"}}, + Line: 724, + SyntaxPatterns: []ir.PatternString{{Line: 724, Value: "const()"}}, ReportTemplate: "empty const() block", }, { - Line: 737, - SyntaxPatterns: []ir.PatternString{{Line: 737, Value: "type()"}}, + Line: 725, + SyntaxPatterns: []ir.PatternString{{Line: 725, Value: "type()"}}, ReportTemplate: "empty type() block", }, }, }, { - Line: 744, + Line: 732, Name: "dynamicFmtString", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2408,16 +2367,16 @@ var PrecompiledRules = &ir.File{ DocAfter: "fmt.Errorf(\"%s\", msg)", Rules: []ir.Rule{ { - Line: 745, - SyntaxPatterns: []ir.PatternString{{Line: 745, Value: "fmt.Errorf($f)"}}, + Line: 733, + SyntaxPatterns: []ir.PatternString{{Line: 733, Value: "fmt.Errorf($f)"}}, ReportTemplate: "use errors.New($f) or fmt.Errorf(\"%s\", $f) instead", SuggestTemplate: "errors.New($f)", WhereExpr: ir.FilterExpr{ - Line: 746, + Line: 734, Op: ir.FilterNotOp, Src: "!m[\"f\"].Const", Args: []ir.FilterExpr{{ - Line: 746, + Line: 734, Op: ir.FilterVarConstOp, Src: "m[\"f\"].Const", Value: "f", @@ -2425,15 +2384,15 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 750, - SyntaxPatterns: []ir.PatternString{{Line: 750, Value: "fmt.Errorf($f($*args))"}}, + Line: 738, + SyntaxPatterns: []ir.PatternString{{Line: 738, Value: "fmt.Errorf($f($*args))"}}, ReportTemplate: "use errors.New($f($*args)) or fmt.Errorf(\"%s\", $f($*args)) instead", SuggestTemplate: "errors.New($f($*args))", }, }, }, { - Line: 759, + Line: 747, Name: "stringsCompare", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -2442,25 +2401,25 @@ var PrecompiledRules = &ir.File{ DocAfter: "x < y", Rules: []ir.Rule{ { - Line: 760, - SyntaxPatterns: []ir.PatternString{{Line: 760, Value: "strings.Compare($s1, $s2) == 0"}}, + Line: 748, + SyntaxPatterns: []ir.PatternString{{Line: 748, Value: "strings.Compare($s1, $s2) == 0"}}, ReportTemplate: "suggestion: $s1 == $s2", SuggestTemplate: "$s1 == $s2", }, { - Line: 763, + Line: 751, SyntaxPatterns: []ir.PatternString{ - {Line: 763, Value: "strings.Compare($s1, $s2) == -1"}, - {Line: 764, Value: "strings.Compare($s1, $s2) < 0"}, + {Line: 751, Value: "strings.Compare($s1, $s2) == -1"}, + {Line: 752, Value: "strings.Compare($s1, $s2) < 0"}, }, ReportTemplate: "suggestion: $s1 < $s2", SuggestTemplate: "$s1 < $s2", }, { - Line: 767, + Line: 755, SyntaxPatterns: []ir.PatternString{ - {Line: 767, Value: "strings.Compare($s1, $s2) == 1"}, - {Line: 768, Value: "strings.Compare($s1, $s2) > 0"}, + {Line: 755, Value: "strings.Compare($s1, $s2) == 1"}, + {Line: 756, Value: "strings.Compare($s1, $s2) > 0"}, }, ReportTemplate: "suggestion: $s1 > $s2", SuggestTemplate: "$s1 > $s2", @@ -2468,7 +2427,7 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 776, + Line: 764, Name: "uncheckedInlineErr", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2476,47 +2435,47 @@ var PrecompiledRules = &ir.File{ DocBefore: "if err := expr(); err2 != nil { /*...*/ }", DocAfter: "if err := expr(); err != nil { /*...*/ }", Rules: []ir.Rule{{ - Line: 777, + Line: 765, SyntaxPatterns: []ir.PatternString{ - {Line: 778, Value: "if $err := $_($*_); $err2 != nil { $*_ }"}, - {Line: 779, Value: "if $err = $_($*_); $err2 != nil { $*_ }"}, - {Line: 780, Value: "if $*_, $err := $_($*_); $err2 != nil { $*_ }"}, - {Line: 781, Value: "if $*_, $err = $_($*_); $err2 != nil { $*_ }"}, + {Line: 766, Value: "if $err := $_($*_); $err2 != nil { $*_ }"}, + {Line: 767, Value: "if $err = $_($*_); $err2 != nil { $*_ }"}, + {Line: 768, Value: "if $*_, $err := $_($*_); $err2 != nil { $*_ }"}, + {Line: 769, Value: "if $*_, $err = $_($*_); $err2 != nil { $*_ }"}, }, ReportTemplate: "$err error is unchecked, maybe intended to check it instead of $err2", WhereExpr: ir.FilterExpr{ - Line: 782, + Line: 770, Op: ir.FilterAndOp, Src: "m[\"err\"].Type.Implements(\"error\") && m[\"err2\"].Type.Implements(\"error\") &&\n\tm[\"err\"].Text != m[\"err2\"].Text", Args: []ir.FilterExpr{ { - Line: 782, + Line: 770, Op: ir.FilterAndOp, Src: "m[\"err\"].Type.Implements(\"error\") && m[\"err2\"].Type.Implements(\"error\")", Args: []ir.FilterExpr{ { - Line: 782, + Line: 770, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"err\"].Type.Implements(\"error\")", Value: "err", - Args: []ir.FilterExpr{{Line: 782, Op: ir.FilterStringOp, Src: "\"error\"", Value: "error"}}, + Args: []ir.FilterExpr{{Line: 770, Op: ir.FilterStringOp, Src: "\"error\"", Value: "error"}}, }, { - Line: 782, + Line: 770, Op: ir.FilterVarTypeImplementsOp, Src: "m[\"err2\"].Type.Implements(\"error\")", Value: "err2", - Args: []ir.FilterExpr{{Line: 782, Op: ir.FilterStringOp, Src: "\"error\"", Value: "error"}}, + Args: []ir.FilterExpr{{Line: 770, Op: ir.FilterStringOp, Src: "\"error\"", Value: "error"}}, }, }, }, { - Line: 783, + Line: 771, Op: ir.FilterNeqOp, Src: "m[\"err\"].Text != m[\"err2\"].Text", Args: []ir.FilterExpr{ - {Line: 783, Op: ir.FilterVarTextOp, Src: "m[\"err\"].Text", Value: "err"}, - {Line: 783, Op: ir.FilterVarTextOp, Src: "m[\"err2\"].Text", Value: "err2"}, + {Line: 771, Op: ir.FilterVarTextOp, Src: "m[\"err\"].Text", Value: "err"}, + {Line: 771, Op: ir.FilterVarTextOp, Src: "m[\"err2\"].Text", Value: "err2"}, }, }, }, @@ -2525,108 +2484,34 @@ var PrecompiledRules = &ir.File{ }}, }, { - Line: 792, - Name: "sloppyTestFuncName", + Line: 780, + Name: "badSyncOnceFunc", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, - DocSummary: "Detects unsupported test and benchmark funcs", - DocBefore: "func TessstUnit(t *testing.T)", - DocAfter: "func TestUnit(t *testing.T)", + DocSummary: "Detects bad usage of sync.OnceFunc", + DocBefore: "sync.OnceFunc(foo)()", + DocAfter: "fooOnce := sync.OnceFunc(foo); ...; fooOnce()", Rules: []ir.Rule{ { - Line: 793, - SyntaxPatterns: []ir.PatternString{{Line: 793, Value: "func $test($_ *testing.T) { $*_ }"}}, - ReportTemplate: "function $test should be of form TestXXX(t *testing.T)", + Line: 781, + SyntaxPatterns: []ir.PatternString{{Line: 781, Value: "$*_; sync.OnceFunc($x); $*_;"}}, + ReportTemplate: "possible sync.OnceFunc misuse, sync.OnceFunc($x) result is not used", WhereExpr: ir.FilterExpr{ - Line: 794, - Op: ir.FilterAndOp, - Src: "!m[\"test\"].Text.Matches(\"Test.*\") &&\n\t!m[\"test\"].Text.Matches(\"test.*\")", - Args: []ir.FilterExpr{ - { - Line: 794, - Op: ir.FilterNotOp, - Src: "!m[\"test\"].Text.Matches(\"Test.*\")", - Args: []ir.FilterExpr{{ - Line: 794, - Op: ir.FilterVarTextMatchesOp, - Src: "m[\"test\"].Text.Matches(\"Test.*\")", - Value: "test", - Args: []ir.FilterExpr{{Line: 794, Op: ir.FilterStringOp, Src: "\"Test.*\"", Value: "Test.*"}}, - }}, - }, - { - Line: 795, - Op: ir.FilterNotOp, - Src: "!m[\"test\"].Text.Matches(\"test.*\")", - Args: []ir.FilterExpr{{ - Line: 795, - Op: ir.FilterVarTextMatchesOp, - Src: "m[\"test\"].Text.Matches(\"test.*\")", - Value: "test", - Args: []ir.FilterExpr{{Line: 795, Op: ir.FilterStringOp, Src: "\"test.*\"", Value: "test.*"}}, - }}, - }, - }, - }, - }, - { - Line: 798, - SyntaxPatterns: []ir.PatternString{{Line: 798, Value: "func $bench($_ *testing.B) { $*_ }"}}, - ReportTemplate: "function $bench should be of form BenchmarkXXX(b *testing.B)", - WhereExpr: ir.FilterExpr{ - Line: 799, - Op: ir.FilterAndOp, - Src: "!m[\"bench\"].Text.Matches(\"Benchmark.*\") &&\n\t!m[\"bench\"].Text.Matches(\"bench.*\")", - Args: []ir.FilterExpr{ - { - Line: 799, - Op: ir.FilterNotOp, - Src: "!m[\"bench\"].Text.Matches(\"Benchmark.*\")", - Args: []ir.FilterExpr{{ - Line: 799, - Op: ir.FilterVarTextMatchesOp, - Src: "m[\"bench\"].Text.Matches(\"Benchmark.*\")", - Value: "bench", - Args: []ir.FilterExpr{{Line: 799, Op: ir.FilterStringOp, Src: "\"Benchmark.*\"", Value: "Benchmark.*"}}, - }}, - }, - { - Line: 800, - Op: ir.FilterNotOp, - Src: "!m[\"bench\"].Text.Matches(\"bench.*\")", - Args: []ir.FilterExpr{{ - Line: 800, - Op: ir.FilterVarTextMatchesOp, - Src: "m[\"bench\"].Text.Matches(\"bench.*\")", - Value: "bench", - Args: []ir.FilterExpr{{Line: 800, Op: ir.FilterStringOp, Src: "\"bench.*\"", Value: "bench.*"}}, - }}, - }, - }, - }, - }, - { - Line: 803, - SyntaxPatterns: []ir.PatternString{{Line: 803, Value: "func $test($_ *testing.T) { $*_ }"}}, - ReportTemplate: "function $test looks like a test helper, consider to change 1st param to 'tb testing.TB'", - WhereExpr: ir.FilterExpr{ - Line: 804, - Op: ir.FilterVarTextMatchesOp, - Src: "m[\"test\"].Text.Matches(\"^test.*\")", - Value: "test", - Args: []ir.FilterExpr{{Line: 804, Op: ir.FilterStringOp, Src: "\"^test.*\"", Value: "^test.*"}}, + Line: 783, + Op: ir.FilterGoVersionGreaterEqThanOp, + Src: "m.GoVersion().GreaterEqThan(\"1.21\")", + Value: "1.21", }, }, { - Line: 807, - SyntaxPatterns: []ir.PatternString{{Line: 807, Value: "func $bench($_ *testing.B) { $*_ }"}}, - ReportTemplate: "function $bench looks like a benchmark helper, consider to change 1st param to 'tb testing.TB'", + Line: 785, + SyntaxPatterns: []ir.PatternString{{Line: 785, Value: "sync.OnceFunc($x)()"}}, + ReportTemplate: "possible sync.OnceFunc misuse, consider to assign sync.OnceFunc($x) to a variable", WhereExpr: ir.FilterExpr{ - Line: 808, - Op: ir.FilterVarTextMatchesOp, - Src: "m[\"bench\"].Text.Matches(\"^bench(mark)?.*\")", - Value: "bench", - Args: []ir.FilterExpr{{Line: 808, Op: ir.FilterStringOp, Src: "\"^bench(mark)?.*\"", Value: "^bench(mark)?.*"}}, + Line: 787, + Op: ir.FilterGoVersionGreaterEqThanOp, + Src: "m.GoVersion().GreaterEqThan(\"1.21\")", + Value: "1.21", }, }, }, diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go index d270268bd..e2e225ebf 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go @@ -14,7 +14,7 @@ func init() { var info linter.CheckerInfo info.Name = "typeUnparen" info.Tags = []string{linter.StyleTag, linter.OpinionatedTag} - info.Summary = "Detects unneded parenthesis inside type expressions and suggests to remove them" + info.Summary = "Detects unneeded parenthesis inside type expressions and suggests to remove them" info.Before = `type foo [](func([](func())))` info.After = `type foo []func([]func())` diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go index bcfe5a0c4..0401bf5d3 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go @@ -91,7 +91,7 @@ func (c *unlambdaChecker) VisitExpr(x ast.Expr) { } } - if len(result.Args) == n { + if c.lenArgs(result.Args) == n { c.warn(fn, callable) } } @@ -99,3 +99,20 @@ func (c *unlambdaChecker) VisitExpr(x ast.Expr) { func (c *unlambdaChecker) warn(cause ast.Node, suggestion string) { c.ctx.Warn(cause, "replace `%s` with `%s`", cause, suggestion) } + +func (c *unlambdaChecker) lenArgs(args []ast.Expr) int { + lenArgs := len(args) + + for _, arg := range args { + callExp, ok := arg.(*ast.CallExpr) + if !ok { + continue + } + + // Don't count function call. only args. + lenArgs-- + lenArgs += c.lenArgs(callExp.Args) + } + + return lenArgs +} diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/unnecessaryDefer_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/unnecessaryDefer_checker.go index 4358ab171..4c1ed41f6 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/unnecessaryDefer_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/unnecessaryDefer_checker.go @@ -37,7 +37,7 @@ type unnecessaryDeferChecker struct { // Visit implements the ast.Visitor. This visitor keeps track of the block // statement belongs to a function or any other block. If the block is not a // function and ends with a defer statement that should be OK since it's -// defering the outer function. +// deferring the outer function. func (c *unnecessaryDeferChecker) Visit(node ast.Node) ast.Visitor { switch n := node.(type) { case *ast.FuncDecl, *ast.FuncLit: diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/utils.go b/tools/vendor/github.com/go-critic/go-critic/checkers/utils.go index e9123352d..6e12cf9b3 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/utils.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/utils.go @@ -223,6 +223,8 @@ var goBuiltins = map[string]bool{ "imag": true, "len": true, "make": true, + "min": true, + "max": true, "new": true, "panic": true, "print": true, @@ -260,7 +262,7 @@ func isUnitTestFunc(ctx *linter.CheckerContext, fn *ast.FuncDecl) bool { return false } -// qualifiedName returns called expr fully-quallified name. +// qualifiedName returns called expr fully-qualified name. // // It works for simple identifiers like f => "f" and identifiers // from other package like pkg.f => "pkg.f". diff --git a/tools/vendor/github.com/go-toolsmith/astequal/astequal.go b/tools/vendor/github.com/go-toolsmith/astequal/astequal.go index 3d8db4af9..d1a04e942 100644 --- a/tools/vendor/github.com/go-toolsmith/astequal/astequal.go +++ b/tools/vendor/github.com/go-toolsmith/astequal/astequal.go @@ -4,8 +4,6 @@ package astequal import ( "go/ast" "go/token" - - "golang.org/x/exp/typeparams" ) // Node reports whether two AST nodes are structurally (deep) equal. @@ -109,8 +107,8 @@ func astExprEq(x, y ast.Expr) bool { y, ok := y.(*ast.IndexExpr) return ok && astIndexExprEq(x, y) - case *typeparams.IndexListExpr: - y, ok := y.(*typeparams.IndexListExpr) + case *ast.IndexListExpr: + y, ok := y.(*ast.IndexListExpr) return ok && astIndexListExprEq(x, y) case *ast.SliceExpr: @@ -323,7 +321,7 @@ func astFuncTypeEq(x, y *ast.FuncType) bool { } return astFieldListEq(x.Params, y.Params) && astFieldListEq(x.Results, y.Results) && - astFieldListEq(typeparams.ForFuncType(x), typeparams.ForFuncType(y)) + astFieldListEq(forFuncType(x), forFuncType(y)) } func astBasicLitEq(x, y *ast.BasicLit) bool { @@ -378,7 +376,7 @@ func astIndexExprEq(x, y *ast.IndexExpr) bool { return astExprEq(x.X, y.X) && astExprEq(x.Index, y.Index) } -func astIndexListExprEq(x, y *typeparams.IndexListExpr) bool { +func astIndexListExprEq(x, y *ast.IndexListExpr) bool { if x == nil || y == nil { return x == y } @@ -690,7 +688,7 @@ func astTypeSpecEq(x, y *ast.TypeSpec) bool { return x == y } return astIdentEq(x.Name, y.Name) && astExprEq(x.Type, y.Type) && - astFieldListEq(typeparams.ForTypeSpec(x), typeparams.ForTypeSpec(y)) + astFieldListEq(forTypeSpec(x), forTypeSpec(y)) } func astValueSpecEq(x, y *ast.ValueSpec) bool { @@ -755,3 +753,19 @@ func astExprSliceEq(xs, ys []ast.Expr) bool { } return true } + +// forTypeSpec returns n.TypeParams. +func forTypeSpec(n *ast.TypeSpec) *ast.FieldList { + if n == nil { + return nil + } + return n.TypeParams +} + +// forFuncType returns n.TypeParams. +func forFuncType(n *ast.FuncType) *ast.FieldList { + if n == nil { + return nil + } + return n.TypeParams +} diff --git a/tools/vendor/github.com/go-toolsmith/astequal/diff.go b/tools/vendor/github.com/go-toolsmith/astequal/diff.go new file mode 100644 index 000000000..cd69b4525 --- /dev/null +++ b/tools/vendor/github.com/go-toolsmith/astequal/diff.go @@ -0,0 +1,23 @@ +package astequal + +import ( + "bytes" + "go/ast" + "go/format" + "go/token" + + "github.com/google/go-cmp/cmp" +) + +func Diff(x, y ast.Node) string { + var buf bytes.Buffer + format.Node(&buf, token.NewFileSet(), x) + s1 := buf.String() + + buf.Reset() + format.Node(&buf, token.NewFileSet(), y) + s2 := buf.String() + + // TODO(cristaloleg): replace with a more lightweight diff impl. + return cmp.Diff(s1, s2) +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/.editorconfig b/tools/vendor/github.com/go-viper/mapstructure/v2/.editorconfig new file mode 100644 index 000000000..1f664d13a --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.go] +indent_style = tab + +[{Makefile,*.mk}] +indent_style = tab + +[*.nix] +indent_size = 2 diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/.envrc b/tools/vendor/github.com/go-viper/mapstructure/v2/.envrc new file mode 100644 index 000000000..2e0f9f5f7 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/.envrc @@ -0,0 +1,4 @@ +if ! has nix_direnv_version || ! nix_direnv_version 3.0.4; then + source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.0.4/direnvrc" "sha256-DzlYZ33mWF/Gs8DDeyjr8mnVmQGx7ASYqA5WlxwvBG4=" +fi +use flake . --impure diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/.gitignore b/tools/vendor/github.com/go-viper/mapstructure/v2/.gitignore new file mode 100644 index 000000000..470e7ca2b --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/.gitignore @@ -0,0 +1,6 @@ +/.devenv/ +/.direnv/ +/.pre-commit-config.yaml +/bin/ +/build/ +/var/ diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/.golangci.yaml b/tools/vendor/github.com/go-viper/mapstructure/v2/.golangci.yaml new file mode 100644 index 000000000..763143aa7 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/.golangci.yaml @@ -0,0 +1,23 @@ +run: + timeout: 5m + +linters-settings: + gci: + sections: + - standard + - default + - prefix(github.com/go-viper/mapstructure) + golint: + min-confidence: 0 + goimports: + local-prefixes: github.com/go-viper/maptstructure + +linters: + disable-all: true + enable: + - gci + - gofmt + - gofumpt + - goimports + - staticcheck + # - stylecheck diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/CHANGELOG.md b/tools/vendor/github.com/go-viper/mapstructure/v2/CHANGELOG.md new file mode 100644 index 000000000..afd44e5f5 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/CHANGELOG.md @@ -0,0 +1,104 @@ +> [!WARNING] +> As of v2 of this library, change log can be found in GitHub releases. + +## 1.5.1 + +* Wrap errors so they're compatible with `errors.Is` and `errors.As` [GH-282] +* Fix map of slices not decoding properly in certain cases. [GH-266] + +## 1.5.0 + +* New option `IgnoreUntaggedFields` to ignore decoding to any fields + without `mapstructure` (or the configured tag name) set [GH-277] +* New option `ErrorUnset` which makes it an error if any fields + in a target struct are not set by the decoding process. [GH-225] +* New function `OrComposeDecodeHookFunc` to help compose decode hooks. [GH-240] +* Decoding to slice from array no longer crashes [GH-265] +* Decode nested struct pointers to map [GH-271] +* Fix issue where `,squash` was ignored if `Squash` option was set. [GH-280] +* Fix issue where fields with `,omitempty` would sometimes decode + into a map with an empty string key [GH-281] + +## 1.4.3 + +* Fix cases where `json.Number` didn't decode properly [GH-261] + +## 1.4.2 + +* Custom name matchers to support any sort of casing, formatting, etc. for + field names. [GH-250] +* Fix possible panic in ComposeDecodeHookFunc [GH-251] + +## 1.4.1 + +* Fix regression where `*time.Time` value would be set to empty and not be sent + to decode hooks properly [GH-232] + +## 1.4.0 + +* A new decode hook type `DecodeHookFuncValue` has been added that has + access to the full values. [GH-183] +* Squash is now supported with embedded fields that are struct pointers [GH-205] +* Empty strings will convert to 0 for all numeric types when weakly decoding [GH-206] + +## 1.3.3 + +* Decoding maps from maps creates a settable value for decode hooks [GH-203] + +## 1.3.2 + +* Decode into interface type with a struct value is supported [GH-187] + +## 1.3.1 + +* Squash should only squash embedded structs. [GH-194] + +## 1.3.0 + +* Added `",omitempty"` support. This will ignore zero values in the source + structure when encoding. [GH-145] + +## 1.2.3 + +* Fix duplicate entries in Keys list with pointer values. [GH-185] + +## 1.2.2 + +* Do not add unsettable (unexported) values to the unused metadata key + or "remain" value. [GH-150] + +## 1.2.1 + +* Go modules checksum mismatch fix + +## 1.2.0 + +* Added support to capture unused values in a field using the `",remain"` value + in the mapstructure tag. There is an example to showcase usage. +* Added `DecoderConfig` option to always squash embedded structs +* `json.Number` can decode into `uint` types +* Empty slices are preserved and not replaced with nil slices +* Fix panic that can occur in when decoding a map into a nil slice of structs +* Improved package documentation for godoc + +## 1.1.2 + +* Fix error when decode hook decodes interface implementation into interface + type. [GH-140] + +## 1.1.1 + +* Fix panic that can happen in `decodePtr` + +## 1.1.0 + +* Added `StringToIPHookFunc` to convert `string` to `net.IP` and `net.IPNet` [GH-133] +* Support struct to struct decoding [GH-137] +* If source map value is nil, then destination map value is nil (instead of empty) +* If source slice value is nil, then destination slice value is nil (instead of empty) +* If source pointer is nil, then destination pointer is set to nil (instead of + allocated zero value of type) + +## 1.0.0 + +* Initial tagged stable release. diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/LICENSE b/tools/vendor/github.com/go-viper/mapstructure/v2/LICENSE new file mode 100644 index 000000000..f9c841a51 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Mitchell Hashimoto + +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/tools/vendor/github.com/go-viper/mapstructure/v2/README.md b/tools/vendor/github.com/go-viper/mapstructure/v2/README.md new file mode 100644 index 000000000..dd5ec69dd --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/README.md @@ -0,0 +1,80 @@ +# mapstructure + +[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/go-viper/mapstructure/ci.yaml?branch=main&style=flat-square)](https://github.com/go-viper/mapstructure/actions?query=workflow%3ACI) +[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/mod/github.com/go-viper/mapstructure/v2) +![Go Version](https://img.shields.io/badge/go%20version-%3E=1.18-61CFDD.svg?style=flat-square) + +mapstructure is a Go library for decoding generic map values to structures +and vice versa, while providing helpful error handling. + +This library is most useful when decoding values from some data stream (JSON, +Gob, etc.) where you don't _quite_ know the structure of the underlying data +until you read a part of it. You can therefore read a `map[string]interface{}` +and use this library to decode it into the proper underlying native Go +structure. + +## Installation + +```shell +go get github.com/go-viper/mapstructure/v2 +``` + +## Migrating from `github.com/mitchellh/mapstructure` + +[@mitchehllh](https://github.com/mitchellh) announced his intent to archive some of his unmaintained projects (see [here](https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc) and [here](https://github.com/mitchellh/mapstructure/issues/349)). This is a repository achieved the "blessed fork" status. + +You can migrate to this package by changing your import paths in your Go files to `github.com/go-viper/mapstructure/v2`. +The API is the same, so you don't need to change anything else. + +Here is a script that can help you with the migration: + +```shell +sed -i 's/github.com\/mitchellh\/mapstructure/github.com\/go-viper\/mapstructure\/v2/g' $(find . -type f -name '*.go') +``` + +If you need more time to migrate your code, that is absolutely fine. + +Some of the latest fixes are backported to the v1 release branch of this package, so you can use the Go modules `replace` feature until you are ready to migrate: + +```shell +replace github.com/mitchellh/mapstructure => github.com/go-viper/mapstructure v1.6.0 +``` + +## Usage & Example + +For usage and examples see the [documentation](https://pkg.go.dev/mod/github.com/go-viper/mapstructure/v2). + +The `Decode` function has examples associated with it there. + +## But Why?! + +Go offers fantastic standard libraries for decoding formats such as JSON. +The standard method is to have a struct pre-created, and populate that struct +from the bytes of the encoded format. This is great, but the problem is if +you have configuration or an encoding that changes slightly depending on +specific fields. For example, consider this JSON: + +```json +{ + "type": "person", + "name": "Mitchell" +} +``` + +Perhaps we can't populate a specific structure without first reading +the "type" field from the JSON. We could always do two passes over the +decoding of the JSON (reading the "type" first, and the rest later). +However, it is much simpler to just decode this into a `map[string]interface{}` +structure, read the "type" key, then use something like this library +to decode it into the proper structure. + +## Credits + +Mapstructure was originally created by [@mitchellh](https://github.com/mitchellh). +This is a maintained fork of the original library. + +Read more about the reasons for the fork [here](https://github.com/mitchellh/mapstructure/issues/349). + +## License + +The project is licensed under the [MIT License](LICENSE). diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go b/tools/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go new file mode 100644 index 000000000..24d82f07c --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/decode_hooks.go @@ -0,0 +1,577 @@ +package mapstructure + +import ( + "encoding" + "errors" + "fmt" + "net" + "net/netip" + "reflect" + "strconv" + "strings" + "time" +) + +// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns +// it into the proper DecodeHookFunc type, such as DecodeHookFuncType. +func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { + // Create variables here so we can reference them with the reflect pkg + var f1 DecodeHookFuncType + var f2 DecodeHookFuncKind + var f3 DecodeHookFuncValue + + // Fill in the variables into this interface and the rest is done + // automatically using the reflect package. + potential := []interface{}{f1, f2, f3} + + v := reflect.ValueOf(h) + vt := v.Type() + for _, raw := range potential { + pt := reflect.ValueOf(raw).Type() + if vt.ConvertibleTo(pt) { + return v.Convert(pt).Interface() + } + } + + return nil +} + +// DecodeHookExec executes the given decode hook. This should be used +// since it'll naturally degrade to the older backwards compatible DecodeHookFunc +// that took reflect.Kind instead of reflect.Type. +func DecodeHookExec( + raw DecodeHookFunc, + from reflect.Value, to reflect.Value, +) (interface{}, error) { + switch f := typedDecodeHook(raw).(type) { + case DecodeHookFuncType: + return f(from.Type(), to.Type(), from.Interface()) + case DecodeHookFuncKind: + return f(from.Kind(), to.Kind(), from.Interface()) + case DecodeHookFuncValue: + return f(from, to) + default: + return nil, errors.New("invalid decode hook signature") + } +} + +// ComposeDecodeHookFunc creates a single DecodeHookFunc that +// automatically composes multiple DecodeHookFuncs. +// +// The composed funcs are called in order, with the result of the +// previous transformation. +func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { + return func(f reflect.Value, t reflect.Value) (interface{}, error) { + var err error + data := f.Interface() + + newFrom := f + for _, f1 := range fs { + data, err = DecodeHookExec(f1, newFrom, t) + if err != nil { + return nil, err + } + newFrom = reflect.ValueOf(data) + } + + return data, nil + } +} + +// OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned. +// If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages. +func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc { + return func(a, b reflect.Value) (interface{}, error) { + var allErrs string + var out interface{} + var err error + + for _, f := range ff { + out, err = DecodeHookExec(f, a, b) + if err != nil { + allErrs += err.Error() + "\n" + continue + } + + return out, nil + } + + return nil, errors.New(allErrs) + } +} + +// StringToSliceHookFunc returns a DecodeHookFunc that converts +// string to []string by splitting on the given sep. +func StringToSliceHookFunc(sep string) DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.SliceOf(f) { + return data, nil + } + + raw := data.(string) + if raw == "" { + return []string{}, nil + } + + return strings.Split(raw, sep), nil + } +} + +// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts +// strings to time.Duration. +func StringToTimeDurationHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Duration(5)) { + return data, nil + } + + // Convert it by parsing + return time.ParseDuration(data.(string)) + } +} + +// StringToIPHookFunc returns a DecodeHookFunc that converts +// strings to net.IP +func StringToIPHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IP{}) { + return data, nil + } + + // Convert it by parsing + ip := net.ParseIP(data.(string)) + if ip == nil { + return net.IP{}, fmt.Errorf("failed parsing ip %v", data) + } + + return ip, nil + } +} + +// StringToIPNetHookFunc returns a DecodeHookFunc that converts +// strings to net.IPNet +func StringToIPNetHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(net.IPNet{}) { + return data, nil + } + + // Convert it by parsing + _, net, err := net.ParseCIDR(data.(string)) + return net, err + } +} + +// StringToTimeHookFunc returns a DecodeHookFunc that converts +// strings to time.Time. +func StringToTimeHookFunc(layout string) DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Time{}) { + return data, nil + } + + // Convert it by parsing + return time.Parse(layout, data.(string)) + } +} + +// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to +// the decoder. +// +// Note that this is significantly different from the WeaklyTypedInput option +// of the DecoderConfig. +func WeaklyTypedHook( + f reflect.Kind, + t reflect.Kind, + data interface{}, +) (interface{}, error) { + dataVal := reflect.ValueOf(data) + switch t { + case reflect.String: + switch f { + case reflect.Bool: + if dataVal.Bool() { + return "1", nil + } + return "0", nil + case reflect.Float32: + return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil + case reflect.Int: + return strconv.FormatInt(dataVal.Int(), 10), nil + case reflect.Slice: + dataType := dataVal.Type() + elemKind := dataType.Elem().Kind() + if elemKind == reflect.Uint8 { + return string(dataVal.Interface().([]uint8)), nil + } + case reflect.Uint: + return strconv.FormatUint(dataVal.Uint(), 10), nil + } + } + + return data, nil +} + +func RecursiveStructToMapHookFunc() DecodeHookFunc { + return func(f reflect.Value, t reflect.Value) (interface{}, error) { + if f.Kind() != reflect.Struct { + return f.Interface(), nil + } + + var i interface{} = struct{}{} + if t.Type() != reflect.TypeOf(&i).Elem() { + return f.Interface(), nil + } + + m := make(map[string]interface{}) + t.Set(reflect.ValueOf(m)) + + return f.Interface(), nil + } +} + +// TextUnmarshallerHookFunc returns a DecodeHookFunc that applies +// strings to the UnmarshalText function, when the target type +// implements the encoding.TextUnmarshaler interface +func TextUnmarshallerHookFunc() DecodeHookFuncType { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + result := reflect.New(t).Interface() + unmarshaller, ok := result.(encoding.TextUnmarshaler) + if !ok { + return data, nil + } + str, ok := data.(string) + if !ok { + str = reflect.Indirect(reflect.ValueOf(&data)).Elem().String() + } + if err := unmarshaller.UnmarshalText([]byte(str)); err != nil { + return nil, err + } + return result, nil + } +} + +// StringToNetIPAddrHookFunc returns a DecodeHookFunc that converts +// strings to netip.Addr. +func StringToNetIPAddrHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(netip.Addr{}) { + return data, nil + } + + // Convert it by parsing + return netip.ParseAddr(data.(string)) + } +} + +// StringToNetIPAddrPortHookFunc returns a DecodeHookFunc that converts +// strings to netip.AddrPort. +func StringToNetIPAddrPortHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}, + ) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(netip.AddrPort{}) { + return data, nil + } + + // Convert it by parsing + return netip.ParseAddrPort(data.(string)) + } +} + +// StringToBasicTypeHookFunc returns a DecodeHookFunc that converts +// strings to basic types. +// int8, uint8, int16, uint16, int32, uint32, int64, uint64, int, uint, float32, float64, bool, byte, rune, complex64, complex128 +func StringToBasicTypeHookFunc() DecodeHookFunc { + return ComposeDecodeHookFunc( + StringToInt8HookFunc(), + StringToUint8HookFunc(), + StringToInt16HookFunc(), + StringToUint16HookFunc(), + StringToInt32HookFunc(), + StringToUint32HookFunc(), + StringToInt64HookFunc(), + StringToUint64HookFunc(), + StringToIntHookFunc(), + StringToUintHookFunc(), + StringToFloat32HookFunc(), + StringToFloat64HookFunc(), + StringToBoolHookFunc(), + // byte and rune are aliases for uint8 and int32 respectively + // StringToByteHookFunc(), + // StringToRuneHookFunc(), + StringToComplex64HookFunc(), + StringToComplex128HookFunc(), + ) +} + +// StringToInt8HookFunc returns a DecodeHookFunc that converts +// strings to int8. +func StringToInt8HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int8 { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 8) + return int8(i64), err + } +} + +// StringToUint8HookFunc returns a DecodeHookFunc that converts +// strings to uint8. +func StringToUint8HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint8 { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 8) + return uint8(u64), err + } +} + +// StringToInt16HookFunc returns a DecodeHookFunc that converts +// strings to int16. +func StringToInt16HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int16 { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 16) + return int16(i64), err + } +} + +// StringToUint16HookFunc returns a DecodeHookFunc that converts +// strings to uint16. +func StringToUint16HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint16 { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 16) + return uint16(u64), err + } +} + +// StringToInt32HookFunc returns a DecodeHookFunc that converts +// strings to int32. +func StringToInt32HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int32 { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 32) + return int32(i64), err + } +} + +// StringToUint32HookFunc returns a DecodeHookFunc that converts +// strings to uint32. +func StringToUint32HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint32 { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 32) + return uint32(u64), err + } +} + +// StringToInt64HookFunc returns a DecodeHookFunc that converts +// strings to int64. +func StringToInt64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int64 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseInt(data.(string), 0, 64) + } +} + +// StringToUint64HookFunc returns a DecodeHookFunc that converts +// strings to uint64. +func StringToUint64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint64 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseUint(data.(string), 0, 64) + } +} + +// StringToIntHookFunc returns a DecodeHookFunc that converts +// strings to int. +func StringToIntHookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Int { + return data, nil + } + + // Convert it by parsing + i64, err := strconv.ParseInt(data.(string), 0, 0) + return int(i64), err + } +} + +// StringToUintHookFunc returns a DecodeHookFunc that converts +// strings to uint. +func StringToUintHookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Uint { + return data, nil + } + + // Convert it by parsing + u64, err := strconv.ParseUint(data.(string), 0, 0) + return uint(u64), err + } +} + +// StringToFloat32HookFunc returns a DecodeHookFunc that converts +// strings to float32. +func StringToFloat32HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Float32 { + return data, nil + } + + // Convert it by parsing + f64, err := strconv.ParseFloat(data.(string), 32) + return float32(f64), err + } +} + +// StringToFloat64HookFunc returns a DecodeHookFunc that converts +// strings to float64. +func StringToFloat64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Float64 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseFloat(data.(string), 64) + } +} + +// StringToBoolHookFunc returns a DecodeHookFunc that converts +// strings to bool. +func StringToBoolHookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Bool { + return data, nil + } + + // Convert it by parsing + return strconv.ParseBool(data.(string)) + } +} + +// StringToByteHookFunc returns a DecodeHookFunc that converts +// strings to byte. +func StringToByteHookFunc() DecodeHookFunc { + return StringToUint8HookFunc() +} + +// StringToRuneHookFunc returns a DecodeHookFunc that converts +// strings to rune. +func StringToRuneHookFunc() DecodeHookFunc { + return StringToInt32HookFunc() +} + +// StringToComplex64HookFunc returns a DecodeHookFunc that converts +// strings to complex64. +func StringToComplex64HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Complex64 { + return data, nil + } + + // Convert it by parsing + c128, err := strconv.ParseComplex(data.(string), 64) + return complex64(c128), err + } +} + +// StringToComplex128HookFunc returns a DecodeHookFunc that converts +// strings to complex128. +func StringToComplex128HookFunc() DecodeHookFunc { + return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if f.Kind() != reflect.String || t.Kind() != reflect.Complex128 { + return data, nil + } + + // Convert it by parsing + return strconv.ParseComplex(data.(string), 128) + } +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/flake.lock b/tools/vendor/github.com/go-viper/mapstructure/v2/flake.lock new file mode 100644 index 000000000..4bea8154e --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/flake.lock @@ -0,0 +1,472 @@ +{ + "nodes": { + "cachix": { + "inputs": { + "devenv": "devenv_2", + "flake-compat": [ + "devenv", + "flake-compat" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "pre-commit-hooks": [ + "devenv", + "pre-commit-hooks" + ] + }, + "locked": { + "lastModified": 1712055811, + "narHash": "sha256-7FcfMm5A/f02yyzuavJe06zLa9hcMHsagE28ADcmQvk=", + "owner": "cachix", + "repo": "cachix", + "rev": "02e38da89851ec7fec3356a5c04bc8349cae0e30", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "cachix", + "type": "github" + } + }, + "devenv": { + "inputs": { + "cachix": "cachix", + "flake-compat": "flake-compat_2", + "nix": "nix_2", + "nixpkgs": "nixpkgs_2", + "pre-commit-hooks": "pre-commit-hooks" + }, + "locked": { + "lastModified": 1717245169, + "narHash": "sha256-+mW3rTBjGU8p1THJN0lX/Dd/8FbnF+3dB+mJuSaxewE=", + "owner": "cachix", + "repo": "devenv", + "rev": "c3f9f053c077c6f88a3de5276d9178c62baa3fc3", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "devenv_2": { + "inputs": { + "flake-compat": [ + "devenv", + "cachix", + "flake-compat" + ], + "nix": "nix", + "nixpkgs": "nixpkgs", + "poetry2nix": "poetry2nix", + "pre-commit-hooks": [ + "devenv", + "cachix", + "pre-commit-hooks" + ] + }, + "locked": { + "lastModified": 1708704632, + "narHash": "sha256-w+dOIW60FKMaHI1q5714CSibk99JfYxm0CzTinYWr+Q=", + "owner": "cachix", + "repo": "devenv", + "rev": "2ee4450b0f4b95a1b90f2eb5ffea98b90e48c196", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "python-rewrite", + "repo": "devenv", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1673956053, + "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-compat_2": { + "flake": false, + "locked": { + "lastModified": 1696426674, + "narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "0f9255e01c2351cc7d116c072cb317785dd33b33", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1717285511, + "narHash": "sha256-iKzJcpdXih14qYVcZ9QC9XuZYnPc6T8YImb6dX166kw=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "2a55567fcf15b1b1c7ed712a2c6fadaec7412ea8", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1689068808, + "narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_2": { + "inputs": { + "systems": "systems_2" + }, + "locked": { + "lastModified": 1710146030, + "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "gitignore": { + "inputs": { + "nixpkgs": [ + "devenv", + "pre-commit-hooks", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1709087332, + "narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=", + "owner": "hercules-ci", + "repo": "gitignore.nix", + "rev": "637db329424fd7e46cf4185293b9cc8c88c95394", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "gitignore.nix", + "type": "github" + } + }, + "nix": { + "inputs": { + "flake-compat": "flake-compat", + "nixpkgs": [ + "devenv", + "cachix", + "devenv", + "nixpkgs" + ], + "nixpkgs-regression": "nixpkgs-regression" + }, + "locked": { + "lastModified": 1712911606, + "narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=", + "owner": "domenkozar", + "repo": "nix", + "rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12", + "type": "github" + }, + "original": { + "owner": "domenkozar", + "ref": "devenv-2.21", + "repo": "nix", + "type": "github" + } + }, + "nix-github-actions": { + "inputs": { + "nixpkgs": [ + "devenv", + "cachix", + "devenv", + "poetry2nix", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1688870561, + "narHash": "sha256-4UYkifnPEw1nAzqqPOTL2MvWtm3sNGw1UTYTalkTcGY=", + "owner": "nix-community", + "repo": "nix-github-actions", + "rev": "165b1650b753316aa7f1787f3005a8d2da0f5301", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nix-github-actions", + "type": "github" + } + }, + "nix_2": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-regression": "nixpkgs-regression_2" + }, + "locked": { + "lastModified": 1712911606, + "narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=", + "owner": "domenkozar", + "repo": "nix", + "rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12", + "type": "github" + }, + "original": { + "owner": "domenkozar", + "ref": "devenv-2.21", + "repo": "nix", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1692808169, + "narHash": "sha256-x9Opq06rIiwdwGeK2Ykj69dNc2IvUH1fY55Wm7atwrE=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "9201b5ff357e781bf014d0330d18555695df7ba8", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1717284937, + "narHash": "sha256-lIbdfCsf8LMFloheeE6N31+BMIeixqyQWbSr2vk79EQ=", + "type": "tarball", + "url": "https://github.com/NixOS/nixpkgs/archive/eb9ceca17df2ea50a250b6b27f7bf6ab0186f198.tar.gz" + }, + "original": { + "type": "tarball", + "url": "https://github.com/NixOS/nixpkgs/archive/eb9ceca17df2ea50a250b6b27f7bf6ab0186f198.tar.gz" + } + }, + "nixpkgs-regression": { + "locked": { + "lastModified": 1643052045, + "narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + } + }, + "nixpkgs-regression_2": { + "locked": { + "lastModified": 1643052045, + "narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", + "type": "github" + } + }, + "nixpkgs-stable": { + "locked": { + "lastModified": 1710695816, + "narHash": "sha256-3Eh7fhEID17pv9ZxrPwCLfqXnYP006RKzSs0JptsN84=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "614b4613980a522ba49f0d194531beddbb7220d3", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-23.11", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1713361204, + "narHash": "sha256-TA6EDunWTkc5FvDCqU3W2T3SFn0gRZqh6D/hJnM02MM=", + "owner": "cachix", + "repo": "devenv-nixpkgs", + "rev": "285676e87ad9f0ca23d8714a6ab61e7e027020c6", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "rolling", + "repo": "devenv-nixpkgs", + "type": "github" + } + }, + "nixpkgs_3": { + "locked": { + "lastModified": 1717112898, + "narHash": "sha256-7R2ZvOnvd9h8fDd65p0JnB7wXfUvreox3xFdYWd1BnY=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6132b0f6e344ce2fe34fc051b72fb46e34f668e0", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "poetry2nix": { + "inputs": { + "flake-utils": "flake-utils", + "nix-github-actions": "nix-github-actions", + "nixpkgs": [ + "devenv", + "cachix", + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1692876271, + "narHash": "sha256-IXfZEkI0Mal5y1jr6IRWMqK8GW2/f28xJenZIPQqkY0=", + "owner": "nix-community", + "repo": "poetry2nix", + "rev": "d5006be9c2c2417dafb2e2e5034d83fabd207ee3", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "poetry2nix", + "type": "github" + } + }, + "pre-commit-hooks": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "flake-utils": "flake-utils_2", + "gitignore": "gitignore", + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-stable": "nixpkgs-stable" + }, + "locked": { + "lastModified": 1713775815, + "narHash": "sha256-Wu9cdYTnGQQwtT20QQMg7jzkANKQjwBD9iccfGKkfls=", + "owner": "cachix", + "repo": "pre-commit-hooks.nix", + "rev": "2ac4dcbf55ed43f3be0bae15e181f08a57af24a4", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "pre-commit-hooks.nix", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "flake-parts": "flake-parts", + "nixpkgs": "nixpkgs_3" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + }, + "systems_2": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/flake.nix b/tools/vendor/github.com/go-viper/mapstructure/v2/flake.nix new file mode 100644 index 000000000..4ed0f5331 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/flake.nix @@ -0,0 +1,39 @@ +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + flake-parts.url = "github:hercules-ci/flake-parts"; + devenv.url = "github:cachix/devenv"; + }; + + outputs = inputs@{ flake-parts, ... }: + flake-parts.lib.mkFlake { inherit inputs; } { + imports = [ + inputs.devenv.flakeModule + ]; + + systems = [ "x86_64-linux" "x86_64-darwin" "aarch64-darwin" ]; + + perSystem = { config, self', inputs', pkgs, system, ... }: rec { + devenv.shells = { + default = { + languages = { + go.enable = true; + }; + + pre-commit.hooks = { + nixpkgs-fmt.enable = true; + }; + + packages = with pkgs; [ + golangci-lint + ]; + + # https://github.com/cachix/devenv/issues/528#issuecomment-1556108767 + containers = pkgs.lib.mkForce { }; + }; + + ci = devenv.shells.default; + }; + }; + }; +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/errors.go b/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/errors.go new file mode 100644 index 000000000..d1c15e474 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/errors.go @@ -0,0 +1,11 @@ +package errors + +import "errors" + +func New(text string) error { + return errors.New(text) +} + +func As(err error, target interface{}) bool { + return errors.As(err, target) +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join.go b/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join.go new file mode 100644 index 000000000..d74e3a0b5 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join.go @@ -0,0 +1,9 @@ +//go:build go1.20 + +package errors + +import "errors" + +func Join(errs ...error) error { + return errors.Join(errs...) +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join_go1_19.go b/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join_go1_19.go new file mode 100644 index 000000000..700b40229 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/internal/errors/join_go1_19.go @@ -0,0 +1,61 @@ +//go:build !go1.20 + +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package errors + +// Join returns an error that wraps the given errors. +// Any nil error values are discarded. +// Join returns nil if every value in errs is nil. +// The error formats as the concatenation of the strings obtained +// by calling the Error method of each element of errs, with a newline +// between each string. +// +// A non-nil error returned by Join implements the Unwrap() []error method. +func Join(errs ...error) error { + n := 0 + for _, err := range errs { + if err != nil { + n++ + } + } + if n == 0 { + return nil + } + e := &joinError{ + errs: make([]error, 0, n), + } + for _, err := range errs { + if err != nil { + e.errs = append(e.errs, err) + } + } + return e +} + +type joinError struct { + errs []error +} + +func (e *joinError) Error() string { + // Since Join returns nil if every value in errs is nil, + // e.errs cannot be empty. + if len(e.errs) == 1 { + return e.errs[0].Error() + } + + b := []byte(e.errs[0].Error()) + for _, err := range e.errs[1:] { + b = append(b, '\n') + b = append(b, err.Error()...) + } + // At this point, b has at least one byte '\n'. + // return unsafe.String(&b[0], len(b)) + return string(b) +} + +func (e *joinError) Unwrap() []error { + return e.errs +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go b/tools/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go new file mode 100644 index 000000000..4b54fae08 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/mapstructure.go @@ -0,0 +1,1576 @@ +// Package mapstructure exposes functionality to convert one arbitrary +// Go type into another, typically to convert a map[string]interface{} +// into a native Go structure. +// +// The Go structure can be arbitrarily complex, containing slices, +// other structs, etc. and the decoder will properly decode nested +// maps and so on into the proper structures in the native Go struct. +// See the examples to see what the decoder is capable of. +// +// The simplest function to start with is Decode. +// +// # Field Tags +// +// When decoding to a struct, mapstructure will use the field name by +// default to perform the mapping. For example, if a struct has a field +// "Username" then mapstructure will look for a key in the source value +// of "username" (case insensitive). +// +// type User struct { +// Username string +// } +// +// You can change the behavior of mapstructure by using struct tags. +// The default struct tag that mapstructure looks for is "mapstructure" +// but you can customize it using DecoderConfig. +// +// # Renaming Fields +// +// To rename the key that mapstructure looks for, use the "mapstructure" +// tag and set a value directly. For example, to change the "username" example +// above to "user": +// +// type User struct { +// Username string `mapstructure:"user"` +// } +// +// # Embedded Structs and Squashing +// +// Embedded structs are treated as if they're another field with that name. +// By default, the two structs below are equivalent when decoding with +// mapstructure: +// +// type Person struct { +// Name string +// } +// +// type Friend struct { +// Person +// } +// +// type Friend struct { +// Person Person +// } +// +// This would require an input that looks like below: +// +// map[string]interface{}{ +// "person": map[string]interface{}{"name": "alice"}, +// } +// +// If your "person" value is NOT nested, then you can append ",squash" to +// your tag value and mapstructure will treat it as if the embedded struct +// were part of the struct directly. Example: +// +// type Friend struct { +// Person `mapstructure:",squash"` +// } +// +// Now the following input would be accepted: +// +// map[string]interface{}{ +// "name": "alice", +// } +// +// When decoding from a struct to a map, the squash tag squashes the struct +// fields into a single map. Using the example structs from above: +// +// Friend{Person: Person{Name: "alice"}} +// +// Will be decoded into a map: +// +// map[string]interface{}{ +// "name": "alice", +// } +// +// DecoderConfig has a field that changes the behavior of mapstructure +// to always squash embedded structs. +// +// # Remainder Values +// +// If there are any unmapped keys in the source value, mapstructure by +// default will silently ignore them. You can error by setting ErrorUnused +// in DecoderConfig. If you're using Metadata you can also maintain a slice +// of the unused keys. +// +// You can also use the ",remain" suffix on your tag to collect all unused +// values in a map. The field with this tag MUST be a map type and should +// probably be a "map[string]interface{}" or "map[interface{}]interface{}". +// See example below: +// +// type Friend struct { +// Name string +// Other map[string]interface{} `mapstructure:",remain"` +// } +// +// Given the input below, Other would be populated with the other +// values that weren't used (everything but "name"): +// +// map[string]interface{}{ +// "name": "bob", +// "address": "123 Maple St.", +// } +// +// # Omit Empty Values +// +// When decoding from a struct to any other value, you may use the +// ",omitempty" suffix on your tag to omit that value if it equates to +// the zero value. The zero value of all types is specified in the Go +// specification. +// +// For example, the zero type of a numeric type is zero ("0"). If the struct +// field value is zero and a numeric type, the field is empty, and it won't +// be encoded into the destination type. +// +// type Source struct { +// Age int `mapstructure:",omitempty"` +// } +// +// # Unexported fields +// +// Since unexported (private) struct fields cannot be set outside the package +// where they are defined, the decoder will simply skip them. +// +// For this output type definition: +// +// type Exported struct { +// private string // this unexported field will be skipped +// Public string +// } +// +// Using this map as input: +// +// map[string]interface{}{ +// "private": "I will be ignored", +// "Public": "I made it through!", +// } +// +// The following struct will be decoded: +// +// type Exported struct { +// private: "" // field is left with an empty string (zero value) +// Public: "I made it through!" +// } +// +// # Other Configuration +// +// mapstructure is highly configurable. See the DecoderConfig struct +// for other features and options that are supported. +package mapstructure + +import ( + "encoding/json" + "fmt" + "reflect" + "sort" + "strconv" + "strings" + + "github.com/go-viper/mapstructure/v2/internal/errors" +) + +// DecodeHookFunc is the callback function that can be used for +// data transformations. See "DecodeHook" in the DecoderConfig +// struct. +// +// The type must be one of DecodeHookFuncType, DecodeHookFuncKind, or +// DecodeHookFuncValue. +// Values are a superset of Types (Values can return types), and Types are a +// superset of Kinds (Types can return Kinds) and are generally a richer thing +// to use, but Kinds are simpler if you only need those. +// +// The reason DecodeHookFunc is multi-typed is for backwards compatibility: +// we started with Kinds and then realized Types were the better solution, +// but have a promise to not break backwards compat so we now support +// both. +type DecodeHookFunc interface{} + +// DecodeHookFuncType is a DecodeHookFunc which has complete information about +// the source and target types. +type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) + +// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the +// source and target types. +type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) + +// DecodeHookFuncValue is a DecodeHookFunc which has complete access to both the source and target +// values. +type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error) + +// DecoderConfig is the configuration that is used to create a new decoder +// and allows customization of various aspects of decoding. +type DecoderConfig struct { + // DecodeHook, if set, will be called before any decoding and any + // type conversion (if WeaklyTypedInput is on). This lets you modify + // the values before they're set down onto the resulting struct. The + // DecodeHook is called for every map and value in the input. This means + // that if a struct has embedded fields with squash tags the decode hook + // is called only once with all of the input data, not once for each + // embedded struct. + // + // If an error is returned, the entire decode will fail with that error. + DecodeHook DecodeHookFunc + + // If ErrorUnused is true, then it is an error for there to exist + // keys in the original map that were unused in the decoding process + // (extra keys). + ErrorUnused bool + + // If ErrorUnset is true, then it is an error for there to exist + // fields in the result that were not set in the decoding process + // (extra fields). This only applies to decoding to a struct. This + // will affect all nested structs as well. + ErrorUnset bool + + // ZeroFields, if set to true, will zero fields before writing them. + // For example, a map will be emptied before decoded values are put in + // it. If this is false, a map will be merged. + ZeroFields bool + + // If WeaklyTypedInput is true, the decoder will make the following + // "weak" conversions: + // + // - bools to string (true = "1", false = "0") + // - numbers to string (base 10) + // - bools to int/uint (true = 1, false = 0) + // - strings to int/uint (base implied by prefix) + // - int to bool (true if value != 0) + // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, + // FALSE, false, False. Anything else is an error) + // - empty array = empty map and vice versa + // - negative numbers to overflowed uint values (base 10) + // - slice of maps to a merged map + // - single values are converted to slices if required. Each + // element is weakly decoded. For example: "4" can become []int{4} + // if the target type is an int slice. + // + WeaklyTypedInput bool + + // Squash will squash embedded structs. A squash tag may also be + // added to an individual struct field using a tag. For example: + // + // type Parent struct { + // Child `mapstructure:",squash"` + // } + Squash bool + + // Metadata is the struct that will contain extra metadata about + // the decoding. If this is nil, then no metadata will be tracked. + Metadata *Metadata + + // Result is a pointer to the struct that will contain the decoded + // value. + Result interface{} + + // The tag name that mapstructure reads for field names. This + // defaults to "mapstructure" + TagName string + + // IgnoreUntaggedFields ignores all struct fields without explicit + // TagName, comparable to `mapstructure:"-"` as default behaviour. + IgnoreUntaggedFields bool + + // MatchName is the function used to match the map key to the struct + // field name or tag. Defaults to `strings.EqualFold`. This can be used + // to implement case-sensitive tag values, support snake casing, etc. + MatchName func(mapKey, fieldName string) bool +} + +// A Decoder takes a raw interface value and turns it into structured +// data, keeping track of rich error information along the way in case +// anything goes wrong. Unlike the basic top-level Decode method, you can +// more finely control how the Decoder behaves using the DecoderConfig +// structure. The top-level Decode method is just a convenience that sets +// up the most basic Decoder. +type Decoder struct { + config *DecoderConfig +} + +// Metadata contains information about decoding a structure that +// is tedious or difficult to get otherwise. +type Metadata struct { + // Keys are the keys of the structure which were successfully decoded + Keys []string + + // Unused is a slice of keys that were found in the raw value but + // weren't decoded since there was no matching field in the result interface + Unused []string + + // Unset is a slice of field names that were found in the result interface + // but weren't set in the decoding process since there was no matching value + // in the input + Unset []string +} + +// Decode takes an input structure and uses reflection to translate it to +// the output structure. output must be a pointer to a map or struct. +func Decode(input interface{}, output interface{}) error { + config := &DecoderConfig{ + Metadata: nil, + Result: output, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// WeakDecode is the same as Decode but is shorthand to enable +// WeaklyTypedInput. See DecoderConfig for more info. +func WeakDecode(input, output interface{}) error { + config := &DecoderConfig{ + Metadata: nil, + Result: output, + WeaklyTypedInput: true, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// DecodeMetadata is the same as Decode, but is shorthand to +// enable metadata collection. See DecoderConfig for more info. +func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// WeakDecodeMetadata is the same as Decode, but is shorthand to +// enable both WeaklyTypedInput and metadata collection. See +// DecoderConfig for more info. +func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + WeaklyTypedInput: true, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// NewDecoder returns a new decoder for the given configuration. Once +// a decoder has been returned, the same configuration must not be used +// again. +func NewDecoder(config *DecoderConfig) (*Decoder, error) { + val := reflect.ValueOf(config.Result) + if val.Kind() != reflect.Ptr { + return nil, errors.New("result must be a pointer") + } + + val = val.Elem() + if !val.CanAddr() { + return nil, errors.New("result must be addressable (a pointer)") + } + + if config.Metadata != nil { + if config.Metadata.Keys == nil { + config.Metadata.Keys = make([]string, 0) + } + + if config.Metadata.Unused == nil { + config.Metadata.Unused = make([]string, 0) + } + + if config.Metadata.Unset == nil { + config.Metadata.Unset = make([]string, 0) + } + } + + if config.TagName == "" { + config.TagName = "mapstructure" + } + + if config.MatchName == nil { + config.MatchName = strings.EqualFold + } + + result := &Decoder{ + config: config, + } + + return result, nil +} + +// Decode decodes the given raw interface to the target pointer specified +// by the configuration. +func (d *Decoder) Decode(input interface{}) error { + err := d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) + + // Retain some of the original behavior when multiple errors ocurr + var joinedErr interface{ Unwrap() []error } + if errors.As(err, &joinedErr) { + return fmt.Errorf("decoding failed due to the following error(s):\n\n%w", err) + } + + return err +} + +// Decodes an unknown data type into a specific reflection value. +func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { + var inputVal reflect.Value + if input != nil { + inputVal = reflect.ValueOf(input) + + // We need to check here if input is a typed nil. Typed nils won't + // match the "input == nil" below so we check that here. + if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() { + input = nil + } + } + + if input == nil { + // If the data is nil, then we don't set anything, unless ZeroFields is set + // to true. + if d.config.ZeroFields { + outVal.Set(reflect.Zero(outVal.Type())) + + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + } + return nil + } + + if !inputVal.IsValid() { + // If the input value is invalid, then we just set the value + // to be the zero value. + outVal.Set(reflect.Zero(outVal.Type())) + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + return nil + } + + if d.config.DecodeHook != nil { + // We have a DecodeHook, so let's pre-process the input. + var err error + input, err = DecodeHookExec(d.config.DecodeHook, inputVal, outVal) + if err != nil { + return fmt.Errorf("error decoding '%s': %w", name, err) + } + } + + var err error + outputKind := getKind(outVal) + addMetaKey := true + switch outputKind { + case reflect.Bool: + err = d.decodeBool(name, input, outVal) + case reflect.Interface: + err = d.decodeBasic(name, input, outVal) + case reflect.String: + err = d.decodeString(name, input, outVal) + case reflect.Int: + err = d.decodeInt(name, input, outVal) + case reflect.Uint: + err = d.decodeUint(name, input, outVal) + case reflect.Float32: + err = d.decodeFloat(name, input, outVal) + case reflect.Complex64: + err = d.decodeComplex(name, input, outVal) + case reflect.Struct: + err = d.decodeStruct(name, input, outVal) + case reflect.Map: + err = d.decodeMap(name, input, outVal) + case reflect.Ptr: + addMetaKey, err = d.decodePtr(name, input, outVal) + case reflect.Slice: + err = d.decodeSlice(name, input, outVal) + case reflect.Array: + err = d.decodeArray(name, input, outVal) + case reflect.Func: + err = d.decodeFunc(name, input, outVal) + default: + // If we reached this point then we weren't able to decode it + return fmt.Errorf("%s: unsupported type: %s", name, outputKind) + } + + // If we reached here, then we successfully decoded SOMETHING, so + // mark the key as used if we're tracking metainput. + if addMetaKey && d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + + return err +} + +// This decodes a basic type (bool, int, string, etc.) and sets the +// value to "data" of that type. +func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { + if val.IsValid() && val.Elem().IsValid() { + elem := val.Elem() + + // If we can't address this element, then its not writable. Instead, + // we make a copy of the value (which is a pointer and therefore + // writable), decode into that, and replace the whole value. + copied := false + if !elem.CanAddr() { + copied = true + + // Make *T + copy := reflect.New(elem.Type()) + + // *T = elem + copy.Elem().Set(elem) + + // Set elem so we decode into it + elem = copy + } + + // Decode. If we have an error then return. We also return right + // away if we're not a copy because that means we decoded directly. + if err := d.decode(name, data, elem); err != nil || !copied { + return err + } + + // If we're a copy, we need to set te final result + val.Set(elem.Elem()) + return nil + } + + dataVal := reflect.ValueOf(data) + + // If the input data is a pointer, and the assigned type is the dereference + // of that exact pointer, then indirect it so that we can assign it. + // Example: *string to string + if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() { + dataVal = reflect.Indirect(dataVal) + } + + if !dataVal.IsValid() { + dataVal = reflect.Zero(val.Type()) + } + + dataValType := dataVal.Type() + if !dataValType.AssignableTo(val.Type()) { + return fmt.Errorf( + "'%s' expected type '%s', got '%s'", + name, val.Type(), dataValType) + } + + val.Set(dataVal) + return nil +} + +func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + + converted := true + switch { + case dataKind == reflect.String: + val.SetString(dataVal.String()) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetString("1") + } else { + val.SetString("0") + } + case dataKind == reflect.Int && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatInt(dataVal.Int(), 10)) + case dataKind == reflect.Uint && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) + case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: + val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) + case dataKind == reflect.Slice && d.config.WeaklyTypedInput, + dataKind == reflect.Array && d.config.WeaklyTypedInput: + dataType := dataVal.Type() + elemKind := dataType.Elem().Kind() + switch elemKind { + case reflect.Uint8: + var uints []uint8 + if dataKind == reflect.Array { + uints = make([]uint8, dataVal.Len(), dataVal.Len()) + for i := range uints { + uints[i] = dataVal.Index(i).Interface().(uint8) + } + } else { + uints = dataVal.Interface().([]uint8) + } + val.SetString(string(uints)) + default: + converted = false + } + default: + converted = false + } + + if !converted { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() + + switch { + case dataKind == reflect.Int: + val.SetInt(dataVal.Int()) + case dataKind == reflect.Uint: + val.SetInt(int64(dataVal.Uint())) + case dataKind == reflect.Float32: + val.SetInt(int64(dataVal.Float())) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetInt(1) + } else { + val.SetInt(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } + + i, err := strconv.ParseInt(str, 0, val.Type().Bits()) + if err == nil { + val.SetInt(i) + } else { + return fmt.Errorf("cannot parse '%s' as int: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Int64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetInt(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() + + switch { + case dataKind == reflect.Int: + i := dataVal.Int() + if i < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %d overflows uint", + name, i) + } + val.SetUint(uint64(i)) + case dataKind == reflect.Uint: + val.SetUint(dataVal.Uint()) + case dataKind == reflect.Float32: + f := dataVal.Float() + if f < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %f overflows uint", + name, f) + } + val.SetUint(uint64(f)) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetUint(1) + } else { + val.SetUint(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } + + i, err := strconv.ParseUint(str, 0, val.Type().Bits()) + if err == nil { + val.SetUint(i) + } else { + return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := strconv.ParseUint(string(jn), 0, 64) + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetUint(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + + switch { + case dataKind == reflect.Bool: + val.SetBool(dataVal.Bool()) + case dataKind == reflect.Int && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Int() != 0) + case dataKind == reflect.Uint && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Uint() != 0) + case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: + val.SetBool(dataVal.Float() != 0) + case dataKind == reflect.String && d.config.WeaklyTypedInput: + b, err := strconv.ParseBool(dataVal.String()) + if err == nil { + val.SetBool(b) + } else if dataVal.String() == "" { + val.SetBool(false) + } else { + return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) + } + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + dataType := dataVal.Type() + + switch { + case dataKind == reflect.Int: + val.SetFloat(float64(dataVal.Int())) + case dataKind == reflect.Uint: + val.SetFloat(float64(dataVal.Uint())) + case dataKind == reflect.Float32: + val.SetFloat(dataVal.Float()) + case dataKind == reflect.Bool && d.config.WeaklyTypedInput: + if dataVal.Bool() { + val.SetFloat(1) + } else { + val.SetFloat(0) + } + case dataKind == reflect.String && d.config.WeaklyTypedInput: + str := dataVal.String() + if str == "" { + str = "0" + } + + f, err := strconv.ParseFloat(str, val.Type().Bits()) + if err == nil { + val.SetFloat(f) + } else { + return fmt.Errorf("cannot parse '%s' as float: %s", name, err) + } + case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": + jn := data.(json.Number) + i, err := jn.Float64() + if err != nil { + return fmt.Errorf( + "error decoding json.Number into %s: %s", name, err) + } + val.SetFloat(i) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeComplex(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataKind := getKind(dataVal) + + switch { + case dataKind == reflect.Complex64: + val.SetComplex(dataVal.Complex()) + default: + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + + return nil +} + +func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() + + // By default we overwrite keys in the current map + valMap := val + + // If the map is nil or we're purposely zeroing fields, make a new map + if valMap.IsNil() || d.config.ZeroFields { + // Make a new map to hold our result + mapType := reflect.MapOf(valKeyType, valElemType) + valMap = reflect.MakeMap(mapType) + } + + dataVal := reflect.ValueOf(data) + + // Resolve any levels of indirection + for dataVal.Kind() == reflect.Pointer { + dataVal = reflect.Indirect(dataVal) + } + + // Check input type and based on the input type jump to the proper func + switch dataVal.Kind() { + case reflect.Map: + return d.decodeMapFromMap(name, dataVal, val, valMap) + + case reflect.Struct: + return d.decodeMapFromStruct(name, dataVal, val, valMap) + + case reflect.Array, reflect.Slice: + if d.config.WeaklyTypedInput { + return d.decodeMapFromSlice(name, dataVal, val, valMap) + } + + fallthrough + + default: + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) + } +} + +func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + // Special case for BC reasons (covered by tests) + if dataVal.Len() == 0 { + val.Set(valMap) + return nil + } + + for i := 0; i < dataVal.Len(); i++ { + err := d.decode( + name+"["+strconv.Itoa(i)+"]", + dataVal.Index(i).Interface(), val) + if err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() + + // Accumulate errors + var errs []error + + // If the input data is empty, then we just match what the input data is. + if dataVal.Len() == 0 { + if dataVal.IsNil() { + if !val.IsNil() { + val.Set(dataVal) + } + } else { + // Set to empty allocated value + val.Set(valMap) + } + + return nil + } + + for _, k := range dataVal.MapKeys() { + fieldName := name + "[" + k.String() + "]" + + // First decode the key into the proper type + currentKey := reflect.Indirect(reflect.New(valKeyType)) + if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { + errs = append(errs, err) + continue + } + + // Next decode the data into the proper type + v := dataVal.MapIndex(k).Interface() + currentVal := reflect.Indirect(reflect.New(valElemType)) + if err := d.decode(fieldName, v, currentVal); err != nil { + errs = append(errs, err) + continue + } + + valMap.SetMapIndex(currentKey, currentVal) + } + + // Set the built up map to the value + val.Set(valMap) + + return errors.Join(errs...) +} + +func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + typ := dataVal.Type() + for i := 0; i < typ.NumField(); i++ { + // Get the StructField first since this is a cheap operation. If the + // field is unexported, then ignore it. + f := typ.Field(i) + if f.PkgPath != "" { + continue + } + + // Next get the actual value of this field and verify it is assignable + // to the map value. + v := dataVal.Field(i) + if !v.Type().AssignableTo(valMap.Type().Elem()) { + return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) + } + + tagValue := f.Tag.Get(d.config.TagName) + keyName := f.Name + + if tagValue == "" && d.config.IgnoreUntaggedFields { + continue + } + + // If Squash is set in the config, we squash the field down. + squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous + + v = dereferencePtrToStructIfNeeded(v, d.config.TagName) + + // Determine the name of the key in the map + if index := strings.Index(tagValue, ","); index != -1 { + if tagValue[:index] == "-" { + continue + } + // If "omitempty" is specified in the tag, it ignores empty values. + if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) { + continue + } + + // If "squash" is specified in the tag, we squash the field down. + squash = squash || strings.Index(tagValue[index+1:], "squash") != -1 + if squash { + // When squashing, the embedded type can be a pointer to a struct. + if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { + v = v.Elem() + } + + // The final type must be a struct + if v.Kind() != reflect.Struct { + return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) + } + } else { + if strings.Index(tagValue[index+1:], "remain") != -1 { + if v.Kind() != reflect.Map { + return fmt.Errorf("error remain-tag field with invalid type: '%s'", v.Type()) + } + + ptr := v.MapRange() + for ptr.Next() { + valMap.SetMapIndex(ptr.Key(), ptr.Value()) + } + continue + } + } + if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" { + keyName = keyNameTagValue + } + } else if len(tagValue) > 0 { + if tagValue == "-" { + continue + } + keyName = tagValue + } + + switch v.Kind() { + // this is an embedded struct, so handle it differently + case reflect.Struct: + x := reflect.New(v.Type()) + x.Elem().Set(v) + + vType := valMap.Type() + vKeyType := vType.Key() + vElemType := vType.Elem() + mType := reflect.MapOf(vKeyType, vElemType) + vMap := reflect.MakeMap(mType) + + // Creating a pointer to a map so that other methods can completely + // overwrite the map if need be (looking at you decodeMapFromMap). The + // indirection allows the underlying map to be settable (CanSet() == true) + // where as reflect.MakeMap returns an unsettable map. + addrVal := reflect.New(vMap.Type()) + reflect.Indirect(addrVal).Set(vMap) + + err := d.decode(keyName, x.Interface(), reflect.Indirect(addrVal)) + if err != nil { + return err + } + + // the underlying map may have been completely overwritten so pull + // it indirectly out of the enclosing value. + vMap = reflect.Indirect(addrVal) + + if squash { + for _, k := range vMap.MapKeys() { + valMap.SetMapIndex(k, vMap.MapIndex(k)) + } + } else { + valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) + } + + default: + valMap.SetMapIndex(reflect.ValueOf(keyName), v) + } + } + + if val.CanAddr() { + val.Set(valMap) + } + + return nil +} + +func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) (bool, error) { + // If the input data is nil, then we want to just set the output + // pointer to be nil as well. + isNil := data == nil + if !isNil { + switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() { + case reflect.Chan, + reflect.Func, + reflect.Interface, + reflect.Map, + reflect.Ptr, + reflect.Slice: + isNil = v.IsNil() + } + } + if isNil { + if !val.IsNil() && val.CanSet() { + nilValue := reflect.New(val.Type()).Elem() + val.Set(nilValue) + } + + return true, nil + } + + // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + valType := val.Type() + valElemType := valType.Elem() + if val.CanSet() { + realVal := val + if realVal.IsNil() || d.config.ZeroFields { + realVal = reflect.New(valElemType) + } + + if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { + return false, err + } + + val.Set(realVal) + } else { + if err := d.decode(name, data, reflect.Indirect(val)); err != nil { + return false, err + } + } + return false, nil +} + +func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { + // Create an element of the concrete (non pointer) type and decode + // into that. Then set the value of the pointer to this type. + dataVal := reflect.Indirect(reflect.ValueOf(data)) + if val.Type() != dataVal.Type() { + return fmt.Errorf( + "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", + name, val.Type(), dataVal.Type(), data) + } + val.Set(dataVal) + return nil +} + +func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + sliceType := reflect.SliceOf(valElemType) + + // If we have a non array/slice type then we first attempt to convert. + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Slice and array we use the normal logic + case dataValKind == reflect.Slice, dataValKind == reflect.Array: + break + + // Empty maps turn into empty slices + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.MakeSlice(sliceType, 0, 0)) + return nil + } + // Create slice of maps of other sizes + return d.decodeSlice(name, []interface{}{data}, val) + + case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: + return d.decodeSlice(name, []byte(dataVal.String()), val) + + // All other types we try to convert to the slice type + // and "lift" it into it. i.e. a string becomes a string slice. + default: + // Just re-try this function with data as a slice. + return d.decodeSlice(name, []interface{}{data}, val) + } + } + + return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + } + + // If the input value is nil, then don't allocate since empty != nil + if dataValKind != reflect.Array && dataVal.IsNil() { + return nil + } + + valSlice := val + if valSlice.IsNil() || d.config.ZeroFields { + // Make a new slice to hold our result, same size as the original data. + valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) + } else if valSlice.Len() > dataVal.Len() { + valSlice = valSlice.Slice(0, dataVal.Len()) + } + + // Accumulate any errors + var errs []error + + for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + for valSlice.Len() <= i { + valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) + } + currentField := valSlice.Index(i) + + fieldName := name + "[" + strconv.Itoa(i) + "]" + if err := d.decode(fieldName, currentData, currentField); err != nil { + errs = append(errs, err) + } + } + + // Finally, set the value to the slice we built up + val.Set(valSlice) + + return errors.Join(errs...) +} + +func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + arrayType := reflect.ArrayOf(valType.Len(), valElemType) + + valArray := val + + if isComparable(valArray) && valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields { + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Empty maps turn into empty arrays + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.Zero(arrayType)) + return nil + } + + // All other types we try to convert to the array type + // and "lift" it into it. i.e. a string becomes a string array. + default: + // Just re-try this function with data as a slice. + return d.decodeArray(name, []interface{}{data}, val) + } + } + + return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + + } + if dataVal.Len() > arrayType.Len() { + return fmt.Errorf( + "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) + } + + // Make a new array to hold our result, same size as the original data. + valArray = reflect.New(arrayType).Elem() + } + + // Accumulate any errors + var errs []error + + for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + currentField := valArray.Index(i) + + fieldName := name + "[" + strconv.Itoa(i) + "]" + if err := d.decode(fieldName, currentData, currentField); err != nil { + errs = append(errs, err) + } + } + + // Finally, set the value to the array we built up + val.Set(valArray) + + return errors.Join(errs...) +} + +func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + + // If the type of the value to write to and the data match directly, + // then we just set it directly instead of recursing into the structure. + if dataVal.Type() == val.Type() { + val.Set(dataVal) + return nil + } + + dataValKind := dataVal.Kind() + switch dataValKind { + case reflect.Map: + return d.decodeStructFromMap(name, dataVal, val) + + case reflect.Struct: + // Not the most efficient way to do this but we can optimize later if + // we want to. To convert from struct to struct we go to map first + // as an intermediary. + + // Make a new map to hold our result + mapType := reflect.TypeOf((map[string]interface{})(nil)) + mval := reflect.MakeMap(mapType) + + // Creating a pointer to a map so that other methods can completely + // overwrite the map if need be (looking at you decodeMapFromMap). The + // indirection allows the underlying map to be settable (CanSet() == true) + // where as reflect.MakeMap returns an unsettable map. + addrVal := reflect.New(mval.Type()) + + reflect.Indirect(addrVal).Set(mval) + if err := d.decodeMapFromStruct(name, dataVal, reflect.Indirect(addrVal), mval); err != nil { + return err + } + + result := d.decodeStructFromMap(name, reflect.Indirect(addrVal), val) + return result + + default: + return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) + } +} + +func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error { + dataValType := dataVal.Type() + if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { + return fmt.Errorf( + "'%s' needs a map with string keys, has '%s' keys", + name, dataValType.Key().Kind()) + } + + dataValKeys := make(map[reflect.Value]struct{}) + dataValKeysUnused := make(map[interface{}]struct{}) + for _, dataValKey := range dataVal.MapKeys() { + dataValKeys[dataValKey] = struct{}{} + dataValKeysUnused[dataValKey.Interface()] = struct{}{} + } + + targetValKeysUnused := make(map[interface{}]struct{}) + + var errs []error + + // This slice will keep track of all the structs we'll be decoding. + // There can be more than one struct if there are embedded structs + // that are squashed. + structs := make([]reflect.Value, 1, 5) + structs[0] = val + + // Compile the list of all the fields that we're going to be decoding + // from all the structs. + type field struct { + field reflect.StructField + val reflect.Value + } + + // remainField is set to a valid field set with the "remain" tag if + // we are keeping track of remaining values. + var remainField *field + + fields := []field{} + for len(structs) > 0 { + structVal := structs[0] + structs = structs[1:] + + structType := structVal.Type() + + for i := 0; i < structType.NumField(); i++ { + fieldType := structType.Field(i) + fieldVal := structVal.Field(i) + if fieldVal.Kind() == reflect.Ptr && fieldVal.Elem().Kind() == reflect.Struct { + // Handle embedded struct pointers as embedded structs. + fieldVal = fieldVal.Elem() + } + + // If "squash" is specified in the tag, we squash the field down. + squash := d.config.Squash && fieldVal.Kind() == reflect.Struct && fieldType.Anonymous + remain := false + + // We always parse the tags cause we're looking for other tags too + tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") + for _, tag := range tagParts[1:] { + if tag == "squash" { + squash = true + break + } + + if tag == "remain" { + remain = true + break + } + } + + if squash { + if fieldVal.Kind() != reflect.Struct { + errs = append(errs, fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldVal.Kind())) + } else { + structs = append(structs, fieldVal) + } + continue + } + + // Build our field + if remain { + remainField = &field{fieldType, fieldVal} + } else { + // Normal struct field, store it away + fields = append(fields, field{fieldType, fieldVal}) + } + } + } + + // for fieldType, field := range fields { + for _, f := range fields { + field, fieldValue := f.field, f.val + fieldName := field.Name + + tagValue := field.Tag.Get(d.config.TagName) + if tagValue == "" && d.config.IgnoreUntaggedFields { + continue + } + tagValue = strings.SplitN(tagValue, ",", 2)[0] + if tagValue != "" { + fieldName = tagValue + } + + rawMapKey := reflect.ValueOf(fieldName) + rawMapVal := dataVal.MapIndex(rawMapKey) + if !rawMapVal.IsValid() { + // Do a slower search by iterating over each key and + // doing case-insensitive search. + for dataValKey := range dataValKeys { + mK, ok := dataValKey.Interface().(string) + if !ok { + // Not a string key + continue + } + + if d.config.MatchName(mK, fieldName) { + rawMapKey = dataValKey + rawMapVal = dataVal.MapIndex(dataValKey) + break + } + } + + if !rawMapVal.IsValid() { + // There was no matching key in the map for the value in + // the struct. Remember it for potential errors and metadata. + targetValKeysUnused[fieldName] = struct{}{} + continue + } + } + + if !fieldValue.IsValid() { + // This should never happen + panic("field is not valid") + } + + // If we can't set the field, then it is unexported or something, + // and we just continue onwards. + if !fieldValue.CanSet() { + continue + } + + // Delete the key we're using from the unused map so we stop tracking + delete(dataValKeysUnused, rawMapKey.Interface()) + + // If the name is empty string, then we're at the root, and we + // don't dot-join the fields. + if name != "" { + fieldName = name + "." + fieldName + } + + if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil { + errs = append(errs, err) + } + } + + // If we have a "remain"-tagged field and we have unused keys then + // we put the unused keys directly into the remain field. + if remainField != nil && len(dataValKeysUnused) > 0 { + // Build a map of only the unused values + remain := map[interface{}]interface{}{} + for key := range dataValKeysUnused { + remain[key] = dataVal.MapIndex(reflect.ValueOf(key)).Interface() + } + + // Decode it as-if we were just decoding this map onto our map. + if err := d.decodeMap(name, remain, remainField.val); err != nil { + errs = append(errs, err) + } + + // Set the map to nil so we have none so that the next check will + // not error (ErrorUnused) + dataValKeysUnused = nil + } + + if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { + keys := make([]string, 0, len(dataValKeysUnused)) + for rawKey := range dataValKeysUnused { + keys = append(keys, rawKey.(string)) + } + sort.Strings(keys) + + err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", ")) + errs = append(errs, err) + } + + if d.config.ErrorUnset && len(targetValKeysUnused) > 0 { + keys := make([]string, 0, len(targetValKeysUnused)) + for rawKey := range targetValKeysUnused { + keys = append(keys, rawKey.(string)) + } + sort.Strings(keys) + + err := fmt.Errorf("'%s' has unset fields: %s", name, strings.Join(keys, ", ")) + errs = append(errs, err) + } + + if err := errors.Join(errs...); err != nil { + return err + } + + // Add the unused keys to the list of unused keys if we're tracking metadata + if d.config.Metadata != nil { + for rawKey := range dataValKeysUnused { + key := rawKey.(string) + if name != "" { + key = name + "." + key + } + + d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) + } + for rawKey := range targetValKeysUnused { + key := rawKey.(string) + if name != "" { + key = name + "." + key + } + + d.config.Metadata.Unset = append(d.config.Metadata.Unset, key) + } + } + + return nil +} + +func isEmptyValue(v reflect.Value) bool { + switch getKind(v) { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} + +func getKind(val reflect.Value) reflect.Kind { + kind := val.Kind() + + switch { + case kind >= reflect.Int && kind <= reflect.Int64: + return reflect.Int + case kind >= reflect.Uint && kind <= reflect.Uint64: + return reflect.Uint + case kind >= reflect.Float32 && kind <= reflect.Float64: + return reflect.Float32 + case kind >= reflect.Complex64 && kind <= reflect.Complex128: + return reflect.Complex64 + default: + return kind + } +} + +func isStructTypeConvertibleToMap(typ reflect.Type, checkMapstructureTags bool, tagName string) bool { + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if f.PkgPath == "" && !checkMapstructureTags { // check for unexported fields + return true + } + if checkMapstructureTags && f.Tag.Get(tagName) != "" { // check for mapstructure tags inside + return true + } + } + return false +} + +func dereferencePtrToStructIfNeeded(v reflect.Value, tagName string) reflect.Value { + if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct { + return v + } + deref := v.Elem() + derefT := deref.Type() + if isStructTypeConvertibleToMap(derefT, true, tagName) { + return deref + } + return v +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_19.go b/tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_19.go new file mode 100644 index 000000000..d0913fff6 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_19.go @@ -0,0 +1,44 @@ +//go:build !go1.20 + +package mapstructure + +import "reflect" + +func isComparable(v reflect.Value) bool { + k := v.Kind() + switch k { + case reflect.Invalid: + return false + + case reflect.Array: + switch v.Type().Elem().Kind() { + case reflect.Interface, reflect.Array, reflect.Struct: + for i := 0; i < v.Type().Len(); i++ { + // if !v.Index(i).Comparable() { + if !isComparable(v.Index(i)) { + return false + } + } + return true + } + return v.Type().Comparable() + + case reflect.Interface: + // return v.Elem().Comparable() + return isComparable(v.Elem()) + + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + return false + + // if !v.Field(i).Comparable() { + if !isComparable(v.Field(i)) { + return false + } + } + return true + + default: + return v.Type().Comparable() + } +} diff --git a/tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_20.go b/tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_20.go new file mode 100644 index 000000000..f8255a1b1 --- /dev/null +++ b/tools/vendor/github.com/go-viper/mapstructure/v2/reflect_go1_20.go @@ -0,0 +1,10 @@ +//go:build go1.20 + +package mapstructure + +import "reflect" + +// TODO: remove once we drop support for Go <1.20 +func isComparable(v reflect.Value) bool { + return v.Comparable() +} diff --git a/tools/vendor/github.com/gofrs/flock/.golangci.yml b/tools/vendor/github.com/gofrs/flock/.golangci.yml new file mode 100644 index 000000000..3ad88a38f --- /dev/null +++ b/tools/vendor/github.com/gofrs/flock/.golangci.yml @@ -0,0 +1,114 @@ +run: + timeout: 10m + +linters: + enable: + - asasalint + - bidichk + - dogsled + - dupword + - durationcheck + - err113 + - errname + - errorlint + - fatcontext + - forbidigo + - gocheckcompilerdirectives + - gochecknoinits + - gocritic + - godot + - godox + - gofumpt + - goheader + - goimports + - gomoddirectives + - goprintffuncname + - gosec + - inamedparam + - interfacebloat + - ireturn + - mirror + - misspell + - nolintlint + - revive + - stylecheck + - tenv + - testifylint + - thelper + - unconvert + - unparam + - usestdlibvars + - whitespace + +linters-settings: + misspell: + locale: US + godox: + keywords: + - FIXME + goheader: + template: |- + Copyright 2015 Tim Heckman. All rights reserved. + Copyright 2018-{{ YEAR }} The Gofrs. All rights reserved. + Use of this source code is governed by the BSD 3-Clause + license that can be found in the LICENSE file. + gofumpt: + extra-rules: true + gocritic: + enabled-tags: + - diagnostic + - style + - performance + disabled-checks: + - paramTypeCombine # already handle by gofumpt.extra-rules + - whyNoLint # already handle by nonolint + - unnamedResult + - hugeParam + - sloppyReassign + - rangeValCopy + - octalLiteral + - ptrToRefParam + - appendAssign + - ruleguard + - httpNoBody + - exposedSyncMutex + + revive: + rules: + - name: struct-tag + - name: blank-imports + - name: context-as-argument + - name: context-keys-type + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: exported + - name: if-return + - name: increment-decrement + - name: var-naming + - name: var-declaration + - name: package-comments + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf + - name: empty-block + - name: superfluous-else + - name: unused-parameter + - name: unreachable-code + - name: redefines-builtin-id + +issues: + exclude-use-default: true + max-issues-per-linter: 0 + max-same-issues: 0 + +output: + show-stats: true + sort-results: true + sort-order: + - linter + - file diff --git a/tools/vendor/github.com/gofrs/flock/.travis.yml b/tools/vendor/github.com/gofrs/flock/.travis.yml deleted file mode 100644 index b16d040fa..000000000 --- a/tools/vendor/github.com/gofrs/flock/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go: - - 1.14.x - - 1.15.x -script: go test -v -check.vv -race ./... -sudo: false -notifications: - email: - on_success: never - on_failure: always diff --git a/tools/vendor/github.com/gofrs/flock/LICENSE b/tools/vendor/github.com/gofrs/flock/LICENSE index 8b8ff36fe..7de525bf0 100644 --- a/tools/vendor/github.com/gofrs/flock/LICENSE +++ b/tools/vendor/github.com/gofrs/flock/LICENSE @@ -1,3 +1,4 @@ +Copyright (c) 2018-2024, The Gofrs Copyright (c) 2015-2020, Tim Heckman All rights reserved. diff --git a/tools/vendor/github.com/gofrs/flock/Makefile b/tools/vendor/github.com/gofrs/flock/Makefile new file mode 100644 index 000000000..65c139d68 --- /dev/null +++ b/tools/vendor/github.com/gofrs/flock/Makefile @@ -0,0 +1,15 @@ +.PHONY: lint test test_race build_cross_os + +default: lint test build_cross_os + +test: + go test -v -cover ./... + +test_race: + CGO_ENABLED=1 go test -v -race ./... + +lint: + golangci-lint run + +build_cross_os: + ./build.sh diff --git a/tools/vendor/github.com/gofrs/flock/README.md b/tools/vendor/github.com/gofrs/flock/README.md index 71ce63692..f7ca0dd9c 100644 --- a/tools/vendor/github.com/gofrs/flock/README.md +++ b/tools/vendor/github.com/gofrs/flock/README.md @@ -1,26 +1,22 @@ # flock -[![TravisCI Build Status](https://img.shields.io/travis/gofrs/flock/master.svg?style=flat)](https://travis-ci.org/gofrs/flock) -[![GoDoc](https://img.shields.io/badge/godoc-flock-blue.svg?style=flat)](https://godoc.org/github.com/gofrs/flock) -[![License](https://img.shields.io/badge/license-BSD_3--Clause-brightgreen.svg?style=flat)](https://github.com/gofrs/flock/blob/master/LICENSE) -[![Go Report Card](https://goreportcard.com/badge/github.com/gofrs/flock)](https://goreportcard.com/report/github.com/gofrs/flock) -`flock` implements a thread-safe sync.Locker interface for file locking. It also -includes a non-blocking TryLock() function to allow locking without blocking execution. +[![Go Reference](https://pkg.go.dev/badge/github.com/gofrs/flock.svg)](https://pkg.go.dev/github.com/gofrs/flock) +[![License](https://img.shields.io/badge/license-BSD_3--Clause-brightgreen.svg?style=flat)](https://github.com/gofrs/flock/blob/main/LICENSE) +[![Go Report Card](https://goreportcard.com/badge/github.com/gofrs/flock)](https://goreportcard.com/report/github.com/gofrs/flock) -## License -`flock` is released under the BSD 3-Clause License. See the `LICENSE` file for more details. +`flock` implements a thread-safe file lock. -## Go Compatibility -This package makes use of the `context` package that was introduced in Go 1.7. As such, this -package has an implicit dependency on Go 1.7+. +It also includes a non-blocking `TryLock()` function to allow locking without blocking execution. ## Installation -``` + +```bash go get -u github.com/gofrs/flock ``` ## Usage -```Go + +```go import "github.com/gofrs/flock" fileLock := flock.New("/var/lock/go-lock.lock") @@ -38,4 +34,12 @@ if locked { ``` For more detailed usage information take a look at the package API docs on -[GoDoc](https://godoc.org/github.com/gofrs/flock). +[GoDoc](https://pkg.go.dev/github.com/gofrs/flock). + +## License + +`flock` is released under the BSD 3-Clause License. See the [`LICENSE`](./LICENSE) file for more details. + +## Project History + +This project was originally `github.com/theckman/go-flock`, it was transferred to Gofrs by the original author [Tim Heckman ](https://github.com/theckman). diff --git a/tools/vendor/github.com/gofrs/flock/SECURITY.md b/tools/vendor/github.com/gofrs/flock/SECURITY.md new file mode 100644 index 000000000..01419bd59 --- /dev/null +++ b/tools/vendor/github.com/gofrs/flock/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +We support the latest version of this library. +We do not guarantee support of previous versions. + +If a defect is reported, it will generally be fixed on the latest version (provided it exists) irrespective of whether it was introduced in a prior version. + +## Reporting a Vulnerability + +To report a potential security vulnerability, please create a [security advisory](https://github.com/gofrs/flock/security/advisories/new). + +For us to respond to your report most effectively, please include any of the following: + +- Steps to reproduce or a proof-of-concept +- Any relevant information, including the versions used + +## Security Scorecard + +This project submits security [results](https://scorecard.dev/viewer/?uri=github.com/gofrs/flock) to the [OpenSSF Scorecard](https://securityscorecards.dev/). diff --git a/tools/vendor/github.com/gofrs/flock/appveyor.yml b/tools/vendor/github.com/gofrs/flock/appveyor.yml deleted file mode 100644 index 909b4bf7c..000000000 --- a/tools/vendor/github.com/gofrs/flock/appveyor.yml +++ /dev/null @@ -1,25 +0,0 @@ -version: '{build}' - -build: false -deploy: false - -clone_folder: 'c:\gopath\src\github.com\gofrs\flock' - -environment: - GOPATH: 'c:\gopath' - GOVERSION: '1.15' - -init: - - git config --global core.autocrlf input - -install: - - rmdir c:\go /s /q - - appveyor DownloadFile https://storage.googleapis.com/golang/go%GOVERSION%.windows-amd64.msi - - msiexec /i go%GOVERSION%.windows-amd64.msi /q - - set Path=c:\go\bin;c:\gopath\bin;%Path% - - go version - - go env - -test_script: - - go get -t ./... - - go test -race -v ./... diff --git a/tools/vendor/github.com/gofrs/flock/build.sh b/tools/vendor/github.com/gofrs/flock/build.sh new file mode 100644 index 000000000..60f7809f0 --- /dev/null +++ b/tools/vendor/github.com/gofrs/flock/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash -e + +# Not supported by flock: +# - plan9/* +# - js/wasm +# - wasp1/wasm + +for row in $(go tool dist list -json | jq -r '.[] | @base64'); do + _jq() { + echo ${row} | base64 --decode | jq -r ${1} + } + + GOOS=$(_jq '.GOOS') + GOARCH=$(_jq '.GOARCH') + + echo "$GOOS/$GOARCH" + GOOS=$GOOS GOARCH=$GOARCH go build +done diff --git a/tools/vendor/github.com/gofrs/flock/flock.go b/tools/vendor/github.com/gofrs/flock/flock.go index 95c784ca5..ff942b228 100644 --- a/tools/vendor/github.com/gofrs/flock/flock.go +++ b/tools/vendor/github.com/gofrs/flock/flock.go @@ -1,4 +1,5 @@ // Copyright 2015 Tim Heckman. All rights reserved. +// Copyright 2018-2024 The Gofrs. All rights reserved. // Use of this source code is governed by the BSD 3-Clause // license that can be found in the LICENSE file. @@ -18,12 +19,29 @@ package flock import ( "context" + "io/fs" "os" "runtime" "sync" "time" ) +type Option func(f *Flock) + +// SetFlag sets the flag used to create/open the file. +func SetFlag(flag int) Option { + return func(f *Flock) { + f.flag = flag + } +} + +// SetPermissions sets the OS permissions to set on the file. +func SetPermissions(perm fs.FileMode) Option { + return func(f *Flock) { + f.perm = perm + } +} + // Flock is the struct type to handle file locking. All fields are unexported, // with access to some of the fields provided by getter methods (Path() and Locked()). type Flock struct { @@ -32,12 +50,37 @@ type Flock struct { fh *os.File l bool r bool + + // flag is the flag used to create/open the file. + flag int + // perm is the OS permissions to set on the file. + perm fs.FileMode } // New returns a new instance of *Flock. The only parameter // it takes is the path to the desired lockfile. -func New(path string) *Flock { - return &Flock{path: path} +func New(path string, opts ...Option) *Flock { + // create it if it doesn't exist, and open the file read-only. + flags := os.O_CREATE + switch runtime.GOOS { + case "aix", "solaris", "illumos": + // AIX cannot preform write-lock (i.e. exclusive) on a read-only file. + flags |= os.O_RDWR + default: + flags |= os.O_RDONLY + } + + f := &Flock{ + path: path, + flag: flags, + perm: fs.FileMode(0o600), + } + + for _, opt := range opts { + opt(f) + } + + return f } // NewFlock returns a new instance of *Flock. The only parameter @@ -67,6 +110,7 @@ func (f *Flock) Path() string { func (f *Flock) Locked() bool { f.m.RLock() defer f.m.RUnlock() + return f.l } @@ -76,6 +120,7 @@ func (f *Flock) Locked() bool { func (f *Flock) RLocked() bool { f.m.RLock() defer f.m.RUnlock() + return f.r } @@ -83,16 +128,18 @@ func (f *Flock) String() string { return f.path } -// TryLockContext repeatedly tries to take an exclusive lock until one of the -// conditions is met: TryLock succeeds, TryLock fails with error, or Context -// Done channel is closed. +// TryLockContext repeatedly tries to take an exclusive lock until one of the conditions is met: +// - TryLock succeeds +// - TryLock fails with error +// - Context Done channel is closed. func (f *Flock) TryLockContext(ctx context.Context, retryDelay time.Duration) (bool, error) { return tryCtx(ctx, f.TryLock, retryDelay) } -// TryRLockContext repeatedly tries to take a shared lock until one of the -// conditions is met: TryRLock succeeds, TryRLock fails with error, or Context -// Done channel is closed. +// TryRLockContext repeatedly tries to take a shared lock until one of the conditions is met: +// - TryRLock succeeds +// - TryRLock fails with error +// - Context Done channel is closed. func (f *Flock) TryRLockContext(ctx context.Context, retryDelay time.Duration) (bool, error) { return tryCtx(ctx, f.TryRLock, retryDelay) } @@ -101,10 +148,12 @@ func tryCtx(ctx context.Context, fn func() (bool, error), retryDelay time.Durati if ctx.Err() != nil { return false, ctx.Err() } + for { if ok, err := fn(); ok || err != nil { return ok, err } + select { case <-ctx.Done(): return false, ctx.Err() @@ -114,31 +163,44 @@ func tryCtx(ctx context.Context, fn func() (bool, error), retryDelay time.Durati } } -func (f *Flock) setFh() error { +func (f *Flock) setFh(flag int) error { // open a new os.File instance - // create it if it doesn't exist, and open the file read-only. - flags := os.O_CREATE - if runtime.GOOS == "aix" { - // AIX cannot preform write-lock (ie exclusive) on a - // read-only file. - flags |= os.O_RDWR - } else { - flags |= os.O_RDONLY - } - fh, err := os.OpenFile(f.path, flags, os.FileMode(0600)) + fh, err := os.OpenFile(f.path, flag, f.perm) if err != nil { return err } - // set the filehandle on the struct + // set the file handle on the struct f.fh = fh + return nil } -// ensure the file handle is closed if no lock is held +// resetFh resets file handle: +// - tries to close the file (ignore errors) +// - sets fh to nil. +func (f *Flock) resetFh() { + if f.fh == nil { + return + } + + _ = f.fh.Close() + + f.fh = nil +} + +// ensure the file handle is closed if no lock is held. func (f *Flock) ensureFhState() { - if !f.l && !f.r && f.fh != nil { - f.fh.Close() - f.fh = nil + if f.l || f.r || f.fh == nil { + return } + + f.resetFh() +} + +func (f *Flock) reset() { + f.l = false + f.r = false + + f.resetFh() } diff --git a/tools/vendor/github.com/gofrs/flock/flock_aix.go b/tools/vendor/github.com/gofrs/flock/flock_aix.go deleted file mode 100644 index 7277c1b6b..000000000 --- a/tools/vendor/github.com/gofrs/flock/flock_aix.go +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright 2019 Tim Heckman. All rights reserved. Use of this source code is -// governed by the BSD 3-Clause license that can be found in the LICENSE file. - -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code implements the filelock API using POSIX 'fcntl' locks, which attach -// to an (inode, process) pair rather than a file descriptor. To avoid unlocking -// files prematurely when the same file is opened through different descriptors, -// we allow only one read-lock at a time. -// -// This code is adapted from the Go package: -// cmd/go/internal/lockedfile/internal/filelock - -//+build aix - -package flock - -import ( - "errors" - "io" - "os" - "sync" - "syscall" - - "golang.org/x/sys/unix" -) - -type lockType int16 - -const ( - readLock lockType = unix.F_RDLCK - writeLock lockType = unix.F_WRLCK -) - -type cmdType int - -const ( - tryLock cmdType = unix.F_SETLK - waitLock cmdType = unix.F_SETLKW -) - -type inode = uint64 - -type inodeLock struct { - owner *Flock - queue []<-chan *Flock -} - -var ( - mu sync.Mutex - inodes = map[*Flock]inode{} - locks = map[inode]inodeLock{} -) - -// Lock is a blocking call to try and take an exclusive file lock. It will wait -// until it is able to obtain the exclusive file lock. It's recommended that -// TryLock() be used over this function. This function may block the ability to -// query the current Locked() or RLocked() status due to a RW-mutex lock. -// -// If we are already exclusive-locked, this function short-circuits and returns -// immediately assuming it can take the mutex lock. -// -// If the *Flock has a shared lock (RLock), this may transparently replace the -// shared lock with an exclusive lock on some UNIX-like operating systems. Be -// careful when using exclusive locks in conjunction with shared locks -// (RLock()), because calling Unlock() may accidentally release the exclusive -// lock that was once a shared lock. -func (f *Flock) Lock() error { - return f.lock(&f.l, writeLock) -} - -// RLock is a blocking call to try and take a shared file lock. It will wait -// until it is able to obtain the shared file lock. It's recommended that -// TryRLock() be used over this function. This function may block the ability to -// query the current Locked() or RLocked() status due to a RW-mutex lock. -// -// If we are already shared-locked, this function short-circuits and returns -// immediately assuming it can take the mutex lock. -func (f *Flock) RLock() error { - return f.lock(&f.r, readLock) -} - -func (f *Flock) lock(locked *bool, flag lockType) error { - f.m.Lock() - defer f.m.Unlock() - - if *locked { - return nil - } - - if f.fh == nil { - if err := f.setFh(); err != nil { - return err - } - defer f.ensureFhState() - } - - if _, err := f.doLock(waitLock, flag, true); err != nil { - return err - } - - *locked = true - return nil -} - -func (f *Flock) doLock(cmd cmdType, lt lockType, blocking bool) (bool, error) { - // POSIX locks apply per inode and process, and the lock for an inode is - // released when *any* descriptor for that inode is closed. So we need to - // synchronize access to each inode internally, and must serialize lock and - // unlock calls that refer to the same inode through different descriptors. - fi, err := f.fh.Stat() - if err != nil { - return false, err - } - ino := inode(fi.Sys().(*syscall.Stat_t).Ino) - - mu.Lock() - if i, dup := inodes[f]; dup && i != ino { - mu.Unlock() - return false, &os.PathError{ - Path: f.Path(), - Err: errors.New("inode for file changed since last Lock or RLock"), - } - } - - inodes[f] = ino - - var wait chan *Flock - l := locks[ino] - if l.owner == f { - // This file already owns the lock, but the call may change its lock type. - } else if l.owner == nil { - // No owner: it's ours now. - l.owner = f - } else if !blocking { - // Already owned: cannot take the lock. - mu.Unlock() - return false, nil - } else { - // Already owned: add a channel to wait on. - wait = make(chan *Flock) - l.queue = append(l.queue, wait) - } - locks[ino] = l - mu.Unlock() - - if wait != nil { - wait <- f - } - - err = setlkw(f.fh.Fd(), cmd, lt) - - if err != nil { - f.doUnlock() - if cmd == tryLock && err == unix.EACCES { - return false, nil - } - return false, err - } - - return true, nil -} - -func (f *Flock) Unlock() error { - f.m.Lock() - defer f.m.Unlock() - - // if we aren't locked or if the lockfile instance is nil - // just return a nil error because we are unlocked - if (!f.l && !f.r) || f.fh == nil { - return nil - } - - if err := f.doUnlock(); err != nil { - return err - } - - f.fh.Close() - - f.l = false - f.r = false - f.fh = nil - - return nil -} - -func (f *Flock) doUnlock() (err error) { - var owner *Flock - mu.Lock() - ino, ok := inodes[f] - if ok { - owner = locks[ino].owner - } - mu.Unlock() - - if owner == f { - err = setlkw(f.fh.Fd(), waitLock, unix.F_UNLCK) - } - - mu.Lock() - l := locks[ino] - if len(l.queue) == 0 { - // No waiters: remove the map entry. - delete(locks, ino) - } else { - // The first waiter is sending us their file now. - // Receive it and update the queue. - l.owner = <-l.queue[0] - l.queue = l.queue[1:] - locks[ino] = l - } - delete(inodes, f) - mu.Unlock() - - return err -} - -// TryLock is the preferred function for taking an exclusive file lock. This -// function takes an RW-mutex lock before it tries to lock the file, so there is -// the possibility that this function may block for a short time if another -// goroutine is trying to take any action. -// -// The actual file lock is non-blocking. If we are unable to get the exclusive -// file lock, the function will return false instead of waiting for the lock. If -// we get the lock, we also set the *Flock instance as being exclusive-locked. -func (f *Flock) TryLock() (bool, error) { - return f.try(&f.l, writeLock) -} - -// TryRLock is the preferred function for taking a shared file lock. This -// function takes an RW-mutex lock before it tries to lock the file, so there is -// the possibility that this function may block for a short time if another -// goroutine is trying to take any action. -// -// The actual file lock is non-blocking. If we are unable to get the shared file -// lock, the function will return false instead of waiting for the lock. If we -// get the lock, we also set the *Flock instance as being share-locked. -func (f *Flock) TryRLock() (bool, error) { - return f.try(&f.r, readLock) -} - -func (f *Flock) try(locked *bool, flag lockType) (bool, error) { - f.m.Lock() - defer f.m.Unlock() - - if *locked { - return true, nil - } - - if f.fh == nil { - if err := f.setFh(); err != nil { - return false, err - } - defer f.ensureFhState() - } - - haslock, err := f.doLock(tryLock, flag, false) - if err != nil { - return false, err - } - - *locked = haslock - return haslock, nil -} - -// setlkw calls FcntlFlock with cmd for the entire file indicated by fd. -func setlkw(fd uintptr, cmd cmdType, lt lockType) error { - for { - err := unix.FcntlFlock(fd, int(cmd), &unix.Flock_t{ - Type: int16(lt), - Whence: io.SeekStart, - Start: 0, - Len: 0, // All bytes. - }) - if err != unix.EINTR { - return err - } - } -} diff --git a/tools/vendor/github.com/gofrs/flock/flock_others.go b/tools/vendor/github.com/gofrs/flock/flock_others.go new file mode 100644 index 000000000..18b14f1bd --- /dev/null +++ b/tools/vendor/github.com/gofrs/flock/flock_others.go @@ -0,0 +1,40 @@ +//go:build (!unix && !windows) || plan9 + +package flock + +import ( + "errors" + "io/fs" +) + +func (f *Flock) Lock() error { + return &fs.PathError{ + Op: "Lock", + Path: f.Path(), + Err: errors.ErrUnsupported, + } +} + +func (f *Flock) RLock() error { + return &fs.PathError{ + Op: "RLock", + Path: f.Path(), + Err: errors.ErrUnsupported, + } +} + +func (f *Flock) Unlock() error { + return &fs.PathError{ + Op: "Unlock", + Path: f.Path(), + Err: errors.ErrUnsupported, + } +} + +func (f *Flock) TryLock() (bool, error) { + return false, f.Lock() +} + +func (f *Flock) TryRLock() (bool, error) { + return false, f.RLock() +} diff --git a/tools/vendor/github.com/gofrs/flock/flock_unix.go b/tools/vendor/github.com/gofrs/flock/flock_unix.go index c315a3e29..cf8919c7a 100644 --- a/tools/vendor/github.com/gofrs/flock/flock_unix.go +++ b/tools/vendor/github.com/gofrs/flock/flock_unix.go @@ -1,42 +1,44 @@ // Copyright 2015 Tim Heckman. All rights reserved. +// Copyright 2018-2024 The Gofrs. All rights reserved. // Use of this source code is governed by the BSD 3-Clause // license that can be found in the LICENSE file. -// +build !aix,!windows +//go:build darwin || dragonfly || freebsd || illumos || linux || netbsd || openbsd package flock import ( + "errors" "os" - "syscall" + + "golang.org/x/sys/unix" ) -// Lock is a blocking call to try and take an exclusive file lock. It will wait -// until it is able to obtain the exclusive file lock. It's recommended that -// TryLock() be used over this function. This function may block the ability to -// query the current Locked() or RLocked() status due to a RW-mutex lock. +// Lock is a blocking call to try and take an exclusive file lock. +// It will wait until it is able to obtain the exclusive file lock. +// It's recommended that TryLock() be used over this function. +// This function may block the ability to query the current Locked() or RLocked() status due to a RW-mutex lock. // -// If we are already exclusive-locked, this function short-circuits and returns -// immediately assuming it can take the mutex lock. +// If we are already exclusive-locked, +// this function short-circuits and returns immediately assuming it can take the mutex lock. // -// If the *Flock has a shared lock (RLock), this may transparently replace the -// shared lock with an exclusive lock on some UNIX-like operating systems. Be -// careful when using exclusive locks in conjunction with shared locks -// (RLock()), because calling Unlock() may accidentally release the exclusive -// lock that was once a shared lock. +// If the *Flock has a shared lock (RLock), +// this may transparently replace the shared lock with an exclusive lock on some UNIX-like operating systems. +// Be careful when using exclusive locks in conjunction with shared locks (RLock()), +// because calling Unlock() may accidentally release the exclusive lock that was once a shared lock. func (f *Flock) Lock() error { - return f.lock(&f.l, syscall.LOCK_EX) + return f.lock(&f.l, unix.LOCK_EX) } -// RLock is a blocking call to try and take a shared file lock. It will wait -// until it is able to obtain the shared file lock. It's recommended that -// TryRLock() be used over this function. This function may block the ability to -// query the current Locked() or RLocked() status due to a RW-mutex lock. +// RLock is a blocking call to try and take a shared file lock. +// It will wait until it is able to obtain the shared file lock. +// It's recommended that TryRLock() be used over this function. +// This function may block the ability to query the current Locked() or RLocked() status due to a RW-mutex lock. // -// If we are already shared-locked, this function short-circuits and returns -// immediately assuming it can take the mutex lock. +// If we are already shared-locked, +// this function short-circuits and returns immediately assuming it can take the mutex lock. func (f *Flock) RLock() error { - return f.lock(&f.r, syscall.LOCK_SH) + return f.lock(&f.r, unix.LOCK_SH) } func (f *Flock) lock(locked *bool, flag int) error { @@ -48,13 +50,15 @@ func (f *Flock) lock(locked *bool, flag int) error { } if f.fh == nil { - if err := f.setFh(); err != nil { + if err := f.setFh(f.flag); err != nil { return err } + defer f.ensureFhState() } - if err := syscall.Flock(int(f.fh.Fd()), flag); err != nil { + err := unix.Flock(int(f.fh.Fd()), flag) + if err != nil { shouldRetry, reopenErr := f.reopenFDOnError(err) if reopenErr != nil { return reopenErr @@ -64,71 +68,74 @@ func (f *Flock) lock(locked *bool, flag int) error { return err } - if err = syscall.Flock(int(f.fh.Fd()), flag); err != nil { + err = unix.Flock(int(f.fh.Fd()), flag) + if err != nil { return err } } *locked = true + return nil } -// Unlock is a function to unlock the file. This file takes a RW-mutex lock, so -// while it is running the Locked() and RLocked() functions will be blocked. +// Unlock is a function to unlock the file. +// This file takes a RW-mutex lock, +// so while it is running the Locked() and RLocked() functions will be blocked. // -// This function short-circuits if we are unlocked already. If not, it calls -// syscall.LOCK_UN on the file and closes the file descriptor. It does not -// remove the file from disk. It's up to your application to do. +// This function short-circuits if we are unlocked already. +// If not, it calls unix.LOCK_UN on the file and closes the file descriptor. +// It does not remove the file from disk. It's up to your application to do. // -// Please note, if your shared lock became an exclusive lock this may -// unintentionally drop the exclusive lock if called by the consumer that -// believes they have a shared lock. Please see Lock() for more details. +// Please note, +// if your shared lock became an exclusive lock, +// this may unintentionally drop the exclusive lock if called by the consumer that believes they have a shared lock. +// Please see Lock() for more details. func (f *Flock) Unlock() error { f.m.Lock() defer f.m.Unlock() - // if we aren't locked or if the lockfile instance is nil - // just return a nil error because we are unlocked + // If we aren't locked or if the lockfile instance is nil + // just return a nil error because we are unlocked. if (!f.l && !f.r) || f.fh == nil { return nil } - // mark the file as unlocked - if err := syscall.Flock(int(f.fh.Fd()), syscall.LOCK_UN); err != nil { + // Mark the file as unlocked. + err := unix.Flock(int(f.fh.Fd()), unix.LOCK_UN) + if err != nil { return err } - f.fh.Close() - - f.l = false - f.r = false - f.fh = nil + f.reset() return nil } -// TryLock is the preferred function for taking an exclusive file lock. This -// function takes an RW-mutex lock before it tries to lock the file, so there is -// the possibility that this function may block for a short time if another -// goroutine is trying to take any action. +// TryLock is the preferred function for taking an exclusive file lock. +// This function takes an RW-mutex lock before it tries to lock the file, +// so there is the possibility that this function may block for a short time +// if another goroutine is trying to take any action. // -// The actual file lock is non-blocking. If we are unable to get the exclusive -// file lock, the function will return false instead of waiting for the lock. If -// we get the lock, we also set the *Flock instance as being exclusive-locked. +// The actual file lock is non-blocking. +// If we are unable to get the exclusive file lock, +// the function will return false instead of waiting for the lock. +// If we get the lock, we also set the *Flock instance as being exclusive-locked. func (f *Flock) TryLock() (bool, error) { - return f.try(&f.l, syscall.LOCK_EX) + return f.try(&f.l, unix.LOCK_EX) } -// TryRLock is the preferred function for taking a shared file lock. This -// function takes an RW-mutex lock before it tries to lock the file, so there is -// the possibility that this function may block for a short time if another -// goroutine is trying to take any action. +// TryRLock is the preferred function for taking a shared file lock. +// This function takes an RW-mutex lock before it tries to lock the file, +// so there is the possibility that this function may block for a short time +// if another goroutine is trying to take any action. // -// The actual file lock is non-blocking. If we are unable to get the shared file -// lock, the function will return false instead of waiting for the lock. If we -// get the lock, we also set the *Flock instance as being share-locked. +// The actual file lock is non-blocking. +// If we are unable to get the shared file lock, +// the function will return false instead of waiting for the lock. +// If we get the lock, we also set the *Flock instance as being share-locked. func (f *Flock) TryRLock() (bool, error) { - return f.try(&f.r, syscall.LOCK_SH) + return f.try(&f.r, unix.LOCK_SH) } func (f *Flock) try(locked *bool, flag int) (bool, error) { @@ -140,25 +147,28 @@ func (f *Flock) try(locked *bool, flag int) (bool, error) { } if f.fh == nil { - if err := f.setFh(); err != nil { + if err := f.setFh(f.flag); err != nil { return false, err } + defer f.ensureFhState() } var retried bool retry: - err := syscall.Flock(int(f.fh.Fd()), flag|syscall.LOCK_NB) + err := unix.Flock(int(f.fh.Fd()), flag|unix.LOCK_NB) - switch err { - case syscall.EWOULDBLOCK: + switch { + case errors.Is(err, unix.EWOULDBLOCK): return false, nil - case nil: + case err == nil: *locked = true return true, nil } + if !retried { - if shouldRetry, reopenErr := f.reopenFDOnError(err); reopenErr != nil { + shouldRetry, reopenErr := f.reopenFDOnError(err) + if reopenErr != nil { return false, reopenErr } else if shouldRetry { retried = true @@ -169,29 +179,32 @@ retry: return false, err } -// reopenFDOnError determines whether we should reopen the file handle -// in readwrite mode and try again. This comes from util-linux/sys-utils/flock.c: -// Since Linux 3.4 (commit 55725513) -// Probably NFSv4 where flock() is emulated by fcntl(). +// reopenFDOnError determines whether we should reopen the file handle in readwrite mode and try again. +// This comes from `util-linux/sys-utils/flock.c`: +// > Since Linux 3.4 (commit 55725513) +// > Probably NFSv4 where flock() is emulated by fcntl(). +// > https://github.com/util-linux/util-linux/blob/198e920aa24743ef6ace4e07cf6237de527f9261/sys-utils/flock.c#L374-L390 func (f *Flock) reopenFDOnError(err error) (bool, error) { - if err != syscall.EIO && err != syscall.EBADF { + if !errors.Is(err, unix.EIO) && !errors.Is(err, unix.EBADF) { return false, nil } - if st, err := f.fh.Stat(); err == nil { - // if the file is able to be read and written - if st.Mode()&0600 == 0600 { - f.fh.Close() - f.fh = nil - - // reopen in read-write mode and set the filehandle - fh, err := os.OpenFile(f.path, os.O_CREATE|os.O_RDWR, os.FileMode(0600)) - if err != nil { - return false, err - } - f.fh = fh - return true, nil - } + + st, err := f.fh.Stat() + if err != nil { + return false, nil + } + + if st.Mode()&f.perm != f.perm { + return false, nil + } + + f.resetFh() + + // reopen in read-write mode and set the file handle + err = f.setFh(f.flag | os.O_RDWR) + if err != nil { + return false, err } - return false, nil + return true, nil } diff --git a/tools/vendor/github.com/gofrs/flock/flock_unix_fcntl.go b/tools/vendor/github.com/gofrs/flock/flock_unix_fcntl.go new file mode 100644 index 000000000..ea007b47d --- /dev/null +++ b/tools/vendor/github.com/gofrs/flock/flock_unix_fcntl.go @@ -0,0 +1,393 @@ +// Copyright 2015 Tim Heckman. All rights reserved. +// Copyright 2018-2024 The Gofrs. All rights reserved. +// Use of this source code is governed by the BSD 3-Clause +// license that can be found in the LICENSE file. + +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This code implements the filelock API using POSIX 'fcntl' locks, +// which attach to an (inode, process) pair rather than a file descriptor. +// To avoid unlocking files prematurely when the same file is opened through different descriptors, +// we allow only one read-lock at a time. +// +// This code is adapted from the Go package (go.22): +// https://github.com/golang/go/blob/release-branch.go1.22/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go + +//go:build aix || (solaris && !illumos) + +package flock + +import ( + "errors" + "io" + "io/fs" + "math/rand" + "sync" + "syscall" + "time" + + "golang.org/x/sys/unix" +) + +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go#L28 +type lockType int16 + +// String returns the name of the function corresponding to lt +// (Lock, RLock, or Unlock). +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock.go#L67 +func (lt lockType) String() string { + switch lt { + case readLock: + return "RLock" + case writeLock: + return "Lock" + default: + return "Unlock" + } +} + +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go#L30-L33 +const ( + readLock lockType = unix.F_RDLCK + writeLock lockType = unix.F_WRLCK +) + +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go#L35 +type inode = uint64 + +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go#L37-L40 +type inodeLock struct { + owner *Flock + queue []<-chan *Flock +} + +type cmdType int + +const ( + tryLock cmdType = unix.F_SETLK + waitLock cmdType = unix.F_SETLKW +) + +var ( + mu sync.Mutex + inodes = map[*Flock]inode{} + locks = map[inode]inodeLock{} +) + +// Lock is a blocking call to try and take an exclusive file lock. +// It will wait until it is able to obtain the exclusive file lock. +// It's recommended that TryLock() be used over this function. +// This function may block the ability to query the current Locked() or RLocked() status due to a RW-mutex lock. +// +// If we are already exclusive-locked, this function short-circuits and +// returns immediately assuming it can take the mutex lock. +// +// If the *Flock has a shared lock (RLock), +// this may transparently replace the shared lock with an exclusive lock on some UNIX-like operating systems. +// Be careful when using exclusive locks in conjunction with shared locks (RLock()), +// because calling Unlock() may accidentally release the exclusive lock that was once a shared lock. +func (f *Flock) Lock() error { + return f.lock(&f.l, writeLock) +} + +// RLock is a blocking call to try and take a shared file lock. +// It will wait until it is able to obtain the shared file lock. +// It's recommended that TryRLock() be used over this function. +// This function may block the ability to query the current Locked() or RLocked() status due to a RW-mutex lock. +// +// If we are already shared-locked, this function short-circuits and +// returns immediately assuming it can take the mutex lock. +func (f *Flock) RLock() error { + return f.lock(&f.r, readLock) +} + +func (f *Flock) lock(locked *bool, flag lockType) error { + f.m.Lock() + defer f.m.Unlock() + + if *locked { + return nil + } + + if f.fh == nil { + if err := f.setFh(f.flag); err != nil { + return err + } + + defer f.ensureFhState() + } + + _, err := f.doLock(waitLock, flag, true) + if err != nil { + return err + } + + *locked = true + + return nil +} + +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go#L48 +func (f *Flock) doLock(cmd cmdType, lt lockType, blocking bool) (bool, error) { + // POSIX locks apply per inode and process, + // and the lock for an inode is released when *any* descriptor for that inode is closed. + // So we need to synchronize access to each inode internally, + // and must serialize lock and unlock calls that refer to the same inode through different descriptors. + fi, err := f.fh.Stat() + if err != nil { + return false, err + } + + // Note(ldez): don't replace `syscall.Stat_t` by `unix.Stat_t` because `FileInfo.Sys()` returns `syscall.Stat_t` + ino := fi.Sys().(*syscall.Stat_t).Ino + + mu.Lock() + + if i, dup := inodes[f]; dup && i != ino { + mu.Unlock() + return false, &fs.PathError{ + Op: lt.String(), + Path: f.Path(), + Err: errors.New("inode for file changed since last Lock or RLock"), + } + } + + inodes[f] = ino + + var wait chan *Flock + + l := locks[ino] + + switch { + case l.owner == f: + // This file already owns the lock, but the call may change its lock type. + case l.owner == nil: + // No owner: it's ours now. + l.owner = f + + case !blocking: + // Already owned: cannot take the lock. + mu.Unlock() + return false, nil + + default: + // Already owned: add a channel to wait on. + wait = make(chan *Flock) + l.queue = append(l.queue, wait) + } + + locks[ino] = l + + mu.Unlock() + + if wait != nil { + wait <- f + } + + // Spurious EDEADLK errors arise on platforms that compute deadlock graphs at + // the process, rather than thread, level. Consider processes P and Q, with + // threads P.1, P.2, and Q.3. The following trace is NOT a deadlock, but will be + // reported as a deadlock on systems that consider only process granularity: + // + // P.1 locks file A. + // Q.3 locks file B. + // Q.3 blocks on file A. + // P.2 blocks on file B. (This is erroneously reported as a deadlock.) + // P.1 unlocks file A. + // Q.3 unblocks and locks file A. + // Q.3 unlocks files A and B. + // P.2 unblocks and locks file B. + // P.2 unlocks file B. + // + // These spurious errors were observed in practice on AIX and Solaris in + // cmd/go: see https://golang.org/issue/32817. + // + // We work around this bug by treating EDEADLK as always spurious. If there + // really is a lock-ordering bug between the interacting processes, it will + // become a livelock instead, but that's not appreciably worse than if we had + // a proper flock implementation (which generally does not even attempt to + // diagnose deadlocks). + // + // In the above example, that changes the trace to: + // + // P.1 locks file A. + // Q.3 locks file B. + // Q.3 blocks on file A. + // P.2 spuriously fails to lock file B and goes to sleep. + // P.1 unlocks file A. + // Q.3 unblocks and locks file A. + // Q.3 unlocks files A and B. + // P.2 wakes up and locks file B. + // P.2 unlocks file B. + // + // We know that the retry loop will not introduce a *spurious* livelock + // because, according to the POSIX specification, EDEADLK is only to be + // returned when “the lock is blocked by a lock from another process”. + // If that process is blocked on some lock that we are holding, then the + // resulting livelock is due to a real deadlock (and would manifest as such + // when using, for example, the flock implementation of this package). + // If the other process is *not* blocked on some other lock that we are + // holding, then it will eventually release the requested lock. + + nextSleep := 1 * time.Millisecond + const maxSleep = 500 * time.Millisecond + for { + err = setlkw(f.fh.Fd(), cmd, lt) + if !errors.Is(err, unix.EDEADLK) { + break + } + + time.Sleep(nextSleep) + + nextSleep += nextSleep + if nextSleep > maxSleep { + nextSleep = maxSleep + } + // Apply 10% jitter to avoid synchronizing collisions when we finally unblock. + nextSleep += time.Duration((0.1*rand.Float64() - 0.05) * float64(nextSleep)) + } + + if err != nil { + f.doUnlock() + + if cmd == tryLock && errors.Is(err, unix.EACCES) { + return false, nil + } + + return false, &fs.PathError{ + Op: lt.String(), + Path: f.Path(), + Err: err, + } + } + + return true, nil +} + +func (f *Flock) Unlock() error { + f.m.Lock() + defer f.m.Unlock() + + // If we aren't locked or if the lockfile instance is nil + // just return a nil error because we are unlocked. + if (!f.l && !f.r) || f.fh == nil { + return nil + } + + if err := f.doUnlock(); err != nil { + return err + } + + f.reset() + + return nil +} + +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go#L163 +func (f *Flock) doUnlock() (err error) { + var owner *Flock + + mu.Lock() + + ino, ok := inodes[f] + if ok { + owner = locks[ino].owner + } + + mu.Unlock() + + if owner == f { + err = setlkw(f.fh.Fd(), waitLock, unix.F_UNLCK) + } + + mu.Lock() + + l := locks[ino] + + if len(l.queue) == 0 { + // No waiters: remove the map entry. + delete(locks, ino) + } else { + // The first waiter is sending us their file now. + // Receive it and update the queue. + l.owner = <-l.queue[0] + l.queue = l.queue[1:] + locks[ino] = l + } + + delete(inodes, f) + + mu.Unlock() + + return err +} + +// TryLock is the preferred function for taking an exclusive file lock. +// This function takes an RW-mutex lock before it tries to lock the file, +// so there is the possibility that this function may block for a short time +// if another goroutine is trying to take any action. +// +// The actual file lock is non-blocking. +// If we are unable to get the exclusive file lock, +// the function will return false instead of waiting for the lock. +// If we get the lock, we also set the *Flock instance as being exclusive-locked. +func (f *Flock) TryLock() (bool, error) { + return f.try(&f.l, writeLock) +} + +// TryRLock is the preferred function for taking a shared file lock. +// This function takes an RW-mutex lock before it tries to lock the file, +// so there is the possibility that this function may block for a short time +// if another goroutine is trying to take any action. +// +// The actual file lock is non-blocking. +// If we are unable to get the shared file lock, +// the function will return false instead of waiting for the lock. +// If we get the lock, we also set the *Flock instance as being share-locked. +func (f *Flock) TryRLock() (bool, error) { + return f.try(&f.r, readLock) +} + +func (f *Flock) try(locked *bool, flag lockType) (bool, error) { + f.m.Lock() + defer f.m.Unlock() + + if *locked { + return true, nil + } + + if f.fh == nil { + if err := f.setFh(f.flag); err != nil { + return false, err + } + + defer f.ensureFhState() + } + + hasLock, err := f.doLock(tryLock, flag, false) + if err != nil { + return false, err + } + + *locked = hasLock + + return hasLock, nil +} + +// setlkw calls FcntlFlock with cmd for the entire file indicated by fd. +// https://github.com/golang/go/blob/09aeb6e33ab426eff4676a3baf694d5a3019e9fc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_fcntl.go#L198 +func setlkw(fd uintptr, cmd cmdType, lt lockType) error { + for { + err := unix.FcntlFlock(fd, int(cmd), &unix.Flock_t{ + Type: int16(lt), + Whence: io.SeekStart, + Start: 0, + Len: 0, // All bytes. + }) + if !errors.Is(err, unix.EINTR) { + return err + } + } +} diff --git a/tools/vendor/github.com/gofrs/flock/flock_winapi.go b/tools/vendor/github.com/gofrs/flock/flock_winapi.go deleted file mode 100644 index fe405a255..000000000 --- a/tools/vendor/github.com/gofrs/flock/flock_winapi.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2015 Tim Heckman. All rights reserved. -// Use of this source code is governed by the BSD 3-Clause -// license that can be found in the LICENSE file. - -// +build windows - -package flock - -import ( - "syscall" - "unsafe" -) - -var ( - kernel32, _ = syscall.LoadLibrary("kernel32.dll") - procLockFileEx, _ = syscall.GetProcAddress(kernel32, "LockFileEx") - procUnlockFileEx, _ = syscall.GetProcAddress(kernel32, "UnlockFileEx") -) - -const ( - winLockfileFailImmediately = 0x00000001 - winLockfileExclusiveLock = 0x00000002 - winLockfileSharedLock = 0x00000000 -) - -// Use of 0x00000000 for the shared lock is a guess based on some the MS Windows -// `LockFileEX` docs, which document the `LOCKFILE_EXCLUSIVE_LOCK` flag as: -// -// > The function requests an exclusive lock. Otherwise, it requests a shared -// > lock. -// -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx - -func lockFileEx(handle syscall.Handle, flags uint32, reserved uint32, numberOfBytesToLockLow uint32, numberOfBytesToLockHigh uint32, offset *syscall.Overlapped) (bool, syscall.Errno) { - r1, _, errNo := syscall.Syscall6( - uintptr(procLockFileEx), - 6, - uintptr(handle), - uintptr(flags), - uintptr(reserved), - uintptr(numberOfBytesToLockLow), - uintptr(numberOfBytesToLockHigh), - uintptr(unsafe.Pointer(offset))) - - if r1 != 1 { - if errNo == 0 { - return false, syscall.EINVAL - } - - return false, errNo - } - - return true, 0 -} - -func unlockFileEx(handle syscall.Handle, reserved uint32, numberOfBytesToLockLow uint32, numberOfBytesToLockHigh uint32, offset *syscall.Overlapped) (bool, syscall.Errno) { - r1, _, errNo := syscall.Syscall6( - uintptr(procUnlockFileEx), - 5, - uintptr(handle), - uintptr(reserved), - uintptr(numberOfBytesToLockLow), - uintptr(numberOfBytesToLockHigh), - uintptr(unsafe.Pointer(offset)), - 0) - - if r1 != 1 { - if errNo == 0 { - return false, syscall.EINVAL - } - - return false, errNo - } - - return true, 0 -} diff --git a/tools/vendor/github.com/gofrs/flock/flock_windows.go b/tools/vendor/github.com/gofrs/flock/flock_windows.go index ddb534cce..dfd31e15f 100644 --- a/tools/vendor/github.com/gofrs/flock/flock_windows.go +++ b/tools/vendor/github.com/gofrs/flock/flock_windows.go @@ -1,35 +1,48 @@ // Copyright 2015 Tim Heckman. All rights reserved. +// Copyright 2018-2024 The Gofrs. All rights reserved. // Use of this source code is governed by the BSD 3-Clause // license that can be found in the LICENSE file. +//go:build windows + package flock import ( - "syscall" + "errors" + + "golang.org/x/sys/windows" ) -// ErrorLockViolation is the error code returned from the Windows syscall when a -// lock would block and you ask to fail immediately. -const ErrorLockViolation syscall.Errno = 0x21 // 33 +// Use of 0x00000000 for the shared lock is a guess based on some the MS Windows `LockFileEX` docs, +// which document the `LOCKFILE_EXCLUSIVE_LOCK` flag as: +// +// > The function requests an exclusive lock. Otherwise, it requests a shared lock. +// +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx +const winLockfileSharedLock = 0x00000000 + +// ErrorLockViolation is the error code returned from the Windows syscall when a lock would block, +// and you ask to fail immediately. +const ErrorLockViolation windows.Errno = 0x21 // 33 -// Lock is a blocking call to try and take an exclusive file lock. It will wait -// until it is able to obtain the exclusive file lock. It's recommended that -// TryLock() be used over this function. This function may block the ability to -// query the current Locked() or RLocked() status due to a RW-mutex lock. +// Lock is a blocking call to try and take an exclusive file lock. +// It will wait until it is able to obtain the exclusive file lock. +// It's recommended that TryLock() be used over this function. +// This function may block the ability to query the current Locked() or RLocked() status due to a RW-mutex lock. // -// If we are already locked, this function short-circuits and returns -// immediately assuming it can take the mutex lock. +// If we are already locked, this function short-circuits and +// returns immediately assuming it can take the mutex lock. func (f *Flock) Lock() error { - return f.lock(&f.l, winLockfileExclusiveLock) + return f.lock(&f.l, windows.LOCKFILE_EXCLUSIVE_LOCK) } -// RLock is a blocking call to try and take a shared file lock. It will wait -// until it is able to obtain the shared file lock. It's recommended that -// TryRLock() be used over this function. This function may block the ability to -// query the current Locked() or RLocked() status due to a RW-mutex lock. +// RLock is a blocking call to try and take a shared file lock. +// It will wait until it is able to obtain the shared file lock. +// It's recommended that TryRLock() be used over this function. +// This function may block the ability to query the current Locked() or RLocked() status due to a RW-mutex lock. // -// If we are already locked, this function short-circuits and returns -// immediately assuming it can take the mutex lock. +// If we are already locked, this function short-circuits and +// returns immediately assuming it can take the mutex lock. func (f *Flock) RLock() error { return f.lock(&f.r, winLockfileSharedLock) } @@ -43,26 +56,31 @@ func (f *Flock) lock(locked *bool, flag uint32) error { } if f.fh == nil { - if err := f.setFh(); err != nil { + if err := f.setFh(f.flag); err != nil { return err } + defer f.ensureFhState() } - if _, errNo := lockFileEx(syscall.Handle(f.fh.Fd()), flag, 0, 1, 0, &syscall.Overlapped{}); errNo > 0 { - return errNo + err := windows.LockFileEx(windows.Handle(f.fh.Fd()), flag, 0, 1, 0, &windows.Overlapped{}) + if err != nil && !errors.Is(err, windows.Errno(0)) { + return err } *locked = true + return nil } -// Unlock is a function to unlock the file. This file takes a RW-mutex lock, so -// while it is running the Locked() and RLocked() functions will be blocked. +// Unlock is a function to unlock the file. +// This file takes a RW-mutex lock, +// so while it is running the Locked() and RLocked() functions will be blocked. // -// This function short-circuits if we are unlocked already. If not, it calls -// UnlockFileEx() on the file and closes the file descriptor. It does not remove -// the file from disk. It's up to your application to do. +// This function short-circuits if we are unlocked already. +// If not, it calls UnlockFileEx() on the file and closes the file descriptor. +// It does not remove the file from disk. +// It's up to your application to do. func (f *Flock) Unlock() error { f.m.Lock() defer f.m.Unlock() @@ -74,39 +92,37 @@ func (f *Flock) Unlock() error { } // mark the file as unlocked - if _, errNo := unlockFileEx(syscall.Handle(f.fh.Fd()), 0, 1, 0, &syscall.Overlapped{}); errNo > 0 { - return errNo + err := windows.UnlockFileEx(windows.Handle(f.fh.Fd()), 0, 1, 0, &windows.Overlapped{}) + if err != nil && !errors.Is(err, windows.Errno(0)) { + return err } - f.fh.Close() - - f.l = false - f.r = false - f.fh = nil + f.reset() return nil } -// TryLock is the preferred function for taking an exclusive file lock. This -// function does take a RW-mutex lock before it tries to lock the file, so there -// is the possibility that this function may block for a short time if another -// goroutine is trying to take any action. +// TryLock is the preferred function for taking an exclusive file lock. +// This function does take a RW-mutex lock before it tries to lock the file, +// so there is the possibility that this function may block for a short time +// if another goroutine is trying to take any action. // -// The actual file lock is non-blocking. If we are unable to get the exclusive -// file lock, the function will return false instead of waiting for the lock. If -// we get the lock, we also set the *Flock instance as being exclusive-locked. +// The actual file lock is non-blocking. +// If we are unable to get the exclusive file lock, +// the function will return false instead of waiting for the lock. +// If we get the lock, we also set the *Flock instance as being exclusive-locked. func (f *Flock) TryLock() (bool, error) { - return f.try(&f.l, winLockfileExclusiveLock) + return f.try(&f.l, windows.LOCKFILE_EXCLUSIVE_LOCK) } -// TryRLock is the preferred function for taking a shared file lock. This -// function does take a RW-mutex lock before it tries to lock the file, so there -// is the possibility that this function may block for a short time if another -// goroutine is trying to take any action. +// TryRLock is the preferred function for taking a shared file lock. +// This function does take a RW-mutex lock before it tries to lock the file, +// so there is the possibility that this function may block for a short time if another goroutine is trying to take any action. // -// The actual file lock is non-blocking. If we are unable to get the shared file -// lock, the function will return false instead of waiting for the lock. If we -// get the lock, we also set the *Flock instance as being shared-locked. +// The actual file lock is non-blocking. +// If we are unable to get the shared file lock, +// the function will return false instead of waiting for the lock. +// If we get the lock, we also set the *Flock instance as being shared-locked. func (f *Flock) TryRLock() (bool, error) { return f.try(&f.r, winLockfileSharedLock) } @@ -120,20 +136,20 @@ func (f *Flock) try(locked *bool, flag uint32) (bool, error) { } if f.fh == nil { - if err := f.setFh(); err != nil { + if err := f.setFh(f.flag); err != nil { return false, err } + defer f.ensureFhState() } - _, errNo := lockFileEx(syscall.Handle(f.fh.Fd()), flag|winLockfileFailImmediately, 0, 1, 0, &syscall.Overlapped{}) - - if errNo > 0 { - if errNo == ErrorLockViolation || errNo == syscall.ERROR_IO_PENDING { + err := windows.LockFileEx(windows.Handle(f.fh.Fd()), flag|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{}) + if err != nil && !errors.Is(err, windows.Errno(0)) { + if errors.Is(err, ErrorLockViolation) || errors.Is(err, windows.ERROR_IO_PENDING) { return false, nil } - return false, errNo + return false, err } *locked = true diff --git a/tools/vendor/github.com/golangci/check/cmd/structcheck/structcheck.go b/tools/vendor/github.com/golangci/check/cmd/structcheck/structcheck.go deleted file mode 100644 index 5dc5f8380..000000000 --- a/tools/vendor/github.com/golangci/check/cmd/structcheck/structcheck.go +++ /dev/null @@ -1,193 +0,0 @@ -// structcheck -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -package structcheck - -import ( - "flag" - "fmt" - "go/ast" - "go/token" - "go/types" - - "golang.org/x/tools/go/loader" -) - -var ( - assignmentsOnly = flag.Bool("structcheck.a", false, "Count assignments only") - loadTestFiles = flag.Bool("structcheck.t", false, "Load test files too") - buildTags = flag.String("structcheck.tags", "", "Build tags") -) - -type visitor struct { - prog *loader.Program - pkg *loader.PackageInfo - m map[types.Type]map[string]int - skip map[types.Type]struct{} -} - -func (v *visitor) decl(t types.Type, fieldName string) { - if _, ok := v.m[t]; !ok { - v.m[t] = make(map[string]int) - } - if _, ok := v.m[t][fieldName]; !ok { - v.m[t][fieldName] = 0 - } -} - -func (v *visitor) assignment(t types.Type, fieldName string) { - if _, ok := v.m[t]; !ok { - v.m[t] = make(map[string]int) - } - if _, ok := v.m[t][fieldName]; ok { - v.m[t][fieldName]++ - } else { - v.m[t][fieldName] = 1 - } -} - -func (v *visitor) typeSpec(node *ast.TypeSpec) { - if strukt, ok := node.Type.(*ast.StructType); ok { - t := v.pkg.Info.Defs[node.Name].Type() - for _, f := range strukt.Fields.List { - if len(f.Names) > 0 { - fieldName := f.Names[0].Name - v.decl(t, fieldName) - } - } - } -} - -func (v *visitor) typeAndFieldName(expr *ast.SelectorExpr) (types.Type, string, bool) { - selection := v.pkg.Info.Selections[expr] - if selection == nil { - return nil, "", false - } - recv := selection.Recv() - if ptr, ok := recv.(*types.Pointer); ok { - recv = ptr.Elem() - } - return recv, selection.Obj().Name(), true -} - -func (v *visitor) assignStmt(node *ast.AssignStmt) { - for _, lhs := range node.Lhs { - var selector *ast.SelectorExpr - switch expr := lhs.(type) { - case *ast.SelectorExpr: - selector = expr - case *ast.IndexExpr: - if expr, ok := expr.X.(*ast.SelectorExpr); ok { - selector = expr - } - } - if selector != nil { - if t, fn, ok := v.typeAndFieldName(selector); ok { - v.assignment(t, fn) - } - } - } -} - -func (v *visitor) compositeLiteral(node *ast.CompositeLit) { - t := v.pkg.Info.Types[node.Type].Type - for _, expr := range node.Elts { - if kv, ok := expr.(*ast.KeyValueExpr); ok { - if ident, ok := kv.Key.(*ast.Ident); ok { - v.assignment(t, ident.Name) - } - } else { - // Struct literal with positional values. - // All the fields are assigned. - v.skip[t] = struct{}{} - break - } - } -} - -func (v *visitor) Visit(node ast.Node) ast.Visitor { - switch node := node.(type) { - case *ast.TypeSpec: - v.typeSpec(node) - - case *ast.AssignStmt: - if *assignmentsOnly { - v.assignStmt(node) - } - - case *ast.SelectorExpr: - if !*assignmentsOnly { - if t, fn, ok := v.typeAndFieldName(node); ok { - v.assignment(t, fn) - } - } - - case *ast.CompositeLit: - v.compositeLiteral(node) - } - - return v -} - -type Issue struct { - Pos token.Position - Type string - FieldName string -} - -func Run(program *loader.Program, reportExported bool) []Issue { - var issues []Issue - for _, pkg := range program.InitialPackages() { - visitor := &visitor{ - m: make(map[types.Type]map[string]int), - skip: make(map[types.Type]struct{}), - prog: program, - pkg: pkg, - } - for _, f := range pkg.Files { - ast.Walk(visitor, f) - } - - for t := range visitor.m { - if _, skip := visitor.skip[t]; skip { - continue - } - for fieldName, v := range visitor.m[t] { - if !reportExported && ast.IsExported(fieldName) { - continue - } - if v == 0 { - field, _, _ := types.LookupFieldOrMethod(t, false, pkg.Pkg, fieldName) - if field == nil { - fmt.Printf("%s: unknown field or method: %s.%s\n", pkg.Pkg.Path(), t, fieldName) - continue - } - if fieldName == "XMLName" { - if named, ok := field.Type().(*types.Named); ok && named.Obj().Pkg().Path() == "encoding/xml" { - continue - } - } - pos := program.Fset.Position(field.Pos()) - issues = append(issues, Issue{ - Pos: pos, - Type: types.TypeString(t, nil), - FieldName: fieldName, - }) - } - } - } - } - - return issues -} diff --git a/tools/vendor/github.com/golangci/check/cmd/varcheck/varcheck.go b/tools/vendor/github.com/golangci/check/cmd/varcheck/varcheck.go deleted file mode 100644 index 8e93e0473..000000000 --- a/tools/vendor/github.com/golangci/check/cmd/varcheck/varcheck.go +++ /dev/null @@ -1,163 +0,0 @@ -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -package varcheck - -import ( - "flag" - "go/ast" - "go/token" - "strings" - - "go/types" - - "golang.org/x/tools/go/loader" -) - -var ( - buildTags = flag.String("varcheck.tags", "", "Build tags") -) - -type object struct { - pkgPath string - name string -} - -type visitor struct { - prog *loader.Program - pkg *loader.PackageInfo - uses map[object]int - positions map[object]token.Position - insideFunc bool -} - -func getKey(obj types.Object) object { - if obj == nil { - return object{} - } - - pkg := obj.Pkg() - pkgPath := "" - if pkg != nil { - pkgPath = pkg.Path() - } - - return object{ - pkgPath: pkgPath, - name: obj.Name(), - } -} - -func (v *visitor) decl(obj types.Object) { - key := getKey(obj) - if _, ok := v.uses[key]; !ok { - v.uses[key] = 0 - } - if _, ok := v.positions[key]; !ok { - v.positions[key] = v.prog.Fset.Position(obj.Pos()) - } -} - -func (v *visitor) use(obj types.Object) { - key := getKey(obj) - if _, ok := v.uses[key]; ok { - v.uses[key]++ - } else { - v.uses[key] = 1 - } -} - -func isReserved(name string) bool { - return name == "_" || strings.HasPrefix(strings.ToLower(name), "_cgo_") -} - -func (v *visitor) Visit(node ast.Node) ast.Visitor { - switch node := node.(type) { - case *ast.Ident: - v.use(v.pkg.Info.Uses[node]) - - case *ast.ValueSpec: - if !v.insideFunc { - for _, ident := range node.Names { - if !isReserved(ident.Name) { - v.decl(v.pkg.Info.Defs[ident]) - } - } - } - for _, val := range node.Values { - ast.Walk(v, val) - } - if node.Type != nil { - ast.Walk(v, node.Type) - } - return nil - - case *ast.FuncDecl: - if node.Body != nil { - v.insideFunc = true - ast.Walk(v, node.Body) - v.insideFunc = false - } - - if node.Recv != nil { - ast.Walk(v, node.Recv) - } - if node.Type != nil { - ast.Walk(v, node.Type) - } - - return nil - } - - return v -} - -type Issue struct { - Pos token.Position - VarName string -} - -func Run(program *loader.Program, reportExported bool) []Issue { - var issues []Issue - uses := make(map[object]int) - positions := make(map[object]token.Position) - - for _, pkgInfo := range program.InitialPackages() { - if pkgInfo.Pkg.Path() == "unsafe" { - continue - } - - v := &visitor{ - prog: program, - pkg: pkgInfo, - uses: uses, - positions: positions, - } - - for _, f := range v.pkg.Files { - ast.Walk(v, f) - } - } - - for obj, useCount := range uses { - if useCount == 0 && (reportExported || !ast.IsExported(obj.name)) { - pos := positions[obj] - issues = append(issues, Issue{ - Pos: pos, - VarName: obj.name, - }) - } - } - - return issues -} diff --git a/tools/vendor/github.com/golangci/go-misc/LICENSE b/tools/vendor/github.com/golangci/go-misc/LICENSE deleted file mode 100644 index cc42dd45d..000000000 --- a/tools/vendor/github.com/golangci/go-misc/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rémy Oudompheng. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * The name of Rémy Oudompheng may not be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/tools/vendor/github.com/golangci/go-misc/deadcode/README.md b/tools/vendor/github.com/golangci/go-misc/deadcode/README.md deleted file mode 100644 index 550423128..000000000 --- a/tools/vendor/github.com/golangci/go-misc/deadcode/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# deadcode - -`deadcode` is a very simple utility which detects unused declarations in a Go package. - -## Usage -``` -deadcode [-test] [packages] - - -test Include test files - packages A list of packages using the same conventions as the go tool -``` - -## Limitations - -* Self-referential unused code is not currently reported -* A single package can be tested at a time -* Unused methods are not reported - diff --git a/tools/vendor/github.com/golangci/go-misc/deadcode/deadcode.go b/tools/vendor/github.com/golangci/go-misc/deadcode/deadcode.go deleted file mode 100644 index c154a576b..000000000 --- a/tools/vendor/github.com/golangci/go-misc/deadcode/deadcode.go +++ /dev/null @@ -1,138 +0,0 @@ -package deadcode - -import ( - "fmt" - "go/ast" - "go/token" - "go/types" - "os" - "path/filepath" - "sort" - "strings" - - "golang.org/x/tools/go/loader" -) - -var exitCode int - -var ( - withTestFiles bool -) - -type Issue struct { - Pos token.Position - UnusedIdentName string -} - -func Run(program *loader.Program) ([]Issue, error) { - ctx := &Context{ - program: program, - } - report := ctx.Process() - var issues []Issue - for _, obj := range report { - issues = append(issues, Issue{ - Pos: program.Fset.Position(obj.Pos()), - UnusedIdentName: obj.Name(), - }) - } - - return issues, nil -} - -func fatalf(format string, args ...interface{}) { - panic(fmt.Errorf(format, args...)) -} - -type Context struct { - cwd string - withTests bool - - program *loader.Program -} - -// pos resolves a compact position encoding into a verbose one -func (ctx *Context) pos(pos token.Pos) token.Position { - if ctx.cwd == "" { - ctx.cwd, _ = os.Getwd() - } - p := ctx.program.Fset.Position(pos) - f, err := filepath.Rel(ctx.cwd, p.Filename) - if err == nil { - p.Filename = f - } - return p -} - -// error formats the error to standard error, adding program -// identification and a newline -func (ctx *Context) errorf(pos token.Pos, format string, args ...interface{}) { - p := ctx.pos(pos) - fmt.Fprintf(os.Stderr, p.String()+": "+format+"\n", args...) - exitCode = 2 -} - -func (ctx *Context) Load(args ...string) { - // TODO -} - -func (ctx *Context) Process() []types.Object { - prog := ctx.program - var allUnused []types.Object - for _, pkg := range prog.Imported { - unused := ctx.doPackage(prog, pkg) - allUnused = append(allUnused, unused...) - } - for _, pkg := range prog.Created { - unused := ctx.doPackage(prog, pkg) - allUnused = append(allUnused, unused...) - } - sort.Sort(objects(allUnused)) - return allUnused -} - -func isTestFuncByName(name string) bool { - return strings.HasPrefix(name, "Test") || - strings.HasPrefix(name, "Benchmark") || - strings.HasPrefix(name, "Fuzz") || - strings.HasPrefix(name, "Example") -} - -func (ctx *Context) doPackage(prog *loader.Program, pkg *loader.PackageInfo) []types.Object { - used := make(map[types.Object]bool) - for _, file := range pkg.Files { - ast.Inspect(file, func(n ast.Node) bool { - id, ok := n.(*ast.Ident) - if !ok { - return true - } - obj := pkg.Info.Uses[id] - if obj != nil { - used[obj] = true - } - return false - }) - } - - global := pkg.Pkg.Scope() - var unused []types.Object - for _, name := range global.Names() { - if pkg.Pkg.Name() == "main" && name == "main" { - continue - } - obj := global.Lookup(name) - _, isSig := obj.Type().(*types.Signature) - pos := ctx.pos(obj.Pos()) - isTestMethod := isSig && isTestFuncByName(obj.Name()) && strings.HasSuffix(pos.Filename, "_test.go") - if !used[obj] && ((pkg.Pkg.Name() == "main" && !isTestMethod) || !ast.IsExported(name)) { - unused = append(unused, obj) - } - } - return unused -} - -type objects []types.Object - -func (s objects) Len() int { return len(s) } -func (s objects) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s objects) Less(i, j int) bool { return s[i].Pos() < s[j].Pos() } diff --git a/tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/main.go b/tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/main.go index 9d1daa81d..413e071d6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/main.go +++ b/tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/main.go @@ -13,33 +13,69 @@ var ( goVersion = "unknown" // Populated by goreleaser during build - version = "master" + version = "unknown" commit = "?" date = "" ) func main() { - if buildInfo, available := debug.ReadBuildInfo(); available { - goVersion = buildInfo.GoVersion + info := createBuildInfo() - if date == "" { - version = buildInfo.Main.Version - commit = fmt.Sprintf("(unknown, mod sum: %q)", buildInfo.Main.Sum) - date = "(unknown)" - } + if err := commands.Execute(info); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "Failed executing command with error: %v\n", err) + os.Exit(exitcodes.Failure) } +} +func createBuildInfo() commands.BuildInfo { info := commands.BuildInfo{ - GoVersion: goVersion, - Version: version, Commit: commit, + Version: version, + GoVersion: goVersion, Date: date, } - e := commands.NewExecutor(info) + buildInfo, available := debug.ReadBuildInfo() + if !available { + return info + } - if err := e.Execute(); err != nil { - fmt.Fprintf(os.Stderr, "failed executing command with error %v\n", err) - os.Exit(exitcodes.Failure) + info.GoVersion = buildInfo.GoVersion + + if date != "" { + return info + } + + info.Version = buildInfo.Main.Version + + var revision string + var modified string + for _, setting := range buildInfo.Settings { + // The `vcs.xxx` information is only available with `go build`. + // This information is not available with `go install` or `go run`. + switch setting.Key { + case "vcs.time": + info.Date = setting.Value + case "vcs.revision": + revision = setting.Value + case "vcs.modified": + modified = setting.Value + } } + + if revision == "" { + revision = "unknown" + } + + if modified == "" { + modified = "?" + } + + if info.Date == "" { + info.Date = "(unknown)" + } + + info.Commit = fmt.Sprintf("(%s, modified: %s, mod sum: %q)", revision, modified, buildInfo.Main.Sum) + + return info } diff --git a/tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/plugins.go b/tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/plugins.go new file mode 100644 index 000000000..541ff7624 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/cmd/golangci-lint/plugins.go @@ -0,0 +1,3 @@ +package main + +// This file is used to declare module plugins. diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/cache.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/cache.go index 6fdaebaed..cc6c0eacd 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/cache.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/cache.go @@ -12,7 +12,13 @@ import ( "github.com/golangci/golangci-lint/pkg/logutils" ) -func (e *Executor) initCache() { +type cacheCommand struct { + cmd *cobra.Command +} + +func newCacheCommand() *cacheCommand { + c := &cacheCommand{} + cacheCmd := &cobra.Command{ Use: "cache", Short: "Cache control and information", @@ -21,28 +27,32 @@ func (e *Executor) initCache() { return cmd.Help() }, } - e.rootCmd.AddCommand(cacheCmd) - cacheCmd.AddCommand(&cobra.Command{ - Use: "clean", - Short: "Clean cache", - Args: cobra.NoArgs, - ValidArgsFunction: cobra.NoFileCompletions, - RunE: e.executeCleanCache, - }) - cacheCmd.AddCommand(&cobra.Command{ - Use: "status", - Short: "Show cache status", - Args: cobra.NoArgs, - ValidArgsFunction: cobra.NoFileCompletions, - Run: e.executeCacheStatus, - }) + cacheCmd.AddCommand( + &cobra.Command{ + Use: "clean", + Short: "Clean cache", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + RunE: c.executeClean, + }, + &cobra.Command{ + Use: "status", + Short: "Show cache status", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + Run: c.executeStatus, + }, + ) - // TODO: add trim command? + c.cmd = cacheCmd + + return c } -func (e *Executor) executeCleanCache(_ *cobra.Command, _ []string) error { +func (*cacheCommand) executeClean(_ *cobra.Command, _ []string) error { cacheDir := cache.DefaultDir() + if err := os.RemoveAll(cacheDir); err != nil { return fmt.Errorf("failed to remove dir %s: %w", cacheDir, err) } @@ -50,13 +60,13 @@ func (e *Executor) executeCleanCache(_ *cobra.Command, _ []string) error { return nil } -func (e *Executor) executeCacheStatus(_ *cobra.Command, _ []string) { +func (*cacheCommand) executeStatus(_ *cobra.Command, _ []string) { cacheDir := cache.DefaultDir() - fmt.Fprintf(logutils.StdOut, "Dir: %s\n", cacheDir) + _, _ = fmt.Fprintf(logutils.StdOut, "Dir: %s\n", cacheDir) cacheSizeBytes, err := dirSizeBytes(cacheDir) if err == nil { - fmt.Fprintf(logutils.StdOut, "Size: %s\n", fsutils.PrettifyBytesCount(cacheSizeBytes)) + _, _ = fmt.Fprintf(logutils.StdOut, "Size: %s\n", fsutils.PrettifyBytesCount(cacheSizeBytes)) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go index a16ef6310..935ec5e86 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go @@ -4,58 +4,119 @@ import ( "fmt" "os" + "github.com/fatih/color" "github.com/spf13/cobra" "github.com/spf13/viper" + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/exitcodes" "github.com/golangci/golangci-lint/pkg/fsutils" + "github.com/golangci/golangci-lint/pkg/logutils" ) -func (e *Executor) initConfig() { - cmd := &cobra.Command{ +type configCommand struct { + viper *viper.Viper + cmd *cobra.Command + + opts config.LoaderOptions + verifyOpts verifyOptions + + buildInfo BuildInfo + + log logutils.Log +} + +func newConfigCommand(log logutils.Log, info BuildInfo) *configCommand { + c := &configCommand{ + viper: viper.New(), + log: log, + buildInfo: info, + } + + configCmd := &cobra.Command{ Use: "config", - Short: "Config", + Short: "Config file information", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, + PersistentPreRunE: c.preRunE, } - e.rootCmd.AddCommand(cmd) - pathCmd := &cobra.Command{ - Use: "path", - Short: "Print used config path", + verifyCommand := &cobra.Command{ + Use: "verify", + Short: "Verify configuration against JSON schema", Args: cobra.NoArgs, ValidArgsFunction: cobra.NoFileCompletions, - Run: e.executePathCmd, + RunE: c.executeVerify, + SilenceUsage: true, + SilenceErrors: true, } - e.initRunConfiguration(pathCmd) // allow --config - cmd.AddCommand(pathCmd) + + configCmd.AddCommand( + &cobra.Command{ + Use: "path", + Short: "Print used config path", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + Run: c.executePath, + }, + verifyCommand, + ) + + flagSet := configCmd.PersistentFlags() + flagSet.SortFlags = false // sort them as they are defined here + + setupConfigFileFlagSet(flagSet, &c.opts) + + // ex: --schema jsonschema/golangci.next.jsonschema.json + verifyFlagSet := verifyCommand.Flags() + verifyFlagSet.StringVar(&c.verifyOpts.schemaURL, "schema", "", color.GreenString("JSON schema URL")) + _ = verifyFlagSet.MarkHidden("schema") + + c.cmd = configCmd + + return c } -// getUsedConfig returns the resolved path to the golangci config file, or the empty string -// if no configuration could be found. -func (e *Executor) getUsedConfig() string { - usedConfigFile := viper.ConfigFileUsed() - if usedConfigFile == "" { - return "" - } +func (c *configCommand) preRunE(cmd *cobra.Command, args []string) error { + // The command doesn't depend on the real configuration. + // It only needs to know the path of the configuration file. + cfg := config.NewDefault() - prettyUsedConfigFile, err := fsutils.ShortestRelPath(usedConfigFile, "") + loader := config.NewLoader(c.log.Child(logutils.DebugKeyConfigReader), c.viper, cmd.Flags(), c.opts, cfg, args) + + err := loader.Load(config.LoadOptions{}) if err != nil { - e.log.Warnf("Can't pretty print config file path: %s", err) - return usedConfigFile + return fmt.Errorf("can't load config: %w", err) } - return prettyUsedConfigFile + return nil } -func (e *Executor) executePathCmd(_ *cobra.Command, _ []string) { - usedConfigFile := e.getUsedConfig() +func (c *configCommand) executePath(cmd *cobra.Command, _ []string) { + usedConfigFile := c.getUsedConfig() if usedConfigFile == "" { - e.log.Warnf("No config file detected") + c.log.Warnf("No config file detected") os.Exit(exitcodes.NoConfigFileDetected) } - fmt.Println(usedConfigFile) + cmd.Println(usedConfigFile) +} + +// getUsedConfig returns the resolved path to the golangci config file, +// or the empty string if no configuration could be found. +func (c *configCommand) getUsedConfig() string { + usedConfigFile := c.viper.ConfigFileUsed() + if usedConfigFile == "" { + return "" + } + + prettyUsedConfigFile, err := fsutils.ShortestRelPath(usedConfigFile, "") + if err != nil { + c.log.Warnf("Can't pretty print config file path: %s", err) + return usedConfigFile + } + + return prettyUsedConfigFile } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config_verify.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config_verify.go new file mode 100644 index 000000000..a44050b59 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/config_verify.go @@ -0,0 +1,180 @@ +package commands + +import ( + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + hcversion "github.com/hashicorp/go-version" + "github.com/pelletier/go-toml/v2" + "github.com/santhosh-tekuri/jsonschema/v5" + "github.com/santhosh-tekuri/jsonschema/v5/httploader" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "gopkg.in/yaml.v3" + + "github.com/golangci/golangci-lint/pkg/exitcodes" +) + +type verifyOptions struct { + schemaURL string // For debugging purpose only (Flag only). +} + +func (c *configCommand) executeVerify(cmd *cobra.Command, _ []string) error { + usedConfigFile := c.getUsedConfig() + if usedConfigFile == "" { + c.log.Warnf("No config file detected") + os.Exit(exitcodes.NoConfigFileDetected) + } + + schemaURL, err := createSchemaURL(cmd.Flags(), c.buildInfo) + if err != nil { + return fmt.Errorf("get JSON schema: %w", err) + } + + err = validateConfiguration(schemaURL, usedConfigFile) + if err != nil { + var v *jsonschema.ValidationError + if !errors.As(err, &v) { + return fmt.Errorf("[%s] validate: %w", usedConfigFile, err) + } + + detail := v.DetailedOutput() + + printValidationDetail(cmd, &detail) + + return errors.New("the configuration contains invalid elements") + } + + return nil +} + +func createSchemaURL(flags *pflag.FlagSet, buildInfo BuildInfo) (string, error) { + schemaURL, err := flags.GetString("schema") + if err != nil { + return "", fmt.Errorf("get schema flag: %w", err) + } + + if schemaURL != "" { + return schemaURL, nil + } + + switch { + case buildInfo.Version != "" && buildInfo.Version != "(devel)": + version, err := hcversion.NewVersion(buildInfo.Version) + if err != nil { + return "", fmt.Errorf("parse version: %w", err) + } + + schemaURL = fmt.Sprintf("https://golangci-lint.run/jsonschema/golangci.v%d.%d.jsonschema.json", + version.Segments()[0], version.Segments()[1]) + + case buildInfo.Commit != "" && buildInfo.Commit != "?": + if buildInfo.Commit == "unknown" { + return "", errors.New("unknown commit information") + } + + commit := buildInfo.Commit + + if strings.HasPrefix(commit, "(") { + c, _, ok := strings.Cut(strings.TrimPrefix(commit, "("), ",") + if !ok { + return "", errors.New("commit information not found") + } + + commit = c + } + + schemaURL = fmt.Sprintf("https://raw.githubusercontent.com/golangci/golangci-lint/%s/jsonschema/golangci.next.jsonschema.json", + commit) + + default: + return "", errors.New("version not found") + } + + return schemaURL, nil +} + +func validateConfiguration(schemaPath, targetFile string) error { + httploader.Client = &http.Client{Timeout: 2 * time.Second} + + compiler := jsonschema.NewCompiler() + compiler.Draft = jsonschema.Draft7 + + schema, err := compiler.Compile(schemaPath) + if err != nil { + return fmt.Errorf("compile schema: %w", err) + } + + var m any + + switch strings.ToLower(filepath.Ext(targetFile)) { + case ".yaml", ".yml", ".json": + m, err = decodeYamlFile(targetFile) + if err != nil { + return err + } + + case ".toml": + m, err = decodeTomlFile(targetFile) + if err != nil { + return err + } + + default: + // unsupported + return errors.New("unsupported configuration format") + } + + return schema.Validate(m) +} + +func printValidationDetail(cmd *cobra.Command, detail *jsonschema.Detailed) { + if detail.Error != "" { + cmd.PrintErrf("jsonschema: %q does not validate with %q: %s\n", + strings.ReplaceAll(strings.TrimPrefix(detail.InstanceLocation, "/"), "/", "."), detail.KeywordLocation, detail.Error) + } + + for _, d := range detail.Errors { + d := d + printValidationDetail(cmd, &d) + } +} + +func decodeYamlFile(filename string) (any, error) { + file, err := os.Open(filename) + if err != nil { + return nil, fmt.Errorf("[%s] file open: %w", filename, err) + } + + defer func() { _ = file.Close() }() + + var m any + err = yaml.NewDecoder(file).Decode(&m) + if err != nil { + return nil, fmt.Errorf("[%s] YAML decode: %w", filename, err) + } + + return m, nil +} + +func decodeTomlFile(filename string) (any, error) { + file, err := os.Open(filename) + if err != nil { + return nil, fmt.Errorf("[%s] file open: %w", filename, err) + } + + defer func() { _ = file.Close() }() + + var m any + err = toml.NewDecoder(file).Decode(&m) + if err != nil { + return nil, fmt.Errorf("[%s] TOML decode: %w", filename, err) + } + + return m, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/custom.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/custom.go new file mode 100644 index 000000000..1bc9f9014 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/custom.go @@ -0,0 +1,79 @@ +package commands + +import ( + "fmt" + "log" + "os" + + "github.com/spf13/cobra" + + "github.com/golangci/golangci-lint/pkg/commands/internal" + "github.com/golangci/golangci-lint/pkg/logutils" +) + +const envKeepTempFiles = "CUSTOM_GCL_KEEP_TEMP_FILES" + +type customCommand struct { + cmd *cobra.Command + + cfg *internal.Configuration + + log logutils.Log +} + +func newCustomCommand(logger logutils.Log) *customCommand { + c := &customCommand{log: logger} + + customCmd := &cobra.Command{ + Use: "custom", + Short: "Build a version of golangci-lint with custom linters", + Args: cobra.NoArgs, + PreRunE: c.preRunE, + RunE: c.runE, + SilenceUsage: true, + } + + c.cmd = customCmd + + return c +} + +func (c *customCommand) preRunE(_ *cobra.Command, _ []string) error { + cfg, err := internal.LoadConfiguration() + if err != nil { + return err + } + + err = cfg.Validate() + if err != nil { + return err + } + + c.cfg = cfg + + return nil +} + +func (c *customCommand) runE(cmd *cobra.Command, _ []string) error { + tmp, err := os.MkdirTemp(os.TempDir(), "custom-gcl") + if err != nil { + return fmt.Errorf("create temporary directory: %w", err) + } + + defer func() { + if os.Getenv(envKeepTempFiles) != "" { + log.Printf("WARN: The env var %s has been detected: the temporary directory is preserved: %s", envKeepTempFiles, tmp) + + return + } + + _ = os.RemoveAll(tmp) + }() + + err = internal.NewBuilder(c.log, c.cfg, tmp).Build(cmd.Context()) + if err != nil { + return fmt.Errorf("build process: %w", err) + } + + return nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go deleted file mode 100644 index 61e221cb8..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go +++ /dev/null @@ -1,253 +0,0 @@ -package commands - -import ( - "bytes" - "context" - "crypto/sha256" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "time" - - "github.com/fatih/color" - "github.com/gofrs/flock" - "github.com/spf13/cobra" - "github.com/spf13/pflag" - "gopkg.in/yaml.v3" - - "github.com/golangci/golangci-lint/internal/cache" - "github.com/golangci/golangci-lint/internal/pkgcache" - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/fsutils" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load" - "github.com/golangci/golangci-lint/pkg/goutil" - "github.com/golangci/golangci-lint/pkg/lint" - "github.com/golangci/golangci-lint/pkg/lint/lintersdb" - "github.com/golangci/golangci-lint/pkg/logutils" - "github.com/golangci/golangci-lint/pkg/report" - "github.com/golangci/golangci-lint/pkg/timeutils" -) - -type BuildInfo struct { - GoVersion string `json:"goVersion"` - Version string `json:"version"` - Commit string `json:"commit"` - Date string `json:"date"` -} - -type Executor struct { - rootCmd *cobra.Command - runCmd *cobra.Command - lintersCmd *cobra.Command - - exitCode int - buildInfo BuildInfo - - cfg *config.Config // cfg is the unmarshaled data from the golangci config file. - log logutils.Log - reportData report.Data - DBManager *lintersdb.Manager - EnabledLintersSet *lintersdb.EnabledSet - contextLoader *lint.ContextLoader - goenv *goutil.Env - fileCache *fsutils.FileCache - lineCache *fsutils.LineCache - pkgCache *pkgcache.Cache - debugf logutils.DebugFunc - sw *timeutils.Stopwatch - - loadGuard *load.Guard - flock *flock.Flock -} - -// NewExecutor creates and initializes a new command executor. -func NewExecutor(buildInfo BuildInfo) *Executor { - startedAt := time.Now() - e := &Executor{ - cfg: config.NewDefault(), - buildInfo: buildInfo, - DBManager: lintersdb.NewManager(nil, nil), - debugf: logutils.Debug(logutils.DebugKeyExec), - } - - e.debugf("Starting execution...") - e.log = report.NewLogWrapper(logutils.NewStderrLog(logutils.DebugKeyEmpty), &e.reportData) - - // to setup log level early we need to parse config from command line extra time to - // find `-v` option - commandLineCfg, err := e.getConfigForCommandLine() - if err != nil && err != pflag.ErrHelp { - e.log.Fatalf("Can't get config for command line: %s", err) - } - if commandLineCfg != nil { - logutils.SetupVerboseLog(e.log, commandLineCfg.Run.IsVerbose) - - switch commandLineCfg.Output.Color { - case "always": - color.NoColor = false - case "never": - color.NoColor = true - case "auto": - // nothing - default: - e.log.Fatalf("invalid value %q for --color; must be 'always', 'auto', or 'never'", commandLineCfg.Output.Color) - } - } - - // init of commands must be done before config file reading because - // init sets config with the default values of flags - e.initRoot() - e.initRun() - e.initHelp() - e.initLinters() - e.initConfig() - e.initVersion() - e.initCache() - - // init e.cfg by values from config: flags parse will see these values - // like the default ones. It will overwrite them only if the same option - // is found in command-line: it's ok, command-line has higher priority. - - r := config.NewFileReader(e.cfg, commandLineCfg, e.log.Child(logutils.DebugKeyConfigReader)) - if err = r.Read(); err != nil { - e.log.Fatalf("Can't read config: %s", err) - } - - if (commandLineCfg == nil || commandLineCfg.Run.Go == "") && e.cfg != nil && e.cfg.Run.Go == "" { - e.cfg.Run.Go = config.DetectGoVersion() - } - - // recreate after getting config - e.DBManager = lintersdb.NewManager(e.cfg, e.log) - - // Slice options must be explicitly set for proper merging of config and command-line options. - fixSlicesFlags(e.runCmd.Flags()) - fixSlicesFlags(e.lintersCmd.Flags()) - - e.EnabledLintersSet = lintersdb.NewEnabledSet(e.DBManager, - lintersdb.NewValidator(e.DBManager), e.log.Child(logutils.DebugKeyLintersDB), e.cfg) - e.goenv = goutil.NewEnv(e.log.Child(logutils.DebugKeyGoEnv)) - e.fileCache = fsutils.NewFileCache() - e.lineCache = fsutils.NewLineCache(e.fileCache) - - e.sw = timeutils.NewStopwatch("pkgcache", e.log.Child(logutils.DebugKeyStopwatch)) - e.pkgCache, err = pkgcache.NewCache(e.sw, e.log.Child(logutils.DebugKeyPkgCache)) - if err != nil { - e.log.Fatalf("Failed to build packages cache: %s", err) - } - e.loadGuard = load.NewGuard() - e.contextLoader = lint.NewContextLoader(e.cfg, e.log.Child(logutils.DebugKeyLoader), e.goenv, - e.lineCache, e.fileCache, e.pkgCache, e.loadGuard) - if err = e.initHashSalt(buildInfo.Version); err != nil { - e.log.Fatalf("Failed to init hash salt: %s", err) - } - e.debugf("Initialized executor in %s", time.Since(startedAt)) - return e -} - -func (e *Executor) Execute() error { - return e.rootCmd.Execute() -} - -func (e *Executor) initHashSalt(version string) error { - binSalt, err := computeBinarySalt(version) - if err != nil { - return fmt.Errorf("failed to calculate binary salt: %w", err) - } - - configSalt, err := computeConfigSalt(e.cfg) - if err != nil { - return fmt.Errorf("failed to calculate config salt: %w", err) - } - - b := bytes.NewBuffer(binSalt) - b.Write(configSalt) - cache.SetSalt(b.Bytes()) - return nil -} - -func computeBinarySalt(version string) ([]byte, error) { - if version != "" && version != "(devel)" { - return []byte(version), nil - } - - if logutils.HaveDebugTag(logutils.DebugKeyBinSalt) { - return []byte("debug"), nil - } - - p, err := os.Executable() - if err != nil { - return nil, err - } - f, err := os.Open(p) - if err != nil { - return nil, err - } - defer f.Close() - h := sha256.New() - if _, err := io.Copy(h, f); err != nil { - return nil, err - } - return h.Sum(nil), nil -} - -func computeConfigSalt(cfg *config.Config) ([]byte, error) { - // We don't hash all config fields to reduce meaningless cache - // invalidations. At least, it has a huge impact on tests speed. - - lintersSettingsBytes, err := yaml.Marshal(cfg.LintersSettings) - if err != nil { - return nil, fmt.Errorf("failed to json marshal config linter settings: %w", err) - } - - configData := bytes.NewBufferString("linters-settings=") - configData.Write(lintersSettingsBytes) - configData.WriteString("\nbuild-tags=%s" + strings.Join(cfg.Run.BuildTags, ",")) - - h := sha256.New() - if _, err := h.Write(configData.Bytes()); err != nil { - return nil, err - } - return h.Sum(nil), nil -} - -func (e *Executor) acquireFileLock() bool { - if e.cfg.Run.AllowParallelRunners { - e.debugf("Parallel runners are allowed, no locking") - return true - } - - lockFile := filepath.Join(os.TempDir(), "golangci-lint.lock") - e.debugf("Locking on file %s...", lockFile) - f := flock.New(lockFile) - const retryDelay = time.Second - - ctx := context.Background() - if !e.cfg.Run.AllowSerialRunners { - const totalTimeout = 5 * time.Second - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, totalTimeout) - defer cancel() - } - if ok, _ := f.TryLockContext(ctx, retryDelay); !ok { - return false - } - - e.flock = f - return true -} - -func (e *Executor) releaseFileLock() { - if e.cfg.Run.AllowParallelRunners { - return - } - - if err := e.flock.Unlock(); err != nil { - e.debugf("Failed to unlock on file: %s", err) - } - if err := os.Remove(e.flock.Path()); err != nil { - e.debugf("Failed to remove lock file: %s", err) - } -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/flagsets.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/flagsets.go new file mode 100644 index 000000000..608f6b9de --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/flagsets.go @@ -0,0 +1,146 @@ +package commands + +import ( + "fmt" + "strings" + + "github.com/fatih/color" + "github.com/spf13/pflag" + "github.com/spf13/viper" + + "github.com/golangci/golangci-lint/pkg/commands/internal" + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/exitcodes" + "github.com/golangci/golangci-lint/pkg/lint/lintersdb" + "github.com/golangci/golangci-lint/pkg/result/processors" +) + +const defaultMaxIssuesPerLinter = 50 + +func setupLintersFlagSet(v *viper.Viper, fs *pflag.FlagSet) { + internal.AddHackedStringSliceP(fs, "disable", "D", color.GreenString("Disable specific linter")) + internal.AddFlagAndBind(v, fs, fs.Bool, "disable-all", "linters.disable-all", false, color.GreenString("Disable all linters")) + + internal.AddHackedStringSliceP(fs, "enable", "E", color.GreenString("Enable specific linter")) + internal.AddFlagAndBind(v, fs, fs.Bool, "enable-all", "linters.enable-all", false, color.GreenString("Enable all linters")) + + internal.AddFlagAndBind(v, fs, fs.Bool, "fast", "linters.fast", false, + color.GreenString("Enable only fast linters from enabled linters set (first run won't be fast)")) + + internal.AddHackedStringSliceP(fs, "presets", "p", + color.GreenString(fmt.Sprintf("Enable presets (%s) of linters.\n"+ + "Run 'golangci-lint help linters' to see them.\n"+ + "This option implies option --disable-all", + strings.Join(lintersdb.AllPresets(), "|"), + ))) + + fs.StringSlice("enable-only", nil, + color.GreenString("Override linters configuration section to only run the specific linter(s)")) // Flags only. +} + +func setupRunFlagSet(v *viper.Viper, fs *pflag.FlagSet) { + internal.AddFlagAndBindP(v, fs, fs.IntP, "concurrency", "j", "run.concurrency", getDefaultConcurrency(), + color.GreenString("Number of CPUs to use (Default: number of logical CPUs)")) + + internal.AddFlagAndBind(v, fs, fs.String, "modules-download-mode", "run.modules-download-mode", "", + color.GreenString("Modules download mode. If not empty, passed as -mod= to go tools")) + internal.AddFlagAndBind(v, fs, fs.Int, "issues-exit-code", "run.issues-exit-code", exitcodes.IssuesFound, + color.GreenString("Exit code when issues were found")) + internal.AddFlagAndBind(v, fs, fs.String, "go", "run.go", "", color.GreenString("Targeted Go version")) + internal.AddHackedStringSlice(fs, "build-tags", color.GreenString("Build tags")) + + internal.AddFlagAndBind(v, fs, fs.Duration, "timeout", "run.timeout", defaultTimeout, color.GreenString("Timeout for total work")) + + internal.AddFlagAndBind(v, fs, fs.Bool, "tests", "run.tests", true, color.GreenString("Analyze tests (*_test.go)")) + + internal.AddDeprecatedHackedStringSlice(fs, "skip-files", color.GreenString("Regexps of files to skip")) + internal.AddDeprecatedHackedStringSlice(fs, "skip-dirs", color.GreenString("Regexps of directories to skip")) + internal.AddDeprecatedFlagAndBind(v, fs, fs.Bool, "skip-dirs-use-default", "run.skip-dirs-use-default", true, + getDefaultDirectoryExcludeHelp()) + + const allowParallelDesc = "Allow multiple parallel golangci-lint instances running.\n" + + "If false (default) - golangci-lint acquires file lock on start." + internal.AddFlagAndBind(v, fs, fs.Bool, "allow-parallel-runners", "run.allow-parallel-runners", false, + color.GreenString(allowParallelDesc)) + const allowSerialDesc = "Allow multiple golangci-lint instances running, but serialize them around a lock.\n" + + "If false (default) - golangci-lint exits with an error if it fails to acquire file lock on start." + internal.AddFlagAndBind(v, fs, fs.Bool, "allow-serial-runners", "run.allow-serial-runners", false, color.GreenString(allowSerialDesc)) +} + +func setupOutputFlagSet(v *viper.Viper, fs *pflag.FlagSet) { + internal.AddFlagAndBind(v, fs, fs.String, "out-format", "output.formats", config.OutFormatColoredLineNumber, + color.GreenString(fmt.Sprintf("Formats of output: %s", strings.Join(config.AllOutputFormats, "|")))) + internal.AddFlagAndBind(v, fs, fs.Bool, "print-issued-lines", "output.print-issued-lines", true, + color.GreenString("Print lines of code with issue")) + internal.AddFlagAndBind(v, fs, fs.Bool, "print-linter-name", "output.print-linter-name", true, + color.GreenString("Print linter name in issue line")) + internal.AddFlagAndBind(v, fs, fs.Bool, "uniq-by-line", "output.uniq-by-line", true, + color.GreenString("Make issues output unique by line")) + internal.AddFlagAndBind(v, fs, fs.Bool, "sort-results", "output.sort-results", false, + color.GreenString("Sort linter results")) + internal.AddFlagAndBind(v, fs, fs.StringSlice, "sort-order", "output.sort-order", nil, + color.GreenString("Sort order of linter results")) + internal.AddFlagAndBind(v, fs, fs.String, "path-prefix", "output.path-prefix", "", + color.GreenString("Path prefix to add to output")) + internal.AddFlagAndBind(v, fs, fs.Bool, "show-stats", "output.show-stats", false, color.GreenString("Show statistics per linter")) +} + +//nolint:gomnd // magic numbers here is ok +func setupIssuesFlagSet(v *viper.Viper, fs *pflag.FlagSet) { + internal.AddHackedStringSliceP(fs, "exclude", "e", color.GreenString("Exclude issue by regexp")) + internal.AddFlagAndBind(v, fs, fs.Bool, "exclude-use-default", "issues.exclude-use-default", true, + getDefaultIssueExcludeHelp()) + internal.AddFlagAndBind(v, fs, fs.Bool, "exclude-case-sensitive", "issues.exclude-case-sensitive", false, + color.GreenString("If set to true exclude and exclude rules regular expressions are case-sensitive")) + + internal.AddFlagAndBind(v, fs, fs.Int, "max-issues-per-linter", "issues.max-issues-per-linter", defaultMaxIssuesPerLinter, + color.GreenString("Maximum issues count per one linter. Set to 0 to disable")) + internal.AddFlagAndBind(v, fs, fs.Int, "max-same-issues", "issues.max-same-issues", 3, + color.GreenString("Maximum count of issues with the same text. Set to 0 to disable")) + + internal.AddHackedStringSlice(fs, "exclude-files", color.GreenString("Regexps of files to exclude")) + internal.AddHackedStringSlice(fs, "exclude-dirs", color.GreenString("Regexps of directories to exclude")) + internal.AddFlagAndBind(v, fs, fs.Bool, "exclude-dirs-use-default", "issues.exclude-dirs-use-default", true, + getDefaultDirectoryExcludeHelp()) + + internal.AddFlagAndBind(v, fs, fs.String, "exclude-generated", "issues.exclude-generated", processors.AutogeneratedModeLax, + color.GreenString("Mode of the generated files analysis")) + + const newDesc = "Show only new issues: if there are unstaged changes or untracked files, only those changes " + + "are analyzed, else only changes in HEAD~ are analyzed.\nIt's a super-useful option for integration " + + "of golangci-lint into existing large codebase.\nIt's not practical to fix all existing issues at " + + "the moment of integration: much better to not allow issues in new code.\nFor CI setups, prefer " + + "--new-from-rev=HEAD~, as --new can skip linting the current patch if any scripts generate " + + "unstaged files before golangci-lint runs." + internal.AddFlagAndBindP(v, fs, fs.BoolP, "new", "n", "issues.new", false, color.GreenString(newDesc)) + internal.AddFlagAndBind(v, fs, fs.String, "new-from-rev", "issues.new-from-rev", "", + color.GreenString("Show only new issues created after git revision `REV`")) + internal.AddFlagAndBind(v, fs, fs.String, "new-from-patch", "issues.new-from-patch", "", + color.GreenString("Show only new issues created in git patch with file path `PATH`")) + internal.AddFlagAndBind(v, fs, fs.Bool, "whole-files", "issues.whole-files", false, + color.GreenString("Show issues in any part of update files (requires new-from-rev or new-from-patch)")) + internal.AddFlagAndBind(v, fs, fs.Bool, "fix", "issues.fix", false, + color.GreenString("Fix found issues (if it's supported by the linter)")) +} + +func getDefaultIssueExcludeHelp() string { + parts := []string{color.GreenString("Use or not use default excludes:")} + + for _, ep := range config.DefaultExcludePatterns { + parts = append(parts, + fmt.Sprintf(" - %s (%s): %s", color.BlueString(ep.ID), color.CyanString(ep.Linter), ep.Why), + fmt.Sprintf(` Pattern: %s`, color.YellowString(`'`+ep.Pattern+`'`)), + ) + } + + return strings.Join(parts, "\n") +} + +func getDefaultDirectoryExcludeHelp() string { + parts := []string{color.GreenString("Use or not use default excluded directories:")} + for _, dir := range processors.StdExcludeDirRegexps { + parts = append(parts, fmt.Sprintf(" - %s", color.YellowString(dir))) + } + parts = append(parts, "") + return strings.Join(parts, "\n") +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/help.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/help.go index a06d508f2..094e5d190 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/help.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/help.go @@ -2,17 +2,30 @@ package commands import ( "fmt" + "slices" "sort" "strings" "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/lint/lintersdb" "github.com/golangci/golangci-lint/pkg/logutils" ) -func (e *Executor) initHelp() { +type helpCommand struct { + cmd *cobra.Command + + dbManager *lintersdb.Manager + + log logutils.Log +} + +func newHelpCommand(logger logutils.Log) *helpCommand { + c := &helpCommand{log: logger} + helpCmd := &cobra.Command{ Use: "help", Short: "Help", @@ -21,48 +34,39 @@ func (e *Executor) initHelp() { return cmd.Help() }, } - e.rootCmd.SetHelpCommand(helpCmd) - - lintersHelpCmd := &cobra.Command{ - Use: "linters", - Short: "Help about linters", - Args: cobra.NoArgs, - ValidArgsFunction: cobra.NoFileCompletions, - Run: e.executeLintersHelp, - } - helpCmd.AddCommand(lintersHelpCmd) -} -func printLinterConfigs(lcs []*linter.Config) { - sort.Slice(lcs, func(i, j int) bool { - return lcs[i].Name() < lcs[j].Name() - }) - for _, lc := range lcs { - altNamesStr := "" - if len(lc.AlternativeNames) != 0 { - altNamesStr = fmt.Sprintf(" (%s)", strings.Join(lc.AlternativeNames, ", ")) - } + helpCmd.AddCommand( + &cobra.Command{ + Use: "linters", + Short: "Help about linters", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + Run: c.execute, + PreRunE: c.preRunE, + }, + ) - // If the linter description spans multiple lines, truncate everything following the first newline - linterDescription := lc.Linter.Desc() - firstNewline := strings.IndexRune(linterDescription, '\n') - if firstNewline > 0 { - linterDescription = linterDescription[:firstNewline] - } + c.cmd = helpCmd - deprecatedMark := "" - if lc.IsDeprecated() { - deprecatedMark = " [" + color.RedString("deprecated") + "]" - } + return c +} - fmt.Fprintf(logutils.StdOut, "%s%s%s: %s [fast: %t, auto-fix: %t]\n", color.YellowString(lc.Name()), - altNamesStr, deprecatedMark, linterDescription, !lc.IsSlowLinter(), lc.CanAutoFix) +func (c *helpCommand) preRunE(_ *cobra.Command, _ []string) error { + // The command doesn't depend on the real configuration. + // It just needs the list of all plugins and all presets. + dbManager, err := lintersdb.NewManager(c.log.Child(logutils.DebugKeyLintersDB), config.NewDefault(), lintersdb.NewLinterBuilder()) + if err != nil { + return err } + + c.dbManager = dbManager + + return nil } -func (e *Executor) executeLintersHelp(_ *cobra.Command, _ []string) { +func (c *helpCommand) execute(_ *cobra.Command, _ []string) { var enabledLCs, disabledLCs []*linter.Config - for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { + for _, lc := range c.dbManager.GetAllSupportedLinterConfigs() { if lc.Internal { continue } @@ -75,13 +79,19 @@ func (e *Executor) executeLintersHelp(_ *cobra.Command, _ []string) { } color.Green("Enabled by default linters:\n") - printLinterConfigs(enabledLCs) + printLinters(enabledLCs) + color.Red("\nDisabled by default linters:\n") - printLinterConfigs(disabledLCs) + printLinters(disabledLCs) color.Green("\nLinters presets:") - for _, p := range e.DBManager.AllPresets() { - linters := e.DBManager.GetAllLinterConfigsForPreset(p) + c.printPresets() +} + +func (c *helpCommand) printPresets() { + for _, p := range lintersdb.AllPresets() { + linters := c.dbManager.GetAllLinterConfigsForPreset(p) + var linterNames []string for _, lc := range linters { if lc.Internal { @@ -91,6 +101,42 @@ func (e *Executor) executeLintersHelp(_ *cobra.Command, _ []string) { linterNames = append(linterNames, lc.Name()) } sort.Strings(linterNames) - fmt.Fprintf(logutils.StdOut, "%s: %s\n", color.YellowString(p), strings.Join(linterNames, ", ")) + + _, _ = fmt.Fprintf(logutils.StdOut, "%s: %s\n", color.YellowString(p), strings.Join(linterNames, ", ")) + } +} + +func printLinters(lcs []*linter.Config) { + slices.SortFunc(lcs, func(a, b *linter.Config) int { + if a.IsDeprecated() && b.IsDeprecated() { + return strings.Compare(a.Name(), b.Name()) + } + + if a.IsDeprecated() { + return 1 + } + + if b.IsDeprecated() { + return -1 + } + + return strings.Compare(a.Name(), b.Name()) + }) + + for _, lc := range lcs { + // If the linter description spans multiple lines, truncate everything following the first newline + linterDescription := lc.Linter.Desc() + firstNewline := strings.IndexRune(linterDescription, '\n') + if firstNewline > 0 { + linterDescription = linterDescription[:firstNewline] + } + + deprecatedMark := "" + if lc.IsDeprecated() { + deprecatedMark = " [" + color.RedString("deprecated") + "]" + } + + _, _ = fmt.Fprintf(logutils.StdOut, "%s%s: %s [fast: %t, auto-fix: %t]\n", + color.YellowString(lc.Name()), deprecatedMark, linterDescription, !lc.IsSlowLinter(), lc.CanAutoFix) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/builder.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/builder.go new file mode 100644 index 000000000..f0e259fb0 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/builder.go @@ -0,0 +1,250 @@ +package internal + +import ( + "context" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" + "unicode" + + "github.com/golangci/golangci-lint/pkg/logutils" +) + +// Builder runs all the required commands to build a binary. +type Builder struct { + cfg *Configuration + + log logutils.Log + + root string + repo string +} + +// NewBuilder creates a new Builder. +func NewBuilder(logger logutils.Log, cfg *Configuration, root string) *Builder { + return &Builder{ + cfg: cfg, + log: logger, + root: root, + repo: filepath.Join(root, "golangci-lint"), + } +} + +// Build builds the custom binary. +func (b Builder) Build(ctx context.Context) error { + b.log.Infof("Cloning golangci-lint repository") + + err := b.clone(ctx) + if err != nil { + return fmt.Errorf("clone golangci-lint: %w", err) + } + + b.log.Infof("Adding plugin imports") + + err = b.updatePluginsFile() + if err != nil { + return fmt.Errorf("update plugin file: %w", err) + } + + b.log.Infof("Adding replace directives") + + err = b.addToGoMod(ctx) + if err != nil { + return fmt.Errorf("add to go.mod: %w", err) + } + + b.log.Infof("Running go mod tidy") + + err = b.goModTidy(ctx) + if err != nil { + return fmt.Errorf("go mod tidy: %w", err) + } + + b.log.Infof("Building golangci-lint binary") + + binaryName := b.getBinaryName() + + err = b.goBuild(ctx, binaryName) + if err != nil { + return fmt.Errorf("build golangci-lint binary: %w", err) + } + + b.log.Infof("Moving golangci-lint binary") + + err = b.copyBinary(binaryName) + if err != nil { + return fmt.Errorf("move golangci-lint binary: %w", err) + } + + return nil +} + +func (b Builder) clone(ctx context.Context) error { + //nolint:gosec // the variable is sanitized. + cmd := exec.CommandContext(ctx, + "git", "clone", "--branch", sanitizeVersion(b.cfg.Version), + "--single-branch", "--depth", "1", "-c advice.detachedHead=false", "-q", + "https://github.com/golangci/golangci-lint.git", + ) + cmd.Dir = b.root + + output, err := cmd.CombinedOutput() + if err != nil { + b.log.Infof("%s", string(output)) + + return fmt.Errorf("%s: %w", strings.Join(cmd.Args, " "), err) + } + + return nil +} + +func (b Builder) addToGoMod(ctx context.Context) error { + for _, plugin := range b.cfg.Plugins { + if plugin.Path != "" { + err := b.addReplaceDirective(ctx, plugin) + if err != nil { + return err + } + + continue + } + + err := b.goGet(ctx, plugin) + if err != nil { + return err + } + } + + return nil +} + +func (b Builder) goGet(ctx context.Context, plugin *Plugin) error { + //nolint:gosec // the variables are user related. + cmd := exec.CommandContext(ctx, "go", "get", plugin.Module+"@"+plugin.Version) + cmd.Dir = b.repo + + b.log.Infof("run: %s", strings.Join(cmd.Args, " ")) + + output, err := cmd.CombinedOutput() + if err != nil { + b.log.Warnf("%s", string(output)) + + return fmt.Errorf("%s: %w", strings.Join(cmd.Args, " "), err) + } + + return nil +} + +func (b Builder) addReplaceDirective(ctx context.Context, plugin *Plugin) error { + replace := fmt.Sprintf("%s=%s", plugin.Module, plugin.Path) + + cmd := exec.CommandContext(ctx, "go", "mod", "edit", "-replace", replace) + cmd.Dir = b.repo + + b.log.Infof("run: %s", strings.Join(cmd.Args, " ")) + + output, err := cmd.CombinedOutput() + if err != nil { + b.log.Warnf("%s", string(output)) + + return fmt.Errorf("%s: %w", strings.Join(cmd.Args, " "), err) + } + + return nil +} + +func (b Builder) goModTidy(ctx context.Context) error { + cmd := exec.CommandContext(ctx, "go", "mod", "tidy") + cmd.Dir = b.repo + + output, err := cmd.CombinedOutput() + if err != nil { + b.log.Warnf("%s", string(output)) + + return fmt.Errorf("%s: %w", strings.Join(cmd.Args, " "), err) + } + + return nil +} + +func (b Builder) goBuild(ctx context.Context, binaryName string) error { + //nolint:gosec // the variable is sanitized. + cmd := exec.CommandContext(ctx, "go", "build", + "-ldflags", + fmt.Sprintf( + "-s -w -X 'main.version=%s-custom-gcl' -X 'main.date=%s'", + sanitizeVersion(b.cfg.Version), time.Now().UTC().String(), + ), + "-o", binaryName, + "./cmd/golangci-lint", + ) + cmd.Dir = b.repo + + output, err := cmd.CombinedOutput() + if err != nil { + b.log.Warnf("%s", string(output)) + + return fmt.Errorf("%s: %w", strings.Join(cmd.Args, " "), err) + } + + return nil +} + +func (b Builder) copyBinary(binaryName string) error { + src := filepath.Join(b.repo, binaryName) + + source, err := os.Open(filepath.Clean(src)) + if err != nil { + return fmt.Errorf("open source file: %w", err) + } + + defer func() { _ = source.Close() }() + + info, err := source.Stat() + if err != nil { + return fmt.Errorf("stat source file: %w", err) + } + + if b.cfg.Destination != "" { + err = os.MkdirAll(b.cfg.Destination, os.ModePerm) + if err != nil { + return fmt.Errorf("create destination directory: %w", err) + } + } + + dst, err := os.OpenFile(filepath.Join(b.cfg.Destination, binaryName), os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode()) + if err != nil { + return fmt.Errorf("create destination file: %w", err) + } + + defer func() { _ = dst.Close() }() + + _, err = io.Copy(dst, source) + if err != nil { + return fmt.Errorf("copy source to destination: %w", err) + } + + return nil +} + +func (b Builder) getBinaryName() string { + name := b.cfg.Name + if runtime.GOOS == "windows" { + name += ".exe" + } + + return name +} + +func sanitizeVersion(v string) string { + fn := func(c rune) bool { + return !(unicode.IsLetter(c) || unicode.IsNumber(c) || c == '.' || c == '/') + } + + return strings.Join(strings.FieldsFunc(v, fn), "") +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/configuration.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/configuration.go new file mode 100644 index 000000000..f9de4c47a --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/configuration.go @@ -0,0 +1,140 @@ +package internal + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "gopkg.in/yaml.v3" +) + +const base = ".custom-gcl" + +const defaultBinaryName = "custom-gcl" + +// Configuration represents the configuration file. +type Configuration struct { + // golangci-lint version. + Version string `yaml:"version"` + + // Name of the binary. + Name string `yaml:"name,omitempty"` + + // Destination is the path to a directory to store the binary. + Destination string `yaml:"destination,omitempty"` + + // Plugins information. + Plugins []*Plugin `yaml:"plugins,omitempty"` +} + +// Validate checks and clean the configuration. +func (c *Configuration) Validate() error { + if strings.TrimSpace(c.Version) == "" { + return errors.New("root field 'version' is required") + } + + if strings.TrimSpace(c.Name) == "" { + c.Name = defaultBinaryName + } + + if len(c.Plugins) == 0 { + return errors.New("no plugins defined") + } + + for _, plugin := range c.Plugins { + if strings.TrimSpace(plugin.Module) == "" { + return errors.New("field 'module' is required") + } + + if strings.TrimSpace(plugin.Import) == "" { + plugin.Import = plugin.Module + } + + if strings.TrimSpace(plugin.Path) == "" && strings.TrimSpace(plugin.Version) == "" { + return errors.New("missing information: 'version' or 'path' should be provided") + } + + if strings.TrimSpace(plugin.Path) != "" && strings.TrimSpace(plugin.Version) != "" { + return errors.New("invalid configuration: 'version' and 'path' should not be provided at the same time") + } + + if strings.TrimSpace(plugin.Path) == "" { + continue + } + + abs, err := filepath.Abs(plugin.Path) + if err != nil { + return err + } + + plugin.Path = abs + } + + return nil +} + +// Plugin represents information about a plugin. +type Plugin struct { + // Module name. + Module string `yaml:"module"` + + // Import to use. + Import string `yaml:"import,omitempty"` + + // Version of the module. + // Only for module available through a Go proxy. + Version string `yaml:"version,omitempty"` + + // Path to the local module. + // Only for local module. + Path string `yaml:"path,omitempty"` +} + +func LoadConfiguration() (*Configuration, error) { + configFilePath, err := findConfigurationFile() + if err != nil { + return nil, fmt.Errorf("file %s not found: %w", configFilePath, err) + } + + file, err := os.Open(configFilePath) + if err != nil { + return nil, fmt.Errorf("file %s open: %w", configFilePath, err) + } + + defer func() { _ = file.Close() }() + + var cfg Configuration + + err = yaml.NewDecoder(file).Decode(&cfg) + if err != nil { + return nil, fmt.Errorf("YAML decoding: %w", err) + } + + return &cfg, nil +} + +func findConfigurationFile() (string, error) { + entries, err := os.ReadDir(".") + if err != nil { + return "", fmt.Errorf("read directory: %w", err) + } + + for _, entry := range entries { + ext := filepath.Ext(entry.Name()) + + switch strings.ToLower(strings.TrimPrefix(ext, ".")) { + case "yml", "yaml", "json": + if isConf(ext, entry.Name()) { + return entry.Name(), nil + } + } + } + + return "", errors.New("configuration file not found") +} + +func isConf(ext, name string) bool { + return base+ext == name +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/imports.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/imports.go new file mode 100644 index 000000000..3bebf596b --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/imports.go @@ -0,0 +1,69 @@ +package internal + +import ( + "bytes" + "fmt" + "go/format" + "os" + "path/filepath" + "text/template" +) + +const importsTemplate = ` +package main + +import ( +{{range .Imports -}} + _ "{{.}}" +{{end -}} +) +` + +func (b Builder) updatePluginsFile() error { + importsDest := filepath.Join(b.repo, "cmd", "golangci-lint", "plugins.go") + + info, err := os.Stat(importsDest) + if err != nil { + return fmt.Errorf("file %s not found: %w", importsDest, err) + } + + source, err := generateImports(b.cfg) + if err != nil { + return fmt.Errorf("generate imports: %w", err) + } + + b.log.Infof("generated imports info %s:\n%s\n", importsDest, source) + + err = os.WriteFile(filepath.Clean(importsDest), source, info.Mode()) + if err != nil { + return fmt.Errorf("write file %s: %w", importsDest, err) + } + + return nil +} + +func generateImports(cfg *Configuration) ([]byte, error) { + impTmpl, err := template.New("plugins.go").Parse(importsTemplate) + if err != nil { + return nil, fmt.Errorf("parse template: %w", err) + } + + var imps []string + for _, plugin := range cfg.Plugins { + imps = append(imps, plugin.Import) + } + + buf := &bytes.Buffer{} + + err = impTmpl.Execute(buf, map[string]any{"Imports": imps}) + if err != nil { + return nil, fmt.Errorf("execute template: %w", err) + } + + source, err := format.Source(buf.Bytes()) + if err != nil { + return nil, fmt.Errorf("format source: %w", err) + } + + return source, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/vibra.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/vibra.go new file mode 100644 index 000000000..ece2483fe --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/internal/vibra.go @@ -0,0 +1,59 @@ +package internal + +import ( + "fmt" + + "github.com/spf13/pflag" + "github.com/spf13/viper" +) + +type FlagFunc[T any] func(name string, value T, usage string) *T + +type FlagPFunc[T any] func(name, shorthand string, value T, usage string) *T + +// AddFlagAndBind adds a Cobra/pflag flag and binds it with Viper. +func AddFlagAndBind[T any](v *viper.Viper, fs *pflag.FlagSet, pfn FlagFunc[T], name, bind string, value T, usage string) { + pfn(name, value, usage) + + err := v.BindPFlag(bind, fs.Lookup(name)) + if err != nil { + panic(fmt.Sprintf("failed to bind flag %s: %v", name, err)) + } +} + +// AddFlagAndBindP adds a Cobra/pflag flag and binds it with Viper. +func AddFlagAndBindP[T any](v *viper.Viper, fs *pflag.FlagSet, pfn FlagPFunc[T], name, shorthand, bind string, value T, usage string) { + pfn(name, shorthand, value, usage) + + err := v.BindPFlag(bind, fs.Lookup(name)) + if err != nil { + panic(fmt.Sprintf("failed to bind flag %s: %v", name, err)) + } +} + +// AddDeprecatedFlagAndBind similar to AddFlagAndBind but deprecate the flag. +func AddDeprecatedFlagAndBind[T any](v *viper.Viper, fs *pflag.FlagSet, pfn FlagFunc[T], name, bind string, value T, usage string) { + AddFlagAndBind(v, fs, pfn, name, bind, value, usage) + deprecateFlag(fs, name) +} + +// AddHackedStringSliceP Hack for slice, see Loader.applyStringSliceHack. +func AddHackedStringSliceP(fs *pflag.FlagSet, name, shorthand, usage string) { + fs.StringSliceP(name, shorthand, nil, usage) +} + +// AddHackedStringSlice Hack for slice, see Loader.applyStringSliceHack. +func AddHackedStringSlice(fs *pflag.FlagSet, name, usage string) { + AddHackedStringSliceP(fs, name, "", usage) +} + +// AddDeprecatedHackedStringSlice similar to AddHackedStringSlice but deprecate the flag. +func AddDeprecatedHackedStringSlice(fs *pflag.FlagSet, name, usage string) { + AddHackedStringSlice(fs, name, usage) + deprecateFlag(fs, name) +} + +func deprecateFlag(fs *pflag.FlagSet, name string) { + _ = fs.MarkHidden(name) + _ = fs.MarkDeprecated(name, "check the documentation for more information.") +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go index 292713ec9..a93814f0f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go @@ -5,53 +5,103 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/lint/lintersdb" + "github.com/golangci/golangci-lint/pkg/logutils" ) -func (e *Executor) initLinters() { - e.lintersCmd = &cobra.Command{ +type lintersOptions struct { + config.LoaderOptions +} + +type lintersCommand struct { + viper *viper.Viper + cmd *cobra.Command + + opts lintersOptions + + cfg *config.Config + + log logutils.Log + + dbManager *lintersdb.Manager +} + +func newLintersCommand(logger logutils.Log) *lintersCommand { + c := &lintersCommand{ + viper: viper.New(), + cfg: config.NewDefault(), + log: logger, + } + + lintersCmd := &cobra.Command{ Use: "linters", Short: "List current linters configuration", Args: cobra.NoArgs, ValidArgsFunction: cobra.NoFileCompletions, - RunE: e.executeLinters, + RunE: c.execute, + PreRunE: c.preRunE, + SilenceUsage: true, } - e.rootCmd.AddCommand(e.lintersCmd) - e.initRunConfiguration(e.lintersCmd) + + fs := lintersCmd.Flags() + fs.SortFlags = false // sort them as they are defined here + + setupConfigFileFlagSet(fs, &c.opts.LoaderOptions) + setupLintersFlagSet(c.viper, fs) + + c.cmd = lintersCmd + + return c } -// executeLinters runs the 'linters' CLI command, which displays the supported linters. -func (e *Executor) executeLinters(_ *cobra.Command, _ []string) error { - enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap() +func (c *lintersCommand) preRunE(cmd *cobra.Command, args []string) error { + loader := config.NewLoader(c.log.Child(logutils.DebugKeyConfigReader), c.viper, cmd.Flags(), c.opts.LoaderOptions, c.cfg, args) + + err := loader.Load(config.LoadOptions{Validation: true}) if err != nil { - return fmt.Errorf("can't get enabled linters: %w", err) + return fmt.Errorf("can't load config: %w", err) } - color.Green("Enabled by your configuration linters:\n") - var enabledLinters []*linter.Config - for _, lc := range enabledLintersMap { - if lc.Internal { - continue - } + dbManager, err := lintersdb.NewManager(c.log.Child(logutils.DebugKeyLintersDB), c.cfg, + lintersdb.NewLinterBuilder(), lintersdb.NewPluginModuleBuilder(c.log), lintersdb.NewPluginGoBuilder(c.log)) + if err != nil { + return err + } + + c.dbManager = dbManager - enabledLinters = append(enabledLinters, lc) + return nil +} + +func (c *lintersCommand) execute(_ *cobra.Command, _ []string) error { + enabledLintersMap, err := c.dbManager.GetEnabledLintersMap() + if err != nil { + return fmt.Errorf("can't get enabled linters: %w", err) } - printLinterConfigs(enabledLinters) + var enabledLinters []*linter.Config var disabledLCs []*linter.Config - for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { + + for _, lc := range c.dbManager.GetAllSupportedLinterConfigs() { if lc.Internal { continue } if enabledLintersMap[lc.Name()] == nil { disabledLCs = append(disabledLCs, lc) + } else { + enabledLinters = append(enabledLinters, lc) } } + color.Green("Enabled by your configuration linters:\n") + printLinters(enabledLinters) color.Red("\nDisabled by your configuration linters:\n") - printLinterConfigs(disabledLCs) + printLinters(disabledLCs) return nil } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go index efe62ced2..cbb838aac 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go @@ -1,174 +1,167 @@ package commands import ( + "errors" "fmt" "os" - "runtime" - "runtime/pprof" - "runtime/trace" - "strconv" + "slices" + "github.com/fatih/color" "github.com/spf13/cobra" "github.com/spf13/pflag" - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/exitcodes" "github.com/golangci/golangci-lint/pkg/logutils" ) -const ( - // envHelpRun value: "1". - envHelpRun = "HELP_RUN" - envMemProfileRate = "GL_MEM_PROFILE_RATE" -) +func Execute(info BuildInfo) error { + return newRootCommand(info).Execute() +} -func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) error { - if e.cfg.Run.PrintVersion { - _ = printVersion(logutils.StdOut, e.buildInfo) - os.Exit(exitcodes.Success) // a return nil is not enough to stop the process because we are inside the `preRun`. - } +type rootOptions struct { + PrintVersion bool // Flag only. - runtime.GOMAXPROCS(e.cfg.Run.Concurrency) + Verbose bool // Flag only. + Color string // Flag only. +} - if e.cfg.Run.CPUProfilePath != "" { - f, err := os.Create(e.cfg.Run.CPUProfilePath) - if err != nil { - return fmt.Errorf("can't create file %s: %w", e.cfg.Run.CPUProfilePath, err) - } - if err := pprof.StartCPUProfile(f); err != nil { - return fmt.Errorf("can't start CPU profiling: %w", err) - } - } +type rootCommand struct { + cmd *cobra.Command + opts rootOptions - if e.cfg.Run.MemProfilePath != "" { - if rate := os.Getenv(envMemProfileRate); rate != "" { - runtime.MemProfileRate, _ = strconv.Atoi(rate) - } - } + log logutils.Log +} - if e.cfg.Run.TracePath != "" { - f, err := os.Create(e.cfg.Run.TracePath) - if err != nil { - return fmt.Errorf("can't create file %s: %w", e.cfg.Run.TracePath, err) - } - if err = trace.Start(f); err != nil { - return fmt.Errorf("can't start tracing: %w", err) - } - } +func newRootCommand(info BuildInfo) *rootCommand { + c := &rootCommand{} - return nil -} + rootCmd := &cobra.Command{ + Use: "golangci-lint", + Short: "golangci-lint is a smart linters runner.", + Long: `Smart, fast linters runner.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if c.opts.PrintVersion { + _ = printVersion(logutils.StdOut, info) + return nil + } -func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) error { - if e.cfg.Run.CPUProfilePath != "" { - pprof.StopCPUProfile() + return cmd.Help() + }, } - if e.cfg.Run.MemProfilePath != "" { - f, err := os.Create(e.cfg.Run.MemProfilePath) - if err != nil { - return fmt.Errorf("can't create file %s: %w", e.cfg.Run.MemProfilePath, err) - } + fs := rootCmd.Flags() + fs.BoolVar(&c.opts.PrintVersion, "version", false, color.GreenString("Print version")) - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - printMemStats(&ms, e.log) + setupRootPersistentFlags(rootCmd.PersistentFlags(), &c.opts) - if err := pprof.WriteHeapProfile(f); err != nil { - return fmt.Errorf("cCan't write heap profile: %w", err) - } - _ = f.Close() - } + log := logutils.NewStderrLog(logutils.DebugKeyEmpty) - if e.cfg.Run.TracePath != "" { - trace.Stop() - } + // Each command uses a dedicated configuration structure to avoid side effects of bindings. + rootCmd.AddCommand( + newLintersCommand(log).cmd, + newRunCommand(log, info).cmd, + newCacheCommand().cmd, + newConfigCommand(log, info).cmd, + newVersionCommand(info).cmd, + newCustomCommand(log).cmd, + ) - os.Exit(e.exitCode) + rootCmd.SetHelpCommand(newHelpCommand(log).cmd) - return nil + c.log = log + c.cmd = rootCmd + + return c } -func printMemStats(ms *runtime.MemStats, logger logutils.Log) { - logger.Infof("Mem stats: alloc=%s total_alloc=%s sys=%s "+ - "heap_alloc=%s heap_sys=%s heap_idle=%s heap_released=%s heap_in_use=%s "+ - "stack_in_use=%s stack_sys=%s "+ - "mspan_sys=%s mcache_sys=%s buck_hash_sys=%s gc_sys=%s other_sys=%s "+ - "mallocs_n=%d frees_n=%d heap_objects_n=%d gc_cpu_fraction=%.2f", - formatMemory(ms.Alloc), formatMemory(ms.TotalAlloc), formatMemory(ms.Sys), - formatMemory(ms.HeapAlloc), formatMemory(ms.HeapSys), - formatMemory(ms.HeapIdle), formatMemory(ms.HeapReleased), formatMemory(ms.HeapInuse), - formatMemory(ms.StackInuse), formatMemory(ms.StackSys), - formatMemory(ms.MSpanSys), formatMemory(ms.MCacheSys), formatMemory(ms.BuckHashSys), - formatMemory(ms.GCSys), formatMemory(ms.OtherSys), - ms.Mallocs, ms.Frees, ms.HeapObjects, ms.GCCPUFraction) +func (c *rootCommand) Execute() error { + err := setupLogger(c.log) + if err != nil { + return err + } + + return c.cmd.Execute() } -func formatMemory(memBytes uint64) string { - const Kb = 1024 - const Mb = Kb * 1024 +func setupRootPersistentFlags(fs *pflag.FlagSet, opts *rootOptions) { + fs.BoolP("help", "h", false, color.GreenString("Help for a command")) + fs.BoolVarP(&opts.Verbose, "verbose", "v", false, color.GreenString("Verbose output")) + fs.StringVar(&opts.Color, "color", "auto", color.GreenString("Use color when printing; can be 'always', 'auto', or 'never'")) +} - if memBytes < Kb { - return fmt.Sprintf("%db", memBytes) +func setupLogger(logger logutils.Log) error { + opts, err := forceRootParsePersistentFlags() + if err != nil && !errors.Is(err, pflag.ErrHelp) { + return err } - if memBytes < Mb { - return fmt.Sprintf("%dkb", memBytes/Kb) + + if opts == nil { + return nil } - return fmt.Sprintf("%dmb", memBytes/Mb) -} -func getDefaultConcurrency() int { - if os.Getenv(envHelpRun) == "1" { - // Make stable concurrency for README help generating builds. - const prettyConcurrency = 8 - return prettyConcurrency + logutils.SetupVerboseLog(logger, opts.Verbose) + + switch opts.Color { + case "always": + color.NoColor = false + case "never": + color.NoColor = true + case "auto": + // nothing + default: + logger.Fatalf("invalid value %q for --color; must be 'always', 'auto', or 'never'", opts.Color) } - return runtime.NumCPU() + return nil } -func (e *Executor) initRoot() { - rootCmd := &cobra.Command{ - Use: "golangci-lint", - Short: "golangci-lint is a smart linters runner.", - Long: `Smart, fast linters runner.`, - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, _ []string) error { - return cmd.Help() - }, - PersistentPreRunE: e.persistentPreRun, - PersistentPostRunE: e.persistentPostRun, - } +func forceRootParsePersistentFlags() (*rootOptions, error) { + // We use another pflag.FlagSet here to not set `changed` flag on cmd.Flags() options. + // Otherwise, string slice options will be duplicated. + fs := pflag.NewFlagSet("config flag set", pflag.ContinueOnError) - initRootFlagSet(rootCmd.PersistentFlags(), e.cfg, e.needVersionOption()) - e.rootCmd = rootCmd -} + // Ignore unknown flags because we will parse the command flags later. + fs.ParseErrorsWhitelist = pflag.ParseErrorsWhitelist{UnknownFlags: true} -func (e *Executor) needVersionOption() bool { - return e.buildInfo.Date != "" -} + opts := &rootOptions{} -func initRootFlagSet(fs *pflag.FlagSet, cfg *config.Config, needVersionOption bool) { - fs.BoolVarP(&cfg.Run.IsVerbose, "verbose", "v", false, wh("Verbose output")) + // Don't do `fs.AddFlagSet(cmd.Flags())` because it shares flags representations: + // `changed` variable inside string slice vars will be shared. + // Use another config variable here, + // to not affect main parsing by this parsing of only config option. + setupRootPersistentFlags(fs, opts) - var silent bool - fs.BoolVarP(&silent, "silent", "s", false, wh("Disables congrats outputs")) - if err := fs.MarkHidden("silent"); err != nil { - panic(err) - } - err := fs.MarkDeprecated("silent", - "now golangci-lint by default is silent: it doesn't print Congrats message") - if err != nil { - panic(err) + fs.Usage = func() {} // otherwise, help text will be printed twice + + if err := fs.Parse(safeArgs(fs, os.Args)); err != nil { + if errors.Is(err, pflag.ErrHelp) { + return nil, err + } + + return nil, fmt.Errorf("can't parse args: %w", err) } - fs.StringVar(&cfg.Run.CPUProfilePath, "cpu-profile-path", "", wh("Path to CPU profile output file")) - fs.StringVar(&cfg.Run.MemProfilePath, "mem-profile-path", "", wh("Path to memory profile output file")) - fs.StringVar(&cfg.Run.TracePath, "trace-path", "", wh("Path to trace output file")) - fs.IntVarP(&cfg.Run.Concurrency, "concurrency", "j", getDefaultConcurrency(), wh("Concurrency (default NumCPU)")) - if needVersionOption { - fs.BoolVar(&cfg.Run.PrintVersion, "version", false, wh("Print version")) + return opts, nil +} + +// Shorthands are a problem because pflag, with UnknownFlags, will try to parse all the letters as options. +// A shorthand can aggregate several letters (ex `ps -aux`) +// The function replaces non-supported shorthands by a dumb flag. +func safeArgs(fs *pflag.FlagSet, args []string) []string { + var shorthands []string + fs.VisitAll(func(flag *pflag.Flag) { + shorthands = append(shorthands, flag.Shorthand) + }) + + var cleanArgs []string + for _, arg := range args { + if len(arg) > 1 && arg[0] == '-' && arg[1] != '-' && !slices.Contains(shorthands, string(arg[1])) { + cleanArgs = append(cleanArgs, "--potato") + continue + } + + cleanArgs = append(cleanArgs, arg) } - fs.StringVar(&cfg.Output.Color, "color", "auto", wh("Use color when printing; can be 'always', 'auto', or 'never'")) + return cleanArgs } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go index 9149b177b..f289bfdd7 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go @@ -1,31 +1,50 @@ package commands import ( + "bytes" "context" + "crypto/sha256" "errors" "fmt" "io" "log" "os" + "path/filepath" "runtime" + "runtime/pprof" + "runtime/trace" + "sort" + "strconv" "strings" "time" "github.com/fatih/color" + "github.com/gofrs/flock" "github.com/spf13/cobra" "github.com/spf13/pflag" + "github.com/spf13/viper" + "go.uber.org/automaxprocs/maxprocs" + "golang.org/x/exp/maps" + "gopkg.in/yaml.v3" + "github.com/golangci/golangci-lint/internal/cache" + "github.com/golangci/golangci-lint/internal/pkgcache" "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/exitcodes" + "github.com/golangci/golangci-lint/pkg/fsutils" + "github.com/golangci/golangci-lint/pkg/goanalysis/load" + "github.com/golangci/golangci-lint/pkg/goutil" "github.com/golangci/golangci-lint/pkg/lint" + "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/lintersdb" "github.com/golangci/golangci-lint/pkg/logutils" - "github.com/golangci/golangci-lint/pkg/packages" "github.com/golangci/golangci-lint/pkg/printers" + "github.com/golangci/golangci-lint/pkg/report" "github.com/golangci/golangci-lint/pkg/result" + "github.com/golangci/golangci-lint/pkg/timeutils" ) -const defaultFileMode = 0644 +const defaultTimeout = time.Minute const ( // envFailOnWarnings value: "1" @@ -34,524 +53,468 @@ const ( envMemLogEvery = "GL_MEM_LOG_EVERY" ) -func getDefaultIssueExcludeHelp() string { - parts := []string{"Use or not use default excludes:"} - for _, ep := range config.DefaultExcludePatterns { - parts = append(parts, - fmt.Sprintf(" # %s %s: %s", ep.ID, ep.Linter, ep.Why), - fmt.Sprintf(" - %s", color.YellowString(ep.Pattern)), - "", - ) - } - return strings.Join(parts, "\n") -} +const ( + // envHelpRun value: "1". + envHelpRun = "HELP_RUN" + envMemProfileRate = "GL_MEM_PROFILE_RATE" +) -func getDefaultDirectoryExcludeHelp() string { - parts := []string{"Use or not use default excluded directories:"} - for _, dir := range packages.StdExcludeDirRegexps { - parts = append(parts, fmt.Sprintf(" - %s", color.YellowString(dir))) - } - parts = append(parts, "") - return strings.Join(parts, "\n") +type runOptions struct { + config.LoaderOptions + + CPUProfilePath string // Flag only. + MemProfilePath string // Flag only. + TracePath string // Flag only. + + PrintResourcesUsage bool // Flag only. } -func wh(text string) string { - return color.GreenString(text) +type runCommand struct { + viper *viper.Viper + cmd *cobra.Command + + opts runOptions + + cfg *config.Config + + buildInfo BuildInfo + + dbManager *lintersdb.Manager + + printer *printers.Printer + + log logutils.Log + debugf logutils.DebugFunc + reportData *report.Data + + contextBuilder *lint.ContextBuilder + goenv *goutil.Env + + fileCache *fsutils.FileCache + lineCache *fsutils.LineCache + + flock *flock.Flock + + exitCode int } -const defaultTimeout = time.Minute +func newRunCommand(logger logutils.Log, info BuildInfo) *runCommand { + reportData := &report.Data{} -//nolint:funlen,gomnd -func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, isFinalInit bool) { - hideFlag := func(name string) { - if err := fs.MarkHidden(name); err != nil { - panic(err) - } + c := &runCommand{ + viper: viper.New(), + log: report.NewLogWrapper(logger, reportData), + debugf: logutils.Debug(logutils.DebugKeyExec), + cfg: config.NewDefault(), + reportData: reportData, + buildInfo: info, + } - // we run initFlagSet multiple times, but we wouldn't like to see deprecation message multiple times - if isFinalInit { - const deprecateMessage = "flag will be removed soon, please, use .golangci.yml config" - if err := fs.MarkDeprecated(name, deprecateMessage); err != nil { - panic(err) - } - } + runCmd := &cobra.Command{ + Use: "run", + Short: "Run the linters", + Run: c.execute, + PreRunE: c.preRunE, + PostRun: c.postRun, + PersistentPreRunE: c.persistentPreRunE, + PersistentPostRunE: c.persistentPostRunE, + SilenceUsage: true, } - // Output config - oc := &cfg.Output - fs.StringVar(&oc.Format, "out-format", - config.OutFormatColoredLineNumber, - wh(fmt.Sprintf("Format of output: %s", strings.Join(config.OutFormats, "|")))) - fs.BoolVar(&oc.PrintIssuedLine, "print-issued-lines", true, wh("Print lines of code with issue")) - fs.BoolVar(&oc.PrintLinterName, "print-linter-name", true, wh("Print linter name in issue line")) - fs.BoolVar(&oc.UniqByLine, "uniq-by-line", true, wh("Make issues output unique by line")) - fs.BoolVar(&oc.SortResults, "sort-results", false, wh("Sort linter results")) - fs.BoolVar(&oc.PrintWelcomeMessage, "print-welcome", false, wh("Print welcome message")) - fs.StringVar(&oc.PathPrefix, "path-prefix", "", wh("Path prefix to add to output")) - hideFlag("print-welcome") // no longer used - - fs.BoolVar(&cfg.InternalCmdTest, "internal-cmd-test", false, wh("Option is used only for testing golangci-lint command, don't use it")) - if err := fs.MarkHidden("internal-cmd-test"); err != nil { - panic(err) - } - - // Run config - rc := &cfg.Run - fs.StringVar(&rc.ModulesDownloadMode, "modules-download-mode", "", - "Modules download mode. If not empty, passed as -mod= to go tools") - fs.IntVar(&rc.ExitCodeIfIssuesFound, "issues-exit-code", - exitcodes.IssuesFound, wh("Exit code when issues were found")) - fs.StringVar(&rc.Go, "go", "", wh("Targeted Go version")) - fs.StringSliceVar(&rc.BuildTags, "build-tags", nil, wh("Build tags")) - - fs.DurationVar(&rc.Timeout, "deadline", defaultTimeout, wh("Deadline for total work")) - if err := fs.MarkHidden("deadline"); err != nil { - panic(err) - } - fs.DurationVar(&rc.Timeout, "timeout", defaultTimeout, wh("Timeout for total work")) - - fs.BoolVar(&rc.AnalyzeTests, "tests", true, wh("Analyze tests (*_test.go)")) - fs.BoolVar(&rc.PrintResourcesUsage, "print-resources-usage", false, - wh("Print avg and max memory usage of golangci-lint and total time")) - fs.StringVarP(&rc.Config, "config", "c", "", wh("Read config from file path `PATH`")) - fs.BoolVar(&rc.NoConfig, "no-config", false, wh("Don't read config")) - fs.StringSliceVar(&rc.SkipDirs, "skip-dirs", nil, wh("Regexps of directories to skip")) - fs.BoolVar(&rc.UseDefaultSkipDirs, "skip-dirs-use-default", true, getDefaultDirectoryExcludeHelp()) - fs.StringSliceVar(&rc.SkipFiles, "skip-files", nil, wh("Regexps of files to skip")) - - const allowParallelDesc = "Allow multiple parallel golangci-lint instances running. " + - "If false (default) - golangci-lint acquires file lock on start." - fs.BoolVar(&rc.AllowParallelRunners, "allow-parallel-runners", false, wh(allowParallelDesc)) - const allowSerialDesc = "Allow multiple golangci-lint instances running, but serialize them around a lock. " + - "If false (default) - golangci-lint exits with an error if it fails to acquire file lock on start." - fs.BoolVar(&rc.AllowSerialRunners, "allow-serial-runners", false, wh(allowSerialDesc)) - - // Linters settings config - lsc := &cfg.LintersSettings - - // Hide all linters settings flags: they were initially visible, - // but when number of linters started to grow it became obvious that - // we can't fill 90% of flags by linters settings: common flags became hard to find. - // New linters settings should be done only through config file. - fs.BoolVar(&lsc.Errcheck.CheckTypeAssertions, "errcheck.check-type-assertions", - false, "Errcheck: check for ignored type assertion results") - hideFlag("errcheck.check-type-assertions") - fs.BoolVar(&lsc.Errcheck.CheckAssignToBlank, "errcheck.check-blank", false, - "Errcheck: check for errors assigned to blank identifier: _ = errFunc()") - hideFlag("errcheck.check-blank") - fs.StringVar(&lsc.Errcheck.Exclude, "errcheck.exclude", "", - "Path to a file containing a list of functions to exclude from checking") - hideFlag("errcheck.exclude") - fs.StringVar(&lsc.Errcheck.Ignore, "errcheck.ignore", "fmt:.*", - `Comma-separated list of pairs of the form pkg:regex. The regex is used to ignore names within pkg`) - hideFlag("errcheck.ignore") - - fs.BoolVar(&lsc.Govet.CheckShadowing, "govet.check-shadowing", false, - "Govet: check for shadowed variables") - hideFlag("govet.check-shadowing") - - fs.Float64Var(&lsc.Golint.MinConfidence, "golint.min-confidence", 0.8, - "Golint: minimum confidence of a problem to print it") - hideFlag("golint.min-confidence") - - fs.BoolVar(&lsc.Gofmt.Simplify, "gofmt.simplify", true, "Gofmt: simplify code") - hideFlag("gofmt.simplify") - - fs.IntVar(&lsc.Gocyclo.MinComplexity, "gocyclo.min-complexity", - 30, "Minimal complexity of function to report it") - hideFlag("gocyclo.min-complexity") - - fs.BoolVar(&lsc.Maligned.SuggestNewOrder, "maligned.suggest-new", false, - "Maligned: print suggested more optimal struct fields ordering") - hideFlag("maligned.suggest-new") - - fs.IntVar(&lsc.Dupl.Threshold, "dupl.threshold", - 150, "Dupl: Minimal threshold to detect copy-paste") - hideFlag("dupl.threshold") - - fs.BoolVar(&lsc.Goconst.MatchWithConstants, "goconst.match-constant", - true, "Goconst: look for existing constants matching the values") - hideFlag("goconst.match-constant") - fs.IntVar(&lsc.Goconst.MinStringLen, "goconst.min-len", - 3, "Goconst: minimum constant string length") - hideFlag("goconst.min-len") - fs.IntVar(&lsc.Goconst.MinOccurrencesCount, "goconst.min-occurrences", - 3, "Goconst: minimum occurrences of constant string count to trigger issue") - hideFlag("goconst.min-occurrences") - fs.BoolVar(&lsc.Goconst.ParseNumbers, "goconst.numbers", - false, "Goconst: search also for duplicated numbers") - hideFlag("goconst.numbers") - fs.IntVar(&lsc.Goconst.NumberMin, "goconst.min", - 3, "minimum value, only works with goconst.numbers") - hideFlag("goconst.min") - fs.IntVar(&lsc.Goconst.NumberMax, "goconst.max", - 3, "maximum value, only works with goconst.numbers") - hideFlag("goconst.max") - fs.BoolVar(&lsc.Goconst.IgnoreCalls, "goconst.ignore-calls", - true, "Goconst: ignore when constant is not used as function argument") - hideFlag("goconst.ignore-calls") - - fs.IntVar(&lsc.Lll.TabWidth, "lll.tab-width", 1, - "Lll: tab width in spaces") - hideFlag("lll.tab-width") - - // Linters config - lc := &cfg.Linters - fs.StringSliceVarP(&lc.Enable, "enable", "E", nil, wh("Enable specific linter")) - fs.StringSliceVarP(&lc.Disable, "disable", "D", nil, wh("Disable specific linter")) - fs.BoolVar(&lc.EnableAll, "enable-all", false, wh("Enable all linters")) - - fs.BoolVar(&lc.DisableAll, "disable-all", false, wh("Disable all linters")) - fs.StringSliceVarP(&lc.Presets, "presets", "p", nil, - wh(fmt.Sprintf("Enable presets (%s) of linters. Run 'golangci-lint linters' to see "+ - "them. This option implies option --disable-all", strings.Join(m.AllPresets(), "|")))) - fs.BoolVar(&lc.Fast, "fast", false, wh("Run only fast linters from enabled linters set (first run won't be fast)")) - - // Issues config - ic := &cfg.Issues - fs.StringSliceVarP(&ic.ExcludePatterns, "exclude", "e", nil, wh("Exclude issue by regexp")) - fs.BoolVar(&ic.UseDefaultExcludes, "exclude-use-default", true, getDefaultIssueExcludeHelp()) - fs.BoolVar(&ic.ExcludeCaseSensitive, "exclude-case-sensitive", false, wh("If set to true exclude "+ - "and exclude rules regular expressions are case sensitive")) - - fs.IntVar(&ic.MaxIssuesPerLinter, "max-issues-per-linter", 50, - wh("Maximum issues count per one linter. Set to 0 to disable")) - fs.IntVar(&ic.MaxSameIssues, "max-same-issues", 3, - wh("Maximum count of issues with the same text. Set to 0 to disable")) - - fs.BoolVarP(&ic.Diff, "new", "n", false, - wh("Show only new issues: if there are unstaged changes or untracked files, only those changes "+ - "are analyzed, else only changes in HEAD~ are analyzed.\nIt's a super-useful option for integration "+ - "of golangci-lint into existing large codebase.\nIt's not practical to fix all existing issues at "+ - "the moment of integration: much better to not allow issues in new code.\nFor CI setups, prefer "+ - "--new-from-rev=HEAD~, as --new can skip linting the current patch if any scripts generate "+ - "unstaged files before golangci-lint runs.")) - fs.StringVar(&ic.DiffFromRevision, "new-from-rev", "", - wh("Show only new issues created after git revision `REV`")) - fs.StringVar(&ic.DiffPatchFilePath, "new-from-patch", "", - wh("Show only new issues created in git patch with file path `PATH`")) - fs.BoolVar(&ic.WholeFiles, "whole-files", false, - wh("Show issues in any part of update files (requires new-from-rev or new-from-patch)")) - fs.BoolVar(&ic.NeedFix, "fix", false, "Fix found issues (if it's supported by the linter)") -} + runCmd.SetOut(logutils.StdOut) // use custom output to properly color it in Windows terminals + runCmd.SetErr(logutils.StdErr) -func (e *Executor) initRunConfiguration(cmd *cobra.Command) { - fs := cmd.Flags() + fs := runCmd.Flags() fs.SortFlags = false // sort them as they are defined here - initFlagSet(fs, e.cfg, e.DBManager, true) -} -func (e *Executor) getConfigForCommandLine() (*config.Config, error) { - // We use another pflag.FlagSet here to not set `changed` flag - // on cmd.Flags() options. Otherwise, string slice options will be duplicated. - fs := pflag.NewFlagSet("config flag set", pflag.ContinueOnError) - - var cfg config.Config - // Don't do `fs.AddFlagSet(cmd.Flags())` because it shares flags representations: - // `changed` variable inside string slice vars will be shared. - // Use another config variable here, not e.cfg, to not - // affect main parsing by this parsing of only config option. - initFlagSet(fs, &cfg, e.DBManager, false) - initVersionFlagSet(fs, &cfg) - - // Parse max options, even force version option: don't want - // to get access to Executor here: it's error-prone to use - // cfg vs e.cfg. - initRootFlagSet(fs, &cfg, true) - - fs.Usage = func() {} // otherwise, help text will be printed twice - if err := fs.Parse(os.Args); err != nil { - if err == pflag.ErrHelp { - return nil, err - } + // Only for testing purpose. + // Don't add other flags here. + fs.BoolVar(&c.cfg.InternalCmdTest, "internal-cmd-test", false, + color.GreenString("Option is used only for testing golangci-lint command, don't use it")) + _ = fs.MarkHidden("internal-cmd-test") - return nil, fmt.Errorf("can't parse args: %s", err) - } + setupConfigFileFlagSet(fs, &c.opts.LoaderOptions) + + setupLintersFlagSet(c.viper, fs) + setupRunFlagSet(c.viper, fs) + setupOutputFlagSet(c.viper, fs) + setupIssuesFlagSet(c.viper, fs) - return &cfg, nil + setupRunPersistentFlags(runCmd.PersistentFlags(), &c.opts) + + c.cmd = runCmd + + return c } -func (e *Executor) initRun() { - e.runCmd = &cobra.Command{ - Use: "run", - Short: "Run the linters", - Run: e.executeRun, - PreRunE: func(_ *cobra.Command, _ []string) error { - if ok := e.acquireFileLock(); !ok { - return errors.New("parallel golangci-lint is running") - } - return nil - }, - PostRun: func(_ *cobra.Command, _ []string) { - e.releaseFileLock() - }, +func (c *runCommand) persistentPreRunE(cmd *cobra.Command, args []string) error { + if err := c.startTracing(); err != nil { + return err } - e.rootCmd.AddCommand(e.runCmd) - e.runCmd.SetOut(logutils.StdOut) // use custom output to properly color it in Windows terminals - e.runCmd.SetErr(logutils.StdErr) + c.log.Infof("%s", c.buildInfo.String()) - e.initRunConfiguration(e.runCmd) -} + loader := config.NewLoader(c.log.Child(logutils.DebugKeyConfigReader), c.viper, cmd.Flags(), c.opts.LoaderOptions, c.cfg, args) -func fixSlicesFlags(fs *pflag.FlagSet) { - // It's a dirty hack to set flag.Changed to true for every string slice flag. - // It's necessary to merge config and command-line slices: otherwise command-line - // flags will always overwrite ones from the config. - fs.VisitAll(func(f *pflag.Flag) { - if f.Value.Type() != "stringSlice" { - return - } + err := loader.Load(config.LoadOptions{CheckDeprecation: true, Validation: true}) + if err != nil { + return fmt.Errorf("can't load config: %w", err) + } + + if c.cfg.Run.Concurrency == 0 { + backup := runtime.GOMAXPROCS(0) - s, err := fs.GetStringSlice(f.Name) + // Automatically set GOMAXPROCS to match Linux container CPU quota. + _, err := maxprocs.Set(maxprocs.Logger(c.log.Infof)) if err != nil { - return + runtime.GOMAXPROCS(backup) } + } else { + runtime.GOMAXPROCS(c.cfg.Run.Concurrency) + } - if s == nil { // assume that every string slice flag has nil as the default - return - } + return nil +} - var safe []string - for _, v := range s { - // add quotes to escape comma because spf13/pflag use a CSV parser: - // https://github.com/spf13/pflag/blob/85dd5c8bc61cfa382fecd072378089d4e856579d/string_slice.go#L43 - safe = append(safe, `"`+v+`"`) - } +func (c *runCommand) persistentPostRunE(_ *cobra.Command, _ []string) error { + if err := c.stopTracing(); err != nil { + return err + } + + os.Exit(c.exitCode) - // calling Set sets Changed to true: next Set calls will append, not overwrite - _ = f.Value.Set(strings.Join(safe, ",")) - }) + return nil } -// runAnalysis executes the linters that have been enabled in the configuration. -func (e *Executor) runAnalysis(ctx context.Context, args []string) ([]result.Issue, error) { - e.cfg.Run.Args = args +func (c *runCommand) preRunE(_ *cobra.Command, args []string) error { + dbManager, err := lintersdb.NewManager(c.log.Child(logutils.DebugKeyLintersDB), c.cfg, + lintersdb.NewLinterBuilder(), lintersdb.NewPluginModuleBuilder(c.log), lintersdb.NewPluginGoBuilder(c.log)) + if err != nil { + return err + } - lintersToRun, err := e.EnabledLintersSet.GetOptimizedLinters() + c.dbManager = dbManager + + printer, err := printers.NewPrinter(c.log, &c.cfg.Output, c.reportData) if err != nil { - return nil, err + return err } - enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap() + c.printer = printer + + c.goenv = goutil.NewEnv(c.log.Child(logutils.DebugKeyGoEnv)) + + c.fileCache = fsutils.NewFileCache() + c.lineCache = fsutils.NewLineCache(c.fileCache) + + sw := timeutils.NewStopwatch("pkgcache", c.log.Child(logutils.DebugKeyStopwatch)) + + pkgCache, err := pkgcache.NewCache(sw, c.log.Child(logutils.DebugKeyPkgCache)) if err != nil { - return nil, err + return fmt.Errorf("failed to build packages cache: %w", err) } - for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { - isEnabled := enabledLintersMap[lc.Name()] != nil - e.reportData.AddLinter(lc.Name(), isEnabled, lc.EnabledByDefault) + guard := load.NewGuard() + + pkgLoader := lint.NewPackageLoader(c.log.Child(logutils.DebugKeyLoader), c.cfg, args, c.goenv, guard) + + c.contextBuilder = lint.NewContextBuilder(c.cfg, pkgLoader, c.fileCache, pkgCache, guard) + + if err = initHashSalt(c.buildInfo.Version, c.cfg); err != nil { + return fmt.Errorf("failed to init hash salt: %w", err) } - lintCtx, err := e.contextLoader.Load(ctx, lintersToRun) - if err != nil { - return nil, fmt.Errorf("context loading failed: %w", err) + if ok := c.acquireFileLock(); !ok { + return errors.New("parallel golangci-lint is running") } - lintCtx.Log = e.log.Child(logutils.DebugKeyLintersContext) - runner, err := lint.NewRunner(e.cfg, e.log.Child(logutils.DebugKeyRunner), - e.goenv, e.EnabledLintersSet, e.lineCache, e.fileCache, e.DBManager, lintCtx.Packages) - if err != nil { - return nil, err + return nil +} + +func (c *runCommand) postRun(_ *cobra.Command, _ []string) { + c.releaseFileLock() +} + +func (c *runCommand) execute(_ *cobra.Command, args []string) { + needTrackResources := logutils.IsVerbose() || c.opts.PrintResourcesUsage + + trackResourcesEndCh := make(chan struct{}) + defer func() { // XXX: this defer must be before ctx.cancel defer + if needTrackResources { // wait until resource tracking finished to print properly + <-trackResourcesEndCh + } + }() + + ctx, cancel := context.WithTimeout(context.Background(), c.cfg.Run.Timeout) + defer cancel() + + if needTrackResources { + go watchResources(ctx, trackResourcesEndCh, c.log, c.debugf) } - return runner.Run(ctx, lintersToRun, lintCtx) + if err := c.runAndPrint(ctx, args); err != nil { + c.log.Errorf("Running error: %s", err) + if c.exitCode == exitcodes.Success { + var exitErr *exitcodes.ExitError + if errors.As(err, &exitErr) { + c.exitCode = exitErr.Code + } else { + c.exitCode = exitcodes.Failure + } + } + } + + c.setupExitCode(ctx) } -func (e *Executor) setOutputToDevNull() (savedStdout, savedStderr *os.File) { - savedStdout, savedStderr = os.Stdout, os.Stderr - devNull, err := os.Open(os.DevNull) - if err != nil { - e.log.Warnf("Can't open null device %q: %s", os.DevNull, err) - return +func (c *runCommand) startTracing() error { + if c.opts.CPUProfilePath != "" { + f, err := os.Create(c.opts.CPUProfilePath) + if err != nil { + return fmt.Errorf("can't create file %s: %w", c.opts.CPUProfilePath, err) + } + if err := pprof.StartCPUProfile(f); err != nil { + return fmt.Errorf("can't start CPU profiling: %w", err) + } } - os.Stdout, os.Stderr = devNull, devNull - return + if c.opts.MemProfilePath != "" { + if rate := os.Getenv(envMemProfileRate); rate != "" { + runtime.MemProfileRate, _ = strconv.Atoi(rate) + } + } + + if c.opts.TracePath != "" { + f, err := os.Create(c.opts.TracePath) + if err != nil { + return fmt.Errorf("can't create file %s: %w", c.opts.TracePath, err) + } + if err = trace.Start(f); err != nil { + return fmt.Errorf("can't start tracing: %w", err) + } + } + + return nil } -func (e *Executor) setExitCodeIfIssuesFound(issues []result.Issue) { - if len(issues) != 0 { - e.exitCode = e.cfg.Run.ExitCodeIfIssuesFound +func (c *runCommand) stopTracing() error { + if c.opts.CPUProfilePath != "" { + pprof.StopCPUProfile() } + + if c.opts.MemProfilePath != "" { + f, err := os.Create(c.opts.MemProfilePath) + if err != nil { + return fmt.Errorf("can't create file %s: %w", c.opts.MemProfilePath, err) + } + + var ms runtime.MemStats + runtime.ReadMemStats(&ms) + printMemStats(&ms, c.log) + + if err := pprof.WriteHeapProfile(f); err != nil { + return fmt.Errorf("can't write heap profile: %w", err) + } + _ = f.Close() + } + + if c.opts.TracePath != "" { + trace.Stop() + } + + return nil } -func (e *Executor) runAndPrint(ctx context.Context, args []string) error { - if err := e.goenv.Discover(ctx); err != nil { - e.log.Warnf("Failed to discover go env: %s", err) +func (c *runCommand) runAndPrint(ctx context.Context, args []string) error { + if err := c.goenv.Discover(ctx); err != nil { + c.log.Warnf("Failed to discover go env: %s", err) } if !logutils.HaveDebugTag(logutils.DebugKeyLintersOutput) { // Don't allow linters and loader to print anything log.SetOutput(io.Discard) - savedStdout, savedStderr := e.setOutputToDevNull() + savedStdout, savedStderr := c.setOutputToDevNull() defer func() { os.Stdout, os.Stderr = savedStdout, savedStderr }() } - issues, err := e.runAnalysis(ctx, args) + enabledLintersMap, err := c.dbManager.GetEnabledLintersMap() if err != nil { - return err // XXX: don't loose type + return err } - formats := strings.Split(e.cfg.Output.Format, ",") - for _, format := range formats { - out := strings.SplitN(format, ":", 2) - if len(out) < 2 { - out = append(out, "") - } + c.printDeprecatedLinterMessages(enabledLintersMap) - err := e.printReports(issues, out[1], out[0]) - if err != nil { - return err - } + issues, err := c.runAnalysis(ctx, args) + if err != nil { + return err // XXX: don't lose type } - e.setExitCodeIfIssuesFound(issues) + // Fills linters information for the JSON printer. + for _, lc := range c.dbManager.GetAllSupportedLinterConfigs() { + isEnabled := enabledLintersMap[lc.Name()] != nil + c.reportData.AddLinter(lc.Name(), isEnabled, lc.EnabledByDefault) + } - e.fileCache.PrintStats(e.log) + err = c.printer.Print(issues) + if err != nil { + return err + } + + c.printStats(issues) + + c.setExitCodeIfIssuesFound(issues) + + c.fileCache.PrintStats(c.log) return nil } -func (e *Executor) printReports(issues []result.Issue, path, format string) error { - w, shouldClose, err := e.createWriter(path) +// runAnalysis executes the linters that have been enabled in the configuration. +func (c *runCommand) runAnalysis(ctx context.Context, args []string) ([]result.Issue, error) { + lintersToRun, err := c.dbManager.GetOptimizedLinters() if err != nil { - return fmt.Errorf("can't create output for %s: %w", path, err) + return nil, err } - p, err := e.createPrinter(format, w) + lintCtx, err := c.contextBuilder.Build(ctx, c.log.Child(logutils.DebugKeyLintersContext), lintersToRun) if err != nil { - if file, ok := w.(io.Closer); shouldClose && ok { - _ = file.Close() - } - return err - } - - if err = p.Print(issues); err != nil { - if file, ok := w.(io.Closer); shouldClose && ok { - _ = file.Close() - } - return fmt.Errorf("can't print %d issues: %s", len(issues), err) + return nil, fmt.Errorf("context loading failed: %w", err) } - if file, ok := w.(io.Closer); shouldClose && ok { - _ = file.Close() + runner, err := lint.NewRunner(c.log.Child(logutils.DebugKeyRunner), c.cfg, args, + c.goenv, c.lineCache, c.fileCache, c.dbManager, lintCtx) + if err != nil { + return nil, err } - return nil + return runner.Run(ctx, lintersToRun) } -func (e *Executor) createWriter(path string) (io.Writer, bool, error) { - if path == "" || path == "stdout" { - return logutils.StdOut, false, nil - } - if path == "stderr" { - return logutils.StdErr, false, nil - } - f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, defaultFileMode) +func (c *runCommand) setOutputToDevNull() (savedStdout, savedStderr *os.File) { + savedStdout, savedStderr = os.Stdout, os.Stderr + devNull, err := os.Open(os.DevNull) if err != nil { - return nil, false, err + c.log.Warnf("Can't open null device %q: %s", os.DevNull, err) + return } - return f, true, nil + + os.Stdout, os.Stderr = devNull, devNull + return } -func (e *Executor) createPrinter(format string, w io.Writer) (printers.Printer, error) { - var p printers.Printer - switch format { - case config.OutFormatJSON: - p = printers.NewJSON(&e.reportData, w) - case config.OutFormatColoredLineNumber, config.OutFormatLineNumber: - p = printers.NewText(e.cfg.Output.PrintIssuedLine, - format == config.OutFormatColoredLineNumber, e.cfg.Output.PrintLinterName, - e.log.Child(logutils.DebugKeyTextPrinter), w) - case config.OutFormatTab, config.OutFormatColoredTab: - p = printers.NewTab(e.cfg.Output.PrintLinterName, - format == config.OutFormatColoredTab, - e.log.Child(logutils.DebugKeyTabPrinter), w) - case config.OutFormatCheckstyle: - p = printers.NewCheckstyle(w) - case config.OutFormatCodeClimate: - p = printers.NewCodeClimate(w) - case config.OutFormatHTML: - p = printers.NewHTML(w) - case config.OutFormatJunitXML: - p = printers.NewJunitXML(w) - case config.OutFormatGithubActions: - p = printers.NewGithub(w) - case config.OutFormatTeamCity: - p = printers.NewTeamCity(w) - default: - return nil, fmt.Errorf("unknown output format %s", format) - } - - return p, nil +func (c *runCommand) setExitCodeIfIssuesFound(issues []result.Issue) { + if len(issues) != 0 { + c.exitCode = c.cfg.Run.ExitCodeIfIssuesFound + } } -// executeRun executes the 'run' CLI command, which runs the linters. -func (e *Executor) executeRun(_ *cobra.Command, args []string) { - needTrackResources := e.cfg.Run.IsVerbose || e.cfg.Run.PrintResourcesUsage - trackResourcesEndCh := make(chan struct{}) - defer func() { // XXX: this defer must be before ctx.cancel defer - if needTrackResources { // wait until resource tracking finished to print properly - <-trackResourcesEndCh +func (c *runCommand) printDeprecatedLinterMessages(enabledLinters map[string]*linter.Config) { + if c.cfg.InternalCmdTest || os.Getenv(logutils.EnvTestRun) == "1" { + return + } + + for name, lc := range enabledLinters { + if !lc.IsDeprecated() { + continue } - }() - e.setTimeoutToDeadlineIfOnlyDeadlineIsSet() - ctx, cancel := context.WithTimeout(context.Background(), e.cfg.Run.Timeout) - defer cancel() + var extra string + if lc.Deprecation.Replacement != "" { + extra = fmt.Sprintf("Replaced by %s.", lc.Deprecation.Replacement) + } - if needTrackResources { - go watchResources(ctx, trackResourcesEndCh, e.log, e.debugf) + c.log.Warnf("The linter '%s' is deprecated (since %s) due to: %s %s", name, lc.Deprecation.Since, lc.Deprecation.Message, extra) } +} - if err := e.runAndPrint(ctx, args); err != nil { - e.log.Errorf("Running error: %s", err) - if e.exitCode == exitcodes.Success { - var exitErr *exitcodes.ExitError - if errors.As(err, &exitErr) { - e.exitCode = exitErr.Code - } else { - e.exitCode = exitcodes.Failure - } - } +func (c *runCommand) printStats(issues []result.Issue) { + if !c.cfg.Output.ShowStats { + return } - e.setupExitCode(ctx) -} + if len(issues) == 0 { + c.cmd.Println("0 issues.") + return + } -// to be removed when deadline is finally decommissioned -func (e *Executor) setTimeoutToDeadlineIfOnlyDeadlineIsSet() { - deadlineValue := e.cfg.Run.Deadline - if deadlineValue != 0 && e.cfg.Run.Timeout == defaultTimeout { - e.cfg.Run.Timeout = deadlineValue + stats := map[string]int{} + for idx := range issues { + stats[issues[idx].FromLinter]++ + } + + c.cmd.Printf("%d issues:\n", len(issues)) + + keys := maps.Keys(stats) + sort.Strings(keys) + + for _, key := range keys { + c.cmd.Printf("* %s: %d\n", key, stats[key]) } } -func (e *Executor) setupExitCode(ctx context.Context) { +func (c *runCommand) setupExitCode(ctx context.Context) { if ctx.Err() != nil { - e.exitCode = exitcodes.Timeout - e.log.Errorf("Timeout exceeded: try increasing it by passing --timeout option") + c.exitCode = exitcodes.Timeout + c.log.Errorf("Timeout exceeded: try increasing it by passing --timeout option") return } - if e.exitCode != exitcodes.Success { + if c.exitCode != exitcodes.Success { return } - needFailOnWarnings := os.Getenv(lintersdb.EnvTestRun) == "1" || os.Getenv(envFailOnWarnings) == "1" - if needFailOnWarnings && len(e.reportData.Warnings) != 0 { - e.exitCode = exitcodes.WarningInTest + needFailOnWarnings := os.Getenv(logutils.EnvTestRun) == "1" || os.Getenv(envFailOnWarnings) == "1" + if needFailOnWarnings && len(c.reportData.Warnings) != 0 { + c.exitCode = exitcodes.WarningInTest return } - if e.reportData.Error != "" { + if c.reportData.Error != "" { // it's a case e.g. when typecheck linter couldn't parse and error and just logged it - e.exitCode = exitcodes.ErrorWasLogged + c.exitCode = exitcodes.ErrorWasLogged + return + } +} + +func (c *runCommand) acquireFileLock() bool { + if c.cfg.Run.AllowParallelRunners { + c.debugf("Parallel runners are allowed, no locking") + return true + } + + lockFile := filepath.Join(os.TempDir(), "golangci-lint.lock") + c.debugf("Locking on file %s...", lockFile) + f := flock.New(lockFile) + const retryDelay = time.Second + + ctx := context.Background() + if !c.cfg.Run.AllowSerialRunners { + const totalTimeout = 5 * time.Second + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, totalTimeout) + defer cancel() + } + if ok, _ := f.TryLockContext(ctx, retryDelay); !ok { + return false + } + + c.flock = f + return true +} + +func (c *runCommand) releaseFileLock() { + if c.cfg.Run.AllowParallelRunners { return } + + if err := c.flock.Unlock(); err != nil { + c.debugf("Failed to unlock on file: %s", err) + } + if err := os.Remove(c.flock.Path()); err != nil { + c.debugf("Failed to remove lock file: %s", err) + } } func watchResources(ctx context.Context, done chan struct{}, logger logutils.Log, debugf logutils.DebugFunc) { @@ -609,3 +572,120 @@ func watchResources(ctx context.Context, done chan struct{}, logger logutils.Log logger.Infof("Execution took %s", time.Since(startedAt)) close(done) } + +func setupConfigFileFlagSet(fs *pflag.FlagSet, cfg *config.LoaderOptions) { + fs.StringVarP(&cfg.Config, "config", "c", "", color.GreenString("Read config from file path `PATH`")) + fs.BoolVar(&cfg.NoConfig, "no-config", false, color.GreenString("Don't read config file")) +} + +func setupRunPersistentFlags(fs *pflag.FlagSet, opts *runOptions) { + fs.BoolVar(&opts.PrintResourcesUsage, "print-resources-usage", false, + color.GreenString("Print avg and max memory usage of golangci-lint and total time")) + + fs.StringVar(&opts.CPUProfilePath, "cpu-profile-path", "", color.GreenString("Path to CPU profile output file")) + fs.StringVar(&opts.MemProfilePath, "mem-profile-path", "", color.GreenString("Path to memory profile output file")) + fs.StringVar(&opts.TracePath, "trace-path", "", color.GreenString("Path to trace output file")) +} + +func getDefaultConcurrency() int { + if os.Getenv(envHelpRun) == "1" { + // Make stable concurrency for generating help documentation. + const prettyConcurrency = 8 + return prettyConcurrency + } + + return runtime.NumCPU() +} + +func printMemStats(ms *runtime.MemStats, logger logutils.Log) { + logger.Infof("Mem stats: alloc=%s total_alloc=%s sys=%s "+ + "heap_alloc=%s heap_sys=%s heap_idle=%s heap_released=%s heap_in_use=%s "+ + "stack_in_use=%s stack_sys=%s "+ + "mspan_sys=%s mcache_sys=%s buck_hash_sys=%s gc_sys=%s other_sys=%s "+ + "mallocs_n=%d frees_n=%d heap_objects_n=%d gc_cpu_fraction=%.2f", + formatMemory(ms.Alloc), formatMemory(ms.TotalAlloc), formatMemory(ms.Sys), + formatMemory(ms.HeapAlloc), formatMemory(ms.HeapSys), + formatMemory(ms.HeapIdle), formatMemory(ms.HeapReleased), formatMemory(ms.HeapInuse), + formatMemory(ms.StackInuse), formatMemory(ms.StackSys), + formatMemory(ms.MSpanSys), formatMemory(ms.MCacheSys), formatMemory(ms.BuckHashSys), + formatMemory(ms.GCSys), formatMemory(ms.OtherSys), + ms.Mallocs, ms.Frees, ms.HeapObjects, ms.GCCPUFraction) +} + +func formatMemory(memBytes uint64) string { + const Kb = 1024 + const Mb = Kb * 1024 + + if memBytes < Kb { + return fmt.Sprintf("%db", memBytes) + } + if memBytes < Mb { + return fmt.Sprintf("%dkb", memBytes/Kb) + } + return fmt.Sprintf("%dmb", memBytes/Mb) +} + +// Related to cache. + +func initHashSalt(version string, cfg *config.Config) error { + binSalt, err := computeBinarySalt(version) + if err != nil { + return fmt.Errorf("failed to calculate binary salt: %w", err) + } + + configSalt, err := computeConfigSalt(cfg) + if err != nil { + return fmt.Errorf("failed to calculate config salt: %w", err) + } + + b := bytes.NewBuffer(binSalt) + b.Write(configSalt) + cache.SetSalt(b.Bytes()) + return nil +} + +func computeBinarySalt(version string) ([]byte, error) { + if version != "" && version != "(devel)" { + return []byte(version), nil + } + + if logutils.HaveDebugTag(logutils.DebugKeyBinSalt) { + return []byte("debug"), nil + } + + p, err := os.Executable() + if err != nil { + return nil, err + } + f, err := os.Open(p) + if err != nil { + return nil, err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return nil, err + } + return h.Sum(nil), nil +} + +// computeConfigSalt computes configuration hash. +// We don't hash all config fields to reduce meaningless cache invalidations. +// At least, it has a huge impact on tests speed. +// Fields: `LintersSettings` and `Run.BuildTags`. +func computeConfigSalt(cfg *config.Config) ([]byte, error) { + lintersSettingsBytes, err := yaml.Marshal(cfg.LintersSettings) + if err != nil { + return nil, fmt.Errorf("failed to JSON marshal config linter settings: %w", err) + } + + configData := bytes.NewBufferString("linters-settings=") + configData.Write(lintersSettingsBytes) + configData.WriteString("\nbuild-tags=%s" + strings.Join(cfg.Run.BuildTags, ",")) + + h := sha256.New() + if _, err := h.Write(configData.Bytes()); err != nil { + return nil, err + } + return h.Sum(nil), nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/version.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/version.go index bb7732250..ac665f4c5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/version.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/version.go @@ -8,76 +8,95 @@ import ( "runtime/debug" "strings" + "github.com/fatih/color" "github.com/spf13/cobra" - "github.com/spf13/pflag" - - "github.com/golangci/golangci-lint/pkg/config" ) +type BuildInfo struct { + GoVersion string `json:"goVersion"` + Version string `json:"version"` + Commit string `json:"commit"` + Date string `json:"date"` +} + +func (b BuildInfo) String() string { + return fmt.Sprintf("golangci-lint has version %s built with %s from %s on %s", + b.Version, b.GoVersion, b.Commit, b.Date) +} + type versionInfo struct { Info BuildInfo BuildInfo *debug.BuildInfo } -func (e *Executor) initVersionConfiguration(cmd *cobra.Command) { - fs := cmd.Flags() - fs.SortFlags = false // sort them as they are defined here - initVersionFlagSet(fs, e.cfg) +type versionOptions struct { + Format string + Debug bool } -func initVersionFlagSet(fs *pflag.FlagSet, cfg *config.Config) { - // Version config - vc := &cfg.Version - fs.StringVar(&vc.Format, "format", "", wh("The version's format can be: 'short', 'json'")) - fs.BoolVar(&vc.Debug, "debug", false, wh("Add build information")) +type versionCommand struct { + cmd *cobra.Command + opts versionOptions + + info BuildInfo } -func (e *Executor) initVersion() { +func newVersionCommand(info BuildInfo) *versionCommand { + c := &versionCommand{info: info} + versionCmd := &cobra.Command{ Use: "version", Short: "Version", Args: cobra.NoArgs, ValidArgsFunction: cobra.NoFileCompletions, - RunE: func(cmd *cobra.Command, _ []string) error { - if e.cfg.Version.Debug { - info, ok := debug.ReadBuildInfo() - if !ok { - return nil - } - - switch strings.ToLower(e.cfg.Version.Format) { - case "json": - return json.NewEncoder(os.Stdout).Encode(versionInfo{ - Info: e.buildInfo, - BuildInfo: info, - }) - - default: - fmt.Println(info.String()) - return printVersion(os.Stdout, e.buildInfo) - } - } - - switch strings.ToLower(e.cfg.Version.Format) { - case "short": - fmt.Println(e.buildInfo.Version) - return nil - - case "json": - return json.NewEncoder(os.Stdout).Encode(e.buildInfo) - - default: - return printVersion(os.Stdout, e.buildInfo) - } - }, + RunE: c.execute, } - e.rootCmd.AddCommand(versionCmd) - e.initVersionConfiguration(versionCmd) + fs := versionCmd.Flags() + fs.SortFlags = false // sort them as they are defined here + + fs.StringVar(&c.opts.Format, "format", "", color.GreenString("The version's format can be: 'short', 'json'")) + fs.BoolVar(&c.opts.Debug, "debug", false, color.GreenString("Add build information")) + + c.cmd = versionCmd + + return c +} + +func (c *versionCommand) execute(_ *cobra.Command, _ []string) error { + if c.opts.Debug { + info, ok := debug.ReadBuildInfo() + if !ok { + return nil + } + + switch strings.ToLower(c.opts.Format) { + case "json": + return json.NewEncoder(os.Stdout).Encode(versionInfo{ + Info: c.info, + BuildInfo: info, + }) + + default: + fmt.Println(info.String()) + return printVersion(os.Stdout, c.info) + } + } + + switch strings.ToLower(c.opts.Format) { + case "short": + fmt.Println(c.info.Version) + return nil + + case "json": + return json.NewEncoder(os.Stdout).Encode(c.info) + + default: + return printVersion(os.Stdout, c.info) + } } -func printVersion(w io.Writer, buildInfo BuildInfo) error { - _, err := fmt.Fprintf(w, "golangci-lint has version %s built with %s from %s on %s\n", - buildInfo.Version, buildInfo.GoVersion, buildInfo.Commit, buildInfo.Date) +func printVersion(w io.Writer, info BuildInfo) error { + _, err := fmt.Fprintln(w, info.String()) return err } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/config.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/config.go index 7941f428f..1dd064013 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/config.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/config.go @@ -2,26 +2,27 @@ package config import ( "os" + "regexp" "strings" hcversion "github.com/hashicorp/go-version" "github.com/ldez/gomoddirectives" ) -// Config encapsulates the config data specified in the golangci yaml config file. +// Config encapsulates the config data specified in the golangci-lint YAML config file. type Config struct { - cfgDir string // The directory containing the golangci config file. - Run Run + cfgDir string // The directory containing the golangci-lint config file. - Output Output + Run Run `mapstructure:"run"` + + Output Output `mapstructure:"output"` LintersSettings LintersSettings `mapstructure:"linters-settings"` - Linters Linters - Issues Issues - Severity Severity - Version Version + Linters Linters `mapstructure:"linters"` + Issues Issues `mapstructure:"issues"` + Severity Severity `mapstructure:"severity"` - InternalCmdTest bool `mapstructure:"internal-cmd-test"` // Option is used only for testing golangci-lint command, don't use it + InternalCmdTest bool // Option is used only for testing golangci-lint command, don't use it InternalTest bool // Option is used only for testing golangci-lint code, don't use it } @@ -30,6 +31,25 @@ func (c *Config) GetConfigDir() string { return c.cfgDir } +func (c *Config) Validate() error { + validators := []func() error{ + c.Run.Validate, + c.Output.Validate, + c.LintersSettings.Validate, + c.Linters.Validate, + c.Issues.Validate, + c.Severity.Validate, + } + + for _, v := range validators { + if err := v(); err != nil { + return err + } + } + + return nil +} + func NewDefault() *Config { return &Config{ LintersSettings: defaultLintersSettings, @@ -41,21 +61,21 @@ type Version struct { Debug bool `mapstructure:"debug"` } -func IsGreaterThanOrEqualGo121(v string) bool { - v1, err := hcversion.NewVersion(strings.TrimPrefix(v, "go")) +func IsGoGreaterThanOrEqual(current, limit string) bool { + v1, err := hcversion.NewVersion(strings.TrimPrefix(current, "go")) if err != nil { return false } - limit, err := hcversion.NewVersion("1.21") + l, err := hcversion.NewVersion(limit) if err != nil { return false } - return v1.GreaterThanOrEqual(limit) + return v1.GreaterThanOrEqual(l) } -func DetectGoVersion() string { +func detectGoVersion() string { file, _ := gomoddirectives.GetModuleFile() if file != nil && file.Go != nil && file.Go.Version != "" { @@ -69,3 +89,22 @@ func DetectGoVersion() string { return "1.17" } + +// Trims the Go version to keep only M.m. +// Since Go 1.21 the version inside the go.mod can be a patched version (ex: 1.21.0). +// The version can also include information which we want to remove (ex: 1.21alpha1) +// https://go.dev/doc/toolchain#versions +// This a problem with staticcheck and gocritic. +func trimGoVersion(v string) string { + if v == "" { + return "" + } + + exp := regexp.MustCompile(`(\d\.\d+)(?:\.\d+|[a-z]+\d)`) + + if exp.MatchString(v) { + return exp.FindStringSubmatch(v)[1] + } + + return v +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/issues.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/issues.go index 5968d83d5..2ee9364aa 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/issues.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/issues.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "regexp" ) @@ -13,93 +14,92 @@ var DefaultExcludePatterns = []ExcludePattern{ Pattern: "Error return value of .((os\\.)?std(out|err)\\..*|.*Close" + "|.*Flush|os\\.Remove(All)?|.*print(f|ln)?|os\\.(Un)?Setenv). is not checked", Linter: "errcheck", - Why: "Almost all programs ignore errors on these functions and in most cases it's ok", + Why: "Almost all programs ignore errors on these functions and in most cases it's ok.", }, { - ID: "EXC0002", + ID: "EXC0002", // TODO(ldez): should be remove in v2 Pattern: "(comment on exported (method|function|type|const)|" + "should have( a package)? comment|comment should be of the form)", Linter: "golint", - Why: "Annoying issue about not having a comment. The rare codebase has such comments", + Why: "Annoying issue about not having a comment. The rare codebase has such comments.", }, { - ID: "EXC0003", + ID: "EXC0003", // TODO(ldez): should be remove in v2 Pattern: "func name will be used as test\\.Test.* by other packages, and that stutters; consider calling this", Linter: "golint", - Why: "False positive when tests are defined in package 'test'", + Why: "False positive when tests are defined in package 'test'.", }, { ID: "EXC0004", Pattern: "(possible misuse of unsafe.Pointer|should have signature)", Linter: "govet", - Why: "Common false positives", + Why: "Common false positives.", }, { ID: "EXC0005", - Pattern: "ineffective break statement. Did you mean to break out of the outer loop", + Pattern: "SA4011", // CheckScopedBreak Linter: "staticcheck", - Why: "Developers tend to write in C-style with an explicit 'break' in a 'switch', so it's ok to ignore", + Why: "Developers tend to write in C-style with an explicit 'break' in a 'switch', so it's ok to ignore.", }, { ID: "EXC0006", - Pattern: "Use of unsafe calls should be audited", + Pattern: "G103: Use of unsafe calls should be audited", Linter: "gosec", - Why: "Too many false-positives on 'unsafe' usage", + Why: "Too many false-positives on 'unsafe' usage.", }, { ID: "EXC0007", - Pattern: "Subprocess launch(ed with variable|ing should be audited)", + Pattern: "G204: Subprocess launched with variable", Linter: "gosec", - Why: "Too many false-positives for parametrized shell calls", + Why: "Too many false-positives for parametrized shell calls.", }, { ID: "EXC0008", - Pattern: "(G104)", + Pattern: "G104", // Errors unhandled. Linter: "gosec", - Why: "Duplicated errcheck checks", + Why: "Duplicated errcheck checks.", }, { ID: "EXC0009", - Pattern: "(Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less)", + Pattern: "(G301|G302|G307): Expect (directory permissions to be 0750|file permissions to be 0600) or less", Linter: "gosec", - Why: "Too many issues in popular repos", + Why: "Too many issues in popular repos.", }, { ID: "EXC0010", - Pattern: "Potential file inclusion via variable", + Pattern: "G304: Potential file inclusion via variable", Linter: "gosec", - Why: "False positive is triggered by 'src, err := ioutil.ReadFile(filename)'", + Why: "False positive is triggered by 'src, err := ioutil.ReadFile(filename)'.", }, { - ID: "EXC0011", - Pattern: "(comment on exported (method|function|type|const)|" + - "should have( a package)? comment|comment should be of the form)", - Linter: "stylecheck", - Why: "Annoying issue about not having a comment. The rare codebase has such comments", + ID: "EXC0011", + Pattern: "(ST1000|ST1020|ST1021|ST1022)", // CheckPackageComment, CheckExportedFunctionDocs, CheckExportedTypeDocs, CheckExportedVarDocs + Linter: "stylecheck", + Why: "Annoying issue about not having a comment. The rare codebase has such comments.", }, { ID: "EXC0012", - Pattern: `exported (.+) should have comment( \(or a comment on this block\))? or be unexported`, + Pattern: `exported (.+) should have comment( \(or a comment on this block\))? or be unexported`, // rule: exported Linter: "revive", - Why: "Annoying issue about not having a comment. The rare codebase has such comments", + Why: "Annoying issue about not having a comment. The rare codebase has such comments.", }, { ID: "EXC0013", - Pattern: `package comment should be of the form "(.+)...`, + Pattern: `package comment should be of the form "(.+)..."`, // rule: package-comments Linter: "revive", - Why: "Annoying issue about not having a comment. The rare codebase has such comments", + Why: "Annoying issue about not having a comment. The rare codebase has such comments.", }, { ID: "EXC0014", - Pattern: `comment on exported (.+) should be of the form "(.+)..."`, + Pattern: `comment on exported (.+) should be of the form "(.+)..."`, // rule: exported Linter: "revive", - Why: "Annoying issue about not having a comment. The rare codebase has such comments", + Why: "Annoying issue about not having a comment. The rare codebase has such comments.", }, { ID: "EXC0015", - Pattern: `should have a package comment`, + Pattern: `should have a package comment`, // rule: package-comments Linter: "revive", - Why: "Annoying issue about not having a comment. The rare codebase has such comments", + Why: "Annoying issue about not having a comment. The rare codebase has such comments.", }, } @@ -110,6 +110,13 @@ type Issues struct { ExcludeRules []ExcludeRule `mapstructure:"exclude-rules"` UseDefaultExcludes bool `mapstructure:"exclude-use-default"` + ExcludeGenerated string `mapstructure:"exclude-generated"` + + ExcludeFiles []string `mapstructure:"exclude-files"` + ExcludeDirs []string `mapstructure:"exclude-dirs"` + + UseDefaultExcludeDirs bool `mapstructure:"exclude-dirs-use-default"` + MaxIssuesPerLinter int `mapstructure:"max-issues-per-linter"` MaxSameIssues int `mapstructure:"max-same-issues"` @@ -119,6 +126,18 @@ type Issues struct { Diff bool `mapstructure:"new"` NeedFix bool `mapstructure:"fix"` + + ExcludeGeneratedStrict bool `mapstructure:"exclude-generated-strict"` // Deprecated: use ExcludeGenerated instead. +} + +func (i *Issues) Validate() error { + for i, rule := range i.ExcludeRules { + if err := rule.Validate(); err != nil { + return fmt.Errorf("error in exclude rule #%d: %w", i, err) + } + } + + return nil } type ExcludeRule struct { @@ -139,36 +158,49 @@ type BaseRule struct { func (b *BaseRule) Validate(minConditionsCount int) error { if err := validateOptionalRegex(b.Path); err != nil { - return fmt.Errorf("invalid path regex: %v", err) + return fmt.Errorf("invalid path regex: %w", err) } + if err := validateOptionalRegex(b.PathExcept); err != nil { - return fmt.Errorf("invalid path-except regex: %v", err) + return fmt.Errorf("invalid path-except regex: %w", err) } + if err := validateOptionalRegex(b.Text); err != nil { - return fmt.Errorf("invalid text regex: %v", err) + return fmt.Errorf("invalid text regex: %w", err) } + if err := validateOptionalRegex(b.Source); err != nil { - return fmt.Errorf("invalid source regex: %v", err) + return fmt.Errorf("invalid source regex: %w", err) } + + if b.Path != "" && b.PathExcept != "" { + return errors.New("path and path-except should not be set at the same time") + } + nonBlank := 0 if len(b.Linters) > 0 { nonBlank++ } + // Filtering by path counts as one condition, regardless how it is done (one or both). // Otherwise, a rule with Path and PathExcept set would pass validation // whereas before the introduction of path-except that wouldn't have been precise enough. if b.Path != "" || b.PathExcept != "" { nonBlank++ } + if b.Text != "" { nonBlank++ } + if b.Source != "" { nonBlank++ } + if nonBlank < minConditionsCount { return fmt.Errorf("at least %d of (text, source, path[-except], linters) should be set", minConditionsCount) } + return nil } @@ -176,6 +208,7 @@ func validateOptionalRegex(value string) error { if value == "" { return nil } + _, err := regexp.Compile(value) return err } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters.go index ccbdc123a..5c2628272 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters.go @@ -1,5 +1,10 @@ package config +import ( + "errors" + "fmt" +) + type Linters struct { Enable []string Disable []string @@ -9,3 +14,52 @@ type Linters struct { Presets []string } + +func (l *Linters) Validate() error { + if err := l.validateAllDisableEnableOptions(); err != nil { + return err + } + + if err := l.validateDisabledAndEnabledAtOneMoment(); err != nil { + return err + } + + return nil +} + +func (l *Linters) validateAllDisableEnableOptions() error { + if l.EnableAll && l.DisableAll { + return errors.New("--enable-all and --disable-all options must not be combined") + } + + if l.DisableAll { + if len(l.Enable) == 0 && len(l.Presets) == 0 { + return errors.New("all linters were disabled, but no one linter was enabled: must enable at least one") + } + + if len(l.Disable) != 0 { + return errors.New("can't combine options --disable-all and --disable") + } + } + + if l.EnableAll && len(l.Enable) != 0 && !l.Fast { + return errors.New("can't combine options --enable-all and --enable") + } + + return nil +} + +func (l *Linters) validateDisabledAndEnabledAtOneMoment() error { + enabledLintersSet := map[string]bool{} + for _, name := range l.Enable { + enabledLintersSet[name] = true + } + + for _, name := range l.Disable { + if enabledLintersSet[name] { + return fmt.Errorf("linter %q can't be disabled and enabled at one moment", name) + } + } + + return nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters_settings.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters_settings.go index 0fee9f81e..267efe2cf 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters_settings.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters_settings.go @@ -3,6 +3,7 @@ package config import ( "encoding" "errors" + "fmt" "runtime" "gopkg.in/yaml.v3" @@ -21,6 +22,9 @@ var defaultLintersSettings = LintersSettings{ Dogsled: DogsledSettings{ MaxBlankIdentifiers: 2, }, + Dupl: DuplSettings{ + Threshold: 150, + }, ErrorLint: ErrorLintSettings{ Errorf: true, ErrorfMulti: true, @@ -46,9 +50,20 @@ var defaultLintersSettings = LintersSettings{ Gocognit: GocognitSettings{ MinComplexity: 30, }, + Goconst: GoConstSettings{ + MatchWithConstants: true, + MinStringLen: 3, + MinOccurrencesCount: 3, + NumberMin: 3, + NumberMax: 3, + IgnoreCalls: true, + }, Gocritic: GoCriticSettings{ SettingsPerCheck: map[string]GoCriticCheckSettings{}, }, + Gocyclo: GoCycloSettings{ + MinComplexity: 30, + }, Godox: GodoxSettings{ Keywords: []string{}, }, @@ -56,6 +71,9 @@ var defaultLintersSettings = LintersSettings{ Scope: "declarations", Period: true, }, + Gofmt: GoFmtSettings{ + Simplify: true, + }, Gofumpt: GofumptSettings{ LangVersion: "", ModulePath: "", @@ -70,9 +88,8 @@ var defaultLintersSettings = LintersSettings{ IgnoreTests: true, WatchForScripts: []string{"Han"}, }, - Ifshort: IfshortSettings{ - MaxDeclLines: 1, - MaxDeclChars: 30, + Inamedparam: INamedParamSettings{ + SkipSingleParam: false, }, InterfaceBloat: InterfaceBloatSettings{ Max: 10, @@ -104,6 +121,13 @@ var defaultLintersSettings = LintersSettings{ RequireSpecific: false, AllowUnused: false, }, + PerfSprint: PerfSprintSettings{ + IntConversion: true, + ErrError: false, + ErrorF: true, + SprintF1: true, + StrConcat: true, + }, Prealloc: PreallocSettings{ Simple: true, RangeLoops: true, @@ -114,9 +138,15 @@ var defaultLintersSettings = LintersSettings{ Qualified: false, }, SlogLint: SlogLintSettings{ + NoMixedArgs: true, KVOnly: false, AttrOnly: false, + NoGlobal: "", + Context: "", + StaticMsg: false, NoRawKeys: false, + KeyNamingCase: "", + ForbiddenKeys: nil, ArgsOnSepLines: false, }, TagAlign: TagAlignSettings{ @@ -167,89 +197,104 @@ var defaultLintersSettings = LintersSettings{ } type LintersSettings struct { - Asasalint AsasalintSettings - BiDiChk BiDiChkSettings - Cyclop Cyclop - Decorder DecorderSettings - Depguard DepGuardSettings - Dogsled DogsledSettings - Dupl DuplSettings - DupWord DupWordSettings - Errcheck ErrcheckSettings - ErrChkJSON ErrChkJSONSettings - ErrorLint ErrorLintSettings - Exhaustive ExhaustiveSettings - ExhaustiveStruct ExhaustiveStructSettings - Exhaustruct ExhaustructSettings - Forbidigo ForbidigoSettings - Funlen FunlenSettings - Gci GciSettings - GinkgoLinter GinkgoLinterSettings - Gocognit GocognitSettings - Goconst GoConstSettings - Gocritic GoCriticSettings - Gocyclo GoCycloSettings - Godot GodotSettings - Godox GodoxSettings - Gofmt GoFmtSettings - Gofumpt GofumptSettings - Goheader GoHeaderSettings - Goimports GoImportsSettings - Golint GoLintSettings - Gomnd GoMndSettings - GoModDirectives GoModDirectivesSettings - Gomodguard GoModGuardSettings - Gosec GoSecSettings - Gosimple StaticCheckSettings - Gosmopolitan GosmopolitanSettings - Govet GovetSettings - Grouper GrouperSettings - Ifshort IfshortSettings - ImportAs ImportAsSettings - InterfaceBloat InterfaceBloatSettings - Ireturn IreturnSettings - Lll LllSettings - LoggerCheck LoggerCheckSettings - MaintIdx MaintIdxSettings - Makezero MakezeroSettings - Maligned MalignedSettings - Misspell MisspellSettings - MustTag MustTagSettings - Nakedret NakedretSettings - Nestif NestifSettings - NilNil NilNilSettings - Nlreturn NlreturnSettings - NoLintLint NoLintLintSettings - NoNamedReturns NoNamedReturnsSettings - ParallelTest ParallelTestSettings - Prealloc PreallocSettings - Predeclared PredeclaredSettings - Promlinter PromlinterSettings - Reassign ReassignSettings - Revive ReviveSettings - RowsErrCheck RowsErrCheckSettings - SlogLint SlogLintSettings - Staticcheck StaticCheckSettings - Structcheck StructCheckSettings - Stylecheck StaticCheckSettings - TagAlign TagAlignSettings - Tagliatelle TagliatelleSettings - Testifylint TestifylintSettings - Tenv TenvSettings - Testpackage TestpackageSettings - Thelper ThelperSettings - Unparam UnparamSettings - Unused UnusedSettings - UseStdlibVars UseStdlibVarsSettings - Varcheck VarCheckSettings - Varnamelen VarnamelenSettings - Whitespace WhitespaceSettings - Wrapcheck WrapcheckSettings - WSL WSLSettings + Asasalint AsasalintSettings + BiDiChk BiDiChkSettings + CopyLoopVar CopyLoopVarSettings + Cyclop Cyclop + Decorder DecorderSettings + Depguard DepGuardSettings + Dogsled DogsledSettings + Dupl DuplSettings + DupWord DupWordSettings + Errcheck ErrcheckSettings + ErrChkJSON ErrChkJSONSettings + ErrorLint ErrorLintSettings + Exhaustive ExhaustiveSettings + Exhaustruct ExhaustructSettings + Forbidigo ForbidigoSettings + Funlen FunlenSettings + Gci GciSettings + GinkgoLinter GinkgoLinterSettings + Gocognit GocognitSettings + Goconst GoConstSettings + Gocritic GoCriticSettings + Gocyclo GoCycloSettings + Godot GodotSettings + Godox GodoxSettings + Gofmt GoFmtSettings + Gofumpt GofumptSettings + Goheader GoHeaderSettings + Goimports GoImportsSettings + Gomnd GoMndSettings + GoModDirectives GoModDirectivesSettings + Gomodguard GoModGuardSettings + Gosec GoSecSettings + Gosimple StaticCheckSettings + Gosmopolitan GosmopolitanSettings + Govet GovetSettings + Grouper GrouperSettings + ImportAs ImportAsSettings + Inamedparam INamedParamSettings + InterfaceBloat InterfaceBloatSettings + Ireturn IreturnSettings + Lll LllSettings + LoggerCheck LoggerCheckSettings + MaintIdx MaintIdxSettings + Makezero MakezeroSettings + Misspell MisspellSettings + Mnd MndSettings + MustTag MustTagSettings + Nakedret NakedretSettings + Nestif NestifSettings + NilNil NilNilSettings + Nlreturn NlreturnSettings + NoLintLint NoLintLintSettings + NoNamedReturns NoNamedReturnsSettings + ParallelTest ParallelTestSettings + PerfSprint PerfSprintSettings + Prealloc PreallocSettings + Predeclared PredeclaredSettings + Promlinter PromlinterSettings + ProtoGetter ProtoGetterSettings + Reassign ReassignSettings + Revive ReviveSettings + RowsErrCheck RowsErrCheckSettings + SlogLint SlogLintSettings + Spancheck SpancheckSettings + Staticcheck StaticCheckSettings + Stylecheck StaticCheckSettings + TagAlign TagAlignSettings + Tagliatelle TagliatelleSettings + Tenv TenvSettings + Testifylint TestifylintSettings + Testpackage TestpackageSettings + Thelper ThelperSettings + Unconvert UnconvertSettings + Unparam UnparamSettings + Unused UnusedSettings + UseStdlibVars UseStdlibVarsSettings + Varnamelen VarnamelenSettings + Whitespace WhitespaceSettings + Wrapcheck WrapcheckSettings + WSL WSLSettings Custom map[string]CustomLinterSettings } +func (s *LintersSettings) Validate() error { + if err := s.Govet.Validate(); err != nil { + return err + } + + for name, settings := range s.Custom { + if err := settings.Validate(); err != nil { + return fmt.Errorf("custom linter %q: %w", name, err) + } + } + + return nil +} + type AsasalintSettings struct { Exclude []string `mapstructure:"exclude"` UseBuiltinExclusions bool `mapstructure:"use-builtin-exclusions"` @@ -268,6 +313,11 @@ type BiDiChkSettings struct { PopDirectionalIsolate bool `mapstructure:"pop-directional-isolate"` } +type CopyLoopVarSettings struct { + IgnoreAlias bool `mapstructure:"ignore-alias"` // Deprecated: use CheckAlias + CheckAlias bool `mapstructure:"check-alias"` +} + type Cyclop struct { MaxComplexity int `mapstructure:"max-complexity"` PackageAverage float64 `mapstructure:"package-average"` @@ -279,9 +329,10 @@ type DepGuardSettings struct { } type DepGuardList struct { - Files []string `mapstructure:"files"` - Allow []string `mapstructure:"allow"` - Deny []DepGuardDeny `mapstructure:"deny"` + ListMode string `mapstructure:"list-mode"` + Files []string `mapstructure:"files"` + Allow []string `mapstructure:"allow"` + Deny []DepGuardDeny `mapstructure:"deny"` } type DepGuardDeny struct { @@ -317,11 +368,13 @@ type ErrcheckSettings struct { DisableDefaultExclusions bool `mapstructure:"disable-default-exclusions"` CheckTypeAssertions bool `mapstructure:"check-type-assertions"` CheckAssignToBlank bool `mapstructure:"check-blank"` - Ignore string `mapstructure:"ignore"` ExcludeFunctions []string `mapstructure:"exclude-functions"` // Deprecated: use ExcludeFunctions instead Exclude string `mapstructure:"exclude"` + + // Deprecated: use ExcludeFunctions instead + Ignore string `mapstructure:"ignore"` } type ErrChkJSONSettings struct { @@ -330,10 +383,17 @@ type ErrChkJSONSettings struct { } type ErrorLintSettings struct { - Errorf bool `mapstructure:"errorf"` - ErrorfMulti bool `mapstructure:"errorf-multi"` - Asserts bool `mapstructure:"asserts"` - Comparison bool `mapstructure:"comparison"` + Errorf bool `mapstructure:"errorf"` + ErrorfMulti bool `mapstructure:"errorf-multi"` + Asserts bool `mapstructure:"asserts"` + Comparison bool `mapstructure:"comparison"` + AllowedErrors []ErrorLintAllowPair `mapstructure:"allowed-errors"` + AllowedErrorsWildcard []ErrorLintAllowPair `mapstructure:"allowed-errors-wildcard"` +} + +type ErrorLintAllowPair struct { + Err string `mapstructure:"err"` + Fun string `mapstructure:"fun"` } type ExhaustiveSettings struct { @@ -345,10 +405,7 @@ type ExhaustiveSettings struct { PackageScopeOnly bool `mapstructure:"package-scope-only"` ExplicitExhaustiveMap bool `mapstructure:"explicit-exhaustive-map"` ExplicitExhaustiveSwitch bool `mapstructure:"explicit-exhaustive-switch"` -} - -type ExhaustiveStructSettings struct { - StructPatterns []string `mapstructure:"struct-patterns"` + DefaultCaseRequired bool `mapstructure:"default-case-required"` } type ExhaustructSettings struct { @@ -405,10 +462,12 @@ type FunlenSettings struct { } type GciSettings struct { - LocalPrefixes string `mapstructure:"local-prefixes"` // Deprecated Sections []string `mapstructure:"sections"` SkipGenerated bool `mapstructure:"skip-generated"` CustomOrder bool `mapstructure:"custom-order"` + + // Deprecated: use Sections instead. + LocalPrefixes string `mapstructure:"local-prefixes"` } type GinkgoLinterSettings struct { @@ -420,6 +479,9 @@ type GinkgoLinterSettings struct { SuppressTypeCompareWarning bool `mapstructure:"suppress-type-compare-assertion"` ForbidFocusContainer bool `mapstructure:"forbid-focus-container"` AllowHaveLenZero bool `mapstructure:"allow-havelen-zero"` + ForceExpectTo bool `mapstructure:"force-expect-to"` + ValidateAsyncIntervals bool `mapstructure:"validate-async-intervals"` + ForbidSpecPollution bool `mapstructure:"forbid-spec-pollution"` } type GocognitSettings struct { @@ -427,19 +489,22 @@ type GocognitSettings struct { } type GoConstSettings struct { - IgnoreTests bool `mapstructure:"ignore-tests"` - MatchWithConstants bool `mapstructure:"match-constant"` - MinStringLen int `mapstructure:"min-len"` - MinOccurrencesCount int `mapstructure:"min-occurrences"` - ParseNumbers bool `mapstructure:"numbers"` - NumberMin int `mapstructure:"min"` - NumberMax int `mapstructure:"max"` - IgnoreCalls bool `mapstructure:"ignore-calls"` + IgnoreStrings string `mapstructure:"ignore-strings"` + IgnoreTests bool `mapstructure:"ignore-tests"` + MatchWithConstants bool `mapstructure:"match-constant"` + MinStringLen int `mapstructure:"min-len"` + MinOccurrencesCount int `mapstructure:"min-occurrences"` + ParseNumbers bool `mapstructure:"numbers"` + NumberMin int `mapstructure:"min"` + NumberMax int `mapstructure:"max"` + IgnoreCalls bool `mapstructure:"ignore-calls"` } type GoCriticSettings struct { Go string `mapstructure:"-"` + DisableAll bool `mapstructure:"disable-all"` EnabledChecks []string `mapstructure:"enabled-checks"` + EnableAll bool `mapstructure:"enable-all"` DisabledChecks []string `mapstructure:"disabled-checks"` EnabledTags []string `mapstructure:"enabled-tags"` DisabledTags []string `mapstructure:"disabled-tags"` @@ -458,7 +523,7 @@ type GodotSettings struct { Capital bool `mapstructure:"capital"` Period bool `mapstructure:"period"` - // Deprecated: use `Scope` instead + // Deprecated: use Scope instead CheckAll bool `mapstructure:"check-all"` } @@ -494,16 +559,12 @@ type GoImportsSettings struct { LocalPrefixes string `mapstructure:"local-prefixes"` } -type GoLintSettings struct { - MinConfidence float64 `mapstructure:"min-confidence"` -} - +// Deprecated: use MndSettings. type GoMndSettings struct { - Settings map[string]map[string]any // Deprecated - Checks []string `mapstructure:"checks"` - IgnoredNumbers []string `mapstructure:"ignored-numbers"` - IgnoredFiles []string `mapstructure:"ignored-files"` - IgnoredFunctions []string `mapstructure:"ignored-functions"` + MndSettings `mapstructure:",squash"` + + // Deprecated: use root level settings instead. + Settings map[string]map[string]any } type GoModDirectivesSettings struct { @@ -549,25 +610,28 @@ type GosmopolitanSettings struct { } type GovetSettings struct { - Go string `mapstructure:"-"` - CheckShadowing bool `mapstructure:"check-shadowing"` - Settings map[string]map[string]any + Go string `mapstructure:"-"` Enable []string Disable []string EnableAll bool `mapstructure:"enable-all"` DisableAll bool `mapstructure:"disable-all"` + + Settings map[string]map[string]any + + // Deprecated: the linter should be enabled inside Enable. + CheckShadowing bool `mapstructure:"check-shadowing"` } func (cfg *GovetSettings) Validate() error { if cfg.EnableAll && cfg.DisableAll { - return errors.New("enable-all and disable-all can't be combined") + return errors.New("govet: enable-all and disable-all can't be combined") } if cfg.EnableAll && len(cfg.Enable) != 0 { - return errors.New("enable-all and enable can't be combined") + return errors.New("govet: enable-all and enable can't be combined") } if cfg.DisableAll && len(cfg.Disable) != 0 { - return errors.New("disable-all and disable can't be combined") + return errors.New("govet: disable-all and disable can't be combined") } return nil } @@ -583,11 +647,6 @@ type GrouperSettings struct { VarRequireGrouping bool `mapstructure:"var-require-grouping"` } -type IfshortSettings struct { - MaxDeclLines int `mapstructure:"max-decl-lines"` - MaxDeclChars int `mapstructure:"max-decl-chars"` -} - type ImportAsSettings struct { Alias []ImportAsAlias NoUnaliased bool `mapstructure:"no-unaliased"` @@ -599,6 +658,10 @@ type ImportAsAlias struct { Alias string } +type INamedParamSettings struct { + SkipSingleParam bool `mapstructure:"skip-single-param"` +} + type InterfaceBloatSettings struct { Max int `mapstructure:"max"` } @@ -631,16 +694,19 @@ type MakezeroSettings struct { Always bool } -type MalignedSettings struct { - SuggestNewOrder bool `mapstructure:"suggest-new"` -} - type MisspellSettings struct { - Locale string - // TODO(ldez): v2 the options must be renamed to `IgnoredRules`. + Mode string `mapstructure:"mode"` + Locale string `mapstructure:"locale"` + ExtraWords []MisspellExtraWords `mapstructure:"extra-words"` + // TODO(ldez): v2 the option must be renamed to `IgnoredRules`. IgnoreWords []string `mapstructure:"ignore-words"` } +type MisspellExtraWords struct { + Typo string `mapstructure:"typo"` + Correction string `mapstructure:"correction"` +} + type MustTagSettings struct { Functions []struct { Name string `mapstructure:"name"` @@ -665,6 +731,13 @@ type NlreturnSettings struct { BlockSize int `mapstructure:"block-size"` } +type MndSettings struct { + Checks []string `mapstructure:"checks"` + IgnoredNumbers []string `mapstructure:"ignored-numbers"` + IgnoredFiles []string `mapstructure:"ignored-files"` + IgnoredFunctions []string `mapstructure:"ignored-functions"` +} + type NoLintLintSettings struct { RequireExplanation bool `mapstructure:"require-explanation"` RequireSpecific bool `mapstructure:"require-specific"` @@ -675,9 +748,19 @@ type NoLintLintSettings struct { type NoNamedReturnsSettings struct { ReportErrorInDefer bool `mapstructure:"report-error-in-defer"` } + type ParallelTestSettings struct { - IgnoreMissing bool `mapstructure:"ignore-missing"` - IgnoreMissingSubtests bool `mapstructure:"ignore-missing-subtests"` + Go string `mapstructure:"-"` + IgnoreMissing bool `mapstructure:"ignore-missing"` + IgnoreMissingSubtests bool `mapstructure:"ignore-missing-subtests"` +} + +type PerfSprintSettings struct { + IntConversion bool `mapstructure:"int-conversion"` + ErrError bool `mapstructure:"err-error"` + ErrorF bool `mapstructure:"errorf"` + SprintF1 bool `mapstructure:"sprintf1"` + StrConcat bool `mapstructure:"strconcat"` } type PreallocSettings struct { @@ -696,13 +779,21 @@ type PromlinterSettings struct { DisabledLinters []string `mapstructure:"disabled-linters"` } +type ProtoGetterSettings struct { + SkipGeneratedBy []string `mapstructure:"skip-generated-by"` + SkipFiles []string `mapstructure:"skip-files"` + SkipAnyGenerated bool `mapstructure:"skip-any-generated"` + ReplaceFirstArgInAppend bool `mapstructure:"replace-first-arg-in-append"` +} + type ReassignSettings struct { Patterns []string `mapstructure:"patterns"` } type ReviveSettings struct { - MaxOpenFiles int `mapstructure:"max-open-files"` - IgnoreGeneratedHeader bool `mapstructure:"ignore-generated-header"` + Go string `mapstructure:"-"` + MaxOpenFiles int `mapstructure:"max-open-files"` + IgnoreGeneratedHeader bool `mapstructure:"ignore-generated-header"` Confidence float64 Severity string EnableAllRules bool `mapstructure:"enable-all-rules"` @@ -711,6 +802,7 @@ type ReviveSettings struct { Arguments []any Severity string Disabled bool + Exclude []string } ErrorCode int `mapstructure:"error-code"` WarningCode int `mapstructure:"warning-code"` @@ -725,30 +817,41 @@ type RowsErrCheckSettings struct { } type SlogLintSettings struct { - KVOnly bool `mapstructure:"kv-only"` - AttrOnly bool `mapstructure:"attr-only"` - NoRawKeys bool `mapstructure:"no-raw-keys"` - ArgsOnSepLines bool `mapstructure:"args-on-sep-lines"` + NoMixedArgs bool `mapstructure:"no-mixed-args"` + KVOnly bool `mapstructure:"kv-only"` + AttrOnly bool `mapstructure:"attr-only"` + NoGlobal string `mapstructure:"no-global"` + Context string `mapstructure:"context"` + StaticMsg bool `mapstructure:"static-msg"` + NoRawKeys bool `mapstructure:"no-raw-keys"` + KeyNamingCase string `mapstructure:"key-naming-case"` + ForbiddenKeys []string `mapstructure:"forbidden-keys"` + ArgsOnSepLines bool `mapstructure:"args-on-sep-lines"` + + // Deprecated: use Context instead. + ContextOnly bool `mapstructure:"context-only"` } -type StaticCheckSettings struct { - // Deprecated: use the global `run.go` instead. - GoVersion string `mapstructure:"go"` +type SpancheckSettings struct { + Checks []string `mapstructure:"checks"` + IgnoreCheckSignatures []string `mapstructure:"ignore-check-signatures"` + ExtraStartSpanSignatures []string `mapstructure:"extra-start-span-signatures"` +} +type StaticCheckSettings struct { Checks []string `mapstructure:"checks"` Initialisms []string `mapstructure:"initialisms"` // only for stylecheck DotImportWhitelist []string `mapstructure:"dot-import-whitelist"` // only for stylecheck HTTPStatusCodeWhitelist []string `mapstructure:"http-status-code-whitelist"` // only for stylecheck + + // Deprecated: use the global `run.go` instead. + GoVersion string `mapstructure:"go"` } func (s *StaticCheckSettings) HasConfiguration() bool { return len(s.Initialisms) > 0 || len(s.HTTPStatusCodeWhitelist) > 0 || len(s.DotImportWhitelist) > 0 || len(s.Checks) > 0 } -type StructCheckSettings struct { - CheckExportedFields bool `mapstructure:"exported-fields"` -} - type TagAlignSettings struct { Align bool `mapstructure:"align"` Sort bool `mapstructure:"sort"` @@ -764,13 +867,32 @@ type TagliatelleSettings struct { } type TestifylintSettings struct { - EnableAll bool `mapstructure:"enable-all"` - EnabledCheckers []string `mapstructure:"enable"` + EnableAll bool `mapstructure:"enable-all"` + DisableAll bool `mapstructure:"disable-all"` + EnabledCheckers []string `mapstructure:"enable"` + DisabledCheckers []string `mapstructure:"disable"` + + BoolCompare struct { + IgnoreCustomTypes bool `mapstructure:"ignore-custom-types"` + } `mapstructure:"bool-compare"` ExpectedActual struct { ExpVarPattern string `mapstructure:"pattern"` } `mapstructure:"expected-actual"` + Formatter struct { + CheckFormatString *bool `mapstructure:"check-format-string"` + RequireFFuncs bool `mapstructure:"require-f-funcs"` + } `mapstructure:"formatter"` + + GoRequire struct { + IgnoreHTTPHandlers bool `mapstructure:"ignore-http-handlers"` + } `mapstructure:"go-require"` + + RequireError struct { + FnPattern string `mapstructure:"fn-pattern"` + } `mapstructure:"require-error"` + SuiteExtraAssertCall struct { Mode string `mapstructure:"mode"` } `mapstructure:"suite-extra-assert-call"` @@ -806,11 +928,16 @@ type UseStdlibVarsSettings struct { TimeLayout bool `mapstructure:"time-layout"` CryptoHash bool `mapstructure:"crypto-hash"` DefaultRPCPath bool `mapstructure:"default-rpc-path"` - OSDevNull bool `mapstructure:"os-dev-null"` + OSDevNull bool `mapstructure:"os-dev-null"` // Deprecated SQLIsolationLevel bool `mapstructure:"sql-isolation-level"` TLSSignatureScheme bool `mapstructure:"tls-signature-scheme"` ConstantKind bool `mapstructure:"constant-kind"` - SyslogPriority bool `mapstructure:"syslog-priority"` + SyslogPriority bool `mapstructure:"syslog-priority"` // Deprecated +} + +type UnconvertSettings struct { + FastMath bool `mapstructure:"fast-math"` + Safe bool `mapstructure:"safe"` } type UnparamSettings struct { @@ -821,17 +948,13 @@ type UnparamSettings struct { type UnusedSettings struct { FieldWritesAreUses bool `mapstructure:"field-writes-are-uses"` PostStatementsAreReads bool `mapstructure:"post-statements-are-reads"` - ExportedIsUsed bool `mapstructure:"exported-is-used"` + ExportedIsUsed bool `mapstructure:"exported-is-used"` // Deprecated ExportedFieldsAreUsed bool `mapstructure:"exported-fields-are-used"` ParametersAreUsed bool `mapstructure:"parameters-are-used"` LocalVariablesAreUsed bool `mapstructure:"local-variables-are-used"` GeneratedIsUsed bool `mapstructure:"generated-is-used"` } -type VarCheckSettings struct { - CheckExportedFields bool `mapstructure:"exported-fields"` -} - type VarnamelenSettings struct { MaxDistance int `mapstructure:"max-distance"` MinNameLength int `mapstructure:"min-name-length"` @@ -875,17 +998,15 @@ type WSLSettings struct { } // CustomLinterSettings encapsulates the meta-data of a private linter. -// For example, a private linter may be added to the golangci config file as shown below. -// -// linters-settings: -// custom: -// example: -// path: /example.so -// description: The description of the linter -// original-url: github.com/golangci/example-linter type CustomLinterSettings struct { + // Type plugin type. + // It can be `goplugin` or `module`. + Type string `mapstructure:"type"` + // Path to a plugin *.so file that implements the private linter. + // Only for Go plugin system. Path string + // Description describes the purpose of the private linter. Description string // OriginalURL The URL containing the source code for the private linter. @@ -894,3 +1015,19 @@ type CustomLinterSettings struct { // Settings plugin settings only work with linterdb.PluginConstructor symbol. Settings any } + +func (s *CustomLinterSettings) Validate() error { + if s.Type == "module" { + if s.Path != "" { + return errors.New("path not supported with module type") + } + + return nil + } + + if s.Path == "" { + return errors.New("path is required") + } + + return nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/loader.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/loader.go new file mode 100644 index 000000000..91984930d --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/loader.go @@ -0,0 +1,490 @@ +package config + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "slices" + + "github.com/go-viper/mapstructure/v2" + "github.com/mitchellh/go-homedir" + "github.com/spf13/pflag" + "github.com/spf13/viper" + + "github.com/golangci/golangci-lint/pkg/exitcodes" + "github.com/golangci/golangci-lint/pkg/fsutils" + "github.com/golangci/golangci-lint/pkg/logutils" +) + +var errConfigDisabled = errors.New("config is disabled by --no-config") + +type LoaderOptions struct { + Config string // Flag only. The path to the golangci config file, as specified with the --config argument. + NoConfig bool // Flag only. +} + +type LoadOptions struct { + CheckDeprecation bool + Validation bool +} + +type Loader struct { + opts LoaderOptions + + viper *viper.Viper + fs *pflag.FlagSet + + log logutils.Log + + cfg *Config + args []string +} + +func NewLoader(log logutils.Log, v *viper.Viper, fs *pflag.FlagSet, opts LoaderOptions, cfg *Config, args []string) *Loader { + return &Loader{ + opts: opts, + viper: v, + fs: fs, + log: log, + cfg: cfg, + args: args, + } +} + +func (l *Loader) Load(opts LoadOptions) error { + err := l.setConfigFile() + if err != nil { + return err + } + + err = l.parseConfig() + if err != nil { + return err + } + + l.applyStringSliceHack() + + if opts.CheckDeprecation { + err = l.handleDeprecation() + if err != nil { + return err + } + } + + l.handleGoVersion() + + err = l.handleEnableOnlyOption() + if err != nil { + return err + } + + if opts.Validation { + err = l.cfg.Validate() + if err != nil { + return err + } + } + + return nil +} + +func (l *Loader) setConfigFile() error { + configFile, err := l.evaluateOptions() + if err != nil { + if errors.Is(err, errConfigDisabled) { + return nil + } + + return fmt.Errorf("can't parse --config option: %w", err) + } + + if configFile != "" { + l.viper.SetConfigFile(configFile) + + // Assume YAML if the file has no extension. + if filepath.Ext(configFile) == "" { + l.viper.SetConfigType("yaml") + } + } else { + l.setupConfigFileSearch() + } + + return nil +} + +func (l *Loader) evaluateOptions() (string, error) { + if l.opts.NoConfig && l.opts.Config != "" { + return "", errors.New("can't combine option --config and --no-config") + } + + if l.opts.NoConfig { + return "", errConfigDisabled + } + + configFile, err := homedir.Expand(l.opts.Config) + if err != nil { + return "", errors.New("failed to expand configuration path") + } + + return configFile, nil +} + +func (l *Loader) setupConfigFileSearch() { + l.viper.SetConfigName(".golangci") + + configSearchPaths := l.getConfigSearchPaths() + + l.log.Infof("Config search paths: %s", configSearchPaths) + + for _, p := range configSearchPaths { + l.viper.AddConfigPath(p) + } +} + +func (l *Loader) getConfigSearchPaths() []string { + firstArg := "./..." + if len(l.args) > 0 { + firstArg = l.args[0] + } + + absPath, err := filepath.Abs(firstArg) + if err != nil { + l.log.Warnf("Can't make abs path for %q: %s", firstArg, err) + absPath = filepath.Clean(firstArg) + } + + // start from it + var currentDir string + if fsutils.IsDir(absPath) { + currentDir = absPath + } else { + currentDir = filepath.Dir(absPath) + } + + // find all dirs from it up to the root + searchPaths := []string{"./"} + + for { + searchPaths = append(searchPaths, currentDir) + + parent := filepath.Dir(currentDir) + if currentDir == parent || parent == "" { + break + } + + currentDir = parent + } + + // find home directory for global config + if home, err := homedir.Dir(); err != nil { + l.log.Warnf("Can't get user's home directory: %v", err) + } else if !slices.Contains(searchPaths, home) { + searchPaths = append(searchPaths, home) + } + + return searchPaths +} + +func (l *Loader) parseConfig() error { + if err := l.viper.ReadInConfig(); err != nil { + var configFileNotFoundError viper.ConfigFileNotFoundError + if errors.As(err, &configFileNotFoundError) { + // Load configuration from flags only. + err = l.viper.Unmarshal(l.cfg, customDecoderHook()) + if err != nil { + return fmt.Errorf("can't unmarshal config by viper (flags): %w", err) + } + + return nil + } + + return fmt.Errorf("can't read viper config: %w", err) + } + + err := l.setConfigDir() + if err != nil { + return err + } + + // Load configuration from all sources (flags, file). + if err := l.viper.Unmarshal(l.cfg, customDecoderHook()); err != nil { + return fmt.Errorf("can't unmarshal config by viper (flags, file): %w", err) + } + + if l.cfg.InternalTest { // just for testing purposes: to detect config file usage + _, _ = fmt.Fprintln(logutils.StdOut, "test") + os.Exit(exitcodes.Success) + } + + return nil +} + +func (l *Loader) setConfigDir() error { + usedConfigFile := l.viper.ConfigFileUsed() + if usedConfigFile == "" { + return nil + } + + if usedConfigFile == os.Stdin.Name() { + usedConfigFile = "" + l.log.Infof("Reading config file stdin") + } else { + var err error + usedConfigFile, err = fsutils.ShortestRelPath(usedConfigFile, "") + if err != nil { + l.log.Warnf("Can't pretty print config file path: %v", err) + } + + l.log.Infof("Used config file %s", usedConfigFile) + } + + usedConfigDir, err := filepath.Abs(filepath.Dir(usedConfigFile)) + if err != nil { + return errors.New("can't get config directory") + } + + l.cfg.cfgDir = usedConfigDir + + return nil +} + +// Hack to append values from StringSlice flags. +// Viper always overrides StringSlice values. +// https://github.com/spf13/viper/issues/1448 +// So StringSlice flags are not bind to Viper like that their values are obtain via Cobra Flags. +func (l *Loader) applyStringSliceHack() { + if l.fs == nil { + return + } + + l.appendStringSlice("enable", &l.cfg.Linters.Enable) + l.appendStringSlice("disable", &l.cfg.Linters.Disable) + l.appendStringSlice("presets", &l.cfg.Linters.Presets) + l.appendStringSlice("build-tags", &l.cfg.Run.BuildTags) + l.appendStringSlice("exclude", &l.cfg.Issues.ExcludePatterns) + + l.appendStringSlice("skip-dirs", &l.cfg.Run.SkipDirs) + l.appendStringSlice("skip-files", &l.cfg.Run.SkipFiles) + l.appendStringSlice("exclude-dirs", &l.cfg.Issues.ExcludeDirs) + l.appendStringSlice("exclude-files", &l.cfg.Issues.ExcludeFiles) +} + +func (l *Loader) appendStringSlice(name string, current *[]string) { + if l.fs.Changed(name) { + val, _ := l.fs.GetStringSlice(name) + *current = append(*current, val...) + } +} + +func (l *Loader) handleGoVersion() { + if l.cfg.Run.Go == "" { + l.cfg.Run.Go = detectGoVersion() + } + + l.cfg.LintersSettings.Govet.Go = l.cfg.Run.Go + + l.cfg.LintersSettings.ParallelTest.Go = l.cfg.Run.Go + + if l.cfg.LintersSettings.Gofumpt.LangVersion == "" { + l.cfg.LintersSettings.Gofumpt.LangVersion = l.cfg.Run.Go + } + + trimmedGoVersion := trimGoVersion(l.cfg.Run.Go) + + l.cfg.LintersSettings.Revive.Go = trimmedGoVersion + + l.cfg.LintersSettings.Gocritic.Go = trimmedGoVersion + + // staticcheck related linters. + if l.cfg.LintersSettings.Staticcheck.GoVersion == "" { + l.cfg.LintersSettings.Staticcheck.GoVersion = trimmedGoVersion + } + if l.cfg.LintersSettings.Gosimple.GoVersion == "" { + l.cfg.LintersSettings.Gosimple.GoVersion = trimmedGoVersion + } + if l.cfg.LintersSettings.Stylecheck.GoVersion == "" { + l.cfg.LintersSettings.Stylecheck.GoVersion = trimmedGoVersion + } + + os.Setenv("GOSECGOVERSION", l.cfg.Run.Go) +} + +func (l *Loader) handleDeprecation() error { + if l.cfg.InternalTest || l.cfg.InternalCmdTest || os.Getenv(logutils.EnvTestRun) == "1" { + return nil + } + + // Deprecated since v1.57.0 + if len(l.cfg.Run.SkipFiles) > 0 { + l.log.Warnf("The configuration option `run.skip-files` is deprecated, please use `issues.exclude-files`.") + l.cfg.Issues.ExcludeFiles = l.cfg.Run.SkipFiles + } + + // Deprecated since v1.57.0 + if len(l.cfg.Run.SkipDirs) > 0 { + l.log.Warnf("The configuration option `run.skip-dirs` is deprecated, please use `issues.exclude-dirs`.") + l.cfg.Issues.ExcludeDirs = l.cfg.Run.SkipDirs + } + + // The 2 options are true by default. + // Deprecated since v1.57.0 + if !l.cfg.Run.UseDefaultSkipDirs { + l.log.Warnf("The configuration option `run.skip-dirs-use-default` is deprecated, please use `issues.exclude-dirs-use-default`.") + } + l.cfg.Issues.UseDefaultExcludeDirs = l.cfg.Run.UseDefaultSkipDirs && l.cfg.Issues.UseDefaultExcludeDirs + + // The 2 options are false by default. + // Deprecated since v1.57.0 + if l.cfg.Run.ShowStats { + l.log.Warnf("The configuration option `run.show-stats` is deprecated, please use `output.show-stats`") + } + l.cfg.Output.ShowStats = l.cfg.Run.ShowStats || l.cfg.Output.ShowStats + + // Deprecated since v1.57.0 + if l.cfg.Output.Format != "" { + l.log.Warnf("The configuration option `output.format` is deprecated, please use `output.formats`") + + var f OutputFormats + err := f.UnmarshalText([]byte(l.cfg.Output.Format)) + if err != nil { + return fmt.Errorf("unmarshal output format: %w", err) + } + + l.cfg.Output.Formats = f + } + + for _, format := range l.cfg.Output.Formats { + if format.Format == OutFormatGithubActions { + l.log.Warnf("The output format `%s` is deprecated, please use `%s`", OutFormatGithubActions, OutFormatColoredLineNumber) + break // To avoid repeating the message if there are several usages of github-actions format. + } + } + + // Deprecated since v1.59.0 + if l.cfg.Issues.ExcludeGeneratedStrict { + l.log.Warnf("The configuration option `issues.exclude-generated-strict` is deprecated, please use `issues.exclude-generated`") + l.cfg.Issues.ExcludeGenerated = "strict" // Don't use the constants to avoid cyclic dependencies. + } + + l.handleLinterOptionDeprecations() + + return nil +} + +//nolint:gocyclo // the complexity cannot be reduced. +func (l *Loader) handleLinterOptionDeprecations() { + // Deprecated since v1.57.0, + // but it was unofficially deprecated since v1.19 (2019) (https://github.com/golangci/golangci-lint/pull/697). + if l.cfg.LintersSettings.Govet.CheckShadowing { + l.log.Warnf("The configuration option `linters.govet.check-shadowing` is deprecated. " + + "Please enable `shadow` instead, if you are not using `enable-all`.") + } + + if l.cfg.LintersSettings.CopyLoopVar.IgnoreAlias { + l.log.Warnf("The configuration option `linters.copyloopvar.ignore-alias` is deprecated and ignored," + + "please use `linters.copyloopvar.check-alias`.") + } + + // Deprecated since v1.42.0. + if l.cfg.LintersSettings.Errcheck.Exclude != "" { + l.log.Warnf("The configuration option `linters.errcheck.exclude` is deprecated, please use `linters.errcheck.exclude-functions`.") + } + + // Deprecated since v1.59.0, + // but it was unofficially deprecated since v1.13 (2018) (https://github.com/golangci/golangci-lint/pull/332). + if l.cfg.LintersSettings.Errcheck.Ignore != "" { + l.log.Warnf("The configuration option `linters.errcheck.ignore` is deprecated, please use `linters.errcheck.exclude-functions`.") + } + + // Deprecated since v1.44.0. + if l.cfg.LintersSettings.Gci.LocalPrefixes != "" { + l.log.Warnf("The configuration option `linters.gci.local-prefixes` is deprecated, please use `prefix()` inside `linters.gci.sections`.") + } + + // Deprecated since v1.33.0. + if l.cfg.LintersSettings.Godot.CheckAll { + l.log.Warnf("The configuration option `linters.godot.check-all` is deprecated, please use `linters.godot.scope: all`.") + } + + // Deprecated since v1.44.0. + if len(l.cfg.LintersSettings.Gomnd.Settings) > 0 { + l.log.Warnf("The configuration option `linters.gomnd.settings` is deprecated. Please use the options " + + "`linters.gomnd.checks`,`linters.gomnd.ignored-numbers`,`linters.gomnd.ignored-files`,`linters.gomnd.ignored-functions`.") + } + + // Deprecated since v1.47.0 + if l.cfg.LintersSettings.Gofumpt.LangVersion != "" { + l.log.Warnf("The configuration option `linters.gofumpt.lang-version` is deprecated, please use global `run.go`.") + } + + // Deprecated since v1.47.0 + if l.cfg.LintersSettings.Staticcheck.GoVersion != "" { + l.log.Warnf("The configuration option `linters.staticcheck.go` is deprecated, please use global `run.go`.") + } + + // Deprecated since v1.47.0 + if l.cfg.LintersSettings.Gosimple.GoVersion != "" { + l.log.Warnf("The configuration option `linters.gosimple.go` is deprecated, please use global `run.go`.") + } + + // Deprecated since v1.47.0 + if l.cfg.LintersSettings.Stylecheck.GoVersion != "" { + l.log.Warnf("The configuration option `linters.stylecheck.go` is deprecated, please use global `run.go`.") + } + + // Deprecated since v1.60.0 + if !l.cfg.LintersSettings.Unused.ExportedIsUsed { + l.log.Warnf("The configuration option `linters.unused.exported-is-used` is deprecated.") + } + + // Deprecated since v1.58.0 + if l.cfg.LintersSettings.SlogLint.ContextOnly { + l.log.Warnf("The configuration option `linters.sloglint.context-only` is deprecated, please use `linters.sloglint.context`.") + if l.cfg.LintersSettings.SlogLint.Context == "" { + l.cfg.LintersSettings.SlogLint.Context = "all" + } + } + + // Deprecated since v1.51.0 + if l.cfg.LintersSettings.UseStdlibVars.OSDevNull { + l.log.Warnf("The configuration option `linters.usestdlibvars.os-dev-null` is deprecated.") + } + + // Deprecated since v1.51.0 + if l.cfg.LintersSettings.UseStdlibVars.SyslogPriority { + l.log.Warnf("The configuration option `linters.usestdlibvars.syslog-priority` is deprecated.") + } +} + +func (l *Loader) handleEnableOnlyOption() error { + lookup := l.fs.Lookup("enable-only") + if lookup == nil { + return nil + } + + only, err := l.fs.GetStringSlice("enable-only") + if err != nil { + return err + } + + if len(only) > 0 { + l.cfg.Linters = Linters{ + Enable: only, + DisableAll: true, + } + } + + return nil +} + +func customDecoderHook() viper.DecoderConfigOption { + return viper.DecodeHook(mapstructure.ComposeDecodeHookFunc( + // Default hooks (https://github.com/spf13/viper/blob/518241257478c557633ab36e474dfcaeb9a3c623/viper.go#L135-L138). + mapstructure.StringToTimeDurationHookFunc(), + mapstructure.StringToSliceHookFunc(","), + + // Needed for forbidigo, and output.formats. + mapstructure.TextUnmarshallerHookFunc(), + )) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/output.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/output.go index e87263920..592e293e0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/output.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/output.go @@ -1,5 +1,12 @@ package config +import ( + "errors" + "fmt" + "slices" + "strings" +) + const ( OutFormatJSON = "json" OutFormatLineNumber = "line-number" @@ -10,32 +17,99 @@ const ( OutFormatCodeClimate = "code-climate" OutFormatHTML = "html" OutFormatJunitXML = "junit-xml" - OutFormatGithubActions = "github-actions" + OutFormatGithubActions = "github-actions" // Deprecated OutFormatTeamCity = "teamcity" + OutFormatSarif = "sarif" ) -var OutFormats = []string{ - OutFormatColoredLineNumber, - OutFormatLineNumber, +var AllOutputFormats = []string{ OutFormatJSON, + OutFormatLineNumber, + OutFormatColoredLineNumber, OutFormatTab, + OutFormatColoredTab, OutFormatCheckstyle, OutFormatCodeClimate, OutFormatHTML, OutFormatJunitXML, OutFormatGithubActions, OutFormatTeamCity, + OutFormatSarif, } type Output struct { - Format string - PrintIssuedLine bool `mapstructure:"print-issued-lines"` - PrintLinterName bool `mapstructure:"print-linter-name"` - UniqByLine bool `mapstructure:"uniq-by-line"` - SortResults bool `mapstructure:"sort-results"` - PrintWelcomeMessage bool `mapstructure:"print-welcome"` - PathPrefix string `mapstructure:"path-prefix"` - - // only work with CLI flags because the setup of logs is done before the config file parsing. - Color string + Formats OutputFormats `mapstructure:"formats"` + PrintIssuedLine bool `mapstructure:"print-issued-lines"` + PrintLinterName bool `mapstructure:"print-linter-name"` + UniqByLine bool `mapstructure:"uniq-by-line"` + SortResults bool `mapstructure:"sort-results"` + SortOrder []string `mapstructure:"sort-order"` + PathPrefix string `mapstructure:"path-prefix"` + ShowStats bool `mapstructure:"show-stats"` + + // Deprecated: use Formats instead. + Format string `mapstructure:"format"` +} + +func (o *Output) Validate() error { + if !o.SortResults && len(o.SortOrder) > 0 { + return errors.New("sort-results should be 'true' to use sort-order") + } + + validOrders := []string{"linter", "file", "severity"} + + all := strings.Join(o.SortOrder, " ") + + for _, order := range o.SortOrder { + if strings.Count(all, order) > 1 { + return fmt.Errorf("the sort-order name %q is repeated several times", order) + } + + if !slices.Contains(validOrders, order) { + return fmt.Errorf("unsupported sort-order name %q", order) + } + } + + for _, format := range o.Formats { + err := format.Validate() + if err != nil { + return err + } + } + + return nil +} + +type OutputFormat struct { + Format string `mapstructure:"format"` + Path string `mapstructure:"path"` +} + +func (o *OutputFormat) Validate() error { + if o.Format == "" { + return errors.New("the format is required") + } + + if !slices.Contains(AllOutputFormats, o.Format) { + return fmt.Errorf("unsupported output format %q", o.Format) + } + + return nil +} + +type OutputFormats []OutputFormat + +func (p *OutputFormats) UnmarshalText(text []byte) error { + formats := strings.Split(string(text), ",") + + for _, item := range formats { + format, path, _ := strings.Cut(item, ":") + + *p = append(*p, OutputFormat{ + Path: path, + Format: format, + }) + } + + return nil } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go deleted file mode 100644 index de203876e..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go +++ /dev/null @@ -1,248 +0,0 @@ -package config - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/mitchellh/go-homedir" - "github.com/mitchellh/mapstructure" - "github.com/spf13/viper" - "golang.org/x/exp/slices" - - "github.com/golangci/golangci-lint/pkg/exitcodes" - "github.com/golangci/golangci-lint/pkg/fsutils" - "github.com/golangci/golangci-lint/pkg/logutils" -) - -type FileReader struct { - log logutils.Log - cfg *Config - commandLineCfg *Config -} - -func NewFileReader(toCfg, commandLineCfg *Config, log logutils.Log) *FileReader { - return &FileReader{ - log: log, - cfg: toCfg, - commandLineCfg: commandLineCfg, - } -} - -func (r *FileReader) Read() error { - // XXX: hack with double parsing for 2 purposes: - // 1. to access "config" option here. - // 2. to give config less priority than command line. - - configFile, err := r.parseConfigOption() - if err != nil { - if err == errConfigDisabled { - return nil - } - - return fmt.Errorf("can't parse --config option: %s", err) - } - - if configFile != "" { - viper.SetConfigFile(configFile) - - // Assume YAML if the file has no extension. - if filepath.Ext(configFile) == "" { - viper.SetConfigType("yaml") - } - } else { - r.setupConfigFileSearch() - } - - return r.parseConfig() -} - -func (r *FileReader) parseConfig() error { - if err := viper.ReadInConfig(); err != nil { - if _, ok := err.(viper.ConfigFileNotFoundError); ok { - return nil - } - - return fmt.Errorf("can't read viper config: %s", err) - } - - usedConfigFile := viper.ConfigFileUsed() - if usedConfigFile == "" { - return nil - } - - if usedConfigFile == os.Stdin.Name() { - usedConfigFile = "" - r.log.Infof("Reading config file stdin") - } else { - var err error - usedConfigFile, err = fsutils.ShortestRelPath(usedConfigFile, "") - if err != nil { - r.log.Warnf("Can't pretty print config file path: %v", err) - } - - r.log.Infof("Used config file %s", usedConfigFile) - } - - usedConfigDir, err := filepath.Abs(filepath.Dir(usedConfigFile)) - if err != nil { - return errors.New("can't get config directory") - } - r.cfg.cfgDir = usedConfigDir - - if err := viper.Unmarshal(r.cfg, viper.DecodeHook(mapstructure.ComposeDecodeHookFunc( - // Default hooks (https://github.com/spf13/viper/blob/518241257478c557633ab36e474dfcaeb9a3c623/viper.go#L135-L138). - mapstructure.StringToTimeDurationHookFunc(), - mapstructure.StringToSliceHookFunc(","), - - // Needed for forbidigo. - mapstructure.TextUnmarshallerHookFunc(), - ))); err != nil { - return fmt.Errorf("can't unmarshal config by viper: %s", err) - } - - if err := r.validateConfig(); err != nil { - return fmt.Errorf("can't validate config: %s", err) - } - - if r.cfg.InternalTest { // just for testing purposes: to detect config file usage - fmt.Fprintln(logutils.StdOut, "test") - os.Exit(exitcodes.Success) - } - - return nil -} - -func (r *FileReader) validateConfig() error { - c := r.cfg - if len(c.Run.Args) != 0 { - return errors.New("option run.args in config isn't supported now") - } - - if c.Run.CPUProfilePath != "" { - return errors.New("option run.cpuprofilepath in config isn't allowed") - } - - if c.Run.MemProfilePath != "" { - return errors.New("option run.memprofilepath in config isn't allowed") - } - - if c.Run.TracePath != "" { - return errors.New("option run.tracepath in config isn't allowed") - } - - if c.Run.IsVerbose { - return errors.New("can't set run.verbose option with config: only on command-line") - } - for i, rule := range c.Issues.ExcludeRules { - if err := rule.Validate(); err != nil { - return fmt.Errorf("error in exclude rule #%d: %v", i, err) - } - } - if len(c.Severity.Rules) > 0 && c.Severity.Default == "" { - return errors.New("can't set severity rule option: no default severity defined") - } - for i, rule := range c.Severity.Rules { - if err := rule.Validate(); err != nil { - return fmt.Errorf("error in severity rule #%d: %v", i, err) - } - } - if err := c.LintersSettings.Govet.Validate(); err != nil { - return fmt.Errorf("error in govet config: %v", err) - } - return nil -} - -func getFirstPathArg() string { - args := os.Args - - // skip all args ([golangci-lint, run/linters]) before files/dirs list - for len(args) != 0 { - if args[0] == "run" { - args = args[1:] - break - } - - args = args[1:] - } - - // find first file/dir arg - firstArg := "./..." - for _, arg := range args { - if !strings.HasPrefix(arg, "-") { - firstArg = arg - break - } - } - - return firstArg -} - -func (r *FileReader) setupConfigFileSearch() { - firstArg := getFirstPathArg() - absStartPath, err := filepath.Abs(firstArg) - if err != nil { - r.log.Warnf("Can't make abs path for %q: %s", firstArg, err) - absStartPath = filepath.Clean(firstArg) - } - - // start from it - var curDir string - if fsutils.IsDir(absStartPath) { - curDir = absStartPath - } else { - curDir = filepath.Dir(absStartPath) - } - - // find all dirs from it up to the root - configSearchPaths := []string{"./"} - - for { - configSearchPaths = append(configSearchPaths, curDir) - newCurDir := filepath.Dir(curDir) - if curDir == newCurDir || newCurDir == "" { - break - } - curDir = newCurDir - } - - // find home directory for global config - if home, err := homedir.Dir(); err != nil { - r.log.Warnf("Can't get user's home directory: %s", err.Error()) - } else if !slices.Contains(configSearchPaths, home) { - configSearchPaths = append(configSearchPaths, home) - } - - r.log.Infof("Config search paths: %s", configSearchPaths) - viper.SetConfigName(".golangci") - for _, p := range configSearchPaths { - viper.AddConfigPath(p) - } -} - -var errConfigDisabled = errors.New("config is disabled by --no-config") - -func (r *FileReader) parseConfigOption() (string, error) { - cfg := r.commandLineCfg - if cfg == nil { - return "", nil - } - - configFile := cfg.Run.Config - if cfg.Run.NoConfig && configFile != "" { - return "", errors.New("can't combine option --config and --no-config") - } - - if cfg.Run.NoConfig { - return "", errConfigDisabled - } - - configFile, err := homedir.Expand(configFile) - if err != nil { - return "", errors.New("failed to expand configuration path") - } - - return configFile, nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/run.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/run.go index ff812d0a2..2f6523c0b 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/run.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/run.go @@ -1,21 +1,17 @@ package config -import "time" +import ( + "fmt" + "slices" + "strings" + "time" +) // Run encapsulates the config options for running the linter analysis. type Run struct { - IsVerbose bool `mapstructure:"verbose"` - Silent bool - CPUProfilePath string - MemProfilePath string - TracePath string - Concurrency int - PrintResourcesUsage bool `mapstructure:"print-resources-usage"` + Timeout time.Duration `mapstructure:"timeout"` - Config string // The path to the golangci config file, as specified with the --config argument. - NoConfig bool - - Args []string + Concurrency int `mapstructure:"concurrency"` Go string `mapstructure:"go"` @@ -25,16 +21,27 @@ type Run struct { ExitCodeIfIssuesFound int `mapstructure:"issues-exit-code"` AnalyzeTests bool `mapstructure:"tests"` - // Deprecated: Deadline exists for historical compatibility - // and should not be used. To set run timeout use Timeout instead. - Deadline time.Duration - Timeout time.Duration - - PrintVersion bool - SkipFiles []string `mapstructure:"skip-files"` - SkipDirs []string `mapstructure:"skip-dirs"` - UseDefaultSkipDirs bool `mapstructure:"skip-dirs-use-default"` - AllowParallelRunners bool `mapstructure:"allow-parallel-runners"` AllowSerialRunners bool `mapstructure:"allow-serial-runners"` + + // Deprecated: use Issues.ExcludeFiles instead. + SkipFiles []string `mapstructure:"skip-files"` + // Deprecated: use Issues.ExcludeDirs instead. + SkipDirs []string `mapstructure:"skip-dirs"` + // Deprecated: use Issues.UseDefaultExcludeDirs instead. + UseDefaultSkipDirs bool `mapstructure:"skip-dirs-use-default"` + + // Deprecated: use Output.ShowStats instead. + ShowStats bool `mapstructure:"show-stats"` +} + +func (r *Run) Validate() error { + // go help modules + allowedMods := []string{"mod", "readonly", "vendor"} + + if r.ModulesDownloadMode != "" && !slices.Contains(allowedMods, r.ModulesDownloadMode) { + return fmt.Errorf("invalid modules download path %s, only (%s) allowed", r.ModulesDownloadMode, strings.Join(allowedMods, "|")) + } + + return nil } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/severity.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/severity.go index 3068a0ed6..a6d2c9ec3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/severity.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/severity.go @@ -1,5 +1,10 @@ package config +import ( + "errors" + "fmt" +) + const severityRuleMinConditionsCount = 1 type Severity struct { @@ -8,11 +13,29 @@ type Severity struct { Rules []SeverityRule `mapstructure:"rules"` } +func (s *Severity) Validate() error { + if len(s.Rules) > 0 && s.Default == "" { + return errors.New("can't set severity rule option: no default severity defined") + } + + for i, rule := range s.Rules { + if err := rule.Validate(); err != nil { + return fmt.Errorf("error in severity rule #%d: %w", i, err) + } + } + + return nil +} + type SeverityRule struct { BaseRule `mapstructure:",squash"` Severity string } func (s *SeverityRule) Validate() error { + if s.Severity == "" { + return errors.New("severity should be set") + } + return s.BaseRule.Validate(severityRuleMinConditionsCount) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/fsutils.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/fsutils.go index a39c105e4..80bb9c5b4 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/fsutils.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/fsutils.go @@ -12,10 +12,12 @@ func IsDir(filename string) bool { return err == nil && fi.IsDir() } -var cachedWd string -var cachedWdError error -var getWdOnce sync.Once -var useCache = true +var ( + cachedWd string + cachedWdError error + getWdOnce sync.Once + useCache = true +) func UseWdCache(use bool) { useCache = use @@ -34,7 +36,7 @@ func Getwd() (string, error) { evaledWd, err := EvalSymlinks(cachedWd) if err != nil { - cachedWd, cachedWdError = "", fmt.Errorf("can't eval symlinks on wd %s: %s", cachedWd, err) + cachedWd, cachedWdError = "", fmt.Errorf("can't eval symlinks on wd %s: %w", cachedWd, err) return } @@ -70,13 +72,13 @@ func ShortestRelPath(path, wd string) (string, error) { var err error wd, err = Getwd() if err != nil { - return "", fmt.Errorf("can't get working directory: %s", err) + return "", fmt.Errorf("can't get working directory: %w", err) } } evaledPath, err := EvalSymlinks(path) if err != nil { - return "", fmt.Errorf("can't eval symlinks for path %s: %s", path, err) + return "", fmt.Errorf("can't eval symlinks for path %s: %w", path, err) } path = evaledPath @@ -92,7 +94,7 @@ func ShortestRelPath(path, wd string) (string, error) { relPath, err := filepath.Rel(wd, absPath) if err != nil { - return "", fmt.Errorf("can't get relative path for path %s and root %s: %s", + return "", fmt.Errorf("can't get relative path for path %s and root %s: %w", absPath, wd, err) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/issue.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/issue.go similarity index 81% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/issue.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/issue.go index f331a3ab9..15d8dd2b3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/issue.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/issue.go @@ -13,9 +13,9 @@ type Issue struct { Pass *analysis.Pass } -func NewIssue(i *result.Issue, pass *analysis.Pass) Issue { +func NewIssue(issue *result.Issue, pass *analysis.Pass) Issue { return Issue{ - Issue: *i, + Issue: *issue, Pass: pass, } } @@ -23,6 +23,7 @@ func NewIssue(i *result.Issue, pass *analysis.Pass) Issue { type EncodingIssue struct { FromLinter string Text string + Severity string Pos token.Position LineRange *result.Range Replacement *result.Replacement diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/linter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/linter.go similarity index 97% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/linter.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/linter.go index f8ca2e755..13d3a09a5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/linter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/linter.go @@ -102,7 +102,7 @@ func (lnt *Linter) allAnalyzerNames() []string { return ret } -func (lnt *Linter) configureAnalyzer(a *analysis.Analyzer, cfg map[string]any) error { +func (*Linter) configureAnalyzer(a *analysis.Analyzer, cfg map[string]any) error { for k, v := range cfg { f := a.Flags.Lookup(k) if f == nil { @@ -116,7 +116,7 @@ func (lnt *Linter) configureAnalyzer(a *analysis.Analyzer, cfg map[string]any) e } if err := f.Value.Set(valueToString(v)); err != nil { - return fmt.Errorf("failed to set analyzer setting %q with value %v: %w", k, v, err) + return fmt.Errorf("failed to set analyzer setting %q with value %q: %w", k, v, err) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load/guard.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/load/guard.go similarity index 100% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load/guard.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/load/guard.go diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/metalinter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/metalinter.go similarity index 92% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/metalinter.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/metalinter.go index 333ab20f1..c2a794997 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/metalinter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/metalinter.go @@ -31,11 +31,11 @@ func (ml MetaLinter) Run(_ context.Context, lintCtx *linter.Context) ([]result.I return runAnalyzers(ml, lintCtx) } -func (ml MetaLinter) Name() string { +func (MetaLinter) Name() string { return "goanalysis_metalinter" } -func (ml MetaLinter) Desc() string { +func (MetaLinter) Desc() string { return "" } @@ -57,11 +57,11 @@ func (ml MetaLinter) getAnalyzers() []*analysis.Analyzer { return allAnalyzers } -func (ml MetaLinter) getName() string { +func (MetaLinter) getName() string { return "metalinter" } -func (ml MetaLinter) useOriginalPackages() bool { +func (MetaLinter) useOriginalPackages() bool { return false // `unused` can't be run by this metalinter } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/errors.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/errors.go similarity index 60% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/errors.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/errors.go index f59e02cc6..91f6dd39d 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/errors.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/errors.go @@ -1,4 +1,4 @@ -package goanalysis +package pkgerrors import ( "errors" @@ -7,7 +7,6 @@ import ( "golang.org/x/tools/go/packages" "github.com/golangci/golangci-lint/pkg/lint/linter" - libpackages "github.com/golangci/golangci-lint/pkg/packages" "github.com/golangci/golangci-lint/pkg/result" ) @@ -19,7 +18,7 @@ func (e *IllTypedError) Error() string { return fmt.Sprintf("errors in package: %v", e.Pkg.Errors) } -func buildIssuesFromIllTypedError(errs []error, lintCtx *linter.Context) ([]result.Issue, error) { +func BuildIssuesFromIllTypedError(errs []error, lintCtx *linter.Context) ([]result.Issue, error) { var issues []result.Issue uniqReportedIssues := map[string]bool{} @@ -36,8 +35,8 @@ func buildIssuesFromIllTypedError(errs []error, lintCtx *linter.Context) ([]resu continue } - for _, err := range libpackages.ExtractErrors(ill.Pkg) { - i, perr := parseError(err) + for _, err := range extractErrors(ill.Pkg) { + issue, perr := parseError(err) if perr != nil { // failed to parse if uniqReportedIssues[err.Msg] { continue @@ -45,8 +44,8 @@ func buildIssuesFromIllTypedError(errs []error, lintCtx *linter.Context) ([]resu uniqReportedIssues[err.Msg] = true lintCtx.Log.Errorf("typechecking error: %s", err.Msg) } else { - i.Pkg = ill.Pkg // to save to cache later - issues = append(issues, *i) + issue.Pkg = ill.Pkg // to save to cache later + issues = append(issues, *issue) } } } @@ -57,16 +56,3 @@ func buildIssuesFromIllTypedError(errs []error, lintCtx *linter.Context) ([]resu return issues, nil } - -func parseError(srcErr packages.Error) (*result.Issue, error) { - pos, err := libpackages.ParseErrorPosition(srcErr.Pos) - if err != nil { - return nil, err - } - - return &result.Issue{ - Pos: *pos, - Text: srcErr.Msg, - FromLinter: "typecheck", - }, nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/packages/util.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/extract.go similarity index 93% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/packages/util.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/extract.go index 6a7789ebb..d1257e663 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/packages/util.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/extract.go @@ -1,4 +1,4 @@ -package packages +package pkgerrors import ( "fmt" @@ -12,7 +12,7 @@ import ( // ex: `/example/main.go:11:17: foobar` var reFile = regexp.MustCompile(`^.+\.go:\d+:\d+: .+`) -func ExtractErrors(pkg *packages.Package) []packages.Error { +func extractErrors(pkg *packages.Package) []packages.Error { errors := extractErrorsImpl(pkg, map[*packages.Package]bool{}) if len(errors) == 0 { return errors @@ -38,7 +38,7 @@ func ExtractErrors(pkg *packages.Package) []packages.Error { if len(pkg.GoFiles) != 0 { // errors were extracted from deps and have at least one file in package for i := range uniqErrors { - if _, parseErr := ParseErrorPosition(uniqErrors[i].Pos); parseErr == nil { + if _, parseErr := parseErrorPosition(uniqErrors[i].Pos); parseErr == nil { continue } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/packages/errors.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/parse.go similarity index 53% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/packages/errors.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/parse.go index 489836712..b25b50f71 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/packages/errors.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors/parse.go @@ -1,4 +1,4 @@ -package packages +package pkgerrors import ( "errors" @@ -6,9 +6,26 @@ import ( "go/token" "strconv" "strings" + + "golang.org/x/tools/go/packages" + + "github.com/golangci/golangci-lint/pkg/result" ) -func ParseErrorPosition(pos string) (*token.Position, error) { +func parseError(srcErr packages.Error) (*result.Issue, error) { + pos, err := parseErrorPosition(srcErr.Pos) + if err != nil { + return nil, err + } + + return &result.Issue{ + Pos: *pos, + Text: srcErr.Msg, + FromLinter: "typecheck", + }, nil +} + +func parseErrorPosition(pos string) (*token.Position, error) { // file:line(:colon) parts := strings.Split(pos, ":") if len(parts) == 1 { @@ -18,7 +35,7 @@ func ParseErrorPosition(pos string) (*token.Position, error) { file := parts[0] line, err := strconv.Atoi(parts[1]) if err != nil { - return nil, fmt.Errorf("can't parse line number %q: %s", parts[1], err) + return nil, fmt.Errorf("can't parse line number %q: %w", parts[1], err) } var column int diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner.go similarity index 92% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner.go index 46871bc5b..c1274ec09 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner.go @@ -17,12 +17,13 @@ import ( "sort" "sync" + "golang.org/x/exp/maps" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/packages" "github.com/golangci/golangci-lint/internal/errorutil" "github.com/golangci/golangci-lint/internal/pkgcache" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load" + "github.com/golangci/golangci-lint/pkg/goanalysis/load" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/timeutils" ) @@ -60,7 +61,8 @@ type runner struct { } func newRunner(prefix string, logger logutils.Log, pkgCache *pkgcache.Cache, loadGuard *load.Guard, - loadMode LoadMode, sw *timeutils.Stopwatch) *runner { + loadMode LoadMode, sw *timeutils.Stopwatch, +) *runner { return &runner{ prefix: prefix, log: logger, @@ -79,7 +81,8 @@ func newRunner(prefix string, logger logutils.Log, pkgCache *pkgcache.Cache, loa // singlechecker and the multi-analysis commands. // It returns the appropriate exit code. func (r *runner) run(analyzers []*analysis.Analyzer, initialPackages []*packages.Package) ([]Diagnostic, - []error, map[*analysis.Pass]*packages.Package) { + []error, map[*analysis.Pass]*packages.Package, +) { debugf("Analyzing %d packages on load mode %s", len(initialPackages), r.loadMode) defer r.pkgCache.Trim() @@ -115,7 +118,8 @@ func (r *runner) markAllActions(a *analysis.Analyzer, pkg *packages.Package, mar } func (r *runner) makeAction(a *analysis.Analyzer, pkg *packages.Package, - initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator) *action { + initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator, +) *action { k := actKey{a, pkg} act, ok := actions[k] if ok { @@ -149,7 +153,8 @@ func (r *runner) makeAction(a *analysis.Analyzer, pkg *packages.Package, } func (r *runner) buildActionFactDeps(act *action, a *analysis.Analyzer, pkg *packages.Package, - initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator) { + initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator, +) { // An analysis that consumes/produces facts // must run on the package's dependencies too. if len(a.FactTypes) == 0 { @@ -159,10 +164,7 @@ func (r *runner) buildActionFactDeps(act *action, a *analysis.Analyzer, pkg *pac act.objectFacts = make(map[objectFactKey]analysis.Fact) act.packageFacts = make(map[packageFactKey]analysis.Fact) - paths := make([]string, 0, len(pkg.Imports)) - for path := range pkg.Imports { - paths = append(paths, path) - } + paths := maps.Keys(pkg.Imports) sort.Strings(paths) // for determinism for _, path := range paths { dep := r.makeAction(a, pkg.Imports[path], initialPkgs, actions, actAlloc) @@ -175,9 +177,9 @@ func (r *runner) buildActionFactDeps(act *action, a *analysis.Analyzer, pkg *pac } } -//nolint:gocritic func (r *runner) prepareAnalysis(pkgs []*packages.Package, - analyzers []*analysis.Analyzer) (map[*packages.Package]bool, []*action, []*action) { + analyzers []*analysis.Analyzer, +) (initialPkgs map[*packages.Package]bool, allActions, roots []*action) { // Construct the action graph. // Each graph node (action) is one unit of analysis. @@ -197,13 +199,13 @@ func (r *runner) prepareAnalysis(pkgs []*packages.Package, actions := make(map[actKey]*action, totalActionsCount) actAlloc := newActionAllocator(totalActionsCount) - initialPkgs := make(map[*packages.Package]bool, len(pkgs)) + initialPkgs = make(map[*packages.Package]bool, len(pkgs)) for _, pkg := range pkgs { initialPkgs[pkg] = true } // Build nodes for initial packages. - roots := make([]*action, 0, len(pkgs)*len(analyzers)) + roots = make([]*action, 0, len(pkgs)*len(analyzers)) for _, a := range analyzers { for _, pkg := range pkgs { root := r.makeAction(a, pkg, initialPkgs, actions, actAlloc) @@ -212,10 +214,7 @@ func (r *runner) prepareAnalysis(pkgs []*packages.Package, } } - allActions := make([]*action, 0, len(actions)) - for _, act := range actions { - allActions = append(allActions, act) - } + allActions = maps.Values(actions) debugf("Built %d actions", len(actions)) @@ -281,7 +280,6 @@ func (r *runner) analyze(pkgs []*packages.Package, analyzers []*analysis.Analyze return rootActions } -//nolint:nakedret func extractDiagnostics(roots []*action) (retDiags []Diagnostic, retErrors []error) { extracted := make(map[*action]bool) var extract func(*action) @@ -338,5 +336,5 @@ func extractDiagnostics(roots []*action) (retDiags []Diagnostic, retErrors []err } } visitAll(roots) - return + return retDiags, retErrors } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_action.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_action.go similarity index 97% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_action.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_action.go index 5ded9fac9..58ea297ea 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_action.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_action.go @@ -9,13 +9,13 @@ import ( "runtime/debug" "time" - "github.com/hashicorp/go-multierror" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/types/objectpath" "github.com/golangci/golangci-lint/internal/errorutil" "github.com/golangci/golangci-lint/internal/pkgcache" + "github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors" ) type actionAllocator struct { @@ -126,20 +126,16 @@ func (act *action) analyze() { }(time.Now()) // Report an error if any dependency failures. - var depErrors *multierror.Error + var depErrors error for _, dep := range act.deps { if dep.err == nil { continue } - depErrors = multierror.Append(depErrors, errors.Unwrap(dep.err)) + depErrors = errors.Join(depErrors, errors.Unwrap(dep.err)) } if depErrors != nil { - depErrors.ErrorFormat = func(e []error) string { - return fmt.Sprintf("failed prerequisites: %v", e) - } - - act.err = depErrors + act.err = fmt.Errorf("failed prerequisites: %w", depErrors) return } @@ -189,7 +185,7 @@ func (act *action) analyze() { // It looks like there should be !pass.Analyzer.RunDespiteErrors // but govet's cgocall crashes on it. Govet itself contains !pass.Analyzer.RunDespiteErrors condition here, // but it exits before it if packages.Load have failed. - act.err = fmt.Errorf("analysis skipped: %w", &IllTypedError{Pkg: act.pkg}) + act.err = fmt.Errorf("analysis skipped: %w", &pkgerrors.IllTypedError{Pkg: act.pkg}) } else { startedAt = time.Now() act.result, act.err = pass.Analyzer.Run(pass) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_facts.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_facts.go similarity index 100% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_facts.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_facts.go diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_loadingpackage.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_loadingpackage.go similarity index 99% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_loadingpackage.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_loadingpackage.go index e39e2212c..c54357eb6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_loadingpackage.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runner_loadingpackage.go @@ -15,7 +15,7 @@ import ( "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/go/packages" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load" + "github.com/golangci/golangci-lint/pkg/goanalysis/load" "github.com/golangci/golangci-lint/pkg/logutils" ) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runners.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runners.go similarity index 88% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runners.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runners.go index 559fb1392..c02d33b79 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runners.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goanalysis/runners.go @@ -13,6 +13,7 @@ import ( "golang.org/x/tools/go/packages" "github.com/golangci/golangci-lint/internal/pkgcache" + "github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" @@ -74,7 +75,7 @@ func runAnalyzers(cfg runAnalyzersConfig, lintCtx *linter.Context) ([]result.Iss return retIssues } - errIssues, err := buildIssuesFromIllTypedError(errs, lintCtx) + errIssues, err := pkgerrors.BuildIssuesFromIllTypedError(errs, lintCtx) if err != nil { return nil, err } @@ -124,7 +125,8 @@ func getIssuesCacheKey(analyzers []*analysis.Analyzer) string { } func saveIssuesToCache(allPkgs []*packages.Package, pkgsFromCache map[*packages.Package]bool, - issues []result.Issue, lintCtx *linter.Context, analyzers []*analysis.Analyzer) { + issues []result.Issue, lintCtx *linter.Context, analyzers []*analysis.Analyzer, +) { startedAt := time.Now() perPkgIssues := map[*packages.Package][]result.Issue{} for ind := range issues { @@ -151,6 +153,7 @@ func saveIssuesToCache(allPkgs []*packages.Package, pkgsFromCache map[*packages. encodedIssues = append(encodedIssues, EncodingIssue{ FromLinter: i.FromLinter, Text: i.Text, + Severity: i.Severity, Pos: i.Pos, LineRange: i.LineRange, Replacement: i.Replacement, @@ -182,9 +185,9 @@ func saveIssuesToCache(allPkgs []*packages.Package, pkgsFromCache map[*packages. issuesCacheDebugf("Saved %d issues from %d packages to cache in %s", savedIssuesCount, len(allPkgs), time.Since(startedAt)) } -//nolint:gocritic func loadIssuesFromCache(pkgs []*packages.Package, lintCtx *linter.Context, - analyzers []*analysis.Analyzer) ([]result.Issue, map[*packages.Package]bool) { + analyzers []*analysis.Analyzer, +) (issuesFromCache []result.Issue, pkgsFromCache map[*packages.Package]bool) { startedAt := time.Now() lintResKey := getIssuesCacheKey(analyzers) @@ -218,16 +221,18 @@ func loadIssuesFromCache(pkgs []*packages.Package, lintCtx *linter.Context, } issues := make([]result.Issue, 0, len(pkgIssues)) - for _, i := range pkgIssues { + for i := range pkgIssues { + issue := &pkgIssues[i] issues = append(issues, result.Issue{ - FromLinter: i.FromLinter, - Text: i.Text, - Pos: i.Pos, - LineRange: i.LineRange, - Replacement: i.Replacement, + FromLinter: issue.FromLinter, + Text: issue.Text, + Severity: issue.Severity, + Pos: issue.Pos, + LineRange: issue.LineRange, + Replacement: issue.Replacement, Pkg: pkg, - ExpectNoLint: i.ExpectNoLint, - ExpectedNoLintLinter: i.ExpectedNoLintLinter, + ExpectNoLint: issue.ExpectNoLint, + ExpectedNoLintLinter: issue.ExpectedNoLintLinter, }) } cacheRes.issues = issues @@ -242,13 +247,12 @@ func loadIssuesFromCache(pkgs []*packages.Package, lintCtx *linter.Context, wg.Wait() loadedIssuesCount := 0 - var issues []result.Issue - pkgsFromCache := map[*packages.Package]bool{} + pkgsFromCache = map[*packages.Package]bool{} for pkg, cacheRes := range pkgToCacheRes { if cacheRes.loadErr == nil { loadedIssuesCount += len(cacheRes.issues) pkgsFromCache[pkg] = true - issues = append(issues, cacheRes.issues...) + issuesFromCache = append(issuesFromCache, cacheRes.issues...) issuesCacheDebugf("Loaded package %s issues (%d) from cache", pkg, len(cacheRes.issues)) } else { issuesCacheDebugf("Didn't load package %s issues from cache: %s", pkg, cacheRes.loadErr) @@ -256,7 +260,7 @@ func loadIssuesFromCache(pkgs []*packages.Package, lintCtx *linter.Context, } issuesCacheDebugf("Loaded %d issues from cache in %s, analyzing %d/%d packages", loadedIssuesCount, time.Since(startedAt), len(pkgs)-len(pkgsFromCache), len(pkgs)) - return issues, pkgsFromCache + return issuesFromCache, pkgsFromCache } func analyzersHashID(analyzers []*analysis.Analyzer) string { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asasalint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asasalint/asasalint.go similarity index 65% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asasalint.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asasalint/asasalint.go index 67dde7991..653a2d514 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asasalint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asasalint/asasalint.go @@ -1,14 +1,15 @@ -package golinters +package asasalint import ( "github.com/alingse/asasalint" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" ) -func NewAsasalint(setting *config.AsasalintSettings) *goanalysis.Linter { +func New(setting *config.AsasalintSettings) *goanalysis.Linter { cfg := asasalint.LinterSetting{} if setting != nil { cfg.Exclude = setting.Exclude @@ -18,7 +19,7 @@ func NewAsasalint(setting *config.AsasalintSettings) *goanalysis.Linter { a, err := asasalint.NewAnalyzer(cfg) if err != nil { - linterLogger.Fatalf("asasalint: create analyzer: %v", err) + internal.LinterLogger.Fatalf("asasalint: create analyzer: %v", err) } return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck.go deleted file mode 100644 index df301b417..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck.go +++ /dev/null @@ -1,17 +0,0 @@ -package golinters - -import ( - "github.com/tdakkota/asciicheck" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewAsciicheck() *goanalysis.Linter { - return goanalysis.NewLinter( - "asciicheck", - "Simple linter to check that your code does not contain non-ASCII identifiers", - []*analysis.Analyzer{asciicheck.NewAnalyzer()}, - nil, - ).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck/asciicheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck/asciicheck.go new file mode 100644 index 000000000..675dfc478 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck/asciicheck.go @@ -0,0 +1,19 @@ +package asciicheck + +import ( + "github.com/tdakkota/asciicheck" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := asciicheck.NewAnalyzer() + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bidichk.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bidichk/bidichk.go similarity index 88% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bidichk.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bidichk/bidichk.go index e1b347176..4ced901e8 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bidichk.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bidichk/bidichk.go @@ -1,4 +1,4 @@ -package golinters +package bidichk import ( "strings" @@ -7,10 +7,10 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewBiDiChkFuncName(cfg *config.BiDiChkSettings) *goanalysis.Linter { +func New(cfg *config.BiDiChkSettings) *goanalysis.Linter { a := bidichk.NewAnalyzer() cfgMap := map[string]map[string]any{} @@ -51,7 +51,7 @@ func NewBiDiChkFuncName(cfg *config.BiDiChkSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - "bidichk", + a.Name, "Checks for dangerous unicode character sequences", []*analysis.Analyzer{a}, cfgMap, diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose/bodyclose.go similarity index 57% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose/bodyclose.go index e56bd83f2..f39814edc 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose/bodyclose.go @@ -1,17 +1,19 @@ -package golinters +package bodyclose import ( "github.com/timakin/bodyclose/passes/bodyclose" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewBodyclose() *goanalysis.Linter { +func New() *goanalysis.Linter { + a := bodyclose.Analyzer + return goanalysis.NewLinter( - "bodyclose", + a.Name, "checks whether HTTP response body is closed successfully", - []*analysis.Analyzer{bodyclose.Analyzer}, + []*analysis.Analyzer{a}, nil, ).WithLoadMode(goanalysis.LoadModeTypesInfo) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/canonicalheader/canonicalheader.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/canonicalheader/canonicalheader.go new file mode 100644 index 000000000..d721916a4 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/canonicalheader/canonicalheader.go @@ -0,0 +1,19 @@ +package canonicalheader + +import ( + "github.com/lasiar/canonicalheader" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := canonicalheader.Analyzer + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/commons.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/commons.go deleted file mode 100644 index 3b40e59bf..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/commons.go +++ /dev/null @@ -1,6 +0,0 @@ -package golinters - -import "github.com/golangci/golangci-lint/pkg/logutils" - -// linterLogger must be use only when the context logger is not available. -var linterLogger = logutils.NewStderrLog(logutils.DebugKeyLinter) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/containedctx.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/containedctx/containedctx.go similarity index 66% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/containedctx.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/containedctx/containedctx.go index 8f7859af7..6fdb4ea6e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/containedctx.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/containedctx/containedctx.go @@ -1,13 +1,13 @@ -package golinters +package containedctx import ( "github.com/sivchari/containedctx" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewContainedCtx() *goanalysis.Linter { +func New() *goanalysis.Linter { a := containedctx.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck/contextcheck.go similarity index 79% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck/contextcheck.go index f54192a18..a34c518b2 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck/contextcheck.go @@ -1,14 +1,14 @@ -package golinters +package contextcheck import ( "github.com/kkHAIKE/contextcheck" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" ) -func NewContextCheck() *goanalysis.Linter { +func New() *goanalysis.Linter { analyzer := contextcheck.NewAnalyzer(contextcheck.Configuration{}) return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/copyloopvar/copyloopvar.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/copyloopvar/copyloopvar.go new file mode 100644 index 000000000..adb4ee728 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/copyloopvar/copyloopvar.go @@ -0,0 +1,29 @@ +package copyloopvar + +import ( + "github.com/karamaru-alpha/copyloopvar" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.CopyLoopVarSettings) *goanalysis.Linter { + a := copyloopvar.NewAnalyzer() + + var cfg map[string]map[string]any + if settings != nil { + cfg = map[string]map[string]any{ + a.Name: { + "check-alias": settings.CheckAlias, + }, + } + } + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + cfg, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/cyclop.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/cyclop/cyclop.go similarity index 78% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/cyclop.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/cyclop/cyclop.go index 5ad65f122..eb8c0577a 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/cyclop.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/cyclop/cyclop.go @@ -1,16 +1,14 @@ -package golinters +package cyclop import ( "github.com/bkielbasa/cyclop/pkg/analyzer" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -const cyclopName = "cyclop" - -func NewCyclop(settings *config.Cyclop) *goanalysis.Linter { +func New(settings *config.Cyclop) *goanalysis.Linter { a := analyzer.NewAnalyzer() var cfg map[string]map[string]any @@ -31,7 +29,7 @@ func NewCyclop(settings *config.Cyclop) *goanalysis.Linter { } return goanalysis.NewLinter( - cyclopName, + a.Name, "checks function and package cyclomatic complexity", []*analysis.Analyzer{a}, cfg, diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/deadcode.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/deadcode.go deleted file mode 100644 index 4f563c381..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/deadcode.go +++ /dev/null @@ -1,61 +0,0 @@ -package golinters - -import ( - "fmt" - "sync" - - deadcodeAPI "github.com/golangci/go-misc/deadcode" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const deadcodeName = "deadcode" - -func NewDeadcode() *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: deadcodeName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - prog := goanalysis.MakeFakeLoaderProgram(pass) - - issues, err := deadcodeAPI.Run(prog) - if err != nil { - return nil, err - } - - res := make([]goanalysis.Issue, 0, len(issues)) - for _, i := range issues { - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: fmt.Sprintf("%s is unused", formatCode(i.UnusedIdentName, nil)), - FromLinter: deadcodeName, - }, pass)) - } - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, res...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - deadcodeName, - "Finds unused code", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder/decorder.go similarity index 89% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder/decorder.go index 5202a03a4..a05f6a325 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder/decorder.go @@ -1,4 +1,4 @@ -package golinters +package decorder import ( "strings" @@ -7,10 +7,10 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewDecorder(settings *config.DecorderSettings) *goanalysis.Linter { +func New(settings *config.DecorderSettings) *goanalysis.Linter { a := decorder.Analyzer // disable all rules/checks by default diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard/depguard.go similarity index 82% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard/depguard.go index 23986708c..d2aedf252 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard/depguard.go @@ -1,22 +1,23 @@ -package golinters +package depguard import ( "github.com/OpenPeeDeeP/depguard/v2" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" ) -func NewDepguard(settings *config.DepGuardSettings) *goanalysis.Linter { +func New(settings *config.DepGuardSettings) *goanalysis.Linter { conf := depguard.LinterSettings{} if settings != nil { for s, rule := range settings.Rules { list := &depguard.List{ - Files: rule.Files, - Allow: rule.Allow, + ListMode: rule.ListMode, + Files: rule.Files, + Allow: rule.Allow, } // because of bug with Viper parsing (split on dot) we use a list of struct instead of a map. diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled/dogsled.go similarity index 88% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled/dogsled.go index 79502fe8b..49108f4f1 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled/dogsled.go @@ -1,4 +1,4 @@ -package golinters +package dogsled import ( "fmt" @@ -9,20 +9,19 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const dogsledName = "dogsled" +const linterName = "dogsled" -//nolint:dupl -func NewDogsled(settings *config.DogsledSettings) *goanalysis.Linter { +func New(settings *config.DogsledSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: dogsledName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues := runDogsled(pass, settings) @@ -40,7 +39,7 @@ func NewDogsled(settings *config.DogsledSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - dogsledName, + linterName, "Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())", []*analysis.Analyzer{analyzer}, nil, @@ -101,7 +100,7 @@ func (v *returnsVisitor) Visit(node ast.Node) ast.Visitor { if numBlank > v.maxBlanks { v.issues = append(v.issues, result.Issue{ - FromLinter: dogsledName, + FromLinter: linterName, Text: fmt.Sprintf("declaration has %v blank identifiers", numBlank), Pos: v.f.Position(assgnStmt.Pos()), }) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl/dupl.go similarity index 84% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl/dupl.go index 5d772a5f2..7abcb4c4f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl/dupl.go @@ -1,4 +1,4 @@ -package golinters +package dupl import ( "fmt" @@ -10,20 +10,20 @@ import ( "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/fsutils" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const duplName = "dupl" +const linterName = "dupl" -//nolint:dupl -func NewDupl(settings *config.DuplSettings) *goanalysis.Linter { +func New(settings *config.DuplSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: duplName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runDupl(pass, settings) @@ -44,7 +44,7 @@ func NewDupl(settings *config.DuplSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - duplName, + linterName, "Tool for code clone detection", []*analysis.Analyzer{analyzer}, nil, @@ -54,7 +54,7 @@ func NewDupl(settings *config.DuplSettings) *goanalysis.Linter { } func runDupl(pass *analysis.Pass, settings *config.DuplSettings) ([]goanalysis.Issue, error) { - fileNames := getFileNames(pass) + fileNames := internal.GetFileNames(pass) issues, err := duplAPI.Run(fileNames, settings.Threshold) if err != nil { @@ -76,7 +76,7 @@ func runDupl(pass *analysis.Pass, settings *config.DuplSettings) ([]goanalysis.I dupl := fmt.Sprintf("%s:%d-%d", toFilename, i.To.LineStart(), i.To.LineEnd()) text := fmt.Sprintf("%d-%d lines are duplicate of %s", i.From.LineStart(), i.From.LineEnd(), - formatCode(dupl, nil)) + internal.FormatCode(dupl, nil)) res = append(res, goanalysis.NewIssue(&result.Issue{ Pos: token.Position{ @@ -88,7 +88,7 @@ func runDupl(pass *analysis.Pass, settings *config.DuplSettings) ([]goanalysis.I To: i.From.LineEnd(), }, Text: text, - FromLinter: duplName, + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupword.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupword/dupword.go similarity index 78% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupword.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupword/dupword.go index 6f079ffc8..bba4fc9e1 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupword.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupword/dupword.go @@ -1,4 +1,4 @@ -package golinters +package dupword import ( "strings" @@ -7,10 +7,10 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewDupWord(setting *config.DupWordSettings) *goanalysis.Linter { +func New(setting *config.DupWordSettings) *goanalysis.Linter { a := dupword.NewAnalyzer() cfgMap := map[string]map[string]any{} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck/durationcheck.go similarity index 66% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck/durationcheck.go index 880de5d42..88f22c27c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck/durationcheck.go @@ -1,13 +1,13 @@ -package golinters +package durationcheck import ( "github.com/charithe/durationcheck" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewDurationCheck() *goanalysis.Linter { +func New() *goanalysis.Linter { a := durationcheck.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goerr113.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/err113/err113.go similarity index 55% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goerr113.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/err113/err113.go index 10addc57c..2600128be 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goerr113.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/err113/err113.go @@ -1,17 +1,19 @@ -package golinters +package err113 import ( "github.com/Djarvur/go-err113" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewGoerr113() *goanalysis.Linter { +func New() *goanalysis.Linter { + a := err113.NewAnalyzer() + return goanalysis.NewLinter( - "goerr113", + a.Name, "Go linter to check the errors handling expressions", - []*analysis.Analyzer{err113.NewAnalyzer()}, + []*analysis.Analyzer{a}, nil, ).WithLoadMode(goanalysis.LoadModeTypesInfo) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck/errcheck.go similarity index 94% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck/errcheck.go index 89b18519c..9a8a2aa87 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck/errcheck.go @@ -1,4 +1,4 @@ -package golinters +package errcheck import ( "bufio" @@ -16,25 +16,26 @@ import ( "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/fsutils" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const errcheckName = "errcheck" +const linterName = "errcheck" -func NewErrcheck(settings *config.ErrcheckSettings) *goanalysis.Linter { +func New(settings *config.ErrcheckSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: errcheckName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: goanalysis.DummyRun, } return goanalysis.NewLinter( - errcheckName, + linterName, "errcheck is a program for checking for unchecked errors in Go code. "+ "These unchecked errors can be critical bugs in some cases", []*analysis.Analyzer{analyzer}, @@ -94,12 +95,12 @@ func runErrCheck(lintCtx *linter.Context, pass *analysis.Pass, checker *errcheck code = err.FuncName } - text = fmt.Sprintf("Error return value of %s is not checked", formatCode(code, lintCtx.Cfg)) + text = fmt.Sprintf("Error return value of %s is not checked", internal.FormatCode(code, lintCtx.Cfg)) } issues[i] = goanalysis.NewIssue( &result.Issue{ - FromLinter: errcheckName, + FromLinter: linterName, Text: text, Pos: err.Pos, }, @@ -253,6 +254,7 @@ func readExcludeFile(name string) ([]string, error) { if fh == nil { return nil, fmt.Errorf("failed reading exclude file: %s: %w", name, err) } + defer func() { _ = fh.Close() }() scanner := bufio.NewScanner(fh) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errchkjson.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errchkjson/errchkjson.go similarity index 59% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errchkjson.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errchkjson/errchkjson.go index 171de00a4..8389a750c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errchkjson.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errchkjson/errchkjson.go @@ -1,14 +1,14 @@ -package golinters +package errchkjson import ( "github.com/breml/errchkjson" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewErrChkJSONFuncName(cfg *config.ErrChkJSONSettings) *goanalysis.Linter { +func New(cfg *config.ErrChkJSONSettings) *goanalysis.Linter { a := errchkjson.NewAnalyzer() cfgMap := map[string]map[string]any{} @@ -23,10 +23,8 @@ func NewErrChkJSONFuncName(cfg *config.ErrChkJSONSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - "errchkjson", - "Checks types passed to the json encoding functions. "+ - "Reports unsupported types and optionally reports occasions, "+ - "where the check for the returned error can be omitted.", + a.Name, + a.Doc, []*analysis.Analyzer{a}, cfgMap, ).WithLoadMode(goanalysis.LoadModeTypesInfo) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname.go deleted file mode 100644 index 96564cfa8..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname.go +++ /dev/null @@ -1,17 +0,0 @@ -package golinters - -import ( - "github.com/Antonboom/errname/pkg/analyzer" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewErrName() *goanalysis.Linter { - return goanalysis.NewLinter( - "errname", - "Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.", - []*analysis.Analyzer{analyzer.New()}, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname/errname.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname/errname.go new file mode 100644 index 000000000..f868854c1 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname/errname.go @@ -0,0 +1,19 @@ +package errname + +import ( + "github.com/Antonboom/errname/pkg/analyzer" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := analyzer.New() + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint.go deleted file mode 100644 index cac94159d..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint.go +++ /dev/null @@ -1,32 +0,0 @@ -package golinters - -import ( - "github.com/polyfloyd/go-errorlint/errorlint" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewErrorLint(cfg *config.ErrorLintSettings) *goanalysis.Linter { - a := errorlint.NewAnalyzer() - - cfgMap := map[string]map[string]any{} - - if cfg != nil { - cfgMap[a.Name] = map[string]any{ - "errorf": cfg.Errorf, - "errorf-multi": cfg.ErrorfMulti, - "asserts": cfg.Asserts, - "comparison": cfg.Comparison, - } - } - - return goanalysis.NewLinter( - a.Name, - "errorlint is a linter for that can be used to find code "+ - "that will cause problems with the error wrapping scheme introduced in Go 1.13.", - []*analysis.Analyzer{a}, - cfgMap, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint/errorlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint/errorlint.go new file mode 100644 index 000000000..86db8552d --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errorlint/errorlint.go @@ -0,0 +1,54 @@ +package errorlint + +import ( + "github.com/polyfloyd/go-errorlint/errorlint" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(cfg *config.ErrorLintSettings) *goanalysis.Linter { + var opts []errorlint.Option + + if cfg != nil { + ae := toAllowPairs(cfg.AllowedErrors) + if len(ae) > 0 { + opts = append(opts, errorlint.WithAllowedErrors(ae)) + } + + aew := toAllowPairs(cfg.AllowedErrorsWildcard) + if len(aew) > 0 { + opts = append(opts, errorlint.WithAllowedWildcard(aew)) + } + } + + a := errorlint.NewAnalyzer(opts...) + + cfgMap := map[string]map[string]any{} + + if cfg != nil { + cfgMap[a.Name] = map[string]any{ + "errorf": cfg.Errorf, + "errorf-multi": cfg.ErrorfMulti, + "asserts": cfg.Asserts, + "comparison": cfg.Comparison, + } + } + + return goanalysis.NewLinter( + a.Name, + "errorlint is a linter for that can be used to find code "+ + "that will cause problems with the error wrapping scheme introduced in Go 1.13.", + []*analysis.Analyzer{a}, + cfgMap, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} + +func toAllowPairs(data []config.ErrorLintAllowPair) []errorlint.AllowPair { + var pairs []errorlint.AllowPair + for _, allowedError := range data { + pairs = append(pairs, errorlint.AllowPair(allowedError)) + } + return pairs +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/execinquery.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/execinquery/execinquery.go similarity index 66% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/execinquery.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/execinquery/execinquery.go index 9911d315e..3832873c6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/execinquery.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/execinquery/execinquery.go @@ -1,13 +1,13 @@ -package golinters +package execinquery import ( "github.com/lufeee/execinquery" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewExecInQuery() *goanalysis.Linter { +func New() *goanalysis.Linter { a := execinquery.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive/exhaustive.go similarity index 82% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive/exhaustive.go index 3824afa0b..9249efb69 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive/exhaustive.go @@ -1,14 +1,14 @@ -package golinters +package exhaustive import ( "github.com/nishanths/exhaustive" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewExhaustive(settings *config.ExhaustiveSettings) *goanalysis.Linter { +func New(settings *config.ExhaustiveSettings) *goanalysis.Linter { a := exhaustive.Analyzer var cfg map[string]map[string]any @@ -23,6 +23,7 @@ func NewExhaustive(settings *config.ExhaustiveSettings) *goanalysis.Linter { exhaustive.PackageScopeOnlyFlag: settings.PackageScopeOnly, exhaustive.ExplicitExhaustiveMapFlag: settings.ExplicitExhaustiveMap, exhaustive.ExplicitExhaustiveSwitchFlag: settings.ExplicitExhaustiveSwitch, + exhaustive.DefaultCaseRequiredFlag: settings.DefaultCaseRequired, }, } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustivestruct.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustivestruct.go deleted file mode 100644 index 9bc9bbfb0..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustivestruct.go +++ /dev/null @@ -1,31 +0,0 @@ -package golinters - -import ( - "strings" - - "github.com/mbilski/exhaustivestruct/pkg/analyzer" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewExhaustiveStruct(settings *config.ExhaustiveStructSettings) *goanalysis.Linter { - a := analyzer.Analyzer - - var cfg map[string]map[string]any - if settings != nil { - cfg = map[string]map[string]any{ - a.Name: { - "struct_patterns": strings.Join(settings.StructPatterns, ","), - }, - } - } - - return goanalysis.NewLinter( - a.Name, - a.Doc, - []*analysis.Analyzer{a}, - cfg, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct/exhaustruct.go similarity index 63% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct/exhaustruct.go index 5272879e1..53ad87154 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct/exhaustruct.go @@ -1,14 +1,15 @@ -package golinters +package exhaustruct import ( "github.com/GaijinEntertainment/go-exhaustruct/v3/analyzer" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" ) -func NewExhaustruct(settings *config.ExhaustructSettings) *goanalysis.Linter { +func New(settings *config.ExhaustructSettings) *goanalysis.Linter { var include, exclude []string if settings != nil { include = settings.Include @@ -17,7 +18,7 @@ func NewExhaustruct(settings *config.ExhaustructSettings) *goanalysis.Linter { a, err := analyzer.NewAnalyzer(include, exclude) if err != nil { - linterLogger.Fatalf("exhaustruct configuration: %v", err) + internal.LinterLogger.Fatalf("exhaustruct configuration: %v", err) } return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref/exportloopref.go similarity index 66% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref/exportloopref.go index 1131c575b..e232f8045 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref/exportloopref.go @@ -1,13 +1,13 @@ -package golinters +package exportloopref import ( "github.com/kyoh86/exportloopref" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewExportLoopRef() *goanalysis.Linter { +func New() *goanalysis.Linter { a := exportloopref.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/perfsprint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/fatcontext/fatcontext.go similarity index 54% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/perfsprint.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/fatcontext/fatcontext.go index fb248a85d..378025a8c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/perfsprint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/fatcontext/fatcontext.go @@ -1,13 +1,13 @@ -package golinters +package fatcontext import ( - "github.com/catenacyber/perfsprint/analyzer" + "github.com/Crocmagnon/fatcontext/pkg/analyzer" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewPerfSprint() *goanalysis.Linter { +func New() *goanalysis.Linter { a := analyzer.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo/forbidigo.go similarity index 88% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo/forbidigo.go index 6aced2922..3572b60c2 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo/forbidigo.go @@ -1,4 +1,4 @@ -package golinters +package forbidigo import ( "fmt" @@ -8,21 +8,20 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" ) -const forbidigoName = "forbidigo" +const linterName = "forbidigo" -//nolint:dupl -func NewForbidigo(settings *config.ForbidigoSettings) *goanalysis.Linter { +func New(settings *config.ForbidigoSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: forbidigoName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runForbidigo(pass, settings) @@ -45,7 +44,7 @@ func NewForbidigo(settings *config.ForbidigoSettings) *goanalysis.Linter { // But we cannot make this depend on the settings and have to mirror the mode chosen in GetAllSupportedLinterConfigs, // therefore we have to use LoadModeTypesInfo in all cases. return goanalysis.NewLinter( - forbidigoName, + linterName, "Forbids identifiers", []*analysis.Analyzer{analyzer}, nil, @@ -74,7 +73,7 @@ func runForbidigo(pass *analysis.Pass, settings *config.ForbidigoSettings) ([]go forbid, err := forbidigo.NewLinter(patterns, options...) if err != nil { - return nil, fmt.Errorf("failed to create linter %q: %w", forbidigoName, err) + return nil, fmt.Errorf("failed to create linter %q: %w", linterName, err) } var issues []goanalysis.Issue @@ -95,7 +94,7 @@ func runForbidigo(pass *analysis.Pass, settings *config.ForbidigoSettings) ([]go issues = append(issues, goanalysis.NewIssue(&result.Issue{ Pos: hint.Position(), Text: hint.Details(), - FromLinter: forbidigoName, + FromLinter: linterName, }, pass)) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert/forcetypeassert.go similarity index 68% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert/forcetypeassert.go index 873c833b5..741b57cea 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert/forcetypeassert.go @@ -1,13 +1,13 @@ -package golinters +package forcetypeassert import ( "github.com/gostaticanalysis/forcetypeassert" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewForceTypeAssert() *goanalysis.Linter { +func New() *goanalysis.Linter { a := forcetypeassert.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen/funlen.go similarity index 85% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen/funlen.go index 8def9c1f6..e43339394 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen/funlen.go @@ -1,4 +1,4 @@ -package golinters +package funlen import ( "go/token" @@ -9,20 +9,19 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const funlenName = "funlen" +const linterName = "funlen" -//nolint:dupl -func NewFunlen(settings *config.FunlenSettings) *goanalysis.Linter { +func New(settings *config.FunlenSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: funlenName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues := runFunlen(pass, settings) @@ -40,7 +39,7 @@ func NewFunlen(settings *config.FunlenSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - funlenName, + linterName, "Tool for detection of long functions", []*analysis.Analyzer{analyzer}, nil, @@ -68,7 +67,7 @@ func runFunlen(pass *analysis.Pass, settings *config.FunlenSettings) []goanalysi Line: i.Pos.Line, }, Text: strings.TrimRight(i.Message, "\n"), - FromLinter: funlenName, + FromLinter: linterName, }, pass) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci/gci.go similarity index 53% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci/gci.go index 386226769..38ed2a033 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci/gci.go @@ -1,33 +1,41 @@ -package golinters +package gci import ( "fmt" + "sort" + "strings" "sync" gcicfg "github.com/daixiang0/gci/pkg/config" "github.com/daixiang0/gci/pkg/gci" "github.com/daixiang0/gci/pkg/io" "github.com/daixiang0/gci/pkg/log" + "github.com/daixiang0/gci/pkg/section" + "github.com/golangci/modinfo" "github.com/hexops/gotextdiff" "github.com/hexops/gotextdiff/myers" "github.com/hexops/gotextdiff/span" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" ) -const gciName = "gci" +const linterName = "gci" -func NewGci(settings *config.GciSettings) *goanalysis.Linter { +func New(settings *config.GciSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: gciName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: goanalysis.DummyRun, + Requires: []*analysis.Analyzer{ + modinfo.Analyzer, + }, } var cfg *gcicfg.Config @@ -46,21 +54,27 @@ func NewGci(settings *config.GciSettings) *goanalysis.Linter { } var err error - cfg, err = rawCfg.Parse() + cfg, err = YamlConfig{origin: rawCfg}.Parse() if err != nil { - linterLogger.Fatalf("gci: configuration parsing: %v", err) + internal.LinterLogger.Fatalf("gci: configuration parsing: %v", err) } } var lock sync.Mutex return goanalysis.NewLinter( - gciName, + linterName, "Gci controls Go package import order and makes it always deterministic.", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { analyzer.Run = func(pass *analysis.Pass) (any, error) { + var err error + cfg.Sections, err = hackSectionList(pass, cfg) + if err != nil { + return nil, err + } + issues, err := runGci(pass, lintCtx, cfg, &lock) if err != nil { return nil, err @@ -82,7 +96,7 @@ func NewGci(settings *config.GciSettings) *goanalysis.Linter { } func runGci(pass *analysis.Pass, lintCtx *linter.Context, cfg *gcicfg.Config, lock *sync.Mutex) ([]goanalysis.Issue, error) { - fileNames := getFileNames(pass) + fileNames := internal.GetFileNames(pass) var diffs []string err := diffFormattedFilesToArray(fileNames, *cfg, &diffs, lock) @@ -97,7 +111,7 @@ func runGci(pass *analysis.Pass, lintCtx *linter.Context, cfg *gcicfg.Config, lo continue } - is, err := extractIssuesFromPatch(diff, lintCtx, gciName) + is, err := internal.ExtractIssuesFromPatch(diff, lintCtx, linterName, getIssuedTextGci) if err != nil { return nil, fmt.Errorf("can't extract issues from gci diff output %s: %w", diff, err) } @@ -110,6 +124,57 @@ func runGci(pass *analysis.Pass, lintCtx *linter.Context, cfg *gcicfg.Config, lo return issues, nil } +func getIssuedTextGci(settings *config.LintersSettings) string { + text := "File is not `gci`-ed" + + hasOptions := settings.Gci.SkipGenerated || len(settings.Gci.Sections) > 0 + if !hasOptions { + return text + } + + text += " with" + + if settings.Gci.SkipGenerated { + text += " --skip-generated" + } + + if len(settings.Gci.Sections) > 0 { + for _, sect := range settings.Gci.Sections { + text += " -s " + sect + } + } + + if settings.Gci.CustomOrder { + text += " --custom-order" + } + + return text +} + +func hackSectionList(pass *analysis.Pass, cfg *gcicfg.Config) (section.SectionList, error) { + var sections section.SectionList + + for _, sect := range cfg.Sections { + // local module hack + if v, ok := sect.(*section.LocalModule); ok { + info, err := modinfo.FindModuleFromPass(pass) + if err != nil { + return nil, err + } + + if info.Path == "" { + continue + } + + v.Path = info.Path + } + + sections = append(sections, sect) + } + + return sections, nil +} + // diffFormattedFilesToArray is a copy of gci.DiffFormattedFilesToArray without io.StdInGenerator. // gci.DiffFormattedFilesToArray uses gci.processStdInAndGoFilesInPaths that uses io.StdInGenerator but stdin is not active on CI. // https://github.com/daixiang0/gci/blob/6f5cb16718ba07f0342a58de9b830ec5a6d58790/pkg/gci/gci.go#L63-L75 @@ -129,29 +194,55 @@ func diffFormattedFilesToArray(paths []string, cfg gcicfg.Config, diffs *[]strin }) } -func getErrorTextForGci(settings config.GciSettings) string { - text := "File is not `gci`-ed" +// Code below this comment is borrowed and modified from gci. +// https://github.com/daixiang0/gci/blob/4725b0c101801e7449530eee2ddb0c72592e3405/pkg/config/config.go + +var defaultOrder = map[string]int{ + section.StandardType: 0, + section.DefaultType: 1, + section.CustomType: 2, + section.BlankType: 3, + section.DotType: 4, + section.AliasType: 5, + section.LocalModuleType: 6, +} - hasOptions := settings.SkipGenerated || len(settings.Sections) > 0 - if !hasOptions { - return text - } +type YamlConfig struct { + origin gcicfg.YamlConfig +} - text += " with" +//nolint:gocritic // code borrowed from gci and modified to fix LocalModule section behavior. +func (g YamlConfig) Parse() (*gcicfg.Config, error) { + var err error - if settings.SkipGenerated { - text += " --skip-generated" + sections, err := section.Parse(g.origin.SectionStrings) + if err != nil { + return nil, err } - if len(settings.Sections) > 0 { - for _, section := range settings.Sections { - text += " -s " + section - } + if sections == nil { + sections = section.DefaultSections() } - if settings.CustomOrder { - text += " --custom-order" + // if default order sorted sections + if !g.origin.Cfg.CustomOrder { + sort.Slice(sections, func(i, j int) bool { + sectionI, sectionJ := sections[i].Type(), sections[j].Type() + + if strings.Compare(sectionI, sectionJ) == 0 { + return strings.Compare(sections[i].String(), sections[j].String()) < 0 + } + return defaultOrder[sectionI] < defaultOrder[sectionJ] + }) } - return text + sectionSeparators, err := section.Parse(g.origin.SectionSeparatorStrings) + if err != nil { + return nil, err + } + if sectionSeparators == nil { + sectionSeparators = section.DefaultSectionSeparators() + } + + return &gcicfg.Config{BoolConfig: g.origin.Cfg, Sections: sections, SectionSeparators: sectionSeparators}, nil } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter.go deleted file mode 100644 index 8919de15b..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter.go +++ /dev/null @@ -1,34 +0,0 @@ -package golinters - -import ( - "github.com/nunnatsa/ginkgolinter" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewGinkgoLinter(cfg *config.GinkgoLinterSettings) *goanalysis.Linter { - a := ginkgolinter.NewAnalyzer() - - cfgMap := make(map[string]map[string]any) - if cfg != nil { - cfgMap[a.Name] = map[string]any{ - "suppress-len-assertion": cfg.SuppressLenAssertion, - "suppress-nil-assertion": cfg.SuppressNilAssertion, - "suppress-err-assertion": cfg.SuppressErrAssertion, - "suppress-compare-assertion": cfg.SuppressCompareAssertion, - "suppress-async-assertion": cfg.SuppressAsyncAssertion, - "suppress-type-compare-assertion": cfg.SuppressTypeCompareWarning, - "forbid-focus-container": cfg.ForbidFocusContainer, - "allow-havelen-0": cfg.AllowHaveLenZero, - } - } - - return goanalysis.NewLinter( - a.Name, - "enforces standards of using ginkgo and gomega", - []*analysis.Analyzer{a}, - cfgMap, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter/ginkgolinter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter/ginkgolinter.go new file mode 100644 index 000000000..54d207257 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter/ginkgolinter.go @@ -0,0 +1,39 @@ +package ginkgolinter + +import ( + "github.com/nunnatsa/ginkgolinter" + "github.com/nunnatsa/ginkgolinter/types" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.GinkgoLinterSettings) *goanalysis.Linter { + cfg := &types.Config{} + + if settings != nil { + cfg = &types.Config{ + SuppressLen: types.Boolean(settings.SuppressLenAssertion), + SuppressNil: types.Boolean(settings.SuppressNilAssertion), + SuppressErr: types.Boolean(settings.SuppressErrAssertion), + SuppressCompare: types.Boolean(settings.SuppressCompareAssertion), + SuppressAsync: types.Boolean(settings.SuppressAsyncAssertion), + ForbidFocus: types.Boolean(settings.ForbidFocusContainer), + SuppressTypeCompare: types.Boolean(settings.SuppressTypeCompareWarning), + AllowHaveLen0: types.Boolean(settings.AllowHaveLenZero), + ForceExpectTo: types.Boolean(settings.ForceExpectTo), + ValidateAsyncIntervals: types.Boolean(settings.ForbidSpecPollution), + ForbidSpecPollution: types.Boolean(settings.ValidateAsyncIntervals), + } + } + + a := ginkgolinter.NewAnalyzerWithConfig(cfg) + + return goanalysis.NewLinter( + a.Name, + "enforces standards of using ginkgo and gomega", + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/adapters.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/adapters.go deleted file mode 100644 index 284215dfc..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/adapters.go +++ /dev/null @@ -1,41 +0,0 @@ -package goanalysis - -import ( - "go/types" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/loader" //nolint:staticcheck // it's an adapter for golang.org/x/tools/go/packages -) - -func MakeFakeLoaderProgram(pass *analysis.Pass) *loader.Program { - var info types.Info - if pass.TypesInfo != nil { - info = *pass.TypesInfo - } - - prog := &loader.Program{ - Fset: pass.Fset, - Created: []*loader.PackageInfo{ - { - Pkg: pass.Pkg, - Importable: true, // not used - TransitivelyErrorFree: true, // TODO ??? - - Files: pass.Files, - Errors: nil, - Info: info, - }, - }, - AllPackages: map[*types.Package]*loader.PackageInfo{ - pass.Pkg: { - Pkg: pass.Pkg, - Importable: true, - TransitivelyErrorFree: true, - Files: pass.Files, - Errors: nil, - Info: info, - }, - }, - } - return prog -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives/gocheckcompilerdirectives.go similarity index 67% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives/gocheckcompilerdirectives.go index 2592c8994..be604d805 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives/gocheckcompilerdirectives.go @@ -1,13 +1,13 @@ -package golinters +package gocheckcompilerdirectives import ( "4d63.com/gocheckcompilerdirectives/checkcompilerdirectives" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewGoCheckCompilerDirectives() *goanalysis.Linter { +func New() *goanalysis.Linter { a := checkcompilerdirectives.Analyzer() return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals.go deleted file mode 100644 index 6e18aeb27..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals.go +++ /dev/null @@ -1,29 +0,0 @@ -package golinters - -import ( - "4d63.com/gochecknoglobals/checknoglobals" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewGochecknoglobals() *goanalysis.Linter { - gochecknoglobals := checknoglobals.Analyzer() - - // gochecknoglobals only lints test files if the `-t` flag is passed, so we - // pass the `t` flag as true to the analyzer before running it. This can be - // turned off by using the regular golangci-lint flags such as `--tests` or - // `--skip-files`. - linterConfig := map[string]map[string]any{ - gochecknoglobals.Name: { - "t": true, - }, - } - - return goanalysis.NewLinter( - gochecknoglobals.Name, - gochecknoglobals.Doc, - []*analysis.Analyzer{gochecknoglobals}, - linterConfig, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals/gochecknoglobals.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals/gochecknoglobals.go new file mode 100644 index 000000000..af22b2f8e --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals/gochecknoglobals.go @@ -0,0 +1,26 @@ +package gochecknoglobals + +import ( + "4d63.com/gochecknoglobals/checknoglobals" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := checknoglobals.Analyzer() + + // gochecknoglobals only lints test files if the `-t` flag is passed, + // so we pass the `t` flag as true to the analyzer before running it. + // This can be turned off by using the regular golangci-lint flags such as `--tests` or `--exclude-files`. + linterConfig := map[string]map[string]any{ + a.Name: {"t": true}, + } + + return goanalysis.NewLinter( + a.Name, + "Check that no global variables exist.", + []*analysis.Analyzer{a}, + linterConfig, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits/gochecknoinits.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits/gochecknoinits.go index a51b531b9..1345eb8c2 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits/gochecknoinits.go @@ -1,4 +1,4 @@ -package golinters +package gochecknoinits import ( "fmt" @@ -8,19 +8,20 @@ import ( "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const gochecknoinitsName = "gochecknoinits" +const linterName = "gochecknoinits" -func NewGochecknoinits() *goanalysis.Linter { +func New() *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: gochecknoinitsName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { var res []goanalysis.Issue @@ -43,7 +44,7 @@ func NewGochecknoinits() *goanalysis.Linter { } return goanalysis.NewLinter( - gochecknoinitsName, + linterName, "Checks that no init functions are present in Go code", []*analysis.Analyzer{analyzer}, nil, @@ -60,12 +61,12 @@ func checkFileForInits(f *ast.File, fset *token.FileSet) []result.Issue { continue } - name := funcDecl.Name.Name - if name == "init" && funcDecl.Recv.NumFields() == 0 { + fnName := funcDecl.Name.Name + if fnName == "init" && funcDecl.Recv.NumFields() == 0 { res = append(res, result.Issue{ Pos: fset.Position(funcDecl.Pos()), - Text: fmt.Sprintf("don't use %s function", formatCode(name, nil)), - FromLinter: gochecknoinitsName, + Text: fmt.Sprintf("don't use %s function", internal.FormatCode(fnName, nil)), + FromLinter: linterName, }) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype/gochecksumtype.go similarity index 82% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype/gochecksumtype.go index fcc0cad58..446f0e564 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype/gochecksumtype.go @@ -1,4 +1,4 @@ -package golinters +package gochecksumtype import ( "strings" @@ -8,19 +8,19 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/packages" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const goCheckSumTypeName = "gochecksumtype" +const linterName = "gochecksumtype" -func NewGoCheckSumType() *goanalysis.Linter { +func New() *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: goCheckSumTypeName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runGoCheckSumType(pass) @@ -41,11 +41,11 @@ func NewGoCheckSumType() *goanalysis.Linter { } return goanalysis.NewLinter( - goCheckSumTypeName, + linterName, `Run exhaustiveness checks on Go "sum types"`, []*analysis.Analyzer{analyzer}, nil, - ).WithIssuesReporter(func(ctx *linter.Context) []goanalysis.Issue { + ).WithIssuesReporter(func(_ *linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeTypesInfo) } @@ -70,7 +70,7 @@ func runGoCheckSumType(pass *analysis.Pass) ([]goanalysis.Issue, error) { } resIssues = append(resIssues, goanalysis.NewIssue(&result.Issue{ - FromLinter: goCheckSumTypeName, + FromLinter: linterName, Text: strings.TrimPrefix(err.Error(), err.Pos().String()+": "), Pos: err.Pos(), }, pass)) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit/gocognit.go similarity index 82% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit/gocognit.go index 406d34ed6..5fe0f90f0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit/gocognit.go @@ -1,4 +1,4 @@ -package golinters +package gocognit import ( "fmt" @@ -9,15 +9,15 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const gocognitName = "gocognit" +const linterName = "gocognit" -//nolint:dupl -func NewGocognit(settings *config.GocognitSettings) *goanalysis.Linter { +func New(settings *config.GocognitSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -40,7 +40,7 @@ func NewGocognit(settings *config.GocognitSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - gocognitName, + linterName, "Computes and checks the cognitive complexity of functions", []*analysis.Analyzer{analyzer}, nil, @@ -71,8 +71,8 @@ func runGocognit(pass *analysis.Pass, settings *config.GocognitSettings) []goana issues = append(issues, goanalysis.NewIssue(&result.Issue{ Pos: s.Pos, Text: fmt.Sprintf("cognitive complexity %d of func %s is high (> %d)", - s.Complexity, formatCode(s.FuncName, nil), settings.MinComplexity), - FromLinter: gocognitName, + s.Complexity, internal.FormatCode(s.FuncName, nil), settings.MinComplexity), + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst/goconst.go similarity index 80% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst/goconst.go index e277509d2..07bed301f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst/goconst.go @@ -1,4 +1,4 @@ -package golinters +package goconst import ( "fmt" @@ -8,20 +8,20 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const goconstName = "goconst" +const linterName = "goconst" -//nolint:dupl -func NewGoconst(settings *config.GoConstSettings) *goanalysis.Linter { +func New(settings *config.GoConstSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: goconstName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runGoconst(pass, settings) @@ -42,7 +42,7 @@ func NewGoconst(settings *config.GoConstSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - goconstName, + linterName, "Finds repeated strings that could be replaced by a constant", []*analysis.Analyzer{analyzer}, nil, @@ -53,6 +53,7 @@ func NewGoconst(settings *config.GoConstSettings) *goanalysis.Linter { func runGoconst(pass *analysis.Pass, settings *config.GoConstSettings) ([]goanalysis.Issue, error) { cfg := goconstAPI.Config{ + IgnoreStrings: settings.IgnoreStrings, IgnoreTests: settings.IgnoreTests, MatchWithConstants: settings.MatchWithConstants, MinStringLength: settings.MinStringLen, @@ -78,18 +79,18 @@ func runGoconst(pass *analysis.Pass, settings *config.GoConstSettings) ([]goanal res := make([]goanalysis.Issue, 0, len(lintIssues)) for _, i := range lintIssues { - text := fmt.Sprintf("string %s has %d occurrences", formatCode(i.Str, nil), i.OccurrencesCount) + text := fmt.Sprintf("string %s has %d occurrences", internal.FormatCode(i.Str, nil), i.OccurrencesCount) if i.MatchingConst == "" { text += ", make it a constant" } else { - text += fmt.Sprintf(", but such constant %s already exists", formatCode(i.MatchingConst, nil)) + text += fmt.Sprintf(", but such constant %s already exists", internal.FormatCode(i.MatchingConst, nil)) } res = append(res, goanalysis.NewIssue(&result.Issue{ Pos: i.Pos, Text: text, - FromLinter: goconstName, + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go deleted file mode 100644 index 1319c72d9..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go +++ /dev/null @@ -1,641 +0,0 @@ -package golinters - -import ( - "errors" - "fmt" - "go/ast" - "go/types" - "path/filepath" - "reflect" - "runtime" - "sort" - "strings" - "sync" - - "github.com/go-critic/go-critic/checkers" - gocriticlinter "github.com/go-critic/go-critic/linter" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/logutils" - "github.com/golangci/golangci-lint/pkg/result" -) - -const goCriticName = "gocritic" - -var ( - goCriticDebugf = logutils.Debug(logutils.DebugKeyGoCritic) - isGoCriticDebug = logutils.HaveDebugTag(logutils.DebugKeyGoCritic) -) - -func NewGoCritic(settings *config.GoCriticSettings, cfg *config.Config) *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - wrapper := &goCriticWrapper{ - cfg: cfg, - sizes: types.SizesFor("gc", runtime.GOARCH), - } - - analyzer := &analysis.Analyzer{ - Name: goCriticName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues, err := wrapper.run(pass) - if err != nil { - return nil, err - } - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - goCriticName, - `Provides diagnostics that check for bugs, performance and style issues. -Extensible without recompilation through dynamic rules. -Dynamic rules are written declaratively with AST patterns, filters, report message and optional suggestion.`, - []*analysis.Analyzer{analyzer}, - nil, - ). - WithContextSetter(func(context *linter.Context) { - wrapper.init(settings, context.Log) - }). - WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) -} - -type goCriticWrapper struct { - settingsWrapper *goCriticSettingsWrapper - cfg *config.Config - sizes types.Sizes - once sync.Once -} - -func (w *goCriticWrapper) init(settings *config.GoCriticSettings, logger logutils.Log) { - if settings == nil { - return - } - - w.once.Do(func() { - err := checkers.InitEmbeddedRules() - if err != nil { - logger.Fatalf("%s: %v: setting an explicit GOROOT can fix this problem.", goCriticName, err) - } - }) - - settingsWrapper := newGoCriticSettingsWrapper(settings, logger) - - settingsWrapper.inferEnabledChecks() - - if err := settingsWrapper.validate(); err != nil { - logger.Fatalf("%s: invalid settings: %s", goCriticName, err) - } - - w.settingsWrapper = settingsWrapper -} - -func (w *goCriticWrapper) run(pass *analysis.Pass) ([]goanalysis.Issue, error) { - if w.settingsWrapper == nil { - return nil, fmt.Errorf("the settings wrapper is nil") - } - - linterCtx := gocriticlinter.NewContext(pass.Fset, w.sizes) - - linterCtx.SetGoVersion(w.settingsWrapper.Go) - - enabledCheckers, err := w.buildEnabledCheckers(linterCtx) - if err != nil { - return nil, err - } - - linterCtx.SetPackageInfo(pass.TypesInfo, pass.Pkg) - - pkgIssues := runGocriticOnPackage(linterCtx, enabledCheckers, pass.Files) - - issues := make([]goanalysis.Issue, 0, len(pkgIssues)) - for i := range pkgIssues { - issues = append(issues, goanalysis.NewIssue(&pkgIssues[i], pass)) - } - - return issues, nil -} - -func (w *goCriticWrapper) buildEnabledCheckers(linterCtx *gocriticlinter.Context) ([]*gocriticlinter.Checker, error) { - allParams := w.settingsWrapper.getLowerCasedParams() - - var enabledCheckers []*gocriticlinter.Checker - for _, info := range gocriticlinter.GetCheckersInfo() { - if !w.settingsWrapper.isCheckEnabled(info.Name) { - continue - } - - if err := w.configureCheckerInfo(info, allParams); err != nil { - return nil, err - } - - c, err := gocriticlinter.NewChecker(linterCtx, info) - if err != nil { - return nil, err - } - enabledCheckers = append(enabledCheckers, c) - } - - return enabledCheckers, nil -} - -func runGocriticOnPackage(linterCtx *gocriticlinter.Context, checks []*gocriticlinter.Checker, - files []*ast.File) []result.Issue { - var res []result.Issue - for _, f := range files { - filename := filepath.Base(linterCtx.FileSet.Position(f.Pos()).Filename) - linterCtx.SetFileInfo(filename, f) - - issues := runGocriticOnFile(linterCtx, f, checks) - res = append(res, issues...) - } - return res -} - -func runGocriticOnFile(linterCtx *gocriticlinter.Context, f *ast.File, checks []*gocriticlinter.Checker) []result.Issue { - var res []result.Issue - - for _, c := range checks { - // All checkers are expected to use *lint.Context - // as read-only structure, so no copying is required. - for _, warn := range c.Check(f) { - pos := linterCtx.FileSet.Position(warn.Pos) - issue := result.Issue{ - Pos: pos, - Text: fmt.Sprintf("%s: %s", c.Info.Name, warn.Text), - FromLinter: goCriticName, - } - - if warn.HasQuickFix() { - issue.Replacement = &result.Replacement{ - Inline: &result.InlineFix{ - StartCol: pos.Column - 1, - Length: int(warn.Suggestion.To - warn.Suggestion.From), - NewString: string(warn.Suggestion.Replacement), - }, - } - } - - res = append(res, issue) - } - } - - return res -} - -func (w *goCriticWrapper) configureCheckerInfo(info *gocriticlinter.CheckerInfo, allParams map[string]config.GoCriticCheckSettings) error { - params := allParams[strings.ToLower(info.Name)] - if params == nil { // no config for this checker - return nil - } - - infoParams := normalizeCheckerInfoParams(info) - for k, p := range params { - v, ok := infoParams[k] - if ok { - v.Value = w.normalizeCheckerParamsValue(p) - continue - } - - // param `k` isn't supported - if len(info.Params) == 0 { - return fmt.Errorf("checker %s config param %s doesn't exist: checker doesn't have params", - info.Name, k) - } - - var supportedKeys []string - for sk := range info.Params { - supportedKeys = append(supportedKeys, sk) - } - sort.Strings(supportedKeys) - - return fmt.Errorf("checker %s config param %s doesn't exist, all existing: %s", - info.Name, k, supportedKeys) - } - - return nil -} - -func normalizeCheckerInfoParams(info *gocriticlinter.CheckerInfo) gocriticlinter.CheckerParams { - // lowercase info param keys here because golangci-lint's config parser lowercases all strings - ret := gocriticlinter.CheckerParams{} - for k, v := range info.Params { - ret[strings.ToLower(k)] = v - } - - return ret -} - -// normalizeCheckerParamsValue normalizes value types. -// go-critic asserts that CheckerParam.Value has some specific types, -// but the file parsers (TOML, YAML, JSON) don't create the same representation for raw type. -// then we have to convert value types into the expected value types. -// Maybe in the future, this kind of conversion will be done in go-critic itself. -func (w *goCriticWrapper) normalizeCheckerParamsValue(p any) any { - rv := reflect.ValueOf(p) - switch rv.Type().Kind() { - case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: - return int(rv.Int()) - case reflect.Bool: - return rv.Bool() - case reflect.String: - // Perform variable substitution. - return strings.ReplaceAll(rv.String(), "${configDir}", w.cfg.GetConfigDir()) - default: - return p - } -} - -// TODO(ldez): rewrite and simplify goCriticSettingsWrapper. - -type goCriticSettingsWrapper struct { - *config.GoCriticSettings - - logger logutils.Log - - allCheckers []*gocriticlinter.CheckerInfo - allCheckerMap map[string]*gocriticlinter.CheckerInfo - - inferredEnabledChecks map[string]bool -} - -func newGoCriticSettingsWrapper(settings *config.GoCriticSettings, logger logutils.Log) *goCriticSettingsWrapper { - allCheckers := gocriticlinter.GetCheckersInfo() - - allCheckerMap := make(map[string]*gocriticlinter.CheckerInfo) - for _, checkInfo := range allCheckers { - allCheckerMap[checkInfo.Name] = checkInfo - } - - return &goCriticSettingsWrapper{ - GoCriticSettings: settings, - logger: logger, - allCheckers: allCheckers, - allCheckerMap: allCheckerMap, - inferredEnabledChecks: map[string]bool{}, - } -} - -func (s *goCriticSettingsWrapper) buildTagToCheckersMap() map[string][]string { - tagToCheckers := map[string][]string{} - - for _, checker := range s.allCheckers { - for _, tag := range checker.Tags { - tagToCheckers[tag] = append(tagToCheckers[tag], checker.Name) - } - } - - return tagToCheckers -} - -func (s *goCriticSettingsWrapper) checkerTagsDebugf() { - if !isGoCriticDebug { - return - } - - tagToCheckers := s.buildTagToCheckersMap() - - allTags := make([]string, 0, len(tagToCheckers)) - for tag := range tagToCheckers { - allTags = append(allTags, tag) - } - - sort.Strings(allTags) - - goCriticDebugf("All gocritic existing tags and checks:") - for _, tag := range allTags { - debugChecksListf(tagToCheckers[tag], " tag %q", tag) - } -} - -func (s *goCriticSettingsWrapper) disabledCheckersDebugf() { - if !isGoCriticDebug { - return - } - - var disabledCheckers []string - for _, checker := range s.allCheckers { - if s.inferredEnabledChecks[strings.ToLower(checker.Name)] { - continue - } - - disabledCheckers = append(disabledCheckers, checker.Name) - } - - if len(disabledCheckers) == 0 { - goCriticDebugf("All checks are enabled") - } else { - debugChecksListf(disabledCheckers, "Final not used") - } -} - -func (s *goCriticSettingsWrapper) inferEnabledChecks() { - s.checkerTagsDebugf() - - enabledByDefaultChecks := s.getDefaultEnabledCheckersNames() - debugChecksListf(enabledByDefaultChecks, "Enabled by default") - - disabledByDefaultChecks := s.getDefaultDisabledCheckersNames() - debugChecksListf(disabledByDefaultChecks, "Disabled by default") - - enabledChecks := make([]string, 0, len(s.EnabledTags)+len(enabledByDefaultChecks)) - - // EnabledTags - if len(s.EnabledTags) != 0 { - tagToCheckers := s.buildTagToCheckersMap() - for _, tag := range s.EnabledTags { - enabledChecks = append(enabledChecks, tagToCheckers[tag]...) - } - - debugChecksListf(enabledChecks, "Enabled by config tags %s", sprintStrings(s.EnabledTags)) - } - - if !(len(s.EnabledTags) == 0 && len(s.EnabledChecks) != 0) { - // don't use default checks only if we have no enabled tags and enable some checks manually - enabledChecks = append(enabledChecks, enabledByDefaultChecks...) - } - - // DisabledTags - if len(s.DisabledTags) != 0 { - enabledChecks = s.filterByDisableTags(enabledChecks, s.DisabledTags) - } - - // EnabledChecks - if len(s.EnabledChecks) != 0 { - debugChecksListf(s.EnabledChecks, "Enabled by config") - - alreadyEnabledChecksSet := stringsSliceToSet(enabledChecks) - for _, enabledCheck := range s.EnabledChecks { - if alreadyEnabledChecksSet[enabledCheck] { - s.logger.Warnf("%s: no need to enable check %q: it's already enabled", goCriticName, enabledCheck) - continue - } - enabledChecks = append(enabledChecks, enabledCheck) - } - } - - // DisabledChecks - if len(s.DisabledChecks) != 0 { - debugChecksListf(s.DisabledChecks, "Disabled by config") - - enabledChecksSet := stringsSliceToSet(enabledChecks) - for _, disabledCheck := range s.DisabledChecks { - if !enabledChecksSet[disabledCheck] { - s.logger.Warnf("%s: check %q was explicitly disabled via config. However, as this check "+ - "is disabled by default, there is no need to explicitly disable it via config.", goCriticName, disabledCheck) - continue - } - delete(enabledChecksSet, disabledCheck) - } - - enabledChecks = nil - for enabledCheck := range enabledChecksSet { - enabledChecks = append(enabledChecks, enabledCheck) - } - } - - s.inferredEnabledChecks = map[string]bool{} - for _, check := range enabledChecks { - s.inferredEnabledChecks[strings.ToLower(check)] = true - } - - debugChecksListf(enabledChecks, "Final used") - - s.disabledCheckersDebugf() -} - -func (s *goCriticSettingsWrapper) validate() error { - if len(s.EnabledTags) == 0 { - if len(s.EnabledChecks) != 0 && len(s.DisabledChecks) != 0 { - return errors.New("both enabled and disabled check aren't allowed for gocritic") - } - } else { - if err := validateStringsUniq(s.EnabledTags); err != nil { - return fmt.Errorf("validate enabled tags: %w", err) - } - - tagToCheckers := s.buildTagToCheckersMap() - - for _, tag := range s.EnabledTags { - if _, ok := tagToCheckers[tag]; !ok { - return fmt.Errorf("gocritic [enabled]tag %q doesn't exist", tag) - } - } - } - - if len(s.DisabledTags) > 0 { - tagToCheckers := s.buildTagToCheckersMap() - for _, tag := range s.EnabledTags { - if _, ok := tagToCheckers[tag]; !ok { - return fmt.Errorf("gocritic [disabled]tag %q doesn't exist", tag) - } - } - } - - if err := validateStringsUniq(s.EnabledChecks); err != nil { - return fmt.Errorf("validate enabled checks: %w", err) - } - - if err := validateStringsUniq(s.DisabledChecks); err != nil { - return fmt.Errorf("validate disabled checks: %w", err) - } - - if err := s.validateCheckerNames(); err != nil { - return fmt.Errorf("validation failed: %w", err) - } - - return nil -} - -func (s *goCriticSettingsWrapper) isCheckEnabled(name string) bool { - return s.inferredEnabledChecks[strings.ToLower(name)] -} - -// getAllCheckerNames returns a map containing all checker names supported by gocritic. -func (s *goCriticSettingsWrapper) getAllCheckerNames() map[string]bool { - allCheckerNames := make(map[string]bool, len(s.allCheckers)) - - for _, checker := range s.allCheckers { - allCheckerNames[strings.ToLower(checker.Name)] = true - } - - return allCheckerNames -} - -func (s *goCriticSettingsWrapper) getDefaultEnabledCheckersNames() []string { - var enabled []string - - for _, info := range s.allCheckers { - enable := s.isEnabledByDefaultCheck(info) - if enable { - enabled = append(enabled, info.Name) - } - } - - return enabled -} - -func (s *goCriticSettingsWrapper) getDefaultDisabledCheckersNames() []string { - var disabled []string - - for _, info := range s.allCheckers { - enable := s.isEnabledByDefaultCheck(info) - if !enable { - disabled = append(disabled, info.Name) - } - } - - return disabled -} - -func (s *goCriticSettingsWrapper) validateCheckerNames() error { - allowedNames := s.getAllCheckerNames() - - for _, name := range s.EnabledChecks { - if !allowedNames[strings.ToLower(name)] { - return fmt.Errorf("enabled checker %s doesn't exist, all existing checkers: %s", - name, sprintAllowedCheckerNames(allowedNames)) - } - } - - for _, name := range s.DisabledChecks { - if !allowedNames[strings.ToLower(name)] { - return fmt.Errorf("disabled checker %s doesn't exist, all existing checkers: %s", - name, sprintAllowedCheckerNames(allowedNames)) - } - } - - for checkName := range s.SettingsPerCheck { - if _, ok := allowedNames[checkName]; !ok { - return fmt.Errorf("invalid setting, checker %s doesn't exist, all existing checkers: %s", - checkName, sprintAllowedCheckerNames(allowedNames)) - } - - if !s.isCheckEnabled(checkName) { - s.logger.Warnf("%s: settings were provided for not enabled check %q", goCriticName, checkName) - } - } - - return nil -} - -func (s *goCriticSettingsWrapper) getLowerCasedParams() map[string]config.GoCriticCheckSettings { - ret := make(map[string]config.GoCriticCheckSettings, len(s.SettingsPerCheck)) - - for checker, params := range s.SettingsPerCheck { - ret[strings.ToLower(checker)] = params - } - - return ret -} - -func (s *goCriticSettingsWrapper) filterByDisableTags(enabledChecks, disableTags []string) []string { - enabledChecksSet := stringsSliceToSet(enabledChecks) - - for _, enabledCheck := range enabledChecks { - checkInfo, checkInfoExists := s.allCheckerMap[enabledCheck] - if !checkInfoExists { - s.logger.Warnf("%s: check %q was not exists via filtering disabled tags", goCriticName, enabledCheck) - continue - } - - hitTags := intersectStringSlice(checkInfo.Tags, disableTags) - if len(hitTags) != 0 { - delete(enabledChecksSet, enabledCheck) - } - } - - debugChecksListf(enabledChecks, "Disabled by config tags %s", sprintStrings(disableTags)) - - enabledChecks = nil - for enabledCheck := range enabledChecksSet { - enabledChecks = append(enabledChecks, enabledCheck) - } - - return enabledChecks -} - -func (s *goCriticSettingsWrapper) isEnabledByDefaultCheck(info *gocriticlinter.CheckerInfo) bool { - return !info.HasTag("experimental") && - !info.HasTag("opinionated") && - !info.HasTag("performance") -} - -func validateStringsUniq(ss []string) error { - set := map[string]bool{} - - for _, s := range ss { - _, ok := set[s] - if ok { - return fmt.Errorf("%q occurs multiple times in list", s) - } - set[s] = true - } - - return nil -} - -func intersectStringSlice(s1, s2 []string) []string { - s1Map := make(map[string]struct{}, len(s1)) - - for _, s := range s1 { - s1Map[s] = struct{}{} - } - - results := make([]string, 0) - for _, s := range s2 { - if _, exists := s1Map[s]; exists { - results = append(results, s) - } - } - - return results -} - -func sprintAllowedCheckerNames(allowedNames map[string]bool) string { - namesSlice := make([]string, 0, len(allowedNames)) - - for name := range allowedNames { - namesSlice = append(namesSlice, name) - } - - return sprintStrings(namesSlice) -} - -func sprintStrings(ss []string) string { - sort.Strings(ss) - return fmt.Sprint(ss) -} - -func debugChecksListf(checks []string, format string, args ...any) { - if !isGoCriticDebug { - return - } - - goCriticDebugf("%s checks (%d): %s", fmt.Sprintf(format, args...), len(checks), sprintStrings(checks)) -} - -func stringsSliceToSet(ss []string) map[string]bool { - ret := make(map[string]bool, len(ss)) - for _, s := range ss { - ret[s] = true - } - - return ret -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic/gocritic.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic/gocritic.go new file mode 100644 index 000000000..68cc338e4 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic/gocritic.go @@ -0,0 +1,590 @@ +package gocritic + +import ( + "errors" + "fmt" + "go/ast" + "go/types" + "path/filepath" + "reflect" + "runtime" + "sort" + "strings" + "sync" + + "github.com/go-critic/go-critic/checkers" + gocriticlinter "github.com/go-critic/go-critic/linter" + _ "github.com/quasilyte/go-ruleguard/dsl" + "golang.org/x/exp/maps" + "golang.org/x/exp/slices" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/logutils" + "github.com/golangci/golangci-lint/pkg/result" +) + +const linterName = "gocritic" + +var ( + debugf = logutils.Debug(logutils.DebugKeyGoCritic) + isDebug = logutils.HaveDebugTag(logutils.DebugKeyGoCritic) +) + +func New(settings *config.GoCriticSettings) *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue + + wrapper := &goCriticWrapper{ + sizes: types.SizesFor("gc", runtime.GOARCH), + } + + analyzer := &analysis.Analyzer{ + Name: linterName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (any, error) { + issues, err := wrapper.run(pass) + if err != nil { + return nil, err + } + + if len(issues) == 0 { + return nil, nil + } + + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() + + return nil, nil + }, + } + + return goanalysis.NewLinter( + linterName, + `Provides diagnostics that check for bugs, performance and style issues. +Extensible without recompilation through dynamic rules. +Dynamic rules are written declaratively with AST patterns, filters, report message and optional suggestion.`, + []*analysis.Analyzer{analyzer}, + nil, + ). + WithContextSetter(func(context *linter.Context) { + wrapper.configDir = context.Cfg.GetConfigDir() + + wrapper.init(context.Log, settings) + }). + WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }). + WithLoadMode(goanalysis.LoadModeTypesInfo) +} + +type goCriticWrapper struct { + settingsWrapper *settingsWrapper + configDir string + sizes types.Sizes + once sync.Once +} + +func (w *goCriticWrapper) init(logger logutils.Log, settings *config.GoCriticSettings) { + if settings == nil { + return + } + + w.once.Do(func() { + err := checkers.InitEmbeddedRules() + if err != nil { + logger.Fatalf("%s: %v: setting an explicit GOROOT can fix this problem", linterName, err) + } + }) + + settingsWrapper := newSettingsWrapper(settings, logger) + settingsWrapper.InferEnabledChecks() + // Validate must be after InferEnabledChecks, not before. + // Because it uses gathered information about tags set and finally enabled checks. + if err := settingsWrapper.Validate(); err != nil { + logger.Fatalf("%s: invalid settings: %s", linterName, err) + } + + w.settingsWrapper = settingsWrapper +} + +func (w *goCriticWrapper) run(pass *analysis.Pass) ([]goanalysis.Issue, error) { + if w.settingsWrapper == nil { + return nil, errors.New("the settings wrapper is nil") + } + + linterCtx := gocriticlinter.NewContext(pass.Fset, w.sizes) + + linterCtx.SetGoVersion(w.settingsWrapper.Go) + + enabledCheckers, err := w.buildEnabledCheckers(linterCtx) + if err != nil { + return nil, err + } + + linterCtx.SetPackageInfo(pass.TypesInfo, pass.Pkg) + + pkgIssues := runOnPackage(linterCtx, enabledCheckers, pass.Files) + + issues := make([]goanalysis.Issue, 0, len(pkgIssues)) + for i := range pkgIssues { + issues = append(issues, goanalysis.NewIssue(&pkgIssues[i], pass)) + } + + return issues, nil +} + +func (w *goCriticWrapper) buildEnabledCheckers(linterCtx *gocriticlinter.Context) ([]*gocriticlinter.Checker, error) { + allLowerCasedParams := w.settingsWrapper.GetLowerCasedParams() + + var enabledCheckers []*gocriticlinter.Checker + for _, info := range gocriticlinter.GetCheckersInfo() { + if !w.settingsWrapper.IsCheckEnabled(info.Name) { + continue + } + + if err := w.configureCheckerInfo(info, allLowerCasedParams); err != nil { + return nil, err + } + + c, err := gocriticlinter.NewChecker(linterCtx, info) + if err != nil { + return nil, err + } + enabledCheckers = append(enabledCheckers, c) + } + + return enabledCheckers, nil +} + +func (w *goCriticWrapper) configureCheckerInfo( + info *gocriticlinter.CheckerInfo, + allLowerCasedParams map[string]config.GoCriticCheckSettings, +) error { + params := allLowerCasedParams[strings.ToLower(info.Name)] + if params == nil { // no config for this checker + return nil + } + + // To lowercase info param keys here because golangci-lint's config parser lowercases all strings. + infoParams := normalizeMap(info.Params) + for k, p := range params { + v, ok := infoParams[k] + if ok { + v.Value = w.normalizeCheckerParamsValue(p) + continue + } + + // param `k` isn't supported + if len(info.Params) == 0 { + return fmt.Errorf("checker %s config param %s doesn't exist: checker doesn't have params", + info.Name, k) + } + + supportedKeys := maps.Keys(info.Params) + sort.Strings(supportedKeys) + + return fmt.Errorf("checker %s config param %s doesn't exist, all existing: %s", + info.Name, k, supportedKeys) + } + + return nil +} + +// normalizeCheckerParamsValue normalizes value types. +// go-critic asserts that CheckerParam.Value has some specific types, +// but the file parsers (TOML, YAML, JSON) don't create the same representation for raw type. +// then we have to convert value types into the expected value types. +// Maybe in the future, this kind of conversion will be done in go-critic itself. +func (w *goCriticWrapper) normalizeCheckerParamsValue(p any) any { + rv := reflect.ValueOf(p) + switch rv.Type().Kind() { + case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: + return int(rv.Int()) + case reflect.Bool: + return rv.Bool() + case reflect.String: + // Perform variable substitution. + return strings.ReplaceAll(rv.String(), "${configDir}", w.configDir) + default: + return p + } +} + +func runOnPackage(linterCtx *gocriticlinter.Context, checks []*gocriticlinter.Checker, files []*ast.File) []result.Issue { + var res []result.Issue + for _, f := range files { + filename := filepath.Base(linterCtx.FileSet.Position(f.Pos()).Filename) + linterCtx.SetFileInfo(filename, f) + + issues := runOnFile(linterCtx, f, checks) + res = append(res, issues...) + } + return res +} + +func runOnFile(linterCtx *gocriticlinter.Context, f *ast.File, checks []*gocriticlinter.Checker) []result.Issue { + var res []result.Issue + + for _, c := range checks { + // All checkers are expected to use *lint.Context + // as read-only structure, so no copying is required. + for _, warn := range c.Check(f) { + pos := linterCtx.FileSet.Position(warn.Pos) + issue := result.Issue{ + Pos: pos, + Text: fmt.Sprintf("%s: %s", c.Info.Name, warn.Text), + FromLinter: linterName, + } + + if warn.HasQuickFix() { + issue.Replacement = &result.Replacement{ + Inline: &result.InlineFix{ + StartCol: pos.Column - 1, + Length: int(warn.Suggestion.To - warn.Suggestion.From), + NewString: string(warn.Suggestion.Replacement), + }, + } + } + + res = append(res, issue) + } + } + + return res +} + +type goCriticChecks[T any] map[string]T + +func (m goCriticChecks[T]) has(name string) bool { + _, ok := m[name] + return ok +} + +type settingsWrapper struct { + *config.GoCriticSettings + + logger logutils.Log + + allCheckers []*gocriticlinter.CheckerInfo + + allChecks goCriticChecks[struct{}] + allChecksByTag goCriticChecks[[]string] + allTagsSorted []string + inferredEnabledChecks goCriticChecks[struct{}] + + // *LowerCased fields are used for GoCriticSettings.SettingsPerCheck validation only. + + allChecksLowerCased goCriticChecks[struct{}] + inferredEnabledChecksLowerCased goCriticChecks[struct{}] +} + +func newSettingsWrapper(settings *config.GoCriticSettings, logger logutils.Log) *settingsWrapper { + allCheckers := gocriticlinter.GetCheckersInfo() + + allChecks := make(goCriticChecks[struct{}], len(allCheckers)) + allChecksLowerCased := make(goCriticChecks[struct{}], len(allCheckers)) + allChecksByTag := make(goCriticChecks[[]string]) + for _, checker := range allCheckers { + allChecks[checker.Name] = struct{}{} + allChecksLowerCased[strings.ToLower(checker.Name)] = struct{}{} + + for _, tag := range checker.Tags { + allChecksByTag[tag] = append(allChecksByTag[tag], checker.Name) + } + } + + allTagsSorted := maps.Keys(allChecksByTag) + sort.Strings(allTagsSorted) + + return &settingsWrapper{ + GoCriticSettings: settings, + logger: logger, + allCheckers: allCheckers, + allChecks: allChecks, + allChecksLowerCased: allChecksLowerCased, + allChecksByTag: allChecksByTag, + allTagsSorted: allTagsSorted, + inferredEnabledChecks: make(goCriticChecks[struct{}]), + inferredEnabledChecksLowerCased: make(goCriticChecks[struct{}]), + } +} + +func (s *settingsWrapper) IsCheckEnabled(name string) bool { + return s.inferredEnabledChecks.has(name) +} + +func (s *settingsWrapper) GetLowerCasedParams() map[string]config.GoCriticCheckSettings { + return normalizeMap(s.SettingsPerCheck) +} + +// InferEnabledChecks tries to be consistent with (lintersdb.Manager).build. +func (s *settingsWrapper) InferEnabledChecks() { + s.debugChecksInitialState() + + enabledByDefaultChecks, disabledByDefaultChecks := s.buildEnabledAndDisabledByDefaultChecks() + debugChecksListf(enabledByDefaultChecks, "Enabled by default") + debugChecksListf(disabledByDefaultChecks, "Disabled by default") + + enabledChecks := make(goCriticChecks[struct{}]) + + if s.EnableAll { + enabledChecks = make(goCriticChecks[struct{}], len(s.allCheckers)) + for _, info := range s.allCheckers { + enabledChecks[info.Name] = struct{}{} + } + } else if !s.DisableAll { + // enable-all/disable-all revokes the default settings. + enabledChecks = make(goCriticChecks[struct{}], len(enabledByDefaultChecks)) + for _, check := range enabledByDefaultChecks { + enabledChecks[check] = struct{}{} + } + } + + if len(s.EnabledTags) != 0 { + enabledFromTags := s.expandTagsToChecks(s.EnabledTags) + debugChecksListf(enabledFromTags, "Enabled by config tags %s", sprintSortedStrings(s.EnabledTags)) + + for _, check := range enabledFromTags { + enabledChecks[check] = struct{}{} + } + } + + if len(s.EnabledChecks) != 0 { + debugChecksListf(s.EnabledChecks, "Enabled by config") + + for _, check := range s.EnabledChecks { + if enabledChecks.has(check) { + s.logger.Warnf("%s: no need to enable check %q: it's already enabled", linterName, check) + continue + } + enabledChecks[check] = struct{}{} + } + } + + if len(s.DisabledTags) != 0 { + disabledFromTags := s.expandTagsToChecks(s.DisabledTags) + debugChecksListf(disabledFromTags, "Disabled by config tags %s", sprintSortedStrings(s.DisabledTags)) + + for _, check := range disabledFromTags { + delete(enabledChecks, check) + } + } + + if len(s.DisabledChecks) != 0 { + debugChecksListf(s.DisabledChecks, "Disabled by config") + + for _, check := range s.DisabledChecks { + if !enabledChecks.has(check) { + s.logger.Warnf("%s: no need to disable check %q: it's already disabled", linterName, check) + continue + } + delete(enabledChecks, check) + } + } + + s.inferredEnabledChecks = enabledChecks + s.inferredEnabledChecksLowerCased = normalizeMap(s.inferredEnabledChecks) + s.debugChecksFinalState() +} + +func (s *settingsWrapper) buildEnabledAndDisabledByDefaultChecks() (enabled, disabled []string) { + for _, info := range s.allCheckers { + if enabledByDef := isEnabledByDefaultGoCriticChecker(info); enabledByDef { + enabled = append(enabled, info.Name) + } else { + disabled = append(disabled, info.Name) + } + } + return enabled, disabled +} + +func (s *settingsWrapper) expandTagsToChecks(tags []string) []string { + var checks []string + for _, tag := range tags { + checks = append(checks, s.allChecksByTag[tag]...) + } + return checks +} + +func (s *settingsWrapper) debugChecksInitialState() { + if !isDebug { + return + } + + debugf("All gocritic existing tags and checks:") + for _, tag := range s.allTagsSorted { + debugChecksListf(s.allChecksByTag[tag], " tag %q", tag) + } +} + +func (s *settingsWrapper) debugChecksFinalState() { + if !isDebug { + return + } + + var enabledChecks []string + var disabledChecks []string + + for _, checker := range s.allCheckers { + check := checker.Name + if s.inferredEnabledChecks.has(check) { + enabledChecks = append(enabledChecks, check) + } else { + disabledChecks = append(disabledChecks, check) + } + } + + debugChecksListf(enabledChecks, "Final used") + + if len(disabledChecks) == 0 { + debugf("All checks are enabled") + } else { + debugChecksListf(disabledChecks, "Final not used") + } +} + +// Validate tries to be consistent with (lintersdb.Validator).validateEnabledDisabledLintersConfig. +func (s *settingsWrapper) Validate() error { + for _, v := range []func() error{ + s.validateOptionsCombinations, + s.validateCheckerTags, + s.validateCheckerNames, + s.validateDisabledAndEnabledAtOneMoment, + s.validateAtLeastOneCheckerEnabled, + } { + if err := v(); err != nil { + return err + } + } + return nil +} + +func (s *settingsWrapper) validateOptionsCombinations() error { + if s.EnableAll { + if s.DisableAll { + return errors.New("enable-all and disable-all options must not be combined") + } + + if len(s.EnabledTags) != 0 { + return errors.New("enable-all and enabled-tags options must not be combined") + } + + if len(s.EnabledChecks) != 0 { + return errors.New("enable-all and enabled-checks options must not be combined") + } + } + + if s.DisableAll { + if len(s.DisabledTags) != 0 { + return errors.New("disable-all and disabled-tags options must not be combined") + } + + if len(s.DisabledChecks) != 0 { + return errors.New("disable-all and disabled-checks options must not be combined") + } + + if len(s.EnabledTags) == 0 && len(s.EnabledChecks) == 0 { + return errors.New("all checks were disabled, but no one check was enabled: at least one must be enabled") + } + } + + return nil +} + +func (s *settingsWrapper) validateCheckerTags() error { + for _, tag := range s.EnabledTags { + if !s.allChecksByTag.has(tag) { + return fmt.Errorf("enabled tag %q doesn't exist, see %s's documentation", tag, linterName) + } + } + + for _, tag := range s.DisabledTags { + if !s.allChecksByTag.has(tag) { + return fmt.Errorf("disabled tag %q doesn't exist, see %s's documentation", tag, linterName) + } + } + + return nil +} + +func (s *settingsWrapper) validateCheckerNames() error { + for _, check := range s.EnabledChecks { + if !s.allChecks.has(check) { + return fmt.Errorf("enabled check %q doesn't exist, see %s's documentation", check, linterName) + } + } + + for _, check := range s.DisabledChecks { + if !s.allChecks.has(check) { + return fmt.Errorf("disabled check %q doesn't exist, see %s documentation", check, linterName) + } + } + + for check := range s.SettingsPerCheck { + lcName := strings.ToLower(check) + if !s.allChecksLowerCased.has(lcName) { + return fmt.Errorf("invalid check settings: check %q doesn't exist, see %s documentation", check, linterName) + } + if !s.inferredEnabledChecksLowerCased.has(lcName) { + s.logger.Warnf("%s: settings were provided for disabled check %q", check, linterName) + } + } + + return nil +} + +func (s *settingsWrapper) validateDisabledAndEnabledAtOneMoment() error { + for _, tag := range s.DisabledTags { + if slices.Contains(s.EnabledTags, tag) { + return fmt.Errorf("tag %q disabled and enabled at one moment", tag) + } + } + + for _, check := range s.DisabledChecks { + if slices.Contains(s.EnabledChecks, check) { + return fmt.Errorf("check %q disabled and enabled at one moment", check) + } + } + + return nil +} + +func (s *settingsWrapper) validateAtLeastOneCheckerEnabled() error { + if len(s.inferredEnabledChecks) == 0 { + return errors.New("eventually all checks were disabled: at least one must be enabled") + } + return nil +} + +func normalizeMap[ValueT any](in map[string]ValueT) map[string]ValueT { + ret := make(map[string]ValueT, len(in)) + for k, v := range in { + ret[strings.ToLower(k)] = v + } + return ret +} + +func isEnabledByDefaultGoCriticChecker(info *gocriticlinter.CheckerInfo) bool { + // https://github.com/go-critic/go-critic/blob/5b67cfd487ae9fe058b4b19321901b3131810f65/cmd/gocritic/check.go#L342-L345 + return !info.HasTag(gocriticlinter.ExperimentalTag) && + !info.HasTag(gocriticlinter.OpinionatedTag) && + !info.HasTag(gocriticlinter.PerformanceTag) && + !info.HasTag(gocriticlinter.SecurityTag) +} + +func debugChecksListf(checks []string, format string, args ...any) { + if !isDebug { + return + } + + debugf("%s checks (%d): %s", fmt.Sprintf(format, args...), len(checks), sprintSortedStrings(checks)) +} + +func sprintSortedStrings(v []string) string { + sort.Strings(slices.Clone(v)) + return fmt.Sprint(v) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo/gocyclo.go similarity index 80% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo/gocyclo.go index b502623ba..51333dc15 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo/gocyclo.go @@ -1,4 +1,4 @@ -package golinters +package gocyclo import ( "fmt" @@ -8,20 +8,20 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const gocycloName = "gocyclo" +const linterName = "gocyclo" -//nolint:dupl -func NewGocyclo(settings *config.GoCycloSettings) *goanalysis.Linter { +func New(settings *config.GoCycloSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: gocycloName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues := runGoCyclo(pass, settings) @@ -39,7 +39,7 @@ func NewGocyclo(settings *config.GoCycloSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - gocycloName, + linterName, "Computes and checks the cyclomatic complexity of functions", []*analysis.Analyzer{analyzer}, nil, @@ -63,12 +63,12 @@ func runGoCyclo(pass *analysis.Pass, settings *config.GoCycloSettings) []goanaly for _, s := range stats { text := fmt.Sprintf("cyclomatic complexity %d of func %s is high (> %d)", - s.Complexity, formatCode(s.FuncName, nil), settings.MinComplexity) + s.Complexity, internal.FormatCode(s.FuncName, nil), settings.MinComplexity) issues = append(issues, goanalysis.NewIssue(&result.Issue{ Pos: s.Pos, Text: text, - FromLinter: gocycloName, + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot/godot.go similarity index 84% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot/godot.go index b0ee64434..fc51b5bb8 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot/godot.go @@ -1,4 +1,4 @@ -package golinters +package godot import ( "sync" @@ -7,14 +7,14 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const godotName = "godot" +const linterName = "godot" -func NewGodot(settings *config.GodotSettings) *goanalysis.Linter { +func New(settings *config.GodotSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -29,8 +29,7 @@ func NewGodot(settings *config.GodotSettings) *goanalysis.Linter { } // Convert deprecated setting - // todo(butuzov): remove on v2 release - if settings.CheckAll { //nolint:staticcheck // Keep for retro-compatibility. + if settings.CheckAll { dotSettings.Scope = godot.AllScope } } @@ -40,7 +39,7 @@ func NewGodot(settings *config.GodotSettings) *goanalysis.Linter { } analyzer := &analysis.Analyzer{ - Name: godotName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runGodot(pass, dotSettings) @@ -61,7 +60,7 @@ func NewGodot(settings *config.GodotSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - godotName, + linterName, "Check if comments end in a period", []*analysis.Analyzer{analyzer}, nil, @@ -89,7 +88,7 @@ func runGodot(pass *analysis.Pass, settings godot.Settings) ([]goanalysis.Issue, issue := result.Issue{ Pos: i.Pos, Text: i.Message, - FromLinter: godotName, + FromLinter: linterName, Replacement: &result.Replacement{ NewLines: []string{i.Replacement}, }, diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox/godox.go similarity index 85% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox/godox.go index 955810417..d8de026ba 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox/godox.go @@ -1,4 +1,4 @@ -package golinters +package godox import ( "go/token" @@ -9,20 +9,19 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const godoxName = "godox" +const linterName = "godox" -//nolint:dupl -func NewGodox(settings *config.GodoxSettings) *goanalysis.Linter { +func New(settings *config.GodoxSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: godoxName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues := runGodox(pass, settings) @@ -40,7 +39,7 @@ func NewGodox(settings *config.GodoxSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - godoxName, + linterName, "Tool for detection of FIXME, TODO and other comment keywords", []*analysis.Analyzer{analyzer}, nil, @@ -68,7 +67,7 @@ func runGodox(pass *analysis.Pass, settings *config.GodoxSettings) []goanalysis. Line: i.Pos.Line, }, Text: strings.TrimRight(i.Message, "\n"), - FromLinter: godoxName, + FromLinter: linterName, }, pass) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt/gofmt.go similarity index 72% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt/gofmt.go index d2d0d3ccc..289ceab8a 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt/gofmt.go @@ -1,4 +1,4 @@ -package golinters +package gofmt import ( "fmt" @@ -8,24 +8,25 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" ) -const gofmtName = "gofmt" +const linterName = "gofmt" -func NewGofmt(settings *config.GoFmtSettings) *goanalysis.Linter { +func New(settings *config.GoFmtSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: gofmtName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: goanalysis.DummyRun, } return goanalysis.NewLinter( - gofmtName, + linterName, "Gofmt checks whether code was gofmt-ed. By default "+ "this tool runs with -s option to check for code simplification", []*analysis.Analyzer{analyzer}, @@ -53,7 +54,7 @@ func NewGofmt(settings *config.GoFmtSettings) *goanalysis.Linter { } func runGofmt(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoFmtSettings) ([]goanalysis.Issue, error) { - fileNames := getFileNames(pass) + fileNames := internal.GetFileNames(pass) var rewriteRules []gofmtAPI.RewriteRule for _, rule := range settings.RewriteRules { @@ -71,7 +72,7 @@ func runGofmt(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoF continue } - is, err := extractIssuesFromPatch(string(diff), lintCtx, gofmtName) + is, err := internal.ExtractIssuesFromPatch(string(diff), lintCtx, linterName, getIssuedTextGoFmt) if err != nil { return nil, fmt.Errorf("can't extract issues from gofmt diff output %q: %w", string(diff), err) } @@ -83,3 +84,15 @@ func runGofmt(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoF return issues, nil } + +func getIssuedTextGoFmt(settings *config.LintersSettings) string { + text := "File is not `gofmt`-ed" + if settings.Gofmt.Simplify { + text += " with `-s`" + } + for _, rule := range settings.Gofmt.RewriteRules { + text += fmt.Sprintf(" `-r '%s -> %s'`", rule.Pattern, rule.Replacement) + } + + return text +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt/gofumpt.go similarity index 81% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt/gofumpt.go index c2aaf121d..9a0bef84a 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt/gofumpt.go @@ -1,4 +1,4 @@ -package golinters +package gofumpt import ( "bytes" @@ -12,17 +12,18 @@ import ( "mvdan.cc/gofumpt/format" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" ) -const gofumptName = "gofumpt" +const linterName = "gofumpt" type differ interface { Diff(out io.Writer, a io.ReadSeeker, b io.ReadSeeker) error } -func NewGofumpt(settings *config.GofumptSettings) *goanalysis.Linter { +func New(settings *config.GofumptSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -39,13 +40,13 @@ func NewGofumpt(settings *config.GofumptSettings) *goanalysis.Linter { } analyzer := &analysis.Analyzer{ - Name: gofumptName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: goanalysis.DummyRun, } return goanalysis.NewLinter( - gofumptName, + linterName, "Gofumpt checks whether code was gofumpt-ed.", []*analysis.Analyzer{analyzer}, nil, @@ -72,7 +73,7 @@ func NewGofumpt(settings *config.GofumptSettings) *goanalysis.Linter { } func runGofumpt(lintCtx *linter.Context, pass *analysis.Pass, diff differ, options format.Options) ([]goanalysis.Issue, error) { - fileNames := getFileNames(pass) + fileNames := internal.GetFileNames(pass) var issues []goanalysis.Issue @@ -96,7 +97,7 @@ func runGofumpt(lintCtx *linter.Context, pass *analysis.Pass, diff differ, optio } diff := out.String() - is, err := extractIssuesFromPatch(diff, lintCtx, gofumptName) + is, err := internal.ExtractIssuesFromPatch(diff, lintCtx, linterName, getIssuedTextGoFumpt) if err != nil { return nil, fmt.Errorf("can't extract issues from gofumpt diff output %q: %w", diff, err) } @@ -117,3 +118,13 @@ func getLangVersion(settings *config.GofumptSettings) string { } return settings.LangVersion } + +func getIssuedTextGoFumpt(settings *config.LintersSettings) string { + text := "File is not `gofumpt`-ed" + + if settings.Gofumpt.ExtraRules { + text += " with `-extra`" + } + + return text +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader/goheader.go similarity index 80% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader/goheader.go index d3cfefa90..14d517fb3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader/goheader.go @@ -1,4 +1,4 @@ -package golinters +package goheader import ( "go/token" @@ -8,14 +8,14 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const goHeaderName = "goheader" +const linterName = "goheader" -func NewGoHeader(settings *config.GoHeaderSettings) *goanalysis.Linter { +func New(settings *config.GoHeaderSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -29,7 +29,7 @@ func NewGoHeader(settings *config.GoHeaderSettings) *goanalysis.Linter { } analyzer := &analysis.Analyzer{ - Name: goHeaderName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runGoHeader(pass, conf) @@ -50,7 +50,7 @@ func NewGoHeader(settings *config.GoHeaderSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - goHeaderName, + linterName, "Checks is file header matches to pattern", []*analysis.Analyzer{analyzer}, nil, @@ -94,7 +94,18 @@ func runGoHeader(pass *analysis.Pass, conf *goheader.Configuration) ([]goanalysi Filename: path, }, Text: i.Message(), - FromLinter: goHeaderName, + FromLinter: linterName, + } + + if fix := i.Fix(); fix != nil { + issue.LineRange = &result.Range{ + From: issue.Line(), + To: issue.Line() + len(fix.Actual) - 1, + } + issue.Replacement = &result.Replacement{ + NeedOnlyDelete: len(fix.Expected) == 0, + NewLines: fix.Expected, + } } issues = append(issues, goanalysis.NewIssue(&issue, pass)) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports/goimports.go similarity index 71% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports/goimports.go index aac27f38e..de965d5c8 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports/goimports.go @@ -1,4 +1,4 @@ -package golinters +package goimports import ( "fmt" @@ -9,24 +9,25 @@ import ( "golang.org/x/tools/imports" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" ) -const goimportsName = "goimports" +const linterName = "goimports" -func NewGoimports(settings *config.GoImportsSettings) *goanalysis.Linter { +func New(settings *config.GoImportsSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: goimportsName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: goanalysis.DummyRun, } return goanalysis.NewLinter( - goimportsName, + linterName, "Check import statements are formatted according to the 'goimport' command. "+ "Reformat imports in autofix mode.", []*analysis.Analyzer{analyzer}, @@ -56,7 +57,7 @@ func NewGoimports(settings *config.GoImportsSettings) *goanalysis.Linter { } func runGoImports(lintCtx *linter.Context, pass *analysis.Pass) ([]goanalysis.Issue, error) { - fileNames := getFileNames(pass) + fileNames := internal.GetFileNames(pass) var issues []goanalysis.Issue @@ -69,7 +70,7 @@ func runGoImports(lintCtx *linter.Context, pass *analysis.Pass) ([]goanalysis.Is continue } - is, err := extractIssuesFromPatch(string(diff), lintCtx, goimportsName) + is, err := internal.ExtractIssuesFromPatch(string(diff), lintCtx, linterName, getIssuedTextGoImports) if err != nil { return nil, fmt.Errorf("can't extract issues from gofmt diff output %q: %w", string(diff), err) } @@ -81,3 +82,13 @@ func runGoImports(lintCtx *linter.Context, pass *analysis.Pass) ([]goanalysis.Is return issues, nil } + +func getIssuedTextGoImports(settings *config.LintersSettings) string { + text := "File is not `goimports`-ed" + + if settings.Goimports.LocalPrefixes != "" { + text += " with -local " + settings.Goimports.LocalPrefixes + } + + return text +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/golint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/golint.go deleted file mode 100644 index a6fc73c9e..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/golint.go +++ /dev/null @@ -1,84 +0,0 @@ -package golinters - -import ( - "fmt" - "sync" - - lintAPI "github.com/golangci/lint-1" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const golintName = "golint" - -//nolint:dupl -func NewGolint(settings *config.GoLintSettings) *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: golintName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues, err := runGoLint(pass, settings) - if err != nil { - return nil, err - } - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - golintName, - "Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) -} - -func runGoLint(pass *analysis.Pass, settings *config.GoLintSettings) ([]goanalysis.Issue, error) { - l := new(lintAPI.Linter) - - ps, err := l.LintPkg(pass.Files, pass.Fset, pass.Pkg, pass.TypesInfo) - if err != nil { - return nil, fmt.Errorf("can't lint %d files: %s", len(pass.Files), err) - } - - if len(ps) == 0 { - return nil, nil - } - - lintIssues := make([]*result.Issue, 0, len(ps)) // This is worst case - for idx := range ps { - if ps[idx].Confidence >= settings.MinConfidence { - lintIssues = append(lintIssues, &result.Issue{ - Pos: ps[idx].Position, - Text: ps[idx].Text, - FromLinter: golintName, - }) - // TODO: use p.Link and p.Category - } - } - - issues := make([]goanalysis.Issue, 0, len(lintIssues)) - for _, issue := range lintIssues { - issues = append(issues, goanalysis.NewIssue(issue, pass)) - } - - return issues, nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomnd.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomnd.go deleted file mode 100644 index 2e6d77a80..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomnd.go +++ /dev/null @@ -1,45 +0,0 @@ -package golinters - -import ( - mnd "github.com/tommy-muehle/go-mnd/v2" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewGoMND(settings *config.GoMndSettings) *goanalysis.Linter { - var linterCfg map[string]map[string]any - - if settings != nil { - // TODO(ldez) For compatibility only, must be drop in v2. - if len(settings.Settings) > 0 { - linterCfg = settings.Settings - } else { - cfg := make(map[string]any) - if len(settings.Checks) > 0 { - cfg["checks"] = settings.Checks - } - if len(settings.IgnoredNumbers) > 0 { - cfg["ignored-numbers"] = settings.IgnoredNumbers - } - if len(settings.IgnoredFiles) > 0 { - cfg["ignored-files"] = settings.IgnoredFiles - } - if len(settings.IgnoredFunctions) > 0 { - cfg["ignored-functions"] = settings.IgnoredFunctions - } - - linterCfg = map[string]map[string]any{ - "mnd": cfg, - } - } - } - - return goanalysis.NewLinter( - "gomnd", - "An analyzer to detect magic numbers.", - []*analysis.Analyzer{mnd.Analyzer}, - linterCfg, - ).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives/gomoddirectives.go similarity index 80% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives/gomoddirectives.go index 56afcd465..9cde7e26c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives/gomoddirectives.go @@ -1,4 +1,4 @@ -package golinters +package gomoddirectives import ( "sync" @@ -7,15 +7,14 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const goModDirectivesName = "gomoddirectives" +const linterName = "gomoddirectives" -// NewGoModDirectives returns a new gomoddirectives linter. -func NewGoModDirectives(settings *config.GoModDirectivesSettings) *goanalysis.Linter { +func New(settings *config.GoModDirectivesSettings) *goanalysis.Linter { var issues []goanalysis.Issue var once sync.Once @@ -34,7 +33,7 @@ func NewGoModDirectives(settings *config.GoModDirectivesSettings) *goanalysis.Li } return goanalysis.NewLinter( - goModDirectivesName, + linterName, "Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.", []*analysis.Analyzer{analyzer}, nil, @@ -44,13 +43,13 @@ func NewGoModDirectives(settings *config.GoModDirectivesSettings) *goanalysis.Li results, err := gomoddirectives.Analyze(opts) if err != nil { lintCtx.Log.Warnf("running %s failed: %s: "+ - "if you are not using go modules it is suggested to disable this linter", goModDirectivesName, err) + "if you are not using go modules it is suggested to disable this linter", linterName, err) return } for _, p := range results { issues = append(issues, goanalysis.NewIssue(&result.Issue{ - FromLinter: goModDirectivesName, + FromLinter: linterName, Pos: p.Start, Text: p.Reason, }, pass)) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard/gomodguard.go similarity index 83% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard/gomodguard.go index 157bf56c3..8f1036b0f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard/gomodguard.go @@ -1,4 +1,4 @@ -package golinters +package gomodguard import ( "sync" @@ -7,20 +7,20 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) const ( - gomodguardName = "gomodguard" - gomodguardDesc = "Allow and block list linter for direct Go module dependencies. " + + name = "gomodguard" + desc = "Allow and block list linter for direct Go module dependencies. " + "This is different from depguard where there are different block " + "types for example version constraints and module recommendations." ) -// NewGomodguard returns a new Gomodguard linter. -func NewGomodguard(settings *config.GoModGuardSettings) *goanalysis.Linter { +func New(settings *config.GoModGuardSettings) *goanalysis.Linter { var issues []goanalysis.Issue var mu sync.Mutex @@ -60,8 +60,8 @@ func NewGomodguard(settings *config.GoModGuardSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - gomodguardName, - gomodguardDesc, + name, + desc, []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { @@ -73,14 +73,14 @@ func NewGomodguard(settings *config.GoModGuardSettings) *goanalysis.Linter { } analyzer.Run = func(pass *analysis.Pass) (any, error) { - gomodguardIssues := processor.ProcessFiles(getFileNames(pass)) + gomodguardIssues := processor.ProcessFiles(internal.GetFileNames(pass)) mu.Lock() defer mu.Unlock() for _, gomodguardIssue := range gomodguardIssues { issues = append(issues, goanalysis.NewIssue(&result.Issue{ - FromLinter: gomodguardName, + FromLinter: name, Pos: gomodguardIssue.Position, Text: gomodguardIssue.Reason, }, pass)) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname.go deleted file mode 100644 index c5516dc7f..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname.go +++ /dev/null @@ -1,17 +0,0 @@ -package golinters - -import ( - "github.com/jirfag/go-printf-func-name/pkg/analyzer" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewGoPrintfFuncName() *goanalysis.Linter { - return goanalysis.NewLinter( - "goprintffuncname", - "Checks that printf-like functions are named with `f` at the end", - []*analysis.Analyzer{analyzer.Analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname/goprintffuncname.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname/goprintffuncname.go new file mode 100644 index 000000000..85154a9b3 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname/goprintffuncname.go @@ -0,0 +1,19 @@ +package goprintffuncname + +import ( + "github.com/jirfag/go-printf-func-name/pkg/analyzer" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := analyzer.Analyzer + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec/gosec.go similarity index 90% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec/gosec.go index 235f0e914..c333152e6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec/gosec.go @@ -1,4 +1,4 @@ -package golinters +package gosec import ( "fmt" @@ -16,14 +16,14 @@ import ( "golang.org/x/tools/go/packages" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const gosecName = "gosec" +const linterName = "gosec" -func NewGosec(settings *config.GoSecSettings) *goanalysis.Linter { +func New(settings *config.GoSecSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -39,13 +39,13 @@ func NewGosec(settings *config.GoSecSettings) *goanalysis.Linter { ruleDefinitions := rules.Generate(false, filters...) analyzer := &analysis.Analyzer{ - Name: gosecName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: goanalysis.DummyRun, } return goanalysis.NewLinter( - gosecName, + linterName, "Inspects source code for security problems", []*analysis.Analyzer{analyzer}, nil, @@ -97,7 +97,7 @@ func runGoSec(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoS issues := make([]goanalysis.Issue, 0, len(secIssues)) for _, i := range secIssues { - text := fmt.Sprintf("%s: %s", i.RuleID, i.What) // TODO: use severity and confidence + text := fmt.Sprintf("%s: %s", i.RuleID, i.What) var r *result.Range @@ -118,6 +118,7 @@ func runGoSec(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoS } issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Severity: convertScoreToString(i.Severity), Pos: token.Position{ Filename: i.File, Line: line, @@ -125,7 +126,7 @@ func runGoSec(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoS }, Text: text, LineRange: r, - FromLinter: gosecName, + FromLinter: linterName, }, pass)) } @@ -149,6 +150,19 @@ func toGosecConfig(settings *config.GoSecSettings) gosec.Config { return conf } +func convertScoreToString(score issue.Score) string { + switch score { + case issue.Low: + return "low" + case issue.Medium: + return "medium" + case issue.High: + return "high" + default: + return "" + } +} + // based on https://github.com/securego/gosec/blob/47bfd4eb6fc7395940933388550b547538b4c946/config.go#L52-L62 func convertGosecGlobals(globalOptionFromConfig any, conf gosec.Config) { globalOptionMap, ok := globalOptionFromConfig.(map[string]any) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple.go deleted file mode 100644 index de60ded73..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple.go +++ /dev/null @@ -1,21 +0,0 @@ -package golinters - -import ( - "honnef.co/go/tools/simple" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewGosimple(settings *config.StaticCheckSettings) *goanalysis.Linter { - cfg := staticCheckConfig(settings) - - analyzers := setupStaticCheckAnalyzers(simple.Analyzers, getGoVersion(settings), cfg.Checks) - - return goanalysis.NewLinter( - "gosimple", - "Linter for Go source code that specializes in simplifying code", - analyzers, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple/gosimple.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple/gosimple.go new file mode 100644 index 000000000..6a0d96723 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple/gosimple.go @@ -0,0 +1,22 @@ +package gosimple + +import ( + "honnef.co/go/tools/simple" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" +) + +func New(settings *config.StaticCheckSettings) *goanalysis.Linter { + cfg := internal.StaticCheckConfig(settings) + + analyzers := internal.SetupStaticCheckAnalyzers(simple.Analyzers, internal.GetGoVersion(settings), cfg.Checks) + + return goanalysis.NewLinter( + "gosimple", + "Linter for Go source code that specializes in simplifying code", + analyzers, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan/gosmopolitan.go similarity index 79% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan/gosmopolitan.go index 2e01fcc70..4f6fb8035 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan/gosmopolitan.go @@ -1,4 +1,4 @@ -package golinters +package gosmopolitan import ( "strings" @@ -7,10 +7,10 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewGosmopolitan(s *config.GosmopolitanSettings) *goanalysis.Linter { +func New(s *config.GosmopolitanSettings) *goanalysis.Linter { a := gosmopolitan.NewAnalyzer() cfgMap := map[string]map[string]any{} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet/govet.go similarity index 77% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet/govet.go index 4e16fb142..eb63a5d33 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet/govet.go @@ -1,6 +1,9 @@ -package golinters +package govet import ( + "slices" + "sort" + "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/appends" "golang.org/x/tools/go/analysis/passes/asmdecl" @@ -49,7 +52,8 @@ import ( "golang.org/x/tools/go/analysis/passes/unusedwrite" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/logutils" ) var ( @@ -134,7 +138,12 @@ var ( } ) -func NewGovet(settings *config.GovetSettings) *goanalysis.Linter { +var ( + debugf = logutils.Debug(logutils.DebugKeyGovet) + isDebug = logutils.HaveDebugTag(logutils.DebugKeyGovet) +) + +func New(settings *config.GovetSettings) *goanalysis.Linter { var conf map[string]map[string]any if settings != nil { conf = settings.Settings @@ -142,23 +151,21 @@ func NewGovet(settings *config.GovetSettings) *goanalysis.Linter { return goanalysis.NewLinter( "govet", - "Vet examines Go source code and reports suspicious constructs, "+ - "such as Printf calls whose arguments do not align with the format string", + "Vet examines Go source code and reports suspicious constructs. "+ + "It is roughly the same as 'go vet' and uses its passes.", analyzersFromConfig(settings), conf, ).WithLoadMode(goanalysis.LoadModeTypesInfo) } func analyzersFromConfig(settings *config.GovetSettings) []*analysis.Analyzer { + debugAnalyzersListf(allAnalyzers, "All available analyzers") + debugAnalyzersListf(defaultAnalyzers, "Default analyzers") + if settings == nil { return defaultAnalyzers } - if settings.CheckShadowing { - // Keeping for backward compatibility. - settings.Enable = append(settings.Enable, shadow.Analyzer.Name) - } - var enabledAnalyzers []*analysis.Analyzer for _, a := range allAnalyzers { if isAnalyzerEnabled(a.Name, settings, defaultAnalyzers) { @@ -166,40 +173,51 @@ func analyzersFromConfig(settings *config.GovetSettings) []*analysis.Analyzer { } } + debugAnalyzersListf(enabledAnalyzers, "Enabled by config analyzers") + return enabledAnalyzers } func isAnalyzerEnabled(name string, cfg *config.GovetSettings, defaultAnalyzers []*analysis.Analyzer) bool { - if cfg.EnableAll { - for _, n := range cfg.Disable { - if n == name { - return false - } - } - return true + // TODO(ldez) remove loopclosure when go1.24 + if name == loopclosure.Analyzer.Name && config.IsGoGreaterThanOrEqual(cfg.Go, "1.22") { + return false } - // Raw for loops should be OK on small slice lengths. - for _, n := range cfg.Enable { - if n == name { - return true - } + // Keeping for backward compatibility. + if cfg.CheckShadowing && name == shadow.Analyzer.Name { + return true } - for _, n := range cfg.Disable { - if n == name { - return false - } - } + switch { + case cfg.EnableAll: + return !slices.Contains(cfg.Disable, name) + + case slices.Contains(cfg.Enable, name): + return true - if cfg.DisableAll { + case slices.Contains(cfg.Disable, name): return false + + case cfg.DisableAll: + return false + + default: + return slices.ContainsFunc(defaultAnalyzers, func(a *analysis.Analyzer) bool { return a.Name == name }) } +} - for _, a := range defaultAnalyzers { - if a.Name == name { - return true - } +func debugAnalyzersListf(analyzers []*analysis.Analyzer, message string) { + if !isDebug { + return + } + + analyzerNames := make([]string, 0, len(analyzers)) + for _, a := range analyzers { + analyzerNames = append(analyzerNames, a.Name) } - return false + + sort.Strings(analyzerNames) + + debugf("%s (%d): %s", message, len(analyzerNames), analyzerNames) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/grouper.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/grouper/grouper.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/grouper.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/grouper/grouper.go index 9feecf3ba..aa6ce1ceb 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/grouper.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/grouper/grouper.go @@ -1,17 +1,19 @@ -package golinters +package grouper import ( grouper "github.com/leonklingele/grouper/pkg/analyzer" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewGrouper(settings *config.GrouperSettings) *goanalysis.Linter { +func New(settings *config.GrouperSettings) *goanalysis.Linter { + a := grouper.New() + linterCfg := map[string]map[string]any{} if settings != nil { - linterCfg["grouper"] = map[string]any{ + linterCfg[a.Name] = map[string]any{ "const-require-single-const": settings.ConstRequireSingleConst, "const-require-grouping": settings.ConstRequireGrouping, "import-require-single-import": settings.ImportRequireSingleImport, @@ -24,9 +26,9 @@ func NewGrouper(settings *config.GrouperSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - "grouper", - "An analyzer to analyze expression groups.", - []*analysis.Analyzer{grouper.New()}, + a.Name, + "Analyze expression groups.", + []*analysis.Analyzer{a}, linterCfg, ).WithLoadMode(goanalysis.LoadModeSyntax) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ifshort.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ifshort.go deleted file mode 100644 index 1574eaf70..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ifshort.go +++ /dev/null @@ -1,28 +0,0 @@ -package golinters - -import ( - "github.com/esimonov/ifshort/pkg/analyzer" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewIfshort(settings *config.IfshortSettings) *goanalysis.Linter { - var cfg map[string]map[string]any - if settings != nil { - cfg = map[string]map[string]any{ - analyzer.Analyzer.Name: { - "max-decl-lines": settings.MaxDeclLines, - "max-decl-chars": settings.MaxDeclChars, - }, - } - } - - return goanalysis.NewLinter( - "ifshort", - "Checks that your code uses short syntax for if-statements whenever possible", - []*analysis.Analyzer{analyzer.Analyzer}, - cfg, - ).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas/importas.go similarity index 88% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas/importas.go index b06aec7a3..45117c9a4 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas/importas.go @@ -1,19 +1,19 @@ -package golinters +package importas import ( "fmt" "strconv" "strings" - "github.com/julz/importas" //nolint:misspell + "github.com/julz/importas" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" ) -func NewImportAs(settings *config.ImportAsSettings) *goanalysis.Linter { +func New(settings *config.ImportAsSettings) *goanalysis.Linter { analyzer := importas.Analyzer return goanalysis.NewLinter( @@ -26,7 +26,7 @@ func NewImportAs(settings *config.ImportAsSettings) *goanalysis.Linter { return } if len(settings.Alias) == 0 { - lintCtx.Log.Infof("importas settings found, but no aliases listed. List aliases under alias: key.") //nolint:misspell + lintCtx.Log.Infof("importas settings found, but no aliases listed. List aliases under alias: key.") } if err := analyzer.Flags.Set("no-unaliased", strconv.FormatBool(settings.NoUnaliased)); err != nil { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam.go deleted file mode 100644 index 290630755..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam.go +++ /dev/null @@ -1,19 +0,0 @@ -package golinters - -import ( - "github.com/macabu/inamedparam" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewINamedParam() *goanalysis.Linter { - a := inamedparam.Analyzer - - return goanalysis.NewLinter( - a.Name, - a.Doc, - []*analysis.Analyzer{a}, - nil, - ).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam/inamedparam.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam/inamedparam.go new file mode 100644 index 000000000..5cf06a08c --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/inamedparam/inamedparam.go @@ -0,0 +1,30 @@ +package inamedparam + +import ( + "github.com/macabu/inamedparam" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.INamedParamSettings) *goanalysis.Linter { + a := inamedparam.Analyzer + + var cfg map[string]map[string]any + + if settings != nil { + cfg = map[string]map[string]any{ + a.Name: { + "skip-single-param": settings.SkipSingleParam, + }, + } + } + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + cfg, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign/ineffassign.go similarity index 57% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign/ineffassign.go index c87bb2fa5..ba86fb90e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign/ineffassign.go @@ -1,17 +1,19 @@ -package golinters +package ineffassign import ( "github.com/gordonklaus/ineffassign/pkg/ineffassign" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewIneffassign() *goanalysis.Linter { +func New() *goanalysis.Linter { + a := ineffassign.Analyzer + return goanalysis.NewLinter( - "ineffassign", + a.Name, "Detects when assignments to existing variables are not used", - []*analysis.Analyzer{ineffassign.Analyzer}, + []*analysis.Analyzer{a}, nil, ).WithLoadMode(goanalysis.LoadModeSyntax) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat/interfacebloat.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat/interfacebloat.go index a6dbfe178..88927a3d9 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat/interfacebloat.go @@ -1,14 +1,14 @@ -package golinters +package interfacebloat import ( "github.com/sashamelentyev/interfacebloat/pkg/analyzer" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewInterfaceBloat(settings *config.InterfaceBloatSettings) *goanalysis.Linter { +func New(settings *config.InterfaceBloatSettings) *goanalysis.Linter { a := analyzer.New() var cfg map[string]map[string]any diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacer.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacer.go deleted file mode 100644 index 71bdfddbe..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacer.go +++ /dev/null @@ -1,82 +0,0 @@ -package golinters - -import ( - "sync" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/buildssa" - "mvdan.cc/interfacer/check" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const interfacerName = "interfacer" - -func NewInterfacer() *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: interfacerName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Requires: []*analysis.Analyzer{buildssa.Analyzer}, - Run: func(pass *analysis.Pass) (any, error) { - issues, err := runInterfacer(pass) - if err != nil { - return nil, err - } - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - interfacerName, - "Linter that suggests narrower interface types", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) -} - -func runInterfacer(pass *analysis.Pass) ([]goanalysis.Issue, error) { - c := &check.Checker{} - - prog := goanalysis.MakeFakeLoaderProgram(pass) - c.Program(prog) - - ssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) - ssaPkg := ssa.Pkg - c.ProgramSSA(ssaPkg.Prog) - - lintIssues, err := c.Check() - if err != nil { - return nil, err - } - if len(lintIssues) == 0 { - return nil, nil - } - - issues := make([]goanalysis.Issue, 0, len(lintIssues)) - for _, i := range lintIssues { - pos := pass.Fset.Position(i.Pos()) - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: pos, - Text: i.Message(), - FromLinter: interfacerName, - }, pass)) - } - - return issues, nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/commons.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/commons.go new file mode 100644 index 000000000..c21dd0092 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/commons.go @@ -0,0 +1,6 @@ +package internal + +import "github.com/golangci/golangci-lint/pkg/logutils" + +// LinterLogger must be use only when the context logger is not available. +var LinterLogger = logutils.NewStderrLog(logutils.DebugKeyLinter) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/diff.go similarity index 85% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/diff.go index 6b7184d65..b20230dfa 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/diff.go @@ -1,4 +1,4 @@ -package golinters +package internal import ( "bytes" @@ -27,6 +27,8 @@ const ( diffLineDeleted diffLineType = "deleted" ) +type fmtTextFormatter func(settings *config.LintersSettings) string + type diffLine struct { originalNumber int // 1-based original line number typ diffLineType @@ -133,8 +135,8 @@ func (p *hunkChangesParser) handleDeletedLines(deletedLines []diffLine, addedLin } if len(addedLines) != 0 { - //nolint:gocritic - change.Replacement.NewLines = append(p.replacementLinesToPrepend, addedLines...) + change.Replacement.NewLines = append([]string{}, p.replacementLinesToPrepend...) + change.Replacement.NewLines = append(change.Replacement.NewLines, addedLines...) if len(p.replacementLinesToPrepend) != 0 { p.replacementLinesToPrepend = nil } @@ -217,34 +219,7 @@ func (p *hunkChangesParser) parse(h *diffpkg.Hunk) []Change { return p.ret } -func getErrorTextForLinter(settings *config.LintersSettings, linterName string) string { - text := "File is not formatted" - switch linterName { - case gciName: - text = getErrorTextForGci(settings.Gci) - case gofumptName: - text = "File is not `gofumpt`-ed" - if settings.Gofumpt.ExtraRules { - text += " with `-extra`" - } - case gofmtName: - text = "File is not `gofmt`-ed" - if settings.Gofmt.Simplify { - text += " with `-s`" - } - for _, rule := range settings.Gofmt.RewriteRules { - text += fmt.Sprintf(" `-r '%s -> %s'`", rule.Pattern, rule.Replacement) - } - case goimportsName: - text = "File is not `goimports`-ed" - if settings.Goimports.LocalPrefixes != "" { - text += " with -local " + settings.Goimports.LocalPrefixes - } - } - return text -} - -func extractIssuesFromPatch(patch string, lintCtx *linter.Context, linterName string) ([]result.Issue, error) { +func ExtractIssuesFromPatch(patch string, lintCtx *linter.Context, linterName string, formatter fmtTextFormatter) ([]result.Issue, error) { diffs, err := diffpkg.ParseMultiFileDiff([]byte(patch)) if err != nil { return nil, fmt.Errorf("can't parse patch: %w", err) @@ -274,7 +249,7 @@ func extractIssuesFromPatch(patch string, lintCtx *linter.Context, linterName st Filename: d.NewName, Line: change.LineRange.From, }, - Text: getErrorTextForLinter(lintCtx.Settings(), linterName), + Text: formatter(lintCtx.Settings()), Replacement: &change.Replacement, } if change.LineRange.From != change.LineRange.To { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck_common.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/staticcheck_common.go similarity index 92% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck_common.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/staticcheck_common.go index 0eb21ec9c..5b5812c31 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck_common.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/staticcheck_common.go @@ -1,4 +1,4 @@ -package golinters +package internal import ( "strings" @@ -14,7 +14,7 @@ import ( var debugf = logutils.Debug(logutils.DebugKeyMegacheck) -func getGoVersion(settings *config.StaticCheckSettings) string { +func GetGoVersion(settings *config.StaticCheckSettings) string { var goVersion string if settings != nil { goVersion = settings.GoVersion @@ -27,7 +27,7 @@ func getGoVersion(settings *config.StaticCheckSettings) string { return "1.17" } -func setupStaticCheckAnalyzers(src []*lint.Analyzer, goVersion string, checks []string) []*analysis.Analyzer { +func SetupStaticCheckAnalyzers(src []*lint.Analyzer, goVersion string, checks []string) []*analysis.Analyzer { var names []string for _, a := range src { names = append(names, a.Analyzer.Name) @@ -38,7 +38,7 @@ func setupStaticCheckAnalyzers(src []*lint.Analyzer, goVersion string, checks [] var ret []*analysis.Analyzer for _, a := range src { if filter[a.Analyzer.Name] { - setAnalyzerGoVersion(a.Analyzer, goVersion) + SetAnalyzerGoVersion(a.Analyzer, goVersion) ret = append(ret, a.Analyzer) } } @@ -46,7 +46,7 @@ func setupStaticCheckAnalyzers(src []*lint.Analyzer, goVersion string, checks [] return ret } -func setAnalyzerGoVersion(a *analysis.Analyzer, goVersion string) { +func SetAnalyzerGoVersion(a *analysis.Analyzer, goVersion string) { if v := a.Flags.Lookup("go"); v != nil { if err := v.Value.Set(goVersion); err != nil { debugf("Failed to set go version: %s", err) @@ -54,7 +54,7 @@ func setAnalyzerGoVersion(a *analysis.Analyzer, goVersion string) { } } -func staticCheckConfig(settings *config.StaticCheckSettings) *scconfig.Config { +func StaticCheckConfig(settings *config.StaticCheckSettings) *scconfig.Config { var cfg *scconfig.Config if settings == nil || !settings.HasConfiguration() { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/util.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/util.go similarity index 66% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/util.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/util.go index 1044567a9..80b194dd2 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/util.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/internal/util.go @@ -1,4 +1,4 @@ -package golinters +package internal import ( "fmt" @@ -10,7 +10,7 @@ import ( "github.com/golangci/golangci-lint/pkg/config" ) -func formatCode(code string, _ *config.Config) string { +func FormatCode(code string, _ *config.Config) string { if strings.Contains(code, "`") { return code // TODO: properly escape or remove } @@ -18,15 +18,7 @@ func formatCode(code string, _ *config.Config) string { return fmt.Sprintf("`%s`", code) } -func formatCodeBlock(code string, _ *config.Config) string { - if strings.Contains(code, "`") { - return code // TODO: properly escape or remove - } - - return fmt.Sprintf("```\n%s\n```", code) -} - -func getFileNames(pass *analysis.Pass) []string { +func GetFileNames(pass *analysis.Pass) []string { var fileNames []string for _, f := range pass.Files { fileName := pass.Fset.PositionFor(f.Pos(), true).Filename diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/intrange/intrange.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/intrange/intrange.go new file mode 100644 index 000000000..a27569ebb --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/intrange/intrange.go @@ -0,0 +1,19 @@ +package intrange + +import ( + "github.com/ckaznocha/intrange" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := intrange.Analyzer + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ireturn.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ireturn/ireturn.go similarity index 61% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ireturn.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ireturn/ireturn.go index 34dc09d26..57de57111 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ireturn.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/ireturn/ireturn.go @@ -1,4 +1,4 @@ -package golinters +package ireturn import ( "strings" @@ -7,17 +7,18 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewIreturn(settings *config.IreturnSettings) *goanalysis.Linter { +func New(settings *config.IreturnSettings) *goanalysis.Linter { a := analyzer.NewAnalyzer() cfg := map[string]map[string]any{} if settings != nil { cfg[a.Name] = map[string]any{ - "allow": strings.Join(settings.Allow, ","), - "reject": strings.Join(settings.Reject, ","), + "allow": strings.Join(settings.Allow, ","), + "reject": strings.Join(settings.Reject, ","), + "nonolint": true, } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll/lll.go similarity index 82% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll/lll.go index 9ed320120..67f89eecb 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll/lll.go @@ -1,7 +1,8 @@ -package golinters +package lll import ( "bufio" + "errors" "fmt" "go/token" "os" @@ -12,22 +13,22 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const lllName = "lll" +const linterName = "lll" const goCommentDirectivePrefix = "//go:" -//nolint:dupl -func NewLLL(settings *config.LllSettings) *goanalysis.Linter { +func New(settings *config.LllSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: lllName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runLll(pass, settings) @@ -48,7 +49,7 @@ func NewLLL(settings *config.LllSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - lllName, + linterName, "Reports long lines", []*analysis.Analyzer{analyzer}, nil, @@ -58,7 +59,7 @@ func NewLLL(settings *config.LllSettings) *goanalysis.Linter { } func runLll(pass *analysis.Pass, settings *config.LllSettings) ([]goanalysis.Issue, error) { - fileNames := getFileNames(pass) + fileNames := internal.GetFileNames(pass) spaces := strings.Repeat(" ", settings.TabWidth) @@ -82,7 +83,7 @@ func getLLLIssuesForFile(filename string, maxLineLen int, tabSpaces string) ([]r f, err := os.Open(filename) if err != nil { - return nil, fmt.Errorf("can't open file %s: %s", filename, err) + return nil, fmt.Errorf("can't open file %s: %w", filename, err) } defer f.Close() @@ -120,14 +121,14 @@ func getLLLIssuesForFile(filename string, maxLineLen int, tabSpaces string) ([]r Filename: filename, Line: lineNumber, }, - Text: fmt.Sprintf("line is %d characters", lineLen), - FromLinter: lllName, + Text: fmt.Sprintf("the line is %d characters long, which exceeds the maximum of %d characters.", lineLen, maxLineLen), + FromLinter: linterName, }) } } if err := scanner.Err(); err != nil { - if err == bufio.ErrTooLong && maxLineLen < bufio.MaxScanTokenSize { + if errors.Is(err, bufio.ErrTooLong) && maxLineLen < bufio.MaxScanTokenSize { // scanner.Scan() might fail if the line is longer than bufio.MaxScanTokenSize // In the case where the specified maxLineLen is smaller than bufio.MaxScanTokenSize // we can return this line as a long line instead of returning an error. @@ -145,10 +146,10 @@ func getLLLIssuesForFile(filename string, maxLineLen int, tabSpaces string) ([]r Column: 1, }, Text: fmt.Sprintf("line is more than %d characters", bufio.MaxScanTokenSize), - FromLinter: lllName, + FromLinter: linterName, }) } else { - return nil, fmt.Errorf("can't scan file %s: %s", filename, err) + return nil, fmt.Errorf("can't scan file %s: %w", filename, err) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/loggercheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/loggercheck/loggercheck.go similarity index 84% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/loggercheck.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/loggercheck/loggercheck.go index fc29127c3..077e8a512 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/loggercheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/loggercheck/loggercheck.go @@ -1,14 +1,14 @@ -package golinters +package loggercheck import ( "github.com/timonwong/loggercheck" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewLoggerCheck(settings *config.LoggerCheckSettings) *goanalysis.Linter { +func New(settings *config.LoggerCheckSettings) *goanalysis.Linter { var opts []loggercheck.Option if settings != nil { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx/maintidx.go similarity index 76% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx/maintidx.go index 55509d970..08f12369e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx/maintidx.go @@ -1,14 +1,14 @@ -package golinters +package maintidx import ( "github.com/yagipy/maintidx" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewMaintIdx(cfg *config.MaintIdxSettings) *goanalysis.Linter { +func New(cfg *config.MaintIdxSettings) *goanalysis.Linter { analyzer := maintidx.Analyzer cfgMap := map[string]map[string]any{ diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero/makezero.go similarity index 85% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero/makezero.go index a9828629a..ae4bf2184 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero/makezero.go @@ -1,4 +1,4 @@ -package golinters +package makezero import ( "fmt" @@ -8,20 +8,19 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const makezeroName = "makezero" +const linterName = "makezero" -//nolint:dupl -func NewMakezero(settings *config.MakezeroSettings) *goanalysis.Linter { +func New(settings *config.MakezeroSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: makezeroName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues, err := runMakeZero(pass, settings) @@ -42,7 +41,7 @@ func NewMakezero(settings *config.MakezeroSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - makezeroName, + linterName, "Finds slice declarations with non-zero initial length", []*analysis.Analyzer{analyzer}, nil, @@ -66,7 +65,7 @@ func runMakeZero(pass *analysis.Pass, settings *config.MakezeroSettings) ([]goan issues = append(issues, goanalysis.NewIssue(&result.Issue{ Pos: hint.Position(), Text: hint.Details(), - FromLinter: makezeroName, + FromLinter: linterName, }, pass)) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maligned.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maligned.go deleted file mode 100644 index 0455be76a..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maligned.go +++ /dev/null @@ -1,74 +0,0 @@ -package golinters - -import ( - "fmt" - "sync" - - malignedAPI "github.com/golangci/maligned" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const malignedName = "maligned" - -//nolint:dupl -func NewMaligned(settings *config.MalignedSettings) *goanalysis.Linter { - var mu sync.Mutex - var res []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: malignedName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues := runMaligned(pass, settings) - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - res = append(res, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - malignedName, - "Tool to detect Go structs that would take less memory if their fields were sorted", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return res - }).WithLoadMode(goanalysis.LoadModeTypesInfo) -} - -func runMaligned(pass *analysis.Pass, settings *config.MalignedSettings) []goanalysis.Issue { - prog := goanalysis.MakeFakeLoaderProgram(pass) - - malignedIssues := malignedAPI.Run(prog) - if len(malignedIssues) == 0 { - return nil - } - - issues := make([]goanalysis.Issue, 0, len(malignedIssues)) - for _, i := range malignedIssues { - text := fmt.Sprintf("struct of size %d bytes could be of size %d bytes", i.OldSize, i.NewSize) - if settings.SuggestNewOrder { - text += fmt.Sprintf(":\n%s", formatCodeBlock(i.NewStructDef, nil)) - } - - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: text, - FromLinter: malignedName, - }, pass)) - } - - return issues -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mirror.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mirror/mirror.go similarity index 91% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mirror.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mirror/mirror.go index 4adc001a1..34b880b52 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mirror.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mirror/mirror.go @@ -1,4 +1,4 @@ -package golinters +package mirror import ( "sync" @@ -6,12 +6,12 @@ import ( "github.com/butuzov/mirror" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -func NewMirror() *goanalysis.Linter { +func New() *goanalysis.Linter { var ( mu sync.Mutex issues []goanalysis.Issue @@ -39,7 +39,7 @@ func NewMirror() *goanalysis.Linter { Pos: i.Start, } - if len(i.InlineFix) > 0 { + if i.InlineFix != "" { issue.Replacement = &result.Replacement{ Inline: &result.InlineFix{ StartCol: i.Start.Column - 1, diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell/misspell.go similarity index 55% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell/misspell.go index ce2b79a7c..44409cec9 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell/misspell.go @@ -1,35 +1,37 @@ -package golinters +package misspell import ( "fmt" "go/token" "strings" "sync" + "unicode" "github.com/golangci/misspell" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const misspellName = "misspell" +const linterName = "misspell" -func NewMisspell(settings *config.MisspellSettings) *goanalysis.Linter { +func New(settings *config.MisspellSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: misspellName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: goanalysis.DummyRun, } return goanalysis.NewLinter( - misspellName, - "Finds commonly misspelled English words in comments", + linterName, + "Finds commonly misspelled English words", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { @@ -40,7 +42,7 @@ func NewMisspell(settings *config.MisspellSettings) *goanalysis.Linter { return nil, ruleErr } - issues, err := runMisspell(lintCtx, pass, replacer) + issues, err := runMisspell(lintCtx, pass, replacer, settings.Mode) if err != nil { return nil, err } @@ -60,15 +62,16 @@ func NewMisspell(settings *config.MisspellSettings) *goanalysis.Linter { }).WithLoadMode(goanalysis.LoadModeSyntax) } -func runMisspell(lintCtx *linter.Context, pass *analysis.Pass, replacer *misspell.Replacer) ([]goanalysis.Issue, error) { - fileNames := getFileNames(pass) +func runMisspell(lintCtx *linter.Context, pass *analysis.Pass, replacer *misspell.Replacer, mode string) ([]goanalysis.Issue, error) { + fileNames := internal.GetFileNames(pass) var issues []goanalysis.Issue for _, filename := range fileNames { - lintIssues, err := runMisspellOnFile(lintCtx, filename, replacer) + lintIssues, err := runMisspellOnFile(lintCtx, filename, replacer, mode) if err != nil { return nil, err } + for i := range lintIssues { issues = append(issues, goanalysis.NewIssue(&lintIssues[i], pass)) } @@ -94,6 +97,11 @@ func createMisspellReplacer(settings *config.MisspellSettings) (*misspell.Replac return nil, fmt.Errorf("unknown locale: %q", settings.Locale) } + err := appendExtraWords(replacer, settings.ExtraWords) + if err != nil { + return nil, fmt.Errorf("process extra words: %w", err) + } + if len(settings.IgnoreWords) != 0 { replacer.RemoveRule(settings.IgnoreWords) } @@ -104,25 +112,36 @@ func createMisspellReplacer(settings *config.MisspellSettings) (*misspell.Replac return replacer, nil } -func runMisspellOnFile(lintCtx *linter.Context, filename string, replacer *misspell.Replacer) ([]result.Issue, error) { - var res []result.Issue +func runMisspellOnFile(lintCtx *linter.Context, filename string, replacer *misspell.Replacer, mode string) ([]result.Issue, error) { fileContent, err := lintCtx.FileCache.GetFileBytes(filename) if err != nil { - return nil, fmt.Errorf("can't get file %s contents: %s", filename, err) + return nil, fmt.Errorf("can't get file %s contents: %w", filename, err) + } + + // `r.ReplaceGo` doesn't find issues inside strings: it searches only inside comments. + // `r.Replace` searches all words: it treats input as a plain text. + // The standalone misspell tool uses `r.Replace` by default. + var replace func(input string) (string, []misspell.Diff) + switch strings.ToLower(mode) { + case "restricted": + replace = replacer.ReplaceGo + default: + replace = replacer.Replace } - // use r.Replace, not r.ReplaceGo because r.ReplaceGo doesn't find - // issues inside strings: it searches only inside comments. r.Replace - // searches all words: it treats input as a plain text. A standalone misspell - // tool uses r.Replace by default. - _, diffs := replacer.Replace(string(fileContent)) + _, diffs := replace(string(fileContent)) + + var res []result.Issue + for _, diff := range diffs { text := fmt.Sprintf("`%s` is a misspelling of `%s`", diff.Original, diff.Corrected) + pos := token.Position{ Filename: filename, Line: diff.Line, Column: diff.Column + 1, } + replacement := &result.Replacement{ Inline: &result.InlineFix{ StartCol: diff.Column, @@ -134,10 +153,37 @@ func runMisspellOnFile(lintCtx *linter.Context, filename string, replacer *missp res = append(res, result.Issue{ Pos: pos, Text: text, - FromLinter: misspellName, + FromLinter: linterName, Replacement: replacement, }) } return res, nil } + +func appendExtraWords(replacer *misspell.Replacer, extraWords []config.MisspellExtraWords) error { + if len(extraWords) == 0 { + return nil + } + + extra := make([]string, 0, len(extraWords)*2) + + for _, word := range extraWords { + if word.Typo == "" || word.Correction == "" { + return fmt.Errorf("typo (%q) and correction (%q) fields should not be empty", word.Typo, word.Correction) + } + + if strings.ContainsFunc(word.Typo, func(r rune) bool { return !unicode.IsLetter(r) }) { + return fmt.Errorf("the word %q in the 'typo' field should only contain letters", word.Typo) + } + if strings.ContainsFunc(word.Correction, func(r rune) bool { return !unicode.IsLetter(r) }) { + return fmt.Errorf("the word %q in the 'correction' field should only contain letters", word.Correction) + } + + extra = append(extra, strings.ToLower(word.Typo), strings.ToLower(word.Correction)) + } + + replacer.AddRuleList(extra) + + return nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mnd/mnd.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mnd/mnd.go new file mode 100644 index 000000000..9aa8692ff --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/mnd/mnd.go @@ -0,0 +1,63 @@ +package mnd + +import ( + mnd "github.com/tommy-muehle/go-mnd/v2" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.MndSettings) *goanalysis.Linter { + return newMND(mnd.Analyzer, settings, nil) +} + +func NewGoMND(settings *config.GoMndSettings) *goanalysis.Linter { + // shallow copy because mnd.Analyzer is a global variable. + a := new(analysis.Analyzer) + *a = *mnd.Analyzer + + // Used to force the analyzer name to use the same name as the linter. + // This is required to avoid displaying the analyzer name inside the issue text. + a.Name = "gomnd" + + var linterCfg map[string]map[string]any + + if settings != nil && len(settings.Settings) > 0 { + // Convert deprecated setting. + linterCfg = map[string]map[string]any{ + a.Name: settings.Settings["mnd"], + } + } + + return newMND(a, &settings.MndSettings, linterCfg) +} + +func newMND(a *analysis.Analyzer, settings *config.MndSettings, linterCfg map[string]map[string]any) *goanalysis.Linter { + if len(linterCfg) == 0 && settings != nil { + cfg := make(map[string]any) + if len(settings.Checks) > 0 { + cfg["checks"] = settings.Checks + } + if len(settings.IgnoredNumbers) > 0 { + cfg["ignored-numbers"] = settings.IgnoredNumbers + } + if len(settings.IgnoredFiles) > 0 { + cfg["ignored-files"] = settings.IgnoredFiles + } + if len(settings.IgnoredFunctions) > 0 { + cfg["ignored-functions"] = settings.IgnoredFunctions + } + + linterCfg = map[string]map[string]any{ + a.Name: cfg, + } + } + + return goanalysis.NewLinter( + a.Name, + "An analyzer to detect magic numbers.", + []*analysis.Analyzer{a}, + linterCfg, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/musttag.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/musttag/musttag.go similarity index 72% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/musttag.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/musttag/musttag.go index d9ea7efc7..30047abfc 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/musttag.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/musttag/musttag.go @@ -1,14 +1,14 @@ -package golinters +package musttag import ( - "go.tmz.dev/musttag" + "go-simpler.org/musttag" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewMustTag(setting *config.MustTagSettings) *goanalysis.Linter { +func New(setting *config.MustTagSettings) *goanalysis.Linter { var funcs []musttag.Func if setting != nil { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret.go deleted file mode 100644 index d276ac6a9..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret.go +++ /dev/null @@ -1,27 +0,0 @@ -package golinters - -import ( - "github.com/alexkohler/nakedret/v2" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -const nakedretName = "nakedret" - -func NewNakedret(settings *config.NakedretSettings) *goanalysis.Linter { - var maxLines int - if settings != nil { - maxLines = settings.MaxFuncLines - } - - analyzer := nakedret.NakedReturnAnalyzer(uint(maxLines)) - - return goanalysis.NewLinter( - nakedretName, - "Finds naked returns in functions greater than a specified function length", - []*analysis.Analyzer{analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret/nakedret.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret/nakedret.go new file mode 100644 index 000000000..4dd3fd4c3 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret/nakedret.go @@ -0,0 +1,25 @@ +package nakedret + +import ( + "github.com/alexkohler/nakedret/v2" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.NakedretSettings) *goanalysis.Linter { + var maxLines int + if settings != nil { + maxLines = settings.MaxFuncLines + } + + a := nakedret.NakedReturnAnalyzer(uint(maxLines)) + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif/nestif.go similarity index 87% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif/nestif.go index 12ad69ece..43be973b0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif/nestif.go @@ -1,4 +1,4 @@ -package golinters +package nestif import ( "sort" @@ -8,15 +8,14 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const nestifName = "nestif" +const linterName = "nestif" -//nolint:dupl -func NewNestif(settings *config.NestifSettings) *goanalysis.Linter { +func New(settings *config.NestifSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -39,7 +38,7 @@ func NewNestif(settings *config.NestifSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - nestifName, + linterName, "Reports deeply nested if statements", []*analysis.Analyzer{analyzer}, nil, @@ -71,7 +70,7 @@ func runNestIf(pass *analysis.Pass, settings *config.NestifSettings) []goanalysi issues = append(issues, goanalysis.NewIssue(&result.Issue{ Pos: i.Pos, Text: i.Message, - FromLinter: nestifName, + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr/nilerr.go similarity index 72% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr/nilerr.go index 2ea16f2f3..c9e466905 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr/nilerr.go @@ -1,13 +1,13 @@ -package golinters +package nilerr import ( "github.com/gostaticanalysis/nilerr" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewNilErr() *goanalysis.Linter { +func New() *goanalysis.Linter { a := nilerr.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilnil.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilnil/nilnil.go similarity index 77% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilnil.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilnil/nilnil.go index 804557b76..c9237035d 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilnil.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilnil/nilnil.go @@ -1,4 +1,4 @@ -package golinters +package nilnil import ( "strings" @@ -7,10 +7,10 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewNilNil(cfg *config.NilNilSettings) *goanalysis.Linter { +func New(cfg *config.NilNilSettings) *goanalysis.Linter { a := analyzer.New() cfgMap := make(map[string]map[string]any) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nlreturn.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nlreturn/nlreturn.go similarity index 77% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nlreturn.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nlreturn/nlreturn.go index a359548f4..509218808 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nlreturn.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nlreturn/nlreturn.go @@ -1,14 +1,14 @@ -package golinters +package nlreturn import ( "github.com/ssgreg/nlreturn/v2/pkg/nlreturn" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewNLReturn(settings *config.NlreturnSettings) *goanalysis.Linter { +func New(settings *config.NlreturnSettings) *goanalysis.Linter { a := nlreturn.NewAnalyzer() cfg := map[string]map[string]any{} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go deleted file mode 100644 index b7fcd2a73..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go +++ /dev/null @@ -1,17 +0,0 @@ -package golinters - -import ( - "github.com/sonatard/noctx" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewNoctx() *goanalysis.Linter { - return goanalysis.NewLinter( - "noctx", - "noctx finds sending http request without context.Context", - []*analysis.Analyzer{noctx.Analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx/noctx.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx/noctx.go new file mode 100644 index 000000000..8a063c613 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx/noctx.go @@ -0,0 +1,19 @@ +package noctx + +import ( + "github.com/sonatard/noctx" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := noctx.Analyzer + + return goanalysis.NewLinter( + a.Name, + "Finds sending http request without context.Context", + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint.go deleted file mode 100644 index 00ef1f833..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint.go +++ /dev/null @@ -1,105 +0,0 @@ -package golinters - -import ( - "fmt" - "go/ast" - "sync" - - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/golinters/nolintlint" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const NoLintLintName = "nolintlint" - -//nolint:dupl -func NewNoLintLint(settings *config.NoLintLintSettings) *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: NoLintLintName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues, err := runNoLintLint(pass, settings) - if err != nil { - return nil, err - } - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - NoLintLintName, - "Reports ill-formed or insufficient nolint directives", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) -} - -func runNoLintLint(pass *analysis.Pass, settings *config.NoLintLintSettings) ([]goanalysis.Issue, error) { - var needs nolintlint.Needs - if settings.RequireExplanation { - needs |= nolintlint.NeedsExplanation - } - if settings.RequireSpecific { - needs |= nolintlint.NeedsSpecific - } - if !settings.AllowUnused { - needs |= nolintlint.NeedsUnused - } - - lnt, err := nolintlint.NewLinter(needs, settings.AllowNoExplanation) - if err != nil { - return nil, err - } - - nodes := make([]ast.Node, 0, len(pass.Files)) - for _, n := range pass.Files { - nodes = append(nodes, n) - } - - lintIssues, err := lnt.Run(pass.Fset, nodes...) - if err != nil { - return nil, fmt.Errorf("linter failed to run: %s", err) - } - - var issues []goanalysis.Issue - - for _, i := range lintIssues { - expectNoLint := false - var expectedNolintLinter string - if ii, ok := i.(nolintlint.UnusedCandidate); ok { - expectedNolintLinter = ii.ExpectedLinter - expectNoLint = true - } - - issue := &result.Issue{ - FromLinter: NoLintLintName, - Text: i.Details(), - Pos: i.Position(), - ExpectNoLint: expectNoLint, - ExpectedNoLintLinter: expectedNolintLinter, - Replacement: i.Replacement(), - } - - issues = append(issues, goanalysis.NewIssue(issue, pass)) - } - - return issues, nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/README.md b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal/README.md similarity index 81% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/README.md rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal/README.md index 1643df7a5..e4d48f012 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/README.md +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal/README.md @@ -1,7 +1,7 @@ # nolintlint nolintlint is a Go static analysis tool to find ill-formed or insufficiently explained `//nolint` directives for golangci-lint -(or any other linter, using this package) +(or any other linter, using this package) ## Purpose @@ -15,7 +15,7 @@ func hash(data []byte) []byte { } ``` -In the above case, nolint directives are present but the user has no idea why this is being done or which linter +In the above case, nolint directives are present, but the user has no idea why this is being done or which linter is being suppressed (in this case, gosec recommends against use of md5). `nolintlint` can require that the code provide an explanation, which might look as follows: ```Go @@ -26,6 +26,6 @@ func hash(data []byte) []byte { } ``` -`nolintlint` can also identify cases where you may have written `// nolint`. Finally `nolintlint`, can also enforce that you +`nolintlint` can also identify cases where you may have written `// nolint`. Finally, `nolintlint`, can also enforce that you use the machine-readable nolint directive format `//nolint:all` and that you mention what linter is being suppressed, as shown above when we write `//nolint:gosec`. diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal/nolintlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal/nolintlint.go new file mode 100644 index 000000000..5fed41cfd --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal/nolintlint.go @@ -0,0 +1,304 @@ +// Package internal provides a linter to ensure that all //nolint directives are followed by explanations +package internal + +import ( + "fmt" + "go/ast" + "go/token" + "regexp" + "strings" + "unicode" + + "github.com/golangci/golangci-lint/pkg/result" +) + +type BaseIssue struct { + fullDirective string + directiveWithOptionalLeadingSpace string + position token.Position + replacement *result.Replacement +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (b BaseIssue) Position() token.Position { + return b.position +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (b BaseIssue) Replacement() *result.Replacement { + return b.replacement +} + +type ExtraLeadingSpace struct { + BaseIssue +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (i ExtraLeadingSpace) Details() string { + return fmt.Sprintf("directive `%s` should not have more than one leading space", i.fullDirective) +} + +func (i ExtraLeadingSpace) String() string { return toString(i) } + +type NotMachine struct { + BaseIssue +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (i NotMachine) Details() string { + expected := i.fullDirective[:2] + strings.TrimLeftFunc(i.fullDirective[2:], unicode.IsSpace) + return fmt.Sprintf("directive `%s` should be written without leading space as `%s`", + i.fullDirective, expected) +} + +func (i NotMachine) String() string { return toString(i) } + +type NotSpecific struct { + BaseIssue +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (i NotSpecific) Details() string { + return fmt.Sprintf("directive `%s` should mention specific linter such as `%s:my-linter`", + i.fullDirective, i.directiveWithOptionalLeadingSpace) +} + +func (i NotSpecific) String() string { return toString(i) } + +type ParseError struct { + BaseIssue +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (i ParseError) Details() string { + return fmt.Sprintf("directive `%s` should match `%s[:] [// ]`", + i.fullDirective, + i.directiveWithOptionalLeadingSpace) +} + +func (i ParseError) String() string { return toString(i) } + +type NoExplanation struct { + BaseIssue + fullDirectiveWithoutExplanation string +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (i NoExplanation) Details() string { + return fmt.Sprintf("directive `%s` should provide explanation such as `%s // this is why`", + i.fullDirective, i.fullDirectiveWithoutExplanation) +} + +func (i NoExplanation) String() string { return toString(i) } + +type UnusedCandidate struct { + BaseIssue + ExpectedLinter string +} + +//nolint:gocritic // TODO(ldez) must be change in the future. +func (i UnusedCandidate) Details() string { + details := fmt.Sprintf("directive `%s` is unused", i.fullDirective) + if i.ExpectedLinter != "" { + details += fmt.Sprintf(" for linter %q", i.ExpectedLinter) + } + return details +} + +func (i UnusedCandidate) String() string { return toString(i) } + +func toString(issue Issue) string { + return fmt.Sprintf("%s at %s", issue.Details(), issue.Position()) +} + +type Issue interface { + Details() string + Position() token.Position + String() string + Replacement() *result.Replacement +} + +type Needs uint + +const ( + NeedsMachineOnly Needs = 1 << iota + NeedsSpecific + NeedsExplanation + NeedsUnused + NeedsAll = NeedsMachineOnly | NeedsSpecific | NeedsExplanation +) + +var commentPattern = regexp.MustCompile(`^//\s*(nolint)(:\s*[\w-]+\s*(?:,\s*[\w-]+\s*)*)?\b`) + +// matches a complete nolint directive +var fullDirectivePattern = regexp.MustCompile(`^//\s*nolint(?::(\s*[\w-]+\s*(?:,\s*[\w-]+\s*)*))?\s*(//.*)?\s*\n?$`) + +type Linter struct { + needs Needs // indicates which linter checks to perform + excludeByLinter map[string]bool +} + +// NewLinter creates a linter that enforces that the provided directives fulfill the provided requirements +func NewLinter(needs Needs, excludes []string) (*Linter, error) { + excludeByName := make(map[string]bool) + for _, e := range excludes { + excludeByName[e] = true + } + + return &Linter{ + needs: needs | NeedsMachineOnly, + excludeByLinter: excludeByName, + }, nil +} + +var ( + leadingSpacePattern = regexp.MustCompile(`^//(\s*)`) + trailingBlankExplanation = regexp.MustCompile(`\s*(//\s*)?$`) +) + +//nolint:funlen,gocyclo // the function is going to be refactored in the future +func (l Linter) Run(fset *token.FileSet, nodes ...ast.Node) ([]Issue, error) { + var issues []Issue + + for _, node := range nodes { + file, ok := node.(*ast.File) + if !ok { + continue + } + + for _, c := range file.Comments { + for _, comment := range c.List { + if !commentPattern.MatchString(comment.Text) { + continue + } + + // check for a space between the "//" and the directive + leadingSpaceMatches := leadingSpacePattern.FindStringSubmatch(comment.Text) + + var leadingSpace string + if len(leadingSpaceMatches) > 0 { + leadingSpace = leadingSpaceMatches[1] + } + + directiveWithOptionalLeadingSpace := "//" + if leadingSpace != "" { + directiveWithOptionalLeadingSpace += " " + } + + split := strings.Split(strings.SplitN(comment.Text, ":", 2)[0], "//") + directiveWithOptionalLeadingSpace += strings.TrimSpace(split[1]) + + pos := fset.Position(comment.Pos()) + end := fset.Position(comment.End()) + + base := BaseIssue{ + fullDirective: comment.Text, + directiveWithOptionalLeadingSpace: directiveWithOptionalLeadingSpace, + position: pos, + } + + // check for, report and eliminate leading spaces, so we can check for other issues + if leadingSpace != "" { + removeWhitespace := &result.Replacement{ + Inline: &result.InlineFix{ + StartCol: pos.Column + 1, + Length: len(leadingSpace), + NewString: "", + }, + } + if (l.needs & NeedsMachineOnly) != 0 { + issue := NotMachine{BaseIssue: base} + issue.BaseIssue.replacement = removeWhitespace + issues = append(issues, issue) + } else if len(leadingSpace) > 1 { + issue := ExtraLeadingSpace{BaseIssue: base} + issue.BaseIssue.replacement = removeWhitespace + issue.BaseIssue.replacement.Inline.NewString = " " // assume a single space was intended + issues = append(issues, issue) + } + } + + fullMatches := fullDirectivePattern.FindStringSubmatch(comment.Text) + if len(fullMatches) == 0 { + issues = append(issues, ParseError{BaseIssue: base}) + continue + } + + lintersText, explanation := fullMatches[1], fullMatches[2] + + var linters []string + if lintersText != "" && !strings.HasPrefix(lintersText, "all") { + lls := strings.Split(lintersText, ",") + linters = make([]string, 0, len(lls)) + rangeStart := (pos.Column - 1) + len("//") + len(leadingSpace) + len("nolint:") + for i, ll := range lls { + rangeEnd := rangeStart + len(ll) + if i < len(lls)-1 { + rangeEnd++ // include trailing comma + } + trimmedLinterName := strings.TrimSpace(ll) + if trimmedLinterName != "" { + linters = append(linters, trimmedLinterName) + } + rangeStart = rangeEnd + } + } + + if (l.needs & NeedsSpecific) != 0 { + if len(linters) == 0 { + issues = append(issues, NotSpecific{BaseIssue: base}) + } + } + + // when detecting unused directives, we send all the directives through and filter them out in the nolint processor + if (l.needs & NeedsUnused) != 0 { + removeNolintCompletely := &result.Replacement{ + Inline: &result.InlineFix{ + StartCol: pos.Column - 1, + Length: end.Column - pos.Column, + NewString: "", + }, + } + + if len(linters) == 0 { + issue := UnusedCandidate{BaseIssue: base} + issue.replacement = removeNolintCompletely + issues = append(issues, issue) + } else { + for _, linter := range linters { + issue := UnusedCandidate{BaseIssue: base, ExpectedLinter: linter} + // only offer replacement if there is a single linter + // because of issues around commas and the possibility of all + // linters being removed + if len(linters) == 1 { + issue.replacement = removeNolintCompletely + } + issues = append(issues, issue) + } + } + } + + if (l.needs&NeedsExplanation) != 0 && (explanation == "" || strings.TrimSpace(explanation) == "//") { + needsExplanation := len(linters) == 0 // if no linters are mentioned, we must have explanation + // otherwise, check if we are excluding all the mentioned linters + for _, ll := range linters { + if !l.excludeByLinter[ll] { // if a linter does require explanation + needsExplanation = true + break + } + } + + if needsExplanation { + fullDirectiveWithoutExplanation := trailingBlankExplanation.ReplaceAllString(comment.Text, "") + issues = append(issues, NoExplanation{ + BaseIssue: base, + fullDirectiveWithoutExplanation: fullDirectiveWithoutExplanation, + }) + } + } + } + } + } + + return issues, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/nolintlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/nolintlint.go index 9c6b10f38..9f04454a5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/nolintlint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/nolintlint.go @@ -1,307 +1,103 @@ -// Package nolintlint provides a linter to ensure that all //nolint directives are followed by explanations package nolintlint import ( "fmt" "go/ast" - "go/token" - "regexp" - "strings" - "unicode" + "sync" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal" + "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -type BaseIssue struct { - fullDirective string - directiveWithOptionalLeadingSpace string - position token.Position - replacement *result.Replacement -} - -//nolint:gocritic // TODO must be change in the future. -func (b BaseIssue) Position() token.Position { - return b.position -} - -//nolint:gocritic // TODO must be change in the future. -func (b BaseIssue) Replacement() *result.Replacement { - return b.replacement -} - -type ExtraLeadingSpace struct { - BaseIssue -} - -//nolint:gocritic // TODO must be change in the future. -func (i ExtraLeadingSpace) Details() string { - return fmt.Sprintf("directive `%s` should not have more than one leading space", i.fullDirective) -} - -//nolint:gocritic // TODO must be change in the future. -func (i ExtraLeadingSpace) String() string { return toString(i) } - -type NotMachine struct { - BaseIssue -} - -//nolint:gocritic // TODO must be change in the future. -func (i NotMachine) Details() string { - expected := i.fullDirective[:2] + strings.TrimLeftFunc(i.fullDirective[2:], unicode.IsSpace) - return fmt.Sprintf("directive `%s` should be written without leading space as `%s`", - i.fullDirective, expected) -} - -//nolint:gocritic // TODO must be change in the future. -func (i NotMachine) String() string { return toString(i) } +const LinterName = "nolintlint" -type NotSpecific struct { - BaseIssue -} - -//nolint:gocritic // TODO must be change in the future. -func (i NotSpecific) Details() string { - return fmt.Sprintf("directive `%s` should mention specific linter such as `%s:my-linter`", - i.fullDirective, i.directiveWithOptionalLeadingSpace) -} - -//nolint:gocritic // TODO must be change in the future. -func (i NotSpecific) String() string { return toString(i) } - -type ParseError struct { - BaseIssue -} - -//nolint:gocritic // TODO must be change in the future. -func (i ParseError) Details() string { - return fmt.Sprintf("directive `%s` should match `%s[:] [// ]`", - i.fullDirective, - i.directiveWithOptionalLeadingSpace) -} +func New(settings *config.NoLintLintSettings) *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue -//nolint:gocritic // TODO must be change in the future. -func (i ParseError) String() string { return toString(i) } - -type NoExplanation struct { - BaseIssue - fullDirectiveWithoutExplanation string -} - -//nolint:gocritic // TODO must be change in the future. -func (i NoExplanation) Details() string { - return fmt.Sprintf("directive `%s` should provide explanation such as `%s // this is why`", - i.fullDirective, i.fullDirectiveWithoutExplanation) -} + analyzer := &analysis.Analyzer{ + Name: LinterName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (any, error) { + issues, err := runNoLintLint(pass, settings) + if err != nil { + return nil, err + } -//nolint:gocritic // TODO must be change in the future. -func (i NoExplanation) String() string { return toString(i) } + if len(issues) == 0 { + return nil, nil + } -type UnusedCandidate struct { - BaseIssue - ExpectedLinter string -} + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() -//nolint:gocritic // TODO must be change in the future. -func (i UnusedCandidate) Details() string { - details := fmt.Sprintf("directive `%s` is unused", i.fullDirective) - if i.ExpectedLinter != "" { - details += fmt.Sprintf(" for linter %q", i.ExpectedLinter) + return nil, nil + }, } - return details -} -//nolint:gocritic // TODO must be change in the future. -func (i UnusedCandidate) String() string { return toString(i) } - -func toString(i Issue) string { - return fmt.Sprintf("%s at %s", i.Details(), i.Position()) -} - -type Issue interface { - Details() string - Position() token.Position - String() string - Replacement() *result.Replacement + return goanalysis.NewLinter( + LinterName, + "Reports ill-formed or insufficient nolint directives", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) } -type Needs uint - -const ( - NeedsMachineOnly Needs = 1 << iota - NeedsSpecific - NeedsExplanation - NeedsUnused - NeedsAll = NeedsMachineOnly | NeedsSpecific | NeedsExplanation -) - -var commentPattern = regexp.MustCompile(`^//\s*(nolint)(:\s*[\w-]+\s*(?:,\s*[\w-]+\s*)*)?\b`) - -// matches a complete nolint directive -var fullDirectivePattern = regexp.MustCompile(`^//\s*nolint(?::(\s*[\w-]+\s*(?:,\s*[\w-]+\s*)*))?\s*(//.*)?\s*\n?$`) - -type Linter struct { - needs Needs // indicates which linter checks to perform - excludeByLinter map[string]bool -} +func runNoLintLint(pass *analysis.Pass, settings *config.NoLintLintSettings) ([]goanalysis.Issue, error) { + var needs internal.Needs + if settings.RequireExplanation { + needs |= internal.NeedsExplanation + } + if settings.RequireSpecific { + needs |= internal.NeedsSpecific + } + if !settings.AllowUnused { + needs |= internal.NeedsUnused + } -// NewLinter creates a linter that enforces that the provided directives fulfill the provided requirements -func NewLinter(needs Needs, excludes []string) (*Linter, error) { - excludeByName := make(map[string]bool) - for _, e := range excludes { - excludeByName[e] = true + lnt, err := internal.NewLinter(needs, settings.AllowNoExplanation) + if err != nil { + return nil, err } - return &Linter{ - needs: needs | NeedsMachineOnly, - excludeByLinter: excludeByName, - }, nil -} + nodes := make([]ast.Node, 0, len(pass.Files)) + for _, n := range pass.Files { + nodes = append(nodes, n) + } -var leadingSpacePattern = regexp.MustCompile(`^//(\s*)`) -var trailingBlankExplanation = regexp.MustCompile(`\s*(//\s*)?$`) + lintIssues, err := lnt.Run(pass.Fset, nodes...) + if err != nil { + return nil, fmt.Errorf("linter failed to run: %w", err) + } -//nolint:funlen,gocyclo -func (l Linter) Run(fset *token.FileSet, nodes ...ast.Node) ([]Issue, error) { - var issues []Issue + var issues []goanalysis.Issue - for _, node := range nodes { - file, ok := node.(*ast.File) - if !ok { - continue + for _, i := range lintIssues { + expectNoLint := false + var expectedNolintLinter string + if ii, ok := i.(internal.UnusedCandidate); ok { + expectedNolintLinter = ii.ExpectedLinter + expectNoLint = true } - for _, c := range file.Comments { - for _, comment := range c.List { - if !commentPattern.MatchString(comment.Text) { - continue - } - - // check for a space between the "//" and the directive - leadingSpaceMatches := leadingSpacePattern.FindStringSubmatch(comment.Text) - - var leadingSpace string - if len(leadingSpaceMatches) > 0 { - leadingSpace = leadingSpaceMatches[1] - } - - directiveWithOptionalLeadingSpace := "//" - if len(leadingSpace) > 0 { - directiveWithOptionalLeadingSpace += " " - } - - split := strings.Split(strings.SplitN(comment.Text, ":", 2)[0], "//") - directiveWithOptionalLeadingSpace += strings.TrimSpace(split[1]) - - pos := fset.Position(comment.Pos()) - end := fset.Position(comment.End()) - - base := BaseIssue{ - fullDirective: comment.Text, - directiveWithOptionalLeadingSpace: directiveWithOptionalLeadingSpace, - position: pos, - } - - // check for, report and eliminate leading spaces, so we can check for other issues - if len(leadingSpace) > 0 { - removeWhitespace := &result.Replacement{ - Inline: &result.InlineFix{ - StartCol: pos.Column + 1, - Length: len(leadingSpace), - NewString: "", - }, - } - if (l.needs & NeedsMachineOnly) != 0 { - issue := NotMachine{BaseIssue: base} - issue.BaseIssue.replacement = removeWhitespace - issues = append(issues, issue) - } else if len(leadingSpace) > 1 { - issue := ExtraLeadingSpace{BaseIssue: base} - issue.BaseIssue.replacement = removeWhitespace - issue.BaseIssue.replacement.Inline.NewString = " " // assume a single space was intended - issues = append(issues, issue) - } - } - - fullMatches := fullDirectivePattern.FindStringSubmatch(comment.Text) - if len(fullMatches) == 0 { - issues = append(issues, ParseError{BaseIssue: base}) - continue - } - - lintersText, explanation := fullMatches[1], fullMatches[2] - - var linters []string - if len(lintersText) > 0 && !strings.HasPrefix(lintersText, "all") { - lls := strings.Split(lintersText, ",") - linters = make([]string, 0, len(lls)) - rangeStart := (pos.Column - 1) + len("//") + len(leadingSpace) + len("nolint:") - for i, ll := range lls { - rangeEnd := rangeStart + len(ll) - if i < len(lls)-1 { - rangeEnd++ // include trailing comma - } - trimmedLinterName := strings.TrimSpace(ll) - if trimmedLinterName != "" { - linters = append(linters, trimmedLinterName) - } - rangeStart = rangeEnd - } - } - - if (l.needs & NeedsSpecific) != 0 { - if len(linters) == 0 { - issues = append(issues, NotSpecific{BaseIssue: base}) - } - } - - // when detecting unused directives, we send all the directives through and filter them out in the nolint processor - if (l.needs & NeedsUnused) != 0 { - removeNolintCompletely := &result.Replacement{ - Inline: &result.InlineFix{ - StartCol: pos.Column - 1, - Length: end.Column - pos.Column, - NewString: "", - }, - } - - if len(linters) == 0 { - issue := UnusedCandidate{BaseIssue: base} - issue.replacement = removeNolintCompletely - issues = append(issues, issue) - } else { - for _, linter := range linters { - issue := UnusedCandidate{BaseIssue: base, ExpectedLinter: linter} - // only offer replacement if there is a single linter - // because of issues around commas and the possibility of all - // linters being removed - if len(linters) == 1 { - issue.replacement = removeNolintCompletely - } - issues = append(issues, issue) - } - } - } - - if (l.needs&NeedsExplanation) != 0 && (explanation == "" || strings.TrimSpace(explanation) == "//") { - needsExplanation := len(linters) == 0 // if no linters are mentioned, we must have explanation - // otherwise, check if we are excluding all the mentioned linters - for _, ll := range linters { - if !l.excludeByLinter[ll] { // if a linter does require explanation - needsExplanation = true - break - } - } - - if needsExplanation { - fullDirectiveWithoutExplanation := trailingBlankExplanation.ReplaceAllString(comment.Text, "") - issues = append(issues, NoExplanation{ - BaseIssue: base, - fullDirectiveWithoutExplanation: fullDirectiveWithoutExplanation, - }) - } - } - } + issue := &result.Issue{ + FromLinter: LinterName, + Text: i.Details(), + Pos: i.Position(), + ExpectNoLint: expectNoLint, + ExpectedNoLintLinter: expectedNolintLinter, + Replacement: i.Replacement(), } + + issues = append(issues, goanalysis.NewIssue(issue, pass)) } return issues, nil diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns/nonamedreturns.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns/nonamedreturns.go index 7856f6d61..42a618e64 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns/nonamedreturns.go @@ -1,14 +1,14 @@ -package golinters +package nonamedreturns import ( "github.com/firefart/nonamedreturns/analyzer" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewNoNamedReturns(settings *config.NoNamedReturnsSettings) *goanalysis.Linter { +func New(settings *config.NoNamedReturnsSettings) *goanalysis.Linter { a := analyzer.Analyzer var cfg map[string]map[string]any diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosnakecase.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosnakecase.go deleted file mode 100644 index 26d5d6d4c..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosnakecase.go +++ /dev/null @@ -1,19 +0,0 @@ -package golinters - -import ( - "github.com/sivchari/nosnakecase" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewNoSnakeCase() *goanalysis.Linter { - a := nosnakecase.Analyzer - - return goanalysis.NewLinter( - a.Name, - a.Doc, - []*analysis.Analyzer{a}, - nil, - ).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport/nosprintfhostport.go similarity index 66% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport/nosprintfhostport.go index a63b9bb5f..8f06ae1f6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport/nosprintfhostport.go @@ -1,13 +1,13 @@ -package golinters +package nosprintfhostport import ( "github.com/stbenjam/no-sprintf-host-port/pkg/analyzer" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewNoSprintfHostPort() *goanalysis.Linter { +func New() *goanalysis.Linter { a := analyzer.Analyzer return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest.go deleted file mode 100644 index 4c03952c1..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest.go +++ /dev/null @@ -1,30 +0,0 @@ -package golinters - -import ( - "github.com/kunwardeep/paralleltest/pkg/paralleltest" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewParallelTest(settings *config.ParallelTestSettings) *goanalysis.Linter { - a := paralleltest.NewAnalyzer() - - var cfg map[string]map[string]any - if settings != nil { - cfg = map[string]map[string]any{ - a.Name: { - "i": settings.IgnoreMissing, - "ignoremissingsubtests": settings.IgnoreMissingSubtests, - }, - } - } - - return goanalysis.NewLinter( - "paralleltest", - "paralleltest detects missing usage of t.Parallel() method in your Go test", - []*analysis.Analyzer{a}, - cfg, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest/paralleltest.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest/paralleltest.go new file mode 100644 index 000000000..0c908fa38 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest/paralleltest.go @@ -0,0 +1,34 @@ +package paralleltest + +import ( + "github.com/kunwardeep/paralleltest/pkg/paralleltest" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.ParallelTestSettings) *goanalysis.Linter { + a := paralleltest.NewAnalyzer() + + var cfg map[string]map[string]any + if settings != nil { + d := map[string]any{ + "i": settings.IgnoreMissing, + "ignoremissingsubtests": settings.IgnoreMissingSubtests, + } + + if config.IsGoGreaterThanOrEqual(settings.Go, "1.22") { + d["ignoreloopVar"] = true + } + + cfg = map[string]map[string]any{a.Name: d} + } + + return goanalysis.NewLinter( + a.Name, + "Detects missing usage of t.Parallel() method in your Go test", + []*analysis.Analyzer{a}, + cfg, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/perfsprint/perfsprint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/perfsprint/perfsprint.go new file mode 100644 index 000000000..a4ead1914 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/perfsprint/perfsprint.go @@ -0,0 +1,32 @@ +package perfsprint + +import ( + "github.com/catenacyber/perfsprint/analyzer" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.PerfSprintSettings) *goanalysis.Linter { + a := analyzer.New() + + cfg := map[string]map[string]any{ + a.Name: {"fiximports": false}, + } + + if settings != nil { + cfg[a.Name]["int-conversion"] = settings.IntConversion + cfg[a.Name]["err-error"] = settings.ErrError + cfg[a.Name]["errorf"] = settings.ErrorF + cfg[a.Name]["sprintf1"] = settings.SprintF1 + cfg[a.Name]["strconcat"] = settings.StrConcat + } + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + cfg, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc/prealloc.go similarity index 76% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc/prealloc.go index f48d57562..ce7ff9d59 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc/prealloc.go @@ -1,4 +1,4 @@ -package golinters +package prealloc import ( "fmt" @@ -8,20 +8,20 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const preallocName = "prealloc" +const linterName = "prealloc" -//nolint:dupl -func NewPreAlloc(settings *config.PreallocSettings) *goanalysis.Linter { +func New(settings *config.PreallocSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: preallocName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues := runPreAlloc(pass, settings) @@ -39,7 +39,7 @@ func NewPreAlloc(settings *config.PreallocSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - preallocName, + linterName, "Finds slice declarations that could potentially be pre-allocated", []*analysis.Analyzer{analyzer}, nil, @@ -56,8 +56,8 @@ func runPreAlloc(pass *analysis.Pass, settings *config.PreallocSettings) []goana for _, hint := range hints { issues = append(issues, goanalysis.NewIssue(&result.Issue{ Pos: pass.Fset.Position(hint.Pos), - Text: fmt.Sprintf("Consider pre-allocating %s", formatCode(hint.DeclaredSliceName, nil)), - FromLinter: preallocName, + Text: fmt.Sprintf("Consider pre-allocating %s", internal.FormatCode(hint.DeclaredSliceName, nil)), + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/predeclared.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/predeclared/predeclared.go similarity index 76% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/predeclared.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/predeclared/predeclared.go index d3c25e274..b8d189fd5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/predeclared.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/predeclared/predeclared.go @@ -1,14 +1,14 @@ -package golinters +package predeclared import ( "github.com/nishanths/predeclared/passes/predeclared" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewPredeclared(settings *config.PredeclaredSettings) *goanalysis.Linter { +func New(settings *config.PredeclaredSettings) *goanalysis.Linter { a := predeclared.Analyzer var cfg map[string]map[string]any diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter/promlinter.go similarity index 85% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter/promlinter.go index 381c57489..5decbbc7c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter/promlinter.go @@ -1,4 +1,4 @@ -package golinters +package promlinter import ( "fmt" @@ -8,14 +8,14 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const promlinterName = "promlinter" +const linterName = "promlinter" -func NewPromlinter(settings *config.PromlinterSettings) *goanalysis.Linter { +func New(settings *config.PromlinterSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -28,7 +28,7 @@ func NewPromlinter(settings *config.PromlinterSettings) *goanalysis.Linter { } analyzer := &analysis.Analyzer{ - Name: promlinterName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { issues := runPromLinter(pass, promSettings) @@ -46,7 +46,7 @@ func NewPromlinter(settings *config.PromlinterSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - promlinterName, + linterName, "Check Prometheus metrics naming via promlint", []*analysis.Analyzer{analyzer}, nil, @@ -67,7 +67,7 @@ func runPromLinter(pass *analysis.Pass, promSettings promlinter.Setting) []goana issue := result.Issue{ Pos: i.Pos, Text: fmt.Sprintf("Metric: %s Error: %s", i.Metric, i.Text), - FromLinter: promlinterName, + FromLinter: linterName, } issues[k] = goanalysis.NewIssue(&issue, pass) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/protogetter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/protogetter/protogetter.go similarity index 63% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/protogetter.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/protogetter/protogetter.go index 23325ad55..302ce67b8 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/protogetter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/protogetter/protogetter.go @@ -1,4 +1,4 @@ -package golinters +package protogetter import ( "sync" @@ -6,18 +6,33 @@ import ( "github.com/ghostiam/protogetter" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -func NewProtoGetter() *goanalysis.Linter { +func New(settings *config.ProtoGetterSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue - a := protogetter.NewAnalyzer() + var cfg protogetter.Config + if settings != nil { + cfg = protogetter.Config{ + SkipGeneratedBy: settings.SkipGeneratedBy, + SkipFiles: settings.SkipFiles, + SkipAnyGenerated: settings.SkipAnyGenerated, + ReplaceFirstArgInAppend: settings.ReplaceFirstArgInAppend, + } + } + cfg.Mode = protogetter.GolangciLintMode + + a := protogetter.NewAnalyzer(&cfg) a.Run = func(pass *analysis.Pass) (any, error) { - pgIssues := protogetter.Run(pass, protogetter.GolangciLintMode) + pgIssues, err := protogetter.Run(pass, &cfg) + if err != nil { + return nil, err + } issues := make([]goanalysis.Issue, len(pgIssues)) for i, issue := range pgIssues { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/reassign.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/reassign/reassign.go similarity index 78% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/reassign.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/reassign/reassign.go index a6dd67053..cfc85635e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/reassign.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/reassign/reassign.go @@ -1,4 +1,4 @@ -package golinters +package reassign import ( "fmt" @@ -8,10 +8,10 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewReassign(settings *config.ReassignSettings) *goanalysis.Linter { +func New(settings *config.ReassignSettings) *goanalysis.Linter { a := reassign.NewAnalyzer() var cfg map[string]map[string]any diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive/revive.go similarity index 77% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive/revive.go index 28231957c..90ce15db6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive/revive.go @@ -1,4 +1,4 @@ -package golinters +package revive import ( "bytes" @@ -10,21 +10,23 @@ import ( "sync" "github.com/BurntSushi/toml" + hcversion "github.com/hashicorp/go-version" reviveConfig "github.com/mgechev/revive/config" "github.com/mgechev/revive/lint" "github.com/mgechev/revive/rule" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" ) -const reviveName = "revive" +const linterName = "revive" -var reviveDebugf = logutils.Debug(logutils.DebugKeyRevive) +var debugf = logutils.Debug(logutils.DebugKeyRevive) // jsonObject defines a JSON object of a failure type jsonObject struct { @@ -32,10 +34,7 @@ type jsonObject struct { lint.Failure `json:",inline"` } -// NewRevive returns a new Revive linter. -// -//nolint:dupl -func NewRevive(settings *config.ReviveSettings) *goanalysis.Linter { +func New(settings *config.ReviveSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -46,13 +45,19 @@ func NewRevive(settings *config.ReviveSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - reviveName, + linterName, "Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { + w, err := newWrapper(settings) + if err != nil { + lintCtx.Log.Errorf("setup revive: %v", err) + return + } + analyzer.Run = func(pass *analysis.Pass) (any, error) { - issues, err := runRevive(lintCtx, pass, settings) + issues, err := w.run(lintCtx, pass) if err != nil { return nil, err } @@ -72,27 +77,46 @@ func NewRevive(settings *config.ReviveSettings) *goanalysis.Linter { }).WithLoadMode(goanalysis.LoadModeSyntax) } -func runRevive(lintCtx *linter.Context, pass *analysis.Pass, settings *config.ReviveSettings) ([]goanalysis.Issue, error) { - packages := [][]string{getFileNames(pass)} +type wrapper struct { + revive lint.Linter + formatter lint.Formatter + lintingRules []lint.Rule + conf *lint.Config +} - conf, err := getReviveConfig(settings) +func newWrapper(settings *config.ReviveSettings) (*wrapper, error) { + conf, err := getConfig(settings) if err != nil { return nil, err } - formatter, err := reviveConfig.GetFormatter("json") + conf.GoVersion, err = hcversion.NewVersion(settings.Go) if err != nil { return nil, err } - revive := lint.New(os.ReadFile, settings.MaxOpenFiles) + formatter, err := reviveConfig.GetFormatter("json") + if err != nil { + return nil, err + } lintingRules, err := reviveConfig.GetLintingRules(conf, []lint.Rule{}) if err != nil { return nil, err } - failures, err := revive.Lint(packages, lintingRules, *conf) + return &wrapper{ + revive: lint.New(os.ReadFile, settings.MaxOpenFiles), + formatter: formatter, + lintingRules: lintingRules, + conf: conf, + }, nil +} + +func (w *wrapper) run(lintCtx *linter.Context, pass *analysis.Pass) ([]goanalysis.Issue, error) { + packages := [][]string{internal.GetFileNames(pass)} + + failures, err := w.revive.Lint(packages, w.lintingRules, *w.conf) if err != nil { return nil, err } @@ -102,7 +126,7 @@ func runRevive(lintCtx *linter.Context, pass *analysis.Pass, settings *config.Re var output string go func() { - output, err = formatter.Format(formatChan, *conf) + output, err = w.formatter.Format(formatChan, *w.conf) if err != nil { lintCtx.Log.Errorf("Format error: %v", err) } @@ -110,7 +134,7 @@ func runRevive(lintCtx *linter.Context, pass *analysis.Pass, settings *config.Re }() for f := range failures { - if f.Confidence < conf.Confidence { + if f.Confidence < w.conf.Confidence { continue } @@ -128,13 +152,13 @@ func runRevive(lintCtx *linter.Context, pass *analysis.Pass, settings *config.Re var issues []goanalysis.Issue for i := range results { - issues = append(issues, reviveToIssue(pass, &results[i])) + issues = append(issues, toIssue(pass, &results[i])) } return issues, nil } -func reviveToIssue(pass *analysis.Pass, object *jsonObject) goanalysis.Issue { +func toIssue(pass *analysis.Pass, object *jsonObject) goanalysis.Issue { lineRangeTo := object.Position.End.Line if object.RuleName == (&rule.ExportedRule{}).Name() { lineRangeTo = object.Position.Start.Line @@ -153,18 +177,22 @@ func reviveToIssue(pass *analysis.Pass, object *jsonObject) goanalysis.Issue { From: object.Position.Start.Line, To: lineRangeTo, }, - FromLinter: reviveName, + FromLinter: linterName, }, pass) } // This function mimics the GetConfig function of revive. // This allows to get default values and right types. // https://github.com/golangci/golangci-lint/issues/1745 -// https://github.com/mgechev/revive/blob/v1.1.4/config/config.go#L182 -func getReviveConfig(cfg *config.ReviveSettings) (*lint.Config, error) { +// https://github.com/mgechev/revive/blob/v1.3.7/config/config.go#L217 +// https://github.com/mgechev/revive/blob/v1.3.7/config/config.go#L169-L174 +func getConfig(cfg *config.ReviveSettings) (*lint.Config, error) { conf := defaultConfig() - if !reflect.DeepEqual(cfg, &config.ReviveSettings{}) { + // Since the Go version is dynamic, this value must be neutralized in order to compare with a "zero value" of the configuration structure. + zero := &config.ReviveSettings{Go: cfg.Go} + + if !reflect.DeepEqual(cfg, zero) { rawRoot := createConfigMap(cfg) buf := bytes.NewBuffer(nil) @@ -182,7 +210,15 @@ func getReviveConfig(cfg *config.ReviveSettings) (*lint.Config, error) { normalizeConfig(conf) - reviveDebugf("revive configuration: %#v", conf) + for k, r := range conf.Rules { + err := r.Initialize() + if err != nil { + return nil, fmt.Errorf("error in config of rule %q: %w", k, err) + } + conf.Rules[k] = r + } + + debugf("revive configuration: %#v", conf) return conf, nil } @@ -214,6 +250,7 @@ func createConfigMap(cfg *config.ReviveSettings) map[string]any { "severity": s.Severity, "arguments": safeTomlSlice(s.Arguments), "disabled": s.Disabled, + "exclude": s.Exclude, } } @@ -247,7 +284,7 @@ func safeTomlSlice(r []any) []any { } // This element is not exported by revive, so we need copy the code. -// Extracted from https://github.com/mgechev/revive/blob/v1.3.4/config/config.go#L15 +// Extracted from https://github.com/mgechev/revive/blob/v1.3.9/config/config.go#L15 var defaultRules = []lint.Rule{ &rule.VarDeclarationsRule{}, &rule.PackageCommentsRule{}, @@ -290,7 +327,7 @@ var allRules = append([]lint.Rule{ &rule.ModifiesValRecRule{}, &rule.ConstantLogicalExprRule{}, &rule.BoolLiteralRule{}, - &rule.ImportsBlacklistRule{}, + &rule.ImportsBlocklistRule{}, &rule.FunctionResultsLimitRule{}, &rule.MaxPublicStructsRule{}, &rule.RangeValInClosureRule{}, @@ -327,6 +364,10 @@ var allRules = append([]lint.Rule{ &rule.RedundantImportAlias{}, &rule.ImportAliasNamingRule{}, &rule.EnforceMapStyleRule{}, + &rule.EnforceRepeatedArgTypeStyleRule{}, + &rule.EnforceSliceStyleRule{}, + &rule.MaxControlNestingRule{}, + &rule.CommentsDensityRule{}, }, defaultRules...) const defaultConfidence = 0.8 @@ -349,8 +390,8 @@ func normalizeConfig(cfg *lint.Config) { } if cfg.EnableAllRules { // Add to the configuration all rules not yet present in it - for _, rule := range allRules { - ruleName := rule.Name() + for _, r := range allRules { + ruleName := r.Name() _, alreadyInConf := cfg.Rules[ruleName] if alreadyInConf { continue diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck.go deleted file mode 100644 index 5a66d62e7..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck.go +++ /dev/null @@ -1,25 +0,0 @@ -package golinters - -import ( - "github.com/jingyugao/rowserrcheck/passes/rowserr" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewRowsErrCheck(settings *config.RowsErrCheckSettings) *goanalysis.Linter { - var pkgs []string - if settings != nil { - pkgs = settings.Packages - } - - analyzer := rowserr.NewAnalyzer(pkgs...) - - return goanalysis.NewLinter( - "rowserrcheck", - "checks whether Err of rows is checked successfully", - []*analysis.Analyzer{analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck/rowserrcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck/rowserrcheck.go new file mode 100644 index 000000000..3fe824467 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck/rowserrcheck.go @@ -0,0 +1,25 @@ +package rowserrcheck + +import ( + "github.com/jingyugao/rowserrcheck/passes/rowserr" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.RowsErrCheckSettings) *goanalysis.Linter { + var pkgs []string + if settings != nil { + pkgs = settings.Packages + } + + a := rowserr.NewAnalyzer(pkgs...) + + return goanalysis.NewLinter( + a.Name, + "checks whether Rows.Err of rows is checked successfully", + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/scopelint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/scopelint.go deleted file mode 100644 index e6ef15ede..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/scopelint.go +++ /dev/null @@ -1,190 +0,0 @@ -package golinters - -import ( - "fmt" - "go/ast" - "go/token" - "sync" - - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const scopelintName = "scopelint" - -//nolint:dupl -func NewScopelint() *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: scopelintName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues := runScopeLint(pass) - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - scopelintName, - "Scopelint checks for unpinned variables in go programs", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) -} - -func runScopeLint(pass *analysis.Pass) []goanalysis.Issue { - var lintIssues []result.Issue - - for _, file := range pass.Files { - n := Node{ - fset: pass.Fset, - DangerObjects: map[*ast.Object]int{}, - UnsafeObjects: map[*ast.Object]int{}, - SkipFuncs: map[*ast.FuncLit]int{}, - issues: &lintIssues, - } - ast.Walk(&n, file) - } - - var issues []goanalysis.Issue - for i := range lintIssues { - issues = append(issues, goanalysis.NewIssue(&lintIssues[i], pass)) - } - - return issues -} - -// The code below is copy-pasted from https://github.com/kyoh86/scopelint 92cbe2cc9276abda0e309f52cc9e309d407f174e - -// Node represents a Node being linted. -type Node struct { - fset *token.FileSet - DangerObjects map[*ast.Object]int - UnsafeObjects map[*ast.Object]int - SkipFuncs map[*ast.FuncLit]int - issues *[]result.Issue -} - -// Visit method is invoked for each node encountered by Walk. -// If the result visitor w is not nil, Walk visits each of the children -// of node with the visitor w, followed by a call of w.Visit(nil). -// -//nolint:gocyclo,gocritic -func (f *Node) Visit(node ast.Node) ast.Visitor { - switch typedNode := node.(type) { - case *ast.ForStmt: - switch init := typedNode.Init.(type) { - case *ast.AssignStmt: - for _, lh := range init.Lhs { - switch tlh := lh.(type) { - case *ast.Ident: - f.UnsafeObjects[tlh.Obj] = 0 - } - } - } - - case *ast.RangeStmt: - // Memory variables declared in range statement - switch k := typedNode.Key.(type) { - case *ast.Ident: - f.UnsafeObjects[k.Obj] = 0 - } - switch v := typedNode.Value.(type) { - case *ast.Ident: - f.UnsafeObjects[v.Obj] = 0 - } - - case *ast.UnaryExpr: - if typedNode.Op == token.AND { - switch ident := typedNode.X.(type) { - case *ast.Ident: - if _, unsafe := f.UnsafeObjects[ident.Obj]; unsafe { - f.errorf(ident, "Using a reference for the variable on range scope %s", formatCode(ident.Name, nil)) - } - } - } - - case *ast.Ident: - if _, obj := f.DangerObjects[typedNode.Obj]; obj { - // It is the naked variable in scope of range statement. - f.errorf(node, "Using the variable on range scope %s in function literal", formatCode(typedNode.Name, nil)) - break - } - - case *ast.CallExpr: - // Ignore func literals that'll be called immediately. - switch funcLit := typedNode.Fun.(type) { - case *ast.FuncLit: - f.SkipFuncs[funcLit] = 0 - } - - case *ast.FuncLit: - if _, skip := f.SkipFuncs[typedNode]; !skip { - dangers := map[*ast.Object]int{} - for d := range f.DangerObjects { - dangers[d] = 0 - } - for u := range f.UnsafeObjects { - dangers[u] = 0 - f.UnsafeObjects[u]++ - } - return &Node{ - fset: f.fset, - DangerObjects: dangers, - UnsafeObjects: f.UnsafeObjects, - SkipFuncs: f.SkipFuncs, - issues: f.issues, - } - } - - case *ast.ReturnStmt: - unsafe := map[*ast.Object]int{} - for u := range f.UnsafeObjects { - if f.UnsafeObjects[u] == 0 { - continue - } - unsafe[u] = f.UnsafeObjects[u] - } - return &Node{ - fset: f.fset, - DangerObjects: f.DangerObjects, - UnsafeObjects: unsafe, - SkipFuncs: f.SkipFuncs, - issues: f.issues, - } - } - return f -} - -// The variadic arguments may start with link and category types, -// and must end with a format string and any arguments. -// -//nolint:interfacer -func (f *Node) errorf(n ast.Node, format string, args ...any) { - pos := f.fset.Position(n.Pos()) - f.errorAtf(pos, format, args...) -} - -func (f *Node) errorAtf(pos token.Position, format string, args ...any) { - *f.issues = append(*f.issues, result.Issue{ - Pos: pos, - Text: fmt.Sprintf(format, args...), - FromLinter: scopelintName, - }) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sloglint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sloglint/sloglint.go similarity index 57% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sloglint.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sloglint/sloglint.go index b506d187f..486662577 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sloglint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sloglint/sloglint.go @@ -1,20 +1,26 @@ -package golinters +package sloglint import ( "go-simpler.org/sloglint" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewSlogLint(settings *config.SlogLintSettings) *goanalysis.Linter { +func New(settings *config.SlogLintSettings) *goanalysis.Linter { var opts *sloglint.Options if settings != nil { opts = &sloglint.Options{ + NoMixedArgs: settings.NoMixedArgs, KVOnly: settings.KVOnly, AttrOnly: settings.AttrOnly, + NoGlobal: settings.NoGlobal, + ContextOnly: settings.Context, + StaticMsg: settings.StaticMsg, NoRawKeys: settings.NoRawKeys, + KeyNamingCase: settings.KeyNamingCase, + ForbiddenKeys: settings.ForbiddenKeys, ArgsOnSepLines: settings.ArgsOnSepLines, } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/spancheck/spancheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/spancheck/spancheck.go new file mode 100644 index 000000000..a800a1705 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/spancheck/spancheck.go @@ -0,0 +1,33 @@ +package spancheck + +import ( + "github.com/jjti/go-spancheck" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.SpancheckSettings) *goanalysis.Linter { + cfg := spancheck.NewDefaultConfig() + + if settings != nil { + if settings.Checks != nil { + cfg.EnabledChecks = settings.Checks + } + + if settings.IgnoreCheckSignatures != nil { + cfg.IgnoreChecksSignaturesSlice = settings.IgnoreCheckSignatures + } + + if settings.ExtraStartSpanSignatures != nil { + cfg.StartSpanMatchersSlice = settings.ExtraStartSpanSignatures + } + } + + a := spancheck.NewAnalyzerWithConfig(cfg) + + return goanalysis. + NewLinter(a.Name, a.Doc, []*analysis.Analyzer{a}, nil). + WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go deleted file mode 100644 index ff2c0c08f..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go +++ /dev/null @@ -1,19 +0,0 @@ -package golinters - -import ( - "github.com/ryanrolds/sqlclosecheck/pkg/analyzer" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewSQLCloseCheck() *goanalysis.Linter { - return goanalysis.NewLinter( - "sqlclosecheck", - "Checks that sql.Rows and sql.Stmt are closed.", - []*analysis.Analyzer{ - analyzer.NewAnalyzer(), - }, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck/sqlclosecheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck/sqlclosecheck.go new file mode 100644 index 000000000..5eb32ff9d --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck/sqlclosecheck.go @@ -0,0 +1,19 @@ +package sqlclosecheck + +import ( + "github.com/ryanrolds/sqlclosecheck/pkg/analyzer" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := analyzer.NewAnalyzer() + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck/staticcheck.go similarity index 53% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck/staticcheck.go index 673484630..0c0534539 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck/staticcheck.go @@ -1,15 +1,16 @@ -package golinters +package staticcheck import ( "honnef.co/go/tools/staticcheck" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" ) -func NewStaticcheck(settings *config.StaticCheckSettings) *goanalysis.Linter { - cfg := staticCheckConfig(settings) - analyzers := setupStaticCheckAnalyzers(staticcheck.Analyzers, getGoVersion(settings), cfg.Checks) +func New(settings *config.StaticCheckSettings) *goanalysis.Linter { + cfg := internal.StaticCheckConfig(settings) + analyzers := internal.SetupStaticCheckAnalyzers(staticcheck.Analyzers, internal.GetGoVersion(settings), cfg.Checks) return goanalysis.NewLinter( "staticcheck", diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/structcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/structcheck.go deleted file mode 100644 index f3df0c2f3..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/structcheck.go +++ /dev/null @@ -1,71 +0,0 @@ -package golinters - -import ( - "fmt" - "sync" - - structcheckAPI "github.com/golangci/check/cmd/structcheck" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const structcheckName = "structcheck" - -//nolint:dupl -func NewStructcheck(settings *config.StructCheckSettings) *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: structcheckName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues := runStructCheck(pass, settings) - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - structcheckName, - "Finds unused struct fields", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) -} - -//nolint:dupl -func runStructCheck(pass *analysis.Pass, settings *config.StructCheckSettings) []goanalysis.Issue { - prog := goanalysis.MakeFakeLoaderProgram(pass) - - lintIssues := structcheckAPI.Run(prog, settings.CheckExportedFields) - if len(lintIssues) == 0 { - return nil - } - - issues := make([]goanalysis.Issue, 0, len(lintIssues)) - - for _, i := range lintIssues { - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: fmt.Sprintf("%s is unused", formatCode(i.FieldName, nil)), - FromLinter: structcheckName, - }, pass)) - } - - return issues -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/stylecheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/stylecheck/stylecheck.go similarity index 61% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/stylecheck.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/stylecheck/stylecheck.go index 2e1e21c5b..b8fc8fe54 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/stylecheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/stylecheck/stylecheck.go @@ -1,4 +1,4 @@ -package golinters +package stylecheck import ( "golang.org/x/tools/go/analysis" @@ -6,20 +6,21 @@ import ( "honnef.co/go/tools/stylecheck" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" ) -func NewStylecheck(settings *config.StaticCheckSettings) *goanalysis.Linter { - cfg := staticCheckConfig(settings) +func New(settings *config.StaticCheckSettings) *goanalysis.Linter { + cfg := internal.StaticCheckConfig(settings) // `scconfig.Analyzer` is a singleton, then it's not possible to have more than one instance for all staticcheck "sub-linters". // When we will merge the 4 "sub-linters", the problem will disappear: https://github.com/golangci/golangci-lint/issues/357 // Currently only stylecheck analyzer has a configuration in staticcheck. - scconfig.Analyzer.Run = func(pass *analysis.Pass) (any, error) { + scconfig.Analyzer.Run = func(_ *analysis.Pass) (any, error) { return cfg, nil } - analyzers := setupStaticCheckAnalyzers(stylecheck.Analyzers, getGoVersion(settings), cfg.Checks) + analyzers := internal.SetupStaticCheckAnalyzers(stylecheck.Analyzers, internal.GetGoVersion(settings), cfg.Checks) return goanalysis.NewLinter( "stylecheck", diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagalign.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagalign/tagalign.go similarity index 92% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagalign.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagalign/tagalign.go index c23838f70..f438c51b5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagalign.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagalign/tagalign.go @@ -1,4 +1,4 @@ -package golinters +package tagalign import ( "sync" @@ -7,12 +7,12 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -func NewTagAlign(settings *config.TagAlignSettings) *goanalysis.Linter { +func New(settings *config.TagAlignSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle/tagliatelle.go similarity index 77% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle/tagliatelle.go index 67c14cbd4..d1674c3e9 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle/tagliatelle.go @@ -1,14 +1,14 @@ -package golinters +package tagliatelle import ( "github.com/ldez/tagliatelle" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewTagliatelle(settings *config.TagliatelleSettings) *goanalysis.Linter { +func New(settings *config.TagliatelleSettings) *goanalysis.Linter { cfg := tagliatelle.Config{ Rules: map[string]string{ "json": "camel", diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv/tenv.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv/tenv.go index 6c6bd3186..b80a783b6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv/tenv.go @@ -1,14 +1,14 @@ -package golinters +package tenv import ( "github.com/sivchari/tenv" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewTenv(settings *config.TenvSettings) *goanalysis.Linter { +func New(settings *config.TenvSettings) *goanalysis.Linter { a := tenv.Analyzer var cfg map[string]map[string]any diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testableexamples.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testableexamples/testableexamples.go similarity index 68% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testableexamples.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testableexamples/testableexamples.go index 3333593a6..6b76271db 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testableexamples.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testableexamples/testableexamples.go @@ -1,13 +1,13 @@ -package golinters +package testableexamples import ( "github.com/maratori/testableexamples/pkg/testableexamples" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewTestableexamples() *goanalysis.Linter { +func New() *goanalysis.Linter { a := testableexamples.NewAnalyzer() return goanalysis.NewLinter( diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint.go deleted file mode 100644 index 83bae2868..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint.go +++ /dev/null @@ -1,36 +0,0 @@ -package golinters - -import ( - "github.com/Antonboom/testifylint/analyzer" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewTestifylint(settings *config.TestifylintSettings) *goanalysis.Linter { - a := analyzer.New() - - cfg := make(map[string]map[string]any) - if settings != nil { - cfg[a.Name] = map[string]any{ - "enable-all": settings.EnableAll, - } - if len(settings.EnabledCheckers) > 0 { - cfg[a.Name]["enable"] = settings.EnabledCheckers - } - if p := settings.ExpectedActual.ExpVarPattern; p != "" { - cfg[a.Name]["expected-actual.pattern"] = p - } - if m := settings.SuiteExtraAssertCall.Mode; m != "" { - cfg[a.Name]["suite-extra-assert-call.mode"] = m - } - } - - return goanalysis.NewLinter( - a.Name, - a.Doc, - []*analysis.Analyzer{a}, - cfg, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint/testifylint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint/testifylint.go new file mode 100644 index 000000000..b3f2f0bd4 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testifylint/testifylint.go @@ -0,0 +1,51 @@ +package testifylint + +import ( + "github.com/Antonboom/testifylint/analyzer" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.TestifylintSettings) *goanalysis.Linter { + a := analyzer.New() + + cfg := make(map[string]map[string]any) + if settings != nil { + cfg[a.Name] = map[string]any{ + "enable-all": settings.EnableAll, + "disable-all": settings.DisableAll, + + "bool-compare.ignore-custom-types": settings.BoolCompare.IgnoreCustomTypes, + "formatter.require-f-funcs": settings.Formatter.RequireFFuncs, + "go-require.ignore-http-handlers": settings.GoRequire.IgnoreHTTPHandlers, + } + if len(settings.EnabledCheckers) > 0 { + cfg[a.Name]["enable"] = settings.EnabledCheckers + } + if len(settings.DisabledCheckers) > 0 { + cfg[a.Name]["disable"] = settings.DisabledCheckers + } + + if b := settings.Formatter.CheckFormatString; b != nil { + cfg[a.Name]["formatter.check-format-string"] = *b + } + if p := settings.ExpectedActual.ExpVarPattern; p != "" { + cfg[a.Name]["expected-actual.pattern"] = p + } + if p := settings.RequireError.FnPattern; p != "" { + cfg[a.Name]["require-error.fn-pattern"] = p + } + if m := settings.SuiteExtraAssertCall.Mode; m != "" { + cfg[a.Name]["suite-extra-assert-call.mode"] = m + } + } + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + cfg, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage/testpackage.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage/testpackage.go index db1ead966..632152712 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage/testpackage.go @@ -1,4 +1,4 @@ -package golinters +package testpackage import ( "strings" @@ -7,11 +7,11 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewTestpackage(cfg *config.TestpackageSettings) *goanalysis.Linter { - var a = testpackage.NewAnalyzer() +func New(cfg *config.TestpackageSettings) *goanalysis.Linter { + a := testpackage.NewAnalyzer() var settings map[string]map[string]any if cfg != nil { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/thelper.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/thelper/thelper.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/thelper.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/thelper/thelper.go index 84a8e9e8b..cc6ea755c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/thelper.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/thelper/thelper.go @@ -1,16 +1,18 @@ -package golinters +package thelper import ( "strings" "github.com/kulti/thelper/pkg/analyzer" + "golang.org/x/exp/maps" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" ) -func NewThelper(cfg *config.ThelperSettings) *goanalysis.Linter { +func New(cfg *config.ThelperSettings) *goanalysis.Linter { a := analyzer.NewAnalyzer() opts := map[string]struct{}{ @@ -39,13 +41,10 @@ func NewThelper(cfg *config.ThelperSettings) *goanalysis.Linter { } if len(opts) == 0 { - linterLogger.Fatalf("thelper: at least one option must be enabled") + internal.LinterLogger.Fatalf("thelper: at least one option must be enabled") } - var args []string - for k := range opts { - args = append(args, k) - } + args := maps.Keys(opts) cfgMap := map[string]map[string]any{ a.Name: { @@ -54,8 +53,8 @@ func NewThelper(cfg *config.ThelperSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - "thelper", - "thelper detects Go test helpers without t.Helper() call and checks the consistency of test helpers", + a.Name, + a.Doc, []*analysis.Analyzer{a}, cfgMap, ).WithLoadMode(goanalysis.LoadModeTypesInfo) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel.go deleted file mode 100644 index cbe97516c..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel.go +++ /dev/null @@ -1,17 +0,0 @@ -package golinters - -import ( - "github.com/moricho/tparallel" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewTparallel() *goanalysis.Linter { - return goanalysis.NewLinter( - "tparallel", - "tparallel detects inappropriate usage of t.Parallel() method in your Go test codes", - []*analysis.Analyzer{tparallel.Analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel/tparallel.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel/tparallel.go new file mode 100644 index 000000000..4f7c43a99 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel/tparallel.go @@ -0,0 +1,18 @@ +package tparallel + +import ( + "github.com/moricho/tparallel" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := tparallel.Analyzer + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/typecheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/typecheck.go index e9b26ef48..d0eaa00d0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/typecheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/typecheck.go @@ -3,7 +3,7 @@ package golinters import ( "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) func NewTypecheck() *goanalysis.Linter { @@ -20,5 +20,5 @@ func NewTypecheck() *goanalysis.Linter { "Like the front-end of a Go compiler, parses and type-checks Go code", []*analysis.Analyzer{analyzer}, nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) + ).WithLoadMode(goanalysis.LoadModeNone) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert/unconvert.go similarity index 58% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert/unconvert.go index aad858dfd..954cc9eb3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert/unconvert.go @@ -1,28 +1,28 @@ -package golinters +package unconvert import ( "sync" - unconvertAPI "github.com/golangci/unconvert" + "github.com/golangci/unconvert" "golang.org/x/tools/go/analysis" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const unconvertName = "unconvert" +const linterName = "unconvert" -//nolint:dupl -func NewUnconvert() *goanalysis.Linter { +func New(settings *config.UnconvertSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: unconvertName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (any, error) { - issues := runUnconvert(pass) + issues := runUnconvert(pass, settings) if len(issues) == 0 { return nil, nil @@ -37,7 +37,7 @@ func NewUnconvert() *goanalysis.Linter { } return goanalysis.NewLinter( - unconvertName, + linterName, "Remove unnecessary type conversions", []*analysis.Analyzer{analyzer}, nil, @@ -46,20 +46,15 @@ func NewUnconvert() *goanalysis.Linter { }).WithLoadMode(goanalysis.LoadModeTypesInfo) } -func runUnconvert(pass *analysis.Pass) []goanalysis.Issue { - prog := goanalysis.MakeFakeLoaderProgram(pass) +func runUnconvert(pass *analysis.Pass, settings *config.UnconvertSettings) []goanalysis.Issue { + positions := unconvert.Run(pass, settings.FastMath, settings.Safe) - positions := unconvertAPI.Run(prog) - if len(positions) == 0 { - return nil - } - - issues := make([]goanalysis.Issue, 0, len(positions)) - for _, pos := range positions { + var issues []goanalysis.Issue + for _, position := range positions { issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: pos, + Pos: position, Text: "unnecessary conversion", - FromLinter: unconvertName, + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam/unparam.go similarity index 88% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam/unparam.go index 4078d9498..0fe184736 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam/unparam.go @@ -1,4 +1,4 @@ -package golinters +package unparam import ( "sync" @@ -9,19 +9,19 @@ import ( "mvdan.cc/unparam/check" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const unparamName = "unparam" +const linterName = "unparam" -func NewUnparam(settings *config.UnparamSettings) *goanalysis.Linter { +func New(settings *config.UnparamSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: unparamName, + Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, Requires: []*analysis.Analyzer{buildssa.Analyzer}, Run: func(pass *analysis.Pass) (any, error) { @@ -43,7 +43,7 @@ func NewUnparam(settings *config.UnparamSettings) *goanalysis.Linter { } return goanalysis.NewLinter( - unparamName, + linterName, "Reports unused function parameters", []*analysis.Analyzer{analyzer}, nil, @@ -82,7 +82,7 @@ func runUnparam(pass *analysis.Pass, settings *config.UnparamSettings) ([]goanal issues = append(issues, goanalysis.NewIssue(&result.Issue{ Pos: pass.Fset.Position(i.Pos()), Text: i.Message(), - FromLinter: unparamName, + FromLinter: linterName, }, pass)) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused/unused.go similarity index 74% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused/unused.go index 89ae7e98a..19cf7476f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused/unused.go @@ -1,4 +1,4 @@ -package golinters +package unused import ( "fmt" @@ -11,19 +11,20 @@ import ( "honnef.co/go/tools/unused" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/golinters/internal" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const unusedName = "unused" +const linterName = "unused" -func NewUnused(settings *config.UnusedSettings, scSettings *config.StaticCheckSettings) *goanalysis.Linter { +func New(settings *config.UnusedSettings, scSettings *config.StaticCheckSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: unusedName, + Name: linterName, Doc: unused.Analyzer.Analyzer.Doc, Requires: unused.Analyzer.Analyzer.Requires, Run: func(pass *analysis.Pass) (any, error) { @@ -40,14 +41,14 @@ func NewUnused(settings *config.UnusedSettings, scSettings *config.StaticCheckSe }, } - setAnalyzerGoVersion(analyzer, getGoVersion(scSettings)) + internal.SetAnalyzerGoVersion(analyzer, internal.GetGoVersion(scSettings)) return goanalysis.NewLinter( - unusedName, + linterName, "Checks Go code for unused constants, variables, functions and types", []*analysis.Analyzer{analyzer}, nil, - ).WithIssuesReporter(func(lintCtx *linter.Context) []goanalysis.Issue { + ).WithIssuesReporter(func(_ *linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeTypesInfo) } @@ -74,7 +75,7 @@ func runUnused(pass *analysis.Pass, cfg *config.UnusedSettings) []goanalysis.Iss } issue := goanalysis.NewIssue(&result.Issue{ - FromLinter: unusedName, + FromLinter: linterName, Text: fmt.Sprintf("%s %s is unused", object.Kind, object.Name), Pos: object.Position, }, pass) @@ -89,11 +90,13 @@ func getUnusedResults(pass *analysis.Pass, settings *config.UnusedSettings) unus opts := unused.Options{ FieldWritesAreUses: settings.FieldWritesAreUses, PostStatementsAreReads: settings.PostStatementsAreReads, - ExportedIsUsed: settings.ExportedIsUsed, - ExportedFieldsAreUsed: settings.ExportedFieldsAreUsed, - ParametersAreUsed: settings.ParametersAreUsed, - LocalVariablesAreUsed: settings.LocalVariablesAreUsed, - GeneratedIsUsed: settings.GeneratedIsUsed, + // Related to https://github.com/golangci/golangci-lint/issues/4218 + // https://github.com/dominikh/go-tools/issues/1474#issuecomment-1850760813 + ExportedIsUsed: true, + ExportedFieldsAreUsed: settings.ExportedFieldsAreUsed, + ParametersAreUsed: settings.ParametersAreUsed, + LocalVariablesAreUsed: settings.LocalVariablesAreUsed, + GeneratedIsUsed: settings.GeneratedIsUsed, } // ref: https://github.com/dominikh/go-tools/blob/4ec1f474ca6c0feb8e10a8fcca4ab95f5b5b9881/internal/cmd/unused/unused.go#L68 diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars/usestdlibvars.go similarity index 87% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars/usestdlibvars.go index 663a841ac..050e47f24 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars/usestdlibvars.go @@ -1,14 +1,14 @@ -package golinters +package usestdlibvars import ( "github.com/sashamelentyev/usestdlibvars/pkg/analyzer" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewUseStdlibVars(cfg *config.UseStdlibVarsSettings) *goanalysis.Linter { +func New(cfg *config.UseStdlibVarsSettings) *goanalysis.Linter { a := analyzer.New() cfgMap := make(map[string]map[string]any) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varcheck.go deleted file mode 100644 index 495c5b59f..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varcheck.go +++ /dev/null @@ -1,72 +0,0 @@ -package golinters - -import ( - "fmt" - "sync" - - varcheckAPI "github.com/golangci/check/cmd/varcheck" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const varcheckName = "varcheck" - -func NewVarcheck(settings *config.VarCheckSettings) *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: varcheckName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: goanalysis.DummyRun, - } - - return goanalysis.NewLinter( - varcheckName, - "Finds unused global variables and constants", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (any, error) { - issues := runVarCheck(pass, settings) - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) -} - -//nolint:dupl -func runVarCheck(pass *analysis.Pass, settings *config.VarCheckSettings) []goanalysis.Issue { - prog := goanalysis.MakeFakeLoaderProgram(pass) - - lintIssues := varcheckAPI.Run(prog, settings.CheckExportedFields) - if len(lintIssues) == 0 { - return nil - } - - issues := make([]goanalysis.Issue, 0, len(lintIssues)) - - for _, i := range lintIssues { - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: fmt.Sprintf("%s is unused", formatCode(i.VarName, nil)), - FromLinter: varcheckName, - }, pass)) - } - - return issues -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varnamelen.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varnamelen/varnamelen.go similarity index 89% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varnamelen.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varnamelen/varnamelen.go index 688dfa804..6cb57ffa5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varnamelen.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varnamelen/varnamelen.go @@ -1,4 +1,4 @@ -package golinters +package varnamelen import ( "strconv" @@ -8,10 +8,10 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -func NewVarnamelen(settings *config.VarnamelenSettings) *goanalysis.Linter { +func New(settings *config.VarnamelenSettings) *goanalysis.Linter { analyzer := varnamelen.NewAnalyzer() cfg := map[string]map[string]any{} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign.go deleted file mode 100644 index 92798d4f7..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign.go +++ /dev/null @@ -1,17 +0,0 @@ -package golinters - -import ( - "github.com/sanposhiho/wastedassign/v2" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewWastedAssign() *goanalysis.Linter { - return goanalysis.NewLinter( - "wastedassign", - "wastedassign finds wasted assignment statements.", - []*analysis.Analyzer{wastedassign.Analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign/wastedassign.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign/wastedassign.go new file mode 100644 index 000000000..094fa95c2 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign/wastedassign.go @@ -0,0 +1,19 @@ +package wastedassign + +import ( + "github.com/sanposhiho/wastedassign/v2" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := wastedassign.Analyzer + + return goanalysis.NewLinter( + a.Name, + "Finds wasted assignment statements", + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace.go deleted file mode 100644 index e5941fa5d..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace.go +++ /dev/null @@ -1,108 +0,0 @@ -package golinters - -import ( - "fmt" - "go/token" - "sync" - - "github.com/ultraware/whitespace" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const whitespaceName = "whitespace" - -//nolint:dupl -func NewWhitespace(settings *config.WhitespaceSettings) *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - var wsSettings whitespace.Settings - if settings != nil { - wsSettings = whitespace.Settings{ - MultiIf: settings.MultiIf, - MultiFunc: settings.MultiFunc, - } - } - - analyzer := &analysis.Analyzer{ - Name: whitespaceName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: goanalysis.DummyRun, - } - - return goanalysis.NewLinter( - whitespaceName, - "Tool for detection of leading and trailing whitespace", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (any, error) { - issues, err := runWhitespace(lintCtx, pass, wsSettings) - if err != nil { - return nil, err - } - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) -} - -func runWhitespace(lintCtx *linter.Context, pass *analysis.Pass, wsSettings whitespace.Settings) ([]goanalysis.Issue, error) { - var messages []whitespace.Message - for _, file := range pass.Files { - messages = append(messages, whitespace.Run(file, pass.Fset, wsSettings)...) - } - - if len(messages) == 0 { - return nil, nil - } - - issues := make([]goanalysis.Issue, len(messages)) - for k, i := range messages { - issue := result.Issue{ - Pos: token.Position{ - Filename: i.Pos.Filename, - Line: i.Pos.Line, - }, - LineRange: &result.Range{From: i.Pos.Line, To: i.Pos.Line}, - Text: i.Message, - FromLinter: whitespaceName, - Replacement: &result.Replacement{}, - } - - bracketLine, err := lintCtx.LineCache.GetLine(issue.Pos.Filename, issue.Pos.Line) - if err != nil { - return nil, fmt.Errorf("failed to get line %s:%d: %w", issue.Pos.Filename, issue.Pos.Line, err) - } - - switch i.Type { - case whitespace.MessageTypeLeading: - issue.LineRange.To++ // cover two lines by the issue: opening bracket "{" (issue.Pos.Line) and following empty line - case whitespace.MessageTypeTrailing: - issue.LineRange.From-- // cover two lines by the issue: closing bracket "}" (issue.Pos.Line) and preceding empty line - issue.Pos.Line-- // set in sync with LineRange.From to not break fixer and other code features - case whitespace.MessageTypeAddAfter: - bracketLine += "\n" - } - issue.Replacement.NewLines = []string{bracketLine} - - issues[k] = goanalysis.NewIssue(&issue, pass) - } - - return issues, nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace/whitespace.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace/whitespace.go new file mode 100644 index 000000000..721bfada1 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace/whitespace.go @@ -0,0 +1,102 @@ +package whitespace + +import ( + "fmt" + "sync" + + "github.com/ultraware/whitespace" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/result" +) + +const linterName = "whitespace" + +func New(settings *config.WhitespaceSettings) *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue + + var wsSettings whitespace.Settings + if settings != nil { + wsSettings = whitespace.Settings{ + Mode: whitespace.RunningModeGolangCI, + MultiIf: settings.MultiIf, + MultiFunc: settings.MultiFunc, + } + } + + a := whitespace.NewAnalyzer(&wsSettings) + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithContextSetter(func(_ *linter.Context) { + a.Run = func(pass *analysis.Pass) (any, error) { + issues, err := runWhitespace(pass, wsSettings) + if err != nil { + return nil, err + } + + if len(issues) == 0 { + return nil, nil + } + + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() + + return nil, nil + } + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} + +func runWhitespace(pass *analysis.Pass, wsSettings whitespace.Settings) ([]goanalysis.Issue, error) { + lintIssues := whitespace.Run(pass, &wsSettings) + + issues := make([]goanalysis.Issue, len(lintIssues)) + for i, issue := range lintIssues { + report := &result.Issue{ + FromLinter: linterName, + Pos: pass.Fset.PositionFor(issue.Diagnostic, false), + Text: issue.Message, + } + + switch issue.MessageType { + case whitespace.MessageTypeRemove: + if len(issue.LineNumbers) == 0 { + continue + } + + report.LineRange = &result.Range{ + From: issue.LineNumbers[0], + To: issue.LineNumbers[len(issue.LineNumbers)-1], + } + + report.Replacement = &result.Replacement{NeedOnlyDelete: true} + + case whitespace.MessageTypeAdd: + report.Pos = pass.Fset.PositionFor(issue.FixStart, false) + report.Replacement = &result.Replacement{ + Inline: &result.InlineFix{ + StartCol: 0, + Length: 1, + NewString: "\n\t", + }, + } + + default: + return nil, fmt.Errorf("unknown message type: %v", issue.MessageType) + } + + issues[i] = goanalysis.NewIssue(report, pass) + } + + return issues, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wrapcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wrapcheck/wrapcheck.go similarity index 78% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wrapcheck.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wrapcheck/wrapcheck.go index 098eb87ba..96ec2eeae 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wrapcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wrapcheck/wrapcheck.go @@ -1,16 +1,14 @@ -package golinters +package wrapcheck import ( "github.com/tomarrell/wrapcheck/v2/wrapcheck" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/goanalysis" ) -const wrapcheckName = "wrapcheck" - -func NewWrapcheck(settings *config.WrapcheckSettings) *goanalysis.Linter { +func New(settings *config.WrapcheckSettings) *goanalysis.Linter { cfg := wrapcheck.NewDefaultConfig() if settings != nil { if len(settings.IgnoreSigs) != 0 { @@ -30,7 +28,7 @@ func NewWrapcheck(settings *config.WrapcheckSettings) *goanalysis.Linter { a := wrapcheck.NewAnalyzer(cfg) return goanalysis.NewLinter( - wrapcheckName, + a.Name, a.Doc, []*analysis.Analyzer{a}, nil, diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go deleted file mode 100644 index 05697a629..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go +++ /dev/null @@ -1,89 +0,0 @@ -package golinters - -import ( - "sync" - - "github.com/bombsimon/wsl/v3" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/result" -) - -const wslName = "wsl" - -// NewWSL returns a new WSL linter. -func NewWSL(settings *config.WSLSettings) *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - conf := wsl.DefaultConfig() - - if settings != nil { - conf.StrictAppend = settings.StrictAppend - conf.AllowAssignAndCallCuddle = settings.AllowAssignAndCallCuddle - conf.AllowAssignAndAnythingCuddle = settings.AllowAssignAndAnythingCuddle - conf.AllowMultiLineAssignCuddle = settings.AllowMultiLineAssignCuddle - conf.ForceCaseTrailingWhitespaceLimit = settings.ForceCaseTrailingWhitespaceLimit - conf.AllowTrailingComment = settings.AllowTrailingComment - conf.AllowSeparatedLeadingComment = settings.AllowSeparatedLeadingComment - conf.AllowCuddleDeclaration = settings.AllowCuddleDeclaration - conf.AllowCuddleWithCalls = settings.AllowCuddleWithCalls - conf.AllowCuddleWithRHS = settings.AllowCuddleWithRHS - conf.ForceCuddleErrCheckAndAssign = settings.ForceCuddleErrCheckAndAssign - conf.ErrorVariableNames = settings.ErrorVariableNames - conf.ForceExclusiveShortDeclarations = settings.ForceExclusiveShortDeclarations - } - - analyzer := &analysis.Analyzer{ - Name: goanalysis.TheOnlyAnalyzerName, - Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (any, error) { - issues := runWSL(pass, &conf) - - if len(issues) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, issues...) - mu.Unlock() - - return nil, nil - }, - } - - return goanalysis.NewLinter( - wslName, - "Whitespace Linter - Forces you to use empty lines!", - []*analysis.Analyzer{analyzer}, - nil, - ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) -} - -func runWSL(pass *analysis.Pass, conf *wsl.Configuration) []goanalysis.Issue { - if conf == nil { - return nil - } - - files := getFileNames(pass) - wslErrors, _ := wsl.NewProcessorWithConfig(*conf).ProcessFiles(files) - if len(wslErrors) == 0 { - return nil - } - - var issues []goanalysis.Issue - for _, err := range wslErrors { - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - FromLinter: wslName, - Pos: err.Position, - Text: err.Reason, - }, pass)) - } - - return issues -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl/wsl.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl/wsl.go new file mode 100644 index 000000000..c728340ec --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl/wsl.go @@ -0,0 +1,40 @@ +package wsl + +import ( + "github.com/bombsimon/wsl/v4" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New(settings *config.WSLSettings) *goanalysis.Linter { + var conf *wsl.Configuration + if settings != nil { + conf = &wsl.Configuration{ + StrictAppend: settings.StrictAppend, + AllowAssignAndCallCuddle: settings.AllowAssignAndCallCuddle, + AllowAssignAndAnythingCuddle: settings.AllowAssignAndAnythingCuddle, + AllowMultiLineAssignCuddle: settings.AllowMultiLineAssignCuddle, + ForceCaseTrailingWhitespaceLimit: settings.ForceCaseTrailingWhitespaceLimit, + AllowTrailingComment: settings.AllowTrailingComment, + AllowSeparatedLeadingComment: settings.AllowSeparatedLeadingComment, + AllowCuddleDeclaration: settings.AllowCuddleDeclaration, + AllowCuddleWithCalls: settings.AllowCuddleWithCalls, + AllowCuddleWithRHS: settings.AllowCuddleWithRHS, + ForceCuddleErrCheckAndAssign: settings.ForceCuddleErrCheckAndAssign, + ErrorVariableNames: settings.ErrorVariableNames, + ForceExclusiveShortDeclarations: settings.ForceExclusiveShortDeclarations, + IncludeGenerated: true, // force to true because golangci-lint already have a way to filter generated files. + } + } + + a := wsl.NewAnalyzer(conf) + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint.go deleted file mode 100644 index a37bca12e..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint.go +++ /dev/null @@ -1,17 +0,0 @@ -package golinters - -import ( - "github.com/ykadowak/zerologlint" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" -) - -func NewZerologLint() *goanalysis.Linter { - return goanalysis.NewLinter( - "zerologlint", - "Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg`.", - []*analysis.Analyzer{zerologlint.Analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint/zerologlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint/zerologlint.go new file mode 100644 index 000000000..6ca74020c --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/zerologlint/zerologlint.go @@ -0,0 +1,19 @@ +package zerologlint + +import ( + "github.com/ykadowak/zerologlint" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/goanalysis" +) + +func New() *goanalysis.Linter { + a := zerologlint.Analyzer + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/goutil/env.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/goutil/env.go index 93922f85a..7b748d8e9 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/goutil/env.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/goutil/env.go @@ -33,20 +33,23 @@ func NewEnv(log logutils.Log) *Env { } } -func (e *Env) Discover(ctx context.Context) error { +func (e Env) Discover(ctx context.Context) error { startedAt := time.Now() - args := []string{"env", "-json"} - args = append(args, string(EnvGoCache), string(EnvGoRoot)) - out, err := exec.CommandContext(ctx, "go", args...).Output() + + //nolint:gosec // Everything is static here. + cmd := exec.CommandContext(ctx, "go", "env", "-json", string(EnvGoCache), string(EnvGoRoot)) + + out, err := cmd.Output() if err != nil { - return fmt.Errorf("failed to run 'go env': %w", err) + return fmt.Errorf("failed to run '%s': %w", strings.Join(cmd.Args, " "), err) } if err = json.Unmarshal(out, &e.vars); err != nil { - return fmt.Errorf("failed to parse 'go %s' json: %w", strings.Join(args, " "), err) + return fmt.Errorf("failed to parse '%s' json: %w", strings.Join(cmd.Args, " "), err) } e.debugf("Read go env for %s: %#v", time.Since(startedAt), e.vars) + return nil } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/context.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/context.go new file mode 100644 index 000000000..160620338 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/context.go @@ -0,0 +1,64 @@ +package lint + +import ( + "context" + "fmt" + + "github.com/golangci/golangci-lint/internal/pkgcache" + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/exitcodes" + "github.com/golangci/golangci-lint/pkg/fsutils" + "github.com/golangci/golangci-lint/pkg/goanalysis/load" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/logutils" +) + +type ContextBuilder struct { + cfg *config.Config + + pkgLoader *PackageLoader + + fileCache *fsutils.FileCache + pkgCache *pkgcache.Cache + + loadGuard *load.Guard +} + +func NewContextBuilder(cfg *config.Config, pkgLoader *PackageLoader, + fileCache *fsutils.FileCache, pkgCache *pkgcache.Cache, loadGuard *load.Guard, +) *ContextBuilder { + return &ContextBuilder{ + cfg: cfg, + pkgLoader: pkgLoader, + fileCache: fileCache, + pkgCache: pkgCache, + loadGuard: loadGuard, + } +} + +func (cl *ContextBuilder) Build(ctx context.Context, log logutils.Log, linters []*linter.Config) (*linter.Context, error) { + pkgs, deduplicatedPkgs, err := cl.pkgLoader.Load(ctx, linters) + if err != nil { + return nil, fmt.Errorf("failed to load packages: %w", err) + } + + if len(deduplicatedPkgs) == 0 { + return nil, fmt.Errorf("%w: running `go mod tidy` may solve the problem", exitcodes.ErrNoGoFiles) + } + + ret := &linter.Context{ + Packages: deduplicatedPkgs, + + // At least `unused` linters works properly only on original (not deduplicated) packages, + // see https://github.com/golangci/golangci-lint/pull/585. + OriginalPackages: pkgs, + + Cfg: cl.cfg, + Log: log, + FileCache: cl.fileCache, + PkgCache: cl.pkgCache, + LoadGuard: cl.loadGuard, + } + + return ret, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go index c911b5613..57c51fa75 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go @@ -1,7 +1,8 @@ package linter import ( - "golang.org/x/tools/go/analysis" + "fmt" + "golang.org/x/tools/go/packages" "github.com/golangci/golangci-lint/pkg/config" @@ -26,10 +27,19 @@ const ( // LastLinter nolintlint must be last because it looks at the results of all the previous linters for unused nolint directives. const LastLinter = "nolintlint" +type DeprecationLevel int + +const ( + DeprecationNone DeprecationLevel = iota + DeprecationWarning + DeprecationError +) + type Deprecation struct { Since string Message string Replacement string + Level DeprecationLevel } type Config struct { @@ -112,15 +122,24 @@ func (lc *Config) WithSince(version string) *Config { return lc } -func (lc *Config) Deprecated(message, version, replacement string) *Config { +func (lc *Config) Deprecated(message, version, replacement string, level DeprecationLevel) *Config { lc.Deprecation = &Deprecation{ Since: version, Message: message, Replacement: replacement, + Level: level, } return lc } +func (lc *Config) DeprecatedWarning(message, version, replacement string) *Config { + return lc.Deprecated(message, version, replacement, DeprecationWarning) +} + +func (lc *Config) DeprecatedError(message, version, replacement string) *Config { + return lc.Deprecated(message, version, replacement, DeprecationError) +} + func (lc *Config) IsDeprecated() bool { return lc.Deprecation != nil } @@ -133,23 +152,27 @@ func (lc *Config) Name() string { return lc.Linter.Name() } -func (lc *Config) WithNoopFallback(cfg *config.Config) *Config { - if cfg != nil && config.IsGreaterThanOrEqualGo121(cfg.Run.Go) { - lc.Linter = &Noop{ - name: lc.Linter.Name(), - desc: lc.Linter.Desc(), - run: func(pass *analysis.Pass) (any, error) { - return nil, nil - }, - } - +func (lc *Config) WithNoopFallback(cfg *config.Config, cond func(cfg *config.Config) error) *Config { + if err := cond(cfg); err != nil { + lc.Linter = NewNoop(lc.Linter, err.Error()) lc.LoadMode = 0 + return lc.WithLoadFiles() } return lc } +func IsGoLowerThanGo122() func(cfg *config.Config) error { + return func(cfg *config.Config) error { + if cfg == nil || config.IsGoGreaterThanOrEqual(cfg.Run.Go, "1.22") { + return nil + } + + return fmt.Errorf("this linter is disabled because the Go version (%s) of your project is lower than Go 1.22", cfg.Run.Go) + } +} + func NewConfig(linter Linter) *Config { lc := &Config{ Linter: linter, diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/context.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/context.go index a9f9d7d7f..5c03630b2 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/context.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/context.go @@ -8,7 +8,7 @@ import ( "github.com/golangci/golangci-lint/internal/pkgcache" "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/fsutils" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load" + "github.com/golangci/golangci-lint/pkg/goanalysis/load" "github.com/golangci/golangci-lint/pkg/logutils" ) @@ -22,7 +22,6 @@ type Context struct { Cfg *config.Config FileCache *fsutils.FileCache - LineCache *fsutils.LineCache Log logutils.Log PkgCache *pkgcache.Cache diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/linter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/linter.go index a65d6b927..088aa3d78 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/linter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/linter.go @@ -3,8 +3,7 @@ package linter import ( "context" - "golang.org/x/tools/go/analysis" - + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/result" ) @@ -15,14 +14,47 @@ type Linter interface { } type Noop struct { - name string - desc string - run func(pass *analysis.Pass) (any, error) + name string + desc string + reason string + level DeprecationLevel +} + +func NewNoop(l Linter, reason string) Noop { + return Noop{ + name: l.Name(), + desc: l.Desc(), + reason: reason, + } +} + +func NewNoopDeprecated(name string, cfg *config.Config, level DeprecationLevel) Noop { + noop := Noop{ + name: name, + desc: "Deprecated", + reason: "This linter is fully inactivated: it will not produce any reports.", + level: level, + } + + if cfg.InternalCmdTest { + noop.reason = "" + } + + return noop } func (n Noop) Run(_ context.Context, lintCtx *Context) ([]result.Issue, error) { - lintCtx.Log.Warnf("%s is disabled because of generics."+ - " You can track the evolution of the generics support by following the https://github.com/golangci/golangci-lint/issues/2649.", n.name) + if n.reason == "" { + return nil, nil + } + + switch n.level { + case DeprecationError: + lintCtx.Log.Errorf("%s: %s", n.name, n.reason) + default: + lintCtx.Log.Warnf("%s: %s", n.name, n.reason) + } + return nil, nil } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_linter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_linter.go new file mode 100644 index 000000000..7b83a8153 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_linter.go @@ -0,0 +1,841 @@ +package lintersdb + +import ( + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/golinters" + "github.com/golangci/golangci-lint/pkg/golinters/asasalint" + "github.com/golangci/golangci-lint/pkg/golinters/asciicheck" + "github.com/golangci/golangci-lint/pkg/golinters/bidichk" + "github.com/golangci/golangci-lint/pkg/golinters/bodyclose" + "github.com/golangci/golangci-lint/pkg/golinters/canonicalheader" + "github.com/golangci/golangci-lint/pkg/golinters/containedctx" + "github.com/golangci/golangci-lint/pkg/golinters/contextcheck" + "github.com/golangci/golangci-lint/pkg/golinters/copyloopvar" + "github.com/golangci/golangci-lint/pkg/golinters/cyclop" + "github.com/golangci/golangci-lint/pkg/golinters/decorder" + "github.com/golangci/golangci-lint/pkg/golinters/depguard" + "github.com/golangci/golangci-lint/pkg/golinters/dogsled" + "github.com/golangci/golangci-lint/pkg/golinters/dupl" + "github.com/golangci/golangci-lint/pkg/golinters/dupword" + "github.com/golangci/golangci-lint/pkg/golinters/durationcheck" + "github.com/golangci/golangci-lint/pkg/golinters/err113" + "github.com/golangci/golangci-lint/pkg/golinters/errcheck" + "github.com/golangci/golangci-lint/pkg/golinters/errchkjson" + "github.com/golangci/golangci-lint/pkg/golinters/errname" + "github.com/golangci/golangci-lint/pkg/golinters/errorlint" + "github.com/golangci/golangci-lint/pkg/golinters/execinquery" + "github.com/golangci/golangci-lint/pkg/golinters/exhaustive" + "github.com/golangci/golangci-lint/pkg/golinters/exhaustruct" + "github.com/golangci/golangci-lint/pkg/golinters/exportloopref" + "github.com/golangci/golangci-lint/pkg/golinters/fatcontext" + "github.com/golangci/golangci-lint/pkg/golinters/forbidigo" + "github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert" + "github.com/golangci/golangci-lint/pkg/golinters/funlen" + "github.com/golangci/golangci-lint/pkg/golinters/gci" + "github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter" + "github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives" + "github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals" + "github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits" + "github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype" + "github.com/golangci/golangci-lint/pkg/golinters/gocognit" + "github.com/golangci/golangci-lint/pkg/golinters/goconst" + "github.com/golangci/golangci-lint/pkg/golinters/gocritic" + "github.com/golangci/golangci-lint/pkg/golinters/gocyclo" + "github.com/golangci/golangci-lint/pkg/golinters/godot" + "github.com/golangci/golangci-lint/pkg/golinters/godox" + "github.com/golangci/golangci-lint/pkg/golinters/gofmt" + "github.com/golangci/golangci-lint/pkg/golinters/gofumpt" + "github.com/golangci/golangci-lint/pkg/golinters/goheader" + "github.com/golangci/golangci-lint/pkg/golinters/goimports" + "github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives" + "github.com/golangci/golangci-lint/pkg/golinters/gomodguard" + "github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname" + "github.com/golangci/golangci-lint/pkg/golinters/gosec" + "github.com/golangci/golangci-lint/pkg/golinters/gosimple" + "github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan" + "github.com/golangci/golangci-lint/pkg/golinters/govet" + "github.com/golangci/golangci-lint/pkg/golinters/grouper" + "github.com/golangci/golangci-lint/pkg/golinters/importas" + "github.com/golangci/golangci-lint/pkg/golinters/inamedparam" + "github.com/golangci/golangci-lint/pkg/golinters/ineffassign" + "github.com/golangci/golangci-lint/pkg/golinters/interfacebloat" + "github.com/golangci/golangci-lint/pkg/golinters/intrange" + "github.com/golangci/golangci-lint/pkg/golinters/ireturn" + "github.com/golangci/golangci-lint/pkg/golinters/lll" + "github.com/golangci/golangci-lint/pkg/golinters/loggercheck" + "github.com/golangci/golangci-lint/pkg/golinters/maintidx" + "github.com/golangci/golangci-lint/pkg/golinters/makezero" + "github.com/golangci/golangci-lint/pkg/golinters/mirror" + "github.com/golangci/golangci-lint/pkg/golinters/misspell" + "github.com/golangci/golangci-lint/pkg/golinters/mnd" + "github.com/golangci/golangci-lint/pkg/golinters/musttag" + "github.com/golangci/golangci-lint/pkg/golinters/nakedret" + "github.com/golangci/golangci-lint/pkg/golinters/nestif" + "github.com/golangci/golangci-lint/pkg/golinters/nilerr" + "github.com/golangci/golangci-lint/pkg/golinters/nilnil" + "github.com/golangci/golangci-lint/pkg/golinters/nlreturn" + "github.com/golangci/golangci-lint/pkg/golinters/noctx" + "github.com/golangci/golangci-lint/pkg/golinters/nolintlint" + "github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns" + "github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport" + "github.com/golangci/golangci-lint/pkg/golinters/paralleltest" + "github.com/golangci/golangci-lint/pkg/golinters/perfsprint" + "github.com/golangci/golangci-lint/pkg/golinters/prealloc" + "github.com/golangci/golangci-lint/pkg/golinters/predeclared" + "github.com/golangci/golangci-lint/pkg/golinters/promlinter" + "github.com/golangci/golangci-lint/pkg/golinters/protogetter" + "github.com/golangci/golangci-lint/pkg/golinters/reassign" + "github.com/golangci/golangci-lint/pkg/golinters/revive" + "github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck" + "github.com/golangci/golangci-lint/pkg/golinters/sloglint" + "github.com/golangci/golangci-lint/pkg/golinters/spancheck" + "github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck" + "github.com/golangci/golangci-lint/pkg/golinters/staticcheck" + "github.com/golangci/golangci-lint/pkg/golinters/stylecheck" + "github.com/golangci/golangci-lint/pkg/golinters/tagalign" + "github.com/golangci/golangci-lint/pkg/golinters/tagliatelle" + "github.com/golangci/golangci-lint/pkg/golinters/tenv" + "github.com/golangci/golangci-lint/pkg/golinters/testableexamples" + "github.com/golangci/golangci-lint/pkg/golinters/testifylint" + "github.com/golangci/golangci-lint/pkg/golinters/testpackage" + "github.com/golangci/golangci-lint/pkg/golinters/thelper" + "github.com/golangci/golangci-lint/pkg/golinters/tparallel" + "github.com/golangci/golangci-lint/pkg/golinters/unconvert" + "github.com/golangci/golangci-lint/pkg/golinters/unparam" + "github.com/golangci/golangci-lint/pkg/golinters/unused" + "github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars" + "github.com/golangci/golangci-lint/pkg/golinters/varnamelen" + "github.com/golangci/golangci-lint/pkg/golinters/wastedassign" + "github.com/golangci/golangci-lint/pkg/golinters/whitespace" + "github.com/golangci/golangci-lint/pkg/golinters/wrapcheck" + "github.com/golangci/golangci-lint/pkg/golinters/wsl" + "github.com/golangci/golangci-lint/pkg/golinters/zerologlint" + "github.com/golangci/golangci-lint/pkg/lint/linter" +) + +// LinterBuilder builds the "internal" linters based on the configuration. +type LinterBuilder struct{} + +// NewLinterBuilder creates a new LinterBuilder. +func NewLinterBuilder() *LinterBuilder { + return &LinterBuilder{} +} + +// Build loads all the "internal" linters. +// The configuration is use for the linter settings. +func (LinterBuilder) Build(cfg *config.Config) ([]*linter.Config, error) { + if cfg == nil { + return nil, nil + } + + const megacheckName = "megacheck" + + // The linters are sorted in the alphabetical order (case-insensitive). + // When a new linter is added the version in `WithSince(...)` must be the next minor version of golangci-lint. + return []*linter.Config{ + linter.NewConfig(asasalint.New(&cfg.LintersSettings.Asasalint)). + WithSince("1.47.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/alingse/asasalint"), + + linter.NewConfig(asciicheck.New()). + WithSince("v1.26.0"). + WithPresets(linter.PresetBugs, linter.PresetStyle). + WithURL("https://github.com/tdakkota/asciicheck"), + + linter.NewConfig(bidichk.New(&cfg.LintersSettings.BiDiChk)). + WithSince("1.43.0"). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/breml/bidichk"), + + linter.NewConfig(bodyclose.New()). + WithSince("v1.18.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetPerformance, linter.PresetBugs). + WithURL("https://github.com/timakin/bodyclose"), + + linter.NewConfig(canonicalheader.New()). + WithSince("v1.58.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/lasiar/canonicalHeader"), + + linter.NewConfig(containedctx.New()). + WithSince("1.44.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/sivchari/containedctx"), + + linter.NewConfig(contextcheck.New()). + WithSince("v1.43.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/kkHAIKE/contextcheck"), + + linter.NewConfig(copyloopvar.New(&cfg.LintersSettings.CopyLoopVar)). + WithSince("v1.57.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/karamaru-alpha/copyloopvar"). + WithNoopFallback(cfg, linter.IsGoLowerThanGo122()), + + linter.NewConfig(cyclop.New(&cfg.LintersSettings.Cyclop)). + WithSince("v1.37.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetComplexity). + WithURL("https://github.com/bkielbasa/cyclop"), + + linter.NewConfig(decorder.New(&cfg.LintersSettings.Decorder)). + WithSince("v1.44.0"). + WithPresets(linter.PresetFormatting, linter.PresetStyle). + WithURL("https://gitlab.com/bosi/decorder"), + + linter.NewConfig(linter.NewNoopDeprecated("deadcode", cfg, linter.DeprecationError)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetUnused). + WithURL("https://github.com/remyoudompheng/go-misc/tree/master/deadcode"). + DeprecatedError("The owner seems to have abandoned the linter.", "v1.49.0", "unused"), + + linter.NewConfig(depguard.New(&cfg.LintersSettings.Depguard)). + WithSince("v1.4.0"). + WithPresets(linter.PresetStyle, linter.PresetImport, linter.PresetModule). + WithURL("https://github.com/OpenPeeDeeP/depguard"), + + linter.NewConfig(dogsled.New(&cfg.LintersSettings.Dogsled)). + WithSince("v1.19.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/alexkohler/dogsled"), + + linter.NewConfig(dupl.New(&cfg.LintersSettings.Dupl)). + WithSince("v1.0.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/mibk/dupl"), + + linter.NewConfig(dupword.New(&cfg.LintersSettings.DupWord)). + WithSince("1.50.0"). + WithPresets(linter.PresetComment). + WithURL("https://github.com/Abirdcfly/dupword"), + + linter.NewConfig(durationcheck.New()). + WithSince("v1.37.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/charithe/durationcheck"), + + linter.NewConfig(errcheck.New(&cfg.LintersSettings.Errcheck)). + WithEnabledByDefault(). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs, linter.PresetError). + WithURL("https://github.com/kisielk/errcheck"), + + linter.NewConfig(errchkjson.New(&cfg.LintersSettings.ErrChkJSON)). + WithSince("1.44.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/breml/errchkjson"), + + linter.NewConfig(errname.New()). + WithSince("v1.42.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/Antonboom/errname"), + + linter.NewConfig(errorlint.New(&cfg.LintersSettings.ErrorLint)). + WithSince("v1.32.0"). + WithPresets(linter.PresetBugs, linter.PresetError). + WithLoadForGoAnalysis(). + WithURL("https://github.com/polyfloyd/go-errorlint"), + + linter.NewConfig(execinquery.New()). + WithSince("v1.46.0"). + WithPresets(linter.PresetSQL). + WithLoadForGoAnalysis(). + WithURL("https://github.com/1uf3/execinquery"). + DeprecatedWarning("The repository of the linter has been archived by the owner.", "v1.58.0", ""), + + linter.NewConfig(exhaustive.New(&cfg.LintersSettings.Exhaustive)). + WithSince(" v1.28.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/nishanths/exhaustive"), + + linter.NewConfig(linter.NewNoopDeprecated("exhaustivestruct", cfg, linter.DeprecationError)). + WithSince("v1.32.0"). + WithPresets(linter.PresetStyle, linter.PresetTest). + WithLoadForGoAnalysis(). + WithURL("https://github.com/mbilski/exhaustivestruct"). + DeprecatedError("The repository of the linter has been deprecated by the owner.", "v1.46.0", "exhaustruct"), + + linter.NewConfig(exhaustruct.New(&cfg.LintersSettings.Exhaustruct)). + WithSince("v1.46.0"). + WithPresets(linter.PresetStyle, linter.PresetTest). + WithLoadForGoAnalysis(). + WithURL("https://github.com/GaijinEntertainment/go-exhaustruct"), + + linter.NewConfig(exportloopref.New()). + WithSince("v1.28.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/kyoh86/exportloopref"), + + linter.NewConfig(forbidigo.New(&cfg.LintersSettings.Forbidigo)). + WithSince("v1.34.0"). + WithPresets(linter.PresetStyle). + // Strictly speaking, + // the additional information is only needed when forbidigoCfg.AnalyzeTypes is chosen by the user. + // But we don't know that here in all cases (sometimes config is not loaded), + // so we have to assume that it is needed to be on the safe side. + WithLoadForGoAnalysis(). + WithURL("https://github.com/ashanbrown/forbidigo"), + + linter.NewConfig(forcetypeassert.New()). + WithSince("v1.38.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/gostaticanalysis/forcetypeassert"), + + linter.NewConfig(fatcontext.New()). + WithSince("1.58.0"). + WithPresets(linter.PresetPerformance). + WithLoadForGoAnalysis(). + WithURL("https://github.com/Crocmagnon/fatcontext"), + + linter.NewConfig(funlen.New(&cfg.LintersSettings.Funlen)). + WithSince("v1.18.0"). + WithPresets(linter.PresetComplexity). + WithURL("https://github.com/ultraware/funlen"), + + linter.NewConfig(gci.New(&cfg.LintersSettings.Gci)). + WithSince("v1.30.0"). + WithPresets(linter.PresetFormatting, linter.PresetImport). + WithAutoFix(). + WithURL("https://github.com/daixiang0/gci"), + + linter.NewConfig(ginkgolinter.New(&cfg.LintersSettings.GinkgoLinter)). + WithSince("v1.51.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/nunnatsa/ginkgolinter"), + + linter.NewConfig(gocheckcompilerdirectives.New()). + WithSince("v1.51.0"). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/leighmcculloch/gocheckcompilerdirectives"), + + linter.NewConfig(gochecknoglobals.New()). + WithSince("v1.12.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/leighmcculloch/gochecknoglobals"), + + linter.NewConfig(gochecknoinits.New()). + WithSince("v1.12.0"). + WithPresets(linter.PresetStyle), + + linter.NewConfig(gochecksumtype.New()). + WithSince("v1.55.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/alecthomas/go-check-sumtype"), + + linter.NewConfig(gocognit.New(&cfg.LintersSettings.Gocognit)). + WithSince("v1.20.0"). + WithPresets(linter.PresetComplexity). + WithURL("https://github.com/uudashr/gocognit"), + + linter.NewConfig(goconst.New(&cfg.LintersSettings.Goconst)). + WithSince("v1.0.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/jgautheron/goconst"), + + linter.NewConfig(gocritic.New(&cfg.LintersSettings.Gocritic)). + WithSince("v1.12.0"). + WithPresets(linter.PresetStyle, linter.PresetMetaLinter). + WithLoadForGoAnalysis(). + WithAutoFix(). + WithURL("https://github.com/go-critic/go-critic"), + + linter.NewConfig(gocyclo.New(&cfg.LintersSettings.Gocyclo)). + WithSince("v1.0.0"). + WithPresets(linter.PresetComplexity). + WithURL("https://github.com/fzipp/gocyclo"), + + linter.NewConfig(godot.New(&cfg.LintersSettings.Godot)). + WithSince("v1.25.0"). + WithPresets(linter.PresetStyle, linter.PresetComment). + WithAutoFix(). + WithURL("https://github.com/tetafro/godot"), + + linter.NewConfig(godox.New(&cfg.LintersSettings.Godox)). + WithSince("v1.19.0"). + WithPresets(linter.PresetStyle, linter.PresetComment). + WithURL("https://github.com/matoous/godox"), + + linter.NewConfig(err113.New()). + WithSince("v1.26.0"). + WithPresets(linter.PresetStyle, linter.PresetError). + WithLoadForGoAnalysis(). + WithAlternativeNames("goerr113"). + WithURL("https://github.com/Djarvur/go-err113"), + + linter.NewConfig(gofmt.New(&cfg.LintersSettings.Gofmt)). + WithSince("v1.0.0"). + WithPresets(linter.PresetFormatting). + WithAutoFix(). + WithURL("https://pkg.go.dev/cmd/gofmt"), + + linter.NewConfig(gofumpt.New(&cfg.LintersSettings.Gofumpt)). + WithSince("v1.28.0"). + WithPresets(linter.PresetFormatting). + WithAutoFix(). + WithURL("https://github.com/mvdan/gofumpt"), + + linter.NewConfig(goheader.New(&cfg.LintersSettings.Goheader)). + WithSince("v1.28.0"). + WithPresets(linter.PresetStyle). + WithAutoFix(). + WithURL("https://github.com/denis-tingaikin/go-header"), + + linter.NewConfig(goimports.New(&cfg.LintersSettings.Goimports)). + WithSince("v1.20.0"). + WithPresets(linter.PresetFormatting, linter.PresetImport). + WithAutoFix(). + WithURL("https://pkg.go.dev/golang.org/x/tools/cmd/goimports"), + + linter.NewConfig(linter.NewNoopDeprecated("golint", cfg, linter.DeprecationError)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/golang/lint"). + DeprecatedError("The repository of the linter has been archived by the owner.", "v1.41.0", "revive"), + + linter.NewConfig(mnd.New(&cfg.LintersSettings.Mnd)). + WithSince("v1.22.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/tommy-muehle/go-mnd"), + + linter.NewConfig(mnd.NewGoMND(&cfg.LintersSettings.Gomnd)). + WithSince("v1.22.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/tommy-muehle/go-mnd"). + DeprecatedWarning("The linter has been renamed.", "v1.58.0", "mnd"), + + linter.NewConfig(gomoddirectives.New(&cfg.LintersSettings.GoModDirectives)). + WithSince("v1.39.0"). + WithPresets(linter.PresetStyle, linter.PresetModule). + WithURL("https://github.com/ldez/gomoddirectives"), + + linter.NewConfig(gomodguard.New(&cfg.LintersSettings.Gomodguard)). + WithSince("v1.25.0"). + WithPresets(linter.PresetStyle, linter.PresetImport, linter.PresetModule). + WithURL("https://github.com/ryancurrah/gomodguard"), + + linter.NewConfig(goprintffuncname.New()). + WithSince("v1.23.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/jirfag/go-printf-func-name"), + + linter.NewConfig(gosec.New(&cfg.LintersSettings.Gosec)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/securego/gosec"). + WithAlternativeNames("gas"), + + linter.NewConfig(gosimple.New(&cfg.LintersSettings.Gosimple)). + WithEnabledByDefault(). + WithSince("v1.20.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithAlternativeNames(megacheckName). + WithURL("https://github.com/dominikh/go-tools/tree/master/simple"), + + linter.NewConfig(gosmopolitan.New(&cfg.LintersSettings.Gosmopolitan)). + WithSince("v1.53.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/xen0n/gosmopolitan"), + + linter.NewConfig(govet.New(&cfg.LintersSettings.Govet)). + WithEnabledByDefault(). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs, linter.PresetMetaLinter). + WithAlternativeNames("vet", "vetshadow"). + WithURL("https://pkg.go.dev/cmd/vet"), + + linter.NewConfig(grouper.New(&cfg.LintersSettings.Grouper)). + WithSince("v1.44.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/leonklingele/grouper"), + + linter.NewConfig(linter.NewNoopDeprecated("ifshort", cfg, linter.DeprecationError)). + WithSince("v1.36.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/esimonov/ifshort"). + DeprecatedError("The repository of the linter has been deprecated by the owner.", "v1.48.0", ""), + + linter.NewConfig(importas.New(&cfg.LintersSettings.ImportAs)). + WithSince("v1.38.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/julz/importas"), + + linter.NewConfig(inamedparam.New(&cfg.LintersSettings.Inamedparam)). + WithSince("v1.55.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/macabu/inamedparam"), + + linter.NewConfig(ineffassign.New()). + WithEnabledByDefault(). + WithSince("v1.0.0"). + WithPresets(linter.PresetUnused). + WithURL("https://github.com/gordonklaus/ineffassign"), + + linter.NewConfig(interfacebloat.New(&cfg.LintersSettings.InterfaceBloat)). + WithSince("v1.49.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/sashamelentyev/interfacebloat"), + + linter.NewConfig(linter.NewNoopDeprecated("interfacer", cfg, linter.DeprecationError)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/mvdan/interfacer"). + DeprecatedError("The repository of the linter has been archived by the owner.", "v1.38.0", ""), + + linter.NewConfig(intrange.New()). + WithSince("v1.57.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/ckaznocha/intrange"). + WithNoopFallback(cfg, linter.IsGoLowerThanGo122()), + + linter.NewConfig(ireturn.New(&cfg.LintersSettings.Ireturn)). + WithSince("v1.43.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/butuzov/ireturn"), + + linter.NewConfig(lll.New(&cfg.LintersSettings.Lll)). + WithSince("v1.8.0"). + WithPresets(linter.PresetStyle), + + linter.NewConfig(loggercheck.New(&cfg.LintersSettings.LoggerCheck)). + WithSince("v1.49.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle, linter.PresetBugs). + WithAlternativeNames("logrlint"). + WithURL("https://github.com/timonwong/loggercheck"), + + linter.NewConfig(maintidx.New(&cfg.LintersSettings.MaintIdx)). + WithSince("v1.44.0"). + WithPresets(linter.PresetComplexity). + WithURL("https://github.com/yagipy/maintidx"), + + linter.NewConfig(makezero.New(&cfg.LintersSettings.Makezero)). + WithSince("v1.34.0"). + WithPresets(linter.PresetStyle, linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/ashanbrown/makezero"), + + linter.NewConfig(linter.NewNoopDeprecated("maligned", cfg, linter.DeprecationError)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetPerformance). + WithURL("https://github.com/mdempsky/maligned"). + DeprecatedError("The repository of the linter has been archived by the owner.", "v1.38.0", "govet 'fieldalignment'"), + + linter.NewConfig(mirror.New()). + WithSince("v1.53.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithAutoFix(). + WithURL("https://github.com/butuzov/mirror"), + + linter.NewConfig(misspell.New(&cfg.LintersSettings.Misspell)). + WithSince("v1.8.0"). + WithPresets(linter.PresetStyle, linter.PresetComment). + WithAutoFix(). + WithURL("https://github.com/client9/misspell"), + + linter.NewConfig(musttag.New(&cfg.LintersSettings.MustTag)). + WithSince("v1.51.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle, linter.PresetBugs). + WithURL("https://github.com/go-simpler/musttag"), + + linter.NewConfig(nakedret.New(&cfg.LintersSettings.Nakedret)). + WithSince("v1.19.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/alexkohler/nakedret"), + + linter.NewConfig(nestif.New(&cfg.LintersSettings.Nestif)). + WithSince("v1.25.0"). + WithPresets(linter.PresetComplexity). + WithURL("https://github.com/nakabonne/nestif"), + + linter.NewConfig(nilerr.New()). + WithSince("v1.38.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/gostaticanalysis/nilerr"), + + linter.NewConfig(nilnil.New(&cfg.LintersSettings.NilNil)). + WithSince("v1.43.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/Antonboom/nilnil"), + + linter.NewConfig(nlreturn.New(&cfg.LintersSettings.Nlreturn)). + WithSince("v1.30.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/ssgreg/nlreturn"), + + linter.NewConfig(noctx.New()). + WithSince("v1.28.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetPerformance, linter.PresetBugs). + WithURL("https://github.com/sonatard/noctx"), + + linter.NewConfig(nonamedreturns.New(&cfg.LintersSettings.NoNamedReturns)). + WithSince("v1.46.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/firefart/nonamedreturns"), + + linter.NewConfig(linter.NewNoopDeprecated("nosnakecase", cfg, linter.DeprecationError)). + WithSince("v1.47.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/sivchari/nosnakecase"). + DeprecatedError("The repository of the linter has been deprecated by the owner.", "v1.48.1", "revive 'var-naming'"), + + linter.NewConfig(nosprintfhostport.New()). + WithSince("v1.46.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/stbenjam/no-sprintf-host-port"), + + linter.NewConfig(paralleltest.New(&cfg.LintersSettings.ParallelTest)). + WithSince("v1.33.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle, linter.PresetTest). + WithURL("https://github.com/kunwardeep/paralleltest"), + + linter.NewConfig(perfsprint.New(&cfg.LintersSettings.PerfSprint)). + WithSince("v1.55.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetPerformance). + WithURL("https://github.com/catenacyber/perfsprint"), + + linter.NewConfig(prealloc.New(&cfg.LintersSettings.Prealloc)). + WithSince("v1.19.0"). + WithPresets(linter.PresetPerformance). + WithURL("https://github.com/alexkohler/prealloc"), + + linter.NewConfig(predeclared.New(&cfg.LintersSettings.Predeclared)). + WithSince("v1.35.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/nishanths/predeclared"), + + linter.NewConfig(promlinter.New(&cfg.LintersSettings.Promlinter)). + WithSince("v1.40.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/yeya24/promlinter"), + + linter.NewConfig(protogetter.New(&cfg.LintersSettings.ProtoGetter)). + WithSince("v1.55.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithAutoFix(). + WithURL("https://github.com/ghostiam/protogetter"), + + linter.NewConfig(reassign.New(&cfg.LintersSettings.Reassign)). + WithSince("1.49.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/curioswitch/go-reassign"), + + linter.NewConfig(revive.New(&cfg.LintersSettings.Revive)). + WithSince("v1.37.0"). + WithPresets(linter.PresetStyle, linter.PresetMetaLinter). + ConsiderSlow(). + WithURL("https://github.com/mgechev/revive"), + + linter.NewConfig(rowserrcheck.New(&cfg.LintersSettings.RowsErrCheck)). + WithSince("v1.23.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs, linter.PresetSQL). + WithURL("https://github.com/jingyugao/rowserrcheck"), + + linter.NewConfig(sloglint.New(&cfg.LintersSettings.SlogLint)). + WithSince("v1.55.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle, linter.PresetFormatting). + WithURL("https://github.com/go-simpler/sloglint"), + + linter.NewConfig(linter.NewNoopDeprecated("scopelint", cfg, linter.DeprecationError)). + WithSince("v1.12.0"). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/kyoh86/scopelint"). + DeprecatedError("The repository of the linter has been deprecated by the owner.", "v1.39.0", "exportloopref"), + + linter.NewConfig(sqlclosecheck.New()). + WithSince("v1.28.0"). + WithPresets(linter.PresetBugs, linter.PresetSQL). + WithLoadForGoAnalysis(). + WithURL("https://github.com/ryanrolds/sqlclosecheck"), + + linter.NewConfig(spancheck.New(&cfg.LintersSettings.Spancheck)). + WithSince("v1.56.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/jjti/go-spancheck"), + + linter.NewConfig(staticcheck.New(&cfg.LintersSettings.Staticcheck)). + WithEnabledByDefault(). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs, linter.PresetMetaLinter). + WithAlternativeNames(megacheckName). + WithURL("https://staticcheck.io/"), + + linter.NewConfig(linter.NewNoopDeprecated("structcheck", cfg, linter.DeprecationError)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetUnused). + WithURL("https://github.com/opennota/check"). + DeprecatedError("The owner seems to have abandoned the linter.", "v1.49.0", "unused"), + + linter.NewConfig(stylecheck.New(&cfg.LintersSettings.Stylecheck)). + WithSince("v1.20.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/dominikh/go-tools/tree/master/stylecheck"), + + linter.NewConfig(tagalign.New(&cfg.LintersSettings.TagAlign)). + WithSince("v1.53.0"). + WithPresets(linter.PresetStyle, linter.PresetFormatting). + WithAutoFix(). + WithURL("https://github.com/4meepo/tagalign"), + + linter.NewConfig(tagliatelle.New(&cfg.LintersSettings.Tagliatelle)). + WithSince("v1.40.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/ldez/tagliatelle"), + + linter.NewConfig(tenv.New(&cfg.LintersSettings.Tenv)). + WithSince("v1.43.0"). + WithPresets(linter.PresetTest). + WithLoadForGoAnalysis(). + WithURL("https://github.com/sivchari/tenv"), + + linter.NewConfig(testableexamples.New()). + WithSince("v1.50.0"). + WithPresets(linter.PresetTest). + WithURL("https://github.com/maratori/testableexamples"), + + linter.NewConfig(testifylint.New(&cfg.LintersSettings.Testifylint)). + WithSince("v1.55.0"). + WithPresets(linter.PresetTest, linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/Antonboom/testifylint"), + + linter.NewConfig(testpackage.New(&cfg.LintersSettings.Testpackage)). + WithSince("v1.25.0"). + WithPresets(linter.PresetStyle, linter.PresetTest). + WithURL("https://github.com/maratori/testpackage"), + + linter.NewConfig(thelper.New(&cfg.LintersSettings.Thelper)). + WithSince("v1.34.0"). + WithPresets(linter.PresetTest). + WithLoadForGoAnalysis(). + WithURL("https://github.com/kulti/thelper"), + + linter.NewConfig(tparallel.New()). + WithSince("v1.32.0"). + WithPresets(linter.PresetStyle, linter.PresetTest). + WithLoadForGoAnalysis(). + WithURL("https://github.com/moricho/tparallel"), + + linter.NewConfig(golinters.NewTypecheck()). + WithInternal(). + WithEnabledByDefault(). + WithSince("v1.3.0"), + + linter.NewConfig(unconvert.New(&cfg.LintersSettings.Unconvert)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/mdempsky/unconvert"), + + linter.NewConfig(unparam.New(&cfg.LintersSettings.Unparam)). + WithSince("v1.9.0"). + WithPresets(linter.PresetUnused). + WithLoadForGoAnalysis(). + WithURL("https://github.com/mvdan/unparam"), + + linter.NewConfig(unused.New(&cfg.LintersSettings.Unused, &cfg.LintersSettings.Staticcheck)). + WithEnabledByDefault(). + WithSince("v1.20.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetUnused). + WithAlternativeNames(megacheckName). + ConsiderSlow(). + WithChangeTypes(). + WithURL("https://github.com/dominikh/go-tools/tree/master/unused"), + + linter.NewConfig(usestdlibvars.New(&cfg.LintersSettings.UseStdlibVars)). + WithSince("v1.48.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/sashamelentyev/usestdlibvars"), + + linter.NewConfig(linter.NewNoopDeprecated("varcheck", cfg, linter.DeprecationError)). + WithSince("v1.0.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetUnused). + WithURL("https://github.com/opennota/check"). + DeprecatedError("The owner seems to have abandoned the linter.", "v1.49.0", "unused"), + + linter.NewConfig(varnamelen.New(&cfg.LintersSettings.Varnamelen)). + WithSince("v1.43.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/blizzy78/varnamelen"), + + linter.NewConfig(wastedassign.New()). + WithSince("v1.38.0"). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/sanposhiho/wastedassign"), + + linter.NewConfig(whitespace.New(&cfg.LintersSettings.Whitespace)). + WithSince("v1.19.0"). + WithPresets(linter.PresetStyle). + WithAutoFix(). + WithURL("https://github.com/ultraware/whitespace"), + + linter.NewConfig(wrapcheck.New(&cfg.LintersSettings.Wrapcheck)). + WithSince("v1.32.0"). + WithPresets(linter.PresetStyle, linter.PresetError). + WithLoadForGoAnalysis(). + WithURL("https://github.com/tomarrell/wrapcheck"), + + linter.NewConfig(wsl.New(&cfg.LintersSettings.WSL)). + WithSince("v1.20.0"). + WithPresets(linter.PresetStyle). + WithURL("https://github.com/bombsimon/wsl"), + + linter.NewConfig(zerologlint.New()). + WithSince("v1.53.0"). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/ykadowak/zerologlint"), + + // nolintlint must be last because it looks at the results of all the previous linters for unused nolint directives + linter.NewConfig(nolintlint.New(&cfg.LintersSettings.NoLintLint)). + WithSince("v1.26.0"). + WithPresets(linter.PresetStyle). + WithAutoFix(). + WithURL("https://github.com/golangci/golangci-lint/blob/master/pkg/golinters/nolintlint/README.md"), + }, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_go.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_go.go new file mode 100644 index 000000000..c6dbaf793 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_go.go @@ -0,0 +1,138 @@ +package lintersdb + +import ( + "errors" + "fmt" + "path/filepath" + "plugin" + + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/logutils" +) + +const goPluginType = "goplugin" + +type AnalyzerPlugin interface { + GetAnalyzers() []*analysis.Analyzer +} + +// PluginGoBuilder builds the custom linters (Go plugin) based on the configuration. +type PluginGoBuilder struct { + log logutils.Log +} + +// NewPluginGoBuilder creates new PluginGoBuilder. +func NewPluginGoBuilder(log logutils.Log) *PluginGoBuilder { + return &PluginGoBuilder{log: log} +} + +// Build loads custom linters that are specified in the golangci-lint config file. +func (b *PluginGoBuilder) Build(cfg *config.Config) ([]*linter.Config, error) { + if cfg == nil || b.log == nil { + return nil, nil + } + + var linters []*linter.Config + + for name, settings := range cfg.LintersSettings.Custom { + if settings.Type != goPluginType && settings.Type != "" { + continue + } + + settings := settings + + lc, err := b.loadConfig(cfg, name, &settings) + if err != nil { + return nil, fmt.Errorf("unable to load custom analyzer %q: %s, %w", name, settings.Path, err) + } + linters = append(linters, lc) + } + + return linters, nil +} + +// loadConfig loads the configuration of private linters. +// Private linters are dynamically loaded from .so plugin files. +func (b *PluginGoBuilder) loadConfig(cfg *config.Config, name string, settings *config.CustomLinterSettings) (*linter.Config, error) { + analyzers, err := b.getAnalyzerPlugin(cfg, settings.Path, settings.Settings) + if err != nil { + return nil, err + } + + b.log.Infof("Loaded %s: %s", settings.Path, name) + + customLinter := goanalysis.NewLinter(name, settings.Description, analyzers, nil). + WithLoadMode(goanalysis.LoadModeTypesInfo) + + linterConfig := linter.NewConfig(customLinter). + WithEnabledByDefault(). + WithLoadForGoAnalysis(). + WithURL(settings.OriginalURL) + + return linterConfig, nil +} + +// getAnalyzerPlugin loads a private linter as specified in the config file, +// loads the plugin from a .so file, +// and returns the 'AnalyzerPlugin' interface implemented by the private plugin. +// An error is returned if the private linter cannot be loaded +// or the linter does not implement the AnalyzerPlugin interface. +func (b *PluginGoBuilder) getAnalyzerPlugin(cfg *config.Config, path string, settings any) ([]*analysis.Analyzer, error) { + if !filepath.IsAbs(path) { + // resolve non-absolute paths relative to config file's directory + path = filepath.Join(cfg.GetConfigDir(), path) + } + + plug, err := plugin.Open(path) + if err != nil { + return nil, err + } + + analyzers, err := b.lookupPlugin(plug, settings) + if err != nil { + return nil, fmt.Errorf("lookup plugin %s: %w", path, err) + } + + return analyzers, nil +} + +func (b *PluginGoBuilder) lookupPlugin(plug *plugin.Plugin, settings any) ([]*analysis.Analyzer, error) { + symbol, err := plug.Lookup("New") + if err != nil { + analyzers, errP := b.lookupAnalyzerPlugin(plug) + if errP != nil { + return nil, errors.Join(err, errP) + } + + return analyzers, nil + } + + // The type func cannot be used here, must be the explicit signature. + constructor, ok := symbol.(func(any) ([]*analysis.Analyzer, error)) + if !ok { + return nil, fmt.Errorf("plugin does not abide by 'New' function: %T", symbol) + } + + return constructor(settings) +} + +func (b *PluginGoBuilder) lookupAnalyzerPlugin(plug *plugin.Plugin) ([]*analysis.Analyzer, error) { + symbol, err := plug.Lookup("AnalyzerPlugin") + if err != nil { + return nil, err + } + + b.log.Warnf("plugin: 'AnalyzerPlugin' plugins are deprecated, please use the new plugin signature: " + + "https://golangci-lint.run/plugins/go-plugins#create-a-plugin") + + analyzerPlugin, ok := symbol.(AnalyzerPlugin) + if !ok { + return nil, fmt.Errorf("plugin does not abide by 'AnalyzerPlugin' interface: %T", symbol) + } + + return analyzerPlugin.GetAnalyzers(), nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_module.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_module.go new file mode 100644 index 000000000..60fb58d8c --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/builder_plugin_module.go @@ -0,0 +1,85 @@ +package lintersdb + +import ( + "fmt" + "strings" + + "github.com/golangci/plugin-module-register/register" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/logutils" +) + +const modulePluginType = "module" + +// PluginModuleBuilder builds the custom linters (module plugin) based on the configuration. +type PluginModuleBuilder struct { + log logutils.Log +} + +// NewPluginModuleBuilder creates new PluginModuleBuilder. +func NewPluginModuleBuilder(log logutils.Log) *PluginModuleBuilder { + return &PluginModuleBuilder{log: log} +} + +// Build loads custom linters that are specified in the golangci-lint config file. +func (b *PluginModuleBuilder) Build(cfg *config.Config) ([]*linter.Config, error) { + if cfg == nil || b.log == nil { + return nil, nil + } + + var linters []*linter.Config + + for name, settings := range cfg.LintersSettings.Custom { + if settings.Type != modulePluginType { + continue + } + + b.log.Infof("Loaded %s: %s", settings.Path, name) + + newPlugin, err := register.GetPlugin(name) + if err != nil { + return nil, fmt.Errorf("plugin(%s): %w", name, err) + } + + p, err := newPlugin(settings.Settings) + if err != nil { + return nil, fmt.Errorf("plugin(%s): newPlugin %w", name, err) + } + + analyzers, err := p.BuildAnalyzers() + if err != nil { + return nil, fmt.Errorf("plugin(%s): BuildAnalyzers %w", name, err) + } + + customLinter := goanalysis.NewLinter(name, settings.Description, analyzers, nil) + + switch strings.ToLower(p.GetLoadMode()) { + case register.LoadModeSyntax: + customLinter = customLinter.WithLoadMode(goanalysis.LoadModeSyntax) + case register.LoadModeTypesInfo: + customLinter = customLinter.WithLoadMode(goanalysis.LoadModeTypesInfo) + default: + customLinter = customLinter.WithLoadMode(goanalysis.LoadModeTypesInfo) + } + + lc := linter.NewConfig(customLinter). + WithEnabledByDefault(). + WithURL(settings.OriginalURL) + + switch strings.ToLower(p.GetLoadMode()) { + case register.LoadModeSyntax: + // noop + case register.LoadModeTypesInfo: + lc = lc.WithLoadForGoAnalysis() + default: + lc = lc.WithLoadForGoAnalysis() + } + + linters = append(linters, lc) + } + + return linters, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/custom_linters.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/custom_linters.go deleted file mode 100644 index d0eaa7905..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/custom_linters.go +++ /dev/null @@ -1,131 +0,0 @@ -package lintersdb - -import ( - "fmt" - "os" - "path/filepath" - "plugin" - - "github.com/hashicorp/go-multierror" - "github.com/spf13/viper" - "golang.org/x/tools/go/analysis" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" -) - -type AnalyzerPlugin interface { - GetAnalyzers() []*analysis.Analyzer -} - -// getCustomLinterConfigs loads private linters that are specified in the golangci config file. -func (m *Manager) getCustomLinterConfigs() []*linter.Config { - if m.cfg == nil || m.log == nil { - return nil - } - - var linters []*linter.Config - - for name, settings := range m.cfg.LintersSettings.Custom { - lc, err := m.loadCustomLinterConfig(name, settings) - if err != nil { - m.log.Errorf("Unable to load custom analyzer %s:%s, %v", name, settings.Path, err) - } else { - linters = append(linters, lc) - } - } - - return linters -} - -// loadCustomLinterConfig loads the configuration of private linters. -// Private linters are dynamically loaded from .so plugin files. -func (m *Manager) loadCustomLinterConfig(name string, settings config.CustomLinterSettings) (*linter.Config, error) { - analyzers, err := m.getAnalyzerPlugin(settings.Path, settings.Settings) - if err != nil { - return nil, err - } - - m.log.Infof("Loaded %s: %s", settings.Path, name) - - customLinter := goanalysis.NewLinter(name, settings.Description, analyzers, nil). - WithLoadMode(goanalysis.LoadModeTypesInfo) - - linterConfig := linter.NewConfig(customLinter). - WithEnabledByDefault(). - WithLoadForGoAnalysis(). - WithURL(settings.OriginalURL) - - return linterConfig, nil -} - -// getAnalyzerPlugin loads a private linter as specified in the config file, -// loads the plugin from a .so file, -// and returns the 'AnalyzerPlugin' interface implemented by the private plugin. -// An error is returned if the private linter cannot be loaded -// or the linter does not implement the AnalyzerPlugin interface. -func (m *Manager) getAnalyzerPlugin(path string, settings any) ([]*analysis.Analyzer, error) { - if !filepath.IsAbs(path) { - // resolve non-absolute paths relative to config file's directory - configFilePath := viper.ConfigFileUsed() - absConfigFilePath, err := filepath.Abs(configFilePath) - if err != nil { - return nil, fmt.Errorf("could not get absolute representation of config file path %q: %v", configFilePath, err) - } - path = filepath.Join(filepath.Dir(absConfigFilePath), path) - } - - plug, err := plugin.Open(path) - if err != nil { - return nil, err - } - - analyzers, err := m.lookupPlugin(plug, settings) - if err != nil { - return nil, fmt.Errorf("lookup plugin %s: %w", path, err) - } - - return analyzers, nil -} - -func (m *Manager) lookupPlugin(plug *plugin.Plugin, settings any) ([]*analysis.Analyzer, error) { - symbol, err := plug.Lookup("New") - if err != nil { - analyzers, errP := m.lookupAnalyzerPlugin(plug) - if errP != nil { - // TODO(ldez): use `errors.Join` when we will upgrade to go1.20. - return nil, multierror.Append(err, errP) - } - - return analyzers, nil - } - - // The type func cannot be used here, must be the explicit signature. - constructor, ok := symbol.(func(any) ([]*analysis.Analyzer, error)) - if !ok { - return nil, fmt.Errorf("plugin does not abide by 'New' function: %T", symbol) - } - - return constructor(settings) -} - -func (m *Manager) lookupAnalyzerPlugin(plug *plugin.Plugin) ([]*analysis.Analyzer, error) { - symbol, err := plug.Lookup("AnalyzerPlugin") - if err != nil { - return nil, err - } - - // TODO(ldez): remove this env var (but keep the log) in the next minor version (v1.55.0) - if _, ok := os.LookupEnv("GOLANGCI_LINT_HIDE_WARNING_ABOUT_PLUGIN_API_DEPRECATION"); !ok { - m.log.Warnf("plugin: 'AnalyzerPlugin' plugins are deprecated, please use the new plugin signature: " + - "https://golangci-lint.run/contributing/new-linters/#create-a-plugin") - } - - analyzerPlugin, ok := symbol.(AnalyzerPlugin) - if !ok { - return nil, fmt.Errorf("plugin does not abide by 'AnalyzerPlugin' interface: %T", symbol) - } - - return analyzerPlugin.GetAnalyzers(), nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go deleted file mode 100644 index c5c7874e4..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go +++ /dev/null @@ -1,223 +0,0 @@ -package lintersdb - -import ( - "os" - "sort" - - "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" - "github.com/golangci/golangci-lint/pkg/lint/linter" - "github.com/golangci/golangci-lint/pkg/logutils" -) - -// EnvTestRun value: "1" -const EnvTestRun = "GL_TEST_RUN" - -type EnabledSet struct { - m *Manager - v *Validator - log logutils.Log - cfg *config.Config - debugf logutils.DebugFunc -} - -func NewEnabledSet(m *Manager, v *Validator, log logutils.Log, cfg *config.Config) *EnabledSet { - return &EnabledSet{ - m: m, - v: v, - log: log, - cfg: cfg, - debugf: logutils.Debug(logutils.DebugKeyEnabledLinters), - } -} - -//nolint:gocyclo // the complexity cannot be reduced. -func (es EnabledSet) build(lcfg *config.Linters, enabledByDefaultLinters []*linter.Config) map[string]*linter.Config { - es.debugf("Linters config: %#v", lcfg) - - resultLintersSet := map[string]*linter.Config{} - switch { - case len(lcfg.Presets) != 0: - break // imply --disable-all - case lcfg.EnableAll: - resultLintersSet = linterConfigsToMap(es.m.GetAllSupportedLinterConfigs()) - case lcfg.DisableAll: - break - default: - resultLintersSet = linterConfigsToMap(enabledByDefaultLinters) - } - - // --presets can only add linters to default set - for _, p := range lcfg.Presets { - for _, lc := range es.m.GetAllLinterConfigsForPreset(p) { - lc := lc - resultLintersSet[lc.Name()] = lc - } - } - - // --fast removes slow linters from current set. - // It should be after --presets to be able to run only fast linters in preset. - // It should be before --enable and --disable to be able to enable or disable specific linter. - if lcfg.Fast { - for name, lc := range resultLintersSet { - if lc.IsSlowLinter() { - delete(resultLintersSet, name) - } - } - } - - for _, name := range lcfg.Enable { - for _, lc := range es.m.GetLinterConfigs(name) { - // it's important to use lc.Name() nor name because name can be alias - resultLintersSet[lc.Name()] = lc - } - } - - for _, name := range lcfg.Disable { - for _, lc := range es.m.GetLinterConfigs(name) { - // it's important to use lc.Name() nor name because name can be alias - delete(resultLintersSet, lc.Name()) - } - } - - // typecheck is not a real linter and cannot be disabled. - if _, ok := resultLintersSet["typecheck"]; !ok && (es.cfg == nil || !es.cfg.InternalCmdTest) { - for _, lc := range es.m.GetLinterConfigs("typecheck") { - // it's important to use lc.Name() nor name because name can be alias - resultLintersSet[lc.Name()] = lc - } - } - - return resultLintersSet -} - -func (es EnabledSet) GetEnabledLintersMap() (map[string]*linter.Config, error) { - if err := es.v.validateEnabledDisabledLintersConfig(&es.cfg.Linters); err != nil { - return nil, err - } - - enabledLinters := es.build(&es.cfg.Linters, es.m.GetAllEnabledByDefaultLinters()) - if os.Getenv(EnvTestRun) == "1" { - es.verbosePrintLintersStatus(enabledLinters) - } - return enabledLinters, nil -} - -// GetOptimizedLinters returns enabled linters after optimization (merging) of multiple linters -// into a fewer number of linters. E.g. some go/analysis linters can be optimized into -// one metalinter for data reuse and speed up. -func (es EnabledSet) GetOptimizedLinters() ([]*linter.Config, error) { - if err := es.v.validateEnabledDisabledLintersConfig(&es.cfg.Linters); err != nil { - return nil, err - } - - resultLintersSet := es.build(&es.cfg.Linters, es.m.GetAllEnabledByDefaultLinters()) - es.verbosePrintLintersStatus(resultLintersSet) - es.combineGoAnalysisLinters(resultLintersSet) - - var resultLinters []*linter.Config - for _, lc := range resultLintersSet { - resultLinters = append(resultLinters, lc) - } - - // Make order of execution of linters (go/analysis metalinter and unused) stable. - sort.Slice(resultLinters, func(i, j int) bool { - a, b := resultLinters[i], resultLinters[j] - - if b.Name() == linter.LastLinter { - return true - } - - if a.Name() == linter.LastLinter { - return false - } - - if a.DoesChangeTypes != b.DoesChangeTypes { - return b.DoesChangeTypes // move type-changing linters to the end to optimize speed - } - return a.Name() < b.Name() - }) - - return resultLinters, nil -} - -func (es EnabledSet) combineGoAnalysisLinters(linters map[string]*linter.Config) { - var goanalysisLinters []*goanalysis.Linter - goanalysisPresets := map[string]bool{} - for _, lc := range linters { - lnt, ok := lc.Linter.(*goanalysis.Linter) - if !ok { - continue - } - if lnt.LoadMode() == goanalysis.LoadModeWholeProgram { - // It's ineffective by CPU and memory to run whole-program and incremental analyzers at once. - continue - } - goanalysisLinters = append(goanalysisLinters, lnt) - for _, p := range lc.InPresets { - goanalysisPresets[p] = true - } - } - - if len(goanalysisLinters) <= 1 { - es.debugf("Didn't combine go/analysis linters: got only %d linters", len(goanalysisLinters)) - return - } - - for _, lnt := range goanalysisLinters { - delete(linters, lnt.Name()) - } - - // Make order of execution of go/analysis analyzers stable. - sort.Slice(goanalysisLinters, func(i, j int) bool { - a, b := goanalysisLinters[i], goanalysisLinters[j] - - if b.Name() == linter.LastLinter { - return true - } - - if a.Name() == linter.LastLinter { - return false - } - - return a.Name() <= b.Name() - }) - - ml := goanalysis.NewMetaLinter(goanalysisLinters) - - var presets []string - for p := range goanalysisPresets { - presets = append(presets, p) - } - - mlConfig := &linter.Config{ - Linter: ml, - EnabledByDefault: false, - InPresets: presets, - AlternativeNames: nil, - OriginalURL: "", - } - - mlConfig = mlConfig.WithLoadForGoAnalysis() - - linters[ml.Name()] = mlConfig - es.debugf("Combined %d go/analysis linters into one metalinter", len(goanalysisLinters)) -} - -func (es EnabledSet) verbosePrintLintersStatus(lcs map[string]*linter.Config) { - var linterNames []string - for _, lc := range lcs { - if lc.Internal { - continue - } - - linterNames = append(linterNames, lc.Name()) - } - sort.StringSlice(linterNames).Sort() - es.log.Infof("Active %d linters: %s", len(linterNames), linterNames) - - if len(es.cfg.Linters.Presets) != 0 { - sort.StringSlice(es.cfg.Linters.Presets).Sort() - es.log.Infof("Active presets: %s", es.cfg.Linters.Presets) - } -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go index fd329ce57..0a487be92 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go @@ -1,937 +1,140 @@ package lintersdb import ( - "regexp" + "fmt" + "os" + "slices" + "sort" + + "golang.org/x/exp/maps" "github.com/golangci/golangci-lint/pkg/config" - "github.com/golangci/golangci-lint/pkg/golinters" + "github.com/golangci/golangci-lint/pkg/goanalysis" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/logutils" ) +type Builder interface { + Build(cfg *config.Config) ([]*linter.Config, error) +} + +// Manager is a type of database for all linters (internals or plugins). +// It provides methods to access to the linter sets. type Manager struct { + log logutils.Log + debugf logutils.DebugFunc + cfg *config.Config - log logutils.Log - nameToLCs map[string][]*linter.Config - customLinters []*linter.Config + linters []*linter.Config + + nameToLCs map[string][]*linter.Config } -func NewManager(cfg *config.Config, log logutils.Log) *Manager { - m := &Manager{cfg: cfg, log: log} - m.customLinters = m.getCustomLinterConfigs() +// NewManager creates a new Manager. +// This constructor will call the builders to build and store the linters. +func NewManager(log logutils.Log, cfg *config.Config, builders ...Builder) (*Manager, error) { + m := &Manager{ + log: log, + debugf: logutils.Debug(logutils.DebugKeyEnabledLinters), + nameToLCs: make(map[string][]*linter.Config), + } + + m.cfg = cfg + if cfg == nil { + m.cfg = config.NewDefault() + } + + for _, builder := range builders { + linters, err := builder.Build(m.cfg) + if err != nil { + return nil, fmt.Errorf("build linters: %w", err) + } + + m.linters = append(m.linters, linters...) + } - nameToLCs := make(map[string][]*linter.Config) - for _, lc := range m.GetAllSupportedLinterConfigs() { + for _, lc := range m.linters { for _, name := range lc.AllNames() { - nameToLCs[name] = append(nameToLCs[name], lc) + m.nameToLCs[name] = append(m.nameToLCs[name], lc) } } - m.nameToLCs = nameToLCs + err := NewValidator(m).Validate(m.cfg) + if err != nil { + return nil, err + } - return m + return m, nil } -func (Manager) AllPresets() []string { - return []string{ - linter.PresetBugs, - linter.PresetComment, - linter.PresetComplexity, - linter.PresetError, - linter.PresetFormatting, - linter.PresetImport, - linter.PresetMetaLinter, - linter.PresetModule, - linter.PresetPerformance, - linter.PresetSQL, - linter.PresetStyle, - linter.PresetTest, - linter.PresetUnused, - } +func (m *Manager) GetLinterConfigs(name string) []*linter.Config { + return m.nameToLCs[name] +} + +func (m *Manager) GetAllSupportedLinterConfigs() []*linter.Config { + return m.linters } -func (m Manager) allPresetsSet() map[string]bool { - ret := map[string]bool{} - for _, p := range m.AllPresets() { - ret[p] = true +func (m *Manager) GetAllLinterConfigsForPreset(p string) []*linter.Config { + var ret []*linter.Config + for _, lc := range m.linters { + if lc.IsDeprecated() { + continue + } + + if slices.Contains(lc.InPresets, p) { + ret = append(ret, lc) + } } + return ret } -func (m Manager) GetLinterConfigs(name string) []*linter.Config { - return m.nameToLCs[name] +func (m *Manager) GetEnabledLintersMap() (map[string]*linter.Config, error) { + enabledLinters := m.build(m.GetAllEnabledByDefaultLinters()) + + if os.Getenv(logutils.EnvTestRun) == "1" { + m.verbosePrintLintersStatus(enabledLinters) + } + + return enabledLinters, nil } -//nolint:funlen -func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { - var ( - asasalintCfg *config.AsasalintSettings - bidichkCfg *config.BiDiChkSettings - cyclopCfg *config.Cyclop - decorderCfg *config.DecorderSettings - depGuardCfg *config.DepGuardSettings - dogsledCfg *config.DogsledSettings - duplCfg *config.DuplSettings - dupwordCfg *config.DupWordSettings - errcheckCfg *config.ErrcheckSettings - errchkjsonCfg *config.ErrChkJSONSettings - errorlintCfg *config.ErrorLintSettings - exhaustiveCfg *config.ExhaustiveSettings - exhaustiveStructCfg *config.ExhaustiveStructSettings - exhaustructCfg *config.ExhaustructSettings - forbidigoCfg *config.ForbidigoSettings - funlenCfg *config.FunlenSettings - gciCfg *config.GciSettings - ginkgolinterCfg *config.GinkgoLinterSettings - gocognitCfg *config.GocognitSettings - goconstCfg *config.GoConstSettings - gocriticCfg *config.GoCriticSettings - gocycloCfg *config.GoCycloSettings - godotCfg *config.GodotSettings - godoxCfg *config.GodoxSettings - gofmtCfg *config.GoFmtSettings - gofumptCfg *config.GofumptSettings - goheaderCfg *config.GoHeaderSettings - goimportsCfg *config.GoImportsSettings - golintCfg *config.GoLintSettings - goMndCfg *config.GoMndSettings - goModDirectivesCfg *config.GoModDirectivesSettings - gomodguardCfg *config.GoModGuardSettings - gosecCfg *config.GoSecSettings - gosimpleCfg *config.StaticCheckSettings - gosmopolitanCfg *config.GosmopolitanSettings - govetCfg *config.GovetSettings - grouperCfg *config.GrouperSettings - ifshortCfg *config.IfshortSettings - importAsCfg *config.ImportAsSettings - interfaceBloatCfg *config.InterfaceBloatSettings - ireturnCfg *config.IreturnSettings - lllCfg *config.LllSettings - loggerCheckCfg *config.LoggerCheckSettings - maintIdxCfg *config.MaintIdxSettings - makezeroCfg *config.MakezeroSettings - malignedCfg *config.MalignedSettings - misspellCfg *config.MisspellSettings - musttagCfg *config.MustTagSettings - nakedretCfg *config.NakedretSettings - nestifCfg *config.NestifSettings - nilNilCfg *config.NilNilSettings - nlreturnCfg *config.NlreturnSettings - noLintLintCfg *config.NoLintLintSettings - noNamedReturnsCfg *config.NoNamedReturnsSettings - parallelTestCfg *config.ParallelTestSettings - preallocCfg *config.PreallocSettings - predeclaredCfg *config.PredeclaredSettings - promlinterCfg *config.PromlinterSettings - reassignCfg *config.ReassignSettings - reviveCfg *config.ReviveSettings - rowserrcheckCfg *config.RowsErrCheckSettings - sloglintCfg *config.SlogLintSettings - staticcheckCfg *config.StaticCheckSettings - structcheckCfg *config.StructCheckSettings - stylecheckCfg *config.StaticCheckSettings - tagalignCfg *config.TagAlignSettings - tagliatelleCfg *config.TagliatelleSettings - tenvCfg *config.TenvSettings - testifylintCfg *config.TestifylintSettings - testpackageCfg *config.TestpackageSettings - thelperCfg *config.ThelperSettings - unparamCfg *config.UnparamSettings - unusedCfg *config.UnusedSettings - usestdlibvars *config.UseStdlibVarsSettings - varcheckCfg *config.VarCheckSettings - varnamelenCfg *config.VarnamelenSettings - whitespaceCfg *config.WhitespaceSettings - wrapcheckCfg *config.WrapcheckSettings - wslCfg *config.WSLSettings - ) - - if m.cfg != nil { - asasalintCfg = &m.cfg.LintersSettings.Asasalint - bidichkCfg = &m.cfg.LintersSettings.BiDiChk - cyclopCfg = &m.cfg.LintersSettings.Cyclop - decorderCfg = &m.cfg.LintersSettings.Decorder - depGuardCfg = &m.cfg.LintersSettings.Depguard - dogsledCfg = &m.cfg.LintersSettings.Dogsled - duplCfg = &m.cfg.LintersSettings.Dupl - dupwordCfg = &m.cfg.LintersSettings.DupWord - errcheckCfg = &m.cfg.LintersSettings.Errcheck - errchkjsonCfg = &m.cfg.LintersSettings.ErrChkJSON - errorlintCfg = &m.cfg.LintersSettings.ErrorLint - exhaustiveCfg = &m.cfg.LintersSettings.Exhaustive - exhaustiveStructCfg = &m.cfg.LintersSettings.ExhaustiveStruct - exhaustructCfg = &m.cfg.LintersSettings.Exhaustruct - forbidigoCfg = &m.cfg.LintersSettings.Forbidigo - funlenCfg = &m.cfg.LintersSettings.Funlen - gciCfg = &m.cfg.LintersSettings.Gci - ginkgolinterCfg = &m.cfg.LintersSettings.GinkgoLinter - gocognitCfg = &m.cfg.LintersSettings.Gocognit - goconstCfg = &m.cfg.LintersSettings.Goconst - gocriticCfg = &m.cfg.LintersSettings.Gocritic - gocycloCfg = &m.cfg.LintersSettings.Gocyclo - godotCfg = &m.cfg.LintersSettings.Godot - godoxCfg = &m.cfg.LintersSettings.Godox - gofmtCfg = &m.cfg.LintersSettings.Gofmt - gofumptCfg = &m.cfg.LintersSettings.Gofumpt - goheaderCfg = &m.cfg.LintersSettings.Goheader - goimportsCfg = &m.cfg.LintersSettings.Goimports - golintCfg = &m.cfg.LintersSettings.Golint - goMndCfg = &m.cfg.LintersSettings.Gomnd - goModDirectivesCfg = &m.cfg.LintersSettings.GoModDirectives - gomodguardCfg = &m.cfg.LintersSettings.Gomodguard - gosecCfg = &m.cfg.LintersSettings.Gosec - gosimpleCfg = &m.cfg.LintersSettings.Gosimple - gosmopolitanCfg = &m.cfg.LintersSettings.Gosmopolitan - govetCfg = &m.cfg.LintersSettings.Govet - grouperCfg = &m.cfg.LintersSettings.Grouper - ifshortCfg = &m.cfg.LintersSettings.Ifshort - importAsCfg = &m.cfg.LintersSettings.ImportAs - interfaceBloatCfg = &m.cfg.LintersSettings.InterfaceBloat - ireturnCfg = &m.cfg.LintersSettings.Ireturn - lllCfg = &m.cfg.LintersSettings.Lll - loggerCheckCfg = &m.cfg.LintersSettings.LoggerCheck - maintIdxCfg = &m.cfg.LintersSettings.MaintIdx - makezeroCfg = &m.cfg.LintersSettings.Makezero - malignedCfg = &m.cfg.LintersSettings.Maligned - misspellCfg = &m.cfg.LintersSettings.Misspell - musttagCfg = &m.cfg.LintersSettings.MustTag - nakedretCfg = &m.cfg.LintersSettings.Nakedret - nestifCfg = &m.cfg.LintersSettings.Nestif - nilNilCfg = &m.cfg.LintersSettings.NilNil - nlreturnCfg = &m.cfg.LintersSettings.Nlreturn - noLintLintCfg = &m.cfg.LintersSettings.NoLintLint - noNamedReturnsCfg = &m.cfg.LintersSettings.NoNamedReturns - preallocCfg = &m.cfg.LintersSettings.Prealloc - parallelTestCfg = &m.cfg.LintersSettings.ParallelTest - predeclaredCfg = &m.cfg.LintersSettings.Predeclared - promlinterCfg = &m.cfg.LintersSettings.Promlinter - reassignCfg = &m.cfg.LintersSettings.Reassign - reviveCfg = &m.cfg.LintersSettings.Revive - rowserrcheckCfg = &m.cfg.LintersSettings.RowsErrCheck - sloglintCfg = &m.cfg.LintersSettings.SlogLint - staticcheckCfg = &m.cfg.LintersSettings.Staticcheck - structcheckCfg = &m.cfg.LintersSettings.Structcheck - stylecheckCfg = &m.cfg.LintersSettings.Stylecheck - tagalignCfg = &m.cfg.LintersSettings.TagAlign - tagliatelleCfg = &m.cfg.LintersSettings.Tagliatelle - tenvCfg = &m.cfg.LintersSettings.Tenv - testifylintCfg = &m.cfg.LintersSettings.Testifylint - testpackageCfg = &m.cfg.LintersSettings.Testpackage - thelperCfg = &m.cfg.LintersSettings.Thelper - unparamCfg = &m.cfg.LintersSettings.Unparam - unusedCfg = &m.cfg.LintersSettings.Unused - usestdlibvars = &m.cfg.LintersSettings.UseStdlibVars - varcheckCfg = &m.cfg.LintersSettings.Varcheck - varnamelenCfg = &m.cfg.LintersSettings.Varnamelen - whitespaceCfg = &m.cfg.LintersSettings.Whitespace - wrapcheckCfg = &m.cfg.LintersSettings.Wrapcheck - wslCfg = &m.cfg.LintersSettings.WSL - - if govetCfg != nil { - govetCfg.Go = m.cfg.Run.Go - } +// GetOptimizedLinters returns enabled linters after optimization (merging) of multiple linters into a fewer number of linters. +// E.g. some go/analysis linters can be optimized into one metalinter for data reuse and speed up. +func (m *Manager) GetOptimizedLinters() ([]*linter.Config, error) { + resultLintersSet := m.build(m.GetAllEnabledByDefaultLinters()) + m.verbosePrintLintersStatus(resultLintersSet) - if gocriticCfg != nil { - gocriticCfg.Go = trimGoVersion(m.cfg.Run.Go) - } + m.combineGoAnalysisLinters(resultLintersSet) - if gofumptCfg != nil && gofumptCfg.LangVersion == "" { - gofumptCfg.LangVersion = m.cfg.Run.Go - } + resultLinters := maps.Values(resultLintersSet) - if staticcheckCfg != nil && staticcheckCfg.GoVersion == "" { - staticcheckCfg.GoVersion = trimGoVersion(m.cfg.Run.Go) + // Make order of execution of linters (go/analysis metalinter and unused) stable. + sort.Slice(resultLinters, func(i, j int) bool { + a, b := resultLinters[i], resultLinters[j] + + if b.Name() == linter.LastLinter { + return true } - if gosimpleCfg != nil && gosimpleCfg.GoVersion == "" { - gosimpleCfg.GoVersion = trimGoVersion(m.cfg.Run.Go) + + if a.Name() == linter.LastLinter { + return false } - if stylecheckCfg != nil && stylecheckCfg.GoVersion != "" { - stylecheckCfg.GoVersion = trimGoVersion(m.cfg.Run.Go) + + if a.DoesChangeTypes != b.DoesChangeTypes { + return b.DoesChangeTypes // move type-changing linters to the end to optimize speed } - } + return a.Name() < b.Name() + }) - const megacheckName = "megacheck" - - var linters []*linter.Config - linters = append(linters, m.customLinters...) - - // The linters are sorted in the alphabetical order (case-insensitive). - // When a new linter is added the version in `WithSince(...)` must be the next minor version of golangci-lint. - linters = append(linters, - linter.NewConfig(golinters.NewAsasalint(asasalintCfg)). - WithSince("1.47.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/alingse/asasalint"), - - linter.NewConfig(golinters.NewAsciicheck()). - WithSince("v1.26.0"). - WithPresets(linter.PresetBugs, linter.PresetStyle). - WithURL("https://github.com/tdakkota/asciicheck"), - - linter.NewConfig(golinters.NewBiDiChkFuncName(bidichkCfg)). - WithSince("1.43.0"). - WithPresets(linter.PresetBugs). - WithURL("https://github.com/breml/bidichk"), - - linter.NewConfig(golinters.NewBodyclose()). - WithSince("v1.18.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetPerformance, linter.PresetBugs). - WithURL("https://github.com/timakin/bodyclose"), - - linter.NewConfig(golinters.NewContainedCtx()). - WithSince("1.44.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/sivchari/containedctx"), - - linter.NewConfig(golinters.NewContextCheck()). - WithSince("v1.43.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/kkHAIKE/contextcheck"), - - linter.NewConfig(golinters.NewCyclop(cyclopCfg)). - WithSince("v1.37.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetComplexity). - WithURL("https://github.com/bkielbasa/cyclop"), - - linter.NewConfig(golinters.NewDecorder(decorderCfg)). - WithSince("v1.44.0"). - WithPresets(linter.PresetFormatting, linter.PresetStyle). - WithURL("https://gitlab.com/bosi/decorder"), - - linter.NewConfig(golinters.NewDeadcode()). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetUnused). - WithURL("https://github.com/remyoudompheng/go-misc/tree/master/deadcode"). - Deprecated("The owner seems to have abandoned the linter.", "v1.49.0", "unused"), - - linter.NewConfig(golinters.NewDepguard(depGuardCfg)). - WithSince("v1.4.0"). - WithPresets(linter.PresetStyle, linter.PresetImport, linter.PresetModule). - WithURL("https://github.com/OpenPeeDeeP/depguard"), - - linter.NewConfig(golinters.NewDogsled(dogsledCfg)). - WithSince("v1.19.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/alexkohler/dogsled"), - - linter.NewConfig(golinters.NewDupl(duplCfg)). - WithSince("v1.0.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/mibk/dupl"), - - linter.NewConfig(golinters.NewDupWord(dupwordCfg)). - WithSince("1.50.0"). - WithPresets(linter.PresetComment). - WithAutoFix(). - WithURL("https://github.com/Abirdcfly/dupword"), - - linter.NewConfig(golinters.NewDurationCheck()). - WithSince("v1.37.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/charithe/durationcheck"), - - linter.NewConfig(golinters.NewErrcheck(errcheckCfg)). - WithEnabledByDefault(). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs, linter.PresetError). - WithURL("https://github.com/kisielk/errcheck"), - - linter.NewConfig(golinters.NewErrChkJSONFuncName(errchkjsonCfg)). - WithSince("1.44.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/breml/errchkjson"), - - linter.NewConfig(golinters.NewErrName()). - WithSince("v1.42.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/Antonboom/errname"), - - linter.NewConfig(golinters.NewErrorLint(errorlintCfg)). - WithSince("v1.32.0"). - WithPresets(linter.PresetBugs, linter.PresetError). - WithLoadForGoAnalysis(). - WithURL("https://github.com/polyfloyd/go-errorlint"), - - linter.NewConfig(golinters.NewExecInQuery()). - WithSince("v1.46.0"). - WithPresets(linter.PresetSQL). - WithLoadForGoAnalysis(). - WithURL("https://github.com/lufeee/execinquery"), - - linter.NewConfig(golinters.NewExhaustive(exhaustiveCfg)). - WithSince(" v1.28.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/nishanths/exhaustive"), - - linter.NewConfig(golinters.NewExhaustiveStruct(exhaustiveStructCfg)). - WithSince("v1.32.0"). - WithPresets(linter.PresetStyle, linter.PresetTest). - WithLoadForGoAnalysis(). - WithURL("https://github.com/mbilski/exhaustivestruct"). - Deprecated("The owner seems to have abandoned the linter.", "v1.46.0", "exhaustruct"), - - linter.NewConfig(golinters.NewExhaustruct(exhaustructCfg)). - WithSince("v1.46.0"). - WithPresets(linter.PresetStyle, linter.PresetTest). - WithLoadForGoAnalysis(). - WithURL("https://github.com/GaijinEntertainment/go-exhaustruct"), - - linter.NewConfig(golinters.NewExportLoopRef()). - WithSince("v1.28.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/kyoh86/exportloopref"), - - linter.NewConfig(golinters.NewForbidigo(forbidigoCfg)). - WithSince("v1.34.0"). - WithPresets(linter.PresetStyle). - // Strictly speaking, - // the additional information is only needed when forbidigoCfg.AnalyzeTypes is chosen by the user. - // But we don't know that here in all cases (sometimes config is not loaded), - // so we have to assume that it is needed to be on the safe side. - WithLoadForGoAnalysis(). - WithURL("https://github.com/ashanbrown/forbidigo"), - - linter.NewConfig(golinters.NewForceTypeAssert()). - WithSince("v1.38.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/gostaticanalysis/forcetypeassert"), - - linter.NewConfig(golinters.NewFunlen(funlenCfg)). - WithSince("v1.18.0"). - WithPresets(linter.PresetComplexity). - WithURL("https://github.com/ultraware/funlen"), - - linter.NewConfig(golinters.NewGci(gciCfg)). - WithSince("v1.30.0"). - WithPresets(linter.PresetFormatting, linter.PresetImport). - WithURL("https://github.com/daixiang0/gci"), - - linter.NewConfig(golinters.NewGinkgoLinter(ginkgolinterCfg)). - WithSince("v1.51.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/nunnatsa/ginkgolinter"), - - linter.NewConfig(golinters.NewGoCheckCompilerDirectives()). - WithSince("v1.51.0"). - WithPresets(linter.PresetBugs). - WithURL("https://github.com/leighmcculloch/gocheckcompilerdirectives"), - - linter.NewConfig(golinters.NewGochecknoglobals()). - WithSince("v1.12.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/leighmcculloch/gochecknoglobals"), - - linter.NewConfig(golinters.NewGochecknoinits()). - WithSince("v1.12.0"). - WithPresets(linter.PresetStyle), - - linter.NewConfig(golinters.NewGoCheckSumType()). - WithSince("v1.55.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/alecthomas/go-check-sumtype"), - - linter.NewConfig(golinters.NewGocognit(gocognitCfg)). - WithSince("v1.20.0"). - WithPresets(linter.PresetComplexity). - WithURL("https://github.com/uudashr/gocognit"), - - linter.NewConfig(golinters.NewGoconst(goconstCfg)). - WithSince("v1.0.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/jgautheron/goconst"), - - linter.NewConfig(golinters.NewGoCritic(gocriticCfg, m.cfg)). - WithSince("v1.12.0"). - WithPresets(linter.PresetStyle, linter.PresetMetaLinter). - WithLoadForGoAnalysis(). - WithURL("https://github.com/go-critic/go-critic"), - - linter.NewConfig(golinters.NewGocyclo(gocycloCfg)). - WithSince("v1.0.0"). - WithPresets(linter.PresetComplexity). - WithURL("https://github.com/fzipp/gocyclo"), - - linter.NewConfig(golinters.NewGodot(godotCfg)). - WithSince("v1.25.0"). - WithPresets(linter.PresetStyle, linter.PresetComment). - WithAutoFix(). - WithURL("https://github.com/tetafro/godot"), - - linter.NewConfig(golinters.NewGodox(godoxCfg)). - WithSince("v1.19.0"). - WithPresets(linter.PresetStyle, linter.PresetComment). - WithURL("https://github.com/matoous/godox"), - - linter.NewConfig(golinters.NewGoerr113()). - WithSince("v1.26.0"). - WithPresets(linter.PresetStyle, linter.PresetError). - WithLoadForGoAnalysis(). - WithURL("https://github.com/Djarvur/go-err113"), - - linter.NewConfig(golinters.NewGofmt(gofmtCfg)). - WithSince("v1.0.0"). - WithPresets(linter.PresetFormatting). - WithAutoFix(). - WithURL("https://pkg.go.dev/cmd/gofmt"), - - linter.NewConfig(golinters.NewGofumpt(gofumptCfg)). - WithSince("v1.28.0"). - WithPresets(linter.PresetFormatting). - WithAutoFix(). - WithURL("https://github.com/mvdan/gofumpt"), - - linter.NewConfig(golinters.NewGoHeader(goheaderCfg)). - WithSince("v1.28.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/denis-tingaikin/go-header"), - - linter.NewConfig(golinters.NewGoimports(goimportsCfg)). - WithSince("v1.20.0"). - WithPresets(linter.PresetFormatting, linter.PresetImport). - WithAutoFix(). - WithURL("https://pkg.go.dev/golang.org/x/tools/cmd/goimports"), - - linter.NewConfig(golinters.NewGolint(golintCfg)). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/golang/lint"). - Deprecated("The repository of the linter has been archived by the owner.", "v1.41.0", "revive"), - - linter.NewConfig(golinters.NewGoMND(goMndCfg)). - WithSince("v1.22.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/tommy-muehle/go-mnd"), - - linter.NewConfig(golinters.NewGoModDirectives(goModDirectivesCfg)). - WithSince("v1.39.0"). - WithPresets(linter.PresetStyle, linter.PresetModule). - WithURL("https://github.com/ldez/gomoddirectives"), - - linter.NewConfig(golinters.NewGomodguard(gomodguardCfg)). - WithSince("v1.25.0"). - WithPresets(linter.PresetStyle, linter.PresetImport, linter.PresetModule). - WithURL("https://github.com/ryancurrah/gomodguard"), - - linter.NewConfig(golinters.NewGoPrintfFuncName()). - WithSince("v1.23.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/jirfag/go-printf-func-name"), - - linter.NewConfig(golinters.NewGosec(gosecCfg)). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs). - WithURL("https://github.com/securego/gosec"). - WithAlternativeNames("gas"), - - linter.NewConfig(golinters.NewGosimple(gosimpleCfg)). - WithEnabledByDefault(). - WithSince("v1.20.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithAlternativeNames(megacheckName). - WithURL("https://github.com/dominikh/go-tools/tree/master/simple"), - - linter.NewConfig(golinters.NewGosmopolitan(gosmopolitanCfg)). - WithSince("v1.53.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs). - WithURL("https://github.com/xen0n/gosmopolitan"), - - linter.NewConfig(golinters.NewGovet(govetCfg)). - WithEnabledByDefault(). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs, linter.PresetMetaLinter). - WithAlternativeNames("vet", "vetshadow"). - WithURL("https://pkg.go.dev/cmd/vet"), - - linter.NewConfig(golinters.NewGrouper(grouperCfg)). - WithSince("v1.44.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/leonklingele/grouper"), - - linter.NewConfig(golinters.NewIfshort(ifshortCfg)). - WithSince("v1.36.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/esimonov/ifshort"). - Deprecated("The repository of the linter has been deprecated by the owner.", "v1.48.0", ""), - - linter.NewConfig(golinters.NewImportAs(importAsCfg)). - WithSince("v1.38.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/julz/importas"), - - linter.NewConfig(golinters.NewINamedParam()). - WithSince("v1.55.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/macabu/inamedparam"), - - linter.NewConfig(golinters.NewIneffassign()). - WithEnabledByDefault(). - WithSince("v1.0.0"). - WithPresets(linter.PresetUnused). - WithURL("https://github.com/gordonklaus/ineffassign"), - - linter.NewConfig(golinters.NewInterfaceBloat(interfaceBloatCfg)). - WithSince("v1.49.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/sashamelentyev/interfacebloat"), - - linter.NewConfig(golinters.NewInterfacer()). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/mvdan/interfacer"). - Deprecated("The repository of the linter has been archived by the owner.", "v1.38.0", ""), - - linter.NewConfig(golinters.NewIreturn(ireturnCfg)). - WithSince("v1.43.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/butuzov/ireturn"), - - linter.NewConfig(golinters.NewLLL(lllCfg)). - WithSince("v1.8.0"). - WithPresets(linter.PresetStyle), - - linter.NewConfig(golinters.NewLoggerCheck(loggerCheckCfg)). - WithSince("v1.49.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle, linter.PresetBugs). - WithAlternativeNames("logrlint"). - WithURL("https://github.com/timonwong/loggercheck"), - - linter.NewConfig(golinters.NewMaintIdx(maintIdxCfg)). - WithSince("v1.44.0"). - WithPresets(linter.PresetComplexity). - WithURL("https://github.com/yagipy/maintidx"), - - linter.NewConfig(golinters.NewMakezero(makezeroCfg)). - WithSince("v1.34.0"). - WithPresets(linter.PresetStyle, linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/ashanbrown/makezero"), - - linter.NewConfig(golinters.NewMaligned(malignedCfg)). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetPerformance). - WithURL("https://github.com/mdempsky/maligned"). - Deprecated("The repository of the linter has been archived by the owner.", "v1.38.0", "govet 'fieldalignment'"), - - linter.NewConfig(golinters.NewMirror()). - WithSince("v1.53.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/butuzov/mirror"), - - linter.NewConfig(golinters.NewMisspell(misspellCfg)). - WithSince("v1.8.0"). - WithPresets(linter.PresetStyle, linter.PresetComment). - WithAutoFix(). - WithURL("https://github.com/client9/misspell"), - - linter.NewConfig(golinters.NewMustTag(musttagCfg)). - WithSince("v1.51.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle, linter.PresetBugs). - WithURL("https://github.com/tmzane/musttag"), - - linter.NewConfig(golinters.NewNakedret(nakedretCfg)). - WithSince("v1.19.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/alexkohler/nakedret"), - - linter.NewConfig(golinters.NewNestif(nestifCfg)). - WithSince("v1.25.0"). - WithPresets(linter.PresetComplexity). - WithURL("https://github.com/nakabonne/nestif"), - - linter.NewConfig(golinters.NewNilErr()). - WithSince("v1.38.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs). - WithURL("https://github.com/gostaticanalysis/nilerr"), - - linter.NewConfig(golinters.NewNilNil(nilNilCfg)). - WithSince("v1.43.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/Antonboom/nilnil"), - - linter.NewConfig(golinters.NewNLReturn(nlreturnCfg)). - WithSince("v1.30.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/ssgreg/nlreturn"), - - linter.NewConfig(golinters.NewNoctx()). - WithSince("v1.28.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetPerformance, linter.PresetBugs). - WithURL("https://github.com/sonatard/noctx"), - - linter.NewConfig(golinters.NewNoNamedReturns(noNamedReturnsCfg)). - WithSince("v1.46.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/firefart/nonamedreturns"), - - linter.NewConfig(golinters.NewNoSnakeCase()). - WithSince("v1.47.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/sivchari/nosnakecase"). - Deprecated("The repository of the linter has been deprecated by the owner.", "v1.48.1", "revive(var-naming)"), - - linter.NewConfig(golinters.NewNoSprintfHostPort()). - WithSince("v1.46.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/stbenjam/no-sprintf-host-port"), - - linter.NewConfig(golinters.NewParallelTest(parallelTestCfg)). - WithSince("v1.33.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle, linter.PresetTest). - WithURL("https://github.com/kunwardeep/paralleltest"), - - linter.NewConfig(golinters.NewPerfSprint()). - WithSince("v1.55.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetPerformance). - WithURL("https://github.com/catenacyber/perfsprint"), - - linter.NewConfig(golinters.NewPreAlloc(preallocCfg)). - WithSince("v1.19.0"). - WithPresets(linter.PresetPerformance). - WithURL("https://github.com/alexkohler/prealloc"), - - linter.NewConfig(golinters.NewPredeclared(predeclaredCfg)). - WithSince("v1.35.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/nishanths/predeclared"), - - linter.NewConfig(golinters.NewPromlinter(promlinterCfg)). - WithSince("v1.40.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/yeya24/promlinter"), - - linter.NewConfig(golinters.NewProtoGetter()). - WithSince("v1.55.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithAutoFix(). - WithURL("https://github.com/ghostiam/protogetter"), - - linter.NewConfig(golinters.NewReassign(reassignCfg)). - WithSince("1.49.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/curioswitch/go-reassign"), - - linter.NewConfig(golinters.NewRevive(reviveCfg)). - WithSince("v1.37.0"). - WithPresets(linter.PresetStyle, linter.PresetMetaLinter). - ConsiderSlow(). - WithURL("https://github.com/mgechev/revive"), - - linter.NewConfig(golinters.NewRowsErrCheck(rowserrcheckCfg)). - WithSince("v1.23.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs, linter.PresetSQL). - WithURL("https://github.com/jingyugao/rowserrcheck"), - - linter.NewConfig(golinters.NewSlogLint(sloglintCfg)). - WithSince("v1.55.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle, linter.PresetFormatting). - WithURL("https://github.com/go-simpler/sloglint"), - - linter.NewConfig(golinters.NewScopelint()). - WithSince("v1.12.0"). - WithPresets(linter.PresetBugs). - WithURL("https://github.com/kyoh86/scopelint"). - Deprecated("The repository of the linter has been deprecated by the owner.", "v1.39.0", "exportloopref"), - - linter.NewConfig(golinters.NewSQLCloseCheck()). - WithSince("v1.28.0"). - WithPresets(linter.PresetBugs, linter.PresetSQL). - WithLoadForGoAnalysis(). - WithURL("https://github.com/ryanrolds/sqlclosecheck"), - - linter.NewConfig(golinters.NewStaticcheck(staticcheckCfg)). - WithEnabledByDefault(). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs, linter.PresetMetaLinter). - WithAlternativeNames(megacheckName). - WithURL("https://staticcheck.io/"), - - linter.NewConfig(golinters.NewStructcheck(structcheckCfg)). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetUnused). - WithURL("https://github.com/opennota/check"). - Deprecated("The owner seems to have abandoned the linter.", "v1.49.0", "unused"), - - linter.NewConfig(golinters.NewStylecheck(stylecheckCfg)). - WithSince("v1.20.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/dominikh/go-tools/tree/master/stylecheck"), - - linter.NewConfig(golinters.NewTagAlign(tagalignCfg)). - WithSince("v1.53.0"). - WithPresets(linter.PresetStyle, linter.PresetFormatting). - WithAutoFix(). - WithURL("https://github.com/4meepo/tagalign"), - - linter.NewConfig(golinters.NewTagliatelle(tagliatelleCfg)). - WithSince("v1.40.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/ldez/tagliatelle"), - - linter.NewConfig(golinters.NewTenv(tenvCfg)). - WithSince("v1.43.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/sivchari/tenv"), - - linter.NewConfig(golinters.NewTestableexamples()). - WithSince("v1.50.0"). - WithPresets(linter.PresetTest). - WithURL("https://github.com/maratori/testableexamples"), - - linter.NewConfig(golinters.NewTestifylint(testifylintCfg)). - WithSince("v1.55.0"). - WithPresets(linter.PresetTest, linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/Antonboom/testifylint"), - - linter.NewConfig(golinters.NewTestpackage(testpackageCfg)). - WithSince("v1.25.0"). - WithPresets(linter.PresetStyle, linter.PresetTest). - WithURL("https://github.com/maratori/testpackage"), - - linter.NewConfig(golinters.NewThelper(thelperCfg)). - WithSince("v1.34.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/kulti/thelper"), - - linter.NewConfig(golinters.NewTparallel()). - WithSince("v1.32.0"). - WithPresets(linter.PresetStyle, linter.PresetTest). - WithLoadForGoAnalysis(). - WithURL("https://github.com/moricho/tparallel"), - - linter.NewConfig(golinters.NewTypecheck()). - WithInternal(). - WithEnabledByDefault(). - WithSince("v1.3.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetBugs). - WithURL(""), - - linter.NewConfig(golinters.NewUnconvert()). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/mdempsky/unconvert"), - - linter.NewConfig(golinters.NewUnparam(unparamCfg)). - WithSince("v1.9.0"). - WithPresets(linter.PresetUnused). - WithLoadForGoAnalysis(). - WithURL("https://github.com/mvdan/unparam"), - - linter.NewConfig(golinters.NewUnused(unusedCfg, staticcheckCfg)). - WithEnabledByDefault(). - WithSince("v1.20.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetUnused). - WithAlternativeNames(megacheckName). - ConsiderSlow(). - WithChangeTypes(). - WithURL("https://github.com/dominikh/go-tools/tree/master/unused"), - - linter.NewConfig(golinters.NewUseStdlibVars(usestdlibvars)). - WithSince("v1.48.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/sashamelentyev/usestdlibvars"), - - linter.NewConfig(golinters.NewVarcheck(varcheckCfg)). - WithSince("v1.0.0"). - WithLoadForGoAnalysis(). - WithPresets(linter.PresetUnused). - WithURL("https://github.com/opennota/check"). - Deprecated("The owner seems to have abandoned the linter.", "v1.49.0", "unused"), - - linter.NewConfig(golinters.NewVarnamelen(varnamelenCfg)). - WithSince("v1.43.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/blizzy78/varnamelen"), - - linter.NewConfig(golinters.NewWastedAssign()). - WithSince("v1.38.0"). - WithPresets(linter.PresetStyle). - WithLoadForGoAnalysis(). - WithURL("https://github.com/sanposhiho/wastedassign"), - - linter.NewConfig(golinters.NewWhitespace(whitespaceCfg)). - WithSince("v1.19.0"). - WithPresets(linter.PresetStyle). - WithAutoFix(). - WithURL("https://github.com/ultraware/whitespace"), - - linter.NewConfig(golinters.NewWrapcheck(wrapcheckCfg)). - WithSince("v1.32.0"). - WithPresets(linter.PresetStyle, linter.PresetError). - WithLoadForGoAnalysis(). - WithURL("https://github.com/tomarrell/wrapcheck"), - - linter.NewConfig(golinters.NewWSL(wslCfg)). - WithSince("v1.20.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/bombsimon/wsl"), - - linter.NewConfig(golinters.NewZerologLint()). - WithSince("v1.53.0"). - WithPresets(linter.PresetBugs). - WithLoadForGoAnalysis(). - WithURL("https://github.com/ykadowak/zerologlint"), - - // nolintlint must be last because it looks at the results of all the previous linters for unused nolint directives - linter.NewConfig(golinters.NewNoLintLint(noLintLintCfg)). - WithSince("v1.26.0"). - WithPresets(linter.PresetStyle). - WithURL("https://github.com/golangci/golangci-lint/blob/master/pkg/golinters/nolintlint/README.md"), - ) - - return linters + return resultLinters, nil } -func (m Manager) GetAllEnabledByDefaultLinters() []*linter.Config { +func (m *Manager) GetAllEnabledByDefaultLinters() []*linter.Config { var ret []*linter.Config - for _, lc := range m.GetAllSupportedLinterConfigs() { + for _, lc := range m.linters { if lc.EnabledByDefault { ret = append(ret, lc) } @@ -940,48 +143,172 @@ func (m Manager) GetAllEnabledByDefaultLinters() []*linter.Config { return ret } -func linterConfigsToMap(lcs []*linter.Config) map[string]*linter.Config { - ret := map[string]*linter.Config{} - for _, lc := range lcs { - lc := lc // local copy - ret[lc.Name()] = lc +//nolint:gocyclo // the complexity cannot be reduced. +func (m *Manager) build(enabledByDefaultLinters []*linter.Config) map[string]*linter.Config { + m.debugf("Linters config: %#v", m.cfg.Linters) + + resultLintersSet := map[string]*linter.Config{} + switch { + case m.cfg.Linters.DisableAll: + // no default linters + case len(m.cfg.Linters.Presets) != 0: + // imply --disable-all + case m.cfg.Linters.EnableAll: + resultLintersSet = linterConfigsToMap(m.linters) + default: + resultLintersSet = linterConfigsToMap(enabledByDefaultLinters) } - return ret + // --presets can only add linters to default set + for _, p := range m.cfg.Linters.Presets { + for _, lc := range m.GetAllLinterConfigsForPreset(p) { + lc := lc + resultLintersSet[lc.Name()] = lc + } + } + + // --fast removes slow linters from current set. + // It should be after --presets to be able to run only fast linters in preset. + // It should be before --enable and --disable to be able to enable or disable specific linter. + if m.cfg.Linters.Fast { + for name, lc := range resultLintersSet { + if lc.IsSlowLinter() { + delete(resultLintersSet, name) + } + } + } + + for _, name := range m.cfg.Linters.Enable { + for _, lc := range m.GetLinterConfigs(name) { + // it's important to use lc.Name() nor name because name can be alias + resultLintersSet[lc.Name()] = lc + } + } + + for _, name := range m.cfg.Linters.Disable { + for _, lc := range m.GetLinterConfigs(name) { + // it's important to use lc.Name() nor name because name can be alias + delete(resultLintersSet, lc.Name()) + } + } + + // typecheck is not a real linter and cannot be disabled. + if _, ok := resultLintersSet["typecheck"]; !ok && (m.cfg == nil || !m.cfg.InternalCmdTest) { + for _, lc := range m.GetLinterConfigs("typecheck") { + // it's important to use lc.Name() nor name because name can be alias + resultLintersSet[lc.Name()] = lc + } + } + + return resultLintersSet } -func (m Manager) GetAllLinterConfigsForPreset(p string) []*linter.Config { - var ret []*linter.Config - for _, lc := range m.GetAllSupportedLinterConfigs() { - if lc.IsDeprecated() { +func (m *Manager) combineGoAnalysisLinters(linters map[string]*linter.Config) { + mlConfig := &linter.Config{} + + var goanalysisLinters []*goanalysis.Linter + + for _, lc := range linters { + lnt, ok := lc.Linter.(*goanalysis.Linter) + if !ok { continue } - for _, ip := range lc.InPresets { - if p == ip { - ret = append(ret, lc) - break - } + if lnt.LoadMode() == goanalysis.LoadModeWholeProgram { + // It's ineffective by CPU and memory to run whole-program and incremental analyzers at once. + continue + } + + mlConfig.LoadMode |= lc.LoadMode + + if lc.IsSlowLinter() { + mlConfig.ConsiderSlow() } + + mlConfig.InPresets = append(mlConfig.InPresets, lc.InPresets...) + + goanalysisLinters = append(goanalysisLinters, lnt) } - return ret + if len(goanalysisLinters) <= 1 { + m.debugf("Didn't combine go/analysis linters: got only %d linters", len(goanalysisLinters)) + return + } + + for _, lnt := range goanalysisLinters { + delete(linters, lnt.Name()) + } + + // Make order of execution of go/analysis analyzers stable. + sort.Slice(goanalysisLinters, func(i, j int) bool { + a, b := goanalysisLinters[i], goanalysisLinters[j] + + if b.Name() == linter.LastLinter { + return true + } + + if a.Name() == linter.LastLinter { + return false + } + + return a.Name() <= b.Name() + }) + + mlConfig.Linter = goanalysis.NewMetaLinter(goanalysisLinters) + + sort.Strings(mlConfig.InPresets) + mlConfig.InPresets = slices.Compact(mlConfig.InPresets) + + linters[mlConfig.Linter.Name()] = mlConfig + + m.debugf("Combined %d go/analysis linters into one metalinter", len(goanalysisLinters)) } -// Trims the Go version to keep only M.m. -// Since Go 1.21 the version inside the go.mod can be a patched version (ex: 1.21.0). -// https://go.dev/doc/toolchain#versions -// This a problem with staticcheck and gocritic. -func trimGoVersion(v string) string { - if v == "" { - return "" +func (m *Manager) verbosePrintLintersStatus(lcs map[string]*linter.Config) { + var linterNames []string + for _, lc := range lcs { + if lc.Internal { + continue + } + + linterNames = append(linterNames, lc.Name()) } + sort.Strings(linterNames) + m.log.Infof("Active %d linters: %s", len(linterNames), linterNames) - exp := regexp.MustCompile(`(\d\.\d+)\.\d+`) + if len(m.cfg.Linters.Presets) != 0 { + sort.Strings(m.cfg.Linters.Presets) + m.log.Infof("Active presets: %s", m.cfg.Linters.Presets) + } +} - if exp.MatchString(v) { - return exp.FindStringSubmatch(v)[1] +func AllPresets() []string { + return []string{ + linter.PresetBugs, + linter.PresetComment, + linter.PresetComplexity, + linter.PresetError, + linter.PresetFormatting, + linter.PresetImport, + linter.PresetMetaLinter, + linter.PresetModule, + linter.PresetPerformance, + linter.PresetSQL, + linter.PresetStyle, + linter.PresetTest, + linter.PresetUnused, } +} - return v +func linterConfigsToMap(lcs []*linter.Config) map[string]*linter.Config { + ret := map[string]*linter.Config{} + for _, lc := range lcs { + if lc.IsDeprecated() && lc.Deprecation.Level > linter.DeprecationWarning { + continue + } + + ret[lc.Name()] = lc + } + + return ret } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go index 52a70d859..264d063aa 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go @@ -3,9 +3,13 @@ package lintersdb import ( "errors" "fmt" + "os" + "slices" "strings" "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/logutils" ) type Validator struct { @@ -13,23 +17,52 @@ type Validator struct { } func NewValidator(m *Manager) *Validator { - return &Validator{ - m: m, + return &Validator{m: m} +} + +// Validate validates the configuration by calling all other validators for different +// sections in the configuration and then some additional linter validation functions. +func (v Validator) Validate(cfg *config.Config) error { + validators := []func(cfg *config.Linters) error{ + v.validateLintersNames, + v.validatePresets, + v.alternativeNamesDeprecation, } + + for _, v := range validators { + if err := v(&cfg.Linters); err != nil { + return err + } + } + + return nil } func (v Validator) validateLintersNames(cfg *config.Linters) error { - allNames := append([]string{}, cfg.Enable...) - allNames = append(allNames, cfg.Disable...) - var unknownNames []string - for _, name := range allNames { + for _, name := range cfg.Enable { if v.m.GetLinterConfigs(name) == nil { unknownNames = append(unknownNames, name) } } + for _, name := range cfg.Disable { + lcs := v.m.GetLinterConfigs(name) + if len(lcs) == 0 { + unknownNames = append(unknownNames, name) + continue + } + + for _, lc := range lcs { + if lc.IsDeprecated() && lc.Deprecation.Level > linter.DeprecationWarning { + v.m.log.Warnf("The linter %q is deprecated (step 2) and deactivated. "+ + "It should be removed from the list of disabled linters. "+ + "https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle", lc.Name()) + } + } + } + if len(unknownNames) > 0 { return fmt.Errorf("unknown linters: '%v', run 'golangci-lint help linters' to see the list of supported linters", strings.Join(unknownNames, ",")) @@ -38,12 +71,13 @@ func (v Validator) validateLintersNames(cfg *config.Linters) error { return nil } -func (v Validator) validatePresets(cfg *config.Linters) error { - allPresets := v.m.allPresetsSet() +func (Validator) validatePresets(cfg *config.Linters) error { + presets := AllPresets() + for _, p := range cfg.Presets { - if !allPresets[p] { + if !slices.Contains(presets, p) { return fmt.Errorf("no such preset %q: only next presets exist: (%s)", - p, strings.Join(v.m.AllPresets(), "|")) + p, strings.Join(presets, "|")) } } @@ -54,53 +88,31 @@ func (v Validator) validatePresets(cfg *config.Linters) error { return nil } -func (v Validator) validateAllDisableEnableOptions(cfg *config.Linters) error { - if cfg.EnableAll && cfg.DisableAll { - return errors.New("--enable-all and --disable-all options must not be combined") +func (v Validator) alternativeNamesDeprecation(cfg *config.Linters) error { + if v.m.cfg.InternalTest || v.m.cfg.InternalCmdTest || os.Getenv(logutils.EnvTestRun) == "1" { + return nil } - if cfg.DisableAll { - if len(cfg.Enable) == 0 && len(cfg.Presets) == 0 { - return errors.New("all linters were disabled, but no one linter was enabled: must enable at least one") - } - - if len(cfg.Disable) != 0 { - return fmt.Errorf("can't combine options --disable-all and --disable %s", cfg.Disable[0]) + altNames := map[string][]string{} + for _, lc := range v.m.GetAllSupportedLinterConfigs() { + for _, alt := range lc.AlternativeNames { + altNames[alt] = append(altNames[alt], lc.Name()) } } - if cfg.EnableAll && len(cfg.Enable) != 0 && !cfg.Fast { - return fmt.Errorf("can't combine options --enable-all and --enable %s", cfg.Enable[0]) - } + names := cfg.Enable + names = append(names, cfg.Disable...) - return nil -} - -func (v Validator) validateDisabledAndEnabledAtOneMoment(cfg *config.Linters) error { - enabledLintersSet := map[string]bool{} - for _, name := range cfg.Enable { - enabledLintersSet[name] = true - } - - for _, name := range cfg.Disable { - if enabledLintersSet[name] { - return fmt.Errorf("linter %q can't be disabled and enabled at one moment", name) + for _, name := range names { + lc, ok := altNames[name] + if !ok { + continue } - } - return nil -} - -func (v Validator) validateEnabledDisabledLintersConfig(cfg *config.Linters) error { - validators := []func(cfg *config.Linters) error{ - v.validateLintersNames, - v.validatePresets, - v.validateAllDisableEnableOptions, - v.validateDisabledAndEnabledAtOneMoment, - } - for _, v := range validators { - if err := v(cfg); err != nil { - return err + if len(lc) > 1 { + v.m.log.Warnf("The linter named %q is deprecated. It has been split into: %s.", name, strings.Join(lc, ", ")) + } else { + v.m.log.Warnf("The name %q is deprecated. The linter has been renamed to: %s.", name, lc[0]) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/package.go similarity index 52% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/lint/package.go index babad5ba6..c314166ca 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/package.go @@ -13,151 +13,99 @@ import ( "golang.org/x/tools/go/packages" - "github.com/golangci/golangci-lint/internal/pkgcache" "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/exitcodes" - "github.com/golangci/golangci-lint/pkg/fsutils" - "github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load" + "github.com/golangci/golangci-lint/pkg/goanalysis/load" "github.com/golangci/golangci-lint/pkg/goutil" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/logutils" ) -type ContextLoader struct { - cfg *config.Config - log logutils.Log - debugf logutils.DebugFunc - goenv *goutil.Env +// PackageLoader loads packages based on [golang.org/x/tools/go/packages.Load]. +type PackageLoader struct { + log logutils.Log + debugf logutils.DebugFunc + + cfg *config.Config + + args []string + pkgTestIDRe *regexp.Regexp - lineCache *fsutils.LineCache - fileCache *fsutils.FileCache - pkgCache *pkgcache.Cache - loadGuard *load.Guard + + goenv *goutil.Env + + loadGuard *load.Guard } -func NewContextLoader(cfg *config.Config, log logutils.Log, goenv *goutil.Env, - lineCache *fsutils.LineCache, fileCache *fsutils.FileCache, pkgCache *pkgcache.Cache, loadGuard *load.Guard) *ContextLoader { - return &ContextLoader{ +// NewPackageLoader creates a new PackageLoader. +func NewPackageLoader(log logutils.Log, cfg *config.Config, args []string, goenv *goutil.Env, loadGuard *load.Guard) *PackageLoader { + return &PackageLoader{ cfg: cfg, + args: args, log: log, debugf: logutils.Debug(logutils.DebugKeyLoader), goenv: goenv, pkgTestIDRe: regexp.MustCompile(`^(.*) \[(.*)\.test\]`), - lineCache: lineCache, - fileCache: fileCache, - pkgCache: pkgCache, loadGuard: loadGuard, } } -func (cl *ContextLoader) prepareBuildContext() { - // Set GOROOT to have working cross-compilation: cross-compiled binaries - // have invalid GOROOT. XXX: can't use runtime.GOROOT(). - goroot := cl.goenv.Get(goutil.EnvGoRoot) - if goroot == "" { - return - } - - os.Setenv(string(goutil.EnvGoRoot), goroot) - build.Default.GOROOT = goroot - build.Default.BuildTags = cl.cfg.Run.BuildTags -} +// Load loads packages. +func (l *PackageLoader) Load(ctx context.Context, linters []*linter.Config) (pkgs, deduplicatedPkgs []*packages.Package, err error) { + loadMode := findLoadMode(linters) -func (cl *ContextLoader) findLoadMode(linters []*linter.Config) packages.LoadMode { - loadMode := packages.LoadMode(0) - for _, lc := range linters { - loadMode |= lc.LoadMode + pkgs, err = l.loadPackages(ctx, loadMode) + if err != nil { + return nil, nil, fmt.Errorf("failed to load packages: %w", err) } - return loadMode + return pkgs, l.filterDuplicatePackages(pkgs), nil } -func (cl *ContextLoader) buildArgs() []string { - args := cl.cfg.Run.Args - if len(args) == 0 { - return []string{"./..."} - } - - var retArgs []string - for _, arg := range args { - if strings.HasPrefix(arg, ".") || filepath.IsAbs(arg) { - retArgs = append(retArgs, arg) - } else { - // go/packages doesn't work well if we don't have the prefix ./ for local packages - retArgs = append(retArgs, fmt.Sprintf(".%c%s", filepath.Separator, arg)) - } - } - - return retArgs -} +func (l *PackageLoader) loadPackages(ctx context.Context, loadMode packages.LoadMode) ([]*packages.Package, error) { + defer func(startedAt time.Time) { + l.log.Infof("Go packages loading at mode %s took %s", stringifyLoadMode(loadMode), time.Since(startedAt)) + }(time.Now()) -func (cl *ContextLoader) makeBuildFlags() ([]string, error) { - var buildFlags []string + l.prepareBuildContext() - if len(cl.cfg.Run.BuildTags) != 0 { - // go help build - buildFlags = append(buildFlags, "-tags", strings.Join(cl.cfg.Run.BuildTags, " ")) - cl.log.Infof("Using build tags: %v", cl.cfg.Run.BuildTags) + conf := &packages.Config{ + Mode: loadMode, + Tests: l.cfg.Run.AnalyzeTests, + Context: ctx, + BuildFlags: l.makeBuildFlags(), + Logf: l.debugf, + // TODO: use fset, parsefile, overlay } - mod := cl.cfg.Run.ModulesDownloadMode - if mod != "" { - // go help modules - allowedMods := []string{"mod", "readonly", "vendor"} - var ok bool - for _, am := range allowedMods { - if am == mod { - ok = true - break - } - } - if !ok { - return nil, fmt.Errorf("invalid modules download path %s, only (%s) allowed", mod, strings.Join(allowedMods, "|")) - } + args := buildArgs(l.args) - buildFlags = append(buildFlags, fmt.Sprintf("-mod=%s", cl.cfg.Run.ModulesDownloadMode)) - } + l.debugf("Built loader args are %s", args) - return buildFlags, nil -} - -func stringifyLoadMode(mode packages.LoadMode) string { - m := map[packages.LoadMode]string{ - packages.NeedCompiledGoFiles: "compiled_files", - packages.NeedDeps: "deps", - packages.NeedExportFile: "exports_file", - packages.NeedFiles: "files", - packages.NeedImports: "imports", - packages.NeedName: "name", - packages.NeedSyntax: "syntax", - packages.NeedTypes: "types", - packages.NeedTypesInfo: "types_info", - packages.NeedTypesSizes: "types_sizes", + pkgs, err := packages.Load(conf, args...) + if err != nil { + return nil, fmt.Errorf("failed to load with go/packages: %w", err) } - var flags []string - for flag, flagStr := range m { - if mode&flag != 0 { - flags = append(flags, flagStr) - } + if loadMode&packages.NeedSyntax == 0 { + // Needed e.g. for go/analysis loading. + fset := token.NewFileSet() + packages.Visit(pkgs, nil, func(pkg *packages.Package) { + pkg.Fset = fset + l.loadGuard.AddMutexForPkg(pkg) + }) } - return fmt.Sprintf("%d (%s)", mode, strings.Join(flags, "|")) -} + l.debugPrintLoadedPackages(pkgs) -func (cl *ContextLoader) debugPrintLoadedPackages(pkgs []*packages.Package) { - cl.debugf("loaded %d pkgs", len(pkgs)) - for i, pkg := range pkgs { - var syntaxFiles []string - for _, sf := range pkg.Syntax { - syntaxFiles = append(syntaxFiles, pkg.Fset.Position(sf.Pos()).Filename) - } - cl.debugf("Loaded pkg #%d: ID=%s GoFiles=%s CompiledGoFiles=%s Syntax=%s", - i, pkg.ID, pkg.GoFiles, pkg.CompiledGoFiles, syntaxFiles) + if err := l.parseLoadedPackagesErrors(pkgs); err != nil { + return nil, err } + + return l.filterTestMainPackages(pkgs), nil } -func (cl *ContextLoader) parseLoadedPackagesErrors(pkgs []*packages.Package) error { +func (*PackageLoader) parseLoadedPackagesErrors(pkgs []*packages.Package) error { for _, pkg := range pkgs { var errs []packages.Error for _, err := range pkg.Errors { @@ -185,61 +133,8 @@ func (cl *ContextLoader) parseLoadedPackagesErrors(pkgs []*packages.Package) err return nil } -func (cl *ContextLoader) loadPackages(ctx context.Context, loadMode packages.LoadMode) ([]*packages.Package, error) { - defer func(startedAt time.Time) { - cl.log.Infof("Go packages loading at mode %s took %s", stringifyLoadMode(loadMode), time.Since(startedAt)) - }(time.Now()) - - cl.prepareBuildContext() - - buildFlags, err := cl.makeBuildFlags() - if err != nil { - return nil, fmt.Errorf("failed to make build flags for go list: %w", err) - } - - conf := &packages.Config{ - Mode: loadMode, - Tests: cl.cfg.Run.AnalyzeTests, - Context: ctx, - BuildFlags: buildFlags, - Logf: cl.debugf, - // TODO: use fset, parsefile, overlay - } - - args := cl.buildArgs() - cl.debugf("Built loader args are %s", args) - pkgs, err := packages.Load(conf, args...) - if err != nil { - return nil, fmt.Errorf("failed to load with go/packages: %w", err) - } - - // Currently, go/packages doesn't guarantee that error will be returned - // if context was canceled. See - // https://github.com/golang/tools/commit/c5cec6710e927457c3c29d6c156415e8539a5111#r39261855 - if ctx.Err() != nil { - return nil, fmt.Errorf("timed out to load packages: %w", ctx.Err()) - } - - if loadMode&packages.NeedSyntax == 0 { - // Needed e.g. for go/analysis loading. - fset := token.NewFileSet() - packages.Visit(pkgs, nil, func(pkg *packages.Package) { - pkg.Fset = fset - cl.loadGuard.AddMutexForPkg(pkg) - }) - } - - cl.debugPrintLoadedPackages(pkgs) - - if err := cl.parseLoadedPackagesErrors(pkgs); err != nil { - return nil, err - } - - return cl.filterTestMainPackages(pkgs), nil -} - -func (cl *ContextLoader) tryParseTestPackage(pkg *packages.Package) (name string, isTest bool) { - matches := cl.pkgTestIDRe.FindStringSubmatch(pkg.ID) +func (l *PackageLoader) tryParseTestPackage(pkg *packages.Package) (name string, isTest bool) { + matches := l.pkgTestIDRe.FindStringSubmatch(pkg.ID) if matches == nil { return "", false } @@ -247,36 +142,21 @@ func (cl *ContextLoader) tryParseTestPackage(pkg *packages.Package) (name string return matches[1], true } -func (cl *ContextLoader) filterTestMainPackages(pkgs []*packages.Package) []*packages.Package { - var retPkgs []*packages.Package - for _, pkg := range pkgs { - if pkg.Name == "main" && strings.HasSuffix(pkg.PkgPath, ".test") { - // it's an implicit testmain package - cl.debugf("skip pkg ID=%s", pkg.ID) - continue - } - - retPkgs = append(retPkgs, pkg) - } - - return retPkgs -} - -func (cl *ContextLoader) filterDuplicatePackages(pkgs []*packages.Package) []*packages.Package { +func (l *PackageLoader) filterDuplicatePackages(pkgs []*packages.Package) []*packages.Package { packagesWithTests := map[string]bool{} for _, pkg := range pkgs { - name, isTest := cl.tryParseTestPackage(pkg) + name, isTest := l.tryParseTestPackage(pkg) if !isTest { continue } packagesWithTests[name] = true } - cl.debugf("package with tests: %#v", packagesWithTests) + l.debugf("package with tests: %#v", packagesWithTests) var retPkgs []*packages.Package for _, pkg := range pkgs { - _, isTest := cl.tryParseTestPackage(pkg) + _, isTest := l.tryParseTestPackage(pkg) if !isTest && packagesWithTests[pkg.PkgPath] { // If tests loading is enabled, // for package with files a.go and a_test.go go/packages loads two packages: @@ -284,7 +164,7 @@ func (cl *ContextLoader) filterDuplicatePackages(pkgs []*packages.Package) []*pa // 2. ID=".../a [.../a.test]" GoFiles=[a.go a_test.go] // We need only the second package, otherwise we can get warnings about unused variables/fields/functions // in a.go if they are used only in a_test.go. - cl.debugf("skip pkg ID=%s because we load it with test package", pkg.ID) + l.debugf("skip pkg ID=%s because we load it with test package", pkg.ID) continue } @@ -294,33 +174,110 @@ func (cl *ContextLoader) filterDuplicatePackages(pkgs []*packages.Package) []*pa return retPkgs } -func (cl *ContextLoader) Load(ctx context.Context, linters []*linter.Config) (*linter.Context, error) { - loadMode := cl.findLoadMode(linters) - pkgs, err := cl.loadPackages(ctx, loadMode) - if err != nil { - return nil, fmt.Errorf("failed to load packages: %w", err) +func (l *PackageLoader) filterTestMainPackages(pkgs []*packages.Package) []*packages.Package { + var retPkgs []*packages.Package + for _, pkg := range pkgs { + if pkg.Name == "main" && strings.HasSuffix(pkg.PkgPath, ".test") { + // it's an implicit testmain package + l.debugf("skip pkg ID=%s", pkg.ID) + continue + } + + retPkgs = append(retPkgs, pkg) } - deduplicatedPkgs := cl.filterDuplicatePackages(pkgs) + return retPkgs +} - if len(deduplicatedPkgs) == 0 { - return nil, exitcodes.ErrNoGoFiles +func (l *PackageLoader) debugPrintLoadedPackages(pkgs []*packages.Package) { + l.debugf("loaded %d pkgs", len(pkgs)) + for i, pkg := range pkgs { + var syntaxFiles []string + for _, sf := range pkg.Syntax { + syntaxFiles = append(syntaxFiles, pkg.Fset.Position(sf.Pos()).Filename) + } + l.debugf("Loaded pkg #%d: ID=%s GoFiles=%s CompiledGoFiles=%s Syntax=%s", + i, pkg.ID, pkg.GoFiles, pkg.CompiledGoFiles, syntaxFiles) } +} - ret := &linter.Context{ - Packages: deduplicatedPkgs, +func (l *PackageLoader) prepareBuildContext() { + // Set GOROOT to have working cross-compilation: cross-compiled binaries + // have invalid GOROOT. XXX: can't use runtime.GOROOT(). + goroot := l.goenv.Get(goutil.EnvGoRoot) + if goroot == "" { + return + } + + os.Setenv(string(goutil.EnvGoRoot), goroot) + build.Default.GOROOT = goroot + build.Default.BuildTags = l.cfg.Run.BuildTags +} - // At least `unused` linters works properly only on original (not deduplicated) packages, - // see https://github.com/golangci/golangci-lint/pull/585. - OriginalPackages: pkgs, +func (l *PackageLoader) makeBuildFlags() []string { + var buildFlags []string - Cfg: cl.cfg, - Log: cl.log, - FileCache: cl.fileCache, - LineCache: cl.lineCache, - PkgCache: cl.pkgCache, - LoadGuard: cl.loadGuard, + if len(l.cfg.Run.BuildTags) != 0 { + // go help build + buildFlags = append(buildFlags, "-tags", strings.Join(l.cfg.Run.BuildTags, " ")) + l.log.Infof("Using build tags: %v", l.cfg.Run.BuildTags) + } + + if l.cfg.Run.ModulesDownloadMode != "" { + // go help modules + buildFlags = append(buildFlags, fmt.Sprintf("-mod=%s", l.cfg.Run.ModulesDownloadMode)) + } + + return buildFlags +} + +func buildArgs(args []string) []string { + if len(args) == 0 { + return []string{"./..."} } - return ret, nil + var retArgs []string + for _, arg := range args { + if strings.HasPrefix(arg, ".") || filepath.IsAbs(arg) { + retArgs = append(retArgs, arg) + } else { + // go/packages doesn't work well if we don't have the prefix ./ for local packages + retArgs = append(retArgs, fmt.Sprintf(".%c%s", filepath.Separator, arg)) + } + } + + return retArgs +} + +func findLoadMode(linters []*linter.Config) packages.LoadMode { + loadMode := packages.LoadMode(0) + for _, lc := range linters { + loadMode |= lc.LoadMode + } + + return loadMode +} + +func stringifyLoadMode(mode packages.LoadMode) string { + m := map[packages.LoadMode]string{ + packages.NeedCompiledGoFiles: "compiled_files", + packages.NeedDeps: "deps", + packages.NeedExportFile: "exports_file", + packages.NeedFiles: "files", + packages.NeedImports: "imports", + packages.NeedName: "name", + packages.NeedSyntax: "syntax", + packages.NeedTypes: "types", + packages.NeedTypesInfo: "types_info", + packages.NeedTypesSizes: "types_sizes", + } + + var flags []string + for flag, flagStr := range m { + if mode&flag != 0 { + flags = append(flags, flagStr) + } + } + + return fmt.Sprintf("%d (%s)", mode, strings.Join(flags, "|")) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go index d270892d5..379508ab0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go @@ -2,13 +2,11 @@ package lint import ( "context" + "errors" "fmt" "runtime/debug" "strings" - "github.com/hashicorp/go-multierror" - gopackages "golang.org/x/tools/go/packages" - "github.com/golangci/golangci-lint/internal/errorutil" "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/fsutils" @@ -16,90 +14,84 @@ import ( "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/lintersdb" "github.com/golangci/golangci-lint/pkg/logutils" - "github.com/golangci/golangci-lint/pkg/packages" "github.com/golangci/golangci-lint/pkg/result" "github.com/golangci/golangci-lint/pkg/result/processors" "github.com/golangci/golangci-lint/pkg/timeutils" ) +type processorStat struct { + inCount int + outCount int +} + type Runner struct { + Log logutils.Log + + lintCtx *linter.Context Processors []processors.Processor - Log logutils.Log } -func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, - es *lintersdb.EnabledSet, +func NewRunner(log logutils.Log, cfg *config.Config, args []string, goenv *goutil.Env, lineCache *fsutils.LineCache, fileCache *fsutils.FileCache, - dbManager *lintersdb.Manager, pkgs []*gopackages.Package) (*Runner, error) { + dbManager *lintersdb.Manager, lintCtx *linter.Context, +) (*Runner, error) { // Beware that some processors need to add the path prefix when working with paths // because they get invoked before the path prefixer (exclude and severity rules) // or process other paths (skip files). files := fsutils.NewFiles(lineCache, cfg.Output.PathPrefix) - skipFilesProcessor, err := processors.NewSkipFiles(cfg.Run.SkipFiles, cfg.Output.PathPrefix) + skipFilesProcessor, err := processors.NewSkipFiles(cfg.Issues.ExcludeFiles, cfg.Output.PathPrefix) if err != nil { return nil, err } - skipDirs := cfg.Run.SkipDirs - if cfg.Run.UseDefaultSkipDirs { - skipDirs = append(skipDirs, packages.StdExcludeDirRegexps...) + skipDirs := cfg.Issues.ExcludeDirs + if cfg.Issues.UseDefaultExcludeDirs { + skipDirs = append(skipDirs, processors.StdExcludeDirRegexps...) } - skipDirsProcessor, err := processors.NewSkipDirs(skipDirs, log.Child(logutils.DebugKeySkipDirs), cfg.Run.Args, cfg.Output.PathPrefix) + + skipDirsProcessor, err := processors.NewSkipDirs(log.Child(logutils.DebugKeySkipDirs), skipDirs, args, cfg.Output.PathPrefix) if err != nil { return nil, err } - enabledLinters, err := es.GetEnabledLintersMap() + enabledLinters, err := dbManager.GetEnabledLintersMap() if err != nil { return nil, fmt.Errorf("failed to get enabled linters: %w", err) } - // print deprecated messages - if !cfg.InternalCmdTest { - for name, lc := range enabledLinters { - if !lc.IsDeprecated() { - continue - } - - var extra string - if lc.Deprecation.Replacement != "" { - extra = fmt.Sprintf("Replaced by %s.", lc.Deprecation.Replacement) - } - - log.Warnf("The linter '%s' is deprecated (since %s) due to: %s %s", name, lc.Deprecation.Since, lc.Deprecation.Message, extra) - } - } - return &Runner{ Processors: []processors.Processor{ processors.NewCgo(goenv), // Must go after Cgo. - processors.NewFilenameUnadjuster(pkgs, log.Child(logutils.DebugKeyFilenameUnadjuster)), + processors.NewFilenameUnadjuster(lintCtx.Packages, log.Child(logutils.DebugKeyFilenameUnadjuster)), + + // Must go after FilenameUnadjuster. + processors.NewInvalidIssue(log.Child(logutils.DebugKeyInvalidIssue)), // Must be before diff, nolint and exclude autogenerated processor at least. processors.NewPathPrettifier(), skipFilesProcessor, skipDirsProcessor, // must be after path prettifier - processors.NewAutogeneratedExclude(), + processors.NewAutogeneratedExclude(cfg.Issues.ExcludeGenerated), // Must be before exclude because users see already marked output and configure excluding by it. processors.NewIdentifierMarker(), - getExcludeProcessor(&cfg.Issues), - getExcludeRulesProcessor(&cfg.Issues, log, files), + processors.NewExclude(&cfg.Issues), + processors.NewExcludeRules(log.Child(logutils.DebugKeyExcludeRules), files, &cfg.Issues), processors.NewNolint(log.Child(logutils.DebugKeyNolint), dbManager, enabledLinters), processors.NewUniqByLine(cfg), - processors.NewDiff(cfg.Issues.Diff, cfg.Issues.DiffFromRevision, cfg.Issues.DiffPatchFilePath, cfg.Issues.WholeFiles), + processors.NewDiff(&cfg.Issues), processors.NewMaxPerFileFromLinter(cfg), processors.NewMaxSameIssues(cfg.Issues.MaxSameIssues, log.Child(logutils.DebugKeyMaxSameIssues), cfg), processors.NewMaxFromLinter(cfg.Issues.MaxIssuesPerLinter, log.Child(logutils.DebugKeyMaxFromLinter), cfg), processors.NewSourceCode(lineCache, log.Child(logutils.DebugKeySourceCode)), processors.NewPathShortener(), - getSeverityRulesProcessor(&cfg.Severity, log, files), + processors.NewSeverity(log.Child(logutils.DebugKeySeverityRules), files, &cfg.Severity), // The fixer still needs to see paths for the issues that are relative to the current directory. processors.NewFixer(cfg, log, fileCache), @@ -108,12 +100,41 @@ func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, processors.NewPathPrefixer(cfg.Output.PathPrefix), processors.NewSortResults(cfg), }, - Log: log, + lintCtx: lintCtx, + Log: log, }, nil } +func (r *Runner) Run(ctx context.Context, linters []*linter.Config) ([]result.Issue, error) { + sw := timeutils.NewStopwatch("linters", r.Log) + defer sw.Print() + + var ( + lintErrors error + issues []result.Issue + ) + + for _, lc := range linters { + lc := lc + sw.TrackStage(lc.Name(), func() { + linterIssues, err := r.runLinterSafe(ctx, r.lintCtx, lc) + if err != nil { + lintErrors = errors.Join(lintErrors, fmt.Errorf("can't run linter %s", lc.Linter.Name()), err) + r.Log.Warnf("Can't run linter %s: %v", lc.Linter.Name(), err) + + return + } + + issues = append(issues, linterIssues...) + }) + } + + return r.processLintResults(issues), lintErrors +} + func (r *Runner) runLinterSafe(ctx context.Context, lintCtx *linter.Context, - lc *linter.Config) (ret []result.Issue, err error) { + lc *linter.Config, +) (ret []result.Issue, err error) { defer func() { if panicData := recover(); panicData != nil { if pe, ok := panicData.(*errorutil.PanicError); ok { @@ -152,12 +173,7 @@ func (r *Runner) runLinterSafe(ctx context.Context, lintCtx *linter.Context, return issues, nil } -type processorStat struct { - inCount int - outCount int -} - -func (r Runner) processLintResults(inIssues []result.Issue) []result.Issue { +func (r *Runner) processLintResults(inIssues []result.Issue) []result.Issue { sw := timeutils.NewStopwatch("processing", r.Log) var issuesBefore, issuesAfter int @@ -188,45 +204,18 @@ func (r Runner) processLintResults(inIssues []result.Issue) []result.Issue { return outIssues } -func (r Runner) printPerProcessorStat(stat map[string]processorStat) { +func (r *Runner) printPerProcessorStat(stat map[string]processorStat) { parts := make([]string, 0, len(stat)) for name, ps := range stat { if ps.inCount != 0 { - parts = append(parts, fmt.Sprintf("%s: %d/%d", name, ps.outCount, ps.inCount)) + parts = append(parts, fmt.Sprintf("%s: %d/%d", name, ps.inCount, ps.outCount)) } } if len(parts) != 0 { - r.Log.Infof("Processors filtering stat (out/in): %s", strings.Join(parts, ", ")) + r.Log.Infof("Processors filtering stat (in/out): %s", strings.Join(parts, ", ")) } } -func (r Runner) Run(ctx context.Context, linters []*linter.Config, lintCtx *linter.Context) ([]result.Issue, error) { - sw := timeutils.NewStopwatch("linters", r.Log) - defer sw.Print() - - var ( - lintErrors *multierror.Error - issues []result.Issue - ) - - for _, lc := range linters { - lc := lc - sw.TrackStage(lc.Name(), func() { - linterIssues, err := r.runLinterSafe(ctx, lintCtx, lc) - if err != nil { - lintErrors = multierror.Append(lintErrors, fmt.Errorf("can't run linter %s: %w", lc.Linter.Name(), err)) - r.Log.Warnf("Can't run linter %s: %v", lc.Linter.Name(), err) - - return - } - - issues = append(issues, linterIssues...) - }) - } - - return r.processLintResults(issues), lintErrors.ErrorOrNil() -} - func (r *Runner) processIssues(issues []result.Issue, sw *timeutils.Stopwatch, statPerProcessor map[string]processorStat) []result.Issue { for _, p := range r.Processors { var newIssues []result.Issue @@ -246,6 +235,7 @@ func (r *Runner) processIssues(issues []result.Issue, sw *timeutils.Stopwatch, s issues = newIssues } + // This is required by JSON serialization if issues == nil { issues = []result.Issue{} } @@ -253,98 +243,3 @@ func (r *Runner) processIssues(issues []result.Issue, sw *timeutils.Stopwatch, s return issues } - -func getExcludeProcessor(cfg *config.Issues) processors.Processor { - var excludeTotalPattern string - - if len(cfg.ExcludePatterns) != 0 { - excludeTotalPattern = fmt.Sprintf("(%s)", strings.Join(cfg.ExcludePatterns, "|")) - } - - var excludeProcessor processors.Processor - if cfg.ExcludeCaseSensitive { - excludeProcessor = processors.NewExcludeCaseSensitive(excludeTotalPattern) - } else { - excludeProcessor = processors.NewExclude(excludeTotalPattern) - } - - return excludeProcessor -} - -func getExcludeRulesProcessor(cfg *config.Issues, log logutils.Log, files *fsutils.Files) processors.Processor { - var excludeRules []processors.ExcludeRule - for _, r := range cfg.ExcludeRules { - excludeRules = append(excludeRules, processors.ExcludeRule{ - BaseRule: processors.BaseRule{ - Text: r.Text, - Source: r.Source, - Path: r.Path, - PathExcept: r.PathExcept, - Linters: r.Linters, - }, - }) - } - - if cfg.UseDefaultExcludes { - for _, r := range config.GetExcludePatterns(cfg.IncludeDefaultExcludes) { - excludeRules = append(excludeRules, processors.ExcludeRule{ - BaseRule: processors.BaseRule{ - Text: r.Pattern, - Linters: []string{r.Linter}, - }, - }) - } - } - - var excludeRulesProcessor processors.Processor - if cfg.ExcludeCaseSensitive { - excludeRulesProcessor = processors.NewExcludeRulesCaseSensitive( - excludeRules, - files, - log.Child(logutils.DebugKeyExcludeRules), - ) - } else { - excludeRulesProcessor = processors.NewExcludeRules( - excludeRules, - files, - log.Child(logutils.DebugKeyExcludeRules), - ) - } - - return excludeRulesProcessor -} - -func getSeverityRulesProcessor(cfg *config.Severity, log logutils.Log, files *fsutils.Files) processors.Processor { - var severityRules []processors.SeverityRule - for _, r := range cfg.Rules { - severityRules = append(severityRules, processors.SeverityRule{ - Severity: r.Severity, - BaseRule: processors.BaseRule{ - Text: r.Text, - Source: r.Source, - Path: r.Path, - PathExcept: r.PathExcept, - Linters: r.Linters, - }, - }) - } - - var severityRulesProcessor processors.Processor - if cfg.CaseSensitive { - severityRulesProcessor = processors.NewSeverityRulesCaseSensitive( - cfg.Default, - severityRules, - files, - log.Child(logutils.DebugKeySeverityRules), - ) - } else { - severityRulesProcessor = processors.NewSeverityRules( - cfg.Default, - severityRules, - files, - log.Child(logutils.DebugKeySeverityRules), - ) - } - - return severityRulesProcessor -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/logutils.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/logutils.go index 94479bc7b..e4bb98109 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/logutils.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/logutils.go @@ -5,6 +5,9 @@ import ( "strings" ) +// EnvTestRun value: "1" +const EnvTestRun = "GL_TEST_RUN" + // envDebug value: one or several debug keys. // examples: // - Remove output to `/dev/null`: `GL_DEBUG=linters_output ./golangci-lint run` @@ -22,6 +25,7 @@ const ( DebugKeyExcludeRules = "exclude_rules" DebugKeyExec = "exec" DebugKeyFilenameUnadjuster = "filename_unadjuster" + DebugKeyInvalidIssue = "invalid_issue" DebugKeyForbidigo = "forbidigo" DebugKeyGoEnv = "goenv" DebugKeyLinter = "linter" @@ -57,6 +61,7 @@ const ( const ( DebugKeyGoCritic = "gocritic" // Debugs `go-critic` linter. + DebugKeyGovet = "govet" // Debugs `govet` linter. DebugKeyMegacheck = "megacheck" // Debugs `staticcheck` related linters. DebugKeyNolint = "nolint" // Debugs a filter excluding issues by `//nolint` comments. DebugKeyRevive = "revive" // Debugs `revive` linter. @@ -99,8 +104,15 @@ func HaveDebugTag(tag string) bool { return enabledDebugs[tag] } +var verbose bool + func SetupVerboseLog(log Log, isVerbose bool) { if isVerbose { + verbose = isVerbose log.SetLevel(LogLevelInfo) } } + +func IsVerbose() bool { + return verbose +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/mock.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/mock.go index efda8cc20..bddcf8552 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/mock.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/mock.go @@ -13,28 +13,23 @@ func NewMockLog() *MockLog { } func (m *MockLog) Fatalf(format string, args ...any) { - mArgs := []any{format} - m.Called(append(mArgs, args...)...) + m.Called(append([]any{format}, args...)...) } func (m *MockLog) Panicf(format string, args ...any) { - mArgs := []any{format} - m.Called(append(mArgs, args...)...) + m.Called(append([]any{format}, args...)...) } func (m *MockLog) Errorf(format string, args ...any) { - mArgs := []any{format} - m.Called(append(mArgs, args...)...) + m.Called(append([]any{format}, args...)...) } func (m *MockLog) Warnf(format string, args ...any) { - mArgs := []any{format} - m.Called(append(mArgs, args...)...) + m.Called(append([]any{format}, args...)...) } func (m *MockLog) Infof(format string, args ...any) { - mArgs := []any{format} - m.Called(append(mArgs, args...)...) + m.Called(append([]any{format}, args...)...) } func (m *MockLog) Child(name string) Log { @@ -45,3 +40,43 @@ func (m *MockLog) Child(name string) Log { func (m *MockLog) SetLevel(level LogLevel) { m.Called(level) } + +func (m *MockLog) OnFatalf(format string, args ...any) *MockLog { + arguments := append([]any{format}, args...) + + m.On("Fatalf", arguments...) + + return m +} + +func (m *MockLog) OnPanicf(format string, args ...any) *MockLog { + arguments := append([]any{format}, args...) + + m.On("Panicf", arguments...) + + return m +} + +func (m *MockLog) OnErrorf(format string, args ...any) *MockLog { + arguments := append([]any{format}, args...) + + m.On("Errorf", arguments...) + + return m +} + +func (m *MockLog) OnWarnf(format string, args ...any) *MockLog { + arguments := append([]any{format}, args...) + + m.On("Warnf", arguments...) + + return m +} + +func (m *MockLog) OnInfof(format string, args ...any) *MockLog { + arguments := append([]any{format}, args...) + + m.On("Infof", arguments...) + + return m +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/out.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/out.go index 67c70dc8f..ef1375486 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/out.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/out.go @@ -5,5 +5,7 @@ import ( colorable "github.com/mattn/go-colorable" ) -var StdOut = color.Output // https://github.com/golangci/golangci-lint/issues/14 -var StdErr = colorable.NewColorableStderr() +var ( + StdOut = color.Output // https://github.com/golangci/golangci-lint/issues/14 + StdErr = colorable.NewColorableStderr() +) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/stderr_log.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/stderr_log.go index 367c94f38..569a177a7 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/stderr_log.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/logutils/stderr_log.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/sirupsen/logrus" //nolint:depguard + "github.com/sirupsen/logrus" "github.com/golangci/golangci-lint/pkg/exitcodes" ) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/packages/skip.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/packages/skip.go deleted file mode 100644 index cdd327f5d..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/packages/skip.go +++ /dev/null @@ -1,25 +0,0 @@ -package packages - -import ( - "fmt" - "path/filepath" - "regexp" -) - -func pathElemReImpl(e string, sep rune) string { - escapedSep := regexp.QuoteMeta(string(sep)) // needed for windows sep '\\' - return fmt.Sprintf(`(^|%s)%s($|%s)`, escapedSep, e, escapedSep) -} - -func pathElemRe(e string) string { - return pathElemReImpl(e, filepath.Separator) -} - -var StdExcludeDirRegexps = []string{ - pathElemRe("vendor"), - pathElemRe("third_party"), - pathElemRe("testdata"), - pathElemRe("examples"), - pathElemRe("Godeps"), - pathElemRe("builtin"), -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go index 3762ca056..e32eef7f5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go @@ -7,6 +7,7 @@ import ( "sort" "github.com/go-xmlfmt/xmlfmt" + "golang.org/x/exp/maps" "github.com/golangci/golangci-lint/pkg/result" ) @@ -74,10 +75,7 @@ func (p Checkstyle) Print(issues []result.Issue) error { file.Errors = append(file.Errors, newError) } - out.Files = make([]*checkstyleFile, 0, len(files)) - for _, file := range files { - out.Files = append(out.Files, file) - } + out.Files = maps.Values(files) sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].Name < out.Files[j].Name diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/github.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/githubaction.go similarity index 66% rename from tools/vendor/github.com/golangci/golangci-lint/pkg/printers/github.go rename to tools/vendor/github.com/golangci/golangci-lint/pkg/printers/githubaction.go index c1da9df9c..d9cdb1e6e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/github.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/githubaction.go @@ -8,20 +8,30 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -type github struct { +const defaultGithubSeverity = "error" + +type GitHubAction struct { w io.Writer } -const defaultGithubSeverity = "error" +// NewGitHubAction output format outputs issues according to GitHub Action. +// Deprecated +func NewGitHubAction(w io.Writer) *GitHubAction { + return &GitHubAction{w: w} +} -// NewGithub output format outputs issues according to GitHub actions format: -// https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message -func NewGithub(w io.Writer) Printer { - return &github{w: w} +func (p *GitHubAction) Print(issues []result.Issue) error { + for ind := range issues { + _, err := fmt.Fprintln(p.w, formatIssueAsGitHub(&issues[ind])) + if err != nil { + return err + } + } + return nil } // print each line as: ::error file=app.js,line=10,col=15::Something went wrong -func formatIssueAsGithub(issue *result.Issue) string { +func formatIssueAsGitHub(issue *result.Issue) string { severity := defaultGithubSeverity if issue.Severity != "" { severity = issue.Severity @@ -40,13 +50,3 @@ func formatIssueAsGithub(issue *result.Issue) string { ret += fmt.Sprintf("::%s (%s)", issue.Text, issue.FromLinter) return ret } - -func (p *github) Print(issues []result.Issue) error { - for ind := range issues { - _, err := fmt.Fprintln(p.w, formatIssueAsGithub(&issues[ind])) - if err != nil { - return err - } - } - return nil -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/json.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/json.go index 4bae526b8..28509cac4 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/json.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/json.go @@ -9,7 +9,7 @@ import ( ) type JSON struct { - rd *report.Data + rd *report.Data // TODO(ldez) should be drop in v2. Only use by JSON reporter. w io.Writer } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go index 86a3811e4..3e3f82f58 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go @@ -7,6 +7,8 @@ import ( "sort" "strings" + "golang.org/x/exp/maps" + "github.com/golangci/golangci-lint/pkg/result" ) @@ -71,9 +73,7 @@ func (p JunitXML) Print(issues []result.Issue) error { } var res testSuitesXML - for _, val := range suites { - res.TestSuites = append(res.TestSuites, val) - } + res.TestSuites = maps.Values(suites) sort.Slice(res.TestSuites, func(i, j int) bool { return res.TestSuites[i].Suite < res.TestSuites[j].Suite diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/printer.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/printer.go index ce3116fa4..53db01220 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/printer.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/printer.go @@ -1,9 +1,145 @@ package printers import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/logutils" + "github.com/golangci/golangci-lint/pkg/report" "github.com/golangci/golangci-lint/pkg/result" ) -type Printer interface { +const defaultFileMode = 0o644 + +type issuePrinter interface { Print(issues []result.Issue) error } + +// Printer prints issues +type Printer struct { + cfg *config.Output + reportData *report.Data + + log logutils.Log + + stdOut io.Writer + stdErr io.Writer +} + +// NewPrinter creates a new Printer. +func NewPrinter(log logutils.Log, cfg *config.Output, reportData *report.Data) (*Printer, error) { + if log == nil { + return nil, errors.New("missing log argument in constructor") + } + if cfg == nil { + return nil, errors.New("missing config argument in constructor") + } + if reportData == nil { + return nil, errors.New("missing reportData argument in constructor") + } + + return &Printer{ + cfg: cfg, + reportData: reportData, + log: log, + stdOut: logutils.StdOut, + stdErr: logutils.StdErr, + }, nil +} + +// Print prints issues based on the formats defined +func (c *Printer) Print(issues []result.Issue) error { + for _, format := range c.cfg.Formats { + err := c.printReports(issues, format) + if err != nil { + return err + } + } + + return nil +} + +func (c *Printer) printReports(issues []result.Issue, format config.OutputFormat) error { + w, shouldClose, err := c.createWriter(format.Path) + if err != nil { + return fmt.Errorf("can't create output for %s: %w", format.Path, err) + } + + defer func() { + if file, ok := w.(io.Closer); shouldClose && ok { + _ = file.Close() + } + }() + + p, err := c.createPrinter(format.Format, w) + if err != nil { + return err + } + + if err = p.Print(issues); err != nil { + return fmt.Errorf("can't print %d issues: %w", len(issues), err) + } + + return nil +} + +func (c *Printer) createWriter(path string) (io.Writer, bool, error) { + if path == "" || path == "stdout" { + return c.stdOut, false, nil + } + + if path == "stderr" { + return c.stdErr, false, nil + } + + err := os.MkdirAll(filepath.Dir(path), os.ModePerm) + if err != nil { + return nil, false, err + } + + f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, defaultFileMode) + if err != nil { + return nil, false, err + } + + return f, true, nil +} + +func (c *Printer) createPrinter(format string, w io.Writer) (issuePrinter, error) { + var p issuePrinter + + switch format { + case config.OutFormatJSON: + p = NewJSON(c.reportData, w) + case config.OutFormatColoredLineNumber, config.OutFormatLineNumber: + p = NewText(c.cfg.PrintIssuedLine, + format == config.OutFormatColoredLineNumber, c.cfg.PrintLinterName, + c.log.Child(logutils.DebugKeyTextPrinter), w) + case config.OutFormatTab, config.OutFormatColoredTab: + p = NewTab(c.cfg.PrintLinterName, + format == config.OutFormatColoredTab, + c.log.Child(logutils.DebugKeyTabPrinter), w) + case config.OutFormatCheckstyle: + p = NewCheckstyle(w) + case config.OutFormatCodeClimate: + p = NewCodeClimate(w) + case config.OutFormatHTML: + p = NewHTML(w) + case config.OutFormatJunitXML: + p = NewJunitXML(w) + case config.OutFormatGithubActions: + p = NewGitHubAction(w) + case config.OutFormatTeamCity: + p = NewTeamCity(w) + case config.OutFormatSarif: + p = NewSarif(w) + default: + return nil, fmt.Errorf("unknown output format %q", format) + } + + return p, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/sarif.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/sarif.go new file mode 100644 index 000000000..8b1dd2ee2 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/sarif.go @@ -0,0 +1,117 @@ +package printers + +import ( + "encoding/json" + "io" + + "github.com/golangci/golangci-lint/pkg/result" +) + +const ( + sarifVersion = "2.1.0" + sarifSchemaURI = "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.6.json" +) + +type SarifOutput struct { + Version string `json:"version"` + Schema string `json:"$schema"` + Runs []sarifRun `json:"runs"` +} + +type sarifRun struct { + Tool sarifTool `json:"tool"` + Results []sarifResult `json:"results"` +} + +type sarifTool struct { + Driver struct { + Name string `json:"name"` + } `json:"driver"` +} + +type sarifResult struct { + RuleID string `json:"ruleId"` + Level string `json:"level"` + Message sarifMessage `json:"message"` + Locations []sarifLocation `json:"locations"` +} + +type sarifMessage struct { + Text string `json:"text"` +} + +type sarifLocation struct { + PhysicalLocation sarifPhysicalLocation `json:"physicalLocation"` +} + +type sarifPhysicalLocation struct { + ArtifactLocation sarifArtifactLocation `json:"artifactLocation"` + Region sarifRegion `json:"region"` +} + +type sarifArtifactLocation struct { + URI string `json:"uri"` + Index int `json:"index"` +} + +type sarifRegion struct { + StartLine int `json:"startLine"` + StartColumn int `json:"startColumn"` +} + +type Sarif struct { + w io.Writer +} + +func NewSarif(w io.Writer) *Sarif { + return &Sarif{w: w} +} + +func (p Sarif) Print(issues []result.Issue) error { + run := sarifRun{} + run.Tool.Driver.Name = "golangci-lint" + run.Results = make([]sarifResult, 0) + + for i := range issues { + issue := issues[i] + + severity := issue.Severity + + switch severity { + // https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/sarif-v2.1.0-errata01-os-complete.html#_Toc141790898 + case "none", "note", "warning", "error": + // Valid levels. + default: + severity = "error" + } + + sr := sarifResult{ + RuleID: issue.FromLinter, + Level: severity, + Message: sarifMessage{Text: issue.Text}, + Locations: []sarifLocation{ + { + PhysicalLocation: sarifPhysicalLocation{ + ArtifactLocation: sarifArtifactLocation{URI: issue.FilePath()}, + Region: sarifRegion{ + StartLine: issue.Line(), + // If startColumn is absent, it SHALL default to 1. + // https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/sarif-v2.1.0-errata01-os-complete.html#_Toc141790941 + StartColumn: max(1, issue.Column()), + }, + }, + }, + }, + } + + run.Results = append(run.Results, sr) + } + + output := SarifOutput{ + Version: sarifVersion, + Schema: sarifSchemaURI, + Runs: []sarifRun{run}, + } + + return json.NewEncoder(p.w).Encode(output) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/tab.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/tab.go index 8ede89740..c6d390d18 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/tab.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/tab.go @@ -52,15 +52,15 @@ func (p *Tab) Print(issues []result.Issue) error { return nil } -func (p *Tab) printIssue(i *result.Issue, w io.Writer) { - text := p.SprintfColored(color.FgRed, "%s", i.Text) +func (p *Tab) printIssue(issue *result.Issue, w io.Writer) { + text := p.SprintfColored(color.FgRed, "%s", issue.Text) if p.printLinterName { - text = fmt.Sprintf("%s\t%s", i.FromLinter, text) + text = fmt.Sprintf("%s\t%s", issue.FromLinter, text) } - pos := p.SprintfColored(color.Bold, "%s:%d", i.FilePath(), i.Line()) - if i.Pos.Column != 0 { - pos += fmt.Sprintf(":%d", i.Pos.Column) + pos := p.SprintfColored(color.Bold, "%s:%d", issue.FilePath(), issue.Line()) + if issue.Pos.Column != 0 { + pos += fmt.Sprintf(":%d", issue.Pos.Column) } fmt.Fprintf(w, "%s\t%s\n", pos, text) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/teamcity.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/teamcity.go index d3693e997..1d1c9f7d3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/teamcity.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/teamcity.go @@ -88,8 +88,8 @@ type InspectionType struct { } func (i InspectionType) Print(w io.Writer, escaper *strings.Replacer) (int, error) { - return fmt.Fprintf(w, "##teamcity[InspectionType id='%s' name='%s' description='%s' category='%s']\n", - limit(i.id, smallLimit), limit(i.name, smallLimit), limit(escaper.Replace(i.description), largeLimit), limit(i.category, smallLimit)) + return fmt.Fprintf(w, "##teamcity[inspectionType id='%s' name='%s' description='%s' category='%s']\n", + cutVal(i.id, smallLimit), cutVal(i.name, smallLimit), cutVal(escaper.Replace(i.description), largeLimit), cutVal(i.category, smallLimit)) } // InspectionInstance reports a specific defect, warning, error message. @@ -105,15 +105,15 @@ type InspectionInstance struct { func (i InspectionInstance) Print(w io.Writer, replacer *strings.Replacer) (int, error) { return fmt.Fprintf(w, "##teamcity[inspection typeId='%s' message='%s' file='%s' line='%d' SEVERITY='%s']\n", - limit(i.typeID, smallLimit), - limit(replacer.Replace(i.message), largeLimit), - limit(i.file, largeLimit), + cutVal(i.typeID, smallLimit), + cutVal(replacer.Replace(i.message), largeLimit), + cutVal(i.file, largeLimit), i.line, strings.ToUpper(i.severity)) } -func limit(s string, max int) string { +func cutVal(s string, limit int) string { var size, count int - for i := 0; i < max && count < len(s); i++ { + for i := 0; i < limit && count < len(s); i++ { _, size = utf8.DecodeRuneInString(s[count:]) count += size } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/text.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/text.go index 6e29c4b50..56cced769 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/text.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/printers/text.go @@ -55,32 +55,32 @@ func (p *Text) Print(issues []result.Issue) error { return nil } -func (p *Text) printIssue(i *result.Issue) { - text := p.SprintfColored(color.FgRed, "%s", strings.TrimSpace(i.Text)) +func (p *Text) printIssue(issue *result.Issue) { + text := p.SprintfColored(color.FgRed, "%s", strings.TrimSpace(issue.Text)) if p.printLinterName { - text += fmt.Sprintf(" (%s)", i.FromLinter) + text += fmt.Sprintf(" (%s)", issue.FromLinter) } - pos := p.SprintfColored(color.Bold, "%s:%d", i.FilePath(), i.Line()) - if i.Pos.Column != 0 { - pos += fmt.Sprintf(":%d", i.Pos.Column) + pos := p.SprintfColored(color.Bold, "%s:%d", issue.FilePath(), issue.Line()) + if issue.Pos.Column != 0 { + pos += fmt.Sprintf(":%d", issue.Pos.Column) } fmt.Fprintf(p.w, "%s: %s\n", pos, text) } -func (p *Text) printSourceCode(i *result.Issue) { - for _, line := range i.SourceLines { +func (p *Text) printSourceCode(issue *result.Issue) { + for _, line := range issue.SourceLines { fmt.Fprintln(p.w, line) } } -func (p *Text) printUnderLinePointer(i *result.Issue) { +func (p *Text) printUnderLinePointer(issue *result.Issue) { // if column == 0 it means column is unknown (e.g. for gosec) - if len(i.SourceLines) != 1 || i.Pos.Column == 0 { + if len(issue.SourceLines) != 1 || issue.Pos.Column == 0 { return } - col0 := i.Pos.Column - 1 - line := i.SourceLines[0] + col0 := issue.Pos.Column - 1 + line := issue.SourceLines[0] prefixRunes := make([]rune, 0, len(line)) for j := 0; j < len(line) && j < col0; j++ { if line[j] == '\t' { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go index 1e8cd3052..32246a6df 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go @@ -1,7 +1,7 @@ package result import ( - "crypto/md5" //nolint:gosec + "crypto/md5" //nolint:gosec // for md5 hash "fmt" "go/token" @@ -91,7 +91,7 @@ func (i *Issue) Fingerprint() string { firstLine = i.SourceLines[0] } - hash := md5.New() //nolint:gosec + hash := md5.New() //nolint:gosec // we don't need a strong hash here _, _ = fmt.Fprintf(hash, "%s%s%s", i.Pos.Filename, i.Text, firstLine) return fmt.Sprintf("%X", hash.Sum(nil)) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go index c7675fce8..8ceb936e8 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go @@ -1,121 +1,158 @@ package processors import ( - "errors" "fmt" "go/parser" "go/token" "path/filepath" + "regexp" "strings" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" ) -var autogenDebugf = logutils.Debug(logutils.DebugKeyAutogenExclude) +const ( + AutogeneratedModeLax = "lax" + AutogeneratedModeStrict = "strict" + AutogeneratedModeDisable = "disable" +) -type ageFileSummary struct { - isGenerated bool -} +const ( + genCodeGenerated = "code generated" + genDoNotEdit = "do not edit" + genAutoFile = "autogenerated file" // easyjson +) -type ageFileSummaryCache map[string]*ageFileSummary +var _ Processor = (*AutogeneratedExclude)(nil) + +type fileSummary struct { + generated bool +} type AutogeneratedExclude struct { - fileSummaryCache ageFileSummaryCache + debugf logutils.DebugFunc + + mode string + strictPattern *regexp.Regexp + + fileSummaryCache map[string]*fileSummary } -func NewAutogeneratedExclude() *AutogeneratedExclude { +func NewAutogeneratedExclude(mode string) *AutogeneratedExclude { return &AutogeneratedExclude{ - fileSummaryCache: ageFileSummaryCache{}, + debugf: logutils.Debug(logutils.DebugKeyAutogenExclude), + mode: mode, + strictPattern: regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`), + fileSummaryCache: map[string]*fileSummary{}, } } -var _ Processor = &AutogeneratedExclude{} - -func (p *AutogeneratedExclude) Name() string { +func (*AutogeneratedExclude) Name() string { return "autogenerated_exclude" } func (p *AutogeneratedExclude) Process(issues []result.Issue) ([]result.Issue, error) { + if p.mode == AutogeneratedModeDisable { + return issues, nil + } + return filterIssuesErr(issues, p.shouldPassIssue) } -func isSpecialAutogeneratedFile(filePath string) bool { - fileName := filepath.Base(filePath) - // fake files or generation definitions to which //line points to for generated files - return filepath.Ext(fileName) != ".go" -} +func (*AutogeneratedExclude) Finish() {} -func (p *AutogeneratedExclude) shouldPassIssue(i *result.Issue) (bool, error) { - if i.FromLinter == "typecheck" { - // don't hide typechecking errors in generated files: users expect to see why the project isn't compiling +func (p *AutogeneratedExclude) shouldPassIssue(issue *result.Issue) (bool, error) { + if filepath.Base(issue.FilePath()) == "go.mod" { return true, nil } - if filepath.Base(i.FilePath()) == "go.mod" { - return true, nil + // The file is already known. + fs := p.fileSummaryCache[issue.FilePath()] + if fs != nil { + return !fs.generated, nil } - if isSpecialAutogeneratedFile(i.FilePath()) { - return false, nil - } + fs = &fileSummary{} + p.fileSummaryCache[issue.FilePath()] = fs - fs, err := p.getOrCreateFileSummary(i) - if err != nil { - return false, err + if p.mode == AutogeneratedModeStrict { + var err error + fs.generated, err = p.isGeneratedFileStrict(issue.FilePath()) + if err != nil { + return false, fmt.Errorf("failed to get doc (strict) of file %s: %w", issue.FilePath(), err) + } + } else { + doc, err := getComments(issue.FilePath()) + if err != nil { + return false, fmt.Errorf("failed to get doc (lax) of file %s: %w", issue.FilePath(), err) + } + + fs.generated = p.isGeneratedFileLax(doc) } + p.debugf("file %q is generated: %t", issue.FilePath(), fs.generated) + // don't report issues for autogenerated files - return !fs.isGenerated, nil + return !fs.generated, nil } -// isGenerated reports whether the source file is generated code. -// Using a bit laxer rules than https://go.dev/s/generatedcode to -// match more generated code. See #48 and #72. -func isGeneratedFileByComment(doc string) bool { - const ( - genCodeGenerated = "code generated" - genDoNotEdit = "do not edit" - genAutoFile = "autogenerated file" // easyjson - ) - +// isGeneratedFileLax reports whether the source file is generated code. +// The function uses a bit laxer rules than isGeneratedFileStrict to match more generated code. +// See https://github.com/golangci/golangci-lint/issues/48 and https://github.com/golangci/golangci-lint/issues/72. +func (p *AutogeneratedExclude) isGeneratedFileLax(doc string) bool { markers := []string{genCodeGenerated, genDoNotEdit, genAutoFile} + doc = strings.ToLower(doc) + for _, marker := range markers { if strings.Contains(doc, marker) { - autogenDebugf("doc contains marker %q: file is generated", marker) + p.debugf("doc contains marker %q: file is generated", marker) + return true } } - autogenDebugf("doc of len %d doesn't contain any of markers: %s", len(doc), markers) + p.debugf("doc of len %d doesn't contain any of markers: %s", len(doc), markers) + return false } -func (p *AutogeneratedExclude) getOrCreateFileSummary(i *result.Issue) (*ageFileSummary, error) { - fs := p.fileSummaryCache[i.FilePath()] - if fs != nil { - return fs, nil +// isGeneratedFileStrict returns true if the source file has a line that matches the regular expression: +// +// ^// Code generated .* DO NOT EDIT\.$ +// +// This line must appear before the first non-comment, non-blank text in the file. +// Based on https://go.dev/s/generatedcode. +func (p *AutogeneratedExclude) isGeneratedFileStrict(filePath string) (bool, error) { + file, err := parser.ParseFile(token.NewFileSet(), filePath, nil, parser.PackageClauseOnly|parser.ParseComments) + if err != nil { + return false, fmt.Errorf("failed to parse file: %w", err) } - fs = &ageFileSummary{} - p.fileSummaryCache[i.FilePath()] = fs - - if i.FilePath() == "" { - return nil, errors.New("no file path for issue") + if file == nil || len(file.Comments) == 0 { + return false, nil } - doc, err := getDoc(i.FilePath()) - if err != nil { - return nil, fmt.Errorf("failed to get doc of file %s: %w", i.FilePath(), err) + for _, comment := range file.Comments { + if comment.Pos() > file.Package { + return false, nil + } + + for _, line := range comment.List { + generated := p.strictPattern.MatchString(line.Text) + if generated { + p.debugf("doc contains ignore expression: file is generated") + + return true, nil + } + } } - fs.isGenerated = isGeneratedFileByComment(doc) - autogenDebugf("file %q is generated: %t", i.FilePath(), fs.isGenerated) - return fs, nil + return false, nil } -func getDoc(filePath string) (string, error) { +func getComments(filePath string) (string, error) { fset := token.NewFileSet() syntax, err := parser.ParseFile(fset, filePath, nil, parser.PackageClauseOnly|parser.ParseComments) if err != nil { @@ -129,5 +166,3 @@ func getDoc(filePath string) (string, error) { return strings.Join(docLines, "\n"), nil } - -func (p *AutogeneratedExclude) Finish() {} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/base_rule.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/base_rule.go index b5e138806..d7a4f0ec4 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/base_rule.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/base_rule.go @@ -8,13 +8,7 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -type BaseRule struct { - Text string - Source string - Path string - PathExcept string - Linters []string -} +const caseInsensitivePrefix = "(?i)" type baseRule struct { text *regexp.Regexp @@ -63,7 +57,7 @@ func (r *baseRule) matchLinter(issue *result.Issue) bool { return false } -func (r *baseRule) matchSource(issue *result.Issue, lineCache *fsutils.LineCache, log logutils.Log) bool { //nolint:interfacer +func (r *baseRule) matchSource(issue *result.Issue, lineCache *fsutils.LineCache, log logutils.Log) bool { sourceLine, errSourceLine := lineCache.GetLine(issue.FilePath(), issue.Line()) if errSourceLine != nil { log.Warnf("Failed to get line %s:%d from line cache: %s", issue.FilePath(), issue.Line(), errSourceLine) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/cgo.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/cgo.go index 8e7723751..0e659f0f3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/cgo.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/cgo.go @@ -9,49 +9,51 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*Cgo)(nil) + type Cgo struct { goCacheDir string } -var _ Processor = Cgo{} - func NewCgo(goenv *goutil.Env) *Cgo { return &Cgo{ goCacheDir: goenv.Get(goutil.EnvGoCache), } } -func (p Cgo) Name() string { +func (Cgo) Name() string { return "cgo" } func (p Cgo) Process(issues []result.Issue) ([]result.Issue, error) { - return filterIssuesErr(issues, func(i *result.Issue) (bool, error) { - // some linters (.e.g gosec, deadcode) return incorrect filepaths for cgo issues, - // also cgo files have strange issues looking like false positives. - - // cache dir contains all preprocessed files including cgo files - - issueFilePath := i.FilePath() - if !filepath.IsAbs(i.FilePath()) { - absPath, err := filepath.Abs(i.FilePath()) - if err != nil { - return false, fmt.Errorf("failed to build abs path for %q: %w", i.FilePath(), err) - } - issueFilePath = absPath - } + return filterIssuesErr(issues, p.shouldPassIssue) +} - if p.goCacheDir != "" && strings.HasPrefix(issueFilePath, p.goCacheDir) { - return false, nil - } +func (Cgo) Finish() {} + +func (p Cgo) shouldPassIssue(issue *result.Issue) (bool, error) { + // some linters (e.g. gosec, deadcode) return incorrect filepaths for cgo issues, + // also cgo files have strange issues looking like false positives. + + // cache dir contains all preprocessed files including cgo files - if filepath.Base(i.FilePath()) == "_cgo_gotypes.go" { - // skip cgo warning for go1.10 - return false, nil + issueFilePath := issue.FilePath() + if !filepath.IsAbs(issue.FilePath()) { + absPath, err := filepath.Abs(issue.FilePath()) + if err != nil { + return false, fmt.Errorf("failed to build abs path for %q: %w", issue.FilePath(), err) } + issueFilePath = absPath + } - return true, nil - }) -} + if p.goCacheDir != "" && strings.HasPrefix(issueFilePath, p.goCacheDir) { + return false, nil + } -func (Cgo) Finish() {} + if filepath.Base(issue.FilePath()) == "_cgo_gotypes.go" { + // skip cgo warning for go1.10 + return false, nil + } + + return true, nil +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/diff.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/diff.go index 67104bab0..c602cdc65 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/diff.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/diff.go @@ -9,11 +9,14 @@ import ( "github.com/golangci/revgrep" + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/result" ) const envGolangciDiffProcessorPatch = "GOLANGCI_DIFF_PROCESSOR_PATCH" +var _ Processor = (*Diff)(nil) + type Diff struct { onlyNew bool fromRev string @@ -22,19 +25,17 @@ type Diff struct { patch string } -var _ Processor = Diff{} - -func NewDiff(onlyNew bool, fromRev, patchFilePath string, wholeFiles bool) *Diff { +func NewDiff(cfg *config.Issues) *Diff { return &Diff{ - onlyNew: onlyNew, - fromRev: fromRev, - patchFilePath: patchFilePath, - wholeFiles: wholeFiles, + onlyNew: cfg.Diff, + fromRev: cfg.DiffFromRevision, + patchFilePath: cfg.DiffPatchFilePath, + wholeFiles: cfg.WholeFiles, patch: os.Getenv(envGolangciDiffProcessorPatch), } } -func (p Diff) Name() string { +func (Diff) Name() string { return "diff" } @@ -47,7 +48,7 @@ func (p Diff) Process(issues []result.Issue) ([]result.Issue, error) { if p.patchFilePath != "" { patch, err := os.ReadFile(p.patchFilePath) if err != nil { - return nil, fmt.Errorf("can't read from patch file %s: %s", p.patchFilePath, err) + return nil, fmt.Errorf("can't read from patch file %s: %w", p.patchFilePath, err) } patchReader = bytes.NewReader(patch) } else if p.patch != "" { @@ -60,18 +61,23 @@ func (p Diff) Process(issues []result.Issue) ([]result.Issue, error) { WholeFiles: p.wholeFiles, } if err := c.Prepare(); err != nil { - return nil, fmt.Errorf("can't prepare diff by revgrep: %s", err) + return nil, fmt.Errorf("can't prepare diff by revgrep: %w", err) } - return transformIssues(issues, func(i *result.Issue) *result.Issue { - hunkPos, isNew := c.IsNewIssue(i) + return transformIssues(issues, func(issue *result.Issue) *result.Issue { + if issue.FromLinter == typeCheckName { + // Never hide typechecking errors. + return issue + } + + hunkPos, isNew := c.IsNewIssue(issue) if !isNew { return nil } - newI := *i - newI.HunkPos = hunkPos - return &newI + newIssue := *issue + newIssue.HunkPos = hunkPos + return &newIssue }), nil } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude.go index 92959a328..543120450 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude.go @@ -1,29 +1,45 @@ package processors import ( + "fmt" "regexp" + "strings" + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*Exclude)(nil) + type Exclude struct { + name string + pattern *regexp.Regexp } -var _ Processor = Exclude{} +func NewExclude(cfg *config.Issues) *Exclude { + p := &Exclude{name: "exclude"} -func NewExclude(pattern string) *Exclude { - var patternRe *regexp.Regexp - if pattern != "" { - patternRe = regexp.MustCompile("(?i)" + pattern) + var pattern string + if len(cfg.ExcludePatterns) != 0 { + pattern = fmt.Sprintf("(%s)", strings.Join(cfg.ExcludePatterns, "|")) } - return &Exclude{ - pattern: patternRe, + + prefix := caseInsensitivePrefix + if cfg.ExcludeCaseSensitive { + p.name = "exclude-case-sensitive" + prefix = "" } + + if pattern != "" { + p.pattern = regexp.MustCompile(prefix + pattern) + } + + return p } func (p Exclude) Name() string { - return "exclude" + return p.name } func (p Exclude) Process(issues []result.Issue) ([]result.Issue, error) { @@ -31,29 +47,9 @@ func (p Exclude) Process(issues []result.Issue) ([]result.Issue, error) { return issues, nil } - return filterIssues(issues, func(i *result.Issue) bool { - return !p.pattern.MatchString(i.Text) + return filterIssues(issues, func(issue *result.Issue) bool { + return !p.pattern.MatchString(issue.Text) }), nil } -func (p Exclude) Finish() {} - -type ExcludeCaseSensitive struct { - *Exclude -} - -var _ Processor = ExcludeCaseSensitive{} - -func NewExcludeCaseSensitive(pattern string) *ExcludeCaseSensitive { - var patternRe *regexp.Regexp - if pattern != "" { - patternRe = regexp.MustCompile(pattern) - } - return &ExcludeCaseSensitive{ - &Exclude{pattern: patternRe}, - } -} - -func (p ExcludeCaseSensitive) Name() string { - return "exclude-case-sensitive" -} +func (Exclude) Finish() {} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go index 2f7e30b43..b468c5101 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go @@ -3,93 +3,104 @@ package processors import ( "regexp" + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/fsutils" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*ExcludeRules)(nil) + type excludeRule struct { baseRule } -type ExcludeRule struct { - BaseRule -} - type ExcludeRules struct { - rules []excludeRule - files *fsutils.Files + name string + log logutils.Log + files *fsutils.Files + + rules []excludeRule } -func NewExcludeRules(rules []ExcludeRule, files *fsutils.Files, log logutils.Log) *ExcludeRules { - r := &ExcludeRules{ +func NewExcludeRules(log logutils.Log, files *fsutils.Files, cfg *config.Issues) *ExcludeRules { + p := &ExcludeRules{ + name: "exclude-rules", files: files, log: log, } - r.rules = createRules(rules, "(?i)") - return r -} + prefix := caseInsensitivePrefix + if cfg.ExcludeCaseSensitive { + prefix = "" + p.name = "exclude-rules-case-sensitive" + } -func createRules(rules []ExcludeRule, prefix string) []excludeRule { - parsedRules := make([]excludeRule, 0, len(rules)) - for _, rule := range rules { - parsedRule := excludeRule{} - parsedRule.linters = rule.Linters - if rule.Text != "" { - parsedRule.text = regexp.MustCompile(prefix + rule.Text) - } - if rule.Source != "" { - parsedRule.source = regexp.MustCompile(prefix + rule.Source) - } - if rule.Path != "" { - path := fsutils.NormalizePathInRegex(rule.Path) - parsedRule.path = regexp.MustCompile(path) - } - if rule.PathExcept != "" { - pathExcept := fsutils.NormalizePathInRegex(rule.PathExcept) - parsedRule.pathExcept = regexp.MustCompile(pathExcept) + excludeRules := cfg.ExcludeRules + + if cfg.UseDefaultExcludes { + for _, r := range config.GetExcludePatterns(cfg.IncludeDefaultExcludes) { + excludeRules = append(excludeRules, config.ExcludeRule{ + BaseRule: config.BaseRule{ + Text: r.Pattern, + Linters: []string{r.Linter}, + }, + }) } - parsedRules = append(parsedRules, parsedRule) } - return parsedRules + + p.rules = createRules(excludeRules, prefix) + + return p } +func (p ExcludeRules) Name() string { return p.name } + func (p ExcludeRules) Process(issues []result.Issue) ([]result.Issue, error) { if len(p.rules) == 0 { return issues, nil } - return filterIssues(issues, func(i *result.Issue) bool { + + return filterIssues(issues, func(issue *result.Issue) bool { for _, rule := range p.rules { rule := rule - if rule.match(i, p.files, p.log) { + if rule.match(issue, p.files, p.log) { return false } } + return true }), nil } -func (ExcludeRules) Name() string { return "exclude-rules" } -func (ExcludeRules) Finish() {} +func (ExcludeRules) Finish() {} -var _ Processor = ExcludeRules{} +func createRules(rules []config.ExcludeRule, prefix string) []excludeRule { + parsedRules := make([]excludeRule, 0, len(rules)) -type ExcludeRulesCaseSensitive struct { - *ExcludeRules -} + for _, rule := range rules { + parsedRule := excludeRule{} + parsedRule.linters = rule.Linters -func NewExcludeRulesCaseSensitive(rules []ExcludeRule, files *fsutils.Files, log logutils.Log) *ExcludeRulesCaseSensitive { - r := &ExcludeRules{ - files: files, - log: log, - } - r.rules = createRules(rules, "") + if rule.Text != "" { + parsedRule.text = regexp.MustCompile(prefix + rule.Text) + } - return &ExcludeRulesCaseSensitive{r} -} + if rule.Source != "" { + parsedRule.source = regexp.MustCompile(prefix + rule.Source) + } + + if rule.Path != "" { + parsedRule.path = regexp.MustCompile(fsutils.NormalizePathInRegex(rule.Path)) + } -func (ExcludeRulesCaseSensitive) Name() string { return "exclude-rules-case-sensitive" } + if rule.PathExcept != "" { + parsedRule.pathExcept = regexp.MustCompile(fsutils.NormalizePathInRegex(rule.PathExcept)) + } -var _ Processor = ExcludeCaseSensitive{} + parsedRules = append(parsedRules, parsedRule) + } + + return parsedRules +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go index 2aaafbf58..6a1387c87 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go @@ -14,6 +14,8 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*FilenameUnadjuster)(nil) + type posMapper func(pos token.Position) token.Position type adjustMap struct { @@ -30,7 +32,61 @@ type FilenameUnadjuster struct { loggedUnadjustments map[string]bool } -var _ Processor = &FilenameUnadjuster{} +func NewFilenameUnadjuster(pkgs []*packages.Package, log logutils.Log) *FilenameUnadjuster { + m := adjustMap{m: map[string]posMapper{}} + + startedAt := time.Now() + var wg sync.WaitGroup + wg.Add(len(pkgs)) + for _, pkg := range pkgs { + go func(pkg *packages.Package) { + // It's important to call func here to run GC + processUnadjusterPkg(&m, pkg, log) + wg.Done() + }(pkg) + } + wg.Wait() + log.Infof("Pre-built %d adjustments in %s", len(m.m), time.Since(startedAt)) + + return &FilenameUnadjuster{ + m: m.m, + log: log, + loggedUnadjustments: map[string]bool{}, + } +} + +func (*FilenameUnadjuster) Name() string { + return "filename_unadjuster" +} + +func (p *FilenameUnadjuster) Process(issues []result.Issue) ([]result.Issue, error) { + return transformIssues(issues, func(issue *result.Issue) *result.Issue { + issueFilePath := issue.FilePath() + if !filepath.IsAbs(issue.FilePath()) { + absPath, err := filepath.Abs(issue.FilePath()) + if err != nil { + p.log.Warnf("failed to build abs path for %q: %s", issue.FilePath(), err) + return issue + } + issueFilePath = absPath + } + + mapper := p.m[issueFilePath] + if mapper == nil { + return issue + } + + newIssue := *issue + newIssue.Pos = mapper(issue.Pos) + if !p.loggedUnadjustments[issue.Pos.Filename] { + p.log.Infof("Unadjusted from %v to %v", issue.Pos, newIssue.Pos) + p.loggedUnadjustments[issue.Pos.Filename] = true + } + return &newIssue + }), nil +} + +func (*FilenameUnadjuster) Finish() {} func processUnadjusterPkg(m *adjustMap, pkg *packages.Package, log logutils.Log) { fset := token.NewFileSet() // it's more memory efficient to not store all in one fset @@ -64,68 +120,14 @@ func processUnadjusterFile(filename string, m *adjustMap, log logutils.Log, fset m.Lock() defer m.Unlock() + m.m[adjustedFilename] = func(adjustedPos token.Position) token.Position { tokenFile := fset.File(syntax.Pos()) if tokenFile == nil { log.Warnf("Failed to get token file for %s", adjustedFilename) return adjustedPos } - return fset.PositionFor(tokenFile.Pos(adjustedPos.Offset), false) - } -} - -func NewFilenameUnadjuster(pkgs []*packages.Package, log logutils.Log) *FilenameUnadjuster { - m := adjustMap{m: map[string]posMapper{}} - startedAt := time.Now() - var wg sync.WaitGroup - wg.Add(len(pkgs)) - for _, pkg := range pkgs { - go func(pkg *packages.Package) { - // It's important to call func here to run GC - processUnadjusterPkg(&m, pkg, log) - wg.Done() - }(pkg) - } - wg.Wait() - log.Infof("Pre-built %d adjustments in %s", len(m.m), time.Since(startedAt)) - - return &FilenameUnadjuster{ - m: m.m, - log: log, - loggedUnadjustments: map[string]bool{}, + return fset.PositionFor(tokenFile.Pos(adjustedPos.Offset), false) } } - -func (p *FilenameUnadjuster) Name() string { - return "filename_unadjuster" -} - -func (p *FilenameUnadjuster) Process(issues []result.Issue) ([]result.Issue, error) { - return transformIssues(issues, func(i *result.Issue) *result.Issue { - issueFilePath := i.FilePath() - if !filepath.IsAbs(i.FilePath()) { - absPath, err := filepath.Abs(i.FilePath()) - if err != nil { - p.log.Warnf("failed to build abs path for %q: %s", i.FilePath(), err) - return i - } - issueFilePath = absPath - } - - mapper := p.m[issueFilePath] - if mapper == nil { - return i - } - - newI := *i - newI.Pos = mapper(i.Pos) - if !p.loggedUnadjustments[i.Pos.Filename] { - p.log.Infof("Unadjusted from %v to %v", i.Pos, newI.Pos) - p.loggedUnadjustments[i.Pos.Filename] = true - } - return &newI - }), nil -} - -func (p *FilenameUnadjuster) Finish() {} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/fixer.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/fixer.go index a79a84628..4915dc479 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/fixer.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/fixer.go @@ -16,7 +16,7 @@ import ( "github.com/golangci/golangci-lint/pkg/timeutils" ) -var _ Processor = Fixer{} +var _ Processor = (*Fixer)(nil) type Fixer struct { cfg *config.Config @@ -34,12 +34,12 @@ func NewFixer(cfg *config.Config, log logutils.Log, fileCache *fsutils.FileCache } } -func (f Fixer) printStat() { - f.sw.PrintStages() +func (Fixer) Name() string { + return "fixer" } -func (f Fixer) Process(issues []result.Issue) ([]result.Issue, error) { - if !f.cfg.Issues.NeedFix { +func (p Fixer) Process(issues []result.Issue) ([]result.Issue, error) { + if !p.cfg.Issues.NeedFix { return issues, nil } @@ -57,37 +57,36 @@ func (f Fixer) Process(issues []result.Issue) ([]result.Issue, error) { for file, issuesToFix := range issuesToFixPerFile { var err error - f.sw.TrackStage("all", func() { - err = f.fixIssuesInFile(file, issuesToFix) + p.sw.TrackStage("all", func() { + err = p.fixIssuesInFile(file, issuesToFix) }) if err != nil { - f.log.Errorf("Failed to fix issues in file %s: %s", file, err) + p.log.Errorf("Failed to fix issues in file %s: %s", file, err) // show issues only if can't fix them outIssues = append(outIssues, issuesToFix...) } } - f.printStat() - return outIssues, nil -} + p.printStat() -func (f Fixer) Name() string { - return "fixer" + return outIssues, nil } -func (f Fixer) Finish() {} +func (Fixer) Finish() {} -func (f Fixer) fixIssuesInFile(filePath string, issues []result.Issue) error { +func (p Fixer) fixIssuesInFile(filePath string, issues []result.Issue) error { // TODO: don't read the whole file into memory: read line by line; // can't just use bufio.scanner: it has a line length limit - origFileData, err := f.fileCache.GetFileBytes(filePath) + origFileData, err := p.fileCache.GetFileBytes(filePath) if err != nil { return fmt.Errorf("failed to get file bytes for %s: %w", filePath, err) } + origFileLines := bytes.Split(origFileData, []byte("\n")) tmpFileName := filepath.Join(filepath.Dir(filePath), fmt.Sprintf(".%s.golangci_fix", filepath.Base(filePath))) + tmpOutFile, err := os.Create(tmpFileName) if err != nil { return fmt.Errorf("failed to make file %s: %w", tmpFileName, err) @@ -102,20 +101,21 @@ func (f Fixer) fixIssuesInFile(filePath string, issues []result.Issue) error { issues = issues[:0] // reuse the same memory for line, lineIssues := range issuesPerLine { - if mergedIssue := f.mergeLineIssues(line, lineIssues, origFileLines); mergedIssue != nil { + if mergedIssue := p.mergeLineIssues(line, lineIssues, origFileLines); mergedIssue != nil { issues = append(issues, *mergedIssue) } } - issues = f.findNotIntersectingIssues(issues) + issues = p.findNotIntersectingIssues(issues) - if err = f.writeFixedFile(origFileLines, issues, tmpOutFile); err != nil { + if err = p.writeFixedFile(origFileLines, issues, tmpOutFile); err != nil { tmpOutFile.Close() _ = robustio.RemoveAll(tmpOutFile.Name()) return err } tmpOutFile.Close() + if err = robustio.Rename(tmpOutFile.Name(), filePath); err != nil { _ = robustio.RemoveAll(tmpOutFile.Name()) return fmt.Errorf("failed to rename %s -> %s: %w", tmpOutFile.Name(), filePath, err) @@ -124,7 +124,7 @@ func (f Fixer) fixIssuesInFile(filePath string, issues []result.Issue) error { return nil } -func (f Fixer) mergeLineIssues(lineNum int, lineIssues []result.Issue, origFileLines [][]byte) *result.Issue { +func (p Fixer) mergeLineIssues(lineNum int, lineIssues []result.Issue, origFileLines [][]byte) *result.Issue { origLine := origFileLines[lineNum-1] // lineNum is 1-based if len(lineIssues) == 1 && lineIssues[0].Replacement.Inline == nil { @@ -133,28 +133,30 @@ func (f Fixer) mergeLineIssues(lineNum int, lineIssues []result.Issue, origFileL // check issues first for ind := range lineIssues { - i := &lineIssues[ind] - if i.LineRange != nil { - f.log.Infof("Line %d has multiple issues but at least one of them is ranged: %#v", lineNum, lineIssues) + li := &lineIssues[ind] + + if li.LineRange != nil { + p.log.Infof("Line %d has multiple issues but at least one of them is ranged: %#v", lineNum, lineIssues) return &lineIssues[0] } - r := i.Replacement - if r.Inline == nil || len(r.NewLines) != 0 || r.NeedOnlyDelete { - f.log.Infof("Line %d has multiple issues but at least one of them isn't inline: %#v", lineNum, lineIssues) - return &lineIssues[0] + inline := li.Replacement.Inline + + if inline == nil || len(li.Replacement.NewLines) != 0 || li.Replacement.NeedOnlyDelete { + p.log.Infof("Line %d has multiple issues but at least one of them isn't inline: %#v", lineNum, lineIssues) + return li } - if r.Inline.StartCol < 0 || r.Inline.Length <= 0 || r.Inline.StartCol+r.Inline.Length > len(origLine) { - f.log.Warnf("Line %d (%q) has invalid inline fix: %#v, %#v", lineNum, origLine, i, r.Inline) + if inline.StartCol < 0 || inline.Length <= 0 || inline.StartCol+inline.Length > len(origLine) { + p.log.Warnf("Line %d (%q) has invalid inline fix: %#v, %#v", lineNum, origLine, li, inline) return nil } } - return f.applyInlineFixes(lineIssues, origLine, lineNum) + return p.applyInlineFixes(lineIssues, origLine, lineNum) } -func (f Fixer) applyInlineFixes(lineIssues []result.Issue, origLine []byte, lineNum int) *result.Issue { +func (p Fixer) applyInlineFixes(lineIssues []result.Issue, origLine []byte, lineNum int) *result.Issue { sort.Slice(lineIssues, func(i, j int) bool { return lineIssues[i].Replacement.Inline.StartCol < lineIssues[j].Replacement.Inline.StartCol }) @@ -162,14 +164,14 @@ func (f Fixer) applyInlineFixes(lineIssues []result.Issue, origLine []byte, line var newLineBuf bytes.Buffer newLineBuf.Grow(len(origLine)) - //nolint:misspell + //nolint:misspell // misspelling is intentional // example: origLine="it's becouse of them", StartCol=5, Length=7, NewString="because" curOrigLinePos := 0 for i := range lineIssues { fix := lineIssues[i].Replacement.Inline if fix.StartCol < curOrigLinePos { - f.log.Warnf("Line %d has multiple intersecting issues: %#v", lineNum, lineIssues) + p.log.Warnf("Line %d has multiple intersecting issues: %#v", lineNum, lineIssues) return nil } @@ -190,7 +192,7 @@ func (f Fixer) applyInlineFixes(lineIssues []result.Issue, origLine []byte, line return &mergedIssue } -func (f Fixer) findNotIntersectingIssues(issues []result.Issue) []result.Issue { +func (p Fixer) findNotIntersectingIssues(issues []result.Issue) []result.Issue { sort.SliceStable(issues, func(i, j int) bool { a, b := issues[i], issues[j] return a.Line() < b.Line() @@ -202,10 +204,10 @@ func (f Fixer) findNotIntersectingIssues(issues []result.Issue) []result.Issue { issue := &issues[i] rng := issue.GetLineRange() if rng.From <= currentEnd { - f.log.Infof("Skip issue %#v: intersects with end %d", issue, currentEnd) + p.log.Infof("Skip issue %#v: intersects with end %d", issue, currentEnd) continue // skip intersecting issue } - f.log.Infof("Fix issue %#v with range %v", issue, issue.GetLineRange()) + p.log.Infof("Fix issue %#v with range %v", issue, issue.GetLineRange()) ret = append(ret, *issue) currentEnd = rng.To } @@ -213,7 +215,7 @@ func (f Fixer) findNotIntersectingIssues(issues []result.Issue) []result.Issue { return ret } -func (f Fixer) writeFixedFile(origFileLines [][]byte, issues []result.Issue, tmpOutFile *os.File) error { +func (p Fixer) writeFixedFile(origFileLines [][]byte, issues []result.Issue, tmpOutFile *os.File) error { // issues aren't intersecting nextIssueIndex := 0 @@ -232,7 +234,7 @@ func (f Fixer) writeFixedFile(origFileLines [][]byte, issues []result.Issue, tmp rng := nextIssue.GetLineRange() if rng.From > rng.To { // Maybe better decision is to skip such issues, re-evaluate if regressed. - f.log.Warnf("[fixer]: issue line range is probably invalid, fix can be incorrect (from=%d, to=%d, linter=%s)", + p.log.Warnf("[fixer]: issue line range is probably invalid, fix can be incorrect (from=%d, to=%d, linter=%s)", rng.From, rng.To, nextIssue.FromLinter, ) } @@ -253,3 +255,7 @@ func (f Fixer) writeFixedFile(origFileLines [][]byte, issues []result.Issue, tmp return nil } + +func (p Fixer) printStat() { + p.sw.PrintStages() +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/identifier_marker.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/identifier_marker.go index 5cc4e56ba..876fd3bd3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/identifier_marker.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/identifier_marker.go @@ -6,6 +6,8 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*IdentifierMarker)(nil) + type replacePattern struct { re string repl string @@ -31,27 +33,39 @@ var replacePatterns = []replacePattern{ {`^composites: (\S+) composite literal uses unkeyed fields$`, "composites: `${1}` composite literal uses unkeyed fields"}, // gosec - {`^(\S+): Blacklisted import (\S+): weak cryptographic primitive$`, - "${1}: Blacklisted import `${2}`: weak cryptographic primitive"}, + { + `^(\S+): Blacklisted import (\S+): weak cryptographic primitive$`, + "${1}: Blacklisted import `${2}`: weak cryptographic primitive", + }, {`^TLS InsecureSkipVerify set true.$`, "TLS `InsecureSkipVerify` set true."}, // gosimple {`should replace loop with (.*)$`, "should replace loop with `${1}`"}, - {`should use a simple channel send/receive instead of select with a single case`, - "should use a simple channel send/receive instead of `select` with a single case"}, - {`should omit comparison to bool constant, can be simplified to (.+)$`, - "should omit comparison to bool constant, can be simplified to `${1}`"}, + { + `should use a simple channel send/receive instead of select with a single case`, + "should use a simple channel send/receive instead of `select` with a single case", + }, + { + `should omit comparison to bool constant, can be simplified to (.+)$`, + "should omit comparison to bool constant, can be simplified to `${1}`", + }, {`should write (.+) instead of (.+)$`, "should write `${1}` instead of `${2}`"}, {`redundant return statement$`, "redundant `return` statement"}, - {`should replace this if statement with an unconditional strings.TrimPrefix`, - "should replace this `if` statement with an unconditional `strings.TrimPrefix`"}, + { + `should replace this if statement with an unconditional strings.TrimPrefix`, + "should replace this `if` statement with an unconditional `strings.TrimPrefix`", + }, // staticcheck {`this value of (\S+) is never used$`, "this value of `${1}` is never used"}, - {`should use time.Since instead of time.Now\(\).Sub$`, - "should use `time.Since` instead of `time.Now().Sub`"}, - {`should check returned error before deferring response.Close\(\)$`, - "should check returned error before deferring `response.Close()`"}, + { + `should use time.Since instead of time.Now\(\).Sub$`, + "should use `time.Since` instead of `time.Now().Sub`", + }, + { + `should check returned error before deferring response.Close\(\)$`, + "should check returned error before deferring `response.Close()`", + }, {`no value of type uint is less than 0$`, "no value of type `uint` is less than `0`"}, // unused @@ -59,26 +73,40 @@ var replacePatterns = []replacePattern{ // typecheck {`^unknown field (\S+) in struct literal$`, "unknown field `${1}` in struct literal"}, - {`^invalid operation: (\S+) \(variable of type (\S+)\) has no field or method (\S+)$`, - "invalid operation: `${1}` (variable of type `${2}`) has no field or method `${3}`"}, + { + `^invalid operation: (\S+) \(variable of type (\S+)\) has no field or method (\S+)$`, + "invalid operation: `${1}` (variable of type `${2}`) has no field or method `${3}`", + }, {`^undeclared name: (\S+)$`, "undeclared name: `${1}`"}, - {`^cannot use addr \(variable of type (\S+)\) as (\S+) value in argument to (\S+)$`, - "cannot use addr (variable of type `${1}`) as `${2}` value in argument to `${3}`"}, + { + `^cannot use addr \(variable of type (\S+)\) as (\S+) value in argument to (\S+)$`, + "cannot use addr (variable of type `${1}`) as `${2}` value in argument to `${3}`", + }, {`^other declaration of (\S+)$`, "other declaration of `${1}`"}, {`^(\S+) redeclared in this block$`, "`${1}` redeclared in this block"}, // golint - {`^exported (type|method|function|var|const) (\S+) should have comment or be unexported$`, - "exported ${1} `${2}` should have comment or be unexported"}, - {`^comment on exported (type|method|function|var|const) (\S+) should be of the form "(\S+) ..."$`, - "comment on exported ${1} `${2}` should be of the form `${3} ...`"}, + { + `^exported (type|method|function|var|const) (\S+) should have comment or be unexported$`, + "exported ${1} `${2}` should have comment or be unexported", + }, + { + `^comment on exported (type|method|function|var|const) (\S+) should be of the form "(\S+) ..."$`, + "comment on exported ${1} `${2}` should be of the form `${3} ...`", + }, {`^should replace (.+) with (.+)$`, "should replace `${1}` with `${2}`"}, - {`^if block ends with a return statement, so drop this else and outdent its block$`, - "`if` block ends with a `return` statement, so drop this `else` and outdent its block"}, - {`^(struct field|var|range var|const|type|(?:func|method|interface method) (?:parameter|result)) (\S+) should be (\S+)$`, - "${1} `${2}` should be `${3}`"}, - {`^don't use underscores in Go names; var (\S+) should be (\S+)$`, - "don't use underscores in Go names; var `${1}` should be `${2}`"}, + { + `^if block ends with a return statement, so drop this else and outdent its block$`, + "`if` block ends with a `return` statement, so drop this `else` and outdent its block", + }, + { + `^(struct field|var|range var|const|type|(?:func|method|interface method) (?:parameter|result)) (\S+) should be (\S+)$`, + "${1} `${2}` should be `${3}`", + }, + { + `^don't use underscores in Go names; var (\S+) should be (\S+)$`, + "don't use underscores in Go names; var `${1}` should be `${2}`", + }, } type IdentifierMarker struct { @@ -100,16 +128,22 @@ func NewIdentifierMarker() *IdentifierMarker { } } -func (im IdentifierMarker) Process(issues []result.Issue) ([]result.Issue, error) { - return transformIssues(issues, func(i *result.Issue) *result.Issue { - iCopy := *i - iCopy.Text = im.markIdentifiers(iCopy.Text) - return &iCopy +func (IdentifierMarker) Name() string { + return "identifier_marker" +} + +func (p IdentifierMarker) Process(issues []result.Issue) ([]result.Issue, error) { + return transformIssues(issues, func(issue *result.Issue) *result.Issue { + newIssue := *issue + newIssue.Text = p.markIdentifiers(newIssue.Text) + return &newIssue }), nil } -func (im IdentifierMarker) markIdentifiers(s string) string { - for _, rr := range im.replaceRegexps { +func (IdentifierMarker) Finish() {} + +func (p IdentifierMarker) markIdentifiers(s string) string { + for _, rr := range p.replaceRegexps { rs := rr.re.ReplaceAllString(s, rr.repl) if rs != s { return rs @@ -118,8 +152,3 @@ func (im IdentifierMarker) markIdentifiers(s string) string { return s } - -func (im IdentifierMarker) Name() string { - return "identifier_marker" -} -func (im IdentifierMarker) Finish() {} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/invalid_issue.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/invalid_issue.go new file mode 100644 index 000000000..3f6cfc540 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/invalid_issue.go @@ -0,0 +1,60 @@ +package processors + +import ( + "path/filepath" + + "github.com/golangci/golangci-lint/pkg/logutils" + "github.com/golangci/golangci-lint/pkg/result" +) + +var _ Processor = (*InvalidIssue)(nil) + +type InvalidIssue struct { + log logutils.Log +} + +func NewInvalidIssue(log logutils.Log) *InvalidIssue { + return &InvalidIssue{log: log} +} + +func (InvalidIssue) Name() string { + return "invalid_issue" +} + +func (p InvalidIssue) Process(issues []result.Issue) ([]result.Issue, error) { + tcIssues := filterIssuesUnsafe(issues, func(issue *result.Issue) bool { + return issue.FromLinter == typeCheckName + }) + + if len(tcIssues) > 0 { + return tcIssues, nil + } + + return filterIssuesErr(issues, p.shouldPassIssue) +} + +func (InvalidIssue) Finish() {} + +func (p InvalidIssue) shouldPassIssue(issue *result.Issue) (bool, error) { + if issue.FilePath() == "" { + p.log.Warnf("no file path for the issue: probably a bug inside the linter %q: %#v", issue.FromLinter, issue) + + return false, nil + } + + if filepath.Base(issue.FilePath()) == "go.mod" { + return true, nil + } + + if !isGoFile(issue.FilePath()) { + p.log.Infof("issue related to file %s is skipped", issue.FilePath()) + + return false, nil + } + + return true, nil +} + +func isGoFile(name string) bool { + return filepath.Ext(name) == ".go" +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/issues.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/issues.go index 4691be38a..ab443b87d 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/issues.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/issues.go @@ -6,7 +6,24 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -func filterIssues(issues []result.Issue, filter func(i *result.Issue) bool) []result.Issue { +func filterIssues(issues []result.Issue, filter func(issue *result.Issue) bool) []result.Issue { + retIssues := make([]result.Issue, 0, len(issues)) + for i := range issues { + if issues[i].FromLinter == typeCheckName { + // don't hide typechecking errors in generated files: users expect to see why the project isn't compiling + retIssues = append(retIssues, issues[i]) + continue + } + + if filter(&issues[i]) { + retIssues = append(retIssues, issues[i]) + } + } + + return retIssues +} + +func filterIssuesUnsafe(issues []result.Issue, filter func(issue *result.Issue) bool) []result.Issue { retIssues := make([]result.Issue, 0, len(issues)) for i := range issues { if filter(&issues[i]) { @@ -17,9 +34,15 @@ func filterIssues(issues []result.Issue, filter func(i *result.Issue) bool) []re return retIssues } -func filterIssuesErr(issues []result.Issue, filter func(i *result.Issue) (bool, error)) ([]result.Issue, error) { +func filterIssuesErr(issues []result.Issue, filter func(issue *result.Issue) (bool, error)) ([]result.Issue, error) { retIssues := make([]result.Issue, 0, len(issues)) for i := range issues { + if issues[i].FromLinter == typeCheckName { + // don't hide typechecking errors in generated files: users expect to see why the project isn't compiling + retIssues = append(retIssues, issues[i]) + continue + } + ok, err := filter(&issues[i]) if err != nil { return nil, fmt.Errorf("can't filter issue %#v: %w", issues[i], err) @@ -33,12 +56,12 @@ func filterIssuesErr(issues []result.Issue, filter func(i *result.Issue) (bool, return retIssues, nil } -func transformIssues(issues []result.Issue, transform func(i *result.Issue) *result.Issue) []result.Issue { +func transformIssues(issues []result.Issue, transform func(issue *result.Issue) *result.Issue) []result.Issue { retIssues := make([]result.Issue, 0, len(issues)) for i := range issues { - newI := transform(&issues[i]) - if newI != nil { - retIssues = append(retIssues, *newI) + newIssue := transform(&issues[i]) + if newIssue != nil { + retIssues = append(retIssues, *newIssue) } } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_from_linter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_from_linter.go index 649ed86ae..0680c3f29 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_from_linter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_from_linter.go @@ -6,25 +6,25 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*MaxFromLinter)(nil) + type MaxFromLinter struct { - lc linterToCountMap - limit int - log logutils.Log - cfg *config.Config + linterCounter map[string]int + limit int + log logutils.Log + cfg *config.Config } -var _ Processor = &MaxFromLinter{} - func NewMaxFromLinter(limit int, log logutils.Log, cfg *config.Config) *MaxFromLinter { return &MaxFromLinter{ - lc: linterToCountMap{}, - limit: limit, - log: log, - cfg: cfg, + linterCounter: map[string]int{}, + limit: limit, + log: log, + cfg: cfg, } } -func (p *MaxFromLinter) Name() string { +func (*MaxFromLinter) Name() string { return "max_from_linter" } @@ -33,19 +33,20 @@ func (p *MaxFromLinter) Process(issues []result.Issue) ([]result.Issue, error) { return issues, nil } - return filterIssues(issues, func(i *result.Issue) bool { - if i.Replacement != nil && p.cfg.Issues.NeedFix { + return filterIssuesUnsafe(issues, func(issue *result.Issue) bool { + if issue.Replacement != nil && p.cfg.Issues.NeedFix { // we need to fix all issues at once => we need to return all of them return true } - p.lc[i.FromLinter]++ // always inc for stat - return p.lc[i.FromLinter] <= p.limit + p.linterCounter[issue.FromLinter]++ // always inc for stat + + return p.linterCounter[issue.FromLinter] <= p.limit }), nil } func (p *MaxFromLinter) Finish() { - walkStringToIntMapSortedByValue(p.lc, func(linter string, count int) { + walkStringToIntMapSortedByValue(p.linterCounter, func(linter string, count int) { if count > p.limit { p.log.Infof("%d/%d issues from linter %s were hidden, use --max-issues-per-linter", count-p.limit, count, linter) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_per_file_from_linter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_per_file_from_linter.go index 64182e3e2..a39c98473 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_per_file_from_linter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_per_file_from_linter.go @@ -5,16 +5,13 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -type linterToCountMap map[string]int -type fileToLinterToCountMap map[string]linterToCountMap +var _ Processor = (*MaxPerFileFromLinter)(nil) type MaxPerFileFromLinter struct { - flc fileToLinterToCountMap + fileLinterCounter fileLinterCounter maxPerFileFromLinterConfig map[string]int } -var _ Processor = &MaxPerFileFromLinter{} - func NewMaxPerFileFromLinter(cfg *config.Config) *MaxPerFileFromLinter { maxPerFileFromLinterConfig := map[string]int{} @@ -26,34 +23,51 @@ func NewMaxPerFileFromLinter(cfg *config.Config) *MaxPerFileFromLinter { } return &MaxPerFileFromLinter{ - flc: fileToLinterToCountMap{}, + fileLinterCounter: fileLinterCounter{}, maxPerFileFromLinterConfig: maxPerFileFromLinterConfig, } } -func (p *MaxPerFileFromLinter) Name() string { +func (*MaxPerFileFromLinter) Name() string { return "max_per_file_from_linter" } func (p *MaxPerFileFromLinter) Process(issues []result.Issue) ([]result.Issue, error) { - return filterIssues(issues, func(i *result.Issue) bool { - limit := p.maxPerFileFromLinterConfig[i.FromLinter] + return filterIssuesUnsafe(issues, func(issue *result.Issue) bool { + limit := p.maxPerFileFromLinterConfig[issue.FromLinter] if limit == 0 { return true } - lm := p.flc[i.FilePath()] - if lm == nil { - p.flc[i.FilePath()] = linterToCountMap{} - } - count := p.flc[i.FilePath()][i.FromLinter] - if count >= limit { + if p.fileLinterCounter.GetCount(issue) >= limit { return false } - p.flc[i.FilePath()][i.FromLinter]++ + p.fileLinterCounter.Increment(issue) + return true }), nil } -func (p *MaxPerFileFromLinter) Finish() {} +func (*MaxPerFileFromLinter) Finish() {} + +type fileLinterCounter map[string]map[string]int + +func (f fileLinterCounter) GetCount(issue *result.Issue) int { + return f.getCounter(issue)[issue.FromLinter] +} + +func (f fileLinterCounter) Increment(issue *result.Issue) { + f.getCounter(issue)[issue.FromLinter]++ +} + +func (f fileLinterCounter) getCounter(issue *result.Issue) map[string]int { + lc := f[issue.FilePath()] + + if lc == nil { + lc = map[string]int{} + f[issue.FilePath()] = lc + } + + return lc +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_same_issues.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_same_issues.go index 391ae5fa7..1647cace0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_same_issues.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/max_same_issues.go @@ -8,27 +8,25 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -type textToCountMap map[string]int +var _ Processor = (*MaxSameIssues)(nil) type MaxSameIssues struct { - tc textToCountMap - limit int - log logutils.Log - cfg *config.Config + textCounter map[string]int + limit int + log logutils.Log + cfg *config.Config } -var _ Processor = &MaxSameIssues{} - func NewMaxSameIssues(limit int, log logutils.Log, cfg *config.Config) *MaxSameIssues { return &MaxSameIssues{ - tc: textToCountMap{}, - limit: limit, - log: log, - cfg: cfg, + textCounter: map[string]int{}, + limit: limit, + log: log, + cfg: cfg, } } -func (p *MaxSameIssues) Name() string { +func (*MaxSameIssues) Name() string { return "max_same_issues" } @@ -37,19 +35,19 @@ func (p *MaxSameIssues) Process(issues []result.Issue) ([]result.Issue, error) { return issues, nil } - return filterIssues(issues, func(i *result.Issue) bool { - if i.Replacement != nil && p.cfg.Issues.NeedFix { + return filterIssuesUnsafe(issues, func(issue *result.Issue) bool { + if issue.Replacement != nil && p.cfg.Issues.NeedFix { // we need to fix all issues at once => we need to return all of them return true } - p.tc[i.Text]++ // always inc for stat - return p.tc[i.Text] <= p.limit + p.textCounter[issue.Text]++ // always inc for stat + return p.textCounter[issue.Text] <= p.limit }), nil } func (p *MaxSameIssues) Finish() { - walkStringToIntMapSortedByValue(p.tc, func(text string, count int) { + walkStringToIntMapSortedByValue(p.textCounter, func(text string, count int) { if count > p.limit { p.log.Infof("%d/%d issues with text %q were hidden, use --max-same-issues", count-p.limit, count, text) diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go index 181d3bf1f..7794bd3ec 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go @@ -1,7 +1,6 @@ package processors import ( - "errors" "go/ast" "go/parser" "go/token" @@ -9,15 +8,18 @@ import ( "sort" "strings" - "github.com/golangci/golangci-lint/pkg/golinters" + "golang.org/x/exp/maps" + + "github.com/golangci/golangci-lint/pkg/golinters/nolintlint" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/lintersdb" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*Nolint)(nil) + var nolintDebugf = logutils.Debug(logutils.DebugKeyNolint) -var nolintRe = regexp.MustCompile(`^nolint( |:|$)`) type ignoredRange struct { linters []string @@ -33,7 +35,7 @@ func (i *ignoredRange) doesMatch(issue *result.Issue) bool { } // only allow selective nolinting of nolintlint - nolintFoundForLinter := len(i.linters) == 0 && issue.FromLinter != golinters.NoLintLintName + nolintFoundForLinter := len(i.linters) == 0 && issue.FromLinter != nolintlint.LinterName for _, linterName := range i.linters { if linterName == issue.FromLinter { @@ -48,7 +50,7 @@ func (i *ignoredRange) doesMatch(issue *result.Issue) bool { // handle possible unused nolint directives // nolintlint generates potential issues for every nolint directive, and they are filtered out here - if issue.FromLinter == golinters.NoLintLintName && issue.ExpectNoLint { + if issue.FromLinter == nolintlint.LinterName && issue.ExpectNoLint { if issue.ExpectedNoLintLinter != "" { return i.matchedIssueFromLinter[issue.ExpectedNoLintLinter] } @@ -62,30 +64,29 @@ type fileData struct { ignoredRanges []ignoredRange } -type filesCache map[string]*fileData - type Nolint struct { - cache filesCache + fileCache map[string]*fileData dbManager *lintersdb.Manager enabledLinters map[string]*linter.Config log logutils.Log unknownLintersSet map[string]bool + + pattern *regexp.Regexp } func NewNolint(log logutils.Log, dbManager *lintersdb.Manager, enabledLinters map[string]*linter.Config) *Nolint { return &Nolint{ - cache: filesCache{}, + fileCache: map[string]*fileData{}, dbManager: dbManager, enabledLinters: enabledLinters, log: log, unknownLintersSet: map[string]bool{}, + pattern: regexp.MustCompile(`^nolint( |:|$)`), } } -var _ Processor = &Nolint{} - -func (p *Nolint) Name() string { +func (*Nolint) Name() string { return "nolint" } @@ -95,33 +96,77 @@ func (p *Nolint) Process(issues []result.Issue) ([]result.Issue, error) { return filterIssuesErr(issues, p.shouldPassIssue) } -func (p *Nolint) getOrCreateFileData(i *result.Issue) (*fileData, error) { - fd := p.cache[i.FilePath()] - if fd != nil { - return fd, nil +func (p *Nolint) Finish() { + if len(p.unknownLintersSet) == 0 { + return } - fd = &fileData{} - p.cache[i.FilePath()] = fd + unknownLinters := maps.Keys(p.unknownLintersSet) + sort.Strings(unknownLinters) + + p.log.Warnf("Found unknown linters in //nolint directives: %s", strings.Join(unknownLinters, ", ")) +} + +func (p *Nolint) shouldPassIssue(issue *result.Issue) (bool, error) { + nolintDebugf("got issue: %v", *issue) + + // don't expect disabled linters to cover their nolint statements + if issue.FromLinter == nolintlint.LinterName && issue.ExpectNoLint && issue.ExpectedNoLintLinter != "" { + nolintDebugf("enabled linters: %v", p.enabledLinters) + + if p.enabledLinters[issue.ExpectedNoLintLinter] == nil { + return false, nil + } + + nolintDebugf("checking that lint issue was used for %s: %v", issue.ExpectedNoLintLinter, issue) + } + + fd := p.getOrCreateFileData(issue) + + for _, ir := range fd.ignoredRanges { + if !ir.doesMatch(issue) { + continue + } + + nolintDebugf("found ignored range for issue %v: %v", issue, ir) + + ir.matchedIssueFromLinter[issue.FromLinter] = true + + if ir.originalRange != nil { + ir.originalRange.matchedIssueFromLinter[issue.FromLinter] = true + } + + return false, nil + } + + return true, nil +} - if i.FilePath() == "" { - return nil, errors.New("no file path for issue") +func (p *Nolint) getOrCreateFileData(issue *result.Issue) *fileData { + fd := p.fileCache[issue.FilePath()] + if fd != nil { + return fd } + fd = &fileData{} + p.fileCache[issue.FilePath()] = fd + // TODO: migrate this parsing to go/analysis facts // or cache them somehow per file. // Don't use cached AST because they consume a lot of memory on large projects. fset := token.NewFileSet() - f, err := parser.ParseFile(fset, i.FilePath(), nil, parser.ParseComments) + f, err := parser.ParseFile(fset, issue.FilePath(), nil, parser.ParseComments) if err != nil { // Don't report error because it's already must be reporter by typecheck or go/analysis. - return fd, nil + return fd } - fd.ignoredRanges = p.buildIgnoredRangesForFile(f, fset, i.FilePath()) - nolintDebugf("file %s: built nolint ranges are %+v", i.FilePath(), fd.ignoredRanges) - return fd, nil + fd.ignoredRanges = p.buildIgnoredRangesForFile(f, fset, issue.FilePath()) + + nolintDebugf("file %s: built nolint ranges are %+v", issue.FilePath(), fd.ignoredRanges) + + return fd } func (p *Nolint) buildIgnoredRangesForFile(f *ast.File, fset *token.FileSet, filePath string) []ignoredRange { @@ -146,79 +191,6 @@ func (p *Nolint) buildIgnoredRangesForFile(f *ast.File, fset *token.FileSet, fil return allRanges } -func (p *Nolint) shouldPassIssue(i *result.Issue) (bool, error) { - nolintDebugf("got issue: %v", *i) - if i.FromLinter == golinters.NoLintLintName && i.ExpectNoLint && i.ExpectedNoLintLinter != "" { - // don't expect disabled linters to cover their nolint statements - nolintDebugf("enabled linters: %v", p.enabledLinters) - if p.enabledLinters[i.ExpectedNoLintLinter] == nil { - return false, nil - } - nolintDebugf("checking that lint issue was used for %s: %v", i.ExpectedNoLintLinter, i) - } - - fd, err := p.getOrCreateFileData(i) - if err != nil { - return false, err - } - - for _, ir := range fd.ignoredRanges { - if ir.doesMatch(i) { - nolintDebugf("found ignored range for issue %v: %v", i, ir) - ir.matchedIssueFromLinter[i.FromLinter] = true - if ir.originalRange != nil { - ir.originalRange.matchedIssueFromLinter[i.FromLinter] = true - } - return false, nil - } - } - - return true, nil -} - -type rangeExpander struct { - fset *token.FileSet - inlineRanges []ignoredRange - expandedRanges []ignoredRange -} - -func (e *rangeExpander) Visit(node ast.Node) ast.Visitor { - if node == nil { - return e - } - - nodeStartPos := e.fset.Position(node.Pos()) - nodeStartLine := nodeStartPos.Line - nodeEndLine := e.fset.Position(node.End()).Line - - var foundRange *ignoredRange - for _, r := range e.inlineRanges { - if r.To == nodeStartLine-1 && nodeStartPos.Column == r.col { - r := r - foundRange = &r - break - } - } - if foundRange == nil { - return e - } - - expandedRange := *foundRange - // store the original unexpanded range for matching nolintlint issues - if expandedRange.originalRange == nil { - expandedRange.originalRange = foundRange - } - if expandedRange.To < nodeEndLine { - expandedRange.To = nodeEndLine - } - - nolintDebugf("found range is %v for node %#v [%d;%d], expanded range is %v", - *foundRange, node, nodeStartLine, nodeEndLine, expandedRange) - e.expandedRanges = append(e.expandedRanges, expandedRange) - - return e -} - func (p *Nolint) extractFileCommentsInlineRanges(fset *token.FileSet, comments ...*ast.CommentGroup) []ignoredRange { var ret []ignoredRange for _, g := range comments { @@ -235,7 +207,7 @@ func (p *Nolint) extractFileCommentsInlineRanges(fset *token.FileSet, comments . func (p *Nolint) extractInlineRangeFromComment(text string, g ast.Node, fset *token.FileSet) *ignoredRange { text = strings.TrimLeft(text, "/ ") - if !nolintRe.MatchString(text) { + if !p.pattern.MatchString(text) { return nil } @@ -284,18 +256,47 @@ func (p *Nolint) extractInlineRangeFromComment(text string, g ast.Node, fset *to return buildRange(linters) } -func (p *Nolint) Finish() { - if len(p.unknownLintersSet) == 0 { - return +type rangeExpander struct { + fset *token.FileSet + inlineRanges []ignoredRange + expandedRanges []ignoredRange +} + +func (e *rangeExpander) Visit(node ast.Node) ast.Visitor { + if node == nil { + return e } - unknownLinters := make([]string, 0, len(p.unknownLintersSet)) - for name := range p.unknownLintersSet { - unknownLinters = append(unknownLinters, name) + nodeStartPos := e.fset.Position(node.Pos()) + nodeStartLine := nodeStartPos.Line + nodeEndLine := e.fset.Position(node.End()).Line + + var foundRange *ignoredRange + for _, r := range e.inlineRanges { + if r.To == nodeStartLine-1 && nodeStartPos.Column == r.col { + r := r + foundRange = &r + break + } + } + if foundRange == nil { + return e } - sort.Strings(unknownLinters) - p.log.Warnf("Found unknown linters in //nolint directives: %s", strings.Join(unknownLinters, ", ")) + expandedRange := *foundRange + // store the original unexpanded range for matching nolintlint issues + if expandedRange.originalRange == nil { + expandedRange.originalRange = foundRange + } + if expandedRange.To < nodeEndLine { + expandedRange.To = nodeEndLine + } + + nolintDebugf("found range is %v for node %#v [%d;%d], expanded range is %v", + *foundRange, node, nodeStartLine, nodeEndLine, expandedRange) + e.expandedRanges = append(e.expandedRanges, expandedRange) + + return e } // put nolintlint last @@ -306,7 +307,7 @@ func (issues sortWithNolintlintLast) Len() int { } func (issues sortWithNolintlintLast) Less(i, j int) bool { - return issues[i].FromLinter != golinters.NoLintLintName && issues[j].FromLinter == golinters.NoLintLintName + return issues[i].FromLinter != nolintlint.LinterName && issues[j].FromLinter == nolintlint.LinterName } func (issues sortWithNolintlintLast) Swap(i, j int) { diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prefixer.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prefixer.go index f6b885011..8036e3fd6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prefixer.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prefixer.go @@ -5,13 +5,13 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*PathPrefixer)(nil) + // PathPrefixer adds a customizable prefix to every output path type PathPrefixer struct { prefix string } -var _ Processor = new(PathPrefixer) - // NewPathPrefixer returns a new path prefixer for the provided string func NewPathPrefixer(prefix string) *PathPrefixer { return &PathPrefixer{prefix: prefix} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prettifier.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prettifier.go index 3a140999c..c5c27357c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prettifier.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prettifier.go @@ -1,48 +1,40 @@ package processors import ( - "fmt" "path/filepath" "github.com/golangci/golangci-lint/pkg/fsutils" "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*PathPrettifier)(nil) + type PathPrettifier struct { - root string } -var _ Processor = PathPrettifier{} - func NewPathPrettifier() *PathPrettifier { - root, err := fsutils.Getwd() - if err != nil { - panic(fmt.Sprintf("Can't get working dir: %s", err)) - } - return &PathPrettifier{ - root: root, - } + return &PathPrettifier{} } -func (p PathPrettifier) Name() string { +func (PathPrettifier) Name() string { return "path_prettifier" } -func (p PathPrettifier) Process(issues []result.Issue) ([]result.Issue, error) { - return transformIssues(issues, func(i *result.Issue) *result.Issue { - if !filepath.IsAbs(i.FilePath()) { - return i +func (PathPrettifier) Process(issues []result.Issue) ([]result.Issue, error) { + return transformIssues(issues, func(issue *result.Issue) *result.Issue { + if !filepath.IsAbs(issue.FilePath()) { + return issue } - rel, err := fsutils.ShortestRelPath(i.FilePath(), "") + rel, err := fsutils.ShortestRelPath(issue.FilePath(), "") if err != nil { - return i + return issue } - newI := i - newI.Pos.Filename = rel - return newI + newIssue := issue + newIssue.Pos.Filename = rel + return newIssue }), nil } -func (p PathPrettifier) Finish() {} +func (PathPrettifier) Finish() {} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_shortener.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_shortener.go index 6b66bea8b..b161e86c2 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_shortener.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_shortener.go @@ -8,33 +8,32 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*PathShortener)(nil) + type PathShortener struct { wd string } -var _ Processor = PathShortener{} - func NewPathShortener() *PathShortener { wd, err := fsutils.Getwd() if err != nil { panic(fmt.Sprintf("Can't get working dir: %s", err)) } - return &PathShortener{ - wd: wd, - } + + return &PathShortener{wd: wd} } -func (p PathShortener) Name() string { +func (PathShortener) Name() string { return "path_shortener" } func (p PathShortener) Process(issues []result.Issue) ([]result.Issue, error) { - return transformIssues(issues, func(i *result.Issue) *result.Issue { - newI := i - newI.Text = strings.ReplaceAll(newI.Text, p.wd+"/", "") - newI.Text = strings.ReplaceAll(newI.Text, p.wd, "") - return newI + return transformIssues(issues, func(issue *result.Issue) *result.Issue { + newIssue := issue + newIssue.Text = strings.ReplaceAll(newIssue.Text, p.wd+"/", "") + newIssue.Text = strings.ReplaceAll(newIssue.Text, p.wd, "") + return newIssue }), nil } -func (p PathShortener) Finish() {} +func (PathShortener) Finish() {} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/processor.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/processor.go index 1a7a40434..13e63d604 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/processor.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/processor.go @@ -4,6 +4,8 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +const typeCheckName = "typecheck" + type Processor interface { Process(issues []result.Issue) ([]result.Issue, error) Name() string diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity.go new file mode 100644 index 000000000..93a26586d --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity.go @@ -0,0 +1,116 @@ +package processors + +import ( + "regexp" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/fsutils" + "github.com/golangci/golangci-lint/pkg/logutils" + "github.com/golangci/golangci-lint/pkg/result" +) + +const severityFromLinter = "@linter" + +var _ Processor = (*Severity)(nil) + +type severityRule struct { + baseRule + severity string +} + +type Severity struct { + name string + + log logutils.Log + + files *fsutils.Files + + defaultSeverity string + rules []severityRule +} + +func NewSeverity(log logutils.Log, files *fsutils.Files, cfg *config.Severity) *Severity { + p := &Severity{ + name: "severity-rules", + files: files, + log: log, + defaultSeverity: cfg.Default, + } + + prefix := caseInsensitivePrefix + if cfg.CaseSensitive { + prefix = "" + p.name = "severity-rules-case-sensitive" + } + + p.rules = createSeverityRules(cfg.Rules, prefix) + + return p +} + +func (p *Severity) Name() string { return p.name } + +func (p *Severity) Process(issues []result.Issue) ([]result.Issue, error) { + if len(p.rules) == 0 && p.defaultSeverity == "" { + return issues, nil + } + + return transformIssues(issues, p.transform), nil +} + +func (*Severity) Finish() {} + +func (p *Severity) transform(issue *result.Issue) *result.Issue { + for _, rule := range p.rules { + if rule.match(issue, p.files, p.log) { + if rule.severity == severityFromLinter || (rule.severity == "" && p.defaultSeverity == severityFromLinter) { + return issue + } + + issue.Severity = rule.severity + if issue.Severity == "" { + issue.Severity = p.defaultSeverity + } + + return issue + } + } + + if p.defaultSeverity != severityFromLinter { + issue.Severity = p.defaultSeverity + } + + return issue +} + +func createSeverityRules(rules []config.SeverityRule, prefix string) []severityRule { + parsedRules := make([]severityRule, 0, len(rules)) + + for _, rule := range rules { + parsedRule := severityRule{} + parsedRule.linters = rule.Linters + parsedRule.severity = rule.Severity + + if rule.Text != "" { + parsedRule.text = regexp.MustCompile(prefix + rule.Text) + } + + if rule.Source != "" { + parsedRule.source = regexp.MustCompile(prefix + rule.Source) + } + + if rule.Path != "" { + path := fsutils.NormalizePathInRegex(rule.Path) + parsedRule.path = regexp.MustCompile(path) + } + + if rule.PathExcept != "" { + pathExcept := fsutils.NormalizePathInRegex(rule.PathExcept) + parsedRule.pathExcept = regexp.MustCompile(pathExcept) + } + + parsedRules = append(parsedRules, parsedRule) + } + + return parsedRules +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity_rules.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity_rules.go deleted file mode 100644 index 0a4a643b7..000000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity_rules.go +++ /dev/null @@ -1,108 +0,0 @@ -package processors - -import ( - "regexp" - - "github.com/golangci/golangci-lint/pkg/fsutils" - "github.com/golangci/golangci-lint/pkg/logutils" - "github.com/golangci/golangci-lint/pkg/result" -) - -type severityRule struct { - baseRule - severity string -} - -type SeverityRule struct { - BaseRule - Severity string -} - -type SeverityRules struct { - defaultSeverity string - rules []severityRule - files *fsutils.Files - log logutils.Log -} - -func NewSeverityRules(defaultSeverity string, rules []SeverityRule, files *fsutils.Files, log logutils.Log) *SeverityRules { - r := &SeverityRules{ - files: files, - log: log, - defaultSeverity: defaultSeverity, - } - r.rules = createSeverityRules(rules, "(?i)") - - return r -} - -func createSeverityRules(rules []SeverityRule, prefix string) []severityRule { - parsedRules := make([]severityRule, 0, len(rules)) - for _, rule := range rules { - parsedRule := severityRule{} - parsedRule.linters = rule.Linters - parsedRule.severity = rule.Severity - if rule.Text != "" { - parsedRule.text = regexp.MustCompile(prefix + rule.Text) - } - if rule.Source != "" { - parsedRule.source = regexp.MustCompile(prefix + rule.Source) - } - if rule.Path != "" { - path := fsutils.NormalizePathInRegex(rule.Path) - parsedRule.path = regexp.MustCompile(path) - } - if rule.PathExcept != "" { - pathExcept := fsutils.NormalizePathInRegex(rule.PathExcept) - parsedRule.pathExcept = regexp.MustCompile(pathExcept) - } - parsedRules = append(parsedRules, parsedRule) - } - return parsedRules -} - -func (p SeverityRules) Process(issues []result.Issue) ([]result.Issue, error) { - if len(p.rules) == 0 && p.defaultSeverity == "" { - return issues, nil - } - return transformIssues(issues, func(i *result.Issue) *result.Issue { - for _, rule := range p.rules { - rule := rule - - ruleSeverity := p.defaultSeverity - if rule.severity != "" { - ruleSeverity = rule.severity - } - - if rule.match(i, p.files, p.log) { - i.Severity = ruleSeverity - return i - } - } - i.Severity = p.defaultSeverity - return i - }), nil -} - -func (SeverityRules) Name() string { return "severity-rules" } -func (SeverityRules) Finish() {} - -var _ Processor = SeverityRules{} - -type SeverityRulesCaseSensitive struct { - *SeverityRules -} - -func NewSeverityRulesCaseSensitive(defaultSeverity string, rules []SeverityRule, - files *fsutils.Files, log logutils.Log) *SeverityRulesCaseSensitive { - r := &SeverityRules{ - files: files, - log: log, - defaultSeverity: defaultSeverity, - } - r.rules = createSeverityRules(rules, "") - - return &SeverityRulesCaseSensitive{r} -} - -func (SeverityRulesCaseSensitive) Name() string { return "severity-rules-case-sensitive" } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go index e71495fd0..39dbfd1d3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go @@ -4,13 +4,23 @@ import ( "fmt" "path/filepath" "regexp" - "strings" "github.com/golangci/golangci-lint/pkg/fsutils" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*SkipDirs)(nil) + +var StdExcludeDirRegexps = []string{ + normalizePathRegex("vendor"), + normalizePathRegex("third_party"), + normalizePathRegex("testdata"), + normalizePathRegex("examples"), + normalizePathRegex("Godeps"), + normalizePathRegex("builtin"), +} + type skipStat struct { pattern string count int @@ -25,11 +35,7 @@ type SkipDirs struct { pathPrefix string } -var _ Processor = (*SkipDirs)(nil) - -const goFileSuffix = ".go" - -func NewSkipDirs(patterns []string, log logutils.Log, runArgs []string, pathPrefix string) (*SkipDirs, error) { +func NewSkipDirs(log logutils.Log, patterns, args []string, pathPrefix string) (*SkipDirs, error) { var patternsRe []*regexp.Regexp for _, p := range patterns { p = fsutils.NormalizePathInRegex(p) @@ -40,21 +46,9 @@ func NewSkipDirs(patterns []string, log logutils.Log, runArgs []string, pathPref patternsRe = append(patternsRe, patternRe) } - if len(runArgs) == 0 { - runArgs = append(runArgs, "./...") - } - var absArgsDirs []string - for _, arg := range runArgs { - base := filepath.Base(arg) - if base == "..." || strings.HasSuffix(base, goFileSuffix) { - arg = filepath.Dir(arg) - } - - absArg, err := filepath.Abs(arg) - if err != nil { - return nil, fmt.Errorf("failed to abs-ify arg %q: %w", arg, err) - } - absArgsDirs = append(absArgsDirs, absArg) + absArgsDirs, err := absDirs(args) + if err != nil { + return nil, err } return &SkipDirs{ @@ -67,7 +61,7 @@ func NewSkipDirs(patterns []string, log logutils.Log, runArgs []string, pathPref }, nil } -func (p *SkipDirs) Name() string { +func (*SkipDirs) Name() string { return "skip_dirs" } @@ -79,15 +73,21 @@ func (p *SkipDirs) Process(issues []result.Issue) ([]result.Issue, error) { return filterIssues(issues, p.shouldPassIssue), nil } -func (p *SkipDirs) shouldPassIssue(i *result.Issue) bool { - if filepath.IsAbs(i.FilePath()) { - if !isSpecialAutogeneratedFile(i.FilePath()) { - p.log.Warnf("Got abs path %s in skip dirs processor, it should be relative", i.FilePath()) +func (p *SkipDirs) Finish() { + for dir, stat := range p.skippedDirs { + p.log.Infof("Skipped %d issues from dir %s by pattern %s", stat.count, dir, stat.pattern) + } +} + +func (p *SkipDirs) shouldPassIssue(issue *result.Issue) bool { + if filepath.IsAbs(issue.FilePath()) { + if isGoFile(issue.FilePath()) { + p.log.Warnf("Got abs path %s in skip dirs processor, it should be relative", issue.FilePath()) } return true } - issueRelDir := filepath.Dir(i.FilePath()) + issueRelDir := filepath.Dir(issue.FilePath()) if toPass, ok := p.skippedDirsCache[issueRelDir]; ok { if !toPass { @@ -139,8 +139,34 @@ func (p *SkipDirs) shouldPassIssueDirs(issueRelDir, issueAbsDir string) bool { return true } -func (p *SkipDirs) Finish() { - for dir, stat := range p.skippedDirs { - p.log.Infof("Skipped %d issues from dir %s by pattern %s", stat.count, dir, stat.pattern) +func absDirs(args []string) ([]string, error) { + if len(args) == 0 { + args = append(args, "./...") } + + var absArgsDirs []string + for _, arg := range args { + base := filepath.Base(arg) + if base == "..." || isGoFile(base) { + arg = filepath.Dir(arg) + } + + absArg, err := filepath.Abs(arg) + if err != nil { + return nil, fmt.Errorf("failed to abs-ify arg %q: %w", arg, err) + } + + absArgsDirs = append(absArgsDirs, absArg) + } + + return absArgsDirs, nil +} + +func normalizePathRegex(e string) string { + return createPathRegex(e, filepath.Separator) +} + +func createPathRegex(e string, sep rune) string { + escapedSep := regexp.QuoteMeta(string(sep)) // needed for windows sep '\\' + return fmt.Sprintf(`(^|%[1]s)%[2]s($|%[1]s)`, escapedSep, e) } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go index 9579bee84..3b17a9f32 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go @@ -8,21 +8,23 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*SkipFiles)(nil) + type SkipFiles struct { patterns []*regexp.Regexp pathPrefix string } -var _ Processor = (*SkipFiles)(nil) - func NewSkipFiles(patterns []string, pathPrefix string) (*SkipFiles, error) { var patternsRe []*regexp.Regexp for _, p := range patterns { p = fsutils.NormalizePathInRegex(p) + patternRe, err := regexp.Compile(p) if err != nil { - return nil, fmt.Errorf("can't compile regexp %q: %s", p, err) + return nil, fmt.Errorf("can't compile regexp %q: %w", p, err) } + patternsRe = append(patternsRe, patternRe) } @@ -32,7 +34,7 @@ func NewSkipFiles(patterns []string, pathPrefix string) (*SkipFiles, error) { }, nil } -func (p SkipFiles) Name() string { +func (SkipFiles) Name() string { return "skip_files" } @@ -41,8 +43,9 @@ func (p SkipFiles) Process(issues []result.Issue) ([]result.Issue, error) { return issues, nil } - return filterIssues(issues, func(i *result.Issue) bool { - path := fsutils.WithPathPrefix(p.pathPrefix, i.FilePath()) + return filterIssues(issues, func(issue *result.Issue) bool { + path := fsutils.WithPathPrefix(p.pathPrefix, issue.FilePath()) + for _, pattern := range p.patterns { if pattern.MatchString(path) { return false @@ -53,4 +56,4 @@ func (p SkipFiles) Process(issues []result.Issue) ([]result.Issue, error) { }), nil } -func (p SkipFiles) Finish() {} +func (SkipFiles) Finish() {} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/sort_results.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/sort_results.go index 740c4fa8c..77f58c03e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/sort_results.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/sort_results.go @@ -1,6 +1,9 @@ package processors import ( + "errors" + "fmt" + "slices" "sort" "strings" @@ -13,89 +16,124 @@ import ( // by sorting results.Issues using processor step, and chain based // rules that can compare different properties of the Issues struct. +const ( + orderNameFile = "file" + orderNameLinter = "linter" + orderNameSeverity = "severity" +) + var _ Processor = (*SortResults)(nil) type SortResults struct { - cmp comparator - cfg *config.Config + cmps map[string]*comparator + + cfg *config.Output } func NewSortResults(cfg *config.Config) *SortResults { - // For sorting we are comparing (in next order): file names, line numbers, - // position, and finally - giving up. return &SortResults{ - cmp: ByName{ - next: ByLine{ - next: ByColumn{}, - }, + cmps: map[string]*comparator{ + // For sorting we are comparing (in next order): + // file names, line numbers, position, and finally - giving up. + orderNameFile: byFileName().SetNext(byLine().SetNext(byColumn())), + // For sorting we are comparing: linter name + orderNameLinter: byLinter(), + // For sorting we are comparing: severity + orderNameSeverity: bySeverity(), }, - cfg: cfg, + cfg: &cfg.Output, } } +func (SortResults) Name() string { return "sort_results" } + // Process is performing sorting of the result issues. -func (sr SortResults) Process(issues []result.Issue) ([]result.Issue, error) { - if !sr.cfg.Output.SortResults { +func (p SortResults) Process(issues []result.Issue) ([]result.Issue, error) { + if !p.cfg.SortResults { return issues, nil } + if len(p.cfg.SortOrder) == 0 { + p.cfg.SortOrder = []string{orderNameFile} + } + + var cmps []*comparator + for _, name := range p.cfg.SortOrder { + c, ok := p.cmps[name] + if !ok { + return nil, fmt.Errorf("unsupported sort-order name %q", name) + } + + cmps = append(cmps, c) + } + + cmp, err := mergeComparators(cmps) + if err != nil { + return nil, err + } + sort.Slice(issues, func(i, j int) bool { - return sr.cmp.Compare(&issues[i], &issues[j]) == Less + return cmp.Compare(&issues[i], &issues[j]) == less }) return issues, nil } -func (sr SortResults) Name() string { return "sort_results" } -func (sr SortResults) Finish() {} +func (SortResults) Finish() {} type compareResult int const ( - Less compareResult = iota - 1 - Equal - Greater - None + less compareResult = iota - 1 + equal + greater + none ) func (c compareResult) isNeutral() bool { // return true if compare result is incomparable or equal. - return c == None || c == Equal + return c == none || c == equal } func (c compareResult) String() string { switch c { - case Less: - return "Less" - case Equal: - return "Equal" - case Greater: - return "Greater" + case less: + return "less" + case equal: + return "equal" + case greater: + return "greater" + default: + return "none" } - - return "None" } -// comparator describe how to implement compare for two "issues" lexicographically -type comparator interface { - Compare(a, b *result.Issue) compareResult - Next() comparator +// comparator describes how to implement compare for two "issues". +type comparator struct { + name string + compare func(a, b *result.Issue) compareResult + next *comparator } -var ( - _ comparator = (*ByName)(nil) - _ comparator = (*ByLine)(nil) - _ comparator = (*ByColumn)(nil) -) +func (cmp *comparator) Next() *comparator { return cmp.next } -type ByName struct{ next comparator } +func (cmp *comparator) SetNext(c *comparator) *comparator { + cmp.next = c + return cmp +} -func (cmp ByName) Next() comparator { return cmp.next } +func (cmp *comparator) String() string { + s := cmp.name + if cmp.Next() != nil { + s += " > " + cmp.Next().String() + } -func (cmp ByName) Compare(a, b *result.Issue) compareResult { - var res compareResult + return s +} - if res = compareResult(strings.Compare(a.FilePath(), b.FilePath())); !res.isNeutral() { +func (cmp *comparator) Compare(a, b *result.Issue) compareResult { + res := cmp.compare(a, b) + if !res.isNeutral() { return res } @@ -106,40 +144,95 @@ func (cmp ByName) Compare(a, b *result.Issue) compareResult { return res } -type ByLine struct{ next comparator } +func byFileName() *comparator { + return &comparator{ + name: "byFileName", + compare: func(a, b *result.Issue) compareResult { + return compareResult(strings.Compare(a.FilePath(), b.FilePath())) + }, + } +} -func (cmp ByLine) Next() comparator { return cmp.next } +func byLine() *comparator { + return &comparator{ + name: "byLine", + compare: func(a, b *result.Issue) compareResult { + return numericCompare(a.Line(), b.Line()) + }, + } +} -func (cmp ByLine) Compare(a, b *result.Issue) compareResult { - var res compareResult +func byColumn() *comparator { + return &comparator{ + name: "byColumn", + compare: func(a, b *result.Issue) compareResult { + return numericCompare(a.Column(), b.Column()) + }, + } +} - if res = numericCompare(a.Line(), b.Line()); !res.isNeutral() { - return res +func byLinter() *comparator { + return &comparator{ + name: "byLinter", + compare: func(a, b *result.Issue) compareResult { + return compareResult(strings.Compare(a.FromLinter, b.FromLinter)) + }, } +} - if next := cmp.Next(); next != nil { - return next.Compare(a, b) +func bySeverity() *comparator { + return &comparator{ + name: "bySeverity", + compare: func(a, b *result.Issue) compareResult { + return severityCompare(a.Severity, b.Severity) + }, } +} - return res +func mergeComparators(cmps []*comparator) (*comparator, error) { + if len(cmps) == 0 { + return nil, errors.New("no comparator") + } + + for i := 0; i < len(cmps)-1; i++ { + findComparatorTip(cmps[i]).SetNext(cmps[i+1]) + } + + return cmps[0], nil } -type ByColumn struct{ next comparator } +func findComparatorTip(cmp *comparator) *comparator { + if cmp.Next() != nil { + return findComparatorTip(cmp.Next()) + } -func (cmp ByColumn) Next() comparator { return cmp.next } + return cmp +} -func (cmp ByColumn) Compare(a, b *result.Issue) compareResult { - var res compareResult +func severityCompare(a, b string) compareResult { + // The position inside the slice define the importance (lower to higher). + classic := []string{"low", "medium", "high", "warning", "error"} + + if slices.Contains(classic, a) && slices.Contains(classic, b) { + switch { + case slices.Index(classic, a) > slices.Index(classic, b): + return greater + case slices.Index(classic, a) < slices.Index(classic, b): + return less + default: + return equal + } + } - if res = numericCompare(a.Column(), b.Column()); !res.isNeutral() { - return res + if slices.Contains(classic, a) { + return greater } - if next := cmp.Next(); next != nil { - return next.Compare(a, b) + if slices.Contains(classic, b) { + return less } - return res + return compareResult(strings.Compare(a, b)) } func numericCompare(a, b int) compareResult { @@ -153,14 +246,14 @@ func numericCompare(a, b int) compareResult { switch { case isZeroValuesBoth || isEqual: - return Equal + return equal case isValuesInvalid || isZeroValueInA || isZeroValueInB: - return None + return none case a > b: - return Greater + return greater case a < b: - return Less + return less } - return Equal + return equal } diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/source_code.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/source_code.go index cfd73cb98..4a89fc73e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/source_code.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/source_code.go @@ -6,13 +6,13 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +var _ Processor = (*SourceCode)(nil) + type SourceCode struct { lineCache *fsutils.LineCache log logutils.Log } -var _ Processor = SourceCode{} - func NewSourceCode(lc *fsutils.LineCache, log logutils.Log) *SourceCode { return &SourceCode{ lineCache: lc, @@ -20,28 +20,31 @@ func NewSourceCode(lc *fsutils.LineCache, log logutils.Log) *SourceCode { } } -func (p SourceCode) Name() string { +func (SourceCode) Name() string { return "source_code" } func (p SourceCode) Process(issues []result.Issue) ([]result.Issue, error) { - return transformIssues(issues, func(i *result.Issue) *result.Issue { - newI := *i - - lineRange := i.GetLineRange() - for lineNumber := lineRange.From; lineNumber <= lineRange.To; lineNumber++ { - line, err := p.lineCache.GetLine(i.FilePath(), lineNumber) - if err != nil { - p.log.Warnf("Failed to get line %d for file %s: %s", - lineNumber, i.FilePath(), err) - return i - } - - newI.SourceLines = append(newI.SourceLines, line) + return transformIssues(issues, p.transform), nil +} + +func (SourceCode) Finish() {} + +func (p SourceCode) transform(issue *result.Issue) *result.Issue { + newIssue := *issue + + lineRange := issue.GetLineRange() + for lineNumber := lineRange.From; lineNumber <= lineRange.To; lineNumber++ { + line, err := p.lineCache.GetLine(issue.FilePath(), lineNumber) + if err != nil { + p.log.Warnf("Failed to get line %d for file %s: %s", + lineNumber, issue.FilePath(), err) + + return issue } - return &newI - }), nil -} + newIssue.SourceLines = append(newIssue.SourceLines, line) + } -func (p SourceCode) Finish() {} + return &newIssue +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/uniq_by_line.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/uniq_by_line.go index dc0e1e8cf..115196d9a 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/uniq_by_line.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/uniq_by_line.go @@ -5,24 +5,23 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -type lineToCount map[int]int -type fileToLineToCount map[string]lineToCount +const uniqByLineLimit = 1 + +var _ Processor = (*UniqByLine)(nil) type UniqByLine struct { - flc fileToLineToCount - cfg *config.Config + fileLineCounter fileLineCounter + cfg *config.Config } func NewUniqByLine(cfg *config.Config) *UniqByLine { return &UniqByLine{ - flc: fileToLineToCount{}, - cfg: cfg, + fileLineCounter: fileLineCounter{}, + cfg: cfg, } } -var _ Processor = &UniqByLine{} - -func (p *UniqByLine) Name() string { +func (*UniqByLine) Name() string { return "uniq_by_line" } @@ -31,28 +30,44 @@ func (p *UniqByLine) Process(issues []result.Issue) ([]result.Issue, error) { return issues, nil } - return filterIssues(issues, func(i *result.Issue) bool { - if i.Replacement != nil && p.cfg.Issues.NeedFix { - // if issue will be auto-fixed we shouldn't collapse issues: - // e.g. one line can contain 2 misspellings, they will be in 2 issues and misspell should fix both of them. - return true - } - - lc := p.flc[i.FilePath()] - if lc == nil { - lc = lineToCount{} - p.flc[i.FilePath()] = lc - } - - const limit = 1 - count := lc[i.Line()] - if count == limit { - return false - } - - lc[i.Line()]++ + return filterIssuesUnsafe(issues, p.shouldPassIssue), nil +} + +func (*UniqByLine) Finish() {} + +func (p *UniqByLine) shouldPassIssue(issue *result.Issue) bool { + if issue.Replacement != nil && p.cfg.Issues.NeedFix { + // if issue will be auto-fixed we shouldn't collapse issues: + // e.g. one line can contain 2 misspellings, they will be in 2 issues and misspell should fix both of them. return true - }), nil + } + + if p.fileLineCounter.GetCount(issue) == uniqByLineLimit { + return false + } + + p.fileLineCounter.Increment(issue) + + return true } -func (p *UniqByLine) Finish() {} +type fileLineCounter map[string]map[int]int + +func (f fileLineCounter) GetCount(issue *result.Issue) int { + return f.getCounter(issue)[issue.Line()] +} + +func (f fileLineCounter) Increment(issue *result.Issue) { + f.getCounter(issue)[issue.Line()]++ +} + +func (f fileLineCounter) getCounter(issue *result.Issue) map[int]int { + lc := f[issue.FilePath()] + + if lc == nil { + lc = map[int]int{} + f[issue.FilePath()] = lc + } + + return lc +} diff --git a/tools/vendor/github.com/golangci/lint-1/.travis.yml b/tools/vendor/github.com/golangci/lint-1/.travis.yml deleted file mode 100644 index bc2f4b311..000000000 --- a/tools/vendor/github.com/golangci/lint-1/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -sudo: false -language: go -go: - - 1.10.x - - 1.11.x - - master - -go_import_path: github.com/golangci/lint-1 - -install: - - go get -t -v ./... - -script: - - go test -v -race ./... - -matrix: - allow_failures: - - go: master - fast_finish: true diff --git a/tools/vendor/github.com/golangci/lint-1/CONTRIBUTING.md b/tools/vendor/github.com/golangci/lint-1/CONTRIBUTING.md deleted file mode 100644 index 2e39a1c67..000000000 --- a/tools/vendor/github.com/golangci/lint-1/CONTRIBUTING.md +++ /dev/null @@ -1,15 +0,0 @@ -# Contributing to Golint - -## Before filing an issue: - -### Are you having trouble building golint? - -Check you have the latest version of its dependencies. Run -``` -go get -u github.com/golangci/lint-1/golint -``` -If you still have problems, consider searching for existing issues before filing a new issue. - -## Before sending a pull request: - -Have you understood the purpose of golint? Make sure to carefully read `README`. diff --git a/tools/vendor/github.com/golangci/lint-1/LICENSE b/tools/vendor/github.com/golangci/lint-1/LICENSE deleted file mode 100644 index 65d761bc9..000000000 --- a/tools/vendor/github.com/golangci/lint-1/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013 The Go 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: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/vendor/github.com/golangci/lint-1/README.md b/tools/vendor/github.com/golangci/lint-1/README.md deleted file mode 100644 index 2de6ee835..000000000 --- a/tools/vendor/github.com/golangci/lint-1/README.md +++ /dev/null @@ -1,88 +0,0 @@ -Golint is a linter for Go source code. - -[![Build Status](https://travis-ci.org/golang/lint.svg?branch=master)](https://travis-ci.org/golang/lint) - -## Installation - -Golint requires a -[supported release of Go](https://golang.org/doc/devel/release.html#policy). - - go get -u github.com/golangci/lint-1/golint - -To find out where `golint` was installed you can run `go list -f {{.Target}} github.com/golangci/lint-1/golint`. For `golint` to be used globally add that directory to the `$PATH` environment setting. - -## Usage - -Invoke `golint` with one or more filenames, directories, or packages named -by its import path. Golint uses the same -[import path syntax](https://golang.org/cmd/go/#hdr-Import_path_syntax) as -the `go` command and therefore -also supports relative import paths like `./...`. Additionally the `...` -wildcard can be used as suffix on relative and absolute file paths to recurse -into them. - -The output of this tool is a list of suggestions in Vim quickfix format, -which is accepted by lots of different editors. - -## Purpose - -Golint differs from gofmt. Gofmt reformats Go source code, whereas -golint prints out style mistakes. - -Golint differs from govet. Govet is concerned with correctness, whereas -golint is concerned with coding style. Golint is in use at Google, and it -seeks to match the accepted style of the open source Go project. - -The suggestions made by golint are exactly that: suggestions. -Golint is not perfect, and has both false positives and false negatives. -Do not treat its output as a gold standard. We will not be adding pragmas -or other knobs to suppress specific warnings, so do not expect or require -code to be completely "lint-free". -In short, this tool is not, and will never be, trustworthy enough for its -suggestions to be enforced automatically, for example as part of a build process. -Golint makes suggestions for many of the mechanically checkable items listed in -[Effective Go](https://golang.org/doc/effective_go.html) and the -[CodeReviewComments wiki page](https://golang.org/wiki/CodeReviewComments). - -## Scope - -Golint is meant to carry out the stylistic conventions put forth in -[Effective Go](https://golang.org/doc/effective_go.html) and -[CodeReviewComments](https://golang.org/wiki/CodeReviewComments). -Changes that are not aligned with those documents will not be considered. - -## Contributions - -Contributions to this project are welcome provided they are [in scope](#scope), -though please send mail before starting work on anything major. -Contributors retain their copyright, so we need you to fill out -[a short form](https://developers.google.com/open-source/cla/individual) -before we can accept your contribution. - -## Vim - -Add this to your ~/.vimrc: - - set rtp+=$GOPATH/src/github.com/golangci/lint-1/misc/vim - -If you have multiple entries in your GOPATH, replace `$GOPATH` with the right value. - -Running `:Lint` will run golint on the current file and populate the quickfix list. - -Optionally, add this to your `~/.vimrc` to automatically run `golint` on `:w` - - autocmd BufWritePost,FileWritePost *.go execute 'Lint' | cwindow - - -## Emacs - -Add this to your `.emacs` file: - - (add-to-list 'load-path (concat (getenv "GOPATH") "/src/github.com/golang/lint/misc/emacs")) - (require 'golint) - -If you have multiple entries in your GOPATH, replace `$GOPATH` with the right value. - -Running M-x golint will run golint on the current file. - -For more usage, see [Compilation-Mode](http://www.gnu.org/software/emacs/manual/html_node/emacs/Compilation-Mode.html). diff --git a/tools/vendor/github.com/golangci/lint-1/lint.go b/tools/vendor/github.com/golangci/lint-1/lint.go deleted file mode 100644 index 886c85bf0..000000000 --- a/tools/vendor/github.com/golangci/lint-1/lint.go +++ /dev/null @@ -1,1655 +0,0 @@ -// Copyright (c) 2013 The Go Authors. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file or at -// https://developers.google.com/open-source/licenses/bsd. - -// Package lint contains a linter for Go source code. -package lint // import "github.com/golangci/lint-1" - -import ( - "bufio" - "bytes" - "fmt" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "go/types" - "io/ioutil" - "regexp" - "sort" - "strconv" - "strings" - "unicode" - "unicode/utf8" - - "golang.org/x/tools/go/ast/astutil" - "golang.org/x/tools/go/gcexportdata" -) - -const styleGuideBase = "https://golang.org/wiki/CodeReviewComments" - -// A Linter lints Go source code. -type Linter struct { -} - -// Problem represents a problem in some source code. -type Problem struct { - Position token.Position // position in source file - Text string // the prose that describes the problem - Link string // (optional) the link to the style guide for the problem - Confidence float64 // a value in (0,1] estimating the confidence in this problem's correctness - LineText string // the source line - Category string // a short name for the general category of the problem - - // If the problem has a suggested fix (the minority case), - // ReplacementLine is a full replacement for the relevant line of the source file. - ReplacementLine string -} - -func (p *Problem) String() string { - if p.Link != "" { - return p.Text + "\n\n" + p.Link - } - return p.Text -} - -type byPosition []Problem - -func (p byPosition) Len() int { return len(p) } -func (p byPosition) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p byPosition) Less(i, j int) bool { - pi, pj := p[i].Position, p[j].Position - - if pi.Filename != pj.Filename { - return pi.Filename < pj.Filename - } - if pi.Line != pj.Line { - return pi.Line < pj.Line - } - if pi.Column != pj.Column { - return pi.Column < pj.Column - } - - return p[i].Text < p[j].Text -} - -// Lint lints src. -func (l *Linter) Lint(filename string, src []byte) ([]Problem, error) { - return l.LintFiles(map[string][]byte{filename: src}) -} - -// LintFiles lints a set of files of a single package. -// The argument is a map of filename to source. -func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error) { - pkg := &pkg{ - fset: token.NewFileSet(), - files: make(map[string]*file), - } - var pkgName string - for filename, src := range files { - if isGenerated(src) { - continue // See issue #239 - } - f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments) - if err != nil { - return nil, err - } - if pkgName == "" { - pkgName = f.Name.Name - } else if f.Name.Name != pkgName { - return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) - } - pkg.files[filename] = &file{ - pkg: pkg, - f: f, - fset: pkg.fset, - src: src, - filename: filename, - } - } - if len(pkg.files) == 0 { - return nil, nil - } - return pkg.lint(), nil -} - -// LintFiles lints a set of files of a single package. -// The argument is a map of filename to source. -func (l *Linter) LintPkg(files []*ast.File, fset *token.FileSet, typesPkg *types.Package, typesInfo *types.Info) ([]Problem, error) { - pkg := &pkg{ - fset: fset, - files: make(map[string]*file), - typesPkg: typesPkg, - typesInfo: typesInfo, - } - var pkgName string - for _, f := range files { - // use PositionFor, not Position because of //line directives: - // this filename will be used for source lines extraction. - filename := fset.PositionFor(f.Pos(), false).Filename - if filename == "" { - return nil, fmt.Errorf("no file name for file %+v", f) - } - - if pkgName == "" { - pkgName = f.Name.Name - } else if f.Name.Name != pkgName { - return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) - } - - // TODO: reuse golangci-lint lines cache - src, err := ioutil.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("can't read file %s: %s", filename, err) - } - - pkg.files[filename] = &file{ - pkg: pkg, - f: f, - fset: pkg.fset, - src: src, - filename: filename, - } - } - if len(pkg.files) == 0 { - return nil, nil - } - return pkg.lint(), nil -} - -var ( - genHdr = []byte("// Code generated ") - genFtr = []byte(" DO NOT EDIT.") -) - -// isGenerated reports whether the source file is generated code -// according the rules from https://golang.org/s/generatedcode. -func isGenerated(src []byte) bool { - sc := bufio.NewScanner(bytes.NewReader(src)) - for sc.Scan() { - b := sc.Bytes() - if bytes.HasPrefix(b, genHdr) && bytes.HasSuffix(b, genFtr) && len(b) >= len(genHdr)+len(genFtr) { - return true - } - } - return false -} - -// pkg represents a package being linted. -type pkg struct { - fset *token.FileSet - files map[string]*file - - typesPkg *types.Package - typesInfo *types.Info - - // sortable is the set of types in the package that implement sort.Interface. - sortable map[string]bool - // main is whether this is a "main" package. - main bool - - problems []Problem -} - -func (p *pkg) lint() []Problem { - p.scanSortable() - p.main = p.isMain() - - for _, f := range p.files { - f.lint() - } - - sort.Sort(byPosition(p.problems)) - - return p.problems -} - -// file represents a file being linted. -type file struct { - pkg *pkg - f *ast.File - fset *token.FileSet - src []byte - filename string -} - -func (f *file) isTest() bool { return strings.HasSuffix(f.filename, "_test.go") } - -func (f *file) lint() { - f.lintPackageComment() - f.lintImports() - f.lintBlankImports() - f.lintExported() - f.lintNames() - f.lintElses() - f.lintRanges() - f.lintErrorf() - f.lintErrors() - f.lintErrorStrings() - f.lintReceiverNames() - f.lintIncDec() - f.lintErrorReturn() - f.lintUnexportedReturn() - f.lintTimeNames() - f.lintContextKeyTypes() - f.lintContextArgs() -} - -type link string -type category string - -// The variadic arguments may start with link and category types, -// and must end with a format string and any arguments. -// It returns the new Problem. -func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem { - pos := f.fset.Position(n.Pos()) - if pos.Filename == "" { - pos.Filename = f.filename - } - return f.pkg.errorfAt(pos, confidence, args...) -} - -func (p *pkg) errorfAt(pos token.Position, confidence float64, args ...interface{}) *Problem { - problem := Problem{ - Position: pos, - Confidence: confidence, - } - if pos.Filename != "" { - // The file might not exist in our mapping if a //line directive was encountered. - if f, ok := p.files[pos.Filename]; ok { - problem.LineText = srcLine(f.src, pos) - } - } - -argLoop: - for len(args) > 1 { // always leave at least the format string in args - switch v := args[0].(type) { - case link: - problem.Link = string(v) - case category: - problem.Category = string(v) - default: - break argLoop - } - args = args[1:] - } - - problem.Text = fmt.Sprintf(args[0].(string), args[1:]...) - - p.problems = append(p.problems, problem) - return &p.problems[len(p.problems)-1] -} - -var newImporter = func(fset *token.FileSet) types.ImporterFrom { - return gcexportdata.NewImporter(fset, make(map[string]*types.Package)) -} - -func (p *pkg) typeCheck() error { - config := &types.Config{ - // By setting a no-op error reporter, the type checker does as much work as possible. - Error: func(error) {}, - Importer: newImporter(p.fset), - } - info := &types.Info{ - Types: make(map[ast.Expr]types.TypeAndValue), - Defs: make(map[*ast.Ident]types.Object), - Uses: make(map[*ast.Ident]types.Object), - Scopes: make(map[ast.Node]*types.Scope), - } - var anyFile *file - var astFiles []*ast.File - for _, f := range p.files { - anyFile = f - astFiles = append(astFiles, f.f) - } - pkg, err := config.Check(anyFile.f.Name.Name, p.fset, astFiles, info) - // Remember the typechecking info, even if config.Check failed, - // since we will get partial information. - p.typesPkg = pkg - p.typesInfo = info - return err -} - -func (p *pkg) typeOf(expr ast.Expr) types.Type { - if p.typesInfo == nil { - return nil - } - return p.typesInfo.TypeOf(expr) -} - -func (p *pkg) isNamedType(typ types.Type, importPath, name string) bool { - n, ok := typ.(*types.Named) - if !ok { - return false - } - tn := n.Obj() - return tn != nil && tn.Pkg() != nil && tn.Pkg().Path() == importPath && tn.Name() == name -} - -// scopeOf returns the tightest scope encompassing id. -func (p *pkg) scopeOf(id *ast.Ident) *types.Scope { - var scope *types.Scope - if obj := p.typesInfo.ObjectOf(id); obj != nil { - scope = obj.Parent() - } - if scope == p.typesPkg.Scope() { - // We were given a top-level identifier. - // Use the file-level scope instead of the package-level scope. - pos := id.Pos() - for _, f := range p.files { - if f.f.Pos() <= pos && pos < f.f.End() { - scope = p.typesInfo.Scopes[f.f] - break - } - } - } - return scope -} - -func (p *pkg) scanSortable() { - p.sortable = make(map[string]bool) - - // bitfield for which methods exist on each type. - const ( - Len = 1 << iota - Less - Swap - ) - nmap := map[string]int{"Len": Len, "Less": Less, "Swap": Swap} - has := make(map[string]int) - for _, f := range p.files { - f.walk(func(n ast.Node) bool { - fn, ok := n.(*ast.FuncDecl) - if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { - return true - } - // TODO(dsymonds): We could check the signature to be more precise. - recv := receiverType(fn) - if i, ok := nmap[fn.Name.Name]; ok { - has[recv] |= i - } - return false - }) - } - for typ, ms := range has { - if ms == Len|Less|Swap { - p.sortable[typ] = true - } - } -} - -func (p *pkg) isMain() bool { - for _, f := range p.files { - if f.isMain() { - return true - } - } - return false -} - -func (f *file) isMain() bool { - if f.f.Name.Name == "main" { - return true - } - return false -} - -// lintPackageComment checks package comments. It complains if -// there is no package comment, or if it is not of the right form. -// This has a notable false positive in that a package comment -// could rightfully appear in a different file of the same package, -// but that's not easy to fix since this linter is file-oriented. -func (f *file) lintPackageComment() { - if f.isTest() { - return - } - - const ref = styleGuideBase + "#package-comments" - prefix := "Package " + f.f.Name.Name + " " - - // Look for a detached package comment. - // First, scan for the last comment that occurs before the "package" keyword. - var lastCG *ast.CommentGroup - for _, cg := range f.f.Comments { - if cg.Pos() > f.f.Package { - // Gone past "package" keyword. - break - } - lastCG = cg - } - if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) { - endPos := f.fset.Position(lastCG.End()) - pkgPos := f.fset.Position(f.f.Package) - if endPos.Line+1 < pkgPos.Line { - // There isn't a great place to anchor this error; - // the start of the blank lines between the doc and the package statement - // is at least pointing at the location of the problem. - pos := token.Position{ - Filename: endPos.Filename, - // Offset not set; it is non-trivial, and doesn't appear to be needed. - Line: endPos.Line + 1, - Column: 1, - } - f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement") - return - } - } - - if f.f.Doc == nil { - f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package") - return - } - s := f.f.Doc.Text() - if ts := strings.TrimLeft(s, " \t"); ts != s { - f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space") - s = ts - } - // Only non-main packages need to keep to this form. - if !f.pkg.main && !strings.HasPrefix(s, prefix) { - f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix) - } -} - -func (f *file) isCgo() bool { - if f.src == nil { - return false - } - newLinePos := bytes.Index(f.src, []byte("\n")) - if newLinePos < 0 { - return false - } - firstLine := string(f.src[:newLinePos]) - - // files using cgo have implicitly added comment "Created by cgo - DO NOT EDIT" for go <= 1.10 - // and "Code generated by cmd/cgo" for go >= 1.11 - return strings.Contains(firstLine, "Created by cgo") || strings.Contains(firstLine, "Code generated by cmd/cgo") -} - -// lintBlankImports complains if a non-main package has blank imports that are -// not documented. -func (f *file) lintBlankImports() { - // In package main and in tests, we don't complain about blank imports. - if f.pkg.main || f.isTest() || f.isCgo() { - return - } - - // The first element of each contiguous group of blank imports should have - // an explanatory comment of some kind. - for i, imp := range f.f.Imports { - pos := f.fset.Position(imp.Pos()) - - if !isBlank(imp.Name) { - continue // Ignore non-blank imports. - } - if i > 0 { - prev := f.f.Imports[i-1] - prevPos := f.fset.Position(prev.Pos()) - if isBlank(prev.Name) && prevPos.Line+1 == pos.Line { - continue // A subsequent blank in a group. - } - } - - // This is the first blank import of a group. - if imp.Doc == nil && imp.Comment == nil { - ref := "" - f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it") - } - } -} - -// lintImports examines import blocks. -func (f *file) lintImports() { - for i, is := range f.f.Imports { - _ = i - if is.Name != nil && is.Name.Name == "." && !f.isTest() { - f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports") - } - - } -} - -const docCommentsLink = styleGuideBase + "#doc-comments" - -// lintExported examines the exported names. -// It complains if any required doc comments are missing, -// or if they are not of the right form. The exact rules are in -// lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function -// also tracks the GenDecl structure being traversed to permit -// doc comments for constants to be on top of the const block. -// It also complains if the names stutter when combined with -// the package name. -func (f *file) lintExported() { - if f.isTest() { - return - } - - var lastGen *ast.GenDecl // last GenDecl entered. - - // Set of GenDecls that have already had missing comments flagged. - genDeclMissingComments := make(map[*ast.GenDecl]bool) - - f.walk(func(node ast.Node) bool { - switch v := node.(type) { - case *ast.GenDecl: - if v.Tok == token.IMPORT { - return false - } - // token.CONST, token.TYPE or token.VAR - lastGen = v - return true - case *ast.FuncDecl: - f.lintFuncDoc(v) - if v.Recv == nil { - // Only check for stutter on functions, not methods. - // Method names are not used package-qualified. - f.checkStutter(v.Name, "func") - } - // Don't proceed inside funcs. - return false - case *ast.TypeSpec: - // inside a GenDecl, which usually has the doc - doc := v.Doc - if doc == nil { - doc = lastGen.Doc - } - f.lintTypeDoc(v, doc) - f.checkStutter(v.Name, "type") - // Don't proceed inside types. - return false - case *ast.ValueSpec: - f.lintValueSpecDoc(v, lastGen, genDeclMissingComments) - return false - } - return true - }) -} - -var ( - allCapsRE = regexp.MustCompile(`^[A-Z0-9_]+$`) - anyCapsRE = regexp.MustCompile(`[A-Z]`) -) - -// knownNameExceptions is a set of names that are known to be exempt from naming checks. -// This is usually because they are constrained by having to match names in the -// standard library. -var knownNameExceptions = map[string]bool{ - "LastInsertId": true, // must match database/sql - "kWh": true, -} - -func isInTopLevel(f *ast.File, ident *ast.Ident) bool { - path, _ := astutil.PathEnclosingInterval(f, ident.Pos(), ident.End()) - for _, f := range path { - switch f.(type) { - case *ast.File, *ast.GenDecl, *ast.ValueSpec, *ast.Ident: - continue - } - return false - } - return true -} - -// lintNames examines all names in the file. -// It complains if any use underscores or incorrect known initialisms. -func (f *file) lintNames() { - // Package names need slightly different handling than other names. - if strings.Contains(f.f.Name.Name, "_") && !strings.HasSuffix(f.f.Name.Name, "_test") { - f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("naming"), "don't use an underscore in package name") - } - if anyCapsRE.MatchString(f.f.Name.Name) { - f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("mixed-caps"), "don't use MixedCaps in package name; %s should be %s", f.f.Name.Name, strings.ToLower(f.f.Name.Name)) - } - - check := func(id *ast.Ident, thing string) { - if id.Name == "_" { - return - } - if knownNameExceptions[id.Name] { - return - } - - // Handle two common styles from other languages that don't belong in Go. - if len(id.Name) >= 5 && allCapsRE.MatchString(id.Name) && strings.Contains(id.Name, "_") { - capCount := 0 - for _, c := range id.Name { - if 'A' <= c && c <= 'Z' { - capCount++ - } - } - if capCount >= 2 { - f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use ALL_CAPS in Go names; use CamelCase") - return - } - } - if thing == "const" || (thing == "var" && isInTopLevel(f.f, id)) { - if len(id.Name) > 2 && id.Name[0] == 'k' && id.Name[1] >= 'A' && id.Name[1] <= 'Z' { - should := string(id.Name[1]+'a'-'A') + id.Name[2:] - f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use leading k in Go names; %s %s should be %s", thing, id.Name, should) - } - } - - should := lintName(id.Name) - if id.Name == should { - return - } - - if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") { - f.errorf(id, 0.9, link("http://golang.org/doc/effective_go.html#mixed-caps"), category("naming"), "don't use underscores in Go names; %s %s should be %s", thing, id.Name, should) - return - } - f.errorf(id, 0.8, link(styleGuideBase+"#initialisms"), category("naming"), "%s %s should be %s", thing, id.Name, should) - } - checkList := func(fl *ast.FieldList, thing string) { - if fl == nil { - return - } - for _, f := range fl.List { - for _, id := range f.Names { - check(id, thing) - } - } - } - f.walk(func(node ast.Node) bool { - switch v := node.(type) { - case *ast.AssignStmt: - if v.Tok == token.ASSIGN { - return true - } - for _, exp := range v.Lhs { - if id, ok := exp.(*ast.Ident); ok { - check(id, "var") - } - } - case *ast.FuncDecl: - if f.isTest() && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) { - return true - } - - thing := "func" - if v.Recv != nil { - thing = "method" - } - - // Exclude naming warnings for functions that are exported to C but - // not exported in the Go API. - // See https://github.com/golang/lint/issues/144. - if ast.IsExported(v.Name.Name) || !isCgoExported(v) { - check(v.Name, thing) - } - - checkList(v.Type.Params, thing+" parameter") - checkList(v.Type.Results, thing+" result") - case *ast.GenDecl: - if v.Tok == token.IMPORT { - return true - } - var thing string - switch v.Tok { - case token.CONST: - thing = "const" - case token.TYPE: - thing = "type" - case token.VAR: - thing = "var" - } - for _, spec := range v.Specs { - switch s := spec.(type) { - case *ast.TypeSpec: - check(s.Name, thing) - case *ast.ValueSpec: - for _, id := range s.Names { - check(id, thing) - } - } - } - case *ast.InterfaceType: - // Do not check interface method names. - // They are often constrainted by the method names of concrete types. - for _, x := range v.Methods.List { - ft, ok := x.Type.(*ast.FuncType) - if !ok { // might be an embedded interface name - continue - } - checkList(ft.Params, "interface method parameter") - checkList(ft.Results, "interface method result") - } - case *ast.RangeStmt: - if v.Tok == token.ASSIGN { - return true - } - if id, ok := v.Key.(*ast.Ident); ok { - check(id, "range var") - } - if id, ok := v.Value.(*ast.Ident); ok { - check(id, "range var") - } - case *ast.StructType: - for _, f := range v.Fields.List { - for _, id := range f.Names { - check(id, "struct field") - } - } - } - return true - }) -} - -// lintName returns a different name if it should be different. -func lintName(name string) (should string) { - // Fast path for simple cases: "_" and all lowercase. - if name == "_" { - return name - } - allLower := true - for _, r := range name { - if !unicode.IsLower(r) { - allLower = false - break - } - } - if allLower { - return name - } - - // Split camelCase at any lower->upper transition, and split on underscores. - // Check each word for common initialisms. - runes := []rune(name) - w, i := 0, 0 // index of start of word, scan - for i+1 <= len(runes) { - eow := false // whether we hit the end of a word - if i+1 == len(runes) { - eow = true - } else if runes[i+1] == '_' { - // underscore; shift the remainder forward over any run of underscores - eow = true - n := 1 - for i+n+1 < len(runes) && runes[i+n+1] == '_' { - n++ - } - - // Leave at most one underscore if the underscore is between two digits - if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) { - n-- - } - - copy(runes[i+1:], runes[i+n+1:]) - runes = runes[:len(runes)-n] - } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) { - // lower->non-lower - eow = true - } - i++ - if !eow { - continue - } - - // [w,i) is a word. - word := string(runes[w:i]) - if u := strings.ToUpper(word); commonInitialisms[u] { - // Keep consistent case, which is lowercase only at the start. - if w == 0 && unicode.IsLower(runes[w]) { - u = strings.ToLower(u) - } - // All the common initialisms are ASCII, - // so we can replace the bytes exactly. - copy(runes[w:], []rune(u)) - } else if w > 0 && strings.ToLower(word) == word { - // already all lowercase, and not the first word, so uppercase the first character. - runes[w] = unicode.ToUpper(runes[w]) - } - w = i - } - return string(runes) -} - -// commonInitialisms is a set of common initialisms. -// Only add entries that are highly unlikely to be non-initialisms. -// For instance, "ID" is fine (Freudian code is rare), but "AND" is not. -var commonInitialisms = map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTP": true, - "HTTPS": true, - "ID": true, - "IP": true, - "JSON": true, - "LHS": true, - "QPS": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "UUID": true, - "URI": true, - "URL": true, - "UTF8": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, -} - -// lintTypeDoc examines the doc comment on a type. -// It complains if they are missing from an exported type, -// or if they are not of the standard form. -func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) { - if !ast.IsExported(t.Name.Name) { - return - } - if doc == nil { - f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name) - return - } - - s := doc.Text() - articles := [...]string{"A", "An", "The"} - for _, a := range articles { - if strings.HasPrefix(s, a+" ") { - s = s[len(a)+1:] - break - } - } - if !strings.HasPrefix(s, t.Name.Name+" ") { - f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name) - } -} - -var commonMethods = map[string]bool{ - "Error": true, - "Read": true, - "ServeHTTP": true, - "String": true, - "Write": true, -} - -// lintFuncDoc examines doc comments on functions and methods. -// It complains if they are missing, or not of the right form. -// It has specific exclusions for well-known methods (see commonMethods above). -func (f *file) lintFuncDoc(fn *ast.FuncDecl) { - if !ast.IsExported(fn.Name.Name) { - // func is unexported - return - } - kind := "function" - name := fn.Name.Name - if fn.Recv != nil && len(fn.Recv.List) > 0 { - // method - kind = "method" - recv := receiverType(fn) - if !ast.IsExported(recv) { - // receiver is unexported - return - } - if commonMethods[name] { - return - } - switch name { - case "Len", "Less", "Swap": - if f.pkg.sortable[recv] { - return - } - } - name = recv + "." + name - } - if fn.Doc == nil { - f.errorf(fn, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment or be unexported", kind, name) - return - } - s := fn.Doc.Text() - prefix := fn.Name.Name + " " - if !strings.HasPrefix(s, prefix) { - f.errorf(fn.Doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix) - } -} - -// lintValueSpecDoc examines package-global variables and constants. -// It complains if they are not individually declared, -// or if they are not suitably documented in the right form (unless they are in a block that is commented). -func (f *file) lintValueSpecDoc(vs *ast.ValueSpec, gd *ast.GenDecl, genDeclMissingComments map[*ast.GenDecl]bool) { - kind := "var" - if gd.Tok == token.CONST { - kind = "const" - } - - if len(vs.Names) > 1 { - // Check that none are exported except for the first. - for _, n := range vs.Names[1:] { - if ast.IsExported(n.Name) { - f.errorf(vs, 1, category("comments"), "exported %s %s should have its own declaration", kind, n.Name) - return - } - } - } - - // Only one name. - name := vs.Names[0].Name - if !ast.IsExported(name) { - return - } - - if vs.Doc == nil && gd.Doc == nil { - if genDeclMissingComments[gd] { - return - } - block := "" - if kind == "const" && gd.Lparen.IsValid() { - block = " (or a comment on this block)" - } - f.errorf(vs, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment%s or be unexported", kind, name, block) - genDeclMissingComments[gd] = true - return - } - // If this GenDecl has parens and a comment, we don't check its comment form. - if gd.Lparen.IsValid() && gd.Doc != nil { - return - } - // The relevant text to check will be on either vs.Doc or gd.Doc. - // Use vs.Doc preferentially. - doc := vs.Doc - if doc == nil { - doc = gd.Doc - } - prefix := name + " " - if !strings.HasPrefix(doc.Text(), prefix) { - f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix) - } -} - -func (f *file) checkStutter(id *ast.Ident, thing string) { - pkg, name := f.f.Name.Name, id.Name - if !ast.IsExported(name) { - // unexported name - return - } - // A name stutters if the package name is a strict prefix - // and the next character of the name starts a new word. - if len(name) <= len(pkg) { - // name is too short to stutter. - // This permits the name to be the same as the package name. - return - } - if !strings.EqualFold(pkg, name[:len(pkg)]) { - return - } - // We can assume the name is well-formed UTF-8. - // If the next rune after the package name is uppercase or an underscore - // the it's starting a new word and thus this name stutters. - rem := name[len(pkg):] - if next, _ := utf8.DecodeRuneInString(rem); next == '_' || unicode.IsUpper(next) { - f.errorf(id, 0.8, link(styleGuideBase+"#package-names"), category("naming"), "%s name will be used as %s.%s by other packages, and that stutters; consider calling this %s", thing, pkg, name, rem) - } -} - -// zeroLiteral is a set of ast.BasicLit values that are zero values. -// It is not exhaustive. -var zeroLiteral = map[string]bool{ - "false": true, // bool - // runes - `'\x00'`: true, - `'\000'`: true, - // strings - `""`: true, - "``": true, - // numerics - "0": true, - "0.": true, - "0.0": true, - "0i": true, -} - -// lintElses examines else blocks. It complains about any else block whose if block ends in a return. -func (f *file) lintElses() { - // We don't want to flag if { } else if { } else { } constructions. - // They will appear as an IfStmt whose Else field is also an IfStmt. - // Record such a node so we ignore it when we visit it. - ignore := make(map[*ast.IfStmt]bool) - - f.walk(func(node ast.Node) bool { - ifStmt, ok := node.(*ast.IfStmt) - if !ok || ifStmt.Else == nil { - return true - } - if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok { - ignore[elseif] = true - return true - } - if ignore[ifStmt] { - return true - } - if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok { - // only care about elses without conditions - return true - } - if len(ifStmt.Body.List) == 0 { - return true - } - shortDecl := false // does the if statement have a ":=" initialization statement? - if ifStmt.Init != nil { - if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE { - shortDecl = true - } - } - lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1] - if _, ok := lastStmt.(*ast.ReturnStmt); ok { - extra := "" - if shortDecl { - extra = " (move short variable declaration to its own line if necessary)" - } - f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra) - } - return true - }) -} - -// lintRanges examines range clauses. It complains about redundant constructions. -func (f *file) lintRanges() { - f.walk(func(node ast.Node) bool { - rs, ok := node.(*ast.RangeStmt) - if !ok { - return true - } - - if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) { - p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`") - - newRS := *rs // shallow copy - newRS.Value = nil - newRS.Key = nil - p.ReplacementLine = f.firstLineOf(&newRS, rs) - - return true - } - - if isIdent(rs.Value, "_") { - p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok) - - newRS := *rs // shallow copy - newRS.Value = nil - p.ReplacementLine = f.firstLineOf(&newRS, rs) - } - - return true - }) -} - -// lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation. -func (f *file) lintErrorf() { - f.walk(func(node ast.Node) bool { - ce, ok := node.(*ast.CallExpr) - if !ok || len(ce.Args) != 1 { - return true - } - isErrorsNew := isPkgDot(ce.Fun, "errors", "New") - var isTestingError bool - se, ok := ce.Fun.(*ast.SelectorExpr) - if ok && se.Sel.Name == "Error" { - if typ := f.pkg.typeOf(se.X); typ != nil { - isTestingError = typ.String() == "*testing.T" - } - } - if !isErrorsNew && !isTestingError { - return true - } - if !f.imports("errors") { - return true - } - arg := ce.Args[0] - ce, ok = arg.(*ast.CallExpr) - if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") { - return true - } - errorfPrefix := "fmt" - if isTestingError { - errorfPrefix = f.render(se.X) - } - p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix) - - m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`) - if m != nil { - p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3] - } - - return true - }) -} - -// lintErrors examines global error vars. It complains if they aren't named in the standard way. -func (f *file) lintErrors() { - for _, decl := range f.f.Decls { - gd, ok := decl.(*ast.GenDecl) - if !ok || gd.Tok != token.VAR { - continue - } - for _, spec := range gd.Specs { - spec := spec.(*ast.ValueSpec) - if len(spec.Names) != 1 || len(spec.Values) != 1 { - continue - } - ce, ok := spec.Values[0].(*ast.CallExpr) - if !ok { - continue - } - if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { - continue - } - - id := spec.Names[0] - prefix := "err" - if id.IsExported() { - prefix = "Err" - } - if !strings.HasPrefix(id.Name, prefix) { - f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix) - } - } - } -} - -func lintErrorString(s string) (isClean bool, conf float64) { - const basicConfidence = 0.8 - const capConfidence = basicConfidence - 0.2 - first, firstN := utf8.DecodeRuneInString(s) - last, _ := utf8.DecodeLastRuneInString(s) - if last == '.' || last == ':' || last == '!' || last == '\n' { - return false, basicConfidence - } - if unicode.IsUpper(first) { - // People use proper nouns and exported Go identifiers in error strings, - // so decrease the confidence of warnings for capitalization. - if len(s) <= firstN { - return false, capConfidence - } - // Flag strings starting with something that doesn't look like an initialism. - if second, _ := utf8.DecodeRuneInString(s[firstN:]); !unicode.IsUpper(second) { - return false, capConfidence - } - } - return true, 0 -} - -// lintErrorStrings examines error strings. -// It complains if they are capitalized or end in punctuation or a newline. -func (f *file) lintErrorStrings() { - f.walk(func(node ast.Node) bool { - ce, ok := node.(*ast.CallExpr) - if !ok { - return true - } - if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { - return true - } - if len(ce.Args) < 1 { - return true - } - str, ok := ce.Args[0].(*ast.BasicLit) - if !ok || str.Kind != token.STRING { - return true - } - s, _ := strconv.Unquote(str.Value) // can assume well-formed Go - if s == "" { - return true - } - clean, conf := lintErrorString(s) - if clean { - return true - } - - f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"), - "error strings should not be capitalized or end with punctuation or a newline") - return true - }) -} - -// lintReceiverNames examines receiver names. It complains about inconsistent -// names used for the same type and names such as "this". -func (f *file) lintReceiverNames() { - typeReceiver := map[string]string{} - f.walk(func(n ast.Node) bool { - fn, ok := n.(*ast.FuncDecl) - if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { - return true - } - names := fn.Recv.List[0].Names - if len(names) < 1 { - return true - } - name := names[0].Name - const ref = styleGuideBase + "#receiver-names" - if name == "_" { - f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`) - return true - } - if name == "this" || name == "self" { - f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`) - return true - } - recv := receiverType(fn) - if prev, ok := typeReceiver[recv]; ok && prev != name { - f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv) - return true - } - typeReceiver[recv] = name - return true - }) -} - -// lintIncDec examines statements that increment or decrement a variable. -// It complains if they don't use x++ or x--. -func (f *file) lintIncDec() { - f.walk(func(n ast.Node) bool { - as, ok := n.(*ast.AssignStmt) - if !ok { - return true - } - if len(as.Lhs) != 1 { - return true - } - if !isOne(as.Rhs[0]) { - return true - } - var suffix string - switch as.Tok { - case token.ADD_ASSIGN: - suffix = "++" - case token.SUB_ASSIGN: - suffix = "--" - default: - return true - } - f.errorf(as, 0.8, category("unary-op"), "should replace %s with %s%s", f.render(as), f.render(as.Lhs[0]), suffix) - return true - }) -} - -// lintErrorReturn examines function declarations that return an error. -// It complains if the error isn't the last parameter. -func (f *file) lintErrorReturn() { - f.walk(func(n ast.Node) bool { - fn, ok := n.(*ast.FuncDecl) - if !ok || fn.Type.Results == nil { - return true - } - ret := fn.Type.Results.List - if len(ret) <= 1 { - return true - } - if isIdent(ret[len(ret)-1].Type, "error") { - return true - } - // An error return parameter should be the last parameter. - // Flag any error parameters found before the last. - for _, r := range ret[:len(ret)-1] { - if isIdent(r.Type, "error") { - f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items") - break // only flag one - } - } - return true - }) -} - -// lintUnexportedReturn examines exported function declarations. -// It complains if any return an unexported type. -func (f *file) lintUnexportedReturn() { - f.walk(func(n ast.Node) bool { - fn, ok := n.(*ast.FuncDecl) - if !ok { - return true - } - if fn.Type.Results == nil { - return false - } - if !fn.Name.IsExported() { - return false - } - thing := "func" - if fn.Recv != nil && len(fn.Recv.List) > 0 { - thing = "method" - if !ast.IsExported(receiverType(fn)) { - // Don't report exported methods of unexported types, - // such as private implementations of sort.Interface. - return false - } - } - for _, ret := range fn.Type.Results.List { - typ := f.pkg.typeOf(ret.Type) - if exportedType(typ) { - continue - } - f.errorf(ret.Type, 0.8, category("unexported-type-in-api"), - "exported %s %s returns unexported type %s, which can be annoying to use", - thing, fn.Name.Name, typ) - break // only flag one - } - return false - }) -} - -// exportedType reports whether typ is an exported type. -// It is imprecise, and will err on the side of returning true, -// such as for composite types. -func exportedType(typ types.Type) bool { - switch T := typ.(type) { - case *types.Named: - // Builtin types have no package. - return T.Obj().Pkg() == nil || T.Obj().Exported() - case *types.Map: - return exportedType(T.Key()) && exportedType(T.Elem()) - case interface { - Elem() types.Type - }: // array, slice, pointer, chan - return exportedType(T.Elem()) - } - // Be conservative about other types, such as struct, interface, etc. - return true -} - -// timeSuffixes is a list of name suffixes that imply a time unit. -// This is not an exhaustive list. -var timeSuffixes = []string{ - "Sec", "Secs", "Seconds", - "Msec", "Msecs", - "Milli", "Millis", "Milliseconds", - "Usec", "Usecs", "Microseconds", - "MS", "Ms", -} - -func (f *file) lintTimeNames() { - f.walk(func(node ast.Node) bool { - v, ok := node.(*ast.ValueSpec) - if !ok { - return true - } - for _, name := range v.Names { - origTyp := f.pkg.typeOf(name) - // Look for time.Duration or *time.Duration; - // the latter is common when using flag.Duration. - typ := origTyp - if pt, ok := typ.(*types.Pointer); ok { - typ = pt.Elem() - } - if !f.pkg.isNamedType(typ, "time", "Duration") { - continue - } - suffix := "" - for _, suf := range timeSuffixes { - if strings.HasSuffix(name.Name, suf) { - suffix = suf - break - } - } - if suffix == "" { - continue - } - f.errorf(v, 0.9, category("time"), "var %s is of type %v; don't use unit-specific suffix %q", name.Name, origTyp, suffix) - } - return true - }) -} - -// lintContextKeyTypes checks for call expressions to context.WithValue with -// basic types used for the key argument. -// See: https://golang.org/issue/17293 -func (f *file) lintContextKeyTypes() { - f.walk(func(node ast.Node) bool { - switch node := node.(type) { - case *ast.CallExpr: - f.checkContextKeyType(node) - } - - return true - }) -} - -// checkContextKeyType reports an error if the call expression calls -// context.WithValue with a key argument of basic type. -func (f *file) checkContextKeyType(x *ast.CallExpr) { - sel, ok := x.Fun.(*ast.SelectorExpr) - if !ok { - return - } - pkg, ok := sel.X.(*ast.Ident) - if !ok || pkg.Name != "context" { - return - } - if sel.Sel.Name != "WithValue" { - return - } - - // key is second argument to context.WithValue - if len(x.Args) != 3 { - return - } - key := f.pkg.typesInfo.Types[x.Args[1]] - - if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid { - f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type)) - } -} - -// lintContextArgs examines function declarations that contain an -// argument with a type of context.Context -// It complains if that argument isn't the first parameter. -func (f *file) lintContextArgs() { - f.walk(func(n ast.Node) bool { - fn, ok := n.(*ast.FuncDecl) - if !ok || len(fn.Type.Params.List) <= 1 { - return true - } - // A context.Context should be the first parameter of a function. - // Flag any that show up after the first. - for _, arg := range fn.Type.Params.List[1:] { - if isPkgDot(arg.Type, "context", "Context") { - f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function") - break // only flag one - } - } - return true - }) -} - -// containsComments returns whether the interval [start, end) contains any -// comments without "// MATCH " prefix. -func (f *file) containsComments(start, end token.Pos) bool { - for _, cgroup := range f.f.Comments { - comments := cgroup.List - if comments[0].Slash >= end { - // All comments starting with this group are after end pos. - return false - } - if comments[len(comments)-1].Slash < start { - // Comments group ends before start pos. - continue - } - for _, c := range comments { - if start <= c.Slash && c.Slash < end && !strings.HasPrefix(c.Text, "// MATCH ") { - return true - } - } - } - return false -} - -// receiverType returns the named type of the method receiver, sans "*", -// or "invalid-type" if fn.Recv is ill formed. -func receiverType(fn *ast.FuncDecl) string { - switch e := fn.Recv.List[0].Type.(type) { - case *ast.Ident: - return e.Name - case *ast.StarExpr: - if id, ok := e.X.(*ast.Ident); ok { - return id.Name - } - } - // The parser accepts much more than just the legal forms. - return "invalid-type" -} - -func (f *file) walk(fn func(ast.Node) bool) { - ast.Walk(walker(fn), f.f) -} - -func (f *file) render(x interface{}) string { - var buf bytes.Buffer - if err := printer.Fprint(&buf, f.fset, x); err != nil { - panic(err) - } - return buf.String() -} - -func (f *file) debugRender(x interface{}) string { - var buf bytes.Buffer - if err := ast.Fprint(&buf, f.fset, x, nil); err != nil { - panic(err) - } - return buf.String() -} - -// walker adapts a function to satisfy the ast.Visitor interface. -// The function return whether the walk should proceed into the node's children. -type walker func(ast.Node) bool - -func (w walker) Visit(node ast.Node) ast.Visitor { - if w(node) { - return w - } - return nil -} - -func isIdent(expr ast.Expr, ident string) bool { - id, ok := expr.(*ast.Ident) - return ok && id.Name == ident -} - -// isBlank returns whether id is the blank identifier "_". -// If id == nil, the answer is false. -func isBlank(id *ast.Ident) bool { return id != nil && id.Name == "_" } - -func isPkgDot(expr ast.Expr, pkg, name string) bool { - sel, ok := expr.(*ast.SelectorExpr) - return ok && isIdent(sel.X, pkg) && isIdent(sel.Sel, name) -} - -func isOne(expr ast.Expr) bool { - lit, ok := expr.(*ast.BasicLit) - return ok && lit.Kind == token.INT && lit.Value == "1" -} - -func isCgoExported(f *ast.FuncDecl) bool { - if f.Recv != nil || f.Doc == nil { - return false - } - - cgoExport := regexp.MustCompile(fmt.Sprintf("(?m)^//export %s$", regexp.QuoteMeta(f.Name.Name))) - for _, c := range f.Doc.List { - if cgoExport.MatchString(c.Text) { - return true - } - } - return false -} - -var basicTypeKinds = map[types.BasicKind]string{ - types.UntypedBool: "bool", - types.UntypedInt: "int", - types.UntypedRune: "rune", - types.UntypedFloat: "float64", - types.UntypedComplex: "complex128", - types.UntypedString: "string", -} - -// isUntypedConst reports whether expr is an untyped constant, -// and indicates what its default type is. -// scope may be nil. -func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) { - // Re-evaluate expr outside of its context to see if it's untyped. - // (An expr evaluated within, for example, an assignment context will get the type of the LHS.) - exprStr := f.render(expr) - tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr) - if err != nil { - return "", false - } - if b, ok := tv.Type.(*types.Basic); ok { - if dt, ok := basicTypeKinds[b.Kind()]; ok { - return dt, true - } - } - - return "", false -} - -// firstLineOf renders the given node and returns its first line. -// It will also match the indentation of another node. -func (f *file) firstLineOf(node, match ast.Node) string { - line := f.render(node) - if i := strings.Index(line, "\n"); i >= 0 { - line = line[:i] - } - return f.indentOf(match) + line -} - -func (f *file) indentOf(node ast.Node) string { - line := srcLine(f.src, f.fset.Position(node.Pos())) - for i, r := range line { - switch r { - case ' ', '\t': - default: - return line[:i] - } - } - return line // unusual or empty line -} - -func (f *file) srcLineWithMatch(node ast.Node, pattern string) (m []string) { - line := srcLine(f.src, f.fset.Position(node.Pos())) - line = strings.TrimSuffix(line, "\n") - rx := regexp.MustCompile(pattern) - return rx.FindStringSubmatch(line) -} - -// imports returns true if the current file imports the specified package path. -func (f *file) imports(importPath string) bool { - all := astutil.Imports(f.fset, f.f) - for _, p := range all { - for _, i := range p { - uq, err := strconv.Unquote(i.Path.Value) - if err == nil && importPath == uq { - return true - } - } - } - return false -} - -// srcLine returns the complete line at p, including the terminating newline. -func srcLine(src []byte, p token.Position) string { - // Run to end of line in both directions if not at line start/end. - lo, hi := p.Offset, p.Offset+1 - for lo > 0 && src[lo-1] != '\n' { - lo-- - } - for hi < len(src) && src[hi-1] != '\n' { - hi++ - } - return string(src[lo:hi]) -} diff --git a/tools/vendor/github.com/golangci/maligned/README b/tools/vendor/github.com/golangci/maligned/README deleted file mode 100644 index 4e57f6eab..000000000 --- a/tools/vendor/github.com/golangci/maligned/README +++ /dev/null @@ -1,7 +0,0 @@ -Install: - - go get github.com/mdempsky/maligned - -Usage: - - maligned cmd/compile/internal/gc cmd/link/internal/ld diff --git a/tools/vendor/github.com/golangci/maligned/maligned.go b/tools/vendor/github.com/golangci/maligned/maligned.go deleted file mode 100644 index c2492b2ff..000000000 --- a/tools/vendor/github.com/golangci/maligned/maligned.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package maligned - -import ( - "fmt" - "go/ast" - "go/build" - "go/token" - "go/types" - "sort" - "strings" - - "golang.org/x/tools/go/loader" -) - -var fset = token.NewFileSet() - -type Issue struct { - OldSize, NewSize int - NewStructDef string - Pos token.Position -} - -func Run(prog *loader.Program) []Issue { - flagVerbose := true - fset = prog.Fset - - var issues []Issue - - for _, pkg := range prog.InitialPackages() { - for _, file := range pkg.Files { - ast.Inspect(file, func(node ast.Node) bool { - if s, ok := node.(*ast.StructType); ok { - i := malign(node.Pos(), pkg.Types[s].Type.(*types.Struct), flagVerbose) - if i != nil { - issues = append(issues, *i) - } - } - return true - }) - } - } - - return issues -} - -func malign(pos token.Pos, str *types.Struct, verbose bool) *Issue { - wordSize := int64(8) - maxAlign := int64(8) - switch build.Default.GOARCH { - case "386", "arm": - wordSize, maxAlign = 4, 4 - case "amd64p32": - wordSize = 4 - } - - s := gcSizes{wordSize, maxAlign} - sz := s.Sizeof(str) - opt, fields := optimalSize(str, &s, verbose) - if sz == opt { - return nil - } - - newStructDefParts := []string{"struct{"} - - var w int - for _, f := range fields { - if n := len(f.Name()); n > w { - w = n - } - } - spaces := strings.Repeat(" ", w) - for _, f := range fields { - line := fmt.Sprintf("\t%s%s\t%s,", f.Name(), spaces[len(f.Name()):], f.Type().String()) - newStructDefParts = append(newStructDefParts, line) - } - newStructDefParts = append(newStructDefParts, "}") - - return &Issue{ - OldSize: int(sz), - NewSize: int(opt), - NewStructDef: strings.Join(newStructDefParts, "\n"), - Pos: fset.Position(pos), - } -} - -func optimalSize(str *types.Struct, sizes *gcSizes, stable bool) (int64, []*types.Var) { - nf := str.NumFields() - fields := make([]*types.Var, nf) - alignofs := make([]int64, nf) - sizeofs := make([]int64, nf) - for i := 0; i < nf; i++ { - fields[i] = str.Field(i) - ft := fields[i].Type() - alignofs[i] = sizes.Alignof(ft) - sizeofs[i] = sizes.Sizeof(ft) - } - if stable { // Stable keeps as much of the order as possible, but slower - sort.Stable(&byAlignAndSize{fields, alignofs, sizeofs}) - } else { - sort.Sort(&byAlignAndSize{fields, alignofs, sizeofs}) - } - return sizes.Sizeof(types.NewStruct(fields, nil)), fields -} - -type byAlignAndSize struct { - fields []*types.Var - alignofs []int64 - sizeofs []int64 -} - -func (s *byAlignAndSize) Len() int { return len(s.fields) } -func (s *byAlignAndSize) Swap(i, j int) { - s.fields[i], s.fields[j] = s.fields[j], s.fields[i] - s.alignofs[i], s.alignofs[j] = s.alignofs[j], s.alignofs[i] - s.sizeofs[i], s.sizeofs[j] = s.sizeofs[j], s.sizeofs[i] -} - -func (s *byAlignAndSize) Less(i, j int) bool { - // Place zero sized objects before non-zero sized objects. - if s.sizeofs[i] == 0 && s.sizeofs[j] != 0 { - return true - } - if s.sizeofs[j] == 0 && s.sizeofs[i] != 0 { - return false - } - - // Next, place more tightly aligned objects before less tightly aligned objects. - if s.alignofs[i] != s.alignofs[j] { - return s.alignofs[i] > s.alignofs[j] - } - - // Lastly, order by size. - if s.sizeofs[i] != s.sizeofs[j] { - return s.sizeofs[i] > s.sizeofs[j] - } - - return false -} - -// Code below based on go/types.StdSizes. - -type gcSizes struct { - WordSize int64 - MaxAlign int64 -} - -func (s *gcSizes) Alignof(T types.Type) int64 { - // NOTE: On amd64, complex64 is 8 byte aligned, - // even though float32 is only 4 byte aligned. - - // For arrays and structs, alignment is defined in terms - // of alignment of the elements and fields, respectively. - switch t := T.Underlying().(type) { - case *types.Array: - // spec: "For a variable x of array type: unsafe.Alignof(x) - // is the same as unsafe.Alignof(x[0]), but at least 1." - return s.Alignof(t.Elem()) - case *types.Struct: - // spec: "For a variable x of struct type: unsafe.Alignof(x) - // is the largest of the values unsafe.Alignof(x.f) for each - // field f of x, but at least 1." - max := int64(1) - for i, nf := 0, t.NumFields(); i < nf; i++ { - if a := s.Alignof(t.Field(i).Type()); a > max { - max = a - } - } - return max - } - a := s.Sizeof(T) // may be 0 - // spec: "For a variable x of any type: unsafe.Alignof(x) is at least 1." - if a < 1 { - return 1 - } - if a > s.MaxAlign { - return s.MaxAlign - } - return a -} - -var basicSizes = [...]byte{ - types.Bool: 1, - types.Int8: 1, - types.Int16: 2, - types.Int32: 4, - types.Int64: 8, - types.Uint8: 1, - types.Uint16: 2, - types.Uint32: 4, - types.Uint64: 8, - types.Float32: 4, - types.Float64: 8, - types.Complex64: 8, - types.Complex128: 16, -} - -func (s *gcSizes) Sizeof(T types.Type) int64 { - switch t := T.Underlying().(type) { - case *types.Basic: - k := t.Kind() - if int(k) < len(basicSizes) { - if s := basicSizes[k]; s > 0 { - return int64(s) - } - } - if k == types.String { - return s.WordSize * 2 - } - case *types.Array: - n := t.Len() - if n == 0 { - return 0 - } - a := s.Alignof(t.Elem()) - z := s.Sizeof(t.Elem()) - return align(z, a)*(n-1) + z - case *types.Slice: - return s.WordSize * 3 - case *types.Struct: - nf := t.NumFields() - if nf == 0 { - return 0 - } - - var o int64 - max := int64(1) - for i := 0; i < nf; i++ { - ft := t.Field(i).Type() - a, sz := s.Alignof(ft), s.Sizeof(ft) - if a > max { - max = a - } - if i == nf-1 && sz == 0 && o != 0 { - sz = 1 - } - o = align(o, a) + sz - } - return align(o, max) - case *types.Interface: - return s.WordSize * 2 - } - return s.WordSize // catch-all -} - -// align returns the smallest y >= x such that y % a == 0. -func align(x, a int64) int64 { - y := x + a - 1 - return y - y%a -} diff --git a/tools/vendor/github.com/golangci/misspell/.golangci.yml b/tools/vendor/github.com/golangci/misspell/.golangci.yml index 31c566eab..2cfed442f 100644 --- a/tools/vendor/github.com/golangci/misspell/.golangci.yml +++ b/tools/vendor/github.com/golangci/misspell/.golangci.yml @@ -1,13 +1,11 @@ run: timeout: 2m - skip-files: [] linters-settings: govet: enable-all: true disable: - fieldalignment - - shadow # FIXME(ldez) must be fixed gocyclo: min-complexity: 16 goconst: @@ -97,7 +95,7 @@ linters: issues: exclude-use-default: false - max-per-linter: 0 + max-issues-per-linter: 0 max-same-issues: 0 exclude: - 'ST1000: at least one file in a package should have a package comment' diff --git a/tools/vendor/github.com/golangci/misspell/.pre-commit-hooks.yaml b/tools/vendor/github.com/golangci/misspell/.pre-commit-hooks.yaml new file mode 100644 index 000000000..5319a75eb --- /dev/null +++ b/tools/vendor/github.com/golangci/misspell/.pre-commit-hooks.yaml @@ -0,0 +1,8 @@ +- id: misspell + name: misspell + description: Correct commonly misspelled English words... quickly + language: golang + entry: misspell + args: + - -w + - -error diff --git a/tools/vendor/github.com/golangci/misspell/Dockerfile b/tools/vendor/github.com/golangci/misspell/Dockerfile index 788ce3a77..c85cd6875 100644 --- a/tools/vendor/github.com/golangci/misspell/Dockerfile +++ b/tools/vendor/github.com/golangci/misspell/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.19-alpine +FROM golang:1.22-alpine # cache buster RUN echo 4 diff --git a/tools/vendor/github.com/golangci/misspell/Makefile b/tools/vendor/github.com/golangci/misspell/Makefile index 783f977cb..fcda870ce 100644 --- a/tools/vendor/github.com/golangci/misspell/Makefile +++ b/tools/vendor/github.com/golangci/misspell/Makefile @@ -9,7 +9,7 @@ build: ## build misspell go build ./cmd/misspell test: ## run all tests - go test -v . + CGO_ENABLED=1 go test -v -race . lint: ## run linter golangci-lint run diff --git a/tools/vendor/github.com/golangci/misspell/README.md b/tools/vendor/github.com/golangci/misspell/README.md index cccd04996..d2c3e7527 100644 --- a/tools/vendor/github.com/golangci/misspell/README.md +++ b/tools/vendor/github.com/golangci/misspell/README.md @@ -1,39 +1,37 @@ -[![Build Status](https://travis-ci.org/client9/misspell.svg?branch=master)](https://travis-ci.org/client9/misspell) [![Go Report Card](https://goreportcard.com/badge/github.com/client9/misspell)](https://goreportcard.com/report/github.com/client9/misspell) [![GoDoc](https://godoc.org/github.com/client9/misspell?status.svg)](https://godoc.org/github.com/client9/misspell) [![Coverage](http://gocover.io/_badge/github.com/client9/misspell)](http://gocover.io/github.com/client9/misspell) [![license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://raw.githubusercontent.com/client9/misspell/master/LICENSE) +[![Main](https://github.com/golangci/misspell/actions/workflows/ci.yml/badge.svg)](https://github.com/golangci/misspell/actions/workflows/ci.yml) +[![Go Report Card](https://goreportcard.com/badge/github.com/golangci/misspell)](https://goreportcard.com/report/github.com/golangci/misspell) +[![Go Reference](https://pkg.go.dev/badge/github.com/golangci/misspell.svg)](https://pkg.go.dev/github.com/golangci/misspell) +[![license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://raw.golangci.com/golangci/misspell/master/LICENSE) Correct commonly misspelled English words... quickly. ### Install - If you just want a binary and to start using `misspell`: +```bash +curl -sfL https://raw.githubusercontent.com/golangci/misspell/master/install-misspell.sh | sh -s -- -b ./bin ${MISSPELL_VERSION} ``` -curl -L -o ./install-misspell.sh https://git.io/misspell -sh ./install-misspell.sh -``` - - -Both will install as `./bin/misspell`. You can adjust the download location using the `-b` flag. File a ticket if you want another platform supported. +Both will install as `./bin/misspell`. +You can adjust the download location using the `-b` flag. +File a ticket if you want another platform supported. -If you use [Go](https://golang.org/), the best way to run `misspell` is by using [gometalinter](#gometalinter). Otherwise, install `misspell` the old-fashioned way: +If you use [Go](https://golang.org/), the best way to run `misspell` is by using [golangci-lint](https://github.com/golangci/golangci-lint). +Otherwise, install `misspell` the old-fashioned way: +```bash +go install github.com/golangci/misspell/cmd/misspell@latest ``` -go install github.com/client9/misspell/cmd/misspell@latest -``` - -and misspell will be in your `GOPATH` - -Also if you like to live dangerously, one could do +Also, if you like to live dangerously, one could do ```bash -curl -L https://git.io/misspell | bash +curl -sfL https://raw.githubusercontent.com/golangci/misspell/master/install-misspell.sh | sh -s -- -b $(go env GOPATH)/bin ${MISSPELL_VERSION} ``` ### Usage - ```bash $ misspell all.html your.txt important.md files.go your.txt:42:10 found "langauge" a misspelling of "language" @@ -41,29 +39,49 @@ your.txt:42:10 found "langauge" a misspelling of "language" # ^ file, line, column ``` -``` +```console $ misspell -help Usage of misspell: -debug - Debug matching, very slow + Debug matching, very slow + -dict string + User defined corrections file path (.csv). CSV format: typo,fix -error - Exit with 2 if misspelling found + Exit with 2 if misspelling found -f string - 'csv', 'sqlite3' or custom Golang template for output + 'csv', 'sqlite3' or custom Golang template for output -i string - ignore the following corrections, comma separated + ignore the following corrections, comma-separated -j int - Number of workers, 0 = number of CPUs + Number of workers, 0 = number of CPUs -legal - Show legal information and exit + Show legal information and exit -locale string - Correct spellings using locale perferances for US or UK. Default is to use a neutral variety of English. Setting locale to US will correct the British spelling of 'colour' to 'color' + Correct spellings using locale preferences for US or UK. Default is to use a neutral variety of English. Setting locale to US will correct the British spelling of 'colour' to 'color' -o string - output file or [stderr|stdout|] (default "stdout") - -q Do not emit misspelling output + output file or [stderr|stdout|] (default "stdout") + -q Do not emit misspelling output -source string - Source mode: auto=guess, go=golang source, text=plain or markdown-like text (default "auto") - -w Overwrite file with corrections (default is just to display) + Source mode: text (default), go (comments only) (default "text") + -v Show version and exit + -w Overwrite file with corrections (default is just to display) +``` + +### Pre-commit hook + +To use misspell with [pre-commit](https://pre-commit.com/), add the following to your `.pre-commit-config.yaml`: + + +```yaml +- repo: https://github.com/golangci/misspell + rev: v0.6.0 + hooks: + - id: misspell + # The hook will run on all files by default. + # To limit to some files only, use pre-commit patterns/types + # files: + # exclude: + # types: ``` ## FAQ @@ -72,7 +90,6 @@ Usage of misspell: * [Converting UK spellings to US](#locale) * [Using pipes and stdin](#stdin) * [Golang special support](#golang) -* [gometalinter support](#gometalinter) * [CSV Output](#csv) * [Using SQLite3](#sqlite) * [Changing output format](#output) @@ -92,7 +109,7 @@ Usage of misspell: Just add the `-w` flag! -``` +```console $ misspell -w all.html your.txt important.md files.go your.txt:9:21:corrected "langauge" to "language" @@ -104,20 +121,19 @@ your.txt:9:21:corrected "langauge" to "language" Add the `-locale US` flag! -```bash +```console $ misspell -locale US important.txt important.txt:10:20 found "colour" a misspelling of "color" ``` Add the `-locale UK` flag! -```bash +```console $ echo "My favorite color is blue" | misspell -locale UK stdin:1:3:found "favorite color" a misspelling of "favourite colour" ``` -Help is appreciated as I'm neither British nor an -expert in the English language. +Help is appreciated as I'm neither British nor an expert in the English language. ### How do you check an entire folder recursively? @@ -141,7 +157,8 @@ or find . -type f | xargs misspell ``` -You can select a type of file as well. The following examples selects all `.txt` files that are *not* in the `vendor` directory: +You can select a type of file as well. +The following examples selects all `.txt` files that are *not* in the `vendor` directory: ```bash find . -type f -name '*.txt' | grep -v vendor/ | xargs misspell -error @@ -154,14 +171,14 @@ Yes! Print messages to `stderr` only: -```bash +```console $ echo "zeebra" | misspell stdin:1:0:found "zeebra" a misspelling of "zebra" ``` Print messages to `stderr`, and corrected text to `stdout`: -```bash +```console $ echo "zeebra" | misspell -w stdin:1:0:corrected "zeebra" to "zebra" zebra @@ -169,7 +186,7 @@ zebra Only print the corrected text to `stdout`: -```bash +```console $ echo "zeebra" | misspell -w -q zebra ``` @@ -177,55 +194,23 @@ zebra ### Are there special rules for golang source files? -Yes! If the file ends in `.go`, then misspell will only check spelling in -comments. - -If you want to force a file to be checked as a golang source, use `-source=go` -on the command line. Conversely, you can check a golang source as if it were -pure text by using `-source=text`. You might want to do this since many -variable names have misspellings in them! - -### Can I check only-comments in other other programming languages? - -I'm told the using `-source=go` works well for ruby, javascript, java, c and -c++. - -It doesn't work well for python and bash. - - -### Does this work with gometalinter? - -[gometalinter](https://github.com/alecthomas/gometalinter) runs -multiple golang linters. Starting on [2016-06-12](https://github.com/alecthomas/gometalinter/pull/134) -gometalinter supports `misspell` natively but it is disabled by default. - -```bash -# update your copy of gometalinter -go get -u github.com/alecthomas/gometalinter - -# install updates and misspell -gometalinter --install --update -``` - -To use, just enable `misspell` - -``` -gometalinter --enable misspell ./... -``` +yes, if you want to force a file to be checked as a golang source, use `-source=go` on the command line. +Conversely, you can check a golang source as if it were pure text by using `-source=text`. +You might want to do this since many variable names have misspellings in them! -Note that gometalinter only checks golang files, and uses the default options -of `misspell` +### Can I check only-comments in other programming languages? -You may wish to run this on your plaintext (.txt) and/or markdown files too. +I'm told the using `-source=go` works well for Ruby, Javascript, Java, C and C++. +It doesn't work well for Python and Bash. ### How Can I Get CSV Output? Using `-f csv`, the output is standard comma-seprated values with headers in the first row. -``` -misspell -f csv * +```console +$ misspell -f csv * file,line,column,typo,corrected "README.md",9,22,langauge,language "README.md",47,25,langauge,language @@ -236,7 +221,7 @@ file,line,column,typo,corrected Using `-f sqlite`, the output is a [sqlite3](https://www.sqlite.org/index.html) dump-file. -```bash +```console $ misspell -f sqlite * > /tmp/misspell.sql $ cat /tmp/misspell.sql @@ -254,7 +239,7 @@ INSERT INTO misspell VALUES("install.txt",202,31,"immediatly","immediately"); COMMIT; ``` -```bash +```console $ sqlite3 -init /tmp/misspell.sql :memory: 'select count(*) from misspell' 1 ``` @@ -271,20 +256,22 @@ misspell -f sqlite * | sqlite3 -init /dev/stdin -column -cmd '.width 60 15' ':me Using the `-i "comma,separated,rules"` flag you can specify corrections to ignore. -For example, if you were to run `misspell -w -error -source=text` against document that contains the string `Guy Finkelshteyn Braswell`, misspell would change the text to `Guy Finkelstheyn Bras well`. You can then -determine the rules to ignore by reverting the change and running the with the `-debug` flag. You can then see -that the corrections were `htey -> they` and `aswell -> as well`. To ignore these two rules, you add `-i "htey,aswell"` to -your command. With debug mode on, you can see it print the corrections, but it will no longer make them. +For example, if you were to run `misspell -w -error -source=text` against document that contains the string `Guy Finkelshteyn Braswell`, +misspell would change the text to `Guy Finkelstheyn Bras well`. +You can then determine the rules to ignore by reverting the change and running the with the `-debug` flag. +You can then see that the corrections were `htey -> they` and `aswell -> as well`. +To ignore these two rules, you add `-i "htey,aswell"` to your command. +With debug mode on, you can see it print the corrections, but it will no longer make them. ### How can I change the output format? -Using the `-f template` flag you can pass in a -[golang text template](https://golang.org/pkg/text/template/) to format the output. +Using the `-f template` flag you can pass in a [golang text template](https://golang.org/pkg/text/template/) to format the output. One can use `printf "%q" VALUE` to safely quote a value. -The default template is compatible with [gometalinter](https://github.com/alecthomas/gometalinter) +The default template: + ``` {{ .Filename }}:{{ .Line }}:{{ .Column }}:corrected {{ printf "%q" .Original }} to "{{ printf "%q" .Corrected }}" ``` @@ -298,14 +285,12 @@ To just print probable misspellings: ### What problem does this solve? -This corrects commonly misspelled English words in computer source -code, and other text-based formats (`.txt`, `.md`, etc). +This corrects commonly misspelled English words in computer source code, and other text-based formats (`.txt`, `.md`, etc.). -It is designed to run quickly so it can be -used as a [pre-commit hook](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) -with minimal burden on the developer. +It is designed to run quickly, +so it can be used as a [pre-commit hook](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) with minimal burden on the developer. -It does not work with binary formats (e.g. Word, etc). +It does not work with binary formats (e.g. Word, etc.). It is not a complete spell-checking program nor a grammar checker. @@ -322,78 +307,71 @@ They all work but had problems that prevented me from using them at scale: * slow, all of the above check one misspelling at a time (i.e. linear) using regexps * not MIT/Apache2 licensed (or equivalent) -* have dependencies that don't work for me (python3, bash, linux sed, etc) +* have dependencies that don't work for me (python3, bash, linux sed, etc.) * don't understand American vs. British English and sometimes makes unwelcome "corrections" -That said, they might be perfect for you and many have more features -than this project! +That said, they might be perfect for you and many have more features than this project! ### How fast is it? -Misspell is easily 100x to 1000x faster than other spelling correctors. You -should be able to check and correct 1000 files in under 250ms. +Misspell is easily 100x to 1000x faster than other spelling correctors. +You should be able to check and correct 1000 files in under 250ms. -This uses the mighty power of golang's -[strings.Replacer](https://golang.org/pkg/strings/#Replacer) which is -a implementation or variation of the -[Aho–Corasick algorithm](https://en.wikipedia.org/wiki/Aho–Corasick_algorithm). +This uses the mighty power of golang's [strings.Replacer](https://golang.org/pkg/strings/#Replacer) +which is an implementation or variation of the [Aho–Corasick algorithm](https://en.wikipedia.org/wiki/Aho–Corasick_algorithm). This makes multiple substring matches *simultaneously*. -In addition this uses multiple CPU cores to work on multiple files. +It also uses multiple CPU cores to work on multiple files concurrently. ### What problems does it have? -Unlike the other projects, this doesn't know what a "word" is. There may be -more false positives and false negatives due to this. On the other hand, it -sometimes catches things others don't. +Unlike the other projects, this doesn't know what a "word" is. +There may be more false positives and false negatives due to this. +On the other hand, it sometimes catches things others don't. Either way, please file bugs and we'll fix them! -Since it operates in parallel to make corrections, it can be non-obvious to -determine exactly what word was corrected. +Since it operates in parallel to make corrections, +it can be non-obvious to determine exactly what word was corrected. ### It's making mistakes. How can I debug? -Run using `-debug` flag on the file you want. It should then print what word -it is trying to correct. Then [file a -bug](https://github.com/client9/misspell/issues) describing the problem. +Run using `-debug` flag on the file you want. +It should then print what word it is trying to correct. +Then [file a bug](https://github.com/golangci/misspell/issues) describing the problem. Thanks! ### Why is it making mistakes or missing items in golang files? -The matching function is *case-sensitive*, so variable names that are multiple -worlds either in all-upper or all-lower case sometimes can cause false -positives. For instance a variable named `bodyreader` could trigger a false -positive since `yrea` is in the middle that could be corrected to `year`. -Other problems happen if the variable name uses a English contraction that -should use an apostrophe. The best way of fixing this is to use the -[Effective Go naming -conventions](https://golang.org/doc/effective_go.html#mixed-caps) and use -[camelCase](https://en.wikipedia.org/wiki/CamelCase) for variable names. You -can check your code using [golint](https://github.com/golang/lint) +The matching function is *case-sensitive*, +so variable names that are multiple worlds either in all-uppercase or all-lowercase case sometimes can cause false positives. +For instance a variable named `bodyreader` could trigger a false positive since `yrea` is in the middle that could be corrected to `year`. +Other problems happen if the variable name uses an English contraction that should use an apostrophe. +The best way of fixing this is to use the [Effective Go naming conventions](https://golang.org/doc/effective_go.html#mixed-caps) +and use [camelCase](https://en.wikipedia.org/wiki/CamelCase) for variable names. +You can check your code using [golint](https://github.com/golang/lint) ### What license is this? -The main code is [MIT](https://github.com/client9/misspell/blob/master/LICENSE). +The main code is [MIT](https://github.com/golangci/misspell/blob/master/LICENSE). Misspell also makes uses of the Golang standard library and contains a modified version of Golang's [strings.Replacer](https://golang.org/pkg/strings/#Replacer) -which are covered under a [BSD License](https://github.com/golang/go/blob/master/LICENSE). Type `misspell -legal` for more details or see [legal.go](https://github.com/client9/misspell/blob/master/legal.go) +which is covered under a [BSD License](https://github.com/golang/go/blob/master/LICENSE). +Type `misspell -legal` for more details or see [legal.go](https://github.com/golangci/misspell/blob/master/legal.go) ### Where do the word lists come from? It started with a word list from [Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:Lists_of_common_misspellings/For_machines). -Unfortunately, this list had to be highly edited as many of the words are -obsolete or based from mistakes on mechanical typewriters (I'm guessing). +Unfortunately, this list had to be highly edited as many of the words are obsolete or based on mistakes on mechanical typewriters (I'm guessing). -Additional words were added based on actually mistakes seen in -the wild (meaning self-generated). +Additional words were added based on actually mistakes seen in the wild (meaning self-generated). Variations of UK and US spellings are based on many sources including: @@ -401,24 +379,23 @@ Variations of UK and US spellings are based on many sources including: * http://www.oxforddictionaries.com/us/words/american-and-british-spelling-american (excellent site but incomplete) * Diffing US and UK [scowl dictionaries](http://wordlist.aspell.net) -American English is more accepting of spelling variations than is British -English, so "what is American or not" is subject to opinion. Corrections and help welcome. +American English is more accepting of spelling variations than is British English, +so "what is American or not" is subject to opinion. +Corrections and help welcome. ### What are some other enhancements that could be done? -Here's some ideas for enhancements: +Here are some ideas for enhancements: *Capitalization of proper nouns* could be done (e.g. weekday and month names, country names, language names) -*Opinionated US spellings* US English has a number of words with alternate -spellings. Think [adviser vs. -advisor](http://grammarist.com/spelling/adviser-advisor/). While "advisor" is not wrong, the opinionated US -locale would correct "advisor" to "adviser". +*Opinionated US spellings* US English has a number of words with alternate spellings. +Think [adviser vs. advisor](http://grammarist.com/spelling/adviser-advisor/). +While "advisor" is not wrong, the opinionated US locale would correct "advisor" to "adviser". *Versioning* Some type of versioning is needed so reporting mistakes and errors is easier. -*Feedback* Mistakes would be sent to some server for agregation and feedback review. +*Feedback* Mistakes would be sent to some server for aggregation and feedback review. -*Contractions and Apostrophes* This would optionally correct "isnt" to -"isn't", etc. +*Contractions and Apostrophes* This would optionally correct "isnt" to "isn't", etc. diff --git a/tools/vendor/github.com/golangci/misspell/goreleaser.yml b/tools/vendor/github.com/golangci/misspell/goreleaser.yml index 97aa83e5a..2d2be1a75 100644 --- a/tools/vendor/github.com/golangci/misspell/goreleaser.yml +++ b/tools/vendor/github.com/golangci/misspell/goreleaser.yml @@ -15,13 +15,14 @@ builds: - CGO_ENABLED=0 archives: - - name_template: "{{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}" - replacements: - amd64: 64bit - 386: 32bit - darwin: mac - files: - - LICENSE + - format: tar.gz + wrap_in_directory: true + format_overrides: + - goos: windows + format: zip + name_template: '{{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}' + files: + - LICENSE checksum: name_template: "{{ .ProjectName }}_{{ .Version }}_checksums.txt" diff --git a/tools/vendor/github.com/golangci/misspell/install-misspell.sh b/tools/vendor/github.com/golangci/misspell/install-misspell.sh index 51e9b3372..d6023e117 100644 --- a/tools/vendor/github.com/golangci/misspell/install-misspell.sh +++ b/tools/vendor/github.com/golangci/misspell/install-misspell.sh @@ -1,39 +1,33 @@ #!/bin/sh set -e -# Code generated by godownloader. DO NOT EDIT. -# usage() { this=$1 cat <] [-d] [] -b sets bindir or installation directory, Defaults to ./bin - [tag] is a tag from + -d turns on debug logging + is a tag from https://github.com/golangci/misspell/releases - If tag is missing, then an attempt to find the latest will be found. - - Consider setting GITHUB_TOKEN to avoid triggering GitHub rate limits. - See the following for more details: - https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/ - - Generated by godownloader - https://github.com/goreleaser/godownloader + If tag is missing, then the latest will be used. EOF exit 2 } parse_args() { - #BINDIR is ./bin unless set be ENV - # over-ridden by flag below + # BINDIR is ./bin unless set be ENV + # overridden by flag below BINDIR=${BINDIR:-./bin} - while getopts "b:h?" arg; do + while getopts "b:dh?x" arg; do case "$arg" in b) BINDIR="$OPTARG" ;; + d) log_set_priority 10 ;; h | \?) usage "$0" ;; + x) set -x ;; esac done shift $((OPTIND - 1)) @@ -44,72 +38,66 @@ parse_args() { # network, either nothing will happen or will syntax error # out preventing half-done work execute() { - TMPDIR=$(mktmpdir) - log_debug "downloading tarball ${TARBALL_URL}" - http_download "${TMPDIR}/${TARBALL}" "${TARBALL_URL}" - log_debug "downloading checksum ${CHECKSUM_URL}" - http_download "${TMPDIR}/${CHECKSUM}" "${CHECKSUM_URL}" - hash_sha256_verify "${TMPDIR}/${TARBALL}" "${TMPDIR}/${CHECKSUM}" - - (cd "${TMPDIR}" && untar "${TARBALL}") - install -d "${BINDIR}" - install "${TMPDIR}/${BINARY}" "${BINDIR}/" - log_info "installed as ${BINDIR}/${BINARY}" + tmpdir=$(mktemp -d) + log_debug "downloading files into ${tmpdir}" + http_download "${tmpdir}/${TARBALL}" "${TARBALL_URL}" + http_download "${tmpdir}/${CHECKSUM}" "${CHECKSUM_URL}" + hash_sha256_verify "${tmpdir}/${TARBALL}" "${tmpdir}/${CHECKSUM}" + srcdir="${tmpdir}/${NAME}" + rm -rf "${srcdir}" + (cd "${tmpdir}" && untar "${TARBALL}") + test ! -d "${BINDIR}" && install -d "${BINDIR}" + for binexe in $BINARIES; do + if [ "$OS" = "windows" ]; then + binexe="${binexe}.exe" + fi + install "${srcdir}/${binexe}" "${BINDIR}/" + log_info "installed ${BINDIR}/${binexe}" + done + rm -rf "${tmpdir}" } -is_supported_platform() { - platform=$1 - found=1 - case "$platform" in - darwin/amd64) found=0 ;; - linux/amd64) found=0 ;; - windows/amd64) found=0 ;; - darwin/arm64) found=0 ;; - linux/arm64) found=0 ;; - esac - case "$platform" in - darwin/386) found=1 ;; - windows/386) found=1 ;; +get_binaries() { + case "$PLATFORM" in + darwin/amd64) BINARIES="misspell" ;; + darwin/arm64) BINARIES="misspell" ;; + linux/amd64) BINARIES="misspell" ;; + linux/arm64) BINARIES="misspell" ;; + windows/amd64) BINARIES="misspell" ;; + windows/arm64) BINARIES="misspell" ;; + *) + log_crit "platform $PLATFORM is not supported. Make sure this script is up-to-date and file request at https://github.com/${PREFIX}/issues/new" + exit 1 + ;; esac - return $found -} -check_platform() { - if is_supported_platform "$PLATFORM"; then - # optional logging goes here - true - else - log_crit "platform $PLATFORM is not supported. Make sure this script is up-to-date and file request at https://github.com/${PREFIX}/issues/new" - exit 1 - fi } tag_to_version() { if [ -z "${TAG}" ]; then log_info "checking GitHub for latest tag" - TAG=$(github_last_release "$OWNER/$REPO") + else + log_info "checking GitHub for tag '${TAG}'" + fi + REALTAG=$(github_release "$OWNER/$REPO" "${TAG}") && true + if test -z "$REALTAG"; then + log_crit "unable to find '${TAG}' - use 'latest' or see https://github.com/${PREFIX}/releases for details" + exit 1 fi # if version starts with 'v', remove it + TAG="$REALTAG" VERSION=${TAG#v} } adjust_format() { - # change format (tar.gz or zip) based on ARCH + # change format (tar.gz or zip) based on OS + case ${OS} in + windows) FORMAT=zip ;; + esac true } adjust_os() { # adjust archive name based on OS - case ${OS} in - 386) OS=32bit ;; - amd64) OS=amd64 ;; - arm64) OS=64bit ;; - darwin) OS=mac ;; - esac true } adjust_arch() { # adjust archive name based on ARCH - case ${ARCH} in - 386) ARCH=32bit ;; - amd64) ARCH=64bit ;; - darwin) ARCH=mac ;; - esac true } @@ -127,9 +115,6 @@ is_command() { echoerr() { echo "$@" 1>&2 } -log_prefix() { - echo "$0" -} _logp=6 log_set_priority() { _logp="$1" @@ -139,24 +124,45 @@ log_priority() { echo "$_logp" return fi - [ "$1" -ge "$_logp" ] + [ "$1" -le "$_logp" ] +} +log_tag() { + case $1 in + 0) echo "emerg" ;; + 1) echo "alert" ;; + 2) echo "crit" ;; + 3) echo "err" ;; + 4) echo "warning" ;; + 5) echo "notice" ;; + 6) echo "info" ;; + 7) echo "debug" ;; + *) echo "$1" ;; + esac } log_debug() { - log_priority 7 && echoerr "$(log_prefix)" "DEBUG" "$@" + log_priority 7 || return 0 + echoerr "$(log_prefix)" "$(log_tag 7)" "$@" } log_info() { - log_priority 6 && echoerr "$(log_prefix)" "INFO" "$@" + log_priority 6 || return 0 + echoerr "$(log_prefix)" "$(log_tag 6)" "$@" } log_err() { - log_priority 3 && echoerr "$(log_prefix)" "ERR" "$@" + log_priority 3 || return 0 + echoerr "$(log_prefix)" "$(log_tag 3)" "$@" } log_crit() { - log_priority 2 && echoerr "$(log_prefix)" "CRIT" "$@" + log_priority 2 || return 0 + echoerr "$(log_prefix)" "$(log_tag 2)" "$@" } uname_os() { os=$(uname -s | tr '[:upper:]' '[:lower:]') case "$os" in - msys_nt) os="windows" ;; + msys*) os="windows" ;; + mingw*) os="windows" ;; + cygwin*) os="windows" ;; + win*) os="windows" ;; + sunos) [ "$(uname -o)" = "illumos" ] && os=illumos ;; esac echo "$os" } @@ -167,12 +173,14 @@ uname_arch() { x86) arch="386" ;; i686) arch="386" ;; i386) arch="386" ;; + i86pc) arch="amd64" ;; aarch64) arch="arm64" ;; - armv5*) arch="arm5" ;; - armv6*) arch="arm6" ;; - armv7*) arch="arm7" ;; + armv5*) arch="armv5" ;; + armv6*) arch="armv6" ;; + armv7*) arch="armv7" ;; + loongarch64) arch="loong64" ;; esac - echo ${arch} + echo "${arch}" } uname_os_check() { os=$(uname_os) @@ -180,6 +188,7 @@ uname_os_check() { darwin) return 0 ;; dragonfly) return 0 ;; freebsd) return 0 ;; + illumos) return 0;; linux) return 0 ;; android) return 0 ;; nacl) return 0 ;; @@ -189,7 +198,7 @@ uname_os_check() { solaris) return 0 ;; windows) return 0 ;; esac - log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib" + log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value." return 1 } uname_arch_check() { @@ -208,16 +217,18 @@ uname_arch_check() { mips64) return 0 ;; mips64le) return 0 ;; s390x) return 0 ;; + riscv64) return 0 ;; amd64p32) return 0 ;; + loong64) return 0 ;; esac - log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib" + log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value." return 1 } untar() { tarball=$1 case "${tarball}" in - *.tar.gz | *.tgz) tar -xzf "${tarball}" ;; - *.tar) tar -xf "${tarball}" ;; + *.tar.gz | *.tgz) tar --no-same-owner -xzf "${tarball}" ;; + *.tar) tar --no-same-owner -xf "${tarball}" ;; *.zip) unzip "${tarball}" ;; *) log_err "untar unknown archive format for ${tarball}" @@ -225,52 +236,57 @@ untar() { ;; esac } -mktmpdir() { - test -z "$TMPDIR" && TMPDIR="$(mktemp -d)" - mkdir -p "${TMPDIR}" - echo "${TMPDIR}" -} -http_download() { +http_download_curl() { local_file=$1 source_url=$2 header=$3 - headerflag='' - destflag='' - if is_command curl; then - cmd='curl --fail -sSL' - destflag='-o' - headerflag='-H' - elif is_command wget; then - cmd='wget -q' - destflag='-O' - headerflag='--header' + if [ -z "$header" ]; then + code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url") else - log_crit "http_download unable to find wget or curl" + code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url") + fi + if [ "$code" != "200" ]; then + log_debug "http_download_curl received HTTP status $code" return 1 fi + return 0 +} +http_download_wget() { + local_file=$1 + source_url=$2 + header=$3 if [ -z "$header" ]; then - $cmd $destflag "$local_file" "$source_url" + wget -q -O "$local_file" "$source_url" else - $cmd $headerflag "$header" $destflag "$local_file" "$source_url" + wget -q --header "$header" -O "$local_file" "$source_url" fi } -github_api() { - local_file=$1 - source_url=$2 - header="" - case "$source_url" in - https://api.github.com*) - test -z "$GITHUB_TOKEN" || header="Authorization: token $GITHUB_TOKEN" - ;; - esac - http_download "$local_file" "$source_url" "$header" +http_download() { + log_debug "http_download $2" + if is_command curl; then + http_download_curl "$@" + return + elif is_command wget; then + http_download_wget "$@" + return + fi + log_crit "http_download unable to find wget or curl" + return 1 } -github_last_release() { +http_copy() { + tmp=$(mktemp) + http_download "${tmp}" "$1" "$2" || return 1 + body=$(cat "$tmp") + rm -f "${tmp}" + echo "$body" +} +github_release() { owner_repo=$1 version=$2 test -z "$version" && version="latest" giturl="https://github.com/${owner_repo}/releases/${version}" - json=$(http_download "-" "$giturl" "Accept:application/json") + json=$(http_copy "$giturl" "Accept:application/json") + test -z "$json" && return 1 version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//') test -z "$version" && return 1 echo "$version" @@ -319,6 +335,7 @@ End of functions from https://github.com/client9/shlib ------------------------------------------------------------------------ EOF +PROJECT_NAME="misspell" OWNER=golangci REPO="misspell" BINARY=misspell @@ -339,7 +356,7 @@ uname_arch_check "$ARCH" parse_args "$@" -check_platform +get_binaries tag_to_version @@ -357,9 +374,4 @@ TARBALL_URL=${GITHUB_DOWNLOAD}/${TAG}/${TARBALL} CHECKSUM=${BINARY}_${VERSION}_checksums.txt CHECKSUM_URL=${GITHUB_DOWNLOAD}/${TAG}/${CHECKSUM} -# Adjust binary name if windows -if [ "$OS" = "windows" ]; then - BINARY="${BINARY}.exe" -fi - execute diff --git a/tools/vendor/github.com/golangci/misspell/mime.go b/tools/vendor/github.com/golangci/misspell/mime.go index 76a96cfd1..19d49e085 100644 --- a/tools/vendor/github.com/golangci/misspell/mime.go +++ b/tools/vendor/github.com/golangci/misspell/mime.go @@ -7,6 +7,7 @@ import ( "net/http" "os" "path/filepath" + "slices" "strings" ) @@ -77,13 +78,12 @@ func isSCMPath(s string) bool { if strings.Contains(filepath.Base(s), "EDITMSG") { return false } + parts := strings.Split(filepath.Clean(s), string(filepath.Separator)) - for _, dir := range parts { - if scm[dir] { - return true - } - } - return false + + return slices.ContainsFunc(parts, func(dir string) bool { + return scm[dir] + }) } var magicHeaders = [][]byte{ @@ -174,7 +174,8 @@ func ReadTextFile(filename string) (string, error) { // if not-text, then exit isText := false if fstat.Size() > 50000 { - fin, err := os.Open(filename) + var fin *os.File + fin, err = os.Open(filename) if err != nil { return "", fmt.Errorf("unable to open large file %q: %w", filename, err) } diff --git a/tools/vendor/github.com/golangci/misspell/notwords.go b/tools/vendor/github.com/golangci/misspell/notwords.go index a250cf7f6..f694f46dc 100644 --- a/tools/vendor/github.com/golangci/misspell/notwords.go +++ b/tools/vendor/github.com/golangci/misspell/notwords.go @@ -4,12 +4,17 @@ import ( "bytes" "regexp" "strings" + "unicode" ) var ( - reEmail = regexp.MustCompile(`[a-zA-Z0-9_.%+-]+@[a-zA-Z0-9-.]+\.[a-zA-Z]{2,6}[^a-zA-Z]`) - reHost = regexp.MustCompile(`[a-zA-Z0-9-.]+\.[a-zA-Z]+`) - reBackslash = regexp.MustCompile(`\\[a-z]`) + reEmail = regexp.MustCompile(`[[:alnum:]_.%+-]+@[[:alnum:]-.]+\.[[:alpha:]]{2,6}[^[:alpha:]]`) + reBackslash = regexp.MustCompile(`\\[[:lower:]]`) + + // reHost Host name regular expression. + // The length of any one label is limited between 1 and 63 octets. (https://www.ietf.org/rfc/rfc2181.txt) + // A TLD has at least 2 letters. + reHost = regexp.MustCompile(`([[:alnum:]-]+\.)+[[:alpha:]]{2,63}`) ) // RemovePath attempts to strip away embedded file system paths, e.g. @@ -20,7 +25,7 @@ var ( func RemovePath(s string) string { out := bytes.Buffer{} var idx int - for len(s) > 0 { + for s != "" { if idx = strings.IndexByte(s, '/'); idx == -1 { out.WriteString(s) break @@ -62,6 +67,18 @@ func replaceWithBlanks(s string) string { return strings.Repeat(" ", len(s)) } +// replaceHost same as replaceWithBlanks but if the string contains at least one uppercase letter returns the string. +// Domain names are case-insensitive but browsers and DNS convert uppercase to lower case. (https://www.ietf.org/rfc/rfc4343.txt) +func replaceHost(s string) string { + for _, r := range s { + if unicode.IsUpper(r) { + return s + } + } + + return replaceWithBlanks(s) +} + // RemoveEmail remove email-like strings, e.g. "nickg+junk@xfoobar.com", "nickg@xyz.abc123.biz". func RemoveEmail(s string) string { return reEmail.ReplaceAllStringFunc(s, replaceWithBlanks) @@ -69,7 +86,7 @@ func RemoveEmail(s string) string { // RemoveHost removes host-like strings "foobar.com" "abc123.fo1231.biz". func RemoveHost(s string) string { - return reHost.ReplaceAllStringFunc(s, replaceWithBlanks) + return reHost.ReplaceAllStringFunc(s, replaceHost) } // RemoveBackslashEscapes removes characters that are preceded by a backslash. diff --git a/tools/vendor/github.com/golangci/misspell/replace.go b/tools/vendor/github.com/golangci/misspell/replace.go index bcfcf8deb..b51dfa83b 100644 --- a/tools/vendor/github.com/golangci/misspell/replace.go +++ b/tools/vendor/github.com/golangci/misspell/replace.go @@ -5,6 +5,7 @@ import ( "bytes" "io" "regexp" + "slices" "strings" "text/scanner" ) @@ -17,12 +18,9 @@ func max(x, y int) int { } func inArray(haystack []string, needle string) bool { - for _, word := range haystack { - if strings.EqualFold(needle, word) { - return true - } - } - return false + return slices.ContainsFunc(haystack, func(word string) bool { + return strings.EqualFold(needle, word) + }) } var wordRegexp = regexp.MustCompile(`[a-zA-Z0-9']+`) @@ -192,7 +190,7 @@ Loop: return buf.String(), diffs } -// Replace is corrects misspellings in input, returning corrected version along with a list of diffs. +// Replace is correcting misspellings in input, returning corrected version along with a list of diffs. func (r *Replacer) Replace(input string) (string, []Diff) { output := r.engine.Replace(input) if input == output { diff --git a/tools/vendor/github.com/golangci/misspell/stringreplacer.go b/tools/vendor/github.com/golangci/misspell/stringreplacer.go index 73ca9a56a..46cb6c4b6 100644 --- a/tools/vendor/github.com/golangci/misspell/stringreplacer.go +++ b/tools/vendor/github.com/golangci/misspell/stringreplacer.go @@ -102,7 +102,6 @@ func (t *trieNode) add(key, val string, priority int, r *genericReplacer) { return } - //nolint:nestif // TODO(ldez) must be fixed. if t.prefix != "" { // Need to split the prefix among multiple nodes. var n int // length of the longest common prefix @@ -111,9 +110,10 @@ func (t *trieNode) add(key, val string, priority int, r *genericReplacer) { break } } - if n == len(t.prefix) { + switch n { + case len(t.prefix): t.next.add(key[n:], val, priority, r) - } else if n == 0 { + case 0: // First byte differs, start a new lookup table here. Looking up // what is currently t.prefix[0] will lead to prefixNode, and // looking up key[0] will lead to keyNode. @@ -133,7 +133,7 @@ func (t *trieNode) add(key, val string, priority int, r *genericReplacer) { t.prefix = "" t.next = nil keyNode.add(key[1:], val, priority, r) - } else { + default: // Insert new node after the common section of the prefix. next := &trieNode{ prefix: t.prefix[n:], @@ -143,18 +143,22 @@ func (t *trieNode) add(key, val string, priority int, r *genericReplacer) { t.next = next next.add(key[n:], val, priority, r) } - } else if t.table != nil { + return + } + + if t.table != nil { // Insert into existing table. m := r.mapping[key[0]] if t.table[m] == nil { t.table[m] = new(trieNode) } t.table[m].add(key[1:], val, priority, r) - } else { - t.prefix = key - t.next = new(trieNode) - t.next.add("", val, priority, r) + return } + + t.prefix = key + t.next = new(trieNode) + t.next.add("", val, priority, r) } // genericReplacer is the fully generic algorithm. @@ -242,7 +246,6 @@ func (r *genericReplacer) Replace(s string) string { return string(buf) } -//nolint:gocognit // TODO(ldez) must be fixed. func (r *genericReplacer) WriteString(w io.Writer, s string) (n int, err error) { sw := getStringWriter(w) var last, wn int diff --git a/tools/vendor/github.com/golangci/misspell/url.go b/tools/vendor/github.com/golangci/misspell/url.go index 203b91a79..a91d1d967 100644 --- a/tools/vendor/github.com/golangci/misspell/url.go +++ b/tools/vendor/github.com/golangci/misspell/url.go @@ -10,7 +10,7 @@ import ( // @(https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?$@iS. var reURL = regexp.MustCompile(`(?i)(https?|ftp)://(-\.)?([^\s/?.#]+\.?)+(/\S*)?`) -// StripURL attemps to replace URLs with blank spaces, e.g. +// StripURL attempts to replace URLs with blank spaces, e.g. // // "xxx http://foo.com/ yyy -> "xxx yyyy". func StripURL(s string) string { diff --git a/tools/vendor/github.com/golangci/modinfo/.gitignore b/tools/vendor/github.com/golangci/modinfo/.gitignore new file mode 100644 index 000000000..9f11b755a --- /dev/null +++ b/tools/vendor/github.com/golangci/modinfo/.gitignore @@ -0,0 +1 @@ +.idea/ diff --git a/tools/vendor/github.com/golangci/modinfo/.golangci.yml b/tools/vendor/github.com/golangci/modinfo/.golangci.yml new file mode 100644 index 000000000..9698182f2 --- /dev/null +++ b/tools/vendor/github.com/golangci/modinfo/.golangci.yml @@ -0,0 +1,157 @@ +run: + timeout: 7m + +linters-settings: + govet: + enable: + - shadow + gocyclo: + min-complexity: 12 + goconst: + min-len: 3 + min-occurrences: 3 + funlen: + lines: -1 + statements: 50 + misspell: + locale: US + depguard: + rules: + main: + deny: + - pkg: "github.com/instana/testify" + desc: not allowed + - pkg: "github.com/pkg/errors" + desc: Should be replaced by standard lib errors package + tagalign: + align: false + order: + - xml + - json + - yaml + - yml + - toml + - mapstructure + - url + godox: + keywords: + - FIXME + gocritic: + enabled-tags: + - diagnostic + - style + - performance + disabled-checks: + - paramTypeCombine # already handle by gofumpt.extra-rules + - whyNoLint # already handle by nonolint + - unnamedResult + - hugeParam + - sloppyReassign + - rangeValCopy + - octalLiteral + - ptrToRefParam + - appendAssign + - ruleguard + - httpNoBody + - exposedSyncMutex + revive: + rules: + - name: struct-tag + - name: blank-imports + - name: context-as-argument + - name: context-keys-type + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: exported + disabled: true + - name: if-return + - name: increment-decrement + - name: var-naming + - name: var-declaration + - name: package-comments + disabled: true + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf + - name: empty-block + - name: superfluous-else + - name: unused-parameter + disabled: true + - name: unreachable-code + - name: redefines-builtin-id + + tagliatelle: + case: + rules: + json: pascal + yaml: camel + xml: camel + header: header + mapstructure: camel + env: upperSnake + envconfig: upperSnake + +linters: + enable-all: true + disable: + - deadcode # deprecated + - exhaustivestruct # deprecated + - golint # deprecated + - ifshort # deprecated + - interfacer # deprecated + - maligned # deprecated + - nosnakecase # deprecated + - scopelint # deprecated + - structcheck # deprecated + - varcheck # deprecated + - cyclop # duplicate of gocyclo + - sqlclosecheck # not relevant (SQL) + - rowserrcheck # not relevant (SQL) + - execinquery # not relevant (SQL) + - lll + - gosec + - dupl # not relevant + - prealloc # too many false-positive + - bodyclose # too many false-positive + - gomnd + - testpackage # not relevant + - tparallel # not relevant + - paralleltest # not relevant + - nestif # too many false-positive + - wrapcheck + - goerr113 # not relevant + - nlreturn # not relevant + - wsl # not relevant + - exhaustive # not relevant + - exhaustruct # not relevant + - makezero # not relevant + - forbidigo + - varnamelen # not relevant + - nilnil # not relevant + - ireturn # not relevant + - contextcheck # too many false-positive + - tenv # we already have a test "framework" to handle env vars + - noctx + - errchkjson + - nonamedreturns + - gosmopolitan # not relevant + - gochecknoglobals + +issues: + exclude-use-default: false + max-issues-per-linter: 0 + max-same-issues: 0 + exclude: + - 'Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*printf?|os\.(Un)?Setenv). is not checked' + - 'ST1000: at least one file in a package should have a package comment' + exclude-rules: + - path: (.+)_test.go + linters: + - funlen + - goconst + - maintidx diff --git a/tools/vendor/github.com/golangci/modinfo/LICENSE b/tools/vendor/github.com/golangci/modinfo/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/tools/vendor/github.com/golangci/modinfo/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/tools/vendor/github.com/golangci/modinfo/Makefile b/tools/vendor/github.com/golangci/modinfo/Makefile new file mode 100644 index 000000000..df91018f1 --- /dev/null +++ b/tools/vendor/github.com/golangci/modinfo/Makefile @@ -0,0 +1,12 @@ +.PHONY: clean check test + +default: clean check test + +clean: + rm -rf dist/ cover.out + +test: clean + go test -v -cover ./... + +check: + golangci-lint run diff --git a/tools/vendor/github.com/golangci/modinfo/module.go b/tools/vendor/github.com/golangci/modinfo/module.go new file mode 100644 index 000000000..ff0b21b9b --- /dev/null +++ b/tools/vendor/github.com/golangci/modinfo/module.go @@ -0,0 +1,157 @@ +package modinfo + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "reflect" + "sort" + "strings" + "sync" + + "golang.org/x/mod/modfile" + "golang.org/x/tools/go/analysis" +) + +type ModInfo struct { + Path string `json:"Path"` + Dir string `json:"Dir"` + GoMod string `json:"GoMod"` + GoVersion string `json:"GoVersion"` + Main bool `json:"Main"` +} + +var ( + once sync.Once + information []ModInfo + errInfo error +) + +var Analyzer = &analysis.Analyzer{ + Name: "modinfo", + Doc: "Module information", + URL: "https://github.com/golangci/modinfo", + Run: runOnce, + ResultType: reflect.TypeOf([]ModInfo(nil)), +} + +func runOnce(pass *analysis.Pass) (any, error) { + _, ok := os.LookupEnv("MODINFO_DEBUG_DISABLE_ONCE") + if ok { + return GetModuleInfo(pass) + } + + once.Do(func() { + information, errInfo = GetModuleInfo(pass) + }) + + return information, errInfo +} + +// GetModuleInfo gets modules information. +// Always returns 1 element except for workspace (returns all the modules of the workspace). +// Based on `go list -m -json` behavior. +func GetModuleInfo(pass *analysis.Pass) ([]ModInfo, error) { + // https://github.com/golang/go/issues/44753#issuecomment-790089020 + cmd := exec.Command("go", "list", "-m", "-json") + for _, file := range pass.Files { + name := pass.Fset.File(file.Pos()).Name() + if filepath.Ext(name) != ".go" { + continue + } + + cmd.Dir = filepath.Dir(name) + break + } + + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("command go list: %w: %s", err, string(out)) + } + + var infos []ModInfo + + for dec := json.NewDecoder(bytes.NewBuffer(out)); dec.More(); { + var v ModInfo + if err := dec.Decode(&v); err != nil { + return nil, fmt.Errorf("unmarshaling error: %w: %s", err, string(out)) + } + + if v.GoMod == "" { + return nil, errors.New("working directory is not part of a module") + } + + if !v.Main || v.Dir == "" { + continue + } + + infos = append(infos, v) + } + + if len(infos) == 0 { + return nil, errors.New("go.mod file not found") + } + + sort.Slice(infos, func(i, j int) bool { + return len(infos[i].Path) > len(infos[j].Path) + }) + + return infos, nil +} + +// FindModuleFromPass finds the module related to the files of the pass. +func FindModuleFromPass(pass *analysis.Pass) (ModInfo, error) { + infos, ok := pass.ResultOf[Analyzer].([]ModInfo) + if !ok { + return ModInfo{}, errors.New("no modinfo analyzer result") + } + + var name string + for _, file := range pass.Files { + f := pass.Fset.File(file.Pos()).Name() + if filepath.Ext(f) != ".go" { + continue + } + + name = f + break + } + + // no Go file found in analysis pass + if name == "" { + name, _ = os.Getwd() + } + + for _, info := range infos { + if !strings.HasPrefix(name, info.Dir) { + continue + } + return info, nil + } + + return ModInfo{}, errors.New("module information not found") +} + +// ReadModuleFileFromPass read the `go.mod` file from the pass result. +func ReadModuleFileFromPass(pass *analysis.Pass) (*modfile.File, error) { + info, err := FindModuleFromPass(pass) + if err != nil { + return nil, err + } + + return ReadModuleFile(info) +} + +// ReadModuleFile read the `go.mod` file. +func ReadModuleFile(info ModInfo) (*modfile.File, error) { + raw, err := os.ReadFile(info.GoMod) + if err != nil { + return nil, fmt.Errorf("reading go.mod file: %w", err) + } + + return modfile.Parse("go.mod", raw, nil) +} diff --git a/tools/vendor/github.com/golangci/modinfo/readme.md b/tools/vendor/github.com/golangci/modinfo/readme.md new file mode 100644 index 000000000..2175de8eb --- /dev/null +++ b/tools/vendor/github.com/golangci/modinfo/readme.md @@ -0,0 +1,73 @@ +# modinfo + +This module contains: +- an analyzer that returns module information. +- methods to find and read `go.mod` file + +## Examples + +```go +package main + +import ( + "fmt" + + "github.com/golangci/modinfo" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var Analyzer = &analysis.Analyzer{ + Name: "example", + Doc: "Example", + Run: func(pass *analysis.Pass) (interface{}, error) { + file, err := modinfo.ReadModuleFileFromPass(pass) + if err != nil { + return nil, err + } + + fmt.Println("go.mod", file) + + // TODO + + return nil, nil + }, + Requires: []*analysis.Analyzer{ + inspect.Analyzer, + modinfo.Analyzer, + }, +} +``` + +```go +package main + +import ( + "fmt" + + "github.com/golangci/modinfo" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var Analyzer = &analysis.Analyzer{ + Name: "example", + Doc: "Example", + Run: func(pass *analysis.Pass) (interface{}, error) { + info, err := modinfo.FindModuleFromPass(pass) + if err != nil { + return nil, err + } + + fmt.Println("Module", info.Dir) + + // TODO + + return nil, nil + }, + Requires: []*analysis.Analyzer{ + inspect.Analyzer, + modinfo.Analyzer, + }, +} +``` diff --git a/tools/vendor/github.com/golangci/check/LICENSE b/tools/vendor/github.com/golangci/plugin-module-register/LICENSE similarity index 98% rename from tools/vendor/github.com/golangci/check/LICENSE rename to tools/vendor/github.com/golangci/plugin-module-register/LICENSE index 5a1774b8e..e72bfddab 100644 --- a/tools/vendor/github.com/golangci/check/LICENSE +++ b/tools/vendor/github.com/golangci/plugin-module-register/LICENSE @@ -1,7 +1,7 @@ -GNU GENERAL PUBLIC LICENSE + GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. {http://fsf.org/} + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @@ -631,8 +631,8 @@ to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. - {one line to give the program's name and a brief idea of what it does.} - Copyright (C) {year} {name of author} + + Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -645,14 +645,14 @@ the "copyright" line and a pointer to where the full notice is found. GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program. If not, see {http://www.gnu.org/licenses/}. + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: - opennota Copyright (C) 2013 opennota + Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. @@ -664,11 +664,11 @@ might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see -{http://www.gnu.org/licenses/}. +. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read -{http://www.gnu.org/philosophy/why-not-lgpl.html}. +. \ No newline at end of file diff --git a/tools/vendor/github.com/golangci/plugin-module-register/register/register.go b/tools/vendor/github.com/golangci/plugin-module-register/register/register.go new file mode 100644 index 000000000..72ad7f46f --- /dev/null +++ b/tools/vendor/github.com/golangci/plugin-module-register/register/register.go @@ -0,0 +1,73 @@ +package register + +import ( + "bytes" + "encoding/json" + "fmt" + "sync" + + "golang.org/x/tools/go/analysis" +) + +// Plugins load mode. +const ( + LoadModeSyntax = "syntax" + LoadModeTypesInfo = "typesinfo" +) + +var ( + pluginsMu sync.RWMutex + plugins = make(map[string]NewPlugin) +) + +// LinterPlugin the interface of the plugin structure. +type LinterPlugin interface { + BuildAnalyzers() ([]*analysis.Analyzer, error) + GetLoadMode() string +} + +// NewPlugin the contract of the constructor of a plugin. +type NewPlugin func(conf any) (LinterPlugin, error) + +// Plugin registers a plugin. +func Plugin(name string, p NewPlugin) { + pluginsMu.Lock() + + plugins[name] = p + + pluginsMu.Unlock() +} + +// GetPlugin gets a plugin by name. +func GetPlugin(name string) (NewPlugin, error) { + pluginsMu.Lock() + defer pluginsMu.Unlock() + + p, ok := plugins[name] + if !ok { + return nil, fmt.Errorf("plugin %q not found", name) + } + + return p, nil +} + +// DecodeSettings decode settings from golangci-lint to the structure of the plugin configuration. +func DecodeSettings[T any](rawSettings any) (T, error) { + var buffer bytes.Buffer + + if err := json.NewEncoder(&buffer).Encode(rawSettings); err != nil { + var zero T + return zero, fmt.Errorf("encoding settings: %w", err) + } + + decoder := json.NewDecoder(&buffer) + decoder.DisallowUnknownFields() + + s := new(T) + if err := decoder.Decode(s); err != nil { + var zero T + return zero, fmt.Errorf("decoding settings: %w", err) + } + + return *s, nil +} diff --git a/tools/vendor/github.com/golangci/revgrep/.golangci.yml b/tools/vendor/github.com/golangci/revgrep/.golangci.yml index 02ed5ec84..5239720ac 100644 --- a/tools/vendor/github.com/golangci/revgrep/.golangci.yml +++ b/tools/vendor/github.com/golangci/revgrep/.golangci.yml @@ -3,7 +3,6 @@ run: linters-settings: govet: - check-shadowing: true enable-all: true disable: - fieldalignment @@ -47,7 +46,6 @@ linters: - nestif - gomnd - goerr113 -# - wrapcheck - nlreturn - wsl - exhaustive @@ -66,7 +64,7 @@ linters: issues: exclude-use-default: false - max-per-linter: 0 + max-issues-per-linter: 0 max-same-issues: 0 exclude: - 'ST1000: at least one file in a package should have a package comment' diff --git a/tools/vendor/github.com/golangci/revgrep/revgrep.go b/tools/vendor/github.com/golangci/revgrep/revgrep.go index 7796b1c01..1ef81b203 100644 --- a/tools/vendor/github.com/golangci/revgrep/revgrep.go +++ b/tools/vendor/github.com/golangci/revgrep/revgrep.go @@ -334,10 +334,13 @@ func (c *Checker) linesChanged() map[string][]pos { return changes } -// GitPatch returns a patch from a git repository, -// if no git repository was found and no errors occurred, nil is returned, else an error is returned revisionFrom and revisionTo defines the git diff parameters, -// if left blank and there are unstaged changes or untracked files, only those will be returned else only check changes since HEAD~. -// If revisionFrom is set but revisionTo is not, untracked files will be included, to exclude untracked files set revisionTo to HEAD~. +// GitPatch returns a patch from a git repository. +// If no git repository was found and no errors occurred, nil is returned, +// else an error is returned revisionFrom and revisionTo defines the git diff parameters, +// if left blank and there are unstaged changes or untracked files, +// only those will be returned else only check changes since HEAD~. +// If revisionFrom is set but revisionTo is not, +// untracked files will be included, to exclude untracked files set revisionTo to HEAD~. // It's incorrect to specify revisionTo without a revisionFrom. func GitPatch(revisionFrom, revisionTo string) (io.Reader, []string, error) { // check if git repo exists @@ -356,59 +359,59 @@ func GitPatch(revisionFrom, revisionTo string) (io.Reader, []string, error) { for _, file := range bytes.Split(ls, []byte{'\n'}) { if len(file) == 0 || bytes.HasSuffix(file, []byte{'/'}) { // ls-files was sometimes showing directories when they were ignored - // I couldn't create a test case for this as I couldn't reproduce correctly - // for the moment, just exclude files with trailing / + // I couldn't create a test case for this as I couldn't reproduce correctly for the moment, + // just exclude files with trailing / continue } + newFiles = append(newFiles, string(file)) } - var patch bytes.Buffer if revisionFrom != "" { - cmd := gitDiff(revisionFrom) + args := []string{revisionFrom} + if revisionTo != "" { - cmd.Args = append(cmd.Args, revisionTo) + args = append(args, revisionTo) } - cmd.Args = append(cmd.Args, "--") - cmd.Stdout = &patch - if err := cmd.Run(); err != nil { - return nil, nil, fmt.Errorf("error executing git diff %q %q: %w", revisionFrom, revisionTo, err) + args = append(args, "--") + + patch, errDiff := gitDiff(args...) + if errDiff != nil { + return nil, nil, errDiff } if revisionTo == "" { - return &patch, newFiles, nil + return patch, newFiles, nil } - return &patch, nil, nil + return patch, nil, nil } // make a patch for unstaged changes - cmd := gitDiff("--") - cmd.Stdout = &patch - if err := cmd.Run(); err != nil { - return nil, nil, fmt.Errorf("error executing git diff: %w", err) + patch, err := gitDiff("--") + if err != nil { + return nil, nil, err } + unstaged := patch.Len() > 0 - // If there's unstaged changes OR untracked changes (or both), then this is - // a suitable patch + // If there's unstaged changes OR untracked changes (or both), + // then this is a suitable patch if unstaged || newFiles != nil { - return &patch, newFiles, nil + return patch, newFiles, nil } // check for changes in recent commit - - cmd = gitDiff("HEAD~", "--") - cmd.Stdout = &patch - if err := cmd.Run(); err != nil { - return nil, nil, fmt.Errorf("error executing git diff HEAD~: %w", err) + patch, err = gitDiff("HEAD~", "--") + if err != nil { + return nil, nil, err } - return &patch, nil, nil + return patch, nil, nil } -func gitDiff(extraArgs ...string) *exec.Cmd { +func gitDiff(extraArgs ...string) (*bytes.Buffer, error) { cmd := exec.Command("git", "diff", "--color=never", "--no-ext-diff") if isSupportedByGit(2, 41, 0) { @@ -418,7 +421,26 @@ func gitDiff(extraArgs ...string) *exec.Cmd { cmd.Args = append(cmd.Args, "--relative") cmd.Args = append(cmd.Args, extraArgs...) - return cmd + patch := new(bytes.Buffer) + errBuff := new(bytes.Buffer) + + cmd.Stdout = patch + cmd.Stderr = errBuff + + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("error executing %q: %w: %w", strings.Join(cmd.Args, " "), err, readAsError(errBuff)) + } + + return patch, nil +} + +func readAsError(buff io.Reader) error { + output, err := io.ReadAll(buff) + if err != nil { + return fmt.Errorf("read stderr: %w", err) + } + + return errors.New(string(output)) } func isSupportedByGit(major, minor, patch int) bool { diff --git a/tools/vendor/github.com/golangci/unconvert/README b/tools/vendor/github.com/golangci/unconvert/README deleted file mode 100644 index dbaea4f57..000000000 --- a/tools/vendor/github.com/golangci/unconvert/README +++ /dev/null @@ -1,36 +0,0 @@ -About: - -The unconvert program analyzes Go packages to identify unnecessary -type conversions; i.e., expressions T(x) where x already has type T. - -Install: - - $ go get github.com/mdempsky/unconvert - -Usage: - - $ unconvert -v bytes fmt - GOROOT/src/bytes/reader.go:117:14: unnecessary conversion - abs = int64(r.i) + offset - ^ - GOROOT/src/fmt/print.go:411:21: unnecessary conversion - p.fmt.integer(int64(v), 16, unsigned, udigits) - ^ - -Flags: - -Using the -v flag, unconvert will also print the source line and a -caret to indicate the unnecessary conversion's position therein. - -Using the -apply flag, unconvert will rewrite the Go source files -without the unnecessary type conversions. - -Using the -all flag, unconvert will analyze the Go packages under all -possible GOOS/GOARCH combinations, and only identify conversions that -are unnecessary in all cases. - -E.g., syscall.Timespec's Sec and Nsec fields are int64 under -linux/amd64 but int32 under linux/386. An int64(ts.Sec) conversion -that appears in a linux/amd64-only file will be identified as -unnecessary, but it will be preserved if it occurs in a file that's -compiled for both linux/amd64 and linux/386. diff --git a/tools/vendor/github.com/golangci/unconvert/README.md b/tools/vendor/github.com/golangci/unconvert/README.md new file mode 100644 index 000000000..e9230c218 --- /dev/null +++ b/tools/vendor/github.com/golangci/unconvert/README.md @@ -0,0 +1,6 @@ +Fork of [unconvert](https://github.com/mdempsky/unconvert) to be usable as a library. + +The specific elements are inside the file `golangci.go`. + +The only modification of the file `unconvert.go` is the remove of the global variables for the flags. +The tests will never work because of that, then the CI is disabled. diff --git a/tools/vendor/github.com/golangci/unconvert/golangci.go b/tools/vendor/github.com/golangci/unconvert/golangci.go new file mode 100644 index 000000000..306c44e5e --- /dev/null +++ b/tools/vendor/github.com/golangci/unconvert/golangci.go @@ -0,0 +1,78 @@ +package unconvert + +import ( + "go/ast" + "go/token" + "strings" + "sync" + + "golang.org/x/tools/go/analysis" +) + +// Transformed version of the original unconvert flags section. +// The section has been removed inside `unconvert.go` +var ( + flagAll = pointer(false) + flagApply = pointer(false) + flagCPUProfile = pointer("") + flagSafe = pointer(false) + flagV = pointer(false) + flagTests = pointer(true) + flagFastMath = pointer(false) + flagTags = pointer("") + flagConfigs = pointer("") +) + +func pointer[T string | int | int32 | int64 | bool](v T) *T { return &v } + +func Run(pass *analysis.Pass, fastMath, safe bool) []token.Position { + type res struct { + file string + edits editSet + } + + flagFastMath = pointer(fastMath) + flagSafe = pointer(safe) + + ch := make(chan res) + var wg sync.WaitGroup + for _, file := range pass.Files { + file := file + + tokenFile := pass.Fset.File(file.Package) + filename := tokenFile.Position(file.Package).Filename + + // Hack to recognize _cgo_gotypes.go. + if strings.HasSuffix(filename, "-d") || strings.HasSuffix(filename, "/_cgo_gotypes.go") { + continue + } + + wg.Add(1) + go func() { + defer wg.Done() + + v := visitor{info: pass.TypesInfo, file: tokenFile, edits: make(editSet)} + ast.Walk(&v, file) + + ch <- res{filename, v.edits} + }() + } + go func() { + wg.Wait() + close(ch) + }() + + m := make(fileToEditSet) + for r := range ch { + m[r.file] = r.edits + } + + var positions []token.Position + for _, edit := range m { + for position, _ := range edit { + positions = append(positions, position) + } + } + + return positions +} diff --git a/tools/vendor/github.com/golangci/unconvert/unconvert.go b/tools/vendor/github.com/golangci/unconvert/unconvert.go index 38737d39f..222aeadf8 100644 --- a/tools/vendor/github.com/golangci/unconvert/unconvert.go +++ b/tools/vendor/github.com/golangci/unconvert/unconvert.go @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Unconvert removes redundant type conversions from Go packages. +// Package unconvert Unconvert removes redundant type conversions from Go packages. package unconvert import ( "bytes" + "encoding/json" "flag" "fmt" "go/ast" - "go/build" "go/format" "go/parser" "go/token" @@ -18,15 +18,16 @@ import ( "io/ioutil" "log" "os" + "os/exec" "reflect" "runtime/pprof" "sort" + "strings" "sync" "unicode" - "github.com/kisielk/gotool" "golang.org/x/text/width" - "golang.org/x/tools/go/loader" + "golang.org/x/tools/go/packages" ) // Unnecessary conversions are identified by the position @@ -34,6 +35,31 @@ import ( type editSet map[token.Position]struct{} +func (e editSet) add(pos token.Position) { + pos.Offset = 0 + e[pos] = struct{}{} +} + +func (e editSet) has(pos token.Position) bool { + pos.Offset = 0 + _, ok := e[pos] + return ok +} + +func (e editSet) remove(pos token.Position) { + pos.Offset = 0 + delete(e, pos) +} + +// intersect removes positions from e that are not present in x. +func (e editSet) intersect(x editSet) { + for pos := range e { + if _, ok := x[pos]; !ok { + delete(e, pos) + } + } +} + type fileToEditSet map[string]editSet func apply(file string, edits editSet) { @@ -97,11 +123,11 @@ func (e *editor) rewrite(f *ast.Expr) { } pos := e.file.Position(call.Lparen) - if _, ok := e.edits[pos]; !ok { + if !e.edits.has(pos) { return } *f = call.Args[0] - delete(e.edits, pos) + e.edits.remove(pos) } var ( @@ -161,21 +187,12 @@ func rub(buf []byte) []byte { return res.Bytes() } -var ( - flagAll = flag.Bool("unconvert.all", false, "type check all GOOS and GOARCH combinations") - flagApply = flag.Bool("unconvert.apply", false, "apply edits to source files") - flagCPUProfile = flag.String("unconvert.cpuprofile", "", "write CPU profile to file") - // TODO(mdempsky): Better description and maybe flag name. - flagSafe = flag.Bool("unconvert.safe", false, "be more conservative (experimental)") - flagV = flag.Bool("unconvert.v", false, "verbose output") -) - func usage() { fmt.Fprintf(os.Stderr, "usage: unconvert [flags] [package ...]\n") flag.PrintDefaults() } -func nomain() { +func main() { flag.Usage = usage flag.Parse() @@ -188,18 +205,29 @@ func nomain() { defer pprof.StopCPUProfile() } - importPaths := gotool.ImportPaths(flag.Args()) - if len(importPaths) == 0 { - return - } + patterns := flag.Args() // 0 or more import path patterns. + + var configs [][]string + if *flagConfigs != "" { + if os.Getenv("UNCONVERT_CONFIGS_EXPERIMENT") != "1" { + fmt.Println("WARNING: -configs is experimental and subject to change without notice.") + fmt.Println("Please comment at https://github.com/mdempsky/unconvert/issues/26") + fmt.Println("if you'd like to rely on this interface.") + fmt.Println("(Set UNCONVERT_CONFIGS_EXPERIMENT=1 to silence this warning.)") + fmt.Println() + } - var m fileToEditSet - if *flagAll { - m = mergeEdits(importPaths) + if err := json.Unmarshal([]byte(*flagConfigs), &configs); err != nil { + log.Fatal(err) + } + } else if *flagAll { + configs = allConfigs() } else { - m = computeEdits(importPaths, build.Default.GOOS, build.Default.GOARCH, build.Default.CgoEnabled) + configs = [][]string{nil} } + m := mergeEdits(patterns, configs) + if *flagApply { var wg sync.WaitGroup for f, e := range m { @@ -226,69 +254,36 @@ func nomain() { } } -func Run(prog *loader.Program) []token.Position { - m := computeEditsFromProg(prog) - var conversions []token.Position - for _, positions := range m { - for pos := range positions { - conversions = append(conversions, pos) - } +func allConfigs() [][]string { + out, err := exec.Command("go", "tool", "dist", "list", "-json").Output() + if err != nil { + log.Fatal(err) + } + + var platforms []struct { + GOOS, GOARCH string + } + err = json.Unmarshal(out, &platforms) + if err != nil { + log.Fatal(err) } - return conversions -} -var plats = [...]struct { - goos, goarch string -}{ - // TODO(mdempsky): buildall.bash also builds linux-386-387 and linux-arm-arm5. - {"android", "386"}, - {"android", "amd64"}, - {"android", "arm"}, - {"android", "arm64"}, - {"darwin", "386"}, - {"darwin", "amd64"}, - {"darwin", "arm"}, - {"darwin", "arm64"}, - {"dragonfly", "amd64"}, - {"freebsd", "386"}, - {"freebsd", "amd64"}, - {"freebsd", "arm"}, - {"linux", "386"}, - {"linux", "amd64"}, - {"linux", "arm"}, - {"linux", "arm64"}, - {"linux", "mips64"}, - {"linux", "mips64le"}, - {"linux", "ppc64"}, - {"linux", "ppc64le"}, - {"linux", "s390x"}, - {"nacl", "386"}, - {"nacl", "amd64p32"}, - {"nacl", "arm"}, - {"netbsd", "386"}, - {"netbsd", "amd64"}, - {"netbsd", "arm"}, - {"openbsd", "386"}, - {"openbsd", "amd64"}, - {"openbsd", "arm"}, - {"plan9", "386"}, - {"plan9", "amd64"}, - {"plan9", "arm"}, - {"solaris", "amd64"}, - {"windows", "386"}, - {"windows", "amd64"}, + var res [][]string + for _, platform := range platforms { + res = append(res, []string{ + "GOOS=" + platform.GOOS, + "GOARCH=" + platform.GOARCH, + }) + } + return res } -func mergeEdits(importPaths []string) fileToEditSet { +func mergeEdits(patterns []string, configs [][]string) fileToEditSet { m := make(fileToEditSet) - for _, plat := range plats { - for f, e := range computeEdits(importPaths, plat.goos, plat.goarch, false) { + for _, config := range configs { + for f, e := range computeEdits(patterns, config) { if e0, ok := m[f]; ok { - for k := range e0 { - if _, ok := e[k]; !ok { - delete(e0, k) - } - } + e0.intersect(e) } else { m[f] = e } @@ -297,48 +292,48 @@ func mergeEdits(importPaths []string) fileToEditSet { return m } -type noImporter struct{} - -func (noImporter) Import(path string) (*types.Package, error) { - panic("golang.org/x/tools/go/loader said this wouldn't be called") -} - -func computeEdits(importPaths []string, os, arch string, cgoEnabled bool) fileToEditSet { - ctxt := build.Default - ctxt.GOOS = os - ctxt.GOARCH = arch - ctxt.CgoEnabled = cgoEnabled - - var conf loader.Config - conf.Build = &ctxt - conf.TypeChecker.Importer = noImporter{} - for _, importPath := range importPaths { - conf.Import(importPath) +func computeEdits(patterns []string, config []string) fileToEditSet { + // TODO(mdempsky): Move into config? + var buildFlags []string + if *flagTags != "" { + buildFlags = []string{"-tags", *flagTags} } - prog, err := conf.Load() + + pkgs, err := packages.Load(&packages.Config{ + Mode: packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo, + Env: append(os.Environ(), config...), + BuildFlags: buildFlags, + Tests: *flagTests, + }, patterns...) if err != nil { log.Fatal(err) } + packages.PrintErrors(pkgs) - return computeEditsFromProg(prog) -} - -func computeEditsFromProg(prog *loader.Program) fileToEditSet { type res struct { file string edits editSet } + ch := make(chan res) var wg sync.WaitGroup - for _, pkg := range prog.InitialPackages() { - for _, file := range pkg.Files { + for _, pkg := range pkgs { + for _, file := range pkg.Syntax { pkg, file := pkg, file + tokenFile := pkg.Fset.File(file.Package) + filename := tokenFile.Position(file.Package).Filename + + // Hack to recognize _cgo_gotypes.go. + if strings.HasSuffix(filename, "-d") || strings.HasSuffix(filename, "/_cgo_gotypes.go") { + continue + } + wg.Add(1) go func() { defer wg.Done() - v := visitor{pkg: pkg, file: prog.Fset.File(file.Package), edits: make(editSet)} + v := visitor{info: pkg.TypesInfo, file: tokenFile, edits: make(editSet)} ast.Walk(&v, file) - ch <- res{v.file.Name(), v.edits} + ch <- res{filename, v.edits} }() } } @@ -360,7 +355,7 @@ type step struct { } type visitor struct { - pkg *loader.PackageInfo + info *types.Info file *token.File edits editSet path []step @@ -390,7 +385,7 @@ func (v *visitor) unconvert(call *ast.CallExpr) { if len(call.Args) != 1 || call.Ellipsis != token.NoPos { return } - ft, ok := v.pkg.Types[call.Fun] + ft, ok := v.info.Types[call.Fun] if !ok { fmt.Println("Missing type for function") return @@ -399,7 +394,7 @@ func (v *visitor) unconvert(call *ast.CallExpr) { // Function call; not a conversion. return } - at, ok := v.pkg.Types[call.Args[0]] + at, ok := v.info.Types[call.Args[0]] if !ok { fmt.Println("Missing type for argument") return @@ -408,7 +403,13 @@ func (v *visitor) unconvert(call *ast.CallExpr) { // A real conversion. return } - if isUntypedValue(call.Args[0], &v.pkg.Info) { + if !*flagFastMath && isFloatingPoint(ft.Type) { + // As of Go 1.9, explicit floating-point type + // conversions are always significant because they + // force rounding and prevent operation fusing. + return + } + if isUntypedValue(call.Args[0], v.info) { // Workaround golang.org/issue/13061. return } @@ -417,31 +418,15 @@ func (v *visitor) unconvert(call *ast.CallExpr) { fmt.Println("Skipped a possible type conversion because of -safe at", v.file.Position(call.Pos())) return } - if v.isCgoCheckPointerContext() { - // cmd/cgo generates explicit type conversions that - // are often redundant when introducing - // _cgoCheckPointer calls (issue #16). Users can't do - // anything about these, so skip over them. - return - } - v.edits[v.file.Position(call.Lparen)] = struct{}{} + v.edits.add(v.file.Position(call.Lparen)) } -func (v *visitor) isCgoCheckPointerContext() bool { - ctxt := &v.path[len(v.path)-2] - if ctxt.i != 1 { - return false - } - call, ok := ctxt.n.(*ast.CallExpr) - if !ok { - return false - } - ident, ok := call.Fun.(*ast.Ident) - if !ok { - return false - } - return ident.Name == "_cgoCheckPointer" +// isFloatingPointer reports whether t's underlying type is a floating +// point type. +func isFloatingPoint(t types.Type) bool { + ut, ok := t.Underlying().(*types.Basic) + return ok && ut.Info()&(types.IsFloat|types.IsComplex) != 0 } // isSafeContext reports whether the current context requires @@ -463,7 +448,7 @@ func (v *visitor) isSafeContext(t types.Type) bool { } // We're a conversion in the pos'th element of n.Rhs. // Check that the corresponding element of n.Lhs is of type t. - lt, ok := v.pkg.Types[n.Lhs[pos]] + lt, ok := v.info.Types[n.Lhs[pos]] if !ok { fmt.Println("Missing type for LHS expression") return false @@ -485,7 +470,7 @@ func (v *visitor) isSafeContext(t types.Type) bool { } else { other = n.X } - ot, ok := v.pkg.Types[other] + ot, ok := v.info.Types[other] if !ok { fmt.Println("Missing type for other binop subexpr") return false @@ -497,7 +482,7 @@ func (v *visitor) isSafeContext(t types.Type) bool { // Type conversion in the function subexpr is okay. return true } - ft, ok := v.pkg.Types[n.Fun] + ft, ok := v.info.Types[n.Fun] if !ok { fmt.Println("Missing type for function expression") return false @@ -550,7 +535,7 @@ func (v *visitor) isSafeContext(t types.Type) bool { if typeExpr == nil { fmt.Println(ctxt) } - pt, ok := v.pkg.Types[typeExpr] + pt, ok := v.info.Types[typeExpr] if !ok { fmt.Println("Missing type for return parameter at", v.file.Position(n.Pos())) return false diff --git a/tools/vendor/github.com/hashicorp/errwrap/LICENSE b/tools/vendor/github.com/hashicorp/errwrap/LICENSE deleted file mode 100644 index c33dcc7c9..000000000 --- a/tools/vendor/github.com/hashicorp/errwrap/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/tools/vendor/github.com/hashicorp/errwrap/README.md b/tools/vendor/github.com/hashicorp/errwrap/README.md deleted file mode 100644 index 444df08f8..000000000 --- a/tools/vendor/github.com/hashicorp/errwrap/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# errwrap - -`errwrap` is a package for Go that formalizes the pattern of wrapping errors -and checking if an error contains another error. - -There is a common pattern in Go of taking a returned `error` value and -then wrapping it (such as with `fmt.Errorf`) before returning it. The problem -with this pattern is that you completely lose the original `error` structure. - -Arguably the _correct_ approach is that you should make a custom structure -implementing the `error` interface, and have the original error as a field -on that structure, such [as this example](http://golang.org/pkg/os/#PathError). -This is a good approach, but you have to know the entire chain of possible -rewrapping that happens, when you might just care about one. - -`errwrap` formalizes this pattern (it doesn't matter what approach you use -above) by giving a single interface for wrapping errors, checking if a specific -error is wrapped, and extracting that error. - -## Installation and Docs - -Install using `go get github.com/hashicorp/errwrap`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/errwrap - -## Usage - -#### Basic Usage - -Below is a very basic example of its usage: - -```go -// A function that always returns an error, but wraps it, like a real -// function might. -func tryOpen() error { - _, err := os.Open("/i/dont/exist") - if err != nil { - return errwrap.Wrapf("Doesn't exist: {{err}}", err) - } - - return nil -} - -func main() { - err := tryOpen() - - // We can use the Contains helpers to check if an error contains - // another error. It is safe to do this with a nil error, or with - // an error that doesn't even use the errwrap package. - if errwrap.Contains(err, "does not exist") { - // Do something - } - if errwrap.ContainsType(err, new(os.PathError)) { - // Do something - } - - // Or we can use the associated `Get` functions to just extract - // a specific error. This would return nil if that specific error doesn't - // exist. - perr := errwrap.GetType(err, new(os.PathError)) -} -``` - -#### Custom Types - -If you're already making custom types that properly wrap errors, then -you can get all the functionality of `errwraps.Contains` and such by -implementing the `Wrapper` interface with just one function. Example: - -```go -type AppError { - Code ErrorCode - Err error -} - -func (e *AppError) WrappedErrors() []error { - return []error{e.Err} -} -``` - -Now this works: - -```go -err := &AppError{Err: fmt.Errorf("an error")} -if errwrap.ContainsType(err, fmt.Errorf("")) { - // This will work! -} -``` diff --git a/tools/vendor/github.com/hashicorp/errwrap/errwrap.go b/tools/vendor/github.com/hashicorp/errwrap/errwrap.go deleted file mode 100644 index a733bef18..000000000 --- a/tools/vendor/github.com/hashicorp/errwrap/errwrap.go +++ /dev/null @@ -1,169 +0,0 @@ -// Package errwrap implements methods to formalize error wrapping in Go. -// -// All of the top-level functions that take an `error` are built to be able -// to take any error, not just wrapped errors. This allows you to use errwrap -// without having to type-check and type-cast everywhere. -package errwrap - -import ( - "errors" - "reflect" - "strings" -) - -// WalkFunc is the callback called for Walk. -type WalkFunc func(error) - -// Wrapper is an interface that can be implemented by custom types to -// have all the Contains, Get, etc. functions in errwrap work. -// -// When Walk reaches a Wrapper, it will call the callback for every -// wrapped error in addition to the wrapper itself. Since all the top-level -// functions in errwrap use Walk, this means that all those functions work -// with your custom type. -type Wrapper interface { - WrappedErrors() []error -} - -// Wrap defines that outer wraps inner, returning an error type that -// can be cleanly used with the other methods in this package, such as -// Contains, GetAll, etc. -// -// This function won't modify the error message at all (the outer message -// will be used). -func Wrap(outer, inner error) error { - return &wrappedError{ - Outer: outer, - Inner: inner, - } -} - -// Wrapf wraps an error with a formatting message. This is similar to using -// `fmt.Errorf` to wrap an error. If you're using `fmt.Errorf` to wrap -// errors, you should replace it with this. -// -// format is the format of the error message. The string '{{err}}' will -// be replaced with the original error message. -func Wrapf(format string, err error) error { - outerMsg := "" - if err != nil { - outerMsg = err.Error() - } - - outer := errors.New(strings.Replace( - format, "{{err}}", outerMsg, -1)) - - return Wrap(outer, err) -} - -// Contains checks if the given error contains an error with the -// message msg. If err is not a wrapped error, this will always return -// false unless the error itself happens to match this msg. -func Contains(err error, msg string) bool { - return len(GetAll(err, msg)) > 0 -} - -// ContainsType checks if the given error contains an error with -// the same concrete type as v. If err is not a wrapped error, this will -// check the err itself. -func ContainsType(err error, v interface{}) bool { - return len(GetAllType(err, v)) > 0 -} - -// Get is the same as GetAll but returns the deepest matching error. -func Get(err error, msg string) error { - es := GetAll(err, msg) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetType is the same as GetAllType but returns the deepest matching error. -func GetType(err error, v interface{}) error { - es := GetAllType(err, v) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetAll gets all the errors that might be wrapped in err with the -// given message. The order of the errors is such that the outermost -// matching error (the most recent wrap) is index zero, and so on. -func GetAll(err error, msg string) []error { - var result []error - - Walk(err, func(err error) { - if err.Error() == msg { - result = append(result, err) - } - }) - - return result -} - -// GetAllType gets all the errors that are the same type as v. -// -// The order of the return value is the same as described in GetAll. -func GetAllType(err error, v interface{}) []error { - var result []error - - var search string - if v != nil { - search = reflect.TypeOf(v).String() - } - Walk(err, func(err error) { - var needle string - if err != nil { - needle = reflect.TypeOf(err).String() - } - - if needle == search { - result = append(result, err) - } - }) - - return result -} - -// Walk walks all the wrapped errors in err and calls the callback. If -// err isn't a wrapped error, this will be called once for err. If err -// is a wrapped error, the callback will be called for both the wrapper -// that implements error as well as the wrapped error itself. -func Walk(err error, cb WalkFunc) { - if err == nil { - return - } - - switch e := err.(type) { - case *wrappedError: - cb(e.Outer) - Walk(e.Inner, cb) - case Wrapper: - cb(err) - - for _, err := range e.WrappedErrors() { - Walk(err, cb) - } - default: - cb(err) - } -} - -// wrappedError is an implementation of error that has both the -// outer and inner errors. -type wrappedError struct { - Outer error - Inner error -} - -func (w *wrappedError) Error() string { - return w.Outer.Error() -} - -func (w *wrappedError) WrappedErrors() []error { - return []error{w.Outer, w.Inner} -} diff --git a/tools/vendor/github.com/hashicorp/go-multierror/LICENSE b/tools/vendor/github.com/hashicorp/go-multierror/LICENSE deleted file mode 100644 index 82b4de97c..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/LICENSE +++ /dev/null @@ -1,353 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. diff --git a/tools/vendor/github.com/hashicorp/go-multierror/Makefile b/tools/vendor/github.com/hashicorp/go-multierror/Makefile deleted file mode 100644 index b97cd6ed0..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TEST?=./... - -default: test - -# test runs the test suite and vets the code. -test: generate - @echo "==> Running tests..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} - -# testrace runs the race checker -testrace: generate - @echo "==> Running tests (race)..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -race ${TESTARGS} - -# updatedeps installs all the dependencies needed to run and build. -updatedeps: - @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" - -# generate runs `go generate` to build the dynamically generated source files. -generate: - @echo "==> Generating..." - @find . -type f -name '.DS_Store' -delete - @go list ./... \ - | grep -v "/vendor/" \ - | xargs -n1 go generate - -.PHONY: default test testrace updatedeps generate diff --git a/tools/vendor/github.com/hashicorp/go-multierror/README.md b/tools/vendor/github.com/hashicorp/go-multierror/README.md deleted file mode 100644 index 71dd308ed..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/README.md +++ /dev/null @@ -1,150 +0,0 @@ -# go-multierror - -[![CircleCI](https://img.shields.io/circleci/build/github/hashicorp/go-multierror/master)](https://circleci.com/gh/hashicorp/go-multierror) -[![Go Reference](https://pkg.go.dev/badge/github.com/hashicorp/go-multierror.svg)](https://pkg.go.dev/github.com/hashicorp/go-multierror) -![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/hashicorp/go-multierror) - -[circleci]: https://app.circleci.com/pipelines/github/hashicorp/go-multierror -[godocs]: https://pkg.go.dev/github.com/hashicorp/go-multierror - -`go-multierror` is a package for Go that provides a mechanism for -representing a list of `error` values as a single `error`. - -This allows a function in Go to return an `error` that might actually -be a list of errors. If the caller knows this, they can unwrap the -list and access the errors. If the caller doesn't know, the error -formats to a nice human-readable format. - -`go-multierror` is fully compatible with the Go standard library -[errors](https://golang.org/pkg/errors/) package, including the -functions `As`, `Is`, and `Unwrap`. This provides a standardized approach -for introspecting on error values. - -## Installation and Docs - -Install using `go get github.com/hashicorp/go-multierror`. - -Full documentation is available at -https://pkg.go.dev/github.com/hashicorp/go-multierror - -### Requires go version 1.13 or newer - -`go-multierror` requires go version 1.13 or newer. Go 1.13 introduced -[error wrapping](https://golang.org/doc/go1.13#error_wrapping), which -this library takes advantage of. - -If you need to use an earlier version of go, you can use the -[v1.0.0](https://github.com/hashicorp/go-multierror/tree/v1.0.0) -tag, which doesn't rely on features in go 1.13. - -If you see compile errors that look like the below, it's likely that -you're on an older version of go: - -``` -/go/src/github.com/hashicorp/go-multierror/multierror.go:112:9: undefined: errors.As -/go/src/github.com/hashicorp/go-multierror/multierror.go:117:9: undefined: errors.Is -``` - -## Usage - -go-multierror is easy to use and purposely built to be unobtrusive in -existing Go applications/libraries that may not be aware of it. - -**Building a list of errors** - -The `Append` function is used to create a list of errors. This function -behaves a lot like the Go built-in `append` function: it doesn't matter -if the first argument is nil, a `multierror.Error`, or any other `error`, -the function behaves as you would expect. - -```go -var result error - -if err := step1(); err != nil { - result = multierror.Append(result, err) -} -if err := step2(); err != nil { - result = multierror.Append(result, err) -} - -return result -``` - -**Customizing the formatting of the errors** - -By specifying a custom `ErrorFormat`, you can customize the format -of the `Error() string` function: - -```go -var result *multierror.Error - -// ... accumulate errors here, maybe using Append - -if result != nil { - result.ErrorFormat = func([]error) string { - return "errors!" - } -} -``` - -**Accessing the list of errors** - -`multierror.Error` implements `error` so if the caller doesn't know about -multierror, it will work just fine. But if you're aware a multierror might -be returned, you can use type switches to access the list of errors: - -```go -if err := something(); err != nil { - if merr, ok := err.(*multierror.Error); ok { - // Use merr.Errors - } -} -``` - -You can also use the standard [`errors.Unwrap`](https://golang.org/pkg/errors/#Unwrap) -function. This will continue to unwrap into subsequent errors until none exist. - -**Extracting an error** - -The standard library [`errors.As`](https://golang.org/pkg/errors/#As) -function can be used directly with a multierror to extract a specific error: - -```go -// Assume err is a multierror value -err := somefunc() - -// We want to know if "err" has a "RichErrorType" in it and extract it. -var errRich RichErrorType -if errors.As(err, &errRich) { - // It has it, and now errRich is populated. -} -``` - -**Checking for an exact error value** - -Some errors are returned as exact errors such as the [`ErrNotExist`](https://golang.org/pkg/os/#pkg-variables) -error in the `os` package. You can check if this error is present by using -the standard [`errors.Is`](https://golang.org/pkg/errors/#Is) function. - -```go -// Assume err is a multierror value -err := somefunc() -if errors.Is(err, os.ErrNotExist) { - // err contains os.ErrNotExist -} -``` - -**Returning a multierror only if there are errors** - -If you build a `multierror.Error`, you can use the `ErrorOrNil` function -to return an `error` implementation only if there are errors to return: - -```go -var result *multierror.Error - -// ... accumulate errors here - -// Return the `error` only if errors were added to the multierror, otherwise -// return nil since there are no errors. -return result.ErrorOrNil() -``` diff --git a/tools/vendor/github.com/hashicorp/go-multierror/append.go b/tools/vendor/github.com/hashicorp/go-multierror/append.go deleted file mode 100644 index 3e2589bfd..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/append.go +++ /dev/null @@ -1,43 +0,0 @@ -package multierror - -// Append is a helper function that will append more errors -// onto an Error in order to create a larger multi-error. -// -// If err is not a multierror.Error, then it will be turned into -// one. If any of the errs are multierr.Error, they will be flattened -// one level into err. -// Any nil errors within errs will be ignored. If err is nil, a new -// *Error will be returned. -func Append(err error, errs ...error) *Error { - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Go through each error and flatten - for _, e := range errs { - switch e := e.(type) { - case *Error: - if e != nil { - err.Errors = append(err.Errors, e.Errors...) - } - default: - if e != nil { - err.Errors = append(err.Errors, e) - } - } - } - - return err - default: - newErrs := make([]error, 0, len(errs)+1) - if err != nil { - newErrs = append(newErrs, err) - } - newErrs = append(newErrs, errs...) - - return Append(&Error{}, newErrs...) - } -} diff --git a/tools/vendor/github.com/hashicorp/go-multierror/flatten.go b/tools/vendor/github.com/hashicorp/go-multierror/flatten.go deleted file mode 100644 index aab8e9abe..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/flatten.go +++ /dev/null @@ -1,26 +0,0 @@ -package multierror - -// Flatten flattens the given error, merging any *Errors together into -// a single *Error. -func Flatten(err error) error { - // If it isn't an *Error, just return the error as-is - if _, ok := err.(*Error); !ok { - return err - } - - // Otherwise, make the result and flatten away! - flatErr := new(Error) - flatten(err, flatErr) - return flatErr -} - -func flatten(err error, flatErr *Error) { - switch err := err.(type) { - case *Error: - for _, e := range err.Errors { - flatten(e, flatErr) - } - default: - flatErr.Errors = append(flatErr.Errors, err) - } -} diff --git a/tools/vendor/github.com/hashicorp/go-multierror/format.go b/tools/vendor/github.com/hashicorp/go-multierror/format.go deleted file mode 100644 index 47f13c49a..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/format.go +++ /dev/null @@ -1,27 +0,0 @@ -package multierror - -import ( - "fmt" - "strings" -) - -// ErrorFormatFunc is a function callback that is called by Error to -// turn the list of errors into a string. -type ErrorFormatFunc func([]error) string - -// ListFormatFunc is a basic formatter that outputs the number of errors -// that occurred along with a bullet point list of the errors. -func ListFormatFunc(es []error) string { - if len(es) == 1 { - return fmt.Sprintf("1 error occurred:\n\t* %s\n\n", es[0]) - } - - points := make([]string, len(es)) - for i, err := range es { - points[i] = fmt.Sprintf("* %s", err) - } - - return fmt.Sprintf( - "%d errors occurred:\n\t%s\n\n", - len(es), strings.Join(points, "\n\t")) -} diff --git a/tools/vendor/github.com/hashicorp/go-multierror/group.go b/tools/vendor/github.com/hashicorp/go-multierror/group.go deleted file mode 100644 index 9c29efb7f..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/group.go +++ /dev/null @@ -1,38 +0,0 @@ -package multierror - -import "sync" - -// Group is a collection of goroutines which return errors that need to be -// coalesced. -type Group struct { - mutex sync.Mutex - err *Error - wg sync.WaitGroup -} - -// Go calls the given function in a new goroutine. -// -// If the function returns an error it is added to the group multierror which -// is returned by Wait. -func (g *Group) Go(f func() error) { - g.wg.Add(1) - - go func() { - defer g.wg.Done() - - if err := f(); err != nil { - g.mutex.Lock() - g.err = Append(g.err, err) - g.mutex.Unlock() - } - }() -} - -// Wait blocks until all function calls from the Go method have returned, then -// returns the multierror. -func (g *Group) Wait() *Error { - g.wg.Wait() - g.mutex.Lock() - defer g.mutex.Unlock() - return g.err -} diff --git a/tools/vendor/github.com/hashicorp/go-multierror/multierror.go b/tools/vendor/github.com/hashicorp/go-multierror/multierror.go deleted file mode 100644 index f54574326..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/multierror.go +++ /dev/null @@ -1,121 +0,0 @@ -package multierror - -import ( - "errors" - "fmt" -) - -// Error is an error type to track multiple errors. This is used to -// accumulate errors in cases and return them as a single "error". -type Error struct { - Errors []error - ErrorFormat ErrorFormatFunc -} - -func (e *Error) Error() string { - fn := e.ErrorFormat - if fn == nil { - fn = ListFormatFunc - } - - return fn(e.Errors) -} - -// ErrorOrNil returns an error interface if this Error represents -// a list of errors, or returns nil if the list of errors is empty. This -// function is useful at the end of accumulation to make sure that the value -// returned represents the existence of errors. -func (e *Error) ErrorOrNil() error { - if e == nil { - return nil - } - if len(e.Errors) == 0 { - return nil - } - - return e -} - -func (e *Error) GoString() string { - return fmt.Sprintf("*%#v", *e) -} - -// WrappedErrors returns the list of errors that this Error is wrapping. It is -// an implementation of the errwrap.Wrapper interface so that multierror.Error -// can be used with that library. -// -// This method is not safe to be called concurrently. Unlike accessing the -// Errors field directly, this function also checks if the multierror is nil to -// prevent a null-pointer panic. It satisfies the errwrap.Wrapper interface. -func (e *Error) WrappedErrors() []error { - if e == nil { - return nil - } - return e.Errors -} - -// Unwrap returns an error from Error (or nil if there are no errors). -// This error returned will further support Unwrap to get the next error, -// etc. The order will match the order of Errors in the multierror.Error -// at the time of calling. -// -// The resulting error supports errors.As/Is/Unwrap so you can continue -// to use the stdlib errors package to introspect further. -// -// This will perform a shallow copy of the errors slice. Any errors appended -// to this error after calling Unwrap will not be available until a new -// Unwrap is called on the multierror.Error. -func (e *Error) Unwrap() error { - // If we have no errors then we do nothing - if e == nil || len(e.Errors) == 0 { - return nil - } - - // If we have exactly one error, we can just return that directly. - if len(e.Errors) == 1 { - return e.Errors[0] - } - - // Shallow copy the slice - errs := make([]error, len(e.Errors)) - copy(errs, e.Errors) - return chain(errs) -} - -// chain implements the interfaces necessary for errors.Is/As/Unwrap to -// work in a deterministic way with multierror. A chain tracks a list of -// errors while accounting for the current represented error. This lets -// Is/As be meaningful. -// -// Unwrap returns the next error. In the cleanest form, Unwrap would return -// the wrapped error here but we can't do that if we want to properly -// get access to all the errors. Instead, users are recommended to use -// Is/As to get the correct error type out. -// -// Precondition: []error is non-empty (len > 0) -type chain []error - -// Error implements the error interface -func (e chain) Error() string { - return e[0].Error() -} - -// Unwrap implements errors.Unwrap by returning the next error in the -// chain or nil if there are no more errors. -func (e chain) Unwrap() error { - if len(e) == 1 { - return nil - } - - return e[1:] -} - -// As implements errors.As by attempting to map to the current value. -func (e chain) As(target interface{}) bool { - return errors.As(e[0], target) -} - -// Is implements errors.Is by comparing the current value directly. -func (e chain) Is(target error) bool { - return errors.Is(e[0], target) -} diff --git a/tools/vendor/github.com/hashicorp/go-multierror/prefix.go b/tools/vendor/github.com/hashicorp/go-multierror/prefix.go deleted file mode 100644 index 5c477abe4..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/prefix.go +++ /dev/null @@ -1,37 +0,0 @@ -package multierror - -import ( - "fmt" - - "github.com/hashicorp/errwrap" -) - -// Prefix is a helper function that will prefix some text -// to the given error. If the error is a multierror.Error, then -// it will be prefixed to each wrapped error. -// -// This is useful to use when appending multiple multierrors -// together in order to give better scoping. -func Prefix(err error, prefix string) error { - if err == nil { - return nil - } - - format := fmt.Sprintf("%s {{err}}", prefix) - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Wrap each of the errors - for i, e := range err.Errors { - err.Errors[i] = errwrap.Wrapf(format, e) - } - - return err - default: - return errwrap.Wrapf(format, err) - } -} diff --git a/tools/vendor/github.com/hashicorp/go-multierror/sort.go b/tools/vendor/github.com/hashicorp/go-multierror/sort.go deleted file mode 100644 index fecb14e81..000000000 --- a/tools/vendor/github.com/hashicorp/go-multierror/sort.go +++ /dev/null @@ -1,16 +0,0 @@ -package multierror - -// Len implements sort.Interface function for length -func (err Error) Len() int { - return len(err.Errors) -} - -// Swap implements sort.Interface function for swapping elements -func (err Error) Swap(i, j int) { - err.Errors[i], err.Errors[j] = err.Errors[j], err.Errors[i] -} - -// Less implements sort.Interface function for determining order -func (err Error) Less(i, j int) bool { - return err.Errors[i].Error() < err.Errors[j].Error() -} diff --git a/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md b/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md index 5f16dd140..6d48174bf 100644 --- a/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md +++ b/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md @@ -1,3 +1,22 @@ +# 1.7.0 (May 24, 2024) + +ENHANCEMENTS: + +- Remove `reflect` dependency ([#91](https://github.com/hashicorp/go-version/pull/91)) +- Implement the `database/sql.Scanner` and `database/sql/driver.Value` interfaces for `Version` ([#133](https://github.com/hashicorp/go-version/pull/133)) + +INTERNAL: + +- [COMPLIANCE] Add Copyright and License Headers ([#115](https://github.com/hashicorp/go-version/pull/115)) +- [COMPLIANCE] Update MPL-2.0 LICENSE ([#105](https://github.com/hashicorp/go-version/pull/105)) +- Bump actions/cache from 3.0.11 to 3.2.5 ([#116](https://github.com/hashicorp/go-version/pull/116)) +- Bump actions/checkout from 3.2.0 to 3.3.0 ([#111](https://github.com/hashicorp/go-version/pull/111)) +- Bump actions/upload-artifact from 3.1.1 to 3.1.2 ([#112](https://github.com/hashicorp/go-version/pull/112)) +- GHA Migration ([#103](https://github.com/hashicorp/go-version/pull/103)) +- github: Pin external GitHub Actions to hashes ([#107](https://github.com/hashicorp/go-version/pull/107)) +- SEC-090: Automated trusted workflow pinning (2023-04-05) ([#124](https://github.com/hashicorp/go-version/pull/124)) +- update readme ([#104](https://github.com/hashicorp/go-version/pull/104)) + # 1.6.0 (June 28, 2022) FEATURES: diff --git a/tools/vendor/github.com/hashicorp/go-version/LICENSE b/tools/vendor/github.com/hashicorp/go-version/LICENSE index c33dcc7c9..1409d6ab9 100644 --- a/tools/vendor/github.com/hashicorp/go-version/LICENSE +++ b/tools/vendor/github.com/hashicorp/go-version/LICENSE @@ -1,3 +1,5 @@ +Copyright (c) 2014 HashiCorp, Inc. + Mozilla Public License, version 2.0 1. Definitions diff --git a/tools/vendor/github.com/hashicorp/go-version/README.md b/tools/vendor/github.com/hashicorp/go-version/README.md index 4d2505090..4b7806cd9 100644 --- a/tools/vendor/github.com/hashicorp/go-version/README.md +++ b/tools/vendor/github.com/hashicorp/go-version/README.md @@ -1,5 +1,5 @@ # Versioning Library for Go -[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/main.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/main) +![Build Status](https://github.com/hashicorp/go-version/actions/workflows/go-tests.yml/badge.svg) [![GoDoc](https://godoc.org/github.com/hashicorp/go-version?status.svg)](https://godoc.org/github.com/hashicorp/go-version) go-version is a library for parsing versions and version constraints, diff --git a/tools/vendor/github.com/hashicorp/go-version/constraint.go b/tools/vendor/github.com/hashicorp/go-version/constraint.go index da5d1aca1..29bdc4d2b 100644 --- a/tools/vendor/github.com/hashicorp/go-version/constraint.go +++ b/tools/vendor/github.com/hashicorp/go-version/constraint.go @@ -1,8 +1,10 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package version import ( "fmt" - "reflect" "regexp" "sort" "strings" @@ -199,7 +201,7 @@ func prereleaseCheck(v, c *Version) bool { case cPre && vPre: // A constraint with a pre-release can only match a pre-release version // with the same base segments. - return reflect.DeepEqual(c.Segments64(), v.Segments64()) + return v.equalSegments(c) case !cPre && vPre: // A constraint without a pre-release can only match a version without a diff --git a/tools/vendor/github.com/hashicorp/go-version/version.go b/tools/vendor/github.com/hashicorp/go-version/version.go index e87df6990..7c683c281 100644 --- a/tools/vendor/github.com/hashicorp/go-version/version.go +++ b/tools/vendor/github.com/hashicorp/go-version/version.go @@ -1,9 +1,12 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package version import ( "bytes" + "database/sql/driver" "fmt" - "reflect" "regexp" "strconv" "strings" @@ -117,11 +120,8 @@ func (v *Version) Compare(other *Version) int { return 0 } - segmentsSelf := v.Segments64() - segmentsOther := other.Segments64() - // If the segments are the same, we must compare on prerelease info - if reflect.DeepEqual(segmentsSelf, segmentsOther) { + if v.equalSegments(other) { preSelf := v.Prerelease() preOther := other.Prerelease() if preSelf == "" && preOther == "" { @@ -137,6 +137,8 @@ func (v *Version) Compare(other *Version) int { return comparePrereleases(preSelf, preOther) } + segmentsSelf := v.Segments64() + segmentsOther := other.Segments64() // Get the highest specificity (hS), or if they're equal, just use segmentSelf length lenSelf := len(segmentsSelf) lenOther := len(segmentsOther) @@ -160,7 +162,7 @@ func (v *Version) Compare(other *Version) int { // this means Other had the lower specificity // Check to see if the remaining segments in Self are all zeros - if !allZero(segmentsSelf[i:]) { - //if not, it means that Self has to be greater than Other + // if not, it means that Self has to be greater than Other return 1 } break @@ -180,6 +182,21 @@ func (v *Version) Compare(other *Version) int { return 0 } +func (v *Version) equalSegments(other *Version) bool { + segmentsSelf := v.Segments64() + segmentsOther := other.Segments64() + + if len(segmentsSelf) != len(segmentsOther) { + return false + } + for i, v := range segmentsSelf { + if v != segmentsOther[i] { + return false + } + } + return true +} + func allZero(segs []int64) bool { for _, s := range segs { if s != 0 { @@ -405,3 +422,20 @@ func (v *Version) UnmarshalText(b []byte) error { func (v *Version) MarshalText() ([]byte, error) { return []byte(v.String()), nil } + +// Scan implements the sql.Scanner interface. +func (v *Version) Scan(src interface{}) error { + switch src := src.(type) { + case string: + return v.UnmarshalText([]byte(src)) + case nil: + return nil + default: + return fmt.Errorf("cannot scan %T as Version", src) + } +} + +// Value implements the driver.Valuer interface. +func (v *Version) Value() (driver.Value, error) { + return v.String(), nil +} diff --git a/tools/vendor/github.com/hashicorp/go-version/version_collection.go b/tools/vendor/github.com/hashicorp/go-version/version_collection.go index cc888d43e..83547fe13 100644 --- a/tools/vendor/github.com/hashicorp/go-version/version_collection.go +++ b/tools/vendor/github.com/hashicorp/go-version/version_collection.go @@ -1,3 +1,6 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + package version // Collection is a type that implements the sort.Interface interface diff --git a/tools/vendor/github.com/jgautheron/goconst/.gitignore b/tools/vendor/github.com/jgautheron/goconst/.gitignore deleted file mode 100644 index a9d34d9c4..000000000 --- a/tools/vendor/github.com/jgautheron/goconst/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.idea -goconst \ No newline at end of file diff --git a/tools/vendor/github.com/jgautheron/goconst/README.md b/tools/vendor/github.com/jgautheron/goconst/README.md index 8dd093baf..c671eb541 100644 --- a/tools/vendor/github.com/jgautheron/goconst/README.md +++ b/tools/vendor/github.com/jgautheron/goconst/README.md @@ -23,6 +23,7 @@ Usage: Flags: -ignore exclude files matching the given regular expression + -ignore-strings exclude strings matching the given regular expression -ignore-tests exclude tests from the search (default: true) -min-occurrences report from how many occurrences (default: 2) -min-length only report strings with the minimum given length (default: 3) diff --git a/tools/vendor/github.com/jgautheron/goconst/api.go b/tools/vendor/github.com/jgautheron/goconst/api.go index d56fcd6c2..b838e035f 100644 --- a/tools/vendor/github.com/jgautheron/goconst/api.go +++ b/tools/vendor/github.com/jgautheron/goconst/api.go @@ -14,6 +14,7 @@ type Issue struct { } type Config struct { + IgnoreStrings string IgnoreTests bool MatchWithConstants bool MinStringLength int @@ -28,6 +29,7 @@ func Run(files []*ast.File, fset *token.FileSet, cfg *Config) ([]Issue, error) { p := New( "", "", + cfg.IgnoreStrings, cfg.IgnoreTests, cfg.MatchWithConstants, cfg.ParseNumbers, diff --git a/tools/vendor/github.com/jgautheron/goconst/parser.go b/tools/vendor/github.com/jgautheron/goconst/parser.go index c1edd4c78..2f32740b9 100644 --- a/tools/vendor/github.com/jgautheron/goconst/parser.go +++ b/tools/vendor/github.com/jgautheron/goconst/parser.go @@ -24,11 +24,11 @@ const ( type Parser struct { // Meant to be passed via New() - path, ignore string - ignoreTests, matchConstant bool - minLength, minOccurrences int - numberMin, numberMax int - excludeTypes map[Type]bool + path, ignore, ignoreStrings string + ignoreTests, matchConstant bool + minLength, minOccurrences int + numberMin, numberMax int + excludeTypes map[Type]bool supportedTokens []token.Token @@ -39,7 +39,7 @@ type Parser struct { // New creates a new instance of the parser. // This is your entry point if you'd like to use goconst as an API. -func New(path, ignore string, ignoreTests, matchConstant, numbers bool, numberMin, numberMax, minLength, minOccurrences int, excludeTypes map[Type]bool) *Parser { +func New(path, ignore, ignoreStrings string, ignoreTests, matchConstant, numbers bool, numberMin, numberMax, minLength, minOccurrences int, excludeTypes map[Type]bool) *Parser { supportedTokens := []token.Token{token.STRING} if numbers { supportedTokens = append(supportedTokens, token.INT, token.FLOAT) @@ -48,6 +48,7 @@ func New(path, ignore string, ignoreTests, matchConstant, numbers bool, numberMi return &Parser{ path: path, ignore: ignore, + ignoreStrings: ignoreStrings, ignoreTests: ignoreTests, matchConstant: matchConstant, minLength: minLength, @@ -98,6 +99,16 @@ func (p *Parser) ProcessResults() { delete(p.strs, str) } + if p.ignoreStrings != "" { + match, err := regexp.MatchString(p.ignoreStrings, str) + if err != nil { + log.Println(err) + } + if match { + delete(p.strs, str) + } + } + // If the value is a number if i, err := strconv.ParseInt(str, 0, 0); err == nil { if p.numberMin != 0 && i < int64(p.numberMin) { diff --git a/tools/vendor/github.com/jgautheron/goconst/visitor.go b/tools/vendor/github.com/jgautheron/goconst/visitor.go index a553814f5..c0974da8f 100644 --- a/tools/vendor/github.com/jgautheron/goconst/visitor.go +++ b/tools/vendor/github.com/jgautheron/goconst/visitor.go @@ -62,6 +62,10 @@ func (v *treeVisitor) Visit(node ast.Node) ast.Visitor { // if foo == "moo" case *ast.BinaryExpr: + if t.Op != token.EQL && t.Op != token.NEQ { + return v + } + var lit *ast.BasicLit var ok bool diff --git a/tools/vendor/github.com/sivchari/nosnakecase/.gitignore b/tools/vendor/github.com/jjti/go-spancheck/.gitignore similarity index 59% rename from tools/vendor/github.com/sivchari/nosnakecase/.gitignore rename to tools/vendor/github.com/jjti/go-spancheck/.gitignore index 66fd13c90..1f83be414 100644 --- a/tools/vendor/github.com/sivchari/nosnakecase/.gitignore +++ b/tools/vendor/github.com/jjti/go-spancheck/.gitignore @@ -1,3 +1,6 @@ +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# # Binaries for programs and plugins *.exe *.exe~ @@ -13,3 +16,4 @@ # Dependency directories (remove the comment below to include it) # vendor/ +src/ diff --git a/tools/vendor/github.com/jjti/go-spancheck/.golangci.yml b/tools/vendor/github.com/jjti/go-spancheck/.golangci.yml new file mode 100644 index 000000000..15d8513d6 --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/.golangci.yml @@ -0,0 +1,103 @@ +## A good ref for this: https://gist.github.com/maratori/47a4d00457a92aa426dbd48a18776322 + +run: + timeout: 5m + tests: true +linters: + enable: + - asasalint # checks for pass []any as any in variadic func(...any) + - asciicheck # checks that your code does not contain non-ASCII identifiers + - bidichk # checks for dangerous unicode character sequences + - bodyclose + - containedctx + - decorder # checks declaration order and count of types, constants, variables and functions + - dogsled + - dupword # checks for duplicate words in the source code + - durationcheck # checks for two durations multiplied together + - errcheck + - errname + - errorlint + - exhaustive # checks exhaustiveness of enum switch statements + - exportloopref # checks for pointers to enclosing loop variables + - gci + - gochecknoinits # checks that no init functions are present in Go code + - gocritic + - gomnd + - gosimple + - govet + - importas # enforces consistent import aliases + - ineffassign + - loggercheck + - makezero # finds slice declarations with non-zero initial length + - mirror + - misspell + - musttag # enforces field tags in (un)marshaled structs + - nakedret + - nestif # reports deeply nested if statements + - nilerr # finds the code that returns nil even if it checks that the error is not nil + - noctx # finds sending http request without context.Context + - nolintlint # reports ill-formed or insufficient nolint directives + - predeclared # finds code that shadows one of Go's predeclared identifiers + - promlinter + - reassign # checks that package variables are not reassigned + - revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint + - staticcheck + - stylecheck + - tenv + - thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers + - unconvert # removes unnecessary type conversions + - unparam # reports unused function parameters + - unused + - usestdlibvars # detects the possibility to use variables/constants from the Go standard library + - wastedassign # finds wasted assignment statements + - whitespace # detects leading and trailing whitespace +linters-settings: + gci: + skip-generated: true + custom-order: true + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/jjti) + exhaustive: + # Program elements to check for exhaustiveness. + # Default: [ switch ] + check: + - switch + - map + gocritic: + settings: + captLocal: + # Whether to restrict checker to params only. + # Default: true + paramsOnly: false + underef: + # Whether to skip (*x).method() calls where x is a pointer receiver. + # Default: true + skipRecvDeref: false + govet: + enable-all: true + disable: + - fieldalignment # too strict + - shadow # bunch of false positive, doesn't realize when we return from a func + misspell: + locale: US + nakedret: + max-func-lines: 0 + nestif: + # Minimal complexity of if statements to report. + # Default: 5 + min-complexity: 4 + nolintlint: + # Enable to require an explanation of nonzero length after each nolint directive. + # Default: false + require-explanation: true + stylecheck: + checks: ["all"] +issues: + include: + - EXC0001 # Error return value of x is not checked + - EXC0013 # package comment should be of the form "(.+)... + - EXC0014 # comment on exported (.+) should be of the form "(.+)..." + exclude: + - ifElseChain diff --git a/tools/vendor/github.com/jjti/go-spancheck/CONTRIBUTING.md b/tools/vendor/github.com/jjti/go-spancheck/CONTRIBUTING.md new file mode 100644 index 000000000..32932fae1 --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/CONTRIBUTING.md @@ -0,0 +1,51 @@ +# Contributing guideline + +Contributions are welcome + appreciated. + +## Open Requests + +These are a couple contributions I would especially appreciate: + +1. Add check for SetAttributes: https://github.com/jjti/go-spancheck/issues/1 +1. Add SuggestedFix(es): https://github.com/jjti/go-spancheck/issues/2 + +## Steps + +### 1. Create an Issue + +If one does not exist already, open a bug report or feature request in [https://github.com/jjti/go-spancheck/issues](https://github.com/jjti/go-spancheck/issues). + +### 2. Add a test case + +Test cases are in `/testdata`. + +If fixing a bug, you can add it to `testdata/enableall/enable_all.go` (for example): + +```go +func _() { + ctx, span := otel.Tracer("foo").Start(context.Background(), "bar") // want "span.End is not called on all paths, possible memory leak" + print(ctx.Done(), span.IsRecording()) +} // want "return can be reached without calling span.End" +``` + +If adding a new feature with a new combination of flags, create a new module within `testdata`: + +1. Create a new module, eg `testdata/setattributes` +1. Copy/paste go.mod/sum into the new module directory and update the module definition, eg `module github.com/jjti/go-spancheck/testdata/setattributes` +1. Add the module to the workspace in [go.work](./go.work) +1. Add the module's directory to the `testvendor` Make target in [Makefile](./Makefile) + +### 3. Run tests + +```bash +make test +``` + +### 4. Open a PR + +Eg of a GitHub snippet for PRs: + +```bash +alias gpr='gh pr view --web 2>/dev/null || gh pr create --web --fill' +gpr +``` diff --git a/tools/vendor/github.com/esimonov/ifshort/LICENSE b/tools/vendor/github.com/jjti/go-spancheck/LICENSE similarity index 96% rename from tools/vendor/github.com/esimonov/ifshort/LICENSE rename to tools/vendor/github.com/jjti/go-spancheck/LICENSE index a04e339c0..552ddf2dc 100644 --- a/tools/vendor/github.com/esimonov/ifshort/LICENSE +++ b/tools/vendor/github.com/jjti/go-spancheck/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2020 Eugene Simonov +Copyright (c) 2023 Joshua Timmons Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/tools/vendor/github.com/jjti/go-spancheck/Makefile b/tools/vendor/github.com/jjti/go-spancheck/Makefile new file mode 100644 index 000000000..8e9d07be3 --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/Makefile @@ -0,0 +1,27 @@ +.PHONY: fmt +fmt: + golangci-lint run --fix --config ./.golangci.yml + +.PHONY: test +test: testvendor + go test -v ./... + +# note: I'm copying https://github.com/ghostiam/protogetter/blob/main/testdata/Makefile +# +# x/tools/go/analysis/analysistest does not support go modules. To work around this issue +# we need to vendor any external modules to `./src`. +# +# Follow https://github.com/golang/go/issues/37054 for more details. +.PHONY: testvendor +testvendor: + rm -rf testdata/base/src + cd testdata/base && GOWORK=off go mod vendor + cp -r testdata/base/vendor testdata/base/src + cp -r testdata/base/vendor testdata/disableerrorchecks/src + cp -r testdata/base/vendor testdata/enableall/src + rm -rf testdata/base/vendor + +.PHONY: install +install: + go install ./cmd/spancheck + @echo "Installed in $(shell which spancheck)" \ No newline at end of file diff --git a/tools/vendor/github.com/jjti/go-spancheck/README.md b/tools/vendor/github.com/jjti/go-spancheck/README.md new file mode 100644 index 000000000..393663ba7 --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/README.md @@ -0,0 +1,268 @@ +# go-spancheck + +![Latest release](https://img.shields.io/github/v/release/jjti/go-spancheck) +[![ci](https://github.com/jjti/go-spancheck/actions/workflows/ci.yaml/badge.svg)](https://github.com/jjti/go-spancheck/actions/workflows/ci.yaml) +[![Go Report Card](https://goreportcard.com/badge/github.com/jjti/go-spancheck)](https://goreportcard.com/report/github.com/jjti/go-spancheck) +[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE) + +Checks usage of: + +- [OpenTelemetry spans](https://opentelemetry.io/docs/instrumentation/go/manual/) from [go.opentelemetry.io/otel/trace](go.opentelemetry.io/otel/trace) +- [OpenCensus spans](https://opencensus.io/quickstart/go/tracing/) from [go.opencensus.io/trace](https://pkg.go.dev/go.opencensus.io/trace#Span) + +## Example + +```bash +spancheck -checks 'end,set-status,record-error' ./... +``` + +```go +func _() error { + // span.End is not called on all paths, possible memory leak + // span.SetStatus is not called on all paths + // span.RecordError is not called on all paths + _, span := otel.Tracer("foo").Start(context.Background(), "bar") + + if true { + // return can be reached without calling span.End + // return can be reached without calling span.SetStatus + // return can be reached without calling span.RecordError + return errors.New("err") + } + + return nil // return can be reached without calling span.End +} +``` + +## Configuration + +### golangci-lint + +Docs on configuring the linter are also available at [https://golangci-lint.run/usage/linters/#spancheck](https://golangci-lint.run/usage/linters/#spancheck): + +```yaml +linters: + enable: + - spancheck + +linters-settings: + spancheck: + # Checks to enable. + # Options include: + # - `end`: check that `span.End()` is called + # - `record-error`: check that `span.RecordError(err)` is called when an error is returned + # - `set-status`: check that `span.SetStatus(codes.Error, msg)` is called when an error is returned + # Default: ["end"] + checks: + - end + - record-error + - set-status + # A list of regexes for function signatures that silence `record-error` and `set-status` reports + # if found in the call path to a returned error. + # https://github.com/jjti/go-spancheck#ignore-check-signatures + # Default: [] + ignore-check-signatures: + - "telemetry.RecordError" + # A list of regexes for additional function signatures that create spans. This is useful if you have a utility + # method to create spans. Each entry should be of the form :, where `telemetry-type` + # can be `opentelemetry` or `opencensus`. + # https://github.com/jjti/go-spancheck#extra-start-span-signatures + # Default: [] + extra-start-span-signatures: + - "github.com/user/repo/telemetry/trace.Start:opentelemetry" +``` + +### CLI + +To install the linter as a CLI: + +```bash +go install github.com/jjti/go-spancheck/cmd/spancheck@latest +spancheck ./... +``` + +Only the `span.End()` check is enabled by default. The others can be enabled with `-checks 'end,set-status,record-error'`. + +```txt +$ spancheck -h +... +Flags: + -checks string + comma-separated list of checks to enable (options: end, set-status, record-error) (default "end") + -extra-start-span-signatures string + comma-separated list of regex:telemetry-type for function signatures that indicate the start of a span + -ignore-check-signatures string + comma-separated list of regex for function signatures that disable checks on errors +``` + +### Ignore Check Signatures + +The `span.SetStatus()` and `span.RecordError()` checks warn when there is: + +1. a path to return statement +1. that returns an error +1. without a call (to `SetStatus` or `RecordError`, respectively) + +But it's convenient to call `SetStatus` and `RecordError` from utility methods [[1](https://andydote.co.uk/2023/09/19/tracing-is-better/#step-2-wrap-the-errors)]. To support that, the `ignore-*-check-signatures` settings will suppress warnings if the configured function is present in the path. + +For example, by default, the code below would have warnings as shown: + +```go +func task(ctx context.Context) error { + ctx, span := otel.Tracer("foo").Start(ctx, "bar") // span.SetStatus is not called on all paths + defer span.End() + + if err := subTask(ctx); err != nil { + return recordErr(span, err) // return can be reached without calling span.SetStatus + } + + return nil +} + +func recordErr(span trace.Span, err error) error { + span.SetStatus(codes.Error, err.Error()) + span.RecordError(err) + return err +} +``` + +The warnings are can be ignored by setting `-ignore-check-signatures` flag to `recordErr`: + +```bash +spancheck -checks 'end,set-status,record-error' -ignore-check-signatures 'recordErr' ./... +``` + +### Extra Start Span Signatures + +By default, Span creation will be tracked from calls to [(go.opentelemetry.io/otel/trace.Tracer).Start](https://github.com/open-telemetry/opentelemetry-go/blob/98b32a6c3a87fbee5d34c063b9096f416b250897/trace/trace.go#L523), [go.opencensus.io/trace.StartSpan](https://pkg.go.dev/go.opencensus.io/trace#StartSpan), or [go.opencensus.io/trace.StartSpanWithRemoteParent](https://github.com/census-instrumentation/opencensus-go/blob/v0.24.0/trace/trace_api.go#L66). + +You can use the `-extra-start-span-signatures` flag to list additional Span creation functions. For all such functions: + +1. their Spans will be linted (for all enable checks) +1. checks will be disabled (i.e. there is no linting of Spans within the creation functions) + +You must pass a comma-separated list of regex patterns and the telemetry library corresponding to the returned Span. Each entry should be of the form `:`, where `telemetry-type` can be `opentelemetry` or `opencensus`. For example, if you have created a function named `StartTrace` in a `telemetry` package, using the `go.opentelemetry.io/otel` library, you can include this function for analysis like so: + +```bash +spancheck -extra-start-span-signatures 'github.com/user/repo/telemetry/StartTrace:opentelemetry' ./... +``` + +## Problem Statement + +Tracing is a celebrated [[1](https://andydote.co.uk/2023/09/19/tracing-is-better/),[2](https://charity.wtf/2022/08/15/live-your-best-life-with-structured-events/)] and well marketed [[3](https://docs.datadoghq.com/tracing/),[4](https://www.honeycomb.io/distributed-tracing)] pillar of observability. But self-instrumented tracing requires a lot of easy-to-forget boilerplate: + +```go +import ( + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/codes" +) + +func task(ctx context.Context) error { + ctx, span := otel.Tracer("foo").Start(ctx, "bar") + defer span.End() // call `.End()` + + if err := subTask(ctx); err != nil { + span.SetStatus(codes.Error, err.Error()) // call SetStatus(codes.Error, msg) to set status:error + span.RecordError(err) // call RecordError(err) to record an error event + return err + } + + return nil +} +``` + +For spans to be _really_ useful, developers need to: + +1. call `span.End()` always +1. call `span.SetStatus(codes.Error, msg)` on error +1. call `span.RecordError(err)` on error +1. call `span.SetAttributes()` liberally + +- OpenTelemetry: [Creating spans](https://opentelemetry.io/docs/instrumentation/go/manual/#creating-spans) +- Uptrace: [OpenTelemetry Go Tracing API](https://uptrace.dev/opentelemetry/go-tracing.html#quickstart) + +This linter helps developers with steps 1-3. + +## Checks + +This linter supports three checks, each documented below. Only the check for `span.End()` is enabled by default. See [Configuration](#configuration) for instructions on enabling the others. + +### `span.End()` + +Enabled by default. + +Not calling `End` can cause memory leaks and prevents spans from being closed. + +> Any Span that is created MUST also be ended. This is the responsibility of the user. Implementations of this API may leak memory or other resources if Spans are not ended. + +[source: trace.go](https://github.com/open-telemetry/opentelemetry-go/blob/98b32a6c3a87fbee5d34c063b9096f416b250897/trace/trace.go#L523) + +```go +func task(ctx context.Context) error { + otel.Tracer("app").Start(ctx, "foo") // span is unassigned, probable memory leak + _, span := otel.Tracer().Start(ctx, "foo") // span.End is not called on all paths, possible memory leak + return nil // return can be reached without calling span.End +} +``` + +### `span.SetStatus(codes.Error, "msg")` + +Disabled by default. Enable with `-checks 'set-status'`. + +Developers should call `SetStatus` on spans. The status attribute is an important, first-class attribute: + +1. observability platforms and APMs differentiate "success" vs "failure" using [span's status codes](https://docs.datadoghq.com/tracing/metrics/). +1. telemetry collector agents, like the [Open Telemetry Collector's Tail Sampling Processor](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/tailsamplingprocessor/README.md#:~:text=Sampling%20Processor.-,status_code,-%3A%20Sample%20based%20upon), are configurable to sample `Error` spans at a higher rate than `OK` spans. +1. observability platforms, like [DataDog, have trace retention filters that use spans' status](https://docs.datadoghq.com/tracing/trace_pipeline/trace_retention/). In other words, `status:error` spans often receive special treatment with the assumption they are more useful for debugging. And forgetting to set the status can lead to spans, with useful debugging information, being dropped. + +```go +func _() error { + _, span := otel.Tracer("foo").Start(context.Background(), "bar") // span.SetStatus is not called on all paths + defer span.End() + + if err := subTask(); err != nil { + span.RecordError(err) + return errors.New(err) // return can be reached without calling span.SetStatus + } + + return nil +} +``` + +OpenTelemetry docs: [Set span status](https://opentelemetry.io/docs/instrumentation/go/manual/#set-span-status). + +### `span.RecordError(err)` + +Disabled by default. Enable with `-checks 'record-error'`. + +Calling `RecordError` creates a new exception-type [event (structured log message)](https://opentelemetry.io/docs/concepts/signals/traces/#span-events) on the span. This is recommended to capture the error's stack trace. + +```go +func _() error { + _, span := otel.Tracer("foo").Start(context.Background(), "bar") // span.RecordError is not called on all paths + defer span.End() + + if err := subTask(); err != nil { + span.SetStatus(codes.Error, err.Error()) + return errors.New(err) // return can be reached without calling span.RecordError + } + + return nil +} +``` + +OpenTelemetry docs: [Record errors](https://opentelemetry.io/docs/instrumentation/go/manual/#record-errors). + +Note: this check is not applied to [OpenCensus spans](https://pkg.go.dev/go.opencensus.io/trace#SpanInterface) because they have no `RecordError` method. + +## Attribution + +This linter is the product of liberal copying of: + +- [github.com/golang/tools/go/analysis/passes/lostcancel](https://github.com/golang/tools/tree/master/go/analysis/passes/lostcancel) (half the linter) +- [github.com/tomarrell/wrapcheck](https://github.com/tomarrell/wrapcheck) (error type checking and config) +- [github.com/Antonboom/testifylint](https://github.com/Antonboom/testifylint) (README) +- [github.com/ghostiam/protogetter](https://github.com/ghostiam/protogetter/blob/main/testdata/Makefile) (test setup) + +And the contributions of: +- [@trixnz](https://github.com/trixnz) who [added support for custom span start functions](https://github.com/jjti/go-spancheck/pull/16) diff --git a/tools/vendor/github.com/jjti/go-spancheck/config.go b/tools/vendor/github.com/jjti/go-spancheck/config.go new file mode 100644 index 000000000..ed02a1ad9 --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/config.go @@ -0,0 +1,223 @@ +package spancheck + +import ( + "flag" + "fmt" + "log" + "regexp" + "strings" +) + +// Check is a type of check that can be enabled or disabled. +type Check int + +const ( + // EndCheck if enabled, checks that span.End() is called after span creation and before the function returns. + EndCheck Check = iota + + // SetStatusCheck if enabled, checks that `span.SetStatus(codes.Error, msg)` is called when returning an error. + SetStatusCheck + + // RecordErrorCheck if enabled, checks that span.RecordError(err) is called when returning an error. + RecordErrorCheck +) + +var ( + startSpanSignatureCols = 2 + defaultStartSpanSignatures = []string{ + // https://github.com/open-telemetry/opentelemetry-go/blob/98b32a6c3a87fbee5d34c063b9096f416b250897/trace/trace.go#L523 + `\(go.opentelemetry.io/otel/trace.Tracer\).Start:opentelemetry`, + // https://pkg.go.dev/go.opencensus.io/trace#StartSpan + `go.opencensus.io/trace.StartSpan:opencensus`, + // https://github.com/census-instrumentation/opencensus-go/blob/v0.24.0/trace/trace_api.go#L66 + `go.opencensus.io/trace.StartSpanWithRemoteParent:opencensus`, + } +) + +func (c Check) String() string { + switch c { + case EndCheck: + return "end" + case SetStatusCheck: + return "set-status" + case RecordErrorCheck: + return "record-error" + default: + return "" + } +} + +// Checks is a list of all checks by name. +var Checks = map[string]Check{ + EndCheck.String(): EndCheck, + SetStatusCheck.String(): SetStatusCheck, + RecordErrorCheck.String(): RecordErrorCheck, +} + +type spanStartMatcher struct { + signature *regexp.Regexp + spanType spanType +} + +// Config is a configuration for the spancheck analyzer. +type Config struct { + fs flag.FlagSet + + // EnabledChecks is a list of checks to enable by name. + EnabledChecks []string + + // IgnoreChecksSignaturesSlice is a slice of strings that are turned into + // the IgnoreSetStatusCheckSignatures regex. + IgnoreChecksSignaturesSlice []string + + StartSpanMatchersSlice []string + + endCheckEnabled bool + setStatusEnabled bool + recordErrorEnabled bool + + // ignoreChecksSignatures is a regex that, if matched, disables the + // SetStatus and RecordError checks on error. + ignoreChecksSignatures *regexp.Regexp + + startSpanMatchers []spanStartMatcher + startSpanMatchersCustomRegex *regexp.Regexp +} + +// NewDefaultConfig returns a new Config with default values. +func NewDefaultConfig() *Config { + return &Config{ + EnabledChecks: []string{EndCheck.String()}, + StartSpanMatchersSlice: defaultStartSpanSignatures, + } +} + +// finalize parses checks and signatures from the public string slices of Config. +func (c *Config) finalize() { + c.parseSignatures() + + checks := parseChecks(c.EnabledChecks) + c.endCheckEnabled = contains(checks, EndCheck) + c.setStatusEnabled = contains(checks, SetStatusCheck) + c.recordErrorEnabled = contains(checks, RecordErrorCheck) +} + +// parseSignatures sets the Ignore*CheckSignatures regex from the string slices. +func (c *Config) parseSignatures() { + c.parseIgnoreSignatures() + c.parseStartSpanSignatures() +} + +func (c *Config) parseIgnoreSignatures() { + if c.ignoreChecksSignatures == nil && len(c.IgnoreChecksSignaturesSlice) > 0 { + if len(c.IgnoreChecksSignaturesSlice) == 1 && c.IgnoreChecksSignaturesSlice[0] == "" { + return + } + + c.ignoreChecksSignatures = createRegex(c.IgnoreChecksSignaturesSlice) + } +} + +func (c *Config) parseStartSpanSignatures() { + if c.startSpanMatchers != nil { + return + } + + customMatchers := []string{} + for i, sig := range c.StartSpanMatchersSlice { + parts := strings.Split(sig, ":") + + // Make sure we have both a signature and a telemetry type + if len(parts) != startSpanSignatureCols { + log.Default().Printf("[WARN] invalid start span signature \"%s\". expected regex:telemetry-type\n", sig) + + continue + } + + sig, sigType := parts[0], parts[1] + if len(sig) < 1 { + log.Default().Print("[WARN] invalid start span signature, empty pattern") + + continue + } + + spanType, ok := SpanTypes[sigType] + if !ok { + validSpanTypes := make([]string, 0, len(SpanTypes)) + for k := range SpanTypes { + validSpanTypes = append(validSpanTypes, k) + } + + log.Default(). + Printf("[WARN] invalid start span type \"%s\". expected one of %s\n", sigType, strings.Join(validSpanTypes, ", ")) + + continue + } + + regex, err := regexp.Compile(sig) + if err != nil { + log.Default().Printf("[WARN] failed to compile regex from signature %s: %v\n", sig, err) + + continue + } + + c.startSpanMatchers = append(c.startSpanMatchers, spanStartMatcher{ + signature: regex, + spanType: spanType, + }) + + if i >= len(defaultStartSpanSignatures) { + customMatchers = append(customMatchers, sig) + } + } + + c.startSpanMatchersCustomRegex = createRegex(customMatchers) +} + +func parseChecks(checksSlice []string) []Check { + if len(checksSlice) == 0 { + return nil + } + + checks := []Check{} + for _, check := range checksSlice { + checkName := strings.TrimSpace(check) + if checkName == "" { + continue + } + + check, ok := Checks[checkName] + if !ok { + continue + } + + checks = append(checks, check) + } + + return checks +} + +func createRegex(sigs []string) *regexp.Regexp { + if len(sigs) == 0 { + return nil + } + + regex := fmt.Sprintf("(%s)", strings.Join(sigs, "|")) + regexCompiled, err := regexp.Compile(regex) + if err != nil { + log.Default().Print("[WARN] failed to compile regex from signature flag", "regex", regex, "err", err) + return nil + } + + return regexCompiled +} + +func contains(s []Check, e Check) bool { + for _, a := range s { + if a == e { + return true + } + } + + return false +} diff --git a/tools/vendor/github.com/jjti/go-spancheck/doc.go b/tools/vendor/github.com/jjti/go-spancheck/doc.go new file mode 100644 index 000000000..f9dec043f --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/doc.go @@ -0,0 +1,37 @@ +// Package spancheck defines a linter that checks for mistakes with OTEL trace spans. +// +// # Analyzer spancheck +// +// spancheck: check for mistakes with OpenTelemetry trace spans. +// +// Common mistakes with OTEL trace spans include forgetting to call End: +// +// func(ctx context.Context) { +// ctx, span := otel.Tracer("app").Start(ctx, "span") +// // defer span.End() should be here +// +// // do stuff +// } +// +// Forgetting to set an Error status: +// +// ctx, span := otel.Tracer("app").Start(ctx, "span") +// defer span.End() +// +// if err := task(); err != nil { +// // span.SetStatus(codes.Error, err.Error()) should be here +// span.RecordError(err) +// return fmt.Errorf("failed to run task: %w", err) +// } +// +// Forgetting to record the Error: +// +// ctx, span := otel.Tracer("app").Start(ctx, "span") +// defer span.End() +// +// if err := task(); err != nil { +// span.SetStatus(codes.Error, err.Error()) +// // span.RecordError(err) should be here +// return fmt.Errorf("failed to run task: %w", err) +// } +package spancheck diff --git a/tools/vendor/github.com/jjti/go-spancheck/go.work b/tools/vendor/github.com/jjti/go-spancheck/go.work new file mode 100644 index 000000000..7d0a87b9e --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/go.work @@ -0,0 +1,8 @@ +go 1.20 + +use ( + . + ./testdata/base + ./testdata/disableerrorchecks + ./testdata/enableall +) diff --git a/tools/vendor/github.com/jjti/go-spancheck/go.work.sum b/tools/vendor/github.com/jjti/go-spancheck/go.work.sum new file mode 100644 index 000000000..04eadf2c5 --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/go.work.sum @@ -0,0 +1,4 @@ +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= +golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= +golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= diff --git a/tools/vendor/github.com/jjti/go-spancheck/spancheck.go b/tools/vendor/github.com/jjti/go-spancheck/spancheck.go new file mode 100644 index 000000000..8fc7945c6 --- /dev/null +++ b/tools/vendor/github.com/jjti/go-spancheck/spancheck.go @@ -0,0 +1,466 @@ +package spancheck + +import ( + "go/ast" + "go/types" + "regexp" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/ctrlflow" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/go/cfg" +) + +const stackLen = 32 + +// spanType differentiates span types. +type spanType int + +const ( + spanUnset spanType = iota // not a span + spanOpenTelemetry // from go.opentelemetry.io/otel + spanOpenCensus // from go.opencensus.io/trace +) + +// SpanTypes is a list of all span types by name. +var SpanTypes = map[string]spanType{ + "opentelemetry": spanOpenTelemetry, + "opencensus": spanOpenCensus, +} + +// this approach stolen from errcheck +// https://github.com/kisielk/errcheck/blob/7f94c385d0116ccc421fbb4709e4a484d98325ee/errcheck/errcheck.go#L22 +var errorType = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) + +// NewAnalyzerWithConfig returns a new analyzer configured with the Config passed in. +// Its config can be set for testing. +func NewAnalyzerWithConfig(config *Config) *analysis.Analyzer { + return newAnalyzer(config) +} + +func newAnalyzer(config *Config) *analysis.Analyzer { + config.finalize() + + return &analysis.Analyzer{ + Name: "spancheck", + Doc: "Checks for mistakes with OpenTelemetry/Census spans.", + Flags: config.fs, + Run: run(config), + Requires: []*analysis.Analyzer{ + ctrlflow.Analyzer, + inspect.Analyzer, + }, + } +} + +func run(config *Config) func(*analysis.Pass) (interface{}, error) { + return func(pass *analysis.Pass) (interface{}, error) { + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + nodeFilter := []ast.Node{ + (*ast.FuncLit)(nil), // f := func() {} + (*ast.FuncDecl)(nil), // func foo() {} + } + inspect.Preorder(nodeFilter, func(n ast.Node) { + runFunc(pass, n, config) + }) + + return nil, nil + } +} + +type spanVar struct { + stmt ast.Node + id *ast.Ident + vr *types.Var + spanType spanType +} + +// runFunc checks if the node is a function, has a span, and the span never has SetStatus set. +func runFunc(pass *analysis.Pass, node ast.Node, config *Config) { + // copying https://cs.opensource.google/go/x/tools/+/master:go/analysis/passes/lostcancel/lostcancel.go + + // Find scope of function node + var funcScope *types.Scope + switch v := node.(type) { + case *ast.FuncLit: + funcScope = pass.TypesInfo.Scopes[v.Type] + case *ast.FuncDecl: + funcScope = pass.TypesInfo.Scopes[v.Type] + fnSig := pass.TypesInfo.ObjectOf(v.Name).String() + + // Skip checking spans in this function if it's a custom starter/creator. + if config.startSpanMatchersCustomRegex != nil && config.startSpanMatchersCustomRegex.MatchString(fnSig) { + return + } + } + + // Maps each span variable to its defining ValueSpec/AssignStmt. + spanVars := make(map[*ast.Ident]spanVar) + + // Find the set of span vars to analyze. + stack := make([]ast.Node, 0, stackLen) + ast.Inspect(node, func(n ast.Node) bool { + switch n.(type) { + case *ast.FuncLit: + if len(stack) > 0 { + return false // don't stray into nested functions + } + case nil: + stack = stack[:len(stack)-1] // pop + return true + } + stack = append(stack, n) // push + + // Look for [{AssignStmt,ValueSpec} CallExpr SelectorExpr]: + // + // ctx, span := otel.Tracer("app").Start(...) + // ctx, span = otel.Tracer("app").Start(...) + // var ctx, span = otel.Tracer("app").Start(...) + sType, isStart := isSpanStart(pass.TypesInfo, n, config.startSpanMatchers) + if !isStart { + return true + } + + if !isCall(stack[len(stack)-2]) { + return true + } + + stmt := stack[len(stack)-3] + id := getID(stmt) + if id == nil { + pass.ReportRangef(n, "span is unassigned, probable memory leak") + return true + } + + if id.Name == "_" { + pass.ReportRangef(id, "span is unassigned, probable memory leak") + } else if v, ok := pass.TypesInfo.Uses[id].(*types.Var); ok { + // If the span variable is defined outside function scope, + // do not analyze it. + if funcScope.Contains(v.Pos()) { + spanVars[id] = spanVar{ + vr: v, + stmt: stmt, + id: id, + spanType: sType, + } + } + } else if v, ok := pass.TypesInfo.Defs[id].(*types.Var); ok { + spanVars[id] = spanVar{ + vr: v, + stmt: stmt, + id: id, + spanType: sType, + } + } + + return true + }) + + if len(spanVars) == 0 { + return // no need to inspect CFG + } + + // Obtain the CFG. + cfgs := pass.ResultOf[ctrlflow.Analyzer].(*ctrlflow.CFGs) + var g *cfg.CFG + var sig *types.Signature + switch node := node.(type) { + case *ast.FuncDecl: + sig, _ = pass.TypesInfo.Defs[node.Name].Type().(*types.Signature) + g = cfgs.FuncDecl(node) + case *ast.FuncLit: + sig, _ = pass.TypesInfo.Types[node.Type].Type.(*types.Signature) + g = cfgs.FuncLit(node) + } + if sig == nil { + return // missing type information + } + + // Check for missing calls. + for _, sv := range spanVars { + if config.endCheckEnabled { + // Check if there's no End to the span. + if ret := getMissingSpanCalls(pass, g, sv, "End", func(_ *analysis.Pass, ret *ast.ReturnStmt) *ast.ReturnStmt { return ret }, nil, config.startSpanMatchers); ret != nil { + pass.ReportRangef(sv.stmt, "%s.End is not called on all paths, possible memory leak", sv.vr.Name()) + pass.ReportRangef(ret, "return can be reached without calling %s.End", sv.vr.Name()) + } + } + + if config.setStatusEnabled { + // Check if there's no SetStatus to the span setting an error. + if ret := getMissingSpanCalls(pass, g, sv, "SetStatus", getErrorReturn, config.ignoreChecksSignatures, config.startSpanMatchers); ret != nil { + pass.ReportRangef(sv.stmt, "%s.SetStatus is not called on all paths", sv.vr.Name()) + pass.ReportRangef(ret, "return can be reached without calling %s.SetStatus", sv.vr.Name()) + } + } + + if config.recordErrorEnabled && sv.spanType == spanOpenTelemetry { // RecordError only exists in OpenTelemetry + // Check if there's no RecordError to the span setting an error. + if ret := getMissingSpanCalls(pass, g, sv, "RecordError", getErrorReturn, config.ignoreChecksSignatures, config.startSpanMatchers); ret != nil { + pass.ReportRangef(sv.stmt, "%s.RecordError is not called on all paths", sv.vr.Name()) + pass.ReportRangef(ret, "return can be reached without calling %s.RecordError", sv.vr.Name()) + } + } + } +} + +// isSpanStart reports whether n is tracer.Start() +func isSpanStart(info *types.Info, n ast.Node, startSpanMatchers []spanStartMatcher) (spanType, bool) { + sel, ok := n.(*ast.SelectorExpr) + if !ok { + return spanUnset, false + } + + fnSig := info.ObjectOf(sel.Sel).String() + + // Check if the function is a span start function + for _, matcher := range startSpanMatchers { + if matcher.signature.MatchString(fnSig) { + return matcher.spanType, true + } + } + + return 0, false +} + +func isCall(n ast.Node) bool { + _, ok := n.(*ast.CallExpr) + return ok +} + +func getID(node ast.Node) *ast.Ident { + switch stmt := node.(type) { + case *ast.ValueSpec: + if len(stmt.Names) > 1 { + return stmt.Names[1] + } else if len(stmt.Names) == 1 { + return stmt.Names[0] + } + case *ast.AssignStmt: + if len(stmt.Lhs) > 1 { + id, _ := stmt.Lhs[1].(*ast.Ident) + return id + } else if len(stmt.Lhs) == 1 { + id, _ := stmt.Lhs[0].(*ast.Ident) + return id + } + } + return nil +} + +// getMissingSpanCalls finds a path through the CFG, from stmt (which defines +// the 'span' variable v) to a return statement, that doesn't call the passed selector on the span. +func getMissingSpanCalls( + pass *analysis.Pass, + g *cfg.CFG, + sv spanVar, + selName string, + checkErr func(pass *analysis.Pass, ret *ast.ReturnStmt) *ast.ReturnStmt, + ignoreCheckSig *regexp.Regexp, + spanStartMatchers []spanStartMatcher, +) *ast.ReturnStmt { + // blockUses computes "uses" for each block, caching the result. + memo := make(map[*cfg.Block]bool) + blockUses := func(pass *analysis.Pass, b *cfg.Block) bool { + res, ok := memo[b] + if !ok { + res = usesCall(pass, b.Nodes, sv, selName, ignoreCheckSig, spanStartMatchers, 0) + memo[b] = res + } + return res + } + + // Find the var's defining block in the CFG, + // plus the rest of the statements of that block. + var defBlock *cfg.Block + var rest []ast.Node +outer: + for _, b := range g.Blocks { + for i, n := range b.Nodes { + if n == sv.stmt { + defBlock = b + rest = b.Nodes[i+1:] + break outer + } + } + } + + // Is the call "used" in the remainder of its defining block? + if usesCall(pass, rest, sv, selName, ignoreCheckSig, spanStartMatchers, 0) { + return nil + } + + // Does the defining block return without making the call? + if ret := defBlock.Return(); ret != nil { + return checkErr(pass, ret) + } + + // Search the CFG depth-first for a path, from defblock to a + // return block, in which v is never "used". + seen := make(map[*cfg.Block]bool) + var search func(blocks []*cfg.Block) *ast.ReturnStmt + search = func(blocks []*cfg.Block) *ast.ReturnStmt { + for _, b := range blocks { + if seen[b] { + continue + } + seen[b] = true + + // Prune the search if the block uses v. + if blockUses(pass, b) { + continue + } + + // Found path to return statement? + if ret := getErrorReturn(pass, b.Return()); ret != nil { + return ret // found + } + + // Recur + if ret := getErrorReturn(pass, search(b.Succs)); ret != nil { + return ret + } + } + return nil + } + + return search(defBlock.Succs) +} + +// usesCall reports whether stmts contain a use of the selName call on variable v. +func usesCall( + pass *analysis.Pass, + stmts []ast.Node, + sv spanVar, + selName string, + ignoreCheckSig *regexp.Regexp, + startSpanMatchers []spanStartMatcher, + depth int, +) bool { + if depth > 1 { // for perf reasons, do not dive too deep thru func literals, just one level deep check. + return false + } + + found, reAssigned := false, false + for _, subStmt := range stmts { + stack := []ast.Node{} + ast.Inspect(subStmt, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.FuncLit: + if len(stack) > 0 { + cfgs := pass.ResultOf[ctrlflow.Analyzer].(*ctrlflow.CFGs) + g := cfgs.FuncLit(n) + if g != nil && len(g.Blocks) > 0 { + return usesCall(pass, g.Blocks[0].Nodes, sv, selName, ignoreCheckSig, startSpanMatchers, depth+1) + } + + return false + } + case *ast.CallExpr: + if ident, ok := n.Fun.(*ast.Ident); ok { + fnSig := pass.TypesInfo.ObjectOf(ident).String() + if ignoreCheckSig != nil && ignoreCheckSig.MatchString(fnSig) { + found = true + return false + } + } + case nil: + if len(stack) > 0 { + stack = stack[:len(stack)-1] // pop + return true + } + return false + } + stack = append(stack, n) // push + + // Check whether the span was assigned over top of its old value. + _, isStart := isSpanStart(pass.TypesInfo, n, startSpanMatchers) + if isStart { + if id := getID(stack[len(stack)-3]); id != nil && id.Obj.Decl == sv.id.Obj.Decl { + reAssigned = true + return false + } + } + + if n, ok := n.(*ast.SelectorExpr); ok { + // Selector (End, SetStatus, RecordError) hit. + if n.Sel.Name == selName { + id, ok := n.X.(*ast.Ident) + found = ok && id.Obj != nil && id.Obj.Decl == sv.id.Obj.Decl + } + + // Check if an ignore signature matches. + fnSig := pass.TypesInfo.ObjectOf(n.Sel).String() + if ignoreCheckSig != nil && ignoreCheckSig.MatchString(fnSig) { + found = true + } + } + + return !found + }) + } + + return found && !reAssigned +} + +func getErrorReturn(pass *analysis.Pass, ret *ast.ReturnStmt) *ast.ReturnStmt { + if ret == nil { + return nil + } + + for _, r := range ret.Results { + if isErrorType(pass.TypesInfo.TypeOf(r)) { + return ret + } + + if r, ok := r.(*ast.CallExpr); ok { + for _, err := range errorsByArg(pass, r) { + if err { + return ret + } + } + } + } + + return nil +} + +// errorsByArg returns a slice s such that +// len(s) == number of return types of call +// s[i] == true iff return type at position i from left is an error type +// +// copied from https://github.com/kisielk/errcheck/blob/master/errcheck/errcheck.go +func errorsByArg(pass *analysis.Pass, call *ast.CallExpr) []bool { + switch t := pass.TypesInfo.Types[call].Type.(type) { + case *types.Named: + // Single return + return []bool{isErrorType(t)} + case *types.Pointer: + // Single return via pointer + return []bool{isErrorType(t)} + case *types.Tuple: + // Multiple returns + s := make([]bool, t.Len()) + for i := 0; i < t.Len(); i++ { + switch et := t.At(i).Type().(type) { + case *types.Named: + // Single return + s[i] = isErrorType(et) + case *types.Pointer: + // Single return via pointer + s[i] = isErrorType(et) + default: + s[i] = false + } + } + return s + } + return []bool{false} +} + +func isErrorType(t types.Type) bool { + return types.Implements(t, errorType) +} diff --git a/tools/vendor/github.com/karamaru-alpha/copyloopvar/.gitignore b/tools/vendor/github.com/karamaru-alpha/copyloopvar/.gitignore new file mode 100644 index 000000000..816abbd92 --- /dev/null +++ b/tools/vendor/github.com/karamaru-alpha/copyloopvar/.gitignore @@ -0,0 +1,2 @@ +.idea/ +copyloopvar diff --git a/tools/vendor/github.com/sivchari/nosnakecase/LICENSE b/tools/vendor/github.com/karamaru-alpha/copyloopvar/LICENSE similarity index 96% rename from tools/vendor/github.com/sivchari/nosnakecase/LICENSE rename to tools/vendor/github.com/karamaru-alpha/copyloopvar/LICENSE index fb4127677..e2567fd0c 100644 --- a/tools/vendor/github.com/sivchari/nosnakecase/LICENSE +++ b/tools/vendor/github.com/karamaru-alpha/copyloopvar/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2022 sivchari +Copyright (c) 2024 Ryosei Karaki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/tools/vendor/github.com/karamaru-alpha/copyloopvar/README.md b/tools/vendor/github.com/karamaru-alpha/copyloopvar/README.md new file mode 100644 index 000000000..d31d1abd9 --- /dev/null +++ b/tools/vendor/github.com/karamaru-alpha/copyloopvar/README.md @@ -0,0 +1,27 @@ +# copyloopvar + +copyloopvar is a linter detects places where loop variables are copied. + +cf. [Fixing For Loops in Go 1.22](https://go.dev/blog/loopvar-preview) + +## Example + +```go +for i, v := range []int{1, 2, 3} { + i := i // The copy of the 'for' variable "i" can be deleted (Go 1.22+) + v := v // The copy of the 'for' variable "v" can be deleted (Go 1.22+) + _, _ = i, v +} + +for i := 1; i <= 3; i++ { + i := i // The copy of the 'for' variable "i" can be deleted (Go 1.22+) + _ = i +} +``` + +## Install + +```bash +go install github.com/karamaru-alpha/copyloopvar/cmd/copyloopvar@latest +go vet -vettool=`which copyloopvar` ./... +``` diff --git a/tools/vendor/github.com/karamaru-alpha/copyloopvar/copyloopvar.go b/tools/vendor/github.com/karamaru-alpha/copyloopvar/copyloopvar.go new file mode 100644 index 000000000..79dc6afcc --- /dev/null +++ b/tools/vendor/github.com/karamaru-alpha/copyloopvar/copyloopvar.go @@ -0,0 +1,133 @@ +package copyloopvar + +import ( + "fmt" + "go/ast" + "go/token" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var checkAlias bool + +func NewAnalyzer() *analysis.Analyzer { + analyzer := &analysis.Analyzer{ + Name: "copyloopvar", + Doc: "copyloopvar is a linter detects places where loop variables are copied", + Run: run, + Requires: []*analysis.Analyzer{ + inspect.Analyzer, + }, + } + analyzer.Flags.BoolVar(&checkAlias, "check-alias", false, "check all assigning the loop variable to another variable") + return analyzer +} + +func run(pass *analysis.Pass) (any, error) { + pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{ + (*ast.RangeStmt)(nil), + (*ast.ForStmt)(nil), + }, func(n ast.Node) { + switch node := n.(type) { + case *ast.RangeStmt: + checkRangeStmt(pass, node) + case *ast.ForStmt: + checkForStmt(pass, node) + } + }) + + return nil, nil +} + +func checkRangeStmt(pass *analysis.Pass, rangeStmt *ast.RangeStmt) { + key, ok := rangeStmt.Key.(*ast.Ident) + if !ok { + return + } + var value *ast.Ident + if rangeStmt.Value != nil { + if value, ok = rangeStmt.Value.(*ast.Ident); !ok { + return + } + } + for _, stmt := range rangeStmt.Body.List { + assignStmt, ok := stmt.(*ast.AssignStmt) + if !ok { + continue + } + if assignStmt.Tok != token.DEFINE { + continue + } + for i, rh := range assignStmt.Rhs { + right, ok := rh.(*ast.Ident) + if !ok { + continue + } + if right.Name != key.Name && (value == nil || right.Name != value.Name) { + continue + } + if !checkAlias { + left, ok := assignStmt.Lhs[i].(*ast.Ident) + if !ok { + continue + } + if left.Name != right.Name { + continue + } + } + pass.Report(analysis.Diagnostic{ + Pos: assignStmt.Pos(), + Message: fmt.Sprintf(`The copy of the 'for' variable "%s" can be deleted (Go 1.22+)`, right.Name), + }) + } + } +} + +func checkForStmt(pass *analysis.Pass, forStmt *ast.ForStmt) { + if forStmt.Init == nil { + return + } + initAssignStmt, ok := forStmt.Init.(*ast.AssignStmt) + if !ok { + return + } + initVarNameMap := make(map[string]interface{}, len(initAssignStmt.Lhs)) + for _, lh := range initAssignStmt.Lhs { + if initVar, ok := lh.(*ast.Ident); ok { + initVarNameMap[initVar.Name] = struct{}{} + } + } + for _, stmt := range forStmt.Body.List { + assignStmt, ok := stmt.(*ast.AssignStmt) + if !ok { + continue + } + if assignStmt.Tok != token.DEFINE { + continue + } + for i, rh := range assignStmt.Rhs { + right, ok := rh.(*ast.Ident) + if !ok { + continue + } + if _, ok := initVarNameMap[right.Name]; !ok { + continue + } + if !checkAlias { + left, ok := assignStmt.Lhs[i].(*ast.Ident) + if !ok { + continue + } + if left.Name != right.Name { + continue + } + } + pass.Report(analysis.Diagnostic{ + Pos: assignStmt.Pos(), + Message: fmt.Sprintf(`The copy of the 'for' variable "%s" can be deleted (Go 1.22+)`, right.Name), + }) + } + } +} diff --git a/tools/vendor/github.com/kisielk/errcheck/errcheck/analyzer.go b/tools/vendor/github.com/kisielk/errcheck/errcheck/analyzer.go index 68593cc9a..82ab6298a 100644 --- a/tools/vendor/github.com/kisielk/errcheck/errcheck/analyzer.go +++ b/tools/vendor/github.com/kisielk/errcheck/errcheck/analyzer.go @@ -31,7 +31,6 @@ func init() { } func runAnalyzer(pass *analysis.Pass) (interface{}, error) { - exclude := map[string]bool{} if !argExcludeOnly { for _, name := range DefaultExcludedSymbols { @@ -65,8 +64,9 @@ func runAnalyzer(pass *analysis.Pass) (interface{}, error) { for _, err := range v.errors { pass.Report(analysis.Diagnostic{ - Pos: pass.Fset.File(f.Pos()).Pos(err.Pos.Offset), - Message: "unchecked error", + Pos: pass.Fset.File(f.Pos()).Pos(err.Pos.Offset), + Message: "unchecked error", + Category: "errcheck", }) } diff --git a/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go b/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go index a5ee3711c..d61d348f7 100644 --- a/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go +++ b/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go @@ -167,7 +167,7 @@ func (c *Checker) LoadPackages(paths ...string) ([]*packages.Package, error) { buildFlags = append(buildFlags, fmt.Sprintf("-mod=%s", c.Mod)) } cfg := &packages.Config{ - Mode: packages.LoadAllSyntax, + Mode: packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo, Tests: !c.Exclusions.TestFiles, BuildFlags: buildFlags, } @@ -205,7 +205,7 @@ func (c *Checker) CheckPackage(pkg *packages.Package) Result { ignore := map[string]*regexp.Regexp{} // Apply SymbolRegexpsByPackage first so that if the same path appears in - // Packages, a more narrow regexp will be superceded by dotStar below. + // Packages, a more narrow regexp will be superseded by dotStar below. if regexps := c.Exclusions.SymbolRegexpsByPackage; regexps != nil { for pkg, re := range regexps { // TODO warn if previous entry overwritten? @@ -337,7 +337,7 @@ func (v *visitor) selectorName(call *ast.CallExpr) string { // names are returned. If the function is package-qualified (like "fmt.Printf()") // then just that function's fullName is returned. // -// Otherwise, we walk through all the potentially embeddded interfaces of the receiver +// Otherwise, we walk through all the potentially embedded interfaces of the receiver // the collect a list of type-qualified function names that we will check. func (v *visitor) namesForExcludeCheck(call *ast.CallExpr) []string { sel, fn, ok := v.selectorAndFunc(call) diff --git a/tools/vendor/github.com/kisielk/errcheck/errcheck/excludes.go b/tools/vendor/github.com/kisielk/errcheck/errcheck/excludes.go index 22db9fe11..a783b5a76 100644 --- a/tools/vendor/github.com/kisielk/errcheck/errcheck/excludes.go +++ b/tools/vendor/github.com/kisielk/errcheck/errcheck/excludes.go @@ -3,64 +3,60 @@ package errcheck import ( "bufio" "bytes" - "io/ioutil" + "os" "strings" ) -var ( - // DefaultExcludedSymbols is a list of symbol names that are usually excluded from checks by default. - // - // Note, that they still need to be explicitly copied to Checker.Exclusions.Symbols - DefaultExcludedSymbols = []string{ - // bytes - "(*bytes.Buffer).Write", - "(*bytes.Buffer).WriteByte", - "(*bytes.Buffer).WriteRune", - "(*bytes.Buffer).WriteString", +// DefaultExcludedSymbols is a list of symbol names that are usually excluded from checks by default. +// +// Note, that they still need to be explicitly copied to Checker.Exclusions.Symbols +var DefaultExcludedSymbols = []string{ + // bytes + "(*bytes.Buffer).Write", + "(*bytes.Buffer).WriteByte", + "(*bytes.Buffer).WriteRune", + "(*bytes.Buffer).WriteString", - // fmt - "fmt.Errorf", - "fmt.Print", - "fmt.Printf", - "fmt.Println", - "fmt.Fprint(*bytes.Buffer)", - "fmt.Fprintf(*bytes.Buffer)", - "fmt.Fprintln(*bytes.Buffer)", - "fmt.Fprint(*strings.Builder)", - "fmt.Fprintf(*strings.Builder)", - "fmt.Fprintln(*strings.Builder)", - "fmt.Fprint(os.Stderr)", - "fmt.Fprintf(os.Stderr)", - "fmt.Fprintln(os.Stderr)", + // fmt + "fmt.Print", + "fmt.Printf", + "fmt.Println", + "fmt.Fprint(*bytes.Buffer)", + "fmt.Fprintf(*bytes.Buffer)", + "fmt.Fprintln(*bytes.Buffer)", + "fmt.Fprint(*strings.Builder)", + "fmt.Fprintf(*strings.Builder)", + "fmt.Fprintln(*strings.Builder)", + "fmt.Fprint(os.Stderr)", + "fmt.Fprintf(os.Stderr)", + "fmt.Fprintln(os.Stderr)", - // io - "(*io.PipeReader).CloseWithError", - "(*io.PipeWriter).CloseWithError", + // io + "(*io.PipeReader).CloseWithError", + "(*io.PipeWriter).CloseWithError", - // math/rand - "math/rand.Read", - "(*math/rand.Rand).Read", + // math/rand + "math/rand.Read", + "(*math/rand.Rand).Read", - // strings - "(*strings.Builder).Write", - "(*strings.Builder).WriteByte", - "(*strings.Builder).WriteRune", - "(*strings.Builder).WriteString", + // strings + "(*strings.Builder).Write", + "(*strings.Builder).WriteByte", + "(*strings.Builder).WriteRune", + "(*strings.Builder).WriteString", - // hash - "(hash.Hash).Write", - } -) + // hash + "(hash.Hash).Write", +} // ReadExcludes reads an excludes file, a newline delimited file that lists // patterns for which to allow unchecked errors. // // Lines that start with two forward slashes are considered comments and are ignored. -// func ReadExcludes(path string) ([]string, error) { var excludes []string - buf, err := ioutil.ReadFile(path) + buf, err := os.ReadFile(path) if err != nil { return nil, err } diff --git a/tools/vendor/github.com/kisielk/gotool/.travis.yml b/tools/vendor/github.com/kisielk/gotool/.travis.yml deleted file mode 100644 index d1784e1e2..000000000 --- a/tools/vendor/github.com/kisielk/gotool/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -sudo: false -language: go -go: - - 1.2 - - 1.3 - - 1.4 - - 1.5 - - 1.6 - - 1.7 - - 1.8 - - 1.9 - - master -matrix: - allow_failures: - - go: master - fast_finish: true -install: - - # Skip. -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go tool vet . - - go test -v -race ./... diff --git a/tools/vendor/github.com/kisielk/gotool/LEGAL b/tools/vendor/github.com/kisielk/gotool/LEGAL deleted file mode 100644 index 72b859cd6..000000000 --- a/tools/vendor/github.com/kisielk/gotool/LEGAL +++ /dev/null @@ -1,32 +0,0 @@ -All the files in this distribution are covered under either the MIT -license (see the file LICENSE) except some files mentioned below. - -match.go, match_test.go: - - Copyright (c) 2009 The Go 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: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - * Neither the name of Google Inc. nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/vendor/github.com/kisielk/gotool/LICENSE b/tools/vendor/github.com/kisielk/gotool/LICENSE deleted file mode 100644 index 1cbf651e2..000000000 --- a/tools/vendor/github.com/kisielk/gotool/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013 Kamil Kisiel - -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/tools/vendor/github.com/kisielk/gotool/README.md b/tools/vendor/github.com/kisielk/gotool/README.md deleted file mode 100644 index 6e4e92b2f..000000000 --- a/tools/vendor/github.com/kisielk/gotool/README.md +++ /dev/null @@ -1,6 +0,0 @@ -gotool -====== -[![GoDoc](https://godoc.org/github.com/kisielk/gotool?status.svg)](https://godoc.org/github.com/kisielk/gotool) -[![Build Status](https://travis-ci.org/kisielk/gotool.svg?branch=master)](https://travis-ci.org/kisielk/gotool) - -Package gotool contains utility functions used to implement the standard "cmd/go" tool, provided as a convenience to developers who want to write tools with similar semantics. diff --git a/tools/vendor/github.com/kisielk/gotool/go13.go b/tools/vendor/github.com/kisielk/gotool/go13.go deleted file mode 100644 index 2dd9b3fdf..000000000 --- a/tools/vendor/github.com/kisielk/gotool/go13.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !go1.4 - -package gotool - -import ( - "go/build" - "path/filepath" - "runtime" -) - -var gorootSrc = filepath.Join(runtime.GOROOT(), "src", "pkg") - -func shouldIgnoreImport(p *build.Package) bool { - return true -} diff --git a/tools/vendor/github.com/kisielk/gotool/go14-15.go b/tools/vendor/github.com/kisielk/gotool/go14-15.go deleted file mode 100644 index aa99a3227..000000000 --- a/tools/vendor/github.com/kisielk/gotool/go14-15.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build go1.4,!go1.6 - -package gotool - -import ( - "go/build" - "path/filepath" - "runtime" -) - -var gorootSrc = filepath.Join(runtime.GOROOT(), "src") - -func shouldIgnoreImport(p *build.Package) bool { - return true -} diff --git a/tools/vendor/github.com/kisielk/gotool/go16-18.go b/tools/vendor/github.com/kisielk/gotool/go16-18.go deleted file mode 100644 index f25cec14a..000000000 --- a/tools/vendor/github.com/kisielk/gotool/go16-18.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build go1.6,!go1.9 - -package gotool - -import ( - "go/build" - "path/filepath" - "runtime" -) - -var gorootSrc = filepath.Join(runtime.GOROOT(), "src") - -func shouldIgnoreImport(p *build.Package) bool { - return p == nil || len(p.InvalidGoFiles) == 0 -} diff --git a/tools/vendor/github.com/kisielk/gotool/internal/load/path.go b/tools/vendor/github.com/kisielk/gotool/internal/load/path.go deleted file mode 100644 index 74e15b9d3..000000000 --- a/tools/vendor/github.com/kisielk/gotool/internal/load/path.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package load - -import ( - "strings" -) - -// hasPathPrefix reports whether the path s begins with the -// elements in prefix. -func hasPathPrefix(s, prefix string) bool { - switch { - default: - return false - case len(s) == len(prefix): - return s == prefix - case len(s) > len(prefix): - if prefix != "" && prefix[len(prefix)-1] == '/' { - return strings.HasPrefix(s, prefix) - } - return s[len(prefix)] == '/' && s[:len(prefix)] == prefix - } -} diff --git a/tools/vendor/github.com/kisielk/gotool/internal/load/pkg.go b/tools/vendor/github.com/kisielk/gotool/internal/load/pkg.go deleted file mode 100644 index b937ede75..000000000 --- a/tools/vendor/github.com/kisielk/gotool/internal/load/pkg.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -// Package load loads packages. -package load - -import ( - "strings" -) - -// isStandardImportPath reports whether $GOROOT/src/path should be considered -// part of the standard distribution. For historical reasons we allow people to add -// their own code to $GOROOT instead of using $GOPATH, but we assume that -// code will start with a domain name (dot in the first element). -func isStandardImportPath(path string) bool { - i := strings.Index(path, "/") - if i < 0 { - i = len(path) - } - elem := path[:i] - return !strings.Contains(elem, ".") -} diff --git a/tools/vendor/github.com/kisielk/gotool/internal/load/search.go b/tools/vendor/github.com/kisielk/gotool/internal/load/search.go deleted file mode 100644 index 17ed62dda..000000000 --- a/tools/vendor/github.com/kisielk/gotool/internal/load/search.go +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package load - -import ( - "fmt" - "go/build" - "log" - "os" - "path" - "path/filepath" - "regexp" - "strings" -) - -// Context specifies values for operation of ImportPaths that would -// otherwise come from cmd/go/internal/cfg package. -// -// This is a construct added for gotool purposes and doesn't have -// an equivalent upstream in cmd/go. -type Context struct { - // BuildContext is the build context to use. - BuildContext build.Context - - // GOROOTsrc is the location of the src directory in GOROOT. - // At this time, it's used only in MatchPackages to skip - // GOOROOT/src entry from BuildContext.SrcDirs output. - GOROOTsrc string -} - -// allPackages returns all the packages that can be found -// under the $GOPATH directories and $GOROOT matching pattern. -// The pattern is either "all" (all packages), "std" (standard packages), -// "cmd" (standard commands), or a path including "...". -func (c *Context) allPackages(pattern string) []string { - pkgs := c.MatchPackages(pattern) - if len(pkgs) == 0 { - fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) - } - return pkgs -} - -// allPackagesInFS is like allPackages but is passed a pattern -// beginning ./ or ../, meaning it should scan the tree rooted -// at the given directory. There are ... in the pattern too. -func (c *Context) allPackagesInFS(pattern string) []string { - pkgs := c.MatchPackagesInFS(pattern) - if len(pkgs) == 0 { - fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) - } - return pkgs -} - -// MatchPackages returns a list of package paths matching pattern -// (see go help packages for pattern syntax). -func (c *Context) MatchPackages(pattern string) []string { - match := func(string) bool { return true } - treeCanMatch := func(string) bool { return true } - if !IsMetaPackage(pattern) { - match = matchPattern(pattern) - treeCanMatch = treeCanMatchPattern(pattern) - } - - have := map[string]bool{ - "builtin": true, // ignore pseudo-package that exists only for documentation - } - if !c.BuildContext.CgoEnabled { - have["runtime/cgo"] = true // ignore during walk - } - var pkgs []string - - for _, src := range c.BuildContext.SrcDirs() { - if (pattern == "std" || pattern == "cmd") && src != c.GOROOTsrc { - continue - } - src = filepath.Clean(src) + string(filepath.Separator) - root := src - if pattern == "cmd" { - root += "cmd" + string(filepath.Separator) - } - filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { - if err != nil || path == src { - return nil - } - - want := true - // Avoid .foo, _foo, and testdata directory trees. - _, elem := filepath.Split(path) - if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" { - want = false - } - - name := filepath.ToSlash(path[len(src):]) - if pattern == "std" && (!isStandardImportPath(name) || name == "cmd") { - // The name "std" is only the standard library. - // If the name is cmd, it's the root of the command tree. - want = false - } - if !treeCanMatch(name) { - want = false - } - - if !fi.IsDir() { - if fi.Mode()&os.ModeSymlink != 0 && want { - if target, err := os.Stat(path); err == nil && target.IsDir() { - fmt.Fprintf(os.Stderr, "warning: ignoring symlink %s\n", path) - } - } - return nil - } - if !want { - return filepath.SkipDir - } - - if have[name] { - return nil - } - have[name] = true - if !match(name) { - return nil - } - pkg, err := c.BuildContext.ImportDir(path, 0) - if err != nil { - if _, noGo := err.(*build.NoGoError); noGo { - return nil - } - } - - // If we are expanding "cmd", skip main - // packages under cmd/vendor. At least as of - // March, 2017, there is one there for the - // vendored pprof tool. - if pattern == "cmd" && strings.HasPrefix(pkg.ImportPath, "cmd/vendor") && pkg.Name == "main" { - return nil - } - - pkgs = append(pkgs, name) - return nil - }) - } - return pkgs -} - -// MatchPackagesInFS returns a list of package paths matching pattern, -// which must begin with ./ or ../ -// (see go help packages for pattern syntax). -func (c *Context) MatchPackagesInFS(pattern string) []string { - // Find directory to begin the scan. - // Could be smarter but this one optimization - // is enough for now, since ... is usually at the - // end of a path. - i := strings.Index(pattern, "...") - dir, _ := path.Split(pattern[:i]) - - // pattern begins with ./ or ../. - // path.Clean will discard the ./ but not the ../. - // We need to preserve the ./ for pattern matching - // and in the returned import paths. - prefix := "" - if strings.HasPrefix(pattern, "./") { - prefix = "./" - } - match := matchPattern(pattern) - - var pkgs []string - filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error { - if err != nil || !fi.IsDir() { - return nil - } - if path == dir { - // filepath.Walk starts at dir and recurses. For the recursive case, - // the path is the result of filepath.Join, which calls filepath.Clean. - // The initial case is not Cleaned, though, so we do this explicitly. - // - // This converts a path like "./io/" to "io". Without this step, running - // "cd $GOROOT/src; go list ./io/..." would incorrectly skip the io - // package, because prepending the prefix "./" to the unclean path would - // result in "././io", and match("././io") returns false. - path = filepath.Clean(path) - } - - // Avoid .foo, _foo, and testdata directory trees, but do not avoid "." or "..". - _, elem := filepath.Split(path) - dot := strings.HasPrefix(elem, ".") && elem != "." && elem != ".." - if dot || strings.HasPrefix(elem, "_") || elem == "testdata" { - return filepath.SkipDir - } - - name := prefix + filepath.ToSlash(path) - if !match(name) { - return nil - } - - // We keep the directory if we can import it, or if we can't import it - // due to invalid Go source files. This means that directories containing - // parse errors will be built (and fail) instead of being silently skipped - // as not matching the pattern. Go 1.5 and earlier skipped, but that - // behavior means people miss serious mistakes. - // See golang.org/issue/11407. - if p, err := c.BuildContext.ImportDir(path, 0); err != nil && (p == nil || len(p.InvalidGoFiles) == 0) { - if _, noGo := err.(*build.NoGoError); !noGo { - log.Print(err) - } - return nil - } - pkgs = append(pkgs, name) - return nil - }) - return pkgs -} - -// treeCanMatchPattern(pattern)(name) reports whether -// name or children of name can possibly match pattern. -// Pattern is the same limited glob accepted by matchPattern. -func treeCanMatchPattern(pattern string) func(name string) bool { - wildCard := false - if i := strings.Index(pattern, "..."); i >= 0 { - wildCard = true - pattern = pattern[:i] - } - return func(name string) bool { - return len(name) <= len(pattern) && hasPathPrefix(pattern, name) || - wildCard && strings.HasPrefix(name, pattern) - } -} - -// matchPattern(pattern)(name) reports whether -// name matches pattern. Pattern is a limited glob -// pattern in which '...' means 'any string' and there -// is no other special syntax. -// Unfortunately, there are two special cases. Quoting "go help packages": -// -// First, /... at the end of the pattern can match an empty string, -// so that net/... matches both net and packages in its subdirectories, like net/http. -// Second, any slash-separted pattern element containing a wildcard never -// participates in a match of the "vendor" element in the path of a vendored -// package, so that ./... does not match packages in subdirectories of -// ./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do. -// Note, however, that a directory named vendor that itself contains code -// is not a vendored package: cmd/vendor would be a command named vendor, -// and the pattern cmd/... matches it. -func matchPattern(pattern string) func(name string) bool { - // Convert pattern to regular expression. - // The strategy for the trailing /... is to nest it in an explicit ? expression. - // The strategy for the vendor exclusion is to change the unmatchable - // vendor strings to a disallowed code point (vendorChar) and to use - // "(anything but that codepoint)*" as the implementation of the ... wildcard. - // This is a bit complicated but the obvious alternative, - // namely a hand-written search like in most shell glob matchers, - // is too easy to make accidentally exponential. - // Using package regexp guarantees linear-time matching. - - const vendorChar = "\x00" - - if strings.Contains(pattern, vendorChar) { - return func(name string) bool { return false } - } - - re := regexp.QuoteMeta(pattern) - re = replaceVendor(re, vendorChar) - switch { - case strings.HasSuffix(re, `/`+vendorChar+`/\.\.\.`): - re = strings.TrimSuffix(re, `/`+vendorChar+`/\.\.\.`) + `(/vendor|/` + vendorChar + `/\.\.\.)` - case re == vendorChar+`/\.\.\.`: - re = `(/vendor|/` + vendorChar + `/\.\.\.)` - case strings.HasSuffix(re, `/\.\.\.`): - re = strings.TrimSuffix(re, `/\.\.\.`) + `(/\.\.\.)?` - } - re = strings.Replace(re, `\.\.\.`, `[^`+vendorChar+`]*`, -1) - - reg := regexp.MustCompile(`^` + re + `$`) - - return func(name string) bool { - if strings.Contains(name, vendorChar) { - return false - } - return reg.MatchString(replaceVendor(name, vendorChar)) - } -} - -// replaceVendor returns the result of replacing -// non-trailing vendor path elements in x with repl. -func replaceVendor(x, repl string) string { - if !strings.Contains(x, "vendor") { - return x - } - elem := strings.Split(x, "/") - for i := 0; i < len(elem)-1; i++ { - if elem[i] == "vendor" { - elem[i] = repl - } - } - return strings.Join(elem, "/") -} - -// ImportPaths returns the import paths to use for the given command line. -func (c *Context) ImportPaths(args []string) []string { - args = c.ImportPathsNoDotExpansion(args) - var out []string - for _, a := range args { - if strings.Contains(a, "...") { - if build.IsLocalImport(a) { - out = append(out, c.allPackagesInFS(a)...) - } else { - out = append(out, c.allPackages(a)...) - } - continue - } - out = append(out, a) - } - return out -} - -// ImportPathsNoDotExpansion returns the import paths to use for the given -// command line, but it does no ... expansion. -func (c *Context) ImportPathsNoDotExpansion(args []string) []string { - if len(args) == 0 { - return []string{"."} - } - var out []string - for _, a := range args { - // Arguments are supposed to be import paths, but - // as a courtesy to Windows developers, rewrite \ to / - // in command-line arguments. Handles .\... and so on. - if filepath.Separator == '\\' { - a = strings.Replace(a, `\`, `/`, -1) - } - - // Put argument in canonical form, but preserve leading ./. - if strings.HasPrefix(a, "./") { - a = "./" + path.Clean(a) - if a == "./." { - a = "." - } - } else { - a = path.Clean(a) - } - if IsMetaPackage(a) { - out = append(out, c.allPackages(a)...) - continue - } - out = append(out, a) - } - return out -} - -// IsMetaPackage checks if name is a reserved package name that expands to multiple packages. -func IsMetaPackage(name string) bool { - return name == "std" || name == "cmd" || name == "all" -} diff --git a/tools/vendor/github.com/kisielk/gotool/match.go b/tools/vendor/github.com/kisielk/gotool/match.go deleted file mode 100644 index 4dbdbff47..000000000 --- a/tools/vendor/github.com/kisielk/gotool/match.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2009 The Go 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: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build go1.9 - -package gotool - -import ( - "path/filepath" - - "github.com/kisielk/gotool/internal/load" -) - -// importPaths returns the import paths to use for the given command line. -func (c *Context) importPaths(args []string) []string { - lctx := load.Context{ - BuildContext: c.BuildContext, - GOROOTsrc: c.joinPath(c.BuildContext.GOROOT, "src"), - } - return lctx.ImportPaths(args) -} - -// joinPath calls c.BuildContext.JoinPath (if not nil) or else filepath.Join. -// -// It's a copy of the unexported build.Context.joinPath helper. -func (c *Context) joinPath(elem ...string) string { - if f := c.BuildContext.JoinPath; f != nil { - return f(elem...) - } - return filepath.Join(elem...) -} diff --git a/tools/vendor/github.com/kisielk/gotool/match18.go b/tools/vendor/github.com/kisielk/gotool/match18.go deleted file mode 100644 index 6d6b1368c..000000000 --- a/tools/vendor/github.com/kisielk/gotool/match18.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright (c) 2009 The Go 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: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build !go1.9 - -package gotool - -import ( - "fmt" - "go/build" - "log" - "os" - "path" - "path/filepath" - "regexp" - "strings" -) - -// This file contains code from the Go distribution. - -// matchPattern(pattern)(name) reports whether -// name matches pattern. Pattern is a limited glob -// pattern in which '...' means 'any string' and there -// is no other special syntax. -func matchPattern(pattern string) func(name string) bool { - re := regexp.QuoteMeta(pattern) - re = strings.Replace(re, `\.\.\.`, `.*`, -1) - // Special case: foo/... matches foo too. - if strings.HasSuffix(re, `/.*`) { - re = re[:len(re)-len(`/.*`)] + `(/.*)?` - } - reg := regexp.MustCompile(`^` + re + `$`) - return reg.MatchString -} - -// matchPackages returns a list of package paths matching pattern -// (see go help packages for pattern syntax). -func (c *Context) matchPackages(pattern string) []string { - match := func(string) bool { return true } - treeCanMatch := func(string) bool { return true } - if !isMetaPackage(pattern) { - match = matchPattern(pattern) - treeCanMatch = treeCanMatchPattern(pattern) - } - - have := map[string]bool{ - "builtin": true, // ignore pseudo-package that exists only for documentation - } - if !c.BuildContext.CgoEnabled { - have["runtime/cgo"] = true // ignore during walk - } - var pkgs []string - - for _, src := range c.BuildContext.SrcDirs() { - if (pattern == "std" || pattern == "cmd") && src != gorootSrc { - continue - } - src = filepath.Clean(src) + string(filepath.Separator) - root := src - if pattern == "cmd" { - root += "cmd" + string(filepath.Separator) - } - filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { - if err != nil || !fi.IsDir() || path == src { - return nil - } - - // Avoid .foo, _foo, and testdata directory trees. - _, elem := filepath.Split(path) - if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" { - return filepath.SkipDir - } - - name := filepath.ToSlash(path[len(src):]) - if pattern == "std" && (!isStandardImportPath(name) || name == "cmd") { - // The name "std" is only the standard library. - // If the name is cmd, it's the root of the command tree. - return filepath.SkipDir - } - if !treeCanMatch(name) { - return filepath.SkipDir - } - if have[name] { - return nil - } - have[name] = true - if !match(name) { - return nil - } - _, err = c.BuildContext.ImportDir(path, 0) - if err != nil { - if _, noGo := err.(*build.NoGoError); noGo { - return nil - } - } - pkgs = append(pkgs, name) - return nil - }) - } - return pkgs -} - -// importPathsNoDotExpansion returns the import paths to use for the given -// command line, but it does no ... expansion. -func (c *Context) importPathsNoDotExpansion(args []string) []string { - if len(args) == 0 { - return []string{"."} - } - var out []string - for _, a := range args { - // Arguments are supposed to be import paths, but - // as a courtesy to Windows developers, rewrite \ to / - // in command-line arguments. Handles .\... and so on. - if filepath.Separator == '\\' { - a = strings.Replace(a, `\`, `/`, -1) - } - - // Put argument in canonical form, but preserve leading ./. - if strings.HasPrefix(a, "./") { - a = "./" + path.Clean(a) - if a == "./." { - a = "." - } - } else { - a = path.Clean(a) - } - if isMetaPackage(a) { - out = append(out, c.allPackages(a)...) - continue - } - out = append(out, a) - } - return out -} - -// importPaths returns the import paths to use for the given command line. -func (c *Context) importPaths(args []string) []string { - args = c.importPathsNoDotExpansion(args) - var out []string - for _, a := range args { - if strings.Contains(a, "...") { - if build.IsLocalImport(a) { - out = append(out, c.allPackagesInFS(a)...) - } else { - out = append(out, c.allPackages(a)...) - } - continue - } - out = append(out, a) - } - return out -} - -// allPackages returns all the packages that can be found -// under the $GOPATH directories and $GOROOT matching pattern. -// The pattern is either "all" (all packages), "std" (standard packages), -// "cmd" (standard commands), or a path including "...". -func (c *Context) allPackages(pattern string) []string { - pkgs := c.matchPackages(pattern) - if len(pkgs) == 0 { - fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) - } - return pkgs -} - -// allPackagesInFS is like allPackages but is passed a pattern -// beginning ./ or ../, meaning it should scan the tree rooted -// at the given directory. There are ... in the pattern too. -func (c *Context) allPackagesInFS(pattern string) []string { - pkgs := c.matchPackagesInFS(pattern) - if len(pkgs) == 0 { - fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) - } - return pkgs -} - -// matchPackagesInFS returns a list of package paths matching pattern, -// which must begin with ./ or ../ -// (see go help packages for pattern syntax). -func (c *Context) matchPackagesInFS(pattern string) []string { - // Find directory to begin the scan. - // Could be smarter but this one optimization - // is enough for now, since ... is usually at the - // end of a path. - i := strings.Index(pattern, "...") - dir, _ := path.Split(pattern[:i]) - - // pattern begins with ./ or ../. - // path.Clean will discard the ./ but not the ../. - // We need to preserve the ./ for pattern matching - // and in the returned import paths. - prefix := "" - if strings.HasPrefix(pattern, "./") { - prefix = "./" - } - match := matchPattern(pattern) - - var pkgs []string - filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error { - if err != nil || !fi.IsDir() { - return nil - } - if path == dir { - // filepath.Walk starts at dir and recurses. For the recursive case, - // the path is the result of filepath.Join, which calls filepath.Clean. - // The initial case is not Cleaned, though, so we do this explicitly. - // - // This converts a path like "./io/" to "io". Without this step, running - // "cd $GOROOT/src; go list ./io/..." would incorrectly skip the io - // package, because prepending the prefix "./" to the unclean path would - // result in "././io", and match("././io") returns false. - path = filepath.Clean(path) - } - - // Avoid .foo, _foo, and testdata directory trees, but do not avoid "." or "..". - _, elem := filepath.Split(path) - dot := strings.HasPrefix(elem, ".") && elem != "." && elem != ".." - if dot || strings.HasPrefix(elem, "_") || elem == "testdata" { - return filepath.SkipDir - } - - name := prefix + filepath.ToSlash(path) - if !match(name) { - return nil - } - - // We keep the directory if we can import it, or if we can't import it - // due to invalid Go source files. This means that directories containing - // parse errors will be built (and fail) instead of being silently skipped - // as not matching the pattern. Go 1.5 and earlier skipped, but that - // behavior means people miss serious mistakes. - // See golang.org/issue/11407. - if p, err := c.BuildContext.ImportDir(path, 0); err != nil && shouldIgnoreImport(p) { - if _, noGo := err.(*build.NoGoError); !noGo { - log.Print(err) - } - return nil - } - pkgs = append(pkgs, name) - return nil - }) - return pkgs -} - -// isMetaPackage checks if name is a reserved package name that expands to multiple packages. -func isMetaPackage(name string) bool { - return name == "std" || name == "cmd" || name == "all" -} - -// isStandardImportPath reports whether $GOROOT/src/path should be considered -// part of the standard distribution. For historical reasons we allow people to add -// their own code to $GOROOT instead of using $GOPATH, but we assume that -// code will start with a domain name (dot in the first element). -func isStandardImportPath(path string) bool { - i := strings.Index(path, "/") - if i < 0 { - i = len(path) - } - elem := path[:i] - return !strings.Contains(elem, ".") -} - -// hasPathPrefix reports whether the path s begins with the -// elements in prefix. -func hasPathPrefix(s, prefix string) bool { - switch { - default: - return false - case len(s) == len(prefix): - return s == prefix - case len(s) > len(prefix): - if prefix != "" && prefix[len(prefix)-1] == '/' { - return strings.HasPrefix(s, prefix) - } - return s[len(prefix)] == '/' && s[:len(prefix)] == prefix - } -} - -// treeCanMatchPattern(pattern)(name) reports whether -// name or children of name can possibly match pattern. -// Pattern is the same limited glob accepted by matchPattern. -func treeCanMatchPattern(pattern string) func(name string) bool { - wildCard := false - if i := strings.Index(pattern, "..."); i >= 0 { - wildCard = true - pattern = pattern[:i] - } - return func(name string) bool { - return len(name) <= len(pattern) && hasPathPrefix(pattern, name) || - wildCard && strings.HasPrefix(name, pattern) - } -} diff --git a/tools/vendor/github.com/kisielk/gotool/tool.go b/tools/vendor/github.com/kisielk/gotool/tool.go deleted file mode 100644 index c7409e11e..000000000 --- a/tools/vendor/github.com/kisielk/gotool/tool.go +++ /dev/null @@ -1,48 +0,0 @@ -// Package gotool contains utility functions used to implement the standard -// "cmd/go" tool, provided as a convenience to developers who want to write -// tools with similar semantics. -package gotool - -import "go/build" - -// Export functions here to make it easier to keep the implementations up to date with upstream. - -// DefaultContext is the default context that uses build.Default. -var DefaultContext = Context{ - BuildContext: build.Default, -} - -// A Context specifies the supporting context. -type Context struct { - // BuildContext is the build.Context that is used when computing import paths. - BuildContext build.Context -} - -// ImportPaths returns the import paths to use for the given command line. -// -// The path "all" is expanded to all packages in $GOPATH and $GOROOT. -// The path "std" is expanded to all packages in the Go standard library. -// The path "cmd" is expanded to all Go standard commands. -// The string "..." is treated as a wildcard within a path. -// When matching recursively, directories are ignored if they are prefixed with -// a dot or an underscore (such as ".foo" or "_foo"), or are named "testdata". -// Relative import paths are not converted to full import paths. -// If args is empty, a single element "." is returned. -func (c *Context) ImportPaths(args []string) []string { - return c.importPaths(args) -} - -// ImportPaths returns the import paths to use for the given command line -// using default context. -// -// The path "all" is expanded to all packages in $GOPATH and $GOROOT. -// The path "std" is expanded to all packages in the Go standard library. -// The path "cmd" is expanded to all Go standard commands. -// The string "..." is treated as a wildcard within a path. -// When matching recursively, directories are ignored if they are prefixed with -// a dot or an underscore (such as ".foo" or "_foo"), or are named "testdata". -// Relative import paths are not converted to full import paths. -// If args is empty, a single element "." is returned. -func ImportPaths(args []string) []string { - return DefaultContext.importPaths(args) -} diff --git a/tools/vendor/github.com/kkHAIKE/contextcheck/.gitignore b/tools/vendor/github.com/kkHAIKE/contextcheck/.gitignore index fc1b400c8..1c2ffa5f4 100644 --- a/tools/vendor/github.com/kkHAIKE/contextcheck/.gitignore +++ b/tools/vendor/github.com/kkHAIKE/contextcheck/.gitignore @@ -16,3 +16,5 @@ .idea .DS_Store + +/contextcheck diff --git a/tools/vendor/github.com/kkHAIKE/contextcheck/Makefile b/tools/vendor/github.com/kkHAIKE/contextcheck/Makefile index 9321e9de3..613d35e93 100644 --- a/tools/vendor/github.com/kkHAIKE/contextcheck/Makefile +++ b/tools/vendor/github.com/kkHAIKE/contextcheck/Makefile @@ -1,5 +1,15 @@ +.PHONY: clean test build + +default: test build + +clean: + rm -rf dist/ cover.out + +test: clean + go test -v -cover ./... + build: - @GO111MODULE=on go build -ldflags '-s -w' -o contextcheck ./cmd/contextcheck/main.go + go build -ldflags '-s -w' -o contextcheck ./cmd/contextcheck/main.go install: - @GO111MODULE=on go install -ldflags '-s -w' ./cmd/contextcheck + go install -ldflags '-s -w' ./cmd/contextcheck diff --git a/tools/vendor/github.com/kkHAIKE/contextcheck/README.md b/tools/vendor/github.com/kkHAIKE/contextcheck/README.md index 2cc7b2e48..105b2de5a 100644 --- a/tools/vendor/github.com/kkHAIKE/contextcheck/README.md +++ b/tools/vendor/github.com/kkHAIKE/contextcheck/README.md @@ -3,7 +3,7 @@ # contextcheck -`contextcheck` is a static analysis tool, it is used to check whether the function uses a non-inherited context, which will result in a broken call link. +`contextcheck` is a static analysis tool used to check whether a function uses a non-inherited context that could result in a broken call link. For example: @@ -94,8 +94,8 @@ func NoInheritCancel(_ context.Context) (context.Context,context.CancelFunc) { } ``` -### skip check specify function -You can add `// nolint: contextcheck` in function decl doc comment, to skip this linter in some false-positive case. +### skip the check for the specified function +To skip this linter in some false-positive cases, you can add // nolint: contextcheck to the function declaration's comment. ```go // nolint: contextcheck @@ -112,8 +112,8 @@ func call3() { } ``` -### force mark specify function have server-side http.Request parameter -default behavior is mark http.HandlerFunc or a function use r.Context(). +### force the marking of a specified function as having a server-side http.Request parameter +The default behavior is to mark `http.HandlerFunc` or any function that uses `r.Context()`. ```go // @contextcheck(req_has_ctx) diff --git a/tools/vendor/github.com/kkHAIKE/contextcheck/contextcheck.go b/tools/vendor/github.com/kkHAIKE/contextcheck/contextcheck.go index c9ad0101f..62696351a 100644 --- a/tools/vendor/github.com/kkHAIKE/contextcheck/contextcheck.go +++ b/tools/vendor/github.com/kkHAIKE/contextcheck/contextcheck.go @@ -2,9 +2,9 @@ package contextcheck import ( "go/ast" + "go/token" "go/types" "regexp" - "strconv" "strings" "sync" @@ -68,6 +68,11 @@ var ( pkgFactMu sync.RWMutex ) +type element interface { + Pos() token.Pos + Parent() *ssa.Function +} + type resInfo struct { Valid bool Funcs []string @@ -216,37 +221,6 @@ func (r *runner) collectHttpTyps(pssa *buildssa.SSA) { } } -func (r *runner) noImportedContextAndHttp(f *ssa.Function) (ret bool) { - if !f.Pos().IsValid() { - return false - } - - file := analysisutil.File(r.pass, f.Pos()) - if file == nil { - return false - } - - if skip, has := r.skipFile[file]; has { - return skip - } - defer func() { - r.skipFile[file] = ret - }() - - for _, impt := range file.Imports { - path, err := strconv.Unquote(impt.Path.Value) - if err != nil { - continue - } - path = analysisutil.RemoveVendor(path) - if path == ctxPkg || path == httpPkg { - return false - } - } - - return true -} - func (r *runner) checkIsEntry(f *ssa.Function) (ret entryType) { // if r.noImportedContextAndHttp(f) { // return EntryNormal @@ -456,7 +430,7 @@ func (r *runner) collectCtxRef(f *ssa.Function, isHttpHandler bool) (refMap map[ for instr := range storeInstrs { if !checkedRefMap[instr.Val] { - r.pass.Reportf(instr.Pos(), "Non-inherited new context, use function like `context.WithXXX` instead") + r.Reportf(instr, "Non-inherited new context, use function like `context.WithXXX` instead") ok = false } } @@ -464,7 +438,7 @@ func (r *runner) collectCtxRef(f *ssa.Function, isHttpHandler bool) (refMap map[ for instr := range phiInstrs { for _, v := range instr.Edges { if !checkedRefMap[v] { - r.pass.Reportf(instr.Pos(), "Non-inherited new context, use function like `context.WithXXX` instead") + r.Reportf(instr, "Non-inherited new context, use function like `context.WithXXX` instead") ok = false } } @@ -564,9 +538,9 @@ func (r *runner) checkFuncWithCtx(f *ssa.Function, tp entryType) { if tp&CtxIn != 0 { if !refMap[instr] { if isHttpHandler { - r.pass.Reportf(instr.Pos(), "Non-inherited new context, use function like `context.WithXXX` or `r.Context` instead") + r.Reportf(instr, "Non-inherited new context, use function like `context.WithXXX` or `r.Context` instead") } else { - r.pass.Reportf(instr.Pos(), "Non-inherited new context, use function like `context.WithXXX` instead") + r.Reportf(instr, "Non-inherited new context, use function like `context.WithXXX` instead") } } } @@ -578,9 +552,11 @@ func (r *runner) checkFuncWithCtx(f *ssa.Function, tp entryType) { key := ff.RelString(nil) res, ok := r.getValue(key, ff) - if ok { - if !res.Valid { - r.pass.Reportf(instr.Pos(), "Function `%s` should pass the context parameter", strings.Join(reverse(res.Funcs), "->")) + if ok && !res.Valid { + if instr.Pos().IsValid() { + r.Reportf(instr, "Function `%s` should pass the context parameter", strings.Join(reverse(res.Funcs), "->")) + } else { + r.Reportf(ff, "Function `%s` should pass the context parameter", strings.Join(reverse(res.Funcs), "->")) } } } @@ -806,6 +782,20 @@ func (r *runner) setFact(key string, valid bool, funcs ...string) { } } +func (r *runner) Reportf(instr element, format string, args ...interface{}) { + pos := instr.Pos() + + if !pos.IsValid() && instr.Parent() != nil { + pos = instr.Parent().Pos() + } + + if !pos.IsValid() { + return + } + + r.pass.Reportf(pos, format, args...) +} + // setPkgFact save fact to mem func setPkgFact(pkg *types.Package, fact ctxFact) { pkgFactMu.Lock() diff --git a/tools/vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go b/tools/vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go index e21f278cf..e9187d6fd 100644 --- a/tools/vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go +++ b/tools/vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go @@ -26,6 +26,7 @@ type parallelAnalyzer struct { analyzer *analysis.Analyzer ignoreMissing bool ignoreMissingSubtests bool + ignoreLoopVar bool } func newParallelAnalyzer() *parallelAnalyzer { @@ -34,6 +35,7 @@ func newParallelAnalyzer() *parallelAnalyzer { var flags flag.FlagSet flags.BoolVar(&a.ignoreMissing, "i", false, "ignore missing calls to t.Parallel") flags.BoolVar(&a.ignoreMissingSubtests, "ignoremissingsubtests", false, "ignore missing calls to t.Parallel in subtests") + flags.BoolVar(&a.ignoreLoopVar, "ignoreloopVar", false, "ignore loop variable detection") a.analyzer = &analysis.Analyzer{ Name: "paralleltest", @@ -54,8 +56,10 @@ func (a *parallelAnalyzer) run(pass *analysis.Pass) (interface{}, error) { inspector.Preorder(nodeFilter, func(node ast.Node) { funcDecl := node.(*ast.FuncDecl) var funcHasParallelMethod, + funcCantParallelMethod, rangeStatementOverTestCasesExists, - rangeStatementHasParallelMethod bool + rangeStatementHasParallelMethod, + rangeStatementCantParallelMethod bool var loopVariableUsedInRun *string var numberOfTestRun int var positionOfTestRunNode []ast.Node @@ -77,20 +81,29 @@ func (a *parallelAnalyzer) run(pass *analysis.Pass) (interface{}, error) { funcHasParallelMethod = methodParallelIsCalledInTestFunction(n, testVar) } + // Check if the test calls t.Setenv, cannot be used in parallel tests or tests with parallel ancestors + if !funcCantParallelMethod { + funcCantParallelMethod = methodSetenvIsCalledInTestFunction(n, testVar) + } + // Check if the t.Run within the test function is calling t.Parallel if methodRunIsCalledInTestFunction(n, testVar) { // n is a call to t.Run; find out the name of the subtest's *testing.T parameter. innerTestVar := getRunCallbackParameterName(n) hasParallel := false + cantParallel := false numberOfTestRun++ ast.Inspect(v, func(p ast.Node) bool { if !hasParallel { hasParallel = methodParallelIsCalledInTestFunction(p, innerTestVar) } + if !cantParallel { + cantParallel = methodSetenvIsCalledInTestFunction(p, innerTestVar) + } return true }) - if !hasParallel { + if !hasParallel && !cantParallel { positionOfTestRunNode = append(positionOfTestRunNode, n) } } @@ -122,7 +135,11 @@ func (a *parallelAnalyzer) run(pass *analysis.Pass) (interface{}, error) { rangeStatementHasParallelMethod = methodParallelIsCalledInMethodRun(r.X, innerTestVar) } - if loopVariableUsedInRun == nil { + if !rangeStatementCantParallelMethod { + rangeStatementCantParallelMethod = methodSetenvIsCalledInMethodRun(r.X, innerTestVar) + } + + if !a.ignoreLoopVar && loopVariableUsedInRun == nil { if run, ok := r.X.(*ast.CallExpr); ok { loopVariableUsedInRun = loopVarReferencedInRun(run, loopVars, pass.TypesInfo) } @@ -134,12 +151,17 @@ func (a *parallelAnalyzer) run(pass *analysis.Pass) (interface{}, error) { } } - if !a.ignoreMissing && !funcHasParallelMethod { + // Descendents which call Setenv, also prevent tests from calling Parallel + if rangeStatementCantParallelMethod { + funcCantParallelMethod = true + } + + if !a.ignoreMissing && !funcHasParallelMethod && !funcCantParallelMethod { pass.Reportf(node.Pos(), "Function %s missing the call to method parallel\n", funcDecl.Name.Name) } if rangeStatementOverTestCasesExists && rangeNode != nil { - if !rangeStatementHasParallelMethod { + if !rangeStatementHasParallelMethod && !rangeStatementCantParallelMethod { if !a.ignoreMissing && !a.ignoreMissingSubtests { pass.Reportf(rangeNode.Pos(), "Range statement for test %s missing the call to method parallel in test Run\n", funcDecl.Name.Name) } @@ -162,15 +184,23 @@ func (a *parallelAnalyzer) run(pass *analysis.Pass) (interface{}, error) { } func methodParallelIsCalledInMethodRun(node ast.Node, testVar string) bool { - var methodParallelCalled bool + return targetMethodIsCalledInMethodRun(node, testVar, "Parallel") +} + +func methodSetenvIsCalledInMethodRun(node ast.Node, testVar string) bool { + return targetMethodIsCalledInMethodRun(node, testVar, "Setenv") +} + +func targetMethodIsCalledInMethodRun(node ast.Node, testVar, targetMethod string) bool { + var called bool // nolint: gocritic switch callExp := node.(type) { case *ast.CallExpr: for _, arg := range callExp.Args { - if !methodParallelCalled { + if !called { ast.Inspect(arg, func(n ast.Node) bool { - if !methodParallelCalled { - methodParallelCalled = methodParallelIsCalledInRunMethod(n, testVar) + if !called { + called = exprCallHasMethod(n, testVar, targetMethod) return true } return false @@ -178,11 +208,7 @@ func methodParallelIsCalledInMethodRun(node ast.Node, testVar string) bool { } } } - return methodParallelCalled -} - -func methodParallelIsCalledInRunMethod(node ast.Node, testVar string) bool { - return exprCallHasMethod(node, testVar, "Parallel") + return called } func methodParallelIsCalledInTestFunction(node ast.Node, testVar string) bool { @@ -196,6 +222,11 @@ func methodRunIsCalledInRangeStatement(node ast.Node, testVar string) bool { func methodRunIsCalledInTestFunction(node ast.Node, testVar string) bool { return exprCallHasMethod(node, testVar, "Run") } + +func methodSetenvIsCalledInTestFunction(node ast.Node, testVar string) bool { + return exprCallHasMethod(node, testVar, "Setenv") +} + func exprCallHasMethod(node ast.Node, receiverName, methodName string) bool { // nolint: gocritic switch n := node.(type) { diff --git a/tools/vendor/github.com/lasiar/canonicalheader/.gitignore b/tools/vendor/github.com/lasiar/canonicalheader/.gitignore new file mode 100644 index 000000000..723ef36f4 --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file diff --git a/tools/vendor/github.com/lasiar/canonicalheader/.golangci.yaml b/tools/vendor/github.com/lasiar/canonicalheader/.golangci.yaml new file mode 100644 index 000000000..5652c8d6c --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/.golangci.yaml @@ -0,0 +1,802 @@ +# See: https://olegk.dev/go-linters-configuration-the-right-version + +run: + # Automatically adjust the maximum concurrency to the container CPU quota. + concurrency: 0 + + # I really care about the result, so I'm fine to wait for it. + timeout: 30m + + # Fail if the error was met. + issues-exit-code: 1 + + # This is very important, bugs in tests are not acceptable either. + tests: true + + # In most cases this can be empty but there is a popular pattern + # to keep integration tests under this tag. Such tests often require + # additional setups like Postgres, Redis etc and are run separately. + # (to be honest I don't find this useful but I have such tags) + build-tags: + - integration + + # Autogenerated files can be skipped (I'm looking at you gRPC). + # AFAIK autogen files are skipped but skipping the whole directory should be somewhat faster. + #skip-files: + # - "protobuf/.*.go" + + # With the read-only mode linter will fail if go.mod file is outdated. + modules-download-mode: readonly + + # Till today I didn't know this param exists, never ran 2 golangci-lint at once. + allow-parallel-runners: false + + # Keep this empty to use the Go version from the go.mod file. + go: "" + +linters: + # Set to true runs only fast linters. + # Good option for 'lint on save', pre-commit hook or CI. + fast: false + + enable: + # Check for pass []any as any in variadic func(...any). + # Rare case but saved me from debugging a few times. + - asasalint + + # I prefer plane ASCII identifiers. + # Symbol `∆` instead of `delta` looks cool but no thanks. + - asciicheck + + # Checks for dangerous unicode character sequences. + # Super rare but why not to be a bit paranoid? + - bidichk + + # Checks whether HTTP response body is closed successfully. + - bodyclose + + # Check whether the function uses a non-inherited context. + - contextcheck + + # Check for two durations multiplied together. + - durationcheck + + # Forces to not skip error check. + - errcheck + + # Checks `Err-` prefix for var and `-Error` suffix for error type. + - errname + + # Suggests to use `%w` for error-wrapping. + - errorlint + + # Checks for pointers to enclosing loop variables. + - exportloopref + + # As you already know I'm a co-author. It would be strange to not use + # one of my warmly loved projects. + - gocritic + + # Forces to put `.` at the end of the comment. Code is poetry. + - godot + + # Might not be that important but I prefer to keep all of them. + # `gofumpt` is amazing, kudos to Daniel Marti https://github.com/mvdan/gofumpt + - gofmt + - gofumpt + - goimports + + # Allow or ban replace directives in go.mod + # or force explanation for retract directives. + - gomoddirectives + + # Powerful security-oriented linter. But requires some time to + # configure it properly, see https://github.com/securego/gosec#available-rules + - gosec + + # Linter that specializes in simplifying code. + - gosimple + + # Official Go tool. Must have. + - govet + + # Detects when assignments to existing variables are not used + # Last week I caught a bug with it. + - ineffassign + + # Fix all the misspells, amazing thing. + - misspell + + # Finds naked/bare returns and requires change them. + - nakedret + + # Both require a bit more explicit returns. + - nilerr + - nilnil + + # Finds sending HTTP request without context.Context. + - noctx + + # Forces comment why another check is disabled. + # Better not to have //nolint: at all ;) + - nolintlint + + # Finds slices that could potentially be pre-allocated. + # Small performance win + cleaner code. + - prealloc + + # Finds shadowing of Go's predeclared identifiers. + # I hear a lot of complaints from junior developers. + # But after some time they find it very useful. + - predeclared + + # Lint your Prometheus metrics name. + - promlinter + + # Checks that package variables are not reassigned. + # Super rare case but can catch bad things (like `io.EOF = nil`) + - reassign + + # Drop-in replacement of `golint`. + - revive + + # Somewhat similar to `bodyclose` but for `database/sql` package. + - rowserrcheck + - sqlclosecheck + + # I have found that it's not the same as staticcheck binary :\ + - staticcheck + + # Is a replacement for `golint`, similar to `revive`. + - stylecheck + + # Check struct tags. + - tagliatelle + + # Test-related checks. All of them are good. + - tenv + - testableexamples + - thelper + - tparallel + + # Remove unnecessary type conversions, make code cleaner + - unconvert + + # Might be noisy but better to know what is unused + - unparam + + # Must have. Finds unused declarations. + - unused + + # Detect the possibility to use variables/constants from stdlib. + - usestdlibvars + + # Finds wasted assignment statements. + - wastedassign + + disable: + # Detects struct contained context.Context field. Not a problem. + - containedctx + + # Checks function and package cyclomatic complexity. + # I can have a long but trivial switch-case. + # + # Cyclomatic complexity is a measurement, not a goal. + # (c) Bryan C. Mills / https://github.com/bcmills + - cyclop + + # Abandoned, replaced by `unused`. + - deadcode + + # Check declaration order of types, consts, vars and funcs. + # I like it but I don't use it. + - decorder + + # Checks if package imports are in a list of acceptable packages. + # I'm very picky about what I import, so no automation. + - depguard + + # Checks assignments with too many blank identifiers. Very rare. + - dogsled + + # Tool for code clone detection. + - dupl + + # Find duplicate words, rare. + - dupword + + # I'm fine to check the error from json.Marshal ¯\_(ツ)_/¯ + - errchkjson + + # All SQL queries MUST BE covered with tests. + - execinquery + + # Forces to handle more cases. Cool but noisy. + - exhaustive + - exhaustivestruct # Deprecated, replaced by check below. + - exhaustruct + + # Forbids some identifiers. I don't have a case for it. + - forbidigo + + # Finds forced type assertions, very good for juniors. + - forcetypeassert + + # I might have long but a simple function. + - funlen + + # Imports order. I do this manually ¯\_(ツ)_/¯ + - gci + + # I'm not a fan of ginkgo and gomega packages. + - ginkgolinter + + # Checks that compiler directive comments (//go:) are valid. Rare. + - gocheckcompilerdirectives + + # Globals and init() are ok. + - gochecknoglobals + - gochecknoinits + + # Same as `cyclop` linter (see above) + - gocognit + - goconst + - gocyclo + + # TODO and friends are ok. + - godox + + # Check the error handling expressions. Too noisy. + - goerr113 + + # I don't use file headers. + - goheader + + # 1st Go linter, deprecated :( use `revive`. + - golint + + # Reports magic consts. Might be noisy but still good. + - gomnd + + # Allowed/blocked packages to import. I prefer to do it manually. + - gomodguard + + # Printf-like functions must have -f. + - goprintffuncname + + # Groupt declarations, I prefer manually. + - grouper + + # Deprecated. + - ifshort + + # Checks imports aliases, rare. + - importas + + # Forces tiny interfaces, very subjective. + - interfacebloat + + # Accept interfaces, return types. Not always. + - ireturn + + # I don't set line length. 120 is fine by the way ;) + - lll + + # Some log checkers, might be useful. + - loggercheck + + # Maintainability index of each function, subjective. + - maintidx + + # Slice declarations with non-zero initial length. Not my case. + - makezero + + # Deprecated. Use govet `fieldalignment`. + - maligned + + # Enforce tags in un/marshaled structs. Cool but not my case. + - musttag + + # Deeply nested if statements, subjective. + - nestif + + # Forces newlines in some places. + - nlreturn + + # Reports all named returns, not that bad. + - nonamedreturns + + # Deprecated. Replaced by `revive`. + - nosnakecase + + # Finds misuse of Sprintf with host:port in a URL. Cool but rare. + - nosprintfhostport + + # I don't use t.Parallel() that much. + - paralleltest + + # Often non-`_test` package is ok. + - testpackage + + # Compiler can do it too :) + - typecheck + + # I'm fine with long variable names with a small scope. + - varnamelen + + # gofmt,gofumpt covers that (from what I know). + - whitespace + + # Don't find it useful to wrap all errors from external packages. + - wrapcheck + + # Forces you to use empty lines. Great if configured correctly. + # I mean there is an agreement in a team. + - wsl + +linters-settings: + revive: + # Maximum number of open files at the same time. + # See https://github.com/mgechev/revive#command-line-flags + # Defaults to unlimited. + max-open-files: 2048 + # When set to false, ignores files with "GENERATED" header, similar to golint. + # See https://github.com/mgechev/revive#available-rules for details. + # Default: false + ignore-generated-header: true + # Sets the default severity. + # See https://github.com/mgechev/revive#configuration + # Default: warning + severity: error + # Enable all available rules. + # Default: false + enable-all-rules: true + # Sets the default failure confidence. + # This means that linting errors with less than 0.8 confidence will be ignored. + # Default: 0.8 + confidence: 0.1 + rules: + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#add-constant + - name: add-constant + severity: warning + disabled: false + arguments: + - maxLitCount: "3" + allowStrs: '""' + allowInts: "0,1,2" + allowFloats: "0.0,0.,1.0,1.,2.0,2." + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#argument-limit + - name: argument-limit + severity: warning + disabled: false + arguments: [4] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#atomic + - name: atomic + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#banned-characters + - name: banned-characters + severity: warning + disabled: false + arguments: ["Ω", "Σ", "σ", "7"] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bare-return + - name: bare-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#blank-imports + - name: blank-imports + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bool-literal-in-expr + - name: bool-literal-in-expr + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#call-to-gc + - name: call-to-gc + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#cognitive-complexity + - name: cognitive-complexity + severity: warning + disabled: true + arguments: [7] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#comment-spacings + - name: comment-spacings + severity: warning + disabled: false + arguments: + - mypragma + - otherpragma + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#confusing-naming + - name: confusing-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#confusing-results + - name: confusing-results + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#constant-logical-expr + - name: constant-logical-expr + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#context-as-argument + - name: context-as-argument + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#context-keys-type + - name: context-keys-type + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#cyclomatic + - name: cyclomatic + severity: warning + disabled: true + arguments: [3] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#datarace + - name: datarace + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#deep-exit + - name: deep-exit + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#defer + - name: defer + severity: warning + disabled: false + arguments: + - ["call-chain", "loop"] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#dot-imports + - name: dot-imports + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#duplicated-imports + - name: duplicated-imports + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#early-return + - name: early-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-block + - name: empty-block + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-lines + - name: empty-lines + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#enforce-map-style + - name: enforce-map-style + severity: warning + disabled: false + arguments: + - "make" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-naming + - name: error-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-return + - name: error-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#function-length + - name: function-length + severity: warning + disabled: true + arguments: [10, 0] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-strings + - name: error-strings + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#errorf + - name: errorf + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#exported + - name: exported + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#file-header + - name: file-header + severity: warning + disabled: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#flag-parameter + - name: flag-parameter + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#function-result-limit + - name: function-result-limit + severity: warning + disabled: false + arguments: [2] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#get-return + - name: get-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#identical-branches + - name: identical-branches + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#if-return + - name: if-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#increment-decrement + - name: increment-decrement + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#indent-error-flow + - name: indent-error-flow + severity: warning + disabled: false + arguments: + - "preserveScope" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#import-alias-naming + - name: import-alias-naming + severity: warning + disabled: false + arguments: + - "^[a-z][a-z0-9]{0,}$" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#imports-blacklist + - name: imports-blacklist + severity: warning + disabled: false + arguments: + - "crypto/md5" + - "crypto/sha1" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#import-shadowing + - name: import-shadowing + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#line-length-limit + - name: line-length-limit + severity: warning + disabled: true + arguments: [80] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#max-public-structs + - name: max-public-structs + severity: warning + disabled: false + arguments: [3] + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#modifies-parameter + - name: modifies-parameter + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#modifies-value-receiver + - name: modifies-value-receiver + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#nested-structs + - name: nested-structs + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#optimize-operands-order + - name: optimize-operands-order + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#package-comments + - name: package-comments + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range + - name: range + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range-val-in-closure + - name: range-val-in-closure + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range-val-address + - name: range-val-address + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#receiver-naming + - name: receiver-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#redundant-import-alias + - name: redundant-import-alias + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#redefines-builtin-id + - name: redefines-builtin-id + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#string-of-int + - name: string-of-int + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#string-format + - name: string-format + severity: warning + disabled: false + arguments: + - - 'core.WriteError[1].Message' + - '/^([^A-Z]|$)/' + - must not start with a capital letter + - - 'fmt.Errorf[0]' + - '/(^|[^\.!?])$/' + - must not end in punctuation + - - panic + - '/^[^\n]*$/' + - must not contain line breaks + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#struct-tag + - name: struct-tag + arguments: + - "json,inline" + - "bson,outline,gnu" + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#superfluous-else + - name: superfluous-else + severity: warning + disabled: false + arguments: + - "preserveScope" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#time-equal + - name: time-equal + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#time-naming + - name: time-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#var-naming + - name: var-naming + severity: warning + disabled: false + arguments: + - ["ID"] # AllowList + - ["VM"] # DenyList + - - upperCaseConst: true + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#var-declaration + - name: var-declaration + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unconditional-recursion + - name: unconditional-recursion + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unexported-naming + - name: unexported-naming + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unexported-return + - name: unexported-return + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unhandled-error + - name: unhandled-error + severity: warning + disabled: false + arguments: + - "fmt.Printf" + - "myFunction" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unnecessary-stmt + - name: unnecessary-stmt + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unreachable-code + - name: unreachable-code + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter + - name: unused-parameter + severity: warning + disabled: false + arguments: + - allowRegex: "^_" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-receiver + - name: unused-receiver + severity: warning + disabled: false + arguments: + - allowRegex: "^_" + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#useless-break + - name: useless-break + severity: warning + disabled: false + # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#waitgroup-by-value + - name: waitgroup-by-value + severity: warning + disabled: false + # I'm biased and I'm enabling more than 100 checks + # Might be too much for you. See https://go-critic.com/overview.html + gocritic: + enabled-tags: + - diagnostic + - experimental + - opinionated + - performance + - style + disabled-checks: + # These 3 will detect many cases, but they do sense + # if it's performance oriented code + - hugeParam + - rangeExprCopy + - rangeValCopy + + godot: + scope: all + + errcheck: + # Report `a := b.(MyStruct)` when `a, ok := ...` should be. + check-type-assertions: true # Default: false + + # Report skipped checks:`num, _ := strconv.Atoi(numStr)`. + check-blank: true # Default: false + + # Function to skip. + exclude-functions: + - io/ioutil.ReadFile + - io.Copy(*bytes.Buffer) + - io.Copy(os.Stdout) + + govet: + disable: + - fieldalignment # I'm ok to waste some bytes + + nakedret: + # No naked returns, ever. + max-func-lines: 1 # Default: 30 + + tagliatelle: + case: + rules: + json: snake # why it's not a `snake` by default?! + yaml: snake # why it's not a `snake` by default?! + xml: camel + bson: camel + avro: snake + mapstructure: kebab + +# See also https://gist.github.com/cristaloleg/dc29ca0ef2fb554de28d94c3c6f6dc88 + +output: + # I prefer the simplest one: `line-number` and saving to `lint.txt` + # + # The `tab` also looks good and with the next release I will switch to it + # (ref: https://github.com/golangci/golangci-lint/issues/3728) + # + # There are more formats which can be used on CI or by your IDE. + formats: + - format: line-number + + # I do not find this useful, parameter above already enables filepath + # with a line and column. For me, it's easier to follow the path and + # see the line in an IDE where I see more code and understand it better. + print-issued-lines: false + + # Must have. Easier to understand the output. + print-linter-name: true + + # No, no skips, everything should be reported. + uniq-by-line: false + + # To be honest no idea when this can be needed, maybe a multi-module setup? + path-prefix: "" + + # Slightly easier to follow the results + getting deterministic output. + sort-results: true + +issues: + exclude-dirs-use-default: false + # I found it strange to skip the errors, setting 0 to have all the results. + max-issues-per-linter: 0 + + # Same here, nothing should be skipped to not miss errors. + max-same-issues: 0 + + # When set to `true` linter will analyze only new code which are + # not committed or after some specific revision. This is a cool + # feature when you're going to introduce linter into a big project. + # But I prefer going gradually package by package. + # So, it's set to `false` to scan all code. + new: false + + # 2 other params regarding git integration + + # Even with a recent GPT-4 release I still believe that + # I know better how to do my job and fix the suggestions. + fix: false \ No newline at end of file diff --git a/tools/vendor/github.com/lasiar/canonicalheader/.goreleaser.yaml b/tools/vendor/github.com/lasiar/canonicalheader/.goreleaser.yaml new file mode 100644 index 000000000..ada67063e --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/.goreleaser.yaml @@ -0,0 +1,18 @@ +builds: + - main: ./cmd/canonicalheader + env: + - CGO_ENABLED=0 + flags: + - -trimpath + ldflags: + - -s -w + targets: + - darwin_amd64 + - darwin_arm64 + - linux_amd64 + - windows_amd64 + +archives: + - format_overrides: + - goos: windows + format: zip \ No newline at end of file diff --git a/tools/vendor/github.com/lasiar/canonicalheader/LICENCE b/tools/vendor/github.com/lasiar/canonicalheader/LICENCE new file mode 100644 index 000000000..5b93b736c --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/LICENCE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Roman Chaliy + +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/tools/vendor/github.com/lasiar/canonicalheader/README.md b/tools/vendor/github.com/lasiar/canonicalheader/README.md new file mode 100644 index 000000000..997145219 --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/README.md @@ -0,0 +1,77 @@ +# canonicalheader + +[![CI](https://github.com/lasiar/canonicalheader/actions/workflows/test.yml/badge.svg)](https://github.com/lasiar/canonicalheader/actions/workflows/test.yml) +[![tag](https://img.shields.io/github/tag/lasiar/canonicalheader.svg)](https://github.com/lasiar/canonicalheader/releases) +[![Go Report Card](https://goreportcard.com/badge/github.com/lasiar/canonicalheader)](https://goreportcard.com/report/github.com/lasiar/canonicalheader) +[![License](https://img.shields.io/github/license/lasiar/canonicalheader)](./LICENCE) + +Golang linter for check canonical header. + +### Install + +```shell +go install -v github.com/lasiar/canonicalheader/cmd/canonicalheader@latest +``` + +Or download the binary file from the [release](https://github.com/lasiar/canonicalheader/releases/latest). + + +### Example + +before + +```go +package main + +import ( + "net/http" +) + +const testHeader = "testHeader" + +func main() { + v := http.Header{} + v.Get(testHeader) + + v.Get("Test-HEader") + v.Set("Test-HEader", "value") + v.Add("Test-HEader", "value") + v.Del("Test-HEader") + v.Values("Test-HEader") + + v.Set("Test-Header", "value") + v.Add("Test-Header", "value") + v.Del("Test-Header") + v.Values("Test-Header") +} + +``` + +after + +```go +package main + +import ( + "net/http" +) + +const testHeader = "testHeader" + +func main() { + v := http.Header{} + v.Get(testHeader) + + v.Get("Test-Header") + v.Set("Test-Header", "value") + v.Add("Test-Header", "value") + v.Del("Test-Header") + v.Values("Test-Header") + + v.Set("Test-Header", "value") + v.Add("Test-Header", "value") + v.Del("Test-Header") + v.Values("Test-Header") +} + +``` diff --git a/tools/vendor/github.com/lasiar/canonicalheader/analyzer.go b/tools/vendor/github.com/lasiar/canonicalheader/analyzer.go new file mode 100644 index 000000000..d3fb529eb --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/analyzer.go @@ -0,0 +1,264 @@ +package canonicalheader + +import ( + "fmt" + "go/ast" + "go/types" + "net/http" + + "github.com/go-toolsmith/astcast" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/go/types/typeutil" +) + +const ( + pkgPath = "net/http" + name = "Header" +) + +var Analyzer = &analysis.Analyzer{ + Name: "canonicalheader", + Doc: "canonicalheader checks whether net/http.Header uses canonical header", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, +} + +type argumenter interface { + diagnostic(canonicalHeader string) analysis.Diagnostic + value() string +} + +func run(pass *analysis.Pass) (any, error) { + var headerObject types.Object + for _, object := range pass.TypesInfo.Uses { + if object.Pkg() != nil && + object.Pkg().Path() == pkgPath && + object.Name() == name { + headerObject = object + break + } + } + + if headerObject == nil { + //nolint:nilnil // nothing to do here, because http.Header{} not usage. + return nil, nil + } + + spctor, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + if !ok { + return nil, fmt.Errorf("want %T, got %T", spctor, pass.ResultOf[inspect.Analyzer]) + } + + wellKnownHeaders := initialism() + + nodeFilter := []ast.Node{ + (*ast.CallExpr)(nil), + } + var outerErr error + + spctor.Preorder(nodeFilter, func(n ast.Node) { + if outerErr != nil { + return + } + + callExp, ok := n.(*ast.CallExpr) + if !ok { + return + } + + var ( + // gotType type receiver. + gotType types.Type + gotMethodName string + ) + + switch t := typeutil.Callee(pass.TypesInfo, callExp).(type) { + // Direct call method. + case *types.Func: + fn := t + // Find net/http.Header{} by function call. + signature, ok := fn.Type().(*types.Signature) + if !ok { + return + } + + recv := signature.Recv() + + // It's a func, not a method. + if recv == nil { + return + } + gotType = recv.Type() + gotMethodName = astcast.ToSelectorExpr(callExp.Fun).Sel.Name + + // h := http.Header{} + // f := h.Get + // v("Test-Value"). + case *types.Var: + ident, ok := callExp.Fun.(*ast.Ident) + if !ok { + return + } + + if ident.Obj == nil { + return + } + + // f := h.Get. + assign, ok := ident.Obj.Decl.(*ast.AssignStmt) + if !ok { + return + } + + // For case `i, v := 0, h.Get`. + // indexAssign--^. + indexAssign := -1 + for i, lh := range assign.Lhs { + // Find by name of variable. + if astcast.ToIdent(lh).Name == ident.Name { + indexAssign = i + } + } + + // Not found. + if indexAssign == -1 { + return + } + + if len(assign.Rhs) <= indexAssign { + return + } + + sel, ok := assign.Rhs[indexAssign].(*ast.SelectorExpr) + if !ok { + return + } + + gotMethodName = sel.Sel.Name + ident, ok = sel.X.(*ast.Ident) + if !ok { + return + } + + obj := pass.TypesInfo.ObjectOf(ident) + gotType = obj.Type() + + default: + return + } + + // It is not net/http.Header{}. + if !types.Identical(gotType, headerObject.Type()) { + return + } + + // Search for known methods where the key is the first arg. + if !isValidMethod(gotMethodName) { + return + } + + // Should be more than one. Because get the value by index it + // will not be superfluous. + if len(callExp.Args) == 0 { + return + } + + callArg := callExp.Args[0] + + // Check for type casting from myString to string. + // it could be: Get(string(string(string(myString)))). + // need this node------------------------^^^^^^^^. + for { + // If it is not *ast.CallExpr, this is a value. + c, ok := callArg.(*ast.CallExpr) + if !ok { + break + } + + // Some function is called, skip this case. + if len(c.Args) == 0 { + return + } + + f, ok := c.Fun.(*ast.Ident) + if !ok { + break + } + + obj := pass.TypesInfo.ObjectOf(f) + // nil may be by code, but not by logic. + // TypeInfo should contain of type. + if obj == nil { + break + } + + // This is function. + // Skip this method call. + _, ok = obj.Type().(*types.Signature) + if ok { + return + } + + callArg = c.Args[0] + } + + var arg argumenter + switch t := callArg.(type) { + case *ast.BasicLit: + lString, err := newLiteralString(t) + if err != nil { + return + } + + arg = lString + + case *ast.Ident: + constString, err := newConstantKey(pass.TypesInfo, t) + if err != nil { + return + } + + arg = constString + + default: + return + } + + argValue := arg.value() + headerKeyCanonical := http.CanonicalHeaderKey(argValue) + if argValue == headerKeyCanonical { + return + } + + headerKeyCanonical, isWellKnown := canonicalHeaderKey(argValue, wellKnownHeaders) + if argValue == headerKeyCanonical || isWellKnown { + return + } + + pass.Report(arg.diagnostic(headerKeyCanonical)) + }) + + return nil, outerErr +} + +func canonicalHeaderKey(s string, m map[string]string) (string, bool) { + canonical := http.CanonicalHeaderKey(s) + + wellKnown, ok := m[canonical] + if !ok { + return canonical, ok + } + + return wellKnown, ok +} + +func isValidMethod(name string) bool { + switch name { + case "Get", "Set", "Add", "Del", "Values": + return true + default: + return false + } +} diff --git a/tools/vendor/github.com/lasiar/canonicalheader/constant_string.go b/tools/vendor/github.com/lasiar/canonicalheader/constant_string.go new file mode 100644 index 000000000..27988f0d5 --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/constant_string.go @@ -0,0 +1,50 @@ +package canonicalheader + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + + "golang.org/x/tools/go/analysis" +) + +type constantString struct { + originalValue, + nameOfConst string + + pos token.Pos + end token.Pos +} + +func newConstantKey(info *types.Info, ident *ast.Ident) (constantString, error) { + c, ok := info.ObjectOf(ident).(*types.Const) + if !ok { + return constantString{}, fmt.Errorf("type %T is not support", c) + } + + return constantString{ + nameOfConst: c.Name(), + originalValue: constant.StringVal(c.Val()), + pos: ident.Pos(), + end: ident.End(), + }, nil +} + +func (c constantString) diagnostic(canonicalHeader string) analysis.Diagnostic { + return analysis.Diagnostic{ + Pos: c.pos, + End: c.end, + Message: fmt.Sprintf( + "const %q used as a key at http.Header, but %q is not canonical, want %q", + c.nameOfConst, + c.originalValue, + canonicalHeader, + ), + } +} + +func (c constantString) value() string { + return c.originalValue +} diff --git a/tools/vendor/github.com/lasiar/canonicalheader/initialism.go b/tools/vendor/github.com/lasiar/canonicalheader/initialism.go new file mode 100644 index 000000000..c3d91c23e --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/initialism.go @@ -0,0 +1,75 @@ +// Code generated by initialismer; DO NOT EDIT. +package canonicalheader + +// initialism mapping of not canonical headers from +// https://en.wikipedia.org/wiki/List_of_HTTP_header_fields +// https://www.iana.org/assignments/http-fields/http-fields.xhtml. +func initialism() map[string]string { + return map[string]string{ + "A-Im": "A-IM", + "Accept-Ch": "Accept-CH", + "Alpn": "ALPN", + "Amp-Cache-Transform": "AMP-Cache-Transform", + "C-Pep": "C-PEP", + "C-Pep-Info": "C-PEP-Info", + "Cal-Managed-Id": "Cal-Managed-ID", + "Caldav-Timezones": "CalDAV-Timezones", + "Cdn-Cache-Control": "CDN-Cache-Control", + "Cdn-Loop": "CDN-Loop", + "Content-Id": "Content-ID", + "Content-Md5": "Content-MD5", + "Dasl": "DASL", + "Dav": "DAV", + "Differential-Id": "Differential-ID", + "Dnt": "DNT", + "Dpop": "DPoP", + "Dpop-Nonce": "DPoP-Nonce", + "Ediint-Features": "EDIINT-Features", + "Etag": "ETag", + "Expect-Ct": "Expect-CT", + "Getprofile": "GetProfile", + "Http2-Settings": "HTTP2-Settings", + "Im": "IM", + "Include-Referred-Token-Binding-Id": "Include-Referred-Token-Binding-ID", + "Last-Event-Id": "Last-Event-ID", + "Mime-Version": "MIME-Version", + "Nel": "NEL", + "Odata-Entityid": "OData-EntityId", + "Odata-Isolation": "OData-Isolation", + "Odata-Maxversion": "OData-MaxVersion", + "Odata-Version": "OData-Version", + "Optional-Www-Authenticate": "Optional-WWW-Authenticate", + "Oscore": "OSCORE", + "Oslc-Core-Version": "OSLC-Core-Version", + "P3p": "P3P", + "Pep": "PEP", + "Pep-Info": "PEP-Info", + "Pics-Label": "PICS-Label", + "Profileobject": "ProfileObject", + "Repeatability-Client-Id": "Repeatability-Client-ID", + "Repeatability-Request-Id": "Repeatability-Request-ID", + "Sec-Gpc": "Sec-GPC", + "Sec-Websocket-Accept": "Sec-WebSocket-Accept", + "Sec-Websocket-Extensions": "Sec-WebSocket-Extensions", + "Sec-Websocket-Key": "Sec-WebSocket-Key", + "Sec-Websocket-Protocol": "Sec-WebSocket-Protocol", + "Sec-Websocket-Version": "Sec-WebSocket-Version", + "Setprofile": "SetProfile", + "Slug": "SLUG", + "Soapaction": "SoapAction", + "Status-Uri": "Status-URI", + "Tcn": "TCN", + "Te": "TE", + "Ttl": "TTL", + "Uri": "URI", + "Www-Authenticate": "WWW-Authenticate", + "X-Correlation-Id": "X-Correlation-ID", + "X-Dns-Prefetch-Control": "X-DNS-Prefetch-Control", + "X-Real-Ip": "X-Real-IP", + "X-Request-Id": "X-Request-ID", + "X-Ua-Compatible": "X-UA-Compatible", + "X-Webkit-Csp": "X-WebKit-CSP", + "X-Xss": "X-XSS", + "X-Xss-Protection": "X-XSS-Protection", + } +} diff --git a/tools/vendor/github.com/lasiar/canonicalheader/literal_string.go b/tools/vendor/github.com/lasiar/canonicalheader/literal_string.go new file mode 100644 index 000000000..71cd5f397 --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/literal_string.go @@ -0,0 +1,80 @@ +package canonicalheader + +import ( + "fmt" + "go/ast" + "go/token" + "strconv" + "unicode/utf8" + "unsafe" + + "golang.org/x/tools/go/analysis" +) + +type literalString struct { + originalValue string + quote byte + pos, end token.Pos +} + +func newLiteralString(basicList *ast.BasicLit) (literalString, error) { + if basicList.Kind != token.STRING { + return literalString{}, fmt.Errorf("%#v is not a string", basicList) + } + + if len(basicList.Value) < 2 { + return literalString{}, fmt.Errorf("%#v has a strange value length %q", basicList, basicList.Value) + } + + quote := basicList.Value[0] + switch quote { + case '`', '"': + default: + return literalString{}, fmt.Errorf("%q is a strange quote", quote) + } + + originalValue, err := strconv.Unquote(basicList.Value) + if err != nil { + return literalString{}, fmt.Errorf("unquote %q: %w", basicList.Value, err) + } + + if !utf8.ValidString(originalValue) { + return literalString{}, fmt.Errorf("%#v is not a valid utf8 string", basicList.Value) + } + + return literalString{ + originalValue: originalValue, + quote: quote, + pos: basicList.Pos(), + end: basicList.End(), + }, nil +} + +func (l literalString) diagnostic(canonicalHeader string) analysis.Diagnostic { + newText := make([]byte, 0, len(canonicalHeader)+2) + newText = append(newText, l.quote) + newText = append(newText, unsafe.Slice(unsafe.StringData(canonicalHeader), len(canonicalHeader))...) + newText = append(newText, l.quote) + + return analysis.Diagnostic{ + Pos: l.pos, + End: l.end, + Message: fmt.Sprintf("non-canonical header %q, instead use: %q", l.originalValue, canonicalHeader), + SuggestedFixes: []analysis.SuggestedFix{ + { + Message: fmt.Sprintf("should replace %q with %q", l.originalValue, canonicalHeader), + TextEdits: []analysis.TextEdit{ + { + Pos: l.pos, + End: l.end, + NewText: newText, + }, + }, + }, + }, + } +} + +func (l literalString) value() string { + return l.originalValue +} diff --git a/tools/vendor/github.com/lasiar/canonicalheader/makefile b/tools/vendor/github.com/lasiar/canonicalheader/makefile new file mode 100644 index 000000000..a96cb628e --- /dev/null +++ b/tools/vendor/github.com/lasiar/canonicalheader/makefile @@ -0,0 +1,12 @@ +.PHONY: + +test: + go test -v -race ./... + +linter: + golangci-lint -v run ./... + +generate: + go run ./cmd/initialismer/*.go -target="mapping" > ./initialism.go + go run ./cmd/initialismer/*.go -target="test" > ./testdata/src/initialism/initialism.go + gofmt -w ./initialism.go ./testdata/src/initialism/initialism.go diff --git a/tools/vendor/github.com/ldez/gomoddirectives/.golangci.yml b/tools/vendor/github.com/ldez/gomoddirectives/.golangci.yml index a2483e95f..034745570 100644 --- a/tools/vendor/github.com/ldez/gomoddirectives/.golangci.yml +++ b/tools/vendor/github.com/ldez/gomoddirectives/.golangci.yml @@ -1,7 +1,5 @@ run: - deadline: 2m - skip-files: [] - skip-dirs: [] + timeout: 2m linters-settings: govet: @@ -16,10 +14,13 @@ linters-settings: gofumpt: extra-rules: true depguard: - list-type: blacklist - include-go-root: false - packages: - - github.com/pkg/errors + rules: + main: + deny: + - pkg: "github.com/instana/testify" + desc: not allowed + - pkg: "github.com/pkg/errors" + desc: Should be replaced by standard lib errors package godox: keywords: - FIXME @@ -51,12 +52,19 @@ linters-settings: linters: enable-all: true disable: - - maligned # deprecated - - interfacer # deprecated + - deadcode # deprecated + - exhaustivestruct # deprecated - golint # deprecated + - ifshort # deprecated + - interfacer # deprecated + - maligned # deprecated + - nosnakecase # deprecated - scopelint # deprecated + - structcheck # deprecated + - varcheck # deprecated - sqlclosecheck # not relevant (SQL) - rowserrcheck # not relevant (SQL) + - execinquery # not relevant (SQL) - cyclop # duplicate of gocyclo - lll - dupl @@ -71,14 +79,16 @@ linters: - goerr113 - wrapcheck - exhaustive - - exhaustivestruct + - exhaustruct - varnamelen issues: exclude-use-default: false - max-per-linter: 0 + max-issues-per-linter: 0 max-same-issues: 0 - exclude: [] + exclude: [ + 'package-comments: should have a package comment' + ] exclude-rules: - path: "(.+)_test.go" linters: @@ -86,3 +96,7 @@ issues: - goconst - path: cmd/gomoddirectives/gomoddirectives.go text: 'use of `fmt.Println` forbidden' + +output: + show-stats: true + sort-results: true diff --git a/tools/vendor/github.com/ldez/gomoddirectives/Makefile b/tools/vendor/github.com/ldez/gomoddirectives/Makefile index dd3b335c7..5a0a852c8 100644 --- a/tools/vendor/github.com/ldez/gomoddirectives/Makefile +++ b/tools/vendor/github.com/ldez/gomoddirectives/Makefile @@ -12,4 +12,4 @@ check: golangci-lint run build: - go build -v -ldflags "-s -w" -trimpath ./cmd/gomoddirectives/ + go build -ldflags "-s -w" -trimpath ./cmd/gomoddirectives/ diff --git a/tools/vendor/github.com/ldez/gomoddirectives/module.go b/tools/vendor/github.com/ldez/gomoddirectives/module.go index 907be244f..4cb365379 100644 --- a/tools/vendor/github.com/ldez/gomoddirectives/module.go +++ b/tools/vendor/github.com/ldez/gomoddirectives/module.go @@ -24,7 +24,7 @@ func GetModuleFile() (*modfile.File, error) { // https://github.com/golang/go/issues/44753#issuecomment-790089020 cmd := exec.Command("go", "list", "-m", "-json") - raw, err := cmd.CombinedOutput() + raw, err := cmd.Output() if err != nil { return nil, fmt.Errorf("command go list: %w: %s", err, string(raw)) } diff --git a/tools/vendor/github.com/leonklingele/grouper/pkg/analyzer/analyzer.go b/tools/vendor/github.com/leonklingele/grouper/pkg/analyzer/analyzer.go index 9852c7838..7d8c0c4f0 100644 --- a/tools/vendor/github.com/leonklingele/grouper/pkg/analyzer/analyzer.go +++ b/tools/vendor/github.com/leonklingele/grouper/pkg/analyzer/analyzer.go @@ -15,7 +15,9 @@ import ( const ( Name = "grouper" - Doc = `expression group analyzer: require 'import', 'const', 'var' and/or 'type' declaration groups` + Doc = `analyze expression groups + +Require 'import', 'const', 'var' and/or 'type' declaration groups.` ) func New() *analysis.Analyzer { diff --git a/tools/vendor/github.com/macabu/inamedparam/.gitignore b/tools/vendor/github.com/macabu/inamedparam/.gitignore index 3b735ec4a..f8d51e94c 100644 --- a/tools/vendor/github.com/macabu/inamedparam/.gitignore +++ b/tools/vendor/github.com/macabu/inamedparam/.gitignore @@ -7,6 +7,7 @@ *.dll *.so *.dylib +inamedparam # Test binary, built with `go test -c` *.test diff --git a/tools/vendor/github.com/macabu/inamedparam/.golangci.yml b/tools/vendor/github.com/macabu/inamedparam/.golangci.yml new file mode 100644 index 000000000..f0efa1cb6 --- /dev/null +++ b/tools/vendor/github.com/macabu/inamedparam/.golangci.yml @@ -0,0 +1,33 @@ +run: + deadline: 30s + +linters: + enable-all: true + disable: + - cyclop + - deadcode + - depguard + - exhaustivestruct + - exhaustruct + - forcetypeassert + - gochecknoglobals + - gocognit + - golint + - ifshort + - interfacer + - maligned + - nilnil + - nosnakecase + - paralleltest + - scopelint + - structcheck + - varcheck + +linters-settings: + gci: + sections: + - standard + - default + - prefix(github.com/macabu/inamedparam) + section-separators: + - newLine diff --git a/tools/vendor/github.com/macabu/inamedparam/README.md b/tools/vendor/github.com/macabu/inamedparam/README.md index 80911c9d7..3336cb950 100644 --- a/tools/vendor/github.com/macabu/inamedparam/README.md +++ b/tools/vendor/github.com/macabu/inamedparam/README.md @@ -2,10 +2,16 @@ A linter that reports interfaces with unnamed method parameters. +## Flags/Config +```sh +-skip-single-param + skip interfaces with a single unnamed parameter +``` + ## Usage ### Standalone -You can also run it standalone through `go vet`. +You can run it standalone through `go vet`. You must install the binary to your `$GOBIN` folder like so: ```sh @@ -16,3 +22,17 @@ And then navigate to your Go project's root folder, where can run `go vet` in th ```sh $ go vet -vettool=$(which inamedparam) ./... ``` + +### golangci-lint +`inamedparam` was added as a linter to `golangci-lint` on version `v1.55.0`. It is disabled by default. + +To enable it, you can add it to your `.golangci.yml` file, as such: +```yaml +run: + deadline: 30s + +linters: + disable-all: true + enable: + - inamedparam +``` diff --git a/tools/vendor/github.com/macabu/inamedparam/inamedparam.go b/tools/vendor/github.com/macabu/inamedparam/inamedparam.go index 433e04e5b..8ba7fe188 100644 --- a/tools/vendor/github.com/macabu/inamedparam/inamedparam.go +++ b/tools/vendor/github.com/macabu/inamedparam/inamedparam.go @@ -1,6 +1,7 @@ package inamedparam import ( + "flag" "go/ast" "golang.org/x/tools/go/analysis" @@ -8,15 +9,30 @@ import ( "golang.org/x/tools/go/ast/inspector" ) +const ( + analyzerName = "inamedparam" + + flagSkipSingleParam = "skip-single-param" +) + var Analyzer = &analysis.Analyzer{ - Name: "inamedparam", - Doc: "reports interfaces with unnamed method parameters", - Run: run, + Name: analyzerName, + Doc: "reports interfaces with unnamed method parameters", + Run: run, + Flags: flags(), Requires: []*analysis.Analyzer{ inspect.Analyzer, }, } +func flags() flag.FlagSet { + flags := flag.NewFlagSet(analyzerName, flag.ExitOnError) + + flags.Bool(flagSkipSingleParam, false, "skip interface methods with a single unnamed parameter") + + return *flags +} + func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) @@ -24,6 +40,8 @@ func run(pass *analysis.Pass) (interface{}, error) { &ast.InterfaceType{}, } + skipSingleParam := pass.Analyzer.Flags.Lookup(flagSkipSingleParam).Value.(flag.Getter).Get().(bool) + inspect.Preorder(types, func(n ast.Node) { interfaceType, ok := n.(*ast.InterfaceType) if !ok || interfaceType == nil || interfaceType.Methods == nil { @@ -36,8 +54,17 @@ func run(pass *analysis.Pass) (interface{}, error) { continue } + // Improvement: add test case to reproduce this. Help wanted. + if len(method.Names) == 0 { + continue + } + methodName := method.Names[0].Name + if skipSingleParam && len(interfaceFunc.Params.List) == 1 { + continue + } + for _, param := range interfaceFunc.Params.List { if param.Names == nil { var builtParamType string diff --git a/tools/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/tools/vendor/github.com/mattn/go-isatty/isatty_bsd.go index d569c0c94..d0ea68f40 100644 --- a/tools/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ b/tools/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -1,6 +1,7 @@ -//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine +//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine && !tinygo // +build darwin freebsd openbsd netbsd dragonfly hurd // +build !appengine +// +build !tinygo package isatty diff --git a/tools/vendor/github.com/mattn/go-isatty/isatty_others.go b/tools/vendor/github.com/mattn/go-isatty/isatty_others.go index 31503226f..7402e0618 100644 --- a/tools/vendor/github.com/mattn/go-isatty/isatty_others.go +++ b/tools/vendor/github.com/mattn/go-isatty/isatty_others.go @@ -1,5 +1,6 @@ -//go:build appengine || js || nacl || wasm -// +build appengine js nacl wasm +//go:build (appengine || js || nacl || tinygo || wasm) && !windows +// +build appengine js nacl tinygo wasm +// +build !windows package isatty diff --git a/tools/vendor/github.com/mattn/go-isatty/isatty_tcgets.go b/tools/vendor/github.com/mattn/go-isatty/isatty_tcgets.go index 67787657f..0337d8cf6 100644 --- a/tools/vendor/github.com/mattn/go-isatty/isatty_tcgets.go +++ b/tools/vendor/github.com/mattn/go-isatty/isatty_tcgets.go @@ -1,6 +1,7 @@ -//go:build (linux || aix || zos) && !appengine +//go:build (linux || aix || zos) && !appengine && !tinygo // +build linux aix zos // +build !appengine +// +build !tinygo package isatty diff --git a/tools/vendor/github.com/mbilski/exhaustivestruct/pkg/analyzer/analyzer.go b/tools/vendor/github.com/mbilski/exhaustivestruct/pkg/analyzer/analyzer.go deleted file mode 100644 index 0dfb713c5..000000000 --- a/tools/vendor/github.com/mbilski/exhaustivestruct/pkg/analyzer/analyzer.go +++ /dev/null @@ -1,187 +0,0 @@ -package analyzer - -import ( - "flag" - "fmt" - "go/ast" - "go/types" - "path" - "strings" - - "golang.org/x/tools/go/analysis/passes/inspect" - "golang.org/x/tools/go/ast/inspector" - - "golang.org/x/tools/go/analysis" -) - -// Analyzer that checks if all struct's fields are initialized -var Analyzer = &analysis.Analyzer{ - Name: "exhaustivestruct", - Doc: "Checks if all struct's fields are initialized", - Run: run, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - Flags: newFlagSet(), -} - -// StructPatternList is a comma separated list of expressions to match struct packages and names -// The struct packages have the form example.com/package.ExampleStruct -// The matching patterns can use matching syntax from https://pkg.go.dev/path#Match -// If this list is empty, all structs are tested. -var StructPatternList string - -func newFlagSet() flag.FlagSet { - fs := flag.NewFlagSet("", flag.PanicOnError) - fs.StringVar(&StructPatternList, "struct_patterns", "", "This is a comma separated list of expressions to match struct packages and names") - return *fs -} - -func run(pass *analysis.Pass) (interface{}, error) { - splitFn := func(c rune) bool { return c == ',' } - inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) - structPatterns := strings.FieldsFunc(StructPatternList, splitFn) - // validate the pattern syntax - for _, pattern := range structPatterns { - _, err := path.Match(pattern, "") - if err != nil { - return nil, fmt.Errorf("invalid struct pattern %s: %w", pattern, err) - } - } - - nodeFilter := []ast.Node{ - (*ast.CompositeLit)(nil), - (*ast.ReturnStmt)(nil), - } - - var returnStmt *ast.ReturnStmt - - inspector.Preorder(nodeFilter, func(node ast.Node) { - var name string - - compositeLit, ok := node.(*ast.CompositeLit) - if !ok { - // Keep track of the last return statement whilte iterating - retLit, ok := node.(*ast.ReturnStmt) - if ok { - returnStmt = retLit - } - return - } - - i, ok := compositeLit.Type.(*ast.Ident) - - if ok { - name = i.Name - } else { - s, ok := compositeLit.Type.(*ast.SelectorExpr) - - if !ok { - return - } - - name = s.Sel.Name - } - - if compositeLit.Type == nil { - return - } - - t := pass.TypesInfo.TypeOf(compositeLit.Type) - - if t == nil { - return - } - - if len(structPatterns) > 0 { - shouldLint := false - for _, pattern := range structPatterns { - // We check the patterns for vailidy ahead of time, so we don't need to check the error here - if match, _ := path.Match(pattern, t.String()); match { - shouldLint = true - break - } - } - if !shouldLint { - return - } - } - - str, ok := t.Underlying().(*types.Struct) - - if !ok { - return - } - - // Don't report an error if: - // 1. This composite literal contains no fields and - // 2. It's in a return statement and - // 3. The return statement contains a non-nil error - if len(compositeLit.Elts) == 0 { - // Check if this composite is one of the results the last return statement - isInResults := false - if returnStmt != nil { - for _, result := range returnStmt.Results { - compareComposite, ok := result.(*ast.CompositeLit) - if ok { - if compareComposite == compositeLit { - isInResults = true - } - } - } - } - nonNilError := false - if isInResults { - // Check if any of the results has an error type and if that error is set to non-nil (if it's set to nil, the type would be "untyped nil") - for _, result := range returnStmt.Results { - if pass.TypesInfo.TypeOf(result).String() == "error" { - nonNilError = true - } - } - } - - if nonNilError { - return - } - } - - samePackage := strings.HasPrefix(t.String(), pass.Pkg.Path()+".") - - missing := []string{} - - for i := 0; i < str.NumFields(); i++ { - fieldName := str.Field(i).Name() - exists := false - - if !samePackage && !str.Field(i).Exported() { - continue - } - - for eIndex, e := range compositeLit.Elts { - if k, ok := e.(*ast.KeyValueExpr); ok { - if i, ok := k.Key.(*ast.Ident); ok { - if i.Name == fieldName { - exists = true - break - } - } - } else { - if eIndex == i { - exists = true - break - } - } - } - - if !exists { - missing = append(missing, fieldName) - } - } - - if len(missing) == 1 { - pass.Reportf(node.Pos(), "%s is missing in %s", missing[0], name) - } else if len(missing) > 1 { - pass.Reportf(node.Pos(), "%s are missing in %s", strings.Join(missing, ", "), name) - } - }) - - return nil, nil -} diff --git a/tools/vendor/github.com/mgechev/revive/config/config.go b/tools/vendor/github.com/mgechev/revive/config/config.go index abd554a9f..fed1d1913 100644 --- a/tools/vendor/github.com/mgechev/revive/config/config.go +++ b/tools/vendor/github.com/mgechev/revive/config/config.go @@ -1,3 +1,4 @@ +// Package config implements revive's configuration data structures and related methods package config import ( @@ -5,9 +6,9 @@ import ( "fmt" "os" - "github.com/mgechev/revive/formatter" - "github.com/BurntSushi/toml" + + "github.com/mgechev/revive/formatter" "github.com/mgechev/revive/lint" "github.com/mgechev/revive/rule" ) @@ -54,7 +55,7 @@ var allRules = append([]lint.Rule{ &rule.ModifiesValRecRule{}, &rule.ConstantLogicalExprRule{}, &rule.BoolLiteralRule{}, - &rule.ImportsBlacklistRule{}, + &rule.ImportsBlocklistRule{}, &rule.FunctionResultsLimitRule{}, &rule.MaxPublicStructsRule{}, &rule.RangeValInClosureRule{}, @@ -91,6 +92,10 @@ var allRules = append([]lint.Rule{ &rule.RedundantImportAlias{}, &rule.ImportAliasNamingRule{}, &rule.EnforceMapStyleRule{}, + &rule.EnforceRepeatedArgTypeStyleRule{}, + &rule.EnforceSliceStyleRule{}, + &rule.MaxControlNestingRule{}, + &rule.CommentsDensityRule{}, }, defaultRules...) var allFormatters = []lint.Formatter{ @@ -128,7 +133,8 @@ func GetLintingRules(config *lint.Config, extraRules []lint.Rule) ([]lint.Rule, var lintingRules []lint.Rule for name, ruleConfig := range config.Rules { - r, ok := rulesMap[name] + actualName := actualRuleName(name) + r, ok := rulesMap[actualName] if !ok { return nil, fmt.Errorf("cannot find rule: %s", name) } @@ -143,6 +149,15 @@ func GetLintingRules(config *lint.Config, extraRules []lint.Rule) ([]lint.Rule, return lintingRules, nil } +func actualRuleName(name string) string { + switch name { + case "imports-blacklist": + return "imports-blocklist" + default: + return name + } +} + func parseConfig(path string, config *lint.Config) error { file, err := os.ReadFile(path) if err != nil { diff --git a/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go b/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go index 33a3b2ca1..f45b63c92 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go @@ -3,7 +3,7 @@ package formatter import ( "bytes" "encoding/xml" - plainTemplate "text/template" + plain "text/template" "github.com/mgechev/revive/lint" ) @@ -50,7 +50,7 @@ func (*Checkstyle) Format(failures <-chan lint.Failure, config lint.Config) (str issues[fn] = append(issues[fn], iss) } - t, err := plainTemplate.New("revive").Parse(checkstyleTemplate) + t, err := plain.New("revive").Parse(checkstyleTemplate) if err != nil { return "", err } diff --git a/tools/vendor/github.com/mgechev/revive/formatter/default.go b/tools/vendor/github.com/mgechev/revive/formatter/default.go index f76a7b29a..2d5a04434 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/default.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/default.go @@ -1,6 +1,7 @@ package formatter import ( + "bytes" "fmt" "github.com/mgechev/revive/lint" @@ -19,8 +20,9 @@ func (*Default) Name() string { // Format formats the failures gotten from the lint. func (*Default) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { + var buf bytes.Buffer for failure := range failures { - fmt.Printf("%v: %s\n", failure.Position.Start, failure.Failure) + fmt.Fprintf(&buf, "%v: %s\n", failure.Position.Start, failure.Failure) } - return "", nil + return buf.String(), nil } diff --git a/tools/vendor/github.com/mgechev/revive/formatter/doc.go b/tools/vendor/github.com/mgechev/revive/formatter/doc.go new file mode 100644 index 000000000..bb89f20ea --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/formatter/doc.go @@ -0,0 +1,2 @@ +// Package formatter implements the linter output formatters. +package formatter diff --git a/tools/vendor/github.com/mgechev/revive/formatter/friendly.go b/tools/vendor/github.com/mgechev/revive/formatter/friendly.go index ced8fa46c..5ff329a23 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/friendly.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/friendly.go @@ -3,6 +3,7 @@ package formatter import ( "bytes" "fmt" + "io" "sort" "github.com/fatih/color" @@ -31,13 +32,14 @@ func (*Friendly) Name() string { // Format formats the failures gotten from the lint. func (f *Friendly) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { + var buf bytes.Buffer errorMap := map[string]int{} warningMap := map[string]int{} totalErrors := 0 totalWarnings := 0 for failure := range failures { sev := severity(config, failure) - f.printFriendlyFailure(failure, sev) + f.printFriendlyFailure(&buf, failure, sev) if sev == lint.SeverityWarning { warningMap[failure.RuleName]++ totalWarnings++ @@ -47,29 +49,29 @@ func (f *Friendly) Format(failures <-chan lint.Failure, config lint.Config) (str totalErrors++ } } - f.printSummary(totalErrors, totalWarnings) - f.printStatistics(color.RedString("Errors:"), errorMap) - f.printStatistics(color.YellowString("Warnings:"), warningMap) - return "", nil + f.printSummary(&buf, totalErrors, totalWarnings) + f.printStatistics(&buf, color.RedString("Errors:"), errorMap) + f.printStatistics(&buf, color.YellowString("Warnings:"), warningMap) + return buf.String(), nil } -func (f *Friendly) printFriendlyFailure(failure lint.Failure, severity lint.Severity) { - f.printHeaderRow(failure, severity) - f.printFilePosition(failure) - fmt.Println() - fmt.Println() +func (f *Friendly) printFriendlyFailure(w io.Writer, failure lint.Failure, severity lint.Severity) { + f.printHeaderRow(w, failure, severity) + f.printFilePosition(w, failure) + fmt.Fprintln(w) + fmt.Fprintln(w) } -func (f *Friendly) printHeaderRow(failure lint.Failure, severity lint.Severity) { +func (f *Friendly) printHeaderRow(w io.Writer, failure lint.Failure, severity lint.Severity) { emoji := getWarningEmoji() if severity == lint.SeverityError { emoji = getErrorEmoji() } - fmt.Print(f.table([][]string{{emoji, "https://revive.run/r#" + failure.RuleName, color.GreenString(failure.Failure)}})) + fmt.Fprint(w, f.table([][]string{{emoji, "https://revive.run/r#" + failure.RuleName, color.GreenString(failure.Failure)}})) } -func (*Friendly) printFilePosition(failure lint.Failure) { - fmt.Printf(" %s:%d:%d", failure.GetFilename(), failure.Position.Start.Line, failure.Position.Start.Column) +func (*Friendly) printFilePosition(w io.Writer, failure lint.Failure) { + fmt.Fprintf(w, " %s:%d:%d", failure.GetFilename(), failure.Position.Start.Line, failure.Position.Start.Column) } type statEntry struct { @@ -77,7 +79,7 @@ type statEntry struct { failures int } -func (*Friendly) printSummary(errors, warnings int) { +func (*Friendly) printSummary(w io.Writer, errors, warnings int) { emoji := getWarningEmoji() if errors > 0 { emoji = getErrorEmoji() @@ -96,18 +98,18 @@ func (*Friendly) printSummary(errors, warnings int) { } str := fmt.Sprintf("%d %s (%d %s, %d %s)", errors+warnings, problemsLabel, errors, errorsLabel, warnings, warningsLabel) if errors > 0 { - fmt.Printf("%s %s\n", emoji, color.RedString(str)) - fmt.Println() + fmt.Fprintf(w, "%s %s\n", emoji, color.RedString(str)) + fmt.Fprintln(w) return } if warnings > 0 { - fmt.Printf("%s %s\n", emoji, color.YellowString(str)) - fmt.Println() + fmt.Fprintf(w, "%s %s\n", emoji, color.YellowString(str)) + fmt.Fprintln(w) return } } -func (f *Friendly) printStatistics(header string, stats map[string]int) { +func (f *Friendly) printStatistics(w io.Writer, header string, stats map[string]int) { if len(stats) == 0 { return } @@ -122,8 +124,8 @@ func (f *Friendly) printStatistics(header string, stats map[string]int) { for _, entry := range data { formatted = append(formatted, []string{color.GreenString(fmt.Sprintf("%d", entry.failures)), entry.name}) } - fmt.Println(header) - fmt.Println(f.table(formatted)) + fmt.Fprintln(w, header) + fmt.Fprintln(w, f.table(formatted)) } func (*Friendly) table(rows [][]string) string { diff --git a/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go b/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go index a02d9c80f..58b35dc44 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go @@ -1,8 +1,8 @@ package formatter import ( + "bytes" "encoding/json" - "os" "github.com/mgechev/revive/lint" ) @@ -20,7 +20,8 @@ func (*NDJSON) Name() string { // Format formats the failures gotten from the lint. func (*NDJSON) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { - enc := json.NewEncoder(os.Stdout) + var buf bytes.Buffer + enc := json.NewEncoder(&buf) for failure := range failures { obj := jsonObject{} obj.Severity = severity(config, failure) @@ -30,5 +31,5 @@ func (*NDJSON) Format(failures <-chan lint.Failure, config lint.Config) (string, return "", err } } - return "", nil + return buf.String(), nil } diff --git a/tools/vendor/github.com/mgechev/revive/formatter/plain.go b/tools/vendor/github.com/mgechev/revive/formatter/plain.go index 6e083bcfd..09ebf6cdc 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/plain.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/plain.go @@ -1,6 +1,7 @@ package formatter import ( + "bytes" "fmt" "github.com/mgechev/revive/lint" @@ -19,8 +20,9 @@ func (*Plain) Name() string { // Format formats the failures gotten from the lint. func (*Plain) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { + var buf bytes.Buffer for failure := range failures { - fmt.Printf("%v: %s %s\n", failure.Position.Start, failure.Failure, "https://revive.run/r#"+failure.RuleName) + fmt.Fprintf(&buf, "%v: %s %s\n", failure.Position.Start, failure.Failure, "https://revive.run/r#"+failure.RuleName) } - return "", nil + return buf.String(), nil } diff --git a/tools/vendor/github.com/mgechev/revive/formatter/unix.go b/tools/vendor/github.com/mgechev/revive/formatter/unix.go index ef2f1613a..e46f3c275 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/unix.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/unix.go @@ -1,6 +1,7 @@ package formatter import ( + "bytes" "fmt" "github.com/mgechev/revive/lint" @@ -8,7 +9,8 @@ import ( // Unix is an implementation of the Formatter interface // which formats the errors to a simple line based error format -// main.go:24:9: [errorf] should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) +// +// main.go:24:9: [errorf] should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) type Unix struct { Metadata lint.FormatterMetadata } @@ -20,8 +22,9 @@ func (*Unix) Name() string { // Format formats the failures gotten from the lint. func (*Unix) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { + var buf bytes.Buffer for failure := range failures { - fmt.Printf("%v: [%s] %s\n", failure.Position.Start, failure.RuleName, failure.Failure) + fmt.Fprintf(&buf, "%v: [%s] %s\n", failure.Position.Start, failure.RuleName, failure.Failure) } - return "", nil + return buf.String(), nil } diff --git a/tools/vendor/github.com/mgechev/revive/lint/config.go b/tools/vendor/github.com/mgechev/revive/lint/config.go index 9b26d5841..d7ecd964a 100644 --- a/tools/vendor/github.com/mgechev/revive/lint/config.go +++ b/tools/vendor/github.com/mgechev/revive/lint/config.go @@ -1,8 +1,13 @@ package lint +import ( + goversion "github.com/hashicorp/go-version" +) + // Arguments is type used for the arguments of a rule. type Arguments = []interface{} +// FileFilters is type used for modeling file filters to apply to rules. type FileFilters = []*FileFilter // RuleConfig is type used for the rule configuration. @@ -32,8 +37,8 @@ func (rc *RuleConfig) Initialize() error { type RulesConfig = map[string]RuleConfig // MustExclude - checks if given filename `name` must be excluded -func (rcfg *RuleConfig) MustExclude(name string) bool { - for _, exclude := range rcfg.excludeFilters { +func (rc *RuleConfig) MustExclude(name string) bool { + for _, exclude := range rc.excludeFilters { if exclude.MatchFileName(name) { return true } @@ -60,4 +65,7 @@ type Config struct { WarningCode int `toml:"warningCode"` Directives DirectivesConfig `toml:"directive"` Exclude []string `toml:"exclude"` + // If set, overrides the go language version specified in go.mod of + // packages being linted, and assumes this specific language version. + GoVersion *goversion.Version } diff --git a/tools/vendor/github.com/mgechev/revive/lint/doc.go b/tools/vendor/github.com/mgechev/revive/lint/doc.go new file mode 100644 index 000000000..7048adf4b --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/lint/doc.go @@ -0,0 +1,2 @@ +// Package lint implements the linting machinery. +package lint diff --git a/tools/vendor/github.com/mgechev/revive/lint/linter.go b/tools/vendor/github.com/mgechev/revive/lint/linter.go index fb1ab6f28..3c97f306f 100644 --- a/tools/vendor/github.com/mgechev/revive/lint/linter.go +++ b/tools/vendor/github.com/mgechev/revive/lint/linter.go @@ -3,12 +3,18 @@ package lint import ( "bufio" "bytes" + "encoding/json" "fmt" "go/token" "os" + "os/exec" + "path/filepath" "regexp" "strconv" + "strings" "sync" + + goversion "github.com/hashicorp/go-version" ) // ReadFile defines an abstraction for reading files. @@ -57,16 +63,52 @@ var ( func (l *Linter) Lint(packages [][]string, ruleSet []Rule, config Config) (<-chan Failure, error) { failures := make(chan Failure) + perModVersions := make(map[string]*goversion.Version) + perPkgVersions := make([]*goversion.Version, len(packages)) + for n, files := range packages { + if len(files) == 0 { + continue + } + if config.GoVersion != nil { + perPkgVersions[n] = config.GoVersion + continue + } + + dir, err := filepath.Abs(filepath.Dir(files[0])) + if err != nil { + return nil, err + } + + alreadyKnownMod := false + for d, v := range perModVersions { + if strings.HasPrefix(dir, d) { + perPkgVersions[n] = v + alreadyKnownMod = true + break + } + } + if alreadyKnownMod { + continue + } + + d, v, err := detectGoMod(dir) + if err != nil { + return nil, err + } + perModVersions[d] = v + perPkgVersions[n] = v + } + var wg sync.WaitGroup - for _, pkg := range packages { + for n := range packages { wg.Add(1) - go func(pkg []string) { - if err := l.lintPackage(pkg, ruleSet, config, failures); err != nil { + go func(pkg []string, gover *goversion.Version) { + if err := l.lintPackage(pkg, gover, ruleSet, config, failures); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer wg.Done() - }(pkg) + }(packages[n], perPkgVersions[n]) } go func() { @@ -77,10 +119,15 @@ func (l *Linter) Lint(packages [][]string, ruleSet []Rule, config Config) (<-cha return failures, nil } -func (l *Linter) lintPackage(filenames []string, ruleSet []Rule, config Config, failures chan Failure) error { +func (l *Linter) lintPackage(filenames []string, gover *goversion.Version, ruleSet []Rule, config Config, failures chan Failure) error { + if len(filenames) == 0 { + return nil + } + pkg := &Package{ - fset: token.NewFileSet(), - files: map[string]*File{}, + fset: token.NewFileSet(), + files: map[string]*File{}, + goVersion: gover, } for _, filename := range filenames { content, err := l.readFile(filename) @@ -108,6 +155,40 @@ func (l *Linter) lintPackage(filenames []string, ruleSet []Rule, config Config, return nil } +func detectGoMod(dir string) (rootDir string, ver *goversion.Version, err error) { + // https://github.com/golang/go/issues/44753#issuecomment-790089020 + cmd := exec.Command("go", "list", "-m", "-json") + cmd.Dir = dir + + out, err := cmd.Output() + if err != nil { + return "", nil, fmt.Errorf("command go list: %w", err) + } + + // NOTE: A package may be part of a go workspace. In this case `go list -m` + // lists all modules in the workspace, so we need to go through them all. + d := json.NewDecoder(bytes.NewBuffer(out)) + for d.More() { + var v struct { + GoMod string `json:"GoMod"` + GoVersion string `json:"GoVersion"` + Dir string `json:"Dir"` + } + if err = d.Decode(&v); err != nil { + return "", nil, err + } + if v.GoMod == "" { + return "", nil, fmt.Errorf("not part of a module: %q", dir) + } + if v.Dir != "" && strings.HasPrefix(dir, v.Dir) { + rootDir = v.Dir + ver, err = goversion.NewVersion(strings.TrimPrefix(v.GoVersion, "go")) + return rootDir, ver, err + } + } + return "", nil, fmt.Errorf("not part of a module: %q", dir) +} + // isGenerated reports whether the source file is generated code // according the rules from https://golang.org/s/generatedcode. // This is inherited from the original go lint. diff --git a/tools/vendor/github.com/mgechev/revive/lint/package.go b/tools/vendor/github.com/mgechev/revive/lint/package.go index 5976acf99..b4a0a72c7 100644 --- a/tools/vendor/github.com/mgechev/revive/lint/package.go +++ b/tools/vendor/github.com/mgechev/revive/lint/package.go @@ -7,13 +7,16 @@ import ( "go/types" "sync" + goversion "github.com/hashicorp/go-version" + "github.com/mgechev/revive/internal/typeparams" ) // Package represents a package in the project. type Package struct { - fset *token.FileSet - files map[string]*File + fset *token.FileSet + files map[string]*File + goVersion *goversion.Version typesPkg *types.Package typesInfo *types.Info @@ -29,6 +32,8 @@ var ( trueValue = 1 falseValue = 2 notSet = 3 + + go122 = goversion.Must(goversion.NewVersion("1.22")) ) // Files return package's files. @@ -188,3 +193,8 @@ func (p *Package) lint(rules []Rule, config Config, failures chan Failure) { } wg.Wait() } + +// IsAtLeastGo122 returns true if the Go version for this package is 1.22 or higher, false otherwise +func (p *Package) IsAtLeastGo122() bool { + return p.goVersion.GreaterThanOrEqual(go122) +} diff --git a/tools/vendor/github.com/mgechev/revive/lint/utils.go b/tools/vendor/github.com/mgechev/revive/lint/utils.go index 28657c6df..6ccfb0ef2 100644 --- a/tools/vendor/github.com/mgechev/revive/lint/utils.go +++ b/tools/vendor/github.com/mgechev/revive/lint/utils.go @@ -6,7 +6,7 @@ import ( ) // Name returns a different name if it should be different. -func Name(name string, whitelist, blacklist []string) (should string) { +func Name(name string, allowlist, blocklist []string) (should string) { // Fast path for simple cases: "_" and all lowercase. if name == "_" { return name @@ -57,12 +57,12 @@ func Name(name string, whitelist, blacklist []string) (should string) { // [w,i) is a word. word := string(runes[w:i]) ignoreInitWarnings := map[string]bool{} - for _, i := range whitelist { + for _, i := range allowlist { ignoreInitWarnings[i] = true } extraInits := map[string]bool{} - for _, i := range blacklist { + for _, i := range blocklist { extraInits[i] = true } @@ -71,6 +71,10 @@ func Name(name string, whitelist, blacklist []string) (should string) { if w == 0 && unicode.IsLower(runes[w]) { u = strings.ToLower(u) } + // Keep lowercase s for IDs + if u == "IDS" { + u = "IDs" + } // All the common initialisms are ASCII, // so we can replace the bytes exactly. copy(runes[w:], []rune(u)) @@ -99,6 +103,7 @@ var commonInitialisms = map[string]bool{ "HTTP": true, "HTTPS": true, "ID": true, + "IDS": true, "IP": true, "JSON": true, "LHS": true, diff --git a/tools/vendor/github.com/mgechev/revive/rule/add-constant.go b/tools/vendor/github.com/mgechev/revive/rule/add-constant.go index 36a7003da..73dfa932c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/add-constant.go +++ b/tools/vendor/github.com/mgechev/revive/rule/add-constant.go @@ -18,13 +18,13 @@ const ( kindSTRING = "STRING" ) -type whiteList map[string]map[string]bool +type allowList map[string]map[string]bool -func newWhiteList() whiteList { +func newAllowList() allowList { return map[string]map[string]bool{kindINT: {}, kindFLOAT: {}, kindSTRING: {}} } -func (wl whiteList) add(kind, list string) { +func (wl allowList) add(kind, list string) { elems := strings.Split(list, ",") for _, e := range elems { wl[kind][e] = true @@ -33,7 +33,7 @@ func (wl whiteList) add(kind, list string) { // AddConstantRule lints unused params in functions. type AddConstantRule struct { - whiteList whiteList + allowList allowList ignoreFunctions []*regexp.Regexp strLitLimit int sync.Mutex @@ -49,12 +49,13 @@ func (r *AddConstantRule) Apply(file *lint.File, arguments lint.Arguments) []lin failures = append(failures, failure) } - w := lintAddConstantRule{ + w := &lintAddConstantRule{ onFailure: onFailure, strLits: make(map[string]int), strLitLimit: r.strLitLimit, - whiteLst: r.whiteList, + allowList: r.allowList, ignoreFunctions: r.ignoreFunctions, + structTags: make(map[*ast.BasicLit]struct{}), } ast.Walk(w, file.AST) @@ -71,11 +72,16 @@ type lintAddConstantRule struct { onFailure func(lint.Failure) strLits map[string]int strLitLimit int - whiteLst whiteList + allowList allowList ignoreFunctions []*regexp.Regexp + structTags map[*ast.BasicLit]struct{} } -func (w lintAddConstantRule) Visit(node ast.Node) ast.Visitor { +func (w *lintAddConstantRule) Visit(node ast.Node) ast.Visitor { + if node == nil { + return nil + } + switch n := node.(type) { case *ast.CallExpr: w.checkFunc(n) @@ -83,13 +89,23 @@ func (w lintAddConstantRule) Visit(node ast.Node) ast.Visitor { case *ast.GenDecl: return nil // skip declarations case *ast.BasicLit: - w.checkLit(n) + if !w.isStructTag(n) { + w.checkLit(n) + } + case *ast.StructType: + if n.Fields != nil { + for _, field := range n.Fields.List { + if field.Tag != nil { + w.structTags[field.Tag] = struct{}{} + } + } + } } return w } -func (w lintAddConstantRule) checkFunc(expr *ast.CallExpr) { +func (w *lintAddConstantRule) checkFunc(expr *ast.CallExpr) { fName := w.getFuncName(expr) for _, arg := range expr.Args { @@ -105,12 +121,17 @@ func (w lintAddConstantRule) checkFunc(expr *ast.CallExpr) { } } -func (w lintAddConstantRule) getFuncName(expr *ast.CallExpr) string { +func (*lintAddConstantRule) getFuncName(expr *ast.CallExpr) string { switch f := expr.Fun.(type) { case *ast.SelectorExpr: switch prefix := f.X.(type) { case *ast.Ident: return prefix.Name + "." + f.Sel.Name + case *ast.CallExpr: + // If the selector is an CallExpr, like `fn().Info`, we return `.Info` as function name + if f.Sel != nil { + return "." + f.Sel.Name + } } case *ast.Ident: return f.Name @@ -119,7 +140,7 @@ func (w lintAddConstantRule) getFuncName(expr *ast.CallExpr) string { return "" } -func (w lintAddConstantRule) checkLit(n *ast.BasicLit) { +func (w *lintAddConstantRule) checkLit(n *ast.BasicLit) { switch kind := n.Kind.String(); kind { case kindFLOAT, kindINT: w.checkNumLit(kind, n) @@ -128,7 +149,7 @@ func (w lintAddConstantRule) checkLit(n *ast.BasicLit) { } } -func (w lintAddConstantRule) isIgnoredFunc(fName string) bool { +func (w *lintAddConstantRule) isIgnoredFunc(fName string) bool { for _, pattern := range w.ignoreFunctions { if pattern.MatchString(fName) { return true @@ -138,8 +159,8 @@ func (w lintAddConstantRule) isIgnoredFunc(fName string) bool { return false } -func (w lintAddConstantRule) checkStrLit(n *ast.BasicLit) { - if w.whiteLst[kindSTRING][n.Value] { +func (w *lintAddConstantRule) checkStrLit(n *ast.BasicLit) { + if w.allowList[kindSTRING][n.Value] { return } @@ -158,8 +179,8 @@ func (w lintAddConstantRule) checkStrLit(n *ast.BasicLit) { } } -func (w lintAddConstantRule) checkNumLit(kind string, n *ast.BasicLit) { - if w.whiteLst[kind][n.Value] { +func (w *lintAddConstantRule) checkNumLit(kind string, n *ast.BasicLit) { + if w.allowList[kind][n.Value] { return } @@ -171,15 +192,20 @@ func (w lintAddConstantRule) checkNumLit(kind string, n *ast.BasicLit) { }) } +func (w *lintAddConstantRule) isStructTag(n *ast.BasicLit) bool { + _, ok := w.structTags[n] + return ok +} + func (r *AddConstantRule) configure(arguments lint.Arguments) { r.Lock() defer r.Unlock() - if r.whiteList == nil { + if r.allowList == nil { r.strLitLimit = defaultStrLitLimit - r.whiteList = newWhiteList() + r.allowList = newAllowList() if len(arguments) > 0 { - args, ok := arguments[0].(map[string]interface{}) + args, ok := arguments[0].(map[string]any) if !ok { panic(fmt.Sprintf("Invalid argument to the add-constant rule. Expecting a k,v map, got %T", arguments[0])) } @@ -202,7 +228,7 @@ func (r *AddConstantRule) configure(arguments lint.Arguments) { if !ok { panic(fmt.Sprintf("Invalid argument to the add-constant rule, string expected. Got '%v' (%T)", v, v)) } - r.whiteList.add(kind, list) + r.allowList.add(kind, list) case "maxLitCount": sl, ok := v.(string) if !ok { diff --git a/tools/vendor/github.com/mgechev/revive/rule/comment-spacings.go b/tools/vendor/github.com/mgechev/revive/rule/comment-spacings.go index 0d75c55f3..bfb7eaf23 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/comment-spacings.go +++ b/tools/vendor/github.com/mgechev/revive/rule/comment-spacings.go @@ -8,7 +8,7 @@ import ( "github.com/mgechev/revive/lint" ) -// CommentSpacings Rule check the whether there is a space between +// CommentSpacingsRule check the whether there is a space between // the comment symbol( // ) and the start of the comment text type CommentSpacingsRule struct { allowList []string @@ -20,22 +20,18 @@ func (r *CommentSpacingsRule) configure(arguments lint.Arguments) { defer r.Unlock() if r.allowList == nil { - r.allowList = []string{ - "//go:", - "//revive:", - "//nolint:", - } - + r.allowList = []string{} for _, arg := range arguments { allow, ok := arg.(string) // Alt. non panicking version if !ok { panic(fmt.Sprintf("invalid argument %v for %s; expected string but got %T", arg, r.Name(), arg)) } - r.allowList = append(r.allowList, `//`+allow+`:`) + r.allowList = append(r.allowList, `//`+allow) } } } +// Apply the rule. func (r *CommentSpacingsRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure { r.configure(args) @@ -74,6 +70,7 @@ func (r *CommentSpacingsRule) Apply(file *lint.File, args lint.Arguments) []lint return failures } +// Name yields this rule name. func (*CommentSpacingsRule) Name() string { return "comment-spacings" } @@ -85,5 +82,5 @@ func (r *CommentSpacingsRule) isAllowed(line string) bool { } } - return false + return isDirectiveComment(line) } diff --git a/tools/vendor/github.com/mgechev/revive/rule/comments-density.go b/tools/vendor/github.com/mgechev/revive/rule/comments-density.go new file mode 100644 index 000000000..5956fea23 --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/rule/comments-density.go @@ -0,0 +1,95 @@ +package rule + +import ( + "fmt" + "go/ast" + "strings" + "sync" + + "github.com/mgechev/revive/lint" +) + +// CommentsDensityRule lints given else constructs. +type CommentsDensityRule struct { + minimumCommentsDensity int64 + configured bool + sync.Mutex +} + +const defaultMinimumCommentsPercentage = 0 + +func (r *CommentsDensityRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() + + if r.configured { + return + } + + r.configured = true + + if len(arguments) < 1 { + r.minimumCommentsDensity = defaultMinimumCommentsPercentage + return + } + + var ok bool + r.minimumCommentsDensity, ok = arguments[0].(int64) + if !ok { + panic(fmt.Sprintf("invalid argument for %q rule: argument should be an int, got %T", r.Name(), arguments[0])) + } +} + +// Apply applies the rule to given file. +func (r *CommentsDensityRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + + commentsLines := countDocLines(file.AST.Comments) + statementsCount := countStatements(file.AST) + density := (float32(commentsLines) / float32(statementsCount+commentsLines)) * 100 + + if density < float32(r.minimumCommentsDensity) { + return []lint.Failure{ + { + Node: file.AST, + Confidence: 1, + Failure: fmt.Sprintf("the file has a comment density of %2.f%% (%d comment lines for %d code lines) but expected a minimum of %d%%", density, commentsLines, statementsCount, r.minimumCommentsDensity), + }, + } + } + + return nil +} + +// Name returns the rule name. +func (*CommentsDensityRule) Name() string { + return "comments-density" +} + +// countStatements counts the number of program statements in the given AST. +func countStatements(node ast.Node) int { + counter := 0 + + ast.Inspect(node, func(n ast.Node) bool { + switch n.(type) { + case *ast.ExprStmt, *ast.AssignStmt, *ast.ReturnStmt, *ast.GoStmt, *ast.DeferStmt, + *ast.BranchStmt, *ast.IfStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt, + *ast.SelectStmt, *ast.ForStmt, *ast.RangeStmt, *ast.CaseClause, *ast.CommClause, + *ast.DeclStmt, *ast.FuncDecl: + counter++ + } + return true + }) + + return counter +} + +func countDocLines(comments []*ast.CommentGroup) int { + acc := 0 + for _, c := range comments { + lines := strings.Split(c.Text(), "\n") + acc += len(lines) - 1 + } + + return acc +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/confusing-naming.go b/tools/vendor/github.com/mgechev/revive/rule/confusing-naming.go index 8b1c3eac4..32f6dd803 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/confusing-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/confusing-naming.go @@ -71,7 +71,6 @@ func (*ConfusingNamingRule) Name() string { // checkMethodName checks if a given method/function name is similar (just case differences) to other method/function of the same struct/file. func checkMethodName(holder string, id *ast.Ident, w *lintConfusingNames) { - if id.Name == "init" && holder == defaultStructName { // ignore init functions return @@ -112,7 +111,7 @@ func checkMethodName(holder string, id *ast.Ident, w *lintConfusingNames) { pkgm.methods[holder] = make(map[string]*referenceMethod, 1) } - // update the black list + // update the block list if pkgm.methods[holder] == nil { println("no entry for '", holder, "'") } @@ -139,16 +138,32 @@ func getStructName(r *ast.FieldList) string { switch v := t.(type) { case *ast.StarExpr: - t = v.X + return extractFromStarExpr(v) case *ast.IndexExpr: - t = v.X + return extractFromIndexExpr(v) + case *ast.Ident: + return v.Name } - if p, _ := t.(*ast.Ident); p != nil { - result = p.Name + return defaultStructName +} + +func extractFromStarExpr(expr *ast.StarExpr) string { + switch v := expr.X.(type) { + case *ast.IndexExpr: + return extractFromIndexExpr(v) + case *ast.Ident: + return v.Name } + return defaultStructName +} - return result +func extractFromIndexExpr(expr *ast.IndexExpr) string { + switch v := expr.X.(type) { + case *ast.Ident: + return v.Name + } + return defaultStructName } func checkStructFields(fields *ast.FieldList, structName string, w *lintConfusingNames) { diff --git a/tools/vendor/github.com/mgechev/revive/rule/constant-logical-expr.go b/tools/vendor/github.com/mgechev/revive/rule/constant-logical-expr.go index 9abc95d67..36cd641f7 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/constant-logical-expr.go +++ b/tools/vendor/github.com/mgechev/revive/rule/constant-logical-expr.go @@ -11,7 +11,7 @@ import ( type ConstantLogicalExprRule struct{} // Apply applies the rule to given file. -func (r *ConstantLogicalExprRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ConstantLogicalExprRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -63,7 +63,7 @@ func (w *lintConstantLogicalExpr) Visit(node ast.Node) ast.Visitor { return w } -func (w *lintConstantLogicalExpr) isOperatorWithLogicalResult(t token.Token) bool { +func (*lintConstantLogicalExpr) isOperatorWithLogicalResult(t token.Token) bool { switch t { case token.LAND, token.LOR, token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ: return true @@ -72,7 +72,7 @@ func (w *lintConstantLogicalExpr) isOperatorWithLogicalResult(t token.Token) boo return false } -func (w *lintConstantLogicalExpr) isEqualityOperator(t token.Token) bool { +func (*lintConstantLogicalExpr) isEqualityOperator(t token.Token) bool { switch t { case token.EQL, token.LEQ, token.GEQ: return true @@ -81,7 +81,7 @@ func (w *lintConstantLogicalExpr) isEqualityOperator(t token.Token) bool { return false } -func (w *lintConstantLogicalExpr) isInequalityOperator(t token.Token) bool { +func (*lintConstantLogicalExpr) isInequalityOperator(t token.Token) bool { switch t { case token.LSS, token.GTR, token.NEQ: return true diff --git a/tools/vendor/github.com/mgechev/revive/rule/context-as-argument.go b/tools/vendor/github.com/mgechev/revive/rule/context-as-argument.go index 3c400065e..e0c8cfa5e 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/context-as-argument.go +++ b/tools/vendor/github.com/mgechev/revive/rule/context-as-argument.go @@ -82,7 +82,7 @@ func (w lintContextArguments) Visit(n ast.Node) ast.Visitor { func getAllowTypesFromArguments(args lint.Arguments) map[string]struct{} { allowTypesBefore := []string{} if len(args) >= 1 { - argKV, ok := args[0].(map[string]interface{}) + argKV, ok := args[0].(map[string]any) if !ok { panic(fmt.Sprintf("Invalid argument to the context-as-argument rule. Expecting a k,v map, got %T", args[0])) } diff --git a/tools/vendor/github.com/mgechev/revive/rule/datarace.go b/tools/vendor/github.com/mgechev/revive/rule/datarace.go index 26fcadcdc..86ec6e113 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/datarace.go +++ b/tools/vendor/github.com/mgechev/revive/rule/datarace.go @@ -16,7 +16,7 @@ func (*DataRaceRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { onFailure := func(failure lint.Failure) { failures = append(failures, failure) } - w := lintDataRaces{onFailure: onFailure} + w := lintDataRaces{onFailure: onFailure, go122for: file.Pkg.IsAtLeastGo122()} ast.Walk(w, file.AST) @@ -30,6 +30,7 @@ func (*DataRaceRule) Name() string { type lintDataRaces struct { onFailure func(failure lint.Failure) + go122for bool } func (w lintDataRaces) Visit(n ast.Node) ast.Visitor { @@ -47,13 +48,13 @@ func (w lintDataRaces) Visit(n ast.Node) ast.Visitor { if results != nil { returnIDs = w.ExtractReturnIDs(results.List) } - fl := &lintFunctionForDataRaces{onFailure: w.onFailure, returnIDs: returnIDs, rangeIDs: map[*ast.Object]struct{}{}} + fl := &lintFunctionForDataRaces{onFailure: w.onFailure, returnIDs: returnIDs, rangeIDs: map[*ast.Object]struct{}{}, go122for: w.go122for} ast.Walk(fl, node.Body) return nil } -func (w lintDataRaces) ExtractReturnIDs(fields []*ast.Field) map[*ast.Object]struct{} { +func (lintDataRaces) ExtractReturnIDs(fields []*ast.Field) map[*ast.Object]struct{} { r := map[*ast.Object]struct{}{} for _, f := range fields { for _, id := range f.Names { @@ -69,6 +70,7 @@ type lintFunctionForDataRaces struct { onFailure func(failure lint.Failure) returnIDs map[*ast.Object]struct{} rangeIDs map[*ast.Object]struct{} + go122for bool } func (w lintFunctionForDataRaces) Visit(node ast.Node) ast.Visitor { @@ -111,14 +113,14 @@ func (w lintFunctionForDataRaces) Visit(node ast.Node) ast.Visitor { return ok } - ids := pick(funcLit.Body, selectIDs, nil) + ids := pick(funcLit.Body, selectIDs) for _, id := range ids { id := id.(*ast.Ident) _, isRangeID := w.rangeIDs[id.Obj] _, isReturnID := w.returnIDs[id.Obj] switch { - case isRangeID: + case isRangeID && !w.go122for: w.onFailure(lint.Failure{ Confidence: 1, Node: id, diff --git a/tools/vendor/github.com/mgechev/revive/rule/defer.go b/tools/vendor/github.com/mgechev/revive/rule/defer.go index f3ea17920..adc6478ae 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/defer.go +++ b/tools/vendor/github.com/mgechev/revive/rule/defer.go @@ -56,7 +56,7 @@ func (*DeferRule) allowFromArgs(args lint.Arguments) map[string]bool { return allow } - aa, ok := args[0].([]interface{}) + aa, ok := args[0].([]any) if !ok { panic(fmt.Sprintf("Invalid argument '%v' for 'defer' rule. Expecting []string, got %T", args[0], args[0])) } @@ -144,8 +144,8 @@ func (w lintDeferRule) Visit(node ast.Node) ast.Visitor { w.newFailure("be careful when deferring calls to methods without pointer receiver", fn, 0.8, "bad practice", "method-call") } } - } + return nil } diff --git a/tools/vendor/github.com/mgechev/revive/rule/doc.go b/tools/vendor/github.com/mgechev/revive/rule/doc.go new file mode 100644 index 000000000..55bf6caa6 --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/rule/doc.go @@ -0,0 +1,2 @@ +// Package rule implements revive's linting rules. +package rule diff --git a/tools/vendor/github.com/mgechev/revive/rule/dot-imports.go b/tools/vendor/github.com/mgechev/revive/rule/dot-imports.go index db78f1957..6b877677d 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/dot-imports.go +++ b/tools/vendor/github.com/mgechev/revive/rule/dot-imports.go @@ -1,16 +1,23 @@ package rule import ( + "fmt" "go/ast" + "sync" "github.com/mgechev/revive/lint" ) // DotImportsRule lints given else constructs. -type DotImportsRule struct{} +type DotImportsRule struct { + sync.Mutex + allowedPackages allowPackages +} // Apply applies the rule to given file. -func (*DotImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (r *DotImportsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + var failures []lint.Failure fileAst := file.AST @@ -20,6 +27,7 @@ func (*DotImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { onFailure: func(failure lint.Failure) { failures = append(failures, failure) }, + allowPackages: r.allowedPackages, } ast.Walk(walker, fileAst) @@ -32,15 +40,49 @@ func (*DotImportsRule) Name() string { return "dot-imports" } +func (r *DotImportsRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() + + if r.allowedPackages != nil { + return + } + + r.allowedPackages = make(allowPackages) + if len(arguments) == 0 { + return + } + + args, ok := arguments[0].(map[string]any) + if !ok { + panic(fmt.Sprintf("Invalid argument to the dot-imports rule. Expecting a k,v map, got %T", arguments[0])) + } + + if allowedPkgArg, ok := args["allowedPackages"]; ok { + if pkgs, ok := allowedPkgArg.([]any); ok { + for _, p := range pkgs { + if pkg, ok := p.(string); ok { + r.allowedPackages.add(pkg) + } else { + panic(fmt.Sprintf("Invalid argument to the dot-imports rule, string expected. Got '%v' (%T)", p, p)) + } + } + } else { + panic(fmt.Sprintf("Invalid argument to the dot-imports rule, []string expected. Got '%v' (%T)", allowedPkgArg, allowedPkgArg)) + } + } +} + type lintImports struct { - file *lint.File - fileAst *ast.File - onFailure func(lint.Failure) + file *lint.File + fileAst *ast.File + onFailure func(lint.Failure) + allowPackages allowPackages } func (w lintImports) Visit(_ ast.Node) ast.Visitor { for _, is := range w.fileAst.Imports { - if is.Name != nil && is.Name.Name == "." { + if is.Name != nil && is.Name.Name == "." && !w.allowPackages.isAllowedPackage(is.Path.Value) { w.onFailure(lint.Failure{ Confidence: 1, Failure: "should not use dot imports", @@ -51,3 +93,14 @@ func (w lintImports) Visit(_ ast.Node) ast.Visitor { } return nil } + +type allowPackages map[string]struct{} + +func (ap allowPackages) add(pkg string) { + ap[fmt.Sprintf(`"%s"`, pkg)] = struct{}{} // import path strings are with double quotes +} + +func (ap allowPackages) isAllowedPackage(pkg string) bool { + _, allowed := ap[pkg] + return allowed +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/early-return.go b/tools/vendor/github.com/mgechev/revive/rule/early-return.go index 90a0acc55..9c04a1dbe 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/early-return.go +++ b/tools/vendor/github.com/mgechev/revive/rule/early-return.go @@ -22,7 +22,7 @@ func (*EarlyReturnRule) Name() string { } // CheckIfElse evaluates the rule against an ifelse.Chain. -func (e *EarlyReturnRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) { +func (*EarlyReturnRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) { if !chain.Else.Deviates() { // this rule only applies if the else-block deviates control flow return diff --git a/tools/vendor/github.com/mgechev/revive/rule/enforce-map-style.go b/tools/vendor/github.com/mgechev/revive/rule/enforce-map-style.go index ae27b654f..36ac2374c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/enforce-map-style.go +++ b/tools/vendor/github.com/mgechev/revive/rule/enforce-map-style.go @@ -47,7 +47,7 @@ type EnforceMapStyleRule struct { func (r *EnforceMapStyleRule) configure(arguments lint.Arguments) { r.Lock() defer r.Unlock() - + if r.configured { return } @@ -58,7 +58,7 @@ func (r *EnforceMapStyleRule) configure(arguments lint.Arguments) { return } - enforceMapStyle, ok := arguments[0].(string) + enforceMapStyle, ok := arguments[0].(string) if !ok { panic(fmt.Sprintf("Invalid argument '%v' for 'enforce-map-style' rule. Expecting string, got %T", arguments[0], arguments[0])) } @@ -141,7 +141,7 @@ func (r *EnforceMapStyleRule) Apply(file *lint.File, arguments lint.Arguments) [ } // Name returns the rule name. -func (r *EnforceMapStyleRule) Name() string { +func (*EnforceMapStyleRule) Name() string { return "enforce-map-style" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/enforce-repeated-arg-type-style.go b/tools/vendor/github.com/mgechev/revive/rule/enforce-repeated-arg-type-style.go new file mode 100644 index 000000000..067082b1b --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/rule/enforce-repeated-arg-type-style.go @@ -0,0 +1,191 @@ +package rule + +import ( + "fmt" + "go/ast" + "go/types" + "sync" + + "github.com/mgechev/revive/lint" +) + +type enforceRepeatedArgTypeStyleType string + +const ( + enforceRepeatedArgTypeStyleTypeAny enforceRepeatedArgTypeStyleType = "any" + enforceRepeatedArgTypeStyleTypeShort enforceRepeatedArgTypeStyleType = "short" + enforceRepeatedArgTypeStyleTypeFull enforceRepeatedArgTypeStyleType = "full" +) + +func repeatedArgTypeStyleFromString(s string) enforceRepeatedArgTypeStyleType { + switch s { + case string(enforceRepeatedArgTypeStyleTypeAny), "": + return enforceRepeatedArgTypeStyleTypeAny + case string(enforceRepeatedArgTypeStyleTypeShort): + return enforceRepeatedArgTypeStyleTypeShort + case string(enforceRepeatedArgTypeStyleTypeFull): + return enforceRepeatedArgTypeStyleTypeFull + default: + err := fmt.Errorf( + "invalid repeated arg type style: %s (expecting one of %v)", + s, + []enforceRepeatedArgTypeStyleType{ + enforceRepeatedArgTypeStyleTypeAny, + enforceRepeatedArgTypeStyleTypeShort, + enforceRepeatedArgTypeStyleTypeFull, + }, + ) + + panic(fmt.Sprintf("Invalid argument to the enforce-repeated-arg-type-style rule: %v", err)) + } +} + +// EnforceRepeatedArgTypeStyleRule implements a rule to enforce repeated argument type style. +type EnforceRepeatedArgTypeStyleRule struct { + configured bool + funcArgStyle enforceRepeatedArgTypeStyleType + funcRetValStyle enforceRepeatedArgTypeStyleType + + sync.Mutex +} + +func (r *EnforceRepeatedArgTypeStyleRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() + + if r.configured { + return + } + r.configured = true + + r.funcArgStyle = enforceRepeatedArgTypeStyleTypeAny + r.funcRetValStyle = enforceRepeatedArgTypeStyleTypeAny + + if len(arguments) == 0 { + return + } + + switch funcArgStyle := arguments[0].(type) { + case string: + r.funcArgStyle = repeatedArgTypeStyleFromString(funcArgStyle) + r.funcRetValStyle = repeatedArgTypeStyleFromString(funcArgStyle) + case map[string]any: // expecting map[string]string + for k, v := range funcArgStyle { + switch k { + case "funcArgStyle": + val, ok := v.(string) + if !ok { + panic(fmt.Sprintf("Invalid map value type for 'enforce-repeated-arg-type-style' rule. Expecting string, got %T", v)) + } + r.funcArgStyle = repeatedArgTypeStyleFromString(val) + case "funcRetValStyle": + val, ok := v.(string) + if !ok { + panic(fmt.Sprintf("Invalid map value '%v' for 'enforce-repeated-arg-type-style' rule. Expecting string, got %T", v, v)) + } + r.funcRetValStyle = repeatedArgTypeStyleFromString(val) + default: + panic(fmt.Sprintf("Invalid map key for 'enforce-repeated-arg-type-style' rule. Expecting 'funcArgStyle' or 'funcRetValStyle', got %v", k)) + } + } + default: + panic(fmt.Sprintf("Invalid argument '%v' for 'import-alias-naming' rule. Expecting string or map[string]string, got %T", arguments[0], arguments[0])) + } +} + +// Apply applies the rule to a given file. +func (r *EnforceRepeatedArgTypeStyleRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + + if r.funcArgStyle == enforceRepeatedArgTypeStyleTypeAny && r.funcRetValStyle == enforceRepeatedArgTypeStyleTypeAny { + // This linter is not configured, return no failures. + return nil + } + + var failures []lint.Failure + + err := file.Pkg.TypeCheck() + if err != nil { + // the file has other issues + return nil + } + typesInfo := file.Pkg.TypesInfo() + + astFile := file.AST + ast.Inspect(astFile, func(n ast.Node) bool { + switch fn := n.(type) { + case *ast.FuncDecl: + if r.funcArgStyle == enforceRepeatedArgTypeStyleTypeFull { + if fn.Type.Params != nil { + for _, field := range fn.Type.Params.List { + if len(field.Names) > 1 { + failures = append(failures, lint.Failure{ + Confidence: 1, + Node: field, + Category: "style", + Failure: "argument types should not be omitted", + }) + } + } + } + } + + if r.funcArgStyle == enforceRepeatedArgTypeStyleTypeShort { + var prevType ast.Expr + if fn.Type.Params != nil { + for _, field := range fn.Type.Params.List { + if types.Identical(typesInfo.Types[field.Type].Type, typesInfo.Types[prevType].Type) { + failures = append(failures, lint.Failure{ + Confidence: 1, + Node: field, + Category: "style", + Failure: "repeated argument type can be omitted", + }) + } + prevType = field.Type + } + } + } + + if r.funcRetValStyle == enforceRepeatedArgTypeStyleTypeFull { + if fn.Type.Results != nil { + for _, field := range fn.Type.Results.List { + if len(field.Names) > 1 { + failures = append(failures, lint.Failure{ + Confidence: 1, + Node: field, + Category: "style", + Failure: "return types should not be omitted", + }) + } + } + } + } + + if r.funcRetValStyle == enforceRepeatedArgTypeStyleTypeShort { + var prevType ast.Expr + if fn.Type.Results != nil { + for _, field := range fn.Type.Results.List { + if field.Names != nil && types.Identical(typesInfo.Types[field.Type].Type, typesInfo.Types[prevType].Type) { + failures = append(failures, lint.Failure{ + Confidence: 1, + Node: field, + Category: "style", + Failure: "repeated return type can be omitted", + }) + } + prevType = field.Type + } + } + } + } + return true + }) + + return failures +} + +// Name returns the name of the linter rule. +func (*EnforceRepeatedArgTypeStyleRule) Name() string { + return "enforce-repeated-arg-type-style" +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/enforce-slice-style.go b/tools/vendor/github.com/mgechev/revive/rule/enforce-slice-style.go new file mode 100644 index 000000000..60d8ac066 --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/rule/enforce-slice-style.go @@ -0,0 +1,214 @@ +package rule + +import ( + "fmt" + "go/ast" + "sync" + + "github.com/mgechev/revive/lint" +) + +type enforceSliceStyleType string + +const ( + enforceSliceStyleTypeAny enforceSliceStyleType = "any" + enforceSliceStyleTypeMake enforceSliceStyleType = "make" + enforceSliceStyleTypeLiteral enforceSliceStyleType = "literal" + enforceSliceStyleTypeNil enforceSliceStyleType = "nil" +) + +func sliceStyleFromString(s string) (enforceSliceStyleType, error) { + switch s { + case string(enforceSliceStyleTypeAny), "": + return enforceSliceStyleTypeAny, nil + case string(enforceSliceStyleTypeMake): + return enforceSliceStyleTypeMake, nil + case string(enforceSliceStyleTypeLiteral): + return enforceSliceStyleTypeLiteral, nil + case string(enforceSliceStyleTypeNil): + return enforceSliceStyleTypeNil, nil + default: + return enforceSliceStyleTypeAny, fmt.Errorf( + "invalid slice style: %s (expecting one of %v)", + s, + []enforceSliceStyleType{ + enforceSliceStyleTypeAny, + enforceSliceStyleTypeMake, + enforceSliceStyleTypeLiteral, + enforceSliceStyleTypeNil, + }, + ) + } +} + +// EnforceSliceStyleRule implements a rule to enforce `make([]type)` over `[]type{}`. +type EnforceSliceStyleRule struct { + configured bool + enforceSliceStyle enforceSliceStyleType + sync.Mutex +} + +func (r *EnforceSliceStyleRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() + + if r.configured { + return + } + r.configured = true + + if len(arguments) < 1 { + r.enforceSliceStyle = enforceSliceStyleTypeAny + return + } + + enforceSliceStyle, ok := arguments[0].(string) + if !ok { + panic(fmt.Sprintf("Invalid argument '%v' for 'enforce-slice-style' rule. Expecting string, got %T", arguments[0], arguments[0])) + } + + var err error + r.enforceSliceStyle, err = sliceStyleFromString(enforceSliceStyle) + + if err != nil { + panic(fmt.Sprintf("Invalid argument to the enforce-slice-style rule: %v", err)) + } +} + +// Apply applies the rule to given file. +func (r *EnforceSliceStyleRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + + if r.enforceSliceStyle == enforceSliceStyleTypeAny { + // this linter is not configured + return nil + } + + var failures []lint.Failure + + astFile := file.AST + ast.Inspect(astFile, func(n ast.Node) bool { + switch v := n.(type) { + case *ast.CompositeLit: + switch r.enforceSliceStyle { + case enforceSliceStyleTypeMake, enforceSliceStyleTypeNil: + // continue + default: + return true + } + + if !r.isSliceType(v.Type) { + return true + } + + if len(v.Elts) > 0 { + // not an empty slice + return true + } + + var failureMessage string + if r.enforceSliceStyle == enforceSliceStyleTypeNil { + failureMessage = "use nil slice declaration (e.g. var args []type) instead of []type{}" + } else { + failureMessage = "use make([]type) instead of []type{} (or declare nil slice)" + } + failures = append(failures, lint.Failure{ + Confidence: 1, + Node: v, + Category: "style", + Failure: failureMessage, + }) + case *ast.CallExpr: + switch r.enforceSliceStyle { + case enforceSliceStyleTypeLiteral, enforceSliceStyleTypeNil: + default: + // skip any function calls, even if it's make([]type) + // we don't want to report it if literals are not enforced + return true + } + + ident, ok := v.Fun.(*ast.Ident) + if !ok || ident.Name != "make" { + return true + } + + if len(v.Args) < 2 { + // skip invalid make declarations + return true + } + + if !r.isSliceType(v.Args[0]) { + // not a slice type + return true + } + + arg, ok := v.Args[1].(*ast.BasicLit) + if !ok { + // skip invalid make declarations + return true + } + + if arg.Value != "0" { + // skip slice with non-zero size + return true + } + + if len(v.Args) > 2 { + arg, ok := v.Args[2].(*ast.BasicLit) + if !ok { + // skip invalid make declarations + return true + } + + if arg.Value != "0" { + // skip non-zero capacity slice + return true + } + } + + var failureMessage string + if r.enforceSliceStyle == enforceSliceStyleTypeNil { + failureMessage = "use nil slice declaration (e.g. var args []type) instead of make([]type, 0)" + } else { + failureMessage = "use []type{} instead of make([]type, 0) (or declare nil slice)" + } + failures = append(failures, lint.Failure{ + Confidence: 1, + Node: v.Args[0], + Category: "style", + Failure: failureMessage, + }) + } + return true + }) + + return failures +} + +// Name returns the rule name. +func (*EnforceSliceStyleRule) Name() string { + return "enforce-slice-style" +} + +func (r *EnforceSliceStyleRule) isSliceType(v ast.Expr) bool { + switch t := v.(type) { + case *ast.ArrayType: + if t.Len != nil { + // array + return false + } + // slice + return true + case *ast.Ident: + if t.Obj == nil { + return false + } + typeSpec, ok := t.Obj.Decl.(*ast.TypeSpec) + if !ok { + return false + } + return r.isSliceType(typeSpec.Type) + default: + return false + } +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/flag-param.go b/tools/vendor/github.com/mgechev/revive/rule/flag-param.go index 19a05f9fe..f9bfb712c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/flag-param.go +++ b/tools/vendor/github.com/mgechev/revive/rule/flag-param.go @@ -88,7 +88,7 @@ func (w conditionVisitor) Visit(node ast.Node) ast.Visitor { return false } - uses := pick(ifStmt.Cond, fselect, nil) + uses := pick(ifStmt.Cond, fselect) if len(uses) < 1 { return w diff --git a/tools/vendor/github.com/mgechev/revive/rule/function-length.go b/tools/vendor/github.com/mgechev/revive/rule/function-length.go index f7ab8b98e..fd65884e9 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/function-length.go +++ b/tools/vendor/github.com/mgechev/revive/rule/function-length.go @@ -171,7 +171,7 @@ func (w lintFuncLength) countFuncLitStmts(stmt ast.Expr) int { return 0 } -func (w lintFuncLength) countBodyListStmts(t interface{}) int { +func (w lintFuncLength) countBodyListStmts(t any) int { i := reflect.ValueOf(t).Elem().FieldByName(`Body`).Elem().FieldByName(`List`).Interface() return w.countStmts(i.([]ast.Stmt)) } diff --git a/tools/vendor/github.com/mgechev/revive/rule/import-alias-naming.go b/tools/vendor/github.com/mgechev/revive/rule/import-alias-naming.go index 292392b5d..a6d096c8b 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/import-alias-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/import-alias-naming.go @@ -10,14 +10,15 @@ import ( // ImportAliasNamingRule lints import alias naming. type ImportAliasNamingRule struct { - configured bool - namingRuleRegexp *regexp.Regexp + configured bool + allowRegexp *regexp.Regexp + denyRegexp *regexp.Regexp sync.Mutex } -const defaultNamingRule = "^[a-z][a-z0-9]{0,}$" +const defaultImportAliasNamingAllowRule = "^[a-z][a-z0-9]{0,}$" -var defaultNamingRuleRegexp = regexp.MustCompile(defaultNamingRule) +var defaultImportAliasNamingAllowRegexp = regexp.MustCompile(defaultImportAliasNamingAllowRule) func (r *ImportAliasNamingRule) configure(arguments lint.Arguments) { r.Lock() @@ -26,20 +27,31 @@ func (r *ImportAliasNamingRule) configure(arguments lint.Arguments) { return } - if len(arguments) < 1 { - r.namingRuleRegexp = defaultNamingRuleRegexp + if len(arguments) == 0 { + r.allowRegexp = defaultImportAliasNamingAllowRegexp return } - namingRule, ok := arguments[0].(string) // Alt. non panicking version - if !ok { - panic(fmt.Sprintf("Invalid argument '%v' for 'import-alias-naming' rule. Expecting string, got %T", arguments[0], arguments[0])) + switch namingRule := arguments[0].(type) { + case string: + r.setAllowRule(namingRule) + case map[string]any: // expecting map[string]string + for k, v := range namingRule { + switch k { + case "allowRegex": + r.setAllowRule(v) + case "denyRegex": + r.setDenyRule(v) + default: + panic(fmt.Sprintf("Invalid map key for 'import-alias-naming' rule. Expecting 'allowRegex' or 'denyRegex', got %v", k)) + } + } + default: + panic(fmt.Sprintf("Invalid argument '%v' for 'import-alias-naming' rule. Expecting string or map[string]string, got %T", arguments[0], arguments[0])) } - var err error - r.namingRuleRegexp, err = regexp.Compile(namingRule) - if err != nil { - panic(fmt.Sprintf("Invalid argument to the import-alias-naming rule. Expecting %q to be a valid regular expression, got: %v", namingRule, err)) + if r.allowRegexp == nil && r.denyRegexp == nil { + r.allowRegexp = defaultImportAliasNamingAllowRegexp } } @@ -56,14 +68,23 @@ func (r *ImportAliasNamingRule) Apply(file *lint.File, arguments lint.Arguments) } alias := is.Name - if alias == nil || alias.Name == "_" { + if alias == nil || alias.Name == "_" || alias.Name == "." { // "_" and "." are special types of import aiases and should be processed by another linter rule continue } - if !r.namingRuleRegexp.MatchString(alias.Name) { + if r.allowRegexp != nil && !r.allowRegexp.MatchString(alias.Name) { + failures = append(failures, lint.Failure{ + Confidence: 1, + Failure: fmt.Sprintf("import name (%s) must match the regular expression: %s", alias.Name, r.allowRegexp.String()), + Node: alias, + Category: "imports", + }) + } + + if r.denyRegexp != nil && r.denyRegexp.MatchString(alias.Name) { failures = append(failures, lint.Failure{ Confidence: 1, - Failure: fmt.Sprintf("import name (%s) must match the regular expression: %s", alias.Name, r.namingRuleRegexp.String()), + Failure: fmt.Sprintf("import name (%s) must NOT match the regular expression: %s", alias.Name, r.denyRegexp.String()), Node: alias, Category: "imports", }) @@ -77,3 +98,29 @@ func (r *ImportAliasNamingRule) Apply(file *lint.File, arguments lint.Arguments) func (*ImportAliasNamingRule) Name() string { return "import-alias-naming" } + +func (r *ImportAliasNamingRule) setAllowRule(value any) { + namingRule, ok := value.(string) + if !ok { + panic(fmt.Sprintf("Invalid argument '%v' for import-alias-naming allowRegexp rule. Expecting string, got %T", value, value)) + } + + namingRuleRegexp, err := regexp.Compile(namingRule) + if err != nil { + panic(fmt.Sprintf("Invalid argument to the import-alias-naming allowRegexp rule. Expecting %q to be a valid regular expression, got: %v", namingRule, err)) + } + r.allowRegexp = namingRuleRegexp +} + +func (r *ImportAliasNamingRule) setDenyRule(value any) { + namingRule, ok := value.(string) + if !ok { + panic(fmt.Sprintf("Invalid argument '%v' for import-alias-naming denyRegexp rule. Expecting string, got %T", value, value)) + } + + namingRuleRegexp, err := regexp.Compile(namingRule) + if err != nil { + panic(fmt.Sprintf("Invalid argument to the import-alias-naming denyRegexp rule. Expecting %q to be a valid regular expression, got: %v", namingRule, err)) + } + r.denyRegexp = namingRuleRegexp +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/imports-blacklist.go b/tools/vendor/github.com/mgechev/revive/rule/imports-blocklist.go similarity index 50% rename from tools/vendor/github.com/mgechev/revive/rule/imports-blacklist.go rename to tools/vendor/github.com/mgechev/revive/rule/imports-blocklist.go index bb8262cae..431066403 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/imports-blacklist.go +++ b/tools/vendor/github.com/mgechev/revive/rule/imports-blocklist.go @@ -8,37 +8,37 @@ import ( "github.com/mgechev/revive/lint" ) -// ImportsBlacklistRule lints given else constructs. -type ImportsBlacklistRule struct { - blacklist []*regexp.Regexp +// ImportsBlocklistRule lints given else constructs. +type ImportsBlocklistRule struct { + blocklist []*regexp.Regexp sync.Mutex } -var replaceRegexp = regexp.MustCompile(`/?\*\*/?`) +var replaceImportRegexp = regexp.MustCompile(`/?\*\*/?`) -func (r *ImportsBlacklistRule) configure(arguments lint.Arguments) { +func (r *ImportsBlocklistRule) configure(arguments lint.Arguments) { r.Lock() defer r.Unlock() - if r.blacklist == nil { - r.blacklist = make([]*regexp.Regexp, 0) + if r.blocklist == nil { + r.blocklist = make([]*regexp.Regexp, 0) for _, arg := range arguments { argStr, ok := arg.(string) if !ok { - panic(fmt.Sprintf("Invalid argument to the imports-blacklist rule. Expecting a string, got %T", arg)) + panic(fmt.Sprintf("Invalid argument to the imports-blocklist rule. Expecting a string, got %T", arg)) } - regStr, err := regexp.Compile(fmt.Sprintf(`(?m)"%s"$`, replaceRegexp.ReplaceAllString(argStr, `(\W|\w)*`))) + regStr, err := regexp.Compile(fmt.Sprintf(`(?m)"%s"$`, replaceImportRegexp.ReplaceAllString(argStr, `(\W|\w)*`))) if err != nil { - panic(fmt.Sprintf("Invalid argument to the imports-blacklist rule. Expecting %q to be a valid regular expression, got: %v", argStr, err)) + panic(fmt.Sprintf("Invalid argument to the imports-blocklist rule. Expecting %q to be a valid regular expression, got: %v", argStr, err)) } - r.blacklist = append(r.blacklist, regStr) + r.blocklist = append(r.blocklist, regStr) } } } -func (r *ImportsBlacklistRule) isBlacklisted(path string) bool { - for _, regex := range r.blacklist { +func (r *ImportsBlocklistRule) isBlocklisted(path string) bool { + for _, regex := range r.blocklist { if regex.MatchString(path) { return true } @@ -47,17 +47,17 @@ func (r *ImportsBlacklistRule) isBlacklisted(path string) bool { } // Apply applies the rule to given file. -func (r *ImportsBlacklistRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *ImportsBlocklistRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { r.configure(arguments) var failures []lint.Failure for _, is := range file.AST.Imports { path := is.Path - if path != nil && r.isBlacklisted(path.Value) { + if path != nil && r.isBlocklisted(path.Value) { failures = append(failures, lint.Failure{ Confidence: 1, - Failure: "should not use the following blacklisted import: " + path.Value, + Failure: "should not use the following blocklisted import: " + path.Value, Node: is, Category: "imports", }) @@ -68,6 +68,6 @@ func (r *ImportsBlacklistRule) Apply(file *lint.File, arguments lint.Arguments) } // Name returns the rule name. -func (*ImportsBlacklistRule) Name() string { - return "imports-blacklist" +func (*ImportsBlocklistRule) Name() string { + return "imports-blocklist" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/indent-error-flow.go b/tools/vendor/github.com/mgechev/revive/rule/indent-error-flow.go index b80e6486c..294ceef84 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/indent-error-flow.go +++ b/tools/vendor/github.com/mgechev/revive/rule/indent-error-flow.go @@ -19,7 +19,7 @@ func (*IndentErrorFlowRule) Name() string { } // CheckIfElse evaluates the rule against an ifelse.Chain. -func (e *IndentErrorFlowRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) { +func (*IndentErrorFlowRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) { if !chain.If.Deviates() { // this rule only applies if the if-block deviates control flow return diff --git a/tools/vendor/github.com/mgechev/revive/rule/max-control-nesting.go b/tools/vendor/github.com/mgechev/revive/rule/max-control-nesting.go new file mode 100644 index 000000000..c4eb36193 --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/rule/max-control-nesting.go @@ -0,0 +1,128 @@ +package rule + +import ( + "fmt" + "go/ast" + "sync" + + "github.com/mgechev/revive/lint" +) + +// MaxControlNestingRule lints given else constructs. +type MaxControlNestingRule struct { + max int64 + sync.Mutex +} + +const defaultMaxControlNesting = 5 + +// Apply applies the rule to given file. +func (r *MaxControlNestingRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + + var failures []lint.Failure + + fileAst := file.AST + + walker := &lintMaxControlNesting{ + onFailure: func(failure lint.Failure) { + failures = append(failures, failure) + }, + max: int(r.max), + } + + ast.Walk(walker, fileAst) + + return failures +} + +// Name returns the rule name. +func (*MaxControlNestingRule) Name() string { + return "max-control-nesting" +} + +type lintMaxControlNesting struct { + max int + onFailure func(lint.Failure) + nestingLevelAcc int + lastCtrlStmt ast.Node +} + +func (w *lintMaxControlNesting) Visit(n ast.Node) ast.Visitor { + if w.nestingLevelAcc > w.max { // we are visiting a node beyond the max nesting level + w.onFailure(lint.Failure{ + Failure: fmt.Sprintf("control flow nesting exceeds %d", w.max), + Confidence: 1, + Node: w.lastCtrlStmt, + Category: "complexity", + }) + return nil // stop visiting deeper + } + + switch v := n.(type) { + case *ast.IfStmt: + w.lastCtrlStmt = v + w.walkControlledBlock(v.Body) // "then" branch block + if v.Else != nil { + w.walkControlledBlock(v.Else) // "else" branch block + } + return nil // stop re-visiting nesting blocks (already visited by w.walkControlledBlock) + + case *ast.ForStmt: + w.lastCtrlStmt = v + w.walkControlledBlock(v.Body) + return nil // stop re-visiting nesting blocks (already visited by w.walkControlledBlock) + + case *ast.CaseClause: // switch case + w.lastCtrlStmt = v + for _, s := range v.Body { // visit each statement in the case clause + w.walkControlledBlock(s) + } + return nil // stop re-visiting nesting blocks (already visited by w.walkControlledBlock) + + case *ast.CommClause: // select case + w.lastCtrlStmt = v + for _, s := range v.Body { // visit each statement in the select case clause + w.walkControlledBlock(s) + } + return nil // stop re-visiting nesting blocks (already visited by w.walkControlledBlock) + + case *ast.FuncLit: + walker := &lintMaxControlNesting{ + onFailure: w.onFailure, + max: w.max, + } + ast.Walk(walker, v.Body) + return nil + } + + return w +} + +func (w *lintMaxControlNesting) walkControlledBlock(b ast.Node) { + oldNestingLevel := w.nestingLevelAcc + w.nestingLevelAcc++ + ast.Walk(w, b) + w.nestingLevelAcc = oldNestingLevel +} + +func (r *MaxControlNestingRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() + if !(r.max < 1) { + return // max already set + } + + if len(arguments) < 1 { + r.max = defaultMaxControlNesting + return + } + + checkNumberOfArguments(1, arguments, r.Name()) + + max, ok := arguments[0].(int64) // Alt. non panicking version + if !ok { + panic(`invalid value passed as argument number to the "max-control-nesting" rule`) + } + r.max = max +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/modifies-value-receiver.go b/tools/vendor/github.com/mgechev/revive/rule/modifies-value-receiver.go index 34e651557..e9e64b9a6 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/modifies-value-receiver.go +++ b/tools/vendor/github.com/mgechev/revive/rule/modifies-value-receiver.go @@ -78,11 +78,6 @@ func (w lintModifiesValRecRule) Visit(node ast.Node) ast.Visitor { if name == "" || name != receiverName { continue } - - if w.skipType(ast.Expr(e.Sel)) { - continue - } - case *ast.Ident: // receiver := ... if e.Name != receiverName { continue @@ -97,7 +92,7 @@ func (w lintModifiesValRecRule) Visit(node ast.Node) ast.Visitor { return false } - assignmentsToReceiver := pick(n.Body, fselect, nil) + assignmentsToReceiver := pick(n.Body, fselect) for _, assignment := range assignmentsToReceiver { w.onFailure(lint.Failure{ diff --git a/tools/vendor/github.com/mgechev/revive/rule/optimize-operands-order.go b/tools/vendor/github.com/mgechev/revive/rule/optimize-operands-order.go index 88928bb98..43d982d6b 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/optimize-operands-order.go +++ b/tools/vendor/github.com/mgechev/revive/rule/optimize-operands-order.go @@ -49,18 +49,27 @@ func (w lintOptimizeOperandsOrderlExpr) Visit(node ast.Node) ast.Visitor { } isCaller := func(n ast.Node) bool { - _, ok := n.(*ast.CallExpr) - return ok + ce, ok := n.(*ast.CallExpr) + if !ok { + return false + } + + ident, isIdent := ce.Fun.(*ast.Ident) + if !isIdent { + return true + } + + return ident.Name != "len" || ident.Obj != nil } // check if the left sub-expression contains a function call - nodes := pick(binExpr.X, isCaller, nil) + nodes := pick(binExpr.X, isCaller) if len(nodes) < 1 { return w } // check if the right sub-expression does not contain a function call - nodes = pick(binExpr.Y, isCaller, nil) + nodes = pick(binExpr.Y, isCaller) if len(nodes) > 0 { return w } diff --git a/tools/vendor/github.com/mgechev/revive/rule/package-comments.go b/tools/vendor/github.com/mgechev/revive/rule/package-comments.go index 02f246be0..f1e5462fe 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/package-comments.go +++ b/tools/vendor/github.com/mgechev/revive/rule/package-comments.go @@ -150,17 +150,9 @@ func (l *lintPackageComments) Visit(_ ast.Node) ast.Visitor { return nil } s := l.fileAst.Doc.Text() - if ts := strings.TrimLeft(s, " \t"); ts != s { - l.onFailure(lint.Failure{ - Category: "comments", - Node: l.fileAst.Doc, - Confidence: 1, - Failure: "package comment should not have leading space", - }) - s = ts - } + // Only non-main packages need to keep to this form. - if !l.file.Pkg.IsMain() && !strings.HasPrefix(s, prefix) { + if !l.file.Pkg.IsMain() && !strings.HasPrefix(s, prefix) && !isDirectiveComment(s) { l.onFailure(lint.Failure{ Category: "comments", Node: l.fileAst.Doc, diff --git a/tools/vendor/github.com/mgechev/revive/rule/range-val-address.go b/tools/vendor/github.com/mgechev/revive/rule/range-val-address.go index 51ad8e108..d2ab0392a 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/range-val-address.go +++ b/tools/vendor/github.com/mgechev/revive/rule/range-val-address.go @@ -16,6 +16,10 @@ type RangeValAddress struct{} func (*RangeValAddress) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure + if file.Pkg.IsAtLeastGo122() { + return failures + } + walker := rangeValAddress{ file: file, onFailure: func(failure lint.Failure) { diff --git a/tools/vendor/github.com/mgechev/revive/rule/range-val-in-closure.go b/tools/vendor/github.com/mgechev/revive/rule/range-val-in-closure.go index 1e85d0d0d..6f9255a74 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/range-val-in-closure.go +++ b/tools/vendor/github.com/mgechev/revive/rule/range-val-in-closure.go @@ -14,6 +14,10 @@ type RangeValInClosureRule struct{} func (*RangeValInClosureRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure + if file.Pkg.IsAtLeastGo122() { + return failures + } + walker := rangeValInClosure{ onFailure: func(failure lint.Failure) { failures = append(failures, failure) diff --git a/tools/vendor/github.com/mgechev/revive/rule/string-format.go b/tools/vendor/github.com/mgechev/revive/rule/string-format.go index 3edd62477..70edf7387 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/string-format.go +++ b/tools/vendor/github.com/mgechev/revive/rule/string-format.go @@ -38,7 +38,7 @@ func (*StringFormatRule) Name() string { // ParseArgumentsTest is a public wrapper around w.parseArguments used for testing. Returns the error message provided to panic, or nil if no error was encountered func (StringFormatRule) ParseArgumentsTest(arguments lint.Arguments) *string { w := lintStringFormatRule{} - c := make(chan interface{}) + c := make(chan any) // Parse the arguments in a goroutine, defer a recover() call, return the error encountered (or nil if there was no error) go func() { defer func() { @@ -101,8 +101,8 @@ func (w *lintStringFormatRule) parseArguments(arguments lint.Arguments) { } } -func (w lintStringFormatRule) parseArgument(argument interface{}, ruleNum int) (scope stringFormatSubruleScope, regex *regexp.Regexp, negated bool, errorMessage string) { - g, ok := argument.([]interface{}) // Cast to generic slice first +func (w lintStringFormatRule) parseArgument(argument any, ruleNum int) (scope stringFormatSubruleScope, regex *regexp.Regexp, negated bool, errorMessage string) { + g, ok := argument.([]any) // Cast to generic slice first if !ok { w.configError("argument is not a slice", ruleNum, 0) } diff --git a/tools/vendor/github.com/mgechev/revive/rule/struct-tag.go b/tools/vendor/github.com/mgechev/revive/rule/struct-tag.go index d1c8056aa..f6ee47a73 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/struct-tag.go +++ b/tools/vendor/github.com/mgechev/revive/rule/struct-tag.go @@ -140,7 +140,7 @@ func (lintStructTagRule) getTagName(tag *structtag.Tag) string { return strings.TrimPrefix(option, "name=") } } - return "" //protobuf tag lacks 'name' option + return "" // protobuf tag lacks 'name' option default: return tag.Name } diff --git a/tools/vendor/github.com/mgechev/revive/rule/superfluous-else.go b/tools/vendor/github.com/mgechev/revive/rule/superfluous-else.go index 1ef67bf1a..2aa1b6b2c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/superfluous-else.go +++ b/tools/vendor/github.com/mgechev/revive/rule/superfluous-else.go @@ -20,7 +20,7 @@ func (*SuperfluousElseRule) Name() string { } // CheckIfElse evaluates the rule against an ifelse.Chain. -func (e *SuperfluousElseRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) { +func (*SuperfluousElseRule) CheckIfElse(chain ifelse.Chain, args ifelse.Args) (failMsg string) { if !chain.If.Deviates() { // this rule only applies if the if-block deviates control flow return diff --git a/tools/vendor/github.com/mgechev/revive/rule/unconditional-recursion.go b/tools/vendor/github.com/mgechev/revive/rule/unconditional-recursion.go index bad907533..9ac2648cd 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unconditional-recursion.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unconditional-recursion.go @@ -45,8 +45,9 @@ type funcStatus struct { } type lintUnconditionalRecursionRule struct { - onFailure func(lint.Failure) - currentFunc *funcStatus + onFailure func(lint.Failure) + currentFunc *funcStatus + inGoStatement bool } // Visit will traverse the file AST. @@ -68,9 +69,13 @@ func (w lintUnconditionalRecursionRule) Visit(node ast.Node) ast.Visitor { default: rec = n.Recv.List[0].Names[0] } - w.currentFunc = &funcStatus{&funcDesc{rec, n.Name}, false} case *ast.CallExpr: + // check if call arguments has a recursive call + for _, arg := range n.Args { + ast.Walk(w, arg) + } + var funcID *ast.Ident var selector *ast.Ident switch c := n.Fun.(type) { @@ -84,6 +89,9 @@ func (w lintUnconditionalRecursionRule) Visit(node ast.Node) ast.Visitor { return nil } funcID = c.Sel + case *ast.FuncLit: + ast.Walk(w, c.Body) // analyze the body of the function literal + return nil default: return w } @@ -93,11 +101,12 @@ func (w lintUnconditionalRecursionRule) Visit(node ast.Node) ast.Visitor { w.currentFunc.funcDesc.equal(&funcDesc{selector, funcID}) { w.onFailure(lint.Failure{ Category: "logic", - Confidence: 1, + Confidence: 0.8, Node: n, Failure: "unconditional recursive call", }) } + return nil case *ast.IfStmt: w.updateFuncStatus(n.Body) w.updateFuncStatus(n.Else) @@ -115,16 +124,21 @@ func (w lintUnconditionalRecursionRule) Visit(node ast.Node) ast.Visitor { w.updateFuncStatus(n.Body) return nil case *ast.GoStmt: - for _, a := range n.Call.Args { - ast.Walk(w, a) // check if arguments have a recursive call - } - return nil // recursive async call is not an issue + w.inGoStatement = true + ast.Walk(w, n.Call) + w.inGoStatement = false + return nil case *ast.ForStmt: if n.Cond != nil { return nil } // unconditional loop return w + case *ast.FuncLit: + if w.inGoStatement { + return w + } + return nil // literal call (closure) is not necessarily an issue } return w @@ -181,5 +195,5 @@ func (lintUnconditionalRecursionRule) hasControlExit(node ast.Node) bool { return false } - return len(pick(node, isExit, nil)) != 0 + return len(pick(node, isExit)) != 0 } diff --git a/tools/vendor/github.com/mgechev/revive/rule/unhandled-error.go b/tools/vendor/github.com/mgechev/revive/rule/unhandled-error.go index 32a5fe48b..ce6fa3864 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unhandled-error.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unhandled-error.go @@ -119,7 +119,7 @@ func (w *lintUnhandledErrors) addFailure(n *ast.CallExpr) { Category: "bad practice", Confidence: 1, Node: n, - Failure: fmt.Sprintf("Unhandled error in call to function %v", gofmt(n.Fun)), + Failure: fmt.Sprintf("Unhandled error in call to function %v", name), }) } diff --git a/tools/vendor/github.com/mgechev/revive/rule/unused-param.go b/tools/vendor/github.com/mgechev/revive/rule/unused-param.go index df6cd9af0..4b04ee916 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unused-param.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unused-param.go @@ -35,7 +35,7 @@ func (r *UnusedParamRule) configure(args lint.Arguments) { r.failureMsg = "parameter '%s' seems to be unused, consider removing or renaming it as _" } else { // Arguments = [{}] - options := args[0].(map[string]interface{}) + options := args[0].(map[string]any) // Arguments = [{allowedRegex="^_"}] if allowedRegexParam, ok := options["allowRegex"]; ok { @@ -87,54 +87,64 @@ type lintUnusedParamRule struct { } func (w lintUnusedParamRule) Visit(node ast.Node) ast.Visitor { + var ( + funcType *ast.FuncType + funcBody *ast.BlockStmt + ) switch n := node.(type) { + case *ast.FuncLit: + funcType = n.Type + funcBody = n.Body case *ast.FuncDecl: - params := retrieveNamedParams(n.Type.Params) - if len(params) < 1 { - return nil // skip, func without parameters - } - if n.Body == nil { return nil // skip, is a function prototype } - // inspect the func body looking for references to parameters - fselect := func(n ast.Node) bool { - ident, isAnID := n.(*ast.Ident) + funcType = n.Type + funcBody = n.Body + default: + return w // skip, not a function + } - if !isAnID { - return false - } + params := retrieveNamedParams(funcType.Params) + if len(params) < 1 { + return w // skip, func without parameters + } - _, isAParam := params[ident.Obj] - if isAParam { - params[ident.Obj] = false // mark as used - } + // inspect the func body looking for references to parameters + fselect := func(n ast.Node) bool { + ident, isAnID := n.(*ast.Ident) + if !isAnID { return false } - _ = pick(n.Body, fselect, nil) - - for _, p := range n.Type.Params.List { - for _, n := range p.Names { - if w.allowRegex.FindStringIndex(n.Name) != nil { - continue - } - if params[n.Obj] { - w.onFailure(lint.Failure{ - Confidence: 1, - Node: n, - Category: "bad practice", - Failure: fmt.Sprintf(w.failureMsg, n.Name), - }) - } - } + + _, isAParam := params[ident.Obj] + if isAParam { + params[ident.Obj] = false // mark as used } - return nil // full method body already inspected + return false + } + _ = pick(funcBody, fselect) + + for _, p := range funcType.Params.List { + for _, n := range p.Names { + if w.allowRegex.FindStringIndex(n.Name) != nil { + continue + } + if params[n.Obj] { + w.onFailure(lint.Failure{ + Confidence: 1, + Node: n, + Category: "bad practice", + Failure: fmt.Sprintf(w.failureMsg, n.Name), + }) + } + } } - return w + return w // full method body was inspected } func retrieveNamedParams(params *ast.FieldList) map[*ast.Object]bool { diff --git a/tools/vendor/github.com/mgechev/revive/rule/unused-receiver.go b/tools/vendor/github.com/mgechev/revive/rule/unused-receiver.go index 488572b7b..715dba338 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unused-receiver.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unused-receiver.go @@ -35,7 +35,7 @@ func (r *UnusedReceiverRule) configure(args lint.Arguments) { r.failureMsg = "method receiver '%s' is not referenced in method's body, consider removing or renaming it as _" } else { // Arguments = [{}] - options := args[0].(map[string]interface{}) + options := args[0].(map[string]any) // Arguments = [{allowedRegex="^_"}] if allowedRegexParam, ok := options["allowRegex"]; ok { @@ -113,7 +113,7 @@ func (w lintUnusedReceiverRule) Visit(node ast.Node) ast.Visitor { return isAnID && ident.Obj == recID.Obj } - refs2recID := pick(n.Body, fselect, nil) + refs2recID := pick(n.Body, fselect) if len(refs2recID) > 0 { return nil // the receiver is referenced in the func body diff --git a/tools/vendor/github.com/mgechev/revive/rule/utils.go b/tools/vendor/github.com/mgechev/revive/rule/utils.go index dca1674ca..1267c2d39 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/utils.go +++ b/tools/vendor/github.com/mgechev/revive/rule/utils.go @@ -93,21 +93,15 @@ func srcLine(src []byte, p token.Position) string { // pick yields a list of nodes by picking them from a sub-ast with root node n. // Nodes are selected by applying the fselect function -// f function is applied to each selected node before inserting it in the final result. -// If f==nil then it defaults to the identity function (ie it returns the node itself) -func pick(n ast.Node, fselect func(n ast.Node) bool, f func(n ast.Node) []ast.Node) []ast.Node { +func pick(n ast.Node, fselect func(n ast.Node) bool) []ast.Node { var result []ast.Node if n == nil { return result } - if f == nil { - f = func(n ast.Node) []ast.Node { return []ast.Node{n} } - } - onSelect := func(n ast.Node) { - result = append(result, f(n)...) + result = append(result, n) } p := picker{fselect: fselect, onSelect: onSelect} ast.Walk(p, n) @@ -158,7 +152,7 @@ func isExprABooleanLit(n ast.Node) (lexeme string, ok bool) { } // gofmt returns a string representation of an AST subtree. -func gofmt(x interface{}) string { +func gofmt(x any) string { buf := bytes.Buffer{} fs := token.NewFileSet() printer.Fprint(&buf, fs, x) @@ -171,3 +165,9 @@ func checkNumberOfArguments(expected int, args lint.Arguments, ruleName string) panic(fmt.Sprintf("not enough arguments for %s rule, expected %d, got %d. Please check the rule's documentation", ruleName, expected, len(args))) } } + +var directiveCommentRE = regexp.MustCompile("^//(line |extern |export |[a-z0-9]+:[a-z0-9])") // see https://go-review.googlesource.com/c/website/+/442516/1..2/_content/doc/comment.md#494 + +func isDirectiveComment(line string) bool { + return directiveCommentRE.MatchString(line) +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/var-naming.go b/tools/vendor/github.com/mgechev/revive/rule/var-naming.go index 286ff9d75..e91c22dc2 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/var-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/var-naming.go @@ -18,10 +18,11 @@ var upperCaseConstRE = regexp.MustCompile(`^_?[A-Z][A-Z\d]*(_[A-Z\d]+)*$`) // VarNamingRule lints given else constructs. type VarNamingRule struct { - configured bool - whitelist []string - blacklist []string - upperCaseConst bool // if true - allows to use UPPER_SOME_NAMES for constants + configured bool + allowlist []string + blocklist []string + upperCaseConst bool // if true - allows to use UPPER_SOME_NAMES for constants + skipPackageNameChecks bool sync.Mutex } @@ -34,31 +35,53 @@ func (r *VarNamingRule) configure(arguments lint.Arguments) { r.configured = true if len(arguments) >= 1 { - r.whitelist = getList(arguments[0], "whitelist") + r.allowlist = getList(arguments[0], "allowlist") } if len(arguments) >= 2 { - r.blacklist = getList(arguments[1], "blacklist") + r.blocklist = getList(arguments[1], "blocklist") } if len(arguments) >= 3 { // not pretty code because should keep compatibility with TOML (no mixed array types) and new map parameters thirdArgument := arguments[2] - asSlice, ok := thirdArgument.([]interface{}) + asSlice, ok := thirdArgument.([]any) if !ok { panic(fmt.Sprintf("Invalid third argument to the var-naming rule. Expecting a %s of type slice, got %T", "options", arguments[2])) } if len(asSlice) != 1 { panic(fmt.Sprintf("Invalid third argument to the var-naming rule. Expecting a %s of type slice, of len==1, but %d", "options", len(asSlice))) } - args, ok := asSlice[0].(map[string]interface{}) + args, ok := asSlice[0].(map[string]any) if !ok { panic(fmt.Sprintf("Invalid third argument to the var-naming rule. Expecting a %s of type slice, of len==1, with map, but %T", "options", asSlice[0])) } r.upperCaseConst = fmt.Sprint(args["upperCaseConst"]) == "true" + r.skipPackageNameChecks = fmt.Sprint(args["skipPackageNameChecks"]) == "true" } } +func (r *VarNamingRule) applyPackageCheckRules(walker *lintNames) { + // Package names need slightly different handling than other names. + if strings.Contains(walker.fileAst.Name.Name, "_") && !strings.HasSuffix(walker.fileAst.Name.Name, "_test") { + walker.onFailure(lint.Failure{ + Failure: "don't use an underscore in package name", + Confidence: 1, + Node: walker.fileAst.Name, + Category: "naming", + }) + } + if anyCapsRE.MatchString(walker.fileAst.Name.Name) { + walker.onFailure(lint.Failure{ + Failure: fmt.Sprintf("don't use MixedCaps in package name; %s should be %s", walker.fileAst.Name.Name, strings.ToLower(walker.fileAst.Name.Name)), + Confidence: 1, + Node: walker.fileAst.Name, + Category: "naming", + }) + } + +} + // Apply applies the rule to given file. func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { r.configure(arguments) @@ -70,30 +93,16 @@ func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint. walker := lintNames{ file: file, fileAst: fileAst, - whitelist: r.whitelist, - blacklist: r.blacklist, + allowlist: r.allowlist, + blocklist: r.blocklist, onFailure: func(failure lint.Failure) { failures = append(failures, failure) }, upperCaseConst: r.upperCaseConst, } - // Package names need slightly different handling than other names. - if strings.Contains(walker.fileAst.Name.Name, "_") && !strings.HasSuffix(walker.fileAst.Name.Name, "_test") { - walker.onFailure(lint.Failure{ - Failure: "don't use an underscore in package name", - Confidence: 1, - Node: walker.fileAst.Name, - Category: "naming", - }) - } - if anyCapsRE.MatchString(walker.fileAst.Name.Name) { - walker.onFailure(lint.Failure{ - Failure: fmt.Sprintf("don't use MixedCaps in package name; %s should be %s", walker.fileAst.Name.Name, strings.ToLower(walker.fileAst.Name.Name)), - Confidence: 1, - Node: walker.fileAst.Name, - Category: "naming", - }) + if !r.skipPackageNameChecks { + r.applyPackageCheckRules(&walker) } ast.Walk(&walker, fileAst) @@ -127,7 +136,7 @@ func (w *lintNames) check(id *ast.Ident, thing string) { // #851 upperCaseConst support // if it's const - if thing == token.CONST.String() && w.upperCaseConst && upperCaseConstRE.Match([]byte(id.Name)) { + if thing == token.CONST.String() && w.upperCaseConst && upperCaseConstRE.MatchString(id.Name) { return } @@ -142,7 +151,7 @@ func (w *lintNames) check(id *ast.Ident, thing string) { return } - should := lint.Name(id.Name, w.whitelist, w.blacklist) + should := lint.Name(id.Name, w.allowlist, w.blocklist) if id.Name == should { return } @@ -168,8 +177,8 @@ type lintNames struct { file *lint.File fileAst *ast.File onFailure func(lint.Failure) - whitelist []string - blacklist []string + allowlist []string + blocklist []string upperCaseConst bool } @@ -255,8 +264,8 @@ func (w *lintNames) Visit(n ast.Node) ast.Visitor { return w } -func getList(arg interface{}, argName string) []string { - temp, ok := arg.([]interface{}) +func getList(arg any, argName string) []string { + temp, ok := arg.([]any) if !ok { panic(fmt.Sprintf("Invalid argument to the var-naming rule. Expecting a %s of type slice with initialisms, got %T", argName, arg)) } diff --git a/tools/vendor/github.com/moricho/tparallel/.goreleaser.yaml b/tools/vendor/github.com/moricho/tparallel/.goreleaser.yaml index 4a04fe25b..5349004c5 100644 --- a/tools/vendor/github.com/moricho/tparallel/.goreleaser.yaml +++ b/tools/vendor/github.com/moricho/tparallel/.goreleaser.yaml @@ -1,7 +1,9 @@ project_name: tparallel + before: hooks: - go mod tidy + builds: - main: ./cmd/tparallel binary: tparallel @@ -19,15 +21,17 @@ builds: archives: - format: tar.gz name_template: >- - {{ .ProjectName }}_ + {{- .ProjectName }}_ {{- title .Os }}_ {{- if eq .Arch "amd64" }}x86_64 {{- else if eq .Arch "386" }}i386 {{- else }}{{ .Arch }}{{ end }} - {{- if .Arm }}v{{ .Arm }}{{ end }} + {{- if .Arm }}v{{ .Arm }}{{ end -}} + format_overrides: - - goos: windows - format: zip + - goos: windows + format: zip + checksum: name_template: 'checksums.txt' snapshot: @@ -38,10 +42,12 @@ changelog: exclude: - '^docs:' - '^test:' + release: prerelease: auto + brews: - - tap: + - repository: owner: moricho name: homebrew-tparallel homepage: https://github.com/moricho/tparallel @@ -49,4 +55,4 @@ brews: install: | bin.install "tparallel" test: | - system "#{bin}/goreleaser -v" + system "#{bin}/tparallel help" diff --git a/tools/vendor/github.com/moricho/tparallel/README.md b/tools/vendor/github.com/moricho/tparallel/README.md index 65ed46c42..c4f1efd01 100644 --- a/tools/vendor/github.com/moricho/tparallel/README.md +++ b/tools/vendor/github.com/moricho/tparallel/README.md @@ -10,7 +10,7 @@ It detects the following: - `t.Parallel()` is called in either a top-level test function or a sub-test function only - Although `t.Parallel()` is called in the sub-test function, it is post-processed by `defer` instead of `t.Cleanup()` -This tool was inspired by this blog: [Go 言語でのテストの並列化 〜t.Parallel()メソッドを理解する〜](https://engineering.mercari.com/blog/entry/how_to_use_t_parallel/) +This tool was inspired by this blog: [Test parallelization in Go: Understanding the t.Parallel() method](https://engineering.mercari.com/en/blog/entry/20220408-how_to_use_t_parallel/) ## Installation diff --git a/tools/vendor/github.com/moricho/tparallel/testmap.go b/tools/vendor/github.com/moricho/tparallel/testmap.go index fa9bed708..fd6a3b432 100644 --- a/tools/vendor/github.com/moricho/tparallel/testmap.go +++ b/tools/vendor/github.com/moricho/tparallel/testmap.go @@ -49,6 +49,10 @@ func appendTestMap(subtests []*ssa.Function, instr ssa.Instruction) []*ssa.Funct } ssaCall := call.Value() + if ssaCall == nil { + return subtests + } + for _, arg := range ssaCall.Call.Args { switch arg := arg.(type) { case *ssa.Function: diff --git a/tools/vendor/github.com/nishanths/exhaustive/comment.go b/tools/vendor/github.com/nishanths/exhaustive/comment.go index cc84beaf7..123e0181b 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/comment.go +++ b/tools/vendor/github.com/nishanths/exhaustive/comment.go @@ -3,45 +3,14 @@ package exhaustive import ( "go/ast" "go/token" - "regexp" "strings" ) -// For definition of generated file see: -// http://golang.org/s/generatedcode - -var generatedCodeRe = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`) - -func isGeneratedFile(file *ast.File) bool { - // NOTE: file.Comments includes file.Doc as well, so no need - // to separately check file.Doc. - for _, c := range file.Comments { - for _, cc := range c.List { - // This check handles the "must appear before the first - // non-comment, non-blank text in the file" requirement. - // - // According to https://golang.org/ref/spec#Source_file_organization - // the package clause is the first element in a file, which - // should make it the first non-comment, non-blank text. - if c.Pos() >= file.Package { - return false - } - // According to the docs: - // '\r' has been removed. - // '\n' has been removed for //-style comments - // This has also been manually verified. - if generatedCodeRe.MatchString(cc.Text) { - return true - } - } - } - - return false -} - const ( - ignoreComment = "//exhaustive:ignore" - enforceComment = "//exhaustive:enforce" + ignoreComment = "//exhaustive:ignore" + enforceComment = "//exhaustive:enforce" + ignoreDefaultCaseRequiredComment = "//exhaustive:ignore-default-case-required" + enforceDefaultCaseRequiredComment = "//exhaustive:enforce-default-case-required" ) func hasCommentPrefix(comments []*ast.CommentGroup, comment string) bool { diff --git a/tools/vendor/github.com/nishanths/exhaustive/comment_go121.go b/tools/vendor/github.com/nishanths/exhaustive/comment_go121.go new file mode 100644 index 000000000..a7bbc8881 --- /dev/null +++ b/tools/vendor/github.com/nishanths/exhaustive/comment_go121.go @@ -0,0 +1,11 @@ +//go:build go1.21 + +package exhaustive + +import ( + "go/ast" +) + +func isGeneratedFile(file *ast.File) bool { + return ast.IsGenerated(file) +} diff --git a/tools/vendor/github.com/nishanths/exhaustive/comment_pre_go121.go b/tools/vendor/github.com/nishanths/exhaustive/comment_pre_go121.go new file mode 100644 index 000000000..28d2ed493 --- /dev/null +++ b/tools/vendor/github.com/nishanths/exhaustive/comment_pre_go121.go @@ -0,0 +1,27 @@ +//go:build !go1.21 + +package exhaustive + +import ( + "go/ast" + "regexp" +) + +// For definition of generated file see: +// http://golang.org/s/generatedcode + +var generatedCodeRe = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`) + +func isGeneratedFile(file *ast.File) bool { + for _, c := range file.Comments { + for _, cc := range c.List { + if cc.Pos() > file.Package { + break + } + if generatedCodeRe.MatchString(cc.Text) { + return true + } + } + } + return false +} diff --git a/tools/vendor/github.com/nishanths/exhaustive/doc.go b/tools/vendor/github.com/nishanths/exhaustive/doc.go index 8435e5d24..a745247db 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/doc.go +++ b/tools/vendor/github.com/nishanths/exhaustive/doc.go @@ -10,8 +10,8 @@ The Go [language spec] does not have an explicit definition for enums. For the purpose of this analyzer, and by convention, an enum type is any named type that: - - has underlying type float, string, or integer (includes byte and rune); - and + - has an [underlying type] of float, string, or integer (includes byte + and rune); and - has at least one constant of its type defined in the same [block]. In the example below, Biome is an enum type. The three constants are its @@ -209,6 +209,7 @@ To ignore specific types, specify the -ignore-enum-types flag: exhaustive -ignore-enum-types '^time\.Duration$|^example\.org/measure\.Unit$' [language spec]: https://golang.org/ref/spec +[underlying type]: https://golang.org/ref/spec#Underlying_types [block]: https://golang.org/ref/spec#Blocks [BasicKind]: https://pkg.go.dev/go/types#BasicKind */ diff --git a/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go b/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go index d67a60c32..013ac47bb 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go +++ b/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go @@ -19,6 +19,7 @@ func registerFlags() { Analyzer.Flags.BoolVar(&fExplicitExhaustiveMap, ExplicitExhaustiveMapFlag, false, `check map literal only if associated with "//exhaustive:enforce" comment`) Analyzer.Flags.BoolVar(&fCheckGenerated, CheckGeneratedFlag, false, "check generated files") Analyzer.Flags.BoolVar(&fDefaultSignifiesExhaustive, DefaultSignifiesExhaustiveFlag, false, "switch statement is unconditionally exhaustive if it has a default case") + Analyzer.Flags.BoolVar(&fDefaultCaseRequired, DefaultCaseRequiredFlag, false, "switch statement requires default case even if exhaustive") Analyzer.Flags.Var(&fIgnoreEnumMembers, IgnoreEnumMembersFlag, "ignore constants matching `regexp`") Analyzer.Flags.Var(&fIgnoreEnumTypes, IgnoreEnumTypesFlag, "ignore types matching `regexp`") Analyzer.Flags.BoolVar(&fPackageScopeOnly, PackageScopeOnlyFlag, false, "only discover enums declared in file-level blocks") @@ -36,6 +37,7 @@ const ( ExplicitExhaustiveMapFlag = "explicit-exhaustive-map" CheckGeneratedFlag = "check-generated" DefaultSignifiesExhaustiveFlag = "default-signifies-exhaustive" + DefaultCaseRequiredFlag = "default-case-required" IgnoreEnumMembersFlag = "ignore-enum-members" IgnoreEnumTypesFlag = "ignore-enum-types" PackageScopeOnlyFlag = "package-scope-only" @@ -52,6 +54,7 @@ var ( fExplicitExhaustiveMap bool fCheckGenerated bool fDefaultSignifiesExhaustive bool + fDefaultCaseRequired bool fIgnoreEnumMembers regexpFlag fIgnoreEnumTypes regexpFlag fPackageScopeOnly bool @@ -65,6 +68,7 @@ func resetFlags() { fExplicitExhaustiveMap = false fCheckGenerated = false fDefaultSignifiesExhaustive = false + fDefaultCaseRequired = false fIgnoreEnumMembers = regexpFlag{} fIgnoreEnumTypes = regexpFlag{} fPackageScopeOnly = false @@ -121,6 +125,7 @@ func run(pass *analysis.Pass) (interface{}, error) { conf := switchConfig{ explicit: fExplicitExhaustiveSwitch, defaultSignifiesExhaustive: fDefaultSignifiesExhaustive, + defaultCaseRequired: fDefaultCaseRequired, checkGenerated: fCheckGenerated, ignoreConstant: fIgnoreEnumMembers.re, ignoreType: fIgnoreEnumTypes.re, diff --git a/tools/vendor/github.com/nishanths/exhaustive/switch.go b/tools/vendor/github.com/nishanths/exhaustive/switch.go index 000ef9886..d235fbec4 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/switch.go +++ b/tools/vendor/github.com/nishanths/exhaustive/switch.go @@ -5,6 +5,7 @@ import ( "go/ast" "go/types" "regexp" + "strings" "golang.org/x/tools/go/analysis" ) @@ -44,6 +45,7 @@ const ( resultNoEnforceComment = "has no enforce comment" resultEnumMembersAccounted = "required enum members accounted for" resultDefaultCaseSuffices = "default case satisfies exhaustiveness" + resultMissingDefaultCase = "missing required default case" resultReportedDiagnostic = "reported diagnostic" resultEnumTypes = "invalid or empty composing enum types" ) @@ -52,11 +54,47 @@ const ( type switchConfig struct { explicit bool defaultSignifiesExhaustive bool + defaultCaseRequired bool checkGenerated bool ignoreConstant *regexp.Regexp // can be nil ignoreType *regexp.Regexp // can be nil } +// There are few possibilities, and often none, so we use a possibly-nil slice +func userDirectives(comments []*ast.CommentGroup) []string { + var directives []string + for _, c := range comments { + for _, cc := range c.List { + // The order matters here: we always want to check the longest first. + for _, d := range []string{ + enforceDefaultCaseRequiredComment, + ignoreDefaultCaseRequiredComment, + enforceComment, + ignoreComment, + } { + if strings.HasPrefix(cc.Text, d) { + directives = append(directives, d) + // The break here is important: once we associate a comment + // with a particular (longest-possible) directive, we don't want + // to map to another! + break + } + } + } + } + return directives +} + +// Can be replaced with slices.Contains with go1.21 +func directivesIncludes(directives []string, d string) bool { + for _, ud := range directives { + if ud == d { + return true + } + } + return false +} + // switchChecker returns a node visitor that checks exhaustiveness of // enum switch statements for the supplied pass, and reports // diagnostics. The node visitor expects only *ast.SwitchStmt nodes. @@ -80,17 +118,27 @@ func switchChecker(pass *analysis.Pass, cfg switchConfig, generated boolCache, c sw := n.(*ast.SwitchStmt) switchComments := comments.get(pass.Fset, file)[sw] - if !cfg.explicit && hasCommentPrefix(switchComments, ignoreComment) { + uDirectives := userDirectives(switchComments) + if !cfg.explicit && directivesIncludes(uDirectives, ignoreComment) { // Skip checking of this switch statement due to ignore // comment. Still return true because there may be nested // switch statements that are not to be ignored. return true, resultIgnoreComment } - if cfg.explicit && !hasCommentPrefix(switchComments, enforceComment) { + if cfg.explicit && !directivesIncludes(uDirectives, enforceComment) { // Skip checking of this switch statement due to missing // enforce comment. return true, resultNoEnforceComment } + requireDefaultCase := cfg.defaultCaseRequired + if directivesIncludes(uDirectives, ignoreDefaultCaseRequiredComment) { + requireDefaultCase = false + } + if directivesIncludes(uDirectives, enforceDefaultCaseRequiredComment) { + // We have "if" instead of "else if" here in case of conflicting ignore/enforce directives. + // In that case, because this is second, we will default to enforcing. + requireDefaultCase = true + } if sw.Tag == nil { return true, resultNoSwitchTag // never possible for valid Go program? @@ -114,13 +162,21 @@ func switchChecker(pass *analysis.Pass, cfg switchConfig, generated boolCache, c checkl.add(e.typ, e.members, pass.Pkg == e.typ.Pkg()) } - def := analyzeSwitchClauses(sw, pass.TypesInfo, checkl.found) + defaultCaseExists := analyzeSwitchClauses(sw, pass.TypesInfo, checkl.found) + if !defaultCaseExists && requireDefaultCase { + // Even if the switch explicitly enumerates all the + // enum values, the user has still required all switches + // to have a default case. We check this first to avoid + // early-outs + pass.Report(makeMissingDefaultDiagnostic(sw, dedupEnumTypes(toEnumTypes(es)))) + return true, resultMissingDefaultCase + } if len(checkl.remaining()) == 0 { // All enum members accounted for. // Nothing to report. return true, resultEnumMembersAccounted } - if def && cfg.defaultSignifiesExhaustive { + if defaultCaseExists && cfg.defaultSignifiesExhaustive { // Though enum members are not accounted for, the // existence of the default case signifies // exhaustiveness. So don't report. @@ -167,3 +223,14 @@ func makeSwitchDiagnostic(sw *ast.SwitchStmt, enumTypes []enumType, missing map[ ), } } + +func makeMissingDefaultDiagnostic(sw *ast.SwitchStmt, enumTypes []enumType) analysis.Diagnostic { + return analysis.Diagnostic{ + Pos: sw.Pos(), + End: sw.End(), + Message: fmt.Sprintf( + "missing default case in switch of type %s", + diagnosticEnumTypes(enumTypes), + ), + } +} diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/Makefile b/tools/vendor/github.com/nunnatsa/ginkgolinter/Makefile index e8efae583..586633006 100644 --- a/tools/vendor/github.com/nunnatsa/ginkgolinter/Makefile +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/Makefile @@ -5,9 +5,12 @@ HASH_FLAG := -X github.com/nunnatsa/ginkgolinter/version.gitHash=$(COMMIT_HASH) BUILD_ARGS := -ldflags "$(VERSION_FLAG) $(HASH_FLAG)" -build: +build: unit-test go build $(BUILD_ARGS) -o ginkgolinter ./cmd/ginkgolinter +unit-test: + go test ./... + build-for-windows: GOOS=windows GOARCH=amd64 go build $(BUILD_ARGS) -o bin/ginkgolinter-amd64.exe ./cmd/ginkgolinter diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/README.md b/tools/vendor/github.com/nunnatsa/ginkgolinter/README.md index 6c95917d2..977cec903 100644 --- a/tools/vendor/github.com/nunnatsa/ginkgolinter/README.md +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/README.md @@ -44,7 +44,7 @@ It is not enabled by default, though. There are two ways to run ginkgolinter wit enable: - ginkgolinter ``` -## Linter Checks +## Linter Rules The linter checks the ginkgo and gomega assertions in golang test code. Gomega may be used together with ginkgo tests, For example: ```go @@ -177,7 +177,8 @@ var _ = Describe("checking something", Focus, func() { }) ``` -These container, or the `Focus` spec, must not be part of the final source code, and should only be used locally by the developer. +These container, or the `Focus` spec, must not be part of the final source code, and should only be used locally by the +developer. ***This rule is disabled by default***. Use the `--forbid-focus-container=true` command line flag to enable it. @@ -205,8 +206,78 @@ To suppress this warning entirely, use the `--suppress-type-compare-assertion=tr To suppress a specific file or line, use the `// ginkgo-linter:ignore-type-compare-warning` comment (see [below](#suppress-warning-from-the-code)) +### Wrong Usage of the `MatchError` gomega Matcher [BUG] +The `MatchError` gomega matcher asserts an error value (and if it's not nil). +There are four valid formats for using this Matcher: +* error value; e.g. `Expect(err).To(MatchError(anotherErr))` +* string, to be equal to the output of the `Error()` method; e.g. `Expect(err).To(MatchError("Not Found"))` +* A gomega matcher that asserts strings; e.g. `Expect(err).To(MatchError(ContainSubstring("Found")))` +* [from v0.29.0] a function that receive a single error parameter and returns a single boolean value. + In this format, an additional single string parameter, with the function description, is also required; e.g. + `Expect(err).To(MatchError(isNotFound, "is the error is a not found error"))` + +These four format are checked on runtime, but sometimes it's too late. ginkgolinter performs a static analysis and so it +will find these issues on build time. + +ginkgolinter checks the following: +* Is the first parameter is one of the four options above. +* That there are no additional parameters passed to the matcher; e.g. + `MatchError(isNotFoundFunc, "a valid description" , "not used string")`. In this case, the matcher won't fail on run + time, but the additional parameters are not in use and ignored. +* If the first parameter is a function with the format of `func(error)bool`, ginkgolinter makes sure that the second + parameter exists and its type is string. + +### Async timing interval: timeout is shorter than polling interval [BUG] +***Note***: Only applied when the `suppress-async-assertion` flag is **not set** *and* the `validate-async-intervals` +flag **is** set. + +***Note***: This rule work with best-effort approach. It can't find many cases, like const defined not in the same +package, or when using variables. + +The timeout and polling intervals may be passed as optional arguments to the `Eventually` or `Constanly` functions, or +using the `WithTimeout` or , `Within` methods (timeout), and `WithPolling` or `ProbeEvery` methods (polling). + +This rule checks if the async (`Eventually` or `Consistently`) timeout duration, is not shorter than the polling interval. + +For example: + ```go + Eventually(aFunc).WithTimeout(500 * time.Millisecond).WithPolling(10 * time.Second).Should(Succeed()) + ``` + +This will probably happen when using the old format: + ```go + Eventually(aFunc, 500 * time.Millisecond /*timeout*/, 10 * time.Second /*polling*/).Should(Succeed()) + ``` + +### Avoid Spec Pollution: Don't Initialize Variables in Container Nodes [BUG/STYLE]: +***Note***: Only applied when the `--forbid-spec-pollution=true` flag is set (disabled by default). + +According to [ginkgo documentation](https://onsi.github.io/ginkgo/#avoid-spec-pollution-dont-initialize-variables-in-container-nodes), +no variable should be assigned within a container node (`Describe`, `Context`, `When` or their `F`, `P` or `X` forms) + +For example: +```go +var _ = Describe("description", func(){ + var x = 10 + ... +}) +``` + +Instead, use `BeforeEach()`; e.g. +```go +var _ = Describe("description", func (){ + var x int + + BeforeEach(func (){ + x = 10 + }) + ... +}) +``` + ### Wrong Length Assertion [STYLE] -The linter finds assertion of the golang built-in `len` function, with all kind of matchers, while there are already gomega matchers for these usecases; We want to assert the item, rather than its length. +The linter finds assertion of the golang built-in `len` function, with all kind of matchers, while there are already +gomega matchers for these usecases; We want to assert the item, rather than its length. There are several wrong patterns: ```go @@ -236,11 +307,26 @@ The output of the linter,when finding issues, looks like this: ./testdata/src/a/a.go:18:5: ginkgo-linter: wrong length assertion; consider using `Expect("").Should(BeEmpty())` instead ./testdata/src/a/a.go:22:5: ginkgo-linter: wrong length assertion; consider using `Expect("").Should(BeEmpty())` instead ``` + +### Wrong Cap Assertion [STYLE] +The linter finds assertion of the golang built-in `cap` function, with all kind of matchers, while there are already +gomega matchers for these usecases; We want to assert the item, rather than its cap. + +There are several wrong patterns: +```go +Expect(cap(x)).To(Equal(0)) // should be: Expect(x).To(HaveCap(0)) +Expect(cap(x)).To(BeZero()) // should be: Expect(x).To(HaveCap(0)) +Expect(cap(x)).To(BeNumeric(">", 0)) // should be: Expect(x).ToNot(HaveCap(0)) +Expect(cap(x)).To(BeNumeric("==", 2)) // should be: Expect(x).To(HaveCap(2)) +Expect(cap(x)).To(BeNumeric("!=", 3)) // should be: Expect(x).ToNot(HaveCap(3)) +``` + #### use the `HaveLen(0)` matcher. [STYLE] The linter will also warn about the `HaveLen(0)` matcher, and will suggest to replace it with `BeEmpty()` ### Wrong `nil` Assertion [STYLE] -The linter finds assertion of the comparison to nil, with all kind of matchers, instead of using the existing `BeNil()` matcher; We want to assert the item, rather than a comparison result. +The linter finds assertion of the comparison to nil, with all kind of matchers, instead of using the existing `BeNil()` +matcher; We want to assert the item, rather than a comparison result. There are several wrong patterns: @@ -332,9 +418,67 @@ Expect(x1 == c1).Should(BeTrue()) // ==> Expect(x1).Should(Equal(c1)) Expect(c1 == x1).Should(BeTrue()) // ==> Expect(x1).Should(Equal(c1)) ``` +### Don't Allow Using `Expect` with `Should` or `ShouldNot` [STYLE] +This optional rule forces the usage of the `Expect` method only with the `To`, `ToNot` or `NotTo` +assertion methods; e.g. +```go +Expect("abc").Should(HaveLen(3)) // => Expect("abc").To(HaveLen(3)) +Expect("abc").ShouldNot(BeEmpty()) // => Expect("abc").ToNot(BeEmpty()) +``` +This rule support auto fixing. + +***This rule is disabled by default***. Use the `--force-expect-to=true` command line flag to enable it. + +### Async timing interval: multiple timeout or polling intervals [STYLE] +***Note***: Only applied when the `suppress-async-assertion` flag is **not set** *and* the `validate-async-intervals` +flag **is** set. + +The timeout and polling intervals may be passed as optional arguments to the `Eventually` or `Constanly` functions, or +using the `WithTimeout` or , `Within` methods (timeout), and `WithPolling` or `ProbeEvery` methods (polling). + +The linter checks that there is up to one polling argument and up to one timeout argument. + +For example: + +```go +// both WithTimeout() and Within() +Eventually(aFunc).WithTimeout(time.Second * 10).Within(time.Second * 10).WithPolling(time.Millisecond * 500).Should(BeTrue()) +// both polling argument, and WithPolling() method +Eventually(aFunc, time.Second*10, time.Millisecond * 500).WithPolling(time.Millisecond * 500).Should(BeTrue()) +``` + +### Async timing interval: non-time.Duration intervals [STYLE] +***Note***: Only applied when the `suppress-async-assertion` flag is **not set** *and* the `validate-async-intervals` +flag **is** set. + +gomega supports a few formats for timeout and polling intervals, when using the old format (the last two parameters of Eventually and Constantly): +* a `time.Duration` value +* any kind of numeric value (int(8/16/32/64), uint(8/16/32/64) or float(32/64), as the number of seconds. +* duration string like `"12s"` + +The linter triggers a warning for any duration value that is not of the `time.Duration` type, assuming that this is +the desired type, given the type of the argument of the newer "WithTimeout", "WithPolling", "Within" and "ProbeEvery" +methods. + +For example: + ```go + Eventually(func() bool { return true }, "1s").Should(BeTrue()) + Eventually(context.Background(), func() bool { return true }, time.Second*60, float64(2)).Should(BeTrue()) + ``` + +This rule offers a limited auto fix: for integer values, or integer consts, the linter will suggest multiply the +value with `time.Second`; e.g. +```go +const polling = 1 +Eventually(aFunc, 5, polling) +``` +will be changed to: +```go +Eventually(aFunc, time.Second*5, time.Second*polling) +``` ## Suppress the linter ### Suppress warning from command line -* Use the `--suppress-len-assertion=true` flag to suppress the wrong length assertion warning +* Use the `--suppress-len-assertion=true` flag to suppress the wrong length and cap assertions warning * Use the `--suppress-nil-assertion=true` flag to suppress the wrong nil assertion warning * Use the `--suppress-err-assertion=true` flag to suppress the wrong error assertion warning * Use the `--suppress-compare-assertion=true` flag to suppress the wrong comparison assertion warning @@ -345,7 +489,7 @@ Expect(c1 == x1).Should(BeTrue()) // ==> Expect(x1).Should(Equal(c1)) command line, and not from a comment. ### Suppress warning from the code -To suppress the wrong length assertion warning, add a comment with (only) +To suppress the wrong length and cap assertions warning, add a comment with (only) `ginkgo-linter:ignore-len-assert-warning`. diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/analyzer.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/analyzer.go new file mode 100644 index 000000000..edff57acd --- /dev/null +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/analyzer.go @@ -0,0 +1,58 @@ +package ginkgolinter + +import ( + "flag" + "fmt" + + "golang.org/x/tools/go/analysis" + + "github.com/nunnatsa/ginkgolinter/linter" + "github.com/nunnatsa/ginkgolinter/types" + "github.com/nunnatsa/ginkgolinter/version" +) + +// NewAnalyzerWithConfig returns an Analyzer. +func NewAnalyzerWithConfig(config *types.Config) *analysis.Analyzer { + theLinter := linter.NewGinkgoLinter(config) + + return &analysis.Analyzer{ + Name: "ginkgolinter", + Doc: fmt.Sprintf(doc, version.Version()), + Run: theLinter.Run, + } +} + +// NewAnalyzer returns an Analyzer - the package interface with nogo +func NewAnalyzer() *analysis.Analyzer { + config := &types.Config{ + SuppressLen: false, + SuppressNil: false, + SuppressErr: false, + SuppressCompare: false, + ForbidFocus: false, + AllowHaveLen0: false, + ForceExpectTo: false, + } + + a := NewAnalyzerWithConfig(config) + + var ignored bool + a.Flags.Init("ginkgolinter", flag.ExitOnError) + a.Flags.Var(&config.SuppressLen, "suppress-len-assertion", "Suppress warning for wrong length assertions") + a.Flags.Var(&config.SuppressNil, "suppress-nil-assertion", "Suppress warning for wrong nil assertions") + a.Flags.Var(&config.SuppressErr, "suppress-err-assertion", "Suppress warning for wrong error assertions") + a.Flags.Var(&config.SuppressCompare, "suppress-compare-assertion", "Suppress warning for wrong comparison assertions") + a.Flags.Var(&config.SuppressAsync, "suppress-async-assertion", "Suppress warning for function call in async assertion, like Eventually") + a.Flags.Var(&config.ValidateAsyncIntervals, "validate-async-intervals", "best effort validation of async intervals (timeout and polling); ignored the suppress-async-assertion flag is true") + a.Flags.Var(&config.SuppressTypeCompare, "suppress-type-compare-assertion", "Suppress warning for comparing values from different types, like int32 and uint32") + a.Flags.Var(&config.AllowHaveLen0, "allow-havelen-0", "Do not warn for HaveLen(0); default = false") + a.Flags.Var(&config.ForceExpectTo, "force-expect-to", "force using `Expect` with `To`, `ToNot` or `NotTo`. reject using `Expect` with `Should` or `ShouldNot`; default = false (not forced)") + a.Flags.BoolVar(&ignored, "suppress-focus-container", true, "Suppress warning for ginkgo focus containers like FDescribe, FContext, FWhen or FIt. Deprecated and ignored: use --forbid-focus-container instead") + a.Flags.Var(&config.ForbidFocus, "forbid-focus-container", "trigger a warning for ginkgo focus containers like FDescribe, FContext, FWhen or FIt; default = false.") + a.Flags.Var(&config.ForbidSpecPollution, "forbid-spec-pollution", "trigger a warning for variable assignments in ginkgo containers like Describe, Context and When, instead of in BeforeEach(); default = false.") + + return a +} + +// Analyzer is the interface to go_vet +var Analyzer = NewAnalyzer() diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/doc.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/doc.go new file mode 100644 index 000000000..dd9ecf58a --- /dev/null +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/doc.go @@ -0,0 +1,99 @@ +package ginkgolinter + +const doc = `enforces standards of using ginkgo and gomega + +or + ginkgolinter version + +version: %s + +currently, the linter searches for following: +* trigger a warning when using Eventually or Consistently with a function call. This is in order to prevent the case when + using a function call instead of a function. Function call returns a value only once, and so the original value + is tested again and again and is never changed. [Bug] + +* trigger a warning when comparing a pointer to a value. [Bug] + +* trigger a warning for missing assertion method: [Bug] + Eventually(checkSomething) + +* trigger a warning when a ginkgo focus container (FDescribe, FContext, FWhen or FIt) is found. [Bug] + +* validate the MatchError gomega matcher [Bug] + +* trigger a warning when using the Equal or the BeIdentical matcher with two different types, as these matchers will + fail in runtime. + +* async timing interval: timeout is shorter than polling interval [Bug] +For example: + Eventually(aFunc).WithTimeout(500 * time.Millisecond).WithPolling(10 * time.Second).Should(Succeed()) +This will probably happen when using the old format: + Eventually(aFunc, 500 * time.Millisecond, 10 * time.Second).Should(Succeed()) + +* reject variable assignments in ginkgo containers [Bug/Style]: +For example: + var _ = Describe("description", func(){ + var x = 10 + }) + +Should use BeforeEach instead; e.g. + var _ = Describe("description", func(){ + var x int + BeforeEach(func(){ + x = 10 + }) + }) + +* wrong length assertions. We want to assert the item rather than its length. [Style] +For example: + Expect(len(x)).Should(Equal(1)) +This should be replaced with: + Expect(x)).Should(HavelLen(1)) + +* wrong cap assertions. We want to assert the item rather than its cap. [Style] +For example: + Expect(cap(x)).Should(Equal(1)) +This should be replaced with: + Expect(x)).Should(HavelCap(1)) + +* wrong nil assertions. We want to assert the item rather than a comparison result. [Style] +For example: + Expect(x == nil).Should(BeTrue()) +This should be replaced with: + Expect(x).Should(BeNil()) + +* wrong error assertions. For example: [Style] + Expect(err == nil).Should(BeTrue()) +This should be replaced with: + Expect(err).ShouldNot(HaveOccurred()) + +* wrong boolean comparison, for example: [Style] + Expect(x == 8).Should(BeTrue()) +This should be replaced with: + Expect(x).Should(BeEqual(8)) + +* replaces Equal(true/false) with BeTrue()/BeFalse() [Style] + +* replaces HaveLen(0) with BeEmpty() [Style] + +* replaces Expect(...).Should(...) with Expect(...).To() [Style] + +* async timing interval: multiple timeout or polling interval [Style] +For example: + Eventually(context.Background(), func() bool { return true }, time.Second*10).WithTimeout(time.Second * 10).WithPolling(time.Millisecond * 500).Should(BeTrue()) + Eventually(context.Background(), func() bool { return true }, time.Second*10).Within(time.Second * 10).WithPolling(time.Millisecond * 500).Should(BeTrue()) + Eventually(func() bool { return true }, time.Second*10, 500*time.Millisecond).WithPolling(time.Millisecond * 500).Should(BeTrue()) + Eventually(func() bool { return true }, time.Second*10, 500*time.Millisecond).ProbeEvery(time.Millisecond * 500).Should(BeTrue()) + +* async timing interval: non-time.Duration intervals [Style] +gomega supports a few formats for timeout and polling intervals, when using the old format (the last two parameters of Eventually and Constantly): + * time.Duration + * any kind of numeric value, as number of seconds + * duration string like "12s" +The linter triggers a warning for any duration value that is not of the time.Duration type, assuming that this is +the desired type, given the type of the argument of the newer "WithTimeout", "WithPolling", "Within" and "ProbeEvery" +methods. +For example: + Eventually(context.Background(), func() bool { return true }, "1s").Should(BeTrue()) + Eventually(context.Background(), func() bool { return true }, time.Second*60, 15).Should(BeTrue()) +` diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/ginkgohandler/handler.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/ginkgohandler/handler.go similarity index 72% rename from tools/vendor/github.com/nunnatsa/ginkgolinter/ginkgohandler/handler.go rename to tools/vendor/github.com/nunnatsa/ginkgolinter/internal/ginkgohandler/handler.go index c0829c469..f10d83184 100644 --- a/tools/vendor/github.com/nunnatsa/ginkgolinter/ginkgohandler/handler.go +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/ginkgohandler/handler.go @@ -15,6 +15,7 @@ const ( // in imported with "." name, custom name or without any name. type Handler interface { GetFocusContainerName(*ast.CallExpr) (bool, *ast.Ident) + IsWrapContainer(*ast.CallExpr) bool IsFocusSpec(ident ast.Expr) bool } @@ -49,6 +50,13 @@ func (h dotHandler) GetFocusContainerName(exp *ast.CallExpr) (bool, *ast.Ident) return false, nil } +func (h dotHandler) IsWrapContainer(exp *ast.CallExpr) bool { + if fun, ok := exp.Fun.(*ast.Ident); ok { + return IsWrapContainer(fun.Name) + } + return false +} + func (h dotHandler) IsFocusSpec(exp ast.Expr) bool { id, ok := exp.(*ast.Ident) return ok && id.Name == focusSpec @@ -70,6 +78,16 @@ func (h nameHandler) GetFocusContainerName(exp *ast.CallExpr) (bool, *ast.Ident) return false, nil } +func (h nameHandler) IsWrapContainer(exp *ast.CallExpr) bool { + if sel, ok := exp.Fun.(*ast.SelectorExpr); ok { + if id, ok := sel.X.(*ast.Ident); ok && id.Name == string(h) { + return IsWrapContainer(sel.Sel.Name) + } + } + return false + +} + func (h nameHandler) IsFocusSpec(exp ast.Expr) bool { if selExp, ok := exp.(*ast.SelectorExpr); ok { if x, ok := selExp.X.(*ast.Ident); ok && x.Name == string(h) { @@ -88,10 +106,24 @@ func isFocusContainer(name string) bool { return false } -func IsContainer(id *ast.Ident) bool { - switch id.Name { - case "It", "When", "Context", "Describe", "DescribeTable", "Entry": +func IsContainer(name string) bool { + switch name { + case "It", "When", "Context", "Describe", "DescribeTable", "Entry", + "PIt", "PWhen", "PContext", "PDescribe", "PDescribeTable", "PEntry", + "XIt", "XWhen", "XContext", "XDescribe", "XDescribeTable", "XEntry": + return true + } + return isFocusContainer(name) +} + +func IsWrapContainer(name string) bool { + switch name { + case "When", "Context", "Describe", + "FWhen", "FContext", "FDescribe", + "PWhen", "PContext", "PDescribe", + "XWhen", "XContext", "XDescribe": return true } - return isFocusContainer(id.Name) + + return false } diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/gomegahandler/handler.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/gomegahandler/handler.go similarity index 96% rename from tools/vendor/github.com/nunnatsa/ginkgolinter/gomegahandler/handler.go rename to tools/vendor/github.com/nunnatsa/ginkgolinter/internal/gomegahandler/handler.go index 0c34cb7c1..4290e7373 100644 --- a/tools/vendor/github.com/nunnatsa/ginkgolinter/gomegahandler/handler.go +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/gomegahandler/handler.go @@ -5,6 +5,10 @@ import ( "go/token" ) +const ( + importPath = `"github.com/onsi/gomega"` +) + // Handler provide different handling, depend on the way gomega was imported, whether // in imported with "." name, custom name or without any name. type Handler interface { @@ -23,7 +27,7 @@ type Handler interface { // GetGomegaHandler returns a gomegar handler according to the way gomega was imported in the specific file func GetGomegaHandler(file *ast.File) Handler { for _, imp := range file.Imports { - if imp.Path.Value != `"github.com/onsi/gomega"` { + if imp.Path.Value != importPath { continue } @@ -66,7 +70,12 @@ func (h dotHandler) GetActualFuncName(expr *ast.CallExpr) (string, bool) { // ReplaceFunction replaces the function with another one, for fix suggestions func (dotHandler) ReplaceFunction(caller *ast.CallExpr, newExpr *ast.Ident) { - caller.Fun = newExpr + switch f := caller.Fun.(type) { + case *ast.Ident: + caller.Fun = newExpr + case *ast.SelectorExpr: + f.Sel = newExpr + } } func (dotHandler) getDefFuncName(expr *ast.CallExpr) string { diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/interfaces/interfaces.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/interfaces/interfaces.go new file mode 100644 index 000000000..dafeacd4f --- /dev/null +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/interfaces/interfaces.go @@ -0,0 +1,76 @@ +package interfaces + +import ( + "go/token" + gotypes "go/types" +) + +var ( + errorType *gotypes.Interface + gomegaMatcherType *gotypes.Interface +) + +func init() { + errorType = gotypes.Universe.Lookup("error").Type().Underlying().(*gotypes.Interface) + gomegaMatcherType = generateTheGomegaMatcherInfType() +} + +// generateTheGomegaMatcherInfType generates a types.Interface instance that represents the +// GomegaMatcher interface. +// The original code is (copied from https://github.com/nunnatsa/ginkgolinter/blob/8fdd05eee922578d4699f49d267001c01e0b9f1e/testdata/src/a/vendor/github.com/onsi/gomega/types/types.go) +// +// type GomegaMatcher interface { +// Match(actual interface{}) (success bool, err error) +// FailureMessage(actual interface{}) (message string) +// NegatedFailureMessage(actual interface{}) (message string) +// } +func generateTheGomegaMatcherInfType() *gotypes.Interface { + err := gotypes.Universe.Lookup("error").Type() + bl := gotypes.Typ[gotypes.Bool] + str := gotypes.Typ[gotypes.String] + anyType := gotypes.Universe.Lookup("any").Type() + + return gotypes.NewInterfaceType([]*gotypes.Func{ + // Match(actual interface{}) (success bool, err error) + gotypes.NewFunc(token.NoPos, nil, "Match", gotypes.NewSignatureType( + nil, nil, nil, + gotypes.NewTuple( + gotypes.NewVar(token.NoPos, nil, "actual", anyType), + ), + gotypes.NewTuple( + gotypes.NewVar(token.NoPos, nil, "", bl), + gotypes.NewVar(token.NoPos, nil, "", err), + ), false), + ), + // FailureMessage(actual interface{}) (message string) + gotypes.NewFunc(token.NoPos, nil, "FailureMessage", gotypes.NewSignatureType( + nil, nil, nil, + gotypes.NewTuple( + gotypes.NewVar(token.NoPos, nil, "", anyType), + ), + gotypes.NewTuple( + gotypes.NewVar(token.NoPos, nil, "", str), + ), + false), + ), + //NegatedFailureMessage(actual interface{}) (message string) + gotypes.NewFunc(token.NoPos, nil, "NegatedFailureMessage", gotypes.NewSignatureType( + nil, nil, nil, + gotypes.NewTuple( + gotypes.NewVar(token.NoPos, nil, "", anyType), + ), + gotypes.NewTuple( + gotypes.NewVar(token.NoPos, nil, "", str), + ), + false), + ), + }, nil) +} + +func ImplementsError(t gotypes.Type) bool { + return gotypes.Implements(t, errorType) +} + +func ImplementsGomegaMatcher(t gotypes.Type) bool { + return gotypes.Implements(t, gomegaMatcherType) +} diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/intervals/intervals.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/intervals/intervals.go new file mode 100644 index 000000000..b8166bdb2 --- /dev/null +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/intervals/intervals.go @@ -0,0 +1,285 @@ +package intervals + +import ( + "errors" + "go/ast" + "go/constant" + "go/token" + gotypes "go/types" + "strconv" + "time" + + "golang.org/x/tools/go/analysis" + + "github.com/nunnatsa/ginkgolinter/internal/gomegahandler" + "github.com/nunnatsa/ginkgolinter/internal/reports" +) + +type noDurationIntervalErr struct { + value string +} + +func (err noDurationIntervalErr) Error() string { + return "only use time.Duration for timeout and polling in Eventually() or Consistently()" +} + +func CheckIntervals(pass *analysis.Pass, expr *ast.CallExpr, actualExpr *ast.CallExpr, reportBuilder *reports.Builder, handler gomegahandler.Handler, timePkg string, funcIndex int) { + var ( + timeout time.Duration + polling time.Duration + err error + ) + + timeoutOffset := funcIndex + 1 + if len(actualExpr.Args) > timeoutOffset { + timeout, err = getDuration(pass, actualExpr.Args[timeoutOffset], timePkg) + if err != nil { + suggestFix := false + if tryFixIntDuration(expr, err, handler, timePkg, timeoutOffset) { + suggestFix = true + } + reportBuilder.AddIssue(suggestFix, err.Error()) + } + pollingOffset := funcIndex + 2 + if len(actualExpr.Args) > pollingOffset { + polling, err = getDuration(pass, actualExpr.Args[pollingOffset], timePkg) + if err != nil { + suggestFix := false + if tryFixIntDuration(expr, err, handler, timePkg, pollingOffset) { + suggestFix = true + } + reportBuilder.AddIssue(suggestFix, err.Error()) + } + } + } + + selExp := expr.Fun.(*ast.SelectorExpr) + for { + call, ok := selExp.X.(*ast.CallExpr) + if !ok { + break + } + + fun, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + break + } + + switch fun.Sel.Name { + case "WithTimeout", "Within": + if timeout != 0 { + reportBuilder.AddIssue(false, "timeout defined more than once") + } else if len(call.Args) == 1 { + timeout, err = getDurationFromValue(pass, call.Args[0], timePkg) + if err != nil { + reportBuilder.AddIssue(false, err.Error()) + } + } + + case "WithPolling", "ProbeEvery": + if polling != 0 { + reportBuilder.AddIssue(false, "polling defined more than once") + } else if len(call.Args) == 1 { + polling, err = getDurationFromValue(pass, call.Args[0], timePkg) + if err != nil { + reportBuilder.AddIssue(false, err.Error()) + } + } + } + + selExp = fun + } + + if timeout != 0 && polling != 0 && timeout < polling { + reportBuilder.AddIssue(false, "timeout must not be shorter than the polling interval") + } +} + +func tryFixIntDuration(expr *ast.CallExpr, err error, handler gomegahandler.Handler, timePkg string, offset int) bool { + suggestFix := false + var durErr noDurationIntervalErr + if errors.As(err, &durErr) { + if len(durErr.value) > 0 { + actualExpr := handler.GetActualExpr(expr.Fun.(*ast.SelectorExpr)) + var newArg ast.Expr + second := &ast.SelectorExpr{ + Sel: ast.NewIdent("Second"), + X: ast.NewIdent(timePkg), + } + if durErr.value == "1" { + newArg = second + } else { + newArg = &ast.BinaryExpr{ + X: second, + Op: token.MUL, + Y: actualExpr.Args[offset], + } + } + actualExpr.Args[offset] = newArg + suggestFix = true + } + } + + return suggestFix +} + +func getDuration(pass *analysis.Pass, interval ast.Expr, timePkg string) (time.Duration, error) { + argType := pass.TypesInfo.TypeOf(interval) + if durType, ok := argType.(*gotypes.Named); ok { + if durType.Obj().Name() == "Duration" && durType.Obj().Pkg().Name() == "time" { + return getDurationFromValue(pass, interval, timePkg) + } + } + + value := "" + switch val := interval.(type) { + case *ast.BasicLit: + if val.Kind == token.INT { + value = val.Value + } + case *ast.Ident: + i, err := getConstDuration(pass, val, timePkg) + if err != nil || i == 0 { + return 0, nil + } + value = val.Name + } + + return 0, noDurationIntervalErr{value: value} +} + +func getDurationFromValue(pass *analysis.Pass, interval ast.Expr, timePkg string) (time.Duration, error) { + switch dur := interval.(type) { + case *ast.SelectorExpr: + ident, ok := dur.X.(*ast.Ident) + if ok { + if ident.Name == timePkg { + return getTimeDurationValue(dur) + } + return getDurationFromValue(pass, dur.Sel, timePkg) + } + case *ast.BinaryExpr: + return getBinaryExprDuration(pass, dur, timePkg) + + case *ast.Ident: + return getConstDuration(pass, dur, timePkg) + } + + return 0, nil +} + +func getConstDuration(pass *analysis.Pass, ident *ast.Ident, timePkg string) (time.Duration, error) { + o := pass.TypesInfo.ObjectOf(ident) + if o != nil { + if c, ok := o.(*gotypes.Const); ok { + if c.Val().Kind() == constant.Int { + i, err := strconv.Atoi(c.Val().String()) + if err != nil { + return 0, nil + } + return time.Duration(i), nil + } + } + } + + if ident.Obj != nil && ident.Obj.Kind == ast.Con && ident.Obj.Decl != nil { + if vals, ok := ident.Obj.Decl.(*ast.ValueSpec); ok { + if len(vals.Values) == 1 { + switch val := vals.Values[0].(type) { + case *ast.BasicLit: + if val.Kind == token.INT { + i, err := strconv.Atoi(val.Value) + if err != nil { + return 0, nil + } + return time.Duration(i), nil + } + return 0, nil + case *ast.BinaryExpr: + return getBinaryExprDuration(pass, val, timePkg) + } + } + } + } + + return 0, nil +} + +func getTimeDurationValue(dur *ast.SelectorExpr) (time.Duration, error) { + switch dur.Sel.Name { + case "Nanosecond": + return time.Nanosecond, nil + case "Microsecond": + return time.Microsecond, nil + case "Millisecond": + return time.Millisecond, nil + case "Second": + return time.Second, nil + case "Minute": + return time.Minute, nil + case "Hour": + return time.Hour, nil + default: + return 0, errors.New("unknown duration value") // should never happen + } +} + +func getBinaryExprDuration(pass *analysis.Pass, expr *ast.BinaryExpr, timePkg string) (time.Duration, error) { + x, err := getBinaryDurValue(pass, expr.X, timePkg) + if err != nil || x == 0 { + return 0, nil + } + y, err := getBinaryDurValue(pass, expr.Y, timePkg) + if err != nil || y == 0 { + return 0, nil + } + + switch expr.Op { + case token.ADD: + return x + y, nil + case token.SUB: + val := x - y + if val > 0 { + return val, nil + } + return 0, nil + case token.MUL: + return x * y, nil + case token.QUO: + if y == 0 { + return 0, nil + } + return x / y, nil + case token.REM: + if y == 0 { + return 0, nil + } + return x % y, nil + default: + return 0, nil + } +} + +func getBinaryDurValue(pass *analysis.Pass, expr ast.Expr, timePkg string) (time.Duration, error) { + switch x := expr.(type) { + case *ast.SelectorExpr: + return getDurationFromValue(pass, x, timePkg) + case *ast.BinaryExpr: + return getBinaryExprDuration(pass, x, timePkg) + case *ast.BasicLit: + if x.Kind == token.INT { + val, err := strconv.Atoi(x.Value) + if err != nil { + return 0, err + } + return time.Duration(val), nil + } + case *ast.ParenExpr: + return getBinaryDurValue(pass, x.X, timePkg) + + case *ast.Ident: + return getConstDuration(pass, x, timePkg) + } + + return 0, nil +} diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/reports/report-builder.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/reports/report-builder.go new file mode 100644 index 000000000..c7f931ca7 --- /dev/null +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/reports/report-builder.go @@ -0,0 +1,98 @@ +package reports + +import ( + "bytes" + "fmt" + "go/ast" + "go/printer" + "go/token" + "strings" + + "golang.org/x/tools/go/analysis" +) + +type Builder struct { + pos token.Pos + end token.Pos + oldExpr string + issues []string + fixOffer string + suggestFix bool +} + +func NewBuilder(fset *token.FileSet, oldExpr ast.Expr) *Builder { + b := &Builder{ + pos: oldExpr.Pos(), + end: oldExpr.End(), + oldExpr: goFmt(fset, oldExpr), + suggestFix: false, + } + + return b +} + +func (b *Builder) AddIssue(suggestFix bool, issue string, args ...any) { + if len(args) > 0 { + issue = fmt.Sprintf(issue, args...) + } + b.issues = append(b.issues, issue) + + if suggestFix { + b.suggestFix = true + } +} + +func (b *Builder) SetFixOffer(fset *token.FileSet, fixOffer ast.Expr) { + if offer := goFmt(fset, fixOffer); offer != b.oldExpr { + b.fixOffer = offer + } +} + +func (b *Builder) HasReport() bool { + return len(b.issues) > 0 +} + +func (b *Builder) Build() analysis.Diagnostic { + diagnostic := analysis.Diagnostic{ + Pos: b.pos, + Message: b.getMessage(), + } + + if b.suggestFix && len(b.fixOffer) > 0 { + diagnostic.SuggestedFixes = []analysis.SuggestedFix{ + { + Message: fmt.Sprintf("should replace %s with %s", b.oldExpr, b.fixOffer), + TextEdits: []analysis.TextEdit{ + { + Pos: b.pos, + End: b.end, + NewText: []byte(b.fixOffer), + }, + }, + }, + } + } + + return diagnostic +} + +func goFmt(fset *token.FileSet, x ast.Expr) string { + var b bytes.Buffer + _ = printer.Fprint(&b, fset, x) + return b.String() +} + +func (b *Builder) getMessage() string { + sb := strings.Builder{} + sb.WriteString("ginkgo-linter: ") + if len(b.issues) > 1 { + sb.WriteString("multiple issues: ") + } + sb.WriteString(strings.Join(b.issues, "; ")) + + if b.suggestFix && len(b.fixOffer) != 0 { + sb.WriteString(fmt.Sprintf(". Consider using `%s` instead", b.fixOffer)) + } + + return sb.String() +} diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/reverseassertion/reverse_assertion.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/internal/reverseassertion/reverse_assertion.go similarity index 100% rename from tools/vendor/github.com/nunnatsa/ginkgolinter/reverseassertion/reverse_assertion.go rename to tools/vendor/github.com/nunnatsa/ginkgolinter/internal/reverseassertion/reverse_assertion.go diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/ginkgo_linter.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/linter/ginkgo_linter.go similarity index 59% rename from tools/vendor/github.com/nunnatsa/ginkgolinter/ginkgo_linter.go rename to tools/vendor/github.com/nunnatsa/ginkgolinter/linter/ginkgo_linter.go index d1e5164fa..574fdfadf 100644 --- a/tools/vendor/github.com/nunnatsa/ginkgolinter/ginkgo_linter.go +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/linter/ginkgo_linter.go @@ -1,8 +1,7 @@ -package ginkgolinter +package linter import ( "bytes" - "flag" "fmt" "go/ast" "go/constant" @@ -14,11 +13,13 @@ import ( "github.com/go-toolsmith/astcopy" "golang.org/x/tools/go/analysis" - "github.com/nunnatsa/ginkgolinter/ginkgohandler" - "github.com/nunnatsa/ginkgolinter/gomegahandler" - "github.com/nunnatsa/ginkgolinter/reverseassertion" + "github.com/nunnatsa/ginkgolinter/internal/ginkgohandler" + "github.com/nunnatsa/ginkgolinter/internal/gomegahandler" + "github.com/nunnatsa/ginkgolinter/internal/interfaces" + "github.com/nunnatsa/ginkgolinter/internal/intervals" + "github.com/nunnatsa/ginkgolinter/internal/reports" + "github.com/nunnatsa/ginkgolinter/internal/reverseassertion" "github.com/nunnatsa/ginkgolinter/types" - "github.com/nunnatsa/ginkgolinter/version" ) // The ginkgolinter enforces standards of using ginkgo and gomega. @@ -27,21 +28,28 @@ import ( const ( linterName = "ginkgo-linter" - wrongLengthWarningTemplate = linterName + ": wrong length assertion; consider using `%s` instead" - wrongNilWarningTemplate = linterName + ": wrong nil assertion; consider using `%s` instead" - wrongBoolWarningTemplate = linterName + ": wrong boolean assertion; consider using `%s` instead" - wrongErrWarningTemplate = linterName + ": wrong error assertion; consider using `%s` instead" - wrongCompareWarningTemplate = linterName + ": wrong comparison assertion; consider using `%s` instead" - doubleNegativeWarningTemplate = linterName + ": avoid double negative assertion; consider using `%s` instead" - valueInEventually = linterName + ": use a function call in %s. This actually checks nothing, because %s receives the function returned value, instead of function itself, and this value is never changed" - comparePointerToValue = linterName + ": comparing a pointer to a value will always fail. consider using `%s` instead" - missingAssertionMessage = linterName + `: %q: missing assertion method. Expected "Should()", "To()", "ShouldNot()", "ToNot()" or "NotTo()"` - missingAsyncAssertionMessage = linterName + `: %q: missing assertion method. Expected "Should()" or "ShouldNot()"` - focusContainerFound = linterName + ": Focus container found. This is used only for local debug and should not be part of the actual source code, consider to replace with %q" - focusSpecFound = linterName + ": Focus spec found. This is used only for local debug and should not be part of the actual source code, consider to remove it" - compareDifferentTypes = linterName + ": use %[1]s with different types: Comparing %[2]s with %[3]s; either change the expected value type if possible, or use the BeEquivalentTo() matcher, instead of %[1]s()" - compareInterfaces = linterName + ": be careful comparing interfaces. This can fail in runtime, if the actual implementing types are different" + wrongLengthWarningTemplate = "wrong length assertion" + wrongCapWarningTemplate = "wrong cap assertion" + wrongNilWarningTemplate = "wrong nil assertion" + wrongBoolWarningTemplate = "wrong boolean assertion" + wrongErrWarningTemplate = "wrong error assertion" + wrongCompareWarningTemplate = "wrong comparison assertion" + doubleNegativeWarningTemplate = "avoid double negative assertion" + valueInEventually = "use a function call in %s. This actually checks nothing, because %s receives the function returned value, instead of function itself, and this value is never changed" + comparePointerToValue = "comparing a pointer to a value will always fail" + missingAssertionMessage = linterName + `: %q: missing assertion method. Expected %s` + focusContainerFound = linterName + ": Focus container found. This is used only for local debug and should not be part of the actual source code. Consider to replace with %q" + focusSpecFound = linterName + ": Focus spec found. This is used only for local debug and should not be part of the actual source code. Consider to remove it" + compareDifferentTypes = "use %[1]s with different types: Comparing %[2]s with %[3]s; either change the expected value type if possible, or use the BeEquivalentTo() matcher, instead of %[1]s()" + matchErrorArgWrongType = "the MatchError matcher used to assert a non error type (%s)" + matchErrorWrongTypeAssertion = "MatchError first parameter (%s) must be error, string, GomegaMatcher or func(error)bool are allowed" + matchErrorMissingDescription = "missing function description as second parameter of MatchError" + matchErrorRedundantArg = "redundant MatchError arguments; consider removing them" + matchErrorNoFuncDescription = "The second parameter of MatchError must be the function description (string)" + forceExpectToTemplate = "must not use Expect with %s" + useBeforeEachTemplate = "use BeforeEach() to assign variable %s" ) + const ( // gomega matchers beEmpty = "BeEmpty" beEquivalentTo = "BeEquivalentTo" @@ -53,6 +61,7 @@ const ( // gomega matchers beZero = "BeZero" equal = "Equal" haveLen = "HaveLen" + haveCap = "HaveCap" haveOccurred = "HaveOccurred" haveValue = "HaveValue" not = "Not" @@ -61,6 +70,7 @@ const ( // gomega matchers and = "And" or = "Or" withTransform = "WithTransform" + matchError = "MatchError" ) const ( // gomega actuals @@ -72,99 +82,19 @@ const ( // gomega actuals consistentlyWithOffset = "ConsistentlyWithOffset" ) -// Analyzer is the interface to go_vet -var Analyzer = NewAnalyzer() - -type ginkgoLinter struct { +type GinkgoLinter struct { config *types.Config } -// NewAnalyzer returns an Analyzer - the package interface with nogo -func NewAnalyzer() *analysis.Analyzer { - linter := ginkgoLinter{ - config: &types.Config{ - SuppressLen: false, - SuppressNil: false, - SuppressErr: false, - SuppressCompare: false, - ForbidFocus: false, - AllowHaveLen0: false, - }, - } - - a := &analysis.Analyzer{ - Name: "ginkgolinter", - Doc: fmt.Sprintf(doc, version.Version()), - Run: linter.run, +// NewGinkgoLinter return new ginkgolinter object +func NewGinkgoLinter(config *types.Config) *GinkgoLinter { + return &GinkgoLinter{ + config: config, } - - var ignored bool - a.Flags.Init("ginkgolinter", flag.ExitOnError) - a.Flags.Var(&linter.config.SuppressLen, "suppress-len-assertion", "Suppress warning for wrong length assertions") - a.Flags.Var(&linter.config.SuppressNil, "suppress-nil-assertion", "Suppress warning for wrong nil assertions") - a.Flags.Var(&linter.config.SuppressErr, "suppress-err-assertion", "Suppress warning for wrong error assertions") - a.Flags.Var(&linter.config.SuppressCompare, "suppress-compare-assertion", "Suppress warning for wrong comparison assertions") - a.Flags.Var(&linter.config.SuppressAsync, "suppress-async-assertion", "Suppress warning for function call in async assertion, like Eventually") - a.Flags.Var(&linter.config.SuppressTypeCompare, "suppress-type-compare-assertion", "Suppress warning for comparing values from different types, like int32 and uint32") - a.Flags.Var(&linter.config.AllowHaveLen0, "allow-havelen-0", "Do not warn for HaveLen(0); default = false") - - a.Flags.BoolVar(&ignored, "suppress-focus-container", true, "Suppress warning for ginkgo focus containers like FDescribe, FContext, FWhen or FIt. Deprecated and ignored: use --forbid-focus-container instead") - a.Flags.Var(&linter.config.ForbidFocus, "forbid-focus-container", "trigger a warning for ginkgo focus containers like FDescribe, FContext, FWhen or FIt; default = false.") - - return a } -const doc = `enforces standards of using ginkgo and gomega - -or - ginkgolinter version - -version: %s - -currently, the linter searches for following: -* trigger a warning when using Eventually or Constantly with a function call. This is in order to prevent the case when - using a function call instead of a function. Function call returns a value only once, and so the original value - is tested again and again and is never changed. [Bug] - -* trigger a warning when comparing a pointer to a value. [Bug] - -* trigger a warning for missing assertion method: [Bug] - Eventually(checkSomething) - -* trigger a warning when a ginkgo focus container (FDescribe, FContext, FWhen or FIt) is found. [Bug] - -* trigger a warning when using the Equal or the BeIdentical matcher with two different types, as these matchers will - fail in runtime. - -* wrong length assertions. We want to assert the item rather than its length. [Style] -For example: - Expect(len(x)).Should(Equal(1)) -This should be replaced with: - Expect(x)).Should(HavelLen(1)) - -* wrong nil assertions. We want to assert the item rather than a comparison result. [Style] -For example: - Expect(x == nil).Should(BeTrue()) -This should be replaced with: - Expect(x).Should(BeNil()) - -* wrong error assertions. For example: [Style] - Expect(err == nil).Should(BeTrue()) -This should be replaced with: - Expect(err).ShouldNot(HaveOccurred()) - -* wrong boolean comparison, for example: [Style] - Expect(x == 8).Should(BeTrue()) -This should be replaced with: - Expect(x).Should(BeEqual(8)) - -* replaces Equal(true/false) with BeTrue()/BeFalse() [Style] - -* replaces HaveLen(0) with BeEmpty() [Style] -` - -// main assertion function -func (l *ginkgoLinter) run(pass *analysis.Pass) (interface{}, error) { +// Run is the main assertion function +func (l *GinkgoLinter) Run(pass *analysis.Pass) (interface{}, error) { for _, file := range pass.Files { fileConfig := l.config.Clone() @@ -179,18 +109,37 @@ func (l *ginkgoLinter) run(pass *analysis.Pass) (interface{}, error) { continue } + timePks := "" + for _, imp := range file.Imports { + if imp.Path.Value == `"time"` { + if imp.Name == nil { + timePks = "time" + } else { + timePks = imp.Name.Name + } + } + } + ast.Inspect(file, func(n ast.Node) bool { - if ginkgoHndlr != nil && fileConfig.ForbidFocus { + if ginkgoHndlr != nil { + goDeeper := false spec, ok := n.(*ast.ValueSpec) if ok { for _, val := range spec.Values { if exp, ok := val.(*ast.CallExpr); ok { - if checkFocusContainer(pass, ginkgoHndlr, exp) { - return true + if bool(fileConfig.ForbidFocus) && checkFocusContainer(pass, ginkgoHndlr, exp) { + goDeeper = true + } + + if bool(fileConfig.ForbidSpecPollution) && checkAssignmentsInContainer(pass, ginkgoHndlr, exp) { + goDeeper = true } } } } + if goDeeper { + return true + } } stmt, ok := n.(*ast.ExprStmt) @@ -210,8 +159,17 @@ func (l *ginkgoLinter) run(pass *analysis.Pass) (interface{}, error) { return true } - if ginkgoHndlr != nil && bool(config.ForbidFocus) && checkFocusContainer(pass, ginkgoHndlr, assertionExp) { - return true + if ginkgoHndlr != nil { + goDeeper := false + if bool(config.ForbidFocus) && checkFocusContainer(pass, ginkgoHndlr, assertionExp) { + goDeeper = true + } + if bool(config.ForbidSpecPollution) && checkAssignmentsInContainer(pass, ginkgoHndlr, assertionExp) { + goDeeper = true + } + if goDeeper { + return true + } } // no more ginkgo checks. From here it's only gomega. So if there is no gomega handler, exit here. This is @@ -236,12 +194,89 @@ func (l *ginkgoLinter) run(pass *analysis.Pass) (interface{}, error) { return true } - return checkExpression(pass, config, assertionExp, actualExpr, gomegaHndlr) + return checkExpression(pass, config, assertionExp, actualExpr, gomegaHndlr, timePks) }) } return nil, nil } +func checkAssignmentsInContainer(pass *analysis.Pass, ginkgoHndlr ginkgohandler.Handler, exp *ast.CallExpr) bool { + foundSomething := false + if ginkgoHndlr.IsWrapContainer(exp) { + for _, arg := range exp.Args { + if fn, ok := arg.(*ast.FuncLit); ok { + if fn.Body != nil { + if checkAssignments(pass, fn.Body.List) { + foundSomething = true + } + break + } + } + } + } + + return foundSomething +} + +func checkAssignments(pass *analysis.Pass, list []ast.Stmt) bool { + foundSomething := false + for _, stmt := range list { + switch st := stmt.(type) { + case *ast.DeclStmt: + if gen, ok := st.Decl.(*ast.GenDecl); ok { + if gen.Tok != token.VAR { + continue + } + for _, spec := range gen.Specs { + if valSpec, ok := spec.(*ast.ValueSpec); ok { + if checkAssignmentsValues(pass, valSpec.Names, valSpec.Values) { + foundSomething = true + } + } + } + } + + case *ast.AssignStmt: + for i, val := range st.Rhs { + if !is[*ast.FuncLit](val) { + if id, isIdent := st.Lhs[i].(*ast.Ident); isIdent && id.Name != "_" { + reportNoFix(pass, id.Pos(), useBeforeEachTemplate, id.Name) + foundSomething = true + } + } + } + + case *ast.IfStmt: + if st.Body != nil { + if checkAssignments(pass, st.Body.List) { + foundSomething = true + } + } + if st.Else != nil { + if block, isBlock := st.Else.(*ast.BlockStmt); isBlock { + if checkAssignments(pass, block.List) { + foundSomething = true + } + } + } + } + } + + return foundSomething +} + +func checkAssignmentsValues(pass *analysis.Pass, names []*ast.Ident, values []ast.Expr) bool { + foundSomething := false + for i, val := range values { + if !is[*ast.FuncLit](val) { + reportNoFix(pass, names[i].Pos(), useBeforeEachTemplate, names[i].Name) + foundSomething = true + } + } + + return foundSomething +} + func checkFocusContainer(pass *analysis.Pass, ginkgoHndlr ginkgohandler.Handler, exp *ast.CallExpr) bool { foundFocus := false isFocus, id := ginkgoHndlr.GetFocusContainerName(exp) @@ -250,7 +285,7 @@ func checkFocusContainer(pass *analysis.Pass, ginkgoHndlr ginkgohandler.Handler, foundFocus = true } - if id != nil && ginkgohandler.IsContainer(id) { + if id != nil && ginkgohandler.IsContainer(id.Name) { for _, arg := range exp.Args { if ginkgoHndlr.IsFocusSpec(arg) { reportNoFix(pass, arg.Pos(), focusSpecFound) @@ -266,21 +301,69 @@ func checkFocusContainer(pass *analysis.Pass, ginkgoHndlr ginkgohandler.Handler, return foundFocus } -func checkExpression(pass *analysis.Pass, config types.Config, assertionExp *ast.CallExpr, actualExpr *ast.CallExpr, handler gomegahandler.Handler) bool { +func checkExpression(pass *analysis.Pass, config types.Config, assertionExp *ast.CallExpr, actualExpr *ast.CallExpr, handler gomegahandler.Handler, timePkg string) bool { expr := astcopy.CallExpr(assertionExp) - oldExpr := goFmt(pass.Fset, expr) - if checkAsyncAssertion(pass, config, expr, actualExpr, handler, oldExpr) { - return true + reportBuilder := reports.NewBuilder(pass.Fset, expr) + + goNested := false + if checkAsyncAssertion(pass, config, expr, actualExpr, handler, reportBuilder, timePkg) { + goNested = true + } else { + + actualArg := getActualArg(actualExpr, handler) + if actualArg == nil { + return true + } + + if config.ForceExpectTo { + goNested = forceExpectTo(expr, handler, reportBuilder) || goNested + } + + goNested = doCheckExpression(pass, config, assertionExp, actualArg, expr, handler, reportBuilder) || goNested } - actualArg := getActualArg(actualExpr, handler) - if actualArg == nil { - return true + if reportBuilder.HasReport() { + reportBuilder.SetFixOffer(pass.Fset, expr) + pass.Report(reportBuilder.Build()) } + return goNested +} + +func forceExpectTo(expr *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { + if asrtFun, ok := expr.Fun.(*ast.SelectorExpr); ok { + if actualFuncName, ok := handler.GetActualFuncName(expr); ok && actualFuncName == expect { + var ( + name string + newIdent *ast.Ident + ) + + switch name = asrtFun.Sel.Name; name { + case "Should": + newIdent = ast.NewIdent("To") + case "ShouldNot": + newIdent = ast.NewIdent("ToNot") + default: + return false + } + + handler.ReplaceFunction(expr, newIdent) + reportBuilder.AddIssue(true, fmt.Sprintf(forceExpectToTemplate, name)) + return true + } + } + + return false +} + +func doCheckExpression(pass *analysis.Pass, config types.Config, assertionExp *ast.CallExpr, actualArg ast.Expr, expr *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { if !bool(config.SuppressLen) && isActualIsLenFunc(actualArg) { - return checkLengthMatcher(expr, pass, handler, oldExpr) + return checkLengthMatcher(expr, pass, handler, reportBuilder) + + } else if !bool(config.SuppressLen) && isActualIsCapFunc(actualArg) { + return checkCapMatcher(expr, handler, reportBuilder) + } else if nilable, compOp := getNilableFromComparison(actualArg); nilable != nil { if isExprError(pass, nilable) { if config.SuppressErr { @@ -290,44 +373,177 @@ func checkExpression(pass *analysis.Pass, config types.Config, assertionExp *ast return true } - return checkNilMatcher(expr, pass, nilable, handler, compOp == token.NEQ, oldExpr) + return checkNilMatcher(expr, pass, nilable, handler, compOp == token.NEQ, reportBuilder) } else if first, second, op, ok := isComparison(pass, actualArg); ok { matcher, shouldContinue := startCheckComparison(expr, handler) if !shouldContinue { return false } - if !bool(config.SuppressLen) && isActualIsLenFunc(first) { - if handleLenComparison(pass, expr, matcher, first, second, op, handler, oldExpr) { - return false + if !config.SuppressLen { + if isActualIsLenFunc(first) { + if handleLenComparison(pass, expr, matcher, first, second, op, handler, reportBuilder) { + return false + } + } + if isActualIsCapFunc(first) { + if handleCapComparison(expr, matcher, first, second, op, handler, reportBuilder) { + return false + } } } - return bool(config.SuppressCompare) || checkComparison(expr, pass, matcher, handler, first, second, op, oldExpr) + return bool(config.SuppressCompare) || checkComparison(expr, pass, matcher, handler, first, second, op, reportBuilder) + } else if checkMatchError(pass, assertionExp, actualArg, handler, reportBuilder) { + return false } else if isExprError(pass, actualArg) { - return bool(config.SuppressErr) || checkNilError(pass, expr, handler, actualArg, oldExpr) + return bool(config.SuppressErr) || checkNilError(pass, expr, handler, actualArg, reportBuilder) - } else if checkPointerComparison(pass, config, assertionExp, expr, actualArg, handler, oldExpr) { + } else if checkPointerComparison(pass, config, assertionExp, expr, actualArg, handler, reportBuilder) { return false - } else if !handleAssertionOnly(pass, config, expr, handler, actualArg, oldExpr, true) { + } else if !handleAssertionOnly(pass, config, expr, handler, actualArg, reportBuilder) { return false } else if !config.SuppressTypeCompare { - return !checkEqualWrongType(pass, assertionExp, actualArg, handler, oldExpr) + return !checkEqualWrongType(pass, assertionExp, actualArg, handler, reportBuilder) } return true } -func checkEqualWrongType(pass *analysis.Pass, origExp *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, old string) bool { +func checkMatchError(pass *analysis.Pass, origExp *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { + matcher, ok := origExp.Args[0].(*ast.CallExpr) + if !ok { + return false + } + + return doCheckMatchError(pass, origExp, matcher, actualArg, handler, reportBuilder) +} + +func doCheckMatchError(pass *analysis.Pass, origExp *ast.CallExpr, matcher *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { + name, ok := handler.GetActualFuncName(matcher) + if !ok { + return false + } + switch name { + case matchError: + case not: + nested, ok := matcher.Args[0].(*ast.CallExpr) + if !ok { + return false + } + + return doCheckMatchError(pass, origExp, nested, actualArg, handler, reportBuilder) + case and, or: + res := false + for _, arg := range matcher.Args { + if nested, ok := arg.(*ast.CallExpr); ok { + if valid := doCheckMatchError(pass, origExp, nested, actualArg, handler, reportBuilder); valid { + res = true + } + } + } + return res + default: + return false + } + + if !isExprError(pass, actualArg) { + reportBuilder.AddIssue(false, matchErrorArgWrongType, goFmt(pass.Fset, actualArg)) + } + + expr := astcopy.CallExpr(matcher) + + validAssertion, requiredParams := checkMatchErrorAssertion(pass, matcher) + if !validAssertion { + reportBuilder.AddIssue(false, matchErrorWrongTypeAssertion, goFmt(pass.Fset, matcher.Args[0])) + } + + numParams := len(matcher.Args) + if numParams == requiredParams { + if numParams == 2 { + t := pass.TypesInfo.TypeOf(matcher.Args[1]) + if !gotypes.Identical(t, gotypes.Typ[gotypes.String]) { + reportBuilder.AddIssue(false, matchErrorNoFuncDescription) + return true + } + } + return true + } + + if requiredParams == 2 && numParams == 1 { + reportBuilder.AddIssue(false, matchErrorMissingDescription) + return true + } + + var newArgsSuggestion = []ast.Expr{expr.Args[0]} + if requiredParams == 2 { + newArgsSuggestion = append(newArgsSuggestion, expr.Args[1]) + } + expr.Args = newArgsSuggestion + + reportBuilder.AddIssue(true, matchErrorRedundantArg) + return true +} + +func checkMatchErrorAssertion(pass *analysis.Pass, matcher *ast.CallExpr) (bool, int) { + if isErrorMatcherValidArg(pass, matcher.Args[0]) { + return true, 1 + } + + t1 := pass.TypesInfo.TypeOf(matcher.Args[0]) + if isFuncErrBool(t1) { + return true, 2 + } + + return false, 0 +} + +// isFuncErrBool checks if a function is with the signature `func(error) bool` +func isFuncErrBool(t gotypes.Type) bool { + sig, ok := t.(*gotypes.Signature) + if !ok { + return false + } + if sig.Params().Len() != 1 || sig.Results().Len() != 1 { + return false + } + + if !interfaces.ImplementsError(sig.Params().At(0).Type()) { + return false + } + + b, ok := sig.Results().At(0).Type().(*gotypes.Basic) + if ok && b.Name() == "bool" && b.Info() == gotypes.IsBoolean && b.Kind() == gotypes.Bool { + return true + } + + return false +} + +func isErrorMatcherValidArg(pass *analysis.Pass, arg ast.Expr) bool { + if isExprError(pass, arg) { + return true + } + + if t, ok := pass.TypesInfo.TypeOf(arg).(*gotypes.Basic); ok && t.Kind() == gotypes.String { + return true + } + + t := pass.TypesInfo.TypeOf(arg) + + return interfaces.ImplementsGomegaMatcher(t) +} + +func checkEqualWrongType(pass *analysis.Pass, origExp *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { matcher, ok := origExp.Args[0].(*ast.CallExpr) if !ok { return false } - return checkEqualDifferentTypes(pass, matcher, actualArg, handler, old, false) + return checkEqualDifferentTypes(pass, matcher, actualArg, handler, false, reportBuilder) } -func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, old string, parentPointer bool) bool { +func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, parentPointer bool, reportBuilder *reports.Builder) bool { matcherFuncName, ok := handler.GetActualFuncName(matcher) if !ok { return false @@ -344,7 +560,7 @@ func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actual if !ok { continue } - if checkEqualDifferentTypes(pass, nested, actualArg, handler, old, parentPointer) { + if checkEqualDifferentTypes(pass, nested, actualArg, handler, parentPointer, reportBuilder) { foundIssue = true } } @@ -360,7 +576,7 @@ func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actual switch matcherFuncName { case equal, beIdenticalTo: case not: - return checkEqualDifferentTypes(pass, nested, actualArg, handler, old, parentPointer) + return checkEqualDifferentTypes(pass, nested, actualArg, handler, parentPointer, reportBuilder) default: return false } @@ -373,7 +589,7 @@ func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actual return false } } else { - return checkEqualDifferentTypes(pass, nested, actualArg, handler, old, parentPointer) + return checkEqualDifferentTypes(pass, nested, actualArg, handler, parentPointer, reportBuilder) } case not: @@ -382,7 +598,7 @@ func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actual return false } - return checkEqualDifferentTypes(pass, nested, actualArg, handler, old, parentPointer) + return checkEqualDifferentTypes(pass, nested, actualArg, handler, parentPointer, reportBuilder) case haveValue: nested, ok := matcher.Args[0].(*ast.CallExpr) @@ -390,7 +606,7 @@ func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actual return false } - return checkEqualDifferentTypes(pass, nested, actualArg, handler, old, true) + return checkEqualDifferentTypes(pass, nested, actualArg, handler, true, reportBuilder) default: return false } @@ -414,7 +630,7 @@ func checkEqualDifferentTypes(pass *analysis.Pass, matcher *ast.CallExpr, actual return false } - reportNoFix(pass, matcher.Pos(), compareDifferentTypes, matcherFuncName, actualType, matcherType) + reportBuilder.AddIssue(false, compareDifferentTypes, matcherFuncName, actualType, matcherType) return true } @@ -459,7 +675,7 @@ func isImplementing(ifs, impl gotypes.Type) bool { } // be careful - never change origExp!!! only modify its clone, expr!!! -func checkPointerComparison(pass *analysis.Pass, config types.Config, origExp *ast.CallExpr, expr *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, oldExpr string) bool { +func checkPointerComparison(pass *analysis.Pass, config types.Config, origExp *ast.CallExpr, expr *ast.CallExpr, actualArg ast.Expr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { if !isPointer(pass, actualArg) { return false } @@ -506,20 +722,19 @@ func checkPointerComparison(pass *analysis.Pass, config types.Config, origExp *a return false } - handleAssertionOnly(pass, config, expr, handler, actualArg, oldExpr, false) + handleAssertionOnly(pass, config, expr, handler, actualArg, reportBuilder) args := []ast.Expr{astcopy.CallExpr(expr.Args[0].(*ast.CallExpr))} handler.ReplaceFunction(expr.Args[0].(*ast.CallExpr), ast.NewIdent(haveValue)) expr.Args[0].(*ast.CallExpr).Args = args - report(pass, expr, comparePointerToValue, oldExpr) + reportBuilder.AddIssue(true, comparePointerToValue) return true - } // check async assertion does not assert function call. This is a real bug in the test. In this case, the assertion is // done on the returned value, instead of polling the result of a function, for instance. -func checkAsyncAssertion(pass *analysis.Pass, config types.Config, expr *ast.CallExpr, actualExpr *ast.CallExpr, handler gomegahandler.Handler, oldExpr string) bool { +func checkAsyncAssertion(pass *analysis.Pass, config types.Config, expr *ast.CallExpr, actualExpr *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder, timePkg string) bool { funcName, ok := handler.GetActualFuncName(actualExpr) if !ok { return false @@ -565,19 +780,22 @@ func checkAsyncAssertion(pass *analysis.Pass, config types.Config, expr *ast.Cal actualExpr.Fun = call actualExpr.Args = fun.Args + actualExpr = actualExpr.Fun.(*ast.SelectorExpr).X.(*ast.CallExpr) } else { actualExpr.Args[funcIndex] = fun.Fun } - handleAssertionOnly(pass, config, expr, handler, actualExpr, oldExpr, false) - report(pass, expr, fmt.Sprintf(valueInEventually, funcName, funcName)+"; consider using `%s` instead", oldExpr) - return true + reportBuilder.AddIssue(true, valueInEventually, funcName, funcName) } } } + + if config.ValidateAsyncIntervals { + intervals.CheckIntervals(pass, expr, actualExpr, reportBuilder, handler, timePkg, funcIndex) + } } - handleAssertionOnly(pass, config, expr, handler, actualExpr, oldExpr, true) + handleAssertionOnly(pass, config, expr, handler, actualExpr, reportBuilder) return true } @@ -632,7 +850,7 @@ func startCheckComparison(exp *ast.CallExpr, handler gomegahandler.Handler) (*as return matcher, true } -func checkComparison(exp *ast.CallExpr, pass *analysis.Pass, matcher *ast.CallExpr, handler gomegahandler.Handler, first ast.Expr, second ast.Expr, op token.Token, oldExp string) bool { +func checkComparison(exp *ast.CallExpr, pass *analysis.Pass, matcher *ast.CallExpr, handler gomegahandler.Handler, first ast.Expr, second ast.Expr, op token.Token, reportBuilder *reports.Builder) bool { fun, ok := exp.Fun.(*ast.SelectorExpr) if !ok { return true @@ -664,7 +882,7 @@ func checkComparison(exp *ast.CallExpr, pass *analysis.Pass, matcher *ast.CallEx } call.Args = []ast.Expr{first} - report(pass, exp, wrongCompareWarningTemplate, oldExp) + reportBuilder.AddIssue(true, wrongCompareWarningTemplate) return false } @@ -676,7 +894,7 @@ func handleEqualComparison(pass *analysis.Pass, matcher *ast.CallExpr, first ast t := pass.TypesInfo.TypeOf(first) if gotypes.IsInterface(t) { handler.ReplaceFunction(matcher, ast.NewIdent(beIdenticalTo)) - } else if _, ok := t.(*gotypes.Pointer); ok { + } else if is[*gotypes.Pointer](t) { handler.ReplaceFunction(matcher, ast.NewIdent(beIdenticalTo)) } else { handler.ReplaceFunction(matcher, ast.NewIdent(equal)) @@ -686,7 +904,7 @@ func handleEqualComparison(pass *analysis.Pass, matcher *ast.CallExpr, first ast } } -func handleLenComparison(pass *analysis.Pass, exp *ast.CallExpr, matcher *ast.CallExpr, first ast.Expr, second ast.Expr, op token.Token, handler gomegahandler.Handler, oldExpr string) bool { +func handleLenComparison(pass *analysis.Pass, exp *ast.CallExpr, matcher *ast.CallExpr, first ast.Expr, second ast.Expr, op token.Token, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { switch op { case token.EQL: case token.NEQ: @@ -713,23 +931,58 @@ func handleLenComparison(pass *analysis.Pass, exp *ast.CallExpr, matcher *ast.Ca fun := handler.GetActualExpr(exp.Fun.(*ast.SelectorExpr)) fun.Args = []ast.Expr{val} - report(pass, exp, wrongLengthWarningTemplate, oldExpr) + reportBuilder.AddIssue(true, wrongLengthWarningTemplate) + return true +} + +func handleCapComparison(exp *ast.CallExpr, matcher *ast.CallExpr, first ast.Expr, second ast.Expr, op token.Token, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { + switch op { + case token.EQL: + case token.NEQ: + reverseAssertionFuncLogic(exp) + default: + return false + } + + eql := ast.NewIdent(haveCap) + matcher.Args = []ast.Expr{second} + + handler.ReplaceFunction(matcher, eql) + firstLen, ok := first.(*ast.CallExpr) // assuming it's len() + if !ok { + return false // should never happen + } + + val := firstLen.Args[0] + fun := handler.GetActualExpr(exp.Fun.(*ast.SelectorExpr)) + fun.Args = []ast.Expr{val} + + reportBuilder.AddIssue(true, wrongCapWarningTemplate) return true } // Check if the "actual" argument is a call to the golang built-in len() function func isActualIsLenFunc(actualArg ast.Expr) bool { + return checkActualFuncName(actualArg, "len") +} + +// Check if the "actual" argument is a call to the golang built-in len() function +func isActualIsCapFunc(actualArg ast.Expr) bool { + return checkActualFuncName(actualArg, "cap") +} + +func checkActualFuncName(actualArg ast.Expr, name string) bool { lenArgExp, ok := actualArg.(*ast.CallExpr) if !ok { return false } lenFunc, ok := lenArgExp.Fun.(*ast.Ident) - return ok && lenFunc.Name == "len" + return ok && lenFunc.Name == name } // Check if matcher function is in one of the patterns we want to avoid -func checkLengthMatcher(exp *ast.CallExpr, pass *analysis.Pass, handler gomegahandler.Handler, oldExp string) bool { +func checkLengthMatcher(exp *ast.CallExpr, pass *analysis.Pass, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { matcher, ok := exp.Args[0].(*ast.CallExpr) if !ok { return true @@ -742,20 +995,20 @@ func checkLengthMatcher(exp *ast.CallExpr, pass *analysis.Pass, handler gomegaha switch matcherFuncName { case equal: - handleEqualMatcher(matcher, pass, exp, handler, oldExp) + handleEqualLenMatcher(matcher, pass, exp, handler, reportBuilder) return false case beZero: - handleBeZero(pass, exp, handler, oldExp) + handleBeZero(exp, handler, reportBuilder) return false case beNumerically: - return handleBeNumerically(matcher, pass, exp, handler, oldExp) + return handleBeNumerically(matcher, pass, exp, handler, reportBuilder) case not: reverseAssertionFuncLogic(exp) exp.Args[0] = exp.Args[0].(*ast.CallExpr).Args[0] - return checkLengthMatcher(exp, pass, handler, oldExp) + return checkLengthMatcher(exp, pass, handler, reportBuilder) default: return true @@ -763,7 +1016,7 @@ func checkLengthMatcher(exp *ast.CallExpr, pass *analysis.Pass, handler gomegaha } // Check if matcher function is in one of the patterns we want to avoid -func checkNilMatcher(exp *ast.CallExpr, pass *analysis.Pass, nilable ast.Expr, handler gomegahandler.Handler, notEqual bool, oldExp string) bool { +func checkCapMatcher(exp *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { matcher, ok := exp.Args[0].(*ast.CallExpr) if !ok { return true @@ -776,19 +1029,53 @@ func checkNilMatcher(exp *ast.CallExpr, pass *analysis.Pass, nilable ast.Expr, h switch matcherFuncName { case equal: - handleEqualNilMatcher(matcher, pass, exp, handler, nilable, notEqual, oldExp) + handleEqualCapMatcher(matcher, exp, handler, reportBuilder) + return false + + case beZero: + handleCapBeZero(exp, handler, reportBuilder) + return false + + case beNumerically: + return handleCapBeNumerically(matcher, exp, handler, reportBuilder) + + case not: + reverseAssertionFuncLogic(exp) + exp.Args[0] = exp.Args[0].(*ast.CallExpr).Args[0] + return checkCapMatcher(exp, handler, reportBuilder) + + default: + return true + } +} + +// Check if matcher function is in one of the patterns we want to avoid +func checkNilMatcher(exp *ast.CallExpr, pass *analysis.Pass, nilable ast.Expr, handler gomegahandler.Handler, notEqual bool, reportBuilder *reports.Builder) bool { + matcher, ok := exp.Args[0].(*ast.CallExpr) + if !ok { + return true + } + + matcherFuncName, ok := handler.GetActualFuncName(matcher) + if !ok { + return true + } + + switch matcherFuncName { + case equal: + handleEqualNilMatcher(matcher, pass, exp, handler, nilable, notEqual, reportBuilder) case beTrue: - handleNilBeBoolMatcher(pass, exp, handler, nilable, notEqual, oldExp) + handleNilBeBoolMatcher(pass, exp, handler, nilable, notEqual, reportBuilder) case beFalse: reverseAssertionFuncLogic(exp) - handleNilBeBoolMatcher(pass, exp, handler, nilable, notEqual, oldExp) + handleNilBeBoolMatcher(pass, exp, handler, nilable, notEqual, reportBuilder) case not: reverseAssertionFuncLogic(exp) exp.Args[0] = exp.Args[0].(*ast.CallExpr).Args[0] - return checkNilMatcher(exp, pass, nilable, handler, notEqual, oldExp) + return checkNilMatcher(exp, pass, nilable, handler, notEqual, reportBuilder) default: return true @@ -796,7 +1083,7 @@ func checkNilMatcher(exp *ast.CallExpr, pass *analysis.Pass, nilable ast.Expr, h return false } -func checkNilError(pass *analysis.Pass, assertionExp *ast.CallExpr, handler gomegahandler.Handler, actualArg ast.Expr, oldExpr string) bool { +func checkNilError(pass *analysis.Pass, assertionExp *ast.CallExpr, handler gomegahandler.Handler, actualArg ast.Expr, reportBuilder *reports.Builder) bool { if len(assertionExp.Args) == 0 { return true } @@ -827,13 +1114,13 @@ func checkNilError(pass *analysis.Pass, assertionExp *ast.CallExpr, handler gome case not: reverseAssertionFuncLogic(assertionExp) assertionExp.Args[0] = assertionExp.Args[0].(*ast.CallExpr).Args[0] - return checkNilError(pass, assertionExp, handler, actualArg, oldExpr) + return checkNilError(pass, assertionExp, handler, actualArg, reportBuilder) default: return true } var newFuncName string - if _, ok := actualArg.(*ast.CallExpr); ok { + if is[*ast.CallExpr](actualArg) { newFuncName = succeed } else { reverseAssertionFuncLogic(assertionExp) @@ -843,7 +1130,7 @@ func checkNilError(pass *analysis.Pass, assertionExp *ast.CallExpr, handler gome handler.ReplaceFunction(equalFuncExpr, ast.NewIdent(newFuncName)) equalFuncExpr.Args = nil - report(pass, assertionExp, wrongErrWarningTemplate, oldExpr) + reportBuilder.AddIssue(true, wrongErrWarningTemplate) return false } @@ -854,7 +1141,7 @@ func checkNilError(pass *analysis.Pass, assertionExp *ast.CallExpr, handler gome // Equal(true) => BeTrue() // Equal(false) => BeFalse() // HaveLen(0) => BeEmpty() -func handleAssertionOnly(pass *analysis.Pass, config types.Config, expr *ast.CallExpr, handler gomegahandler.Handler, actualArg ast.Expr, oldExpr string, shouldReport bool) bool { +func handleAssertionOnly(pass *analysis.Pass, config types.Config, expr *ast.CallExpr, handler gomegahandler.Handler, actualArg ast.Expr, reportBuilder *reports.Builder) bool { if len(expr.Args) == 0 { return true } @@ -907,19 +1194,15 @@ func handleAssertionOnly(pass *analysis.Pass, config types.Config, expr *ast.Cal handler.ReplaceFunction(equalFuncExpr, ast.NewIdent(replacement)) equalFuncExpr.Args = nil - if shouldReport { - report(pass, expr, template, oldExpr) - } - + reportBuilder.AddIssue(true, template) return false case beFalse: if isNegativeAssertion(expr) { reverseAssertionFuncLogic(expr) handler.ReplaceFunction(equalFuncExpr, ast.NewIdent(beTrue)) - if shouldReport { - report(pass, expr, doubleNegativeWarningTemplate, oldExpr) - } + reportBuilder.AddIssue(true, doubleNegativeWarningTemplate) + return false } return false @@ -932,9 +1215,7 @@ func handleAssertionOnly(pass *analysis.Pass, config types.Config, expr *ast.Cal if isZero(pass, equalFuncExpr.Args[0]) { handler.ReplaceFunction(equalFuncExpr, ast.NewIdent(beEmpty)) equalFuncExpr.Args = nil - if shouldReport { - report(pass, expr, wrongLengthWarningTemplate, oldExpr) - } + reportBuilder.AddIssue(true, wrongLengthWarningTemplate) return false } } @@ -944,7 +1225,7 @@ func handleAssertionOnly(pass *analysis.Pass, config types.Config, expr *ast.Cal case not: reverseAssertionFuncLogic(expr) expr.Args[0] = expr.Args[0].(*ast.CallExpr).Args[0] - return handleAssertionOnly(pass, config, expr, handler, actualArg, oldExpr, shouldReport) + return handleAssertionOnly(pass, config, expr, handler, actualArg, reportBuilder) default: return true } @@ -1002,13 +1283,13 @@ func replaceLenActualArg(actualExpr *ast.CallExpr, handler gomegahandler.Handler switch name { case expect, omega: arg := actualExpr.Args[0] - if isActualIsLenFunc(arg) { + if isActualIsLenFunc(arg) || isActualIsCapFunc(arg) { // replace the len function call by its parameter, to create a fix suggestion actualExpr.Args[0] = arg.(*ast.CallExpr).Args[0] } case expectWithOffset: arg := actualExpr.Args[1] - if isActualIsLenFunc(arg) { + if isActualIsLenFunc(arg) || isActualIsCapFunc(arg) { // replace the len function call by its parameter, to create a fix suggestion actualExpr.Args[1] = arg.(*ast.CallExpr).Args[0] } @@ -1037,7 +1318,7 @@ func replaceNilActualArg(actualExpr *ast.CallExpr, handler gomegahandler.Handler } // For the BeNumerically matcher, we want to avoid the assertion of length to be > 0 or >= 1, or just == number -func handleBeNumerically(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, oldExp string) bool { +func handleBeNumerically(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { opExp, ok1 := matcher.Args[0].(*ast.BasicLit) valExp, ok2 := matcher.Args[1].(*ast.BasicLit) @@ -1049,20 +1330,45 @@ func handleBeNumerically(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.Ca reverseAssertionFuncLogic(exp) handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(beEmpty)) exp.Args[0].(*ast.CallExpr).Args = nil - reportLengthAssertion(pass, exp, handler, oldExp) - return false } else if op == `"=="` { chooseNumericMatcher(pass, exp, handler, valExp) - reportLengthAssertion(pass, exp, handler, oldExp) - - return false } else if op == `"!="` { reverseAssertionFuncLogic(exp) chooseNumericMatcher(pass, exp, handler, valExp) - reportLengthAssertion(pass, exp, handler, oldExp) + } else { + return true + } - return false + reportLengthAssertion(exp, handler, reportBuilder) + return false + } + return true +} + +// For the BeNumerically matcher, we want to avoid the assertion of length to be > 0 or >= 1, or just == number +func handleCapBeNumerically(matcher *ast.CallExpr, exp *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) bool { + opExp, ok1 := matcher.Args[0].(*ast.BasicLit) + valExp, ok2 := matcher.Args[1].(*ast.BasicLit) + + if ok1 && ok2 { + op := opExp.Value + val := valExp.Value + + if (op == `">"` && val == "0") || (op == `">="` && val == "1") { + reverseAssertionFuncLogic(exp) + handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(haveCap)) + exp.Args[0].(*ast.CallExpr).Args = []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: "0"}} + } else if op == `"=="` { + replaceNumericCapMatcher(exp, handler, valExp) + } else if op == `"!="` { + reverseAssertionFuncLogic(exp) + replaceNumericCapMatcher(exp, handler, valExp) + } else { + return true } + + reportCapAssertion(exp, handler, reportBuilder) + return false } return true } @@ -1078,6 +1384,12 @@ func chooseNumericMatcher(pass *analysis.Pass, exp *ast.CallExpr, handler gomega } } +func replaceNumericCapMatcher(exp *ast.CallExpr, handler gomegahandler.Handler, valExp ast.Expr) { + caller := exp.Args[0].(*ast.CallExpr) + handler.ReplaceFunction(caller, ast.NewIdent(haveCap)) + exp.Args[0].(*ast.CallExpr).Args = []ast.Expr{valExp} +} + func reverseAssertionFuncLogic(exp *ast.CallExpr) { assertionFunc := exp.Fun.(*ast.SelectorExpr).Sel assertionFunc.Name = reverseassertion.ChangeAssertionLogic(assertionFunc.Name) @@ -1088,7 +1400,7 @@ func isNegativeAssertion(exp *ast.CallExpr) bool { return reverseassertion.IsNegativeLogic(assertionFunc.Name) } -func handleEqualMatcher(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, oldExp string) { +func handleEqualLenMatcher(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) { equalTo, ok := matcher.Args[0].(*ast.BasicLit) if ok { chooseNumericMatcher(pass, exp, handler, equalTo) @@ -1096,16 +1408,29 @@ func handleEqualMatcher(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.Cal handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(haveLen)) exp.Args[0].(*ast.CallExpr).Args = []ast.Expr{matcher.Args[0]} } - reportLengthAssertion(pass, exp, handler, oldExp) + reportLengthAssertion(exp, handler, reportBuilder) +} + +func handleEqualCapMatcher(matcher *ast.CallExpr, exp *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) { + handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(haveCap)) + exp.Args[0].(*ast.CallExpr).Args = []ast.Expr{matcher.Args[0]} + reportCapAssertion(exp, handler, reportBuilder) } -func handleBeZero(pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, oldExp string) { +func handleBeZero(exp *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) { exp.Args[0].(*ast.CallExpr).Args = nil handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(beEmpty)) - reportLengthAssertion(pass, exp, handler, oldExp) + reportLengthAssertion(exp, handler, reportBuilder) } -func handleEqualNilMatcher(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, nilable ast.Expr, notEqual bool, oldExp string) { +func handleCapBeZero(exp *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) { + exp.Args[0].(*ast.CallExpr).Args = nil + handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(haveCap)) + exp.Args[0].(*ast.CallExpr).Args = []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: "0"}} + reportCapAssertion(exp, handler, reportBuilder) +} + +func handleEqualNilMatcher(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, nilable ast.Expr, notEqual bool, reportBuilder *reports.Builder) { equalTo, ok := matcher.Args[0].(*ast.Ident) if !ok { return @@ -1122,22 +1447,22 @@ func handleEqualNilMatcher(matcher *ast.CallExpr, pass *analysis.Pass, exp *ast. handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(newFuncName)) exp.Args[0].(*ast.CallExpr).Args = nil - reportNilAssertion(pass, exp, handler, nilable, notEqual, oldExp, isItError) + reportNilAssertion(exp, handler, nilable, notEqual, isItError, reportBuilder) } -func handleNilBeBoolMatcher(pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, nilable ast.Expr, notEqual bool, oldExp string) { +func handleNilBeBoolMatcher(pass *analysis.Pass, exp *ast.CallExpr, handler gomegahandler.Handler, nilable ast.Expr, notEqual bool, reportBuilder *reports.Builder) { newFuncName, isItError := handleNilComparisonErr(pass, exp, nilable) handler.ReplaceFunction(exp.Args[0].(*ast.CallExpr), ast.NewIdent(newFuncName)) exp.Args[0].(*ast.CallExpr).Args = nil - reportNilAssertion(pass, exp, handler, nilable, notEqual, oldExp, isItError) + reportNilAssertion(exp, handler, nilable, notEqual, isItError, reportBuilder) } func handleNilComparisonErr(pass *analysis.Pass, exp *ast.CallExpr, nilable ast.Expr) (string, bool) { newFuncName := beNil isItError := isExprError(pass, nilable) if isItError { - if _, ok := nilable.(*ast.CallExpr); ok { + if is[*ast.CallExpr](nilable) { newFuncName = succeed } else { reverseAssertionFuncLogic(exp) @@ -1156,14 +1481,21 @@ func isAssertionFunc(name string) bool { return false } -func reportLengthAssertion(pass *analysis.Pass, expr *ast.CallExpr, handler gomegahandler.Handler, oldExpr string) { +func reportLengthAssertion(expr *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) { actualExpr := handler.GetActualExpr(expr.Fun.(*ast.SelectorExpr)) replaceLenActualArg(actualExpr, handler) - report(pass, expr, wrongLengthWarningTemplate, oldExpr) + reportBuilder.AddIssue(true, wrongLengthWarningTemplate) } -func reportNilAssertion(pass *analysis.Pass, expr *ast.CallExpr, handler gomegahandler.Handler, nilable ast.Expr, notEqual bool, oldExpr string, isItError bool) { +func reportCapAssertion(expr *ast.CallExpr, handler gomegahandler.Handler, reportBuilder *reports.Builder) { + actualExpr := handler.GetActualExpr(expr.Fun.(*ast.SelectorExpr)) + replaceLenActualArg(actualExpr, handler) + + reportBuilder.AddIssue(true, wrongCapWarningTemplate) +} + +func reportNilAssertion(expr *ast.CallExpr, handler gomegahandler.Handler, nilable ast.Expr, notEqual bool, isItError bool, reportBuilder *reports.Builder) { actualExpr := handler.GetActualExpr(expr.Fun.(*ast.SelectorExpr)) changed := replaceNilActualArg(actualExpr, handler, nilable) if !changed { @@ -1178,27 +1510,7 @@ func reportNilAssertion(pass *analysis.Pass, expr *ast.CallExpr, handler gomegah template = wrongErrWarningTemplate } - report(pass, expr, template, oldExpr) -} - -func report(pass *analysis.Pass, expr ast.Expr, messageTemplate, oldExpr string) { - newExp := goFmt(pass.Fset, expr) - pass.Report(analysis.Diagnostic{ - Pos: expr.Pos(), - Message: fmt.Sprintf(messageTemplate, newExp), - SuggestedFixes: []analysis.SuggestedFix{ - { - Message: fmt.Sprintf("should replace %s with %s", oldExpr, newExp), - TextEdits: []analysis.TextEdit{ - { - Pos: expr.Pos(), - End: expr.End(), - NewText: []byte(newExp), - }, - }, - }, - }, - }) + reportBuilder.AddIssue(true, template) } func reportNewName(pass *analysis.Pass, id *ast.Ident, newName string, messageTemplate, oldExpr string) { @@ -1265,7 +1577,7 @@ func isComparison(pass *analysis.Pass, actualArg ast.Expr) (ast.Expr, ast.Expr, case *ast.Ident: // check if const info, ok := pass.TypesInfo.Types[realFirst] if ok { - if _, ok := info.Type.(*gotypes.Basic); ok && info.Value != nil { + if is[*gotypes.Basic](info.Type) && info.Value != nil { replace = true } } @@ -1297,28 +1609,18 @@ func goFmt(fset *token.FileSet, x ast.Expr) string { return b.String() } -var errorType *gotypes.Interface - -func init() { - errorType = gotypes.Universe.Lookup("error").Type().Underlying().(*gotypes.Interface) -} - -func isError(t gotypes.Type) bool { - return gotypes.Implements(t, errorType) -} - func isExprError(pass *analysis.Pass, expr ast.Expr) bool { actualArgType := pass.TypesInfo.TypeOf(expr) switch t := actualArgType.(type) { case *gotypes.Named: - if isError(actualArgType) { + if interfaces.ImplementsError(actualArgType) { return true } case *gotypes.Tuple: if t.Len() > 0 { switch t0 := t.At(0).Type().(type) { case *gotypes.Named, *gotypes.Pointer: - if isError(t0) { + if interfaces.ImplementsError(t0) { return true } } @@ -1329,8 +1631,7 @@ func isExprError(pass *analysis.Pass, expr ast.Expr) bool { func isPointer(pass *analysis.Pass, expr ast.Expr) bool { t := pass.TypesInfo.TypeOf(expr) - _, ok := t.(*gotypes.Pointer) - return ok + return is[*gotypes.Pointer](t) } func isInterface(pass *analysis.Pass, expr ast.Expr) bool { @@ -1351,22 +1652,22 @@ func isNumeric(pass *analysis.Pass, node ast.Expr) bool { func checkNoAssertion(pass *analysis.Pass, expr *ast.CallExpr, handler gomegahandler.Handler) { funcName, ok := handler.GetActualFuncName(expr) if ok { - if isActualFunc(funcName) { - reportNoFix(pass, expr.Pos(), missingAssertionMessage, funcName) - } else if isActualAsyncFunc(funcName) { - reportNoFix(pass, expr.Pos(), missingAsyncAssertionMessage, funcName) + var allowedFunction string + switch funcName { + case expect, expectWithOffset: + allowedFunction = `"To()", "ToNot()" or "NotTo()"` + case eventually, eventuallyWithOffset, consistently, consistentlyWithOffset: + allowedFunction = `"Should()" or "ShouldNot()"` + case omega: + allowedFunction = `"Should()", "To()", "ShouldNot()", "ToNot()" or "NotTo()"` + default: + return } + reportNoFix(pass, expr.Pos(), missingAssertionMessage, funcName, allowedFunction) } } -func isActualFunc(name string) bool { - return name == expect || name == expectWithOffset -} - -func isActualAsyncFunc(name string) bool { - switch name { - case eventually, eventuallyWithOffset, consistently, consistentlyWithOffset: - return true - } - return false +func is[T any](x any) bool { + _, matchType := x.(T) + return matchType } diff --git a/tools/vendor/github.com/nunnatsa/ginkgolinter/types/config.go b/tools/vendor/github.com/nunnatsa/ginkgolinter/types/config.go index 6de22738d..b6838e524 100644 --- a/tools/vendor/github.com/nunnatsa/ginkgolinter/types/config.go +++ b/tools/vendor/github.com/nunnatsa/ginkgolinter/types/config.go @@ -1,9 +1,8 @@ package types import ( - "strings" - "go/ast" + "strings" ) const ( @@ -18,14 +17,17 @@ const ( ) type Config struct { - SuppressLen Boolean - SuppressNil Boolean - SuppressErr Boolean - SuppressCompare Boolean - SuppressAsync Boolean - ForbidFocus Boolean - SuppressTypeCompare Boolean - AllowHaveLen0 Boolean + SuppressLen Boolean + SuppressNil Boolean + SuppressErr Boolean + SuppressCompare Boolean + SuppressAsync Boolean + ForbidFocus Boolean + SuppressTypeCompare Boolean + AllowHaveLen0 Boolean + ForceExpectTo Boolean + ValidateAsyncIntervals Boolean + ForbidSpecPollution Boolean } func (s *Config) AllTrue() bool { @@ -34,14 +36,17 @@ func (s *Config) AllTrue() bool { func (s *Config) Clone() Config { return Config{ - SuppressLen: s.SuppressLen, - SuppressNil: s.SuppressNil, - SuppressErr: s.SuppressErr, - SuppressCompare: s.SuppressCompare, - SuppressAsync: s.SuppressAsync, - ForbidFocus: s.ForbidFocus, - SuppressTypeCompare: s.SuppressTypeCompare, - AllowHaveLen0: s.AllowHaveLen0, + SuppressLen: s.SuppressLen, + SuppressNil: s.SuppressNil, + SuppressErr: s.SuppressErr, + SuppressCompare: s.SuppressCompare, + SuppressAsync: s.SuppressAsync, + ForbidFocus: s.ForbidFocus, + SuppressTypeCompare: s.SuppressTypeCompare, + AllowHaveLen0: s.AllowHaveLen0, + ForceExpectTo: s.ForceExpectTo, + ValidateAsyncIntervals: s.ValidateAsyncIntervals, + ForbidSpecPollution: s.ForbidSpecPollution, } } diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/.gitignore b/tools/vendor/github.com/pelletier/go-toml/v2/.gitignore index a69e2b0eb..4b7c4eda3 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/.gitignore +++ b/tools/vendor/github.com/pelletier/go-toml/v2/.gitignore @@ -3,4 +3,5 @@ fuzz/ cmd/tomll/tomll cmd/tomljson/tomljson cmd/tomltestgen/tomltestgen -dist \ No newline at end of file +dist +tests/ diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml b/tools/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml index 3aa1840ec..1d8b69e65 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml +++ b/tools/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml @@ -18,6 +18,7 @@ builds: - linux_amd64 - linux_arm64 - linux_arm + - linux_riscv64 - windows_amd64 - windows_arm64 - windows_arm @@ -37,6 +38,7 @@ builds: - linux_amd64 - linux_arm64 - linux_arm + - linux_riscv64 - windows_amd64 - windows_arm64 - windows_arm @@ -55,6 +57,7 @@ builds: targets: - linux_amd64 - linux_arm64 + - linux_riscv64 - linux_arm - windows_amd64 - windows_arm64 diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/CONTRIBUTING.md b/tools/vendor/github.com/pelletier/go-toml/v2/CONTRIBUTING.md index 04dd12bcb..96ecf9e2b 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/CONTRIBUTING.md +++ b/tools/vendor/github.com/pelletier/go-toml/v2/CONTRIBUTING.md @@ -165,25 +165,22 @@ Checklist: ### New release -1. Decide on the next version number. Use semver. -2. Generate release notes using [`gh`][gh]. Example: +1. Decide on the next version number. Use semver. Review commits since last + version to assess. +2. Tag release. For example: ``` -$ gh api -X POST \ - -F tag_name='v2.0.0-beta.5' \ - -F target_commitish='v2' \ - -F previous_tag_name='v2.0.0-beta.4' \ - --jq '.body' \ - repos/pelletier/go-toml/releases/generate-notes +git checkout v2 +git pull +git tag v2.2.0 +git push --tags ``` -3. Look for "Other changes". That would indicate a pull request not labeled - properly. Tweak labels and pull request titles until changelog looks good for - users. -4. [Draft new release][new-release]. -5. Fill tag and target with the same value used to generate the changelog. -6. Set title to the new tag value. -7. Paste the generated changelog. -8. Check "create discussion", in the "Releases" category. -9. Check pre-release if new version is an alpha or beta. +3. CI automatically builds a draft Github release. Review it and edit as + necessary. Look for "Other changes". That would indicate a pull request not + labeled properly. Tweak labels and pull request titles until changelog looks + good for users. +4. Check "create discussion" box, in the "Releases" category. +5. If new version is an alpha or beta only, check pre-release box. + [issues-tracker]: https://github.com/pelletier/go-toml/issues [bug-report]: https://github.com/pelletier/go-toml/issues/new?template=bug_report.md diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/LICENSE b/tools/vendor/github.com/pelletier/go-toml/v2/LICENSE index 6839d51cd..991e2ae96 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/LICENSE +++ b/tools/vendor/github.com/pelletier/go-toml/v2/LICENSE @@ -1,6 +1,7 @@ The MIT License (MIT) -Copyright (c) 2013 - 2022 Thomas Pelletier, Eric Anderton +go-toml v2 +Copyright (c) 2021 - 2023 Thomas Pelletier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/README.md b/tools/vendor/github.com/pelletier/go-toml/v2/README.md index a63c3a796..d964b25fe 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/README.md +++ b/tools/vendor/github.com/pelletier/go-toml/v2/README.md @@ -45,16 +45,15 @@ to check for typos. [See example in the documentation][strict]. ### Contextualized errors -When most decoding errors occur, go-toml returns [`DecodeError`][decode-err]), +When most decoding errors occur, go-toml returns [`DecodeError`][decode-err], which contains a human readable contextualized version of the error. For example: ``` -2| key1 = "value1" -3| key2 = "missing2" - | ~~~~ missing field -4| key3 = "missing3" -5| key4 = "value4" +1| [server] +2| path = 100 + | ~~~ cannot decode TOML integer into struct field toml_test.Server.Path of type string +3| port = 50 ``` [decode-err]: https://pkg.go.dev/github.com/pelletier/go-toml/v2#DecodeError @@ -73,15 +72,35 @@ representation. [tlt]: https://pkg.go.dev/github.com/pelletier/go-toml/v2#LocalTime [tldt]: https://pkg.go.dev/github.com/pelletier/go-toml/v2#LocalDateTime +### Commented config + +Since TOML is often used for configuration files, go-toml can emit documents +annotated with [comments and commented-out values][comments-example]. For +example, it can generate the following file: + +```toml +# Host IP to connect to. +host = '127.0.0.1' +# Port of the remote server. +port = 4242 + +# Encryption parameters (optional) +# [TLS] +# cipher = 'AEAD-AES128-GCM-SHA256' +# version = 'TLS 1.3' +``` + +[comments-example]: https://pkg.go.dev/github.com/pelletier/go-toml/v2#example-Marshal-Commented + ## Getting started Given the following struct, let's see how to read it and write it as TOML: ```go type MyConfig struct { - Version int - Name string - Tags []string + Version int + Name string + Tags []string } ``` @@ -100,7 +119,7 @@ tags = ["go", "toml"] var cfg MyConfig err := toml.Unmarshal([]byte(doc), &cfg) if err != nil { - panic(err) + panic(err) } fmt.Println("version:", cfg.Version) fmt.Println("name:", cfg.Name) @@ -121,14 +140,14 @@ as a TOML document: ```go cfg := MyConfig{ - Version: 2, - Name: "go-toml", - Tags: []string{"go", "toml"}, + Version: 2, + Name: "go-toml", + Tags: []string{"go", "toml"}, } b, err := toml.Marshal(cfg) if err != nil { - panic(err) + panic(err) } fmt.Println(string(b)) @@ -140,22 +159,33 @@ fmt.Println(string(b)) [marshal]: https://pkg.go.dev/github.com/pelletier/go-toml/v2#Marshal +## Unstable API + +This API does not yet follow the backward compatibility guarantees of this +library. They provide early access to features that may have rough edges or an +API subject to change. + +### Parser + +Parser is the unstable API that allows iterative parsing of a TOML document at +the AST level. See https://pkg.go.dev/github.com/pelletier/go-toml/v2/unstable. + ## Benchmarks Execution time speedup compared to other Go TOML libraries: - - - - - - - - - - - + + + + + + + + + + +
Benchmarkgo-toml v1BurntSushi/toml
Marshal/HugoFrontMatter-21.9x1.9x
Marshal/ReferenceFile/map-21.7x1.8x
Marshal/ReferenceFile/struct-22.2x2.5x
Unmarshal/HugoFrontMatter-22.9x2.9x
Unmarshal/ReferenceFile/map-22.6x2.9x
Unmarshal/ReferenceFile/struct-24.4x5.3x
Benchmarkgo-toml v1BurntSushi/toml
Marshal/HugoFrontMatter-21.9x2.2x
Marshal/ReferenceFile/map-21.7x2.1x
Marshal/ReferenceFile/struct-22.2x3.0x
Unmarshal/HugoFrontMatter-22.9x2.7x
Unmarshal/ReferenceFile/map-22.6x2.7x
Unmarshal/ReferenceFile/struct-24.6x5.1x
See more

The table above has the results of the most common use-cases. The table below @@ -163,22 +193,22 @@ contains the results of all benchmarks, including unrealistic ones. It is provided for completeness.

- - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + +
Benchmarkgo-toml v1BurntSushi/toml
Marshal/SimpleDocument/map-21.8x2.9x
Marshal/SimpleDocument/struct-22.7x4.2x
Unmarshal/SimpleDocument/map-24.5x3.1x
Unmarshal/SimpleDocument/struct-26.2x3.9x
UnmarshalDataset/example-23.1x3.5x
UnmarshalDataset/code-22.3x3.1x
UnmarshalDataset/twitter-22.5x2.6x
UnmarshalDataset/citm_catalog-22.1x2.2x
UnmarshalDataset/canada-21.6x1.3x
UnmarshalDataset/config-24.3x3.2x
[Geo mean]2.7x2.8x
Benchmarkgo-toml v1BurntSushi/toml
Marshal/SimpleDocument/map-21.8x2.7x
Marshal/SimpleDocument/struct-22.7x3.8x
Unmarshal/SimpleDocument/map-23.8x3.0x
Unmarshal/SimpleDocument/struct-25.6x4.1x
UnmarshalDataset/example-23.0x3.2x
UnmarshalDataset/code-22.3x2.9x
UnmarshalDataset/twitter-22.6x2.7x
UnmarshalDataset/citm_catalog-22.2x2.3x
UnmarshalDataset/canada-21.8x1.5x
UnmarshalDataset/config-24.1x2.9x
geomean2.7x2.8x

This table can be generated with ./ci.sh benchmark -a -html.

@@ -203,24 +233,24 @@ Go-toml provides three handy command line tools: * `tomljson`: Reads a TOML file and outputs its JSON representation. - ``` - $ go install github.com/pelletier/go-toml/v2/cmd/tomljson@latest - $ tomljson --help - ``` + ``` + $ go install github.com/pelletier/go-toml/v2/cmd/tomljson@latest + $ tomljson --help + ``` * `jsontoml`: Reads a JSON file and outputs a TOML representation. - ``` - $ go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest - $ jsontoml --help - ``` + ``` + $ go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest + $ jsontoml --help + ``` * `tomll`: Lints and reformats a TOML file. - ``` - $ go install github.com/pelletier/go-toml/v2/cmd/tomll@latest - $ tomll --help - ``` + ``` + $ go install github.com/pelletier/go-toml/v2/cmd/tomll@latest + $ tomll --help + ``` ### Docker image @@ -231,7 +261,7 @@ Those tools are also available as a [Docker image][docker]. For example, to use docker run -i ghcr.io/pelletier/go-toml:v2 tomljson < example.toml ``` -Multiple versions are availble on [ghcr.io][docker]. +Multiple versions are available on [ghcr.io][docker]. [docker]: https://github.com/pelletier/go-toml/pkgs/container/go-toml @@ -263,16 +293,16 @@ element in the interface to decode the object. For example: ```go type inner struct { - B interface{} + B interface{} } type doc struct { - A interface{} + A interface{} } d := doc{ - A: inner{ - B: "Before", - }, + A: inner{ + B: "Before", + }, } data := ` @@ -311,7 +341,7 @@ contained in the doc is superior to the capacity of the array. For example: ```go type doc struct { - A [2]string + A [2]string } d := doc{} err := toml.Unmarshal([]byte(`A = ["one", "two", "many"]`), &d) @@ -486,27 +516,20 @@ is not necessary anymore. V1 used to provide multiple struct tags: `comment`, `commented`, `multiline`, `toml`, and `omitempty`. To behave more like the standard library, v2 has merged -`toml`, `multiline`, and `omitempty`. For example: +`toml`, `multiline`, `commented`, and `omitempty`. For example: ```go type doc struct { // v1 - F string `toml:"field" multiline:"true" omitempty:"true"` + F string `toml:"field" multiline:"true" omitempty:"true" commented:"true"` // v2 - F string `toml:"field,multiline,omitempty"` + F string `toml:"field,multiline,omitempty,commented"` } ``` Has a result, the `Encoder.SetTag*` methods have been removed, as there is just one tag now. - -#### `commented` tag has been removed - -There is no replacement for the `commented` tag. This feature would be better -suited in a proper document model for go-toml v2, which has been [cut from -scope][nodoc] at the moment. - #### `Encoder.ArraysWithOneElementPerLine` has been renamed The new name is `Encoder.SetArraysMultiline`. The behavior should be the same. @@ -542,10 +565,11 @@ complete solutions exist out there. ## Versioning -Go-toml follows [Semantic Versioning](http://semver.org/). The supported version -of [TOML](https://github.com/toml-lang/toml) is indicated at the beginning of -this document. The last two major versions of Go are supported -(see [Go Release Policy](https://golang.org/doc/devel/release.html#policy)). +Expect for parts explicitely marked otherwise, go-toml follows [Semantic +Versioning](https://semver.org). The supported version of +[TOML](https://github.com/toml-lang/toml) is indicated at the beginning of this +document. The last two major versions of Go are supported (see [Go Release +Policy](https://golang.org/doc/devel/release.html#policy)). ## License diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/SECURITY.md b/tools/vendor/github.com/pelletier/go-toml/v2/SECURITY.md index b2f21cfc9..d4d554fda 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/SECURITY.md +++ b/tools/vendor/github.com/pelletier/go-toml/v2/SECURITY.md @@ -2,9 +2,6 @@ ## Supported Versions -Use this section to tell people about which versions of your project are -currently being supported with security updates. - | Version | Supported | | ---------- | ------------------ | | Latest 2.x | :white_check_mark: | diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/ci.sh b/tools/vendor/github.com/pelletier/go-toml/v2/ci.sh index d916c5f23..86217a9b0 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/ci.sh +++ b/tools/vendor/github.com/pelletier/go-toml/v2/ci.sh @@ -77,8 +77,9 @@ cover() { pushd "$dir" go test -covermode=atomic -coverpkg=./... -coverprofile=coverage.out.tmp ./... - cat coverage.out.tmp | grep -v testsuite | grep -v tomltestgen | grep -v gotoml-test-decoder > coverage.out + grep -Ev '(fuzz|testsuite|tomltestgen|gotoml-test-decoder|gotoml-test-encoder)' coverage.out.tmp > coverage.out go tool cover -func=coverage.out + echo "Coverage profile for ${branch}: ${dir}/coverage.out" >&2 popd if [ "${branch}" != "HEAD" ]; then @@ -151,7 +152,7 @@ bench() { fi export GOMAXPROCS=2 - nice -n -19 taskset --cpu-list 0,1 go test '-bench=^Benchmark(Un)?[mM]arshal' -count=5 -run=Nothing ./... | tee "${out}" + go test '-bench=^Benchmark(Un)?[mM]arshal' -count=10 -run=Nothing ./... | tee "${out}" popd if [ "${branch}" != "HEAD" ]; then @@ -160,10 +161,12 @@ bench() { } fmktemp() { - if mktemp --version|grep GNU >/dev/null; then - mktemp --suffix=-$1; + if mktemp --version &> /dev/null; then + # GNU + mktemp --suffix=-$1 else - mktemp -t $1; + # BSD + mktemp -t $1 fi } @@ -183,12 +186,14 @@ with open(sys.argv[1]) as f: lines.append(line.split(',')) results = [] -for line in reversed(lines[1:]): +for line in reversed(lines[2:]): + if len(line) < 8 or line[0] == "": + continue v2 = float(line[1]) results.append([ line[0].replace("-32", ""), "%.1fx" % (float(line[3])/v2), # v1 - "%.1fx" % (float(line[5])/v2), # bs + "%.1fx" % (float(line[7])/v2), # bs ]) # move geomean to the end results.append(results[0]) @@ -259,10 +264,10 @@ benchmark() { if [ "$1" = "-html" ]; then tmpcsv=`fmktemp csv` - benchstat -csv -geomean go-toml-v2.txt go-toml-v1.txt bs-toml.txt > $tmpcsv + benchstat -format csv go-toml-v2.txt go-toml-v1.txt bs-toml.txt > $tmpcsv benchstathtml $tmpcsv else - benchstat -geomean go-toml-v2.txt go-toml-v1.txt bs-toml.txt + benchstat go-toml-v2.txt go-toml-v1.txt bs-toml.txt fi rm -f go-toml-v2.txt go-toml-v1.txt bs-toml.txt diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/decode.go b/tools/vendor/github.com/pelletier/go-toml/v2/decode.go index 4af965360..f0ec3b170 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/decode.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/decode.go @@ -5,6 +5,8 @@ import ( "math" "strconv" "time" + + "github.com/pelletier/go-toml/v2/unstable" ) func parseInteger(b []byte) (int64, error) { @@ -32,7 +34,7 @@ func parseLocalDate(b []byte) (LocalDate, error) { var date LocalDate if len(b) != 10 || b[4] != '-' || b[7] != '-' { - return date, newDecodeError(b, "dates are expected to have the format YYYY-MM-DD") + return date, unstable.NewParserError(b, "dates are expected to have the format YYYY-MM-DD") } var err error @@ -53,7 +55,7 @@ func parseLocalDate(b []byte) (LocalDate, error) { } if !isValidDate(date.Year, date.Month, date.Day) { - return LocalDate{}, newDecodeError(b, "impossible date") + return LocalDate{}, unstable.NewParserError(b, "impossible date") } return date, nil @@ -64,7 +66,7 @@ func parseDecimalDigits(b []byte) (int, error) { for i, c := range b { if c < '0' || c > '9' { - return 0, newDecodeError(b[i:i+1], "expected digit (0-9)") + return 0, unstable.NewParserError(b[i:i+1], "expected digit (0-9)") } v *= 10 v += int(c - '0') @@ -97,7 +99,7 @@ func parseDateTime(b []byte) (time.Time, error) { } else { const dateTimeByteLen = 6 if len(b) != dateTimeByteLen { - return time.Time{}, newDecodeError(b, "invalid date-time timezone") + return time.Time{}, unstable.NewParserError(b, "invalid date-time timezone") } var direction int switch b[0] { @@ -106,11 +108,11 @@ func parseDateTime(b []byte) (time.Time, error) { case '+': direction = +1 default: - return time.Time{}, newDecodeError(b[:1], "invalid timezone offset character") + return time.Time{}, unstable.NewParserError(b[:1], "invalid timezone offset character") } if b[3] != ':' { - return time.Time{}, newDecodeError(b[3:4], "expected a : separator") + return time.Time{}, unstable.NewParserError(b[3:4], "expected a : separator") } hours, err := parseDecimalDigits(b[1:3]) @@ -118,7 +120,7 @@ func parseDateTime(b []byte) (time.Time, error) { return time.Time{}, err } if hours > 23 { - return time.Time{}, newDecodeError(b[:1], "invalid timezone offset hours") + return time.Time{}, unstable.NewParserError(b[:1], "invalid timezone offset hours") } minutes, err := parseDecimalDigits(b[4:6]) @@ -126,7 +128,7 @@ func parseDateTime(b []byte) (time.Time, error) { return time.Time{}, err } if minutes > 59 { - return time.Time{}, newDecodeError(b[:1], "invalid timezone offset minutes") + return time.Time{}, unstable.NewParserError(b[:1], "invalid timezone offset minutes") } seconds := direction * (hours*3600 + minutes*60) @@ -139,7 +141,7 @@ func parseDateTime(b []byte) (time.Time, error) { } if len(b) > 0 { - return time.Time{}, newDecodeError(b, "extra bytes at the end of the timezone") + return time.Time{}, unstable.NewParserError(b, "extra bytes at the end of the timezone") } t := time.Date( @@ -160,7 +162,7 @@ func parseLocalDateTime(b []byte) (LocalDateTime, []byte, error) { const localDateTimeByteMinLen = 11 if len(b) < localDateTimeByteMinLen { - return dt, nil, newDecodeError(b, "local datetimes are expected to have the format YYYY-MM-DDTHH:MM:SS[.NNNNNNNNN]") + return dt, nil, unstable.NewParserError(b, "local datetimes are expected to have the format YYYY-MM-DDTHH:MM:SS[.NNNNNNNNN]") } date, err := parseLocalDate(b[:10]) @@ -171,7 +173,7 @@ func parseLocalDateTime(b []byte) (LocalDateTime, []byte, error) { sep := b[10] if sep != 'T' && sep != ' ' && sep != 't' { - return dt, nil, newDecodeError(b[10:11], "datetime separator is expected to be T or a space") + return dt, nil, unstable.NewParserError(b[10:11], "datetime separator is expected to be T or a space") } t, rest, err := parseLocalTime(b[11:]) @@ -195,7 +197,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) { // check if b matches to have expected format HH:MM:SS[.NNNNNN] const localTimeByteLen = 8 if len(b) < localTimeByteLen { - return t, nil, newDecodeError(b, "times are expected to have the format HH:MM:SS[.NNNNNN]") + return t, nil, unstable.NewParserError(b, "times are expected to have the format HH:MM:SS[.NNNNNN]") } var err error @@ -206,10 +208,10 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) { } if t.Hour > 23 { - return t, nil, newDecodeError(b[0:2], "hour cannot be greater 23") + return t, nil, unstable.NewParserError(b[0:2], "hour cannot be greater 23") } if b[2] != ':' { - return t, nil, newDecodeError(b[2:3], "expecting colon between hours and minutes") + return t, nil, unstable.NewParserError(b[2:3], "expecting colon between hours and minutes") } t.Minute, err = parseDecimalDigits(b[3:5]) @@ -217,10 +219,10 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) { return t, nil, err } if t.Minute > 59 { - return t, nil, newDecodeError(b[3:5], "minutes cannot be greater 59") + return t, nil, unstable.NewParserError(b[3:5], "minutes cannot be greater 59") } if b[5] != ':' { - return t, nil, newDecodeError(b[5:6], "expecting colon between minutes and seconds") + return t, nil, unstable.NewParserError(b[5:6], "expecting colon between minutes and seconds") } t.Second, err = parseDecimalDigits(b[6:8]) @@ -229,7 +231,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) { } if t.Second > 60 { - return t, nil, newDecodeError(b[6:8], "seconds cannot be greater 60") + return t, nil, unstable.NewParserError(b[6:8], "seconds cannot be greater 60") } b = b[8:] @@ -242,7 +244,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) { for i, c := range b[1:] { if !isDigit(c) { if i == 0 { - return t, nil, newDecodeError(b[0:1], "need at least one digit after fraction point") + return t, nil, unstable.NewParserError(b[0:1], "need at least one digit after fraction point") } break } @@ -266,7 +268,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) { } if precision == 0 { - return t, nil, newDecodeError(b[:1], "nanoseconds need at least one digit") + return t, nil, unstable.NewParserError(b[:1], "nanoseconds need at least one digit") } t.Nanosecond = frac * nspow[precision] @@ -289,24 +291,24 @@ func parseFloat(b []byte) (float64, error) { } if cleaned[0] == '.' { - return 0, newDecodeError(b, "float cannot start with a dot") + return 0, unstable.NewParserError(b, "float cannot start with a dot") } if cleaned[len(cleaned)-1] == '.' { - return 0, newDecodeError(b, "float cannot end with a dot") + return 0, unstable.NewParserError(b, "float cannot end with a dot") } dotAlreadySeen := false for i, c := range cleaned { if c == '.' { if dotAlreadySeen { - return 0, newDecodeError(b[i:i+1], "float can have at most one decimal point") + return 0, unstable.NewParserError(b[i:i+1], "float can have at most one decimal point") } if !isDigit(cleaned[i-1]) { - return 0, newDecodeError(b[i-1:i+1], "float decimal point must be preceded by a digit") + return 0, unstable.NewParserError(b[i-1:i+1], "float decimal point must be preceded by a digit") } if !isDigit(cleaned[i+1]) { - return 0, newDecodeError(b[i:i+2], "float decimal point must be followed by a digit") + return 0, unstable.NewParserError(b[i:i+2], "float decimal point must be followed by a digit") } dotAlreadySeen = true } @@ -316,13 +318,13 @@ func parseFloat(b []byte) (float64, error) { if cleaned[0] == '+' || cleaned[0] == '-' { start = 1 } - if cleaned[start] == '0' && isDigit(cleaned[start+1]) { - return 0, newDecodeError(b, "float integer part cannot have leading zeroes") + if cleaned[start] == '0' && len(cleaned) > start+1 && isDigit(cleaned[start+1]) { + return 0, unstable.NewParserError(b, "float integer part cannot have leading zeroes") } f, err := strconv.ParseFloat(string(cleaned), 64) if err != nil { - return 0, newDecodeError(b, "unable to parse float: %w", err) + return 0, unstable.NewParserError(b, "unable to parse float: %w", err) } return f, nil @@ -336,7 +338,7 @@ func parseIntHex(b []byte) (int64, error) { i, err := strconv.ParseInt(string(cleaned), 16, 64) if err != nil { - return 0, newDecodeError(b, "couldn't parse hexadecimal number: %w", err) + return 0, unstable.NewParserError(b, "couldn't parse hexadecimal number: %w", err) } return i, nil @@ -350,7 +352,7 @@ func parseIntOct(b []byte) (int64, error) { i, err := strconv.ParseInt(string(cleaned), 8, 64) if err != nil { - return 0, newDecodeError(b, "couldn't parse octal number: %w", err) + return 0, unstable.NewParserError(b, "couldn't parse octal number: %w", err) } return i, nil @@ -364,7 +366,7 @@ func parseIntBin(b []byte) (int64, error) { i, err := strconv.ParseInt(string(cleaned), 2, 64) if err != nil { - return 0, newDecodeError(b, "couldn't parse binary number: %w", err) + return 0, unstable.NewParserError(b, "couldn't parse binary number: %w", err) } return i, nil @@ -387,12 +389,12 @@ func parseIntDec(b []byte) (int64, error) { } if len(cleaned) > startIdx+1 && cleaned[startIdx] == '0' { - return 0, newDecodeError(b, "leading zero not allowed on decimal number") + return 0, unstable.NewParserError(b, "leading zero not allowed on decimal number") } i, err := strconv.ParseInt(string(cleaned), 10, 64) if err != nil { - return 0, newDecodeError(b, "couldn't parse decimal number: %w", err) + return 0, unstable.NewParserError(b, "couldn't parse decimal number: %w", err) } return i, nil @@ -409,11 +411,11 @@ func checkAndRemoveUnderscoresIntegers(b []byte) ([]byte, error) { } if b[start] == '_' { - return nil, newDecodeError(b[start:start+1], "number cannot start with underscore") + return nil, unstable.NewParserError(b[start:start+1], "number cannot start with underscore") } if b[len(b)-1] == '_' { - return nil, newDecodeError(b[len(b)-1:], "number cannot end with underscore") + return nil, unstable.NewParserError(b[len(b)-1:], "number cannot end with underscore") } // fast path @@ -435,7 +437,7 @@ func checkAndRemoveUnderscoresIntegers(b []byte) ([]byte, error) { c := b[i] if c == '_' { if !before { - return nil, newDecodeError(b[i-1:i+1], "number must have at least one digit between underscores") + return nil, unstable.NewParserError(b[i-1:i+1], "number must have at least one digit between underscores") } before = false } else { @@ -449,11 +451,11 @@ func checkAndRemoveUnderscoresIntegers(b []byte) ([]byte, error) { func checkAndRemoveUnderscoresFloats(b []byte) ([]byte, error) { if b[0] == '_' { - return nil, newDecodeError(b[0:1], "number cannot start with underscore") + return nil, unstable.NewParserError(b[0:1], "number cannot start with underscore") } if b[len(b)-1] == '_' { - return nil, newDecodeError(b[len(b)-1:], "number cannot end with underscore") + return nil, unstable.NewParserError(b[len(b)-1:], "number cannot end with underscore") } // fast path @@ -476,10 +478,10 @@ func checkAndRemoveUnderscoresFloats(b []byte) ([]byte, error) { switch c { case '_': if !before { - return nil, newDecodeError(b[i-1:i+1], "number must have at least one digit between underscores") + return nil, unstable.NewParserError(b[i-1:i+1], "number must have at least one digit between underscores") } if i < len(b)-1 && (b[i+1] == 'e' || b[i+1] == 'E') { - return nil, newDecodeError(b[i+1:i+2], "cannot have underscore before exponent") + return nil, unstable.NewParserError(b[i+1:i+2], "cannot have underscore before exponent") } before = false case '+', '-': @@ -488,15 +490,15 @@ func checkAndRemoveUnderscoresFloats(b []byte) ([]byte, error) { before = false case 'e', 'E': if i < len(b)-1 && b[i+1] == '_' { - return nil, newDecodeError(b[i+1:i+2], "cannot have underscore after exponent") + return nil, unstable.NewParserError(b[i+1:i+2], "cannot have underscore after exponent") } cleaned = append(cleaned, c) case '.': if i < len(b)-1 && b[i+1] == '_' { - return nil, newDecodeError(b[i+1:i+2], "cannot have underscore after decimal point") + return nil, unstable.NewParserError(b[i+1:i+2], "cannot have underscore after decimal point") } if i > 0 && b[i-1] == '_' { - return nil, newDecodeError(b[i-1:i], "cannot have underscore before decimal point") + return nil, unstable.NewParserError(b[i-1:i], "cannot have underscore before decimal point") } cleaned = append(cleaned, c) default: @@ -542,3 +544,7 @@ func daysIn(m int, year int) int { func isLeap(year int) bool { return year%4 == 0 && (year%100 != 0 || year%400 == 0) } + +func isDigit(r byte) bool { + return r >= '0' && r <= '9' +} diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/errors.go b/tools/vendor/github.com/pelletier/go-toml/v2/errors.go index 2e7f0ffdf..309733f1f 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/errors.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/errors.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/pelletier/go-toml/v2/internal/danger" + "github.com/pelletier/go-toml/v2/unstable" ) // DecodeError represents an error encountered during the parsing or decoding @@ -55,25 +56,6 @@ func (s *StrictMissingError) String() string { type Key []string -// internal version of DecodeError that is used as the base to create a -// DecodeError with full context. -type decodeError struct { - highlight []byte - message string - key Key // optional -} - -func (de *decodeError) Error() string { - return de.message -} - -func newDecodeError(highlight []byte, format string, args ...interface{}) error { - return &decodeError{ - highlight: highlight, - message: fmt.Errorf(format, args...).Error(), - } -} - // Error returns the error message contained in the DecodeError. func (e *DecodeError) Error() string { return "toml: " + e.message @@ -105,12 +87,12 @@ func (e *DecodeError) Key() Key { // highlight can be freely deallocated. // //nolint:funlen -func wrapDecodeError(document []byte, de *decodeError) *DecodeError { - offset := danger.SubsliceOffset(document, de.highlight) +func wrapDecodeError(document []byte, de *unstable.ParserError) *DecodeError { + offset := danger.SubsliceOffset(document, de.Highlight) errMessage := de.Error() errLine, errColumn := positionAtEnd(document[:offset]) - before, after := linesOfContext(document, de.highlight, offset, 3) + before, after := linesOfContext(document, de.Highlight, offset, 3) var buf strings.Builder @@ -140,7 +122,7 @@ func wrapDecodeError(document []byte, de *decodeError) *DecodeError { buf.Write(before[0]) } - buf.Write(de.highlight) + buf.Write(de.Highlight) if len(after) > 0 { buf.Write(after[0]) @@ -158,7 +140,7 @@ func wrapDecodeError(document []byte, de *decodeError) *DecodeError { buf.WriteString(strings.Repeat(" ", len(before[0]))) } - buf.WriteString(strings.Repeat("~", len(de.highlight))) + buf.WriteString(strings.Repeat("~", len(de.Highlight))) if len(errMessage) > 0 { buf.WriteString(" ") @@ -183,7 +165,7 @@ func wrapDecodeError(document []byte, de *decodeError) *DecodeError { message: errMessage, line: errLine, column: errColumn, - key: de.key, + key: de.Key, human: buf.String(), } } diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/builder.go b/tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/builder.go deleted file mode 100644 index 120f16e5c..000000000 --- a/tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/builder.go +++ /dev/null @@ -1,51 +0,0 @@ -package ast - -type Reference int - -const InvalidReference Reference = -1 - -func (r Reference) Valid() bool { - return r != InvalidReference -} - -type Builder struct { - tree Root - lastIdx int -} - -func (b *Builder) Tree() *Root { - return &b.tree -} - -func (b *Builder) NodeAt(ref Reference) *Node { - return b.tree.at(ref) -} - -func (b *Builder) Reset() { - b.tree.nodes = b.tree.nodes[:0] - b.lastIdx = 0 -} - -func (b *Builder) Push(n Node) Reference { - b.lastIdx = len(b.tree.nodes) - b.tree.nodes = append(b.tree.nodes, n) - return Reference(b.lastIdx) -} - -func (b *Builder) PushAndChain(n Node) Reference { - newIdx := len(b.tree.nodes) - b.tree.nodes = append(b.tree.nodes, n) - if b.lastIdx >= 0 { - b.tree.nodes[b.lastIdx].next = newIdx - b.lastIdx - } - b.lastIdx = newIdx - return Reference(b.lastIdx) -} - -func (b *Builder) AttachChild(parent Reference, child Reference) { - b.tree.nodes[parent].child = int(child) - int(parent) -} - -func (b *Builder) Chain(from Reference, to Reference) { - b.tree.nodes[from].next = int(to) - int(from) -} diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/internal/characters/ascii.go b/tools/vendor/github.com/pelletier/go-toml/v2/internal/characters/ascii.go new file mode 100644 index 000000000..80f698db4 --- /dev/null +++ b/tools/vendor/github.com/pelletier/go-toml/v2/internal/characters/ascii.go @@ -0,0 +1,42 @@ +package characters + +var invalidAsciiTable = [256]bool{ + 0x00: true, + 0x01: true, + 0x02: true, + 0x03: true, + 0x04: true, + 0x05: true, + 0x06: true, + 0x07: true, + 0x08: true, + // 0x09 TAB + // 0x0A LF + 0x0B: true, + 0x0C: true, + // 0x0D CR + 0x0E: true, + 0x0F: true, + 0x10: true, + 0x11: true, + 0x12: true, + 0x13: true, + 0x14: true, + 0x15: true, + 0x16: true, + 0x17: true, + 0x18: true, + 0x19: true, + 0x1A: true, + 0x1B: true, + 0x1C: true, + 0x1D: true, + 0x1E: true, + 0x1F: true, + // 0x20 - 0x7E Printable ASCII characters + 0x7F: true, +} + +func InvalidAscii(b byte) bool { + return invalidAsciiTable[b] +} diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/utf8.go b/tools/vendor/github.com/pelletier/go-toml/v2/internal/characters/utf8.go similarity index 87% rename from tools/vendor/github.com/pelletier/go-toml/v2/utf8.go rename to tools/vendor/github.com/pelletier/go-toml/v2/internal/characters/utf8.go index d47a4f20c..db4f45acb 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/utf8.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/internal/characters/utf8.go @@ -1,4 +1,4 @@ -package toml +package characters import ( "unicode/utf8" @@ -32,7 +32,7 @@ func (u utf8Err) Zero() bool { // 0x9 => tab, ok // 0xA - 0x1F => invalid // 0x7F => invalid -func utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) { +func Utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) { // Fast path. Check for and skip 8 bytes of ASCII characters per iteration. offset := 0 for len(p) >= 8 { @@ -48,7 +48,7 @@ func utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) { } for i, b := range p[:8] { - if invalidAscii(b) { + if InvalidAscii(b) { err.Index = offset + i err.Size = 1 return @@ -62,7 +62,7 @@ func utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) { for i := 0; i < n; { pi := p[i] if pi < utf8.RuneSelf { - if invalidAscii(pi) { + if InvalidAscii(pi) { err.Index = offset + i err.Size = 1 return @@ -106,11 +106,11 @@ func utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) { } // Return the size of the next rune if valid, 0 otherwise. -func utf8ValidNext(p []byte) int { +func Utf8ValidNext(p []byte) int { c := p[0] if c < utf8.RuneSelf { - if invalidAscii(c) { + if InvalidAscii(c) { return 0 } return 1 @@ -140,47 +140,6 @@ func utf8ValidNext(p []byte) int { return size } -var invalidAsciiTable = [256]bool{ - 0x00: true, - 0x01: true, - 0x02: true, - 0x03: true, - 0x04: true, - 0x05: true, - 0x06: true, - 0x07: true, - 0x08: true, - // 0x09 TAB - // 0x0A LF - 0x0B: true, - 0x0C: true, - // 0x0D CR - 0x0E: true, - 0x0F: true, - 0x10: true, - 0x11: true, - 0x12: true, - 0x13: true, - 0x14: true, - 0x15: true, - 0x16: true, - 0x17: true, - 0x18: true, - 0x19: true, - 0x1A: true, - 0x1B: true, - 0x1C: true, - 0x1D: true, - 0x1E: true, - 0x1F: true, - // 0x20 - 0x7E Printable ASCII characters - 0x7F: true, -} - -func invalidAscii(b byte) bool { - return invalidAsciiTable[b] -} - // acceptRange gives the range of valid values for the second byte in a UTF-8 // sequence. type acceptRange struct { diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/key.go b/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/key.go index 7c148f48d..149b17f53 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/key.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/key.go @@ -1,8 +1,6 @@ package tracker -import ( - "github.com/pelletier/go-toml/v2/internal/ast" -) +import "github.com/pelletier/go-toml/v2/unstable" // KeyTracker is a tracker that keeps track of the current Key as the AST is // walked. @@ -11,19 +9,19 @@ type KeyTracker struct { } // UpdateTable sets the state of the tracker with the AST table node. -func (t *KeyTracker) UpdateTable(node *ast.Node) { +func (t *KeyTracker) UpdateTable(node *unstable.Node) { t.reset() t.Push(node) } // UpdateArrayTable sets the state of the tracker with the AST array table node. -func (t *KeyTracker) UpdateArrayTable(node *ast.Node) { +func (t *KeyTracker) UpdateArrayTable(node *unstable.Node) { t.reset() t.Push(node) } // Push the given key on the stack. -func (t *KeyTracker) Push(node *ast.Node) { +func (t *KeyTracker) Push(node *unstable.Node) { it := node.Key() for it.Next() { t.k = append(t.k, string(it.Node().Data)) @@ -31,7 +29,7 @@ func (t *KeyTracker) Push(node *ast.Node) { } // Pop key from stack. -func (t *KeyTracker) Pop(node *ast.Node) { +func (t *KeyTracker) Pop(node *unstable.Node) { it := node.Key() for it.Next() { t.k = t.k[:len(t.k)-1] diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/seen.go b/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/seen.go index a7ee05ba6..76df2d5b6 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/seen.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/internal/tracker/seen.go @@ -5,7 +5,7 @@ import ( "fmt" "sync" - "github.com/pelletier/go-toml/v2/internal/ast" + "github.com/pelletier/go-toml/v2/unstable" ) type keyKind uint8 @@ -57,7 +57,11 @@ type SeenTracker struct { currentIdx int } -var pool sync.Pool +var pool = sync.Pool{ + New: func() interface{} { + return &SeenTracker{} + }, +} func (s *SeenTracker) reset() { // Always contains a root element at index 0. @@ -149,24 +153,25 @@ func (s *SeenTracker) setExplicitFlag(parentIdx int) { // CheckExpression takes a top-level node and checks that it does not contain // keys that have been seen in previous calls, and validates that types are -// consistent. -func (s *SeenTracker) CheckExpression(node *ast.Node) error { +// consistent. It returns true if it is the first time this node's key is seen. +// Useful to clear array tables on first use. +func (s *SeenTracker) CheckExpression(node *unstable.Node) (bool, error) { if s.entries == nil { s.reset() } switch node.Kind { - case ast.KeyValue: + case unstable.KeyValue: return s.checkKeyValue(node) - case ast.Table: + case unstable.Table: return s.checkTable(node) - case ast.ArrayTable: + case unstable.ArrayTable: return s.checkArrayTable(node) default: panic(fmt.Errorf("this should not be a top level node type: %s", node.Kind)) } } -func (s *SeenTracker) checkTable(node *ast.Node) error { +func (s *SeenTracker) checkTable(node *unstable.Node) (bool, error) { if s.currentIdx >= 0 { s.setExplicitFlag(s.currentIdx) } @@ -192,7 +197,7 @@ func (s *SeenTracker) checkTable(node *ast.Node) error { } else { entry := s.entries[idx] if entry.kind == valueKind { - return fmt.Errorf("toml: expected %s to be a table, not a %s", string(k), entry.kind) + return false, fmt.Errorf("toml: expected %s to be a table, not a %s", string(k), entry.kind) } } parentIdx = idx @@ -201,25 +206,27 @@ func (s *SeenTracker) checkTable(node *ast.Node) error { k := it.Node().Data idx := s.find(parentIdx, k) + first := false if idx >= 0 { kind := s.entries[idx].kind if kind != tableKind { - return fmt.Errorf("toml: key %s should be a table, not a %s", string(k), kind) + return false, fmt.Errorf("toml: key %s should be a table, not a %s", string(k), kind) } if s.entries[idx].explicit { - return fmt.Errorf("toml: table %s already exists", string(k)) + return false, fmt.Errorf("toml: table %s already exists", string(k)) } s.entries[idx].explicit = true } else { idx = s.create(parentIdx, k, tableKind, true, false) + first = true } s.currentIdx = idx - return nil + return first, nil } -func (s *SeenTracker) checkArrayTable(node *ast.Node) error { +func (s *SeenTracker) checkArrayTable(node *unstable.Node) (bool, error) { if s.currentIdx >= 0 { s.setExplicitFlag(s.currentIdx) } @@ -242,7 +249,7 @@ func (s *SeenTracker) checkArrayTable(node *ast.Node) error { } else { entry := s.entries[idx] if entry.kind == valueKind { - return fmt.Errorf("toml: expected %s to be a table, not a %s", string(k), entry.kind) + return false, fmt.Errorf("toml: expected %s to be a table, not a %s", string(k), entry.kind) } } @@ -252,22 +259,23 @@ func (s *SeenTracker) checkArrayTable(node *ast.Node) error { k := it.Node().Data idx := s.find(parentIdx, k) - if idx >= 0 { + firstTime := idx < 0 + if firstTime { + idx = s.create(parentIdx, k, arrayTableKind, true, false) + } else { kind := s.entries[idx].kind if kind != arrayTableKind { - return fmt.Errorf("toml: key %s already exists as a %s, but should be an array table", kind, string(k)) + return false, fmt.Errorf("toml: key %s already exists as a %s, but should be an array table", kind, string(k)) } s.clear(idx) - } else { - idx = s.create(parentIdx, k, arrayTableKind, true, false) } s.currentIdx = idx - return nil + return firstTime, nil } -func (s *SeenTracker) checkKeyValue(node *ast.Node) error { +func (s *SeenTracker) checkKeyValue(node *unstable.Node) (bool, error) { parentIdx := s.currentIdx it := node.Key() @@ -281,11 +289,11 @@ func (s *SeenTracker) checkKeyValue(node *ast.Node) error { } else { entry := s.entries[idx] if it.IsLast() { - return fmt.Errorf("toml: key %s is already defined", string(k)) + return false, fmt.Errorf("toml: key %s is already defined", string(k)) } else if entry.kind != tableKind { - return fmt.Errorf("toml: expected %s to be a table, not a %s", string(k), entry.kind) + return false, fmt.Errorf("toml: expected %s to be a table, not a %s", string(k), entry.kind) } else if entry.explicit { - return fmt.Errorf("toml: cannot redefine table %s that has already been explicitly defined", string(k)) + return false, fmt.Errorf("toml: cannot redefine table %s that has already been explicitly defined", string(k)) } } @@ -297,51 +305,45 @@ func (s *SeenTracker) checkKeyValue(node *ast.Node) error { value := node.Value() switch value.Kind { - case ast.InlineTable: + case unstable.InlineTable: return s.checkInlineTable(value) - case ast.Array: + case unstable.Array: return s.checkArray(value) } - return nil + return false, nil } -func (s *SeenTracker) checkArray(node *ast.Node) error { +func (s *SeenTracker) checkArray(node *unstable.Node) (first bool, err error) { it := node.Children() for it.Next() { n := it.Node() switch n.Kind { - case ast.InlineTable: - err := s.checkInlineTable(n) + case unstable.InlineTable: + first, err = s.checkInlineTable(n) if err != nil { - return err + return false, err } - case ast.Array: - err := s.checkArray(n) + case unstable.Array: + first, err = s.checkArray(n) if err != nil { - return err + return false, err } } } - return nil + return first, nil } -func (s *SeenTracker) checkInlineTable(node *ast.Node) error { - if pool.New == nil { - pool.New = func() interface{} { - return &SeenTracker{} - } - } - +func (s *SeenTracker) checkInlineTable(node *unstable.Node) (first bool, err error) { s = pool.Get().(*SeenTracker) s.reset() it := node.Children() for it.Next() { n := it.Node() - err := s.checkKeyValue(n) + first, err = s.checkKeyValue(n) if err != nil { - return err + return false, err } } @@ -352,5 +354,5 @@ func (s *SeenTracker) checkInlineTable(node *ast.Node) error { // redefinition of its keys: check* functions cannot walk into // a value. pool.Put(s) - return nil + return first, nil } diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/localtime.go b/tools/vendor/github.com/pelletier/go-toml/v2/localtime.go index 30a31dcbd..a856bfdb0 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/localtime.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/localtime.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" "time" + + "github.com/pelletier/go-toml/v2/unstable" ) // LocalDate represents a calendar day in no specific timezone. @@ -75,7 +77,7 @@ func (d LocalTime) MarshalText() ([]byte, error) { func (d *LocalTime) UnmarshalText(b []byte) error { res, left, err := parseLocalTime(b) if err == nil && len(left) != 0 { - err = newDecodeError(left, "extra characters") + err = unstable.NewParserError(left, "extra characters") } if err != nil { return err @@ -109,7 +111,7 @@ func (d LocalDateTime) MarshalText() ([]byte, error) { func (d *LocalDateTime) UnmarshalText(data []byte) error { res, left, err := parseLocalDateTime(data) if err == nil && len(left) != 0 { - err = newDecodeError(left, "extra characters") + err = unstable.NewParserError(left, "extra characters") } if err != nil { return err diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/marshaler.go b/tools/vendor/github.com/pelletier/go-toml/v2/marshaler.go index acb288315..7f4e20c12 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/marshaler.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/marshaler.go @@ -3,6 +3,7 @@ package toml import ( "bytes" "encoding" + "encoding/json" "fmt" "io" "math" @@ -12,6 +13,8 @@ import ( "strings" "time" "unicode" + + "github.com/pelletier/go-toml/v2/internal/characters" ) // Marshal serializes a Go value as a TOML document. @@ -35,10 +38,11 @@ type Encoder struct { w io.Writer // global settings - tablesInline bool - arraysMultiline bool - indentSymbol string - indentTables bool + tablesInline bool + arraysMultiline bool + indentSymbol string + indentTables bool + marshalJsonNumbers bool } // NewEncoder returns a new Encoder that writes to w. @@ -85,6 +89,17 @@ func (enc *Encoder) SetIndentTables(indent bool) *Encoder { return enc } +// SetMarshalJsonNumbers forces the encoder to serialize `json.Number` as a +// float or integer instead of relying on TextMarshaler to emit a string. +// +// *Unstable:* This method does not follow the compatibility guarantees of +// semver. It can be changed or removed without a new major version being +// issued. +func (enc *Encoder) SetMarshalJsonNumbers(indent bool) *Encoder { + enc.marshalJsonNumbers = indent + return enc +} + // Encode writes a TOML representation of v to the stream. // // If v cannot be represented to TOML it returns an error. @@ -146,6 +161,9 @@ func (enc *Encoder) SetIndentTables(indent bool) *Encoder { // // The "omitempty" option prevents empty values or groups from being emitted. // +// The "commented" option prefixes the value and all its children with a comment +// symbol. +// // In addition to the "toml" tag struct tag, a "comment" tag can be used to emit // a TOML comment before the value being annotated. Comments are ignored inside // inline tables. For array tables, the comment is only present before the first @@ -178,6 +196,7 @@ func (enc *Encoder) Encode(v interface{}) error { type valueOptions struct { multiline bool omitempty bool + commented bool comment string } @@ -203,6 +222,9 @@ type encoderCtx struct { // Indentation level indent int + // Prefix the current value with a comment. + commented bool + // Options coming from struct tags options valueOptions } @@ -243,6 +265,18 @@ func (enc *Encoder) encode(b []byte, ctx encoderCtx, v reflect.Value) ([]byte, e return append(b, x.String()...), nil case LocalDateTime: return append(b, x.String()...), nil + case json.Number: + if enc.marshalJsonNumbers { + if x == "" { /// Useful zero value. + return append(b, "0"...), nil + } else if v, err := x.Int64(); err == nil { + return enc.encode(b, ctx, reflect.ValueOf(v)) + } else if f, err := x.Float64(); err == nil { + return enc.encode(b, ctx, reflect.ValueOf(f)) + } else { + return nil, fmt.Errorf("toml: unable to convert %q to int64 or float64", x) + } + } } hasTextMarshaler := v.Type().Implements(textMarshalerType) @@ -271,7 +305,7 @@ func (enc *Encoder) encode(b []byte, ctx encoderCtx, v reflect.Value) ([]byte, e return enc.encodeMap(b, ctx, v) case reflect.Struct: return enc.encodeStruct(b, ctx, v) - case reflect.Slice: + case reflect.Slice, reflect.Array: return enc.encodeSlice(b, ctx, v) case reflect.Interface: if v.IsNil() { @@ -355,9 +389,10 @@ func (enc *Encoder) encodeKv(b []byte, ctx encoderCtx, options valueOptions, v r if !ctx.inline { b = enc.encodeComment(ctx.indent, options.comment, b) + b = enc.commented(ctx.commented, b) + b = enc.indent(ctx.indent, b) } - b = enc.indent(ctx.indent, b) b = enc.encodeKey(b, ctx.key) b = append(b, " = "...) @@ -376,6 +411,13 @@ func (enc *Encoder) encodeKv(b []byte, ctx encoderCtx, options valueOptions, v r return b, nil } +func (enc *Encoder) commented(commented bool, b []byte) []byte { + if commented { + return append(b, "# "...) + } + return b +} + func isEmptyValue(v reflect.Value) bool { switch v.Kind() { case reflect.Struct: @@ -437,7 +479,7 @@ func (enc *Encoder) encodeString(b []byte, v string, options valueOptions) []byt func needsQuoting(v string) bool { // TODO: vectorize for _, b := range []byte(v) { - if b == '\'' || b == '\r' || b == '\n' || invalidAscii(b) { + if b == '\'' || b == '\r' || b == '\n' || characters.InvalidAscii(b) { return true } } @@ -524,6 +566,8 @@ func (enc *Encoder) encodeTableHeader(ctx encoderCtx, b []byte) ([]byte, error) b = enc.encodeComment(ctx.indent, ctx.options.comment, b) + b = enc.commented(ctx.commented, b) + b = enc.indent(ctx.indent, b) b = append(b, '[') @@ -575,11 +619,23 @@ func (enc *Encoder) encodeKey(b []byte, k string) []byte { } } -func (enc *Encoder) encodeMap(b []byte, ctx encoderCtx, v reflect.Value) ([]byte, error) { - if v.Type().Key().Kind() != reflect.String { - return nil, fmt.Errorf("toml: type %s is not supported as a map key", v.Type().Key().Kind()) +func (enc *Encoder) keyToString(k reflect.Value) (string, error) { + keyType := k.Type() + switch { + case keyType.Kind() == reflect.String: + return k.String(), nil + + case keyType.Implements(textMarshalerType): + keyB, err := k.Interface().(encoding.TextMarshaler).MarshalText() + if err != nil { + return "", fmt.Errorf("toml: error marshalling key %v from text: %w", k, err) + } + return string(keyB), nil } + return "", fmt.Errorf("toml: type %s is not supported as a map key", keyType.Kind()) +} +func (enc *Encoder) encodeMap(b []byte, ctx encoderCtx, v reflect.Value) ([]byte, error) { var ( t table emptyValueOptions valueOptions @@ -587,13 +643,17 @@ func (enc *Encoder) encodeMap(b []byte, ctx encoderCtx, v reflect.Value) ([]byte iter := v.MapRange() for iter.Next() { - k := iter.Key().String() v := iter.Value() if isNil(v) { continue } + k, err := enc.keyToString(iter.Key()) + if err != nil { + return nil, err + } + if willConvertToTableOrArrayTable(ctx, v) { t.pushTable(k, v, emptyValueOptions) } else { @@ -672,6 +732,8 @@ func walkStruct(ctx encoderCtx, t *table, v reflect.Value) { if fieldType.Anonymous { if fieldType.Type.Kind() == reflect.Struct { walkStruct(ctx, t, f) + } else if fieldType.Type.Kind() == reflect.Pointer && !f.IsNil() && f.Elem().Kind() == reflect.Struct { + walkStruct(ctx, t, f.Elem()) } continue } else { @@ -686,6 +748,7 @@ func walkStruct(ctx encoderCtx, t *table, v reflect.Value) { options := valueOptions{ multiline: opts.multiline, omitempty: opts.omitempty, + commented: opts.commented, comment: fieldType.Tag.Get("comment"), } @@ -745,6 +808,7 @@ type tagOptions struct { multiline bool inline bool omitempty bool + commented bool } func parseTag(tag string) (string, tagOptions) { @@ -772,6 +836,8 @@ func parseTag(tag string) (string, tagOptions) { opts.inline = true case "omitempty": opts.omitempty = true + case "commented": + opts.commented = true } } @@ -807,8 +873,10 @@ func (enc *Encoder) encodeTable(b []byte, ctx encoderCtx, t table) ([]byte, erro hasNonEmptyKV = true ctx.setKey(kv.Key) + ctx2 := ctx + ctx2.commented = kv.Options.commented || ctx2.commented - b, err = enc.encodeKv(b, ctx, kv.Options, kv.Value) + b, err = enc.encodeKv(b, ctx2, kv.Options, kv.Value) if err != nil { return nil, err } @@ -833,8 +901,10 @@ func (enc *Encoder) encodeTable(b []byte, ctx encoderCtx, t table) ([]byte, erro ctx.setKey(table.Key) ctx.options = table.Options + ctx2 := ctx + ctx2.commented = ctx2.commented || ctx.options.commented - b, err = enc.encode(b, ctx, table.Value) + b, err = enc.encode(b, ctx2, table.Value) if err != nil { return nil, err } @@ -912,7 +982,7 @@ func willConvertToTableOrArrayTable(ctx encoderCtx, v reflect.Value) bool { return willConvertToTableOrArrayTable(ctx, v.Elem()) } - if t.Kind() == reflect.Slice { + if t.Kind() == reflect.Slice || t.Kind() == reflect.Array { if v.Len() == 0 { // An empty slice should be a kv = []. return false @@ -952,6 +1022,13 @@ func (enc *Encoder) encodeSliceAsArrayTable(b []byte, ctx encoderCtx, v reflect. ctx.shiftKey() scratch := make([]byte, 0, 64) + + scratch = enc.commented(ctx.commented, scratch) + + if enc.indentTables { + scratch = enc.indent(ctx.indent, scratch) + } + scratch = append(scratch, "[["...) for i, k := range ctx.parentKey { @@ -967,6 +1044,10 @@ func (enc *Encoder) encodeSliceAsArrayTable(b []byte, ctx encoderCtx, v reflect. b = enc.encodeComment(ctx.indent, ctx.options.comment, b) + if enc.indentTables { + ctx.indent++ + } + for i := 0; i < v.Len(); i++ { if i != 0 { b = append(b, "\n"...) diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/strict.go b/tools/vendor/github.com/pelletier/go-toml/v2/strict.go index b7830d139..802e7e4d1 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/strict.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/strict.go @@ -1,9 +1,9 @@ package toml import ( - "github.com/pelletier/go-toml/v2/internal/ast" "github.com/pelletier/go-toml/v2/internal/danger" "github.com/pelletier/go-toml/v2/internal/tracker" + "github.com/pelletier/go-toml/v2/unstable" ) type strict struct { @@ -12,10 +12,10 @@ type strict struct { // Tracks the current key being processed. key tracker.KeyTracker - missing []decodeError + missing []unstable.ParserError } -func (s *strict) EnterTable(node *ast.Node) { +func (s *strict) EnterTable(node *unstable.Node) { if !s.Enabled { return } @@ -23,7 +23,7 @@ func (s *strict) EnterTable(node *ast.Node) { s.key.UpdateTable(node) } -func (s *strict) EnterArrayTable(node *ast.Node) { +func (s *strict) EnterArrayTable(node *unstable.Node) { if !s.Enabled { return } @@ -31,7 +31,7 @@ func (s *strict) EnterArrayTable(node *ast.Node) { s.key.UpdateArrayTable(node) } -func (s *strict) EnterKeyValue(node *ast.Node) { +func (s *strict) EnterKeyValue(node *unstable.Node) { if !s.Enabled { return } @@ -39,7 +39,7 @@ func (s *strict) EnterKeyValue(node *ast.Node) { s.key.Push(node) } -func (s *strict) ExitKeyValue(node *ast.Node) { +func (s *strict) ExitKeyValue(node *unstable.Node) { if !s.Enabled { return } @@ -47,27 +47,27 @@ func (s *strict) ExitKeyValue(node *ast.Node) { s.key.Pop(node) } -func (s *strict) MissingTable(node *ast.Node) { +func (s *strict) MissingTable(node *unstable.Node) { if !s.Enabled { return } - s.missing = append(s.missing, decodeError{ - highlight: keyLocation(node), - message: "missing table", - key: s.key.Key(), + s.missing = append(s.missing, unstable.ParserError{ + Highlight: keyLocation(node), + Message: "missing table", + Key: s.key.Key(), }) } -func (s *strict) MissingField(node *ast.Node) { +func (s *strict) MissingField(node *unstable.Node) { if !s.Enabled { return } - s.missing = append(s.missing, decodeError{ - highlight: keyLocation(node), - message: "missing field", - key: s.key.Key(), + s.missing = append(s.missing, unstable.ParserError{ + Highlight: keyLocation(node), + Message: "missing field", + Key: s.key.Key(), }) } @@ -88,7 +88,7 @@ func (s *strict) Error(doc []byte) error { return err } -func keyLocation(node *ast.Node) []byte { +func keyLocation(node *unstable.Node) []byte { k := node.Key() hasOne := k.Next() diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/types.go b/tools/vendor/github.com/pelletier/go-toml/v2/types.go index 630a45466..3c6b8fe57 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/types.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/types.go @@ -6,9 +6,9 @@ import ( "time" ) -var timeType = reflect.TypeOf(time.Time{}) -var textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem() -var textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem() -var mapStringInterfaceType = reflect.TypeOf(map[string]interface{}{}) -var sliceInterfaceType = reflect.TypeOf([]interface{}{}) +var timeType = reflect.TypeOf((*time.Time)(nil)).Elem() +var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() +var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() +var mapStringInterfaceType = reflect.TypeOf(map[string]interface{}(nil)) +var sliceInterfaceType = reflect.TypeOf([]interface{}(nil)) var stringType = reflect.TypeOf("") diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go b/tools/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go index d0d7a72d0..98231bae6 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unmarshaler.go @@ -12,16 +12,16 @@ import ( "sync/atomic" "time" - "github.com/pelletier/go-toml/v2/internal/ast" "github.com/pelletier/go-toml/v2/internal/danger" "github.com/pelletier/go-toml/v2/internal/tracker" + "github.com/pelletier/go-toml/v2/unstable" ) // Unmarshal deserializes a TOML document into a Go value. // // It is a shortcut for Decoder.Decode() with the default options. func Unmarshal(data []byte, v interface{}) error { - p := parser{} + p := unstable.Parser{} p.Reset(data) d := decoder{p: &p} @@ -35,6 +35,9 @@ type Decoder struct { // global settings strict bool + + // toggles unmarshaler interface + unmarshalerInterface bool } // NewDecoder creates a new Decoder that will read from r. @@ -54,13 +57,31 @@ func (d *Decoder) DisallowUnknownFields() *Decoder { return d } +// EnableUnmarshalerInterface allows to enable unmarshaler interface. +// +// With this feature enabled, types implementing the unstable/Unmarshaler +// interface can be decoded from any structure of the document. It allows types +// that don't have a straightfoward TOML representation to provide their own +// decoding logic. +// +// Currently, types can only decode from a single value. Tables and array tables +// are not supported. +// +// *Unstable:* This method does not follow the compatibility guarantees of +// semver. It can be changed or removed without a new major version being +// issued. +func (d *Decoder) EnableUnmarshalerInterface() *Decoder { + d.unmarshalerInterface = true + return d +} + // Decode the whole content of r into v. // // By default, values in the document that don't exist in the target Go value // are ignored. See Decoder.DisallowUnknownFields() to change this behavior. // // When a TOML local date, time, or date-time is decoded into a time.Time, its -// value is represented in time.Local timezone. Otherwise the approriate Local* +// value is represented in time.Local timezone. Otherwise the appropriate Local* // structure is used. For time values, precision up to the nanosecond is // supported by truncating extra digits. // @@ -101,13 +122,14 @@ func (d *Decoder) Decode(v interface{}) error { return fmt.Errorf("toml: %w", err) } - p := parser{} + p := unstable.Parser{} p.Reset(b) dec := decoder{ p: &p, strict: strict{ Enabled: d.strict, }, + unmarshalerInterface: d.unmarshalerInterface, } return dec.FromParser(v) @@ -115,7 +137,7 @@ func (d *Decoder) Decode(v interface{}) error { type decoder struct { // Which parser instance in use for this decoding session. - p *parser + p *unstable.Parser // Flag indicating that the current expression is stashed. // If set to true, calling nextExpr will not actually pull a new expression @@ -127,6 +149,10 @@ type decoder struct { // need to be skipped. skipUntilTable bool + // Flag indicating that the current array/slice table should be cleared because + // it is the first encounter of an array table. + clearArrayTable bool + // Tracks position in Go arrays. // This is used when decoding [[array tables]] into Go arrays. Given array // tables are separate TOML expression, we need to keep track of where we @@ -139,6 +165,9 @@ type decoder struct { // Strict mode strict strict + // Flag that enables/disables unmarshaler interface. + unmarshalerInterface bool + // Current context for the error. errorContext *errorContext } @@ -149,15 +178,19 @@ type errorContext struct { } func (d *decoder) typeMismatchError(toml string, target reflect.Type) error { + return fmt.Errorf("toml: %s", d.typeMismatchString(toml, target)) +} + +func (d *decoder) typeMismatchString(toml string, target reflect.Type) string { if d.errorContext != nil && d.errorContext.Struct != nil { ctx := d.errorContext f := ctx.Struct.FieldByIndex(ctx.Field) - return fmt.Errorf("toml: cannot decode TOML %s into struct field %s.%s of type %s", toml, ctx.Struct, f.Name, f.Type) + return fmt.Sprintf("cannot decode TOML %s into struct field %s.%s of type %s", toml, ctx.Struct, f.Name, f.Type) } - return fmt.Errorf("toml: cannot decode TOML %s into a Go value of type %s", toml, target) + return fmt.Sprintf("cannot decode TOML %s into a Go value of type %s", toml, target) } -func (d *decoder) expr() *ast.Node { +func (d *decoder) expr() *unstable.Node { return d.p.Expression() } @@ -208,12 +241,12 @@ func (d *decoder) FromParser(v interface{}) error { err := d.fromParser(r) if err == nil { - return d.strict.Error(d.p.data) + return d.strict.Error(d.p.Data()) } - var e *decodeError + var e *unstable.ParserError if errors.As(err, &e) { - return wrapDecodeError(d.p.data, e) + return wrapDecodeError(d.p.Data(), e) } return err @@ -234,42 +267,44 @@ func (d *decoder) fromParser(root reflect.Value) error { Rules for the unmarshal code: - The stack is used to keep track of which values need to be set where. -- handle* functions <=> switch on a given ast.Kind. +- handle* functions <=> switch on a given unstable.Kind. - unmarshalX* functions need to unmarshal a node of kind X. - An "object" is either a struct or a map. */ -func (d *decoder) handleRootExpression(expr *ast.Node, v reflect.Value) error { +func (d *decoder) handleRootExpression(expr *unstable.Node, v reflect.Value) error { var x reflect.Value var err error + var first bool // used for to clear array tables on first use - if !(d.skipUntilTable && expr.Kind == ast.KeyValue) { - err = d.seen.CheckExpression(expr) + if !(d.skipUntilTable && expr.Kind == unstable.KeyValue) { + first, err = d.seen.CheckExpression(expr) if err != nil { return err } } switch expr.Kind { - case ast.KeyValue: + case unstable.KeyValue: if d.skipUntilTable { return nil } x, err = d.handleKeyValue(expr, v) - case ast.Table: + case unstable.Table: d.skipUntilTable = false d.strict.EnterTable(expr) x, err = d.handleTable(expr.Key(), v) - case ast.ArrayTable: + case unstable.ArrayTable: d.skipUntilTable = false d.strict.EnterArrayTable(expr) + d.clearArrayTable = first x, err = d.handleArrayTable(expr.Key(), v) default: panic(fmt.Errorf("parser should not permit expression of kind %s at document root", expr.Kind)) } if d.skipUntilTable { - if expr.Kind == ast.Table || expr.Kind == ast.ArrayTable { + if expr.Kind == unstable.Table || expr.Kind == unstable.ArrayTable { d.strict.MissingTable(expr) } } else if err == nil && x.IsValid() { @@ -279,14 +314,14 @@ func (d *decoder) handleRootExpression(expr *ast.Node, v reflect.Value) error { return err } -func (d *decoder) handleArrayTable(key ast.Iterator, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleArrayTable(key unstable.Iterator, v reflect.Value) (reflect.Value, error) { if key.Next() { return d.handleArrayTablePart(key, v) } return d.handleKeyValues(v) } -func (d *decoder) handleArrayTableCollectionLast(key ast.Iterator, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleArrayTableCollectionLast(key unstable.Iterator, v reflect.Value) (reflect.Value, error) { switch v.Kind() { case reflect.Interface: elem := v.Elem() @@ -303,6 +338,10 @@ func (d *decoder) handleArrayTableCollectionLast(key ast.Iterator, v reflect.Val reflect.Copy(nelem, elem) elem = nelem } + if d.clearArrayTable && elem.Len() > 0 { + elem.SetLen(0) + d.clearArrayTable = false + } } return d.handleArrayTableCollectionLast(key, elem) case reflect.Ptr: @@ -321,6 +360,10 @@ func (d *decoder) handleArrayTableCollectionLast(key ast.Iterator, v reflect.Val return v, nil case reflect.Slice: + if d.clearArrayTable && v.Len() > 0 { + v.SetLen(0) + d.clearArrayTable = false + } elemType := v.Type().Elem() var elem reflect.Value if elemType.Kind() == reflect.Interface { @@ -339,13 +382,13 @@ func (d *decoder) handleArrayTableCollectionLast(key ast.Iterator, v reflect.Val case reflect.Array: idx := d.arrayIndex(true, v) if idx >= v.Len() { - return v, fmt.Errorf("toml: cannot decode array table into %s at position %d", v.Type(), idx) + return v, fmt.Errorf("%s at position %d", d.typeMismatchError("array table", v.Type()), idx) } elem := v.Index(idx) _, err := d.handleArrayTable(key, elem) return v, err default: - return reflect.Value{}, fmt.Errorf("toml: cannot decode array table into a %s", v.Type()) + return reflect.Value{}, d.typeMismatchError("array table", v.Type()) } } @@ -353,7 +396,7 @@ func (d *decoder) handleArrayTableCollectionLast(key ast.Iterator, v reflect.Val // evaluated like a normal key, but if it returns a collection, it also needs to // point to the last element of the collection. Unless it is the last part of // the key, then it needs to create a new element at the end. -func (d *decoder) handleArrayTableCollection(key ast.Iterator, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleArrayTableCollection(key unstable.Iterator, v reflect.Value) (reflect.Value, error) { if key.IsLast() { return d.handleArrayTableCollectionLast(key, v) } @@ -390,7 +433,7 @@ func (d *decoder) handleArrayTableCollection(key ast.Iterator, v reflect.Value) case reflect.Array: idx := d.arrayIndex(false, v) if idx >= v.Len() { - return v, fmt.Errorf("toml: cannot decode array table into %s at position %d", v.Type(), idx) + return v, fmt.Errorf("%s at position %d", d.typeMismatchError("array table", v.Type()), idx) } elem := v.Index(idx) _, err := d.handleArrayTable(key, elem) @@ -400,7 +443,7 @@ func (d *decoder) handleArrayTableCollection(key ast.Iterator, v reflect.Value) return d.handleArrayTable(key, v) } -func (d *decoder) handleKeyPart(key ast.Iterator, v reflect.Value, nextFn handlerFn, makeFn valueMakerFn) (reflect.Value, error) { +func (d *decoder) handleKeyPart(key unstable.Iterator, v reflect.Value, nextFn handlerFn, makeFn valueMakerFn) (reflect.Value, error) { var rv reflect.Value // First, dispatch over v to make sure it is a valid object. @@ -417,7 +460,10 @@ func (d *decoder) handleKeyPart(key ast.Iterator, v reflect.Value, nextFn handle vt := v.Type() // Create the key for the map element. Convert to key type. - mk := reflect.ValueOf(string(key.Node().Data)).Convert(vt.Key()) + mk, err := d.keyFromData(vt.Key(), key.Node().Data) + if err != nil { + return reflect.Value{}, err + } // If the map does not exist, create it. if v.IsNil() { @@ -518,7 +564,7 @@ func (d *decoder) handleKeyPart(key ast.Iterator, v reflect.Value, nextFn handle // HandleArrayTablePart navigates the Go structure v using the key v. It is // only used for the prefix (non-last) parts of an array-table. When // encountering a collection, it should go to the last element. -func (d *decoder) handleArrayTablePart(key ast.Iterator, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleArrayTablePart(key unstable.Iterator, v reflect.Value) (reflect.Value, error) { var makeFn valueMakerFn if key.IsLast() { makeFn = makeSliceInterface @@ -530,10 +576,10 @@ func (d *decoder) handleArrayTablePart(key ast.Iterator, v reflect.Value) (refle // HandleTable returns a reference when it has checked the next expression but // cannot handle it. -func (d *decoder) handleTable(key ast.Iterator, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleTable(key unstable.Iterator, v reflect.Value) (reflect.Value, error) { if v.Kind() == reflect.Slice { if v.Len() == 0 { - return reflect.Value{}, newDecodeError(key.Node().Data, "cannot store a table in a slice") + return reflect.Value{}, unstable.NewParserError(key.Node().Data, "cannot store a table in a slice") } elem := v.Index(v.Len() - 1) x, err := d.handleTable(key, elem) @@ -560,7 +606,7 @@ func (d *decoder) handleKeyValues(v reflect.Value) (reflect.Value, error) { var rv reflect.Value for d.nextExpr() { expr := d.expr() - if expr.Kind != ast.KeyValue { + if expr.Kind != unstable.KeyValue { // Stash the expression so that fromParser can just loop and use // the right handler. // We could just recurse ourselves here, but at least this gives a @@ -569,7 +615,7 @@ func (d *decoder) handleKeyValues(v reflect.Value) (reflect.Value, error) { break } - err := d.seen.CheckExpression(expr) + _, err := d.seen.CheckExpression(expr) if err != nil { return reflect.Value{}, err } @@ -587,7 +633,7 @@ func (d *decoder) handleKeyValues(v reflect.Value) (reflect.Value, error) { } type ( - handlerFn func(key ast.Iterator, v reflect.Value) (reflect.Value, error) + handlerFn func(key unstable.Iterator, v reflect.Value) (reflect.Value, error) valueMakerFn func() reflect.Value ) @@ -599,11 +645,11 @@ func makeSliceInterface() reflect.Value { return reflect.MakeSlice(sliceInterfaceType, 0, 16) } -func (d *decoder) handleTablePart(key ast.Iterator, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleTablePart(key unstable.Iterator, v reflect.Value) (reflect.Value, error) { return d.handleKeyPart(key, v, d.handleTable, makeMapStringInterface) } -func (d *decoder) tryTextUnmarshaler(node *ast.Node, v reflect.Value) (bool, error) { +func (d *decoder) tryTextUnmarshaler(node *unstable.Node, v reflect.Value) (bool, error) { // Special case for time, because we allow to unmarshal to it from // different kind of AST nodes. if v.Type() == timeType { @@ -613,7 +659,7 @@ func (d *decoder) tryTextUnmarshaler(node *ast.Node, v reflect.Value) (bool, err if v.CanAddr() && v.Addr().Type().Implements(textUnmarshalerType) { err := v.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText(node.Data) if err != nil { - return false, newDecodeError(d.p.Raw(node.Raw), "%w", err) + return false, unstable.NewParserError(d.p.Raw(node.Raw), "%w", err) } return true, nil @@ -622,43 +668,51 @@ func (d *decoder) tryTextUnmarshaler(node *ast.Node, v reflect.Value) (bool, err return false, nil } -func (d *decoder) handleValue(value *ast.Node, v reflect.Value) error { +func (d *decoder) handleValue(value *unstable.Node, v reflect.Value) error { for v.Kind() == reflect.Ptr { v = initAndDereferencePointer(v) } + if d.unmarshalerInterface { + if v.CanAddr() && v.Addr().CanInterface() { + if outi, ok := v.Addr().Interface().(unstable.Unmarshaler); ok { + return outi.UnmarshalTOML(value) + } + } + } + ok, err := d.tryTextUnmarshaler(value, v) if ok || err != nil { return err } switch value.Kind { - case ast.String: + case unstable.String: return d.unmarshalString(value, v) - case ast.Integer: + case unstable.Integer: return d.unmarshalInteger(value, v) - case ast.Float: + case unstable.Float: return d.unmarshalFloat(value, v) - case ast.Bool: + case unstable.Bool: return d.unmarshalBool(value, v) - case ast.DateTime: + case unstable.DateTime: return d.unmarshalDateTime(value, v) - case ast.LocalDate: + case unstable.LocalDate: return d.unmarshalLocalDate(value, v) - case ast.LocalTime: + case unstable.LocalTime: return d.unmarshalLocalTime(value, v) - case ast.LocalDateTime: + case unstable.LocalDateTime: return d.unmarshalLocalDateTime(value, v) - case ast.InlineTable: + case unstable.InlineTable: return d.unmarshalInlineTable(value, v) - case ast.Array: + case unstable.Array: return d.unmarshalArray(value, v) default: panic(fmt.Errorf("handleValue not implemented for %s", value.Kind)) } } -func (d *decoder) unmarshalArray(array *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalArray(array *unstable.Node, v reflect.Value) error { switch v.Kind() { case reflect.Slice: if v.IsNil() { @@ -729,7 +783,7 @@ func (d *decoder) unmarshalArray(array *ast.Node, v reflect.Value) error { return nil } -func (d *decoder) unmarshalInlineTable(itable *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalInlineTable(itable *unstable.Node, v reflect.Value) error { // Make sure v is an initialized object. switch v.Kind() { case reflect.Map: @@ -746,7 +800,7 @@ func (d *decoder) unmarshalInlineTable(itable *ast.Node, v reflect.Value) error } return d.unmarshalInlineTable(itable, elem) default: - return newDecodeError(itable.Data, "cannot store inline table in Go type %s", v.Kind()) + return unstable.NewParserError(d.p.Raw(itable.Raw), "cannot store inline table in Go type %s", v.Kind()) } it := itable.Children() @@ -765,7 +819,7 @@ func (d *decoder) unmarshalInlineTable(itable *ast.Node, v reflect.Value) error return nil } -func (d *decoder) unmarshalDateTime(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalDateTime(value *unstable.Node, v reflect.Value) error { dt, err := parseDateTime(value.Data) if err != nil { return err @@ -775,7 +829,7 @@ func (d *decoder) unmarshalDateTime(value *ast.Node, v reflect.Value) error { return nil } -func (d *decoder) unmarshalLocalDate(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalLocalDate(value *unstable.Node, v reflect.Value) error { ld, err := parseLocalDate(value.Data) if err != nil { return err @@ -792,28 +846,28 @@ func (d *decoder) unmarshalLocalDate(value *ast.Node, v reflect.Value) error { return nil } -func (d *decoder) unmarshalLocalTime(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalLocalTime(value *unstable.Node, v reflect.Value) error { lt, rest, err := parseLocalTime(value.Data) if err != nil { return err } if len(rest) > 0 { - return newDecodeError(rest, "extra characters at the end of a local time") + return unstable.NewParserError(rest, "extra characters at the end of a local time") } v.Set(reflect.ValueOf(lt)) return nil } -func (d *decoder) unmarshalLocalDateTime(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalLocalDateTime(value *unstable.Node, v reflect.Value) error { ldt, rest, err := parseLocalDateTime(value.Data) if err != nil { return err } if len(rest) > 0 { - return newDecodeError(rest, "extra characters at the end of a local date time") + return unstable.NewParserError(rest, "extra characters at the end of a local date time") } if v.Type() == timeType { @@ -828,7 +882,7 @@ func (d *decoder) unmarshalLocalDateTime(value *ast.Node, v reflect.Value) error return nil } -func (d *decoder) unmarshalBool(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalBool(value *unstable.Node, v reflect.Value) error { b := value.Data[0] == 't' switch v.Kind() { @@ -837,13 +891,13 @@ func (d *decoder) unmarshalBool(value *ast.Node, v reflect.Value) error { case reflect.Interface: v.Set(reflect.ValueOf(b)) default: - return newDecodeError(value.Data, "cannot assign boolean to a %t", b) + return unstable.NewParserError(value.Data, "cannot assign boolean to a %t", b) } return nil } -func (d *decoder) unmarshalFloat(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalFloat(value *unstable.Node, v reflect.Value) error { f, err := parseFloat(value.Data) if err != nil { return err @@ -854,13 +908,13 @@ func (d *decoder) unmarshalFloat(value *ast.Node, v reflect.Value) error { v.SetFloat(f) case reflect.Float32: if f > math.MaxFloat32 { - return newDecodeError(value.Data, "number %f does not fit in a float32", f) + return unstable.NewParserError(value.Data, "number %f does not fit in a float32", f) } v.SetFloat(f) case reflect.Interface: v.Set(reflect.ValueOf(f)) default: - return newDecodeError(value.Data, "float cannot be assigned to %s", v.Kind()) + return unstable.NewParserError(value.Data, "float cannot be assigned to %s", v.Kind()) } return nil @@ -886,7 +940,12 @@ func init() { } } -func (d *decoder) unmarshalInteger(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalInteger(value *unstable.Node, v reflect.Value) error { + kind := v.Kind() + if kind == reflect.Float32 || kind == reflect.Float64 { + return d.unmarshalFloat(value, v) + } + i, err := parseInteger(value.Data) if err != nil { return err @@ -894,7 +953,7 @@ func (d *decoder) unmarshalInteger(value *ast.Node, v reflect.Value) error { var r reflect.Value - switch v.Kind() { + switch kind { case reflect.Int64: v.SetInt(i) return nil @@ -955,7 +1014,7 @@ func (d *decoder) unmarshalInteger(value *ast.Node, v reflect.Value) error { case reflect.Interface: r = reflect.ValueOf(i) default: - return d.typeMismatchError("integer", v.Type()) + return unstable.NewParserError(d.p.Raw(value.Raw), d.typeMismatchString("integer", v.Type())) } if !r.Type().AssignableTo(v.Type()) { @@ -967,20 +1026,20 @@ func (d *decoder) unmarshalInteger(value *ast.Node, v reflect.Value) error { return nil } -func (d *decoder) unmarshalString(value *ast.Node, v reflect.Value) error { +func (d *decoder) unmarshalString(value *unstable.Node, v reflect.Value) error { switch v.Kind() { case reflect.String: v.SetString(string(value.Data)) case reflect.Interface: v.Set(reflect.ValueOf(string(value.Data))) default: - return newDecodeError(d.p.Raw(value.Raw), "cannot store TOML string into a Go %s", v.Kind()) + return unstable.NewParserError(d.p.Raw(value.Raw), d.typeMismatchString("string", v.Type())) } return nil } -func (d *decoder) handleKeyValue(expr *ast.Node, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleKeyValue(expr *unstable.Node, v reflect.Value) (reflect.Value, error) { d.strict.EnterKeyValue(expr) v, err := d.handleKeyValueInner(expr.Key(), expr.Value(), v) @@ -994,7 +1053,7 @@ func (d *decoder) handleKeyValue(expr *ast.Node, v reflect.Value) (reflect.Value return v, err } -func (d *decoder) handleKeyValueInner(key ast.Iterator, value *ast.Node, v reflect.Value) (reflect.Value, error) { +func (d *decoder) handleKeyValueInner(key unstable.Iterator, value *unstable.Node, v reflect.Value) (reflect.Value, error) { if key.Next() { // Still scoping the key return d.handleKeyValuePart(key, value, v) @@ -1004,7 +1063,32 @@ func (d *decoder) handleKeyValueInner(key ast.Iterator, value *ast.Node, v refle return reflect.Value{}, d.handleValue(value, v) } -func (d *decoder) handleKeyValuePart(key ast.Iterator, value *ast.Node, v reflect.Value) (reflect.Value, error) { +func (d *decoder) keyFromData(keyType reflect.Type, data []byte) (reflect.Value, error) { + switch { + case stringType.AssignableTo(keyType): + return reflect.ValueOf(string(data)), nil + + case stringType.ConvertibleTo(keyType): + return reflect.ValueOf(string(data)).Convert(keyType), nil + + case keyType.Implements(textUnmarshalerType): + mk := reflect.New(keyType.Elem()) + if err := mk.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { + return reflect.Value{}, fmt.Errorf("toml: error unmarshalling key type %s from text: %w", stringType, err) + } + return mk, nil + + case reflect.PtrTo(keyType).Implements(textUnmarshalerType): + mk := reflect.New(keyType) + if err := mk.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { + return reflect.Value{}, fmt.Errorf("toml: error unmarshalling key type %s from text: %w", stringType, err) + } + return mk.Elem(), nil + } + return reflect.Value{}, fmt.Errorf("toml: cannot convert map key of type %s to expected type %s", stringType, keyType) +} + +func (d *decoder) handleKeyValuePart(key unstable.Iterator, value *unstable.Node, v reflect.Value) (reflect.Value, error) { // contains the replacement for v var rv reflect.Value @@ -1014,16 +1098,9 @@ func (d *decoder) handleKeyValuePart(key ast.Iterator, value *ast.Node, v reflec case reflect.Map: vt := v.Type() - mk := reflect.ValueOf(string(key.Node().Data)) - mkt := stringType - - keyType := vt.Key() - if !mkt.AssignableTo(keyType) { - if !mkt.ConvertibleTo(keyType) { - return reflect.Value{}, fmt.Errorf("toml: cannot convert map key of type %s to expected type %s", mkt, keyType) - } - - mk = mk.Convert(keyType) + mk, err := d.keyFromData(vt.Key(), key.Node().Data) + if err != nil { + return reflect.Value{}, err } // If the map does not exist, create it. @@ -1034,15 +1111,9 @@ func (d *decoder) handleKeyValuePart(key ast.Iterator, value *ast.Node, v reflec mv := v.MapIndex(mk) set := false - if !mv.IsValid() { + if !mv.IsValid() || key.IsLast() { set = true mv = reflect.New(v.Type().Elem()).Elem() - } else { - if key.IsLast() { - var x interface{} - mv = reflect.ValueOf(&x).Elem() - set = true - } } nv, err := d.handleKeyValueInner(key, value, mv) @@ -1072,6 +1143,19 @@ func (d *decoder) handleKeyValuePart(key ast.Iterator, value *ast.Node, v reflec d.errorContext.Field = path f := fieldByIndex(v, path) + + if !f.CanAddr() { + // If the field is not addressable, need to take a slower path and + // make a copy of the struct itself to a new location. + nvp := reflect.New(v.Type()) + nvp.Elem().Set(v) + v = nvp.Elem() + _, err := d.handleKeyValuePart(key, value, v) + if err != nil { + return reflect.Value{}, err + } + return nvp.Elem(), nil + } x, err := d.handleKeyValueInner(key, value, f) if err != nil { return reflect.Value{}, err @@ -1137,10 +1221,10 @@ func initAndDereferencePointer(v reflect.Value) reflect.Value { // Same as reflect.Value.FieldByIndex, but creates pointers if needed. func fieldByIndex(v reflect.Value, path []int) reflect.Value { - for i, x := range path { + for _, x := range path { v = v.Field(x) - if i < len(path)-1 && v.Kind() == reflect.Ptr { + if v.Kind() == reflect.Ptr { if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/ast.go b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/ast.go similarity index 60% rename from tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/ast.go rename to tools/vendor/github.com/pelletier/go-toml/v2/unstable/ast.go index 9dec2e000..f526bf2c0 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/ast.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/ast.go @@ -1,4 +1,4 @@ -package ast +package unstable import ( "fmt" @@ -7,13 +7,16 @@ import ( "github.com/pelletier/go-toml/v2/internal/danger" ) -// Iterator starts uninitialized, you need to call Next() first. +// Iterator over a sequence of nodes. +// +// Starts uninitialized, you need to call Next() first. // // For example: // // it := n.Children() // for it.Next() { -// it.Node() +// n := it.Node() +// // do something with n // } type Iterator struct { started bool @@ -32,42 +35,31 @@ func (c *Iterator) Next() bool { } // IsLast returns true if the current node of the iterator is the last -// one. Subsequent call to Next() will return false. +// one. Subsequent calls to Next() will return false. func (c *Iterator) IsLast() bool { return c.node.next == 0 } -// Node returns a copy of the node pointed at by the iterator. +// Node returns a pointer to the node pointed at by the iterator. func (c *Iterator) Node() *Node { return c.node } -// Root contains a full AST. +// Node in a TOML expression AST. // -// It is immutable once constructed with Builder. -type Root struct { - nodes []Node -} - -// Iterator over the top level nodes. -func (r *Root) Iterator() Iterator { - it := Iterator{} - if len(r.nodes) > 0 { - it.node = &r.nodes[0] - } - return it -} - -func (r *Root) at(idx Reference) *Node { - return &r.nodes[idx] -} - -// Arrays have one child per element in the array. InlineTables have -// one child per key-value pair in the table. KeyValues have at least -// two children. The first one is the value. The rest make a -// potentially dotted key. Table and Array table have one child per -// element of the key they represent (same as KeyValue, but without -// the last node being the value). +// Depending on Kind, its sequence of children should be interpreted +// differently. +// +// - Array have one child per element in the array. +// - InlineTable have one child per key-value in the table (each of kind +// InlineTable). +// - KeyValue have at least two children. The first one is the value. The rest +// make a potentially dotted key. +// - Table and ArrayTable's children represent a dotted key (same as +// KeyValue, but without the first node being the value). +// +// When relevant, Raw describes the range of bytes this node is referring to in +// the input document. Use Parser.Raw() to retrieve the actual bytes. type Node struct { Kind Kind Raw Range // Raw bytes from the input. @@ -80,13 +72,13 @@ type Node struct { child int // 0 if no child } +// Range of bytes in the document. type Range struct { Offset uint32 Length uint32 } -// Next returns a copy of the next node, or an invalid Node if there -// is no next node. +// Next returns a pointer to the next node, or nil if there is no next node. func (n *Node) Next() *Node { if n.next == 0 { return nil @@ -96,9 +88,9 @@ func (n *Node) Next() *Node { return (*Node)(danger.Stride(ptr, size, n.next)) } -// Child returns a copy of the first child node of this node. Other -// children can be accessed calling Next on the first child. Returns -// an invalid Node if there is none. +// Child returns a pointer to the first child node of this node. Other children +// can be accessed calling Next on the first child. Returns an nil if this Node +// has no child. func (n *Node) Child() *Node { if n.child == 0 { return nil @@ -113,9 +105,9 @@ func (n *Node) Valid() bool { return n != nil } -// Key returns the child nodes making the Key on a supported -// node. Panics otherwise. They are guaranteed to be all be of the -// Kind Key. A simple key would return just one element. +// Key returns the children nodes making the Key on a supported node. Panics +// otherwise. They are guaranteed to be all be of the Kind Key. A simple key +// would return just one element. func (n *Node) Key() Iterator { switch n.Kind { case KeyValue: diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/unstable/builder.go b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/builder.go new file mode 100644 index 000000000..9538e30df --- /dev/null +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/builder.go @@ -0,0 +1,71 @@ +package unstable + +// root contains a full AST. +// +// It is immutable once constructed with Builder. +type root struct { + nodes []Node +} + +// Iterator over the top level nodes. +func (r *root) Iterator() Iterator { + it := Iterator{} + if len(r.nodes) > 0 { + it.node = &r.nodes[0] + } + return it +} + +func (r *root) at(idx reference) *Node { + return &r.nodes[idx] +} + +type reference int + +const invalidReference reference = -1 + +func (r reference) Valid() bool { + return r != invalidReference +} + +type builder struct { + tree root + lastIdx int +} + +func (b *builder) Tree() *root { + return &b.tree +} + +func (b *builder) NodeAt(ref reference) *Node { + return b.tree.at(ref) +} + +func (b *builder) Reset() { + b.tree.nodes = b.tree.nodes[:0] + b.lastIdx = 0 +} + +func (b *builder) Push(n Node) reference { + b.lastIdx = len(b.tree.nodes) + b.tree.nodes = append(b.tree.nodes, n) + return reference(b.lastIdx) +} + +func (b *builder) PushAndChain(n Node) reference { + newIdx := len(b.tree.nodes) + b.tree.nodes = append(b.tree.nodes, n) + if b.lastIdx >= 0 { + b.tree.nodes[b.lastIdx].next = newIdx - b.lastIdx + } + b.lastIdx = newIdx + return reference(b.lastIdx) +} + +func (b *builder) AttachChild(parent reference, child reference) { + b.tree.nodes[parent].child = int(child) - int(parent) +} + +func (b *builder) Chain(from reference, to reference) { + b.tree.nodes[from].next = int(to) - int(from) +} diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/unstable/doc.go b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/doc.go new file mode 100644 index 000000000..7ff26c53c --- /dev/null +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/doc.go @@ -0,0 +1,3 @@ +// Package unstable provides APIs that do not meet the backward compatibility +// guarantees yet. +package unstable diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/kind.go b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/kind.go similarity index 81% rename from tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/kind.go rename to tools/vendor/github.com/pelletier/go-toml/v2/unstable/kind.go index 2b50c67fc..ff9df1bef 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/internal/ast/kind.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/kind.go @@ -1,25 +1,26 @@ -package ast +package unstable import "fmt" +// Kind represents the type of TOML structure contained in a given Node. type Kind int const ( - // meta + // Meta Invalid Kind = iota Comment Key - // top level structures + // Top level structures Table ArrayTable KeyValue - // containers values + // Containers values Array InlineTable - // values + // Values String Bool Float @@ -30,6 +31,7 @@ const ( DateTime ) +// String implementation of fmt.Stringer. func (k Kind) String() string { switch k { case Invalid: diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/parser.go b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/parser.go similarity index 62% rename from tools/vendor/github.com/pelletier/go-toml/v2/parser.go rename to tools/vendor/github.com/pelletier/go-toml/v2/unstable/parser.go index 9859a795b..50358a44f 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/parser.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/parser.go @@ -1,50 +1,108 @@ -package toml +package unstable import ( "bytes" + "fmt" "unicode" - "github.com/pelletier/go-toml/v2/internal/ast" + "github.com/pelletier/go-toml/v2/internal/characters" "github.com/pelletier/go-toml/v2/internal/danger" ) -type parser struct { - builder ast.Builder - ref ast.Reference +// ParserError describes an error relative to the content of the document. +// +// It cannot outlive the instance of Parser it refers to, and may cause panics +// if the parser is reset. +type ParserError struct { + Highlight []byte + Message string + Key []string // optional +} + +// Error is the implementation of the error interface. +func (e *ParserError) Error() string { + return e.Message +} + +// NewParserError is a convenience function to create a ParserError +// +// Warning: Highlight needs to be a subslice of Parser.data, so only slices +// returned by Parser.Raw are valid candidates. +func NewParserError(highlight []byte, format string, args ...interface{}) error { + return &ParserError{ + Highlight: highlight, + Message: fmt.Errorf(format, args...).Error(), + } +} + +// Parser scans over a TOML-encoded document and generates an iterative AST. +// +// To prime the Parser, first reset it with the contents of a TOML document. +// Then, process all top-level expressions sequentially. See Example. +// +// Don't forget to check Error() after you're done parsing. +// +// Each top-level expression needs to be fully processed before calling +// NextExpression() again. Otherwise, calls to various Node methods may panic if +// the parser has moved on the next expression. +// +// For performance reasons, go-toml doesn't make a copy of the input bytes to +// the parser. Make sure to copy all the bytes you need to outlive the slice +// given to the parser. +type Parser struct { data []byte + builder builder + ref reference left []byte err error first bool + + KeepComments bool +} + +// Data returns the slice provided to the last call to Reset. +func (p *Parser) Data() []byte { + return p.data } -func (p *parser) Range(b []byte) ast.Range { - return ast.Range{ +// Range returns a range description that corresponds to a given slice of the +// input. If the argument is not a subslice of the parser input, this function +// panics. +func (p *Parser) Range(b []byte) Range { + return Range{ Offset: uint32(danger.SubsliceOffset(p.data, b)), Length: uint32(len(b)), } } -func (p *parser) Raw(raw ast.Range) []byte { +// Raw returns the slice corresponding to the bytes in the given range. +func (p *Parser) Raw(raw Range) []byte { return p.data[raw.Offset : raw.Offset+raw.Length] } -func (p *parser) Reset(b []byte) { +// Reset brings the parser to its initial state for a given input. It wipes an +// reuses internal storage to reduce allocation. +func (p *Parser) Reset(b []byte) { p.builder.Reset() - p.ref = ast.InvalidReference + p.ref = invalidReference p.data = b p.left = b p.err = nil p.first = true } -//nolint:cyclop -func (p *parser) NextExpression() bool { +// NextExpression parses the next top-level expression. If an expression was +// successfully parsed, it returns true. If the parser is at the end of the +// document or an error occurred, it returns false. +// +// Retrieve the parsed expression with Expression(). +func (p *Parser) NextExpression() bool { if len(p.left) == 0 || p.err != nil { return false } p.builder.Reset() - p.ref = ast.InvalidReference + p.ref = invalidReference for { if len(p.left) == 0 || p.err != nil { @@ -73,15 +131,56 @@ func (p *parser) NextExpression() bool { } } -func (p *parser) Expression() *ast.Node { +// Expression returns a pointer to the node representing the last successfully +// parsed expression. +func (p *Parser) Expression() *Node { return p.builder.NodeAt(p.ref) } -func (p *parser) Error() error { +// Error returns any error that has occurred during parsing. +func (p *Parser) Error() error { return p.err } -func (p *parser) parseNewline(b []byte) ([]byte, error) { +// Position describes a position in the input. +type Position struct { + // Number of bytes from the beginning of the input. + Offset int + // Line number, starting at 1. + Line int + // Column number, starting at 1. + Column int +} + +// Shape describes the position of a range in the input. +type Shape struct { + Start Position + End Position +} + +func (p *Parser) position(b []byte) Position { + offset := danger.SubsliceOffset(p.data, b) + + lead := p.data[:offset] + + return Position{ + Offset: offset, + Line: bytes.Count(lead, []byte{'\n'}) + 1, + Column: len(lead) - bytes.LastIndex(lead, []byte{'\n'}), + } +} + +// Shape returns the shape of the given range in the input. Will +// panic if the range is not a subslice of the input. +func (p *Parser) Shape(r Range) Shape { + raw := p.Raw(r) + return Shape{ + Start: p.position(raw), + End: p.position(raw[r.Length:]), + } +} + +func (p *Parser) parseNewline(b []byte) ([]byte, error) { if b[0] == '\n' { return b[1:], nil } @@ -91,14 +190,27 @@ func (p *parser) parseNewline(b []byte) ([]byte, error) { return rest, err } - return nil, newDecodeError(b[0:1], "expected newline but got %#U", b[0]) + return nil, NewParserError(b[0:1], "expected newline but got %#U", b[0]) +} + +func (p *Parser) parseComment(b []byte) (reference, []byte, error) { + ref := invalidReference + data, rest, err := scanComment(b) + if p.KeepComments && err == nil { + ref = p.builder.Push(Node{ + Kind: Comment, + Raw: p.Range(data), + Data: data, + }) + } + return ref, rest, err } -func (p *parser) parseExpression(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseExpression(b []byte) (reference, []byte, error) { // expression = ws [ comment ] // expression =/ ws keyval ws [ comment ] // expression =/ ws table ws [ comment ] - ref := ast.InvalidReference + ref := invalidReference b = p.parseWhitespace(b) @@ -107,7 +219,7 @@ func (p *parser) parseExpression(b []byte) (ast.Reference, []byte, error) { } if b[0] == '#' { - _, rest, err := scanComment(b) + ref, rest, err := p.parseComment(b) return ref, rest, err } @@ -129,14 +241,17 @@ func (p *parser) parseExpression(b []byte) (ast.Reference, []byte, error) { b = p.parseWhitespace(b) if len(b) > 0 && b[0] == '#' { - _, rest, err := scanComment(b) + cref, rest, err := p.parseComment(b) + if cref != invalidReference { + p.builder.Chain(ref, cref) + } return ref, rest, err } return ref, b, nil } -func (p *parser) parseTable(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseTable(b []byte) (reference, []byte, error) { // table = std-table / array-table if len(b) > 1 && b[1] == '[' { return p.parseArrayTable(b) @@ -145,12 +260,12 @@ func (p *parser) parseTable(b []byte) (ast.Reference, []byte, error) { return p.parseStdTable(b) } -func (p *parser) parseArrayTable(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseArrayTable(b []byte) (reference, []byte, error) { // array-table = array-table-open key array-table-close // array-table-open = %x5B.5B ws ; [[ Double left square bracket // array-table-close = ws %x5D.5D ; ]] Double right square bracket - ref := p.builder.Push(ast.Node{ - Kind: ast.ArrayTable, + ref := p.builder.Push(Node{ + Kind: ArrayTable, }) b = b[2:] @@ -174,12 +289,12 @@ func (p *parser) parseArrayTable(b []byte) (ast.Reference, []byte, error) { return ref, b, err } -func (p *parser) parseStdTable(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseStdTable(b []byte) (reference, []byte, error) { // std-table = std-table-open key std-table-close // std-table-open = %x5B ws ; [ Left square bracket // std-table-close = ws %x5D ; ] Right square bracket - ref := p.builder.Push(ast.Node{ - Kind: ast.Table, + ref := p.builder.Push(Node{ + Kind: Table, }) b = b[1:] @@ -199,15 +314,15 @@ func (p *parser) parseStdTable(b []byte) (ast.Reference, []byte, error) { return ref, b, err } -func (p *parser) parseKeyval(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseKeyval(b []byte) (reference, []byte, error) { // keyval = key keyval-sep val - ref := p.builder.Push(ast.Node{ - Kind: ast.KeyValue, + ref := p.builder.Push(Node{ + Kind: KeyValue, }) key, b, err := p.parseKey(b) if err != nil { - return ast.InvalidReference, nil, err + return invalidReference, nil, err } // keyval-sep = ws %x3D ws ; = @@ -215,12 +330,12 @@ func (p *parser) parseKeyval(b []byte) (ast.Reference, []byte, error) { b = p.parseWhitespace(b) if len(b) == 0 { - return ast.InvalidReference, nil, newDecodeError(b, "expected = after a key, but the document ends there") + return invalidReference, nil, NewParserError(b, "expected = after a key, but the document ends there") } b, err = expect('=', b) if err != nil { - return ast.InvalidReference, nil, err + return invalidReference, nil, err } b = p.parseWhitespace(b) @@ -237,12 +352,12 @@ func (p *parser) parseKeyval(b []byte) (ast.Reference, []byte, error) { } //nolint:cyclop,funlen -func (p *parser) parseVal(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseVal(b []byte) (reference, []byte, error) { // val = string / boolean / array / inline-table / date-time / float / integer - ref := ast.InvalidReference + ref := invalidReference if len(b) == 0 { - return ref, nil, newDecodeError(b, "expected value, not eof") + return ref, nil, NewParserError(b, "expected value, not eof") } var err error @@ -259,8 +374,8 @@ func (p *parser) parseVal(b []byte) (ast.Reference, []byte, error) { } if err == nil { - ref = p.builder.Push(ast.Node{ - Kind: ast.String, + ref = p.builder.Push(Node{ + Kind: String, Raw: p.Range(raw), Data: v, }) @@ -277,8 +392,8 @@ func (p *parser) parseVal(b []byte) (ast.Reference, []byte, error) { } if err == nil { - ref = p.builder.Push(ast.Node{ - Kind: ast.String, + ref = p.builder.Push(Node{ + Kind: String, Raw: p.Range(raw), Data: v, }) @@ -287,22 +402,22 @@ func (p *parser) parseVal(b []byte) (ast.Reference, []byte, error) { return ref, b, err case 't': if !scanFollowsTrue(b) { - return ref, nil, newDecodeError(atmost(b, 4), "expected 'true'") + return ref, nil, NewParserError(atmost(b, 4), "expected 'true'") } - ref = p.builder.Push(ast.Node{ - Kind: ast.Bool, + ref = p.builder.Push(Node{ + Kind: Bool, Data: b[:4], }) return ref, b[4:], nil case 'f': if !scanFollowsFalse(b) { - return ref, nil, newDecodeError(atmost(b, 5), "expected 'false'") + return ref, nil, NewParserError(atmost(b, 5), "expected 'false'") } - ref = p.builder.Push(ast.Node{ - Kind: ast.Bool, + ref = p.builder.Push(Node{ + Kind: Bool, Data: b[:5], }) @@ -324,7 +439,7 @@ func atmost(b []byte, n int) []byte { return b[:n] } -func (p *parser) parseLiteralString(b []byte) ([]byte, []byte, []byte, error) { +func (p *Parser) parseLiteralString(b []byte) ([]byte, []byte, []byte, error) { v, rest, err := scanLiteralString(b) if err != nil { return nil, nil, nil, err @@ -333,19 +448,20 @@ func (p *parser) parseLiteralString(b []byte) ([]byte, []byte, []byte, error) { return v, v[1 : len(v)-1], rest, nil } -func (p *parser) parseInlineTable(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseInlineTable(b []byte) (reference, []byte, error) { // inline-table = inline-table-open [ inline-table-keyvals ] inline-table-close // inline-table-open = %x7B ws ; { // inline-table-close = ws %x7D ; } // inline-table-sep = ws %x2C ws ; , Comma // inline-table-keyvals = keyval [ inline-table-sep inline-table-keyvals ] - parent := p.builder.Push(ast.Node{ - Kind: ast.InlineTable, + parent := p.builder.Push(Node{ + Kind: InlineTable, + Raw: p.Range(b[:1]), }) first := true - var child ast.Reference + var child reference b = b[1:] @@ -356,7 +472,7 @@ func (p *parser) parseInlineTable(b []byte) (ast.Reference, []byte, error) { b = p.parseWhitespace(b) if len(b) == 0 { - return parent, nil, newDecodeError(previousB[:1], "inline table is incomplete") + return parent, nil, NewParserError(previousB[:1], "inline table is incomplete") } if b[0] == '}' { @@ -371,7 +487,7 @@ func (p *parser) parseInlineTable(b []byte) (ast.Reference, []byte, error) { b = p.parseWhitespace(b) } - var kv ast.Reference + var kv reference kv, b, err = p.parseKeyval(b) if err != nil { @@ -394,7 +510,7 @@ func (p *parser) parseInlineTable(b []byte) (ast.Reference, []byte, error) { } //nolint:funlen,cyclop -func (p *parser) parseValArray(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseValArray(b []byte) (reference, []byte, error) { // array = array-open [ array-values ] ws-comment-newline array-close // array-open = %x5B ; [ // array-close = %x5D ; ] @@ -405,23 +521,39 @@ func (p *parser) parseValArray(b []byte) (ast.Reference, []byte, error) { arrayStart := b b = b[1:] - parent := p.builder.Push(ast.Node{ - Kind: ast.Array, + parent := p.builder.Push(Node{ + Kind: Array, }) + // First indicates whether the parser is looking for the first element + // (non-comment) of the array. first := true - var lastChild ast.Reference + lastChild := invalidReference + + addChild := func(valueRef reference) { + if lastChild == invalidReference { + p.builder.AttachChild(parent, valueRef) + } else { + p.builder.Chain(lastChild, valueRef) + } + lastChild = valueRef + } var err error for len(b) > 0 { - b, err = p.parseOptionalWhitespaceCommentNewline(b) + cref := invalidReference + cref, b, err = p.parseOptionalWhitespaceCommentNewline(b) if err != nil { return parent, nil, err } + if cref != invalidReference { + addChild(cref) + } + if len(b) == 0 { - return parent, nil, newDecodeError(arrayStart[:1], "array is incomplete") + return parent, nil, NewParserError(arrayStart[:1], "array is incomplete") } if b[0] == ']' { @@ -430,16 +562,19 @@ func (p *parser) parseValArray(b []byte) (ast.Reference, []byte, error) { if b[0] == ',' { if first { - return parent, nil, newDecodeError(b[0:1], "array cannot start with comma") + return parent, nil, NewParserError(b[0:1], "array cannot start with comma") } b = b[1:] - b, err = p.parseOptionalWhitespaceCommentNewline(b) + cref, b, err = p.parseOptionalWhitespaceCommentNewline(b) if err != nil { return parent, nil, err } + if cref != invalidReference { + addChild(cref) + } } else if !first { - return parent, nil, newDecodeError(b[0:1], "array elements must be separated by commas") + return parent, nil, NewParserError(b[0:1], "array elements must be separated by commas") } // TOML allows trailing commas in arrays. @@ -447,23 +582,22 @@ func (p *parser) parseValArray(b []byte) (ast.Reference, []byte, error) { break } - var valueRef ast.Reference + var valueRef reference valueRef, b, err = p.parseVal(b) if err != nil { return parent, nil, err } - if first { - p.builder.AttachChild(parent, valueRef) - } else { - p.builder.Chain(lastChild, valueRef) - } - lastChild = valueRef + addChild(valueRef) - b, err = p.parseOptionalWhitespaceCommentNewline(b) + cref, b, err = p.parseOptionalWhitespaceCommentNewline(b) if err != nil { return parent, nil, err } + if cref != invalidReference { + addChild(cref) + } + first = false } @@ -472,15 +606,34 @@ func (p *parser) parseValArray(b []byte) (ast.Reference, []byte, error) { return parent, rest, err } -func (p *parser) parseOptionalWhitespaceCommentNewline(b []byte) ([]byte, error) { +func (p *Parser) parseOptionalWhitespaceCommentNewline(b []byte) (reference, []byte, error) { + rootCommentRef := invalidReference + latestCommentRef := invalidReference + + addComment := func(ref reference) { + if rootCommentRef == invalidReference { + rootCommentRef = ref + } else if latestCommentRef == invalidReference { + p.builder.AttachChild(rootCommentRef, ref) + latestCommentRef = ref + } else { + p.builder.Chain(latestCommentRef, ref) + latestCommentRef = ref + } + } + for len(b) > 0 { var err error b = p.parseWhitespace(b) if len(b) > 0 && b[0] == '#' { - _, b, err = scanComment(b) + var ref reference + ref, b, err = p.parseComment(b) if err != nil { - return nil, err + return invalidReference, nil, err + } + if ref != invalidReference { + addComment(ref) } } @@ -491,17 +644,17 @@ func (p *parser) parseOptionalWhitespaceCommentNewline(b []byte) ([]byte, error) if b[0] == '\n' || b[0] == '\r' { b, err = p.parseNewline(b) if err != nil { - return nil, err + return invalidReference, nil, err } } else { break } } - return b, nil + return rootCommentRef, b, nil } -func (p *parser) parseMultilineLiteralString(b []byte) ([]byte, []byte, []byte, error) { +func (p *Parser) parseMultilineLiteralString(b []byte) ([]byte, []byte, []byte, error) { token, rest, err := scanMultilineLiteralString(b) if err != nil { return nil, nil, nil, err @@ -520,7 +673,7 @@ func (p *parser) parseMultilineLiteralString(b []byte) ([]byte, []byte, []byte, } //nolint:funlen,gocognit,cyclop -func (p *parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, error) { +func (p *Parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, error) { // ml-basic-string = ml-basic-string-delim [ newline ] ml-basic-body // ml-basic-string-delim // ml-basic-string-delim = 3quotation-mark @@ -551,11 +704,11 @@ func (p *parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, er if !escaped { str := token[startIdx:endIdx] - verr := utf8TomlValidAlreadyEscaped(str) + verr := characters.Utf8TomlValidAlreadyEscaped(str) if verr.Zero() { return token, str, rest, nil } - return nil, nil, nil, newDecodeError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8") + return nil, nil, nil, NewParserError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8") } var builder bytes.Buffer @@ -635,13 +788,13 @@ func (p *parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, er builder.WriteRune(x) i += 8 default: - return nil, nil, nil, newDecodeError(token[i:i+1], "invalid escaped character %#U", c) + return nil, nil, nil, NewParserError(token[i:i+1], "invalid escaped character %#U", c) } i++ } else { - size := utf8ValidNext(token[i:]) + size := characters.Utf8ValidNext(token[i:]) if size == 0 { - return nil, nil, nil, newDecodeError(token[i:i+1], "invalid character %#U", c) + return nil, nil, nil, NewParserError(token[i:i+1], "invalid character %#U", c) } builder.Write(token[i : i+size]) i += size @@ -651,7 +804,7 @@ func (p *parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, er return token, builder.Bytes(), rest, nil } -func (p *parser) parseKey(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseKey(b []byte) (reference, []byte, error) { // key = simple-key / dotted-key // simple-key = quoted-key / unquoted-key // @@ -662,11 +815,11 @@ func (p *parser) parseKey(b []byte) (ast.Reference, []byte, error) { // dot-sep = ws %x2E ws ; . Period raw, key, b, err := p.parseSimpleKey(b) if err != nil { - return ast.InvalidReference, nil, err + return invalidReference, nil, err } - ref := p.builder.Push(ast.Node{ - Kind: ast.Key, + ref := p.builder.Push(Node{ + Kind: Key, Raw: p.Range(raw), Data: key, }) @@ -681,8 +834,8 @@ func (p *parser) parseKey(b []byte) (ast.Reference, []byte, error) { return ref, nil, err } - p.builder.PushAndChain(ast.Node{ - Kind: ast.Key, + p.builder.PushAndChain(Node{ + Kind: Key, Raw: p.Range(raw), Data: key, }) @@ -694,9 +847,9 @@ func (p *parser) parseKey(b []byte) (ast.Reference, []byte, error) { return ref, b, nil } -func (p *parser) parseSimpleKey(b []byte) (raw, key, rest []byte, err error) { +func (p *Parser) parseSimpleKey(b []byte) (raw, key, rest []byte, err error) { if len(b) == 0 { - return nil, nil, nil, newDecodeError(b, "expected key but found none") + return nil, nil, nil, NewParserError(b, "expected key but found none") } // simple-key = quoted-key / unquoted-key @@ -711,12 +864,12 @@ func (p *parser) parseSimpleKey(b []byte) (raw, key, rest []byte, err error) { key, rest = scanUnquotedKey(b) return key, key, rest, nil default: - return nil, nil, nil, newDecodeError(b[0:1], "invalid character at start of key: %c", b[0]) + return nil, nil, nil, NewParserError(b[0:1], "invalid character at start of key: %c", b[0]) } } //nolint:funlen,cyclop -func (p *parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) { +func (p *Parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) { // basic-string = quotation-mark *basic-char quotation-mark // quotation-mark = %x22 ; " // basic-char = basic-unescaped / escaped @@ -744,11 +897,11 @@ func (p *parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) { // validate the string and return a direct reference to the buffer. if !escaped { str := token[startIdx:endIdx] - verr := utf8TomlValidAlreadyEscaped(str) + verr := characters.Utf8TomlValidAlreadyEscaped(str) if verr.Zero() { return token, str, rest, nil } - return nil, nil, nil, newDecodeError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8") + return nil, nil, nil, NewParserError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8") } i := startIdx @@ -795,13 +948,13 @@ func (p *parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) { builder.WriteRune(x) i += 8 default: - return nil, nil, nil, newDecodeError(token[i:i+1], "invalid escaped character %#U", c) + return nil, nil, nil, NewParserError(token[i:i+1], "invalid escaped character %#U", c) } i++ } else { - size := utf8ValidNext(token[i:]) + size := characters.Utf8ValidNext(token[i:]) if size == 0 { - return nil, nil, nil, newDecodeError(token[i:i+1], "invalid character %#U", c) + return nil, nil, nil, NewParserError(token[i:i+1], "invalid character %#U", c) } builder.Write(token[i : i+size]) i += size @@ -813,7 +966,7 @@ func (p *parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) { func hexToRune(b []byte, length int) (rune, error) { if len(b) < length { - return -1, newDecodeError(b, "unicode point needs %d character, not %d", length, len(b)) + return -1, NewParserError(b, "unicode point needs %d character, not %d", length, len(b)) } b = b[:length] @@ -828,19 +981,19 @@ func hexToRune(b []byte, length int) (rune, error) { case 'A' <= c && c <= 'F': d = uint32(c - 'A' + 10) default: - return -1, newDecodeError(b[i:i+1], "non-hex character") + return -1, NewParserError(b[i:i+1], "non-hex character") } r = r*16 + d } if r > unicode.MaxRune || 0xD800 <= r && r < 0xE000 { - return -1, newDecodeError(b, "escape sequence is invalid Unicode code point") + return -1, NewParserError(b, "escape sequence is invalid Unicode code point") } return rune(r), nil } -func (p *parser) parseWhitespace(b []byte) []byte { +func (p *Parser) parseWhitespace(b []byte) []byte { // ws = *wschar // wschar = %x20 ; Space // wschar =/ %x09 ; Horizontal tab @@ -850,25 +1003,27 @@ func (p *parser) parseWhitespace(b []byte) []byte { } //nolint:cyclop -func (p *parser) parseIntOrFloatOrDateTime(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) parseIntOrFloatOrDateTime(b []byte) (reference, []byte, error) { switch b[0] { case 'i': if !scanFollowsInf(b) { - return ast.InvalidReference, nil, newDecodeError(atmost(b, 3), "expected 'inf'") + return invalidReference, nil, NewParserError(atmost(b, 3), "expected 'inf'") } - return p.builder.Push(ast.Node{ - Kind: ast.Float, + return p.builder.Push(Node{ + Kind: Float, Data: b[:3], + Raw: p.Range(b[:3]), }), b[3:], nil case 'n': if !scanFollowsNan(b) { - return ast.InvalidReference, nil, newDecodeError(atmost(b, 3), "expected 'nan'") + return invalidReference, nil, NewParserError(atmost(b, 3), "expected 'nan'") } - return p.builder.Push(ast.Node{ - Kind: ast.Float, + return p.builder.Push(Node{ + Kind: Float, Data: b[:3], + Raw: p.Range(b[:3]), }), b[3:], nil case '+', '-': return p.scanIntOrFloat(b) @@ -898,7 +1053,7 @@ func (p *parser) parseIntOrFloatOrDateTime(b []byte) (ast.Reference, []byte, err return p.scanIntOrFloat(b) } -func (p *parser) scanDateTime(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) scanDateTime(b []byte) (reference, []byte, error) { // scans for contiguous characters in [0-9T:Z.+-], and up to one space if // followed by a digit. hasDate := false @@ -941,30 +1096,30 @@ byteLoop: } } - var kind ast.Kind + var kind Kind if hasTime { if hasDate { if hasTz { - kind = ast.DateTime + kind = DateTime } else { - kind = ast.LocalDateTime + kind = LocalDateTime } } else { - kind = ast.LocalTime + kind = LocalTime } } else { - kind = ast.LocalDate + kind = LocalDate } - return p.builder.Push(ast.Node{ + return p.builder.Push(Node{ Kind: kind, Data: b[:i], }), b[i:], nil } //nolint:funlen,gocognit,cyclop -func (p *parser) scanIntOrFloat(b []byte) (ast.Reference, []byte, error) { +func (p *Parser) scanIntOrFloat(b []byte) (reference, []byte, error) { i := 0 if len(b) > 2 && b[0] == '0' && b[1] != '.' && b[1] != 'e' && b[1] != 'E' { @@ -990,9 +1145,10 @@ func (p *parser) scanIntOrFloat(b []byte) (ast.Reference, []byte, error) { } } - return p.builder.Push(ast.Node{ - Kind: ast.Integer, + return p.builder.Push(Node{ + Kind: Integer, Data: b[:i], + Raw: p.Range(b[:i]), }), b[i:], nil } @@ -1013,42 +1169,45 @@ func (p *parser) scanIntOrFloat(b []byte) (ast.Reference, []byte, error) { if c == 'i' { if scanFollowsInf(b[i:]) { - return p.builder.Push(ast.Node{ - Kind: ast.Float, + return p.builder.Push(Node{ + Kind: Float, Data: b[:i+3], + Raw: p.Range(b[:i+3]), }), b[i+3:], nil } - return ast.InvalidReference, nil, newDecodeError(b[i:i+1], "unexpected character 'i' while scanning for a number") + return invalidReference, nil, NewParserError(b[i:i+1], "unexpected character 'i' while scanning for a number") } if c == 'n' { if scanFollowsNan(b[i:]) { - return p.builder.Push(ast.Node{ - Kind: ast.Float, + return p.builder.Push(Node{ + Kind: Float, Data: b[:i+3], + Raw: p.Range(b[:i+3]), }), b[i+3:], nil } - return ast.InvalidReference, nil, newDecodeError(b[i:i+1], "unexpected character 'n' while scanning for a number") + return invalidReference, nil, NewParserError(b[i:i+1], "unexpected character 'n' while scanning for a number") } break } if i == 0 { - return ast.InvalidReference, b, newDecodeError(b, "incomplete number") + return invalidReference, b, NewParserError(b, "incomplete number") } - kind := ast.Integer + kind := Integer if isFloat { - kind = ast.Float + kind = Float } - return p.builder.Push(ast.Node{ + return p.builder.Push(Node{ Kind: kind, Data: b[:i], + Raw: p.Range(b[:i]), }), b[i:], nil } @@ -1075,11 +1234,11 @@ func isValidBinaryRune(r byte) bool { func expect(x byte, b []byte) ([]byte, error) { if len(b) == 0 { - return nil, newDecodeError(b, "expected character %c but the document ended here", x) + return nil, NewParserError(b, "expected character %c but the document ended here", x) } if b[0] != x { - return nil, newDecodeError(b[0:1], "expected character %c", x) + return nil, NewParserError(b[0:1], "expected character %c", x) } return b[1:], nil diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/scanner.go b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/scanner.go similarity index 79% rename from tools/vendor/github.com/pelletier/go-toml/v2/scanner.go rename to tools/vendor/github.com/pelletier/go-toml/v2/unstable/scanner.go index bb445fab4..0512181d2 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/scanner.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/scanner.go @@ -1,4 +1,6 @@ -package toml +package unstable + +import "github.com/pelletier/go-toml/v2/internal/characters" func scanFollows(b []byte, pattern string) bool { n := len(pattern) @@ -54,16 +56,16 @@ func scanLiteralString(b []byte) ([]byte, []byte, error) { case '\'': return b[:i+1], b[i+1:], nil case '\n', '\r': - return nil, nil, newDecodeError(b[i:i+1], "literal strings cannot have new lines") + return nil, nil, NewParserError(b[i:i+1], "literal strings cannot have new lines") } - size := utf8ValidNext(b[i:]) + size := characters.Utf8ValidNext(b[i:]) if size == 0 { - return nil, nil, newDecodeError(b[i:i+1], "invalid character") + return nil, nil, NewParserError(b[i:i+1], "invalid character") } i += size } - return nil, nil, newDecodeError(b[len(b):], "unterminated literal string") + return nil, nil, NewParserError(b[len(b):], "unterminated literal string") } func scanMultilineLiteralString(b []byte) ([]byte, []byte, error) { @@ -98,39 +100,39 @@ func scanMultilineLiteralString(b []byte) ([]byte, []byte, error) { i++ if i < len(b) && b[i] == '\'' { - return nil, nil, newDecodeError(b[i-3:i+1], "''' not allowed in multiline literal string") + return nil, nil, NewParserError(b[i-3:i+1], "''' not allowed in multiline literal string") } return b[:i], b[i:], nil } case '\r': if len(b) < i+2 { - return nil, nil, newDecodeError(b[len(b):], `need a \n after \r`) + return nil, nil, NewParserError(b[len(b):], `need a \n after \r`) } if b[i+1] != '\n' { - return nil, nil, newDecodeError(b[i:i+2], `need a \n after \r`) + return nil, nil, NewParserError(b[i:i+2], `need a \n after \r`) } i += 2 // skip the \n continue } - size := utf8ValidNext(b[i:]) + size := characters.Utf8ValidNext(b[i:]) if size == 0 { - return nil, nil, newDecodeError(b[i:i+1], "invalid character") + return nil, nil, NewParserError(b[i:i+1], "invalid character") } i += size } - return nil, nil, newDecodeError(b[len(b):], `multiline literal string not terminated by '''`) + return nil, nil, NewParserError(b[len(b):], `multiline literal string not terminated by '''`) } func scanWindowsNewline(b []byte) ([]byte, []byte, error) { const lenCRLF = 2 if len(b) < lenCRLF { - return nil, nil, newDecodeError(b, "windows new line expected") + return nil, nil, NewParserError(b, "windows new line expected") } if b[1] != '\n' { - return nil, nil, newDecodeError(b, `windows new line should be \r\n`) + return nil, nil, NewParserError(b, `windows new line should be \r\n`) } return b[:lenCRLF], b[lenCRLF:], nil @@ -149,7 +151,6 @@ func scanWhitespace(b []byte) ([]byte, []byte) { return b, b[len(b):] } -//nolint:unparam func scanComment(b []byte) ([]byte, []byte, error) { // comment-start-symbol = %x23 ; # // non-ascii = %x80-D7FF / %xE000-10FFFF @@ -165,11 +166,11 @@ func scanComment(b []byte) ([]byte, []byte, error) { if i+1 < len(b) && b[i+1] == '\n' { return b[:i+1], b[i+1:], nil } - return nil, nil, newDecodeError(b[i:i+1], "invalid character in comment") + return nil, nil, NewParserError(b[i:i+1], "invalid character in comment") } - size := utf8ValidNext(b[i:]) + size := characters.Utf8ValidNext(b[i:]) if size == 0 { - return nil, nil, newDecodeError(b[i:i+1], "invalid character in comment") + return nil, nil, NewParserError(b[i:i+1], "invalid character in comment") } i += size @@ -192,17 +193,17 @@ func scanBasicString(b []byte) ([]byte, bool, []byte, error) { case '"': return b[:i+1], escaped, b[i+1:], nil case '\n', '\r': - return nil, escaped, nil, newDecodeError(b[i:i+1], "basic strings cannot have new lines") + return nil, escaped, nil, NewParserError(b[i:i+1], "basic strings cannot have new lines") case '\\': if len(b) < i+2 { - return nil, escaped, nil, newDecodeError(b[i:i+1], "need a character after \\") + return nil, escaped, nil, NewParserError(b[i:i+1], "need a character after \\") } escaped = true i++ // skip the next character } } - return nil, escaped, nil, newDecodeError(b[len(b):], `basic string not terminated by "`) + return nil, escaped, nil, NewParserError(b[len(b):], `basic string not terminated by "`) } func scanMultilineBasicString(b []byte) ([]byte, bool, []byte, error) { @@ -243,27 +244,27 @@ func scanMultilineBasicString(b []byte) ([]byte, bool, []byte, error) { i++ if i < len(b) && b[i] == '"' { - return nil, escaped, nil, newDecodeError(b[i-3:i+1], `""" not allowed in multiline basic string`) + return nil, escaped, nil, NewParserError(b[i-3:i+1], `""" not allowed in multiline basic string`) } return b[:i], escaped, b[i:], nil } case '\\': if len(b) < i+2 { - return nil, escaped, nil, newDecodeError(b[len(b):], "need a character after \\") + return nil, escaped, nil, NewParserError(b[len(b):], "need a character after \\") } escaped = true i++ // skip the next character case '\r': if len(b) < i+2 { - return nil, escaped, nil, newDecodeError(b[len(b):], `need a \n after \r`) + return nil, escaped, nil, NewParserError(b[len(b):], `need a \n after \r`) } if b[i+1] != '\n' { - return nil, escaped, nil, newDecodeError(b[i:i+2], `need a \n after \r`) + return nil, escaped, nil, NewParserError(b[i:i+2], `need a \n after \r`) } i++ // skip the \n } } - return nil, escaped, nil, newDecodeError(b[len(b):], `multiline basic string not terminated by """`) + return nil, escaped, nil, NewParserError(b[len(b):], `multiline basic string not terminated by """`) } diff --git a/tools/vendor/github.com/pelletier/go-toml/v2/unstable/unmarshaler.go b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/unmarshaler.go new file mode 100644 index 000000000..00cfd6de4 --- /dev/null +++ b/tools/vendor/github.com/pelletier/go-toml/v2/unstable/unmarshaler.go @@ -0,0 +1,7 @@ +package unstable + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a TOML document. +type Unmarshaler interface { + UnmarshalTOML(value *Node) error +} diff --git a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/allowed.go b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/allowed.go index df8d5f713..cf481708a 100644 --- a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/allowed.go +++ b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/allowed.go @@ -7,102 +7,135 @@ import ( "strings" ) -var allowedErrors = []struct { - err string - fun string -}{ - // pkg/archive/tar - {err: "io.EOF", fun: "(*archive/tar.Reader).Next"}, - {err: "io.EOF", fun: "(*archive/tar.Reader).Read"}, - // pkg/bufio - {err: "io.EOF", fun: "(*bufio.Reader).Discard"}, - {err: "io.EOF", fun: "(*bufio.Reader).Peek"}, - {err: "io.EOF", fun: "(*bufio.Reader).Read"}, - {err: "io.EOF", fun: "(*bufio.Reader).ReadByte"}, - {err: "io.EOF", fun: "(*bufio.Reader).ReadBytes"}, - {err: "io.EOF", fun: "(*bufio.Reader).ReadLine"}, - {err: "io.EOF", fun: "(*bufio.Reader).ReadSlice"}, - {err: "io.EOF", fun: "(*bufio.Reader).ReadString"}, - {err: "io.EOF", fun: "(*bufio.Scanner).Scan"}, - // pkg/bytes - {err: "io.EOF", fun: "(*bytes.Buffer).Read"}, - {err: "io.EOF", fun: "(*bytes.Buffer).ReadByte"}, - {err: "io.EOF", fun: "(*bytes.Buffer).ReadBytes"}, - {err: "io.EOF", fun: "(*bytes.Buffer).ReadRune"}, - {err: "io.EOF", fun: "(*bytes.Buffer).ReadString"}, - {err: "io.EOF", fun: "(*bytes.Reader).Read"}, - {err: "io.EOF", fun: "(*bytes.Reader).ReadAt"}, - {err: "io.EOF", fun: "(*bytes.Reader).ReadByte"}, - {err: "io.EOF", fun: "(*bytes.Reader).ReadRune"}, - {err: "io.EOF", fun: "(*bytes.Reader).ReadString"}, - // pkg/database/sql - {err: "database/sql.ErrNoRows", fun: "(*database/sql.Row).Scan"}, - // pkg/debug/elf - {err: "io.EOF", fun: "debug/elf.Open"}, - {err: "io.EOF", fun: "debug/elf.NewFile"}, - // pkg/io - {err: "io.EOF", fun: "(io.Reader).Read"}, - {err: "io.EOF", fun: "(io.ReaderAt).ReadAt"}, - {err: "io.EOF", fun: "(*io.LimitedReader).Read"}, - {err: "io.EOF", fun: "(*io.SectionReader).Read"}, - {err: "io.EOF", fun: "(*io.SectionReader).ReadAt"}, - {err: "io.ErrClosedPipe", fun: "(*io.PipeWriter).Write"}, - {err: "io.ErrShortBuffer", fun: "io.ReadAtLeast"}, - {err: "io.ErrUnexpectedEOF", fun: "io.ReadAtLeast"}, - {err: "io.EOF", fun: "io.ReadFull"}, - {err: "io.ErrUnexpectedEOF", fun: "io.ReadFull"}, - // pkg/net/http - {err: "net/http.ErrServerClosed", fun: "(*net/http.Server).ListenAndServe"}, - {err: "net/http.ErrServerClosed", fun: "(*net/http.Server).ListenAndServeTLS"}, - {err: "net/http.ErrServerClosed", fun: "(*net/http.Server).Serve"}, - {err: "net/http.ErrServerClosed", fun: "(*net/http.Server).ServeTLS"}, - {err: "net/http.ErrServerClosed", fun: "net/http.ListenAndServe"}, - {err: "net/http.ErrServerClosed", fun: "net/http.ListenAndServeTLS"}, - {err: "net/http.ErrServerClosed", fun: "net/http.Serve"}, - {err: "net/http.ErrServerClosed", fun: "net/http.ServeTLS"}, - // pkg/os - {err: "io.EOF", fun: "(*os.File).Read"}, - {err: "io.EOF", fun: "(*os.File).ReadAt"}, - {err: "io.EOF", fun: "(*os.File).ReadDir"}, - {err: "io.EOF", fun: "(*os.File).Readdir"}, - {err: "io.EOF", fun: "(*os.File).Readdirnames"}, - // pkg/strings - {err: "io.EOF", fun: "(*strings.Reader).Read"}, - {err: "io.EOF", fun: "(*strings.Reader).ReadAt"}, - {err: "io.EOF", fun: "(*strings.Reader).ReadByte"}, - {err: "io.EOF", fun: "(*strings.Reader).ReadRune"}, +type AllowPair struct { + Err string + Fun string } -var allowedErrorWildcards = []struct { - err string - fun string -}{ +var allowedErrorsMap = make(map[string]map[string]struct{}) + +func setDefaultAllowedErrors() { + allowedMapAppend([]AllowPair{ + // pkg/archive/tar + {Err: "io.EOF", Fun: "(*archive/tar.Reader).Next"}, + {Err: "io.EOF", Fun: "(*archive/tar.Reader).Read"}, + // pkg/bufio + {Err: "io.EOF", Fun: "(*bufio.Reader).Discard"}, + {Err: "io.EOF", Fun: "(*bufio.Reader).Peek"}, + {Err: "io.EOF", Fun: "(*bufio.Reader).Read"}, + {Err: "io.EOF", Fun: "(*bufio.Reader).ReadByte"}, + {Err: "io.EOF", Fun: "(*bufio.Reader).ReadBytes"}, + {Err: "io.EOF", Fun: "(*bufio.Reader).ReadLine"}, + {Err: "io.EOF", Fun: "(*bufio.Reader).ReadSlice"}, + {Err: "io.EOF", Fun: "(*bufio.Reader).ReadString"}, + {Err: "io.EOF", Fun: "(*bufio.Scanner).Scan"}, + // pkg/bytes + {Err: "io.EOF", Fun: "(*bytes.Buffer).Read"}, + {Err: "io.EOF", Fun: "(*bytes.Buffer).ReadByte"}, + {Err: "io.EOF", Fun: "(*bytes.Buffer).ReadBytes"}, + {Err: "io.EOF", Fun: "(*bytes.Buffer).ReadRune"}, + {Err: "io.EOF", Fun: "(*bytes.Buffer).ReadString"}, + {Err: "io.EOF", Fun: "(*bytes.Reader).Read"}, + {Err: "io.EOF", Fun: "(*bytes.Reader).ReadAt"}, + {Err: "io.EOF", Fun: "(*bytes.Reader).ReadByte"}, + {Err: "io.EOF", Fun: "(*bytes.Reader).ReadRune"}, + {Err: "io.EOF", Fun: "(*bytes.Reader).ReadString"}, + // pkg/database/sql + {Err: "database/sql.ErrNoRows", Fun: "(*database/sql.Row).Scan"}, + // pkg/debug/elf + {Err: "io.EOF", Fun: "debug/elf.Open"}, + {Err: "io.EOF", Fun: "debug/elf.NewFile"}, + // pkg/io + {Err: "io.EOF", Fun: "(io.ReadCloser).Read"}, + {Err: "io.EOF", Fun: "(io.Reader).Read"}, + {Err: "io.EOF", Fun: "(io.ReaderAt).ReadAt"}, + {Err: "io.EOF", Fun: "(*io.LimitedReader).Read"}, + {Err: "io.EOF", Fun: "(*io.SectionReader).Read"}, + {Err: "io.EOF", Fun: "(*io.SectionReader).ReadAt"}, + {Err: "io.ErrClosedPipe", Fun: "(*io.PipeWriter).Write"}, + {Err: "io.ErrShortBuffer", Fun: "io.ReadAtLeast"}, + {Err: "io.ErrUnexpectedEOF", Fun: "io.ReadAtLeast"}, + {Err: "io.EOF", Fun: "io.ReadFull"}, + {Err: "io.ErrUnexpectedEOF", Fun: "io.ReadFull"}, + // pkg/mime + {Err: "mime.ErrInvalidMediaParameter", Fun: "mime.ParseMediaType"}, + // pkg/net/http + {Err: "net/http.ErrServerClosed", Fun: "(*net/http.Server).ListenAndServe"}, + {Err: "net/http.ErrServerClosed", Fun: "(*net/http.Server).ListenAndServeTLS"}, + {Err: "net/http.ErrServerClosed", Fun: "(*net/http.Server).Serve"}, + {Err: "net/http.ErrServerClosed", Fun: "(*net/http.Server).ServeTLS"}, + {Err: "net/http.ErrServerClosed", Fun: "net/http.ListenAndServe"}, + {Err: "net/http.ErrServerClosed", Fun: "net/http.ListenAndServeTLS"}, + {Err: "net/http.ErrServerClosed", Fun: "net/http.Serve"}, + {Err: "net/http.ErrServerClosed", Fun: "net/http.ServeTLS"}, + // pkg/os + {Err: "io.EOF", Fun: "(*os.File).Read"}, + {Err: "io.EOF", Fun: "(*os.File).ReadAt"}, + {Err: "io.EOF", Fun: "(*os.File).ReadDir"}, + {Err: "io.EOF", Fun: "(*os.File).Readdir"}, + {Err: "io.EOF", Fun: "(*os.File).Readdirnames"}, + // pkg/strings + {Err: "io.EOF", Fun: "(*strings.Reader).Read"}, + {Err: "io.EOF", Fun: "(*strings.Reader).ReadAt"}, + {Err: "io.EOF", Fun: "(*strings.Reader).ReadByte"}, + {Err: "io.EOF", Fun: "(*strings.Reader).ReadRune"}, + // pkg/context + {Err: "context.DeadlineExceeded", Fun: "(context.Context).Err"}, + {Err: "context.Canceled", Fun: "(context.Context).Err"}, + // pkg/encoding/json + {Err: "io.EOF", Fun: "(*encoding/json.Decoder).Decode"}, + // pkg/encoding/csv + {Err: "io.EOF", Fun: "(*encoding/csv.Reader).Read"}, + // pkg/mime/multipart + {Err: "io.EOF", Fun: "(*mime/multipart.Reader).NextPart"}, + {Err: "io.EOF", Fun: "(*mime/multipart.Reader).NextRawPart"}, + {Err: "mime/multipart.ErrMessageTooLarge", Fun: "(*mime/multipart.Reader).ReadForm"}, + }) +} + +func allowedMapAppend(ap []AllowPair) { + for _, pair := range ap { + if _, ok := allowedErrorsMap[pair.Err]; !ok { + allowedErrorsMap[pair.Err] = make(map[string]struct{}) + } + allowedErrorsMap[pair.Err][pair.Fun] = struct{}{} + } +} + +var allowedErrorWildcards = []AllowPair{ + // pkg/syscall + {Err: "syscall.E", Fun: "syscall."}, // golang.org/x/sys/unix - {err: "golang.org/x/sys/unix.E", fun: "golang.org/x/sys/unix."}, + {Err: "golang.org/x/sys/unix.E", Fun: "golang.org/x/sys/unix."}, +} + +func allowedWildcardAppend(ap []AllowPair) { + allowedErrorWildcards = append(allowedErrorWildcards, ap...) } func isAllowedErrAndFunc(err, fun string) bool { - for _, allow := range allowedErrorWildcards { - if strings.HasPrefix(fun, allow.fun) && strings.HasPrefix(err, allow.err) { + if allowedFuncs, allowErr := allowedErrorsMap[err]; allowErr { + if _, allow := allowedFuncs[fun]; allow { return true } } - for _, allow := range allowedErrors { - if allow.fun == fun && allow.err == err { + for _, allow := range allowedErrorWildcards { + if strings.HasPrefix(fun, allow.Fun) && strings.HasPrefix(err, allow.Err) { return true } } + return false } -func isAllowedErrorComparison(pass *TypesInfoExt, binExpr *ast.BinaryExpr) bool { +func isAllowedErrorComparison(pass *TypesInfoExt, a, b ast.Expr) bool { var errName string // `.`, e.g. `io.EOF` var callExprs []*ast.CallExpr // Figure out which half of the expression is the returned error and which // half is the presumed error declaration. - for _, expr := range []ast.Expr{binExpr.X, binExpr.Y} { + for _, expr := range []ast.Expr{a, b} { switch t := expr.(type) { case *ast.SelectorExpr: // A selector which we assume refers to a staticaly declared error diff --git a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/analysis.go b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/analysis.go index f034913ea..84ebd6cf8 100644 --- a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/analysis.go +++ b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/analysis.go @@ -1,7 +1,6 @@ package errorlint import ( - "flag" "go/ast" "go/types" "sort" @@ -9,32 +8,36 @@ import ( "golang.org/x/tools/go/analysis" ) -func NewAnalyzer() *analysis.Analyzer { - return &analysis.Analyzer{ - Name: "errorlint", - Doc: "Source code linter for Go software that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.", - Run: run, - Flags: flagSet, +func NewAnalyzer(opts ...Option) *analysis.Analyzer { + for _, o := range opts { + o() } + + setDefaultAllowedErrors() + + a := &analysis.Analyzer{ + Name: "errorlint", + Doc: "Source code linter for Go software that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.", + Run: run, + } + + a.Flags.BoolVar(&checkComparison, "comparison", true, "Check for plain error comparisons") + a.Flags.BoolVar(&checkAsserts, "asserts", true, "Check for plain type assertions and type switches") + a.Flags.BoolVar(&checkErrorf, "errorf", false, "Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats") + a.Flags.BoolVar(&checkErrorfMulti, "errorf-multi", true, "Permit more than 1 %w verb, valid per Go 1.20 (Requires -errorf=true)") + + return a } var ( - flagSet flag.FlagSet checkComparison bool checkAsserts bool checkErrorf bool checkErrorfMulti bool ) -func init() { - flagSet.BoolVar(&checkComparison, "comparison", true, "Check for plain error comparisons") - flagSet.BoolVar(&checkAsserts, "asserts", true, "Check for plain type assertions and type switches") - flagSet.BoolVar(&checkErrorf, "errorf", false, "Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats") - flagSet.BoolVar(&checkErrorfMulti, "errorf-multi", true, "Permit more than 1 %w verb, valid per Go 1.20 (Requires -errorf=true)") -} - func run(pass *analysis.Pass) (interface{}, error) { - lints := []analysis.Diagnostic{} + var lints []analysis.Diagnostic extInfo := newTypesInfoExt(pass) if checkComparison { l := LintErrorComparisons(extInfo) diff --git a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/lint.go b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/lint.go index 817cd6904..9ac465c65 100644 --- a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/lint.go +++ b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/lint.go @@ -20,7 +20,8 @@ func (l ByPosition) Less(i, j int) bool { } func LintFmtErrorfCalls(fset *token.FileSet, info types.Info, multipleWraps bool) []analysis.Diagnostic { - lints := []analysis.Diagnostic{} + var lints []analysis.Diagnostic + for expr, t := range info.Types { // Search for error expressions that are the result of fmt.Errorf // invocations. @@ -159,7 +160,7 @@ func isFmtErrorfCallExpr(info types.Info, expr ast.Expr) (*ast.CallExpr, bool) { } func LintErrorComparisons(info *TypesInfoExt) []analysis.Diagnostic { - lints := []analysis.Diagnostic{} + var lints []analysis.Diagnostic for expr := range info.TypesInfo.Types { // Find == and != operations. @@ -171,15 +172,15 @@ func LintErrorComparisons(info *TypesInfoExt) []analysis.Diagnostic { continue } // Comparing errors with nil is okay. - if isNilComparison(binExpr) { + if isNil(binExpr.X) || isNil(binExpr.Y) { continue } // Find comparisons of which one side is a of type error. - if !isErrorComparison(info.TypesInfo, binExpr) { + if !isErrorType(info.TypesInfo, binExpr.X) && !isErrorType(info.TypesInfo, binExpr.Y) { continue } // Some errors that are returned from some functions are exempt. - if isAllowedErrorComparison(info, binExpr) { + if isAllowedErrorComparison(info, binExpr.X, binExpr.Y) { continue } // Comparisons that happen in `func (type) Is(error) bool` are okay. @@ -200,13 +201,29 @@ func LintErrorComparisons(info *TypesInfoExt) []analysis.Diagnostic { continue } // Check whether the switch operates on an error type. - if switchStmt.Tag == nil { + if !isErrorType(info.TypesInfo, switchStmt.Tag) { continue } - tagType := info.TypesInfo.Types[switchStmt.Tag] - if tagType.Type.String() != "error" { + + var problematicCaseClause *ast.CaseClause + outer: + for _, stmt := range switchStmt.Body.List { + caseClause := stmt.(*ast.CaseClause) + for _, caseExpr := range caseClause.List { + if isNil(caseExpr) { + continue + } + // Some errors that are returned from some functions are exempt. + if !isAllowedErrorComparison(info, switchStmt.Tag, caseExpr) { + problematicCaseClause = caseClause + break outer + } + } + } + if problematicCaseClause == nil { continue } + // Comparisons that happen in `func (type) Is(error) bool` are okay. if isNodeInErrorIsFunc(info, switchStmt) { continue } @@ -214,29 +231,22 @@ func LintErrorComparisons(info *TypesInfoExt) []analysis.Diagnostic { if switchComparesNonNil(switchStmt) { lints = append(lints, analysis.Diagnostic{ Message: "switch on an error will fail on wrapped errors. Use errors.Is to check for specific errors", - Pos: switchStmt.Pos(), + Pos: problematicCaseClause.Pos(), }) } - } return lints } -func isNilComparison(binExpr *ast.BinaryExpr) bool { - if ident, ok := binExpr.X.(*ast.Ident); ok && ident.Name == "nil" { - return true - } - if ident, ok := binExpr.Y.(*ast.Ident); ok && ident.Name == "nil" { - return true - } - return false +func isNil(ex ast.Expr) bool { + ident, ok := ex.(*ast.Ident) + return ok && ident.Name == "nil" } -func isErrorComparison(info *types.Info, binExpr *ast.BinaryExpr) bool { - tx := info.Types[binExpr.X] - ty := info.Types[binExpr.Y] - return tx.Type.String() == "error" || ty.Type.String() == "error" +func isErrorType(info *types.Info, ex ast.Expr) bool { + t := info.Types[ex].Type + return t != nil && t.String() == "error" } func isNodeInErrorIsFunc(info *TypesInfoExt, node ast.Node) bool { @@ -289,7 +299,7 @@ func switchComparesNonNil(switchStmt *ast.SwitchStmt) bool { } func LintErrorTypeAssertions(fset *token.FileSet, info *TypesInfoExt) []analysis.Diagnostic { - lints := []analysis.Diagnostic{} + var lints []analysis.Diagnostic for expr := range info.TypesInfo.Types { // Find type assertions. @@ -307,6 +317,11 @@ func LintErrorTypeAssertions(fset *token.FileSet, info *TypesInfoExt) []analysis continue } + // If the asserted type is not an error, allow the expression. + if !implementsError(info.TypesInfo.Types[typeAssert.Type].Type) { + continue + } + lints = append(lints, analysis.Diagnostic{ Message: "type assertion on error will fail on wrapped errors. Use errors.As to check for specific errors", Pos: typeAssert.Pos(), diff --git a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/options.go b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/options.go new file mode 100644 index 000000000..4d7c742d8 --- /dev/null +++ b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/options.go @@ -0,0 +1,15 @@ +package errorlint + +type Option func() + +func WithAllowedErrors(ap []AllowPair) Option { + return func() { + allowedMapAppend(ap) + } +} + +func WithAllowedWildcard(ap []AllowPair) Option { + return func() { + allowedWildcardAppend(ap) + } +} diff --git a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/printf.go b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/printf.go index 973752592..4c0e12525 100644 --- a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/printf.go +++ b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/printf.go @@ -7,23 +7,6 @@ import ( "strings" ) -func verbOrder(verbs []verb, numArgs int) [][]verb { - orderedVerbs := make([][]verb, numArgs) - i := 0 - for _, v := range verbs { - if v.index != -1 { - i = v.index - 1 - } - if i >= len(orderedVerbs) { - continue - } - orderedVerbs[i] = append(orderedVerbs[i], v) - verbs = verbs[1:] - i++ - } - return orderedVerbs -} - type verb struct { format string formatOffset int diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/LICENSE b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/LICENSE new file mode 100644 index 000000000..558f81ff2 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2022, Iskander (Alex) Sharipov / quasilyte +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/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/bundle.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/bundle.go new file mode 100644 index 000000000..45a9455d8 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/bundle.go @@ -0,0 +1,19 @@ +package dsl + +// Bundle is a rules file export manifest. +type Bundle struct { + // TODO: figure out which fields we might want to add here. +} + +// ImportRules imports all rules from the bundle and prefixes them with a specified string. +// +// Empty string prefix is something like "dot import" in Go. +// Group name collisions will result in an error. +// +// Only packages that have an exported Bundle variable can be imported. +// +// Note: right now imported bundle can't import other bundles. +// This is not a fundamental limitation but rather a precaution +// measure before we understand how it should work better. +// If you need this feature, please open an issue at github.com/quasilyte/go-ruleguard. +func ImportRules(prefix string, bundle Bundle) {} diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/do.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/do.go new file mode 100644 index 000000000..86bc163a7 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/do.go @@ -0,0 +1,19 @@ +package dsl + +import ( + "github.com/quasilyte/go-ruleguard/dsl/types" +) + +type DoContext struct{} + +func (*DoContext) Var(varname string) *DoVar { return nil } + +func (*DoContext) SetReport(report string) {} + +func (*DoContext) SetSuggest(suggest string) {} + +type DoVar struct{} + +func (*DoVar) Text() string { return "" } + +func (*DoVar) Type() types.Type { return nil } diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/dsl.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/dsl.go new file mode 100644 index 000000000..d3c73bddd --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/dsl.go @@ -0,0 +1,361 @@ +package dsl + +// Matcher is a main API group-level entry point. +// It's used to define and configure the group rules. +// It also represents a map of all rule-local variables. +type Matcher map[string]Var + +// Import loads given package path into a rule group imports table. +// +// That table is used during the rules compilation. +// +// The table has the following effect on the rules: +// * For type expressions, it's used to resolve the +// full package paths of qualified types, like `foo.Bar`. +// If Import(`a/b/foo`) is called, `foo.Bar` will match +// `a/b/foo.Bar` type during the pattern execution. +func (m Matcher) Import(pkgPath string) {} + +// Match specifies a set of patterns that match a rule being defined. +// Pattern matching succeeds if at least 1 pattern matches. +// +// If none of the given patterns matched, rule execution stops. +func (m Matcher) Match(pattern string, alternatives ...string) Matcher { + return m +} + +// MatchComment is like Match, but handles only comments and uses regexp patterns. +// +// Multi-line /**/ comments are passed as a single string. +// Single-line // comments are passed line-by-line. +// +// Hint: if you want to match a plain text and don't want to do meta char escaping, +// prepend `\Q` to your pattern. `\Qf(x)` will match `f(x)` as a plain text +// and there is no need to escape the `(` and `)` chars. +// +// Named regexp capture groups can be accessed using the usual indexing notation. +// +// Given this pattern: +// +// `(?P\d+)\.(\d+).(?P\d+)` +// +// And this input comment: `// 14.6.600` +// +// We'll get these submatches: +// +// m["$$"] => `14.6.600` +// m["first"] => `14` +// m["second"] => `600` +// +// All usual filters can be applied: +// +// Where(!m["first"].Text.Matches(`foo`)) +// +// You can use this to reject some matches (allow-list behavior). +func (m Matcher) MatchComment(pattern string, alternatives ...string) Matcher { + return m +} + +// Where applies additional constraint to a match. +// If a given cond is not satisfied, a match is rejected and +// rule execution stops. +func (m Matcher) Where(cond bool) Matcher { + return m +} + +// Report prints a message if associated rule match is successful. +// +// A message is a string that can contain interpolated expressions. +// For every matched variable it's possible to interpolate +// their printed representation into the message text with $. +// An entire match can be addressed with $$. +func (m Matcher) Report(message string) Matcher { + return m +} + +// Suggest assigns a quickfix suggestion for the matched code. +func (m Matcher) Suggest(suggestion string) Matcher { + return m +} + +func (m Matcher) Do(fn func(*DoContext)) Matcher { + return m +} + +// At binds the reported node to a named submatch. +// If no explicit location is given, the outermost node ($$) is used. +func (m Matcher) At(v Var) Matcher { + return m +} + +// File returns the current file context. +func (m Matcher) File() File { return File{} } + +// GoVersion returns the analyzer associated target Go language version. +func (m Matcher) GoVersion() GoVersion { return GoVersion{} } + +// Deadcode reports whether this match is contained inside a dead code path. +func (m Matcher) Deadcode() bool { return boolResult } + +// Var is a pattern variable that describes a named submatch. +type Var struct { + // Pure reports whether expr matched by var is side-effect-free. + Pure bool + + // Const reports whether expr matched by var is a constant value. + Const bool + + // ConstSlice reports whether expr matched by var is a slice literal + // consisting of contant elements. + // + // We need a separate Const-like predicate here because Go doesn't + // treat slices of const elements as constants, so including + // them in Const would be incorrect. + // Use `m["x"].Const || m["x"].ConstSlice` when you need + // to have extended definition of "constant value". + // + // Some examples: + // []byte("foo") -- constant byte slice + // []byte{'f', 'o', 'o'} -- same constant byte slice + // []int{1, 2} -- constant int slice + ConstSlice bool + + // Value is a compile-time computable value of the expression. + Value ExprValue + + // Addressable reports whether the corresponding expression is addressable. + // See https://golang.org/ref/spec#Address_operators. + Addressable bool + + // Comparable reports whether the corresponding expression value is comparable. + // See https://pkg.go.dev/go/types#Comparable. + Comparable bool + + // Type is a type of a matched expr. + // + // For function call expressions, a type is a function result type, + // but for a function expression itself it's a *types.Signature. + // + // Suppose we have a `a.b()` expression: + // `$x()` m["x"].Type is `a.b` function type + // `$x` m["x"].Type is `a.b()` function call result type + Type ExprType + + SinkType SinkType + + // Object is an associated "go/types" Object. + Object TypesObject + + // Text is a captured node text as in the source code. + Text MatchedText + + // Node is a captured AST node. + Node MatchedNode + + // Line is a source code line number that contains this match. + // If this match is multi-line, this is the first line number. + Line int +} + +// Filter applies a custom predicate function on a submatch. +// +// The callback function should use VarFilterContext to access the +// information that is usually accessed through Var. +// For example, `VarFilterContext.Type` is mapped to `Var.Type`. +func (Var) Filter(pred func(*VarFilterContext) bool) bool { return boolResult } + +// Contains runs a sub-search from a given pattern using the captured +// vars from the original pattern match. +// +// For example, given the Match(`$lhs = append($lhs, $x)`) pattern, +// we can do m["lhs"].Contains(`$x`) and learn whether $lhs contains +// $x as its sub-expression. +// +// Experimental: this function is not part of the stable API. +func (Var) Contains(pattern string) bool { return boolResult } + +// MatchedNode represents an AST node associated with a named submatch. +type MatchedNode struct{} + +// Is reports whether a matched node AST type is compatible with the specified type. +// A valid argument is a ast.Node implementing type name from the "go/ast" package. +// Examples: "BasicLit", "Expr", "Stmt", "Ident", "ParenExpr". +// See https://golang.org/pkg/go/ast/. +func (MatchedNode) Is(typ string) bool { return boolResult } + +// Parent returns a matched node parent. +func (MatchedNode) Parent() Node { return Node{} } + +// Node represents an AST node somewhere inside a match. +// Unlike MatchedNode, it doesn't have to be associated with a named submatch. +type Node struct{} + +// Is reports whether a node AST type is compatible with the specified type. +// See `MatchedNode.Is` for the full reference. +func (Node) Is(typ string) bool { return boolResult } + +// ExprValue describes a compile-time computable value of a matched expr. +type ExprValue struct{} + +// Int returns compile-time computable int value of the expression. +// If value can't be computed, condition will fail. +func (ExprValue) Int() int { return intResult } + +// TypesObject is a types.Object mapping. +type TypesObject struct{} + +// Is reports whether an associated types.Object is compatible with the specified type. +// A valid argument is a types.Object type name from the "go/types" package. +// Examples: "Func", "Var", "Const", "TypeName", "Label", "PkgName", "Builtin", "Nil" +// See https://golang.org/pkg/go/types/. +func (TypesObject) Is(typ string) bool { return boolResult } + +// IsGlobal reports whether an associated types.Object is defined in global scope. +func (TypesObject) IsGlobal() bool { return boolResult } + +// IsVariadicParam reports whether this object represents a function variadic param. +// This property is not propagated between the assignments. +func (TypesObject) IsVariadicParam() bool { return boolResult } + +type SinkType struct{} + +// Is reports whether a type is identical to a given type. +// Works like ExprType.Is method. +func (SinkType) Is(typ string) bool { return boolResult } + +// ExprType describes a type of a matcher expr. +type ExprType struct { + // Size represents expression type size in bytes. + // + // For expressions of unknown size, like type params in generics, + // any filter using this operand will fail. + Size int +} + +// IdenticalTo applies types.Identical(this, v.Type) operation. +// See https://golang.org/pkg/go/types/#Identical function documentation. +// +// Experimental: this function is not part of the stable API. +func (ExprType) IdenticalTo(v Var) bool { return boolResult } + +// Underlying returns expression type underlying type. +// See https://golang.org/pkg/go/types/#Type Underlying() method documentation. +// Read https://golang.org/ref/spec#Types section to learn more about underlying types. +func (ExprType) Underlying() ExprType { return underlyingType } + +// AssignableTo reports whether a type is assign-compatible with a given type. +// See https://golang.org/pkg/go/types/#AssignableTo. +func (ExprType) AssignableTo(typ string) bool { return boolResult } + +// ConvertibleTo reports whether a type is conversible to a given type. +// See https://golang.org/pkg/go/types/#ConvertibleTo. +func (ExprType) ConvertibleTo(typ string) bool { return boolResult } + +// Implements reports whether a type implements a given interface. +// See https://golang.org/pkg/go/types/#Implements. +func (ExprType) Implements(typ typeName) bool { return boolResult } + +// HasMethod reports whether a type has a given method. +// Unlike Implements(), it will work for both value and pointer types. +// +// fn argument is a function signature, like `WriteString(string) (int, error)`. +// It can also be in form of a method reference for importable types: `io.StringWriter.WriteString`. +// +// To avoid confusion with Implements() method, here is a hint when to use which: +// +// - To check if it's possible to call F on x, use HasMethod(F) +// - To check if x can be passed as I interface, use Implements(I) +func (ExprType) HasMethod(fn string) bool { return boolResult } + +// Is reports whether a type is identical to a given type. +func (ExprType) Is(typ string) bool { return boolResult } + +// HasPointers reports whether a type contains at least one pointer. +// +// We try to be as close to the Go sense of pointer-free objects as possible, +// therefore string type is not considered to be a pointer-free type. +// +// This function may return "true" for some complicated cases as a +// conservative result. It never returns "false" for a type that +// actually contains a pointer. +// +// So this function is mostly useful for !HasPointers() form. +func (ExprType) HasPointers() bool { return boolResult } + +// OfKind reports whether a matched expr type is compatible with the specified kind. +// +// Only a few "kinds" are recognized, the list is provided below. +// +// "integer" -- typ is *types.Basic, where typ.Info()&types.Integer != 0 +// "unsigned" -- typ is *types.Basic, where typ.Info()&types.Unsigned != 0 +// "float" -- typ is *types.Basic, where typ.Info()&types.Float != 0 +// "complex" -- typ is *types.Basic, where typ.Info()&types.Complex != 0 +// "untyped" -- typ is *types.Basic, where typ.Info()&types.Untyped != 0 +// "numeric" -- typ is *types.Basic, where typ.Info()&types.Numeric != 0 +// "signed" -- identical to `OfKind("integer") && !OfKind("unsigned")` +// "int" -- int, int8, int16, int32, int64 +// "uint" -- uint, uint8, uint16, uint32, uint64 +// +// Note: "int" will include "rune" as well, as it's an alias. +// In the same manner, "uint" includes the "byte" type. +// +// Using OfKind("unsigned") is more efficient (and concise) than using a set +// of or-conditions with Is("uint8"), Is("uint16") and so on. +func (ExprType) OfKind(kind string) bool { return boolResult } + +// MatchedText represents a source text associated with a matched node. +type MatchedText string + +// Matches reports whether the text matches the given regexp pattern. +func (MatchedText) Matches(pattern string) bool { return boolResult } + +// String represents an arbitrary string-typed data. +type String string + +// Matches reports whether a string matches the given regexp pattern. +func (String) Matches(pattern string) bool { return boolResult } + +// File represents the current Go source file. +type File struct { + // Name is a file base name. + Name String + + // PkgPath is a file package path. + // Examples: "io/ioutil", "strings", "github.com/quasilyte/go-ruleguard/dsl". + PkgPath String +} + +// Imports reports whether the current file imports the given path. +func (File) Imports(path string) bool { return boolResult } + +// GoVersion is an analysis target go language version. +// It can be compared to Go versions like "1.10", "1.16" using +// the associated methods. +type GoVersion struct{} + +// Eq asserts that target Go version is equal to (==) specified version. +func (GoVersion) Eq(version string) bool { return boolResult } + +// GreaterEqThan asserts that target Go version is greater or equal than (>=) specified version. +func (GoVersion) GreaterEqThan(version string) bool { return boolResult } + +// GreaterThan asserts that target Go version is greater than (>) specified version. +func (GoVersion) GreaterThan(version string) bool { return boolResult } + +// LessThan asserts that target Go version is less than (<) specified version. +func (GoVersion) LessThan(version string) bool { return boolResult } + +// LessEqThan asserts that target Go version is less or equal than (<=) specified version. +func (GoVersion) LessEqThan(version string) bool { return boolResult } + +// typeName is a helper type used to document function params better. +// +// A type name can be: +// - builtin type name: `error`, `string`, etc. +// - qualified name from a standard library: `io.Reader`, etc. +// - fully-qualified type name, like `github.com/username/pkgname.TypeName` +// +// typeName is also affected by a local import table, which can override +// how qualified names are interpreted. +// See `Matcher.Import` for more info. +type typeName = string diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/filter.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/filter.go new file mode 100644 index 000000000..cef880098 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/filter.go @@ -0,0 +1,24 @@ +package dsl + +import ( + "github.com/quasilyte/go-ruleguard/dsl/types" +) + +// VarFilterContext carries Var and environment information into the filter function. +// It's an input parameter type for the Var.Filter function callback. +type VarFilterContext struct { + // Type is mapped to Var.Type field. + Type types.Type +} + +// SizeOf returns the size of the given type. +// It uses the ruleguard.Context.Sizes to calculate the result. +func (*VarFilterContext) SizeOf(x types.Type) int { return 0 } + +// GetType finds a type value by a given name. +// If a type can't be found (or a name is malformed), this function panics. +func (*VarFilterContext) GetType(name typeName) types.Type { return nil } + +// GetInterface finds a type value that represents an interface by a given name. +// Works like `types.AsInterface(ctx.GetType(name))`. +func (*VarFilterContext) GetInterface(name typeName) *types.Interface { return nil } diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/internal.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/internal.go new file mode 100644 index 000000000..3bb6d85dc --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/internal.go @@ -0,0 +1,6 @@ +package dsl + +var boolResult bool +var intResult int + +var underlyingType ExprType diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/ext.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/ext.go new file mode 100644 index 000000000..82595ff30 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/ext.go @@ -0,0 +1,21 @@ +package types + +// AsArray is a type-assert like operation, x.(*Array), but never panics. +// Returns nil if type is not an array. +func AsArray(x Type) *Array { return nil } + +// AsSlice is a type-assert like operation, x.(*Slice), but never panics. +// Returns nil if type is not an array. +func AsSlice(x Type) *Slice { return nil } + +// AsPointer is a type-assert like operation, x.(*Pointer), but never panics. +// Returns nil if type is not a pointer. +func AsPointer(x Type) *Pointer { return nil } + +// AsStruct is a type-assert like operation, x.(*Struct), but never panics. +// Returns nil if type is not a struct. +func AsStruct(x Type) *Struct { return nil } + +// AsInterface is a type-assert like operation, x.(*Interface), but never panics. +// Returns nil if type is not an interface. +func AsInterface(x Type) *Interface { return nil } diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/type_impl.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/type_impl.go new file mode 100644 index 000000000..9fc71d753 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/type_impl.go @@ -0,0 +1,17 @@ +package types + +// Method stubs to make various types implement Type interface. +// +// Nothing interesting here, hence it's moved to a separate file. + +func (*Array) String() string { return "" } +func (*Slice) String() string { return "" } +func (*Pointer) String() string { return "" } +func (*Interface) String() string { return "" } +func (*Struct) String() string { return "" } + +func (*Array) Underlying() Type { return nil } +func (*Slice) Underlying() Type { return nil } +func (*Pointer) Underlying() Type { return nil } +func (*Interface) Underlying() Type { return nil } +func (*Struct) Underlying() Type { return nil } diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/types.go b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/types.go new file mode 100644 index 000000000..b6be7cc35 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/dsl/types/types.go @@ -0,0 +1,68 @@ +// Package types mimics the https://golang.org/pkg/go/types/ package. +// It also contains some extra utility functions, they're defined in ext.go file. +package types + +// Implements reports whether a given type implements the specified interface. +func Implements(typ Type, iface *Interface) bool { return false } + +// Identical reports whether x and y are identical types. Receivers of Signature types are ignored. +func Identical(x, y Type) bool { return false } + +// A Type represents a type of Go. All types implement the Type interface. +type Type interface { + // Underlying returns the underlying type of a type. + Underlying() Type + + // String returns a string representation of a type. + String() string +} + +type ( + // An Array represents an array type. + Array struct{} + + // A Slice represents a slice type. + Slice struct{} + + // A Pointer represents a pointer type. + Pointer struct{} + + // An Interface represents an interface type. + Interface struct{} + + // A struct represents a struct type. + Struct struct{} +) + +// NewArray returns a new array type for the given element type and length. +// A negative length indicates an unknown length. +func NewArray(elem Type, len int) *Array { return nil } + +// Elem returns element type of array. +func (*Array) Elem() Type { return nil } + +// NewSlice returns a new slice type for the given element type. +func NewSlice(elem Type) *Slice { return nil } + +// Elem returns element type of slice. +func (*Slice) Elem() Type { return nil } + +// Len returns the length of array. +// A negative result indicates an unknown length. +func (*Array) Len() int { return 0 } + +// NewPointer returns a new pointer type for the given element (base) type. +func NewPointer(elem Type) *Pointer { return nil } + +// Elem returns the element type for the given pointer. +func (*Pointer) Elem() Type { return nil } + +func (*Struct) NumFields() int { return 0 } + +func (*Struct) Field(i int) *Var { return nil } + +type Var struct{} + +func (*Var) Embedded() bool { return false } + +func (*Var) Type() Type { return nil } diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir_loader.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir_loader.go index dcb2fd2af..90dea56ac 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir_loader.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir_loader.go @@ -195,7 +195,7 @@ func (l *irLoader) compileFilterFuncs(filename string, irfile *ir.File) error { if err != nil { // If this ever happens, user will get unexpected error // lines for it; but we should trust that 99.9% errors - // should be catched at irconv phase so we get a valid Go + // should be caught at irconv phase so we get a valid Go // source here as well? return fmt.Errorf("parse custom decls: %w", err) } diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/textmatch/textmatch.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/textmatch/textmatch.go index a3787e2c1..135f95740 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/textmatch/textmatch.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/textmatch/textmatch.go @@ -9,7 +9,7 @@ type Pattern interface { } // Compile parses a regular expression and returns a compiled -// pattern that can match inputs descriped by the regexp. +// pattern that can match inputs described by the regexp. // // Semantically it's close to the regexp.Compile, but // it does recognize some common patterns and creates diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go index d3226db22..6403d91cd 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go @@ -273,7 +273,7 @@ func isTypeExpr(info *types.Info, x ast.Expr) bool { case *ast.Ident: // Identifier may be a type expression if object - // it reffers to is a type name. + // it refers to is a type name. _, ok := info.ObjectOf(x).(*types.TypeName) return ok diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml b/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml index a0e6fd55e..5be8aa487 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml +++ b/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml @@ -1,111 +1,23 @@ # See https://golangci-lint.run/usage/configuration/ - -linters-settings: - revive: - # see https://github.com/mgechev/revive#available-rules for details. - ignore-generated-header: true - severity: warning - rules: - - name: atomic - - name: blank-imports - - name: bool-literal-in-expr - - name: call-to-gc - - name: confusing-naming - - name: confusing-results - - name: constant-logical-expr - - name: context-as-argument - - name: context-keys-type - - name: deep-exit - - name: defer - - name: dot-imports - - name: duplicated-imports - - name: early-return - - name: empty-block - - name: empty-lines - - name: error-naming - - name: error-return - - name: error-strings - - name: errorf - - name: exported - - name: get-return - - name: identical-branches - - name: if-return - - name: import-shadowing - - name: increment-decrement - - name: indent-error-flow - - name: modifies-parameter - - name: modifies-value-receiver - - name: package-comments - - name: range - - name: range-val-address - - name: range-val-in-closure - - name: receiver-naming - - name: redefines-builtin-id - - name: string-of-int - - name: struct-tag - - name: superfluous-else - - name: time-naming - - name: unconditional-recursion - - name: unexported-naming - - name: unexported-return - - name: unnecessary-stmt - - name: unreachable-code - - name: unused-parameter - - name: var-declaration - - name: var-naming - - name: waitgroup-by-value - linters: - disable-all: true - enable: - - asciicheck - - bodyclose - - dogsled - - dupl - - durationcheck - - errcheck - - errorlint - - exhaustive - - exportloopref - - forcetypeassert - - funlen - - gochecknoinits - - gocognit - - goconst - - gocritic - - gocyclo - - godot - - godox - - goimports - - gomoddirectives - - gomodguard - - goprintffuncname - - gosec - - gosimple - - govet - - importas - - ineffassign + enable-all: true + disable: - lll - - makezero - - misspell - - nakedret - - nestif - - nilerr - - noctx - - nolintlint - - prealloc - - predeclared - - revive - - rowserrcheck - - sqlclosecheck - - staticcheck - - stylecheck - - testpackage - - thelper - - tparallel - - typecheck - - unconvert - - unparam - - unused - - whitespace - - wsl + - gomodguard + - gochecknoglobals + - paralleltest + - varnamelen + - exhaustruct + - gomnd + - depguard + - forbidigo + - funlen + - nlreturn + - gofumpt + - nonamedreturns + - cyclop + - err113 + - perfsprint + - tagliatelle + - wrapcheck + - mnd diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml b/tools/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml index f3675a9c2..a8c1ae493 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml +++ b/tools/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml @@ -9,6 +9,14 @@ archives: {{- if eq .Arch "amd64" }}x86_64 {{- else if eq .Arch "386" }}i386 {{- else }}{{ .Arch }}{{ end }} + wrap_in_directory: true + format_overrides: + - goos: windows + format: zip + - goos: darwin + format: tar.xz + - goos: linux + format: tar.xz checksum: name_template: 'checksums.txt' dockers: diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/Makefile b/tools/vendor/github.com/ryancurrah/gomodguard/Makefile index 5235d5aad..906e366c3 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/Makefile +++ b/tools/vendor/github.com/ryancurrah/gomodguard/Makefile @@ -6,7 +6,7 @@ lint: .PHONY: build build: - go build -o gomodguard cmd/gomodguard/main.go + go build -o "$$(go env GOPATH)/bin/gomodguard" cmd/gomodguard/main.go .PHONY: run run: build @@ -43,4 +43,4 @@ install-tools-mac: .PHONY: install-go-tools install-go-tools: - go install -v github.com/t-yuki/gocover-cobertura + go install -v github.com/t-yuki/gocover-cobertura@latest diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/README.md b/tools/vendor/github.com/ryancurrah/gomodguard/README.md index 4945f0101..68dc86044 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/README.md +++ b/tools/vendor/github.com/ryancurrah/gomodguard/README.md @@ -1,7 +1,7 @@ # gomodguard [![License](https://img.shields.io/github/license/ryancurrah/gomodguard?style=flat-square)](/LICENSE) [![Codecov](https://img.shields.io/codecov/c/gh/ryancurrah/gomodguard?style=flat-square)](https://codecov.io/gh/ryancurrah/gomodguard) -[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/ryancurrah/gomodguard/Go?logo=Go&style=flat-square)](https://github.com/ryancurrah/gomodguard/actions?query=workflow%3AGo) +[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/ryancurrah/gomodguard/go.yml?branch=main&logo=Go&style=flat-square)](https://github.com/ryancurrah/gomodguard/actions?query=workflow%3AGo) [![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/ryancurrah/gomodguard?style=flat-square)](https://github.com/ryancurrah/gomodguard/releases/latest) [![Docker](https://img.shields.io/docker/pulls/ryancurrah/gomodguard?style=flat-square)](https://hub.docker.com/r/ryancurrah/gomodguard) [![Github Releases Stats of golangci-lint](https://img.shields.io/github/downloads/ryancurrah/gomodguard/total.svg?logo=github&style=flat-square)](https://somsubhra.com/github-release-stats/?username=ryancurrah&repository=gomodguard) diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/blocked.go b/tools/vendor/github.com/ryancurrah/gomodguard/blocked.go index 2a6e5c215..df24b85ac 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/blocked.go +++ b/tools/vendor/github.com/ryancurrah/gomodguard/blocked.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/Masterminds/semver" + "github.com/Masterminds/semver/v3" ) // Blocked is a list of modules that are @@ -15,7 +15,7 @@ type Blocked struct { LocalReplaceDirectives bool `yaml:"local_replace_directives"` } -// BlockedVersion has a version constraint a reason why the the module version is blocked. +// BlockedVersion has a version constraint a reason why the module version is blocked. type BlockedVersion struct { Version string `yaml:"version"` Reason string `yaml:"reason"` @@ -23,24 +23,22 @@ type BlockedVersion struct { // IsLintedModuleVersionBlocked returns true if a version constraint is specified and the // linted module version matches the constraint. -func (r *BlockedVersion) IsLintedModuleVersionBlocked(lintedModuleVersion string) bool { +func (r *BlockedVersion) IsLintedModuleVersionBlocked(lintedModuleVersion string) (bool, error) { if r.Version == "" { - return false + return false, nil } constraint, err := semver.NewConstraint(r.Version) if err != nil { - return false + return true, err } version, err := semver.NewVersion(lintedModuleVersion) if err != nil { - return false + return true, err } - meet := constraint.Check(version) - - return meet + return constraint.Check(version), nil } // Message returns the reason why the module version is blocked. diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/processor.go b/tools/vendor/github.com/ryancurrah/gomodguard/processor.go index 8457e3b07..f3f42a5be 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/processor.go +++ b/tools/vendor/github.com/ryancurrah/gomodguard/processor.go @@ -22,12 +22,10 @@ const ( ) var ( - blockReasonNotInAllowedList = "import of package `%s` is blocked because the module is not in the " + - "allowed modules list." - blockReasonInBlockedList = "import of package `%s` is blocked because the module is in the " + - "blocked modules list." - blockReasonHasLocalReplaceDirective = "import of package `%s` is blocked because the module has a " + - "local replace directive." + blockReasonNotInAllowedList = "import of package `%s` is blocked because the module is not in the allowed modules list." + blockReasonInBlockedList = "import of package `%s` is blocked because the module is in the blocked modules list." + blockReasonHasLocalReplaceDirective = "import of package `%s` is blocked because the module has a local replace directive." + blockReasonInvalidVersionConstraint = "import of package `%s` is blocked because the version constraint is invalid." // startsWithVersion is used to test when a string begins with the version identifier of a module, // after having stripped the prefix base module name. IE "github.com/foo/bar/v2/baz" => "v2/baz" @@ -141,7 +139,7 @@ func (p *Processor) addError(fileset *token.FileSet, pos token.Pos, reason strin // // It works by iterating over the dependant modules specified in the require // directive, checking if the module domain or full name is in the allowed list. -func (p *Processor) SetBlockedModules() { //nolint:gocognit,funlen +func (p *Processor) SetBlockedModules() { //nolint:funlen blockedModules := make(map[string][]string, len(p.Modfile.Require)) currentModuleName := p.Modfile.Module.Mod.Path lintedModules := p.Modfile.Require @@ -181,9 +179,21 @@ func (p *Processor) SetBlockedModules() { //nolint:gocognit,funlen fmt.Sprintf("%s %s", blockReasonInBlockedList, blockModuleReason.Message())) } - if blockVersionReason != nil && blockVersionReason.IsLintedModuleVersionBlocked(lintedModuleVersion) { - blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], - fmt.Sprintf("%s %s", blockReasonInBlockedList, blockVersionReason.Message(lintedModuleVersion))) + if blockVersionReason != nil { + isVersBlocked, err := blockVersionReason.IsLintedModuleVersionBlocked(lintedModuleVersion) + + var msg string + + switch err { + case nil: + msg = fmt.Sprintf("%s %s", blockReasonInBlockedList, blockVersionReason.Message(lintedModuleVersion)) + default: + msg = fmt.Sprintf("%s %s", blockReasonInvalidVersionConstraint, err) + } + + if isVersBlocked { + blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], msg) + } } } @@ -223,6 +233,11 @@ func (p *Processor) isBlockedPackageFromModFile(packageName string) []string { return nil } +// loadGoModFile loads the contents of the go.mod file in the current working directory. +// It first checks the "GOMOD" environment variable to determine the path of the go.mod file. +// If the environment variable is not set or the file does not exist, it falls back to reading the go.mod file in the current directory. +// If the "GOMOD" environment variable is set to "/dev/null", it returns an error indicating that the current working directory must have a go.mod file. +// The function returns the contents of the go.mod file as a byte slice and any error encountered during the process. func loadGoModFile() ([]byte, error) { cmd := exec.Command("go", "env", "-json") stdout, _ := cmd.StdoutPipe() @@ -250,14 +265,14 @@ func loadGoModFile() ([]byte, error) { return os.ReadFile(goModFilename) } - if goEnv["GOMOD"] == "/dev/null" { + if goEnv["GOMOD"] == "/dev/null" || goEnv["GOMOD"] == "NUL" { return nil, errors.New("current working directory must have a go.mod file") } return os.ReadFile(goEnv["GOMOD"]) } -// isPackageInModule determines if a package is apart of the specified go module. +// isPackageInModule determines if a package is a part of the specified Go module. func isPackageInModule(pkg, mod string) bool { // Split pkg and mod paths into parts pkgPart := strings.Split(pkg, "/") diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/tools.go b/tools/vendor/github.com/ryancurrah/gomodguard/tools.go deleted file mode 100644 index d56bcc747..000000000 --- a/tools/vendor/github.com/ryancurrah/gomodguard/tools.go +++ /dev/null @@ -1,5 +0,0 @@ -//go:build tools - -package gomodguard - -import _ "github.com/t-yuki/gocover-cobertura" diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitignore b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitignore new file mode 100644 index 000000000..3c0af3825 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitignore @@ -0,0 +1,4 @@ +.vscode +.idea +*.swp +cmd/jv/jv diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitmodules b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitmodules new file mode 100644 index 000000000..314da31c5 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/.gitmodules @@ -0,0 +1,3 @@ +[submodule "testdata/JSON-Schema-Test-Suite"] + path = testdata/JSON-Schema-Test-Suite + url = https://github.com/json-schema-org/JSON-Schema-Test-Suite.git diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/LICENSE b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/LICENSE new file mode 100644 index 000000000..19dc35b24 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/LICENSE @@ -0,0 +1,175 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/README.md b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/README.md new file mode 100644 index 000000000..b0d05054c --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/README.md @@ -0,0 +1,220 @@ +# jsonschema v5.3.1 + +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) +[![GoDoc](https://godoc.org/github.com/santhosh-tekuri/jsonschema?status.svg)](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5) +[![Go Report Card](https://goreportcard.com/badge/github.com/santhosh-tekuri/jsonschema/v5)](https://goreportcard.com/report/github.com/santhosh-tekuri/jsonschema/v5) +[![Build Status](https://github.com/santhosh-tekuri/jsonschema/actions/workflows/go.yaml/badge.svg?branch=master)](https://github.com/santhosh-tekuri/jsonschema/actions/workflows/go.yaml) +[![codecov](https://codecov.io/gh/santhosh-tekuri/jsonschema/branch/master/graph/badge.svg?token=JMVj1pFT2l)](https://codecov.io/gh/santhosh-tekuri/jsonschema) + +Package jsonschema provides json-schema compilation and validation. + +[Benchmarks](https://dev.to/vearutop/benchmarking-correctness-and-performance-of-go-json-schema-validators-3247) + +### Features: + - implements + [draft 2020-12](https://json-schema.org/specification-links.html#2020-12), + [draft 2019-09](https://json-schema.org/specification-links.html#draft-2019-09-formerly-known-as-draft-8), + [draft-7](https://json-schema.org/specification-links.html#draft-7), + [draft-6](https://json-schema.org/specification-links.html#draft-6), + [draft-4](https://json-schema.org/specification-links.html#draft-4) + - fully compliant with [JSON-Schema-Test-Suite](https://github.com/json-schema-org/JSON-Schema-Test-Suite), (excluding some optional) + - list of optional tests that are excluded can be found in schema_test.go(variable [skipTests](https://github.com/santhosh-tekuri/jsonschema/blob/master/schema_test.go#L24)) + - validates schemas against meta-schema + - full support of remote references + - support of recursive references between schemas + - detects infinite loop in schemas + - thread safe validation + - rich, intuitive hierarchial error messages with json-pointers to exact location + - supports output formats flag, basic and detailed + - supports enabling format and content Assertions in draft2019-09 or above + - change `Compiler.AssertFormat`, `Compiler.AssertContent` to `true` + - compiled schema can be introspected. easier to develop tools like generating go structs given schema + - supports user-defined keywords via [extensions](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5/#example-package-Extension) + - implements following formats (supports [user-defined](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5/#example-package-UserDefinedFormat)) + - date-time, date, time, duration, period (supports leap-second) + - uuid, hostname, email + - ip-address, ipv4, ipv6 + - uri, uriref, uri-template(limited validation) + - json-pointer, relative-json-pointer + - regex, format + - implements following contentEncoding (supports [user-defined](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5/#example-package-UserDefinedContent)) + - base64 + - implements following contentMediaType (supports [user-defined](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5/#example-package-UserDefinedContent)) + - application/json + - can load from files/http/https/[string](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5/#example-package-FromString)/[]byte/io.Reader (supports [user-defined](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5/#example-package-UserDefinedLoader)) + + +see examples in [godoc](https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v5) + +The schema is compiled against the version specified in `$schema` property. +If "$schema" property is missing, it uses latest draft which currently implemented +by this library. + +You can force to use specific version, when `$schema` is missing, as follows: + +```go +compiler := jsonschema.NewCompiler() +compiler.Draft = jsonschema.Draft4 +``` + +This package supports loading json-schema from filePath and fileURL. + +To load json-schema from HTTPURL, add following import: + +```go +import _ "github.com/santhosh-tekuri/jsonschema/v5/httploader" +``` + +## Rich Errors + +The ValidationError returned by Validate method contains detailed context to understand why and where the error is. + +schema.json: +```json +{ + "$ref": "t.json#/definitions/employee" +} +``` + +t.json: +```json +{ + "definitions": { + "employee": { + "type": "string" + } + } +} +``` + +doc.json: +```json +1 +``` + +assuming `err` is the ValidationError returned when `doc.json` validated with `schema.json`, +```go +fmt.Printf("%#v\n", err) // using %#v prints errors hierarchy +``` +Prints: +``` +[I#] [S#] doesn't validate with file:///Users/santhosh/jsonschema/schema.json# + [I#] [S#/$ref] doesn't validate with 'file:///Users/santhosh/jsonschema/t.json#/definitions/employee' + [I#] [S#/definitions/employee/type] expected string, but got number +``` + +Here `I` stands for instance document and `S` stands for schema document. +The json-fragments that caused error in instance and schema documents are represented using json-pointer notation. +Nested causes are printed with indent. + +To output `err` in `flag` output format: +```go +b, _ := json.MarshalIndent(err.FlagOutput(), "", " ") +fmt.Println(string(b)) +``` +Prints: +```json +{ + "valid": false +} +``` +To output `err` in `basic` output format: +```go +b, _ := json.MarshalIndent(err.BasicOutput(), "", " ") +fmt.Println(string(b)) +``` +Prints: +```json +{ + "valid": false, + "errors": [ + { + "keywordLocation": "", + "absoluteKeywordLocation": "file:///Users/santhosh/jsonschema/schema.json#", + "instanceLocation": "", + "error": "doesn't validate with file:///Users/santhosh/jsonschema/schema.json#" + }, + { + "keywordLocation": "/$ref", + "absoluteKeywordLocation": "file:///Users/santhosh/jsonschema/schema.json#/$ref", + "instanceLocation": "", + "error": "doesn't validate with 'file:///Users/santhosh/jsonschema/t.json#/definitions/employee'" + }, + { + "keywordLocation": "/$ref/type", + "absoluteKeywordLocation": "file:///Users/santhosh/jsonschema/t.json#/definitions/employee/type", + "instanceLocation": "", + "error": "expected string, but got number" + } + ] +} +``` +To output `err` in `detailed` output format: +```go +b, _ := json.MarshalIndent(err.DetailedOutput(), "", " ") +fmt.Println(string(b)) +``` +Prints: +```json +{ + "valid": false, + "keywordLocation": "", + "absoluteKeywordLocation": "file:///Users/santhosh/jsonschema/schema.json#", + "instanceLocation": "", + "errors": [ + { + "valid": false, + "keywordLocation": "/$ref", + "absoluteKeywordLocation": "file:///Users/santhosh/jsonschema/schema.json#/$ref", + "instanceLocation": "", + "errors": [ + { + "valid": false, + "keywordLocation": "/$ref/type", + "absoluteKeywordLocation": "file:///Users/santhosh/jsonschema/t.json#/definitions/employee/type", + "instanceLocation": "", + "error": "expected string, but got number" + } + ] + } + ] +} +``` + +## CLI + +to install `go install github.com/santhosh-tekuri/jsonschema/cmd/jv@latest` + +```bash +jv [-draft INT] [-output FORMAT] [-assertformat] [-assertcontent] []... + -assertcontent + enable content assertions with draft >= 2019 + -assertformat + enable format assertions with draft >= 2019 + -draft int + draft used when '$schema' attribute is missing. valid values 4, 5, 7, 2019, 2020 (default 2020) + -output string + output format. valid values flag, basic, detailed +``` + +if no `` arguments are passed, it simply validates the ``. +if `$schema` attribute is missing in schema, it uses latest version. this can be overridden by passing `-draft` flag + +exit-code is 1, if there are any validation errors + +`jv` can also validate yaml files. It also accepts schema from yaml files. + +## Validating YAML Documents + +since yaml supports non-string keys, such yaml documents are rendered as invalid json documents. + +most yaml parser use `map[interface{}]interface{}` for object, +whereas json parser uses `map[string]interface{}`. + +so we need to manually convert them to `map[string]interface{}`. +below code shows such conversion by `toStringKeys` function. + +https://play.golang.org/p/Hhax3MrtD8r + +NOTE: if you are using `gopkg.in/yaml.v3`, then you do not need such conversion. since this library +returns `map[string]interface{}` if all keys are strings. \ No newline at end of file diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/compiler.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/compiler.go new file mode 100644 index 000000000..fdb68e648 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/compiler.go @@ -0,0 +1,812 @@ +package jsonschema + +import ( + "encoding/json" + "fmt" + "io" + "math/big" + "regexp" + "strconv" + "strings" +) + +// A Compiler represents a json-schema compiler. +type Compiler struct { + // Draft represents the draft used when '$schema' attribute is missing. + // + // This defaults to latest supported draft (currently 2020-12). + Draft *Draft + resources map[string]*resource + + // Extensions is used to register extensions. + extensions map[string]extension + + // ExtractAnnotations tells whether schema annotations has to be extracted + // in compiled Schema or not. + ExtractAnnotations bool + + // LoadURL loads the document at given absolute URL. + // + // If nil, package global LoadURL is used. + LoadURL func(s string) (io.ReadCloser, error) + + // Formats can be registered by adding to this map. Key is format name, + // value is function that knows how to validate that format. + Formats map[string]func(interface{}) bool + + // AssertFormat for specifications >= draft2019-09. + AssertFormat bool + + // Decoders can be registered by adding to this map. Key is encoding name, + // value is function that knows how to decode string in that format. + Decoders map[string]func(string) ([]byte, error) + + // MediaTypes can be registered by adding to this map. Key is mediaType name, + // value is function that knows how to validate that mediaType. + MediaTypes map[string]func([]byte) error + + // AssertContent for specifications >= draft2019-09. + AssertContent bool +} + +// Compile parses json-schema at given url returns, if successful, +// a Schema object that can be used to match against json. +// +// Returned error can be *SchemaError +func Compile(url string) (*Schema, error) { + return NewCompiler().Compile(url) +} + +// MustCompile is like Compile but panics if the url cannot be compiled to *Schema. +// It simplifies safe initialization of global variables holding compiled Schemas. +func MustCompile(url string) *Schema { + return NewCompiler().MustCompile(url) +} + +// CompileString parses and compiles the given schema with given base url. +func CompileString(url, schema string) (*Schema, error) { + c := NewCompiler() + if err := c.AddResource(url, strings.NewReader(schema)); err != nil { + return nil, err + } + return c.Compile(url) +} + +// MustCompileString is like CompileString but panics on error. +// It simplified safe initialization of global variables holding compiled Schema. +func MustCompileString(url, schema string) *Schema { + c := NewCompiler() + if err := c.AddResource(url, strings.NewReader(schema)); err != nil { + panic(err) + } + return c.MustCompile(url) +} + +// NewCompiler returns a json-schema Compiler object. +// if '$schema' attribute is missing, it is treated as draft7. to change this +// behavior change Compiler.Draft value +func NewCompiler() *Compiler { + return &Compiler{ + Draft: latest, + resources: make(map[string]*resource), + Formats: make(map[string]func(interface{}) bool), + Decoders: make(map[string]func(string) ([]byte, error)), + MediaTypes: make(map[string]func([]byte) error), + extensions: make(map[string]extension), + } +} + +// AddResource adds in-memory resource to the compiler. +// +// Note that url must not have fragment +func (c *Compiler) AddResource(url string, r io.Reader) error { + res, err := newResource(url, r) + if err != nil { + return err + } + c.resources[res.url] = res + return nil +} + +// MustCompile is like Compile but panics if the url cannot be compiled to *Schema. +// It simplifies safe initialization of global variables holding compiled Schemas. +func (c *Compiler) MustCompile(url string) *Schema { + s, err := c.Compile(url) + if err != nil { + panic(fmt.Sprintf("jsonschema: %#v", err)) + } + return s +} + +// Compile parses json-schema at given url returns, if successful, +// a Schema object that can be used to match against json. +// +// error returned will be of type *SchemaError +func (c *Compiler) Compile(url string) (*Schema, error) { + // make url absolute + u, err := toAbs(url) + if err != nil { + return nil, &SchemaError{url, err} + } + url = u + + sch, err := c.compileURL(url, nil, "#") + if err != nil { + err = &SchemaError{url, err} + } + return sch, err +} + +func (c *Compiler) findResource(url string) (*resource, error) { + if _, ok := c.resources[url]; !ok { + // load resource + var rdr io.Reader + if sch, ok := vocabSchemas[url]; ok { + rdr = strings.NewReader(sch) + } else { + loadURL := LoadURL + if c.LoadURL != nil { + loadURL = c.LoadURL + } + r, err := loadURL(url) + if err != nil { + return nil, err + } + defer r.Close() + rdr = r + } + if err := c.AddResource(url, rdr); err != nil { + return nil, err + } + } + + r := c.resources[url] + if r.draft != nil { + return r, nil + } + + // set draft + r.draft = c.Draft + if m, ok := r.doc.(map[string]interface{}); ok { + if sch, ok := m["$schema"]; ok { + sch, ok := sch.(string) + if !ok { + return nil, fmt.Errorf("jsonschema: invalid $schema in %s", url) + } + if !isURI(sch) { + return nil, fmt.Errorf("jsonschema: $schema must be uri in %s", url) + } + r.draft = findDraft(sch) + if r.draft == nil { + sch, _ := split(sch) + if sch == url { + return nil, fmt.Errorf("jsonschema: unsupported draft in %s", url) + } + mr, err := c.findResource(sch) + if err != nil { + return nil, err + } + r.draft = mr.draft + } + } + } + + id, err := r.draft.resolveID(r.url, r.doc) + if err != nil { + return nil, err + } + if id != "" { + r.url = id + } + + if err := r.fillSubschemas(c, r); err != nil { + return nil, err + } + + return r, nil +} + +func (c *Compiler) compileURL(url string, stack []schemaRef, ptr string) (*Schema, error) { + // if url points to a draft, return Draft.meta + if d := findDraft(url); d != nil && d.meta != nil { + return d.meta, nil + } + + b, f := split(url) + r, err := c.findResource(b) + if err != nil { + return nil, err + } + return c.compileRef(r, stack, ptr, r, f) +} + +func (c *Compiler) compileRef(r *resource, stack []schemaRef, refPtr string, res *resource, ref string) (*Schema, error) { + base := r.baseURL(res.floc) + ref, err := resolveURL(base, ref) + if err != nil { + return nil, err + } + + u, f := split(ref) + sr := r.findResource(u) + if sr == nil { + // external resource + return c.compileURL(ref, stack, refPtr) + } + + // ensure root resource is always compiled first. + // this is required to get schema.meta from root resource + if r.schema == nil { + r.schema = newSchema(r.url, r.floc, r.draft, r.doc) + if _, err := c.compile(r, nil, schemaRef{"#", r.schema, false}, r); err != nil { + return nil, err + } + } + + sr, err = r.resolveFragment(c, sr, f) + if err != nil { + return nil, err + } + if sr == nil { + return nil, fmt.Errorf("jsonschema: %s not found", ref) + } + + if sr.schema != nil { + if err := checkLoop(stack, schemaRef{refPtr, sr.schema, false}); err != nil { + return nil, err + } + return sr.schema, nil + } + + sr.schema = newSchema(r.url, sr.floc, r.draft, sr.doc) + return c.compile(r, stack, schemaRef{refPtr, sr.schema, false}, sr) +} + +func (c *Compiler) compileDynamicAnchors(r *resource, res *resource) error { + if r.draft.version < 2020 { + return nil + } + + rr := r.listResources(res) + rr = append(rr, res) + for _, sr := range rr { + if m, ok := sr.doc.(map[string]interface{}); ok { + if _, ok := m["$dynamicAnchor"]; ok { + sch, err := c.compileRef(r, nil, "IGNORED", r, sr.floc) + if err != nil { + return err + } + res.schema.dynamicAnchors = append(res.schema.dynamicAnchors, sch) + } + } + } + return nil +} + +func (c *Compiler) compile(r *resource, stack []schemaRef, sref schemaRef, res *resource) (*Schema, error) { + if err := c.compileDynamicAnchors(r, res); err != nil { + return nil, err + } + + switch v := res.doc.(type) { + case bool: + res.schema.Always = &v + return res.schema, nil + default: + return res.schema, c.compileMap(r, stack, sref, res) + } +} + +func (c *Compiler) compileMap(r *resource, stack []schemaRef, sref schemaRef, res *resource) error { + m := res.doc.(map[string]interface{}) + + if err := checkLoop(stack, sref); err != nil { + return err + } + stack = append(stack, sref) + + var s = res.schema + var err error + + if r == res { // root schema + if sch, ok := m["$schema"]; ok { + sch := sch.(string) + if d := findDraft(sch); d != nil { + s.meta = d.meta + } else { + if s.meta, err = c.compileRef(r, stack, "$schema", res, sch); err != nil { + return err + } + } + } + } + + if ref, ok := m["$ref"]; ok { + s.Ref, err = c.compileRef(r, stack, "$ref", res, ref.(string)) + if err != nil { + return err + } + if r.draft.version < 2019 { + // All other properties in a "$ref" object MUST be ignored + return nil + } + } + + if r.draft.version >= 2019 { + if r == res { // root schema + if vocab, ok := m["$vocabulary"]; ok { + for url, reqd := range vocab.(map[string]interface{}) { + if reqd, ok := reqd.(bool); ok && !reqd { + continue + } + if !r.draft.isVocab(url) { + return fmt.Errorf("jsonschema: unsupported vocab %q in %s", url, res) + } + s.vocab = append(s.vocab, url) + } + } else { + s.vocab = r.draft.defaultVocab + } + } + + if ref, ok := m["$recursiveRef"]; ok { + s.RecursiveRef, err = c.compileRef(r, stack, "$recursiveRef", res, ref.(string)) + if err != nil { + return err + } + } + } + if r.draft.version >= 2020 { + if dref, ok := m["$dynamicRef"]; ok { + s.DynamicRef, err = c.compileRef(r, stack, "$dynamicRef", res, dref.(string)) + if err != nil { + return err + } + if dref, ok := dref.(string); ok { + _, frag := split(dref) + if frag != "#" && !strings.HasPrefix(frag, "#/") { + // frag is anchor + s.dynamicRefAnchor = frag[1:] + } + } + } + } + + loadInt := func(pname string) int { + if num, ok := m[pname]; ok { + i, _ := num.(json.Number).Float64() + return int(i) + } + return -1 + } + + loadRat := func(pname string) *big.Rat { + if num, ok := m[pname]; ok { + r, _ := new(big.Rat).SetString(string(num.(json.Number))) + return r + } + return nil + } + + if r.draft.version < 2019 || r.schema.meta.hasVocab("validation") { + if t, ok := m["type"]; ok { + switch t := t.(type) { + case string: + s.Types = []string{t} + case []interface{}: + s.Types = toStrings(t) + } + } + + if e, ok := m["enum"]; ok { + s.Enum = e.([]interface{}) + allPrimitives := true + for _, item := range s.Enum { + switch jsonType(item) { + case "object", "array": + allPrimitives = false + break + } + } + s.enumError = "enum failed" + if allPrimitives { + if len(s.Enum) == 1 { + s.enumError = fmt.Sprintf("value must be %#v", s.Enum[0]) + } else { + strEnum := make([]string, len(s.Enum)) + for i, item := range s.Enum { + strEnum[i] = fmt.Sprintf("%#v", item) + } + s.enumError = fmt.Sprintf("value must be one of %s", strings.Join(strEnum, ", ")) + } + } + } + + s.Minimum = loadRat("minimum") + if exclusive, ok := m["exclusiveMinimum"]; ok { + if exclusive, ok := exclusive.(bool); ok { + if exclusive { + s.Minimum, s.ExclusiveMinimum = nil, s.Minimum + } + } else { + s.ExclusiveMinimum = loadRat("exclusiveMinimum") + } + } + + s.Maximum = loadRat("maximum") + if exclusive, ok := m["exclusiveMaximum"]; ok { + if exclusive, ok := exclusive.(bool); ok { + if exclusive { + s.Maximum, s.ExclusiveMaximum = nil, s.Maximum + } + } else { + s.ExclusiveMaximum = loadRat("exclusiveMaximum") + } + } + + s.MultipleOf = loadRat("multipleOf") + + s.MinProperties, s.MaxProperties = loadInt("minProperties"), loadInt("maxProperties") + + if req, ok := m["required"]; ok { + s.Required = toStrings(req.([]interface{})) + } + + s.MinItems, s.MaxItems = loadInt("minItems"), loadInt("maxItems") + + if unique, ok := m["uniqueItems"]; ok { + s.UniqueItems = unique.(bool) + } + + s.MinLength, s.MaxLength = loadInt("minLength"), loadInt("maxLength") + + if pattern, ok := m["pattern"]; ok { + s.Pattern = regexp.MustCompile(pattern.(string)) + } + + if r.draft.version >= 2019 { + s.MinContains, s.MaxContains = loadInt("minContains"), loadInt("maxContains") + if s.MinContains == -1 { + s.MinContains = 1 + } + + if deps, ok := m["dependentRequired"]; ok { + deps := deps.(map[string]interface{}) + s.DependentRequired = make(map[string][]string, len(deps)) + for pname, pvalue := range deps { + s.DependentRequired[pname] = toStrings(pvalue.([]interface{})) + } + } + } + } + + compile := func(stack []schemaRef, ptr string) (*Schema, error) { + return c.compileRef(r, stack, ptr, res, r.url+res.floc+"/"+ptr) + } + + loadSchema := func(pname string, stack []schemaRef) (*Schema, error) { + if _, ok := m[pname]; ok { + return compile(stack, escape(pname)) + } + return nil, nil + } + + loadSchemas := func(pname string, stack []schemaRef) ([]*Schema, error) { + if pvalue, ok := m[pname]; ok { + pvalue := pvalue.([]interface{}) + schemas := make([]*Schema, len(pvalue)) + for i := range pvalue { + sch, err := compile(stack, escape(pname)+"/"+strconv.Itoa(i)) + if err != nil { + return nil, err + } + schemas[i] = sch + } + return schemas, nil + } + return nil, nil + } + + if r.draft.version < 2019 || r.schema.meta.hasVocab("applicator") { + if s.Not, err = loadSchema("not", stack); err != nil { + return err + } + if s.AllOf, err = loadSchemas("allOf", stack); err != nil { + return err + } + if s.AnyOf, err = loadSchemas("anyOf", stack); err != nil { + return err + } + if s.OneOf, err = loadSchemas("oneOf", stack); err != nil { + return err + } + + if props, ok := m["properties"]; ok { + props := props.(map[string]interface{}) + s.Properties = make(map[string]*Schema, len(props)) + for pname := range props { + s.Properties[pname], err = compile(nil, "properties/"+escape(pname)) + if err != nil { + return err + } + } + } + + if regexProps, ok := m["regexProperties"]; ok { + s.RegexProperties = regexProps.(bool) + } + + if patternProps, ok := m["patternProperties"]; ok { + patternProps := patternProps.(map[string]interface{}) + s.PatternProperties = make(map[*regexp.Regexp]*Schema, len(patternProps)) + for pattern := range patternProps { + s.PatternProperties[regexp.MustCompile(pattern)], err = compile(nil, "patternProperties/"+escape(pattern)) + if err != nil { + return err + } + } + } + + if additionalProps, ok := m["additionalProperties"]; ok { + switch additionalProps := additionalProps.(type) { + case bool: + s.AdditionalProperties = additionalProps + case map[string]interface{}: + s.AdditionalProperties, err = compile(nil, "additionalProperties") + if err != nil { + return err + } + } + } + + if deps, ok := m["dependencies"]; ok { + deps := deps.(map[string]interface{}) + s.Dependencies = make(map[string]interface{}, len(deps)) + for pname, pvalue := range deps { + switch pvalue := pvalue.(type) { + case []interface{}: + s.Dependencies[pname] = toStrings(pvalue) + default: + s.Dependencies[pname], err = compile(stack, "dependencies/"+escape(pname)) + if err != nil { + return err + } + } + } + } + + if r.draft.version >= 6 { + if s.PropertyNames, err = loadSchema("propertyNames", nil); err != nil { + return err + } + if s.Contains, err = loadSchema("contains", nil); err != nil { + return err + } + } + + if r.draft.version >= 7 { + if m["if"] != nil { + if s.If, err = loadSchema("if", stack); err != nil { + return err + } + if s.Then, err = loadSchema("then", stack); err != nil { + return err + } + if s.Else, err = loadSchema("else", stack); err != nil { + return err + } + } + } + if r.draft.version >= 2019 { + if deps, ok := m["dependentSchemas"]; ok { + deps := deps.(map[string]interface{}) + s.DependentSchemas = make(map[string]*Schema, len(deps)) + for pname := range deps { + s.DependentSchemas[pname], err = compile(stack, "dependentSchemas/"+escape(pname)) + if err != nil { + return err + } + } + } + } + + if r.draft.version >= 2020 { + if s.PrefixItems, err = loadSchemas("prefixItems", nil); err != nil { + return err + } + if s.Items2020, err = loadSchema("items", nil); err != nil { + return err + } + } else { + if items, ok := m["items"]; ok { + switch items.(type) { + case []interface{}: + s.Items, err = loadSchemas("items", nil) + if err != nil { + return err + } + if additionalItems, ok := m["additionalItems"]; ok { + switch additionalItems := additionalItems.(type) { + case bool: + s.AdditionalItems = additionalItems + case map[string]interface{}: + s.AdditionalItems, err = compile(nil, "additionalItems") + if err != nil { + return err + } + } + } + default: + s.Items, err = compile(nil, "items") + if err != nil { + return err + } + } + } + } + + } + + // unevaluatedXXX keywords were in "applicator" vocab in 2019, but moved to new vocab "unevaluated" in 2020 + if (r.draft.version == 2019 && r.schema.meta.hasVocab("applicator")) || (r.draft.version >= 2020 && r.schema.meta.hasVocab("unevaluated")) { + if s.UnevaluatedProperties, err = loadSchema("unevaluatedProperties", nil); err != nil { + return err + } + if s.UnevaluatedItems, err = loadSchema("unevaluatedItems", nil); err != nil { + return err + } + if r.draft.version >= 2020 { + // any item in an array that passes validation of the contains schema is considered "evaluated" + s.ContainsEval = true + } + } + + if format, ok := m["format"]; ok { + s.Format = format.(string) + if r.draft.version < 2019 || c.AssertFormat || r.schema.meta.hasVocab("format-assertion") { + if format, ok := c.Formats[s.Format]; ok { + s.format = format + } else { + s.format, _ = Formats[s.Format] + } + } + } + + if c.ExtractAnnotations { + if title, ok := m["title"]; ok { + s.Title = title.(string) + } + if description, ok := m["description"]; ok { + s.Description = description.(string) + } + s.Default = m["default"] + } + + if r.draft.version >= 6 { + if c, ok := m["const"]; ok { + s.Constant = []interface{}{c} + } + } + + if r.draft.version >= 7 { + if encoding, ok := m["contentEncoding"]; ok { + s.ContentEncoding = encoding.(string) + if decoder, ok := c.Decoders[s.ContentEncoding]; ok { + s.decoder = decoder + } else { + s.decoder, _ = Decoders[s.ContentEncoding] + } + } + if mediaType, ok := m["contentMediaType"]; ok { + s.ContentMediaType = mediaType.(string) + if mediaType, ok := c.MediaTypes[s.ContentMediaType]; ok { + s.mediaType = mediaType + } else { + s.mediaType, _ = MediaTypes[s.ContentMediaType] + } + if s.ContentSchema, err = loadSchema("contentSchema", stack); err != nil { + return err + } + } + if c.ExtractAnnotations { + if comment, ok := m["$comment"]; ok { + s.Comment = comment.(string) + } + if readOnly, ok := m["readOnly"]; ok { + s.ReadOnly = readOnly.(bool) + } + if writeOnly, ok := m["writeOnly"]; ok { + s.WriteOnly = writeOnly.(bool) + } + if examples, ok := m["examples"]; ok { + s.Examples = examples.([]interface{}) + } + } + } + + if r.draft.version >= 2019 { + if !c.AssertContent { + s.decoder = nil + s.mediaType = nil + s.ContentSchema = nil + } + if c.ExtractAnnotations { + if deprecated, ok := m["deprecated"]; ok { + s.Deprecated = deprecated.(bool) + } + } + } + + for name, ext := range c.extensions { + es, err := ext.compiler.Compile(CompilerContext{c, r, stack, res}, m) + if err != nil { + return err + } + if es != nil { + if s.Extensions == nil { + s.Extensions = make(map[string]ExtSchema) + } + s.Extensions[name] = es + } + } + + return nil +} + +func (c *Compiler) validateSchema(r *resource, v interface{}, vloc string) error { + validate := func(meta *Schema) error { + if meta == nil { + return nil + } + return meta.validateValue(v, vloc) + } + + if err := validate(r.draft.meta); err != nil { + return err + } + for _, ext := range c.extensions { + if err := validate(ext.meta); err != nil { + return err + } + } + return nil +} + +func toStrings(arr []interface{}) []string { + s := make([]string, len(arr)) + for i, v := range arr { + s[i] = v.(string) + } + return s +} + +// SchemaRef captures schema and the path referring to it. +type schemaRef struct { + path string // relative-json-pointer to schema + schema *Schema // target schema + discard bool // true when scope left +} + +func (sr schemaRef) String() string { + return fmt.Sprintf("(%s)%v", sr.path, sr.schema) +} + +func checkLoop(stack []schemaRef, sref schemaRef) error { + for _, ref := range stack { + if ref.schema == sref.schema { + return infiniteLoopError(stack, sref) + } + } + return nil +} + +func keywordLocation(stack []schemaRef, path string) string { + var loc string + for _, ref := range stack[1:] { + loc += "/" + ref.path + } + if path != "" { + loc = loc + "/" + path + } + return loc +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/content.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/content.go new file mode 100644 index 000000000..7570b8b5a --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/content.go @@ -0,0 +1,29 @@ +package jsonschema + +import ( + "encoding/base64" + "encoding/json" +) + +// Decoders is a registry of functions, which know how to decode +// string encoded in specific format. +// +// New Decoders can be registered by adding to this map. Key is encoding name, +// value is function that knows how to decode string in that format. +var Decoders = map[string]func(string) ([]byte, error){ + "base64": base64.StdEncoding.DecodeString, +} + +// MediaTypes is a registry of functions, which know how to validate +// whether the bytes represent data of that mediaType. +// +// New mediaTypes can be registered by adding to this map. Key is mediaType name, +// value is function that knows how to validate that mediaType. +var MediaTypes = map[string]func([]byte) error{ + "application/json": validateJSON, +} + +func validateJSON(b []byte) error { + var v interface{} + return json.Unmarshal(b, &v) +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/doc.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/doc.go new file mode 100644 index 000000000..a124262a5 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/doc.go @@ -0,0 +1,49 @@ +/* +Package jsonschema provides json-schema compilation and validation. + +Features: + - implements draft 2020-12, 2019-09, draft-7, draft-6, draft-4 + - fully compliant with JSON-Schema-Test-Suite, (excluding some optional) + - list of optional tests that are excluded can be found in schema_test.go(variable skipTests) + - validates schemas against meta-schema + - full support of remote references + - support of recursive references between schemas + - detects infinite loop in schemas + - thread safe validation + - rich, intuitive hierarchial error messages with json-pointers to exact location + - supports output formats flag, basic and detailed + - supports enabling format and content Assertions in draft2019-09 or above + - change Compiler.AssertFormat, Compiler.AssertContent to true + - compiled schema can be introspected. easier to develop tools like generating go structs given schema + - supports user-defined keywords via extensions + - implements following formats (supports user-defined) + - date-time, date, time, duration (supports leap-second) + - uuid, hostname, email + - ip-address, ipv4, ipv6 + - uri, uriref, uri-template(limited validation) + - json-pointer, relative-json-pointer + - regex, format + - implements following contentEncoding (supports user-defined) + - base64 + - implements following contentMediaType (supports user-defined) + - application/json + - can load from files/http/https/string/[]byte/io.Reader (supports user-defined) + +The schema is compiled against the version specified in "$schema" property. +If "$schema" property is missing, it uses latest draft which currently implemented +by this library. + +You can force to use specific draft, when "$schema" is missing, as follows: + + compiler := jsonschema.NewCompiler() + compiler.Draft = jsonschema.Draft4 + +This package supports loading json-schema from filePath and fileURL. + +To load json-schema from HTTPURL, add following import: + + import _ "github.com/santhosh-tekuri/jsonschema/v5/httploader" + +you can validate yaml documents. see https://play.golang.org/p/sJy1qY7dXgA +*/ +package jsonschema diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/draft.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/draft.go new file mode 100644 index 000000000..154fa5837 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/draft.go @@ -0,0 +1,1454 @@ +package jsonschema + +import ( + "fmt" + "strconv" + "strings" +) + +// A Draft represents json-schema draft +type Draft struct { + version int + meta *Schema + id string // property name used to represent schema id. + boolSchema bool // is boolean valid schema + vocab []string // built-in vocab + defaultVocab []string // vocabs when $vocabulary is not used + subschemas map[string]position +} + +func (d *Draft) URL() string { + switch d.version { + case 2020: + return "https://json-schema.org/draft/2020-12/schema" + case 2019: + return "https://json-schema.org/draft/2019-09/schema" + case 7: + return "https://json-schema.org/draft-07/schema" + case 6: + return "https://json-schema.org/draft-06/schema" + case 4: + return "https://json-schema.org/draft-04/schema" + } + return "" +} + +func (d *Draft) String() string { + return fmt.Sprintf("Draft%d", d.version) +} + +func (d *Draft) loadMeta(url, schema string) { + c := NewCompiler() + c.AssertFormat = true + if err := c.AddResource(url, strings.NewReader(schema)); err != nil { + panic(err) + } + d.meta = c.MustCompile(url) + d.meta.meta = d.meta +} + +func (d *Draft) getID(sch interface{}) string { + m, ok := sch.(map[string]interface{}) + if !ok { + return "" + } + if _, ok := m["$ref"]; ok && d.version <= 7 { + // $ref prevents a sibling id from changing the base uri + return "" + } + v, ok := m[d.id] + if !ok { + return "" + } + id, ok := v.(string) + if !ok { + return "" + } + return id +} + +func (d *Draft) resolveID(base string, sch interface{}) (string, error) { + id, _ := split(d.getID(sch)) // strip fragment + if id == "" { + return "", nil + } + url, err := resolveURL(base, id) + url, _ = split(url) // strip fragment + return url, err +} + +func (d *Draft) anchors(sch interface{}) []string { + m, ok := sch.(map[string]interface{}) + if !ok { + return nil + } + + var anchors []string + + // before draft2019, anchor is specified in id + _, f := split(d.getID(m)) + if f != "#" { + anchors = append(anchors, f[1:]) + } + + if v, ok := m["$anchor"]; ok && d.version >= 2019 { + anchors = append(anchors, v.(string)) + } + if v, ok := m["$dynamicAnchor"]; ok && d.version >= 2020 { + anchors = append(anchors, v.(string)) + } + return anchors +} + +// listSubschemas collects subschemas in r into rr. +func (d *Draft) listSubschemas(r *resource, base string, rr map[string]*resource) error { + add := func(loc string, sch interface{}) error { + url, err := d.resolveID(base, sch) + if err != nil { + return err + } + floc := r.floc + "/" + loc + sr := &resource{url: url, floc: floc, doc: sch} + rr[floc] = sr + + base := base + if url != "" { + base = url + } + return d.listSubschemas(sr, base, rr) + } + + sch, ok := r.doc.(map[string]interface{}) + if !ok { + return nil + } + for kw, pos := range d.subschemas { + v, ok := sch[kw] + if !ok { + continue + } + if pos&self != 0 { + switch v := v.(type) { + case map[string]interface{}: + if err := add(kw, v); err != nil { + return err + } + case bool: + if d.boolSchema { + if err := add(kw, v); err != nil { + return err + } + } + } + } + if pos&item != 0 { + if v, ok := v.([]interface{}); ok { + for i, item := range v { + if err := add(kw+"/"+strconv.Itoa(i), item); err != nil { + return err + } + } + } + } + if pos&prop != 0 { + if v, ok := v.(map[string]interface{}); ok { + for pname, pval := range v { + if err := add(kw+"/"+escape(pname), pval); err != nil { + return err + } + } + } + } + } + return nil +} + +// isVocab tells whether url is built-in vocab. +func (d *Draft) isVocab(url string) bool { + for _, v := range d.vocab { + if url == v { + return true + } + } + return false +} + +type position uint + +const ( + self position = 1 << iota + prop + item +) + +// supported drafts +var ( + Draft4 = &Draft{version: 4, id: "id", boolSchema: false} + Draft6 = &Draft{version: 6, id: "$id", boolSchema: true} + Draft7 = &Draft{version: 7, id: "$id", boolSchema: true} + Draft2019 = &Draft{ + version: 2019, + id: "$id", + boolSchema: true, + vocab: []string{ + "https://json-schema.org/draft/2019-09/vocab/core", + "https://json-schema.org/draft/2019-09/vocab/applicator", + "https://json-schema.org/draft/2019-09/vocab/validation", + "https://json-schema.org/draft/2019-09/vocab/meta-data", + "https://json-schema.org/draft/2019-09/vocab/format", + "https://json-schema.org/draft/2019-09/vocab/content", + }, + defaultVocab: []string{ + "https://json-schema.org/draft/2019-09/vocab/core", + "https://json-schema.org/draft/2019-09/vocab/applicator", + "https://json-schema.org/draft/2019-09/vocab/validation", + }, + } + Draft2020 = &Draft{ + version: 2020, + id: "$id", + boolSchema: true, + vocab: []string{ + "https://json-schema.org/draft/2020-12/vocab/core", + "https://json-schema.org/draft/2020-12/vocab/applicator", + "https://json-schema.org/draft/2020-12/vocab/unevaluated", + "https://json-schema.org/draft/2020-12/vocab/validation", + "https://json-schema.org/draft/2020-12/vocab/meta-data", + "https://json-schema.org/draft/2020-12/vocab/format-annotation", + "https://json-schema.org/draft/2020-12/vocab/format-assertion", + "https://json-schema.org/draft/2020-12/vocab/content", + }, + defaultVocab: []string{ + "https://json-schema.org/draft/2020-12/vocab/core", + "https://json-schema.org/draft/2020-12/vocab/applicator", + "https://json-schema.org/draft/2020-12/vocab/unevaluated", + "https://json-schema.org/draft/2020-12/vocab/validation", + }, + } + + latest = Draft2020 +) + +func findDraft(url string) *Draft { + if strings.HasPrefix(url, "http://") { + url = "https://" + strings.TrimPrefix(url, "http://") + } + if strings.HasSuffix(url, "#") || strings.HasSuffix(url, "#/") { + url = url[:strings.IndexByte(url, '#')] + } + switch url { + case "https://json-schema.org/schema": + return latest + case "https://json-schema.org/draft/2020-12/schema": + return Draft2020 + case "https://json-schema.org/draft/2019-09/schema": + return Draft2019 + case "https://json-schema.org/draft-07/schema": + return Draft7 + case "https://json-schema.org/draft-06/schema": + return Draft6 + case "https://json-schema.org/draft-04/schema": + return Draft4 + } + return nil +} + +func init() { + subschemas := map[string]position{ + // type agnostic + "definitions": prop, + "not": self, + "allOf": item, + "anyOf": item, + "oneOf": item, + // object + "properties": prop, + "additionalProperties": self, + "patternProperties": prop, + // array + "items": self | item, + "additionalItems": self, + "dependencies": prop, + } + Draft4.subschemas = clone(subschemas) + + subschemas["propertyNames"] = self + subschemas["contains"] = self + Draft6.subschemas = clone(subschemas) + + subschemas["if"] = self + subschemas["then"] = self + subschemas["else"] = self + Draft7.subschemas = clone(subschemas) + + subschemas["$defs"] = prop + subschemas["dependentSchemas"] = prop + subschemas["unevaluatedProperties"] = self + subschemas["unevaluatedItems"] = self + subschemas["contentSchema"] = self + Draft2019.subschemas = clone(subschemas) + + subschemas["prefixItems"] = item + Draft2020.subschemas = clone(subschemas) + + Draft4.loadMeta("http://json-schema.org/draft-04/schema", `{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "positiveInteger": { + "type": "integer", + "minimum": 0 + }, + "positiveIntegerDefault0": { + "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ] + }, + "simpleTypes": { + "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "minItems": 1, + "uniqueItems": true + } + }, + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uriref" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "boolean", + "default": false + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "boolean", + "default": false + }, + "maxLength": { "$ref": "#/definitions/positiveInteger" }, + "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/positiveInteger" }, + "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxProperties": { "$ref": "#/definitions/positiveInteger" }, + "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { + "anyOf": [ + { "type": "boolean" }, + { "$ref": "#" } + ], + "default": {} + }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "regexProperties": true, + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "regexProperties": { "type": "boolean" }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" }, + "format": { "type": "string" }, + "$ref": { "type": "string" } + }, + "dependencies": { + "exclusiveMaximum": [ "maximum" ], + "exclusiveMinimum": [ "minimum" ] + }, + "default": {} + }`) + Draft6.loadMeta("http://json-schema.org/draft-06/schema", `{ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": {} + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "regexProperties": true, + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "propertyNames": { "$ref": "#" }, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": {} + }`) + Draft7.loadMeta("http://json-schema.org/draft-07/schema", `{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true + }`) + Draft2019.loadMeta("https://json-schema.org/draft/2019-09/schema", `{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$recursiveRef": "#" }, + { "$ref": "meta/validation#/$defs/stringArray" } + ] + } + } + } + }`) + Draft2020.loadMeta("https://json-schema.org/draft/2020-12/schema", `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$dynamicRef": "#meta" }, + { "$ref": "meta/validation#/$defs/stringArray" } + ] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }`) +} + +var vocabSchemas = map[string]string{ + "https://json-schema.org/draft/2019-09/meta/core": `{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }`, + "https://json-schema.org/draft/2019-09/meta/applicator": `{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": { "$recursiveRef": "#" }, + "unevaluatedItems": { "$recursiveRef": "#" }, + "items": { + "anyOf": [ + { "$recursiveRef": "#" }, + { "$ref": "#/$defs/schemaArray" } + ] + }, + "contains": { "$recursiveRef": "#" }, + "additionalProperties": { "$recursiveRef": "#" }, + "unevaluatedProperties": { "$recursiveRef": "#" }, + "properties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": { "$recursiveRef": "#" }, + "if": { "$recursiveRef": "#" }, + "then": { "$recursiveRef": "#" }, + "else": { "$recursiveRef": "#" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$recursiveRef": "#" } + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$recursiveRef": "#" } + } + } + }`, + "https://json-schema.org/draft/2019-09/meta/validation": `{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + { "$ref": "#/$defs/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }`, + "https://json-schema.org/draft/2019-09/meta/meta-data": `{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }`, + "https://json-schema.org/draft/2019-09/meta/format": `{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": { "type": "string" } + } + }`, + "https://json-schema.org/draft/2019-09/meta/content": `{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }`, + "https://json-schema.org/draft/2020-12/meta/core": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { "$ref": "#/$defs/uriString" }, + "$ref": { "$ref": "#/$defs/uriReferenceString" }, + "$anchor": { "$ref": "#/$defs/anchorString" }, + "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, + "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, + "$vocabulary": { + "type": "object", + "propertyNames": { "$ref": "#/$defs/uriString" }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" } + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } + }`, + "https://json-schema.org/draft/2020-12/meta/applicator": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": { "$ref": "#/$defs/schemaArray" }, + "items": { "$dynamicRef": "#meta" }, + "contains": { "$dynamicRef": "#meta" }, + "additionalProperties": { "$dynamicRef": "#meta" }, + "properties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "propertyNames": { "$dynamicRef": "#meta" }, + "if": { "$dynamicRef": "#meta" }, + "then": { "$dynamicRef": "#meta" }, + "else": { "$dynamicRef": "#meta" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$dynamicRef": "#meta" } + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$dynamicRef": "#meta" } + } + } + }`, + "https://json-schema.org/draft/2020-12/meta/unevaluated": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }`, + "https://json-schema.org/draft/2020-12/meta/validation": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + { "$ref": "#/$defs/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }`, + "https://json-schema.org/draft/2020-12/meta/meta-data": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }`, + "https://json-schema.org/draft/2020-12/meta/format-annotation": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": { "type": "string" } + } + }`, + "https://json-schema.org/draft/2020-12/meta/format-assertion": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-assertion", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-assertion": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for assertion results", + "type": ["object", "boolean"], + "properties": { + "format": { "type": "string" } + } + }`, + "https://json-schema.org/draft/2020-12/meta/content": `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }`, +} + +func clone(m map[string]position) map[string]position { + mm := make(map[string]position) + for k, v := range m { + mm[k] = v + } + return mm +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/errors.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/errors.go new file mode 100644 index 000000000..deaded89f --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/errors.go @@ -0,0 +1,129 @@ +package jsonschema + +import ( + "fmt" + "strings" +) + +// InvalidJSONTypeError is the error type returned by ValidateInterface. +// this tells that specified go object is not valid jsonType. +type InvalidJSONTypeError string + +func (e InvalidJSONTypeError) Error() string { + return fmt.Sprintf("jsonschema: invalid jsonType: %s", string(e)) +} + +// InfiniteLoopError is returned by Compile/Validate. +// this gives url#keywordLocation that lead to infinity loop. +type InfiniteLoopError string + +func (e InfiniteLoopError) Error() string { + return "jsonschema: infinite loop " + string(e) +} + +func infiniteLoopError(stack []schemaRef, sref schemaRef) InfiniteLoopError { + var path string + for _, ref := range stack { + if path == "" { + path += ref.schema.Location + } else { + path += "/" + ref.path + } + } + return InfiniteLoopError(path + "/" + sref.path) +} + +// SchemaError is the error type returned by Compile. +type SchemaError struct { + // SchemaURL is the url to json-schema that filed to compile. + // This is helpful, if your schema refers to external schemas + SchemaURL string + + // Err is the error that occurred during compilation. + // It could be ValidationError, because compilation validates + // given schema against the json meta-schema + Err error +} + +func (se *SchemaError) Unwrap() error { + return se.Err +} + +func (se *SchemaError) Error() string { + s := fmt.Sprintf("jsonschema %s compilation failed", se.SchemaURL) + if se.Err != nil { + return fmt.Sprintf("%s: %v", s, strings.TrimPrefix(se.Err.Error(), "jsonschema: ")) + } + return s +} + +func (se *SchemaError) GoString() string { + if _, ok := se.Err.(*ValidationError); ok { + return fmt.Sprintf("jsonschema %s compilation failed\n%#v", se.SchemaURL, se.Err) + } + return se.Error() +} + +// ValidationError is the error type returned by Validate. +type ValidationError struct { + KeywordLocation string // validation path of validating keyword or schema + AbsoluteKeywordLocation string // absolute location of validating keyword or schema + InstanceLocation string // location of the json value within the instance being validated + Message string // describes error + Causes []*ValidationError // nested validation errors +} + +func (ve *ValidationError) add(causes ...error) error { + for _, cause := range causes { + ve.Causes = append(ve.Causes, cause.(*ValidationError)) + } + return ve +} + +func (ve *ValidationError) causes(err error) error { + if err := err.(*ValidationError); err.Message == "" { + ve.Causes = err.Causes + } else { + ve.add(err) + } + return ve +} + +func (ve *ValidationError) Error() string { + leaf := ve + for len(leaf.Causes) > 0 { + leaf = leaf.Causes[0] + } + u, _ := split(ve.AbsoluteKeywordLocation) + return fmt.Sprintf("jsonschema: %s does not validate with %s: %s", quote(leaf.InstanceLocation), u+"#"+leaf.KeywordLocation, leaf.Message) +} + +func (ve *ValidationError) GoString() string { + sloc := ve.AbsoluteKeywordLocation + sloc = sloc[strings.IndexByte(sloc, '#')+1:] + msg := fmt.Sprintf("[I#%s] [S#%s] %s", ve.InstanceLocation, sloc, ve.Message) + for _, c := range ve.Causes { + for _, line := range strings.Split(c.GoString(), "\n") { + msg += "\n " + line + } + } + return msg +} + +func joinPtr(ptr1, ptr2 string) string { + if len(ptr1) == 0 { + return ptr2 + } + if len(ptr2) == 0 { + return ptr1 + } + return ptr1 + "/" + ptr2 +} + +// quote returns single-quoted string +func quote(s string) string { + s = fmt.Sprintf("%q", s) + s = strings.ReplaceAll(s, `\"`, `"`) + s = strings.ReplaceAll(s, `'`, `\'`) + return "'" + s[1:len(s)-1] + "'" +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/extension.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/extension.go new file mode 100644 index 000000000..452ba118c --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/extension.go @@ -0,0 +1,116 @@ +package jsonschema + +// ExtCompiler compiles custom keyword(s) into ExtSchema. +type ExtCompiler interface { + // Compile compiles the custom keywords in schema m and returns its compiled representation. + // if the schema m does not contain the keywords defined by this extension, + // compiled representation nil should be returned. + Compile(ctx CompilerContext, m map[string]interface{}) (ExtSchema, error) +} + +// ExtSchema is schema representation of custom keyword(s) +type ExtSchema interface { + // Validate validates the json value v with this ExtSchema. + // Returned error must be *ValidationError. + Validate(ctx ValidationContext, v interface{}) error +} + +type extension struct { + meta *Schema + compiler ExtCompiler +} + +// RegisterExtension registers custom keyword(s) into this compiler. +// +// name is extension name, used only to avoid name collisions. +// meta captures the metaschema for the new keywords. +// This is used to validate the schema before calling ext.Compile. +func (c *Compiler) RegisterExtension(name string, meta *Schema, ext ExtCompiler) { + c.extensions[name] = extension{meta, ext} +} + +// CompilerContext --- + +// CompilerContext provides additional context required in compiling for extension. +type CompilerContext struct { + c *Compiler + r *resource + stack []schemaRef + res *resource +} + +// Compile compiles given value at ptr into *Schema. This is useful in implementing +// keyword like allOf/not/patternProperties. +// +// schPath is the relative-json-pointer to the schema to be compiled from parent schema. +// +// applicableOnSameInstance tells whether current schema and the given schema +// are applied on same instance value. this is used to detect infinite loop in schema. +func (ctx CompilerContext) Compile(schPath string, applicableOnSameInstance bool) (*Schema, error) { + var stack []schemaRef + if applicableOnSameInstance { + stack = ctx.stack + } + return ctx.c.compileRef(ctx.r, stack, schPath, ctx.res, ctx.r.url+ctx.res.floc+"/"+schPath) +} + +// CompileRef compiles the schema referenced by ref uri +// +// refPath is the relative-json-pointer to ref. +// +// applicableOnSameInstance tells whether current schema and the given schema +// are applied on same instance value. this is used to detect infinite loop in schema. +func (ctx CompilerContext) CompileRef(ref string, refPath string, applicableOnSameInstance bool) (*Schema, error) { + var stack []schemaRef + if applicableOnSameInstance { + stack = ctx.stack + } + return ctx.c.compileRef(ctx.r, stack, refPath, ctx.res, ref) +} + +// ValidationContext --- + +// ValidationContext provides additional context required in validating for extension. +type ValidationContext struct { + result validationResult + validate func(sch *Schema, schPath string, v interface{}, vpath string) error + validateInplace func(sch *Schema, schPath string) error + validationError func(keywordPath string, format string, a ...interface{}) *ValidationError +} + +// EvaluatedProp marks given property of object as evaluated. +func (ctx ValidationContext) EvaluatedProp(prop string) { + delete(ctx.result.unevalProps, prop) +} + +// EvaluatedItem marks given index of array as evaluated. +func (ctx ValidationContext) EvaluatedItem(index int) { + delete(ctx.result.unevalItems, index) +} + +// Validate validates schema s with value v. Extension must use this method instead of +// *Schema.ValidateInterface method. This will be useful in implementing keywords like +// allOf/oneOf +// +// spath is relative-json-pointer to s +// vpath is relative-json-pointer to v. +func (ctx ValidationContext) Validate(s *Schema, spath string, v interface{}, vpath string) error { + if vpath == "" { + return ctx.validateInplace(s, spath) + } + return ctx.validate(s, spath, v, vpath) +} + +// Error used to construct validation error by extensions. +// +// keywordPath is relative-json-pointer to keyword. +func (ctx ValidationContext) Error(keywordPath string, format string, a ...interface{}) *ValidationError { + return ctx.validationError(keywordPath, format, a...) +} + +// Group is used by extensions to group multiple errors as causes to parent error. +// This is useful in implementing keywords like allOf where each schema specified +// in allOf can result a validationError. +func (ValidationError) Group(parent *ValidationError, causes ...error) error { + return parent.add(causes...) +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/format.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/format.go new file mode 100644 index 000000000..05686073f --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/format.go @@ -0,0 +1,567 @@ +package jsonschema + +import ( + "errors" + "net" + "net/mail" + "net/url" + "regexp" + "strconv" + "strings" + "time" +) + +// Formats is a registry of functions, which know how to validate +// a specific format. +// +// New Formats can be registered by adding to this map. Key is format name, +// value is function that knows how to validate that format. +var Formats = map[string]func(interface{}) bool{ + "date-time": isDateTime, + "date": isDate, + "time": isTime, + "duration": isDuration, + "period": isPeriod, + "hostname": isHostname, + "email": isEmail, + "ip-address": isIPV4, + "ipv4": isIPV4, + "ipv6": isIPV6, + "uri": isURI, + "iri": isURI, + "uri-reference": isURIReference, + "uriref": isURIReference, + "iri-reference": isURIReference, + "uri-template": isURITemplate, + "regex": isRegex, + "json-pointer": isJSONPointer, + "relative-json-pointer": isRelativeJSONPointer, + "uuid": isUUID, +} + +// isDateTime tells whether given string is a valid date representation +// as defined by RFC 3339, section 5.6. +// +// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details +func isDateTime(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + if len(s) < 20 { // yyyy-mm-ddThh:mm:ssZ + return false + } + if s[10] != 'T' && s[10] != 't' { + return false + } + return isDate(s[:10]) && isTime(s[11:]) +} + +// isDate tells whether given string is a valid full-date production +// as defined by RFC 3339, section 5.6. +// +// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details +func isDate(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + _, err := time.Parse("2006-01-02", s) + return err == nil +} + +// isTime tells whether given string is a valid full-time production +// as defined by RFC 3339, section 5.6. +// +// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details +func isTime(v interface{}) bool { + str, ok := v.(string) + if !ok { + return true + } + + // golang time package does not support leap seconds. + // so we are parsing it manually here. + + // hh:mm:ss + // 01234567 + if len(str) < 9 || str[2] != ':' || str[5] != ':' { + return false + } + isInRange := func(str string, min, max int) (int, bool) { + n, err := strconv.Atoi(str) + if err != nil { + return 0, false + } + if n < min || n > max { + return 0, false + } + return n, true + } + var h, m, s int + if h, ok = isInRange(str[0:2], 0, 23); !ok { + return false + } + if m, ok = isInRange(str[3:5], 0, 59); !ok { + return false + } + if s, ok = isInRange(str[6:8], 0, 60); !ok { + return false + } + str = str[8:] + + // parse secfrac if present + if str[0] == '.' { + // dot following more than one digit + str = str[1:] + var numDigits int + for str != "" { + if str[0] < '0' || str[0] > '9' { + break + } + numDigits++ + str = str[1:] + } + if numDigits == 0 { + return false + } + } + + if len(str) == 0 { + return false + } + + if str[0] == 'z' || str[0] == 'Z' { + if len(str) != 1 { + return false + } + } else { + // time-numoffset + // +hh:mm + // 012345 + if len(str) != 6 || str[3] != ':' { + return false + } + + var sign int + if str[0] == '+' { + sign = -1 + } else if str[0] == '-' { + sign = +1 + } else { + return false + } + + var zh, zm int + if zh, ok = isInRange(str[1:3], 0, 23); !ok { + return false + } + if zm, ok = isInRange(str[4:6], 0, 59); !ok { + return false + } + + // apply timezone offset + hm := (h*60 + m) + sign*(zh*60+zm) + if hm < 0 { + hm += 24 * 60 + } + h, m = hm/60, hm%60 + } + + // check leapsecond + if s == 60 { // leap second + if h != 23 || m != 59 { + return false + } + } + + return true +} + +// isDuration tells whether given string is a valid duration format +// from the ISO 8601 ABNF as given in Appendix A of RFC 3339. +// +// see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A, for details +func isDuration(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + if len(s) == 0 || s[0] != 'P' { + return false + } + s = s[1:] + parseUnits := func() (units string, ok bool) { + for len(s) > 0 && s[0] != 'T' { + digits := false + for { + if len(s) == 0 { + break + } + if s[0] < '0' || s[0] > '9' { + break + } + digits = true + s = s[1:] + } + if !digits || len(s) == 0 { + return units, false + } + units += s[:1] + s = s[1:] + } + return units, true + } + units, ok := parseUnits() + if !ok { + return false + } + if units == "W" { + return len(s) == 0 // P_W + } + if len(units) > 0 { + if strings.Index("YMD", units) == -1 { + return false + } + if len(s) == 0 { + return true // "P" dur-date + } + } + if len(s) == 0 || s[0] != 'T' { + return false + } + s = s[1:] + units, ok = parseUnits() + return ok && len(s) == 0 && len(units) > 0 && strings.Index("HMS", units) != -1 +} + +// isPeriod tells whether given string is a valid period format +// from the ISO 8601 ABNF as given in Appendix A of RFC 3339. +// +// see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A, for details +func isPeriod(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + slash := strings.IndexByte(s, '/') + if slash == -1 { + return false + } + start, end := s[:slash], s[slash+1:] + if isDateTime(start) { + return isDateTime(end) || isDuration(end) + } + return isDuration(start) && isDateTime(end) +} + +// isHostname tells whether given string is a valid representation +// for an Internet host name, as defined by RFC 1034 section 3.1 and +// RFC 1123 section 2.1. +// +// See https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names, for details. +func isHostname(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + // entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters + s = strings.TrimSuffix(s, ".") + if len(s) > 253 { + return false + } + + // Hostnames are composed of series of labels concatenated with dots, as are all domain names + for _, label := range strings.Split(s, ".") { + // Each label must be from 1 to 63 characters long + if labelLen := len(label); labelLen < 1 || labelLen > 63 { + return false + } + + // labels must not start with a hyphen + // RFC 1123 section 2.1: restriction on the first character + // is relaxed to allow either a letter or a digit + if first := s[0]; first == '-' { + return false + } + + // must not end with a hyphen + if label[len(label)-1] == '-' { + return false + } + + // labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), + // the digits '0' through '9', and the hyphen ('-') + for _, c := range label { + if valid := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '-'); !valid { + return false + } + } + } + + return true +} + +// isEmail tells whether given string is a valid Internet email address +// as defined by RFC 5322, section 3.4.1. +// +// See https://en.wikipedia.org/wiki/Email_address, for details. +func isEmail(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + // entire email address to be no more than 254 characters long + if len(s) > 254 { + return false + } + + // email address is generally recognized as having two parts joined with an at-sign + at := strings.LastIndexByte(s, '@') + if at == -1 { + return false + } + local := s[0:at] + domain := s[at+1:] + + // local part may be up to 64 characters long + if len(local) > 64 { + return false + } + + // domain if enclosed in brackets, must match an IP address + if len(domain) >= 2 && domain[0] == '[' && domain[len(domain)-1] == ']' { + ip := domain[1 : len(domain)-1] + if strings.HasPrefix(ip, "IPv6:") { + return isIPV6(strings.TrimPrefix(ip, "IPv6:")) + } + return isIPV4(ip) + } + + // domain must match the requirements for a hostname + if !isHostname(domain) { + return false + } + + _, err := mail.ParseAddress(s) + return err == nil +} + +// isIPV4 tells whether given string is a valid representation of an IPv4 address +// according to the "dotted-quad" ABNF syntax as defined in RFC 2673, section 3.2. +func isIPV4(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + groups := strings.Split(s, ".") + if len(groups) != 4 { + return false + } + for _, group := range groups { + n, err := strconv.Atoi(group) + if err != nil { + return false + } + if n < 0 || n > 255 { + return false + } + if n != 0 && group[0] == '0' { + return false // leading zeroes should be rejected, as they are treated as octals + } + } + return true +} + +// isIPV6 tells whether given string is a valid representation of an IPv6 address +// as defined in RFC 2373, section 2.2. +func isIPV6(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + if !strings.Contains(s, ":") { + return false + } + return net.ParseIP(s) != nil +} + +// isURI tells whether given string is valid URI, according to RFC 3986. +func isURI(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + u, err := urlParse(s) + return err == nil && u.IsAbs() +} + +func urlParse(s string) (*url.URL, error) { + u, err := url.Parse(s) + if err != nil { + return nil, err + } + + // if hostname is ipv6, validate it + hostname := u.Hostname() + if strings.IndexByte(hostname, ':') != -1 { + if strings.IndexByte(u.Host, '[') == -1 || strings.IndexByte(u.Host, ']') == -1 { + return nil, errors.New("ipv6 address is not enclosed in brackets") + } + if !isIPV6(hostname) { + return nil, errors.New("invalid ipv6 address") + } + } + return u, nil +} + +// isURIReference tells whether given string is a valid URI Reference +// (either a URI or a relative-reference), according to RFC 3986. +func isURIReference(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + _, err := urlParse(s) + return err == nil && !strings.Contains(s, `\`) +} + +// isURITemplate tells whether given string is a valid URI Template +// according to RFC6570. +// +// Current implementation does minimal validation. +func isURITemplate(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + u, err := urlParse(s) + if err != nil { + return false + } + for _, item := range strings.Split(u.RawPath, "/") { + depth := 0 + for _, ch := range item { + switch ch { + case '{': + depth++ + if depth != 1 { + return false + } + case '}': + depth-- + if depth != 0 { + return false + } + } + } + if depth != 0 { + return false + } + } + return true +} + +// isRegex tells whether given string is a valid regular expression, +// according to the ECMA 262 regular expression dialect. +// +// The implementation uses go-lang regexp package. +func isRegex(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + _, err := regexp.Compile(s) + return err == nil +} + +// isJSONPointer tells whether given string is a valid JSON Pointer. +// +// Note: It returns false for JSON Pointer URI fragments. +func isJSONPointer(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + if s != "" && !strings.HasPrefix(s, "/") { + return false + } + for _, item := range strings.Split(s, "/") { + for i := 0; i < len(item); i++ { + if item[i] == '~' { + if i == len(item)-1 { + return false + } + switch item[i+1] { + case '0', '1': + // valid + default: + return false + } + } + } + } + return true +} + +// isRelativeJSONPointer tells whether given string is a valid Relative JSON Pointer. +// +// see https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3 +func isRelativeJSONPointer(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + if s == "" { + return false + } + if s[0] == '0' { + s = s[1:] + } else if s[0] >= '0' && s[0] <= '9' { + for s != "" && s[0] >= '0' && s[0] <= '9' { + s = s[1:] + } + } else { + return false + } + return s == "#" || isJSONPointer(s) +} + +// isUUID tells whether given string is a valid uuid format +// as specified in RFC4122. +// +// see https://datatracker.ietf.org/doc/html/rfc4122#page-4, for details +func isUUID(v interface{}) bool { + s, ok := v.(string) + if !ok { + return true + } + parseHex := func(n int) bool { + for n > 0 { + if len(s) == 0 { + return false + } + hex := (s[0] >= '0' && s[0] <= '9') || (s[0] >= 'a' && s[0] <= 'f') || (s[0] >= 'A' && s[0] <= 'F') + if !hex { + return false + } + s = s[1:] + n-- + } + return true + } + groups := []int{8, 4, 4, 4, 12} + for i, numDigits := range groups { + if !parseHex(numDigits) { + return false + } + if i == len(groups)-1 { + break + } + if len(s) == 0 || s[0] != '-' { + return false + } + s = s[1:] + } + return len(s) == 0 +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/httploader/httploader.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/httploader/httploader.go new file mode 100644 index 000000000..4198cfe37 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/httploader/httploader.go @@ -0,0 +1,38 @@ +// Package httploader implements loader.Loader for http/https url. +// +// The package is typically only imported for the side effect of +// registering its Loaders. +// +// To use httploader, link this package into your program: +// +// import _ "github.com/santhosh-tekuri/jsonschema/v5/httploader" +package httploader + +import ( + "fmt" + "io" + "net/http" + + "github.com/santhosh-tekuri/jsonschema/v5" +) + +// Client is the default HTTP Client used to Get the resource. +var Client = http.DefaultClient + +// Load loads resource from given http(s) url. +func Load(url string) (io.ReadCloser, error) { + resp, err := Client.Get(url) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + _ = resp.Body.Close() + return nil, fmt.Errorf("%s returned status code %d", url, resp.StatusCode) + } + return resp.Body, nil +} + +func init() { + jsonschema.Loaders["http"] = Load + jsonschema.Loaders["https"] = Load +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/loader.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/loader.go new file mode 100644 index 000000000..c94195c33 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/loader.go @@ -0,0 +1,60 @@ +package jsonschema + +import ( + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" +) + +func loadFileURL(s string) (io.ReadCloser, error) { + u, err := url.Parse(s) + if err != nil { + return nil, err + } + f := u.Path + if runtime.GOOS == "windows" { + f = strings.TrimPrefix(f, "/") + f = filepath.FromSlash(f) + } + return os.Open(f) +} + +// Loaders is a registry of functions, which know how to load +// absolute url of specific schema. +// +// New loaders can be registered by adding to this map. Key is schema, +// value is function that knows how to load url of that schema +var Loaders = map[string]func(url string) (io.ReadCloser, error){ + "file": loadFileURL, +} + +// LoaderNotFoundError is the error type returned by Load function. +// It tells that no Loader is registered for that URL Scheme. +type LoaderNotFoundError string + +func (e LoaderNotFoundError) Error() string { + return fmt.Sprintf("jsonschema: no Loader found for %s", string(e)) +} + +// LoadURL loads document at given absolute URL. The default implementation +// uses Loaders registry to lookup by schema and uses that loader. +// +// Users can change this variable, if they would like to take complete +// responsibility of loading given URL. Used by Compiler if its LoadURL +// field is nil. +var LoadURL = func(s string) (io.ReadCloser, error) { + u, err := url.Parse(s) + if err != nil { + return nil, err + } + loader, ok := Loaders[u.Scheme] + if !ok { + return nil, LoaderNotFoundError(s) + + } + return loader(s) +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/output.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/output.go new file mode 100644 index 000000000..d65ae2a92 --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/output.go @@ -0,0 +1,77 @@ +package jsonschema + +// Flag is output format with simple boolean property valid. +type Flag struct { + Valid bool `json:"valid"` +} + +// FlagOutput returns output in flag format +func (ve *ValidationError) FlagOutput() Flag { + return Flag{} +} + +// Basic --- + +// Basic is output format with flat list of output units. +type Basic struct { + Valid bool `json:"valid"` + Errors []BasicError `json:"errors"` +} + +// BasicError is output unit in basic format. +type BasicError struct { + KeywordLocation string `json:"keywordLocation"` + AbsoluteKeywordLocation string `json:"absoluteKeywordLocation"` + InstanceLocation string `json:"instanceLocation"` + Error string `json:"error"` +} + +// BasicOutput returns output in basic format +func (ve *ValidationError) BasicOutput() Basic { + var errors []BasicError + var flatten func(*ValidationError) + flatten = func(ve *ValidationError) { + errors = append(errors, BasicError{ + KeywordLocation: ve.KeywordLocation, + AbsoluteKeywordLocation: ve.AbsoluteKeywordLocation, + InstanceLocation: ve.InstanceLocation, + Error: ve.Message, + }) + for _, cause := range ve.Causes { + flatten(cause) + } + } + flatten(ve) + return Basic{Errors: errors} +} + +// Detailed --- + +// Detailed is output format based on structure of schema. +type Detailed struct { + Valid bool `json:"valid"` + KeywordLocation string `json:"keywordLocation"` + AbsoluteKeywordLocation string `json:"absoluteKeywordLocation"` + InstanceLocation string `json:"instanceLocation"` + Error string `json:"error,omitempty"` + Errors []Detailed `json:"errors,omitempty"` +} + +// DetailedOutput returns output in detailed format +func (ve *ValidationError) DetailedOutput() Detailed { + var errors []Detailed + for _, cause := range ve.Causes { + errors = append(errors, cause.DetailedOutput()) + } + var message = ve.Message + if len(ve.Causes) > 0 { + message = "" + } + return Detailed{ + KeywordLocation: ve.KeywordLocation, + AbsoluteKeywordLocation: ve.AbsoluteKeywordLocation, + InstanceLocation: ve.InstanceLocation, + Error: message, + Errors: errors, + } +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/resource.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/resource.go new file mode 100644 index 000000000..18349daac --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/resource.go @@ -0,0 +1,280 @@ +package jsonschema + +import ( + "encoding/json" + "fmt" + "io" + "net/url" + "path/filepath" + "runtime" + "strconv" + "strings" +) + +type resource struct { + url string // base url of resource. can be empty + floc string // fragment with json-pointer from root resource + doc interface{} + draft *Draft + subresources map[string]*resource // key is floc. only applicable for root resource + schema *Schema +} + +func (r *resource) String() string { + return r.url + r.floc +} + +func newResource(url string, r io.Reader) (*resource, error) { + if strings.IndexByte(url, '#') != -1 { + panic(fmt.Sprintf("BUG: newResource(%q)", url)) + } + doc, err := unmarshal(r) + if err != nil { + return nil, fmt.Errorf("jsonschema: invalid json %s: %v", url, err) + } + url, err = toAbs(url) + if err != nil { + return nil, err + } + return &resource{ + url: url, + floc: "#", + doc: doc, + }, nil +} + +// fillSubschemas fills subschemas in res into r.subresources +func (r *resource) fillSubschemas(c *Compiler, res *resource) error { + if err := c.validateSchema(r, res.doc, res.floc[1:]); err != nil { + return err + } + + if r.subresources == nil { + r.subresources = make(map[string]*resource) + } + if err := r.draft.listSubschemas(res, r.baseURL(res.floc), r.subresources); err != nil { + return err + } + + // ensure subresource.url uniqueness + url2floc := make(map[string]string) + for _, sr := range r.subresources { + if sr.url != "" { + if floc, ok := url2floc[sr.url]; ok { + return fmt.Errorf("jsonschema: %q and %q in %s have same canonical-uri", floc[1:], sr.floc[1:], r.url) + } + url2floc[sr.url] = sr.floc + } + } + + return nil +} + +// listResources lists all subresources in res +func (r *resource) listResources(res *resource) []*resource { + var result []*resource + prefix := res.floc + "/" + for _, sr := range r.subresources { + if strings.HasPrefix(sr.floc, prefix) { + result = append(result, sr) + } + } + return result +} + +func (r *resource) findResource(url string) *resource { + if r.url == url { + return r + } + for _, res := range r.subresources { + if res.url == url { + return res + } + } + return nil +} + +// resolve fragment f with sr as base +func (r *resource) resolveFragment(c *Compiler, sr *resource, f string) (*resource, error) { + if f == "#" || f == "#/" { + return sr, nil + } + + // resolve by anchor + if !strings.HasPrefix(f, "#/") { + // check in given resource + for _, anchor := range r.draft.anchors(sr.doc) { + if anchor == f[1:] { + return sr, nil + } + } + + // check in subresources that has same base url + prefix := sr.floc + "/" + for _, res := range r.subresources { + if strings.HasPrefix(res.floc, prefix) && r.baseURL(res.floc) == sr.url { + for _, anchor := range r.draft.anchors(res.doc) { + if anchor == f[1:] { + return res, nil + } + } + } + } + return nil, nil + } + + // resolve by ptr + floc := sr.floc + f[1:] + if res, ok := r.subresources[floc]; ok { + return res, nil + } + + // non-standrad location + doc := r.doc + for _, item := range strings.Split(floc[2:], "/") { + item = strings.Replace(item, "~1", "/", -1) + item = strings.Replace(item, "~0", "~", -1) + item, err := url.PathUnescape(item) + if err != nil { + return nil, err + } + switch d := doc.(type) { + case map[string]interface{}: + if _, ok := d[item]; !ok { + return nil, nil + } + doc = d[item] + case []interface{}: + index, err := strconv.Atoi(item) + if err != nil { + return nil, err + } + if index < 0 || index >= len(d) { + return nil, nil + } + doc = d[index] + default: + return nil, nil + } + } + + id, err := r.draft.resolveID(r.baseURL(floc), doc) + if err != nil { + return nil, err + } + res := &resource{url: id, floc: floc, doc: doc} + r.subresources[floc] = res + if err := r.fillSubschemas(c, res); err != nil { + return nil, err + } + return res, nil +} + +func (r *resource) baseURL(floc string) string { + for { + if sr, ok := r.subresources[floc]; ok { + if sr.url != "" { + return sr.url + } + } + slash := strings.LastIndexByte(floc, '/') + if slash == -1 { + break + } + floc = floc[:slash] + } + return r.url +} + +// url helpers --- + +func toAbs(s string) (string, error) { + // if windows absolute file path, convert to file url + // because: net/url parses driver name as scheme + if runtime.GOOS == "windows" && len(s) >= 3 && s[1:3] == `:\` { + s = "file:///" + filepath.ToSlash(s) + } + + u, err := url.Parse(s) + if err != nil { + return "", err + } + if u.IsAbs() { + return s, nil + } + + // s is filepath + if s, err = filepath.Abs(s); err != nil { + return "", err + } + if runtime.GOOS == "windows" { + s = "file:///" + filepath.ToSlash(s) + } else { + s = "file://" + s + } + u, err = url.Parse(s) // to fix spaces in filepath + return u.String(), err +} + +func resolveURL(base, ref string) (string, error) { + if ref == "" { + return base, nil + } + if strings.HasPrefix(ref, "urn:") { + return ref, nil + } + + refURL, err := url.Parse(ref) + if err != nil { + return "", err + } + if refURL.IsAbs() { + return ref, nil + } + + if strings.HasPrefix(base, "urn:") { + base, _ = split(base) + return base + ref, nil + } + + baseURL, err := url.Parse(base) + if err != nil { + return "", err + } + return baseURL.ResolveReference(refURL).String(), nil +} + +func split(uri string) (string, string) { + hash := strings.IndexByte(uri, '#') + if hash == -1 { + return uri, "#" + } + f := uri[hash:] + if f == "#/" { + f = "#" + } + return uri[0:hash], f +} + +func (s *Schema) url() string { + u, _ := split(s.Location) + return u +} + +func (s *Schema) loc() string { + _, f := split(s.Location) + return f[1:] +} + +func unmarshal(r io.Reader) (interface{}, error) { + decoder := json.NewDecoder(r) + decoder.UseNumber() + var doc interface{} + if err := decoder.Decode(&doc); err != nil { + return nil, err + } + if t, _ := decoder.Token(); t != nil { + return nil, fmt.Errorf("invalid character %v after top-level value", t) + } + return doc, nil +} diff --git a/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/schema.go b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/schema.go new file mode 100644 index 000000000..688f0a6fe --- /dev/null +++ b/tools/vendor/github.com/santhosh-tekuri/jsonschema/v5/schema.go @@ -0,0 +1,900 @@ +package jsonschema + +import ( + "bytes" + "encoding/json" + "fmt" + "hash/maphash" + "math/big" + "net/url" + "regexp" + "sort" + "strconv" + "strings" + "unicode/utf8" +) + +// A Schema represents compiled version of json-schema. +type Schema struct { + Location string // absolute location + + Draft *Draft // draft used by schema. + meta *Schema + vocab []string + dynamicAnchors []*Schema + + // type agnostic validations + Format string + format func(interface{}) bool + Always *bool // always pass/fail. used when booleans are used as schemas in draft-07. + Ref *Schema + RecursiveAnchor bool + RecursiveRef *Schema + DynamicAnchor string + DynamicRef *Schema + dynamicRefAnchor string + Types []string // allowed types. + Constant []interface{} // first element in slice is constant value. note: slice is used to capture nil constant. + Enum []interface{} // allowed values. + enumError string // error message for enum fail. captured here to avoid constructing error message every time. + Not *Schema + AllOf []*Schema + AnyOf []*Schema + OneOf []*Schema + If *Schema + Then *Schema // nil, when If is nil. + Else *Schema // nil, when If is nil. + + // object validations + MinProperties int // -1 if not specified. + MaxProperties int // -1 if not specified. + Required []string // list of required properties. + Properties map[string]*Schema + PropertyNames *Schema + RegexProperties bool // property names must be valid regex. used only in draft4 as workaround in metaschema. + PatternProperties map[*regexp.Regexp]*Schema + AdditionalProperties interface{} // nil or bool or *Schema. + Dependencies map[string]interface{} // map value is *Schema or []string. + DependentRequired map[string][]string + DependentSchemas map[string]*Schema + UnevaluatedProperties *Schema + + // array validations + MinItems int // -1 if not specified. + MaxItems int // -1 if not specified. + UniqueItems bool + Items interface{} // nil or *Schema or []*Schema + AdditionalItems interface{} // nil or bool or *Schema. + PrefixItems []*Schema + Items2020 *Schema // items keyword reintroduced in draft 2020-12 + Contains *Schema + ContainsEval bool // whether any item in an array that passes validation of the contains schema is considered "evaluated" + MinContains int // 1 if not specified + MaxContains int // -1 if not specified + UnevaluatedItems *Schema + + // string validations + MinLength int // -1 if not specified. + MaxLength int // -1 if not specified. + Pattern *regexp.Regexp + ContentEncoding string + decoder func(string) ([]byte, error) + ContentMediaType string + mediaType func([]byte) error + ContentSchema *Schema + + // number validators + Minimum *big.Rat + ExclusiveMinimum *big.Rat + Maximum *big.Rat + ExclusiveMaximum *big.Rat + MultipleOf *big.Rat + + // annotations. captured only when Compiler.ExtractAnnotations is true. + Title string + Description string + Default interface{} + Comment string + ReadOnly bool + WriteOnly bool + Examples []interface{} + Deprecated bool + + // user defined extensions + Extensions map[string]ExtSchema +} + +func (s *Schema) String() string { + return s.Location +} + +func newSchema(url, floc string, draft *Draft, doc interface{}) *Schema { + // fill with default values + s := &Schema{ + Location: url + floc, + Draft: draft, + MinProperties: -1, + MaxProperties: -1, + MinItems: -1, + MaxItems: -1, + MinContains: 1, + MaxContains: -1, + MinLength: -1, + MaxLength: -1, + } + + if doc, ok := doc.(map[string]interface{}); ok { + if ra, ok := doc["$recursiveAnchor"]; ok { + if ra, ok := ra.(bool); ok { + s.RecursiveAnchor = ra + } + } + if da, ok := doc["$dynamicAnchor"]; ok { + if da, ok := da.(string); ok { + s.DynamicAnchor = da + } + } + } + return s +} + +func (s *Schema) hasVocab(name string) bool { + if s == nil { // during bootstrap + return true + } + if name == "core" { + return true + } + for _, url := range s.vocab { + if url == "https://json-schema.org/draft/2019-09/vocab/"+name { + return true + } + if url == "https://json-schema.org/draft/2020-12/vocab/"+name { + return true + } + } + return false +} + +// Validate validates given doc, against the json-schema s. +// +// the v must be the raw json value. for number precision +// unmarshal with json.UseNumber(). +// +// returns *ValidationError if v does not confirm with schema s. +// returns InfiniteLoopError if it detects loop during validation. +// returns InvalidJSONTypeError if it detects any non json value in v. +func (s *Schema) Validate(v interface{}) (err error) { + return s.validateValue(v, "") +} + +func (s *Schema) validateValue(v interface{}, vloc string) (err error) { + defer func() { + if r := recover(); r != nil { + switch r := r.(type) { + case InfiniteLoopError, InvalidJSONTypeError: + err = r.(error) + default: + panic(r) + } + } + }() + if _, err := s.validate(nil, 0, "", v, vloc); err != nil { + ve := ValidationError{ + KeywordLocation: "", + AbsoluteKeywordLocation: s.Location, + InstanceLocation: vloc, + Message: fmt.Sprintf("doesn't validate with %s", s.Location), + } + return ve.causes(err) + } + return nil +} + +// validate validates given value v with this schema. +func (s *Schema) validate(scope []schemaRef, vscope int, spath string, v interface{}, vloc string) (result validationResult, err error) { + validationError := func(keywordPath string, format string, a ...interface{}) *ValidationError { + return &ValidationError{ + KeywordLocation: keywordLocation(scope, keywordPath), + AbsoluteKeywordLocation: joinPtr(s.Location, keywordPath), + InstanceLocation: vloc, + Message: fmt.Sprintf(format, a...), + } + } + + sref := schemaRef{spath, s, false} + if err := checkLoop(scope[len(scope)-vscope:], sref); err != nil { + panic(err) + } + scope = append(scope, sref) + vscope++ + + // populate result + switch v := v.(type) { + case map[string]interface{}: + result.unevalProps = make(map[string]struct{}) + for pname := range v { + result.unevalProps[pname] = struct{}{} + } + case []interface{}: + result.unevalItems = make(map[int]struct{}) + for i := range v { + result.unevalItems[i] = struct{}{} + } + } + + validate := func(sch *Schema, schPath string, v interface{}, vpath string) error { + vloc := vloc + if vpath != "" { + vloc += "/" + vpath + } + _, err := sch.validate(scope, 0, schPath, v, vloc) + return err + } + + validateInplace := func(sch *Schema, schPath string) error { + vr, err := sch.validate(scope, vscope, schPath, v, vloc) + if err == nil { + // update result + for pname := range result.unevalProps { + if _, ok := vr.unevalProps[pname]; !ok { + delete(result.unevalProps, pname) + } + } + for i := range result.unevalItems { + if _, ok := vr.unevalItems[i]; !ok { + delete(result.unevalItems, i) + } + } + } + return err + } + + if s.Always != nil { + if !*s.Always { + return result, validationError("", "not allowed") + } + return result, nil + } + + if len(s.Types) > 0 { + vType := jsonType(v) + matched := false + for _, t := range s.Types { + if vType == t { + matched = true + break + } else if t == "integer" && vType == "number" { + num, _ := new(big.Rat).SetString(fmt.Sprint(v)) + if num.IsInt() { + matched = true + break + } + } + } + if !matched { + return result, validationError("type", "expected %s, but got %s", strings.Join(s.Types, " or "), vType) + } + } + + var errors []error + + if len(s.Constant) > 0 { + if !equals(v, s.Constant[0]) { + switch jsonType(s.Constant[0]) { + case "object", "array": + errors = append(errors, validationError("const", "const failed")) + default: + errors = append(errors, validationError("const", "value must be %#v", s.Constant[0])) + } + } + } + + if len(s.Enum) > 0 { + matched := false + for _, item := range s.Enum { + if equals(v, item) { + matched = true + break + } + } + if !matched { + errors = append(errors, validationError("enum", s.enumError)) + } + } + + if s.format != nil && !s.format(v) { + var val = v + if v, ok := v.(string); ok { + val = quote(v) + } + errors = append(errors, validationError("format", "%v is not valid %s", val, quote(s.Format))) + } + + switch v := v.(type) { + case map[string]interface{}: + if s.MinProperties != -1 && len(v) < s.MinProperties { + errors = append(errors, validationError("minProperties", "minimum %d properties allowed, but found %d properties", s.MinProperties, len(v))) + } + if s.MaxProperties != -1 && len(v) > s.MaxProperties { + errors = append(errors, validationError("maxProperties", "maximum %d properties allowed, but found %d properties", s.MaxProperties, len(v))) + } + if len(s.Required) > 0 { + var missing []string + for _, pname := range s.Required { + if _, ok := v[pname]; !ok { + missing = append(missing, quote(pname)) + } + } + if len(missing) > 0 { + errors = append(errors, validationError("required", "missing properties: %s", strings.Join(missing, ", "))) + } + } + + for pname, sch := range s.Properties { + if pvalue, ok := v[pname]; ok { + delete(result.unevalProps, pname) + if err := validate(sch, "properties/"+escape(pname), pvalue, escape(pname)); err != nil { + errors = append(errors, err) + } + } + } + + if s.PropertyNames != nil { + for pname := range v { + if err := validate(s.PropertyNames, "propertyNames", pname, escape(pname)); err != nil { + errors = append(errors, err) + } + } + } + + if s.RegexProperties { + for pname := range v { + if !isRegex(pname) { + errors = append(errors, validationError("", "patternProperty %s is not valid regex", quote(pname))) + } + } + } + for pattern, sch := range s.PatternProperties { + for pname, pvalue := range v { + if pattern.MatchString(pname) { + delete(result.unevalProps, pname) + if err := validate(sch, "patternProperties/"+escape(pattern.String()), pvalue, escape(pname)); err != nil { + errors = append(errors, err) + } + } + } + } + if s.AdditionalProperties != nil { + if allowed, ok := s.AdditionalProperties.(bool); ok { + if !allowed && len(result.unevalProps) > 0 { + errors = append(errors, validationError("additionalProperties", "additionalProperties %s not allowed", result.unevalPnames())) + } + } else { + schema := s.AdditionalProperties.(*Schema) + for pname := range result.unevalProps { + if pvalue, ok := v[pname]; ok { + if err := validate(schema, "additionalProperties", pvalue, escape(pname)); err != nil { + errors = append(errors, err) + } + } + } + } + result.unevalProps = nil + } + for dname, dvalue := range s.Dependencies { + if _, ok := v[dname]; ok { + switch dvalue := dvalue.(type) { + case *Schema: + if err := validateInplace(dvalue, "dependencies/"+escape(dname)); err != nil { + errors = append(errors, err) + } + case []string: + for i, pname := range dvalue { + if _, ok := v[pname]; !ok { + errors = append(errors, validationError("dependencies/"+escape(dname)+"/"+strconv.Itoa(i), "property %s is required, if %s property exists", quote(pname), quote(dname))) + } + } + } + } + } + for dname, dvalue := range s.DependentRequired { + if _, ok := v[dname]; ok { + for i, pname := range dvalue { + if _, ok := v[pname]; !ok { + errors = append(errors, validationError("dependentRequired/"+escape(dname)+"/"+strconv.Itoa(i), "property %s is required, if %s property exists", quote(pname), quote(dname))) + } + } + } + } + for dname, sch := range s.DependentSchemas { + if _, ok := v[dname]; ok { + if err := validateInplace(sch, "dependentSchemas/"+escape(dname)); err != nil { + errors = append(errors, err) + } + } + } + + case []interface{}: + if s.MinItems != -1 && len(v) < s.MinItems { + errors = append(errors, validationError("minItems", "minimum %d items required, but found %d items", s.MinItems, len(v))) + } + if s.MaxItems != -1 && len(v) > s.MaxItems { + errors = append(errors, validationError("maxItems", "maximum %d items required, but found %d items", s.MaxItems, len(v))) + } + if s.UniqueItems { + if len(v) <= 20 { + outer1: + for i := 1; i < len(v); i++ { + for j := 0; j < i; j++ { + if equals(v[i], v[j]) { + errors = append(errors, validationError("uniqueItems", "items at index %d and %d are equal", j, i)) + break outer1 + } + } + } + } else { + m := make(map[uint64][]int) + var h maphash.Hash + outer2: + for i, item := range v { + h.Reset() + hash(item, &h) + k := h.Sum64() + if err != nil { + panic(err) + } + arr, ok := m[k] + if ok { + for _, j := range arr { + if equals(v[j], item) { + errors = append(errors, validationError("uniqueItems", "items at index %d and %d are equal", j, i)) + break outer2 + } + } + } + arr = append(arr, i) + m[k] = arr + } + } + } + + // items + additionalItems + switch items := s.Items.(type) { + case *Schema: + for i, item := range v { + if err := validate(items, "items", item, strconv.Itoa(i)); err != nil { + errors = append(errors, err) + } + } + result.unevalItems = nil + case []*Schema: + for i, item := range v { + if i < len(items) { + delete(result.unevalItems, i) + if err := validate(items[i], "items/"+strconv.Itoa(i), item, strconv.Itoa(i)); err != nil { + errors = append(errors, err) + } + } else if sch, ok := s.AdditionalItems.(*Schema); ok { + delete(result.unevalItems, i) + if err := validate(sch, "additionalItems", item, strconv.Itoa(i)); err != nil { + errors = append(errors, err) + } + } else { + break + } + } + if additionalItems, ok := s.AdditionalItems.(bool); ok { + if additionalItems { + result.unevalItems = nil + } else if len(v) > len(items) { + errors = append(errors, validationError("additionalItems", "only %d items are allowed, but found %d items", len(items), len(v))) + } + } + } + + // prefixItems + items + for i, item := range v { + if i < len(s.PrefixItems) { + delete(result.unevalItems, i) + if err := validate(s.PrefixItems[i], "prefixItems/"+strconv.Itoa(i), item, strconv.Itoa(i)); err != nil { + errors = append(errors, err) + } + } else if s.Items2020 != nil { + delete(result.unevalItems, i) + if err := validate(s.Items2020, "items", item, strconv.Itoa(i)); err != nil { + errors = append(errors, err) + } + } else { + break + } + } + + // contains + minContains + maxContains + if s.Contains != nil && (s.MinContains != -1 || s.MaxContains != -1) { + matched := 0 + var causes []error + for i, item := range v { + if err := validate(s.Contains, "contains", item, strconv.Itoa(i)); err != nil { + causes = append(causes, err) + } else { + matched++ + if s.ContainsEval { + delete(result.unevalItems, i) + } + } + } + if s.MinContains != -1 && matched < s.MinContains { + errors = append(errors, validationError("minContains", "valid must be >= %d, but got %d", s.MinContains, matched).add(causes...)) + } + if s.MaxContains != -1 && matched > s.MaxContains { + errors = append(errors, validationError("maxContains", "valid must be <= %d, but got %d", s.MaxContains, matched)) + } + } + + case string: + // minLength + maxLength + if s.MinLength != -1 || s.MaxLength != -1 { + length := utf8.RuneCount([]byte(v)) + if s.MinLength != -1 && length < s.MinLength { + errors = append(errors, validationError("minLength", "length must be >= %d, but got %d", s.MinLength, length)) + } + if s.MaxLength != -1 && length > s.MaxLength { + errors = append(errors, validationError("maxLength", "length must be <= %d, but got %d", s.MaxLength, length)) + } + } + + if s.Pattern != nil && !s.Pattern.MatchString(v) { + errors = append(errors, validationError("pattern", "does not match pattern %s", quote(s.Pattern.String()))) + } + + // contentEncoding + contentMediaType + if s.decoder != nil || s.mediaType != nil { + decoded := s.ContentEncoding == "" + var content []byte + if s.decoder != nil { + b, err := s.decoder(v) + if err != nil { + errors = append(errors, validationError("contentEncoding", "value is not %s encoded", s.ContentEncoding)) + } else { + content, decoded = b, true + } + } + if decoded && s.mediaType != nil { + if s.decoder == nil { + content = []byte(v) + } + if err := s.mediaType(content); err != nil { + errors = append(errors, validationError("contentMediaType", "value is not of mediatype %s", quote(s.ContentMediaType))) + } + } + if decoded && s.ContentSchema != nil { + contentJSON, err := unmarshal(bytes.NewReader(content)) + if err != nil { + errors = append(errors, validationError("contentSchema", "value is not valid json")) + } else { + err := validate(s.ContentSchema, "contentSchema", contentJSON, "") + if err != nil { + errors = append(errors, err) + } + } + } + } + + case json.Number, float32, float64, int, int8, int32, int64, uint, uint8, uint32, uint64: + // lazy convert to *big.Rat to avoid allocation + var numVal *big.Rat + num := func() *big.Rat { + if numVal == nil { + numVal, _ = new(big.Rat).SetString(fmt.Sprint(v)) + } + return numVal + } + f64 := func(r *big.Rat) float64 { + f, _ := r.Float64() + return f + } + if s.Minimum != nil && num().Cmp(s.Minimum) < 0 { + errors = append(errors, validationError("minimum", "must be >= %v but found %v", f64(s.Minimum), v)) + } + if s.ExclusiveMinimum != nil && num().Cmp(s.ExclusiveMinimum) <= 0 { + errors = append(errors, validationError("exclusiveMinimum", "must be > %v but found %v", f64(s.ExclusiveMinimum), v)) + } + if s.Maximum != nil && num().Cmp(s.Maximum) > 0 { + errors = append(errors, validationError("maximum", "must be <= %v but found %v", f64(s.Maximum), v)) + } + if s.ExclusiveMaximum != nil && num().Cmp(s.ExclusiveMaximum) >= 0 { + errors = append(errors, validationError("exclusiveMaximum", "must be < %v but found %v", f64(s.ExclusiveMaximum), v)) + } + if s.MultipleOf != nil { + if q := new(big.Rat).Quo(num(), s.MultipleOf); !q.IsInt() { + errors = append(errors, validationError("multipleOf", "%v not multipleOf %v", v, f64(s.MultipleOf))) + } + } + } + + // $ref + $recursiveRef + $dynamicRef + validateRef := func(sch *Schema, refPath string) error { + if sch != nil { + if err := validateInplace(sch, refPath); err != nil { + var url = sch.Location + if s.url() == sch.url() { + url = sch.loc() + } + return validationError(refPath, "doesn't validate with %s", quote(url)).causes(err) + } + } + return nil + } + if err := validateRef(s.Ref, "$ref"); err != nil { + errors = append(errors, err) + } + if s.RecursiveRef != nil { + sch := s.RecursiveRef + if sch.RecursiveAnchor { + // recursiveRef based on scope + for _, e := range scope { + if e.schema.RecursiveAnchor { + sch = e.schema + break + } + } + } + if err := validateRef(sch, "$recursiveRef"); err != nil { + errors = append(errors, err) + } + } + if s.DynamicRef != nil { + sch := s.DynamicRef + if s.dynamicRefAnchor != "" && sch.DynamicAnchor == s.dynamicRefAnchor { + // dynamicRef based on scope + for i := len(scope) - 1; i >= 0; i-- { + sr := scope[i] + if sr.discard { + break + } + for _, da := range sr.schema.dynamicAnchors { + if da.DynamicAnchor == s.DynamicRef.DynamicAnchor && da != s.DynamicRef { + sch = da + break + } + } + } + } + if err := validateRef(sch, "$dynamicRef"); err != nil { + errors = append(errors, err) + } + } + + if s.Not != nil && validateInplace(s.Not, "not") == nil { + errors = append(errors, validationError("not", "not failed")) + } + + for i, sch := range s.AllOf { + schPath := "allOf/" + strconv.Itoa(i) + if err := validateInplace(sch, schPath); err != nil { + errors = append(errors, validationError(schPath, "allOf failed").add(err)) + } + } + + if len(s.AnyOf) > 0 { + matched := false + var causes []error + for i, sch := range s.AnyOf { + if err := validateInplace(sch, "anyOf/"+strconv.Itoa(i)); err == nil { + matched = true + } else { + causes = append(causes, err) + } + } + if !matched { + errors = append(errors, validationError("anyOf", "anyOf failed").add(causes...)) + } + } + + if len(s.OneOf) > 0 { + matched := -1 + var causes []error + for i, sch := range s.OneOf { + if err := validateInplace(sch, "oneOf/"+strconv.Itoa(i)); err == nil { + if matched == -1 { + matched = i + } else { + errors = append(errors, validationError("oneOf", "valid against schemas at indexes %d and %d", matched, i)) + break + } + } else { + causes = append(causes, err) + } + } + if matched == -1 { + errors = append(errors, validationError("oneOf", "oneOf failed").add(causes...)) + } + } + + // if + then + else + if s.If != nil { + err := validateInplace(s.If, "if") + // "if" leaves dynamic scope + scope[len(scope)-1].discard = true + if err == nil { + if s.Then != nil { + if err := validateInplace(s.Then, "then"); err != nil { + errors = append(errors, validationError("then", "if-then failed").add(err)) + } + } + } else { + if s.Else != nil { + if err := validateInplace(s.Else, "else"); err != nil { + errors = append(errors, validationError("else", "if-else failed").add(err)) + } + } + } + // restore dynamic scope + scope[len(scope)-1].discard = false + } + + for _, ext := range s.Extensions { + if err := ext.Validate(ValidationContext{result, validate, validateInplace, validationError}, v); err != nil { + errors = append(errors, err) + } + } + + // unevaluatedProperties + unevaluatedItems + switch v := v.(type) { + case map[string]interface{}: + if s.UnevaluatedProperties != nil { + for pname := range result.unevalProps { + if pvalue, ok := v[pname]; ok { + if err := validate(s.UnevaluatedProperties, "unevaluatedProperties", pvalue, escape(pname)); err != nil { + errors = append(errors, err) + } + } + } + result.unevalProps = nil + } + case []interface{}: + if s.UnevaluatedItems != nil { + for i := range result.unevalItems { + if err := validate(s.UnevaluatedItems, "unevaluatedItems", v[i], strconv.Itoa(i)); err != nil { + errors = append(errors, err) + } + } + result.unevalItems = nil + } + } + + switch len(errors) { + case 0: + return result, nil + case 1: + return result, errors[0] + default: + return result, validationError("", "").add(errors...) // empty message, used just for wrapping + } +} + +type validationResult struct { + unevalProps map[string]struct{} + unevalItems map[int]struct{} +} + +func (vr validationResult) unevalPnames() string { + pnames := make([]string, 0, len(vr.unevalProps)) + for pname := range vr.unevalProps { + pnames = append(pnames, quote(pname)) + } + return strings.Join(pnames, ", ") +} + +// jsonType returns the json type of given value v. +// +// It panics if the given value is not valid json value +func jsonType(v interface{}) string { + switch v.(type) { + case nil: + return "null" + case bool: + return "boolean" + case json.Number, float32, float64, int, int8, int32, int64, uint, uint8, uint32, uint64: + return "number" + case string: + return "string" + case []interface{}: + return "array" + case map[string]interface{}: + return "object" + } + panic(InvalidJSONTypeError(fmt.Sprintf("%T", v))) +} + +// equals tells if given two json values are equal or not. +func equals(v1, v2 interface{}) bool { + v1Type := jsonType(v1) + if v1Type != jsonType(v2) { + return false + } + switch v1Type { + case "array": + arr1, arr2 := v1.([]interface{}), v2.([]interface{}) + if len(arr1) != len(arr2) { + return false + } + for i := range arr1 { + if !equals(arr1[i], arr2[i]) { + return false + } + } + return true + case "object": + obj1, obj2 := v1.(map[string]interface{}), v2.(map[string]interface{}) + if len(obj1) != len(obj2) { + return false + } + for k, v1 := range obj1 { + if v2, ok := obj2[k]; ok { + if !equals(v1, v2) { + return false + } + } else { + return false + } + } + return true + case "number": + num1, _ := new(big.Rat).SetString(fmt.Sprint(v1)) + num2, _ := new(big.Rat).SetString(fmt.Sprint(v2)) + return num1.Cmp(num2) == 0 + default: + return v1 == v2 + } +} + +func hash(v interface{}, h *maphash.Hash) { + switch v := v.(type) { + case nil: + h.WriteByte(0) + case bool: + h.WriteByte(1) + if v { + h.WriteByte(1) + } else { + h.WriteByte(0) + } + case json.Number, float32, float64, int, int8, int32, int64, uint, uint8, uint32, uint64: + h.WriteByte(2) + num, _ := new(big.Rat).SetString(fmt.Sprint(v)) + h.Write(num.Num().Bytes()) + h.Write(num.Denom().Bytes()) + case string: + h.WriteByte(3) + h.WriteString(v) + case []interface{}: + h.WriteByte(4) + for _, item := range v { + hash(item, h) + } + case map[string]interface{}: + h.WriteByte(5) + props := make([]string, 0, len(v)) + for prop := range v { + props = append(props, prop) + } + sort.Slice(props, func(i, j int) bool { + return props[i] < props[j] + }) + for _, prop := range props { + hash(prop, h) + hash(v[prop], h) + } + default: + panic(InvalidJSONTypeError(fmt.Sprintf("%T", v))) + } +} + +// escape converts given token to valid json-pointer token +func escape(token string) string { + token = strings.ReplaceAll(token, "~", "~0") + token = strings.ReplaceAll(token, "/", "~1") + return url.PathEscape(token) +} diff --git a/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/analyzer.go b/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/analyzer.go index 4d6ab3cca..09f7c8240 100644 --- a/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/analyzer.go +++ b/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/analyzer.go @@ -63,9 +63,8 @@ func run(pass *analysis.Pass) (interface{}, error) { (*ast.CallExpr)(nil), (*ast.BasicLit)(nil), (*ast.CompositeLit)(nil), - (*ast.IfStmt)(nil), + (*ast.BinaryExpr)(nil), (*ast.SwitchStmt)(nil), - (*ast.ForStmt)(nil), } insp.Preorder(types, func(node ast.Node) { @@ -116,54 +115,30 @@ func run(pass *analysis.Pass) (interface{}, error) { typeElts(pass, x, typ, n.Elts) - case *ast.IfStmt: - cond, ok := n.Cond.(*ast.BinaryExpr) - if !ok { + case *ast.BinaryExpr: + switch n.Op { + case token.LSS, token.GTR, token.LEQ, token.GEQ, token.QUO, token.ADD, token.SUB, token.MUL: return + default: } - switch cond.Op { - case token.LSS, token.GTR, token.LEQ, token.GEQ: - return - } - - x, ok := cond.X.(*ast.SelectorExpr) + x, ok := n.X.(*ast.SelectorExpr) if !ok { return } - y, ok := cond.Y.(*ast.BasicLit) + y, ok := n.Y.(*ast.BasicLit) if !ok { return } - ifElseStmt(pass, x, y) + binaryExpr(pass, x, y) case *ast.SwitchStmt: x, ok := n.Tag.(*ast.SelectorExpr) if ok { switchStmt(pass, x, n.Body.List) - } else { - switchStmtAsIfElseStmt(pass, n.Body.List) - } - - case *ast.ForStmt: - cond, ok := n.Cond.(*ast.BinaryExpr) - if !ok { - return - } - - x, ok := cond.X.(*ast.SelectorExpr) - if !ok { - return - } - - y, ok := cond.Y.(*ast.BasicLit) - if !ok { - return } - - ifElseStmt(pass, x, y) } }) @@ -318,8 +293,11 @@ func typeElts(pass *analysis.Pass, x *ast.Ident, typ *ast.SelectorExpr, elts []a } } -// ifElseStmt checks X and Y in if-else-statement. -func ifElseStmt(pass *analysis.Pass, x *ast.SelectorExpr, y *ast.BasicLit) { +// binaryExpr checks X and Y in binary expressions, including: +// - if-else-statement +// - for loops conditions +// - switch cases without a tag expression +func binaryExpr(pass *analysis.Pass, x *ast.SelectorExpr, y *ast.BasicLit) { switch x.Sel.Name { case "StatusCode": if !lookupFlag(pass, HTTPStatusCodeFlag) { @@ -376,34 +354,6 @@ func switchStmt(pass *analysis.Pass, x *ast.SelectorExpr, cases []ast.Stmt) { } } -func switchStmtAsIfElseStmt(pass *analysis.Pass, cases []ast.Stmt) { - for _, c := range cases { - caseClause, ok := c.(*ast.CaseClause) - if !ok { - continue - } - - for _, expr := range caseClause.List { - binaryExpr, ok := expr.(*ast.BinaryExpr) - if !ok { - continue - } - - x, ok := binaryExpr.X.(*ast.SelectorExpr) - if !ok { - continue - } - - y, ok := binaryExpr.Y.(*ast.BasicLit) - if !ok { - continue - } - - ifElseStmt(pass, x, y) - } - } -} - func lookupFlag(pass *analysis.Pass, name string) bool { return pass.Analyzer.Flags.Lookup(name).Value.(flag.Getter).Get().(bool) } diff --git a/tools/vendor/github.com/securego/gosec/v2/.goreleaser.yml b/tools/vendor/github.com/securego/gosec/v2/.goreleaser.yml index e3c903e7a..bd85bab3a 100644 --- a/tools/vendor/github.com/securego/gosec/v2/.goreleaser.yml +++ b/tools/vendor/github.com/securego/gosec/v2/.goreleaser.yml @@ -19,6 +19,7 @@ builds: - amd64 - arm64 - s390x + - ppc64le ldflags: -X main.Version={{.Version}} -X main.GitTag={{.Tag}} -X main.BuildDate={{.Date}} env: - CGO_ENABLED=0 diff --git a/tools/vendor/github.com/securego/gosec/v2/Makefile b/tools/vendor/github.com/securego/gosec/v2/Makefile index dcfb4b2ed..4f6cce765 100644 --- a/tools/vendor/github.com/securego/gosec/v2/Makefile +++ b/tools/vendor/github.com/securego/gosec/v2/Makefile @@ -17,7 +17,7 @@ GOSEC ?= $(GOBIN)/gosec GINKGO ?= $(GOBIN)/ginkgo GO_MINOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2) GOVULN_MIN_VERSION = 17 -GO_VERSION = 1.20 +GO_VERSION = 1.22 default: $(MAKE) build @@ -76,7 +76,7 @@ release: goreleaser release build-linux: - CGO_ENABLED=$(CGO_ENABLED) GOOS=linux GOARCH=amd64 go build -ldflags=$(BUILDFLAGS) -o $(BIN) ./cmd/gosec/ + CGO_ENABLED=$(CGO_ENABLED) GOOS=linux go build -ldflags=$(BUILDFLAGS) -o $(BIN) ./cmd/gosec/ image: @echo "Building the Docker image..." diff --git a/tools/vendor/github.com/securego/gosec/v2/README.md b/tools/vendor/github.com/securego/gosec/v2/README.md index d9a33f12a..946536a94 100644 --- a/tools/vendor/github.com/securego/gosec/v2/README.md +++ b/tools/vendor/github.com/securego/gosec/v2/README.md @@ -1,5 +1,5 @@ -# gosec - Golang Security Checker +# gosec - Go Security Checker Inspects source code for security problems by scanning the Go AST and SSA code representation. @@ -105,7 +105,7 @@ jobs: # we let the report trigger content trigger a failure using the GitHub Security features. args: '-no-fail -fmt sarif -out results.sarif ./...' - name: Upload SARIF file - uses: github/codeql-action/upload-sarif@v1 + uses: github/codeql-action/upload-sarif@v2 with: # Path to SARIF file relative to the root of the repository sarif_file: results.sarif @@ -113,18 +113,10 @@ jobs: ### Local Installation -#### Go 1.16+ - ```bash go install github.com/securego/gosec/v2/cmd/gosec@latest ``` -#### Go version < 1.16 - -```bash -go get -u github.com/securego/gosec/v2/cmd/gosec -``` - ## Usage Gosec can be configured to only run a subset of rules, to exclude certain file @@ -167,7 +159,7 @@ directory you can supply `./...` as the input argument. - G503: Import blocklist: crypto/rc4 - G504: Import blocklist: net/http/cgi - G505: Import blocklist: crypto/sha1 -- G601: Implicit memory aliasing of items from a range statement +- G601: Implicit memory aliasing of items from a range statement (only for Go 1.21 or lower) - G602: Slice access out of bounds ### Retired rules @@ -238,6 +230,12 @@ You can also configure the hard-coded credentials rule `G101` with additional pa } ``` +#### Go version + +Some rules require a specific Go version which is retrieved from the Go module file present in the project. If this version cannot be found, it will fallback to Go runtime version. + +The Go module version is parsed using the `go list` command which in some cases might lead to performance degradation. In this situation, the go module version can be easily provided by setting the environment variable `GOSECGOVERSION=go1.21.1`. + ### Dependencies gosec will fetch automatically the dependencies of the code which is being analyzed when go module is turned on (e.g.`GO111MODULE=on`). If this is not the case, @@ -393,7 +391,7 @@ schema-generate -i sarif-schema-2.1.0.json -o mypath/types.go ``` Most of the MarshallJSON/UnmarshalJSON are removed except the one for PropertyBag which is handy to inline the additional properties. The rest can be removed. -The URI,ID, UUID, GUID were renamed so it fits the Golang convention defined [here](https://github.com/golang/lint/blob/master/lint.go#L700) +The URI,ID, UUID, GUID were renamed so it fits the Go convention defined [here](https://github.com/golang/lint/blob/master/lint.go#L700) ### Tests diff --git a/tools/vendor/github.com/securego/gosec/v2/action.yml b/tools/vendor/github.com/securego/gosec/v2/action.yml index aba47b60c..b1a776705 100644 --- a/tools/vendor/github.com/securego/gosec/v2/action.yml +++ b/tools/vendor/github.com/securego/gosec/v2/action.yml @@ -10,7 +10,7 @@ inputs: runs: using: 'docker' - image: 'docker://securego/gosec:2.18.1' + image: 'docker://securego/gosec:2.20.0' args: - ${{ inputs.args }} diff --git a/tools/vendor/github.com/securego/gosec/v2/analyzer.go b/tools/vendor/github.com/securego/gosec/v2/analyzer.go index 1fd1f5649..f7dd895ed 100644 --- a/tools/vendor/github.com/securego/gosec/v2/analyzer.go +++ b/tools/vendor/github.com/securego/gosec/v2/analyzer.go @@ -31,11 +31,12 @@ import ( "strings" "sync" - "github.com/securego/gosec/v2/analyzers" - "github.com/securego/gosec/v2/issue" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/buildssa" "golang.org/x/tools/go/packages" + + "github.com/securego/gosec/v2/analyzers" + "github.com/securego/gosec/v2/issue" ) // LoadMode controls the amount of details to return when loading the packages @@ -55,8 +56,6 @@ const externalSuppressionJustification = "Globally suppressed." const aliasOfAllRules = "*" -var generatedCodePattern = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`) - type ignore struct { start int end int @@ -123,7 +122,7 @@ func (i ignores) get(file string, line string) map[string][]issue.SuppressionInf start, end := i.parseLine(line) if is, ok := i[file]; ok { for _, i := range is { - if i.start <= start && i.end >= end { + if start <= i.start && end >= i.end { return i.suppressions } } @@ -376,7 +375,7 @@ func (gosec *Analyzer) CheckRules(pkg *packages.Package) { if filepath.Ext(checkedFile) != ".go" { continue } - if gosec.excludeGenerated && isGeneratedFile(file) { + if gosec.excludeGenerated && ast.IsGenerated(file) { gosec.logger.Println("Ignoring generated file:", checkedFile) continue } @@ -414,6 +413,9 @@ func (gosec *Analyzer) CheckAnalyzers(pkg *packages.Package) { SSA: ssaResult.(*buildssa.SSA), }, } + + generatedFiles := gosec.generatedFiles(pkg) + for _, analyzer := range gosec.analyzerList { pass := &analysis.Pass{ Analyzer: analyzer, @@ -441,6 +443,11 @@ func (gosec *Analyzer) CheckAnalyzers(pkg *packages.Package) { if result != nil { if passIssues, ok := result.([]*issue.Issue); ok { for _, iss := range passIssues { + if gosec.excludeGenerated { + if _, ok := generatedFiles[iss.File]; ok { + continue + } + } gosec.updateIssues(iss) } } @@ -448,6 +455,21 @@ func (gosec *Analyzer) CheckAnalyzers(pkg *packages.Package) { } } +func (gosec *Analyzer) generatedFiles(pkg *packages.Package) map[string]bool { + generatedFiles := map[string]bool{} + for _, file := range pkg.Syntax { + if ast.IsGenerated(file) { + fp := pkg.Fset.File(file.Pos()) + if fp == nil { + // skip files which cannot be located + continue + } + generatedFiles[fp.Name()] = true + } + } + return generatedFiles +} + // buildSSA runs the SSA pass which builds the SSA representation of the package. It handles gracefully any panic. func (gosec *Analyzer) buildSSA(pkg *packages.Package) (interface{}, error) { defer func() { @@ -477,17 +499,6 @@ func (gosec *Analyzer) buildSSA(pkg *packages.Package) (interface{}, error) { return ssaPass.Analyzer.Run(ssaPass) } -func isGeneratedFile(file *ast.File) bool { - for _, comment := range file.Comments { - for _, row := range comment.List { - if generatedCodePattern.MatchString(row.Text) { - return true - } - } - } - return false -} - // ParseErrors parses the errors from given package func (gosec *Analyzer) ParseErrors(pkg *packages.Package) error { if len(pkg.Errors) == 0 { @@ -557,8 +568,8 @@ func (gosec *Analyzer) ignore(n ast.Node) map[string]issue.SuppressionInfo { for _, group := range groups { comment := strings.TrimSpace(group.Text()) - foundDefaultTag := strings.HasPrefix(comment, noSecDefaultTag) || regexp.MustCompile("\n *"+noSecDefaultTag).Match([]byte(comment)) - foundAlternativeTag := strings.HasPrefix(comment, noSecAlternativeTag) || regexp.MustCompile("\n *"+noSecAlternativeTag).Match([]byte(comment)) + foundDefaultTag := strings.HasPrefix(comment, noSecDefaultTag) || regexp.MustCompile("\n *"+noSecDefaultTag).MatchString(comment) + foundAlternativeTag := strings.HasPrefix(comment, noSecAlternativeTag) || regexp.MustCompile("\n *"+noSecAlternativeTag).MatchString(comment) if foundDefaultTag || foundAlternativeTag { gosec.stats.NumNosec++ diff --git a/tools/vendor/github.com/securego/gosec/v2/helpers.go b/tools/vendor/github.com/securego/gosec/v2/helpers.go index 15b2b5f3a..1089f52c0 100644 --- a/tools/vendor/github.com/securego/gosec/v2/helpers.go +++ b/tools/vendor/github.com/securego/gosec/v2/helpers.go @@ -15,12 +15,15 @@ package gosec import ( + "bytes" + "encoding/json" "errors" "fmt" "go/ast" "go/token" "go/types" "os" + "os/exec" "os/user" "path/filepath" "regexp" @@ -29,6 +32,9 @@ import ( "strings" ) +// envGoModVersion overrides the Go version detection. +const envGoModVersion = "GOSECGOVERSION" + // MatchCallByPackage ensures that the specified package is imported, // adjusts the name for any aliases and ignores cases that are // initialization only imports. @@ -260,7 +266,7 @@ func getIdentStringValues(ident *ast.Ident, stringFinder func(ast.Node) (string, return values } -// getIdentStringRecursive returns the string of values of an Ident if they can be resolved +// GetIdentStringValuesRecursive returns the string of values of an Ident if they can be resolved // The difference between this and GetIdentStringValues is that it will attempt to resolve the strings recursively, // if it is passed a *ast.BinaryExpr. See GetStringRecursive for details func GetIdentStringValuesRecursive(ident *ast.Ident) []string { @@ -493,19 +499,49 @@ func RootPath(root string) (string, error) { return filepath.Abs(root) } -// GoVersion returns parsed version of Go from runtime +// GoVersion returns parsed version of Go mod version and fallback to runtime version if not found. func GoVersion() (int, int, int) { - return parseGoVersion(runtime.Version()) + if env, ok := os.LookupEnv(envGoModVersion); ok { + return parseGoVersion(strings.TrimPrefix(env, "go")) + } + + goVersion, err := goModVersion() + if err != nil { + return parseGoVersion(strings.TrimPrefix(runtime.Version(), "go")) + } + + return parseGoVersion(goVersion) +} + +type goListOutput struct { + GoVersion string `json:"GoVersion"` +} + +func goModVersion() (string, error) { + cmd := exec.Command("go", "list", "-m", "-json") + + raw, err := cmd.CombinedOutput() + if err != nil { + return "", fmt.Errorf("command go list: %w: %s", err, string(raw)) + } + + var v goListOutput + err = json.NewDecoder(bytes.NewBuffer(raw)).Decode(&v) + if err != nil { + return "", fmt.Errorf("unmarshaling error: %w: %s", err, string(raw)) + } + + return v.GoVersion, nil } // parseGoVersion parses Go version. // example: -// - go1.19rc2 -// - go1.19beta2 -// - go1.19.4 -// - go1.19 +// - 1.19rc2 +// - 1.19beta2 +// - 1.19.4 +// - 1.19 func parseGoVersion(version string) (int, int, int) { - exp := regexp.MustCompile(`go(\d+).(\d+)(?:.(\d+))?.*`) + exp := regexp.MustCompile(`(\d+).(\d+)(?:.(\d+))?.*`) parts := exp.FindStringSubmatch(version) if len(parts) <= 1 { return 0, 0, 0 diff --git a/tools/vendor/github.com/securego/gosec/v2/import_tracker.go b/tools/vendor/github.com/securego/gosec/v2/import_tracker.go index 7984e99f4..0d9ebfe16 100644 --- a/tools/vendor/github.com/securego/gosec/v2/import_tracker.go +++ b/tools/vendor/github.com/securego/gosec/v2/import_tracker.go @@ -15,9 +15,12 @@ package gosec import ( "go/ast" "go/types" + "regexp" "strings" ) +var versioningPackagePattern = regexp.MustCompile(`v[0-9]+$`) + // ImportTracker is used to normalize the packages that have been imported // by a source file. It is able to differentiate between plain imports, aliased // imports and init only imports. @@ -66,5 +69,10 @@ func importName(importPath string) string { if len(parts) > 0 { name = parts[len(parts)-1] } + // If the last segment of the path is version information, consider the second to last segment as the package name. + // (e.g., `math/rand/v2` would be `rand`) + if len(parts) > 1 && versioningPackagePattern.MatchString(name) { + name = parts[len(parts)-2] + } return name } diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go b/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go index 5311f74c6..eb1fa2eee 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go @@ -61,7 +61,7 @@ func (r *filePermissions) Match(n ast.Node, c *gosec.Context) (*issue.Issue, err for _, pkg := range r.pkgs { if callexpr, matched := gosec.MatchCallByPackage(n, c, pkg, r.calls...); matched { modeArg := callexpr.Args[len(callexpr.Args)-1] - if mode, err := gosec.GetInt(modeArg); err == nil && !modeIsSubset(mode, r.mode) { + if mode, err := gosec.GetInt(modeArg); err == nil && !modeIsSubset(mode, r.mode) || isOsPerm(modeArg) { return c.NewIssue(n, r.ID(), r.What, r.Severity, r.Confidence), nil } } @@ -69,6 +69,18 @@ func (r *filePermissions) Match(n ast.Node, c *gosec.Context) (*issue.Issue, err return nil, nil } +// isOsPerm check if the provide ast node contains a os.PermMode symbol +func isOsPerm(n ast.Node) bool { + if node, ok := n.(*ast.SelectorExpr); ok { + if identX, ok := node.X.(*ast.Ident); ok { + if identX.Name == "os" && node.Sel != nil && node.Sel.Name == "ModePerm" { + return true + } + } + } + return false +} + // NewWritePerms creates a rule to detect file Writes with bad permissions. func NewWritePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { mode := getConfiguredMode(conf, id, 0o600) diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go b/tools/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go index ed1fb947d..c10d18b30 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go @@ -153,10 +153,6 @@ var secretsPatterns = [...]secretPattern{ name: "Stripe API Key", regexp: regexp.MustCompile(`sk_live_[0-9a-zA-Z]{24}`), }, - { - name: "Stripe API Key", - regexp: regexp.MustCompile(`sk_live_[0-9a-zA-Z]{24}`), - }, { name: "Stripe Restricted API Key", regexp: regexp.MustCompile(`rk_live_[0-9a-zA-Z]{24}`), diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go b/tools/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go index a7eabb20b..75de4ed8c 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go @@ -47,6 +47,12 @@ func doGetIdentExpr(expr ast.Expr, hasSelector bool) (*ast.Ident, bool) { } func (r *implicitAliasing) Match(n ast.Node, c *gosec.Context) (*issue.Issue, error) { + // This rule does not apply for Go 1.22, see https://tip.golang.org/doc/go1.22#language. + major, minor, _ := gosec.GoVersion() + if major >= 1 && minor >= 22 { + return nil, nil + } + switch node := n.(type) { case *ast.RangeStmt: // When presented with a range statement, get the underlying Object bound to diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/rand.go b/tools/vendor/github.com/securego/gosec/v2/rules/rand.go index 4491fd928..fe34ca9c3 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/rand.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/rand.go @@ -23,8 +23,7 @@ import ( type weakRand struct { issue.MetaData - funcNames []string - packagePath string + blocklist map[string][]string } func (w *weakRand) ID() string { @@ -32,8 +31,8 @@ func (w *weakRand) ID() string { } func (w *weakRand) Match(n ast.Node, c *gosec.Context) (*issue.Issue, error) { - for _, funcName := range w.funcNames { - if _, matched := gosec.MatchCallByPackage(n, c, w.packagePath, funcName); matched { + for pkg, funcs := range w.blocklist { + if _, matched := gosec.MatchCallByPackage(n, c, pkg, funcs...); matched { return c.NewIssue(n, w.ID(), w.What, w.Severity, w.Confidence), nil } } @@ -43,17 +42,22 @@ func (w *weakRand) Match(n ast.Node, c *gosec.Context) (*issue.Issue, error) { // NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure func NewWeakRandCheck(id string, _ gosec.Config) (gosec.Rule, []ast.Node) { + calls := make(map[string][]string) + calls["math/rand"] = []string{ + "New", "Read", "Float32", "Float64", "Int", "Int31", "Int31n", + "Int63", "Int63n", "Intn", "NormFloat64", "Uint32", "Uint64", + } + calls["math/rand/v2"] = []string{ + "New", "Float32", "Float64", "Int", "Int32", "Int32N", + "Int64", "Int64N", "IntN", "N", "NormFloat64", "Uint32", "Uint32N", "Uint64", "Uint64N", "UintN", + } return &weakRand{ - funcNames: []string{ - "New", "Read", "Float32", "Float64", "Int", "Int31", - "Int31n", "Int63", "Int63n", "Intn", "NormalFloat64", "Uint32", "Uint64", - }, - packagePath: "math/rand", + blocklist: calls, MetaData: issue.MetaData{ ID: id, Severity: issue.High, Confidence: issue.Medium, - What: "Use of weak random number generator (math/rand instead of crypto/rand)", + What: "Use of weak random number generator (math/rand or math/rand/v2 instead of crypto/rand)", }, }, []ast.Node{(*ast.CallExpr)(nil)} } diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/readfile.go b/tools/vendor/github.com/securego/gosec/v2/rules/readfile.go index 7ef4bbad1..da6b9c965 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/readfile.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/readfile.go @@ -143,6 +143,7 @@ func NewReadFile(id string, _ gosec.Config) (gosec.Rule, []ast.Node) { rule.pathJoin.Add("path", "Join") rule.clean.Add("path/filepath", "Clean") rule.clean.Add("path/filepath", "Rel") + rule.clean.Add("path/filepath", "EvalSymlinks") rule.Add("io/ioutil", "ReadFile") rule.Add("os", "ReadFile") rule.Add("os", "Open") diff --git a/tools/vendor/github.com/sivchari/nosnakecase/.golangci.yml b/tools/vendor/github.com/sivchari/nosnakecase/.golangci.yml deleted file mode 100644 index 31e05c4ee..000000000 --- a/tools/vendor/github.com/sivchari/nosnakecase/.golangci.yml +++ /dev/null @@ -1,40 +0,0 @@ -run: - timeout: 5m - skip-files: [] - go: '1.17' - -linters-settings: - govet: - enable-all: true - disable: - - fieldalignment - gocyclo: - min-complexity: 18 - misspell: - locale: US - godox: - keywords: - - FIXME - gofumpt: - extra-rules: true - -linters: - disable-all: true - enable: - - govet - - revive - - goimports - - staticcheck - - gosimple - - unused - - godox - - gofumpt - - misspell - - gocyclo - -issues: - exclude-use-default: true - max-per-linter: 0 - max-same-issues: 0 - exclude: [] - diff --git a/tools/vendor/github.com/sivchari/nosnakecase/README.md b/tools/vendor/github.com/sivchari/nosnakecase/README.md deleted file mode 100644 index 69bb66046..000000000 --- a/tools/vendor/github.com/sivchari/nosnakecase/README.md +++ /dev/null @@ -1,224 +0,0 @@ -# nosnakecase -nosnakecase is a linter that detects snake case of variable naming and function name. - -## Instruction - -```sh -go install github.com/sivchari/nosnakecase/cmd/nosnakecase@latest -``` - -## Usage - -```go -package sandbox - -// global variable name with underscore. -var v_v = 0 // want "v_v is used under score. You should use mixedCap or MixedCap." - -// global constant name with underscore. -const c_c = 0 // want "c_c is used under score. You should use mixedCap or MixedCap." - -// struct name with underscore. -type S_a struct { // want "S_a is used under score. You should use mixedCap or MixedCap." - fi int -} - -// non-exported struct field name with underscore. -type Sa struct { - fi_a int // // want "fi_a is used under score. You should use mixedCap or MixedCap." -} - -// function as struct field, with parameter name with underscore. -type Sb struct { - fib func(p_a int) // want "p_a is used under score. You should use mixedCap or MixedCap." -} - -// exported struct field with underscore. -type Sc struct { - Fi_A int // want "Fi_A is used under score. You should use mixedCap or MixedCap." -} - -// function as struct field, with return name with underscore. -type Sd struct { - fib func(p int) (r_a int) // want "r_a is used under score. You should use mixedCap or MixedCap." -} - -// interface name with underscore. -type I_a interface { // want "I_a is used under score. You should use mixedCap or MixedCap." - fn(p int) -} - -// interface with parameter name with underscore. -type Ia interface { - fn(p_a int) // want "p_a is used under score. You should use mixedCap or MixedCap." -} - -// interface with parameter name with underscore. -type Ib interface { - Fn(p_a int) // want "p_a is used under score. You should use mixedCap or MixedCap." -} - -// function as struct field, with return name with underscore. -type Ic interface { - Fn_a() // want "Fn_a is used under score. You should use mixedCap or MixedCap." -} - -// interface with return name with underscore. -type Id interface { - Fn() (r_a int) // want "r_a is used under score. You should use mixedCap or MixedCap." -} - -// function name with underscore. -func f_a() {} // want "f_a is used under score. You should use mixedCap or MixedCap." - -// function's parameter name with underscore. -func fb(p_a int) {} // want "p_a is used under score. You should use mixedCap or MixedCap." - -// named return with underscore. -func fc() (r_b int) { // want "r_b is used under score. You should use mixedCap or MixedCap." - return 0 -} - -// local variable (short declaration) with underscore. -func fd(p int) int { - v_b := p * 2 // want "v_b is used under score. You should use mixedCap or MixedCap." - - return v_b // want "v_b is used under score. You should use mixedCap or MixedCap." -} - -// local constant with underscore. -func fe(p int) int { - const v_b = 2 // want "v_b is used under score. You should use mixedCap or MixedCap." - - return v_b * p // want "v_b is used under score. You should use mixedCap or MixedCap." -} - -// local variable with underscore. -func ff(p int) int { - var v_b = 2 // want "v_b is used under score. You should use mixedCap or MixedCap." - - return v_b * p // want "v_b is used under score. You should use mixedCap or MixedCap." -} - -// inner function, parameter name with underscore. -func fg() { - fgl := func(p_a int) {} // want "p_a is used under score. You should use mixedCap or MixedCap." - fgl(1) -} - -type Foo struct{} - -// method name with underscore. -func (f Foo) f_a() {} // want "f_a is used under score. You should use mixedCap or MixedCap." - -// method's parameter name with underscore. -func (f Foo) fb(p_a int) {} // want "p_a is used under score. You should use mixedCap or MixedCap." - -// named return with underscore. -func (f Foo) fc() (r_b int) { return 0 } // want "r_b is used under score. You should use mixedCap or MixedCap." - -// local variable (short declaration) with underscore. -func (f Foo) fd(p int) int { - v_b := p * 2 // want "v_b is used under score. You should use mixedCap or MixedCap." - - return v_b // want "v_b is used under score. You should use mixedCap or MixedCap." -} - -// local constant with underscore. -func (f Foo) fe(p int) int { - const v_b = 2 // want "v_b is used under score. You should use mixedCap or MixedCap." - - return v_b * p // want "v_b is used under score. You should use mixedCap or MixedCap." -} - -// local variable with underscore. -func (f Foo) ff(p int) int { - var v_b = 2 // want "v_b is used under score. You should use mixedCap or MixedCap." - - return v_b * p // want "v_b is used under score. You should use mixedCap or MixedCap." -} - -func fna(a, p_a int) {} // want "p_a is used under score. You should use mixedCap or MixedCap." - -func fna1(a string, p_a int) {} // want "p_a is used under score. You should use mixedCap or MixedCap." - -func fnb(a, b, p_a int) {} // want "p_a is used under score. You should use mixedCap or MixedCap." - -func fnb1(a, b string, p_a int) {} // want "p_a is used under score. You should use mixedCap or MixedCap." - -func fnd( - p_a int, // want "p_a is used under score. You should use mixedCap or MixedCap." - p_b int, // want "p_b is used under score. You should use mixedCap or MixedCap." - p_c int, // want "p_c is used under score. You should use mixedCap or MixedCap." -) { -} -``` - -```console -go vet -vettool=(which nosnakecase) ./... - -# command-line-arguments -# a -./a.go:4:5: v_v is used under score. You should use mixedCap or MixedCap. -./a.go:7:7: c_c is used under score. You should use mixedCap or MixedCap. -./a.go:10:6: S_a is used under score. You should use mixedCap or MixedCap. -./a.go:16:2: fi_a is used under score. You should use mixedCap or MixedCap. -./a.go:21:11: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:26:2: Fi_A is used under score. You should use mixedCap or MixedCap. -./a.go:31:19: r_a is used under score. You should use mixedCap or MixedCap. -./a.go:35:6: I_a is used under score. You should use mixedCap or MixedCap. -./a.go:41:5: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:46:5: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:51:2: Fn_a is used under score. You should use mixedCap or MixedCap. -./a.go:56:8: r_a is used under score. You should use mixedCap or MixedCap. -./a.go:60:6: f_a is used under score. You should use mixedCap or MixedCap. -./a.go:63:9: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:66:12: r_b is used under score. You should use mixedCap or MixedCap. -./a.go:72:2: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:74:9: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:79:8: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:81:9: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:86:6: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:88:9: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:93:14: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:100:14: f_a is used under score. You should use mixedCap or MixedCap. -./a.go:103:17: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:106:20: r_b is used under score. You should use mixedCap or MixedCap. -./a.go:110:2: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:112:9: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:117:8: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:119:9: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:124:6: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:126:9: v_b is used under score. You should use mixedCap or MixedCap. -./a.go:129:13: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:131:21: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:133:16: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:135:24: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:138:2: p_a is used under score. You should use mixedCap or MixedCap. -./a.go:139:2: p_b is used under score. You should use mixedCap or MixedCap. -./a.go:140:2: p_c is used under score. You should use mixedCap or MixedCap. -``` - -## CI - -### CircleCI - -```yaml -- run: - name: install nosnakecase - command: go install github.com/sivchari/nosnakecase/cmd/nosnakecase@latest - -- run: - name: run nosnakecase - command: go vet -vettool=`which nosnakecase` ./... -``` - -### GitHub Actions - -```yaml -- name: install nosnakecase - run: go install github.com/sivchari/nosnakecase/cmd/nosnakecase@latest - -- name: run nosnakecase - run: go vet -vettool=`which nosnakecase` ./... -``` diff --git a/tools/vendor/github.com/sivchari/nosnakecase/nosnakecase.go b/tools/vendor/github.com/sivchari/nosnakecase/nosnakecase.go deleted file mode 100644 index 88cf70e3f..000000000 --- a/tools/vendor/github.com/sivchari/nosnakecase/nosnakecase.go +++ /dev/null @@ -1,63 +0,0 @@ -package nosnakecase - -import ( - "go/ast" - "go/token" - "strings" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" - "golang.org/x/tools/go/ast/inspector" -) - -const doc = "nosnakecase is a linter that detects snake case of variable naming and function name." - -// Analyzer is a nosnakecase linter. -var Analyzer = &analysis.Analyzer{ - Name: "nosnakecase", - Doc: doc, - Run: run, - Requires: []*analysis.Analyzer{ - inspect.Analyzer, - }, -} - -func run(pass *analysis.Pass) (interface{}, error) { - result := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) - - nodeFilter := []ast.Node{ - (*ast.Ident)(nil), - } - - result.Preorder(nodeFilter, func(n ast.Node) { - switch n := n.(type) { - case *ast.Ident: - report(pass, n.Pos(), n.Name) - } - }) - - return nil, nil -} - -func report(pass *analysis.Pass, pos token.Pos, name string) { - // skip import _ "xxx" - if name == "_" { - return - } - - // skip package xxx_test - if strings.Contains(name, "_test") { - return - } - - // If prefix is Test or Benchmark, Fuzz, skip - // FYI https://go.dev/blog/examples - if strings.HasPrefix(name, "Test") || strings.HasPrefix(name, "Benchmark") || strings.HasPrefix(name, "Fuzz") { - return - } - - if strings.Contains(name, "_") { - pass.Reportf(pos, "%s contains underscore. You should use mixedCap or MixedCap.", name) - return - } -} diff --git a/tools/vendor/github.com/sivchari/tenv/README.md b/tools/vendor/github.com/sivchari/tenv/README.md index c5d004773..56389e2dd 100644 --- a/tools/vendor/github.com/sivchari/tenv/README.md +++ b/tools/vendor/github.com/sivchari/tenv/README.md @@ -1,6 +1,6 @@ # tenv -![tenv Gopher](./tenv.png "Gopher") +tenv Gopher [![test_and_lint](https://github.com/sivchari/tenv/actions/workflows/workflows.yml/badge.svg?branch=main)](https://github.com/sivchari/tenv/actions/workflows/workflows.yml) @@ -10,7 +10,7 @@ tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 ## Instruction ```sh -go install github.com/sivchari/tenv/cmd/tenv +go install github.com/sivchari/tenv/cmd/tenv@latest ``` ## Usage @@ -39,7 +39,7 @@ func helper() { ``` ```console -go vet -vettool=(which tenv) ./... +go vet -vettool=$(which tenv) ./... # a ./main_test.go:11:2: os.Setenv() can be replaced by `t.Setenv()` in TestMain @@ -75,7 +75,7 @@ func helper() { ``` ```console -go vet -vettool=(which tenv) -tenv.all ./... +go vet -vettool=$(which tenv) -tenv.all ./... # a ./main_test.go:11:2: os.Setenv() can be replaced by `t.Setenv()` in TestMain @@ -89,7 +89,7 @@ go vet -vettool=(which tenv) -tenv.all ./... ```yaml - run: name: install tenv - command: go install github.com/sivchari/tenv + command: go install github.com/sivchari/tenv@latest - run: name: run tenv @@ -100,7 +100,7 @@ go vet -vettool=(which tenv) -tenv.all ./... ```yaml - name: install tenv - run: go install github.com/sivchari/tenv + run: go install github.com/sivchari/tenv@latest - name: run tenv run: go vet -vettool=`which tenv` ./... diff --git a/tools/vendor/github.com/sivchari/tenv/tenv.go b/tools/vendor/github.com/sivchari/tenv/tenv.go index fcff98d05..999c5289d 100644 --- a/tools/vendor/github.com/sivchari/tenv/tenv.go +++ b/tools/vendor/github.com/sivchari/tenv/tenv.go @@ -81,6 +81,8 @@ func checkStmts(pass *analysis.Pass, stmts []ast.Stmt, funcName, argName string) if !checkAssignStmt(pass, stmt, funcName, argName) { continue } + case *ast.ForStmt: + checkForStmt(pass, stmt, funcName, argName) } } } @@ -90,6 +92,7 @@ func checkExprStmt(pass *analysis.Pass, stmt *ast.ExprStmt, funcName, argName st if !ok { return false } + checkArgs(pass, callExpr.Args, funcName, argName) fun, ok := callExpr.Fun.(*ast.SelectorExpr) if !ok { return false @@ -108,6 +111,30 @@ func checkExprStmt(pass *analysis.Pass, stmt *ast.ExprStmt, funcName, argName st return true } +func checkArgs(pass *analysis.Pass, args []ast.Expr, funcName, argName string) { + for _, arg := range args { + callExpr, ok := arg.(*ast.CallExpr) + if !ok { + continue + } + fun, ok := callExpr.Fun.(*ast.SelectorExpr) + if !ok { + continue + } + x, ok := fun.X.(*ast.Ident) + if !ok { + continue + } + targetName := x.Name + "." + fun.Sel.Name + if targetName == "os.Setenv" { + if argName == "" { + argName = "testing" + } + pass.Reportf(arg.Pos(), "os.Setenv() can be replaced by `%s.Setenv()` in %s", argName, funcName) + } + } +} + func checkIfStmt(pass *analysis.Pass, stmt *ast.IfStmt, funcName, argName string) bool { assignStmt, ok := stmt.Init.(*ast.AssignStmt) if !ok { @@ -158,6 +185,10 @@ func checkAssignStmt(pass *analysis.Pass, stmt *ast.AssignStmt, funcName, argNam return true } +func checkForStmt(pass *analysis.Pass, stmt *ast.ForStmt, funcName, argName string) { + checkStmts(pass, stmt.Body.List, funcName, argName) +} + func targetRunner(params []*ast.Field, fileName string) (string, bool) { for _, p := range params { switch typ := p.Type.(type) { @@ -196,7 +227,7 @@ func checkStarExprTarget(typ *ast.StarExpr) bool { } targetName := x.Name + "." + selector.Sel.Name switch targetName { - case "testing.T", "testing.B", "testing.F": + case "testing.T", "testing.B": return true default: return false diff --git a/tools/vendor/github.com/spf13/afero/.travis.yml b/tools/vendor/github.com/spf13/afero/.travis.yml deleted file mode 100644 index e944f5947..000000000 --- a/tools/vendor/github.com/spf13/afero/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -sudo: false -language: go -arch: - - amd64 - - ppc64e - -go: - - "1.14" - - "1.15" - - "1.16" - - tip - -os: - - linux - - osx - -matrix: - allow_failures: - - go: tip - fast_finish: true - -script: - - go build -v ./... - - go test -count=1 -cover -race -v ./... - - go vet ./... - - FILES=$(gofmt -s -l . zipfs sftpfs mem tarfs); if [[ -n "${FILES}" ]]; then echo "You have go format errors; gofmt your changes"; exit 1; fi diff --git a/tools/vendor/github.com/spf13/afero/README.md b/tools/vendor/github.com/spf13/afero/README.md index cab257f56..3bafbfdfc 100644 --- a/tools/vendor/github.com/spf13/afero/README.md +++ b/tools/vendor/github.com/spf13/afero/README.md @@ -2,7 +2,7 @@ A FileSystem Abstraction System for Go -[![Build Status](https://travis-ci.org/spf13/afero.svg)](https://travis-ci.org/spf13/afero) [![Build status](https://ci.appveyor.com/api/projects/status/github/spf13/afero?branch=master&svg=true)](https://ci.appveyor.com/project/spf13/afero) [![GoDoc](https://godoc.org/github.com/spf13/afero?status.svg)](https://godoc.org/github.com/spf13/afero) [![Join the chat at https://gitter.im/spf13/afero](https://badges.gitter.im/Dev%20Chat.svg)](https://gitter.im/spf13/afero?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Test](https://github.com/spf13/afero/actions/workflows/test.yml/badge.svg)](https://github.com/spf13/afero/actions/workflows/test.yml) [![GoDoc](https://godoc.org/github.com/spf13/afero?status.svg)](https://godoc.org/github.com/spf13/afero) [![Join the chat at https://gitter.im/spf13/afero](https://badges.gitter.im/Dev%20Chat.svg)](https://gitter.im/spf13/afero?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Overview diff --git a/tools/vendor/github.com/spf13/afero/afero.go b/tools/vendor/github.com/spf13/afero/afero.go index 469ff7d2d..39f658520 100644 --- a/tools/vendor/github.com/spf13/afero/afero.go +++ b/tools/vendor/github.com/spf13/afero/afero.go @@ -97,14 +97,14 @@ type Fs interface { // Chown changes the uid and gid of the named file. Chown(name string, uid, gid int) error - //Chtimes changes the access and modification times of the named file + // Chtimes changes the access and modification times of the named file Chtimes(name string, atime time.Time, mtime time.Time) error } var ( ErrFileClosed = errors.New("File is closed") - ErrOutOfRange = errors.New("Out of range") - ErrTooLarge = errors.New("Too large") + ErrOutOfRange = errors.New("out of range") + ErrTooLarge = errors.New("too large") ErrFileNotFound = os.ErrNotExist ErrFileExists = os.ErrExist ErrDestinationExists = os.ErrExist diff --git a/tools/vendor/github.com/spf13/afero/appveyor.yml b/tools/vendor/github.com/spf13/afero/appveyor.yml index 5d2f34bf1..65e20e8ca 100644 --- a/tools/vendor/github.com/spf13/afero/appveyor.yml +++ b/tools/vendor/github.com/spf13/afero/appveyor.yml @@ -1,3 +1,5 @@ +# This currently does nothing. We have moved to GitHub action, but this is kept +# until spf13 has disabled this project in AppVeyor. version: '{build}' clone_folder: C:\gopath\src\github.com\spf13\afero environment: @@ -6,10 +8,3 @@ build_script: - cmd: >- go version - go env - - go get -v github.com/spf13/afero/... - - go build -v github.com/spf13/afero/... -test_script: -- cmd: go test -count=1 -cover -race -v github.com/spf13/afero/... diff --git a/tools/vendor/github.com/spf13/afero/basepath.go b/tools/vendor/github.com/spf13/afero/basepath.go index 4f9832829..2e72793a3 100644 --- a/tools/vendor/github.com/spf13/afero/basepath.go +++ b/tools/vendor/github.com/spf13/afero/basepath.go @@ -1,6 +1,7 @@ package afero import ( + "io/fs" "os" "path/filepath" "runtime" @@ -8,7 +9,10 @@ import ( "time" ) -var _ Lstater = (*BasePathFs)(nil) +var ( + _ Lstater = (*BasePathFs)(nil) + _ fs.ReadDirFile = (*BasePathFile)(nil) +) // The BasePathFs restricts all operations to a given path within an Fs. // The given file name to the operations on this Fs will be prepended with @@ -33,6 +37,13 @@ func (f *BasePathFile) Name() string { return strings.TrimPrefix(sourcename, filepath.Clean(f.path)) } +func (f *BasePathFile) ReadDir(n int) ([]fs.DirEntry, error) { + if rdf, ok := f.File.(fs.ReadDirFile); ok { + return rdf.ReadDir(n) + } + return readDirFile{f.File}.ReadDir(n) +} + func NewBasePathFs(source Fs, path string) Fs { return &BasePathFs{source: source, path: path} } diff --git a/tools/vendor/github.com/spf13/afero/const_bsds.go b/tools/vendor/github.com/spf13/afero/const_bsds.go index 18b45824b..30855de57 100644 --- a/tools/vendor/github.com/spf13/afero/const_bsds.go +++ b/tools/vendor/github.com/spf13/afero/const_bsds.go @@ -11,7 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -// +build aix darwin openbsd freebsd netbsd dragonfly +//go:build aix || darwin || openbsd || freebsd || netbsd || dragonfly || zos +// +build aix darwin openbsd freebsd netbsd dragonfly zos package afero diff --git a/tools/vendor/github.com/spf13/afero/const_win_unix.go b/tools/vendor/github.com/spf13/afero/const_win_unix.go index 2b850e4dd..12792d21e 100644 --- a/tools/vendor/github.com/spf13/afero/const_win_unix.go +++ b/tools/vendor/github.com/spf13/afero/const_win_unix.go @@ -10,12 +10,8 @@ // 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. -// +build !darwin -// +build !openbsd -// +build !freebsd -// +build !dragonfly -// +build !netbsd -// +build !aix +//go:build !darwin && !openbsd && !freebsd && !dragonfly && !netbsd && !aix && !zos +// +build !darwin,!openbsd,!freebsd,!dragonfly,!netbsd,!aix,!zos package afero diff --git a/tools/vendor/github.com/spf13/afero/copyOnWriteFs.go b/tools/vendor/github.com/spf13/afero/copyOnWriteFs.go index 6ff8f3099..184d6dd70 100644 --- a/tools/vendor/github.com/spf13/afero/copyOnWriteFs.go +++ b/tools/vendor/github.com/spf13/afero/copyOnWriteFs.go @@ -223,7 +223,7 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, return nil, err } if isaDir { - if err = u.layer.MkdirAll(dir, 0777); err != nil { + if err = u.layer.MkdirAll(dir, 0o777); err != nil { return nil, err } return u.layer.OpenFile(name, flag, perm) @@ -247,8 +247,9 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, // This function handles the 9 different possibilities caused // by the union which are the intersection of the following... -// layer: doesn't exist, exists as a file, and exists as a directory -// base: doesn't exist, exists as a file, and exists as a directory +// +// layer: doesn't exist, exists as a file, and exists as a directory +// base: doesn't exist, exists as a file, and exists as a directory func (u *CopyOnWriteFs) Open(name string) (File, error) { // Since the overlay overrides the base we check that first b, err := u.isBaseFile(name) @@ -322,5 +323,5 @@ func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error { } func (u *CopyOnWriteFs) Create(name string) (File, error) { - return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666) + return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o666) } diff --git a/tools/vendor/github.com/spf13/afero/httpFs.go b/tools/vendor/github.com/spf13/afero/httpFs.go index 2b86e30d1..ac0de6d51 100644 --- a/tools/vendor/github.com/spf13/afero/httpFs.go +++ b/tools/vendor/github.com/spf13/afero/httpFs.go @@ -29,7 +29,7 @@ type httpDir struct { } func (d httpDir) Open(name string) (http.File, error) { - if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 || + if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) || strings.Contains(name, "\x00") { return nil, errors.New("http: invalid character in file path") } diff --git a/tools/vendor/github.com/spf13/afero/internal/common/adapters.go b/tools/vendor/github.com/spf13/afero/internal/common/adapters.go new file mode 100644 index 000000000..60685caa5 --- /dev/null +++ b/tools/vendor/github.com/spf13/afero/internal/common/adapters.go @@ -0,0 +1,27 @@ +// Copyright © 2022 Steve Francia . +// +// 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 common + +import "io/fs" + +// FileInfoDirEntry provides an adapter from os.FileInfo to fs.DirEntry +type FileInfoDirEntry struct { + fs.FileInfo +} + +var _ fs.DirEntry = FileInfoDirEntry{} + +func (d FileInfoDirEntry) Type() fs.FileMode { return d.FileInfo.Mode().Type() } + +func (d FileInfoDirEntry) Info() (fs.FileInfo, error) { return d.FileInfo, nil } diff --git a/tools/vendor/github.com/spf13/afero/iofs.go b/tools/vendor/github.com/spf13/afero/iofs.go index c80345536..938b9316e 100644 --- a/tools/vendor/github.com/spf13/afero/iofs.go +++ b/tools/vendor/github.com/spf13/afero/iofs.go @@ -1,3 +1,4 @@ +//go:build go1.16 // +build go1.16 package afero @@ -7,7 +8,10 @@ import ( "io/fs" "os" "path" + "sort" "time" + + "github.com/spf13/afero/internal/common" ) // IOFS adopts afero.Fs to stdlib io/fs.FS @@ -66,14 +70,31 @@ func (iofs IOFS) Glob(pattern string) ([]string, error) { } func (iofs IOFS) ReadDir(name string) ([]fs.DirEntry, error) { - items, err := ReadDir(iofs.Fs, name) + f, err := iofs.Fs.Open(name) if err != nil { return nil, iofs.wrapError("readdir", name, err) } + defer f.Close() + + if rdf, ok := f.(fs.ReadDirFile); ok { + items, err := rdf.ReadDir(-1) + if err != nil { + return nil, iofs.wrapError("readdir", name, err) + } + sort.Slice(items, func(i, j int) bool { return items[i].Name() < items[j].Name() }) + return items, nil + } + + items, err := f.Readdir(-1) + if err != nil { + return nil, iofs.wrapError("readdir", name, err) + } + sort.Sort(byName(items)) + ret := make([]fs.DirEntry, len(items)) for i := range items { - ret[i] = dirEntry{items[i]} + ret[i] = common.FileInfoDirEntry{FileInfo: items[i]} } return ret, nil @@ -108,17 +129,6 @@ func (IOFS) wrapError(op, path string, err error) error { } } -// dirEntry provides adapter from os.FileInfo to fs.DirEntry -type dirEntry struct { - fs.FileInfo -} - -var _ fs.DirEntry = dirEntry{} - -func (d dirEntry) Type() fs.FileMode { return d.FileInfo.Mode().Type() } - -func (d dirEntry) Info() (fs.FileInfo, error) { return d.FileInfo, nil } - // readDirFile provides adapter from afero.File to fs.ReadDirFile needed for correct Open type readDirFile struct { File @@ -134,7 +144,7 @@ func (r readDirFile) ReadDir(n int) ([]fs.DirEntry, error) { ret := make([]fs.DirEntry, len(items)) for i := range items { - ret[i] = dirEntry{items[i]} + ret[i] = common.FileInfoDirEntry{FileInfo: items[i]} } return ret, nil diff --git a/tools/vendor/github.com/spf13/afero/ioutil.go b/tools/vendor/github.com/spf13/afero/ioutil.go index a403133e2..fa6abe1ee 100644 --- a/tools/vendor/github.com/spf13/afero/ioutil.go +++ b/tools/vendor/github.com/spf13/afero/ioutil.go @@ -141,8 +141,10 @@ func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error { // We generate random temporary file names so that there's a good // chance the file doesn't exist yet - keeps the number of tries in // TempFile to a minimum. -var rand uint32 -var randmu sync.Mutex +var ( + randNum uint32 + randmu sync.Mutex +) func reseed() uint32 { return uint32(time.Now().UnixNano() + int64(os.Getpid())) @@ -150,12 +152,12 @@ func reseed() uint32 { func nextRandom() string { randmu.Lock() - r := rand + r := randNum if r == 0 { r = reseed() } r = r*1664525 + 1013904223 // constants from Numerical Recipes - rand = r + randNum = r randmu.Unlock() return strconv.Itoa(int(1e9 + r%1e9))[1:] } @@ -190,11 +192,11 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { nconflict := 0 for i := 0; i < 10000; i++ { name := filepath.Join(dir, prefix+nextRandom()+suffix) - f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() - rand = reseed() + randNum = reseed() randmu.Unlock() } continue @@ -214,6 +216,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { func (a Afero) TempDir(dir, prefix string) (name string, err error) { return TempDir(a.Fs, dir, prefix) } + func TempDir(fs Fs, dir, prefix string) (name string, err error) { if dir == "" { dir = os.TempDir() @@ -222,11 +225,11 @@ func TempDir(fs Fs, dir, prefix string) (name string, err error) { nconflict := 0 for i := 0; i < 10000; i++ { try := filepath.Join(dir, prefix+nextRandom()) - err = fs.Mkdir(try, 0700) + err = fs.Mkdir(try, 0o700) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() - rand = reseed() + randNum = reseed() randmu.Unlock() } continue diff --git a/tools/vendor/github.com/spf13/afero/mem/file.go b/tools/vendor/github.com/spf13/afero/mem/file.go index 5ef8b6a39..62fe4498e 100644 --- a/tools/vendor/github.com/spf13/afero/mem/file.go +++ b/tools/vendor/github.com/spf13/afero/mem/file.go @@ -18,15 +18,20 @@ import ( "bytes" "errors" "io" + "io/fs" "os" "path/filepath" "sync" "sync/atomic" "time" + + "github.com/spf13/afero/internal/common" ) const FilePathSeparator = string(filepath.Separator) +var _ fs.ReadDirFile = &File{} + type File struct { // atomic requires 64-bit alignment for struct field access at int64 @@ -183,10 +188,23 @@ func (f *File) Readdirnames(n int) (names []string, err error) { return names, err } +// Implements fs.ReadDirFile +func (f *File) ReadDir(n int) ([]fs.DirEntry, error) { + fi, err := f.Readdir(n) + if err != nil { + return nil, err + } + di := make([]fs.DirEntry, len(fi)) + for i, f := range fi { + di[i] = common.FileInfoDirEntry{FileInfo: f} + } + return di, nil +} + func (f *File) Read(b []byte) (n int, err error) { f.fileData.Lock() defer f.fileData.Unlock() - if f.closed == true { + if f.closed { return 0, ErrFileClosed } if len(b) > 0 && int(f.at) == len(f.fileData.data) { @@ -214,7 +232,7 @@ func (f *File) ReadAt(b []byte, off int64) (n int, err error) { } func (f *File) Truncate(size int64) error { - if f.closed == true { + if f.closed { return ErrFileClosed } if f.readOnly { @@ -227,7 +245,7 @@ func (f *File) Truncate(size int64) error { defer f.fileData.Unlock() if size > int64(len(f.fileData.data)) { diff := size - int64(len(f.fileData.data)) - f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...) + f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{0o0}, int(diff))...) } else { f.fileData.data = f.fileData.data[0:size] } @@ -236,7 +254,7 @@ func (f *File) Truncate(size int64) error { } func (f *File) Seek(offset int64, whence int) (int64, error) { - if f.closed == true { + if f.closed { return 0, ErrFileClosed } switch whence { @@ -251,7 +269,7 @@ func (f *File) Seek(offset int64, whence int) (int64, error) { } func (f *File) Write(b []byte) (n int, err error) { - if f.closed == true { + if f.closed { return 0, ErrFileClosed } if f.readOnly { @@ -267,7 +285,7 @@ func (f *File) Write(b []byte) (n int, err error) { tail = f.fileData.data[n+int(cur):] } if diff > 0 { - f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{00}, int(diff)), b...)...) + f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{0o0}, int(diff)), b...)...) f.fileData.data = append(f.fileData.data, tail...) } else { f.fileData.data = append(f.fileData.data[:cur], b...) @@ -303,16 +321,19 @@ func (s *FileInfo) Name() string { s.Unlock() return name } + func (s *FileInfo) Mode() os.FileMode { s.Lock() defer s.Unlock() return s.mode } + func (s *FileInfo) ModTime() time.Time { s.Lock() defer s.Unlock() return s.modtime } + func (s *FileInfo) IsDir() bool { s.Lock() defer s.Unlock() @@ -330,8 +351,8 @@ func (s *FileInfo) Size() int64 { var ( ErrFileClosed = errors.New("File is closed") - ErrOutOfRange = errors.New("Out of range") - ErrTooLarge = errors.New("Too large") + ErrOutOfRange = errors.New("out of range") + ErrTooLarge = errors.New("too large") ErrFileNotFound = os.ErrNotExist ErrFileExists = os.ErrExist ErrDestinationExists = os.ErrExist diff --git a/tools/vendor/github.com/spf13/afero/memmap.go b/tools/vendor/github.com/spf13/afero/memmap.go index ea0798d87..d6c744e8d 100644 --- a/tools/vendor/github.com/spf13/afero/memmap.go +++ b/tools/vendor/github.com/spf13/afero/memmap.go @@ -15,9 +15,13 @@ package afero import ( "fmt" + "io" + "log" "os" "path/filepath" + + "sort" "strings" "sync" "time" @@ -43,7 +47,7 @@ func (m *MemMapFs) getData() map[string]*mem.FileData { // Root should always exist, right? // TODO: what about windows? root := mem.CreateDir(FilePathSeparator) - mem.SetMode(root, os.ModeDir|0755) + mem.SetMode(root, os.ModeDir|0o755) m.data[FilePathSeparator] = root }) return m.data @@ -87,6 +91,24 @@ func (m *MemMapFs) findParent(f *mem.FileData) *mem.FileData { return pfile } +func (m *MemMapFs) findDescendants(name string) []*mem.FileData { + fData := m.getData() + descendants := make([]*mem.FileData, 0, len(fData)) + for p, dFile := range fData { + if strings.HasPrefix(p, name+FilePathSeparator) { + descendants = append(descendants, dFile) + } + } + + sort.Slice(descendants, func(i, j int) bool { + cur := len(strings.Split(descendants[i].Name(), FilePathSeparator)) + next := len(strings.Split(descendants[j].Name(), FilePathSeparator)) + return cur < next + }) + + return descendants +} + func (m *MemMapFs) registerWithParent(f *mem.FileData, perm os.FileMode) { if f == nil { return @@ -96,12 +118,12 @@ func (m *MemMapFs) registerWithParent(f *mem.FileData, perm os.FileMode) { pdir := filepath.Dir(filepath.Clean(f.Name())) err := m.lockfreeMkdir(pdir, perm) if err != nil { - //log.Println("Mkdir error:", err) + // log.Println("Mkdir error:", err) return } parent, err = m.lockfreeOpen(pdir) if err != nil { - //log.Println("Open after Mkdir error:", err) + // log.Println("Open after Mkdir error:", err) return } } @@ -142,6 +164,11 @@ func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error { } m.mu.Lock() + // Dobule check that it doesn't exist. + if _, ok := m.getData()[name]; ok { + m.mu.Unlock() + return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists} + } item := mem.CreateDir(name) mem.SetMode(item, os.ModeDir|perm) m.getData()[name] = item @@ -232,7 +259,7 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data()) } if flag&os.O_APPEND > 0 { - _, err = file.Seek(0, os.SEEK_END) + _, err = file.Seek(0, io.SeekEnd) if err != nil { file.Close() return nil, err @@ -303,11 +330,22 @@ func (m *MemMapFs) Rename(oldname, newname string) error { if _, ok := m.getData()[oldname]; ok { m.mu.RUnlock() m.mu.Lock() - m.unRegisterWithParent(oldname) + err := m.unRegisterWithParent(oldname) + if err != nil { + return err + } + fileData := m.getData()[oldname] - delete(m.getData(), oldname) mem.ChangeFileName(fileData, newname) m.getData()[newname] = fileData + + err = m.renameDescendants(oldname, newname) + if err != nil { + return err + } + + delete(m.getData(), oldname) + m.registerWithParent(fileData, 0) m.mu.Unlock() m.mu.RLock() @@ -317,6 +355,29 @@ func (m *MemMapFs) Rename(oldname, newname string) error { return nil } +func (m *MemMapFs) renameDescendants(oldname, newname string) error { + descendants := m.findDescendants(oldname) + removes := make([]string, 0, len(descendants)) + for _, desc := range descendants { + descNewName := strings.Replace(desc.Name(), oldname, newname, 1) + err := m.unRegisterWithParent(desc.Name()) + if err != nil { + return err + } + + removes = append(removes, desc.Name()) + mem.ChangeFileName(desc, descNewName) + m.getData()[descNewName] = desc + + m.registerWithParent(desc, 0) + } + for _, r := range removes { + delete(m.getData(), r) + } + + return nil +} + func (m *MemMapFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { fileInfo, err := m.Stat(name) return fileInfo, false, err diff --git a/tools/vendor/github.com/spf13/afero/regexpfs.go b/tools/vendor/github.com/spf13/afero/regexpfs.go index ac359c62a..218f3b235 100644 --- a/tools/vendor/github.com/spf13/afero/regexpfs.go +++ b/tools/vendor/github.com/spf13/afero/regexpfs.go @@ -10,7 +10,6 @@ import ( // The RegexpFs filters files (not directories) by regular expression. Only // files matching the given regexp will be allowed, all others get a ENOENT error ( // "No such file or directory"). -// type RegexpFs struct { re *regexp.Regexp source Fs diff --git a/tools/vendor/github.com/spf13/afero/symlink.go b/tools/vendor/github.com/spf13/afero/symlink.go index d1c6ea53d..aa6ae125b 100644 --- a/tools/vendor/github.com/spf13/afero/symlink.go +++ b/tools/vendor/github.com/spf13/afero/symlink.go @@ -21,9 +21,9 @@ import ( // filesystems saying so. // It indicates support for 3 symlink related interfaces that implement the // behaviors of the os methods: -// - Lstat -// - Symlink, and -// - Readlink +// - Lstat +// - Symlink, and +// - Readlink type Symlinker interface { Lstater Linker diff --git a/tools/vendor/github.com/spf13/afero/unionFile.go b/tools/vendor/github.com/spf13/afero/unionFile.go index 34f99a40c..62dd6c93c 100644 --- a/tools/vendor/github.com/spf13/afero/unionFile.go +++ b/tools/vendor/github.com/spf13/afero/unionFile.go @@ -47,7 +47,7 @@ func (f *UnionFile) Read(s []byte) (int, error) { if (err == nil || err == io.EOF) && f.Base != nil { // advance the file position also in the base file, the next // call may be a write at this position (or a seek with SEEK_CUR) - if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil { + if _, seekErr := f.Base.Seek(int64(n), io.SeekCurrent); seekErr != nil { // only overwrite err in case the seek fails: we need to // report an eventual io.EOF to the caller err = seekErr @@ -65,7 +65,7 @@ func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) { if f.Layer != nil { n, err := f.Layer.ReadAt(s, o) if (err == nil || err == io.EOF) && f.Base != nil { - _, err = f.Base.Seek(o+int64(n), os.SEEK_SET) + _, err = f.Base.Seek(o+int64(n), io.SeekStart) } return n, err } @@ -130,7 +130,7 @@ func (f *UnionFile) Name() string { type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { - var files = make(map[string]os.FileInfo) + files := make(map[string]os.FileInfo) for _, fi := range lofi { files[fi.Name()] = fi @@ -151,7 +151,6 @@ var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, err } return rfi, nil - } // Readdir will weave the two directories together and @@ -275,7 +274,7 @@ func copyFile(base Fs, layer Fs, name string, bfh File) error { return err } if !exists { - err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME? + err = layer.MkdirAll(filepath.Dir(name), 0o777) // FIXME? if err != nil { return err } diff --git a/tools/vendor/github.com/spf13/afero/util.go b/tools/vendor/github.com/spf13/afero/util.go index 4f253f481..9e4cba274 100644 --- a/tools/vendor/github.com/spf13/afero/util.go +++ b/tools/vendor/github.com/spf13/afero/util.go @@ -25,6 +25,7 @@ import ( "strings" "unicode" + "golang.org/x/text/runes" "golang.org/x/text/transform" "golang.org/x/text/unicode/norm" ) @@ -42,7 +43,7 @@ func WriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { if err != os.ErrExist { return err @@ -70,7 +71,7 @@ func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { return } @@ -123,7 +124,7 @@ func GetTempDir(fs Fs, subPath string) string { return addSlash(dir) } - err := fs.MkdirAll(dir, 0777) + err := fs.MkdirAll(dir, 0o777) if err != nil { panic(err) } @@ -158,16 +159,12 @@ func UnicodeSanitize(s string) string { // Transform characters with accents into plain forms. func NeuterAccents(s string) string { - t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC) + t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) result, _, _ := transform.String(t, string(s)) return result } -func isMn(r rune) bool { - return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks -} - func (a Afero) FileContainsBytes(filename string, subslice []byte) (bool, error) { return FileContainsBytes(a.Fs, filename, subslice) } @@ -200,7 +197,6 @@ func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, err // readerContains reports whether any of the subslices is within r. func readerContainsAny(r io.Reader, subslices ...[]byte) bool { - if r == nil || len(subslices) == 0 { return false } @@ -299,6 +295,9 @@ func IsEmpty(fs Fs, path string) (bool, error) { } defer f.Close() list, err := f.Readdir(-1) + if err != nil { + return false, err + } return len(list) == 0, nil } return fi.Size() == 0, nil diff --git a/tools/vendor/github.com/spf13/cobra/.golangci.yml b/tools/vendor/github.com/spf13/cobra/.golangci.yml index 2578d94b5..2c8f4808c 100644 --- a/tools/vendor/github.com/spf13/cobra/.golangci.yml +++ b/tools/vendor/github.com/spf13/cobra/.golangci.yml @@ -19,44 +19,39 @@ linters: disable-all: true enable: #- bodyclose - - deadcode + # - deadcode ! deprecated since v1.49.0; replaced by 'unused' #- depguard #- dogsled #- dupl - errcheck #- exhaustive #- funlen - - gas #- gochecknoinits - goconst - #- gocritic + - gocritic #- gocyclo - #- gofmt + - gofmt - goimports - - golint #- gomnd #- goprintffuncname - #- gosec - #- gosimple + - gosec + - gosimple - govet - ineffassign - - interfacer #- lll - - maligned - - megacheck - #- misspell + - misspell #- nakedret #- noctx - #- nolintlint + - nolintlint #- rowserrcheck #- scopelint - #- staticcheck - - structcheck - #- stylecheck + - staticcheck + #- structcheck ! deprecated since v1.49.0; replaced by 'unused' + - stylecheck #- typecheck - unconvert #- unparam - #- unused - - varcheck + - unused + # - varcheck ! deprecated since v1.49.0; replaced by 'unused' #- whitespace fast: false diff --git a/tools/vendor/github.com/spf13/cobra/README.md b/tools/vendor/github.com/spf13/cobra/README.md index 592c0b8ab..6444f4b7f 100644 --- a/tools/vendor/github.com/spf13/cobra/README.md +++ b/tools/vendor/github.com/spf13/cobra/README.md @@ -4,7 +4,7 @@ Cobra is a library for creating powerful modern CLI applications. Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), [Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to -name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. +name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra. [![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) [![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) @@ -80,7 +80,7 @@ which maintains the same interface while adding POSIX compliance. # Installing Using Cobra is easy. First, use `go get` to install the latest version -of the library. +of the library. ``` go get -u github.com/spf13/cobra@latest @@ -105,8 +105,8 @@ go install github.com/spf13/cobra-cli@latest For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) -For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md). +For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md). # License -Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) +Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt) diff --git a/tools/vendor/github.com/spf13/cobra/active_help.go b/tools/vendor/github.com/spf13/cobra/active_help.go index 2d0239437..25c30e3cc 100644 --- a/tools/vendor/github.com/spf13/cobra/active_help.go +++ b/tools/vendor/github.com/spf13/cobra/active_help.go @@ -17,15 +17,14 @@ package cobra import ( "fmt" "os" - "strings" ) const ( activeHelpMarker = "_activeHelp_ " // The below values should not be changed: programs will be using them explicitly // in their user documentation, and users will be using them explicitly. - activeHelpEnvVarSuffix = "_ACTIVE_HELP" - activeHelpGlobalEnvVar = "COBRA_ACTIVE_HELP" + activeHelpEnvVarSuffix = "ACTIVE_HELP" + activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix activeHelpGlobalDisable = "0" ) @@ -42,7 +41,7 @@ func AppendActiveHelp(compArray []string, activeHelpStr string) []string { // GetActiveHelpConfig returns the value of the ActiveHelp environment variable // _ACTIVE_HELP where is the name of the root command in upper -// case, with all - replaced by _. +// case, with all non-ASCII-alphanumeric characters replaced by `_`. // It will always return "0" if the global environment variable COBRA_ACTIVE_HELP // is set to "0". func GetActiveHelpConfig(cmd *Command) string { @@ -55,9 +54,7 @@ func GetActiveHelpConfig(cmd *Command) string { // activeHelpEnvVar returns the name of the program-specific ActiveHelp environment // variable. It has the format _ACTIVE_HELP where is the name of the -// root command in upper case, with all - replaced by _. +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. func activeHelpEnvVar(name string) string { - // This format should not be changed: users will be using it explicitly. - activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix)) - return strings.ReplaceAll(activeHelpEnvVar, "-", "_") + return configEnvVar(name, activeHelpEnvVarSuffix) } diff --git a/tools/vendor/github.com/spf13/cobra/active_help.md b/tools/vendor/github.com/spf13/cobra/active_help.md deleted file mode 100644 index 5e7f59af3..000000000 --- a/tools/vendor/github.com/spf13/cobra/active_help.md +++ /dev/null @@ -1,157 +0,0 @@ -# Active Help - -Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion. - -For example, -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding. - -bash-5.1$ bin/helm package [tab] -Please specify the path to the chart to package - -bash-5.1$ bin/helm package [tab][tab] -bin/ internal/ scripts/ pkg/ testdata/ -``` - -**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program. -## Supported shells - -Active Help is currently only supported for the following shells: -- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed. -- Zsh - -## Adding Active Help messages - -As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md). - -Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details. - -### Active Help for nouns - -Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example: - -```go -cmd := &cobra.Command{ - Use: "add [NAME] [URL]", - Short: "add a chart repository", - Args: require.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - return addRepo(args) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - var comps []string - if len(args) == 0 { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } else if len(args) == 1 { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } else { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - return comps, cobra.ShellCompDirectiveNoFileComp - }, -} -``` -The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior: -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding - -bash-5.1$ helm repo add grafana [tab] -You must specify the URL for the repo you are adding - -bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab] -This command does not take any more arguments -``` -**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions. - -### Active Help for flags - -Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example: -```go -_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 2 { - return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp - } - return compVersionFlag(args[1], toComplete) - }) -``` -The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag. -``` -bash-5.1$ bin/helm install myrelease --version 2.0.[tab] -You must first specify the chart to install before the --version flag can be completed - -bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab] -2.0.1 2.0.2 2.0.3 -``` - -## User control of Active Help - -You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any. -Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration. - -The way to configure Active Help is to use the program's Active Help environment -variable. That variable is named `_ACTIVE_HELP` where `` is the name of your -program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever -Active Help configuration values are supported by the program. - -For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user -would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell. - -For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the -Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages -should or should not be added (instead of reading the environment variable directly). - -For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - activeHelpLevel := cobra.GetActiveHelpConfig(cmd) - - var comps []string - if len(args) == 0 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } - } else if len(args) == 1 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } - } else { - if activeHelpLevel == "local" { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - } - return comps, cobra.ShellCompDirectiveNoFileComp -}, -``` -**Note 1**: If the `_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly. - -**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `_ACTIVE_HELP` is set to. - -**Note 3**: If the user does not set `_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. -## Active Help with Cobra's default completion command - -Cobra provides a default `completion` command for programs that wish to use it. -When using the default `completion` command, Active Help is configurable in the same -fashion as described above using environment variables. You may wish to document this in more -details for your users. - -## Debugging Active Help - -Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details. - -When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below: -``` -$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -_activeHelp_ WARNING: cannot re-use a name that is still in use -:0 -Completion ended with directive: ShellCompDirectiveDefault - -$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -:0 -Completion ended with directive: ShellCompDirectiveDefault -``` diff --git a/tools/vendor/github.com/spf13/cobra/args.go b/tools/vendor/github.com/spf13/cobra/args.go index e79ec33a8..ed1e70cea 100644 --- a/tools/vendor/github.com/spf13/cobra/args.go +++ b/tools/vendor/github.com/spf13/cobra/args.go @@ -52,9 +52,9 @@ func OnlyValidArgs(cmd *Command, args []string) error { if len(cmd.ValidArgs) > 0 { // Remove any description that may be included in ValidArgs. // A description is following a tab character. - var validArgs []string + validArgs := make([]string, 0, len(cmd.ValidArgs)) for _, v := range cmd.ValidArgs { - validArgs = append(validArgs, strings.Split(v, "\t")[0]) + validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0]) } for _, v := range args { if !stringInSlice(v, validArgs) { diff --git a/tools/vendor/github.com/spf13/cobra/bash_completions.go b/tools/vendor/github.com/spf13/cobra/bash_completions.go index 10c78847d..f4d198cbc 100644 --- a/tools/vendor/github.com/spf13/cobra/bash_completions.go +++ b/tools/vendor/github.com/spf13/cobra/bash_completions.go @@ -85,7 +85,7 @@ __%[1]s_handle_go_custom_completion() local out requestComp lastParam lastChar comp directive args # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + # Calling ${words[0]} instead of directly %[1]s allows handling aliases args=("${words[@]:1}") # Disable ActiveHelp which is not supported for bash completion v1 requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}" @@ -597,19 +597,16 @@ func writeRequiredFlag(buf io.StringWriter, cmd *Command) { if nonCompletableFlag(flag) { return } - for key := range flag.Annotations { - switch key { - case BashCompOneRequiredFlag: - format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) - - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) - } + if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok { + format := " must_have_one_flag+=(\"--%s" + if flag.Value.Type() != "bool" { + format += "=" + } + format += cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) + + if len(flag.Shorthand) > 0 { + WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) } } }) @@ -621,7 +618,7 @@ func writeRequiredNouns(buf io.StringWriter, cmd *Command) { for _, value := range cmd.ValidArgs { // Remove any description that may be included following a tab character. // Descriptions are not supported by bash completion. - value = strings.Split(value, "\t")[0] + value = strings.SplitN(value, "\t", 2)[0] WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) } if cmd.ValidArgsFunction != nil { diff --git a/tools/vendor/github.com/spf13/cobra/bash_completions.md b/tools/vendor/github.com/spf13/cobra/bash_completions.md deleted file mode 100644 index 52919b2fa..000000000 --- a/tools/vendor/github.com/spf13/cobra/bash_completions.md +++ /dev/null @@ -1,93 +0,0 @@ -# Generating Bash Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution. - -**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own. - -The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions. - -Some code that works in kubernetes: - -```bash -const ( - bash_completion_func = `__kubectl_parse_get() -{ - local kubectl_output out - if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then - out=($(echo "${kubectl_output}" | awk '{print $1}')) - COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) ) - fi -} - -__kubectl_get_resource() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - return 1 - fi - __kubectl_parse_get ${nouns[${#nouns[@]} -1]} - if [[ $? -eq 0 ]]; then - return 0 - fi -} - -__kubectl_custom_func() { - case ${last_command} in - kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop) - __kubectl_get_resource - return - ;; - *) - ;; - esac -} -`) -``` - -And then I set that in my command definition: - -```go -cmds := &cobra.Command{ - Use: "kubectl", - Short: "kubectl controls the Kubernetes cluster manager", - Long: `kubectl controls the Kubernetes cluster manager. - -Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, - Run: runHelp, - BashCompletionFunction: bash_completion_func, -} -``` - -The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods! - -Similarly, for flags: - -```go - annotation := make(map[string][]string) - annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"} - - flag := &pflag.Flag{ - Name: "namespace", - Usage: usage, - Annotations: annotation, - } - cmd.Flags().AddFlag(flag) -``` - -In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction` -value, e.g.: - -```bash -__kubectl_get_namespaces() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) - fi -} -``` diff --git a/tools/vendor/github.com/spf13/cobra/bash_completionsV2.go b/tools/vendor/github.com/spf13/cobra/bash_completionsV2.go index 19b09560c..1cce5c329 100644 --- a/tools/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ b/tools/vendor/github.com/spf13/cobra/bash_completionsV2.go @@ -57,7 +57,7 @@ __%[1]s_get_completion_results() { local requestComp lastParam lastChar args # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + # Calling ${words[0]} instead of directly %[1]s allows handling aliases args=("${words[@]:1}") requestComp="${words[0]} %[2]s ${args[*]}" diff --git a/tools/vendor/github.com/spf13/cobra/cobra.go b/tools/vendor/github.com/spf13/cobra/cobra.go index b07b44a0c..e0b0947b0 100644 --- a/tools/vendor/github.com/spf13/cobra/cobra.go +++ b/tools/vendor/github.com/spf13/cobra/cobra.go @@ -43,12 +43,13 @@ var initializers []func() var finalizers []func() const ( - defaultPrefixMatching = false - defaultCommandSorting = true - defaultCaseInsensitive = false + defaultPrefixMatching = false + defaultCommandSorting = true + defaultCaseInsensitive = false + defaultTraverseRunHooks = false ) -// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing +// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing // to automatically enable in CLI tools. // Set this to true to enable it. var EnablePrefixMatching = defaultPrefixMatching @@ -60,6 +61,10 @@ var EnableCommandSorting = defaultCommandSorting // EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default) var EnableCaseInsensitive = defaultCaseInsensitive +// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents. +// By default this is disabled, which means only the first run hook to be found is executed. +var EnableTraverseRunHooks = defaultTraverseRunHooks + // MousetrapHelpText enables an information splash screen on Windows // if the CLI is started from explorer.exe. // To disable the mousetrap, just set this variable to blank string (""). @@ -188,8 +193,6 @@ func ld(s, t string, ignoreCase bool) int { d := make([][]int, len(s)+1) for i := range d { d[i] = make([]int, len(t)+1) - } - for i := range d { d[i][0] = i } for j := range d[0] { diff --git a/tools/vendor/github.com/spf13/cobra/command.go b/tools/vendor/github.com/spf13/cobra/command.go index 01f7c6f1c..54748fc67 100644 --- a/tools/vendor/github.com/spf13/cobra/command.go +++ b/tools/vendor/github.com/spf13/cobra/command.go @@ -30,7 +30,10 @@ import ( flag "github.com/spf13/pflag" ) -const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" +const ( + FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" + CommandDisplayNameAnnotation = "cobra_annotation_command_display_name" +) // FParseErrWhitelist configures Flag parse errors to be ignored type FParseErrWhitelist flag.ParseErrorsWhitelist @@ -99,7 +102,7 @@ type Command struct { Deprecated string // Annotations are key/value pairs that can be used by applications to identify or - // group commands. + // group commands or set special options. Annotations map[string]string // Version defines the version for this command. If this value is non-empty and the command does not @@ -115,6 +118,8 @@ type Command struct { // * PostRun() // * PersistentPostRun() // All functions get the same args, the arguments after the command name. + // The *PreRun and *PostRun functions will only be executed if the Run function of the current + // command has been declared. // // PersistentPreRun: children of this command will inherit and execute. PersistentPreRun func(cmd *Command, args []string) @@ -149,8 +154,10 @@ type Command struct { // pflags contains persistent flags. pflags *flag.FlagSet // lflags contains local flags. + // This field does not represent internal state, it's used as a cache to optimise LocalFlags function call lflags *flag.FlagSet // iflags contains inherited flags. + // This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call iflags *flag.FlagSet // parentsPflags is all persistent flags of cmd's parents. parentsPflags *flag.FlagSet @@ -181,6 +188,9 @@ type Command struct { // versionTemplate is the version template defined by user. versionTemplate string + // errPrefix is the error message prefix defined by user. + errPrefix string + // inReader is a reader defined by the user that replaces stdin inReader io.Reader // outWriter is a writer defined by the user that replaces stdout @@ -346,6 +356,11 @@ func (c *Command) SetVersionTemplate(s string) { c.versionTemplate = s } +// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. +func (c *Command) SetErrPrefix(s string) { + c.errPrefix = s +} + // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. // The user should not have a cyclic dependency on commands. func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { @@ -595,6 +610,18 @@ func (c *Command) VersionTemplate() string { ` } +// ErrPrefix return error message prefix for the command +func (c *Command) ErrPrefix() string { + if c.errPrefix != "" { + return c.errPrefix + } + + if c.HasParent() { + return c.parent.ErrPrefix() + } + return "Error:" +} + func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { flag := fs.Lookup(name) if flag == nil { @@ -681,7 +708,7 @@ Loop: // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so, // return the args, excluding the one at this position. if s == x { - ret := []string{} + ret := make([]string, 0, len(args)-1) ret = append(ret, args[:pos]...) ret = append(ret, args[pos+1:]...) return ret @@ -729,14 +756,14 @@ func (c *Command) findSuggestions(arg string) string { if c.SuggestionsMinimumDistance <= 0 { c.SuggestionsMinimumDistance = 2 } - suggestionsString := "" + var sb strings.Builder if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - suggestionsString += "\n\nDid you mean this?\n" + sb.WriteString("\n\nDid you mean this?\n") for _, s := range suggestions { - suggestionsString += fmt.Sprintf("\t%v\n", s) + _, _ = fmt.Fprintf(&sb, "\t%v\n", s) } } - return suggestionsString + return sb.String() } func (c *Command) findNext(next string) *Command { @@ -752,7 +779,9 @@ func (c *Command) findNext(next string) *Command { } if len(matches) == 1 { - return matches[0] + // Temporarily disable gosec G602, which produces a false positive. + // See https://github.com/securego/gosec/issues/1005. + return matches[0] // #nosec G602 } return nil @@ -846,7 +875,7 @@ func (c *Command) ArgsLenAtDash() int { func (c *Command) execute(a []string) (err error) { if c == nil { - return fmt.Errorf("Called Execute() on a nil Command") + return fmt.Errorf("called Execute() on a nil Command") } if len(c.Deprecated) > 0 { @@ -910,15 +939,31 @@ func (c *Command) execute(a []string) (err error) { return err } + parents := make([]*Command, 0, 5) for p := c; p != nil; p = p.Parent() { + if EnableTraverseRunHooks { + // When EnableTraverseRunHooks is set: + // - Execute all persistent pre-runs from the root parent till this command. + // - Execute all persistent post-runs from this command till the root parent. + parents = append([]*Command{p}, parents...) + } else { + // Otherwise, execute only the first found persistent hook. + parents = append(parents, p) + } + } + for _, p := range parents { if p.PersistentPreRunE != nil { if err := p.PersistentPreRunE(c, argWoFlags); err != nil { return err } - break + if !EnableTraverseRunHooks { + break + } } else if p.PersistentPreRun != nil { p.PersistentPreRun(c, argWoFlags) - break + if !EnableTraverseRunHooks { + break + } } } if c.PreRunE != nil { @@ -955,10 +1000,14 @@ func (c *Command) execute(a []string) (err error) { if err := p.PersistentPostRunE(c, argWoFlags); err != nil { return err } - break + if !EnableTraverseRunHooks { + break + } } else if p.PersistentPostRun != nil { p.PersistentPostRun(c, argWoFlags) - break + if !EnableTraverseRunHooks { + break + } } } @@ -1048,7 +1097,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { c = cmd } if !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) + c.PrintErrln(c.ErrPrefix(), err.Error()) c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) } return c, err @@ -1077,7 +1126,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { // If root command has SilenceErrors flagged, // all subcommands should respect it if !cmd.SilenceErrors && !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) + c.PrintErrln(cmd.ErrPrefix(), err.Error()) } // If root command has SilenceUsage flagged, @@ -1140,10 +1189,11 @@ func (c *Command) InitDefaultHelpFlag() { c.mergePersistentFlags() if c.Flags().Lookup("help") == nil { usage := "help for " - if c.Name() == "" { + name := c.displayName() + if name == "" { usage += "this command" } else { - usage += c.Name() + usage += name } c.Flags().BoolP("help", "h", false, usage) _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"}) @@ -1189,7 +1239,7 @@ func (c *Command) InitDefaultHelpCmd() { Use: "help [command]", Short: "Help about any command", Long: `Help provides help for any command in the application. -Simply type ` + c.Name() + ` help [path to command] for full details.`, +Simply type ` + c.displayName() + ` help [path to command] for full details.`, ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) { var completions []string cmd, _, e := c.Root().Find(args) @@ -1380,16 +1430,24 @@ func (c *Command) CommandPath() string { if c.HasParent() { return c.Parent().CommandPath() + " " + c.Name() } + return c.displayName() +} + +func (c *Command) displayName() string { + if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok { + return displayName + } return c.Name() } // UseLine puts out the full usage for a given command (including parents). func (c *Command) UseLine() string { var useline string + use := strings.Replace(c.Use, c.Name(), c.displayName(), 1) if c.HasParent() { - useline = c.parent.CommandPath() + " " + c.Use + useline = c.parent.CommandPath() + " " + use } else { - useline = c.Use + useline = use } if c.DisableFlagsInUseLine { return useline @@ -1591,7 +1649,7 @@ func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) f // to this command (local and persistent declared here and by all parents). func (c *Command) Flags() *flag.FlagSet { if c.flags == nil { - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1602,10 +1660,11 @@ func (c *Command) Flags() *flag.FlagSet { } // LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { persistentFlags := c.PersistentFlags() - out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) + out := flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.LocalFlags().VisitAll(func(f *flag.Flag) { if persistentFlags.Lookup(f.Name) == nil { out.AddFlag(f) @@ -1615,11 +1674,12 @@ func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { } // LocalFlags returns the local FlagSet specifically set in the current command. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) LocalFlags() *flag.FlagSet { c.mergePersistentFlags() if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.lflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1642,11 +1702,12 @@ func (c *Command) LocalFlags() *flag.FlagSet { } // InheritedFlags returns all flags which were inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) InheritedFlags() *flag.FlagSet { c.mergePersistentFlags() if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.iflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1667,6 +1728,7 @@ func (c *Command) InheritedFlags() *flag.FlagSet { } // NonInheritedFlags returns all flags which were not inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. func (c *Command) NonInheritedFlags() *flag.FlagSet { return c.LocalFlags() } @@ -1674,7 +1736,7 @@ func (c *Command) NonInheritedFlags() *flag.FlagSet { // PersistentFlags returns the persistent FlagSet specifically set in the current command. func (c *Command) PersistentFlags() *flag.FlagSet { if c.pflags == nil { - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } @@ -1687,9 +1749,9 @@ func (c *Command) PersistentFlags() *flag.FlagSet { func (c *Command) ResetFlags() { c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf.Reset() - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.pflags.SetOutput(c.flagErrorBuf) c.lflags = nil @@ -1806,7 +1868,7 @@ func (c *Command) mergePersistentFlags() { // If c.parentsPflags == nil, it makes new. func (c *Command) updateParentsPflags() { if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) + c.parentsPflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) c.parentsPflags.SetOutput(c.flagErrorBuf) c.parentsPflags.SortFlags = false } diff --git a/tools/vendor/github.com/spf13/cobra/completions.go b/tools/vendor/github.com/spf13/cobra/completions.go index ee38c4d0b..c0c08b057 100644 --- a/tools/vendor/github.com/spf13/cobra/completions.go +++ b/tools/vendor/github.com/spf13/cobra/completions.go @@ -17,6 +17,8 @@ package cobra import ( "fmt" "os" + "regexp" + "strconv" "strings" "sync" @@ -145,6 +147,20 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman return nil } +// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. +func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) { + flag := c.Flag(flagName) + if flag == nil { + return nil, false + } + + flagCompletionMutex.RLock() + defer flagCompletionMutex.RUnlock() + + completionFunc, exists := flagCompletionFunctions[flag] + return completionFunc, exists +} + // Returns a string listing the different directive enabled in the specified parameter func (d ShellCompDirective) string() string { var directives []string @@ -197,24 +213,29 @@ func (c *Command) initCompleteCmd(args []string) { // 2- Even without completions, we need to print the directive } - noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) + noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd + if !noDescriptions { + if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil { + noDescriptions = !doDescriptions + } + } + noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable + out := finalCmd.OutOrStdout() for _, comp := range completions { - if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable { - // Remove all activeHelp entries in this case - if strings.HasPrefix(comp, activeHelpMarker) { - continue - } + if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) { + // Remove all activeHelp entries if it's disabled. + continue } if noDescriptions { // Remove any description that may be included following a tab character. - comp = strings.Split(comp, "\t")[0] + comp = strings.SplitN(comp, "\t", 2)[0] } // Make sure we only write the first line to the output. // This is needed if a description contains a linebreak. // Otherwise the shell scripts will interpret the other lines as new flags // and could therefore provide a wrong completion. - comp = strings.Split(comp, "\n")[0] + comp = strings.SplitN(comp, "\n", 2)[0] // Finally trim the completion. This is especially important to get rid // of a trailing tab when there are no description following it. @@ -223,14 +244,14 @@ func (c *Command) initCompleteCmd(args []string) { // although there is no description). comp = strings.TrimSpace(comp) - // Print each possible completion to stdout for the completion script to consume. - fmt.Fprintln(finalCmd.OutOrStdout(), comp) + // Print each possible completion to the output for the completion script to consume. + fmt.Fprintln(out, comp) } // As the last printout, print the completion directive for the completion script to parse. // The directive integer must be that last character following a single colon (:). // The completion script expects : - fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive) + fmt.Fprintf(out, ":%d\n", directive) // Print some helpful info to stderr for the user to understand. // Output from stderr must be ignored by the completion script. @@ -277,15 +298,19 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi } if err != nil { // Unable to find the real command. E.g., someInvalidCmd - return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) + return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs) } finalCmd.ctx = c.ctx // These flags are normally added when `execute()` is called on `finalCmd`, // however, when doing completion, we don't call `finalCmd.execute()`. - // Let's add the --help and --version flag ourselves. - finalCmd.InitDefaultHelpFlag() - finalCmd.InitDefaultVersionFlag() + // Let's add the --help and --version flag ourselves but only if the finalCmd + // has not disabled flag parsing; if flag parsing is disabled, it is up to the + // finalCmd itself to handle the completion of *all* flags. + if !finalCmd.DisableFlagParsing { + finalCmd.InitDefaultHelpFlag() + finalCmd.InitDefaultVersionFlag() + } // Check if we are doing flag value completion before parsing the flags. // This is important because if we are completing a flag value, we need to also @@ -389,6 +414,11 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { doCompleteFlags(flag) }) + // Try to complete non-inherited flags even if DisableFlagParsing==true. + // This allows programs to tell Cobra about flags for completion even + // if the actual parsing of flags is not done by Cobra. + // For instance, Helm uses this to provide flag name completion for + // some of its plugins. finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { doCompleteFlags(flag) }) @@ -876,3 +906,34 @@ func CompError(msg string) { func CompErrorln(msg string) { CompError(fmt.Sprintf("%s\n", msg)) } + +// These values should not be changed: users will be using them explicitly. +const ( + configEnvVarGlobalPrefix = "COBRA" + configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS" +) + +var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`) + +// configEnvVar returns the name of the program-specific configuration environment +// variable. It has the format _ where is the name of the +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. +func configEnvVar(name, suffix string) string { + // This format should not be changed: users will be using it explicitly. + v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix)) + v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_") + return v +} + +// getEnvConfig returns the value of the configuration environment variable +// _ where is the name of the root command in upper +// case, with all non-ASCII-alphanumeric characters replaced by `_`. +// If the value is empty or not set, the value of the environment variable +// COBRA_ is returned instead. +func getEnvConfig(cmd *Command, suffix string) string { + v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix)) + if v == "" { + v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix)) + } + return v +} diff --git a/tools/vendor/github.com/spf13/cobra/fish_completions.go b/tools/vendor/github.com/spf13/cobra/fish_completions.go index 12ca0d2b1..12d61b691 100644 --- a/tools/vendor/github.com/spf13/cobra/fish_completions.go +++ b/tools/vendor/github.com/spf13/cobra/fish_completions.go @@ -113,7 +113,7 @@ function __%[1]s_clear_perform_completion_once_result __%[1]s_debug "" __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable ==========" set --erase __%[1]s_perform_completion_once_result - __%[1]s_debug "Succesfully erased the variable __%[1]s_perform_completion_once_result" + __%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result" end function __%[1]s_requires_order_preservation diff --git a/tools/vendor/github.com/spf13/cobra/fish_completions.md b/tools/vendor/github.com/spf13/cobra/fish_completions.md deleted file mode 100644 index 19b2ed129..000000000 --- a/tools/vendor/github.com/spf13/cobra/fish_completions.md +++ /dev/null @@ -1,4 +0,0 @@ -## Generating Fish Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - diff --git a/tools/vendor/github.com/spf13/cobra/flag_groups.go b/tools/vendor/github.com/spf13/cobra/flag_groups.go index b35fde155..560612fd3 100644 --- a/tools/vendor/github.com/spf13/cobra/flag_groups.go +++ b/tools/vendor/github.com/spf13/cobra/flag_groups.go @@ -23,8 +23,9 @@ import ( ) const ( - requiredAsGroup = "cobra_annotation_required_if_others_set" - mutuallyExclusive = "cobra_annotation_mutually_exclusive" + requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" + oneRequiredAnnotation = "cobra_annotation_one_required" + mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive" ) // MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors @@ -36,7 +37,23 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) { if f == nil { panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v)) } - if err := c.Flags().SetAnnotation(v, requiredAsGroup, append(f.Annotations[requiredAsGroup], strings.Join(flagNames, " "))); err != nil { + if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil { + // Only errs if the flag isn't found. + panic(err) + } + } +} + +// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors +// if the command is invoked without at least one flag from the given set of flags. +func (c *Command) MarkFlagsOneRequired(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v)) + } + if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil { // Only errs if the flag isn't found. panic(err) } @@ -53,13 +70,13 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v)) } // Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed. - if err := c.Flags().SetAnnotation(v, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil { + if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil { panic(err) } } } -// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the +// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the // first error encountered. func (c *Command) ValidateFlagGroups() error { if c.DisableFlagParsing { @@ -71,15 +88,20 @@ func (c *Command) ValidateFlagGroups() error { // groupStatus format is the list of flags as a unique ID, // then a map of each flag name and whether it is set or not. groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} flags.VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) }) if err := validateRequiredFlagGroups(groupStatus); err != nil { return err } + if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil { + return err + } if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { return err } @@ -108,7 +130,7 @@ func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annota continue } - groupStatus[group] = map[string]bool{} + groupStatus[group] = make(map[string]bool, len(flagnames)) for _, name := range flagnames { groupStatus[group][name] = false } @@ -142,6 +164,27 @@ func validateRequiredFlagGroups(data map[string]map[string]bool) error { return nil } +func validateOneRequiredFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + var set []string + for flagname, isSet := range flagnameAndStatus { + if isSet { + set = append(set, flagname) + } + } + if len(set) >= 1 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(set) + return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList) + } + return nil +} + func validateExclusiveFlagGroups(data map[string]map[string]bool) error { keys := sortedKeys(data) for _, flagList := range keys { @@ -176,6 +219,7 @@ func sortedKeys(m map[string]map[string]bool) []string { // enforceFlagGroupsForCompletion will do the following: // - when a flag in a group is present, other flags in the group will be marked required +// - when none of the flags in a one-required group are present, all flags in the group will be marked required // - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden // This allows the standard completion logic to behave appropriately for flag groups func (c *Command) enforceFlagGroupsForCompletion() { @@ -185,10 +229,12 @@ func (c *Command) enforceFlagGroupsForCompletion() { flags := c.Flags() groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} mutuallyExclusiveGroupStatus := map[string]map[string]bool{} c.Flags().VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) }) // If a flag that is part of a group is present, we make all the other flags @@ -204,6 +250,26 @@ func (c *Command) enforceFlagGroupsForCompletion() { } } + // If none of the flags of a one-required group are present, we make all the flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range oneRequiredGroupStatus { + isSet := false + + for _, isSet = range flagnameAndStatus { + if isSet { + break + } + } + + // None of the flags of the group are set, mark all flags in the group + // as required + if !isSet { + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + // If a flag that is mutually exclusive to others is present, we hide the other // flags of that group so the shell completion does not suggest them for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { diff --git a/tools/vendor/github.com/spf13/cobra/powershell_completions.go b/tools/vendor/github.com/spf13/cobra/powershell_completions.go index 177d2755f..a830b7bca 100644 --- a/tools/vendor/github.com/spf13/cobra/powershell_completions.go +++ b/tools/vendor/github.com/spf13/cobra/powershell_completions.go @@ -28,8 +28,8 @@ import ( func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { // Variables should not contain a '-' or ':' character nameForVar := name - nameForVar = strings.Replace(nameForVar, "-", "_", -1) - nameForVar = strings.Replace(nameForVar, ":", "_", -1) + nameForVar = strings.ReplaceAll(nameForVar, "-", "_") + nameForVar = strings.ReplaceAll(nameForVar, ":", "_") compCmd := ShellCompRequestCmd if !includeDesc { @@ -47,7 +47,7 @@ filter __%[1]s_escapeStringWithSpecialChars { `+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` } -[scriptblock]$__%[2]sCompleterBlock = { +[scriptblock]${__%[2]sCompleterBlock} = { param( $WordToComplete, $CommandAst, @@ -122,7 +122,7 @@ filter __%[1]s_escapeStringWithSpecialChars { __%[1]s_debug "Calling $RequestComp" # First disable ActiveHelp which is not supported for Powershell - $env:%[10]s=0 + ${env:%[10]s}=0 #call the command store the output in $out and redirect stderr and stdout to null # $Out is an array contains each line per element @@ -279,7 +279,7 @@ filter __%[1]s_escapeStringWithSpecialChars { } } -Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock $__%[2]sCompleterBlock +Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock} `, name, nameForVar, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) diff --git a/tools/vendor/github.com/spf13/cobra/powershell_completions.md b/tools/vendor/github.com/spf13/cobra/powershell_completions.md deleted file mode 100644 index c449f1e5c..000000000 --- a/tools/vendor/github.com/spf13/cobra/powershell_completions.md +++ /dev/null @@ -1,3 +0,0 @@ -# Generating PowerShell Completions For Your Own cobra.Command - -Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details. diff --git a/tools/vendor/github.com/spf13/cobra/projects_using_cobra.md b/tools/vendor/github.com/spf13/cobra/projects_using_cobra.md deleted file mode 100644 index 8a291eb20..000000000 --- a/tools/vendor/github.com/spf13/cobra/projects_using_cobra.md +++ /dev/null @@ -1,64 +0,0 @@ -## Projects using Cobra - -- [Allero](https://github.com/allero-io/allero) -- [Arewefastyet](https://benchmark.vitess.io) -- [Arduino CLI](https://github.com/arduino/arduino-cli) -- [Bleve](https://blevesearch.com/) -- [Cilium](https://cilium.io/) -- [CloudQuery](https://github.com/cloudquery/cloudquery) -- [CockroachDB](https://www.cockroachlabs.com/) -- [Constellation](https://github.com/edgelesssys/constellation) -- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) -- [Datree](https://github.com/datreeio/datree) -- [Delve](https://github.com/derekparker/delve) -- [Docker (distribution)](https://github.com/docker/distribution) -- [Etcd](https://etcd.io/) -- [Gardener](https://github.com/gardener/gardenctl) -- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) -- [Git Bump](https://github.com/erdaltsksn/git-bump) -- [GitHub CLI](https://github.com/cli/cli) -- [GitHub Labeler](https://github.com/erdaltsksn/gh-label) -- [Golangci-lint](https://golangci-lint.run) -- [GopherJS](https://github.com/gopherjs/gopherjs) -- [GoReleaser](https://goreleaser.com) -- [Helm](https://helm.sh) -- [Hugo](https://gohugo.io) -- [Infracost](https://github.com/infracost/infracost) -- [Istio](https://istio.io) -- [Kool](https://github.com/kool-dev/kool) -- [Kubernetes](https://kubernetes.io/) -- [Kubescape](https://github.com/kubescape/kubescape) -- [KubeVirt](https://github.com/kubevirt/kubevirt) -- [Linkerd](https://linkerd.io/) -- [Mattermost-server](https://github.com/mattermost/mattermost-server) -- [Mercure](https://mercure.rocks/) -- [Meroxa CLI](https://github.com/meroxa/cli) -- [Metal Stack CLI](https://github.com/metal-stack/metalctl) -- [Moby (former Docker)](https://github.com/moby/moby) -- [Moldy](https://github.com/Moldy-Community/moldy) -- [Multi-gitter](https://github.com/lindell/multi-gitter) -- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) -- [nFPM](https://nfpm.goreleaser.com) -- [Okteto](https://github.com/okteto/okteto) -- [OpenShift](https://www.openshift.com/) -- [Ory Hydra](https://github.com/ory/hydra) -- [Ory Kratos](https://github.com/ory/kratos) -- [Pixie](https://github.com/pixie-io/pixie) -- [Polygon Edge](https://github.com/0xPolygon/polygon-edge) -- [Pouch](https://github.com/alibaba/pouch) -- [ProjectAtomic (enterprise)](https://www.projectatomic.io/) -- [Prototool](https://github.com/uber/prototool) -- [Pulumi](https://www.pulumi.com) -- [QRcp](https://github.com/claudiodangelis/qrcp) -- [Random](https://github.com/erdaltsksn/random) -- [Rclone](https://rclone.org/) -- [Scaleway CLI](https://github.com/scaleway/scaleway-cli) -- [Sia](https://github.com/SiaFoundation/siad) -- [Skaffold](https://skaffold.dev/) -- [Tendermint](https://github.com/tendermint/tendermint) -- [Twitch CLI](https://github.com/twitchdev/twitch-cli) -- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli) -- [Vitess](https://vitess.io) -- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework) -- [Werf](https://werf.io/) -- [ZITADEL](https://github.com/zitadel/zitadel) diff --git a/tools/vendor/github.com/spf13/cobra/shell_completions.md b/tools/vendor/github.com/spf13/cobra/shell_completions.md deleted file mode 100644 index 065c0621d..000000000 --- a/tools/vendor/github.com/spf13/cobra/shell_completions.md +++ /dev/null @@ -1,576 +0,0 @@ -# Generating shell completions - -Cobra can generate shell completions for multiple shells. -The currently supported shells are: -- Bash -- Zsh -- fish -- PowerShell - -Cobra will automatically provide your program with a fully functional `completion` command, -similarly to how it provides the `help` command. - -## Creating your own completion command - -If you do not wish to use the default `completion` command, you can choose to -provide your own, which will take precedence over the default one. (This also provides -backwards-compatibility with programs that already have their own `completion` command.) - -If you are using the `cobra-cli` generator, -which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli), -you can create a completion command by running - -```bash -cobra-cli add completion -``` -and then modifying the generated `cmd/completion.go` file to look something like this -(writing the shell script to stdout allows the most flexible use): - -```go -var completionCmd = &cobra.Command{ - Use: "completion [bash|zsh|fish|powershell]", - Short: "Generate completion script", - Long: fmt.Sprintf(`To load completions: - -Bash: - - $ source <(%[1]s completion bash) - - # To load completions for each session, execute once: - # Linux: - $ %[1]s completion bash > /etc/bash_completion.d/%[1]s - # macOS: - $ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s - -Zsh: - - # If shell completion is not already enabled in your environment, - # you will need to enable it. You can execute the following once: - - $ echo "autoload -U compinit; compinit" >> ~/.zshrc - - # To load completions for each session, execute once: - $ %[1]s completion zsh > "${fpath[1]}/_%[1]s" - - # You will need to start a new shell for this setup to take effect. - -fish: - - $ %[1]s completion fish | source - - # To load completions for each session, execute once: - $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish - -PowerShell: - - PS> %[1]s completion powershell | Out-String | Invoke-Expression - - # To load completions for every new session, run: - PS> %[1]s completion powershell > %[1]s.ps1 - # and source this file from your PowerShell profile. -`,cmd.Root().Name()), - DisableFlagsInUseLine: true, - ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, - Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), - Run: func(cmd *cobra.Command, args []string) { - switch args[0] { - case "bash": - cmd.Root().GenBashCompletion(os.Stdout) - case "zsh": - cmd.Root().GenZshCompletion(os.Stdout) - case "fish": - cmd.Root().GenFishCompletion(os.Stdout, true) - case "powershell": - cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) - } - }, -} -``` - -**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed. - -## Adapting the default completion command - -Cobra provides a few options for the default `completion` command. To configure such options you must set -the `CompletionOptions` field on the *root* command. - -To tell Cobra *not* to provide the default `completion` command: -``` -rootCmd.CompletionOptions.DisableDefaultCmd = true -``` - -To tell Cobra to mark the default `completion` command as *hidden*: -``` -rootCmd.CompletionOptions.HiddenDefaultCmd = true -``` - -To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: -``` -rootCmd.CompletionOptions.DisableNoDescFlag = true -``` - -To tell Cobra to completely disable descriptions for completions: -``` -rootCmd.CompletionOptions.DisableDescriptions = true -``` - -# Customizing completions - -The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values. - -## Completion of nouns - -### Static completion of nouns - -Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field. -For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. -Some simplified code from `kubectl get` looks like: - -```go -validArgs = []string{ "pod", "node", "service", "replicationcontroller" } - -cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - cobra.CheckErr(RunGet(f, out, cmd, args)) - }, - ValidArgs: validArgs, -} -``` - -Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like: - -```bash -$ kubectl get [tab][tab] -node pod replicationcontroller service -``` - -#### Aliases for nouns - -If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`. - -### Dynamic completion of nouns - -In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both. -Simplified code from `helm status` looks like: - -```go -cmd := &cobra.Command{ - Use: "status RELEASE_NAME", - Short: "Display the status of the named release", - Long: status_long, - RunE: func(cmd *cobra.Command, args []string) { - RunGet(args[0]) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 0 { - return nil, cobra.ShellCompDirectiveNoFileComp - } - return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp - }, -} -``` -Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster. -Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like: - -```bash -$ helm status [tab][tab] -harbor notary rook thanos -``` -You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp` -```go -// Indicates that the shell will perform its default behavior after completions -// have been provided (this implies none of the other directives). -ShellCompDirectiveDefault - -// Indicates an error occurred and completions should be ignored. -ShellCompDirectiveError - -// Indicates that the shell should not add a space after the completion, -// even if there is a single completion provided. -ShellCompDirectiveNoSpace - -// Indicates that the shell should not provide file completion even when -// no completion is provided. -ShellCompDirectiveNoFileComp - -// Indicates that the returned completions should be used as file extension filters. -// For example, to complete only files of the form *.json or *.yaml: -// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt -// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename() -// is a shortcut to using this directive explicitly. -// -ShellCompDirectiveFilterFileExt - -// Indicates that only directory names should be provided in file completion. -// For example: -// return nil, ShellCompDirectiveFilterDirs -// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly. -// -// To request directory names within another directory, the returned completions -// should specify a single directory name within which to search. For example, -// to complete directories within "themes/": -// return []string{"themes"}, ShellCompDirectiveFilterDirs -// -ShellCompDirectiveFilterDirs - -// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order -// in which the completions are provided -ShellCompDirectiveKeepOrder -``` - -***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. - -#### Debugging - -Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly: -```bash -$ helm __complete status har -harbor -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command: -```bash -$ helm __complete status "" -harbor -notary -rook -thanos -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code: -```go -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and optionally prints to stderr. -cobra.CompDebug(msg string, printToStdErr bool) { -cobra.CompDebugln(msg string, printToStdErr bool) - -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and to stderr. -cobra.CompError(msg string) -cobra.CompErrorln(msg string) -``` -***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above. - -## Completions for flags - -### Mark flags as required - -Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so: - -```go -cmd.MarkFlagRequired("pod") -cmd.MarkFlagRequired("container") -``` - -and you'll get something like - -```bash -$ kubectl exec [tab][tab] --c --container= -p --pod= -``` - -### Specify dynamic flag completion - -As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function. - -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault -}) -``` -Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: - -```bash -$ helm status --output [tab][tab] -json table yaml -``` - -#### Debugging - -You can also easily debug your Go completion code for flags: -```bash -$ helm __complete status --output "" -json -table -yaml -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above. - -### Specify valid filename extensions for flags that take a filename - -To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so: -```go -flagName := "output" -cmd.MarkFlagFilename(flagName, "yaml", "json") -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt}) -``` - -### Limit flag completions to directory names - -To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so: -```go -flagName := "output" -cmd.MarkFlagDirname(flagName) -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterDirs -}) -``` -To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so: -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs -}) -``` -### Descriptions for completions - -Cobra provides support for completion descriptions. Such descriptions are supported for each shell -(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)). -For commands and flags, Cobra will provide the descriptions automatically, based on usage information. -For example, using zsh: -``` -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release -``` -while using fish: -``` -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) -``` - -Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp -}} -``` -or -```go -ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"} -``` - -If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like: - -```bash -$ source <(helm completion bash) -$ helm completion [tab][tab] -bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell) -fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh) - -$ source <(helm completion bash --no-descriptions) -$ helm completion [tab][tab] -bash fish powershell zsh -``` -## Bash completions - -### Dependencies - -The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)) - -### Aliases - -You can also configure `bash` aliases for your program and they will also support completions. - -```bash -alias aliasname=origcommand -complete -o default -F __start_origcommand aliasname - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -### Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. -Please refer to [Bash Completions](bash_completions.md) for details. - -### Bash completion V2 - -Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling -`GenBashCompletion()` or `GenBashCompletionFile()`. - -A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or -`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion -(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion -solution described in this document. -Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash -completion V2 solution which provides the following extra features: -- Supports completion descriptions (like the other shells) -- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines) -- Streamlined user experience thanks to a completion behavior aligned with the other shells - -`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()` -you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra -will provide the description automatically based on usage information. You can choose to make this option configurable by -your users. - -``` -# With descriptions -$ helm s[tab][tab] -search (search for a keyword in charts) status (display the status of the named release) -show (show information of a chart) - -# Without descriptions -$ helm s[tab][tab] -search show status -``` -**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. -## Zsh completions - -Cobra supports native zsh completion generated from the root `cobra.Command`. -The generated completion script should be put somewhere in your `$fpath` and be named -`_`. You will need to start a new shell for the completions to become available. - -Zsh supports descriptions for completions. Cobra will provide the description automatically, -based on usage information. Cobra provides a way to completely disable such descriptions by -using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make -this a configurable option to your users. -``` -# With descriptions -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`. - * You should instead use `RegisterFlagCompletionFunc()`. - -### Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced. -Please refer to [Zsh Completions](zsh_completions.md) for details. - -## fish completions - -Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. -``` -# With descriptions -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `fish`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `fish`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) - -## PowerShell completions - -Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. - -The script is designed to support all three PowerShell completion modes: - -* TabCompleteNext (default windows style - on each key press the next option is displayed) -* Complete (works like bash) -* MenuComplete (works like zsh) - -You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function `. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode. - -Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles. - -``` -# With descriptions and Mode 'Complete' -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions. -$ helm s[tab] -search show status - -search for a keyword in charts - -# Without descriptions -$ helm s[tab] -search show status -``` -### Aliases - -You can also configure `powershell` aliases for your program and they will also support completions. - -``` -$ sal aliasname origcommand -$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -The name of the completer block variable is of the form `$__CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `powershell`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `powershell`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) diff --git a/tools/vendor/github.com/spf13/cobra/user_guide.md b/tools/vendor/github.com/spf13/cobra/user_guide.md deleted file mode 100644 index 85201d840..000000000 --- a/tools/vendor/github.com/spf13/cobra/user_guide.md +++ /dev/null @@ -1,726 +0,0 @@ -# User Guide - -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: - -``` - ▾ appName/ - ▾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra-CLI is its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd - -Cobra doesn't require any special constructors. Simply create your commands. - -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - Complete documentation is available at https://gohugo.io/documentation/`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile string - userLicense string - - rootCmd = &cobra.Command{ - Use: "cobra-cli", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - } -) - -// Execute executes the root command. -func Execute() error { - return rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -### Create additional commands - -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. - -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -### Organizing subcommands - -A command may have subcommands which in turn may have other subcommands. This is achieved by using -`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in -its own go package. - -The suggested approach is for the parent command to use `AddCommand` to add its most immediate -subcommands. For example, consider the following directory structure: - -```text -├── cmd -│   ├── root.go -│   └── sub1 -│   ├── sub1.go -│   └── sub2 -│   ├── leafA.go -│   ├── leafB.go -│   └── sub2.go -└── main.go -``` - -In this case: - -* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command. -* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command. -* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the - sub2 command. - -This approach ensures the subcommands are always included at compile time while avoiding cyclic -references. - -### Returning and handling errors - -If you wish to return an error to the caller of a command, `RunE` can be used. - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(tryCmd) -} - -var tryCmd = &cobra.Command{ - Use: "try", - Short: "Try and possibly fail at something", - RunE: func(cmd *cobra.Command, args []string) error { - if err := someFunc(); err != nil { - return err - } - return nil - }, -} -``` - -The error can then be caught at the execute function call. - -## Working with Flags - -Flags provide modifiers to control how the action command operates. - -### Assign flags to a command - -Since the flags are defined and used in different locations, we need to -define a variable outside with the correct scope to assign the flag to -work with. - -```go -var Verbose bool -var Source string -``` - -There are two different approaches to assign a flag. - -### Persistent Flags - -A flag can be 'persistent', meaning that this flag will be available to the -command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. - -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` - -### Local Flags - -A flag can also be assigned locally, which will only apply to that specific command. - -```go -localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` - -### Local Flag on Parent Commands - -By default, Cobra only parses local flags on the target command, and any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will -parse local flags on each command before executing the target command. - -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` - -### Bind Flags with Config - -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string - -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` - -In this example, the persistent flag `author` is bound with `viper`. -**Note**: the variable `author` will not be set to the value from config, -when the `--author` flag is provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -Or, for persistent flags: -```go -rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkPersistentFlagRequired("region") -``` - -### Flag Groups - -If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then -Cobra can enforce that requirement: -```go -rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") -rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") -rootCmd.MarkFlagsRequiredTogether("username", "password") -``` - -You can also prevent different flags from being provided together if they represent mutually -exclusive options such as specifying an output format as either `--json` or `--yaml` but never both: -```go -rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON") -rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML") -rootCmd.MarkFlagsMutuallyExclusive("json", "yaml") -``` - -In both of these cases: - - both local and persistent flags can be used - - **NOTE:** the group is only enforced on commands where every flag is defined - - a flag may appear in multiple groups - - a group may contain any number of flags - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field of `Command`. -The following validators are built in: - -- Number of arguments: - - `NoArgs` - report an error if there are any positional args. - - `ArbitraryArgs` - accept any number of args. - - `MinimumNArgs(int)` - report an error if less than N positional args are provided. - - `MaximumNArgs(int)` - report an error if more than N positional args are provided. - - `ExactArgs(int)` - report an error if there are not exactly N positional args. - - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`. -- Content of the arguments: - - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args. - -If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`. - -Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks. -For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional -args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as -shown below: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`. -For example: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - // Optionally run one of the validators provided by cobra - if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { - return err - } - // Run the custom validation logic - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -## Example - -In the example below, we have defined three commands. Two are at the top level -and one (cmdTimes) is a child of one of the top commands. In this case the root -is not executable, meaning that a subcommand is required. This is accomplished -by not providing a 'Run' for the 'rootCmd'. - -We have only defined one flag for a single command. - -More documentation about flags is available at https://github.com/spf13/pflag - -```go -package main - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -func main() { - var echoTimes int - - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } - - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Echo: " + strings.Join(args, " ")) - }, - } - - var cmdTimes = &cobra.Command{ - Use: "times [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } - - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` - -For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/). - -## Help Command - -Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help -create' is called. Every command will automatically have the '--help' flag added. - -### Example - -The following output is automatically generated by Cobra. Nothing beyond the -command and flag definitions are needed. - - $ cobra-cli help - - Cobra is a CLI library for Go that empowers applications. - This application is a tool to generate the needed files - to quickly create a Cobra application. - - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra-cli [command] --help" for more information about a command. - - -Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. - -### Grouping commands in help - -Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly -defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element -of that subcommand. The groups will appear in the help output in the same order as they are defined using different -calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using -`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively. - -### Defining your own help - -You can provide your own Help command or your own template for the default command to use -with the following functions: - -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` - -The latter two will also apply to any children commands. - -## Usage Message - -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. - -### Example -You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. - - $ cobra-cli --invalid - Error: unknown flag: --invalid - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra [command] --help" for more information about a command. - -### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: - -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` - -## Version Flag - -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. - -## PreRun and PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - -- `PersistentPreRun` -- `PreRun` -- `Run` -- `PostRun` -- `PersistentPostRun` - -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: - -```go -package main - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func main() { - - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } - - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } - - rootCmd.AddCommand(subCmd) - - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() -} -``` - -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] - -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` - -## Suggestions when "unknown command" happens - -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: - -``` -$ hugo srever -Error: unknown command "srever" for "hugo" - -Did you mean this? - server - -Run 'hugo --help' for usage. -``` - -Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. - -If you need to disable suggestions or tweak the string distance in your command, use: - -```go -command.DisableSuggestions = true -``` - -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which -you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). - -## Generating shell completions - -Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). - -## Providing Active Help - -Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md). diff --git a/tools/vendor/github.com/spf13/cobra/zsh_completions.md b/tools/vendor/github.com/spf13/cobra/zsh_completions.md deleted file mode 100644 index 7cff61787..000000000 --- a/tools/vendor/github.com/spf13/cobra/zsh_completions.md +++ /dev/null @@ -1,48 +0,0 @@ -## Generating Zsh Completion For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced. - -### Deprecation summary - -See further below for more details on these deprecations. - -* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored. -* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`. -* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction`. - -### Behavioral changes - -**Noun completion** -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis| -|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`| -`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored| -|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)| -|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior| - -**Flag-value completion** - -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion| -|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored| -|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)| -|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells| -|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`| -|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`| - -**Improvements** - -* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`) -* File completion by default if no other completions found -* Handling of required flags -* File extension filtering no longer mutually exclusive with bash usage -* Completion of directory names *within* another directory -* Support for `=` form of flags diff --git a/tools/vendor/github.com/stretchr/objx/README.md b/tools/vendor/github.com/stretchr/objx/README.md index 246660b21..78dc1f8b0 100644 --- a/tools/vendor/github.com/stretchr/objx/README.md +++ b/tools/vendor/github.com/stretchr/objx/README.md @@ -4,20 +4,20 @@ [![Maintainability](https://api.codeclimate.com/v1/badges/1d64bc6c8474c2074f2b/maintainability)](https://codeclimate.com/github/stretchr/objx/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/1d64bc6c8474c2074f2b/test_coverage)](https://codeclimate.com/github/stretchr/objx/test_coverage) [![Sourcegraph](https://sourcegraph.com/github.com/stretchr/objx/-/badge.svg)](https://sourcegraph.com/github.com/stretchr/objx) -[![GoDoc](https://godoc.org/github.com/stretchr/objx?status.svg)](https://godoc.org/github.com/stretchr/objx) +[![GoDoc](https://pkg.go.dev/badge/github.com/stretchr/objx?utm_source=godoc)](https://pkg.go.dev/github.com/stretchr/objx) Objx - Go package for dealing with maps, slices, JSON and other data. Get started: - Install Objx with [one line of code](#installation), or [update it with another](#staying-up-to-date) -- Check out the API Documentation http://godoc.org/github.com/stretchr/objx +- Check out the API Documentation http://pkg.go.dev/github.com/stretchr/objx ## Overview Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc. ### Pattern -Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going: +Objx uses a predictable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going: m, err := objx.FromJSON(json) @@ -74,7 +74,7 @@ To update Objx to the latest version, run: go get -u github.com/stretchr/objx ### Supported go versions -We support the lastest three major Go versions, which are 1.10, 1.11 and 1.12 at the moment. +We currently support the three recent major Go versions. ## Contributing Please feel free to submit issues, fork the repository and send pull requests! diff --git a/tools/vendor/github.com/stretchr/objx/Taskfile.yml b/tools/vendor/github.com/stretchr/objx/Taskfile.yml index 7746f516d..8a79e8d67 100644 --- a/tools/vendor/github.com/stretchr/objx/Taskfile.yml +++ b/tools/vendor/github.com/stretchr/objx/Taskfile.yml @@ -1,7 +1,4 @@ -version: '2' - -env: - GOFLAGS: -mod=vendor +version: '3' tasks: default: diff --git a/tools/vendor/github.com/stretchr/objx/accessors.go b/tools/vendor/github.com/stretchr/objx/accessors.go index 4c6045588..72f1d1c1c 100644 --- a/tools/vendor/github.com/stretchr/objx/accessors.go +++ b/tools/vendor/github.com/stretchr/objx/accessors.go @@ -14,17 +14,17 @@ const ( // For example, `location.address.city` PathSeparator string = "." - // arrayAccesRegexString is the regex used to extract the array number + // arrayAccessRegexString is the regex used to extract the array number // from the access path - arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` + arrayAccessRegexString = `^(.+)\[([0-9]+)\]$` // mapAccessRegexString is the regex used to extract the map key // from the access path mapAccessRegexString = `^([^\[]*)\[([^\]]+)\](.*)$` ) -// arrayAccesRegex is the compiled arrayAccesRegexString -var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) +// arrayAccessRegex is the compiled arrayAccessRegexString +var arrayAccessRegex = regexp.MustCompile(arrayAccessRegexString) // mapAccessRegex is the compiled mapAccessRegexString var mapAccessRegex = regexp.MustCompile(mapAccessRegexString) @@ -37,11 +37,11 @@ var mapAccessRegex = regexp.MustCompile(mapAccessRegexString) // // Get can only operate directly on map[string]interface{} and []interface. // -// Example +// # Example // // To access the title of the third chapter of the second book, do: // -// o.Get("books[1].chapters[2].title") +// o.Get("books[1].chapters[2].title") func (m Map) Get(selector string) *Value { rawObj := access(m, selector, nil, false) return &Value{data: rawObj} @@ -52,26 +52,26 @@ func (m Map) Get(selector string) *Value { // // Set can only operate directly on map[string]interface{} and []interface // -// Example +// # Example // // To set the title of the third chapter of the second book, do: // -// o.Set("books[1].chapters[2].title","Time to Go") +// o.Set("books[1].chapters[2].title","Time to Go") func (m Map) Set(selector string, value interface{}) Map { access(m, selector, value, true) return m } -// getIndex returns the index, which is hold in s by two braches. -// It also returns s withour the index part, e.g. name[1] will return (1, name). +// getIndex returns the index, which is hold in s by two branches. +// It also returns s without the index part, e.g. name[1] will return (1, name). // If no index is found, -1 is returned func getIndex(s string) (int, string) { - arrayMatches := arrayAccesRegex.FindStringSubmatch(s) + arrayMatches := arrayAccessRegex.FindStringSubmatch(s) if len(arrayMatches) > 0 { // Get the key into the map selector := arrayMatches[1] // Get the index into the array at the key - // We know this cannt fail because arrayMatches[2] is an int for sure + // We know this can't fail because arrayMatches[2] is an int for sure index, _ := strconv.Atoi(arrayMatches[2]) return index, selector } diff --git a/tools/vendor/github.com/stretchr/objx/conversions.go b/tools/vendor/github.com/stretchr/objx/conversions.go index 080aa46e4..01c63d7d3 100644 --- a/tools/vendor/github.com/stretchr/objx/conversions.go +++ b/tools/vendor/github.com/stretchr/objx/conversions.go @@ -15,7 +15,7 @@ import ( const SignatureSeparator = "_" // URLValuesSliceKeySuffix is the character that is used to -// specify a suffic for slices parsed by URLValues. +// specify a suffix for slices parsed by URLValues. // If the suffix is set to "[i]", then the index of the slice // is used in place of i // Ex: Suffix "[]" would have the form a[]=b&a[]=c @@ -30,7 +30,7 @@ const ( ) // SetURLValuesSliceKeySuffix sets the character that is used to -// specify a suffic for slices parsed by URLValues. +// specify a suffix for slices parsed by URLValues. // If the suffix is set to "[i]", then the index of the slice // is used in place of i // Ex: Suffix "[]" would have the form a[]=b&a[]=c diff --git a/tools/vendor/github.com/stretchr/objx/doc.go b/tools/vendor/github.com/stretchr/objx/doc.go index 6d6af1a83..b170af74b 100644 --- a/tools/vendor/github.com/stretchr/objx/doc.go +++ b/tools/vendor/github.com/stretchr/objx/doc.go @@ -1,19 +1,19 @@ /* -Objx - Go package for dealing with maps, slices, JSON and other data. +Package objx provides utilities for dealing with maps, slices, JSON and other data. -Overview +# Overview Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc. -Pattern +# Pattern -Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. +Objx uses a predictable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going: - m, err := objx.FromJSON(json) + m, err := objx.FromJSON(json) NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, the rest will be optimistic and try to figure things out without panicking. @@ -21,46 +21,46 @@ the rest will be optimistic and try to figure things out without panicking. Use `Get` to access the value you're interested in. You can use dot and array notation too: - m.Get("places[0].latlng") + m.Get("places[0].latlng") Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type. - if m.Get("code").IsStr() { // Your code... } + if m.Get("code").IsStr() { // Your code... } Or you can just assume the type, and use one of the strong type methods to extract the real value: - m.Get("code").Int() + m.Get("code").Int() If there's no value there (or if it's the wrong type) then a default value will be returned, or you can be explicit about the default value. - Get("code").Int(-1) + Get("code").Int(-1) If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, manipulating and selecting that data. You can find out more by exploring the index below. -Reading data +# Reading data A simple example of how to use Objx: - // Use MustFromJSON to make an objx.Map from some JSON - m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) + // Use MustFromJSON to make an objx.Map from some JSON + m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) - // Get the details - name := m.Get("name").Str() - age := m.Get("age").Int() + // Get the details + name := m.Get("name").Str() + age := m.Get("age").Int() - // Get their nickname (or use their name if they don't have one) - nickname := m.Get("nickname").Str(name) + // Get their nickname (or use their name if they don't have one) + nickname := m.Get("nickname").Str(name) -Ranging +# Ranging Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For example, to `range` the data, do what you would expect: - m := objx.MustFromJSON(json) - for key, value := range m { - // Your code... - } + m := objx.MustFromJSON(json) + for key, value := range m { + // Your code... + } */ package objx diff --git a/tools/vendor/github.com/stretchr/objx/map.go b/tools/vendor/github.com/stretchr/objx/map.go index a64712a08..ab9f9ae67 100644 --- a/tools/vendor/github.com/stretchr/objx/map.go +++ b/tools/vendor/github.com/stretchr/objx/map.go @@ -47,17 +47,16 @@ func New(data interface{}) Map { // // The arguments follow a key, value pattern. // -// // Returns nil if any key argument is non-string or if there are an odd number of arguments. // -// Example +// # Example // // To easily create Maps: // -// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) +// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) // -// // creates an Map equivalent to -// m := objx.Map{"name": "Mat", "age": 29, "subobj": objx.Map{"active": true}} +// // creates an Map equivalent to +// m := objx.Map{"name": "Mat", "age": 29, "subobj": objx.Map{"active": true}} func MSI(keyAndValuePairs ...interface{}) Map { newMap := Map{} keyAndValuePairsLen := len(keyAndValuePairs) diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_compare.go index b774da88d..4d4b4aad6 100644 --- a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare.go +++ b/tools/vendor/github.com/stretchr/testify/assert/assertion_compare.go @@ -28,6 +28,8 @@ var ( uint32Type = reflect.TypeOf(uint32(1)) uint64Type = reflect.TypeOf(uint64(1)) + uintptrType = reflect.TypeOf(uintptr(1)) + float32Type = reflect.TypeOf(float32(1)) float64Type = reflect.TypeOf(float64(1)) @@ -308,11 +310,11 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { case reflect.Struct: { // All structs enter here. We're not interested in most types. - if !canConvert(obj1Value, timeType) { + if !obj1Value.CanConvert(timeType) { break } - // time.Time can compared! + // time.Time can be compared! timeObj1, ok := obj1.(time.Time) if !ok { timeObj1 = obj1Value.Convert(timeType).Interface().(time.Time) @@ -328,7 +330,7 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { case reflect.Slice: { // We only care about the []byte type. - if !canConvert(obj1Value, bytesType) { + if !obj1Value.CanConvert(bytesType) { break } @@ -345,6 +347,26 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { return CompareType(bytes.Compare(bytesObj1, bytesObj2)), true } + case reflect.Uintptr: + { + uintptrObj1, ok := obj1.(uintptr) + if !ok { + uintptrObj1 = obj1Value.Convert(uintptrType).Interface().(uintptr) + } + uintptrObj2, ok := obj2.(uintptr) + if !ok { + uintptrObj2 = obj2Value.Convert(uintptrType).Interface().(uintptr) + } + if uintptrObj1 > uintptrObj2 { + return compareGreater, true + } + if uintptrObj1 == uintptrObj2 { + return compareEqual, true + } + if uintptrObj1 < uintptrObj2 { + return compareLess, true + } + } } return compareEqual, false diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go deleted file mode 100644 index da867903e..000000000 --- a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build go1.17 -// +build go1.17 - -// TODO: once support for Go 1.16 is dropped, this file can be -// merged/removed with assertion_compare_go1.17_test.go and -// assertion_compare_legacy.go - -package assert - -import "reflect" - -// Wrapper around reflect.Value.CanConvert, for compatibility -// reasons. -func canConvert(value reflect.Value, to reflect.Type) bool { - return value.CanConvert(to) -} diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go deleted file mode 100644 index 1701af2a3..000000000 --- a/tools/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !go1.17 -// +build !go1.17 - -// TODO: once support for Go 1.16 is dropped, this file can be -// merged/removed with assertion_compare_go1.17_test.go and -// assertion_compare_can_convert.go - -package assert - -import "reflect" - -// Older versions of Go does not have the reflect.Value.CanConvert -// method. -func canConvert(value reflect.Value, to reflect.Type) bool { - return false -} diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go index 84dbd6c79..3ddab109a 100644 --- a/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go +++ b/tools/vendor/github.com/stretchr/testify/assert/assertion_format.go @@ -1,7 +1,4 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package assert @@ -107,7 +104,7 @@ func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, return EqualExportedValues(t, expected, actual, append([]interface{}{msg}, args...)...) } -// EqualValuesf asserts that two objects are equal or convertable to the same types +// EqualValuesf asserts that two objects are equal or convertible to the same types // and equal. // // assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") @@ -616,6 +613,16 @@ func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interf return NotErrorIs(t, err, target, append([]interface{}{msg}, args...)...) } +// NotImplementsf asserts that an object does not implement the specified interface. +// +// assert.NotImplementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func NotImplementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotImplements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) +} + // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") @@ -660,10 +667,12 @@ func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, return NotSame(t, expected, actual, append([]interface{}{msg}, args...)...) } -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted") +// assert.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -747,10 +756,11 @@ func Samef(t TestingT, expected interface{}, actual interface{}, msg string, arg return Same(t, expected, actual, append([]interface{}{msg}, args...)...) } -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// assert.Subsetf(t, [1, 2, 3], [1, 2], "error message %s", "formatted") +// assert.Subsetf(t, {"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go index b1d94aec5..a84e09bd4 100644 --- a/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ b/tools/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -1,7 +1,4 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ +// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package assert @@ -189,7 +186,7 @@ func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface return EqualExportedValuesf(a.t, expected, actual, msg, args...) } -// EqualValues asserts that two objects are equal or convertable to the same types +// EqualValues asserts that two objects are equal or convertible to the same types // and equal. // // a.EqualValues(uint32(123), int32(123)) @@ -200,7 +197,7 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn return EqualValues(a.t, expected, actual, msgAndArgs...) } -// EqualValuesf asserts that two objects are equal or convertable to the same types +// EqualValuesf asserts that two objects are equal or convertible to the same types // and equal. // // a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") @@ -1221,6 +1218,26 @@ func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...in return NotErrorIsf(a.t, err, target, msg, args...) } +// NotImplements asserts that an object does not implement the specified interface. +// +// a.NotImplements((*MyInterface)(nil), new(MyObject)) +func (a *Assertions) NotImplements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotImplements(a.t, interfaceObject, object, msgAndArgs...) +} + +// NotImplementsf asserts that an object does not implement the specified interface. +// +// a.NotImplementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +func (a *Assertions) NotImplementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotImplementsf(a.t, interfaceObject, object, msg, args...) +} + // NotNil asserts that the specified object is not nil. // // a.NotNil(err) @@ -1309,10 +1326,12 @@ func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg stri return NotSamef(a.t, expected, actual, msg, args...) } -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// a.NotSubset([1, 3, 4], [1, 2]) +// a.NotSubset({"x": 1, "y": 2}, {"z": 3}) func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1320,10 +1339,12 @@ func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs return NotSubset(a.t, list, subset, msgAndArgs...) } -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubsetf asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// a.NotSubsetf([1, 3, 4], [1, 2], "error message %s", "formatted") +// a.NotSubsetf({"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1483,10 +1504,11 @@ func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, return Samef(a.t, expected, actual, msg, args...) } -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// a.Subset([1, 2, 3], [1, 2]) +// a.Subset({"x": 1, "y": 2}, {"x": 1}) func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1494,10 +1516,11 @@ func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ... return Subset(a.t, list, subset, msgAndArgs...) } -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subsetf asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// a.Subsetf([1, 2, 3], [1, 2], "error message %s", "formatted") +// a.Subsetf({"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() diff --git a/tools/vendor/github.com/stretchr/testify/assert/assertions.go b/tools/vendor/github.com/stretchr/testify/assert/assertions.go index a55d1bba9..0b7570f21 100644 --- a/tools/vendor/github.com/stretchr/testify/assert/assertions.go +++ b/tools/vendor/github.com/stretchr/testify/assert/assertions.go @@ -19,7 +19,7 @@ import ( "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" - yaml "gopkg.in/yaml.v3" + "gopkg.in/yaml.v3" ) //go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl" @@ -110,7 +110,12 @@ func copyExportedFields(expected interface{}) interface{} { return result.Interface() case reflect.Array, reflect.Slice: - result := reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len()) + var result reflect.Value + if expectedKind == reflect.Array { + result = reflect.New(reflect.ArrayOf(expectedValue.Len(), expectedType.Elem())).Elem() + } else { + result = reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len()) + } for i := 0; i < expectedValue.Len(); i++ { index := expectedValue.Index(i) if isNil(index) { @@ -140,6 +145,8 @@ func copyExportedFields(expected interface{}) interface{} { // structures. // // This function does no assertion of any kind. +// +// Deprecated: Use [EqualExportedValues] instead. func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool { expectedCleaned := copyExportedFields(expected) actualCleaned := copyExportedFields(actual) @@ -153,17 +160,40 @@ func ObjectsAreEqualValues(expected, actual interface{}) bool { return true } - actualType := reflect.TypeOf(actual) - if actualType == nil { + expectedValue := reflect.ValueOf(expected) + actualValue := reflect.ValueOf(actual) + if !expectedValue.IsValid() || !actualValue.IsValid() { return false } - expectedValue := reflect.ValueOf(expected) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + + expectedType := expectedValue.Type() + actualType := actualValue.Type() + if !expectedType.ConvertibleTo(actualType) { + return false + } + + if !isNumericType(expectedType) || !isNumericType(actualType) { // Attempt comparison after type conversion - return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + return reflect.DeepEqual( + expectedValue.Convert(actualType).Interface(), actual, + ) } - return false + // If BOTH values are numeric, there are chances of false positives due + // to overflow or underflow. So, we need to make sure to always convert + // the smaller type to a larger type before comparing. + if expectedType.Size() >= actualType.Size() { + return actualValue.Convert(expectedType).Interface() == expected + } + + return expectedValue.Convert(actualType).Interface() == actual +} + +// isNumericType returns true if the type is one of: +// int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, +// float32, float64, complex64, complex128 +func isNumericType(t reflect.Type) bool { + return t.Kind() >= reflect.Int && t.Kind() <= reflect.Complex128 } /* CallerInfo is necessary because the assert functions use the testing object @@ -266,7 +296,7 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { // Aligns the provided message so that all lines after the first line start at the same location as the first line. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). -// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the +// The longestLabelLen parameter specifies the length of the longest label in the output (required because this is the // basis on which the alignment occurs). func indentMessageLines(message string, longestLabelLen int) string { outBuf := new(bytes.Buffer) @@ -382,6 +412,25 @@ func Implements(t TestingT, interfaceObject interface{}, object interface{}, msg return true } +// NotImplements asserts that an object does not implement the specified interface. +// +// assert.NotImplements(t, (*MyInterface)(nil), new(MyObject)) +func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + interfaceType := reflect.TypeOf(interfaceObject).Elem() + + if object == nil { + return Fail(t, fmt.Sprintf("Cannot check if nil does not implement %v", interfaceType), msgAndArgs...) + } + if reflect.TypeOf(object).Implements(interfaceType) { + return Fail(t, fmt.Sprintf("%T implements %v", object, interfaceType), msgAndArgs...) + } + + return true +} + // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -496,7 +545,7 @@ func samePointers(first, second interface{}) bool { // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed -// with the type name, and the value will be enclosed in parenthesis similar +// with the type name, and the value will be enclosed in parentheses similar // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { @@ -523,7 +572,7 @@ func truncatingFormat(data interface{}) string { return value } -// EqualValues asserts that two objects are equal or convertable to the same types +// EqualValues asserts that two objects are equal or convertible to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123)) @@ -566,12 +615,19 @@ func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs .. return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) } + if aType.Kind() == reflect.Ptr { + aType = aType.Elem() + } + if bType.Kind() == reflect.Ptr { + bType = bType.Elem() + } + if aType.Kind() != reflect.Struct { - return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...) + return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...) } if bType.Kind() != reflect.Struct { - return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...) + return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...) } expected = copyExportedFields(expected) @@ -620,17 +676,6 @@ func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return Fail(t, "Expected value not to be nil.", msgAndArgs...) } -// containsKind checks if a specified kind in the slice of kinds. -func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool { - for i := 0; i < len(kinds); i++ { - if kind == kinds[i] { - return true - } - } - - return false -} - // isNil checks if a specified object is nil or not, without Failing. func isNil(object interface{}) bool { if object == nil { @@ -638,16 +683,13 @@ func isNil(object interface{}) bool { } value := reflect.ValueOf(object) - kind := value.Kind() - isNilableKind := containsKind( - []reflect.Kind{ - reflect.Chan, reflect.Func, - reflect.Interface, reflect.Map, - reflect.Ptr, reflect.Slice, reflect.UnsafePointer}, - kind) - - if isNilableKind && value.IsNil() { - return true + switch value.Kind() { + case + reflect.Chan, reflect.Func, + reflect.Interface, reflect.Map, + reflect.Ptr, reflect.Slice, reflect.UnsafePointer: + + return value.IsNil() } return false @@ -731,16 +773,14 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { } -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { +// getLen tries to get the length of an object. +// It returns (0, false) if impossible. +func getLen(x interface{}) (length int, ok bool) { v := reflect.ValueOf(x) defer func() { - if e := recover(); e != nil { - ok = false - } + ok = recover() == nil }() - return true, v.Len() + return v.Len(), true } // Len asserts that the specified object has specific length. @@ -751,13 +791,13 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) if h, ok := t.(tHelper); ok { h.Helper() } - ok, l := getLen(object) + l, ok := getLen(object) if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) + return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...) } if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) + return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) } return true } @@ -919,10 +959,11 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) } -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). +// Subset asserts that the specified list(array, slice...) or map contains all +// elements given in the specified subset list(array, slice...) or map. // -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// assert.Subset(t, [1, 2, 3], [1, 2]) +// assert.Subset(t, {"x": 1, "y": 2}, {"x": 1}) func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() @@ -975,10 +1016,12 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok return true } -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). +// NotSubset asserts that the specified list(array, slice...) or map does NOT +// contain all elements given in the specified subset list(array, slice...) or +// map. // -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// assert.NotSubset(t, [1, 3, 4], [1, 2]) +// assert.NotSubset(t, {"x": 1, "y": 2}, {"z": 3}) func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1439,7 +1482,7 @@ func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAnd h.Helper() } if math.IsNaN(epsilon) { - return Fail(t, "epsilon must not be NaN") + return Fail(t, "epsilon must not be NaN", msgAndArgs...) } actualEpsilon, err := calcRelativeError(expected, actual) if err != nil { @@ -1458,19 +1501,26 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m if h, ok := t.(tHelper); ok { h.Helper() } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { + + if expected == nil || actual == nil { return Fail(t, "Parameters must be slice", msgAndArgs...) } - actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) + actualSlice := reflect.ValueOf(actual) - for i := 0; i < actualSlice.Len(); i++ { - result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) - if !result { - return result + if expectedSlice.Type().Kind() != reflect.Slice { + return Fail(t, "Expected value must be slice", msgAndArgs...) + } + + expectedLen := expectedSlice.Len() + if !IsType(t, expected, actual) || !Len(t, actual, expectedLen) { + return false + } + + for i := 0; i < expectedLen; i++ { + if !InEpsilon(t, expectedSlice.Index(i).Interface(), actualSlice.Index(i).Interface(), epsilon, "at index %d", i) { + return false } } @@ -1870,23 +1920,18 @@ func (c *CollectT) Errorf(format string, args ...interface{}) { } // FailNow panics. -func (c *CollectT) FailNow() { +func (*CollectT) FailNow() { panic("Assertion failed") } -// Reset clears the collected errors. -func (c *CollectT) Reset() { - c.errors = nil +// Deprecated: That was a method for internal usage that should not have been published. Now just panics. +func (*CollectT) Reset() { + panic("Reset() is deprecated") } -// Copy copies the collected errors to the supplied t. -func (c *CollectT) Copy(t TestingT) { - if tt, ok := t.(tHelper); ok { - tt.Helper() - } - for _, err := range c.errors { - t.Errorf("%v", err) - } +// Deprecated: That was a method for internal usage that should not have been published. Now just panics. +func (*CollectT) Copy(TestingT) { + panic("Copy() is deprecated") } // EventuallyWithT asserts that given condition will be met in waitFor time, @@ -1912,8 +1957,8 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time h.Helper() } - collect := new(CollectT) - ch := make(chan bool, 1) + var lastFinishedTickErrs []error + ch := make(chan []error, 1) timer := time.NewTimer(waitFor) defer timer.Stop() @@ -1924,19 +1969,25 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time for tick := ticker.C; ; { select { case <-timer.C: - collect.Copy(t) + for _, err := range lastFinishedTickErrs { + t.Errorf("%v", err) + } return Fail(t, "Condition never satisfied", msgAndArgs...) case <-tick: tick = nil - collect.Reset() go func() { + collect := new(CollectT) + defer func() { + ch <- collect.errors + }() condition(collect) - ch <- len(collect.errors) == 0 }() - case v := <-ch: - if v { + case errs := <-ch: + if len(errs) == 0 { return true } + // Keep the errors from the last ended condition, so that they can be copied to t if timeout is reached. + lastFinishedTickErrs = errs tick = ticker.C } } diff --git a/tools/vendor/github.com/stretchr/testify/assert/http_assertions.go b/tools/vendor/github.com/stretchr/testify/assert/http_assertions.go index d8038c28a..861ed4b7c 100644 --- a/tools/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ b/tools/vendor/github.com/stretchr/testify/assert/http_assertions.go @@ -12,7 +12,7 @@ import ( // an error if building a new request fails. func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { w := httptest.NewRecorder() - req, err := http.NewRequest(method, url, nil) + req, err := http.NewRequest(method, url, http.NoBody) if err != nil { return -1, err } @@ -32,12 +32,12 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, value } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent if !isSuccessCode { - Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isSuccessCode @@ -54,12 +54,12 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, valu } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect if !isRedirectCode { - Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isRedirectCode @@ -76,12 +76,12 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isErrorCode := code >= http.StatusBadRequest if !isErrorCode { - Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isErrorCode @@ -98,12 +98,12 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, va } code, err := httpCode(handler, method, url, values) if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } successful := code == statuscode if !successful { - Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code)) + Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code), msgAndArgs...) } return successful @@ -113,7 +113,10 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, va // empty string if building a new request fails. func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) + if len(values) > 0 { + url += "?" + values.Encode() + } + req, err := http.NewRequest(method, url, http.NoBody) if err != nil { return "" } @@ -135,7 +138,7 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, contains := strings.Contains(body, fmt.Sprint(str)) if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) + Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body), msgAndArgs...) } return contains @@ -155,7 +158,7 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url strin contains := strings.Contains(body, fmt.Sprint(str)) if contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) + Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body), msgAndArgs...) } return !contains diff --git a/tools/vendor/github.com/stretchr/testify/mock/mock.go b/tools/vendor/github.com/stretchr/testify/mock/mock.go index f4b42e44f..213bde2ea 100644 --- a/tools/vendor/github.com/stretchr/testify/mock/mock.go +++ b/tools/vendor/github.com/stretchr/testify/mock/mock.go @@ -18,6 +18,9 @@ import ( "github.com/stretchr/testify/assert" ) +// regex for GCCGO functions +var gccgoRE = regexp.MustCompile(`\.pN\d+_`) + // TestingT is an interface wrapper around *testing.T type TestingT interface { Logf(format string, args ...interface{}) @@ -111,7 +114,7 @@ func (c *Call) Return(returnArguments ...interface{}) *Call { return c } -// Panic specifies if the functon call should fail and the panic message +// Panic specifies if the function call should fail and the panic message // // Mock.On("DoSomething").Panic("test panic") func (c *Call) Panic(msg string) *Call { @@ -123,21 +126,21 @@ func (c *Call) Panic(msg string) *Call { return c } -// Once indicates that that the mock should only return the value once. +// Once indicates that the mock should only return the value once. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() func (c *Call) Once() *Call { return c.Times(1) } -// Twice indicates that that the mock should only return the value twice. +// Twice indicates that the mock should only return the value twice. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() func (c *Call) Twice() *Call { return c.Times(2) } -// Times indicates that that the mock should only return the indicated number +// Times indicates that the mock should only return the indicated number // of times. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) @@ -455,9 +458,8 @@ func (m *Mock) Called(arguments ...interface{}) Arguments { // For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock // uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree // With GCCGO we need to remove interface information starting from pN
. - re := regexp.MustCompile("\\.pN\\d+_") - if re.MatchString(functionPath) { - functionPath = re.Split(functionPath, -1)[0] + if gccgoRE.MatchString(functionPath) { + functionPath = gccgoRE.Split(functionPath, -1)[0] } parts := strings.Split(functionPath, ".") functionName := parts[len(parts)-1] @@ -474,7 +476,7 @@ func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Argumen found, call := m.findExpectedCall(methodName, arguments...) if found < 0 { - // expected call found but it has already been called with repeatable times + // expected call found, but it has already been called with repeatable times if call != nil { m.mutex.Unlock() m.fail("\nassert: mock: The method has been called over %d times.\n\tEither do one more Mock.On(\"%s\").Return(...), or remove extra call.\n\tThis call was unexpected:\n\t\t%s\n\tat: %s", call.totalCalls, methodName, callString(methodName, arguments, true), assert.CallerInfo()) @@ -563,7 +565,7 @@ func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Argumen Assertions */ -type assertExpectationser interface { +type assertExpectationiser interface { AssertExpectations(TestingT) bool } @@ -580,7 +582,7 @@ func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") obj = m } - m := obj.(assertExpectationser) + m := obj.(assertExpectationiser) if !m.AssertExpectations(t) { t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) return false @@ -592,6 +594,9 @@ func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { // AssertExpectations asserts that everything specified with On and Return was // in fact called as expected. Calls may have occurred in any order. func (m *Mock) AssertExpectations(t TestingT) bool { + if s, ok := t.(interface{ Skipped() bool }); ok && s.Skipped() { + return true + } if h, ok := t.(tHelper); ok { h.Helper() } @@ -606,8 +611,8 @@ func (m *Mock) AssertExpectations(t TestingT) bool { satisfied, reason := m.checkExpectation(expectedCall) if !satisfied { failedExpectations++ + t.Logf(reason) } - t.Logf(reason) } if failedExpectations != 0 { @@ -758,25 +763,33 @@ const ( Anything = "mock.Anything" ) -// AnythingOfTypeArgument is a string that contains the type of an argument +// AnythingOfTypeArgument contains the type of an argument +// for use when type checking. Used in Diff and Assert. +// +// Deprecated: this is an implementation detail that must not be used. Use [AnythingOfType] instead. +type AnythingOfTypeArgument = anythingOfTypeArgument + +// anythingOfTypeArgument is a string that contains the type of an argument // for use when type checking. Used in Diff and Assert. -type AnythingOfTypeArgument string +type anythingOfTypeArgument string -// AnythingOfType returns an AnythingOfTypeArgument object containing the -// name of the type to check for. Used in Diff and Assert. +// AnythingOfType returns a special value containing the +// name of the type to check for. The type name will be matched against the type name returned by [reflect.Type.String]. +// +// Used in Diff and Assert. // // For example: // // Assert(t, AnythingOfType("string"), AnythingOfType("int")) func AnythingOfType(t string) AnythingOfTypeArgument { - return AnythingOfTypeArgument(t) + return anythingOfTypeArgument(t) } // IsTypeArgument is a struct that contains the type of an argument // for use when type checking. This is an alternative to AnythingOfType. // Used in Diff and Assert. type IsTypeArgument struct { - t interface{} + t reflect.Type } // IsType returns an IsTypeArgument object containing the type to check for. @@ -786,7 +799,7 @@ type IsTypeArgument struct { // For example: // Assert(t, IsType(""), IsType(0)) func IsType(t interface{}) *IsTypeArgument { - return &IsTypeArgument{t: t} + return &IsTypeArgument{t: reflect.TypeOf(t)} } // FunctionalOptionsArgument is a struct that contains the type and value of an functional option argument @@ -950,53 +963,55 @@ func (args Arguments) Diff(objects []interface{}) (string, int) { differences++ output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher) } - } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { - // type checking - if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt) - } - } else if reflect.TypeOf(expected) == reflect.TypeOf((*IsTypeArgument)(nil)) { - t := expected.(*IsTypeArgument).t - if reflect.TypeOf(t) != reflect.TypeOf(actual) { - differences++ - output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, reflect.TypeOf(t).Name(), reflect.TypeOf(actual).Name(), actualFmt) - } - } else if reflect.TypeOf(expected) == reflect.TypeOf((*FunctionalOptionsArgument)(nil)) { - t := expected.(*FunctionalOptionsArgument).value + } else { + switch expected := expected.(type) { + case anythingOfTypeArgument: + // type checking + if reflect.TypeOf(actual).Name() != string(expected) && reflect.TypeOf(actual).String() != string(expected) { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt) + } + case *IsTypeArgument: + actualT := reflect.TypeOf(actual) + if actualT != expected.t { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected.t.Name(), actualT.Name(), actualFmt) + } + case *FunctionalOptionsArgument: + t := expected.value - var name string - tValue := reflect.ValueOf(t) - if tValue.Len() > 0 { - name = "[]" + reflect.TypeOf(tValue.Index(0).Interface()).String() - } + var name string + tValue := reflect.ValueOf(t) + if tValue.Len() > 0 { + name = "[]" + reflect.TypeOf(tValue.Index(0).Interface()).String() + } - tName := reflect.TypeOf(t).Name() - if name != reflect.TypeOf(actual).String() && tValue.Len() != 0 { - differences++ - output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, tName, reflect.TypeOf(actual).Name(), actualFmt) - } else { - if ef, af := assertOpts(t, actual); ef == "" && af == "" { + tName := reflect.TypeOf(t).Name() + if name != reflect.TypeOf(actual).String() && tValue.Len() != 0 { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, tName, reflect.TypeOf(actual).Name(), actualFmt) + } else { + if ef, af := assertOpts(t, actual); ef == "" && af == "" { + // match + output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, tName, tName) + } else { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, af, ef) + } + } + + default: + if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { // match - output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, tName, tName) + output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt) } else { // not match differences++ - output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, af, ef) + output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt) } } - } else { - // normal checking - - if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { - // match - output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt) - } else { - // not match - differences++ - output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt) - } } } diff --git a/tools/vendor/github.com/t-yuki/gocover-cobertura/.travis.yml b/tools/vendor/github.com/t-yuki/gocover-cobertura/.travis.yml deleted file mode 100644 index f17bb6169..000000000 --- a/tools/vendor/github.com/t-yuki/gocover-cobertura/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: - - 1.6 - - 1.7 - - 1.8 - - tip - -sudo: false -before_install: - - go get github.com/mattn/goveralls -script: - - $GOPATH/bin/goveralls -service=travis-ci diff --git a/tools/vendor/github.com/t-yuki/gocover-cobertura/README.md b/tools/vendor/github.com/t-yuki/gocover-cobertura/README.md deleted file mode 100644 index 60ab1dbe7..000000000 --- a/tools/vendor/github.com/t-yuki/gocover-cobertura/README.md +++ /dev/null @@ -1,35 +0,0 @@ -[![Build Status](https://travis-ci.org/t-yuki/gocover-cobertura.svg?branch=master)](https://travis-ci.org/t-yuki/gocover-cobertura) -[![Coverage Status](https://coveralls.io/repos/github/t-yuki/gocover-cobertura/badge.svg?branch=master)](https://coveralls.io/github/t-yuki/gocover-cobertura?branch=master) - -go tool cover XML (Cobertura) export -==================================== - -This is a simple helper tool for generating XML output in [Cobertura](http://cobertura.sourceforge.net/) format -for CIs like [Jenkins](https://wiki.jenkins-ci.org/display/JENKINS/Cobertura+Plugin) and others -from [go tool cover](https://code.google.com/p/go.tools/) output. - -Installation ------------- - -Just type the following to install the program and its dependencies: - - $ go get code.google.com/p/go.tools/cmd/cover - $ go get github.com/t-yuki/gocover-cobertura - -Usage ------ - -`gocover-cobertura` reads from the standard input: - - $ go test -coverprofile=coverage.txt -covermode count github.com/gorilla/mux - $ gocover-cobertura < coverage.txt > coverage.xml - -Authors -------- - -* [Yukinari Toyota (t-yuki)](https://github.com/t-yuki) - -Thanks ------- - -This tool is originated from [gocov-xml](https://github.com/AlekSi/gocov-xml) by [Alexey Palazhchenko (AlekSi)](https://github.com/AlekSi) diff --git a/tools/vendor/github.com/t-yuki/gocover-cobertura/cobertura.go b/tools/vendor/github.com/t-yuki/gocover-cobertura/cobertura.go deleted file mode 100644 index 8556dc563..000000000 --- a/tools/vendor/github.com/t-yuki/gocover-cobertura/cobertura.go +++ /dev/null @@ -1,178 +0,0 @@ -package main - -import ( - "encoding/xml" -) - -type Coverage struct { - XMLName xml.Name `xml:"coverage"` - LineRate float32 `xml:"line-rate,attr"` - BranchRate float32 `xml:"branch-rate,attr"` - Version string `xml:"version,attr"` - Timestamp int64 `xml:"timestamp,attr"` - LinesCovered int64 `xml:"lines-covered,attr"` - LinesValid int64 `xml:"lines-valid,attr"` - BranchesCovered int64 `xml:"branches-covered,attr"` - BranchesValid int64 `xml:"branches-valid,attr"` - Complexity float32 `xml:"complexity,attr"` - Sources []*Source `xml:"sources>source"` - Packages []*Package `xml:"packages>package"` -} - -type Source struct { - Path string `xml:",chardata"` -} - -type Package struct { - Name string `xml:"name,attr"` - LineRate float32 `xml:"line-rate,attr"` - BranchRate float32 `xml:"branch-rate,attr"` - Complexity float32 `xml:"complexity,attr"` - Classes []*Class `xml:"classes>class"` -} - -type Class struct { - Name string `xml:"name,attr"` - Filename string `xml:"filename,attr"` - LineRate float32 `xml:"line-rate,attr"` - BranchRate float32 `xml:"branch-rate,attr"` - Complexity float32 `xml:"complexity,attr"` - Methods []*Method `xml:"methods>method"` - Lines Lines `xml:"lines>line"` -} - -type Method struct { - Name string `xml:"name,attr"` - Signature string `xml:"signature,attr"` - LineRate float32 `xml:"line-rate,attr"` - BranchRate float32 `xml:"branch-rate,attr"` - Complexity float32 `xml:"complexity,attr"` - Lines Lines `xml:"lines>line"` -} - -type Line struct { - Number int `xml:"number,attr"` - Hits int64 `xml:"hits,attr"` -} - -// Lines is a slice of Line pointers, with some convenience methods -type Lines []*Line - -// HitRate returns a float32 from 0.0 to 1.0 representing what fraction of lines -// have hits -func (lines Lines) HitRate() (hitRate float32) { - return float32(lines.NumLinesWithHits()) / float32(len(lines)) -} - -// NumLines returns the number of lines -func (lines Lines) NumLines() int64 { - return int64(len(lines)) -} - -// NumLinesWithHits returns the number of lines with a hit count > 0 -func (lines Lines) NumLinesWithHits() (numLinesWithHits int64) { - for _, line := range lines { - if line.Hits > 0 { - numLinesWithHits++ - } - } - return numLinesWithHits -} - -// AddOrUpdateLine adds a line if it is a different line than the last line recorded. -// If it's the same line as the last line recorded then we update the hits down -// if the new hits is less; otherwise just leave it as-is -func (lines *Lines) AddOrUpdateLine(lineNumber int, hits int64) { - if len(*lines) > 0 { - lastLine := (*lines)[len(*lines)-1] - if lineNumber == lastLine.Number { - if hits < lastLine.Hits { - lastLine.Hits = hits - } - return - } - } - *lines = append(*lines, &Line{Number: lineNumber, Hits: hits}) -} - -// HitRate returns a float32 from 0.0 to 1.0 representing what fraction of lines -// have hits -func (method Method) HitRate() float32 { - return method.Lines.HitRate() -} - -// NumLines returns the number of lines -func (method Method) NumLines() int64 { - return method.Lines.NumLines() -} - -// NumLinesWithHits returns the number of lines with a hit count > 0 -func (method Method) NumLinesWithHits() int64 { - return method.Lines.NumLinesWithHits() -} - -// HitRate returns a float32 from 0.0 to 1.0 representing what fraction of lines -// have hits -func (class Class) HitRate() float32 { - return float32(class.NumLinesWithHits()) / float32(class.NumLines()) -} - -// NumLines returns the number of lines -func (class Class) NumLines() (numLines int64) { - for _, method := range class.Methods { - numLines += method.NumLines() - } - return numLines -} - -// NumLinesWithHits returns the number of lines with a hit count > 0 -func (class Class) NumLinesWithHits() (numLinesWithHits int64) { - for _, method := range class.Methods { - numLinesWithHits += method.NumLinesWithHits() - } - return numLinesWithHits -} - -// HitRate returns a float32 from 0.0 to 1.0 representing what fraction of lines -// have hits -func (pkg Package) HitRate() float32 { - return float32(pkg.NumLinesWithHits()) / float32(pkg.NumLines()) -} - -// NumLines returns the number of lines -func (pkg Package) NumLines() (numLines int64) { - for _, class := range pkg.Classes { - numLines += class.NumLines() - } - return numLines -} - -// NumLinesWithHits returns the number of lines with a hit count > 0 -func (pkg Package) NumLinesWithHits() (numLinesWithHits int64) { - for _, class := range pkg.Classes { - numLinesWithHits += class.NumLinesWithHits() - } - return numLinesWithHits -} - -// HitRate returns a float32 from 0.0 to 1.0 representing what fraction of lines -// have hits -func (cov Coverage) HitRate() float32 { - return float32(cov.NumLinesWithHits()) / float32(cov.NumLines()) -} - -// NumLines returns the number of lines -func (cov Coverage) NumLines() (numLines int64) { - for _, pkg := range cov.Packages { - numLines += pkg.NumLines() - } - return numLines -} - -// NumLinesWithHits returns the number of lines with a hit count > 0 -func (cov Coverage) NumLinesWithHits() (numLinesWithHits int64) { - for _, pkg := range cov.Packages { - numLinesWithHits += pkg.NumLinesWithHits() - } - return numLinesWithHits -} diff --git a/tools/vendor/github.com/t-yuki/gocover-cobertura/gocover-cobertura.go b/tools/vendor/github.com/t-yuki/gocover-cobertura/gocover-cobertura.go deleted file mode 100644 index e64b5de02..000000000 --- a/tools/vendor/github.com/t-yuki/gocover-cobertura/gocover-cobertura.go +++ /dev/null @@ -1,176 +0,0 @@ -package main - -import ( - "encoding/xml" - "fmt" - "go/ast" - "go/build" - "go/parser" - "go/token" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "time" -) - -const coberturaDTDDecl = "\n" - -func main() { - convert(os.Stdin, os.Stdout) -} - -func convert(in io.Reader, out io.Writer) { - profiles, err := ParseProfiles(in) - if err != nil { - panic("Can't parse profiles") - } - - srcDirs := build.Default.SrcDirs() - sources := make([]*Source, len(srcDirs)) - for i, dir := range srcDirs { - sources[i] = &Source{dir} - } - - coverage := Coverage{Sources: sources, Packages: nil, Timestamp: time.Now().UnixNano() / int64(time.Millisecond)} - coverage.parseProfiles(profiles) - - fmt.Fprintf(out, xml.Header) - fmt.Fprintf(out, coberturaDTDDecl) - - encoder := xml.NewEncoder(out) - encoder.Indent("", "\t") - err = encoder.Encode(coverage) - if err != nil { - panic(err) - } - - fmt.Fprintln(out) -} - -func (cov *Coverage) parseProfiles(profiles []*Profile) error { - cov.Packages = []*Package{} - for _, profile := range profiles { - cov.parseProfile(profile) - } - cov.LinesValid = cov.NumLines() - cov.LinesCovered = cov.NumLinesWithHits() - cov.LineRate = cov.HitRate() - return nil -} - -func (cov *Coverage) parseProfile(profile *Profile) error { - fileName := profile.FileName - absFilePath, err := findFile(fileName) - if err != nil { - return err - } - fset := token.NewFileSet() - parsed, err := parser.ParseFile(fset, absFilePath, nil, 0) - if err != nil { - return err - } - data, err := ioutil.ReadFile(absFilePath) - if err != nil { - return err - } - - pkgPath, _ := filepath.Split(fileName) - pkgPath = strings.TrimRight(pkgPath, string(os.PathSeparator)) - - var pkg *Package - for _, p := range cov.Packages { - if p.Name == pkgPath { - pkg = p - } - } - if pkg == nil { - pkg = &Package{Name: pkgPath, Classes: []*Class{}} - cov.Packages = append(cov.Packages, pkg) - } - visitor := &fileVisitor{ - fset: fset, - fileName: fileName, - fileData: data, - classes: make(map[string]*Class), - pkg: pkg, - profile: profile, - } - ast.Walk(visitor, parsed) - pkg.LineRate = pkg.HitRate() - return nil -} - -type fileVisitor struct { - fset *token.FileSet - fileName string - fileData []byte - pkg *Package - classes map[string]*Class - profile *Profile -} - -func (v *fileVisitor) Visit(node ast.Node) ast.Visitor { - switch n := node.(type) { - case *ast.FuncDecl: - class := v.class(n) - method := v.method(n) - method.LineRate = method.Lines.HitRate() - class.Methods = append(class.Methods, method) - for _, line := range method.Lines { - class.Lines = append(class.Lines, line) - } - class.LineRate = class.Lines.HitRate() - } - return v -} - -func (v *fileVisitor) method(n *ast.FuncDecl) *Method { - method := &Method{Name: n.Name.Name} - method.Lines = []*Line{} - - start := v.fset.Position(n.Pos()) - end := v.fset.Position(n.End()) - startLine := start.Line - startCol := start.Column - endLine := end.Line - endCol := end.Column - // The blocks are sorted, so we can stop counting as soon as we reach the end of the relevant block. - for _, b := range v.profile.Blocks { - if b.StartLine > endLine || (b.StartLine == endLine && b.StartCol >= endCol) { - // Past the end of the function. - break - } - if b.EndLine < startLine || (b.EndLine == startLine && b.EndCol <= startCol) { - // Before the beginning of the function - continue - } - for i := b.StartLine; i <= b.EndLine; i++ { - method.Lines.AddOrUpdateLine(i, int64(b.Count)) - } - } - return method -} - -func (v *fileVisitor) class(n *ast.FuncDecl) *Class { - className := v.recvName(n) - var class *Class = v.classes[className] - if class == nil { - class = &Class{Name: className, Filename: v.fileName, Methods: []*Method{}, Lines: []*Line{}} - v.classes[className] = class - v.pkg.Classes = append(v.pkg.Classes, class) - } - return class -} - -func (v *fileVisitor) recvName(n *ast.FuncDecl) string { - if n.Recv == nil { - return "-" - } - recv := n.Recv.List[0].Type - start := v.fset.Position(recv.Pos()) - end := v.fset.Position(recv.End()) - name := string(v.fileData[start.Offset:end.Offset]) - return strings.TrimSpace(strings.TrimLeft(name, "*")) -} diff --git a/tools/vendor/github.com/t-yuki/gocover-cobertura/profile.go b/tools/vendor/github.com/t-yuki/gocover-cobertura/profile.go deleted file mode 100644 index 99cbac234..000000000 --- a/tools/vendor/github.com/t-yuki/gocover-cobertura/profile.go +++ /dev/null @@ -1,202 +0,0 @@ -// Imported from https://code.google.com/p/go/source/browse/cmd/cover/profile.go?repo=tools&r=c10a9dd5e0b0a859a8385b6f004584cb083a3934 - -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "bufio" - "fmt" - "go/build" - "io" - "math" - "os" - "path/filepath" - "regexp" - "sort" - "strconv" - "strings" -) - -// Profile represents the profiling data for a specific file. -type Profile struct { - FileName string - Mode string - Blocks []ProfileBlock -} - -// ProfileBlock represents a single block of profiling data. -type ProfileBlock struct { - StartLine, StartCol int - EndLine, EndCol int - NumStmt, Count int -} - -type byFileName []*Profile - -func (p byFileName) Len() int { return len(p) } -func (p byFileName) Less(i, j int) bool { return p[i].FileName < p[j].FileName } -func (p byFileName) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// ParseProfiles parses profile data from the given Reader and returns a -// Profile for each file. -func ParseProfiles(in io.Reader) ([]*Profile, error) { - files := make(map[string]*Profile) - // First line is "mode: foo", where foo is "set", "count", or "atomic". - // Rest of file is in the format - // encoding/base64/base64.go:34.44,37.40 3 1 - // where the fields are: name.go:line.column,line.column numberOfStatements count - s := bufio.NewScanner(in) - mode := "" - for s.Scan() { - line := s.Text() - if mode == "" { - const p = "mode: " - if !strings.HasPrefix(line, p) || line == p { - return nil, fmt.Errorf("bad mode line: %v", line) - } - mode = line[len(p):] - continue - } - m := lineRe.FindStringSubmatch(line) - if m == nil { - return nil, fmt.Errorf("line %q doesn't match expected format: %v", m, lineRe) - } - fn := m[1] - p := files[fn] - if p == nil { - p = &Profile{ - FileName: fn, - Mode: mode, - } - files[fn] = p - } - p.Blocks = append(p.Blocks, ProfileBlock{ - StartLine: toInt(m[2]), - StartCol: toInt(m[3]), - EndLine: toInt(m[4]), - EndCol: toInt(m[5]), - NumStmt: toInt(m[6]), - Count: toInt(m[7]), - }) - } - if err := s.Err(); err != nil { - return nil, err - } - for _, p := range files { - sort.Sort(blocksByStart(p.Blocks)) - } - // Generate a sorted slice. - profiles := make([]*Profile, 0, len(files)) - for _, profile := range files { - profiles = append(profiles, profile) - } - sort.Sort(byFileName(profiles)) - return profiles, nil -} - -type blocksByStart []ProfileBlock - -func (b blocksByStart) Len() int { return len(b) } -func (b blocksByStart) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b blocksByStart) Less(i, j int) bool { - bi, bj := b[i], b[j] - return bi.StartLine < bj.StartLine || bi.StartLine == bj.StartLine && bi.StartCol < bj.StartCol -} - -var lineRe = regexp.MustCompile(`^(.+):([0-9]+).([0-9]+),([0-9]+).([0-9]+) ([0-9]+) ([0-9]+)$`) - -func toInt(s string) int { - i, err := strconv.Atoi(s) - if err != nil { - panic(err) - } - return i -} - -// Boundary represents the position in a source file of the beginning or end of a -// block as reported by the coverage profile. In HTML mode, it will correspond to -// the opening or closing of a tag and will be used to colorize the source -type Boundary struct { - Offset int // Location as a byte offset in the source file. - Start bool // Is this the start of a block? - Count int // Event count from the cover profile. - Norm float64 // Count normalized to [0..1]. -} - -// Boundaries returns a Profile as a set of Boundary objects within the provided src. -func (p *Profile) Boundaries(src []byte) (boundaries []Boundary) { - // Find maximum count. - max := 0 - for _, b := range p.Blocks { - if b.Count > max { - max = b.Count - } - } - // Divisor for normalization. - divisor := math.Log(float64(max)) - - // boundary returns a Boundary, populating the Norm field with a normalized Count. - boundary := func(offset int, start bool, count int) Boundary { - b := Boundary{Offset: offset, Start: start, Count: count} - if !start || count == 0 { - return b - } - if max <= 1 { - b.Norm = 0.8 // Profile is in"set" mode; we want a heat map. Use cov8 in the CSS. - } else if count > 0 { - b.Norm = math.Log(float64(count)) / divisor - } - return b - } - - line, col := 1, 2 // TODO: Why is this 2? - for si, bi := 0, 0; si < len(src) && bi < len(p.Blocks); { - b := p.Blocks[bi] - if b.StartLine == line && b.StartCol == col { - boundaries = append(boundaries, boundary(si, true, b.Count)) - } - if b.EndLine == line && b.EndCol == col { - boundaries = append(boundaries, boundary(si, false, 0)) - bi++ - continue // Don't advance through src; maybe the next block starts here. - } - if src[si] == '\n' { - line++ - col = 0 - } - col++ - si++ - } - sort.Sort(boundariesByPos(boundaries)) - return -} - -type boundariesByPos []Boundary - -func (b boundariesByPos) Len() int { return len(b) } -func (b boundariesByPos) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b boundariesByPos) Less(i, j int) bool { - if b[i].Offset == b[j].Offset { - return !b[i].Start && b[j].Start - } - return b[i].Offset < b[j].Offset -} - -// findFile finds the location of the named file in GOROOT, GOPATH etc. -func findFile(file string) (string, error) { - if strings.HasPrefix(file, "_") { - file = file[1:] - } - if _, err := os.Stat(file); err == nil { - return file, nil - } - dir, file := filepath.Split(file) - pkg, err := build.Import(dir, ".", build.FindOnly) - if err != nil { - return "", fmt.Errorf("can't find %q: %v", file, err) - } - return filepath.Join(pkg.Dir, file), nil -} diff --git a/tools/vendor/github.com/tetafro/godot/.golangci.yml b/tools/vendor/github.com/tetafro/godot/.golangci.yml index 920135d40..ea380eb83 100644 --- a/tools/vendor/github.com/tetafro/godot/.golangci.yml +++ b/tools/vendor/github.com/tetafro/godot/.golangci.yml @@ -8,45 +8,53 @@ skip-dirs: linters: disable-all: true enable: - - deadcode - - errcheck - - gosimple - - govet - - ineffassign - - staticcheck - - structcheck - - typecheck - - unused - - varcheck + - asciicheck - bodyclose + - cyclop - dogsled - - dupl - - funlen + - durationcheck + - errcheck + - errname + - errorlint + - exhaustive + - exportloopref + - exportloopref - gochecknoinits + - gocognit - goconst - gocritic - gocyclo - godot + - goerr113 - gofmt - gofumpt - goimports - - golint - - gomnd - - gomodguard - goprintffuncname - gosec + - gosimple + - govet + - importas + - ineffassign - lll - - maligned - misspell - nakedret - nestif + - noctx + - nolintlint - prealloc + - revive - rowserrcheck - - scopelint + - sqlclosecheck + - sqlclosecheck + - staticcheck - stylecheck + - typecheck - unconvert - unparam + - unused + - wastedassign - whitespace + - wrapcheck linters-settings: godot: @@ -54,13 +62,19 @@ linters-settings: issues: exclude-use-default: false + exclude: + - "do not define dynamic errors, use wrapped static errors instead" exclude-rules: - path: _test\.go linters: - dupl - errcheck - funlen + - gocognit + - cyclop - gosec - - path: cmd/godot/main\.go + - noctx + - path: main\.go linters: + - cyclop - gomnd diff --git a/tools/vendor/github.com/tetafro/godot/checks.go b/tools/vendor/github.com/tetafro/godot/checks.go index f5471cdf7..0e53c220a 100644 --- a/tools/vendor/github.com/tetafro/godot/checks.go +++ b/tools/vendor/github.com/tetafro/godot/checks.go @@ -21,7 +21,7 @@ var ( // Abbreviations to exclude from capital letters check. abbreviations = []string{"i.e.", "i. e.", "e.g.", "e. g.", "etc."} - // Special tags in comments like "// nolint:", or "// +k8s:". + // Special tags in comments like "//nolint:", or "//+k8s:". tags = regexp.MustCompile(`^\+?[a-z0-9]+:`) // Special hashtags in comments like "// #nosec". @@ -31,18 +31,24 @@ var ( endURL = regexp.MustCompile(`[a-z]+://[^\s]+$`) ) +// position is a position inside a comment (might be multiline comment). +type position struct { + line int // starts at 1 + column int // starts at 1, byte count +} + // checkComments checks every comment accordings to the rules from // `settings` argument. func checkComments(comments []comment, settings Settings) []Issue { - var issues []Issue // nolint: prealloc + var issues []Issue for _, c := range comments { if settings.Period { - if iss := checkCommentForPeriod(c); iss != nil { + if iss := checkPeriod(c); iss != nil { issues = append(issues, *iss) } } if settings.Capital { - if iss := checkCommentForCapital(c); len(iss) > 0 { + if iss := checkCapital(c); len(iss) > 0 { issues = append(issues, iss...) } } @@ -50,14 +56,34 @@ func checkComments(comments []comment, settings Settings) []Issue { return issues } -// checkCommentForPeriod checks that the last sentense of the comment ends +// checkPeriod checks that the last sentense of the comment ends // in a period. -func checkCommentForPeriod(c comment) *Issue { - pos, ok := checkPeriod(c.text) - if ok { +func checkPeriod(c comment) *Issue { + // Check last non-empty line + var found bool + var line string + var pos position + lines := strings.Split(c.text, "\n") + for i := len(lines) - 1; i >= 0; i-- { + line = strings.TrimRightFunc(lines[i], unicode.IsSpace) + if line == "" { + continue + } + found = true + pos.line = i + 1 + break + } + // All lines are empty + if !found { + return nil + } + // Correct line + if hasSuffix(line, lastChars) { return nil } + pos.column = len(line) + 1 + // Shift position to its real value. `c.text` doesn't contain comment's // special symbols: /* or //, and line indentations inside. It also // contains */ in the end in case of block comment. @@ -94,95 +120,15 @@ func checkCommentForPeriod(c comment) *Issue { return &iss } -// checkCommentForCapital checks that each sentense of the comment starts with -// a capital letter. -// nolint: unparam -func checkCommentForCapital(c comment) []Issue { - pp := checkCapital(c.text, c.decl) - if len(pp) == 0 { - return nil - } - - issues := make([]Issue, len(pp)) - for i, pos := range pp { - // Shift position by the length of comment's special symbols: /* or // - isBlock := strings.HasPrefix(c.lines[0], "/*") - if (isBlock && pos.line == 1) || !isBlock { - pos.column += 2 - } - - iss := Issue{ - Pos: token.Position{ - Filename: c.start.Filename, - Offset: c.start.Offset, - Line: pos.line + c.start.Line - 1, - Column: pos.column + c.start.Column - 1, - }, - Message: noCapitalMessage, - } - - // Make a replacement. Use `pos.original` to get an original original from - // attached lines. Use `iss.Pos.Column` because it's a position in - // the original original. - original := c.lines[pos.line-1] - col := byteToRuneColumn(original, iss.Pos.Column) - 1 - rep := string(unicode.ToTitle([]rune(original)[col])) // capital letter - if len(original) < iss.Pos.Column-1+len(rep) { - // This should never happen. Avoid panics, skip this check. - continue - } - iss.Replacement = original[:iss.Pos.Column-1] + rep + - original[iss.Pos.Column-1+len(rep):] - - // Save replacement to raw lines to be able to combine it with - // further replacements - c.lines[pos.line-1] = iss.Replacement - - issues[i] = iss - } - - return issues -} - -// checkPeriod checks that the last sentense of the text ends in a period. -// NOTE: Returned position is a position inside given text, not in the -// original file. -func checkPeriod(comment string) (pos position, ok bool) { - // Check last non-empty line - var found bool - var line string - lines := strings.Split(comment, "\n") - for i := len(lines) - 1; i >= 0; i-- { - line = strings.TrimRightFunc(lines[i], unicode.IsSpace) - if line == "" { - continue - } - found = true - pos.line = i + 1 - break - } - // All lines are empty - if !found { - return position{}, true - } - // Correct line - if hasSuffix(line, lastChars) { - return position{}, true - } - - pos.column = len(line) + 1 - return pos, false -} - -// checkCapital checks that each sentense of the text starts with +// checkCapital checks that each sentense of the comment starts with // a capital letter. -// NOTE: First letter is not checked in declaration comments, because they -// can describe unexported functions, which start with small letter. -func checkCapital(comment string, skipFirst bool) (pp []position) { +// +//nolint:cyclop,funlen +func checkCapital(c comment) []Issue { // Remove common abbreviations from the comment for _, abbr := range abbreviations { repl := strings.ReplaceAll(abbr, ".", "_") - comment = strings.ReplaceAll(comment, abbr, repl) + c.text = strings.ReplaceAll(c.text, abbr, repl) } // List of states during the scan: `empty` - nothing special, @@ -190,12 +136,14 @@ func checkCapital(comment string, skipFirst bool) (pp []position) { // `endOfSentence` - found `endChar`, and then space or newline. const empty, endChar, endOfSentence = 1, 2, 3 + var pp []position pos := position{line: 1} state := endOfSentence - if skipFirst { + if c.decl { + // Skip first state = empty } - for _, r := range comment { + for _, r := range c.text { s := string(r) pos.column++ @@ -223,12 +171,54 @@ func checkCapital(comment string, skipFirst bool) (pp []position) { if state == endOfSentence && unicode.IsLower(r) { pp = append(pp, position{ line: pos.line, - column: runeToByteColumn(comment, pos.column), + column: runeToByteColumn(c.text, pos.column), }) } state = empty } - return pp + if len(pp) == 0 { + return nil + } + + issues := make([]Issue, len(pp)) + for i, pos := range pp { + // Shift position by the length of comment's special symbols: /* or // + isBlock := strings.HasPrefix(c.lines[0], "/*") + if (isBlock && pos.line == 1) || !isBlock { + pos.column += 2 + } + + iss := Issue{ + Pos: token.Position{ + Filename: c.start.Filename, + Offset: c.start.Offset, + Line: pos.line + c.start.Line - 1, + Column: pos.column + c.start.Column - 1, + }, + Message: noCapitalMessage, + } + + // Make a replacement. Use `pos.original` to get an original original from + // attached lines. Use `iss.Pos.Column` because it's a position in + // the original original. + original := c.lines[pos.line-1] + col := byteToRuneColumn(original, iss.Pos.Column) - 1 + rep := string(unicode.ToTitle([]rune(original)[col])) // capital letter + if len(original) < iss.Pos.Column-1+len(rep) { + // This should never happen. Avoid panics, skip this check. + continue + } + iss.Replacement = original[:iss.Pos.Column-1] + rep + + original[iss.Pos.Column-1+len(rep):] + + // Save replacement to raw lines to be able to combine it with + // further replacements + c.lines[pos.line-1] = iss.Replacement + + issues[i] = iss + } + + return issues } // isSpecialBlock checks that given block of comment lines is special and @@ -246,7 +236,7 @@ func isSpecialBlock(comment string) bool { return false } -// isSpecialBlock checks that given comment line is special and +// isSpecialLine checks that given comment line is special and // shouldn't be checked as a regular sentence. func isSpecialLine(comment string) bool { // Skip cgo export tags: https://golang.org/cmd/cgo/#hdr-C_references_to_Go diff --git a/tools/vendor/github.com/tetafro/godot/getters.go b/tools/vendor/github.com/tetafro/godot/getters.go index 1a47c824f..7d3d22fb1 100644 --- a/tools/vendor/github.com/tetafro/godot/getters.go +++ b/tools/vendor/github.com/tetafro/godot/getters.go @@ -44,7 +44,7 @@ func newParsedFile(file *ast.File, fset *token.FileSet) (*parsedFile, error) { // from "go/format" won't help here if the original file is not gofmt-ed. pf.lines, err = readFile(file, fset) if err != nil { - return nil, fmt.Errorf("read file: %v", err) + return nil, fmt.Errorf("read file: %w", err) } // Dirty hack. For some cases Go generates temporary files during @@ -58,9 +58,13 @@ func newParsedFile(file *ast.File, fset *token.FileSet) (*parsedFile, error) { return nil, errUnsuitableInput } - // Check consistency to avoid checking slice indexes in each function + // Check consistency to avoid checking slice indexes in each function. + // Note that `PositionFor` is used with `adjusted=false` to skip `//line` + // directives that can set references to other files (e.g. templates) + // instead of the real ones, and break consistency here. + // Issue: https://github.com/tetafro/godot/issues/32 lastComment := pf.file.Comments[len(pf.file.Comments)-1] - if p := pf.fset.Position(lastComment.End()); len(pf.lines) < p.Line { + if p := pf.fset.PositionFor(lastComment.End(), false); len(pf.lines) < p.Line { return nil, fmt.Errorf("inconsistency between file and AST: %s", p.Filename) } @@ -82,7 +86,7 @@ func (pf *parsedFile) getComments(scope Scope, exclude []*regexp.Regexp) []comme pf.getBlockComments(exclude), pf.getTopLevelComments(exclude)..., ) - default: + case DeclScope: // Top level declaration comments and comments from the inside // of top level blocks comments = append(pf.getBlockComments(exclude), decl...) @@ -118,7 +122,7 @@ func (pf *parsedFile) getBlockComments(exclude []*regexp.Regexp) []comment { // Skip comments that are not top-level for this block // (the block itself is top level, so comments inside this block // would be on column 2) - // nolint: gomnd + //nolint:gomnd if pf.fset.Position(c.Pos()).Column != 2 { continue } @@ -136,7 +140,7 @@ func (pf *parsedFile) getBlockComments(exclude []*regexp.Regexp) []comment { // getTopLevelComments gets all top level comments. func (pf *parsedFile) getTopLevelComments(exclude []*regexp.Regexp) []comment { - var comments []comment // nolint: prealloc + var comments []comment //nolint:prealloc for _, c := range pf.file.Comments { if c == nil || len(c.List) == 0 { continue @@ -157,7 +161,7 @@ func (pf *parsedFile) getTopLevelComments(exclude []*regexp.Regexp) []comment { // getDeclarationComments gets top level declaration comments. func (pf *parsedFile) getDeclarationComments(exclude []*regexp.Regexp) []comment { - var comments []comment // nolint: prealloc + var comments []comment //nolint:prealloc for _, decl := range pf.file.Decls { var cg *ast.CommentGroup switch d := decl.(type) { @@ -184,7 +188,7 @@ func (pf *parsedFile) getDeclarationComments(exclude []*regexp.Regexp) []comment // getAllComments gets every single comment from the file. func (pf *parsedFile) getAllComments(exclude []*regexp.Regexp) []comment { - var comments []comment //nolint: prealloc + var comments []comment //nolint:prealloc for _, c := range pf.file.Comments { if c == nil || len(c.List) == 0 { continue @@ -205,6 +209,8 @@ func (pf *parsedFile) getAllComments(exclude []*regexp.Regexp) []comment { // special lines (e.g., tags or indented code examples), they are replaced // with `specialReplacer` to skip checks for them. // The result can be multiline. +// +//nolint:cyclop func getText(comment *ast.CommentGroup, exclude []*regexp.Regexp) (s string) { if len(comment.List) == 1 && strings.HasPrefix(comment.List[0].Text, "/*") && @@ -246,7 +252,7 @@ func readFile(file *ast.File, fset *token.FileSet) ([]string, error) { fname := fset.File(file.Package) f, err := os.ReadFile(fname.Name()) if err != nil { - return nil, err + return nil, err //nolint:wrapcheck } return strings.Split(string(f), "\n"), nil } diff --git a/tools/vendor/github.com/tetafro/godot/godot.go b/tools/vendor/github.com/tetafro/godot/godot.go index df9271296..e825e9a6d 100644 --- a/tools/vendor/github.com/tetafro/godot/godot.go +++ b/tools/vendor/github.com/tetafro/godot/godot.go @@ -3,6 +3,7 @@ package godot import ( + "errors" "fmt" "go/ast" "go/token" @@ -24,12 +25,6 @@ type Issue struct { Replacement string } -// position is a position inside a comment (might be multiline comment). -type position struct { - line int // starts at 1 - column int // starts at 1, byte count -} - // comment is an internal representation of AST comment entity with additional // data attached. The latter is used for creating a full replacement for // the line with issues. @@ -43,18 +38,18 @@ type comment struct { // Run runs this linter on the provided code. func Run(file *ast.File, fset *token.FileSet, settings Settings) ([]Issue, error) { pf, err := newParsedFile(file, fset) - if err == errEmptyInput || err == errUnsuitableInput { + if errors.Is(err, errEmptyInput) || errors.Is(err, errUnsuitableInput) { return nil, nil } if err != nil { - return nil, fmt.Errorf("parse input file: %v", err) + return nil, fmt.Errorf("parse input file: %w", err) } exclude := make([]*regexp.Regexp, len(settings.Exclude)) for i := 0; i < len(settings.Exclude); i++ { exclude[i], err = regexp.Compile(settings.Exclude[i]) if err != nil { - return nil, fmt.Errorf("invalid regexp: %v", err) + return nil, fmt.Errorf("invalid regexp: %w", err) } } @@ -68,9 +63,9 @@ func Run(file *ast.File, fset *token.FileSet, settings Settings) ([]Issue, error // Fix fixes all issues and returns new version of file content. func Fix(path string, file *ast.File, fset *token.FileSet, settings Settings) ([]byte, error) { // Read file - content, err := os.ReadFile(path) // nolint: gosec + content, err := os.ReadFile(path) //nolint:gosec if err != nil { - return nil, fmt.Errorf("read file: %v", err) + return nil, fmt.Errorf("read file: %w", err) } if len(content) == 0 { return nil, nil @@ -78,7 +73,7 @@ func Fix(path string, file *ast.File, fset *token.FileSet, settings Settings) ([ issues, err := Run(file, fset, settings) if err != nil { - return nil, fmt.Errorf("run linter: %v", err) + return nil, fmt.Errorf("run linter: %w", err) } // slice -> map @@ -105,17 +100,17 @@ func Fix(path string, file *ast.File, fset *token.FileSet, settings Settings) ([ func Replace(path string, file *ast.File, fset *token.FileSet, settings Settings) error { info, err := os.Stat(path) if err != nil { - return fmt.Errorf("check file: %v", err) + return fmt.Errorf("check file: %w", err) } mode := info.Mode() fixed, err := Fix(path, file, fset, settings) if err != nil { - return fmt.Errorf("fix issues: %v", err) + return fmt.Errorf("fix issues: %w", err) } if err := os.WriteFile(path, fixed, mode); err != nil { - return fmt.Errorf("write file: %v", err) + return fmt.Errorf("write file: %w", err) } return nil } diff --git a/tools/vendor/github.com/tomarrell/wrapcheck/v2/wrapcheck/wrapcheck.go b/tools/vendor/github.com/tomarrell/wrapcheck/v2/wrapcheck/wrapcheck.go index 6da17bd86..79e7bba86 100644 --- a/tools/vendor/github.com/tomarrell/wrapcheck/v2/wrapcheck/wrapcheck.go +++ b/tools/vendor/github.com/tomarrell/wrapcheck/v2/wrapcheck/wrapcheck.go @@ -121,7 +121,20 @@ func run(cfg WrapcheckConfig) func(*analysis.Pass) (interface{}, error) { } for _, file := range pass.Files { + // Keep track of parents so that can can traverse upwards to check for + // FuncDecls and FuncLits. + var parents []ast.Node + ast.Inspect(file, func(n ast.Node) bool { + if n == nil { + // Pop, since we're done with this node and its children. + parents = parents[:len(parents)-1] + } else { + // Push this node on the stack, since its children will be visited + // next. + parents = append(parents, n) + } + ret, ok := n.(*ast.ReturnStmt) if !ok { return true @@ -137,6 +150,17 @@ func run(cfg WrapcheckConfig) func(*analysis.Pass) (interface{}, error) { // to handle it by checking the return params of the function. retFn, ok := expr.(*ast.CallExpr) if ok { + // If you go up, and the parent is a FuncLit, then don't report an + // error as you are in an anonymous function. If you are inside a + // FuncDecl, then continue as normal. + for i := len(parents) - 1; i > 0; i-- { + if _, ok := parents[i].(*ast.FuncLit); ok { + return true + } else if _, ok := parents[i].(*ast.FuncDecl); ok { + break + } + } + // If the return type of the function is a single error. This will not // match an error within multiple return values, for that, the below // tuple check is required. diff --git a/tools/vendor/github.com/ultraware/whitespace/README.md b/tools/vendor/github.com/ultraware/whitespace/README.md index 2a88f1338..f99ecce36 100644 --- a/tools/vendor/github.com/ultraware/whitespace/README.md +++ b/tools/vendor/github.com/ultraware/whitespace/README.md @@ -4,4 +4,6 @@ Whitespace is a linter that checks for unnecessary newlines at the start and end ## Installation guide -Whitespace is included in [golangci-lint](https://github.com/golangci/golangci-lint/). Install it and enable whitespace. +To install as a standalone linter, run `go install github.com/ultraware/whitespace`. + +Whitespace is also included in [golangci-lint](https://github.com/golangci/golangci-lint/). Install it and enable whitespace. diff --git a/tools/vendor/github.com/ultraware/whitespace/main.go b/tools/vendor/github.com/ultraware/whitespace/main.go deleted file mode 100644 index d178ea293..000000000 --- a/tools/vendor/github.com/ultraware/whitespace/main.go +++ /dev/null @@ -1,162 +0,0 @@ -package whitespace - -import ( - "go/ast" - "go/token" -) - -// Message contains a message -type Message struct { - Pos token.Position - Type MessageType - Message string -} - -// MessageType describes what should happen to fix the warning -type MessageType uint8 - -// List of MessageTypes -const ( - MessageTypeLeading MessageType = iota + 1 - MessageTypeTrailing - MessageTypeAddAfter -) - -// Settings contains settings for edge-cases -type Settings struct { - MultiIf bool - MultiFunc bool -} - -// Run runs this linter on the provided code -func Run(file *ast.File, fset *token.FileSet, settings Settings) []Message { - var messages []Message - - for _, f := range file.Decls { - decl, ok := f.(*ast.FuncDecl) - if !ok || decl.Body == nil { // decl.Body can be nil for e.g. cgo - continue - } - - vis := visitor{file.Comments, fset, nil, make(map[*ast.BlockStmt]bool), settings} - ast.Walk(&vis, decl) - - messages = append(messages, vis.messages...) - } - - return messages -} - -type visitor struct { - comments []*ast.CommentGroup - fset *token.FileSet - messages []Message - wantNewline map[*ast.BlockStmt]bool - settings Settings -} - -func (v *visitor) Visit(node ast.Node) ast.Visitor { - if node == nil { - return v - } - - if stmt, ok := node.(*ast.IfStmt); ok && v.settings.MultiIf { - checkMultiLine(v, stmt.Body, stmt.Cond) - } - - if stmt, ok := node.(*ast.FuncLit); ok && v.settings.MultiFunc { - checkMultiLine(v, stmt.Body, stmt.Type) - } - - if stmt, ok := node.(*ast.FuncDecl); ok && v.settings.MultiFunc { - checkMultiLine(v, stmt.Body, stmt.Type) - } - - if stmt, ok := node.(*ast.BlockStmt); ok { - wantNewline := v.wantNewline[stmt] - - comments := v.comments - if wantNewline { - comments = nil // Comments also count as a newline if we want a newline - } - first, last := firstAndLast(comments, v.fset, stmt.Pos(), stmt.End(), stmt.List) - - startMsg := checkStart(v.fset, stmt.Lbrace, first) - - if wantNewline && startMsg == nil { - v.messages = append(v.messages, Message{v.fset.Position(stmt.Pos()), MessageTypeAddAfter, `multi-line statement should be followed by a newline`}) - } else if !wantNewline && startMsg != nil { - v.messages = append(v.messages, *startMsg) - } - - if msg := checkEnd(v.fset, stmt.Rbrace, last); msg != nil { - v.messages = append(v.messages, *msg) - } - } - - return v -} - -func checkMultiLine(v *visitor, body *ast.BlockStmt, stmtStart ast.Node) { - start, end := posLine(v.fset, stmtStart.Pos()), posLine(v.fset, stmtStart.End()) - - if end > start { // Check only multi line conditions - v.wantNewline[body] = true - } -} - -func posLine(fset *token.FileSet, pos token.Pos) int { - return fset.Position(pos).Line -} - -func firstAndLast(comments []*ast.CommentGroup, fset *token.FileSet, start, end token.Pos, stmts []ast.Stmt) (ast.Node, ast.Node) { - if len(stmts) == 0 { - return nil, nil - } - - first, last := ast.Node(stmts[0]), ast.Node(stmts[len(stmts)-1]) - - for _, c := range comments { - if posLine(fset, c.Pos()) == posLine(fset, start) || posLine(fset, c.End()) == posLine(fset, end) { - continue - } - - if c.Pos() < start || c.End() > end { - continue - } - if c.Pos() < first.Pos() { - first = c - } - if c.End() > last.End() { - last = c - } - } - - return first, last -} - -func checkStart(fset *token.FileSet, start token.Pos, first ast.Node) *Message { - if first == nil { - return nil - } - - if posLine(fset, start)+1 < posLine(fset, first.Pos()) { - pos := fset.Position(start) - return &Message{pos, MessageTypeLeading, `unnecessary leading newline`} - } - - return nil -} - -func checkEnd(fset *token.FileSet, end token.Pos, last ast.Node) *Message { - if last == nil { - return nil - } - - if posLine(fset, end)-1 > posLine(fset, last.End()) { - pos := fset.Position(end) - return &Message{pos, MessageTypeTrailing, `unnecessary trailing newline`} - } - - return nil -} diff --git a/tools/vendor/github.com/ultraware/whitespace/whitespace.go b/tools/vendor/github.com/ultraware/whitespace/whitespace.go new file mode 100644 index 000000000..350e9b7e4 --- /dev/null +++ b/tools/vendor/github.com/ultraware/whitespace/whitespace.go @@ -0,0 +1,307 @@ +package whitespace + +import ( + "flag" + "go/ast" + "go/token" + "strings" + + "golang.org/x/tools/go/analysis" +) + +// MessageType describes what should happen to fix the warning. +type MessageType uint8 + +// List of MessageTypes. +const ( + MessageTypeRemove MessageType = iota + 1 + MessageTypeAdd +) + +// RunningMode describes the mode the linter is run in. This can be either +// native or golangci-lint. +type RunningMode uint8 + +const ( + RunningModeNative RunningMode = iota + RunningModeGolangCI +) + +// Message contains a message and diagnostic information. +type Message struct { + // Diagnostic is what position the diagnostic should be put at. This isn't + // always the same as the fix start, f.ex. when we fix trailing newlines we + // put the diagnostic at the right bracket but we fix between the end of the + // last statement and the bracket. + Diagnostic token.Pos + + // FixStart is the span start of the fix. + FixStart token.Pos + + // FixEnd is the span end of the fix. + FixEnd token.Pos + + // LineNumbers represent the actual line numbers in the file. This is set + // when finding the diagnostic to make it easier to suggest fixes in + // golangci-lint. + LineNumbers []int + + // MessageType represents the type of message it is. + MessageType MessageType + + // Message is the diagnostic to show. + Message string +} + +// Settings contains settings for edge-cases. +type Settings struct { + Mode RunningMode + MultiIf bool + MultiFunc bool +} + +// NewAnalyzer creates a new whitespace analyzer. +func NewAnalyzer(settings *Settings) *analysis.Analyzer { + if settings == nil { + settings = &Settings{} + } + + return &analysis.Analyzer{ + Name: "whitespace", + Doc: "Whitespace is a linter that checks for unnecessary newlines at the start and end of functions, if, for, etc.", + Flags: flags(settings), + Run: func(p *analysis.Pass) (any, error) { + Run(p, settings) + return nil, nil + }, + RunDespiteErrors: true, + } +} + +func flags(settings *Settings) flag.FlagSet { + flags := flag.NewFlagSet("", flag.ExitOnError) + flags.BoolVar(&settings.MultiIf, "multi-if", settings.MultiIf, "Check that multi line if-statements have a leading newline") + flags.BoolVar(&settings.MultiFunc, "multi-func", settings.MultiFunc, "Check that multi line functions have a leading newline") + + return *flags +} + +func Run(pass *analysis.Pass, settings *Settings) []Message { + messages := []Message{} + + for _, file := range pass.Files { + filename := pass.Fset.Position(file.Pos()).Filename + if !strings.HasSuffix(filename, ".go") { + continue + } + + fileMessages := runFile(file, pass.Fset, *settings) + + if settings.Mode == RunningModeGolangCI { + messages = append(messages, fileMessages...) + continue + } + + for _, message := range fileMessages { + pass.Report(analysis.Diagnostic{ + Pos: message.Diagnostic, + Category: "whitespace", + Message: message.Message, + SuggestedFixes: []analysis.SuggestedFix{ + { + TextEdits: []analysis.TextEdit{ + { + Pos: message.FixStart, + End: message.FixEnd, + NewText: []byte("\n"), + }, + }, + }, + }, + }) + } + } + + return messages +} + +func runFile(file *ast.File, fset *token.FileSet, settings Settings) []Message { + var messages []Message + + for _, f := range file.Decls { + decl, ok := f.(*ast.FuncDecl) + if !ok || decl.Body == nil { // decl.Body can be nil for e.g. cgo + continue + } + + vis := visitor{file.Comments, fset, nil, make(map[*ast.BlockStmt]bool), settings} + ast.Walk(&vis, decl) + + messages = append(messages, vis.messages...) + } + + return messages +} + +type visitor struct { + comments []*ast.CommentGroup + fset *token.FileSet + messages []Message + wantNewline map[*ast.BlockStmt]bool + settings Settings +} + +func (v *visitor) Visit(node ast.Node) ast.Visitor { + if node == nil { + return v + } + + if stmt, ok := node.(*ast.IfStmt); ok && v.settings.MultiIf { + checkMultiLine(v, stmt.Body, stmt.Cond) + } + + if stmt, ok := node.(*ast.FuncLit); ok && v.settings.MultiFunc { + checkMultiLine(v, stmt.Body, stmt.Type) + } + + if stmt, ok := node.(*ast.FuncDecl); ok && v.settings.MultiFunc { + checkMultiLine(v, stmt.Body, stmt.Type) + } + + if stmt, ok := node.(*ast.BlockStmt); ok { + wantNewline := v.wantNewline[stmt] + + comments := v.comments + if wantNewline { + comments = nil // Comments also count as a newline if we want a newline + } + + opening, first, last := firstAndLast(comments, v.fset, stmt) + startMsg := checkStart(v.fset, opening, first) + + if wantNewline && startMsg == nil && len(stmt.List) >= 1 { + v.messages = append(v.messages, Message{ + Diagnostic: opening, + FixStart: stmt.List[0].Pos(), + FixEnd: stmt.List[0].Pos(), + LineNumbers: []int{v.fset.PositionFor(stmt.List[0].Pos(), false).Line}, + MessageType: MessageTypeAdd, + Message: "multi-line statement should be followed by a newline", + }) + } else if !wantNewline && startMsg != nil { + v.messages = append(v.messages, *startMsg) + } + + if msg := checkEnd(v.fset, stmt.Rbrace, last); msg != nil { + v.messages = append(v.messages, *msg) + } + } + + return v +} + +func checkMultiLine(v *visitor, body *ast.BlockStmt, stmtStart ast.Node) { + start, end := posLine(v.fset, stmtStart.Pos()), posLine(v.fset, stmtStart.End()) + + if end > start { // Check only multi line conditions + v.wantNewline[body] = true + } +} + +func posLine(fset *token.FileSet, pos token.Pos) int { + return fset.PositionFor(pos, false).Line +} + +func firstAndLast(comments []*ast.CommentGroup, fset *token.FileSet, stmt *ast.BlockStmt) (token.Pos, ast.Node, ast.Node) { + openingPos := stmt.Lbrace + 1 + + if len(stmt.List) == 0 { + return openingPos, nil, nil + } + + first, last := ast.Node(stmt.List[0]), ast.Node(stmt.List[len(stmt.List)-1]) + + for _, c := range comments { + // If the comment is on the same line as the opening pos (initially the + // left bracket) but it starts after the pos the comment must be after + // the bracket and where that comment ends should be considered where + // the fix should start. + if posLine(fset, c.Pos()) == posLine(fset, openingPos) && c.Pos() > openingPos { + if posLine(fset, c.End()) != posLine(fset, openingPos) { + // This is a multiline comment that spans from the `LBrace` line + // to a line further down. This should always be seen as ok! + first = c + } else { + openingPos = c.End() + } + } + + if posLine(fset, c.Pos()) == posLine(fset, stmt.Pos()) || posLine(fset, c.End()) == posLine(fset, stmt.End()) { + continue + } + + if c.Pos() < stmt.Pos() || c.End() > stmt.End() { + continue + } + + if c.Pos() < first.Pos() { + first = c + } + + if c.End() > last.End() { + last = c + } + } + + return openingPos, first, last +} + +func checkStart(fset *token.FileSet, start token.Pos, first ast.Node) *Message { + if first == nil { + return nil + } + + if posLine(fset, start)+1 < posLine(fset, first.Pos()) { + return &Message{ + Diagnostic: start, + FixStart: start, + FixEnd: first.Pos(), + LineNumbers: linesBetween(fset, start, first.Pos()), + MessageType: MessageTypeRemove, + Message: "unnecessary leading newline", + } + } + + return nil +} + +func checkEnd(fset *token.FileSet, end token.Pos, last ast.Node) *Message { + if last == nil { + return nil + } + + if posLine(fset, end)-1 > posLine(fset, last.End()) { + return &Message{ + Diagnostic: end, + FixStart: last.End(), + FixEnd: end, + LineNumbers: linesBetween(fset, last.End(), end), + MessageType: MessageTypeRemove, + Message: "unnecessary trailing newline", + } + } + + return nil +} + +func linesBetween(fset *token.FileSet, a, b token.Pos) []int { + lines := []int{} + aPosition := fset.PositionFor(a, false) + bPosition := fset.PositionFor(b, false) + + for i := aPosition.Line + 1; i < bPosition.Line; i++ { + lines = append(lines, i) + } + + return lines +} diff --git a/tools/vendor/github.com/uudashr/gocognit/README.md b/tools/vendor/github.com/uudashr/gocognit/README.md index 57f31cf74..c15f61bcf 100644 --- a/tools/vendor/github.com/uudashr/gocognit/README.md +++ b/tools/vendor/github.com/uudashr/gocognit/README.md @@ -1,4 +1,6 @@ -[![GoDoc](https://godoc.org/github.com/uudashr/gocognit?status.svg)](https://godoc.org/github.com/uudashr/gocognit) +[![Go Reference](https://pkg.go.dev/badge/github.com/uudashr/gocognit.svg)](https://pkg.go.dev/github.com/uudashr/gocognit) +[![go-recipes](https://raw.githubusercontent.com/nikolaydubina/go-recipes/main/badge.svg?raw=true)](https://github.com/nikolaydubina/go-recipes) + # Gocognit Gocognit calculates cognitive complexities of functions (and methods) in Go source code. A measurement of how hard does the code is intuitively to understand. @@ -223,4 +225,4 @@ func IgnoreMe() { ## Related project - [Gocyclo](https://github.com/fzipp/gocyclo) where the code are based on. -- [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) white paper by G. Ann Campbell. \ No newline at end of file +- [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) white paper by G. Ann Campbell. diff --git a/tools/vendor/github.com/yeya24/promlinter/promlinter.go b/tools/vendor/github.com/yeya24/promlinter/promlinter.go index 2ed4d60a8..17a7f4c3e 100644 --- a/tools/vendor/github.com/yeya24/promlinter/promlinter.go +++ b/tools/vendor/github.com/yeya24/promlinter/promlinter.go @@ -82,6 +82,23 @@ type MetricFamilyWithPos struct { Pos token.Position } +func (m *MetricFamilyWithPos) Labels() []string { + var arr []string + if len(m.MetricFamily.Metric) > 0 { + for _, label := range m.MetricFamily.Metric[0].Label { + if label.Value != nil { + arr = append(arr, + fmt.Sprintf("%s=%s", + strings.Trim(*label.Name, `"`), + strings.Trim(*label.Value, `"`))) + } else { + arr = append(arr, strings.Trim(*label.Name, `"`)) + } + } + } + return arr +} + type visitor struct { fs *token.FileSet metrics []MetricFamilyWithPos @@ -93,6 +110,12 @@ type opt struct { namespace string subsystem string name string + + help string + helpSet bool + + labels []string + constLabels map[string]string } func RunList(fs *token.FileSet, files []*ast.File, strict bool) []MetricFamilyWithPos { @@ -151,9 +174,6 @@ func RunLint(fs *token.FileSet, files []*ast.File, s Setting) []Issue { } } - sort.Slice(v.issues, func(i, j int) bool { - return v.issues[i].Pos.String() < v.issues[j].Pos.String() - }) return v.issues } @@ -168,11 +188,23 @@ func (v *visitor) Visit(n ast.Node) ast.Visitor { case *ast.SendStmt: return v.parseSendMetricChanExpr(t) + + default: } return v } +func (v *visitor) addMetric(mfp *MetricFamilyWithPos) { + for _, m := range v.metrics { + if mfp.MetricFamily.String() == m.MetricFamily.String() { + return + } + } + + v.metrics = append(v.metrics, *mfp) +} + func (v *visitor) parseCallerExpr(call *ast.CallExpr) ast.Visitor { var ( metricType dto.MetricType @@ -190,16 +222,17 @@ func (v *visitor) parseCallerExpr(call *ast.CallExpr) ast.Visitor { */ case *ast.Ident: if stmt.Name == "NewCounterFunc" { - return v.parseOpts(call.Args[0], dto.MetricType_COUNTER) + return v.parseOpts(call.Args, dto.MetricType_COUNTER) } if stmt.Name == "NewGaugeFunc" { - return v.parseOpts(call.Args[0], dto.MetricType_GAUGE) + return v.parseOpts(call.Args, dto.MetricType_GAUGE) } if metricType, ok = metricsType[stmt.Name]; !ok { return v } + methodName = stmt.Name /* @@ -216,11 +249,11 @@ func (v *visitor) parseCallerExpr(call *ast.CallExpr) ast.Visitor { */ case *ast.SelectorExpr: if stmt.Sel.Name == "NewCounterFunc" { - return v.parseOpts(call.Args[0], dto.MetricType_COUNTER) + return v.parseOpts(call.Args, dto.MetricType_COUNTER) } if stmt.Sel.Name == "NewGaugeFunc" { - return v.parseOpts(call.Args[0], dto.MetricType_GAUGE) + return v.parseOpts(call.Args, dto.MetricType_GAUGE) } if stmt.Sel.Name == "NewFamilyGenerator" && len(call.Args) == 5 { @@ -230,6 +263,7 @@ func (v *visitor) parseCallerExpr(call *ast.CallExpr) ast.Visitor { if metricType, ok = metricsType[stmt.Sel.Name]; !ok { return v } + methodName = stmt.Sel.Name default: @@ -254,19 +288,44 @@ func (v *visitor) parseCallerExpr(call *ast.CallExpr) ast.Visitor { return v } - return v.parseOpts(call.Args[0], metricType) + return v.parseOpts(call.Args, metricType) } -func (v *visitor) parseOpts(optArg ast.Node, metricType dto.MetricType) ast.Visitor { +func (v *visitor) parseOpts(optArgs []ast.Expr, metricType dto.MetricType) ast.Visitor { // position for the first arg of the CallExpr - optsPosition := v.fs.Position(optArg.Pos()) - opts, help := v.parseOptsExpr(optArg) + optsPosition := v.fs.Position(optArgs[0].Pos()) + opts := v.parseOptsExpr(optArgs[0]) + + var metric *dto.Metric + if len(optArgs) > 1 { + // parse labels + if labelOpts := v.parseOptsExpr(optArgs[1]); labelOpts != nil && len(labelOpts.labels) > 0 { + metric = &dto.Metric{} + for idx, _ := range labelOpts.labels { + metric.Label = append(metric.Label, + &dto.LabelPair{ + Name: &labelOpts.labels[idx], + }) + } + } + } + if opts == nil { return v } + currentMetric := dto.MetricFamily{ Type: &metricType, - Help: help, + } + + if !opts.helpSet { + currentMetric.Help = nil + } else { + currentMetric.Help = &opts.help + } + + if metric != nil { + currentMetric.Metric = append(currentMetric.Metric, metric) } metricName := prometheus.BuildFQName(opts.namespace, opts.subsystem, opts.name) @@ -278,7 +337,7 @@ func (v *visitor) parseOpts(optArg ast.Node, metricType dto.MetricType) ast.Visi } currentMetric.Name = &metricName - v.metrics = append(v.metrics, MetricFamilyWithPos{MetricFamily: ¤tMetric, Pos: optsPosition}) + v.addMetric(&MetricFamilyWithPos{MetricFamily: ¤tMetric, Pos: optsPosition}) return v } @@ -307,7 +366,8 @@ func (v *visitor) parseKSMMetrics(nameArg ast.Node, helpArg ast.Node, metricType } } - v.metrics = append(v.metrics, MetricFamilyWithPos{MetricFamily: ¤tMetric, Pos: optsPosition}) + v.addMetric(&MetricFamilyWithPos{MetricFamily: ¤tMetric, Pos: optsPosition}) + return v } @@ -347,15 +407,40 @@ func (v *visitor) parseSendMetricChanExpr(chExpr *ast.SendStmt) ast.Visitor { return v } - name, help := v.parseConstMetricOptsExpr(call.Args[0]) - if name == nil { + if len(call.Args) == 0 { + return v + } + + descCall := v.parseConstMetricOptsExpr(call.Args[0]) + if descCall == nil { return v } metric := &dto.MetricFamily{ - Name: name, - Help: help, + Name: descCall.name, + Help: descCall.help, } + + if len(descCall.labels) > 0 { + m := &dto.Metric{} + for idx, _ := range descCall.labels { + m.Label = append(m.Label, + &dto.LabelPair{ + Name: &descCall.labels[idx], + }) + } + + for idx, _ := range descCall.constLabels { + m.Label = append(m.Label, + &dto.LabelPair{ + Name: &descCall.constLabels[idx][0], + Value: &descCall.constLabels[idx][1], + }) + } + + metric.Metric = append(metric.Metric, m) + } + switch methodName { case "MustNewConstMetric", "NewLazyConstMetric": switch t := call.Args[1].(type) { @@ -373,11 +458,11 @@ func (v *visitor) parseSendMetricChanExpr(chExpr *ast.SendStmt) ast.Visitor { metric.Type = &metricType } - v.metrics = append(v.metrics, MetricFamilyWithPos{MetricFamily: metric, Pos: v.fs.Position(call.Pos())}) + v.addMetric(&MetricFamilyWithPos{MetricFamily: metric, Pos: v.fs.Position(call.Pos())}) return v } -func (v *visitor) parseOptsExpr(n ast.Node) (*opt, *string) { +func (v *visitor) parseOptsExpr(n ast.Node) *opt { switch stmt := n.(type) { case *ast.CompositeLit: return v.parseCompositeOpts(stmt) @@ -395,17 +480,49 @@ func (v *visitor) parseOptsExpr(n ast.Node) (*opt, *string) { return v.parseOptsExpr(stmt.X) } - return nil, nil + return nil } -func (v *visitor) parseCompositeOpts(stmt *ast.CompositeLit) (*opt, *string) { +func (v *visitor) parseCompositeOpts(stmt *ast.CompositeLit) *opt { metricOption := &opt{} - var help *string + for _, elt := range stmt.Elts { + + // labels + label, ok := elt.(*ast.BasicLit) + if ok { + metricOption.labels = append(metricOption.labels, strings.Trim(label.Value, `"`)) + continue + } + kvExpr, ok := elt.(*ast.KeyValueExpr) if !ok { continue } + + // const labels + if key, ok := kvExpr.Key.(*ast.BasicLit); ok { + + if metricOption.constLabels == nil { + metricOption.constLabels = map[string]string{} + } + + // only accept literal string value + // + // { + // "key": "some-string-literal", + // } + switch val := kvExpr.Value.(type) { + case *ast.BasicLit: + metricOption.constLabels[key.Value] = val.Value + + default: + metricOption.constLabels[key.Value] = "?" // use a placeholder for the const label + } + + continue + } + object, ok := kvExpr.Key.(*ast.Ident) if !ok { continue @@ -418,7 +535,7 @@ func (v *visitor) parseCompositeOpts(stmt *ast.CompositeLit) (*opt, *string) { // If failed to parse field value, stop parsing. stringLiteral, ok := v.parseValue(object.Name, kvExpr.Value) if !ok { - return nil, nil + return nil } switch object.Name { @@ -429,14 +546,16 @@ func (v *visitor) parseCompositeOpts(stmt *ast.CompositeLit) (*opt, *string) { case "Name": metricOption.name = stringLiteral case "Help": - help = &stringLiteral + metricOption.help = stringLiteral + metricOption.helpSet = true } } - return metricOption, help + return metricOption } func (v *visitor) parseValue(object string, n ast.Node) (string, bool) { + switch t := n.(type) { // make sure it is string literal value @@ -452,14 +571,26 @@ func (v *visitor) parseValue(object string, n ast.Node) (string, bool) { return "", false } - if vs, ok := t.Obj.Decl.(*ast.ValueSpec); ok { + switch vs := t.Obj.Decl.(type) { + + case *ast.ValueSpec: + // var some string = "some string" return v.parseValue(object, vs) + + case *ast.AssignStmt: + // TODO: + // some := "some string" + return "", false + + default: + return "", false } case *ast.ValueSpec: if len(t.Values) == 0 { return "", false } + return v.parseValue(object, t.Values[0]) // For binary expr, we only support adding two strings like `foo` + `bar`. @@ -539,7 +670,7 @@ func (v *visitor) parseValueCallExpr(object string, call *ast.CallExpr) (string, return "", false } -func (v *visitor) parseConstMetricOptsExpr(n ast.Node) (*string, *string) { +func (v *visitor) parseConstMetricOptsExpr(n ast.Node) *descCallExpr { switch stmt := n.(type) { case *ast.CallExpr: return v.parseNewDescCallExpr(stmt) @@ -580,10 +711,16 @@ func (v *visitor) parseConstMetricOptsExpr(n ast.Node) (*string, *string) { } } - return nil, nil + return nil } -func (v *visitor) parseNewDescCallExpr(call *ast.CallExpr) (*string, *string) { +type descCallExpr struct { + name, help *string + labels []string + constLabels [][2]string +} + +func (v *visitor) parseNewDescCallExpr(call *ast.CallExpr) *descCallExpr { var ( help string name string @@ -600,7 +737,7 @@ func (v *visitor) parseNewDescCallExpr(call *ast.CallExpr) (*string, *string) { Text: fmt.Sprintf("parsing desc with function %s is not supported", expr.Name), }) } - return nil, nil + return nil } case *ast.SelectorExpr: if expr.Sel.Name != "NewDesc" { @@ -611,7 +748,7 @@ func (v *visitor) parseNewDescCallExpr(call *ast.CallExpr) (*string, *string) { Text: fmt.Sprintf("parsing desc with function %s is not supported", expr.Sel.Name), }) } - return nil, nil + return nil } default: if v.strict { @@ -621,7 +758,7 @@ func (v *visitor) parseNewDescCallExpr(call *ast.CallExpr) (*string, *string) { Text: fmt.Sprintf("parsing desc of %T is not supported", expr), }) } - return nil, nil + return nil } // k8s.io/component-base/metrics.NewDesc has 6 args @@ -632,19 +769,45 @@ func (v *visitor) parseNewDescCallExpr(call *ast.CallExpr) (*string, *string) { Pos: v.fs.Position(call.Pos()), Text: "NewDesc should have at least 4 args", }) - return nil, nil + return nil } name, ok = v.parseValue("fqName", call.Args[0]) if !ok { - return nil, nil + return nil } + help, ok = v.parseValue("help", call.Args[1]) if !ok { - return nil, nil + return nil + } + + res := &descCallExpr{ + name: &name, + help: &help, + } + + if x, ok := call.Args[2].(*ast.CompositeLit); ok { + opt := v.parseCompositeOpts(x) + if opt == nil { + return nil + } + + res.labels = opt.labels + } + + if x, ok := call.Args[3].(*ast.CompositeLit); ok { + opt := v.parseCompositeOpts(x) + if opt == nil { + return nil + } + + for k, v := range opt.constLabels { + res.constLabels = append(res.constLabels, [2]string{k, v}) + } } - return &name, &help + return res } func mustUnquote(str string) string { diff --git a/tools/vendor/github.com/ykadowak/zerologlint/.goreleaser.yaml b/tools/vendor/github.com/ykadowak/zerologlint/.goreleaser.yaml index c1b23f00e..f3af3f212 100644 --- a/tools/vendor/github.com/ykadowak/zerologlint/.goreleaser.yaml +++ b/tools/vendor/github.com/ykadowak/zerologlint/.goreleaser.yaml @@ -11,13 +11,6 @@ builds: - linux - windows - darwin -archives: - - replacements: - darwin: Darwin - linux: Linux - windows: Windows - 386: i386 - amd64: x86_64 checksum: name_template: 'checksums.txt' snapshot: diff --git a/tools/vendor/github.com/ykadowak/zerologlint/zerologlint.go b/tools/vendor/github.com/ykadowak/zerologlint/zerologlint.go index bec50e52b..8c8fb74fc 100644 --- a/tools/vendor/github.com/ykadowak/zerologlint/zerologlint.go +++ b/tools/vendor/github.com/ykadowak/zerologlint/zerologlint.go @@ -13,8 +13,8 @@ import ( ) var Analyzer = &analysis.Analyzer{ - Name: "zerologlinter", - Doc: "finds cases where zerolog methods are not followed by Msg or Send", + Name: "zerologlint", + Doc: "Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg`", Run: run, Requires: []*analysis.Analyzer{ buildssa.Analyzer, @@ -26,42 +26,65 @@ type posser interface { Pos() token.Pos } -// posser is an interface just to hold both ssa.Call and ssa.Defer in our set +// callDefer is an interface just to hold both ssa.Call and ssa.Defer in our set type callDefer interface { Common() *ssa.CallCommon Pos() token.Pos } -func run(pass *analysis.Pass) (interface{}, error) { - srcFuncs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs - - // This set holds all the ssa block that is a zerolog.Event type instance +type linter struct { + // eventSet holds all the ssa block that is a zerolog.Event type instance // that should be dispatched. // Everytime the zerolog.Event is dispatched with Msg() or Send(), // deletes that block from this set. // At the end, check if the set is empty, or report the not dispatched block. - set := make(map[posser]struct{}) + eventSet map[posser]struct{} + // deleteLater holds the ssa block that should be deleted from eventSet after + // all the inspection is done. + // this is required because `else` ssa block comes after the dispatch of `if`` block. + // e.g., if err != nil { log.Error() } else { log.Info() } log.Send() + // deleteLater takes care of the log.Info() block. + deleteLater map[posser]struct{} + recLimit uint +} + +func run(pass *analysis.Pass) (interface{}, error) { + srcFuncs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs + + l := &linter{ + eventSet: make(map[posser]struct{}), + deleteLater: make(map[posser]struct{}), + recLimit: 100, + } for _, sf := range srcFuncs { for _, b := range sf.Blocks { for _, instr := range b.Instrs { if c, ok := instr.(*ssa.Call); ok { - inspect(c, &set) + l.inspect(c) } else if c, ok := instr.(*ssa.Defer); ok { - inspect(c, &set) + l.inspect(c) } } } } + + // apply deleteLater to envetSet for else branches of if-else cases + + for k := range l.deleteLater { + delete(l.eventSet, k) + } + // At the end, if the set is clear -> ok. - // Otherwise, there must be a left zerolog.Event var that weren't dispached. So report it. - for k := range set { + // Otherwise, there must be a left zerolog.Event var that weren't dispatched. So report it. + for k := range l.eventSet { pass.Reportf(k.Pos(), "must be dispatched by Msg or Send method") } + return nil, nil } -func inspect(cd callDefer, set *map[posser]struct{}) { +func (l *linter) inspect(cd callDefer) { c := cd.Common() // check if it's in github.com/rs/zerolog/log since there's some @@ -70,7 +93,7 @@ func inspect(cd callDefer, set *map[posser]struct{}) { if isInLogPkg(*c) || isLoggerRecv(*c) { if isZerologEvent(c.Value) { // this ssa block should be dispatched afterwards at some point - (*set)[cd] = struct{}{} + l.eventSet[cd] = struct{}{} return } } @@ -88,7 +111,7 @@ func inspect(cd callDefer, set *map[posser]struct{}) { for _, p := range f.Params { if isZerologEvent(p) { // check if this zerolog.Event as a parameter is dispatched in the function - // TODO: specifically, it can be dispatched in another function that is called in this function, and + // TODO: technically, it can be dispatched in another function that is called in this function, and // this algorithm cannot track that. But I'm tired of thinking about that for now. for _, b := range f.Blocks { for _, instr := range b.Instrs { @@ -96,10 +119,12 @@ func inspect(cd callDefer, set *map[posser]struct{}) { case *ssa.Call: if inspectDispatchInFunction(v.Common()) { shouldReturn = false + break } case *ssa.Defer: if inspectDispatchInFunction(v.Common()) { shouldReturn = false + break } } } @@ -112,19 +137,56 @@ func inspect(cd callDefer, set *map[posser]struct{}) { } for _, arg := range c.Args { if isZerologEvent(arg) { - val := getRootSsaValue(arg) - // if there's branch, remove both ways from the set - if phi, ok := val.(*ssa.Phi); ok { + // if there's branch, track both ways + // this is for the case like: + // logger := log.Info() + // if err != nil { + // logger = log.Error() + // } + // logger.Send() + // + // Similar case like below goes to the same root but that doesn't + // have any side effect. + // logger := log.Info() + // if err != nil { + // logger = logger.Str("a", "b") + // } + // logger.Send() + if phi, ok := arg.(*ssa.Phi); ok { for _, edge := range phi.Edges { - delete(*set, edge) + l.dfsEdge(edge, make(map[ssa.Value]struct{}), 0) } } else { - delete(*set, val) + val := getRootSsaValue(arg) + delete(l.eventSet, val) } } } } +func (l *linter) dfsEdge(v ssa.Value, visit map[ssa.Value]struct{}, cnt uint) { + // only for safety + if cnt > l.recLimit { + return + } + cnt++ + + if _, ok := visit[v]; ok { + return + } + visit[v] = struct{}{} + + val := getRootSsaValue(v) + phi, ok := val.(*ssa.Phi) + if !ok { + l.deleteLater[val] = struct{}{} + return + } + for _, edge := range phi.Edges { + l.dfsEdge(edge, visit, cnt) + } +} + func inspectDispatchInFunction(cc *ssa.CallCommon) bool { if isDispatchMethod(cc.StaticCallee()) { for _, arg := range cc.Args { diff --git a/tools/vendor/gitlab.com/bosi/decorder/.gitlab-ci.yml b/tools/vendor/gitlab.com/bosi/decorder/.gitlab-ci.yml index 73e1273b3..0e7ed1b7a 100644 --- a/tools/vendor/gitlab.com/bosi/decorder/.gitlab-ci.yml +++ b/tools/vendor/gitlab.com/bosi/decorder/.gitlab-ci.yml @@ -12,7 +12,7 @@ stages: test: stage: test - image: golang:1.21.0@sha256:b490ae1f0ece153648dd3c5d25be59a63f966b5f9e1311245c947de4506981aa + image: golang:1.22.2@sha256:450e3822c7a135e1463cd83e51c8e2eb03b86a02113c89424e6f0f8344bb4168 before_script: - set -eu - if [[ -f .env.pipeline ]];then cp .env.pipeline .env;fi @@ -27,7 +27,7 @@ test: lint:source-code: stage: test - image: golangci/golangci-lint:v1.54.2-alpine@sha256:e950721f6ae622dcc041f57cc0b61c3a78d4bbfc588facfc8b0166901a9f4848 + image: golangci/golangci-lint:v1.55.2-alpine@sha256:22e4dd2bba6ad3c6ef918432b92329b51e82d55e470d268d315bfff6a160bceb script: - apk add make bash - make settings @@ -36,7 +36,7 @@ lint:source-code: license-check: stage: test - image: golang:1.21.0@sha256:b490ae1f0ece153648dd3c5d25be59a63f966b5f9e1311245c947de4506981aa + image: golang:1.22.2@sha256:450e3822c7a135e1463cd83e51c8e2eb03b86a02113c89424e6f0f8344bb4168 before_script: - set -eu - if [[ -f .env.pipeline ]];then cp .env.pipeline .env;fi @@ -53,7 +53,7 @@ license-check: pages: stage: release - image: golang:1.21.0@sha256:b490ae1f0ece153648dd3c5d25be59a63f966b5f9e1311245c947de4506981aa + image: golang:1.22.2@sha256:450e3822c7a135e1463cd83e51c8e2eb03b86a02113c89424e6f0f8344bb4168 only: - tags script: diff --git a/tools/vendor/go.tmz.dev/musttag/.golangci.yml b/tools/vendor/go-simpler.org/musttag/.golangci.yml similarity index 100% rename from tools/vendor/go.tmz.dev/musttag/.golangci.yml rename to tools/vendor/go-simpler.org/musttag/.golangci.yml diff --git a/tools/vendor/go.tmz.dev/musttag/.goreleaser.yml b/tools/vendor/go-simpler.org/musttag/.goreleaser.yml similarity index 55% rename from tools/vendor/go.tmz.dev/musttag/.goreleaser.yml rename to tools/vendor/go-simpler.org/musttag/.goreleaser.yml index 259080886..dd75ac945 100644 --- a/tools/vendor/go.tmz.dev/musttag/.goreleaser.yml +++ b/tools/vendor/go-simpler.org/musttag/.goreleaser.yml @@ -16,12 +16,3 @@ archives: - format_overrides: - goos: windows format: zip - -brews: - - tap: - owner: tmzane - name: homebrew-tap - token: '{{ .Env.HOMEBREW_TAP_TOKEN }}' - homepage: https://github.com/tmzane/musttag - description: A Go linter that enforces field tags in (un)marshaled structs - license: MPL-2.0 diff --git a/tools/vendor/go.tmz.dev/musttag/LICENSE b/tools/vendor/go-simpler.org/musttag/LICENSE similarity index 100% rename from tools/vendor/go.tmz.dev/musttag/LICENSE rename to tools/vendor/go-simpler.org/musttag/LICENSE diff --git a/tools/vendor/go-simpler.org/musttag/Makefile b/tools/vendor/go-simpler.org/musttag/Makefile new file mode 100644 index 000000000..6165b16f4 --- /dev/null +++ b/tools/vendor/go-simpler.org/musttag/Makefile @@ -0,0 +1,28 @@ +.POSIX: +.SUFFIXES: + +all: test lint + +test: + go test -race -shuffle=on -cover ./... + +test/cover: + go test -race -shuffle=on -coverprofile=coverage.out ./... + go tool cover -html=coverage.out + +lint: + golangci-lint run + +tidy: + go mod tidy + +generate: + go generate ./... + +# run `make pre-commit` once to install the hook. +pre-commit: .git/hooks/pre-commit test lint tidy generate + git diff --exit-code + +.git/hooks/pre-commit: + echo "make pre-commit" > .git/hooks/pre-commit + chmod +x .git/hooks/pre-commit diff --git a/tools/vendor/go-simpler.org/musttag/README.md b/tools/vendor/go-simpler.org/musttag/README.md new file mode 100644 index 000000000..3f3a25330 --- /dev/null +++ b/tools/vendor/go-simpler.org/musttag/README.md @@ -0,0 +1,102 @@ +# musttag + +[![checks](https://github.com/go-simpler/musttag/actions/workflows/checks.yml/badge.svg)](https://github.com/go-simpler/musttag/actions/workflows/checks.yml) +[![pkg.go.dev](https://pkg.go.dev/badge/go-simpler.org/musttag.svg)](https://pkg.go.dev/go-simpler.org/musttag) +[![goreportcard](https://goreportcard.com/badge/go-simpler.org/musttag)](https://goreportcard.com/report/go-simpler.org/musttag) +[![codecov](https://codecov.io/gh/go-simpler/musttag/branch/main/graph/badge.svg)](https://codecov.io/gh/go-simpler/musttag) + +A Go linter that enforces field tags in (un)marshaled structs. + +## 📌 About + +`musttag` checks that exported fields of a struct passed to a `Marshal`-like function are annotated with the relevant tag: + +```go +// BAD: +var user struct { + Name string +} +data, err := json.Marshal(user) + +// GOOD: +var user struct { + Name string `json:"name"` +} +data, err := json.Marshal(user) +``` + +The rational from [Uber Style Guide][1]: + +> The serialized form of the structure is a contract between different systems. +> Changes to the structure of the serialized form, including field names, break this contract. +> Specifying field names inside tags makes the contract explicit, +> and it guards against accidentally breaking the contract by refactoring or renaming fields. + +## 🚀 Features + +The following packages are supported out of the box: + +* [encoding/json][2] +* [encoding/xml][3] +* [gopkg.in/yaml.v3][4] +* [github.com/BurntSushi/toml][5] +* [github.com/mitchellh/mapstructure][6] +* [github.com/jmoiron/sqlx][7] + +In addition, any [custom package](#custom-packages) can be added to the list. + +## 📦 Install + +`musttag` is integrated into [`golangci-lint`][8], and this is the recommended way to use it. + +To enable the linter, add the following lines to `.golangci.yml`: + +```yaml +linters: + enable: + - musttag +``` + +Alternatively, you can download a prebuilt binary from the [Releases][9] page to use `musttag` standalone. + +## 📋 Usage + +Run `golangci-lint` with `musttag` enabled. +See the list of [available options][10] to configure the linter. + +When using `musttag` standalone, pass the options as flags. + +### Custom packages + +To report a custom function, you need to add its description to `.golangci.yml`. +The following is an example of adding support for [`hclsimple.Decode`][11]: + +```yaml +linters-settings: + musttag: + functions: + # The full name of the function, including the package. + - name: github.com/hashicorp/hcl/v2/hclsimple.Decode + # The struct tag whose presence should be ensured. + tag: hcl + # The position of the argument to check. + arg-pos: 2 +``` + +The same can be done via the `-fn=` flag when using `musttag` standalone: + +```shell +musttag -fn="github.com/hashicorp/hcl/v2/hclsimple.DecodeFile:hcl:2" ./... +``` + +[1]: https://github.com/uber-go/guide/blob/master/style.md#use-field-tags-in-marshaled-structs +[2]: https://pkg.go.dev/encoding/json +[3]: https://pkg.go.dev/encoding/xml +[4]: https://pkg.go.dev/gopkg.in/yaml.v3 +[5]: https://pkg.go.dev/github.com/BurntSushi/toml +[6]: https://pkg.go.dev/github.com/mitchellh/mapstructure +[7]: https://pkg.go.dev/github.com/jmoiron/sqlx +[8]: https://golangci-lint.run +[9]: https://github.com/go-simpler/musttag/releases +[10]: https://golangci-lint.run/usage/linters/#musttag +[11]: https://pkg.go.dev/github.com/hashicorp/hcl/v2/hclsimple#Decode diff --git a/tools/vendor/go-simpler.org/musttag/builtins.go b/tools/vendor/go-simpler.org/musttag/builtins.go new file mode 100644 index 000000000..3305513f8 --- /dev/null +++ b/tools/vendor/go-simpler.org/musttag/builtins.go @@ -0,0 +1,133 @@ +package musttag + +// builtins is a set of functions supported out of the box. +var builtins = []Func{ + // https://pkg.go.dev/encoding/json + { + Name: "encoding/json.Marshal", Tag: "json", ArgPos: 0, + ifaceWhitelist: []string{"encoding/json.Marshaler", "encoding.TextMarshaler"}, + }, + { + Name: "encoding/json.MarshalIndent", Tag: "json", ArgPos: 0, + ifaceWhitelist: []string{"encoding/json.Marshaler", "encoding.TextMarshaler"}, + }, + { + Name: "encoding/json.Unmarshal", Tag: "json", ArgPos: 1, + ifaceWhitelist: []string{"encoding/json.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + { + Name: "(*encoding/json.Encoder).Encode", Tag: "json", ArgPos: 0, + ifaceWhitelist: []string{"encoding/json.Marshaler", "encoding.TextMarshaler"}, + }, + { + Name: "(*encoding/json.Decoder).Decode", Tag: "json", ArgPos: 0, + ifaceWhitelist: []string{"encoding/json.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + + // https://pkg.go.dev/encoding/xml + { + Name: "encoding/xml.Marshal", Tag: "xml", ArgPos: 0, + ifaceWhitelist: []string{"encoding/xml.Marshaler", "encoding.TextMarshaler"}, + }, + { + Name: "encoding/xml.MarshalIndent", Tag: "xml", ArgPos: 0, + ifaceWhitelist: []string{"encoding/xml.Marshaler", "encoding.TextMarshaler"}, + }, + { + Name: "encoding/xml.Unmarshal", Tag: "xml", ArgPos: 1, + ifaceWhitelist: []string{"encoding/xml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + { + Name: "(*encoding/xml.Encoder).Encode", Tag: "xml", ArgPos: 0, + ifaceWhitelist: []string{"encoding/xml.Marshaler", "encoding.TextMarshaler"}, + }, + { + Name: "(*encoding/xml.Decoder).Decode", Tag: "xml", ArgPos: 0, + ifaceWhitelist: []string{"encoding/xml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + { + Name: "(*encoding/xml.Encoder).EncodeElement", Tag: "xml", ArgPos: 0, + ifaceWhitelist: []string{"encoding/xml.Marshaler", "encoding.TextMarshaler"}, + }, + { + Name: "(*encoding/xml.Decoder).DecodeElement", Tag: "xml", ArgPos: 0, + ifaceWhitelist: []string{"encoding/xml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + + // https://pkg.go.dev/gopkg.in/yaml.v3 + { + Name: "gopkg.in/yaml.v3.Marshal", Tag: "yaml", ArgPos: 0, + ifaceWhitelist: []string{"gopkg.in/yaml.v3.Marshaler"}, + }, + { + Name: "gopkg.in/yaml.v3.Unmarshal", Tag: "yaml", ArgPos: 1, + ifaceWhitelist: []string{"gopkg.in/yaml.v3.Unmarshaler"}, + }, + { + Name: "(*gopkg.in/yaml.v3.Encoder).Encode", Tag: "yaml", ArgPos: 0, + ifaceWhitelist: []string{"gopkg.in/yaml.v3.Marshaler"}, + }, + { + Name: "(*gopkg.in/yaml.v3.Decoder).Decode", Tag: "yaml", ArgPos: 0, + ifaceWhitelist: []string{"gopkg.in/yaml.v3.Unmarshaler"}, + }, + + // https://pkg.go.dev/github.com/BurntSushi/toml + { + Name: "github.com/BurntSushi/toml.Unmarshal", Tag: "toml", ArgPos: 1, + ifaceWhitelist: []string{"github.com/BurntSushi/toml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + { + Name: "github.com/BurntSushi/toml.Decode", Tag: "toml", ArgPos: 1, + ifaceWhitelist: []string{"github.com/BurntSushi/toml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + { + Name: "github.com/BurntSushi/toml.DecodeFS", Tag: "toml", ArgPos: 2, + ifaceWhitelist: []string{"github.com/BurntSushi/toml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + { + Name: "github.com/BurntSushi/toml.DecodeFile", Tag: "toml", ArgPos: 1, + ifaceWhitelist: []string{"github.com/BurntSushi/toml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + { + Name: "(*github.com/BurntSushi/toml.Encoder).Encode", Tag: "toml", ArgPos: 0, + ifaceWhitelist: []string{"encoding.TextMarshaler"}, + }, + { + Name: "(*github.com/BurntSushi/toml.Decoder).Decode", Tag: "toml", ArgPos: 0, + ifaceWhitelist: []string{"github.com/BurntSushi/toml.Unmarshaler", "encoding.TextUnmarshaler"}, + }, + + // https://pkg.go.dev/github.com/mitchellh/mapstructure + {Name: "github.com/mitchellh/mapstructure.Decode", Tag: "mapstructure", ArgPos: 1}, + {Name: "github.com/mitchellh/mapstructure.DecodeMetadata", Tag: "mapstructure", ArgPos: 1}, + {Name: "github.com/mitchellh/mapstructure.WeakDecode", Tag: "mapstructure", ArgPos: 1}, + {Name: "github.com/mitchellh/mapstructure.WeakDecodeMetadata", Tag: "mapstructure", ArgPos: 1}, + + // https://pkg.go.dev/github.com/jmoiron/sqlx + {Name: "github.com/jmoiron/sqlx.Get", Tag: "db", ArgPos: 1}, + {Name: "github.com/jmoiron/sqlx.GetContext", Tag: "db", ArgPos: 2}, + {Name: "github.com/jmoiron/sqlx.Select", Tag: "db", ArgPos: 1}, + {Name: "github.com/jmoiron/sqlx.SelectContext", Tag: "db", ArgPos: 2}, + {Name: "github.com/jmoiron/sqlx.StructScan", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.Conn).GetContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.Conn).SelectContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.DB).Get", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.DB).GetContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.DB).Select", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.DB).SelectContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.NamedStmt).Get", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.NamedStmt).GetContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.NamedStmt).Select", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.NamedStmt).SelectContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.Row).StructScan", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.Rows).StructScan", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.Stmt).Get", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.Stmt).GetContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.Stmt).Select", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.Stmt).SelectContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.Tx).Get", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.Tx).GetContext", Tag: "db", ArgPos: 1}, + {Name: "(*github.com/jmoiron/sqlx.Tx).Select", Tag: "db", ArgPos: 0}, + {Name: "(*github.com/jmoiron/sqlx.Tx).SelectContext", Tag: "db", ArgPos: 1}, +} diff --git a/tools/vendor/go-simpler.org/musttag/musttag.go b/tools/vendor/go-simpler.org/musttag/musttag.go new file mode 100644 index 000000000..70c84201b --- /dev/null +++ b/tools/vendor/go-simpler.org/musttag/musttag.go @@ -0,0 +1,282 @@ +// Package musttag implements the musttag analyzer. +package musttag + +import ( + "flag" + "fmt" + "go/ast" + "go/types" + "reflect" + "strconv" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/go/types/typeutil" +) + +// Func describes a function call to look for, e.g. [json.Marshal]. +type Func struct { + Name string // The full name of the function, including the package. + Tag string // The struct tag whose presence should be ensured. + ArgPos int // The position of the argument to check. + + // a list of interface names (including the package); + // if at least one is implemented by the argument, no check is performed. + ifaceWhitelist []string +} + +// New creates a new musttag analyzer. +// To report a custom function, provide its description as [Func]. +func New(funcs ...Func) *analysis.Analyzer { + var flagFuncs []Func + return &analysis.Analyzer{ + Name: "musttag", + Doc: "enforce field tags in (un)marshaled structs", + Flags: flags(&flagFuncs), + Requires: []*analysis.Analyzer{inspect.Analyzer}, + Run: func(pass *analysis.Pass) (any, error) { + l := len(builtins) + len(funcs) + len(flagFuncs) + allFuncs := make(map[string]Func, l) + + merge := func(slice []Func) { + for _, fn := range slice { + allFuncs[fn.Name] = fn + } + } + merge(builtins) + merge(funcs) + merge(flagFuncs) + + mainModule, err := getMainModule() + if err != nil { + return nil, err + } + + return run(pass, mainModule, allFuncs) + }, + } +} + +func flags(funcs *[]Func) flag.FlagSet { + fs := flag.NewFlagSet("musttag", flag.ContinueOnError) + fs.Func("fn", "report a custom function (name:tag:arg-pos)", func(s string) error { + parts := strings.Split(s, ":") + if len(parts) != 3 || parts[0] == "" || parts[1] == "" { + return strconv.ErrSyntax + } + pos, err := strconv.Atoi(parts[2]) + if err != nil { + return err + } + *funcs = append(*funcs, Func{ + Name: parts[0], + Tag: parts[1], + ArgPos: pos, + }) + return nil + }) + return *fs +} + +func run(pass *analysis.Pass, mainModule string, funcs map[string]Func) (_ any, err error) { + visit := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + filter := []ast.Node{(*ast.CallExpr)(nil)} + + visit.Preorder(filter, func(node ast.Node) { + if err != nil { + return // there is already an error. + } + + call, ok := node.(*ast.CallExpr) + if !ok { + return // not a function call. + } + + callee := typeutil.StaticCallee(pass.TypesInfo, call) + if callee == nil { + return // not a static call. + } + + fn, ok := funcs[cutVendor(callee.FullName())] + if !ok { + return // unsupported function. + } + + if len(call.Args) <= fn.ArgPos { + err = fmt.Errorf("musttag: Func.ArgPos cannot be %d: %s accepts only %d argument(s)", fn.ArgPos, fn.Name, len(call.Args)) + return + } + + arg := call.Args[fn.ArgPos] + if ident, ok := arg.(*ast.Ident); ok && ident.Obj == nil { + return // e.g. json.Marshal(nil) + } + + typ := pass.TypesInfo.TypeOf(arg) + if typ == nil { + return // no type info found. + } + + checker := checker{ + mainModule: mainModule, + seenTypes: make(map[string]struct{}), + ifaceWhitelist: fn.ifaceWhitelist, + imports: pass.Pkg.Imports(), + } + + if valid := checker.checkType(typ, fn.Tag); valid { + return // nothing to report. + } + + pass.Reportf(arg.Pos(), "the given struct should be annotated with the `%s` tag", fn.Tag) + }) + + return nil, err +} + +type checker struct { + mainModule string + seenTypes map[string]struct{} + ifaceWhitelist []string + imports []*types.Package +} + +func (c *checker) checkType(typ types.Type, tag string) bool { + if _, ok := c.seenTypes[typ.String()]; ok { + return true // already checked. + } + c.seenTypes[typ.String()] = struct{}{} + + styp, ok := c.parseStruct(typ) + if !ok { + return true // not a struct. + } + + return c.checkStruct(styp, tag) +} + +// recursively unwrap a type until we get to an underlying +// raw struct type that should have its fields checked +// +// SomeStruct -> struct{SomeStructField: ... } +// []*SomeStruct -> struct{SomeStructField: ... } +// ... +// +// exits early if it hits a type that implements a whitelisted interface +func (c *checker) parseStruct(typ types.Type) (*types.Struct, bool) { + if implementsInterface(typ, c.ifaceWhitelist, c.imports) { + return nil, false // the type implements a Marshaler interface; see issue #64. + } + + switch typ := typ.(type) { + case *types.Pointer: + return c.parseStruct(typ.Elem()) + + case *types.Array: + return c.parseStruct(typ.Elem()) + + case *types.Slice: + return c.parseStruct(typ.Elem()) + + case *types.Map: + return c.parseStruct(typ.Elem()) + + case *types.Named: // a struct of the named type. + pkg := typ.Obj().Pkg() + if pkg == nil { + return nil, false + } + if !strings.HasPrefix(pkg.Path(), c.mainModule) { + return nil, false + } + styp, ok := typ.Underlying().(*types.Struct) + if !ok { + return nil, false + } + return styp, true + + case *types.Struct: // an anonymous struct. + return typ, true + + default: + return nil, false + } +} + +func (c *checker) checkStruct(styp *types.Struct, tag string) (valid bool) { + for i := 0; i < styp.NumFields(); i++ { + field := styp.Field(i) + if !field.Exported() { + continue + } + + tagValue, ok := reflect.StructTag(styp.Tag(i)).Lookup(tag) + if !ok { + // tag is not required for embedded types; see issue #12. + if !field.Embedded() { + return false + } + } + + // Do not recurse into ignored fields. + if tagValue == "-" { + continue + } + + if valid := c.checkType(field.Type(), tag); !valid { + return false + } + } + + return true +} + +func implementsInterface(typ types.Type, ifaces []string, imports []*types.Package) bool { + findScope := func(pkgName string) (*types.Scope, bool) { + // fast path: check direct imports (e.g. looking for "encoding/json.Marshaler"). + for _, direct := range imports { + if pkgName == cutVendor(direct.Path()) { + return direct.Scope(), true + } + } + // slow path: check indirect imports (e.g. looking for "encoding.TextMarshaler"). + // TODO: only check indirect imports from the package (e.g. "encoding/json") of the analyzed function (e.g. "encoding/json.Marshal"). + for _, direct := range imports { + for _, indirect := range direct.Imports() { + if pkgName == cutVendor(indirect.Path()) { + return indirect.Scope(), true + } + } + } + return nil, false + } + + for _, ifacePath := range ifaces { + // "encoding/json.Marshaler" -> "encoding/json" + "Marshaler" + idx := strings.LastIndex(ifacePath, ".") + if idx == -1 { + continue + } + pkgName, ifaceName := ifacePath[:idx], ifacePath[idx+1:] + + scope, ok := findScope(pkgName) + if !ok { + continue + } + obj := scope.Lookup(ifaceName) + if obj == nil { + continue + } + iface, ok := obj.Type().Underlying().(*types.Interface) + if !ok { + continue + } + if types.Implements(typ, iface) || types.Implements(types.NewPointer(typ), iface) { + return true + } + } + + return false +} diff --git a/tools/vendor/go-simpler.org/musttag/utils.go b/tools/vendor/go-simpler.org/musttag/utils.go new file mode 100644 index 000000000..1a13f96c2 --- /dev/null +++ b/tools/vendor/go-simpler.org/musttag/utils.go @@ -0,0 +1,49 @@ +package musttag + +import ( + "encoding/json" + "fmt" + "os/exec" + "strings" +) + +func getMainModule() (string, error) { + args := [...]string{"go", "mod", "edit", "-json"} + + out, err := exec.Command(args[0], args[1:]...).Output() + if err != nil { + return "", fmt.Errorf("running %q: %w", strings.Join(args[:], " "), err) + } + + var info struct { + Module struct { + Path string `json:"Path"` + } `json:"Module"` + } + if err := json.Unmarshal(out, &info); err != nil { + return "", fmt.Errorf("decoding module info: %w\n%s", err, out) + } + + return info.Module.Path, nil +} + +// based on golang.org/x/tools/imports.VendorlessPath +func cutVendor(path string) string { + var prefix string + + switch { + case strings.HasPrefix(path, "(*"): + prefix, path = "(*", path[len("(*"):] + case strings.HasPrefix(path, "("): + prefix, path = "(", path[len("("):] + } + + if i := strings.LastIndex(path, "/vendor/"); i >= 0 { + return prefix + path[i+len("/vendor/"):] + } + if strings.HasPrefix(path, "vendor/") { + return prefix + path[len("vendor/"):] + } + + return prefix + path +} diff --git a/tools/vendor/go-simpler.org/sloglint/Makefile b/tools/vendor/go-simpler.org/sloglint/Makefile new file mode 100644 index 000000000..6165b16f4 --- /dev/null +++ b/tools/vendor/go-simpler.org/sloglint/Makefile @@ -0,0 +1,28 @@ +.POSIX: +.SUFFIXES: + +all: test lint + +test: + go test -race -shuffle=on -cover ./... + +test/cover: + go test -race -shuffle=on -coverprofile=coverage.out ./... + go tool cover -html=coverage.out + +lint: + golangci-lint run + +tidy: + go mod tidy + +generate: + go generate ./... + +# run `make pre-commit` once to install the hook. +pre-commit: .git/hooks/pre-commit test lint tidy generate + git diff --exit-code + +.git/hooks/pre-commit: + echo "make pre-commit" > .git/hooks/pre-commit + chmod +x .git/hooks/pre-commit diff --git a/tools/vendor/go-simpler.org/sloglint/README.md b/tools/vendor/go-simpler.org/sloglint/README.md index 8f26f3aa7..0a35818fb 100644 --- a/tools/vendor/go-simpler.org/sloglint/README.md +++ b/tools/vendor/go-simpler.org/sloglint/README.md @@ -10,36 +10,55 @@ A Go linter that ensures consistent code style when using `log/slog`. ## 📌 About The `log/slog` API allows two different types of arguments: key-value pairs and attributes. -People may have different opinions about which one is better, -but nobody probably wants to mix them up because it makes the code harder to read. - -```go -slog.Info("a user has logged in", "user_id", 42, slog.String("ip_address", "192.0.2.0")) // ugh -``` - -`sloglint` finds such function calls and checks that all the arguments are either key-value pairs or attributes. -The linter has several options, so you can adjust it to your own code style. +While people may have different opinions about which one is better, most seem to agree on one thing: it should be consistent. +With `sloglint` you can enforce various rules for `log/slog` based on your preferred code style. ## 🚀 Features -* Forbid mixing key-value pairs and attributes within a single function call (default) -* Enforce using either key-value pairs or attributes for the entire project (optional) +* Enforce not mixing key-value pairs and attributes (default) +* Enforce using either key-value pairs only or attributes only (optional) +* Enforce not using global loggers (optional) +* Enforce using methods that accept a context (optional) +* Enforce using static log messages (optional) * Enforce using constants instead of raw keys (optional) +* Enforce a single key naming convention (optional) +* Enforce not using specific keys (optional) * Enforce putting arguments on separate lines (optional) ## 📦 Install -Download a prebuilt binary from the [Releases][1] page. +`sloglint` is integrated into [`golangci-lint`][1], and this is the recommended way to use it. + +To enable the linter, add the following lines to `.golangci.yml`: + +```yaml +linters: + enable: + - sloglint +``` + +Alternatively, you can download a prebuilt binary from the [Releases][2] page to use `sloglint` standalone. ## 📋 Usage -```shell -sloglint [flags] ./... +Run `golangci-lint` with `sloglint` enabled. +See the list of [available options][3] to configure the linter. + +When using `sloglint` standalone, pass the options as flags of the same name. + +### No mixed arguments + +The `no-mixed-args` option causes `sloglint` to report mixing key-values pairs and attributes within a single function call: + +```go +slog.Info("a user has logged in", "user_id", 42, slog.String("ip_address", "192.0.2.0")) // sloglint: key-value pairs and attributes should not be mixed ``` +It is enabled by default. + ### Key-value pairs only -The `-kv-only` flag causes `sloglint` to report any use of attributes. +The `kv-only` option causes `sloglint` to report any use of attributes: ```go slog.Info("a user has logged in", slog.Int("user_id", 42)) // sloglint: attributes should not be used @@ -47,16 +66,55 @@ slog.Info("a user has logged in", slog.Int("user_id", 42)) // sloglint: attribut ### Attributes only -In contrast, the `-attr-only` flag causes `sloglint` to report any use of key-value pairs. +In contrast, the `attr-only` option causes `sloglint` to report any use of key-value pairs: ```go slog.Info("a user has logged in", "user_id", 42) // sloglint: key-value pairs should not be used ``` +### No global + +Some projects prefer to pass loggers as explicit dependencies. +The `no-global` option causes `sloglint` to report the use of global loggers. + +```go +slog.Info("a user has logged in", "user_id", 42) // sloglint: global logger should not be used +``` + +Possible values are `all` (report all global loggers) and `default` (report only the default `slog` logger). + +### Context only + +Some `slog.Handler` implementations make use of the given `context.Context` (e.g. to access context values). +For them to work properly, you need to pass a context to all logger calls. +The `context-only` option causes `sloglint` to report the use of methods without a context: + +```go +slog.Info("a user has logged in") // sloglint: InfoContext should be used instead +``` + +Possible values are `all` (report all contextless calls) and `scope` (report only if a context exists in the scope of the outermost function). + +### Static messages + +To get the most out of structured logging, you may want to require log messages to be static. +The `static-msg` option causes `sloglint` to report non-static messages: + +```go +slog.Info(fmt.Sprintf("a user with id %d has logged in", 42)) // sloglint: message should be a string literal or a constant +``` + +The report can be fixed by moving dynamic values to arguments: + +```go +slog.Info("a user has logged in", "user_id", 42) +``` + ### No raw keys To prevent typos, you may want to forbid the use of raw keys altogether. -The `-no-raw-keys` flag causes `sloglint` to report the use of strings as keys (including `slog.Attr` calls, e.g. `slog.Int("user_id", 42)`). +The `no-raw-keys` option causes `sloglint` to report the use of strings as keys +(including `slog.Attr` calls, e.g. `slog.Int("user_id", 42)`): ```go slog.Info("a user has logged in", "user_id", 42) // sloglint: raw keys should not be used @@ -70,7 +128,7 @@ const UserId = "user_id" slog.Info("a user has logged in", UserId, 42) ``` -...or custom `slog.Attr` constructors. +...or custom `slog.Attr` constructors: ```go func UserId(value int) slog.Attr { return slog.Int("user_id", value) } @@ -78,18 +136,42 @@ func UserId(value int) slog.Attr { return slog.Int("user_id", value) } slog.Info("a user has logged in", UserId(42)) ``` -> 💡 Such helpers can be automatically generated for you by the [`sloggen`][2] tool. Give it a try too! +> [!TIP] +> Such helpers can be automatically generated for you by the [`sloggen`][4] tool. Give it a try too! + +### Key naming convention + +To ensure consistency in logs, you may want to enforce a single key naming convention. +The `key-naming-case` option causes `sloglint` to report keys written in a case other than the given one: + +```go +slog.Info("a user has logged in", "user-id", 42) // sloglint: keys should be written in snake_case +``` + +Possible values are `snake`, `kebab`, `camel`, or `pascal`. + +### Forbidden keys + +To prevent accidental use of reserved log keys, you may want to forbid specific keys altogether. +The `forbidden-keys` option causes `sloglint` to report the use of forbidden keys: + +```go +slog.Info("a user has logged in", "reserved", 42) // sloglint: "reserved" key is forbidden and should not be used +``` + +For example, when using the standard `slog.JSONHandler` and `slog.TextHandler`, +you may want to forbid the `time`, `level`, `msg`, and `source` keys, as these are used by the handlers. ### Arguments on separate lines To improve code readability, you may want to put arguments on separate lines, especially when using key-value pairs. -The `-args-on-sep-lines` flag causes `sloglint` to report 2+ arguments on the same line. +The `args-on-sep-lines` option causes `sloglint` to report 2+ arguments on the same line: ```go slog.Info("a user has logged in", "user_id", 42, "ip_address", "192.0.2.0") // sloglint: arguments should be put on separate lines ``` -This report can be fixed by reformatting the code. +This report can be fixed by reformatting the code: ```go slog.Info("a user has logged in", @@ -98,5 +180,7 @@ slog.Info("a user has logged in", ) ``` -[1]: https://github.com/go-simpler/sloglint/releases -[2]: https://github.com/go-simpler/sloggen +[1]: https://golangci-lint.run +[2]: https://github.com/go-simpler/sloglint/releases +[3]: https://golangci-lint.run/usage/linters/#sloglint +[4]: https://github.com/go-simpler/sloggen diff --git a/tools/vendor/go-simpler.org/sloglint/sloglint.go b/tools/vendor/go-simpler.org/sloglint/sloglint.go index 4e4520698..bff37b723 100644 --- a/tools/vendor/go-simpler.org/sloglint/sloglint.go +++ b/tools/vendor/go-simpler.org/sloglint/sloglint.go @@ -4,11 +4,15 @@ package sloglint import ( "errors" "flag" + "fmt" "go/ast" "go/token" "go/types" + "slices" "strconv" + "strings" + "github.com/ettle/strcase" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" @@ -17,17 +21,24 @@ import ( // Options are options for the sloglint analyzer. type Options struct { - KVOnly bool // Enforce using key-value pairs only (incompatible with AttrOnly). - AttrOnly bool // Enforce using attributes only (incompatible with KVOnly). - NoRawKeys bool // Enforce using constants instead of raw keys. - ArgsOnSepLines bool // Enforce putting arguments on separate lines. + NoMixedArgs bool // Enforce not mixing key-value pairs and attributes (default true). + KVOnly bool // Enforce using key-value pairs only (overrides NoMixedArgs, incompatible with AttrOnly). + AttrOnly bool // Enforce using attributes only (overrides NoMixedArgs, incompatible with KVOnly). + NoGlobal string // Enforce not using global loggers ("all" or "default"). + ContextOnly string // Enforce using methods that accept a context ("all" or "scope"). + StaticMsg bool // Enforce using static log messages. + NoRawKeys bool // Enforce using constants instead of raw keys. + KeyNamingCase string // Enforce a single key naming convention ("snake", "kebab", "camel", or "pascal"). + ForbiddenKeys []string // Enforce not using specific keys. + ArgsOnSepLines bool // Enforce putting arguments on separate lines. } // New creates a new sloglint analyzer. func New(opts *Options) *analysis.Analyzer { if opts == nil { - opts = new(Options) + opts = &Options{NoMixedArgs: true} } + return &analysis.Analyzer{ Name: "sloglint", Doc: "ensure consistent code style when using log/slog", @@ -35,52 +46,100 @@ func New(opts *Options) *analysis.Analyzer { Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: func(pass *analysis.Pass) (any, error) { if opts.KVOnly && opts.AttrOnly { - return nil, errors.New("sloglint: incompatible options provided") + return nil, fmt.Errorf("sloglint: Options.KVOnly and Options.AttrOnly: %w", errIncompatible) + } + + switch opts.NoGlobal { + case "", "all", "default": + default: + return nil, fmt.Errorf("sloglint: Options.NoGlobal=%s: %w", opts.NoGlobal, errInvalidValue) } + + switch opts.ContextOnly { + case "", "all", "scope": + default: + return nil, fmt.Errorf("sloglint: Options.ContextOnly=%s: %w", opts.ContextOnly, errInvalidValue) + } + + switch opts.KeyNamingCase { + case "", snakeCase, kebabCase, camelCase, pascalCase: + default: + return nil, fmt.Errorf("sloglint: Options.KeyNamingCase=%s: %w", opts.KeyNamingCase, errInvalidValue) + } + run(pass, opts) return nil, nil }, } } +var ( + errIncompatible = errors.New("incompatible options") + errInvalidValue = errors.New("invalid value") +) + func flags(opts *Options) flag.FlagSet { - fs := flag.NewFlagSet("sloglint", flag.ContinueOnError) + fset := flag.NewFlagSet("sloglint", flag.ContinueOnError) boolVar := func(value *bool, name, usage string) { - fs.Func(name, usage, func(s string) error { + fset.Func(name, usage, func(s string) error { v, err := strconv.ParseBool(s) *value = v return err }) } - boolVar(&opts.KVOnly, "kv-only", "enforce using key-value pairs only (incompatible with -attr-only)") - boolVar(&opts.AttrOnly, "attr-only", "enforce using attributes only (incompatible with -kv-only)") + strVar := func(value *string, name, usage string) { + fset.Func(name, usage, func(s string) error { + *value = s + return nil + }) + } + + boolVar(&opts.NoMixedArgs, "no-mixed-args", "enforce not mixing key-value pairs and attributes (default true)") + boolVar(&opts.KVOnly, "kv-only", "enforce using key-value pairs only (overrides -no-mixed-args, incompatible with -attr-only)") + boolVar(&opts.AttrOnly, "attr-only", "enforce using attributes only (overrides -no-mixed-args, incompatible with -kv-only)") + strVar(&opts.NoGlobal, "no-global", "enforce not using global loggers (all|default)") + strVar(&opts.ContextOnly, "context-only", "enforce using methods that accept a context (all|scope)") + boolVar(&opts.StaticMsg, "static-msg", "enforce using static log messages") boolVar(&opts.NoRawKeys, "no-raw-keys", "enforce using constants instead of raw keys") + strVar(&opts.KeyNamingCase, "key-naming-case", "enforce a single key naming convention (snake|kebab|camel|pascal)") boolVar(&opts.ArgsOnSepLines, "args-on-sep-lines", "enforce putting arguments on separate lines") - return *fs + fset.Func("forbidden-keys", "enforce not using specific keys (comma-separated)", func(s string) error { + opts.ForbiddenKeys = append(opts.ForbiddenKeys, strings.Split(s, ",")...) + return nil + }) + + return *fset } -var slogFuncs = map[string]int{ // funcName:argsPos - "log/slog.Log": 3, - "log/slog.Debug": 1, - "log/slog.Info": 1, - "log/slog.Warn": 1, - "log/slog.Error": 1, - "log/slog.DebugContext": 2, - "log/slog.InfoContext": 2, - "log/slog.WarnContext": 2, - "log/slog.ErrorContext": 2, - "(*log/slog.Logger).Log": 3, - "(*log/slog.Logger).Debug": 1, - "(*log/slog.Logger).Info": 1, - "(*log/slog.Logger).Warn": 1, - "(*log/slog.Logger).Error": 1, - "(*log/slog.Logger).DebugContext": 2, - "(*log/slog.Logger).InfoContext": 2, - "(*log/slog.Logger).WarnContext": 2, - "(*log/slog.Logger).ErrorContext": 2, +var slogFuncs = map[string]struct { + argsPos int + skipContextCheck bool +}{ + "log/slog.With": {argsPos: 0, skipContextCheck: true}, + "log/slog.Log": {argsPos: 3}, + "log/slog.LogAttrs": {argsPos: 3}, + "log/slog.Debug": {argsPos: 1}, + "log/slog.Info": {argsPos: 1}, + "log/slog.Warn": {argsPos: 1}, + "log/slog.Error": {argsPos: 1}, + "log/slog.DebugContext": {argsPos: 2}, + "log/slog.InfoContext": {argsPos: 2}, + "log/slog.WarnContext": {argsPos: 2}, + "log/slog.ErrorContext": {argsPos: 2}, + "(*log/slog.Logger).With": {argsPos: 0, skipContextCheck: true}, + "(*log/slog.Logger).Log": {argsPos: 3}, + "(*log/slog.Logger).LogAttrs": {argsPos: 3}, + "(*log/slog.Logger).Debug": {argsPos: 1}, + "(*log/slog.Logger).Info": {argsPos: 1}, + "(*log/slog.Logger).Warn": {argsPos: 1}, + "(*log/slog.Logger).Error": {argsPos: 1}, + "(*log/slog.Logger).DebugContext": {argsPos: 2}, + "(*log/slog.Logger).InfoContext": {argsPos: 2}, + "(*log/slog.Logger).WarnContext": {argsPos: 2}, + "(*log/slog.Logger).ErrorContext": {argsPos: 2}, } var attrFuncs = map[string]struct{}{ @@ -96,113 +155,254 @@ var attrFuncs = map[string]struct{}{ "log/slog.Any": {}, } +const ( + snakeCase = "snake" + kebabCase = "kebab" + camelCase = "camel" + pascalCase = "pascal" +) + func run(pass *analysis.Pass, opts *Options) { - visit := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + visitor := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) filter := []ast.Node{(*ast.CallExpr)(nil)} - visit.Preorder(filter, func(node ast.Node) { - call := node.(*ast.CallExpr) + // WithStack is ~2x slower than Preorder, use it only when stack is needed. + if opts.ContextOnly == "scope" { + visitor.WithStack(filter, func(node ast.Node, _ bool, stack []ast.Node) bool { + visit(pass, opts, node, stack) + return false + }) + return + } + + visitor.Preorder(filter, func(node ast.Node) { + visit(pass, opts, node, nil) + }) +} + +// NOTE: stack is nil if Preorder is used. +func visit(pass *analysis.Pass, opts *Options, node ast.Node, stack []ast.Node) { + call := node.(*ast.CallExpr) + + fn := typeutil.StaticCallee(pass.TypesInfo, call) + if fn == nil { + return + } + + name := fn.FullName() + funcInfo, ok := slogFuncs[name] + if !ok { + return + } - fn := typeutil.StaticCallee(pass.TypesInfo, call) - if fn == nil { - return + switch opts.NoGlobal { + case "all": + if strings.HasPrefix(name, "log/slog.") || isGlobalLoggerUsed(pass.TypesInfo, call.Fun) { + pass.Reportf(call.Pos(), "global logger should not be used") } + case "default": + if strings.HasPrefix(name, "log/slog.") { + pass.Reportf(call.Pos(), "default logger should not be used") + } + } - argsPos, ok := slogFuncs[fn.FullName()] - if !ok { - return + // NOTE: "With" functions are not checked for context.Context. + if !funcInfo.skipContextCheck { + switch opts.ContextOnly { + case "all": + typ := pass.TypesInfo.TypeOf(call.Args[0]) + if typ != nil && typ.String() != "context.Context" { + pass.Reportf(call.Pos(), "%sContext should be used instead", fn.Name()) + } + case "scope": + typ := pass.TypesInfo.TypeOf(call.Args[0]) + if typ != nil && typ.String() != "context.Context" && isContextInScope(pass.TypesInfo, stack) { + pass.Reportf(call.Pos(), "%sContext should be used instead", fn.Name()) + } } + } + + msgPos := funcInfo.argsPos - 1 + // NOTE: "With" functions have no message argument and must be skipped. + if opts.StaticMsg && msgPos >= 0 && !isStaticMsg(call.Args[msgPos]) { + pass.Reportf(call.Pos(), "message should be a string literal or a constant") + } + + // NOTE: we assume that the arguments have already been validated by govet. + args := call.Args[funcInfo.argsPos:] + if len(args) == 0 { + return + } - // NOTE: we assume that the arguments have already been validated by govet. - args := call.Args[argsPos:] - if len(args) == 0 { - return + var keys []ast.Expr + var attrs []ast.Expr + + for i := 0; i < len(args); i++ { + typ := pass.TypesInfo.TypeOf(args[i]) + if typ == nil { + continue } - var keys []ast.Expr - var attrs []ast.Expr + switch typ.String() { + case "string": + keys = append(keys, args[i]) + i++ // skip the value. + case "log/slog.Attr": + attrs = append(attrs, args[i]) + case "[]any", "[]log/slog.Attr": + continue // the last argument may be an unpacked slice, skip it. + } + } - for i := 0; i < len(args); i++ { - typ := pass.TypesInfo.TypeOf(args[i]) - if typ == nil { - continue + switch { + case opts.KVOnly && len(attrs) > 0: + pass.Reportf(call.Pos(), "attributes should not be used") + case opts.AttrOnly && len(keys) > 0: + pass.Reportf(call.Pos(), "key-value pairs should not be used") + case opts.NoMixedArgs && len(attrs) > 0 && len(keys) > 0: + pass.Reportf(call.Pos(), "key-value pairs and attributes should not be mixed") + } + + if opts.NoRawKeys { + forEachKey(pass.TypesInfo, keys, attrs, func(key ast.Expr) { + if ident, ok := key.(*ast.Ident); !ok || ident.Obj == nil || ident.Obj.Kind != ast.Con { + pass.Reportf(call.Pos(), "raw keys should not be used") } - switch typ.String() { - case "string": - keys = append(keys, args[i]) - i++ // skip the value. - case "log/slog.Attr": - attrs = append(attrs, args[i]) + }) + } + + checkKeyNamingCase := func(caseFn func(string) string, caseName string) { + forEachKey(pass.TypesInfo, keys, attrs, func(key ast.Expr) { + if name, ok := getKeyName(key); ok && name != caseFn(name) { + pass.Reportf(call.Pos(), "keys should be written in %s", caseName) } - } + }) + } - switch { - case opts.KVOnly && len(attrs) > 0: - pass.Reportf(call.Pos(), "attributes should not be used") - case opts.AttrOnly && len(attrs) < len(args): - pass.Reportf(call.Pos(), "key-value pairs should not be used") - case 0 < len(attrs) && len(attrs) < len(args): - pass.Reportf(call.Pos(), "key-value pairs and attributes should not be mixed") - } + switch opts.KeyNamingCase { + case snakeCase: + checkKeyNamingCase(strcase.ToSnake, "snake_case") + case kebabCase: + checkKeyNamingCase(strcase.ToKebab, "kebab-case") + case camelCase: + checkKeyNamingCase(strcase.ToCamel, "camelCase") + case pascalCase: + checkKeyNamingCase(strcase.ToPascal, "PascalCase") + } - if opts.NoRawKeys && rawKeysUsed(pass.TypesInfo, keys, attrs) { - pass.Reportf(call.Pos(), "raw keys should not be used") + if len(opts.ForbiddenKeys) > 0 { + forEachKey(pass.TypesInfo, keys, attrs, func(key ast.Expr) { + if name, ok := getKeyName(key); ok && slices.Contains(opts.ForbiddenKeys, name) { + pass.Reportf(call.Pos(), "%q key is forbidden and should not be used", name) + } + }) + } + + if opts.ArgsOnSepLines && areArgsOnSameLine(pass.Fset, call, keys, attrs) { + pass.Reportf(call.Pos(), "arguments should be put on separate lines") + } +} + +func isGlobalLoggerUsed(info *types.Info, call ast.Expr) bool { + selector, ok := call.(*ast.SelectorExpr) + if !ok { + return false + } + ident, ok := selector.X.(*ast.Ident) + if !ok { + return false + } + obj := info.ObjectOf(ident) + return obj.Parent() == obj.Pkg().Scope() +} + +func isContextInScope(info *types.Info, stack []ast.Node) bool { + for i := len(stack) - 1; i >= 0; i-- { + decl, ok := stack[i].(*ast.FuncDecl) + if !ok { + continue } - if opts.ArgsOnSepLines && argsOnSameLine(pass.Fset, call, keys, attrs) { - pass.Reportf(call.Pos(), "arguments should be put on separate lines") + params := decl.Type.Params + if len(params.List) == 0 || len(params.List[0].Names) == 0 { + continue } - }) + typ := info.TypeOf(params.List[0].Names[0]) + if typ != nil && typ.String() == "context.Context" { + return true + } + } + return false } -func rawKeysUsed(info *types.Info, keys, attrs []ast.Expr) bool { - isConst := func(expr ast.Expr) bool { - ident, ok := expr.(*ast.Ident) - return ok && ident.Obj != nil && ident.Obj.Kind == ast.Con +func isStaticMsg(msg ast.Expr) bool { + switch msg := msg.(type) { + case *ast.BasicLit: // e.g. slog.Info("msg") + return msg.Kind == token.STRING + case *ast.Ident: // e.g. const msg = "msg"; slog.Info(msg) + return msg.Obj != nil && msg.Obj.Kind == ast.Con + default: + return false } +} +func forEachKey(info *types.Info, keys, attrs []ast.Expr, fn func(key ast.Expr)) { for _, key := range keys { - if !isConst(key) { - return true - } + fn(key) } for _, attr := range attrs { switch attr := attr.(type) { case *ast.CallExpr: // e.g. slog.Int() - fn := typeutil.StaticCallee(info, attr) - if _, ok := attrFuncs[fn.FullName()]; ok && !isConst(attr.Args[0]) { - return true + callee := typeutil.StaticCallee(info, attr) + if callee == nil { + continue } - - case *ast.CompositeLit: // slog.Attr{} - isRawKey := func(kv *ast.KeyValueExpr) bool { - return kv.Key.(*ast.Ident).Name == "Key" && !isConst(kv.Value) + if _, ok := attrFuncs[callee.FullName()]; !ok { + continue } + fn(attr.Args[0]) + case *ast.CompositeLit: // slog.Attr{} switch len(attr.Elts) { case 1: // slog.Attr{Key: ...} | slog.Attr{Value: ...} - kv := attr.Elts[0].(*ast.KeyValueExpr) - if isRawKey(kv) { - return true + if kv := attr.Elts[0].(*ast.KeyValueExpr); kv.Key.(*ast.Ident).Name == "Key" { + fn(kv.Value) } - case 2: // slog.Attr{..., ...} | slog.Attr{Key: ..., Value: ...} - kv1, ok := attr.Elts[0].(*ast.KeyValueExpr) - if ok { - kv2 := attr.Elts[1].(*ast.KeyValueExpr) - if isRawKey(kv1) || isRawKey(kv2) { - return true - } - } else if !isConst(attr.Elts[0]) { - return true + case 2: // slog.Attr{Key: ..., Value: ...} | slog.Attr{Value: ..., Key: ...} | slog.Attr{..., ...} + if kv, ok := attr.Elts[0].(*ast.KeyValueExpr); ok && kv.Key.(*ast.Ident).Name == "Key" { + fn(kv.Value) + } else if kv, ok := attr.Elts[1].(*ast.KeyValueExpr); ok && kv.Key.(*ast.Ident).Name == "Key" { + fn(kv.Value) + } else { + fn(attr.Elts[0]) } } } } +} - return false +func getKeyName(key ast.Expr) (string, bool) { + if ident, ok := key.(*ast.Ident); ok { + if ident.Obj == nil || ident.Obj.Decl == nil || ident.Obj.Kind != ast.Con { + return "", false + } + if spec, ok := ident.Obj.Decl.(*ast.ValueSpec); ok && len(spec.Values) > 0 { + // TODO: support len(spec.Values) > 1; e.g. const foo, bar = 1, 2 + key = spec.Values[0] + } + } + if lit, ok := key.(*ast.BasicLit); ok && lit.Kind == token.STRING { + // string literals are always quoted. + value, err := strconv.Unquote(lit.Value) + if err != nil { + panic("unreachable") + } + return value, true + } + return "", false } -func argsOnSameLine(fset *token.FileSet, call ast.Expr, keys, attrs []ast.Expr) bool { +func areArgsOnSameLine(fset *token.FileSet, call ast.Expr, keys, attrs []ast.Expr) bool { if len(keys)+len(attrs) <= 1 { return false // special case: slog.Info("msg", "key", "value") is ok. } diff --git a/tools/vendor/go.tmz.dev/musttag/README.md b/tools/vendor/go.tmz.dev/musttag/README.md deleted file mode 100644 index 621c7a9a3..000000000 --- a/tools/vendor/go.tmz.dev/musttag/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# musttag - -[![checks](https://github.com/tmzane/musttag/actions/workflows/checks.yml/badge.svg)](https://github.com/tmzane/musttag/actions/workflows/checks.yml) -[![pkg.go.dev](https://pkg.go.dev/badge/go.tmz.dev/musttag.svg)](https://pkg.go.dev/go.tmz.dev/musttag) -[![goreportcard](https://goreportcard.com/badge/go.tmz.dev/musttag)](https://goreportcard.com/report/go.tmz.dev/musttag) -[![codecov](https://codecov.io/gh/tmzane/musttag/branch/main/graph/badge.svg)](https://codecov.io/gh/tmzane/musttag) - -A Go linter that enforces field tags in (un)marshaled structs - -## 📌 About - -`musttag` checks that exported fields of a struct passed to a `Marshal`-like function are annotated with the relevant tag: - -```go -// BAD: -var user struct { - Name string -} -data, err := json.Marshal(user) - -// GOOD: -var user struct { - Name string `json:"name"` -} -data, err := json.Marshal(user) -``` - -The rational from [Uber Style Guide][1]: - -> The serialized form of the structure is a contract between different systems. -> Changes to the structure of the serialized form, including field names, break this contract. -> Specifying field names inside tags makes the contract explicit, -> and it guards against accidentally breaking the contract by refactoring or renaming fields. - -## 🚀 Features - -The following packages are supported out of the box: - -* [`encoding/json`][2] -* [`encoding/xml`][3] -* [`gopkg.in/yaml.v3`][4] -* [`github.com/BurntSushi/toml`][5] -* [`github.com/mitchellh/mapstructure`][6] -* [`github.com/jmoiron/sqlx`][7] - -In addition, any [custom package](#custom-packages) can be added to the list. - -## 📋 Usage - -`musttag` is already integrated into `golangci-lint`, and this is the recommended way to use it. - -To enable the linter, add the following lines to `.golangci.yml`: - -```yaml -linters: - enable: - - musttag -``` - -If you'd rather prefer to use `musttag` standalone, you can install it via `brew`... - -```shell -brew install tmzane/tap/musttag -``` - -...or download a prebuilt binary from the [Releases][9] page. - -Then run it either directly or as a `go vet` tool: - -```shell -go vet -vettool=$(which musttag) ./... -``` - -### Custom packages - -To enable reporting a custom function, you need to add its description to `.golangci.yml`. - -The following is an example of adding support for the `hclsimple.DecodeFile` function from [`github.com/hashicorp/hcl`][8]: - -```yaml -linters-settings: - musttag: - functions: - # The full name of the function, including the package. - - name: github.com/hashicorp/hcl/v2/hclsimple.DecodeFile - # The struct tag whose presence should be ensured. - tag: hcl - # The position of the argument to check. - arg-pos: 2 -``` - -The same can be done via the `-fn=name:tag:arg-pos` flag when using `musttag` standalone: - -```shell -musttag -fn="github.com/hashicorp/hcl/v2/hclsimple.DecodeFile:hcl:2" ./... -``` - -[1]: https://github.com/uber-go/guide/blob/master/style.md#use-field-tags-in-marshaled-structs -[2]: https://pkg.go.dev/encoding/json -[3]: https://pkg.go.dev/encoding/xml -[4]: https://github.com/go-yaml/yaml -[5]: https://github.com/BurntSushi/toml -[6]: https://github.com/mitchellh/mapstructure -[7]: https://github.com/jmoiron/sqlx -[8]: https://github.com/hashicorp/hcl -[9]: https://github.com/tmzane/musttag/releases diff --git a/tools/vendor/go.tmz.dev/musttag/builtins.go b/tools/vendor/go.tmz.dev/musttag/builtins.go deleted file mode 100644 index 66914fa9e..000000000 --- a/tools/vendor/go.tmz.dev/musttag/builtins.go +++ /dev/null @@ -1,67 +0,0 @@ -package musttag - -// builtins is a set of functions supported out of the box. -var builtins = []Func{ - // https://pkg.go.dev/encoding/json - {Name: "encoding/json.Marshal", Tag: "json", ArgPos: 0}, - {Name: "encoding/json.MarshalIndent", Tag: "json", ArgPos: 0}, - {Name: "encoding/json.Unmarshal", Tag: "json", ArgPos: 1}, - {Name: "(*encoding/json.Encoder).Encode", Tag: "json", ArgPos: 0}, - {Name: "(*encoding/json.Decoder).Decode", Tag: "json", ArgPos: 0}, - - // https://pkg.go.dev/encoding/xml - {Name: "encoding/xml.Marshal", Tag: "xml", ArgPos: 0}, - {Name: "encoding/xml.MarshalIndent", Tag: "xml", ArgPos: 0}, - {Name: "encoding/xml.Unmarshal", Tag: "xml", ArgPos: 1}, - {Name: "(*encoding/xml.Encoder).Encode", Tag: "xml", ArgPos: 0}, - {Name: "(*encoding/xml.Decoder).Decode", Tag: "xml", ArgPos: 0}, - {Name: "(*encoding/xml.Encoder).EncodeElement", Tag: "xml", ArgPos: 0}, - {Name: "(*encoding/xml.Decoder).DecodeElement", Tag: "xml", ArgPos: 0}, - - // https://github.com/go-yaml/yaml - {Name: "gopkg.in/yaml.v3.Marshal", Tag: "yaml", ArgPos: 0}, - {Name: "gopkg.in/yaml.v3.Unmarshal", Tag: "yaml", ArgPos: 1}, - {Name: "(*gopkg.in/yaml.v3.Encoder).Encode", Tag: "yaml", ArgPos: 0}, - {Name: "(*gopkg.in/yaml.v3.Decoder).Decode", Tag: "yaml", ArgPos: 0}, - - // https://github.com/BurntSushi/toml - {Name: "github.com/BurntSushi/toml.Unmarshal", Tag: "toml", ArgPos: 1}, - {Name: "github.com/BurntSushi/toml.Decode", Tag: "toml", ArgPos: 1}, - {Name: "github.com/BurntSushi/toml.DecodeFS", Tag: "toml", ArgPos: 2}, - {Name: "github.com/BurntSushi/toml.DecodeFile", Tag: "toml", ArgPos: 1}, - {Name: "(*github.com/BurntSushi/toml.Encoder).Encode", Tag: "toml", ArgPos: 0}, - {Name: "(*github.com/BurntSushi/toml.Decoder).Decode", Tag: "toml", ArgPos: 0}, - - // https://github.com/mitchellh/mapstructure - {Name: "github.com/mitchellh/mapstructure.Decode", Tag: "mapstructure", ArgPos: 1}, - {Name: "github.com/mitchellh/mapstructure.DecodeMetadata", Tag: "mapstructure", ArgPos: 1}, - {Name: "github.com/mitchellh/mapstructure.WeakDecode", Tag: "mapstructure", ArgPos: 1}, - {Name: "github.com/mitchellh/mapstructure.WeakDecodeMetadata", Tag: "mapstructure", ArgPos: 1}, - - // https://github.com/jmoiron/sqlx - {Name: "github.com/jmoiron/sqlx.Get", Tag: "db", ArgPos: 1}, - {Name: "github.com/jmoiron/sqlx.GetContext", Tag: "db", ArgPos: 2}, - {Name: "github.com/jmoiron/sqlx.Select", Tag: "db", ArgPos: 1}, - {Name: "github.com/jmoiron/sqlx.SelectContext", Tag: "db", ArgPos: 2}, - {Name: "github.com/jmoiron/sqlx.StructScan", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.Conn).GetContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.Conn).SelectContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.DB).Get", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.DB).GetContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.DB).Select", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.DB).SelectContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.NamedStmt).Get", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.NamedStmt).GetContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.NamedStmt).Select", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.NamedStmt).SelectContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.Row).StructScan", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.Rows).StructScan", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.Stmt).Get", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.Stmt).GetContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.Stmt).Select", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.Stmt).SelectContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.Tx).Get", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.Tx).GetContext", Tag: "db", ArgPos: 1}, - {Name: "(*github.com/jmoiron/sqlx.Tx).Select", Tag: "db", ArgPos: 0}, - {Name: "(*github.com/jmoiron/sqlx.Tx).SelectContext", Tag: "db", ArgPos: 1}, -} diff --git a/tools/vendor/go.tmz.dev/musttag/musttag.go b/tools/vendor/go.tmz.dev/musttag/musttag.go deleted file mode 100644 index 7f4e05e75..000000000 --- a/tools/vendor/go.tmz.dev/musttag/musttag.go +++ /dev/null @@ -1,259 +0,0 @@ -// Package musttag implements the musttag analyzer. -package musttag - -import ( - "flag" - "fmt" - "go/ast" - "go/token" - "go/types" - "path" - "reflect" - "regexp" - "strconv" - "strings" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" - "golang.org/x/tools/go/ast/inspector" - "golang.org/x/tools/go/types/typeutil" -) - -// Func describes a function call to look for, e.g. json.Marshal. -type Func struct { - Name string // Name is the full name of the function, including the package. - Tag string // Tag is the struct tag whose presence should be ensured. - ArgPos int // ArgPos is the position of the argument to check. -} - -func (fn Func) shortName() string { - name := strings.NewReplacer("*", "", "(", "", ")", "").Replace(fn.Name) - return path.Base(name) -} - -// New creates a new musttag analyzer. -// To report a custom function provide its description via Func, -// it will be added to the builtin ones. -func New(funcs ...Func) *analysis.Analyzer { - var flagFuncs []Func - return &analysis.Analyzer{ - Name: "musttag", - Doc: "enforce field tags in (un)marshaled structs", - Flags: flags(&flagFuncs), - Requires: []*analysis.Analyzer{inspect.Analyzer}, - Run: func(pass *analysis.Pass) (any, error) { - l := len(builtins) + len(funcs) + len(flagFuncs) - f := make(map[string]Func, l) - - toMap := func(slice []Func) { - for _, fn := range slice { - f[fn.Name] = fn - } - } - toMap(builtins) - toMap(funcs) - toMap(flagFuncs) - - mainModule, err := getMainModule() - if err != nil { - return nil, err - } - - return run(pass, mainModule, f) - }, - } -} - -// flags creates a flag set for the analyzer. -// The funcs slice will be filled with custom functions passed via CLI flags. -func flags(funcs *[]Func) flag.FlagSet { - fs := flag.NewFlagSet("musttag", flag.ContinueOnError) - fs.Func("fn", "report custom function (name:tag:argpos)", func(s string) error { - parts := strings.Split(s, ":") - if len(parts) != 3 || parts[0] == "" || parts[1] == "" { - return strconv.ErrSyntax - } - pos, err := strconv.Atoi(parts[2]) - if err != nil { - return err - } - *funcs = append(*funcs, Func{ - Name: parts[0], - Tag: parts[1], - ArgPos: pos, - }) - return nil - }) - return *fs -} - -// for tests only. -var report = func(pass *analysis.Pass, st *structType, fn Func, fnPos token.Position) { - const format = "`%s` should be annotated with the `%s` tag as it is passed to `%s` at %s" - pass.Reportf(st.Pos, format, st.Name, fn.Tag, fn.shortName(), fnPos) -} - -var cleanFullName = regexp.MustCompile(`([^*/(]+/vendor/)`) - -// run starts the analysis. -func run(pass *analysis.Pass, mainModule string, funcs map[string]Func) (any, error) { - var err error - - walk := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) - filter := []ast.Node{(*ast.CallExpr)(nil)} - - walk.Preorder(filter, func(n ast.Node) { - if err != nil { - return // there is already an error. - } - - call, ok := n.(*ast.CallExpr) - if !ok { - return // not a function call. - } - - callee := typeutil.StaticCallee(pass.TypesInfo, call) - if callee == nil { - return // not a static call. - } - - name := cleanFullName.ReplaceAllString(callee.FullName(), "") - fn, ok := funcs[name] - if !ok { - return // the function is not supported. - } - - if len(call.Args) <= fn.ArgPos { - err = fmt.Errorf("Func.ArgPos cannot be %d: %s accepts only %d argument(s)", fn.ArgPos, fn.Name, len(call.Args)) - return - } - - arg := call.Args[fn.ArgPos] - if unary, ok := arg.(*ast.UnaryExpr); ok { - arg = unary.X // e.g. json.Marshal(&foo) - } - - initialPos := token.NoPos - switch arg := arg.(type) { - case *ast.Ident: // e.g. json.Marshal(foo) - if arg.Obj == nil { - return // e.g. json.Marshal(nil) - } - initialPos = arg.Obj.Pos() - case *ast.CompositeLit: // e.g. json.Marshal(struct{}{}) - initialPos = arg.Pos() - } - - checker := checker{ - mainModule: mainModule, - seenTypes: make(map[string]struct{}), - } - - t := pass.TypesInfo.TypeOf(arg) - st, ok := checker.parseStructType(t, initialPos) - if !ok { - return // not a struct argument. - } - - result, ok := checker.checkStructType(st, fn.Tag) - if ok { - return // nothing to report. - } - - p := pass.Fset.Position(call.Pos()) - report(pass, result, fn, p) - }) - - return nil, err -} - -// structType is an extension for types.Struct. -// The content of the fields depends on whether the type is named or not. -type structType struct { - *types.Struct - Name string // for types.Named: the type's name; for anonymous: a placeholder string. - Pos token.Pos // for types.Named: the type's position; for anonymous: the corresponding identifier's position. -} - -// checker parses and checks struct types. -type checker struct { - mainModule string - seenTypes map[string]struct{} // prevent panic on recursive types; see issue #16. -} - -// parseStructType parses the given types.Type, returning the underlying struct type. -func (c *checker) parseStructType(t types.Type, pos token.Pos) (*structType, bool) { - for { - // unwrap pointers (if any) first. - ptr, ok := t.(*types.Pointer) - if !ok { - break - } - t = ptr.Elem() - } - - switch t := t.(type) { - case *types.Named: // a struct of the named type. - pkg := t.Obj().Pkg() // may be nil; see issue #38. - if pkg == nil { - return nil, false - } - - if !strings.HasPrefix(pkg.Path(), c.mainModule) { - return nil, false - } - - s, ok := t.Underlying().(*types.Struct) - if !ok { - return nil, false - } - - return &structType{ - Struct: s, - Pos: t.Obj().Pos(), - Name: t.Obj().Name(), - }, true - - case *types.Struct: // an anonymous struct. - return &structType{ - Struct: t, - Pos: pos, - Name: "anonymous struct", - }, true - } - - return nil, false -} - -// checkStructType recursively checks whether the given struct type is annotated with the tag. -// The result is the type of the first nested struct which fields are not properly annotated. -func (c *checker) checkStructType(st *structType, tag string) (*structType, bool) { - c.seenTypes[st.String()] = struct{}{} - - for i := 0; i < st.NumFields(); i++ { - field := st.Field(i) - if !field.Exported() { - continue - } - - if _, ok := reflect.StructTag(st.Tag(i)).Lookup(tag); !ok { - // tag is not required for embedded types; see issue #12. - if !field.Embedded() { - return st, false - } - } - - nested, ok := c.parseStructType(field.Type(), st.Pos) // TODO: or field.Pos()? - if !ok { - continue - } - if _, ok := c.seenTypes[nested.String()]; ok { - continue - } - if result, ok := c.checkStructType(nested, tag); !ok { - return result, false - } - } - - return nil, true -} diff --git a/tools/vendor/go.tmz.dev/musttag/utils.go b/tools/vendor/go.tmz.dev/musttag/utils.go deleted file mode 100644 index 673747f15..000000000 --- a/tools/vendor/go.tmz.dev/musttag/utils.go +++ /dev/null @@ -1,57 +0,0 @@ -package musttag - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "os" - "os/exec" - "strings" -) - -var ( - getwd = os.Getwd - - commandOutput = func(name string, args ...string) (string, error) { - output, err := exec.Command(name, args...).Output() - return string(output), err - } -) - -func getMainModule() (string, error) { - args := []string{"go", "list", "-m", "-json"} - - output, err := commandOutput(args[0], args[1:]...) - if err != nil { - return "", fmt.Errorf("running `%s`: %w", strings.Join(args, " "), err) - } - - cwd, err := getwd() - if err != nil { - return "", fmt.Errorf("getting wd: %w", err) - } - - decoder := json.NewDecoder(strings.NewReader(output)) - - for { - // multiple JSON objects will be returned when using Go workspaces; see #63 for details. - var module struct { - Path string `json:"Path"` - Main bool `json:"Main"` - Dir string `json:"Dir"` - GoMod string `json:"GoMod"` - GoVersion string `json:"GoVersion"` - } - if err := decoder.Decode(&module); err != nil { - if errors.Is(err, io.EOF) { - return "", fmt.Errorf("main module not found\n%s", output) - } - return "", fmt.Errorf("decoding json: %w\n%s", err, output) - } - - if module.Main && strings.HasPrefix(cwd, module.Dir) { - return module.Path, nil - } - } -} diff --git a/tools/vendor/go.uber.org/automaxprocs/LICENSE b/tools/vendor/go.uber.org/automaxprocs/LICENSE new file mode 100644 index 000000000..20dcf51d9 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 Uber Technologies, 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. \ No newline at end of file diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroup.go b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroup.go new file mode 100644 index 000000000..fe4ecf561 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroup.go @@ -0,0 +1,79 @@ +// Copyright (c) 2017 Uber Technologies, 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. + +//go:build linux +// +build linux + +package cgroups + +import ( + "bufio" + "io" + "os" + "path/filepath" + "strconv" +) + +// CGroup represents the data structure for a Linux control group. +type CGroup struct { + path string +} + +// NewCGroup returns a new *CGroup from a given path. +func NewCGroup(path string) *CGroup { + return &CGroup{path: path} +} + +// Path returns the path of the CGroup*. +func (cg *CGroup) Path() string { + return cg.path +} + +// ParamPath returns the path of the given cgroup param under itself. +func (cg *CGroup) ParamPath(param string) string { + return filepath.Join(cg.path, param) +} + +// readFirstLine reads the first line from a cgroup param file. +func (cg *CGroup) readFirstLine(param string) (string, error) { + paramFile, err := os.Open(cg.ParamPath(param)) + if err != nil { + return "", err + } + defer paramFile.Close() + + scanner := bufio.NewScanner(paramFile) + if scanner.Scan() { + return scanner.Text(), nil + } + if err := scanner.Err(); err != nil { + return "", err + } + return "", io.ErrUnexpectedEOF +} + +// readInt parses the first line from a cgroup param file as int. +func (cg *CGroup) readInt(param string) (int, error) { + text, err := cg.readFirstLine(param) + if err != nil { + return 0, err + } + return strconv.Atoi(text) +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups.go b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups.go new file mode 100644 index 000000000..e89f54360 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups.go @@ -0,0 +1,118 @@ +// Copyright (c) 2017 Uber Technologies, 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. + +//go:build linux +// +build linux + +package cgroups + +const ( + // _cgroupFSType is the Linux CGroup file system type used in + // `/proc/$PID/mountinfo`. + _cgroupFSType = "cgroup" + // _cgroupSubsysCPU is the CPU CGroup subsystem. + _cgroupSubsysCPU = "cpu" + // _cgroupSubsysCPUAcct is the CPU accounting CGroup subsystem. + _cgroupSubsysCPUAcct = "cpuacct" + // _cgroupSubsysCPUSet is the CPUSet CGroup subsystem. + _cgroupSubsysCPUSet = "cpuset" + // _cgroupSubsysMemory is the Memory CGroup subsystem. + _cgroupSubsysMemory = "memory" + + // _cgroupCPUCFSQuotaUsParam is the file name for the CGroup CFS quota + // parameter. + _cgroupCPUCFSQuotaUsParam = "cpu.cfs_quota_us" + // _cgroupCPUCFSPeriodUsParam is the file name for the CGroup CFS period + // parameter. + _cgroupCPUCFSPeriodUsParam = "cpu.cfs_period_us" +) + +const ( + _procPathCGroup = "/proc/self/cgroup" + _procPathMountInfo = "/proc/self/mountinfo" +) + +// CGroups is a map that associates each CGroup with its subsystem name. +type CGroups map[string]*CGroup + +// NewCGroups returns a new *CGroups from given `mountinfo` and `cgroup` files +// under for some process under `/proc` file system (see also proc(5) for more +// information). +func NewCGroups(procPathMountInfo, procPathCGroup string) (CGroups, error) { + cgroupSubsystems, err := parseCGroupSubsystems(procPathCGroup) + if err != nil { + return nil, err + } + + cgroups := make(CGroups) + newMountPoint := func(mp *MountPoint) error { + if mp.FSType != _cgroupFSType { + return nil + } + + for _, opt := range mp.SuperOptions { + subsys, exists := cgroupSubsystems[opt] + if !exists { + continue + } + + cgroupPath, err := mp.Translate(subsys.Name) + if err != nil { + return err + } + cgroups[opt] = NewCGroup(cgroupPath) + } + + return nil + } + + if err := parseMountInfo(procPathMountInfo, newMountPoint); err != nil { + return nil, err + } + return cgroups, nil +} + +// NewCGroupsForCurrentProcess returns a new *CGroups instance for the current +// process. +func NewCGroupsForCurrentProcess() (CGroups, error) { + return NewCGroups(_procPathMountInfo, _procPathCGroup) +} + +// CPUQuota returns the CPU quota applied with the CPU cgroup controller. +// It is a result of `cpu.cfs_quota_us / cpu.cfs_period_us`. If the value of +// `cpu.cfs_quota_us` was not set (-1), the method returns `(-1, nil)`. +func (cg CGroups) CPUQuota() (float64, bool, error) { + cpuCGroup, exists := cg[_cgroupSubsysCPU] + if !exists { + return -1, false, nil + } + + cfsQuotaUs, err := cpuCGroup.readInt(_cgroupCPUCFSQuotaUsParam) + if defined := cfsQuotaUs > 0; err != nil || !defined { + return -1, defined, err + } + + cfsPeriodUs, err := cpuCGroup.readInt(_cgroupCPUCFSPeriodUsParam) + if defined := cfsPeriodUs > 0; err != nil || !defined { + return -1, defined, err + } + + return float64(cfsQuotaUs) / float64(cfsPeriodUs), true, nil +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups2.go b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups2.go new file mode 100644 index 000000000..78556062f --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups2.go @@ -0,0 +1,176 @@ +// Copyright (c) 2022 Uber Technologies, 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. + +//go:build linux +// +build linux + +package cgroups + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "path" + "strconv" + "strings" +) + +const ( + // _cgroupv2CPUMax is the file name for the CGroup-V2 CPU max and period + // parameter. + _cgroupv2CPUMax = "cpu.max" + // _cgroupFSType is the Linux CGroup-V2 file system type used in + // `/proc/$PID/mountinfo`. + _cgroupv2FSType = "cgroup2" + + _cgroupv2MountPoint = "/sys/fs/cgroup" + + _cgroupV2CPUMaxDefaultPeriod = 100000 + _cgroupV2CPUMaxQuotaMax = "max" +) + +const ( + _cgroupv2CPUMaxQuotaIndex = iota + _cgroupv2CPUMaxPeriodIndex +) + +// ErrNotV2 indicates that the system is not using cgroups2. +var ErrNotV2 = errors.New("not using cgroups2") + +// CGroups2 provides access to cgroups data for systems using cgroups2. +type CGroups2 struct { + mountPoint string + groupPath string + cpuMaxFile string +} + +// NewCGroups2ForCurrentProcess builds a CGroups2 for the current process. +// +// This returns ErrNotV2 if the system is not using cgroups2. +func NewCGroups2ForCurrentProcess() (*CGroups2, error) { + return newCGroups2From(_procPathMountInfo, _procPathCGroup) +} + +func newCGroups2From(mountInfoPath, procPathCGroup string) (*CGroups2, error) { + isV2, err := isCGroupV2(mountInfoPath) + if err != nil { + return nil, err + } + + if !isV2 { + return nil, ErrNotV2 + } + + subsystems, err := parseCGroupSubsystems(procPathCGroup) + if err != nil { + return nil, err + } + + // Find v2 subsystem by looking for the `0` id + var v2subsys *CGroupSubsys + for _, subsys := range subsystems { + if subsys.ID == 0 { + v2subsys = subsys + break + } + } + + if v2subsys == nil { + return nil, ErrNotV2 + } + + return &CGroups2{ + mountPoint: _cgroupv2MountPoint, + groupPath: v2subsys.Name, + cpuMaxFile: _cgroupv2CPUMax, + }, nil +} + +func isCGroupV2(procPathMountInfo string) (bool, error) { + var ( + isV2 bool + newMountPoint = func(mp *MountPoint) error { + isV2 = isV2 || (mp.FSType == _cgroupv2FSType && mp.MountPoint == _cgroupv2MountPoint) + return nil + } + ) + + if err := parseMountInfo(procPathMountInfo, newMountPoint); err != nil { + return false, err + } + + return isV2, nil +} + +// CPUQuota returns the CPU quota applied with the CPU cgroup2 controller. +// It is a result of reading cpu quota and period from cpu.max file. +// It will return `cpu.max / cpu.period`. If cpu.max is set to max, it returns +// (-1, false, nil) +func (cg *CGroups2) CPUQuota() (float64, bool, error) { + cpuMaxParams, err := os.Open(path.Join(cg.mountPoint, cg.groupPath, cg.cpuMaxFile)) + if err != nil { + if os.IsNotExist(err) { + return -1, false, nil + } + return -1, false, err + } + defer cpuMaxParams.Close() + + scanner := bufio.NewScanner(cpuMaxParams) + if scanner.Scan() { + fields := strings.Fields(scanner.Text()) + if len(fields) == 0 || len(fields) > 2 { + return -1, false, fmt.Errorf("invalid format") + } + + if fields[_cgroupv2CPUMaxQuotaIndex] == _cgroupV2CPUMaxQuotaMax { + return -1, false, nil + } + + max, err := strconv.Atoi(fields[_cgroupv2CPUMaxQuotaIndex]) + if err != nil { + return -1, false, err + } + + var period int + if len(fields) == 1 { + period = _cgroupV2CPUMaxDefaultPeriod + } else { + period, err = strconv.Atoi(fields[_cgroupv2CPUMaxPeriodIndex]) + if err != nil { + return -1, false, err + } + + if period == 0 { + return -1, false, errors.New("zero value for period is not allowed") + } + } + + return float64(max) / float64(period), true, nil + } + + if err := scanner.Err(); err != nil { + return -1, false, err + } + + return 0, false, io.ErrUnexpectedEOF +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/doc.go b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/doc.go new file mode 100644 index 000000000..113555f63 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/doc.go @@ -0,0 +1,23 @@ +// Copyright (c) 2017 Uber Technologies, 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 cgroups provides utilities to access Linux control group (CGroups) +// parameters (CPU quota, for example) for a given process. +package cgroups diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/errors.go b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/errors.go new file mode 100644 index 000000000..94ac75a46 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/errors.go @@ -0,0 +1,52 @@ +// Copyright (c) 2017 Uber Technologies, 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. + +//go:build linux +// +build linux + +package cgroups + +import "fmt" + +type cgroupSubsysFormatInvalidError struct { + line string +} + +type mountPointFormatInvalidError struct { + line string +} + +type pathNotExposedFromMountPointError struct { + mountPoint string + root string + path string +} + +func (err cgroupSubsysFormatInvalidError) Error() string { + return fmt.Sprintf("invalid format for CGroupSubsys: %q", err.line) +} + +func (err mountPointFormatInvalidError) Error() string { + return fmt.Sprintf("invalid format for MountPoint: %q", err.line) +} + +func (err pathNotExposedFromMountPointError) Error() string { + return fmt.Sprintf("path %q is not a descendant of mount point root %q and cannot be exposed from %q", err.path, err.root, err.mountPoint) +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/mountpoint.go b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/mountpoint.go new file mode 100644 index 000000000..f3877f78a --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/mountpoint.go @@ -0,0 +1,171 @@ +// Copyright (c) 2017 Uber Technologies, 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. + +//go:build linux +// +build linux + +package cgroups + +import ( + "bufio" + "os" + "path/filepath" + "strconv" + "strings" +) + +const ( + _mountInfoSep = " " + _mountInfoOptsSep = "," + _mountInfoOptionalFieldsSep = "-" +) + +const ( + _miFieldIDMountID = iota + _miFieldIDParentID + _miFieldIDDeviceID + _miFieldIDRoot + _miFieldIDMountPoint + _miFieldIDOptions + _miFieldIDOptionalFields + + _miFieldCountFirstHalf +) + +const ( + _miFieldOffsetFSType = iota + _miFieldOffsetMountSource + _miFieldOffsetSuperOptions + + _miFieldCountSecondHalf +) + +const _miFieldCountMin = _miFieldCountFirstHalf + _miFieldCountSecondHalf + +// MountPoint is the data structure for the mount points in +// `/proc/$PID/mountinfo`. See also proc(5) for more information. +type MountPoint struct { + MountID int + ParentID int + DeviceID string + Root string + MountPoint string + Options []string + OptionalFields []string + FSType string + MountSource string + SuperOptions []string +} + +// NewMountPointFromLine parses a line read from `/proc/$PID/mountinfo` and +// returns a new *MountPoint. +func NewMountPointFromLine(line string) (*MountPoint, error) { + fields := strings.Split(line, _mountInfoSep) + + if len(fields) < _miFieldCountMin { + return nil, mountPointFormatInvalidError{line} + } + + mountID, err := strconv.Atoi(fields[_miFieldIDMountID]) + if err != nil { + return nil, err + } + + parentID, err := strconv.Atoi(fields[_miFieldIDParentID]) + if err != nil { + return nil, err + } + + for i, field := range fields[_miFieldIDOptionalFields:] { + if field == _mountInfoOptionalFieldsSep { + // End of optional fields. + fsTypeStart := _miFieldIDOptionalFields + i + 1 + + // Now we know where the optional fields end, split the line again with a + // limit to avoid issues with spaces in super options as present on WSL. + fields = strings.SplitN(line, _mountInfoSep, fsTypeStart+_miFieldCountSecondHalf) + if len(fields) != fsTypeStart+_miFieldCountSecondHalf { + return nil, mountPointFormatInvalidError{line} + } + + miFieldIDFSType := _miFieldOffsetFSType + fsTypeStart + miFieldIDMountSource := _miFieldOffsetMountSource + fsTypeStart + miFieldIDSuperOptions := _miFieldOffsetSuperOptions + fsTypeStart + + return &MountPoint{ + MountID: mountID, + ParentID: parentID, + DeviceID: fields[_miFieldIDDeviceID], + Root: fields[_miFieldIDRoot], + MountPoint: fields[_miFieldIDMountPoint], + Options: strings.Split(fields[_miFieldIDOptions], _mountInfoOptsSep), + OptionalFields: fields[_miFieldIDOptionalFields:(fsTypeStart - 1)], + FSType: fields[miFieldIDFSType], + MountSource: fields[miFieldIDMountSource], + SuperOptions: strings.Split(fields[miFieldIDSuperOptions], _mountInfoOptsSep), + }, nil + } + } + + return nil, mountPointFormatInvalidError{line} +} + +// Translate converts an absolute path inside the *MountPoint's file system to +// the host file system path in the mount namespace the *MountPoint belongs to. +func (mp *MountPoint) Translate(absPath string) (string, error) { + relPath, err := filepath.Rel(mp.Root, absPath) + + if err != nil { + return "", err + } + if relPath == ".." || strings.HasPrefix(relPath, "../") { + return "", pathNotExposedFromMountPointError{ + mountPoint: mp.MountPoint, + root: mp.Root, + path: absPath, + } + } + + return filepath.Join(mp.MountPoint, relPath), nil +} + +// parseMountInfo parses procPathMountInfo (usually at `/proc/$PID/mountinfo`) +// and yields parsed *MountPoint into newMountPoint. +func parseMountInfo(procPathMountInfo string, newMountPoint func(*MountPoint) error) error { + mountInfoFile, err := os.Open(procPathMountInfo) + if err != nil { + return err + } + defer mountInfoFile.Close() + + scanner := bufio.NewScanner(mountInfoFile) + + for scanner.Scan() { + mountPoint, err := NewMountPointFromLine(scanner.Text()) + if err != nil { + return err + } + if err := newMountPoint(mountPoint); err != nil { + return err + } + } + + return scanner.Err() +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/subsys.go b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/subsys.go new file mode 100644 index 000000000..cddc3eaec --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/cgroups/subsys.go @@ -0,0 +1,103 @@ +// Copyright (c) 2017 Uber Technologies, 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. + +//go:build linux +// +build linux + +package cgroups + +import ( + "bufio" + "os" + "strconv" + "strings" +) + +const ( + _cgroupSep = ":" + _cgroupSubsysSep = "," +) + +const ( + _csFieldIDID = iota + _csFieldIDSubsystems + _csFieldIDName + _csFieldCount +) + +// CGroupSubsys represents the data structure for entities in +// `/proc/$PID/cgroup`. See also proc(5) for more information. +type CGroupSubsys struct { + ID int + Subsystems []string + Name string +} + +// NewCGroupSubsysFromLine returns a new *CGroupSubsys by parsing a string in +// the format of `/proc/$PID/cgroup` +func NewCGroupSubsysFromLine(line string) (*CGroupSubsys, error) { + fields := strings.SplitN(line, _cgroupSep, _csFieldCount) + + if len(fields) != _csFieldCount { + return nil, cgroupSubsysFormatInvalidError{line} + } + + id, err := strconv.Atoi(fields[_csFieldIDID]) + if err != nil { + return nil, err + } + + cgroup := &CGroupSubsys{ + ID: id, + Subsystems: strings.Split(fields[_csFieldIDSubsystems], _cgroupSubsysSep), + Name: fields[_csFieldIDName], + } + + return cgroup, nil +} + +// parseCGroupSubsystems parses procPathCGroup (usually at `/proc/$PID/cgroup`) +// and returns a new map[string]*CGroupSubsys. +func parseCGroupSubsystems(procPathCGroup string) (map[string]*CGroupSubsys, error) { + cgroupFile, err := os.Open(procPathCGroup) + if err != nil { + return nil, err + } + defer cgroupFile.Close() + + scanner := bufio.NewScanner(cgroupFile) + subsystems := make(map[string]*CGroupSubsys) + + for scanner.Scan() { + cgroup, err := NewCGroupSubsysFromLine(scanner.Text()) + if err != nil { + return nil, err + } + for _, subsys := range cgroup.Subsystems { + subsystems[subsys] = cgroup + } + } + + if err := scanner.Err(); err != nil { + return nil, err + } + + return subsystems, nil +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_linux.go b/tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_linux.go new file mode 100644 index 000000000..3b974754c --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_linux.go @@ -0,0 +1,71 @@ +// Copyright (c) 2017 Uber Technologies, 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. + +//go:build linux +// +build linux + +package runtime + +import ( + "errors" + "math" + + cg "go.uber.org/automaxprocs/internal/cgroups" +) + +// CPUQuotaToGOMAXPROCS converts the CPU quota applied to the calling process +// to a valid GOMAXPROCS value. +func CPUQuotaToGOMAXPROCS(minValue int) (int, CPUQuotaStatus, error) { + cgroups, err := newQueryer() + if err != nil { + return -1, CPUQuotaUndefined, err + } + + quota, defined, err := cgroups.CPUQuota() + if !defined || err != nil { + return -1, CPUQuotaUndefined, err + } + + maxProcs := int(math.Floor(quota)) + if minValue > 0 && maxProcs < minValue { + return minValue, CPUQuotaMinUsed, nil + } + return maxProcs, CPUQuotaUsed, nil +} + +type queryer interface { + CPUQuota() (float64, bool, error) +} + +var ( + _newCgroups2 = cg.NewCGroups2ForCurrentProcess + _newCgroups = cg.NewCGroupsForCurrentProcess +) + +func newQueryer() (queryer, error) { + cgroups, err := _newCgroups2() + if err == nil { + return cgroups, nil + } + if errors.Is(err, cg.ErrNotV2) { + return _newCgroups() + } + return nil, err +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_unsupported.go b/tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_unsupported.go new file mode 100644 index 000000000..692255448 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_unsupported.go @@ -0,0 +1,31 @@ +// Copyright (c) 2017 Uber Technologies, 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. + +//go:build !linux +// +build !linux + +package runtime + +// CPUQuotaToGOMAXPROCS converts the CPU quota applied to the calling process +// to a valid GOMAXPROCS value. This is Linux-specific and not supported in the +// current OS. +func CPUQuotaToGOMAXPROCS(_ int) (int, CPUQuotaStatus, error) { + return -1, CPUQuotaUndefined, nil +} diff --git a/tools/vendor/go.uber.org/automaxprocs/internal/runtime/runtime.go b/tools/vendor/go.uber.org/automaxprocs/internal/runtime/runtime.go new file mode 100644 index 000000000..df6eacf05 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/internal/runtime/runtime.go @@ -0,0 +1,33 @@ +// Copyright (c) 2017 Uber Technologies, 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 runtime + +// CPUQuotaStatus presents the status of how CPU quota is used +type CPUQuotaStatus int + +const ( + // CPUQuotaUndefined is returned when CPU quota is undefined + CPUQuotaUndefined CPUQuotaStatus = iota + // CPUQuotaUsed is returned when a valid CPU quota can be used + CPUQuotaUsed + // CPUQuotaMinUsed is returned when CPU quota is smaller than the min value + CPUQuotaMinUsed +) diff --git a/tools/vendor/go.uber.org/automaxprocs/maxprocs/maxprocs.go b/tools/vendor/go.uber.org/automaxprocs/maxprocs/maxprocs.go new file mode 100644 index 000000000..98176d645 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/maxprocs/maxprocs.go @@ -0,0 +1,130 @@ +// Copyright (c) 2017 Uber Technologies, 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 maxprocs lets Go programs easily configure runtime.GOMAXPROCS to +// match the configured Linux CPU quota. Unlike the top-level automaxprocs +// package, it lets the caller configure logging and handle errors. +package maxprocs // import "go.uber.org/automaxprocs/maxprocs" + +import ( + "os" + "runtime" + + iruntime "go.uber.org/automaxprocs/internal/runtime" +) + +const _maxProcsKey = "GOMAXPROCS" + +func currentMaxProcs() int { + return runtime.GOMAXPROCS(0) +} + +type config struct { + printf func(string, ...interface{}) + procs func(int) (int, iruntime.CPUQuotaStatus, error) + minGOMAXPROCS int +} + +func (c *config) log(fmt string, args ...interface{}) { + if c.printf != nil { + c.printf(fmt, args...) + } +} + +// An Option alters the behavior of Set. +type Option interface { + apply(*config) +} + +// Logger uses the supplied printf implementation for log output. By default, +// Set doesn't log anything. +func Logger(printf func(string, ...interface{})) Option { + return optionFunc(func(cfg *config) { + cfg.printf = printf + }) +} + +// Min sets the minimum GOMAXPROCS value that will be used. +// Any value below 1 is ignored. +func Min(n int) Option { + return optionFunc(func(cfg *config) { + if n >= 1 { + cfg.minGOMAXPROCS = n + } + }) +} + +type optionFunc func(*config) + +func (of optionFunc) apply(cfg *config) { of(cfg) } + +// Set GOMAXPROCS to match the Linux container CPU quota (if any), returning +// any error encountered and an undo function. +// +// Set is a no-op on non-Linux systems and in Linux environments without a +// configured CPU quota. +func Set(opts ...Option) (func(), error) { + cfg := &config{ + procs: iruntime.CPUQuotaToGOMAXPROCS, + minGOMAXPROCS: 1, + } + for _, o := range opts { + o.apply(cfg) + } + + undoNoop := func() { + cfg.log("maxprocs: No GOMAXPROCS change to reset") + } + + // Honor the GOMAXPROCS environment variable if present. Otherwise, amend + // `runtime.GOMAXPROCS()` with the current process' CPU quota if the OS is + // Linux, and guarantee a minimum value of 1. The minimum guaranteed value + // can be overridden using `maxprocs.Min()`. + if max, exists := os.LookupEnv(_maxProcsKey); exists { + cfg.log("maxprocs: Honoring GOMAXPROCS=%q as set in environment", max) + return undoNoop, nil + } + + maxProcs, status, err := cfg.procs(cfg.minGOMAXPROCS) + if err != nil { + return undoNoop, err + } + + if status == iruntime.CPUQuotaUndefined { + cfg.log("maxprocs: Leaving GOMAXPROCS=%v: CPU quota undefined", currentMaxProcs()) + return undoNoop, nil + } + + prev := currentMaxProcs() + undo := func() { + cfg.log("maxprocs: Resetting GOMAXPROCS to %v", prev) + runtime.GOMAXPROCS(prev) + } + + switch status { + case iruntime.CPUQuotaMinUsed: + cfg.log("maxprocs: Updating GOMAXPROCS=%v: using minimum allowed GOMAXPROCS", maxProcs) + case iruntime.CPUQuotaUsed: + cfg.log("maxprocs: Updating GOMAXPROCS=%v: determined from CPU quota", maxProcs) + } + + runtime.GOMAXPROCS(maxProcs) + return undo, nil +} diff --git a/tools/vendor/go.uber.org/automaxprocs/maxprocs/version.go b/tools/vendor/go.uber.org/automaxprocs/maxprocs/version.go new file mode 100644 index 000000000..108a95535 --- /dev/null +++ b/tools/vendor/go.uber.org/automaxprocs/maxprocs/version.go @@ -0,0 +1,24 @@ +// Copyright (c) 2017 Uber Technologies, 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 maxprocs + +// Version is the current package version. +const Version = "1.5.2" diff --git a/tools/vendor/golang.org/x/exp/maps/maps.go b/tools/vendor/golang.org/x/exp/maps/maps.go new file mode 100644 index 000000000..ecc0dabb7 --- /dev/null +++ b/tools/vendor/golang.org/x/exp/maps/maps.go @@ -0,0 +1,94 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package maps defines various functions useful with maps of any type. +package maps + +// Keys returns the keys of the map m. +// The keys will be in an indeterminate order. +func Keys[M ~map[K]V, K comparable, V any](m M) []K { + r := make([]K, 0, len(m)) + for k := range m { + r = append(r, k) + } + return r +} + +// Values returns the values of the map m. +// The values will be in an indeterminate order. +func Values[M ~map[K]V, K comparable, V any](m M) []V { + r := make([]V, 0, len(m)) + for _, v := range m { + r = append(r, v) + } + return r +} + +// Equal reports whether two maps contain the same key/value pairs. +// Values are compared using ==. +func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool { + if len(m1) != len(m2) { + return false + } + for k, v1 := range m1 { + if v2, ok := m2[k]; !ok || v1 != v2 { + return false + } + } + return true +} + +// EqualFunc is like Equal, but compares values using eq. +// Keys are still compared with ==. +func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool { + if len(m1) != len(m2) { + return false + } + for k, v1 := range m1 { + if v2, ok := m2[k]; !ok || !eq(v1, v2) { + return false + } + } + return true +} + +// Clear removes all entries from m, leaving it empty. +func Clear[M ~map[K]V, K comparable, V any](m M) { + for k := range m { + delete(m, k) + } +} + +// Clone returns a copy of m. This is a shallow clone: +// the new keys and values are set using ordinary assignment. +func Clone[M ~map[K]V, K comparable, V any](m M) M { + // Preserve nil in case it matters. + if m == nil { + return nil + } + r := make(M, len(m)) + for k, v := range m { + r[k] = v + } + return r +} + +// Copy copies all key/value pairs in src adding them to dst. +// When a key in src is already present in dst, +// the value in dst will be overwritten by the value associated +// with the key in src. +func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) { + for k, v := range src { + dst[k] = v + } +} + +// DeleteFunc deletes any key/value pairs from m for which del returns true. +func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) { + for k, v := range m { + if del(k, v) { + delete(m, k) + } + } +} diff --git a/tools/vendor/golang.org/x/exp/slices/cmp.go b/tools/vendor/golang.org/x/exp/slices/cmp.go new file mode 100644 index 000000000..fbf1934a0 --- /dev/null +++ b/tools/vendor/golang.org/x/exp/slices/cmp.go @@ -0,0 +1,44 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package slices + +import "golang.org/x/exp/constraints" + +// min is a version of the predeclared function from the Go 1.21 release. +func min[T constraints.Ordered](a, b T) T { + if a < b || isNaN(a) { + return a + } + return b +} + +// max is a version of the predeclared function from the Go 1.21 release. +func max[T constraints.Ordered](a, b T) T { + if a > b || isNaN(a) { + return a + } + return b +} + +// cmpLess is a copy of cmp.Less from the Go 1.21 release. +func cmpLess[T constraints.Ordered](x, y T) bool { + return (isNaN(x) && !isNaN(y)) || x < y +} + +// cmpCompare is a copy of cmp.Compare from the Go 1.21 release. +func cmpCompare[T constraints.Ordered](x, y T) int { + xNaN := isNaN(x) + yNaN := isNaN(y) + if xNaN && yNaN { + return 0 + } + if xNaN || x < y { + return -1 + } + if yNaN || x > y { + return +1 + } + return 0 +} diff --git a/tools/vendor/golang.org/x/exp/slices/slices.go b/tools/vendor/golang.org/x/exp/slices/slices.go index 2540bd682..5e8158bba 100644 --- a/tools/vendor/golang.org/x/exp/slices/slices.go +++ b/tools/vendor/golang.org/x/exp/slices/slices.go @@ -3,23 +3,20 @@ // license that can be found in the LICENSE file. // Package slices defines various functions useful with slices of any type. -// Unless otherwise specified, these functions all apply to the elements -// of a slice at index 0 <= i < len(s). -// -// Note that the less function in IsSortedFunc, SortFunc, SortStableFunc requires a -// strict weak ordering (https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings), -// or the sorting may fail to sort correctly. A common case is when sorting slices of -// floating-point numbers containing NaN values. package slices -import "golang.org/x/exp/constraints" +import ( + "unsafe" + + "golang.org/x/exp/constraints" +) // Equal reports whether two slices are equal: the same length and all // elements equal. If the lengths are different, Equal returns false. // Otherwise, the elements are compared in increasing index order, and the // comparison stops at the first unequal pair. // Floating point NaNs are not considered equal. -func Equal[E comparable](s1, s2 []E) bool { +func Equal[S ~[]E, E comparable](s1, s2 S) bool { if len(s1) != len(s2) { return false } @@ -31,12 +28,12 @@ func Equal[E comparable](s1, s2 []E) bool { return true } -// EqualFunc reports whether two slices are equal using a comparison +// EqualFunc reports whether two slices are equal using an equality // function on each pair of elements. If the lengths are different, // EqualFunc returns false. Otherwise, the elements are compared in // increasing index order, and the comparison stops at the first index // for which eq returns false. -func EqualFunc[E1, E2 any](s1 []E1, s2 []E2, eq func(E1, E2) bool) bool { +func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool { if len(s1) != len(s2) { return false } @@ -49,45 +46,37 @@ func EqualFunc[E1, E2 any](s1 []E1, s2 []E2, eq func(E1, E2) bool) bool { return true } -// Compare compares the elements of s1 and s2. -// The elements are compared sequentially, starting at index 0, +// Compare compares the elements of s1 and s2, using [cmp.Compare] on each pair +// of elements. The elements are compared sequentially, starting at index 0, // until one element is not equal to the other. // The result of comparing the first non-matching elements is returned. // If both slices are equal until one of them ends, the shorter slice is // considered less than the longer one. // The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2. -// Comparisons involving floating point NaNs are ignored. -func Compare[E constraints.Ordered](s1, s2 []E) int { - s2len := len(s2) +func Compare[S ~[]E, E constraints.Ordered](s1, s2 S) int { for i, v1 := range s1 { - if i >= s2len { + if i >= len(s2) { return +1 } v2 := s2[i] - switch { - case v1 < v2: - return -1 - case v1 > v2: - return +1 + if c := cmpCompare(v1, v2); c != 0 { + return c } } - if len(s1) < s2len { + if len(s1) < len(s2) { return -1 } return 0 } -// CompareFunc is like Compare but uses a comparison function -// on each pair of elements. The elements are compared in increasing -// index order, and the comparisons stop after the first time cmp -// returns non-zero. +// CompareFunc is like [Compare] but uses a custom comparison function on each +// pair of elements. // The result is the first non-zero result of cmp; if cmp always // returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2), // and +1 if len(s1) > len(s2). -func CompareFunc[E1, E2 any](s1 []E1, s2 []E2, cmp func(E1, E2) int) int { - s2len := len(s2) +func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int { for i, v1 := range s1 { - if i >= s2len { + if i >= len(s2) { return +1 } v2 := s2[i] @@ -95,7 +84,7 @@ func CompareFunc[E1, E2 any](s1 []E1, s2 []E2, cmp func(E1, E2) int) int { return c } } - if len(s1) < s2len { + if len(s1) < len(s2) { return -1 } return 0 @@ -103,7 +92,7 @@ func CompareFunc[E1, E2 any](s1 []E1, s2 []E2, cmp func(E1, E2) int) int { // Index returns the index of the first occurrence of v in s, // or -1 if not present. -func Index[E comparable](s []E, v E) int { +func Index[S ~[]E, E comparable](s S, v E) int { for i := range s { if v == s[i] { return i @@ -114,7 +103,7 @@ func Index[E comparable](s []E, v E) int { // IndexFunc returns the first index i satisfying f(s[i]), // or -1 if none do. -func IndexFunc[E any](s []E, f func(E) bool) int { +func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int { for i := range s { if f(s[i]) { return i @@ -124,39 +113,104 @@ func IndexFunc[E any](s []E, f func(E) bool) int { } // Contains reports whether v is present in s. -func Contains[E comparable](s []E, v E) bool { +func Contains[S ~[]E, E comparable](s S, v E) bool { return Index(s, v) >= 0 } // ContainsFunc reports whether at least one // element e of s satisfies f(e). -func ContainsFunc[E any](s []E, f func(E) bool) bool { +func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool { return IndexFunc(s, f) >= 0 } // Insert inserts the values v... into s at index i, // returning the modified slice. -// In the returned slice r, r[i] == v[0]. +// The elements at s[i:] are shifted up to make room. +// In the returned slice r, r[i] == v[0], +// and r[i+len(v)] == value originally at r[i]. // Insert panics if i is out of range. // This function is O(len(s) + len(v)). func Insert[S ~[]E, E any](s S, i int, v ...E) S { - tot := len(s) + len(v) - if tot <= cap(s) { - s2 := s[:tot] - copy(s2[i+len(v):], s[i:]) + m := len(v) + if m == 0 { + return s + } + n := len(s) + if i == n { + return append(s, v...) + } + if n+m > cap(s) { + // Use append rather than make so that we bump the size of + // the slice up to the next storage class. + // This is what Grow does but we don't call Grow because + // that might copy the values twice. + s2 := append(s[:i], make(S, n+m-i)...) copy(s2[i:], v) + copy(s2[i+m:], s[i:]) return s2 } - s2 := make(S, tot) - copy(s2, s[:i]) - copy(s2[i:], v) - copy(s2[i+len(v):], s[i:]) - return s2 + s = s[:n+m] + + // before: + // s: aaaaaaaabbbbccccccccdddd + // ^ ^ ^ ^ + // i i+m n n+m + // after: + // s: aaaaaaaavvvvbbbbcccccccc + // ^ ^ ^ ^ + // i i+m n n+m + // + // a are the values that don't move in s. + // v are the values copied in from v. + // b and c are the values from s that are shifted up in index. + // d are the values that get overwritten, never to be seen again. + + if !overlaps(v, s[i+m:]) { + // Easy case - v does not overlap either the c or d regions. + // (It might be in some of a or b, or elsewhere entirely.) + // The data we copy up doesn't write to v at all, so just do it. + + copy(s[i+m:], s[i:]) + + // Now we have + // s: aaaaaaaabbbbbbbbcccccccc + // ^ ^ ^ ^ + // i i+m n n+m + // Note the b values are duplicated. + + copy(s[i:], v) + + // Now we have + // s: aaaaaaaavvvvbbbbcccccccc + // ^ ^ ^ ^ + // i i+m n n+m + // That's the result we want. + return s + } + + // The hard case - v overlaps c or d. We can't just shift up + // the data because we'd move or clobber the values we're trying + // to insert. + // So instead, write v on top of d, then rotate. + copy(s[n:], v) + + // Now we have + // s: aaaaaaaabbbbccccccccvvvv + // ^ ^ ^ ^ + // i i+m n n+m + + rotateRight(s[i:], m) + + // Now we have + // s: aaaaaaaavvvvbbbbcccccccc + // ^ ^ ^ ^ + // i i+m n n+m + // That's the result we want. + return s } // Delete removes the elements s[i:j] from s, returning the modified slice. // Delete panics if s[i:j] is not a valid slice of s. -// Delete modifies the contents of the slice s; it does not create a new slice. // Delete is O(len(s)-j), so if many items must be deleted, it is better to // make a single call deleting them all together than to delete one at a time. // Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those @@ -168,22 +222,113 @@ func Delete[S ~[]E, E any](s S, i, j int) S { return append(s[:i], s[j:]...) } +// DeleteFunc removes any elements from s for which del returns true, +// returning the modified slice. +// When DeleteFunc removes m elements, it might not modify the elements +// s[len(s)-m:len(s)]. If those elements contain pointers you might consider +// zeroing those elements so that objects they reference can be garbage +// collected. +func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S { + i := IndexFunc(s, del) + if i == -1 { + return s + } + // Don't start copying elements until we find one to delete. + for j := i + 1; j < len(s); j++ { + if v := s[j]; !del(v) { + s[i] = v + i++ + } + } + return s[:i] +} + // Replace replaces the elements s[i:j] by the given v, and returns the // modified slice. Replace panics if s[i:j] is not a valid slice of s. func Replace[S ~[]E, E any](s S, i, j int, v ...E) S { _ = s[i:j] // verify that i:j is a valid subslice + + if i == j { + return Insert(s, i, v...) + } + if j == len(s) { + return append(s[:i], v...) + } + tot := len(s[:i]) + len(v) + len(s[j:]) - if tot <= cap(s) { - s2 := s[:tot] - copy(s2[i+len(v):], s[j:]) + if tot > cap(s) { + // Too big to fit, allocate and copy over. + s2 := append(s[:i], make(S, tot-i)...) // See Insert copy(s2[i:], v) + copy(s2[i+len(v):], s[j:]) return s2 } - s2 := make(S, tot) - copy(s2, s[:i]) - copy(s2[i:], v) - copy(s2[i+len(v):], s[j:]) - return s2 + + r := s[:tot] + + if i+len(v) <= j { + // Easy, as v fits in the deleted portion. + copy(r[i:], v) + if i+len(v) != j { + copy(r[i+len(v):], s[j:]) + } + return r + } + + // We are expanding (v is bigger than j-i). + // The situation is something like this: + // (example has i=4,j=8,len(s)=16,len(v)=6) + // s: aaaaxxxxbbbbbbbbyy + // ^ ^ ^ ^ + // i j len(s) tot + // a: prefix of s + // x: deleted range + // b: more of s + // y: area to expand into + + if !overlaps(r[i+len(v):], v) { + // Easy, as v is not clobbered by the first copy. + copy(r[i+len(v):], s[j:]) + copy(r[i:], v) + return r + } + + // This is a situation where we don't have a single place to which + // we can copy v. Parts of it need to go to two different places. + // We want to copy the prefix of v into y and the suffix into x, then + // rotate |y| spots to the right. + // + // v[2:] v[:2] + // | | + // s: aaaavvvvbbbbbbbbvv + // ^ ^ ^ ^ + // i j len(s) tot + // + // If either of those two destinations don't alias v, then we're good. + y := len(v) - (j - i) // length of y portion + + if !overlaps(r[i:j], v) { + copy(r[i:j], v[y:]) + copy(r[len(s):], v[:y]) + rotateRight(r[i:], y) + return r + } + if !overlaps(r[len(s):], v) { + copy(r[len(s):], v[:y]) + copy(r[i:j], v[y:]) + rotateRight(r[i:], y) + return r + } + + // Now we know that v overlaps both x and y. + // That means that the entirety of b is *inside* v. + // So we don't need to preserve b at all; instead we + // can copy v first, then copy the b part of v out of + // v to the right destination. + k := startIdx(v, s[j:]) + copy(r[i:], v) + copy(r[i+len(v):], r[i+k:]) + return r } // Clone returns a copy of the slice. @@ -198,7 +343,8 @@ func Clone[S ~[]E, E any](s S) S { // Compact replaces consecutive runs of equal elements with a single copy. // This is like the uniq command found on Unix. -// Compact modifies the contents of the slice s; it does not create a new slice. +// Compact modifies the contents of the slice s and returns the modified slice, +// which may have a smaller length. // When Compact discards m elements in total, it might not modify the elements // s[len(s)-m:len(s)]. If those elements contain pointers you might consider // zeroing those elements so that objects they reference can be garbage collected. @@ -218,7 +364,8 @@ func Compact[S ~[]E, E comparable](s S) S { return s[:i] } -// CompactFunc is like Compact but uses a comparison function. +// CompactFunc is like [Compact] but uses an equality function to compare elements. +// For runs of elements that compare equal, CompactFunc keeps the first one. func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S { if len(s) < 2 { return s @@ -256,3 +403,97 @@ func Grow[S ~[]E, E any](s S, n int) S { func Clip[S ~[]E, E any](s S) S { return s[:len(s):len(s)] } + +// Rotation algorithm explanation: +// +// rotate left by 2 +// start with +// 0123456789 +// split up like this +// 01 234567 89 +// swap first 2 and last 2 +// 89 234567 01 +// join first parts +// 89234567 01 +// recursively rotate first left part by 2 +// 23456789 01 +// join at the end +// 2345678901 +// +// rotate left by 8 +// start with +// 0123456789 +// split up like this +// 01 234567 89 +// swap first 2 and last 2 +// 89 234567 01 +// join last parts +// 89 23456701 +// recursively rotate second part left by 6 +// 89 01234567 +// join at the end +// 8901234567 + +// TODO: There are other rotate algorithms. +// This algorithm has the desirable property that it moves each element exactly twice. +// The triple-reverse algorithm is simpler and more cache friendly, but takes more writes. +// The follow-cycles algorithm can be 1-write but it is not very cache friendly. + +// rotateLeft rotates b left by n spaces. +// s_final[i] = s_orig[i+r], wrapping around. +func rotateLeft[E any](s []E, r int) { + for r != 0 && r != len(s) { + if r*2 <= len(s) { + swap(s[:r], s[len(s)-r:]) + s = s[:len(s)-r] + } else { + swap(s[:len(s)-r], s[r:]) + s, r = s[len(s)-r:], r*2-len(s) + } + } +} +func rotateRight[E any](s []E, r int) { + rotateLeft(s, len(s)-r) +} + +// swap swaps the contents of x and y. x and y must be equal length and disjoint. +func swap[E any](x, y []E) { + for i := 0; i < len(x); i++ { + x[i], y[i] = y[i], x[i] + } +} + +// overlaps reports whether the memory ranges a[0:len(a)] and b[0:len(b)] overlap. +func overlaps[E any](a, b []E) bool { + if len(a) == 0 || len(b) == 0 { + return false + } + elemSize := unsafe.Sizeof(a[0]) + if elemSize == 0 { + return false + } + // TODO: use a runtime/unsafe facility once one becomes available. See issue 12445. + // Also see crypto/internal/alias/alias.go:AnyOverlap + return uintptr(unsafe.Pointer(&a[0])) <= uintptr(unsafe.Pointer(&b[len(b)-1]))+(elemSize-1) && + uintptr(unsafe.Pointer(&b[0])) <= uintptr(unsafe.Pointer(&a[len(a)-1]))+(elemSize-1) +} + +// startIdx returns the index in haystack where the needle starts. +// prerequisite: the needle must be aliased entirely inside the haystack. +func startIdx[E any](haystack, needle []E) int { + p := &needle[0] + for i := range haystack { + if p == &haystack[i] { + return i + } + } + // TODO: what if the overlap is by a non-integral number of Es? + panic("needle not found") +} + +// Reverse reverses the elements of the slice in place. +func Reverse[S ~[]E, E any](s S) { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } +} diff --git a/tools/vendor/golang.org/x/exp/slices/sort.go b/tools/vendor/golang.org/x/exp/slices/sort.go index 231b6448a..b67897f76 100644 --- a/tools/vendor/golang.org/x/exp/slices/sort.go +++ b/tools/vendor/golang.org/x/exp/slices/sort.go @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:generate go run $GOROOT/src/sort/gen_sort_variants.go -exp + package slices import ( @@ -11,57 +13,116 @@ import ( ) // Sort sorts a slice of any ordered type in ascending order. -// Sort may fail to sort correctly when sorting slices of floating-point -// numbers containing Not-a-number (NaN) values. -// Use slices.SortFunc(x, func(a, b float64) bool {return a < b || (math.IsNaN(a) && !math.IsNaN(b))}) -// instead if the input may contain NaNs. -func Sort[E constraints.Ordered](x []E) { +// When sorting floating-point numbers, NaNs are ordered before other values. +func Sort[S ~[]E, E constraints.Ordered](x S) { n := len(x) pdqsortOrdered(x, 0, n, bits.Len(uint(n))) } -// SortFunc sorts the slice x in ascending order as determined by the less function. -// This sort is not guaranteed to be stable. +// SortFunc sorts the slice x in ascending order as determined by the cmp +// function. This sort is not guaranteed to be stable. +// cmp(a, b) should return a negative number when a < b, a positive number when +// a > b and zero when a == b. // -// SortFunc requires that less is a strict weak ordering. +// SortFunc requires that cmp is a strict weak ordering. // See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings. -func SortFunc[E any](x []E, less func(a, b E) bool) { +func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int) { n := len(x) - pdqsortLessFunc(x, 0, n, bits.Len(uint(n)), less) + pdqsortCmpFunc(x, 0, n, bits.Len(uint(n)), cmp) } // SortStableFunc sorts the slice x while keeping the original order of equal -// elements, using less to compare elements. -func SortStableFunc[E any](x []E, less func(a, b E) bool) { - stableLessFunc(x, len(x), less) +// elements, using cmp to compare elements in the same way as [SortFunc]. +func SortStableFunc[S ~[]E, E any](x S, cmp func(a, b E) int) { + stableCmpFunc(x, len(x), cmp) } // IsSorted reports whether x is sorted in ascending order. -func IsSorted[E constraints.Ordered](x []E) bool { +func IsSorted[S ~[]E, E constraints.Ordered](x S) bool { for i := len(x) - 1; i > 0; i-- { - if x[i] < x[i-1] { + if cmpLess(x[i], x[i-1]) { return false } } return true } -// IsSortedFunc reports whether x is sorted in ascending order, with less as the -// comparison function. -func IsSortedFunc[E any](x []E, less func(a, b E) bool) bool { +// IsSortedFunc reports whether x is sorted in ascending order, with cmp as the +// comparison function as defined by [SortFunc]. +func IsSortedFunc[S ~[]E, E any](x S, cmp func(a, b E) int) bool { for i := len(x) - 1; i > 0; i-- { - if less(x[i], x[i-1]) { + if cmp(x[i], x[i-1]) < 0 { return false } } return true } +// Min returns the minimal value in x. It panics if x is empty. +// For floating-point numbers, Min propagates NaNs (any NaN value in x +// forces the output to be NaN). +func Min[S ~[]E, E constraints.Ordered](x S) E { + if len(x) < 1 { + panic("slices.Min: empty list") + } + m := x[0] + for i := 1; i < len(x); i++ { + m = min(m, x[i]) + } + return m +} + +// MinFunc returns the minimal value in x, using cmp to compare elements. +// It panics if x is empty. If there is more than one minimal element +// according to the cmp function, MinFunc returns the first one. +func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E { + if len(x) < 1 { + panic("slices.MinFunc: empty list") + } + m := x[0] + for i := 1; i < len(x); i++ { + if cmp(x[i], m) < 0 { + m = x[i] + } + } + return m +} + +// Max returns the maximal value in x. It panics if x is empty. +// For floating-point E, Max propagates NaNs (any NaN value in x +// forces the output to be NaN). +func Max[S ~[]E, E constraints.Ordered](x S) E { + if len(x) < 1 { + panic("slices.Max: empty list") + } + m := x[0] + for i := 1; i < len(x); i++ { + m = max(m, x[i]) + } + return m +} + +// MaxFunc returns the maximal value in x, using cmp to compare elements. +// It panics if x is empty. If there is more than one maximal element +// according to the cmp function, MaxFunc returns the first one. +func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E { + if len(x) < 1 { + panic("slices.MaxFunc: empty list") + } + m := x[0] + for i := 1; i < len(x); i++ { + if cmp(x[i], m) > 0 { + m = x[i] + } + } + return m +} + // BinarySearch searches for target in a sorted slice and returns the position // where target is found, or the position where target would appear in the // sort order; it also returns a bool saying whether the target is really found // in the slice. The slice must be sorted in increasing order. -func BinarySearch[E constraints.Ordered](x []E, target E) (int, bool) { +func BinarySearch[S ~[]E, E constraints.Ordered](x S, target E) (int, bool) { // Inlining is faster than calling BinarySearchFunc with a lambda. n := len(x) // Define x[-1] < target and x[n] >= target. @@ -70,24 +131,24 @@ func BinarySearch[E constraints.Ordered](x []E, target E) (int, bool) { for i < j { h := int(uint(i+j) >> 1) // avoid overflow when computing h // i ≤ h < j - if x[h] < target { + if cmpLess(x[h], target) { i = h + 1 // preserves x[i-1] < target } else { j = h // preserves x[j] >= target } } // i == j, x[i-1] < target, and x[j] (= x[i]) >= target => answer is i. - return i, i < n && x[i] == target + return i, i < n && (x[i] == target || (isNaN(x[i]) && isNaN(target))) } -// BinarySearchFunc works like BinarySearch, but uses a custom comparison +// BinarySearchFunc works like [BinarySearch], but uses a custom comparison // function. The slice must be sorted in increasing order, where "increasing" // is defined by cmp. cmp should return 0 if the slice element matches // the target, a negative number if the slice element precedes the target, // or a positive number if the slice element follows the target. // cmp must implement the same ordering as the slice, such that if // cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice. -func BinarySearchFunc[E, T any](x []E, target T, cmp func(E, T) int) (int, bool) { +func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool) { n := len(x) // Define cmp(x[-1], target) < 0 and cmp(x[n], target) >= 0 . // Invariant: cmp(x[i - 1], target) < 0, cmp(x[j], target) >= 0. @@ -126,3 +187,9 @@ func (r *xorshift) Next() uint64 { func nextPowerOfTwo(length int) uint { return 1 << bits.Len(uint(length)) } + +// isNaN reports whether x is a NaN without requiring the math package. +// This will always return false if T is not floating-point. +func isNaN[T constraints.Ordered](x T) bool { + return x != x +} diff --git a/tools/vendor/golang.org/x/exp/slices/zsortfunc.go b/tools/vendor/golang.org/x/exp/slices/zsortanyfunc.go similarity index 64% rename from tools/vendor/golang.org/x/exp/slices/zsortfunc.go rename to tools/vendor/golang.org/x/exp/slices/zsortanyfunc.go index 2a632476c..06f2c7a24 100644 --- a/tools/vendor/golang.org/x/exp/slices/zsortfunc.go +++ b/tools/vendor/golang.org/x/exp/slices/zsortanyfunc.go @@ -6,28 +6,28 @@ package slices -// insertionSortLessFunc sorts data[a:b] using insertion sort. -func insertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { +// insertionSortCmpFunc sorts data[a:b] using insertion sort. +func insertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { for i := a + 1; i < b; i++ { - for j := i; j > a && less(data[j], data[j-1]); j-- { + for j := i; j > a && (cmp(data[j], data[j-1]) < 0); j-- { data[j], data[j-1] = data[j-1], data[j] } } } -// siftDownLessFunc implements the heap property on data[lo:hi]. +// siftDownCmpFunc implements the heap property on data[lo:hi]. // first is an offset into the array where the root of the heap lies. -func siftDownLessFunc[E any](data []E, lo, hi, first int, less func(a, b E) bool) { +func siftDownCmpFunc[E any](data []E, lo, hi, first int, cmp func(a, b E) int) { root := lo for { child := 2*root + 1 if child >= hi { break } - if child+1 < hi && less(data[first+child], data[first+child+1]) { + if child+1 < hi && (cmp(data[first+child], data[first+child+1]) < 0) { child++ } - if !less(data[first+root], data[first+child]) { + if !(cmp(data[first+root], data[first+child]) < 0) { return } data[first+root], data[first+child] = data[first+child], data[first+root] @@ -35,30 +35,30 @@ func siftDownLessFunc[E any](data []E, lo, hi, first int, less func(a, b E) bool } } -func heapSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { +func heapSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { first := a lo := 0 hi := b - a // Build heap with greatest element at top. for i := (hi - 1) / 2; i >= 0; i-- { - siftDownLessFunc(data, i, hi, first, less) + siftDownCmpFunc(data, i, hi, first, cmp) } // Pop elements, largest first, into end of data. for i := hi - 1; i >= 0; i-- { data[first], data[first+i] = data[first+i], data[first] - siftDownLessFunc(data, lo, i, first, less) + siftDownCmpFunc(data, lo, i, first, cmp) } } -// pdqsortLessFunc sorts data[a:b]. +// pdqsortCmpFunc sorts data[a:b]. // The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort. // pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf // C++ implementation: https://github.com/orlp/pdqsort // Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/ // limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort. -func pdqsortLessFunc[E any](data []E, a, b, limit int, less func(a, b E) bool) { +func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) { const maxInsertion = 12 var ( @@ -70,25 +70,25 @@ func pdqsortLessFunc[E any](data []E, a, b, limit int, less func(a, b E) bool) { length := b - a if length <= maxInsertion { - insertionSortLessFunc(data, a, b, less) + insertionSortCmpFunc(data, a, b, cmp) return } // Fall back to heapsort if too many bad choices were made. if limit == 0 { - heapSortLessFunc(data, a, b, less) + heapSortCmpFunc(data, a, b, cmp) return } // If the last partitioning was imbalanced, we need to breaking patterns. if !wasBalanced { - breakPatternsLessFunc(data, a, b, less) + breakPatternsCmpFunc(data, a, b, cmp) limit-- } - pivot, hint := choosePivotLessFunc(data, a, b, less) + pivot, hint := choosePivotCmpFunc(data, a, b, cmp) if hint == decreasingHint { - reverseRangeLessFunc(data, a, b, less) + reverseRangeCmpFunc(data, a, b, cmp) // The chosen pivot was pivot-a elements after the start of the array. // After reversing it is pivot-a elements before the end of the array. // The idea came from Rust's implementation. @@ -98,48 +98,48 @@ func pdqsortLessFunc[E any](data []E, a, b, limit int, less func(a, b E) bool) { // The slice is likely already sorted. if wasBalanced && wasPartitioned && hint == increasingHint { - if partialInsertionSortLessFunc(data, a, b, less) { + if partialInsertionSortCmpFunc(data, a, b, cmp) { return } } // Probably the slice contains many duplicate elements, partition the slice into // elements equal to and elements greater than the pivot. - if a > 0 && !less(data[a-1], data[pivot]) { - mid := partitionEqualLessFunc(data, a, b, pivot, less) + if a > 0 && !(cmp(data[a-1], data[pivot]) < 0) { + mid := partitionEqualCmpFunc(data, a, b, pivot, cmp) a = mid continue } - mid, alreadyPartitioned := partitionLessFunc(data, a, b, pivot, less) + mid, alreadyPartitioned := partitionCmpFunc(data, a, b, pivot, cmp) wasPartitioned = alreadyPartitioned leftLen, rightLen := mid-a, b-mid balanceThreshold := length / 8 if leftLen < rightLen { wasBalanced = leftLen >= balanceThreshold - pdqsortLessFunc(data, a, mid, limit, less) + pdqsortCmpFunc(data, a, mid, limit, cmp) a = mid + 1 } else { wasBalanced = rightLen >= balanceThreshold - pdqsortLessFunc(data, mid+1, b, limit, less) + pdqsortCmpFunc(data, mid+1, b, limit, cmp) b = mid } } } -// partitionLessFunc does one quicksort partition. +// partitionCmpFunc does one quicksort partition. // Let p = data[pivot] // Moves elements in data[a:b] around, so that data[i]

=p for inewpivot. // On return, data[newpivot] = p -func partitionLessFunc[E any](data []E, a, b, pivot int, less func(a, b E) bool) (newpivot int, alreadyPartitioned bool) { +func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int, alreadyPartitioned bool) { data[a], data[pivot] = data[pivot], data[a] i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned - for i <= j && less(data[i], data[a]) { + for i <= j && (cmp(data[i], data[a]) < 0) { i++ } - for i <= j && !less(data[j], data[a]) { + for i <= j && !(cmp(data[j], data[a]) < 0) { j-- } if i > j { @@ -151,10 +151,10 @@ func partitionLessFunc[E any](data []E, a, b, pivot int, less func(a, b E) bool) j-- for { - for i <= j && less(data[i], data[a]) { + for i <= j && (cmp(data[i], data[a]) < 0) { i++ } - for i <= j && !less(data[j], data[a]) { + for i <= j && !(cmp(data[j], data[a]) < 0) { j-- } if i > j { @@ -168,17 +168,17 @@ func partitionLessFunc[E any](data []E, a, b, pivot int, less func(a, b E) bool) return j, false } -// partitionEqualLessFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot]. +// partitionEqualCmpFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot]. // It assumed that data[a:b] does not contain elements smaller than the data[pivot]. -func partitionEqualLessFunc[E any](data []E, a, b, pivot int, less func(a, b E) bool) (newpivot int) { +func partitionEqualCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int) { data[a], data[pivot] = data[pivot], data[a] i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned for { - for i <= j && !less(data[a], data[i]) { + for i <= j && !(cmp(data[a], data[i]) < 0) { i++ } - for i <= j && less(data[a], data[j]) { + for i <= j && (cmp(data[a], data[j]) < 0) { j-- } if i > j { @@ -191,15 +191,15 @@ func partitionEqualLessFunc[E any](data []E, a, b, pivot int, less func(a, b E) return i } -// partialInsertionSortLessFunc partially sorts a slice, returns true if the slice is sorted at the end. -func partialInsertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) bool { +// partialInsertionSortCmpFunc partially sorts a slice, returns true if the slice is sorted at the end. +func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) bool { const ( maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted shortestShifting = 50 // don't shift any elements on short arrays ) i := a + 1 for j := 0; j < maxSteps; j++ { - for i < b && !less(data[i], data[i-1]) { + for i < b && !(cmp(data[i], data[i-1]) < 0) { i++ } @@ -216,7 +216,7 @@ func partialInsertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) b // Shift the smaller one to the left. if i-a >= 2 { for j := i - 1; j >= 1; j-- { - if !less(data[j], data[j-1]) { + if !(cmp(data[j], data[j-1]) < 0) { break } data[j], data[j-1] = data[j-1], data[j] @@ -225,7 +225,7 @@ func partialInsertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) b // Shift the greater one to the right. if b-i >= 2 { for j := i + 1; j < b; j++ { - if !less(data[j], data[j-1]) { + if !(cmp(data[j], data[j-1]) < 0) { break } data[j], data[j-1] = data[j-1], data[j] @@ -235,9 +235,9 @@ func partialInsertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) b return false } -// breakPatternsLessFunc scatters some elements around in an attempt to break some patterns +// breakPatternsCmpFunc scatters some elements around in an attempt to break some patterns // that might cause imbalanced partitions in quicksort. -func breakPatternsLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { +func breakPatternsCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { length := b - a if length >= 8 { random := xorshift(length) @@ -253,12 +253,12 @@ func breakPatternsLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { } } -// choosePivotLessFunc chooses a pivot in data[a:b]. +// choosePivotCmpFunc chooses a pivot in data[a:b]. // // [0,8): chooses a static pivot. // [8,shortestNinther): uses the simple median-of-three method. // [shortestNinther,∞): uses the Tukey ninther method. -func choosePivotLessFunc[E any](data []E, a, b int, less func(a, b E) bool) (pivot int, hint sortedHint) { +func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot int, hint sortedHint) { const ( shortestNinther = 50 maxSwaps = 4 * 3 @@ -276,12 +276,12 @@ func choosePivotLessFunc[E any](data []E, a, b int, less func(a, b E) bool) (piv if l >= 8 { if l >= shortestNinther { // Tukey ninther method, the idea came from Rust's implementation. - i = medianAdjacentLessFunc(data, i, &swaps, less) - j = medianAdjacentLessFunc(data, j, &swaps, less) - k = medianAdjacentLessFunc(data, k, &swaps, less) + i = medianAdjacentCmpFunc(data, i, &swaps, cmp) + j = medianAdjacentCmpFunc(data, j, &swaps, cmp) + k = medianAdjacentCmpFunc(data, k, &swaps, cmp) } // Find the median among i, j, k and stores it into j. - j = medianLessFunc(data, i, j, k, &swaps, less) + j = medianCmpFunc(data, i, j, k, &swaps, cmp) } switch swaps { @@ -294,29 +294,29 @@ func choosePivotLessFunc[E any](data []E, a, b int, less func(a, b E) bool) (piv } } -// order2LessFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a. -func order2LessFunc[E any](data []E, a, b int, swaps *int, less func(a, b E) bool) (int, int) { - if less(data[b], data[a]) { +// order2CmpFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a. +func order2CmpFunc[E any](data []E, a, b int, swaps *int, cmp func(a, b E) int) (int, int) { + if cmp(data[b], data[a]) < 0 { *swaps++ return b, a } return a, b } -// medianLessFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c. -func medianLessFunc[E any](data []E, a, b, c int, swaps *int, less func(a, b E) bool) int { - a, b = order2LessFunc(data, a, b, swaps, less) - b, c = order2LessFunc(data, b, c, swaps, less) - a, b = order2LessFunc(data, a, b, swaps, less) +// medianCmpFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c. +func medianCmpFunc[E any](data []E, a, b, c int, swaps *int, cmp func(a, b E) int) int { + a, b = order2CmpFunc(data, a, b, swaps, cmp) + b, c = order2CmpFunc(data, b, c, swaps, cmp) + a, b = order2CmpFunc(data, a, b, swaps, cmp) return b } -// medianAdjacentLessFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a. -func medianAdjacentLessFunc[E any](data []E, a int, swaps *int, less func(a, b E) bool) int { - return medianLessFunc(data, a-1, a, a+1, swaps, less) +// medianAdjacentCmpFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a. +func medianAdjacentCmpFunc[E any](data []E, a int, swaps *int, cmp func(a, b E) int) int { + return medianCmpFunc(data, a-1, a, a+1, swaps, cmp) } -func reverseRangeLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { +func reverseRangeCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { i := a j := b - 1 for i < j { @@ -326,37 +326,37 @@ func reverseRangeLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { } } -func swapRangeLessFunc[E any](data []E, a, b, n int, less func(a, b E) bool) { +func swapRangeCmpFunc[E any](data []E, a, b, n int, cmp func(a, b E) int) { for i := 0; i < n; i++ { data[a+i], data[b+i] = data[b+i], data[a+i] } } -func stableLessFunc[E any](data []E, n int, less func(a, b E) bool) { +func stableCmpFunc[E any](data []E, n int, cmp func(a, b E) int) { blockSize := 20 // must be > 0 a, b := 0, blockSize for b <= n { - insertionSortLessFunc(data, a, b, less) + insertionSortCmpFunc(data, a, b, cmp) a = b b += blockSize } - insertionSortLessFunc(data, a, n, less) + insertionSortCmpFunc(data, a, n, cmp) for blockSize < n { a, b = 0, 2*blockSize for b <= n { - symMergeLessFunc(data, a, a+blockSize, b, less) + symMergeCmpFunc(data, a, a+blockSize, b, cmp) a = b b += 2 * blockSize } if m := a + blockSize; m < n { - symMergeLessFunc(data, a, m, n, less) + symMergeCmpFunc(data, a, m, n, cmp) } blockSize *= 2 } } -// symMergeLessFunc merges the two sorted subsequences data[a:m] and data[m:b] using +// symMergeCmpFunc merges the two sorted subsequences data[a:m] and data[m:b] using // the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum // Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz // Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in @@ -375,7 +375,7 @@ func stableLessFunc[E any](data []E, n int, less func(a, b E) bool) { // symMerge assumes non-degenerate arguments: a < m && m < b. // Having the caller check this condition eliminates many leaf recursion calls, // which improves performance. -func symMergeLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { +func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { // Avoid unnecessary recursions of symMerge // by direct insertion of data[a] into data[m:b] // if data[a:m] only contains one element. @@ -387,7 +387,7 @@ func symMergeLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { j := b for i < j { h := int(uint(i+j) >> 1) - if less(data[h], data[a]) { + if cmp(data[h], data[a]) < 0 { i = h + 1 } else { j = h @@ -411,7 +411,7 @@ func symMergeLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { j := m for i < j { h := int(uint(i+j) >> 1) - if !less(data[m], data[h]) { + if !(cmp(data[m], data[h]) < 0) { i = h + 1 } else { j = h @@ -438,7 +438,7 @@ func symMergeLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { for start < r { c := int(uint(start+r) >> 1) - if !less(data[p-c], data[c]) { + if !(cmp(data[p-c], data[c]) < 0) { start = c + 1 } else { r = c @@ -447,33 +447,33 @@ func symMergeLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { end := n - start if start < m && m < end { - rotateLessFunc(data, start, m, end, less) + rotateCmpFunc(data, start, m, end, cmp) } if a < start && start < mid { - symMergeLessFunc(data, a, start, mid, less) + symMergeCmpFunc(data, a, start, mid, cmp) } if mid < end && end < b { - symMergeLessFunc(data, mid, end, b, less) + symMergeCmpFunc(data, mid, end, b, cmp) } } -// rotateLessFunc rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data: +// rotateCmpFunc rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data: // Data of the form 'x u v y' is changed to 'x v u y'. // rotate performs at most b-a many calls to data.Swap, // and it assumes non-degenerate arguments: a < m && m < b. -func rotateLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { +func rotateCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { i := m - a j := b - m for i != j { if i > j { - swapRangeLessFunc(data, m-i, m, j, less) + swapRangeCmpFunc(data, m-i, m, j, cmp) i -= j } else { - swapRangeLessFunc(data, m-i, m+j-i, i, less) + swapRangeCmpFunc(data, m-i, m+j-i, i, cmp) j -= i } } // i == j - swapRangeLessFunc(data, m-i, m, i, less) + swapRangeCmpFunc(data, m-i, m, i, cmp) } diff --git a/tools/vendor/golang.org/x/exp/slices/zsortordered.go b/tools/vendor/golang.org/x/exp/slices/zsortordered.go index efaa1c8b7..99b47c398 100644 --- a/tools/vendor/golang.org/x/exp/slices/zsortordered.go +++ b/tools/vendor/golang.org/x/exp/slices/zsortordered.go @@ -11,7 +11,7 @@ import "golang.org/x/exp/constraints" // insertionSortOrdered sorts data[a:b] using insertion sort. func insertionSortOrdered[E constraints.Ordered](data []E, a, b int) { for i := a + 1; i < b; i++ { - for j := i; j > a && (data[j] < data[j-1]); j-- { + for j := i; j > a && cmpLess(data[j], data[j-1]); j-- { data[j], data[j-1] = data[j-1], data[j] } } @@ -26,10 +26,10 @@ func siftDownOrdered[E constraints.Ordered](data []E, lo, hi, first int) { if child >= hi { break } - if child+1 < hi && (data[first+child] < data[first+child+1]) { + if child+1 < hi && cmpLess(data[first+child], data[first+child+1]) { child++ } - if !(data[first+root] < data[first+child]) { + if !cmpLess(data[first+root], data[first+child]) { return } data[first+root], data[first+child] = data[first+child], data[first+root] @@ -107,7 +107,7 @@ func pdqsortOrdered[E constraints.Ordered](data []E, a, b, limit int) { // Probably the slice contains many duplicate elements, partition the slice into // elements equal to and elements greater than the pivot. - if a > 0 && !(data[a-1] < data[pivot]) { + if a > 0 && !cmpLess(data[a-1], data[pivot]) { mid := partitionEqualOrdered(data, a, b, pivot) a = mid continue @@ -138,10 +138,10 @@ func partitionOrdered[E constraints.Ordered](data []E, a, b, pivot int) (newpivo data[a], data[pivot] = data[pivot], data[a] i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned - for i <= j && (data[i] < data[a]) { + for i <= j && cmpLess(data[i], data[a]) { i++ } - for i <= j && !(data[j] < data[a]) { + for i <= j && !cmpLess(data[j], data[a]) { j-- } if i > j { @@ -153,10 +153,10 @@ func partitionOrdered[E constraints.Ordered](data []E, a, b, pivot int) (newpivo j-- for { - for i <= j && (data[i] < data[a]) { + for i <= j && cmpLess(data[i], data[a]) { i++ } - for i <= j && !(data[j] < data[a]) { + for i <= j && !cmpLess(data[j], data[a]) { j-- } if i > j { @@ -177,10 +177,10 @@ func partitionEqualOrdered[E constraints.Ordered](data []E, a, b, pivot int) (ne i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned for { - for i <= j && !(data[a] < data[i]) { + for i <= j && !cmpLess(data[a], data[i]) { i++ } - for i <= j && (data[a] < data[j]) { + for i <= j && cmpLess(data[a], data[j]) { j-- } if i > j { @@ -201,7 +201,7 @@ func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b int) bool ) i := a + 1 for j := 0; j < maxSteps; j++ { - for i < b && !(data[i] < data[i-1]) { + for i < b && !cmpLess(data[i], data[i-1]) { i++ } @@ -218,7 +218,7 @@ func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b int) bool // Shift the smaller one to the left. if i-a >= 2 { for j := i - 1; j >= 1; j-- { - if !(data[j] < data[j-1]) { + if !cmpLess(data[j], data[j-1]) { break } data[j], data[j-1] = data[j-1], data[j] @@ -227,7 +227,7 @@ func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b int) bool // Shift the greater one to the right. if b-i >= 2 { for j := i + 1; j < b; j++ { - if !(data[j] < data[j-1]) { + if !cmpLess(data[j], data[j-1]) { break } data[j], data[j-1] = data[j-1], data[j] @@ -298,7 +298,7 @@ func choosePivotOrdered[E constraints.Ordered](data []E, a, b int) (pivot int, h // order2Ordered returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a. func order2Ordered[E constraints.Ordered](data []E, a, b int, swaps *int) (int, int) { - if data[b] < data[a] { + if cmpLess(data[b], data[a]) { *swaps++ return b, a } @@ -389,7 +389,7 @@ func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) { j := b for i < j { h := int(uint(i+j) >> 1) - if data[h] < data[a] { + if cmpLess(data[h], data[a]) { i = h + 1 } else { j = h @@ -413,7 +413,7 @@ func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) { j := m for i < j { h := int(uint(i+j) >> 1) - if !(data[m] < data[h]) { + if !cmpLess(data[m], data[h]) { i = h + 1 } else { j = h @@ -440,7 +440,7 @@ func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) { for start < r { c := int(uint(start+r) >> 1) - if !(data[p-c] < data[c]) { + if !cmpLess(data[p-c], data[c]) { start = c + 1 } else { r = c diff --git a/tools/vendor/golang.org/x/exp/typeparams/typeparams_go117.go b/tools/vendor/golang.org/x/exp/typeparams/typeparams_go117.go index efc33f10f..c1da79316 100644 --- a/tools/vendor/golang.org/x/exp/typeparams/typeparams_go117.go +++ b/tools/vendor/golang.org/x/exp/typeparams/typeparams_go117.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !go1.18 -// +build !go1.18 package typeparams diff --git a/tools/vendor/golang.org/x/exp/typeparams/typeparams_go118.go b/tools/vendor/golang.org/x/exp/typeparams/typeparams_go118.go index 1176104b2..0b35449d1 100644 --- a/tools/vendor/golang.org/x/exp/typeparams/typeparams_go118.go +++ b/tools/vendor/golang.org/x/exp/typeparams/typeparams_go118.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build go1.18 -// +build go1.18 package typeparams diff --git a/tools/vendor/golang.org/x/mod/LICENSE b/tools/vendor/golang.org/x/mod/LICENSE index 6a66aea5e..2a7cf70da 100644 --- a/tools/vendor/golang.org/x/mod/LICENSE +++ b/tools/vendor/golang.org/x/mod/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/tools/vendor/golang.org/x/mod/modfile/read.go b/tools/vendor/golang.org/x/mod/modfile/read.go index 5b5bb5e11..de1b98211 100644 --- a/tools/vendor/golang.org/x/mod/modfile/read.go +++ b/tools/vendor/golang.org/x/mod/modfile/read.go @@ -225,9 +225,10 @@ func (x *FileSyntax) Cleanup() { if ww == 0 { continue } - if ww == 1 { - // Collapse block into single line. - line := &Line{ + if ww == 1 && len(stmt.RParen.Comments.Before) == 0 { + // Collapse block into single line but keep the Line reference used by the + // parsed File structure. + *stmt.Line[0] = Line{ Comments: Comments{ Before: commentsAdd(stmt.Before, stmt.Line[0].Before), Suffix: commentsAdd(stmt.Line[0].Suffix, stmt.Suffix), @@ -235,7 +236,7 @@ func (x *FileSyntax) Cleanup() { }, Token: stringsAdd(stmt.Token, stmt.Line[0].Token), } - x.Stmt[w] = line + x.Stmt[w] = stmt.Line[0] w++ continue } diff --git a/tools/vendor/golang.org/x/mod/modfile/rule.go b/tools/vendor/golang.org/x/mod/modfile/rule.go index e0869fa38..3e4a1d0ab 100644 --- a/tools/vendor/golang.org/x/mod/modfile/rule.go +++ b/tools/vendor/golang.org/x/mod/modfile/rule.go @@ -38,10 +38,12 @@ type File struct { Module *Module Go *Go Toolchain *Toolchain + Godebug []*Godebug Require []*Require Exclude []*Exclude Replace []*Replace Retract []*Retract + Tool []*Tool Syntax *FileSyntax } @@ -65,6 +67,13 @@ type Toolchain struct { Syntax *Line } +// A Godebug is a single godebug key=value statement. +type Godebug struct { + Key string + Value string + Syntax *Line +} + // An Exclude is a single exclude statement. type Exclude struct { Mod module.Version @@ -85,6 +94,12 @@ type Retract struct { Syntax *Line } +// A Tool is a single tool statement. +type Tool struct { + Path string + Syntax *Line +} + // A VersionInterval represents a range of versions with upper and lower bounds. // Intervals are closed: both bounds are included. When Low is equal to High, // the interval may refer to a single version ('v1.2.3') or an interval @@ -289,7 +304,7 @@ func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (parse }) } continue - case "module", "require", "exclude", "replace", "retract": + case "module", "godebug", "require", "exclude", "replace", "retract", "tool": for _, l := range x.Line { f.add(&errs, x, l, x.Token[0], l.Token, fix, strict) } @@ -308,6 +323,9 @@ var laxGoVersionRE = lazyregexp.New(`^v?(([1-9][0-9]*)\.(0|[1-9][0-9]*))([^0-9]. // Toolchains must be named beginning with `go1`, // like "go1.20.3" or "go1.20.3-gccgo". As a special case, "default" is also permitted. +// Note that this regexp is a much looser condition than go/version.IsValid, +// for forward compatibility. +// (This code has to be work to identify new toolchains even if we tweak the syntax in the future.) var ToolchainRE = lazyregexp.New(`^default$|^go1($|\.)`) func (f *File) add(errs *ErrorList, block *LineBlock, line *Line, verb string, args []string, fix VersionFixer, strict bool) { @@ -383,8 +401,8 @@ func (f *File) add(errs *ErrorList, block *LineBlock, line *Line, verb string, a if len(args) != 1 { errorf("toolchain directive expects exactly one argument") return - } else if strict && !ToolchainRE.MatchString(args[0]) { - errorf("invalid toolchain version '%s': must match format go1.23.0 or local", args[0]) + } else if !ToolchainRE.MatchString(args[0]) { + errorf("invalid toolchain version '%s': must match format go1.23.0 or default", args[0]) return } f.Toolchain = &Toolchain{Syntax: line} @@ -411,6 +429,22 @@ func (f *File) add(errs *ErrorList, block *LineBlock, line *Line, verb string, a } f.Module.Mod = module.Version{Path: s} + case "godebug": + if len(args) != 1 || strings.ContainsAny(args[0], "\"`',") { + errorf("usage: godebug key=value") + return + } + key, value, ok := strings.Cut(args[0], "=") + if !ok { + errorf("usage: godebug key=value") + return + } + f.Godebug = append(f.Godebug, &Godebug{ + Key: key, + Value: value, + Syntax: line, + }) + case "require", "exclude": if len(args) != 2 { errorf("usage: %s module/path v1.2.3", verb) @@ -482,6 +516,21 @@ func (f *File) add(errs *ErrorList, block *LineBlock, line *Line, verb string, a Syntax: line, } f.Retract = append(f.Retract, retract) + + case "tool": + if len(args) != 1 { + errorf("tool directive expects exactly one argument") + return + } + s, err := parseString(&args[0]) + if err != nil { + errorf("invalid quoted string: %v", err) + return + } + f.Tool = append(f.Tool, &Tool{ + Path: s, + Syntax: line, + }) } } @@ -542,7 +591,7 @@ func parseReplace(filename string, line *Line, verb string, args []string, fix V if strings.Contains(ns, "@") { return nil, errorf("replacement module must match format 'path version', not 'path@version'") } - return nil, errorf("replacement module without version must be directory path (rooted or starting with ./ or ../)") + return nil, errorf("replacement module without version must be directory path (rooted or starting with . or ..)") } if filepath.Separator == '/' && strings.Contains(ns, `\`) { return nil, errorf("replacement directory appears to be Windows path (on a non-windows system)") @@ -555,7 +604,6 @@ func parseReplace(filename string, line *Line, verb string, args []string, fix V } if IsDirectoryPath(ns) { return nil, errorf("replacement module directory path %q cannot have version", ns) - } } return &Replace{ @@ -631,7 +679,7 @@ func (f *WorkFile) add(errs *ErrorList, line *Line, verb string, args []string, errorf("go directive expects exactly one argument") return } else if !GoVersionRE.MatchString(args[0]) { - errorf("invalid go version '%s': must match format 1.23", args[0]) + errorf("invalid go version '%s': must match format 1.23.0", args[0]) return } @@ -647,13 +695,29 @@ func (f *WorkFile) add(errs *ErrorList, line *Line, verb string, args []string, errorf("toolchain directive expects exactly one argument") return } else if !ToolchainRE.MatchString(args[0]) { - errorf("invalid toolchain version '%s': must match format go1.23 or local", args[0]) + errorf("invalid toolchain version '%s': must match format go1.23.0 or default", args[0]) return } f.Toolchain = &Toolchain{Syntax: line} f.Toolchain.Name = args[0] + case "godebug": + if len(args) != 1 || strings.ContainsAny(args[0], "\"`',") { + errorf("usage: godebug key=value") + return + } + key, value, ok := strings.Cut(args[0], "=") + if !ok { + errorf("usage: godebug key=value") + return + } + f.Godebug = append(f.Godebug, &Godebug{ + Key: key, + Value: value, + Syntax: line, + }) + case "use": if len(args) != 1 { errorf("usage: %s local/dir", verb) @@ -679,14 +743,15 @@ func (f *WorkFile) add(errs *ErrorList, line *Line, verb string, args []string, } } -// IsDirectoryPath reports whether the given path should be interpreted -// as a directory path. Just like on the go command line, relative paths +// IsDirectoryPath reports whether the given path should be interpreted as a directory path. +// Just like on the go command line, relative paths starting with a '.' or '..' path component // and rooted paths are directory paths; the rest are module paths. func IsDirectoryPath(ns string) bool { // Because go.mod files can move from one system to another, // we check all known path syntaxes, both Unix and Windows. - return strings.HasPrefix(ns, "./") || strings.HasPrefix(ns, "../") || strings.HasPrefix(ns, "/") || - strings.HasPrefix(ns, `.\`) || strings.HasPrefix(ns, `..\`) || strings.HasPrefix(ns, `\`) || + return ns == "." || strings.HasPrefix(ns, "./") || strings.HasPrefix(ns, `.\`) || + ns == ".." || strings.HasPrefix(ns, "../") || strings.HasPrefix(ns, `..\`) || + strings.HasPrefix(ns, "/") || strings.HasPrefix(ns, `\`) || len(ns) >= 2 && ('A' <= ns[0] && ns[0] <= 'Z' || 'a' <= ns[0] && ns[0] <= 'z') && ns[1] == ':' } @@ -928,6 +993,15 @@ func (f *File) Format() ([]byte, error) { // Cleanup cleans out all the cleared entries. func (f *File) Cleanup() { w := 0 + for _, g := range f.Godebug { + if g.Key != "" { + f.Godebug[w] = g + w++ + } + } + f.Godebug = f.Godebug[:w] + + w = 0 for _, r := range f.Require { if r.Mod.Path != "" { f.Require[w] = r @@ -974,6 +1048,8 @@ func (f *File) AddGoStmt(version string) error { var hint Expr if f.Module != nil && f.Module.Syntax != nil { hint = f.Module.Syntax + } else if f.Syntax == nil { + f.Syntax = new(FileSyntax) } f.Go = &Go{ Version: version, @@ -1024,6 +1100,45 @@ func (f *File) AddToolchainStmt(name string) error { return nil } +// AddGodebug sets the first godebug line for key to value, +// preserving any existing comments for that line and removing all +// other godebug lines for key. +// +// If no line currently exists for key, AddGodebug adds a new line +// at the end of the last godebug block. +func (f *File) AddGodebug(key, value string) error { + need := true + for _, g := range f.Godebug { + if g.Key == key { + if need { + g.Value = value + f.Syntax.updateLine(g.Syntax, "godebug", key+"="+value) + need = false + } else { + g.Syntax.markRemoved() + *g = Godebug{} + } + } + } + + if need { + f.addNewGodebug(key, value) + } + return nil +} + +// addNewGodebug adds a new godebug key=value line at the end +// of the last godebug block, regardless of any existing godebug lines for key. +func (f *File) addNewGodebug(key, value string) { + line := f.Syntax.addLine(nil, "godebug", key+"="+value) + g := &Godebug{ + Key: key, + Value: value, + Syntax: line, + } + f.Godebug = append(f.Godebug, g) +} + // AddRequire sets the first require line for path to version vers, // preserving any existing comments for that line and removing all // other lines for path. @@ -1331,6 +1446,16 @@ func (f *File) SetRequireSeparateIndirect(req []*Require) { f.SortBlocks() } +func (f *File) DropGodebug(key string) error { + for _, g := range f.Godebug { + if g.Key == key { + g.Syntax.markRemoved() + *g = Godebug{} + } + } + return nil +} + func (f *File) DropRequire(path string) error { for _, r := range f.Require { if r.Mod.Path == path { @@ -1464,6 +1589,36 @@ func (f *File) DropRetract(vi VersionInterval) error { return nil } +// AddTool adds a new tool directive with the given path. +// It does nothing if the tool line already exists. +func (f *File) AddTool(path string) error { + for _, t := range f.Tool { + if t.Path == path { + return nil + } + } + + f.Tool = append(f.Tool, &Tool{ + Path: path, + Syntax: f.Syntax.addLine(nil, "tool", path), + }) + + f.SortBlocks() + return nil +} + +// RemoveTool removes a tool directive with the given path. +// It does nothing if no such tool directive exists. +func (f *File) DropTool(path string) error { + for _, t := range f.Tool { + if t.Path == path { + t.Syntax.markRemoved() + *t = Tool{} + } + } + return nil +} + func (f *File) SortBlocks() { f.removeDups() // otherwise sorting is unsafe @@ -1490,9 +1645,9 @@ func (f *File) SortBlocks() { } } -// removeDups removes duplicate exclude and replace directives. +// removeDups removes duplicate exclude, replace and tool directives. // -// Earlier exclude directives take priority. +// Earlier exclude and tool directives take priority. // // Later replace directives take priority. // @@ -1502,10 +1657,10 @@ func (f *File) SortBlocks() { // retract directives are not de-duplicated since comments are // meaningful, and versions may be retracted multiple times. func (f *File) removeDups() { - removeDups(f.Syntax, &f.Exclude, &f.Replace) + removeDups(f.Syntax, &f.Exclude, &f.Replace, &f.Tool) } -func removeDups(syntax *FileSyntax, exclude *[]*Exclude, replace *[]*Replace) { +func removeDups(syntax *FileSyntax, exclude *[]*Exclude, replace *[]*Replace, tool *[]*Tool) { kill := make(map[*Line]bool) // Remove duplicate excludes. @@ -1546,6 +1701,24 @@ func removeDups(syntax *FileSyntax, exclude *[]*Exclude, replace *[]*Replace) { } *replace = repl + if tool != nil { + haveTool := make(map[string]bool) + for _, t := range *tool { + if haveTool[t.Path] { + kill[t.Syntax] = true + continue + } + haveTool[t.Path] = true + } + var newTool []*Tool + for _, t := range *tool { + if !kill[t.Syntax] { + newTool = append(newTool, t) + } + } + *tool = newTool + } + // Duplicate require and retract directives are not removed. // Drop killed statements from the syntax tree. diff --git a/tools/vendor/golang.org/x/mod/modfile/work.go b/tools/vendor/golang.org/x/mod/modfile/work.go index d7b99376e..5387d0c26 100644 --- a/tools/vendor/golang.org/x/mod/modfile/work.go +++ b/tools/vendor/golang.org/x/mod/modfile/work.go @@ -14,6 +14,7 @@ import ( type WorkFile struct { Go *Go Toolchain *Toolchain + Godebug []*Godebug Use []*Use Replace []*Replace @@ -68,7 +69,7 @@ func ParseWork(file string, data []byte, fix VersionFixer) (*WorkFile, error) { Err: fmt.Errorf("unknown block type: %s", strings.Join(x.Token, " ")), }) continue - case "use", "replace": + case "godebug", "use", "replace": for _, l := range x.Line { f.add(&errs, l, x.Token[0], l.Token, fix) } @@ -184,6 +185,55 @@ func (f *WorkFile) DropToolchainStmt() { } } +// AddGodebug sets the first godebug line for key to value, +// preserving any existing comments for that line and removing all +// other godebug lines for key. +// +// If no line currently exists for key, AddGodebug adds a new line +// at the end of the last godebug block. +func (f *WorkFile) AddGodebug(key, value string) error { + need := true + for _, g := range f.Godebug { + if g.Key == key { + if need { + g.Value = value + f.Syntax.updateLine(g.Syntax, "godebug", key+"="+value) + need = false + } else { + g.Syntax.markRemoved() + *g = Godebug{} + } + } + } + + if need { + f.addNewGodebug(key, value) + } + return nil +} + +// addNewGodebug adds a new godebug key=value line at the end +// of the last godebug block, regardless of any existing godebug lines for key. +func (f *WorkFile) addNewGodebug(key, value string) { + line := f.Syntax.addLine(nil, "godebug", key+"="+value) + g := &Godebug{ + Key: key, + Value: value, + Syntax: line, + } + f.Godebug = append(f.Godebug, g) +} + +func (f *WorkFile) DropGodebug(key string) error { + for _, g := range f.Godebug { + if g.Key == key { + g.Syntax.markRemoved() + *g = Godebug{} + } + } + return nil +} + func (f *WorkFile) AddUse(diskPath, modulePath string) error { need := true for _, d := range f.Use { @@ -281,5 +331,5 @@ func (f *WorkFile) SortBlocks() { // retract directives are not de-duplicated since comments are // meaningful, and versions may be retracted multiple times. func (f *WorkFile) removeDups() { - removeDups(f.Syntax, nil, &f.Replace) + removeDups(f.Syntax, nil, &f.Replace, nil) } diff --git a/tools/vendor/golang.org/x/sync/LICENSE b/tools/vendor/golang.org/x/sync/LICENSE index 6a66aea5e..2a7cf70da 100644 --- a/tools/vendor/golang.org/x/sync/LICENSE +++ b/tools/vendor/golang.org/x/sync/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/tools/vendor/golang.org/x/sync/errgroup/errgroup.go b/tools/vendor/golang.org/x/sync/errgroup/errgroup.go index b18efb743..948a3ee63 100644 --- a/tools/vendor/golang.org/x/sync/errgroup/errgroup.go +++ b/tools/vendor/golang.org/x/sync/errgroup/errgroup.go @@ -4,6 +4,9 @@ // Package errgroup provides synchronization, error propagation, and Context // cancelation for groups of goroutines working on subtasks of a common task. +// +// [errgroup.Group] is related to [sync.WaitGroup] but adds handling of tasks +// returning errors. package errgroup import ( diff --git a/tools/vendor/golang.org/x/sync/errgroup/go120.go b/tools/vendor/golang.org/x/sync/errgroup/go120.go index 7d419d376..f93c740b6 100644 --- a/tools/vendor/golang.org/x/sync/errgroup/go120.go +++ b/tools/vendor/golang.org/x/sync/errgroup/go120.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build go1.20 -// +build go1.20 package errgroup diff --git a/tools/vendor/golang.org/x/sync/errgroup/pre_go120.go b/tools/vendor/golang.org/x/sync/errgroup/pre_go120.go index 1795c18ac..88ce33434 100644 --- a/tools/vendor/golang.org/x/sync/errgroup/pre_go120.go +++ b/tools/vendor/golang.org/x/sync/errgroup/pre_go120.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build !go1.20 -// +build !go1.20 package errgroup diff --git a/tools/vendor/golang.org/x/sync/semaphore/semaphore.go b/tools/vendor/golang.org/x/sync/semaphore/semaphore.go index 30f632c57..b618162aa 100644 --- a/tools/vendor/golang.org/x/sync/semaphore/semaphore.go +++ b/tools/vendor/golang.org/x/sync/semaphore/semaphore.go @@ -35,11 +35,25 @@ type Weighted struct { // Acquire acquires the semaphore with a weight of n, blocking until resources // are available or ctx is done. On success, returns nil. On failure, returns // ctx.Err() and leaves the semaphore unchanged. -// -// If ctx is already done, Acquire may still succeed without blocking. func (s *Weighted) Acquire(ctx context.Context, n int64) error { + done := ctx.Done() + s.mu.Lock() + select { + case <-done: + // ctx becoming done has "happened before" acquiring the semaphore, + // whether it became done before the call began or while we were + // waiting for the mutex. We prefer to fail even if we could acquire + // the mutex without blocking. + s.mu.Unlock() + return ctx.Err() + default: + } if s.size-s.cur >= n && s.waiters.Len() == 0 { + // Since we hold s.mu and haven't synchronized since checking done, if + // ctx becomes done before we return here, it becoming done must have + // "happened concurrently" with this call - it cannot "happen before" + // we return in this branch. So, we're ok to always acquire here. s.cur += n s.mu.Unlock() return nil @@ -48,7 +62,7 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error { if n > s.size { // Don't make other Acquire calls block on one that's doomed to fail. s.mu.Unlock() - <-ctx.Done() + <-done return ctx.Err() } @@ -58,14 +72,14 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error { s.mu.Unlock() select { - case <-ctx.Done(): - err := ctx.Err() + case <-done: s.mu.Lock() select { case <-ready: - // Acquired the semaphore after we were canceled. Rather than trying to - // fix up the queue, just pretend we didn't notice the cancelation. - err = nil + // Acquired the semaphore after we were canceled. + // Pretend we didn't and put the tokens back. + s.cur -= n + s.notifyWaiters() default: isFront := s.waiters.Front() == elem s.waiters.Remove(elem) @@ -75,9 +89,19 @@ func (s *Weighted) Acquire(ctx context.Context, n int64) error { } } s.mu.Unlock() - return err + return ctx.Err() case <-ready: + // Acquired the semaphore. Check that ctx isn't already done. + // We check the done channel instead of calling ctx.Err because we + // already have the channel, and ctx.Err is O(n) with the nesting + // depth of ctx. + select { + case <-done: + s.Release(n) + return ctx.Err() + default: + } return nil } } diff --git a/tools/vendor/golang.org/x/sys/LICENSE b/tools/vendor/golang.org/x/sys/LICENSE index 6a66aea5e..2a7cf70da 100644 --- a/tools/vendor/golang.org/x/sys/LICENSE +++ b/tools/vendor/golang.org/x/sys/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/tools/vendor/golang.org/x/sys/execabs/execabs.go b/tools/vendor/golang.org/x/sys/execabs/execabs.go deleted file mode 100644 index 3bf40fdfe..000000000 --- a/tools/vendor/golang.org/x/sys/execabs/execabs.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package execabs is a drop-in replacement for os/exec -// that requires PATH lookups to find absolute paths. -// That is, execabs.Command("cmd") runs the same PATH lookup -// as exec.Command("cmd"), but if the result is a path -// which is relative, the Run and Start methods will report -// an error instead of running the executable. -// -// See https://blog.golang.org/path-security for more information -// about when it may be necessary or appropriate to use this package. -package execabs - -import ( - "context" - "fmt" - "os/exec" - "path/filepath" - "reflect" - "unsafe" -) - -// ErrNotFound is the error resulting if a path search failed to find an executable file. -// It is an alias for exec.ErrNotFound. -var ErrNotFound = exec.ErrNotFound - -// Cmd represents an external command being prepared or run. -// It is an alias for exec.Cmd. -type Cmd = exec.Cmd - -// Error is returned by LookPath when it fails to classify a file as an executable. -// It is an alias for exec.Error. -type Error = exec.Error - -// An ExitError reports an unsuccessful exit by a command. -// It is an alias for exec.ExitError. -type ExitError = exec.ExitError - -func relError(file, path string) error { - return fmt.Errorf("%s resolves to executable in current directory (.%c%s)", file, filepath.Separator, path) -} - -// LookPath searches for an executable named file in the directories -// named by the PATH environment variable. If file contains a slash, -// it is tried directly and the PATH is not consulted. The result will be -// an absolute path. -// -// LookPath differs from exec.LookPath in its handling of PATH lookups, -// which are used for file names without slashes. If exec.LookPath's -// PATH lookup would have returned an executable from the current directory, -// LookPath instead returns an error. -func LookPath(file string) (string, error) { - path, err := exec.LookPath(file) - if err != nil && !isGo119ErrDot(err) { - return "", err - } - if filepath.Base(file) == file && !filepath.IsAbs(path) { - return "", relError(file, path) - } - return path, nil -} - -func fixCmd(name string, cmd *exec.Cmd) { - if filepath.Base(name) == name && !filepath.IsAbs(cmd.Path) && !isGo119ErrFieldSet(cmd) { - // exec.Command was called with a bare binary name and - // exec.LookPath returned a path which is not absolute. - // Set cmd.lookPathErr and clear cmd.Path so that it - // cannot be run. - lookPathErr := (*error)(unsafe.Pointer(reflect.ValueOf(cmd).Elem().FieldByName("lookPathErr").Addr().Pointer())) - if *lookPathErr == nil { - *lookPathErr = relError(name, cmd.Path) - } - cmd.Path = "" - } -} - -// CommandContext is like Command but includes a context. -// -// The provided context is used to kill the process (by calling os.Process.Kill) -// if the context becomes done before the command completes on its own. -func CommandContext(ctx context.Context, name string, arg ...string) *exec.Cmd { - cmd := exec.CommandContext(ctx, name, arg...) - fixCmd(name, cmd) - return cmd - -} - -// Command returns the Cmd struct to execute the named program with the given arguments. -// See exec.Command for most details. -// -// Command differs from exec.Command in its handling of PATH lookups, -// which are used when the program name contains no slashes. -// If exec.Command would have returned an exec.Cmd configured to run an -// executable from the current directory, Command instead -// returns an exec.Cmd that will return an error from Start or Run. -func Command(name string, arg ...string) *exec.Cmd { - cmd := exec.Command(name, arg...) - fixCmd(name, cmd) - return cmd -} diff --git a/tools/vendor/golang.org/x/sys/execabs/execabs_go118.go b/tools/vendor/golang.org/x/sys/execabs/execabs_go118.go deleted file mode 100644 index 2000064a8..000000000 --- a/tools/vendor/golang.org/x/sys/execabs/execabs_go118.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.19 -// +build !go1.19 - -package execabs - -import "os/exec" - -func isGo119ErrDot(err error) bool { - return false -} - -func isGo119ErrFieldSet(cmd *exec.Cmd) bool { - return false -} diff --git a/tools/vendor/golang.org/x/sys/execabs/execabs_go119.go b/tools/vendor/golang.org/x/sys/execabs/execabs_go119.go deleted file mode 100644 index f364b3418..000000000 --- a/tools/vendor/golang.org/x/sys/execabs/execabs_go119.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.19 -// +build go1.19 - -package execabs - -import ( - "errors" - "os/exec" -) - -func isGo119ErrDot(err error) bool { - return errors.Is(err, exec.ErrDot) -} - -func isGo119ErrFieldSet(cmd *exec.Cmd) bool { - return cmd.Err != nil -} diff --git a/tools/vendor/golang.org/x/sys/unix/aliases.go b/tools/vendor/golang.org/x/sys/unix/aliases.go index abc89c104..b0e419857 100644 --- a/tools/vendor/golang.org/x/sys/unix/aliases.go +++ b/tools/vendor/golang.org/x/sys/unix/aliases.go @@ -2,9 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos) && go1.9 -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos -// +build go1.9 +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s b/tools/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s index db9171c2e..269e173ca 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_aix_ppc64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_bsd_386.s b/tools/vendor/golang.org/x/sys/unix/asm_bsd_386.s index e0fcd9b3d..a4fcef0e0 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_bsd_386.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_bsd_386.s @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build (freebsd || netbsd || openbsd) && gc -// +build freebsd netbsd openbsd -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_bsd_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_bsd_amd64.s index 2b99c349a..1e63615c5 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_bsd_amd64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_bsd_amd64.s @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build (darwin || dragonfly || freebsd || netbsd || openbsd) && gc -// +build darwin dragonfly freebsd netbsd openbsd -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm.s b/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm.s index d702d4adc..6496c3100 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm.s @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build (freebsd || netbsd || openbsd) && gc -// +build freebsd netbsd openbsd -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm64.s b/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm64.s index fe36a7391..4fd1f54da 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_bsd_arm64.s @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build (darwin || freebsd || netbsd || openbsd) && gc -// +build darwin freebsd netbsd openbsd -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s b/tools/vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s index e5b9a8489..42f7eb9e4 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build (darwin || freebsd || netbsd || openbsd) && gc -// +build darwin freebsd netbsd openbsd -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s b/tools/vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s index d560019ea..f8902667e 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build (darwin || freebsd || netbsd || openbsd) && gc -// +build darwin freebsd netbsd openbsd -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_386.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_386.s index 8fd101d07..3b4734870 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_386.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_386.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_amd64.s index 7ed38e43c..67e29f317 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_amd64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_amd64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_arm.s index 8ef1d5140..d6ae269ce 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_arm.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm64.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_arm64.s index 98ae02760..01e5e253c 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_arm64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_arm64.s @@ -3,9 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && arm64 && gc -// +build linux -// +build arm64 -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_loong64.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_loong64.s index 565357288..2abf12f6e 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_loong64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_loong64.s @@ -3,9 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && loong64 && gc -// +build linux -// +build loong64 -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s index 21231d2ce..f84bae712 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s @@ -3,9 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (mips64 || mips64le) && gc -// +build linux -// +build mips64 mips64le -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s index 6783b26c6..f08f62807 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s @@ -3,9 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (mips || mipsle) && gc -// +build linux -// +build mips mipsle -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s index 19d498934..bdfc024d2 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s @@ -3,9 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (ppc64 || ppc64le) && gc -// +build linux -// +build ppc64 ppc64le -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s index e42eb81d5..2e8c99612 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_riscv64.s @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build riscv64 && gc -// +build riscv64 -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_linux_s390x.s b/tools/vendor/golang.org/x/sys/unix/asm_linux_s390x.s index c46aab339..2c394b11e 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_linux_s390x.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_linux_s390x.s @@ -3,9 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && s390x && gc -// +build linux -// +build s390x -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s b/tools/vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s index 5e7a1169c..fab586a2c 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s b/tools/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s index f8c5394c1..f949ec547 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_solaris_amd64.s @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gc -// +build gc #include "textflag.h" diff --git a/tools/vendor/golang.org/x/sys/unix/asm_zos_s390x.s b/tools/vendor/golang.org/x/sys/unix/asm_zos_s390x.s index 3b54e1858..813dfad7d 100644 --- a/tools/vendor/golang.org/x/sys/unix/asm_zos_s390x.s +++ b/tools/vendor/golang.org/x/sys/unix/asm_zos_s390x.s @@ -3,18 +3,17 @@ // license that can be found in the LICENSE file. //go:build zos && s390x && gc -// +build zos -// +build s390x -// +build gc #include "textflag.h" #define PSALAA 1208(R0) #define GTAB64(x) 80(x) #define LCA64(x) 88(x) +#define SAVSTACK_ASYNC(x) 336(x) // in the LCA #define CAA(x) 8(x) -#define EDCHPXV(x) 1016(x) // in the CAA -#define SAVSTACK_ASYNC(x) 336(x) // in the LCA +#define CEECAATHDID(x) 976(x) // in the CAA +#define EDCHPXV(x) 1016(x) // in the CAA +#define GOCB(x) 1104(x) // in the CAA // SS_*, where x=SAVSTACK_ASYNC #define SS_LE(x) 0(x) @@ -22,405 +21,362 @@ #define SS_ERRNO(x) 16(x) #define SS_ERRNOJR(x) 20(x) -#define LE_CALL BYTE $0x0D; BYTE $0x76; // BL R7, R6 +// Function Descriptor Offsets +#define __errno 0x156*16 +#define __err2ad 0x16C*16 -TEXT ·clearErrno(SB),NOSPLIT,$0-0 - BL addrerrno<>(SB) - MOVD $0, 0(R3) +// Call Instructions +#define LE_CALL BYTE $0x0D; BYTE $0x76 // BL R7, R6 +#define SVC_LOAD BYTE $0x0A; BYTE $0x08 // SVC 08 LOAD +#define SVC_DELETE BYTE $0x0A; BYTE $0x09 // SVC 09 DELETE + +DATA zosLibVec<>(SB)/8, $0 +GLOBL zosLibVec<>(SB), NOPTR, $8 + +TEXT ·initZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD CAA(R8), R8 + MOVD EDCHPXV(R8), R8 + MOVD R8, zosLibVec<>(SB) + RET + +TEXT ·GetZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 + MOVD zosLibVec<>(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·clearErrno(SB), NOSPLIT, $0-0 + BL addrerrno<>(SB) + MOVD $0, 0(R3) RET // Returns the address of errno in R3. -TEXT addrerrno<>(SB),NOSPLIT|NOFRAME,$0-0 +TEXT addrerrno<>(SB), NOSPLIT|NOFRAME, $0-0 // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 // Get __errno FuncDesc. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - ADD $(0x156*16), R9 - LMG 0(R9), R5, R6 + MOVD CAA(R8), R9 + MOVD EDCHPXV(R9), R9 + ADD $(__errno), R9 + LMG 0(R9), R5, R6 // Switch to saved LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) + MOVD SAVSTACK_ASYNC(R8), R9 + MOVD 0(R9), R4 + MOVD $0, 0(R9) // Call __errno function. LE_CALL NOPH // Switch back to Go stack. - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. + XOR R0, R0 // Restore R0 to $0. + MOVD R4, 0(R9) // Save stack pointer. RET -TEXT ·syscall_syscall(SB),NOSPLIT,$0-56 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 +// func svcCall(fnptr unsafe.Pointer, argv *unsafe.Pointer, dsa *uint64) +TEXT ·svcCall(SB), NOSPLIT, $0 + BL runtime·save_g(SB) // Save g and stack pointer + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD SAVSTACK_ASYNC(R8), R9 + MOVD R15, 0(R9) - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 + MOVD argv+8(FP), R1 // Move function arguments into registers + MOVD dsa+16(FP), g + MOVD fnptr+0(FP), R15 - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 + BYTE $0x0D // Branch to function + BYTE $0xEF - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) + BL runtime·load_g(SB) // Restore g and stack pointer + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD SAVSTACK_ASYNC(R8), R9 + MOVD 0(R9), R15 - // Call function. - LE_CALL - NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+32(FP) - MOVD R0, r2+40(FP) - MOVD R0, err+48(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) -done: - BL runtime·exitsyscall(SB) RET -TEXT ·syscall_rawsyscall(SB),NOSPLIT,$0-56 - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 +// func svcLoad(name *byte) unsafe.Pointer +TEXT ·svcLoad(SB), NOSPLIT, $0 + MOVD R15, R2 // Save go stack pointer + MOVD name+0(FP), R0 // Move SVC args into registers + MOVD $0x80000000, R1 + MOVD $0, R15 + SVC_LOAD + MOVW R15, R3 // Save return code from SVC + MOVD R2, R15 // Restore go stack pointer + CMP R3, $0 // Check SVC return code + BNE error + + MOVD $-2, R3 // Reset last bit of entry point to zero + AND R0, R3 + MOVD R3, ret+8(FP) // Return entry point returned by SVC + CMP R0, R3 // Check if last bit of entry point was set + BNE done + + MOVD R15, R2 // Save go stack pointer + MOVD $0, R15 // Move SVC args into registers (entry point still in r0 from SVC 08) + SVC_DELETE + MOVD R2, R15 // Restore go stack pointer - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) +error: + MOVD $0, ret+8(FP) // Return 0 on failure - // Call function. - LE_CALL - NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+32(FP) - MOVD R0, r2+40(FP) - MOVD R0, err+48(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) done: + XOR R0, R0 // Reset r0 to 0 RET -TEXT ·syscall_syscall6(SB),NOSPLIT,$0-80 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 +// func svcUnload(name *byte, fnptr unsafe.Pointer) int64 +TEXT ·svcUnload(SB), NOSPLIT, $0 + MOVD R15, R2 // Save go stack pointer + MOVD name+0(FP), R0 // Move SVC args into registers + MOVD fnptr+8(FP), R15 + SVC_DELETE + XOR R0, R0 // Reset r0 to 0 + MOVD R15, R1 // Save SVC return code + MOVD R2, R15 // Restore go stack pointer + MOVD R1, ret+16(FP) // Return SVC return code + RET +// func gettid() uint64 +TEXT ·gettid(SB), NOSPLIT, $0 // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 + // Get CEECAATHDID + MOVD CAA(R8), R9 + MOVD CEECAATHDID(R9), R9 + MOVD R9, ret+0(FP) - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - - // Call function. - LE_CALL - NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+56(FP) - MOVD R0, r2+64(FP) - MOVD R0, err+72(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+72(FP) -done: - BL runtime·exitsyscall(SB) RET -TEXT ·syscall_rawsyscall6(SB),NOSPLIT,$0-80 - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 +// +// Call LE function, if the return is -1 +// errno and errno2 is retrieved +// +TEXT ·CallLeFuncWithErr(SB), NOSPLIT, $0 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD CAA(R8), R9 + MOVD g, GOCB(R9) // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - - // Call function. - LE_CALL + MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address + MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer + + MOVD parms_base+8(FP), R7 // R7 -> argument array + MOVD parms_len+16(FP), R8 // R8 number of arguments + + // arg 1 ---> R1 + CMP R8, $0 + BEQ docall + SUB $1, R8 + MOVD 0(R7), R1 + + // arg 2 ---> R2 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R2 + + // arg 3 --> R3 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R3 + + CMP R8, $0 + BEQ docall + MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument + +repeat: + ADD $8, R7 + MOVD 0(R7), R0 // advance arg pointer by 8 byte + ADD $8, R6 // advance LE argument address by 8 byte + MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame + SUB $1, R8 + CMP R8, $0 + BNE repeat + +docall: + MOVD funcdesc+0(FP), R8 // R8-> function descriptor + LMG 0(R8), R5, R6 + MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC + LE_CALL // balr R7, R6 (return #1) + NOPH + MOVD R3, ret+32(FP) + CMP R3, $-1 // compare result to -1 + BNE done + + // retrieve errno and errno2 + MOVD zosLibVec<>(SB), R8 + ADD $(__errno), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __errno (return #3) NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+56(FP) - MOVD R0, r2+64(FP) - MOVD R0, err+72(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL ·rrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+72(FP) + MOVWZ 0(R3), R3 + MOVD R3, err+48(FP) + MOVD zosLibVec<>(SB), R8 + ADD $(__err2ad), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __err2ad (return #2) + NOPH + MOVW (R3), R2 // retrieve errno2 + MOVD R2, errno2+40(FP) // store in return area + done: + MOVD R4, 0(R9) // Save stack pointer. RET -TEXT ·syscall_syscall9(SB),NOSPLIT,$0 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 +// +// Call LE function, if the return is 0 +// errno and errno2 is retrieved +// +TEXT ·CallLeFuncWithPtrReturn(SB), NOSPLIT, $0 + MOVW PSALAA, R8 + MOVD LCA64(R8), R8 + MOVD CAA(R8), R9 + MOVD g, GOCB(R9) // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - MOVD a7+56(FP), R12 - MOVD R12, (2176+48)(R4) - MOVD a8+64(FP), R12 - MOVD R12, (2176+56)(R4) - MOVD a9+72(FP), R12 - MOVD R12, (2176+64)(R4) - - // Call function. - LE_CALL + MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address + MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer + + MOVD parms_base+8(FP), R7 // R7 -> argument array + MOVD parms_len+16(FP), R8 // R8 number of arguments + + // arg 1 ---> R1 + CMP R8, $0 + BEQ docall + SUB $1, R8 + MOVD 0(R7), R1 + + // arg 2 ---> R2 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R2 + + // arg 3 --> R3 + CMP R8, $0 + BEQ docall + SUB $1, R8 + ADD $8, R7 + MOVD 0(R7), R3 + + CMP R8, $0 + BEQ docall + MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument + +repeat: + ADD $8, R7 + MOVD 0(R7), R0 // advance arg pointer by 8 byte + ADD $8, R6 // advance LE argument address by 8 byte + MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame + SUB $1, R8 + CMP R8, $0 + BNE repeat + +docall: + MOVD funcdesc+0(FP), R8 // R8-> function descriptor + LMG 0(R8), R5, R6 + MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC + LE_CALL // balr R7, R6 (return #1) NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+80(FP) - MOVD R0, r2+88(FP) - MOVD R0, err+96(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+96(FP) -done: - BL runtime·exitsyscall(SB) - RET - -TEXT ·syscall_rawsyscall9(SB),NOSPLIT,$0 - MOVD a1+8(FP), R1 - MOVD a2+16(FP), R2 - MOVD a3+24(FP), R3 - - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get function. - MOVD CAA(R8), R9 - MOVD EDCHPXV(R9), R9 - MOVD trap+0(FP), R5 - SLD $4, R5 - ADD R5, R9 - LMG 0(R9), R5, R6 - - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R4 - MOVD $0, 0(R9) - - // Fill in parameter list. - MOVD a4+32(FP), R12 - MOVD R12, (2176+24)(R4) - MOVD a5+40(FP), R12 - MOVD R12, (2176+32)(R4) - MOVD a6+48(FP), R12 - MOVD R12, (2176+40)(R4) - MOVD a7+56(FP), R12 - MOVD R12, (2176+48)(R4) - MOVD a8+64(FP), R12 - MOVD R12, (2176+56)(R4) - MOVD a9+72(FP), R12 - MOVD R12, (2176+64)(R4) - - // Call function. - LE_CALL + MOVD R3, ret+32(FP) + CMP R3, $0 // compare result to 0 + BNE done + + // retrieve errno and errno2 + MOVD zosLibVec<>(SB), R8 + ADD $(__errno), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __errno (return #3) NOPH - XOR R0, R0 // Restore R0 to $0. - MOVD R4, 0(R9) // Save stack pointer. - - MOVD R3, r1+80(FP) - MOVD R0, r2+88(FP) - MOVD R0, err+96(FP) - MOVW R3, R4 - CMP R4, $-1 - BNE done - BL addrerrno<>(SB) - MOVWZ 0(R3), R3 - MOVD R3, err+96(FP) -done: - RET - -// func svcCall(fnptr unsafe.Pointer, argv *unsafe.Pointer, dsa *uint64) -TEXT ·svcCall(SB),NOSPLIT,$0 - BL runtime·save_g(SB) // Save g and stack pointer - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD R15, 0(R9) - - MOVD argv+8(FP), R1 // Move function arguments into registers - MOVD dsa+16(FP), g - MOVD fnptr+0(FP), R15 - - BYTE $0x0D // Branch to function - BYTE $0xEF - - BL runtime·load_g(SB) // Restore g and stack pointer - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD SAVSTACK_ASYNC(R8), R9 - MOVD 0(R9), R15 - - RET - -// func svcLoad(name *byte) unsafe.Pointer -TEXT ·svcLoad(SB),NOSPLIT,$0 - MOVD R15, R2 // Save go stack pointer - MOVD name+0(FP), R0 // Move SVC args into registers - MOVD $0x80000000, R1 - MOVD $0, R15 - BYTE $0x0A // SVC 08 LOAD - BYTE $0x08 - MOVW R15, R3 // Save return code from SVC - MOVD R2, R15 // Restore go stack pointer - CMP R3, $0 // Check SVC return code - BNE error - - MOVD $-2, R3 // Reset last bit of entry point to zero - AND R0, R3 - MOVD R3, addr+8(FP) // Return entry point returned by SVC - CMP R0, R3 // Check if last bit of entry point was set - BNE done - - MOVD R15, R2 // Save go stack pointer - MOVD $0, R15 // Move SVC args into registers (entry point still in r0 from SVC 08) - BYTE $0x0A // SVC 09 DELETE - BYTE $0x09 - MOVD R2, R15 // Restore go stack pointer + MOVWZ 0(R3), R3 + MOVD R3, err+48(FP) + MOVD zosLibVec<>(SB), R8 + ADD $(__err2ad), R8 + LMG 0(R8), R5, R6 + LE_CALL // balr R7, R6 __err2ad (return #2) + NOPH + MOVW (R3), R2 // retrieve errno2 + MOVD R2, errno2+40(FP) // store in return area + XOR R2, R2 + MOVWZ R2, (R3) // clear errno2 -error: - MOVD $0, addr+8(FP) // Return 0 on failure done: - XOR R0, R0 // Reset r0 to 0 + MOVD R4, 0(R9) // Save stack pointer. RET -// func svcUnload(name *byte, fnptr unsafe.Pointer) int64 -TEXT ·svcUnload(SB),NOSPLIT,$0 - MOVD R15, R2 // Save go stack pointer - MOVD name+0(FP), R0 // Move SVC args into registers - MOVD addr+8(FP), R15 - BYTE $0x0A // SVC 09 - BYTE $0x09 - XOR R0, R0 // Reset r0 to 0 - MOVD R15, R1 // Save SVC return code - MOVD R2, R15 // Restore go stack pointer - MOVD R1, rc+0(FP) // Return SVC return code +// +// function to test if a pointer can be safely dereferenced (content read) +// return 0 for succces +// +TEXT ·ptrtest(SB), NOSPLIT, $0-16 + MOVD arg+0(FP), R10 // test pointer in R10 + + // set up R2 to point to CEECAADMC + BYTE $0xE3; BYTE $0x20; BYTE $0x04; BYTE $0xB8; BYTE $0x00; BYTE $0x17 // llgt 2,1208 + BYTE $0xB9; BYTE $0x17; BYTE $0x00; BYTE $0x22 // llgtr 2,2 + BYTE $0xA5; BYTE $0x26; BYTE $0x7F; BYTE $0xFF // nilh 2,32767 + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x58; BYTE $0x00; BYTE $0x04 // lg 2,88(2) + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x08; BYTE $0x00; BYTE $0x04 // lg 2,8(2) + BYTE $0x41; BYTE $0x22; BYTE $0x03; BYTE $0x68 // la 2,872(2) + + // set up R5 to point to the "shunt" path which set 1 to R3 (failure) + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x33 // xgr 3,3 + BYTE $0xA7; BYTE $0x55; BYTE $0x00; BYTE $0x04 // bras 5,lbl1 + BYTE $0xA7; BYTE $0x39; BYTE $0x00; BYTE $0x01 // lghi 3,1 + + // if r3 is not zero (failed) then branch to finish + BYTE $0xB9; BYTE $0x02; BYTE $0x00; BYTE $0x33 // lbl1 ltgr 3,3 + BYTE $0xA7; BYTE $0x74; BYTE $0x00; BYTE $0x08 // brc b'0111',lbl2 + + // stomic store shunt address in R5 into CEECAADMC + BYTE $0xE3; BYTE $0x52; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 5,0(2) + + // now try reading from the test pointer in R10, if it fails it branches to the "lghi" instruction above + BYTE $0xE3; BYTE $0x9A; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x04 // lg 9,0(10) + + // finish here, restore 0 into CEECAADMC + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x99 // lbl2 xgr 9,9 + BYTE $0xE3; BYTE $0x92; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 9,0(2) + MOVD R3, ret+8(FP) // result in R3 RET -// func gettid() uint64 -TEXT ·gettid(SB), NOSPLIT, $0 - // Get library control area (LCA). - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - - // Get CEECAATHDID - MOVD CAA(R8), R9 - MOVD 0x3D0(R9), R9 - MOVD R9, ret+0(FP) - +// +// function to test if a untptr can be loaded from a pointer +// return 1: the 8-byte content +// 2: 0 for success, 1 for failure +// +// func safeload(ptr uintptr) ( value uintptr, error uintptr) +TEXT ·safeload(SB), NOSPLIT, $0-24 + MOVD ptr+0(FP), R10 // test pointer in R10 + MOVD $0x0, R6 + BYTE $0xE3; BYTE $0x20; BYTE $0x04; BYTE $0xB8; BYTE $0x00; BYTE $0x17 // llgt 2,1208 + BYTE $0xB9; BYTE $0x17; BYTE $0x00; BYTE $0x22 // llgtr 2,2 + BYTE $0xA5; BYTE $0x26; BYTE $0x7F; BYTE $0xFF // nilh 2,32767 + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x58; BYTE $0x00; BYTE $0x04 // lg 2,88(2) + BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x08; BYTE $0x00; BYTE $0x04 // lg 2,8(2) + BYTE $0x41; BYTE $0x22; BYTE $0x03; BYTE $0x68 // la 2,872(2) + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x33 // xgr 3,3 + BYTE $0xA7; BYTE $0x55; BYTE $0x00; BYTE $0x04 // bras 5,lbl1 + BYTE $0xA7; BYTE $0x39; BYTE $0x00; BYTE $0x01 // lghi 3,1 + BYTE $0xB9; BYTE $0x02; BYTE $0x00; BYTE $0x33 // lbl1 ltgr 3,3 + BYTE $0xA7; BYTE $0x74; BYTE $0x00; BYTE $0x08 // brc b'0111',lbl2 + BYTE $0xE3; BYTE $0x52; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 5,0(2) + BYTE $0xE3; BYTE $0x6A; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x04 // lg 6,0(10) + BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x99 // lbl2 xgr 9,9 + BYTE $0xE3; BYTE $0x92; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 9,0(2) + MOVD R6, value+8(FP) // result in R6 + MOVD R3, error+16(FP) // error in R3 RET diff --git a/tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.go b/tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.go new file mode 100644 index 000000000..39d647d86 --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.go @@ -0,0 +1,657 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build zos + +package unix + +import ( + "bytes" + "fmt" + "unsafe" +) + +//go:noescape +func bpxcall(plist []unsafe.Pointer, bpx_offset int64) + +//go:noescape +func A2e([]byte) + +//go:noescape +func E2a([]byte) + +const ( + BPX4STA = 192 // stat + BPX4FST = 104 // fstat + BPX4LST = 132 // lstat + BPX4OPN = 156 // open + BPX4CLO = 72 // close + BPX4CHR = 500 // chattr + BPX4FCR = 504 // fchattr + BPX4LCR = 1180 // lchattr + BPX4CTW = 492 // cond_timed_wait + BPX4GTH = 1056 // __getthent + BPX4PTQ = 412 // pthread_quiesc + BPX4PTR = 320 // ptrace +) + +const ( + //options + //byte1 + BPX_OPNFHIGH = 0x80 + //byte2 + BPX_OPNFEXEC = 0x80 + //byte3 + BPX_O_NOLARGEFILE = 0x08 + BPX_O_LARGEFILE = 0x04 + BPX_O_ASYNCSIG = 0x02 + BPX_O_SYNC = 0x01 + //byte4 + BPX_O_CREXCL = 0xc0 + BPX_O_CREAT = 0x80 + BPX_O_EXCL = 0x40 + BPX_O_NOCTTY = 0x20 + BPX_O_TRUNC = 0x10 + BPX_O_APPEND = 0x08 + BPX_O_NONBLOCK = 0x04 + BPX_FNDELAY = 0x04 + BPX_O_RDWR = 0x03 + BPX_O_RDONLY = 0x02 + BPX_O_WRONLY = 0x01 + BPX_O_ACCMODE = 0x03 + BPX_O_GETFL = 0x0f + + //mode + // byte1 (file type) + BPX_FT_DIR = 1 + BPX_FT_CHARSPEC = 2 + BPX_FT_REGFILE = 3 + BPX_FT_FIFO = 4 + BPX_FT_SYMLINK = 5 + BPX_FT_SOCKET = 6 + //byte3 + BPX_S_ISUID = 0x08 + BPX_S_ISGID = 0x04 + BPX_S_ISVTX = 0x02 + BPX_S_IRWXU1 = 0x01 + BPX_S_IRUSR = 0x01 + //byte4 + BPX_S_IRWXU2 = 0xc0 + BPX_S_IWUSR = 0x80 + BPX_S_IXUSR = 0x40 + BPX_S_IRWXG = 0x38 + BPX_S_IRGRP = 0x20 + BPX_S_IWGRP = 0x10 + BPX_S_IXGRP = 0x08 + BPX_S_IRWXOX = 0x07 + BPX_S_IROTH = 0x04 + BPX_S_IWOTH = 0x02 + BPX_S_IXOTH = 0x01 + + CW_INTRPT = 1 + CW_CONDVAR = 32 + CW_TIMEOUT = 64 + + PGTHA_NEXT = 2 + PGTHA_CURRENT = 1 + PGTHA_FIRST = 0 + PGTHA_LAST = 3 + PGTHA_PROCESS = 0x80 + PGTHA_CONTTY = 0x40 + PGTHA_PATH = 0x20 + PGTHA_COMMAND = 0x10 + PGTHA_FILEDATA = 0x08 + PGTHA_THREAD = 0x04 + PGTHA_PTAG = 0x02 + PGTHA_COMMANDLONG = 0x01 + PGTHA_THREADFAST = 0x80 + PGTHA_FILEPATH = 0x40 + PGTHA_THDSIGMASK = 0x20 + // thread quiece mode + QUIESCE_TERM int32 = 1 + QUIESCE_FORCE int32 = 2 + QUIESCE_QUERY int32 = 3 + QUIESCE_FREEZE int32 = 4 + QUIESCE_UNFREEZE int32 = 5 + FREEZE_THIS_THREAD int32 = 6 + FREEZE_EXIT int32 = 8 + QUIESCE_SRB int32 = 9 +) + +type Pgtha struct { + Pid uint32 // 0 + Tid0 uint32 // 4 + Tid1 uint32 + Accesspid byte // C + Accesstid byte // D + Accessasid uint16 // E + Loginname [8]byte // 10 + Flag1 byte // 18 + Flag1b2 byte // 19 +} + +type Bpxystat_t struct { // DSECT BPXYSTAT + St_id [4]uint8 // 0 + St_length uint16 // 0x4 + St_version uint16 // 0x6 + St_mode uint32 // 0x8 + St_ino uint32 // 0xc + St_dev uint32 // 0x10 + St_nlink uint32 // 0x14 + St_uid uint32 // 0x18 + St_gid uint32 // 0x1c + St_size uint64 // 0x20 + St_atime uint32 // 0x28 + St_mtime uint32 // 0x2c + St_ctime uint32 // 0x30 + St_rdev uint32 // 0x34 + St_auditoraudit uint32 // 0x38 + St_useraudit uint32 // 0x3c + St_blksize uint32 // 0x40 + St_createtime uint32 // 0x44 + St_auditid [4]uint32 // 0x48 + St_res01 uint32 // 0x58 + Ft_ccsid uint16 // 0x5c + Ft_flags uint16 // 0x5e + St_res01a [2]uint32 // 0x60 + St_res02 uint32 // 0x68 + St_blocks uint32 // 0x6c + St_opaque [3]uint8 // 0x70 + St_visible uint8 // 0x73 + St_reftime uint32 // 0x74 + St_fid uint64 // 0x78 + St_filefmt uint8 // 0x80 + St_fspflag2 uint8 // 0x81 + St_res03 [2]uint8 // 0x82 + St_ctimemsec uint32 // 0x84 + St_seclabel [8]uint8 // 0x88 + St_res04 [4]uint8 // 0x90 + // end of version 1 + _ uint32 // 0x94 + St_atime64 uint64 // 0x98 + St_mtime64 uint64 // 0xa0 + St_ctime64 uint64 // 0xa8 + St_createtime64 uint64 // 0xb0 + St_reftime64 uint64 // 0xb8 + _ uint64 // 0xc0 + St_res05 [16]uint8 // 0xc8 + // end of version 2 +} + +type BpxFilestatus struct { + Oflag1 byte + Oflag2 byte + Oflag3 byte + Oflag4 byte +} + +type BpxMode struct { + Ftype byte + Mode1 byte + Mode2 byte + Mode3 byte +} + +// Thr attribute structure for extended attributes +type Bpxyatt_t struct { // DSECT BPXYATT + Att_id [4]uint8 + Att_version uint16 + Att_res01 [2]uint8 + Att_setflags1 uint8 + Att_setflags2 uint8 + Att_setflags3 uint8 + Att_setflags4 uint8 + Att_mode uint32 + Att_uid uint32 + Att_gid uint32 + Att_opaquemask [3]uint8 + Att_visblmaskres uint8 + Att_opaque [3]uint8 + Att_visibleres uint8 + Att_size_h uint32 + Att_size_l uint32 + Att_atime uint32 + Att_mtime uint32 + Att_auditoraudit uint32 + Att_useraudit uint32 + Att_ctime uint32 + Att_reftime uint32 + // end of version 1 + Att_filefmt uint8 + Att_res02 [3]uint8 + Att_filetag uint32 + Att_res03 [8]uint8 + // end of version 2 + Att_atime64 uint64 + Att_mtime64 uint64 + Att_ctime64 uint64 + Att_reftime64 uint64 + Att_seclabel [8]uint8 + Att_ver3res02 [8]uint8 + // end of version 3 +} + +func BpxOpen(name string, options *BpxFilestatus, mode *BpxMode) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(options) + parms[3] = unsafe.Pointer(mode) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4OPN) + return rv, rc, rn + } + return -1, -1, -1 +} + +func BpxClose(fd int32) (rv int32, rc int32, rn int32) { + var parms [4]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&rv) + parms[2] = unsafe.Pointer(&rc) + parms[3] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CLO) + return rv, rc, rn +} + +func BpxFileFStat(fd int32, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [6]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&stat_sz) + parms[2] = unsafe.Pointer(st) + parms[3] = unsafe.Pointer(&rv) + parms[4] = unsafe.Pointer(&rc) + parms[5] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4FST) + return rv, rc, rn +} + +func BpxFileStat(name string, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&stat_sz) + parms[3] = unsafe.Pointer(st) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4STA) + return rv, rc, rn + } + return -1, -1, -1 +} + +func BpxFileLStat(name string, st *Bpxystat_t) (rv int32, rc int32, rn int32) { + if len(name) < 1024 { + var namebuf [1024]byte + sz := int32(copy(namebuf[:], name)) + A2e(namebuf[:sz]) + st.St_id = [4]uint8{0xe2, 0xe3, 0xc1, 0xe3} + st.St_version = 2 + stat_sz := uint32(unsafe.Sizeof(*st)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&stat_sz) + parms[3] = unsafe.Pointer(st) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4LST) + return rv, rc, rn + } + return -1, -1, -1 +} + +func BpxChattr(path string, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + if len(path) >= 1024 { + return -1, -1, -1 + } + var namebuf [1024]byte + sz := int32(copy(namebuf[:], path)) + A2e(namebuf[:sz]) + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&attr_sz) + parms[3] = unsafe.Pointer(attr) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CHR) + return rv, rc, rn +} + +func BpxLchattr(path string, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + if len(path) >= 1024 { + return -1, -1, -1 + } + var namebuf [1024]byte + sz := int32(copy(namebuf[:], path)) + A2e(namebuf[:sz]) + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [7]unsafe.Pointer + parms[0] = unsafe.Pointer(&sz) + parms[1] = unsafe.Pointer(&namebuf[0]) + parms[2] = unsafe.Pointer(&attr_sz) + parms[3] = unsafe.Pointer(attr) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4LCR) + return rv, rc, rn +} + +func BpxFchattr(fd int32, attr *Bpxyatt_t) (rv int32, rc int32, rn int32) { + attr_sz := uint32(unsafe.Sizeof(*attr)) + var parms [6]unsafe.Pointer + parms[0] = unsafe.Pointer(&fd) + parms[1] = unsafe.Pointer(&attr_sz) + parms[2] = unsafe.Pointer(attr) + parms[3] = unsafe.Pointer(&rv) + parms[4] = unsafe.Pointer(&rc) + parms[5] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4FCR) + return rv, rc, rn +} + +func BpxCondTimedWait(sec uint32, nsec uint32, events uint32, secrem *uint32, nsecrem *uint32) (rv int32, rc int32, rn int32) { + var parms [8]unsafe.Pointer + parms[0] = unsafe.Pointer(&sec) + parms[1] = unsafe.Pointer(&nsec) + parms[2] = unsafe.Pointer(&events) + parms[3] = unsafe.Pointer(secrem) + parms[4] = unsafe.Pointer(nsecrem) + parms[5] = unsafe.Pointer(&rv) + parms[6] = unsafe.Pointer(&rc) + parms[7] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4CTW) + return rv, rc, rn +} +func BpxGetthent(in *Pgtha, outlen *uint32, out unsafe.Pointer) (rv int32, rc int32, rn int32) { + var parms [7]unsafe.Pointer + inlen := uint32(26) // nothing else will work. Go says Pgtha is 28-byte because of alignment, but Pgtha is "packed" and must be 26-byte + parms[0] = unsafe.Pointer(&inlen) + parms[1] = unsafe.Pointer(&in) + parms[2] = unsafe.Pointer(outlen) + parms[3] = unsafe.Pointer(&out) + parms[4] = unsafe.Pointer(&rv) + parms[5] = unsafe.Pointer(&rc) + parms[6] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4GTH) + return rv, rc, rn +} +func ZosJobname() (jobname string, err error) { + var pgtha Pgtha + pgtha.Pid = uint32(Getpid()) + pgtha.Accesspid = PGTHA_CURRENT + pgtha.Flag1 = PGTHA_PROCESS + var out [256]byte + var outlen uint32 + outlen = 256 + rv, rc, rn := BpxGetthent(&pgtha, &outlen, unsafe.Pointer(&out[0])) + if rv == 0 { + gthc := []byte{0x87, 0xa3, 0x88, 0x83} // 'gthc' in ebcdic + ix := bytes.Index(out[:], gthc) + if ix == -1 { + err = fmt.Errorf("BPX4GTH: gthc return data not found") + return + } + jn := out[ix+80 : ix+88] // we didn't declare Pgthc, but jobname is 8-byte at offset 80 + E2a(jn) + jobname = string(bytes.TrimRight(jn, " ")) + + } else { + err = fmt.Errorf("BPX4GTH: rc=%d errno=%d reason=code=0x%x", rv, rc, rn) + } + return +} +func Bpx4ptq(code int32, data string) (rv int32, rc int32, rn int32) { + var userdata [8]byte + var parms [5]unsafe.Pointer + copy(userdata[:], data+" ") + A2e(userdata[:]) + parms[0] = unsafe.Pointer(&code) + parms[1] = unsafe.Pointer(&userdata[0]) + parms[2] = unsafe.Pointer(&rv) + parms[3] = unsafe.Pointer(&rc) + parms[4] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4PTQ) + return rv, rc, rn +} + +const ( + PT_TRACE_ME = 0 // Debug this process + PT_READ_I = 1 // Read a full word + PT_READ_D = 2 // Read a full word + PT_READ_U = 3 // Read control info + PT_WRITE_I = 4 //Write a full word + PT_WRITE_D = 5 //Write a full word + PT_CONTINUE = 7 //Continue the process + PT_KILL = 8 //Terminate the process + PT_READ_GPR = 11 // Read GPR, CR, PSW + PT_READ_FPR = 12 // Read FPR + PT_READ_VR = 13 // Read VR + PT_WRITE_GPR = 14 // Write GPR, CR, PSW + PT_WRITE_FPR = 15 // Write FPR + PT_WRITE_VR = 16 // Write VR + PT_READ_BLOCK = 17 // Read storage + PT_WRITE_BLOCK = 19 // Write storage + PT_READ_GPRH = 20 // Read GPRH + PT_WRITE_GPRH = 21 // Write GPRH + PT_REGHSET = 22 // Read all GPRHs + PT_ATTACH = 30 // Attach to a process + PT_DETACH = 31 // Detach from a process + PT_REGSET = 32 // Read all GPRs + PT_REATTACH = 33 // Reattach to a process + PT_LDINFO = 34 // Read loader info + PT_MULTI = 35 // Multi process mode + PT_LD64INFO = 36 // RMODE64 Info Area + PT_BLOCKREQ = 40 // Block request + PT_THREAD_INFO = 60 // Read thread info + PT_THREAD_MODIFY = 61 + PT_THREAD_READ_FOCUS = 62 + PT_THREAD_WRITE_FOCUS = 63 + PT_THREAD_HOLD = 64 + PT_THREAD_SIGNAL = 65 + PT_EXPLAIN = 66 + PT_EVENTS = 67 + PT_THREAD_INFO_EXTENDED = 68 + PT_REATTACH2 = 71 + PT_CAPTURE = 72 + PT_UNCAPTURE = 73 + PT_GET_THREAD_TCB = 74 + PT_GET_ALET = 75 + PT_SWAPIN = 76 + PT_EXTENDED_EVENT = 98 + PT_RECOVER = 99 // Debug a program check + PT_GPR0 = 0 // General purpose register 0 + PT_GPR1 = 1 // General purpose register 1 + PT_GPR2 = 2 // General purpose register 2 + PT_GPR3 = 3 // General purpose register 3 + PT_GPR4 = 4 // General purpose register 4 + PT_GPR5 = 5 // General purpose register 5 + PT_GPR6 = 6 // General purpose register 6 + PT_GPR7 = 7 // General purpose register 7 + PT_GPR8 = 8 // General purpose register 8 + PT_GPR9 = 9 // General purpose register 9 + PT_GPR10 = 10 // General purpose register 10 + PT_GPR11 = 11 // General purpose register 11 + PT_GPR12 = 12 // General purpose register 12 + PT_GPR13 = 13 // General purpose register 13 + PT_GPR14 = 14 // General purpose register 14 + PT_GPR15 = 15 // General purpose register 15 + PT_FPR0 = 16 // Floating point register 0 + PT_FPR1 = 17 // Floating point register 1 + PT_FPR2 = 18 // Floating point register 2 + PT_FPR3 = 19 // Floating point register 3 + PT_FPR4 = 20 // Floating point register 4 + PT_FPR5 = 21 // Floating point register 5 + PT_FPR6 = 22 // Floating point register 6 + PT_FPR7 = 23 // Floating point register 7 + PT_FPR8 = 24 // Floating point register 8 + PT_FPR9 = 25 // Floating point register 9 + PT_FPR10 = 26 // Floating point register 10 + PT_FPR11 = 27 // Floating point register 11 + PT_FPR12 = 28 // Floating point register 12 + PT_FPR13 = 29 // Floating point register 13 + PT_FPR14 = 30 // Floating point register 14 + PT_FPR15 = 31 // Floating point register 15 + PT_FPC = 32 // Floating point control register + PT_PSW = 40 // PSW + PT_PSW0 = 40 // Left half of the PSW + PT_PSW1 = 41 // Right half of the PSW + PT_CR0 = 42 // Control register 0 + PT_CR1 = 43 // Control register 1 + PT_CR2 = 44 // Control register 2 + PT_CR3 = 45 // Control register 3 + PT_CR4 = 46 // Control register 4 + PT_CR5 = 47 // Control register 5 + PT_CR6 = 48 // Control register 6 + PT_CR7 = 49 // Control register 7 + PT_CR8 = 50 // Control register 8 + PT_CR9 = 51 // Control register 9 + PT_CR10 = 52 // Control register 10 + PT_CR11 = 53 // Control register 11 + PT_CR12 = 54 // Control register 12 + PT_CR13 = 55 // Control register 13 + PT_CR14 = 56 // Control register 14 + PT_CR15 = 57 // Control register 15 + PT_GPRH0 = 58 // GP High register 0 + PT_GPRH1 = 59 // GP High register 1 + PT_GPRH2 = 60 // GP High register 2 + PT_GPRH3 = 61 // GP High register 3 + PT_GPRH4 = 62 // GP High register 4 + PT_GPRH5 = 63 // GP High register 5 + PT_GPRH6 = 64 // GP High register 6 + PT_GPRH7 = 65 // GP High register 7 + PT_GPRH8 = 66 // GP High register 8 + PT_GPRH9 = 67 // GP High register 9 + PT_GPRH10 = 68 // GP High register 10 + PT_GPRH11 = 69 // GP High register 11 + PT_GPRH12 = 70 // GP High register 12 + PT_GPRH13 = 71 // GP High register 13 + PT_GPRH14 = 72 // GP High register 14 + PT_GPRH15 = 73 // GP High register 15 + PT_VR0 = 74 // Vector register 0 + PT_VR1 = 75 // Vector register 1 + PT_VR2 = 76 // Vector register 2 + PT_VR3 = 77 // Vector register 3 + PT_VR4 = 78 // Vector register 4 + PT_VR5 = 79 // Vector register 5 + PT_VR6 = 80 // Vector register 6 + PT_VR7 = 81 // Vector register 7 + PT_VR8 = 82 // Vector register 8 + PT_VR9 = 83 // Vector register 9 + PT_VR10 = 84 // Vector register 10 + PT_VR11 = 85 // Vector register 11 + PT_VR12 = 86 // Vector register 12 + PT_VR13 = 87 // Vector register 13 + PT_VR14 = 88 // Vector register 14 + PT_VR15 = 89 // Vector register 15 + PT_VR16 = 90 // Vector register 16 + PT_VR17 = 91 // Vector register 17 + PT_VR18 = 92 // Vector register 18 + PT_VR19 = 93 // Vector register 19 + PT_VR20 = 94 // Vector register 20 + PT_VR21 = 95 // Vector register 21 + PT_VR22 = 96 // Vector register 22 + PT_VR23 = 97 // Vector register 23 + PT_VR24 = 98 // Vector register 24 + PT_VR25 = 99 // Vector register 25 + PT_VR26 = 100 // Vector register 26 + PT_VR27 = 101 // Vector register 27 + PT_VR28 = 102 // Vector register 28 + PT_VR29 = 103 // Vector register 29 + PT_VR30 = 104 // Vector register 30 + PT_VR31 = 105 // Vector register 31 + PT_PSWG = 106 // PSWG + PT_PSWG0 = 106 // Bytes 0-3 + PT_PSWG1 = 107 // Bytes 4-7 + PT_PSWG2 = 108 // Bytes 8-11 (IA high word) + PT_PSWG3 = 109 // Bytes 12-15 (IA low word) +) + +func Bpx4ptr(request int32, pid int32, addr unsafe.Pointer, data unsafe.Pointer, buffer unsafe.Pointer) (rv int32, rc int32, rn int32) { + var parms [8]unsafe.Pointer + parms[0] = unsafe.Pointer(&request) + parms[1] = unsafe.Pointer(&pid) + parms[2] = unsafe.Pointer(&addr) + parms[3] = unsafe.Pointer(&data) + parms[4] = unsafe.Pointer(&buffer) + parms[5] = unsafe.Pointer(&rv) + parms[6] = unsafe.Pointer(&rc) + parms[7] = unsafe.Pointer(&rn) + bpxcall(parms[:], BPX4PTR) + return rv, rc, rn +} + +func copyU8(val uint8, dest []uint8) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} + +func copyU8Arr(src, dest []uint8) int { + if len(dest) < len(src) { + return 0 + } + for i, v := range src { + dest[i] = v + } + return len(src) +} + +func copyU16(val uint16, dest []uint16) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} + +func copyU32(val uint32, dest []uint32) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} + +func copyU32Arr(src, dest []uint32) int { + if len(dest) < len(src) { + return 0 + } + for i, v := range src { + dest[i] = v + } + return len(src) +} + +func copyU64(val uint64, dest []uint64) int { + if len(dest) < 1 { + return 0 + } + dest[0] = val + return 1 +} diff --git a/tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.s b/tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.s new file mode 100644 index 000000000..4bd4a1798 --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/bpxsvc_zos.s @@ -0,0 +1,192 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +#include "go_asm.h" +#include "textflag.h" + +// function to call USS assembly language services +// +// doc: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_3.1.0/com.ibm.zos.v3r1.bpxb100/bit64env.htm +// +// arg1 unsafe.Pointer array that ressembles an OS PLIST +// +// arg2 function offset as in +// doc: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_3.1.0/com.ibm.zos.v3r1.bpxb100/bpx2cr_List_of_offsets.htm +// +// func bpxcall(plist []unsafe.Pointer, bpx_offset int64) + +TEXT ·bpxcall(SB), NOSPLIT|NOFRAME, $0 + MOVD plist_base+0(FP), R1 // r1 points to plist + MOVD bpx_offset+24(FP), R2 // r2 offset to BPX vector table + MOVD R14, R7 // save r14 + MOVD R15, R8 // save r15 + MOVWZ 16(R0), R9 + MOVWZ 544(R9), R9 + MOVWZ 24(R9), R9 // call vector in r9 + ADD R2, R9 // add offset to vector table + MOVWZ (R9), R9 // r9 points to entry point + BYTE $0x0D // BL R14,R9 --> basr r14,r9 + BYTE $0xE9 // clobbers 0,1,14,15 + MOVD R8, R15 // restore 15 + JMP R7 // return via saved return address + +// func A2e(arr [] byte) +// code page conversion from 819 to 1047 +TEXT ·A2e(SB), NOSPLIT|NOFRAME, $0 + MOVD arg_base+0(FP), R2 // pointer to arry of characters + MOVD arg_len+8(FP), R3 // count + XOR R0, R0 + XOR R1, R1 + BYTE $0xA7; BYTE $0x15; BYTE $0x00; BYTE $0x82 // BRAS 1,(2+(256/2)) + + // ASCII -> EBCDIC conversion table: + BYTE $0x00; BYTE $0x01; BYTE $0x02; BYTE $0x03 + BYTE $0x37; BYTE $0x2d; BYTE $0x2e; BYTE $0x2f + BYTE $0x16; BYTE $0x05; BYTE $0x15; BYTE $0x0b + BYTE $0x0c; BYTE $0x0d; BYTE $0x0e; BYTE $0x0f + BYTE $0x10; BYTE $0x11; BYTE $0x12; BYTE $0x13 + BYTE $0x3c; BYTE $0x3d; BYTE $0x32; BYTE $0x26 + BYTE $0x18; BYTE $0x19; BYTE $0x3f; BYTE $0x27 + BYTE $0x1c; BYTE $0x1d; BYTE $0x1e; BYTE $0x1f + BYTE $0x40; BYTE $0x5a; BYTE $0x7f; BYTE $0x7b + BYTE $0x5b; BYTE $0x6c; BYTE $0x50; BYTE $0x7d + BYTE $0x4d; BYTE $0x5d; BYTE $0x5c; BYTE $0x4e + BYTE $0x6b; BYTE $0x60; BYTE $0x4b; BYTE $0x61 + BYTE $0xf0; BYTE $0xf1; BYTE $0xf2; BYTE $0xf3 + BYTE $0xf4; BYTE $0xf5; BYTE $0xf6; BYTE $0xf7 + BYTE $0xf8; BYTE $0xf9; BYTE $0x7a; BYTE $0x5e + BYTE $0x4c; BYTE $0x7e; BYTE $0x6e; BYTE $0x6f + BYTE $0x7c; BYTE $0xc1; BYTE $0xc2; BYTE $0xc3 + BYTE $0xc4; BYTE $0xc5; BYTE $0xc6; BYTE $0xc7 + BYTE $0xc8; BYTE $0xc9; BYTE $0xd1; BYTE $0xd2 + BYTE $0xd3; BYTE $0xd4; BYTE $0xd5; BYTE $0xd6 + BYTE $0xd7; BYTE $0xd8; BYTE $0xd9; BYTE $0xe2 + BYTE $0xe3; BYTE $0xe4; BYTE $0xe5; BYTE $0xe6 + BYTE $0xe7; BYTE $0xe8; BYTE $0xe9; BYTE $0xad + BYTE $0xe0; BYTE $0xbd; BYTE $0x5f; BYTE $0x6d + BYTE $0x79; BYTE $0x81; BYTE $0x82; BYTE $0x83 + BYTE $0x84; BYTE $0x85; BYTE $0x86; BYTE $0x87 + BYTE $0x88; BYTE $0x89; BYTE $0x91; BYTE $0x92 + BYTE $0x93; BYTE $0x94; BYTE $0x95; BYTE $0x96 + BYTE $0x97; BYTE $0x98; BYTE $0x99; BYTE $0xa2 + BYTE $0xa3; BYTE $0xa4; BYTE $0xa5; BYTE $0xa6 + BYTE $0xa7; BYTE $0xa8; BYTE $0xa9; BYTE $0xc0 + BYTE $0x4f; BYTE $0xd0; BYTE $0xa1; BYTE $0x07 + BYTE $0x20; BYTE $0x21; BYTE $0x22; BYTE $0x23 + BYTE $0x24; BYTE $0x25; BYTE $0x06; BYTE $0x17 + BYTE $0x28; BYTE $0x29; BYTE $0x2a; BYTE $0x2b + BYTE $0x2c; BYTE $0x09; BYTE $0x0a; BYTE $0x1b + BYTE $0x30; BYTE $0x31; BYTE $0x1a; BYTE $0x33 + BYTE $0x34; BYTE $0x35; BYTE $0x36; BYTE $0x08 + BYTE $0x38; BYTE $0x39; BYTE $0x3a; BYTE $0x3b + BYTE $0x04; BYTE $0x14; BYTE $0x3e; BYTE $0xff + BYTE $0x41; BYTE $0xaa; BYTE $0x4a; BYTE $0xb1 + BYTE $0x9f; BYTE $0xb2; BYTE $0x6a; BYTE $0xb5 + BYTE $0xbb; BYTE $0xb4; BYTE $0x9a; BYTE $0x8a + BYTE $0xb0; BYTE $0xca; BYTE $0xaf; BYTE $0xbc + BYTE $0x90; BYTE $0x8f; BYTE $0xea; BYTE $0xfa + BYTE $0xbe; BYTE $0xa0; BYTE $0xb6; BYTE $0xb3 + BYTE $0x9d; BYTE $0xda; BYTE $0x9b; BYTE $0x8b + BYTE $0xb7; BYTE $0xb8; BYTE $0xb9; BYTE $0xab + BYTE $0x64; BYTE $0x65; BYTE $0x62; BYTE $0x66 + BYTE $0x63; BYTE $0x67; BYTE $0x9e; BYTE $0x68 + BYTE $0x74; BYTE $0x71; BYTE $0x72; BYTE $0x73 + BYTE $0x78; BYTE $0x75; BYTE $0x76; BYTE $0x77 + BYTE $0xac; BYTE $0x69; BYTE $0xed; BYTE $0xee + BYTE $0xeb; BYTE $0xef; BYTE $0xec; BYTE $0xbf + BYTE $0x80; BYTE $0xfd; BYTE $0xfe; BYTE $0xfb + BYTE $0xfc; BYTE $0xba; BYTE $0xae; BYTE $0x59 + BYTE $0x44; BYTE $0x45; BYTE $0x42; BYTE $0x46 + BYTE $0x43; BYTE $0x47; BYTE $0x9c; BYTE $0x48 + BYTE $0x54; BYTE $0x51; BYTE $0x52; BYTE $0x53 + BYTE $0x58; BYTE $0x55; BYTE $0x56; BYTE $0x57 + BYTE $0x8c; BYTE $0x49; BYTE $0xcd; BYTE $0xce + BYTE $0xcb; BYTE $0xcf; BYTE $0xcc; BYTE $0xe1 + BYTE $0x70; BYTE $0xdd; BYTE $0xde; BYTE $0xdb + BYTE $0xdc; BYTE $0x8d; BYTE $0x8e; BYTE $0xdf + +retry: + WORD $0xB9931022 // TROO 2,2,b'0001' + BVS retry + RET + +// func e2a(arr [] byte) +// code page conversion from 1047 to 819 +TEXT ·E2a(SB), NOSPLIT|NOFRAME, $0 + MOVD arg_base+0(FP), R2 // pointer to arry of characters + MOVD arg_len+8(FP), R3 // count + XOR R0, R0 + XOR R1, R1 + BYTE $0xA7; BYTE $0x15; BYTE $0x00; BYTE $0x82 // BRAS 1,(2+(256/2)) + + // EBCDIC -> ASCII conversion table: + BYTE $0x00; BYTE $0x01; BYTE $0x02; BYTE $0x03 + BYTE $0x9c; BYTE $0x09; BYTE $0x86; BYTE $0x7f + BYTE $0x97; BYTE $0x8d; BYTE $0x8e; BYTE $0x0b + BYTE $0x0c; BYTE $0x0d; BYTE $0x0e; BYTE $0x0f + BYTE $0x10; BYTE $0x11; BYTE $0x12; BYTE $0x13 + BYTE $0x9d; BYTE $0x0a; BYTE $0x08; BYTE $0x87 + BYTE $0x18; BYTE $0x19; BYTE $0x92; BYTE $0x8f + BYTE $0x1c; BYTE $0x1d; BYTE $0x1e; BYTE $0x1f + BYTE $0x80; BYTE $0x81; BYTE $0x82; BYTE $0x83 + BYTE $0x84; BYTE $0x85; BYTE $0x17; BYTE $0x1b + BYTE $0x88; BYTE $0x89; BYTE $0x8a; BYTE $0x8b + BYTE $0x8c; BYTE $0x05; BYTE $0x06; BYTE $0x07 + BYTE $0x90; BYTE $0x91; BYTE $0x16; BYTE $0x93 + BYTE $0x94; BYTE $0x95; BYTE $0x96; BYTE $0x04 + BYTE $0x98; BYTE $0x99; BYTE $0x9a; BYTE $0x9b + BYTE $0x14; BYTE $0x15; BYTE $0x9e; BYTE $0x1a + BYTE $0x20; BYTE $0xa0; BYTE $0xe2; BYTE $0xe4 + BYTE $0xe0; BYTE $0xe1; BYTE $0xe3; BYTE $0xe5 + BYTE $0xe7; BYTE $0xf1; BYTE $0xa2; BYTE $0x2e + BYTE $0x3c; BYTE $0x28; BYTE $0x2b; BYTE $0x7c + BYTE $0x26; BYTE $0xe9; BYTE $0xea; BYTE $0xeb + BYTE $0xe8; BYTE $0xed; BYTE $0xee; BYTE $0xef + BYTE $0xec; BYTE $0xdf; BYTE $0x21; BYTE $0x24 + BYTE $0x2a; BYTE $0x29; BYTE $0x3b; BYTE $0x5e + BYTE $0x2d; BYTE $0x2f; BYTE $0xc2; BYTE $0xc4 + BYTE $0xc0; BYTE $0xc1; BYTE $0xc3; BYTE $0xc5 + BYTE $0xc7; BYTE $0xd1; BYTE $0xa6; BYTE $0x2c + BYTE $0x25; BYTE $0x5f; BYTE $0x3e; BYTE $0x3f + BYTE $0xf8; BYTE $0xc9; BYTE $0xca; BYTE $0xcb + BYTE $0xc8; BYTE $0xcd; BYTE $0xce; BYTE $0xcf + BYTE $0xcc; BYTE $0x60; BYTE $0x3a; BYTE $0x23 + BYTE $0x40; BYTE $0x27; BYTE $0x3d; BYTE $0x22 + BYTE $0xd8; BYTE $0x61; BYTE $0x62; BYTE $0x63 + BYTE $0x64; BYTE $0x65; BYTE $0x66; BYTE $0x67 + BYTE $0x68; BYTE $0x69; BYTE $0xab; BYTE $0xbb + BYTE $0xf0; BYTE $0xfd; BYTE $0xfe; BYTE $0xb1 + BYTE $0xb0; BYTE $0x6a; BYTE $0x6b; BYTE $0x6c + BYTE $0x6d; BYTE $0x6e; BYTE $0x6f; BYTE $0x70 + BYTE $0x71; BYTE $0x72; BYTE $0xaa; BYTE $0xba + BYTE $0xe6; BYTE $0xb8; BYTE $0xc6; BYTE $0xa4 + BYTE $0xb5; BYTE $0x7e; BYTE $0x73; BYTE $0x74 + BYTE $0x75; BYTE $0x76; BYTE $0x77; BYTE $0x78 + BYTE $0x79; BYTE $0x7a; BYTE $0xa1; BYTE $0xbf + BYTE $0xd0; BYTE $0x5b; BYTE $0xde; BYTE $0xae + BYTE $0xac; BYTE $0xa3; BYTE $0xa5; BYTE $0xb7 + BYTE $0xa9; BYTE $0xa7; BYTE $0xb6; BYTE $0xbc + BYTE $0xbd; BYTE $0xbe; BYTE $0xdd; BYTE $0xa8 + BYTE $0xaf; BYTE $0x5d; BYTE $0xb4; BYTE $0xd7 + BYTE $0x7b; BYTE $0x41; BYTE $0x42; BYTE $0x43 + BYTE $0x44; BYTE $0x45; BYTE $0x46; BYTE $0x47 + BYTE $0x48; BYTE $0x49; BYTE $0xad; BYTE $0xf4 + BYTE $0xf6; BYTE $0xf2; BYTE $0xf3; BYTE $0xf5 + BYTE $0x7d; BYTE $0x4a; BYTE $0x4b; BYTE $0x4c + BYTE $0x4d; BYTE $0x4e; BYTE $0x4f; BYTE $0x50 + BYTE $0x51; BYTE $0x52; BYTE $0xb9; BYTE $0xfb + BYTE $0xfc; BYTE $0xf9; BYTE $0xfa; BYTE $0xff + BYTE $0x5c; BYTE $0xf7; BYTE $0x53; BYTE $0x54 + BYTE $0x55; BYTE $0x56; BYTE $0x57; BYTE $0x58 + BYTE $0x59; BYTE $0x5a; BYTE $0xb2; BYTE $0xd4 + BYTE $0xd6; BYTE $0xd2; BYTE $0xd3; BYTE $0xd5 + BYTE $0x30; BYTE $0x31; BYTE $0x32; BYTE $0x33 + BYTE $0x34; BYTE $0x35; BYTE $0x36; BYTE $0x37 + BYTE $0x38; BYTE $0x39; BYTE $0xb3; BYTE $0xdb + BYTE $0xdc; BYTE $0xd9; BYTE $0xda; BYTE $0x9f + +retry: + WORD $0xB9931022 // TROO 2,2,b'0001' + BVS retry + RET diff --git a/tools/vendor/golang.org/x/sys/unix/cap_freebsd.go b/tools/vendor/golang.org/x/sys/unix/cap_freebsd.go index 0b7c6adb8..a08657890 100644 --- a/tools/vendor/golang.org/x/sys/unix/cap_freebsd.go +++ b/tools/vendor/golang.org/x/sys/unix/cap_freebsd.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build freebsd -// +build freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/constants.go b/tools/vendor/golang.org/x/sys/unix/constants.go index 394a3965b..6fb7cb77d 100644 --- a/tools/vendor/golang.org/x/sys/unix/constants.go +++ b/tools/vendor/golang.org/x/sys/unix/constants.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc.go b/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc.go index 65a998508..d78513461 100644 --- a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix && ppc -// +build aix,ppc // Functions to access/create device major and minor numbers matching the // encoding used by AIX. diff --git a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go b/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go index 8fc08ad0a..623a5e697 100644 --- a/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/dev_aix_ppc64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix && ppc64 -// +build aix,ppc64 // Functions to access/create device major and minor numbers matching the // encoding used AIX. diff --git a/tools/vendor/golang.org/x/sys/unix/dev_zos.go b/tools/vendor/golang.org/x/sys/unix/dev_zos.go index a388e59a0..bb6a64fe9 100644 --- a/tools/vendor/golang.org/x/sys/unix/dev_zos.go +++ b/tools/vendor/golang.org/x/sys/unix/dev_zos.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build zos && s390x -// +build zos,s390x // Functions to access/create device major and minor numbers matching the // encoding used by z/OS. diff --git a/tools/vendor/golang.org/x/sys/unix/dirent.go b/tools/vendor/golang.org/x/sys/unix/dirent.go index 2499f977b..1ebf11782 100644 --- a/tools/vendor/golang.org/x/sys/unix/dirent.go +++ b/tools/vendor/golang.org/x/sys/unix/dirent.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/endian_big.go b/tools/vendor/golang.org/x/sys/unix/endian_big.go index a52026557..1095fd31d 100644 --- a/tools/vendor/golang.org/x/sys/unix/endian_big.go +++ b/tools/vendor/golang.org/x/sys/unix/endian_big.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. // //go:build armbe || arm64be || m68k || mips || mips64 || mips64p32 || ppc || ppc64 || s390 || s390x || shbe || sparc || sparc64 -// +build armbe arm64be m68k mips mips64 mips64p32 ppc ppc64 s390 s390x shbe sparc sparc64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/endian_little.go b/tools/vendor/golang.org/x/sys/unix/endian_little.go index b0f2bc4ae..b9f0e277b 100644 --- a/tools/vendor/golang.org/x/sys/unix/endian_little.go +++ b/tools/vendor/golang.org/x/sys/unix/endian_little.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. // //go:build 386 || amd64 || amd64p32 || alpha || arm || arm64 || loong64 || mipsle || mips64le || mips64p32le || nios2 || ppc64le || riscv || riscv64 || sh -// +build 386 amd64 amd64p32 alpha arm arm64 loong64 mipsle mips64le mips64p32le nios2 ppc64le riscv riscv64 sh package unix diff --git a/tools/vendor/golang.org/x/sys/unix/env_unix.go b/tools/vendor/golang.org/x/sys/unix/env_unix.go index 29ccc4d13..a96da71f4 100644 --- a/tools/vendor/golang.org/x/sys/unix/env_unix.go +++ b/tools/vendor/golang.org/x/sys/unix/env_unix.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos // Unix environment variables. diff --git a/tools/vendor/golang.org/x/sys/unix/epoll_zos.go b/tools/vendor/golang.org/x/sys/unix/epoll_zos.go deleted file mode 100644 index cedaf7e02..000000000 --- a/tools/vendor/golang.org/x/sys/unix/epoll_zos.go +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build zos && s390x -// +build zos,s390x - -package unix - -import ( - "sync" -) - -// This file simulates epoll on z/OS using poll. - -// Analogous to epoll_event on Linux. -// TODO(neeilan): Pad is because the Linux kernel expects a 96-bit struct. We never pass this to the kernel; remove? -type EpollEvent struct { - Events uint32 - Fd int32 - Pad int32 -} - -const ( - EPOLLERR = 0x8 - EPOLLHUP = 0x10 - EPOLLIN = 0x1 - EPOLLMSG = 0x400 - EPOLLOUT = 0x4 - EPOLLPRI = 0x2 - EPOLLRDBAND = 0x80 - EPOLLRDNORM = 0x40 - EPOLLWRBAND = 0x200 - EPOLLWRNORM = 0x100 - EPOLL_CTL_ADD = 0x1 - EPOLL_CTL_DEL = 0x2 - EPOLL_CTL_MOD = 0x3 - // The following constants are part of the epoll API, but represent - // currently unsupported functionality on z/OS. - // EPOLL_CLOEXEC = 0x80000 - // EPOLLET = 0x80000000 - // EPOLLONESHOT = 0x40000000 - // EPOLLRDHUP = 0x2000 // Typically used with edge-triggered notis - // EPOLLEXCLUSIVE = 0x10000000 // Exclusive wake-up mode - // EPOLLWAKEUP = 0x20000000 // Relies on Linux's BLOCK_SUSPEND capability -) - -// TODO(neeilan): We can eliminate these epToPoll / pToEpoll calls by using identical mask values for POLL/EPOLL -// constants where possible The lower 16 bits of epoll events (uint32) can fit any system poll event (int16). - -// epToPollEvt converts epoll event field to poll equivalent. -// In epoll, Events is a 32-bit field, while poll uses 16 bits. -func epToPollEvt(events uint32) int16 { - var ep2p = map[uint32]int16{ - EPOLLIN: POLLIN, - EPOLLOUT: POLLOUT, - EPOLLHUP: POLLHUP, - EPOLLPRI: POLLPRI, - EPOLLERR: POLLERR, - } - - var pollEvts int16 = 0 - for epEvt, pEvt := range ep2p { - if (events & epEvt) != 0 { - pollEvts |= pEvt - } - } - - return pollEvts -} - -// pToEpollEvt converts 16 bit poll event bitfields to 32-bit epoll event fields. -func pToEpollEvt(revents int16) uint32 { - var p2ep = map[int16]uint32{ - POLLIN: EPOLLIN, - POLLOUT: EPOLLOUT, - POLLHUP: EPOLLHUP, - POLLPRI: EPOLLPRI, - POLLERR: EPOLLERR, - } - - var epollEvts uint32 = 0 - for pEvt, epEvt := range p2ep { - if (revents & pEvt) != 0 { - epollEvts |= epEvt - } - } - - return epollEvts -} - -// Per-process epoll implementation. -type epollImpl struct { - mu sync.Mutex - epfd2ep map[int]*eventPoll - nextEpfd int -} - -// eventPoll holds a set of file descriptors being watched by the process. A process can have multiple epoll instances. -// On Linux, this is an in-kernel data structure accessed through a fd. -type eventPoll struct { - mu sync.Mutex - fds map[int]*EpollEvent -} - -// epoll impl for this process. -var impl epollImpl = epollImpl{ - epfd2ep: make(map[int]*eventPoll), - nextEpfd: 0, -} - -func (e *epollImpl) epollcreate(size int) (epfd int, err error) { - e.mu.Lock() - defer e.mu.Unlock() - epfd = e.nextEpfd - e.nextEpfd++ - - e.epfd2ep[epfd] = &eventPoll{ - fds: make(map[int]*EpollEvent), - } - return epfd, nil -} - -func (e *epollImpl) epollcreate1(flag int) (fd int, err error) { - return e.epollcreate(4) -} - -func (e *epollImpl) epollctl(epfd int, op int, fd int, event *EpollEvent) (err error) { - e.mu.Lock() - defer e.mu.Unlock() - - ep, ok := e.epfd2ep[epfd] - if !ok { - - return EBADF - } - - switch op { - case EPOLL_CTL_ADD: - // TODO(neeilan): When we make epfds and fds disjoint, detect epoll - // loops here (instances watching each other) and return ELOOP. - if _, ok := ep.fds[fd]; ok { - return EEXIST - } - ep.fds[fd] = event - case EPOLL_CTL_MOD: - if _, ok := ep.fds[fd]; !ok { - return ENOENT - } - ep.fds[fd] = event - case EPOLL_CTL_DEL: - if _, ok := ep.fds[fd]; !ok { - return ENOENT - } - delete(ep.fds, fd) - - } - return nil -} - -// Must be called while holding ep.mu -func (ep *eventPoll) getFds() []int { - fds := make([]int, len(ep.fds)) - for fd := range ep.fds { - fds = append(fds, fd) - } - return fds -} - -func (e *epollImpl) epollwait(epfd int, events []EpollEvent, msec int) (n int, err error) { - e.mu.Lock() // in [rare] case of concurrent epollcreate + epollwait - ep, ok := e.epfd2ep[epfd] - - if !ok { - e.mu.Unlock() - return 0, EBADF - } - - pollfds := make([]PollFd, 4) - for fd, epollevt := range ep.fds { - pollfds = append(pollfds, PollFd{Fd: int32(fd), Events: epToPollEvt(epollevt.Events)}) - } - e.mu.Unlock() - - n, err = Poll(pollfds, msec) - if err != nil { - return n, err - } - - i := 0 - for _, pFd := range pollfds { - if pFd.Revents != 0 { - events[i] = EpollEvent{Fd: pFd.Fd, Events: pToEpollEvt(pFd.Revents)} - i++ - } - - if i == n { - break - } - } - - return n, nil -} - -func EpollCreate(size int) (fd int, err error) { - return impl.epollcreate(size) -} - -func EpollCreate1(flag int) (fd int, err error) { - return impl.epollcreate1(flag) -} - -func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { - return impl.epollctl(epfd, op, fd, event) -} - -// Because EpollWait mutates events, the caller is expected to coordinate -// concurrent access if calling with the same epfd from multiple goroutines. -func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { - return impl.epollwait(epfd, events, msec) -} diff --git a/tools/vendor/golang.org/x/sys/unix/fcntl.go b/tools/vendor/golang.org/x/sys/unix/fcntl.go index e9b991258..6200876fb 100644 --- a/tools/vendor/golang.org/x/sys/unix/fcntl.go +++ b/tools/vendor/golang.org/x/sys/unix/fcntl.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build dragonfly || freebsd || linux || netbsd || openbsd -// +build dragonfly freebsd linux netbsd openbsd +//go:build dragonfly || freebsd || linux || netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go b/tools/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go index 29d44808b..13b4acd5c 100644 --- a/tools/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go +++ b/tools/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build (linux && 386) || (linux && arm) || (linux && mips) || (linux && mipsle) || (linux && ppc) -// +build linux,386 linux,arm linux,mips linux,mipsle linux,ppc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/fdset.go b/tools/vendor/golang.org/x/sys/unix/fdset.go index a8068f94f..9e83d18cd 100644 --- a/tools/vendor/golang.org/x/sys/unix/fdset.go +++ b/tools/vendor/golang.org/x/sys/unix/fdset.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/fstatfs_zos.go b/tools/vendor/golang.org/x/sys/unix/fstatfs_zos.go deleted file mode 100644 index e377cc9f4..000000000 --- a/tools/vendor/golang.org/x/sys/unix/fstatfs_zos.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build zos && s390x -// +build zos,s390x - -package unix - -import ( - "unsafe" -) - -// This file simulates fstatfs on z/OS using fstatvfs and w_getmntent. - -func Fstatfs(fd int, stat *Statfs_t) (err error) { - var stat_v Statvfs_t - err = Fstatvfs(fd, &stat_v) - if err == nil { - // populate stat - stat.Type = 0 - stat.Bsize = stat_v.Bsize - stat.Blocks = stat_v.Blocks - stat.Bfree = stat_v.Bfree - stat.Bavail = stat_v.Bavail - stat.Files = stat_v.Files - stat.Ffree = stat_v.Ffree - stat.Fsid = stat_v.Fsid - stat.Namelen = stat_v.Namemax - stat.Frsize = stat_v.Frsize - stat.Flags = stat_v.Flag - for passn := 0; passn < 5; passn++ { - switch passn { - case 0: - err = tryGetmntent64(stat) - break - case 1: - err = tryGetmntent128(stat) - break - case 2: - err = tryGetmntent256(stat) - break - case 3: - err = tryGetmntent512(stat) - break - case 4: - err = tryGetmntent1024(stat) - break - default: - break - } - //proceed to return if: err is nil (found), err is nonnil but not ERANGE (another error occurred) - if err == nil || err != nil && err != ERANGE { - break - } - } - } - return err -} - -func tryGetmntent64(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [64]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent128(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [128]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent256(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [256]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent512(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [512]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} - -func tryGetmntent1024(stat *Statfs_t) (err error) { - var mnt_ent_buffer struct { - header W_Mnth - filesys_info [1024]W_Mntent - } - var buffer_size int = int(unsafe.Sizeof(mnt_ent_buffer)) - fs_count, err := W_Getmntent((*byte)(unsafe.Pointer(&mnt_ent_buffer)), buffer_size) - if err != nil { - return err - } - err = ERANGE //return ERANGE if no match is found in this batch - for i := 0; i < fs_count; i++ { - if stat.Fsid == uint64(mnt_ent_buffer.filesys_info[i].Dev) { - stat.Type = uint32(mnt_ent_buffer.filesys_info[i].Fstname[0]) - err = nil - break - } - } - return err -} diff --git a/tools/vendor/golang.org/x/sys/unix/gccgo.go b/tools/vendor/golang.org/x/sys/unix/gccgo.go index b06f52d74..aca5721dd 100644 --- a/tools/vendor/golang.org/x/sys/unix/gccgo.go +++ b/tools/vendor/golang.org/x/sys/unix/gccgo.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gccgo && !aix && !hurd -// +build gccgo,!aix,!hurd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/gccgo_c.c b/tools/vendor/golang.org/x/sys/unix/gccgo_c.c index f98a1c542..d468b7b47 100644 --- a/tools/vendor/golang.org/x/sys/unix/gccgo_c.c +++ b/tools/vendor/golang.org/x/sys/unix/gccgo_c.c @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gccgo && !aix && !hurd -// +build gccgo,!aix,!hurd #include #include diff --git a/tools/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go b/tools/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go index e60e49a3d..972d61bd7 100644 --- a/tools/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build gccgo && linux && amd64 -// +build gccgo,linux,amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ifreq_linux.go b/tools/vendor/golang.org/x/sys/unix/ifreq_linux.go index 15721a510..848840ae4 100644 --- a/tools/vendor/golang.org/x/sys/unix/ifreq_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/ifreq_linux.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux -// +build linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ioctl_linux.go b/tools/vendor/golang.org/x/sys/unix/ioctl_linux.go index 0d12c0851..dbe680eab 100644 --- a/tools/vendor/golang.org/x/sys/unix/ioctl_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/ioctl_linux.go @@ -231,3 +231,8 @@ func IoctlLoopGetStatus64(fd int) (*LoopInfo64, error) { func IoctlLoopSetStatus64(fd int, value *LoopInfo64) error { return ioctlPtr(fd, LOOP_SET_STATUS64, unsafe.Pointer(value)) } + +// IoctlLoopConfigure configures all loop device parameters in a single step +func IoctlLoopConfigure(fd int, value *LoopConfig) error { + return ioctlPtr(fd, LOOP_CONFIGURE, unsafe.Pointer(value)) +} diff --git a/tools/vendor/golang.org/x/sys/unix/ioctl_signed.go b/tools/vendor/golang.org/x/sys/unix/ioctl_signed.go index 7def9580e..5b0759bd8 100644 --- a/tools/vendor/golang.org/x/sys/unix/ioctl_signed.go +++ b/tools/vendor/golang.org/x/sys/unix/ioctl_signed.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || solaris -// +build aix solaris package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ioctl_unsigned.go b/tools/vendor/golang.org/x/sys/unix/ioctl_unsigned.go index 649913d1e..20f470b9d 100644 --- a/tools/vendor/golang.org/x/sys/unix/ioctl_unsigned.go +++ b/tools/vendor/golang.org/x/sys/unix/ioctl_unsigned.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build darwin || dragonfly || freebsd || hurd || linux || netbsd || openbsd -// +build darwin dragonfly freebsd hurd linux netbsd openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ioctl_zos.go b/tools/vendor/golang.org/x/sys/unix/ioctl_zos.go index cdc21bf76..c8b2a750f 100644 --- a/tools/vendor/golang.org/x/sys/unix/ioctl_zos.go +++ b/tools/vendor/golang.org/x/sys/unix/ioctl_zos.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build zos && s390x -// +build zos,s390x package unix diff --git a/tools/vendor/golang.org/x/sys/unix/mkerrors.sh b/tools/vendor/golang.org/x/sys/unix/mkerrors.sh index 47fa6a7eb..d07dd09eb 100644 --- a/tools/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/tools/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -58,6 +58,7 @@ includes_Darwin=' #define _DARWIN_USE_64_BIT_INODE #define __APPLE_USE_RFC_3542 #include +#include #include #include #include @@ -248,6 +249,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -262,6 +264,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -283,10 +286,6 @@ struct ltchars { #include #endif -#ifndef MSG_FASTOPEN -#define MSG_FASTOPEN 0x20000000 -#endif - #ifndef PTRACE_GETREGS #define PTRACE_GETREGS 0xc #endif @@ -295,14 +294,6 @@ struct ltchars { #define PTRACE_SETREGS 0xd #endif -#ifndef SOL_NETLINK -#define SOL_NETLINK 270 -#endif - -#ifndef SOL_SMC -#define SOL_SMC 286 -#endif - #ifdef SOL_BLUETOOTH // SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h // but it is already in bluetooth_linux.go @@ -319,10 +310,23 @@ struct ltchars { #undef TIPC_WAIT_FOREVER #define TIPC_WAIT_FOREVER 0xffffffff -// Copied from linux/l2tp.h -// Including linux/l2tp.h here causes conflicts between linux/in.h -// and netinet/in.h included via net/route.h above. -#define IPPROTO_L2TP 115 +// Copied from linux/netfilter/nf_nat.h +// Including linux/netfilter/nf_nat.h here causes conflicts between linux/in.h +// and netinet/in.h. +#define NF_NAT_RANGE_MAP_IPS (1 << 0) +#define NF_NAT_RANGE_PROTO_SPECIFIED (1 << 1) +#define NF_NAT_RANGE_PROTO_RANDOM (1 << 2) +#define NF_NAT_RANGE_PERSISTENT (1 << 3) +#define NF_NAT_RANGE_PROTO_RANDOM_FULLY (1 << 4) +#define NF_NAT_RANGE_PROTO_OFFSET (1 << 5) +#define NF_NAT_RANGE_NETMAP (1 << 6) +#define NF_NAT_RANGE_PROTO_RANDOM_ALL \ + (NF_NAT_RANGE_PROTO_RANDOM | NF_NAT_RANGE_PROTO_RANDOM_FULLY) +#define NF_NAT_RANGE_MASK \ + (NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED | \ + NF_NAT_RANGE_PROTO_RANDOM | NF_NAT_RANGE_PERSISTENT | \ + NF_NAT_RANGE_PROTO_RANDOM_FULLY | NF_NAT_RANGE_PROTO_OFFSET | \ + NF_NAT_RANGE_NETMAP) // Copied from linux/hid.h. // Keep in sync with the size of the referenced fields. @@ -519,6 +523,7 @@ ccflags="$@" $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^LO_(KEY|NAME)_SIZE$/ || $2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ || + $2 == "LOOP_CONFIGURE" || $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$/ || @@ -546,6 +551,7 @@ ccflags="$@" $2 !~ "NLA_TYPE_MASK" && $2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ || + $2 ~ /^SOCK_|SK_DIAG_|SKNLGRP_$/ || $2 ~ /^FIORDCHK$/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || @@ -560,7 +566,7 @@ ccflags="$@" $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || $2 ~ /^CLONE_[A-Z_]+/ || - $2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ && + $2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+|BPF_F_LINK)$/ && $2 ~ /^(BPF|DLT)_/ || $2 ~ /^AUDIT_/ || $2 ~ /^(CLOCK|TIMER)_/ || @@ -581,7 +587,7 @@ ccflags="$@" $2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ || $2 ~ /^KEYCTL_/ || $2 ~ /^PERF_/ || - $2 ~ /^SECCOMP_MODE_/ || + $2 ~ /^SECCOMP_/ || $2 ~ /^SEEK_/ || $2 ~ /^SCHED_/ || $2 ~ /^SPLICE_/ || @@ -602,6 +608,9 @@ ccflags="$@" $2 ~ /^FSOPT_/ || $2 ~ /^WDIO[CFS]_/ || $2 ~ /^NFN/ || + $2 !~ /^NFT_META_IIFTYPE/ && + $2 ~ /^NFT_/ || + $2 ~ /^NF_NAT_/ || $2 ~ /^XDP_/ || $2 ~ /^RWF_/ || $2 ~ /^(HDIO|WIN|SMART)_/ || @@ -663,7 +672,6 @@ echo '// mkerrors.sh' "$@" echo '// Code generated by the command above; see README.md. DO NOT EDIT.' echo echo "//go:build ${GOARCH} && ${GOOS}" -echo "// +build ${GOARCH},${GOOS}" echo go tool cgo -godefs -- "$@" _const.go >_error.out cat _error.out | grep -vf _error.grep | grep -vf _signal.grep diff --git a/tools/vendor/golang.org/x/sys/unix/mmap_nomremap.go b/tools/vendor/golang.org/x/sys/unix/mmap_nomremap.go index ca0513632..7f602ffd2 100644 --- a/tools/vendor/golang.org/x/sys/unix/mmap_nomremap.go +++ b/tools/vendor/golang.org/x/sys/unix/mmap_nomremap.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build aix || darwin || dragonfly || freebsd || openbsd || solaris -// +build aix darwin dragonfly freebsd openbsd solaris +//go:build aix || darwin || dragonfly || freebsd || openbsd || solaris || zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/mremap.go b/tools/vendor/golang.org/x/sys/unix/mremap.go index fa93d0aa9..3a5e776f8 100644 --- a/tools/vendor/golang.org/x/sys/unix/mremap.go +++ b/tools/vendor/golang.org/x/sys/unix/mremap.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux || netbsd -// +build linux netbsd package unix @@ -51,3 +50,8 @@ func (m *mremapMmapper) Mremap(oldData []byte, newLength int, flags int) (data [ func Mremap(oldData []byte, newLength int, flags int) (data []byte, err error) { return mapper.Mremap(oldData, newLength, flags) } + +func MremapPtr(oldAddr unsafe.Pointer, oldSize uintptr, newAddr unsafe.Pointer, newSize uintptr, flags int) (ret unsafe.Pointer, err error) { + xaddr, err := mapper.mremap(uintptr(oldAddr), oldSize, newSize, flags, uintptr(newAddr)) + return unsafe.Pointer(xaddr), err +} diff --git a/tools/vendor/golang.org/x/sys/unix/pagesize_unix.go b/tools/vendor/golang.org/x/sys/unix/pagesize_unix.go index 53f1b4c5b..0482408d7 100644 --- a/tools/vendor/golang.org/x/sys/unix/pagesize_unix.go +++ b/tools/vendor/golang.org/x/sys/unix/pagesize_unix.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos // For Unix, get the pagesize from the runtime. diff --git a/tools/vendor/golang.org/x/sys/unix/pledge_openbsd.go b/tools/vendor/golang.org/x/sys/unix/pledge_openbsd.go index eb48294b2..6a09af53e 100644 --- a/tools/vendor/golang.org/x/sys/unix/pledge_openbsd.go +++ b/tools/vendor/golang.org/x/sys/unix/pledge_openbsd.go @@ -8,54 +8,31 @@ import ( "errors" "fmt" "strconv" - "syscall" - "unsafe" ) // Pledge implements the pledge syscall. // -// The pledge syscall does not accept execpromises on OpenBSD releases -// before 6.3. -// -// execpromises must be empty when Pledge is called on OpenBSD -// releases predating 6.3, otherwise an error will be returned. +// This changes both the promises and execpromises; use PledgePromises or +// PledgeExecpromises to only change the promises or execpromises +// respectively. // // For more information see pledge(2). func Pledge(promises, execpromises string) error { - maj, min, err := majmin() - if err != nil { + if err := pledgeAvailable(); err != nil { return err } - err = pledgeAvailable(maj, min, execpromises) + pptr, err := BytePtrFromString(promises) if err != nil { return err } - pptr, err := syscall.BytePtrFromString(promises) + exptr, err := BytePtrFromString(execpromises) if err != nil { return err } - // This variable will hold either a nil unsafe.Pointer or - // an unsafe.Pointer to a string (execpromises). - var expr unsafe.Pointer - - // If we're running on OpenBSD > 6.2, pass execpromises to the syscall. - if maj > 6 || (maj == 6 && min > 2) { - exptr, err := syscall.BytePtrFromString(execpromises) - if err != nil { - return err - } - expr = unsafe.Pointer(exptr) - } - - _, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(unsafe.Pointer(pptr)), uintptr(expr), 0) - if e != 0 { - return e - } - - return nil + return pledge(pptr, exptr) } // PledgePromises implements the pledge syscall. @@ -64,30 +41,16 @@ func Pledge(promises, execpromises string) error { // // For more information see pledge(2). func PledgePromises(promises string) error { - maj, min, err := majmin() - if err != nil { - return err - } - - err = pledgeAvailable(maj, min, "") - if err != nil { + if err := pledgeAvailable(); err != nil { return err } - // This variable holds the execpromises and is always nil. - var expr unsafe.Pointer - - pptr, err := syscall.BytePtrFromString(promises) + pptr, err := BytePtrFromString(promises) if err != nil { return err } - _, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(unsafe.Pointer(pptr)), uintptr(expr), 0) - if e != 0 { - return e - } - - return nil + return pledge(pptr, nil) } // PledgeExecpromises implements the pledge syscall. @@ -96,30 +59,16 @@ func PledgePromises(promises string) error { // // For more information see pledge(2). func PledgeExecpromises(execpromises string) error { - maj, min, err := majmin() - if err != nil { + if err := pledgeAvailable(); err != nil { return err } - err = pledgeAvailable(maj, min, execpromises) + exptr, err := BytePtrFromString(execpromises) if err != nil { return err } - // This variable holds the promises and is always nil. - var pptr unsafe.Pointer - - exptr, err := syscall.BytePtrFromString(execpromises) - if err != nil { - return err - } - - _, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(pptr), uintptr(unsafe.Pointer(exptr)), 0) - if e != 0 { - return e - } - - return nil + return pledge(nil, exptr) } // majmin returns major and minor version number for an OpenBSD system. @@ -147,16 +96,15 @@ func majmin() (major int, minor int, err error) { // pledgeAvailable checks for availability of the pledge(2) syscall // based on the running OpenBSD version. -func pledgeAvailable(maj, min int, execpromises string) error { - // If OpenBSD <= 5.9, pledge is not available. - if (maj == 5 && min != 9) || maj < 5 { - return fmt.Errorf("pledge syscall is not available on OpenBSD %d.%d", maj, min) +func pledgeAvailable() error { + maj, min, err := majmin() + if err != nil { + return err } - // If OpenBSD <= 6.2 and execpromises is not empty, - // return an error - execpromises is not available before 6.3 - if (maj < 6 || (maj == 6 && min <= 2)) && execpromises != "" { - return fmt.Errorf("cannot use execpromises on OpenBSD %d.%d", maj, min) + // Require OpenBSD 6.4 as a minimum. + if maj < 6 || (maj == 6 && min <= 3) { + return fmt.Errorf("cannot call Pledge on OpenBSD %d.%d", maj, min) } return nil diff --git a/tools/vendor/golang.org/x/sys/unix/ptrace_darwin.go b/tools/vendor/golang.org/x/sys/unix/ptrace_darwin.go index 463c3eff7..3f0975f3d 100644 --- a/tools/vendor/golang.org/x/sys/unix/ptrace_darwin.go +++ b/tools/vendor/golang.org/x/sys/unix/ptrace_darwin.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build darwin && !ios -// +build darwin,!ios package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ptrace_ios.go b/tools/vendor/golang.org/x/sys/unix/ptrace_ios.go index ed0509a01..a4d35db5d 100644 --- a/tools/vendor/golang.org/x/sys/unix/ptrace_ios.go +++ b/tools/vendor/golang.org/x/sys/unix/ptrace_ios.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build ios -// +build ios package unix diff --git a/tools/vendor/golang.org/x/sys/unix/race.go b/tools/vendor/golang.org/x/sys/unix/race.go index 6f6c5fec5..714d2aae7 100644 --- a/tools/vendor/golang.org/x/sys/unix/race.go +++ b/tools/vendor/golang.org/x/sys/unix/race.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build (darwin && race) || (linux && race) || (freebsd && race) -// +build darwin,race linux,race freebsd,race package unix diff --git a/tools/vendor/golang.org/x/sys/unix/race0.go b/tools/vendor/golang.org/x/sys/unix/race0.go index 706e1322a..4a9f6634c 100644 --- a/tools/vendor/golang.org/x/sys/unix/race0.go +++ b/tools/vendor/golang.org/x/sys/unix/race0.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || (darwin && !race) || (linux && !race) || (freebsd && !race) || netbsd || openbsd || solaris || dragonfly || zos -// +build aix darwin,!race linux,!race freebsd,!race netbsd openbsd solaris dragonfly zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/readdirent_getdents.go b/tools/vendor/golang.org/x/sys/unix/readdirent_getdents.go index 4d6257569..dbd2b6ccb 100644 --- a/tools/vendor/golang.org/x/sys/unix/readdirent_getdents.go +++ b/tools/vendor/golang.org/x/sys/unix/readdirent_getdents.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || dragonfly || freebsd || linux || netbsd || openbsd -// +build aix dragonfly freebsd linux netbsd openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go b/tools/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go index 2a4ba47c4..b903c0060 100644 --- a/tools/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go +++ b/tools/vendor/golang.org/x/sys/unix/readdirent_getdirentries.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build darwin -// +build darwin +//go:build darwin || zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix.go b/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix.go index 3865943f6..c3a62dbb1 100644 --- a/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix.go +++ b/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos // Socket control messages diff --git a/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go b/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go index 0840fe4a5..4a1eab37e 100644 --- a/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go +++ b/tools/vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin freebsd linux netbsd openbsd solaris zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/sockcmsg_zos.go b/tools/vendor/golang.org/x/sys/unix/sockcmsg_zos.go new file mode 100644 index 000000000..3e53dbc02 --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/sockcmsg_zos.go @@ -0,0 +1,58 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Socket control messages + +package unix + +import "unsafe" + +// UnixCredentials encodes credentials into a socket control message +// for sending to another process. This can be used for +// authentication. +func UnixCredentials(ucred *Ucred) []byte { + b := make([]byte, CmsgSpace(SizeofUcred)) + h := (*Cmsghdr)(unsafe.Pointer(&b[0])) + h.Level = SOL_SOCKET + h.Type = SCM_CREDENTIALS + h.SetLen(CmsgLen(SizeofUcred)) + *(*Ucred)(h.data(0)) = *ucred + return b +} + +// ParseUnixCredentials decodes a socket control message that contains +// credentials in a Ucred structure. To receive such a message, the +// SO_PASSCRED option must be enabled on the socket. +func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error) { + if m.Header.Level != SOL_SOCKET { + return nil, EINVAL + } + if m.Header.Type != SCM_CREDENTIALS { + return nil, EINVAL + } + ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0])) + return &ucred, nil +} + +// PktInfo4 encodes Inet4Pktinfo into a socket control message of type IP_PKTINFO. +func PktInfo4(info *Inet4Pktinfo) []byte { + b := make([]byte, CmsgSpace(SizeofInet4Pktinfo)) + h := (*Cmsghdr)(unsafe.Pointer(&b[0])) + h.Level = SOL_IP + h.Type = IP_PKTINFO + h.SetLen(CmsgLen(SizeofInet4Pktinfo)) + *(*Inet4Pktinfo)(h.data(0)) = *info + return b +} + +// PktInfo6 encodes Inet6Pktinfo into a socket control message of type IPV6_PKTINFO. +func PktInfo6(info *Inet6Pktinfo) []byte { + b := make([]byte, CmsgSpace(SizeofInet6Pktinfo)) + h := (*Cmsghdr)(unsafe.Pointer(&b[0])) + h.Level = SOL_IPV6 + h.Type = IPV6_PKTINFO + h.SetLen(CmsgLen(SizeofInet6Pktinfo)) + *(*Inet6Pktinfo)(h.data(0)) = *info + return b +} diff --git a/tools/vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s b/tools/vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s new file mode 100644 index 000000000..3c4f33cb6 --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s @@ -0,0 +1,75 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build zos && s390x && gc + +#include "textflag.h" + +// provide the address of function variable to be fixed up. + +TEXT ·getPipe2Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Pipe2(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_FlockAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Flock(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_GetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Getxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_NanosleepAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Nanosleep(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_SetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Setxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_Wait4Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Wait4(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_MountAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mount(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_UnmountAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Unmount(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_UtimesNanoAtAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·UtimesNanoAt(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_UtimesNanoAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·UtimesNano(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_MkfifoatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mkfifoat(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_ChtagAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Chtag(SB), R8 + MOVD R8, ret+0(FP) + RET + +TEXT ·get_ReadlinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Readlinkat(SB), R8 + MOVD R8, ret+0(FP) + RET + diff --git a/tools/vendor/golang.org/x/sys/unix/syscall.go b/tools/vendor/golang.org/x/sys/unix/syscall.go index 63e8c8383..5ea74da98 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos // Package unix contains an interface to the low-level operating system // primitives. OS details vary depending on the underlying system, and diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_aix.go b/tools/vendor/golang.org/x/sys/unix/syscall_aix.go index e94e6cdac..67ce6cef2 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_aix.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_aix.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix -// +build aix // Aix system calls. // This file is compiled as ordinary Go code, @@ -107,7 +106,8 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { if n > 0 { sl += _Socklen(n) + 1 } - if sa.raw.Path[0] == '@' { + if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) { + // Check sl > 3 so we don't change unnamed socket behavior. sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc.go b/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc.go index f2871fa95..1fdaa4760 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix && ppc -// +build aix,ppc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go b/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go index 75718ec0f..c87f9a9f4 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix && ppc64 -// +build aix,ppc64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_bsd.go b/tools/vendor/golang.org/x/sys/unix/syscall_bsd.go index 4217de518..a00c3e545 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build darwin || dragonfly || freebsd || netbsd || openbsd -// +build darwin dragonfly freebsd netbsd openbsd // BSD system call wrappers shared by *BSD based systems // including OS X (Darwin) and FreeBSD. Like the other @@ -317,7 +316,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { if err != nil { return "", err } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_darwin.go b/tools/vendor/golang.org/x/sys/unix/syscall_darwin.go index 59542a897..2d15200ad 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -402,6 +402,18 @@ func IoctlSetIfreqMTU(fd int, ifreq *IfreqMTU) error { return ioctlPtr(fd, SIOCSIFMTU, unsafe.Pointer(ifreq)) } +//sys renamexNp(from string, to string, flag uint32) (err error) + +func RenamexNp(from string, to string, flag uint32) (err error) { + return renamexNp(from, to, flag) +} + +//sys renameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) + +func RenameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) { + return renameatxNp(fromfd, from, tofd, to, flag) +} + //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS_SYSCTL func Uname(uname *Utsname) error { @@ -542,6 +554,18 @@ func SysctlKinfoProcSlice(name string, args ...int) ([]KinfoProc, error) { } } +//sys pthread_chdir_np(path string) (err error) + +func PthreadChdir(path string) (err error) { + return pthread_chdir_np(path) +} + +//sys pthread_fchdir_np(fd int) (err error) + +func PthreadFchdir(fd int) (err error) { + return pthread_fchdir_np(fd) +} + //sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go b/tools/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go index b37310ce9..0eaecf5fc 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && darwin -// +build amd64,darwin package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go b/tools/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go index d51ec9963..f36c6707c 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm64 && darwin -// +build arm64,darwin package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go b/tools/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go index 53c96641f..2f0fa76e4 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build darwin && go1.12 -// +build darwin,go1.12 +//go:build darwin package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go b/tools/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go index 4e2d32120..14bab6b2d 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && dragonfly -// +build amd64,dragonfly package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd.go index 64d1bb4db..2b57e0f73 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -13,6 +13,7 @@ package unix import ( + "errors" "sync" "unsafe" ) @@ -169,25 +170,26 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { func Uname(uname *Utsname) error { mib := []_C_int{CTL_KERN, KERN_OSTYPE} n := unsafe.Sizeof(uname.Sysname) - if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + // Suppress ENOMEM errors to be compatible with the C library __xuname() implementation. + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } mib = []_C_int{CTL_KERN, KERN_HOSTNAME} n = unsafe.Sizeof(uname.Nodename) - if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } mib = []_C_int{CTL_KERN, KERN_OSRELEASE} n = unsafe.Sizeof(uname.Release) - if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } mib = []_C_int{CTL_KERN, KERN_VERSION} n = unsafe.Sizeof(uname.Version) - if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } @@ -205,7 +207,7 @@ func Uname(uname *Utsname) error { mib = []_C_int{CTL_HW, HW_MACHINE} n = unsafe.Sizeof(uname.Machine) - if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil && !errors.Is(err, ENOMEM) { return err } diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go index b8da51004..3967bca77 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build 386 && freebsd -// +build 386,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go index 47155c483..eff19ada2 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && freebsd -// +build amd64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go index 08932093f..4f24b517a 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm && freebsd -// +build arm,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go index d151a0d0e..ac30759ec 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm64 && freebsd -// +build arm64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go index d5cd64b37..aab725ca7 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build riscv64 && freebsd -// +build riscv64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_hurd.go b/tools/vendor/golang.org/x/sys/unix/syscall_hurd.go index 381fd4673..ba46651f8 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_hurd.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_hurd.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build hurd -// +build hurd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_hurd_386.go b/tools/vendor/golang.org/x/sys/unix/syscall_hurd_386.go index 7cf54a3e4..df89f9e6b 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_hurd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_hurd_386.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build 386 && hurd -// +build 386,hurd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_illumos.go b/tools/vendor/golang.org/x/sys/unix/syscall_illumos.go index 87db5a6a8..a863f7052 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_illumos.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_illumos.go @@ -5,7 +5,6 @@ // illumos system calls not present on Solaris. //go:build amd64 && illumos -// +build amd64,illumos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux.go index fb4e50224..3f1d3d4cb 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -61,15 +61,23 @@ func FanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname string) ( } //sys fchmodat(dirfd int, path string, mode uint32) (err error) - -func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { - // Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior - // and check the flags. Otherwise the mode would be applied to the symlink - // destination which is not what the user expects. - if flags&^AT_SYMLINK_NOFOLLOW != 0 { - return EINVAL - } else if flags&AT_SYMLINK_NOFOLLOW != 0 { - return EOPNOTSUPP +//sys fchmodat2(dirfd int, path string, mode uint32, flags int) (err error) + +func Fchmodat(dirfd int, path string, mode uint32, flags int) error { + // Linux fchmodat doesn't support the flags parameter, but fchmodat2 does. + // Try fchmodat2 if flags are specified. + if flags != 0 { + err := fchmodat2(dirfd, path, mode, flags) + if err == ENOSYS { + // fchmodat2 isn't available. If the flags are known to be valid, + // return EOPNOTSUPP to indicate that fchmodat doesn't support them. + if flags&^(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 { + return EINVAL + } else if flags&(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 { + return EOPNOTSUPP + } + } + return err } return fchmodat(dirfd, path, mode) } @@ -417,7 +425,8 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { if n > 0 { sl += _Socklen(n) + 1 } - if sa.raw.Path[0] == '@' { + if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) { + // Check sl > 3 so we don't change unnamed socket behavior. sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- @@ -1301,7 +1310,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { return "", err } } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } func GetsockoptTpacketStats(fd, level, opt int) (*TpacketStats, error) { @@ -1840,6 +1849,105 @@ func Dup2(oldfd, newfd int) error { //sys Fsmount(fd int, flags int, mountAttrs int) (fsfd int, err error) //sys Fsopen(fsName string, flags int) (fd int, err error) //sys Fspick(dirfd int, pathName string, flags int) (fd int, err error) + +//sys fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) + +func fsconfigCommon(fd int, cmd uint, key string, value *byte, aux int) (err error) { + var keyp *byte + if keyp, err = BytePtrFromString(key); err != nil { + return + } + return fsconfig(fd, cmd, keyp, value, aux) +} + +// FsconfigSetFlag is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_FLAG. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +func FsconfigSetFlag(fd int, key string) (err error) { + return fsconfigCommon(fd, FSCONFIG_SET_FLAG, key, nil, 0) +} + +// FsconfigSetString is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_STRING. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// value is the parameter value to set. +func FsconfigSetString(fd int, key string, value string) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(value); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_STRING, key, valuep, 0) +} + +// FsconfigSetBinary is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_BINARY. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// value is the parameter value to set. +func FsconfigSetBinary(fd int, key string, value []byte) (err error) { + if len(value) == 0 { + return EINVAL + } + return fsconfigCommon(fd, FSCONFIG_SET_BINARY, key, &value[0], len(value)) +} + +// FsconfigSetPath is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_PATH. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// path is a non-empty path for specified key. +// atfd is a file descriptor at which to start lookup from or AT_FDCWD. +func FsconfigSetPath(fd int, key string, path string, atfd int) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(path); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_PATH, key, valuep, atfd) +} + +// FsconfigSetPathEmpty is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_PATH_EMPTY. The same as +// FconfigSetPath but with AT_PATH_EMPTY implied. +func FsconfigSetPathEmpty(fd int, key string, path string, atfd int) (err error) { + var valuep *byte + if valuep, err = BytePtrFromString(path); err != nil { + return + } + return fsconfigCommon(fd, FSCONFIG_SET_PATH_EMPTY, key, valuep, atfd) +} + +// FsconfigSetFd is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_SET_FD. +// +// fd is the filesystem context to act upon. +// key the parameter key to set. +// value is a file descriptor to be assigned to specified key. +func FsconfigSetFd(fd int, key string, value int) (err error) { + return fsconfigCommon(fd, FSCONFIG_SET_FD, key, nil, value) +} + +// FsconfigCreate is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_CMD_CREATE. +// +// fd is the filesystem context to act upon. +func FsconfigCreate(fd int) (err error) { + return fsconfig(fd, FSCONFIG_CMD_CREATE, nil, nil, 0) +} + +// FsconfigReconfigure is equivalent to fsconfig(2) called +// with cmd == FSCONFIG_CMD_RECONFIGURE. +// +// fd is the filesystem context to act upon. +func FsconfigReconfigure(fd int) (err error) { + return fsconfig(fd, FSCONFIG_CMD_RECONFIGURE, nil, nil, 0) +} + //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 //sysnb Getpgid(pid int) (pgid int, err error) @@ -2482,3 +2590,6 @@ func SchedGetAttr(pid int, flags uint) (*SchedAttr, error) { } return attr, nil } + +//sys Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) (err error) +//sys Mseal(b []byte, flags uint) (err error) diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_386.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_386.go index c7d9945ea..506dafa7b 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_386.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_386.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build 386 && linux -// +build 386,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_alarm.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_alarm.go index 08086ac6a..38d55641b 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_alarm.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_alarm.go @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (386 || amd64 || mips || mipsle || mips64 || mipsle || ppc64 || ppc64le || ppc || s390x || sparc64) -// +build linux -// +build 386 amd64 mips mipsle mips64 mipsle ppc64 ppc64le ppc s390x sparc64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go index 70601ce36..d557cf8de 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && linux -// +build amd64,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go index 8b0f0f3aa..facdb83b2 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && linux && gc -// +build amd64,linux,gc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm.go index da2986415..cd2dd797f 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm && linux -// +build arm,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index f5266689a..cf2ee6c75 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm64 && linux -// +build arm64,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc.go index 2b1168d7d..ffc4c2b63 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && gc -// +build linux,gc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go index 9843fb489..9ebfdcf44 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && gc && 386 -// +build linux,gc,386 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go index a6008fccd..5f2b57c4c 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm && gc && linux -// +build arm,gc,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go index 7740af242..d1a3ad826 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && gccgo && 386 -// +build linux,gccgo,386 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go index e16a12299..f2f67423e 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && gccgo && arm -// +build linux,gccgo,arm package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go index f6ab02ec1..3d0e98451 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_loong64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build loong64 && linux -// +build loong64,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go index 93fe59d25..70963a95a 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (mips64 || mips64le) -// +build linux -// +build mips64 mips64le package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go index aae7f0ffd..c218ebd28 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (mips || mipsle) -// +build linux -// +build mips mipsle package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go index 66eff19a3..e6c48500c 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && ppc -// +build linux,ppc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go index 806aa2574..7286a9aa8 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (ppc64 || ppc64le) -// +build linux -// +build ppc64 ppc64le package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go index 5e6ceee12..6f5a28894 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build riscv64 && linux -// +build riscv64,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go index 2f89e8f5d..66f31210d 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build s390x && linux -// +build s390x,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/tools/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go index 7ca064ae7..11d1f1698 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build sparc64 && linux -// +build sparc64,linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go index 5199d282f..7a5eb5743 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_386.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build 386 && netbsd -// +build 386,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go index 70a9c52e9..62d8957ae 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && netbsd -// +build amd64,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go index 3eb5942f9..ce6a06885 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm && netbsd -// +build arm,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go index fc6ccfd81..d46d689d1 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm64 && netbsd -// +build arm64,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd.go index 6f34479b5..b86ded549 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd.go @@ -137,18 +137,13 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e } func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { - var _p0 unsafe.Pointer + var bufptr *Statfs_t var bufsize uintptr if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) + bufptr = &buf[0] bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf)) } - r0, _, e1 := Syscall(SYS_GETFSSTAT, uintptr(_p0), bufsize, uintptr(flags)) - n = int(r0) - if e1 != 0 { - err = e1 - } - return + return getfsstat(bufptr, bufsize, flags) } //sysnb getresuid(ruid *_C_int, euid *_C_int, suid *_C_int) @@ -171,6 +166,20 @@ func Getresgid() (rgid, egid, sgid int) { //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL +//sys fcntl(fd int, cmd int, arg int) (n int, err error) +//sys fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) = SYS_FCNTL + +// FcntlInt performs a fcntl syscall on fd with the provided command and argument. +func FcntlInt(fd uintptr, cmd, arg int) (int, error) { + return fcntl(int(fd), cmd, arg) +} + +// FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. +func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { + _, err := fcntlPtr(int(fd), cmd, unsafe.Pointer(lk)) + return err +} + //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { @@ -284,6 +293,7 @@ func Uname(uname *Utsname) error { //sys Mkfifoat(dirfd int, path string, mode uint32) (err error) //sys Mknod(path string, mode uint32, dev int) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) +//sys Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Open(path string, mode int, perm uint32) (fd int, err error) //sys Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) @@ -326,4 +336,7 @@ func Uname(uname *Utsname) error { //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) +//sys getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) +//sys pledge(promises *byte, execpromises *byte) (err error) +//sys unveil(path *byte, flags *byte) (err error) diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go index 6baabcdcb..9ddc89f4f 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_386.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build 386 && openbsd -// +build 386,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go index bab25360e..70a3c96ee 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && openbsd -// +build amd64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go index 8eed3c4d4..265caa87f 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm && openbsd -// +build arm,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go index 483dde99d..ac4fda171 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build arm64 && openbsd -// +build arm64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go index 04aa43f41..0a451e6dd 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build openbsd -// +build openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_ppc64.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_ppc64.go index c2796139c..30a308cbb 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_ppc64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build ppc64 && openbsd -// +build ppc64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_riscv64.go index 23199a7ff..ea954330f 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_riscv64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build riscv64 && openbsd -// +build riscv64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_solaris.go b/tools/vendor/golang.org/x/sys/unix/syscall_solaris.go index b99cfa134..21974af06 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -128,7 +128,8 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { if n > 0 { sl += _Socklen(n) + 1 } - if sa.raw.Path[0] == '@' { + if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) { + // Check sl > 3 so we don't change unnamed socket behavior. sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- @@ -157,7 +158,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { if err != nil { return "", err } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } const ImplementsGetwd = true diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go b/tools/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go index 0bd25ef81..e02d8ceae 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build amd64 && solaris -// +build amd64,solaris package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_unix.go b/tools/vendor/golang.org/x/sys/unix/syscall_unix.go index f6eda2705..4e92e5aa4 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris package unix @@ -155,6 +154,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) +} + func Read(fd int, p []byte) (n int, err error) { n, err = read(fd, p) if raceenabled { diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc.go b/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc.go index b6919ca58..05c95bccf 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc.go @@ -3,8 +3,6 @@ // license that can be found in the LICENSE file. //go:build (darwin || dragonfly || freebsd || (linux && !ppc64 && !ppc64le) || netbsd || openbsd || solaris) && gc -// +build darwin dragonfly freebsd linux,!ppc64,!ppc64le netbsd openbsd solaris -// +build gc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go b/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go index f6f707acf..23f39b7af 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go @@ -3,9 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux && (ppc64le || ppc64) && gc -// +build linux -// +build ppc64le ppc64 -// +build gc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/tools/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index 4596d041c..312ae6ac1 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -3,13 +3,22 @@ // license that can be found in the LICENSE file. //go:build zos && s390x -// +build zos,s390x + +// Many of the following syscalls are not available on all versions of z/OS. +// Some missing calls have legacy implementations/simulations but others +// will be missing completely. To achieve consistent failing behaviour on +// legacy systems, we first test the function pointer via a safeloading +// mechanism to see if the function exists on a given system. Then execution +// is branched to either continue the function call, or return an error. package unix import ( "bytes" "fmt" + "os" + "reflect" + "regexp" "runtime" "sort" "strings" @@ -18,17 +27,205 @@ import ( "unsafe" ) +//go:noescape +func initZosLibVec() + +//go:noescape +func GetZosLibVec() uintptr + +func init() { + initZosLibVec() + r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACE\x00"))[0]))) + if r0 != 0 { + n, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) + ZosTraceLevel = int(n) + r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACEFD\x00"))[0]))) + if r0 != 0 { + fd, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) + f := os.NewFile(fd, "zostracefile") + if f != nil { + ZosTracefile = f + } + } + + } +} + +//go:noescape +func CallLeFuncWithErr(funcdesc uintptr, parms ...uintptr) (ret, errno2 uintptr, err Errno) + +//go:noescape +func CallLeFuncWithPtrReturn(funcdesc uintptr, parms ...uintptr) (ret, errno2 uintptr, err Errno) + +// ------------------------------- +// pointer validity test +// good pointer returns 0 +// bad pointer returns 1 +// +//go:nosplit +func ptrtest(uintptr) uint64 + +// Load memory at ptr location with error handling if the location is invalid +// +//go:noescape +func safeload(ptr uintptr) (value uintptr, error uintptr) + const ( - O_CLOEXEC = 0 // Dummy value (not supported). - AF_LOCAL = AF_UNIX // AF_LOCAL is an alias for AF_UNIX + entrypointLocationOffset = 8 // From function descriptor + + xplinkEyecatcher = 0x00c300c500c500f1 // ".C.E.E.1" + eyecatcherOffset = 16 // From function entrypoint (negative) + ppa1LocationOffset = 8 // From function entrypoint (negative) + + nameLenOffset = 0x14 // From PPA1 start + nameOffset = 0x16 // From PPA1 start ) -func syscall_syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) -func syscall_rawsyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) -func syscall_syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) -func syscall_rawsyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) -func syscall_syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err Errno) -func syscall_rawsyscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err Errno) +func getPpaOffset(funcptr uintptr) int64 { + entrypoint, err := safeload(funcptr + entrypointLocationOffset) + if err != 0 { + return -1 + } + + // XPLink functions have ".C.E.E.1" as the first 8 bytes (EBCDIC) + val, err := safeload(entrypoint - eyecatcherOffset) + if err != 0 { + return -1 + } + if val != xplinkEyecatcher { + return -1 + } + + ppaoff, err := safeload(entrypoint - ppa1LocationOffset) + if err != 0 { + return -1 + } + + ppaoff >>= 32 + return int64(ppaoff) +} + +//------------------------------- +// function descriptor pointer validity test +// good pointer returns 0 +// bad pointer returns 1 + +// TODO: currently mksyscall_zos_s390x.go generate empty string for funcName +// have correct funcName pass to the funcptrtest function +func funcptrtest(funcptr uintptr, funcName string) uint64 { + entrypoint, err := safeload(funcptr + entrypointLocationOffset) + if err != 0 { + return 1 + } + + ppaoff := getPpaOffset(funcptr) + if ppaoff == -1 { + return 1 + } + + // PPA1 offset value is from the start of the entire function block, not the entrypoint + ppa1 := (entrypoint - eyecatcherOffset) + uintptr(ppaoff) + + nameLen, err := safeload(ppa1 + nameLenOffset) + if err != 0 { + return 1 + } + + nameLen >>= 48 + if nameLen > 128 { + return 1 + } + + // no function name input to argument end here + if funcName == "" { + return 0 + } + + var funcname [128]byte + for i := 0; i < int(nameLen); i += 8 { + v, err := safeload(ppa1 + nameOffset + uintptr(i)) + if err != 0 { + return 1 + } + funcname[i] = byte(v >> 56) + funcname[i+1] = byte(v >> 48) + funcname[i+2] = byte(v >> 40) + funcname[i+3] = byte(v >> 32) + funcname[i+4] = byte(v >> 24) + funcname[i+5] = byte(v >> 16) + funcname[i+6] = byte(v >> 8) + funcname[i+7] = byte(v) + } + + runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, // __e2a_l + []uintptr{uintptr(unsafe.Pointer(&funcname[0])), nameLen}) + + name := string(funcname[:nameLen]) + if name != funcName { + return 1 + } + + return 0 +} + +// For detection of capabilities on a system. +// Is function descriptor f a valid function? +func isValidLeFunc(f uintptr) error { + ret := funcptrtest(f, "") + if ret != 0 { + return fmt.Errorf("Bad pointer, not an LE function ") + } + return nil +} + +// Retrieve function name from descriptor +func getLeFuncName(f uintptr) (string, error) { + // assume it has been checked, only check ppa1 validity here + entry := ((*[2]uintptr)(unsafe.Pointer(f)))[1] + preamp := ((*[4]uint32)(unsafe.Pointer(entry - eyecatcherOffset))) + + offsetPpa1 := preamp[2] + if offsetPpa1 > 0x0ffff { + return "", fmt.Errorf("PPA1 offset seems too big 0x%x\n", offsetPpa1) + } + + ppa1 := uintptr(unsafe.Pointer(preamp)) + uintptr(offsetPpa1) + res := ptrtest(ppa1) + if res != 0 { + return "", fmt.Errorf("PPA1 address not valid") + } + + size := *(*uint16)(unsafe.Pointer(ppa1 + nameLenOffset)) + if size > 128 { + return "", fmt.Errorf("Function name seems too long, length=%d\n", size) + } + + var name [128]byte + funcname := (*[128]byte)(unsafe.Pointer(ppa1 + nameOffset)) + copy(name[0:size], funcname[0:size]) + + runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, // __e2a_l + []uintptr{uintptr(unsafe.Pointer(&name[0])), uintptr(size)}) + + return string(name[:size]), nil +} + +// Check z/OS version +func zosLeVersion() (version, release uint32) { + p1 := (*(*uintptr)(unsafe.Pointer(uintptr(1208)))) >> 32 + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 88))) + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 8))) + p1 = *(*uintptr)(unsafe.Pointer(uintptr(p1 + 984))) + vrm := *(*uint32)(unsafe.Pointer(p1 + 80)) + version = (vrm & 0x00ff0000) >> 16 + release = (vrm & 0x0000ff00) >> 8 + return +} + +// returns a zos C FILE * for stdio fd 0, 1, 2 +func ZosStdioFilep(fd int32) uintptr { + return uintptr(*(*uint64)(unsafe.Pointer(uintptr(*(*uint64)(unsafe.Pointer(uintptr(*(*uint64)(unsafe.Pointer(uintptr(uint64(*(*uint32)(unsafe.Pointer(uintptr(1208)))) + 80))) + uint64((fd+2)<<3)))))))) +} func copyStat(stat *Stat_t, statLE *Stat_LE_t) { stat.Dev = uint64(statLE.Dev) @@ -66,6 +263,21 @@ func (d *Dirent) NameString() string { } } +func DecodeData(dest []byte, sz int, val uint64) { + for i := 0; i < sz; i++ { + dest[sz-1-i] = byte((val >> (uint64(i * 8))) & 0xff) + } +} + +func EncodeData(data []byte) uint64 { + var value uint64 + sz := len(data) + for i := 0; i < sz; i++ { + value |= uint64(data[i]) << uint64(((sz - i - 1) * 8)) + } + return value +} + func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { if sa.Port < 0 || sa.Port > 0xFFFF { return nil, 0, EINVAL @@ -75,7 +287,9 @@ func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) { p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port)) p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) - sa.raw.Addr = sa.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil } @@ -89,7 +303,9 @@ func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) { p[0] = byte(sa.Port >> 8) p[1] = byte(sa.Port) sa.raw.Scope_id = sa.ZoneId - sa.raw.Addr = sa.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil } @@ -147,7 +363,9 @@ func anyToSockaddr(_ int, rsa *RawSockaddrAny) (Sockaddr, error) { sa := new(SockaddrInet4) p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) - sa.Addr = pp.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } return sa, nil case AF_INET6: @@ -156,7 +374,9 @@ func anyToSockaddr(_ int, rsa *RawSockaddrAny) (Sockaddr, error) { p := (*[2]byte)(unsafe.Pointer(&pp.Port)) sa.Port = int(p[0])<<8 + int(p[1]) sa.ZoneId = pp.Scope_id - sa.Addr = pp.Addr + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } return sa, nil } return nil, EAFNOSUPPORT @@ -178,6 +398,43 @@ func Accept(fd int) (nfd int, sa Sockaddr, err error) { return } +func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) { + var rsa RawSockaddrAny + var len _Socklen = SizeofSockaddrAny + nfd, err = accept4(fd, &rsa, &len, flags) + if err != nil { + return + } + if len > SizeofSockaddrAny { + panic("RawSockaddrAny too small") + } + // TODO(neeilan): Remove 0 in call + sa, err = anyToSockaddr(0, &rsa) + if err != nil { + Close(nfd) + nfd = 0 + } + return +} + +func Ctermid() (tty string, err error) { + var termdev [1025]byte + runtime.EnterSyscall() + r0, err2, err1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___CTERMID_A<<4, uintptr(unsafe.Pointer(&termdev[0]))) + runtime.ExitSyscall() + if r0 == 0 { + return "", fmt.Errorf("%s (errno2=0x%x)\n", err1.Error(), err2) + } + s := string(termdev[:]) + idx := strings.Index(s, string(rune(0))) + if idx == -1 { + tty = s + } else { + tty = s[:idx] + } + return +} + func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } @@ -191,10 +448,16 @@ func (cmsg *Cmsghdr) SetLen(length int) { } //sys fcntl(fd int, cmd int, arg int) (val int, err error) +//sys Flistxattr(fd int, dest []byte) (sz int, err error) = SYS___FLISTXATTR_A +//sys Fremovexattr(fd int, attr string) (err error) = SYS___FREMOVEXATTR_A //sys read(fd int, p []byte) (n int, err error) //sys write(fd int, p []byte) (n int, err error) +//sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) = SYS___FGETXATTR_A +//sys Fsetxattr(fd int, attr string, data []byte, flag int) (err error) = SYS___FSETXATTR_A + //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = SYS___ACCEPT_A +//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) = SYS___ACCEPT4_A //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = SYS___BIND_A //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = SYS___CONNECT_A //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) @@ -205,6 +468,7 @@ func (cmsg *Cmsghdr) SetLen(length int) { //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = SYS___GETPEERNAME_A //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) = SYS___GETSOCKNAME_A +//sys Removexattr(path string, attr string) (err error) = SYS___REMOVEXATTR_A //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = SYS___RECVFROM_A //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = SYS___SENDTO_A //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) = SYS___RECVMSG_A @@ -213,6 +477,10 @@ func (cmsg *Cmsghdr) SetLen(length int) { //sys munmap(addr uintptr, length uintptr) (err error) = SYS_MUNMAP //sys ioctl(fd int, req int, arg uintptr) (err error) = SYS_IOCTL //sys ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) = SYS_IOCTL +//sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) = SYS_SHMAT +//sys shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) = SYS_SHMCTL64 +//sys shmdt(addr uintptr) (err error) = SYS_SHMDT +//sys shmget(key int, size int, flag int) (id int, err error) = SYS_SHMGET //sys Access(path string, mode uint32) (err error) = SYS___ACCESS_A //sys Chdir(path string) (err error) = SYS___CHDIR_A @@ -221,14 +489,31 @@ func (cmsg *Cmsghdr) SetLen(length int) { //sys Creat(path string, mode uint32) (fd int, err error) = SYS___CREAT_A //sys Dup(oldfd int) (fd int, err error) //sys Dup2(oldfd int, newfd int) (err error) +//sys Dup3(oldfd int, newfd int, flags int) (err error) = SYS_DUP3 +//sys Dirfd(dirp uintptr) (fd int, err error) = SYS_DIRFD +//sys EpollCreate(size int) (fd int, err error) = SYS_EPOLL_CREATE +//sys EpollCreate1(flags int) (fd int, err error) = SYS_EPOLL_CREATE1 +//sys EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) = SYS_EPOLL_CTL +//sys EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) = SYS_EPOLL_PWAIT +//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_WAIT //sys Errno2() (er2 int) = SYS___ERRNO2 -//sys Err2ad() (eadd *int) = SYS___ERR2AD +//sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD //sys Exit(code int) +//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) = SYS___FACCESSAT_A + +func Faccessat2(dirfd int, path string, mode uint32, flags int) (err error) { + return Faccessat(dirfd, path, mode, flags) +} + //sys Fchdir(fd int) (err error) //sys Fchmod(fd int, mode uint32) (err error) +//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) = SYS___FCHMODAT_A //sys Fchown(fd int, uid int, gid int) (err error) +//sys Fchownat(fd int, path string, uid int, gid int, flags int) (err error) = SYS___FCHOWNAT_A //sys FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) = SYS_FCNTL +//sys Fdatasync(fd int) (err error) = SYS_FDATASYNC //sys fstat(fd int, stat *Stat_LE_t) (err error) +//sys fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) = SYS___FSTATAT_A func Fstat(fd int, stat *Stat_t) (err error) { var statLE Stat_LE_t @@ -237,28 +522,208 @@ func Fstat(fd int, stat *Stat_t) (err error) { return } +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var statLE Stat_LE_t + err = fstatat(dirfd, path, &statLE, flags) + copyStat(stat, &statLE) + return +} + +func impl_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest))) + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_GetxattrAddr() *(func(path string, attr string, dest []byte) (sz int, err error)) + +var Getxattr = enter_Getxattr + +func enter_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + funcref := get_GetxattrAddr() + if validGetxattr() { + *funcref = impl_Getxattr + } else { + *funcref = error_Getxattr + } + return (*funcref)(path, attr, dest) +} + +func error_Getxattr(path string, attr string, dest []byte) (sz int, err error) { + return -1, ENOSYS +} + +func validGetxattr() bool { + if funcptrtest(GetZosLibVec()+SYS___GETXATTR_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___GETXATTR_A<<4); err == nil { + return name == "__getxattr_a" + } + } + return false +} + +//sys Lgetxattr(link string, attr string, dest []byte) (sz int, err error) = SYS___LGETXATTR_A +//sys Lsetxattr(path string, attr string, data []byte, flags int) (err error) = SYS___LSETXATTR_A + +func impl_Setxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_SetxattrAddr() *(func(path string, attr string, data []byte, flags int) (err error)) + +var Setxattr = enter_Setxattr + +func enter_Setxattr(path string, attr string, data []byte, flags int) (err error) { + funcref := get_SetxattrAddr() + if validSetxattr() { + *funcref = impl_Setxattr + } else { + *funcref = error_Setxattr + } + return (*funcref)(path, attr, data, flags) +} + +func error_Setxattr(path string, attr string, data []byte, flags int) (err error) { + return ENOSYS +} + +func validSetxattr() bool { + if funcptrtest(GetZosLibVec()+SYS___SETXATTR_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___SETXATTR_A<<4); err == nil { + return name == "__setxattr_a" + } + } + return false +} + +//sys Fstatfs(fd int, buf *Statfs_t) (err error) = SYS_FSTATFS //sys Fstatvfs(fd int, stat *Statvfs_t) (err error) = SYS_FSTATVFS //sys Fsync(fd int) (err error) +//sys Futimes(fd int, tv []Timeval) (err error) = SYS_FUTIMES +//sys Futimesat(dirfd int, path string, tv []Timeval) (err error) = SYS___FUTIMESAT_A //sys Ftruncate(fd int, length int64) (err error) -//sys Getpagesize() (pgsize int) = SYS_GETPAGESIZE +//sys Getrandom(buf []byte, flags int) (n int, err error) = SYS_GETRANDOM +//sys InotifyInit() (fd int, err error) = SYS_INOTIFY_INIT +//sys InotifyInit1(flags int) (fd int, err error) = SYS_INOTIFY_INIT1 +//sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) = SYS___INOTIFY_ADD_WATCH_A +//sys InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) = SYS_INOTIFY_RM_WATCH +//sys Listxattr(path string, dest []byte) (sz int, err error) = SYS___LISTXATTR_A +//sys Llistxattr(path string, dest []byte) (sz int, err error) = SYS___LLISTXATTR_A +//sys Lremovexattr(path string, attr string) (err error) = SYS___LREMOVEXATTR_A +//sys Lutimes(path string, tv []Timeval) (err error) = SYS___LUTIMES_A //sys Mprotect(b []byte, prot int) (err error) = SYS_MPROTECT //sys Msync(b []byte, flags int) (err error) = SYS_MSYNC +//sys Console2(cmsg *ConsMsg2, modstr *byte, concmd *uint32) (err error) = SYS___CONSOLE2 + +// Pipe2 begin + +//go:nosplit +func getPipe2Addr() *(func([]int, int) error) + +var Pipe2 = pipe2Enter + +func pipe2Enter(p []int, flags int) (err error) { + if funcptrtest(GetZosLibVec()+SYS_PIPE2<<4, "") == 0 { + *getPipe2Addr() = pipe2Impl + } else { + *getPipe2Addr() = pipe2Error + } + return (*getPipe2Addr())(p, flags) +} + +func pipe2Impl(p []int, flags int) (err error) { + var pp [2]_C_int + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PIPE2<<4, uintptr(unsafe.Pointer(&pp[0])), uintptr(flags)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } else { + p[0] = int(pp[0]) + p[1] = int(pp[1]) + } + return +} +func pipe2Error(p []int, flags int) (err error) { + return fmt.Errorf("Pipe2 is not available on this system") +} + +// Pipe2 end + //sys Poll(fds []PollFd, timeout int) (n int, err error) = SYS_POLL + +func Readdir(dir uintptr) (dirent *Dirent, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READDIR_A<<4, uintptr(dir)) + runtime.ExitSyscall() + dirent = (*Dirent)(unsafe.Pointer(r0)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//sys Readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) = SYS___READDIR_R_A +//sys Statfs(path string, buf *Statfs_t) (err error) = SYS___STATFS_A +//sys Syncfs(fd int) (err error) = SYS_SYNCFS //sys Times(tms *Tms) (ticks uintptr, err error) = SYS_TIMES //sys W_Getmntent(buff *byte, size int) (lastsys int, err error) = SYS_W_GETMNTENT //sys W_Getmntent_A(buff *byte, size int) (lastsys int, err error) = SYS___W_GETMNTENT_A //sys mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) = SYS___MOUNT_A -//sys unmount(filesystem string, mtm int) (err error) = SYS___UMOUNT_A +//sys unmount_LE(filesystem string, mtm int) (err error) = SYS___UMOUNT_A //sys Chroot(path string) (err error) = SYS___CHROOT_A //sys Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) = SYS_SELECT -//sysnb Uname(buf *Utsname) (err error) = SYS___UNAME_A +//sysnb Uname(buf *Utsname) (err error) = SYS_____OSNAME_A +//sys Unshare(flags int) (err error) = SYS_UNSHARE func Ptsname(fd int) (name string, err error) { - r0, _, e1 := syscall_syscall(SYS___PTSNAME_A, uintptr(fd), 0, 0) - name = u2s(unsafe.Pointer(r0)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___PTSNAME_A<<4, uintptr(fd)) + runtime.ExitSyscall() + if r0 == 0 { + err = errnoErr2(e1, e2) + } else { + name = u2s(unsafe.Pointer(r0)) } return } @@ -273,13 +738,19 @@ func u2s(cstr unsafe.Pointer) string { } func Close(fd int) (err error) { - _, _, e1 := syscall_syscall(SYS_CLOSE, uintptr(fd), 0, 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSE<<4, uintptr(fd)) + runtime.ExitSyscall() for i := 0; e1 == EAGAIN && i < 10; i++ { - _, _, _ = syscall_syscall(SYS_USLEEP, uintptr(10), 0, 0) - _, _, e1 = syscall_syscall(SYS_CLOSE, uintptr(fd), 0, 0) + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_USLEEP<<4, uintptr(10)) + runtime.ExitSyscall() + runtime.EnterSyscall() + r0, e2, e1 = CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSE<<4, uintptr(fd)) + runtime.ExitSyscall() } - if e1 != 0 { - err = errnoErr(e1) + if r0 != 0 { + err = errnoErr2(e1, e2) } return } @@ -289,9 +760,15 @@ func Madvise(b []byte, advice int) (err error) { return } +func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) { + return mapper.Mmap(fd, offset, length, prot, flags) +} + +func Munmap(b []byte) (err error) { + return mapper.Munmap(b) +} + //sys Gethostname(buf []byte) (err error) = SYS___GETHOSTNAME_A -//sysnb Getegid() (egid int) -//sysnb Geteuid() (uid int) //sysnb Getgid() (gid int) //sysnb Getpid() (pid int) //sysnb Getpgid(pid int) (pgid int, err error) = SYS_GETPGID @@ -318,11 +795,14 @@ func Getrusage(who int, rusage *Rusage) (err error) { return } +//sys Getegid() (egid int) = SYS_GETEGID +//sys Geteuid() (euid int) = SYS_GETEUID //sysnb Getsid(pid int) (sid int, err error) = SYS_GETSID //sysnb Getuid() (uid int) //sysnb Kill(pid int, sig Signal) (err error) //sys Lchown(path string, uid int, gid int) (err error) = SYS___LCHOWN_A //sys Link(path string, link string) (err error) = SYS___LINK_A +//sys Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) = SYS___LINKAT_A //sys Listen(s int, n int) (err error) //sys lstat(path string, stat *Stat_LE_t) (err error) = SYS___LSTAT_A @@ -333,15 +813,150 @@ func Lstat(path string, stat *Stat_t) (err error) { return } +// 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', '/'}} + + var i, j int + for i = 0; i < len(special); i++ { + for j = 0; j < len(special[i]); j++ { + if path[j] != special[i][j] { + break + } + } + if j == len(special[i]) { + return true + } + } + return false +} + +func realpath(srcpath string, abspath []byte) (pathlen int, errno int) { + var source [1024]byte + copy(source[:], srcpath) + source[len(srcpath)] = 0 + ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___REALPATH_A<<4, //__realpath_a() + []uintptr{uintptr(unsafe.Pointer(&source[0])), + uintptr(unsafe.Pointer(&abspath[0]))}) + if ret != 0 { + index := bytes.IndexByte(abspath[:], byte(0)) + if index != -1 { + return index, 0 + } + } else { + errptr := (*int)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, []uintptr{}))) //__errno() + return 0, *errptr + } + return 0, 245 // EBADDATA 245 +} + +func Readlink(path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + n = int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___READLINK_A<<4, + []uintptr{uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))})) + runtime.KeepAlive(unsafe.Pointer(_p0)) + if n == -1 { + value := *(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, []uintptr{}))) + err = errnoErr(Errno(value)) + } else { + if buf[0] == '$' { + if isSpecialPath(buf[1:9]) { + cnt, err1 := realpath(path, buf) + if err1 == 0 { + n = cnt + } + } + } + } + return +} + +func impl_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(buf) > 0 { + _p1 = unsafe.Pointer(&buf[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READLINKAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + return n, err + } else { + if buf[0] == '$' { + if isSpecialPath(buf[1:9]) { + cnt, err1 := realpath(path, buf) + if err1 == 0 { + n = cnt + } + } + } + } + return +} + +//go:nosplit +func get_ReadlinkatAddr() *(func(dirfd int, path string, buf []byte) (n int, err error)) + +var Readlinkat = enter_Readlinkat + +func enter_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + funcref := get_ReadlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___READLINKAT_A<<4, "") == 0 { + *funcref = impl_Readlinkat + } else { + *funcref = error_Readlinkat + } + return (*funcref)(dirfd, path, buf) +} + +func error_Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { + n = -1 + err = ENOSYS + return +} + //sys Mkdir(path string, mode uint32) (err error) = SYS___MKDIR_A +//sys Mkdirat(dirfd int, path string, mode uint32) (err error) = SYS___MKDIRAT_A //sys Mkfifo(path string, mode uint32) (err error) = SYS___MKFIFO_A //sys Mknod(path string, mode uint32, dev int) (err error) = SYS___MKNOD_A +//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) = SYS___MKNODAT_A +//sys PivotRoot(newroot string, oldroot string) (err error) = SYS___PIVOT_ROOT_A //sys Pread(fd int, p []byte, offset int64) (n int, err error) //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) -//sys Readlink(path string, buf []byte) (n int, err error) = SYS___READLINK_A +//sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) = SYS___PRCTL_A +//sysnb Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT //sys Rename(from string, to string) (err error) = SYS___RENAME_A +//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) = SYS___RENAMEAT_A +//sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) = SYS___RENAMEAT2_A //sys Rmdir(path string) (err error) = SYS___RMDIR_A //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK +//sys Setegid(egid int) (err error) = SYS_SETEGID +//sys Seteuid(euid int) (err error) = SYS_SETEUID +//sys Sethostname(p []byte) (err error) = SYS___SETHOSTNAME_A +//sys Setns(fd int, nstype int) (err error) = SYS_SETNS //sys Setpriority(which int, who int, prio int) (err error) //sysnb Setpgid(pid int, pgid int) (err error) = SYS_SETPGID //sysnb Setrlimit(resource int, lim *Rlimit) (err error) @@ -361,32 +976,57 @@ func Stat(path string, sta *Stat_t) (err error) { } //sys Symlink(path string, link string) (err error) = SYS___SYMLINK_A +//sys Symlinkat(oldPath string, dirfd int, newPath string) (err error) = SYS___SYMLINKAT_A //sys Sync() = SYS_SYNC //sys Truncate(path string, length int64) (err error) = SYS___TRUNCATE_A //sys Tcgetattr(fildes int, termptr *Termios) (err error) = SYS_TCGETATTR //sys Tcsetattr(fildes int, when int, termptr *Termios) (err error) = SYS_TCSETATTR //sys Umask(mask int) (oldmask int) //sys Unlink(path string) (err error) = SYS___UNLINK_A +//sys Unlinkat(dirfd int, path string, flags int) (err error) = SYS___UNLINKAT_A //sys Utime(path string, utim *Utimbuf) (err error) = SYS___UTIME_A //sys open(path string, mode int, perm uint32) (fd int, err error) = SYS___OPEN_A func Open(path string, mode int, perm uint32) (fd int, err error) { + if mode&O_ACCMODE == 0 { + mode |= O_RDONLY + } return open(path, mode, perm) } -func Mkfifoat(dirfd int, path string, mode uint32) (err error) { - wd, err := Getwd() - if err != nil { - return err +//sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) = SYS___OPENAT_A + +func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + if flags&O_ACCMODE == 0 { + flags |= O_RDONLY } + return openat(dirfd, path, flags, mode) +} - if err := Fchdir(dirfd); err != nil { - return err +//sys openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) = SYS___OPENAT2_A + +func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) { + if how.Flags&O_ACCMODE == 0 { + how.Flags |= O_RDONLY } - defer Chdir(wd) + return openat2(dirfd, path, how, SizeofOpenHow) +} - return Mkfifo(path, mode) +func ZosFdToPath(dirfd int) (path string, err error) { + var buffer [1024]byte + runtime.EnterSyscall() + ret, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_W_IOCTL<<4, uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))) + runtime.ExitSyscall() + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + CallLeFuncWithErr(GetZosLibVec()+SYS___E2A_L<<4, uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)) + return string(buffer[:zb]), nil + } + return "", errnoErr2(e1, e2) } //sys remove(path string) (err error) @@ -404,10 +1044,12 @@ func Getcwd(buf []byte) (n int, err error) { } else { p = unsafe.Pointer(&_zero) } - _, _, e := syscall_syscall(SYS___GETCWD_A, uintptr(p), uintptr(len(buf)), 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___GETCWD_A<<4, uintptr(p), uintptr(len(buf))) + runtime.ExitSyscall() n = clen(buf) + 1 - if e != 0 { - err = errnoErr(e) + if r0 == 0 { + err = errnoErr2(e1, e2) } return } @@ -521,9 +1163,41 @@ func (w WaitStatus) StopSignal() Signal { func (w WaitStatus) TrapCause() int { return -1 } +//sys waitid(idType int, id int, info *Siginfo, options int) (err error) + +func Waitid(idType int, id int, info *Siginfo, options int, rusage *Rusage) (err error) { + return waitid(idType, id, info, options) +} + //sys waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) -func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { +func impl_Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAIT4<<4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage))) + runtime.ExitSyscall() + wpid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_Wait4Addr() *(func(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)) + +var Wait4 = enter_Wait4 + +func enter_Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { + funcref := get_Wait4Addr() + if funcptrtest(GetZosLibVec()+SYS_WAIT4<<4, "") == 0 { + *funcref = impl_Wait4 + } else { + *funcref = legacyWait4 + } + return (*funcref)(pid, wstatus, options, rusage) +} + +func legacyWait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { // TODO(mundaym): z/OS doesn't have wait4. I don't think getrusage does what we want. // At the moment rusage will not be touched. var status _C_int @@ -572,23 +1246,62 @@ func Pipe(p []int) (err error) { } var pp [2]_C_int err = pipe(&pp) - if err == nil { - p[0] = int(pp[0]) - p[1] = int(pp[1]) - } + p[0] = int(pp[0]) + p[1] = int(pp[1]) return } //sys utimes(path string, timeval *[2]Timeval) (err error) = SYS___UTIMES_A func Utimes(path string, tv []Timeval) (err error) { + if tv == nil { + return utimes(path, nil) + } if len(tv) != 2 { return EINVAL } return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } -func UtimesNano(path string, ts []Timespec) error { +//sys utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) = SYS___UTIMENSAT_A + +func validUtimensat() bool { + if funcptrtest(GetZosLibVec()+SYS___UTIMENSAT_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___UTIMENSAT_A<<4); err == nil { + return name == "__utimensat_a" + } + } + return false +} + +// Begin UtimesNano + +//go:nosplit +func get_UtimesNanoAddr() *(func(path string, ts []Timespec) (err error)) + +var UtimesNano = enter_UtimesNano + +func enter_UtimesNano(path string, ts []Timespec) (err error) { + funcref := get_UtimesNanoAddr() + if validUtimensat() { + *funcref = utimesNanoImpl + } else { + *funcref = legacyUtimesNano + } + return (*funcref)(path, ts) +} + +func utimesNanoImpl(path string, ts []Timespec) (err error) { + if ts == nil { + return utimensat(AT_FDCWD, path, nil, 0) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0) +} + +func legacyUtimesNano(path string, ts []Timespec) (err error) { if len(ts) != 2 { return EINVAL } @@ -601,6 +1314,70 @@ func UtimesNano(path string, ts []Timespec) error { return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0]))) } +// End UtimesNano + +// Begin UtimesNanoAt + +//go:nosplit +func get_UtimesNanoAtAddr() *(func(dirfd int, path string, ts []Timespec, flags int) (err error)) + +var UtimesNanoAt = enter_UtimesNanoAt + +func enter_UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) (err error) { + funcref := get_UtimesNanoAtAddr() + if validUtimensat() { + *funcref = utimesNanoAtImpl + } else { + *funcref = legacyUtimesNanoAt + } + return (*funcref)(dirfd, path, ts, flags) +} + +func utimesNanoAtImpl(dirfd int, path string, ts []Timespec, flags int) (err error) { + if ts == nil { + return utimensat(dirfd, path, nil, flags) + } + if len(ts) != 2 { + return EINVAL + } + return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags) +} + +func legacyUtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) (err error) { + if path[0] != '/' { + dirPath, err := ZosFdToPath(dirfd) + if err != nil { + return err + } + path = dirPath + "/" + path + } + if flags == AT_SYMLINK_NOFOLLOW { + if len(ts) != 2 { + return EINVAL + } + + if ts[0].Nsec >= 5e8 { + ts[0].Sec++ + } + ts[0].Nsec = 0 + if ts[1].Nsec >= 5e8 { + ts[1].Sec++ + } + ts[1].Nsec = 0 + + // Not as efficient as it could be because Timespec and + // Timeval have different types in the different OSes + tv := []Timeval{ + NsecToTimeval(TimespecToNsec(ts[0])), + NsecToTimeval(TimespecToNsec(ts[1])), + } + return Lutimes(path, tv) + } + return UtimesNano(path, ts) +} + +// End UtimesNanoAt + func Getsockname(fd int) (sa Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny @@ -1105,7 +1882,7 @@ func GetsockoptString(fd, level, opt int) (string, error) { return "", err } - return string(buf[:vallen-1]), nil + return ByteSliceToString(buf[:vallen]), nil } func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) { @@ -1187,67 +1964,46 @@ func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) return n, nil } -func Opendir(name string) (uintptr, error) { - p, err := BytePtrFromString(name) - if err != nil { - return 0, err - } - dir, _, e := syscall_syscall(SYS___OPENDIR_A, uintptr(unsafe.Pointer(p)), 0, 0) - runtime.KeepAlive(unsafe.Pointer(p)) - if e != 0 { - err = errnoErr(e) - } - return dir, err -} - -// clearsyscall.Errno resets the errno value to 0. -func clearErrno() - -func Readdir(dir uintptr) (*Dirent, error) { - var ent Dirent - var res uintptr - // __readdir_r_a returns errno at the end of the directory stream, rather than 0. - // Therefore to avoid false positives we clear errno before calling it. - - // TODO(neeilan): Commented this out to get sys/unix compiling on z/OS. Uncomment and fix. Error: "undefined: clearsyscall" - //clearsyscall.Errno() // TODO(mundaym): check pre-emption rules. - - e, _, _ := syscall_syscall(SYS___READDIR_R_A, dir, uintptr(unsafe.Pointer(&ent)), uintptr(unsafe.Pointer(&res))) - var err error - if e != 0 { - err = errnoErr(Errno(e)) - } - if res == 0 { - return nil, err - } - return &ent, err -} - -func readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) { - r0, _, e1 := syscall_syscall(SYS___READDIR_R_A, dirp, uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) - if int64(r0) == -1 { - err = errnoErr(Errno(e1)) +func Opendir(name string) (uintptr, error) { + p, err := BytePtrFromString(name) + if err != nil { + return 0, err } - return + err = nil + runtime.EnterSyscall() + dir, e2, e1 := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___OPENDIR_A<<4, uintptr(unsafe.Pointer(p))) + runtime.ExitSyscall() + runtime.KeepAlive(unsafe.Pointer(p)) + if dir == 0 { + err = errnoErr2(e1, e2) + } + return dir, err } +// clearsyscall.Errno resets the errno value to 0. +func clearErrno() + func Closedir(dir uintptr) error { - _, _, e := syscall_syscall(SYS_CLOSEDIR, dir, 0, 0) - if e != 0 { - return errnoErr(e) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_CLOSEDIR<<4, dir) + runtime.ExitSyscall() + if r0 != 0 { + return errnoErr2(e1, e2) } return nil } func Seekdir(dir uintptr, pos int) { - _, _, _ = syscall_syscall(SYS_SEEKDIR, dir, uintptr(pos), 0) + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_SEEKDIR<<4, dir, uintptr(pos)) + runtime.ExitSyscall() } func Telldir(dir uintptr) (int, error) { - p, _, e := syscall_syscall(SYS_TELLDIR, dir, 0, 0) + p, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TELLDIR<<4, dir) pos := int(p) - if pos == -1 { - return pos, errnoErr(e) + if int64(p) == -1 { + return pos, errnoErr2(e1, e2) } return pos, nil } @@ -1262,19 +2018,55 @@ func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { *(*int64)(unsafe.Pointer(&flock[4])) = lk.Start *(*int64)(unsafe.Pointer(&flock[12])) = lk.Len *(*int32)(unsafe.Pointer(&flock[20])) = lk.Pid - _, _, errno := syscall_syscall(SYS_FCNTL, fd, uintptr(cmd), uintptr(unsafe.Pointer(&flock))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, fd, uintptr(cmd), uintptr(unsafe.Pointer(&flock))) + runtime.ExitSyscall() lk.Type = *(*int16)(unsafe.Pointer(&flock[0])) lk.Whence = *(*int16)(unsafe.Pointer(&flock[2])) lk.Start = *(*int64)(unsafe.Pointer(&flock[4])) lk.Len = *(*int64)(unsafe.Pointer(&flock[12])) lk.Pid = *(*int32)(unsafe.Pointer(&flock[20])) - if errno == 0 { + if r0 == 0 { return nil } - return errno + return errnoErr2(e1, e2) +} + +func impl_Flock(fd int, how int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FLOCK<<4, uintptr(fd), uintptr(how)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FlockAddr() *(func(fd int, how int) (err error)) + +var Flock = enter_Flock + +func validFlock(fp uintptr) bool { + if funcptrtest(GetZosLibVec()+SYS_FLOCK<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS_FLOCK<<4); err == nil { + return name == "flock" + } + } + return false +} + +func enter_Flock(fd int, how int) (err error) { + funcref := get_FlockAddr() + if validFlock(GetZosLibVec() + SYS_FLOCK<<4) { + *funcref = impl_Flock + } else { + *funcref = legacyFlock + } + return (*funcref)(fd, how) } -func Flock(fd int, how int) error { +func legacyFlock(fd int, how int) error { var flock_type int16 var fcntl_cmd int @@ -1308,41 +2100,51 @@ func Flock(fd int, how int) error { } func Mlock(b []byte) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_NONSWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Mlock2(b []byte, flags int) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_NONSWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Mlockall(flags int) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_NONSWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_NONSWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Munlock(b []byte) (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_SWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_SWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } func Munlockall() (err error) { - _, _, e1 := syscall_syscall(SYS___MLOCKALL, _BPX_SWAP, 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MLOCKALL<<4, _BPX_SWAP) + runtime.ExitSyscall() + if r0 != 0 { + err = errnoErr2(e1, e2) } return } @@ -1373,15 +2175,104 @@ func ClockGettime(clockid int32, ts *Timespec) error { return nil } -func Statfs(path string, stat *Statfs_t) (err error) { - fd, err := open(path, O_RDONLY, 0) - defer Close(fd) - if err != nil { - return err +// Chtag + +//go:nosplit +func get_ChtagAddr() *(func(path string, ccsid uint64, textbit uint64) error) + +var Chtag = enter_Chtag + +func enter_Chtag(path string, ccsid uint64, textbit uint64) error { + funcref := get_ChtagAddr() + if validSetxattr() { + *funcref = impl_Chtag + } else { + *funcref = legacy_Chtag + } + return (*funcref)(path, ccsid, textbit) +} + +func legacy_Chtag(path string, ccsid uint64, textbit uint64) error { + tag := ccsid<<16 | textbit<<15 + var tag_buff [8]byte + DecodeData(tag_buff[:], 8, tag) + return Setxattr(path, "filetag", tag_buff[:], XATTR_REPLACE) +} + +func impl_Chtag(path string, ccsid uint64, textbit uint64) error { + tag := ccsid<<16 | textbit<<15 + var tag_buff [4]byte + DecodeData(tag_buff[:], 4, tag) + return Setxattr(path, "system.filetag", tag_buff[:], XATTR_REPLACE) +} + +// End of Chtag + +// Nanosleep + +//go:nosplit +func get_NanosleepAddr() *(func(time *Timespec, leftover *Timespec) error) + +var Nanosleep = enter_Nanosleep + +func enter_Nanosleep(time *Timespec, leftover *Timespec) error { + funcref := get_NanosleepAddr() + if funcptrtest(GetZosLibVec()+SYS_NANOSLEEP<<4, "") == 0 { + *funcref = impl_Nanosleep + } else { + *funcref = legacyNanosleep + } + return (*funcref)(time, leftover) +} + +func impl_Nanosleep(time *Timespec, leftover *Timespec) error { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_NANOSLEEP<<4, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover))) + runtime.ExitSyscall() + if int64(r0) == -1 { + return errnoErr2(e1, e2) + } + return nil +} + +func legacyNanosleep(time *Timespec, leftover *Timespec) error { + t0 := runtime.Nanotime1() + var secrem uint32 + var nsecrem uint32 + total := time.Sec*1000000000 + time.Nsec + elapsed := runtime.Nanotime1() - t0 + var rv int32 + var rc int32 + var err error + // repeatedly sleep for 1 second until less than 1 second left + for total-elapsed > 1000000000 { + rv, rc, _ = BpxCondTimedWait(uint32(1), uint32(0), uint32(CW_CONDVAR), &secrem, &nsecrem) + if rv != 0 && rc != 112 { // 112 is EAGAIN + if leftover != nil && rc == 120 { // 120 is EINTR + leftover.Sec = int64(secrem) + leftover.Nsec = int64(nsecrem) + } + err = Errno(rc) + return err + } + elapsed = runtime.Nanotime1() - t0 } - return Fstatfs(fd, stat) + // sleep the remainder + if total > elapsed { + rv, rc, _ = BpxCondTimedWait(uint32(0), uint32(total-elapsed), uint32(CW_CONDVAR), &secrem, &nsecrem) + } + if leftover != nil && rc == 120 { + leftover.Sec = int64(secrem) + leftover.Nsec = int64(nsecrem) + } + if rv != 0 && rc != 112 { + err = Errno(rc) + } + return err } +// End of Nanosleep + var ( Stdin = 0 Stdout = 1 @@ -1396,6 +2287,9 @@ var ( errENOENT error = syscall.ENOENT ) +var ZosTraceLevel int +var ZosTracefile *os.File + var ( signalNameMapOnce sync.Once signalNameMap map[string]syscall.Signal @@ -1417,6 +2311,56 @@ func errnoErr(e Errno) error { return e } +var reg *regexp.Regexp + +// enhanced with zos specific errno2 +func errnoErr2(e Errno, e2 uintptr) error { + switch e { + case 0: + return nil + case EAGAIN: + return errEAGAIN + /* + Allow the retrieval of errno2 for EINVAL and ENOENT on zos + case EINVAL: + return errEINVAL + case ENOENT: + return errENOENT + */ + } + if ZosTraceLevel > 0 { + var name string + if reg == nil { + reg = regexp.MustCompile("(^unix\\.[^/]+$|.*\\/unix\\.[^/]+$)") + } + i := 1 + pc, file, line, ok := runtime.Caller(i) + if ok { + name = runtime.FuncForPC(pc).Name() + } + for ok && reg.MatchString(runtime.FuncForPC(pc).Name()) { + i += 1 + pc, file, line, ok = runtime.Caller(i) + } + if ok { + if ZosTracefile == nil { + ZosConsolePrintf("From %s:%d\n", file, line) + ZosConsolePrintf("%s: %s (errno2=0x%x)\n", name, e.Error(), e2) + } else { + fmt.Fprintf(ZosTracefile, "From %s:%d\n", file, line) + fmt.Fprintf(ZosTracefile, "%s: %s (errno2=0x%x)\n", name, e.Error(), e2) + } + } else { + if ZosTracefile == nil { + ZosConsolePrintf("%s (errno2=0x%x)\n", e.Error(), e2) + } else { + fmt.Fprintf(ZosTracefile, "%s (errno2=0x%x)\n", e.Error(), e2) + } + } + } + return e +} + // ErrnoName returns the error name for error number e. func ErrnoName(e Errno) string { i := sort.Search(len(errorList), func(i int) bool { @@ -1475,6 +2419,9 @@ func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (d return nil, EINVAL } + // Set __MAP_64 by default + flags |= __MAP_64 + // Map the requested memory. addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset) if errno != nil { @@ -1779,83 +2726,170 @@ func Exec(argv0 string, argv []string, envv []string) error { return syscall.Exec(argv0, argv, envv) } -func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { +func Getag(path string) (ccsid uint16, flag uint16, err error) { + var val [8]byte + sz, err := Getxattr(path, "ccsid", val[:]) + if err != nil { + return + } + ccsid = uint16(EncodeData(val[0:sz])) + sz, err = Getxattr(path, "flags", val[:]) + if err != nil { + return + } + flag = uint16(EncodeData(val[0:sz]) >> 15) + return +} + +// Mount begin +func impl_Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(source) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(target) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + var _p3 *byte + _p3, err = BytePtrFromString(data) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MOUNT1_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(_p3))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MountAddr() *(func(source string, target string, fstype string, flags uintptr, data string) (err error)) + +var Mount = enter_Mount + +func enter_Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { + funcref := get_MountAddr() + if validMount() { + *funcref = impl_Mount + } else { + *funcref = legacyMount + } + return (*funcref)(source, target, fstype, flags, data) +} + +func legacyMount(source string, target string, fstype string, flags uintptr, data string) (err error) { if needspace := 8 - len(fstype); needspace <= 0 { - fstype = fstype[:8] + fstype = fstype[0:8] } else { - fstype += " "[:needspace] + fstype += " "[0:needspace] } return mount_LE(target, source, fstype, uint32(flags), int32(len(data)), data) } -func Unmount(name string, mtm int) (err error) { +func validMount() bool { + if funcptrtest(GetZosLibVec()+SYS___MOUNT1_A<<4, "") == 0 { + if name, err := getLeFuncName(GetZosLibVec() + SYS___MOUNT1_A<<4); err == nil { + return name == "__mount1_a" + } + } + return false +} + +// Mount end + +// Unmount begin +func impl_Unmount(target string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(target) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UMOUNT2_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_UnmountAddr() *(func(target string, flags int) (err error)) + +var Unmount = enter_Unmount + +func enter_Unmount(target string, flags int) (err error) { + funcref := get_UnmountAddr() + if funcptrtest(GetZosLibVec()+SYS___UMOUNT2_A<<4, "") == 0 { + *funcref = impl_Unmount + } else { + *funcref = legacyUnmount + } + return (*funcref)(target, flags) +} + +func legacyUnmount(name string, mtm int) (err error) { // mountpoint is always a full path and starts with a '/' // check if input string is not a mountpoint but a filesystem name if name[0] != '/' { - return unmount(name, mtm) + return unmount_LE(name, mtm) } // treat name as mountpoint b2s := func(arr []byte) string { - nulli := bytes.IndexByte(arr, 0) - if nulli == -1 { - return string(arr) - } else { - return string(arr[:nulli]) + var str string + for i := 0; i < len(arr); i++ { + if arr[i] == 0 { + str = string(arr[:i]) + break + } } + return str } var buffer struct { header W_Mnth fsinfo [64]W_Mntent } - fsCount, err := W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer))) - if err != nil { - return err - } - if fsCount == 0 { - return EINVAL - } - for i := 0; i < fsCount; i++ { - if b2s(buffer.fsinfo[i].Mountpoint[:]) == name { - err = unmount(b2s(buffer.fsinfo[i].Fsname[:]), mtm) - break + fs_count, err := W_Getmntent_A((*byte)(unsafe.Pointer(&buffer)), int(unsafe.Sizeof(buffer))) + if err == nil { + err = EINVAL + for i := 0; i < fs_count; i++ { + if b2s(buffer.fsinfo[i].Mountpoint[:]) == name { + err = unmount_LE(b2s(buffer.fsinfo[i].Fsname[:]), mtm) + break + } } + } else if fs_count == 0 { + err = EINVAL } return err } -func fdToPath(dirfd int) (path string, err error) { - var buffer [1024]byte - // w_ctrl() - ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_W_IOCTL<<4, - []uintptr{uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))}) - if ret == 0 { - zb := bytes.IndexByte(buffer[:], 0) - if zb == -1 { - zb = len(buffer) - } - // __e2a_l() - runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, - []uintptr{uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)}) - return string(buffer[:zb]), nil - } - // __errno() - errno := int(*(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, - []uintptr{})))) - // __errno2() - errno2 := int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO2<<4, - []uintptr{})) - // strerror_r() - ret = runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_STRERROR_R<<4, - []uintptr{uintptr(errno), uintptr(unsafe.Pointer(&buffer[0])), 1024}) - if ret == 0 { - zb := bytes.IndexByte(buffer[:], 0) - if zb == -1 { - zb = len(buffer) - } - return "", fmt.Errorf("%s (errno2=0x%x)", buffer[:zb], errno2) - } else { - return "", fmt.Errorf("fdToPath errno %d (errno2=0x%x)", errno, errno2) +// Unmount end + +func direntIno(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) +} + +func direntReclen(buf []byte) (uint64, bool) { + return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) +} + +func direntNamlen(buf []byte) (uint64, bool) { + reclen, ok := direntReclen(buf) + if !ok { + return 0, false } + return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true } func direntLeToDirentUnix(dirent *direntLE, dir uintptr, path string) (Dirent, error) { @@ -1897,7 +2931,7 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { } // Get path from fd to avoid unavailable call (fdopendir) - path, err := fdToPath(fd) + path, err := ZosFdToPath(fd) if err != nil { return 0, err } @@ -1911,7 +2945,7 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { for { var entryLE direntLE var entrypLE *direntLE - e := readdir_r(d, &entryLE, &entrypLE) + e := Readdir_r(d, &entryLE, &entrypLE) if e != nil { return n, e } @@ -1957,23 +2991,127 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { return n, nil } -func ReadDirent(fd int, buf []byte) (n int, err error) { - var base = (*uintptr)(unsafe.Pointer(new(uint64))) - return Getdirentries(fd, buf, base) +func Err2ad() (eadd *int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS___ERR2AD<<4) + eadd = (*int)(unsafe.Pointer(r0)) + return } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) +func ZosConsolePrintf(format string, v ...interface{}) (int, error) { + type __cmsg struct { + _ uint16 + _ [2]uint8 + __msg_length uint32 + __msg uintptr + _ [4]uint8 + } + msg := fmt.Sprintf(format, v...) + strptr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&msg)).Data) + len := (*reflect.StringHeader)(unsafe.Pointer(&msg)).Len + cmsg := __cmsg{__msg_length: uint32(len), __msg: uintptr(strptr)} + cmd := uint32(0) + runtime.EnterSyscall() + rc, err2, err1 := CallLeFuncWithErr(GetZosLibVec()+SYS_____CONSOLE_A<<4, uintptr(unsafe.Pointer(&cmsg)), 0, uintptr(unsafe.Pointer(&cmd))) + runtime.ExitSyscall() + if rc != 0 { + return 0, fmt.Errorf("%s (errno2=0x%x)\n", err1.Error(), err2) + } + return 0, nil +} +func ZosStringToEbcdicBytes(str string, nullterm bool) (ebcdicBytes []byte) { + if nullterm { + ebcdicBytes = []byte(str + "\x00") + } else { + ebcdicBytes = []byte(str) + } + A2e(ebcdicBytes) + return +} +func ZosEbcdicBytesToString(b []byte, trimRight bool) (str string) { + res := make([]byte, len(b)) + copy(res, b) + E2a(res) + if trimRight { + str = string(bytes.TrimRight(res, " \x00")) + } else { + str = string(res) + } + return } -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) +func fdToPath(dirfd int) (path string, err error) { + var buffer [1024]byte + // w_ctrl() + ret := runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_W_IOCTL<<4, + []uintptr{uintptr(dirfd), 17, 1024, uintptr(unsafe.Pointer(&buffer[0]))}) + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + // __e2a_l() + runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___E2A_L<<4, + []uintptr{uintptr(unsafe.Pointer(&buffer[0])), uintptr(zb)}) + return string(buffer[:zb]), nil + } + // __errno() + errno := int(*(*int32)(unsafe.Pointer(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO<<4, + []uintptr{})))) + // __errno2() + errno2 := int(runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS___ERRNO2<<4, + []uintptr{})) + // strerror_r() + ret = runtime.CallLeFuncByPtr(runtime.XplinkLibvec+SYS_STRERROR_R<<4, + []uintptr{uintptr(errno), uintptr(unsafe.Pointer(&buffer[0])), 1024}) + if ret == 0 { + zb := bytes.IndexByte(buffer[:], 0) + if zb == -1 { + zb = len(buffer) + } + return "", fmt.Errorf("%s (errno2=0x%x)", buffer[:zb], errno2) + } else { + return "", fmt.Errorf("fdToPath errno %d (errno2=0x%x)", errno, errno2) + } } -func direntNamlen(buf []byte) (uint64, bool) { - reclen, ok := direntReclen(buf) - if !ok { - return 0, false +func impl_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return } - return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKFIFOAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MkfifoatAddr() *(func(dirfd int, path string, mode uint32) (err error)) + +var Mkfifoat = enter_Mkfifoat + +func enter_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + funcref := get_MkfifoatAddr() + if funcptrtest(GetZosLibVec()+SYS___MKFIFOAT_A<<4, "") == 0 { + *funcref = impl_Mkfifoat + } else { + *funcref = legacy_Mkfifoat + } + return (*funcref)(dirfd, path, mode) +} + +func legacy_Mkfifoat(dirfd int, path string, mode uint32) (err error) { + dirname, err := ZosFdToPath(dirfd) + if err != nil { + return err + } + return Mkfifo(dirname+"/"+path, mode) } + +//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 diff --git a/tools/vendor/golang.org/x/sys/unix/sysvshm_linux.go b/tools/vendor/golang.org/x/sys/unix/sysvshm_linux.go index 2c3a4437f..4fcd38de2 100644 --- a/tools/vendor/golang.org/x/sys/unix/sysvshm_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/sysvshm_linux.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build linux -// +build linux package unix diff --git a/tools/vendor/golang.org/x/sys/unix/sysvshm_unix.go b/tools/vendor/golang.org/x/sys/unix/sysvshm_unix.go index 5bb41d17b..672d6b0a8 100644 --- a/tools/vendor/golang.org/x/sys/unix/sysvshm_unix.go +++ b/tools/vendor/golang.org/x/sys/unix/sysvshm_unix.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (darwin && !ios) || linux -// +build darwin,!ios linux +//go:build (darwin && !ios) || linux || zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go b/tools/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go index 71bddefdb..8b7977a28 100644 --- a/tools/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go +++ b/tools/vendor/golang.org/x/sys/unix/sysvshm_unix_other.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build darwin && !ios -// +build darwin,!ios +//go:build (darwin && !ios) || zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/timestruct.go b/tools/vendor/golang.org/x/sys/unix/timestruct.go index 616b1b284..7997b1902 100644 --- a/tools/vendor/golang.org/x/sys/unix/timestruct.go +++ b/tools/vendor/golang.org/x/sys/unix/timestruct.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos -// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package unix diff --git a/tools/vendor/golang.org/x/sys/unix/unveil_openbsd.go b/tools/vendor/golang.org/x/sys/unix/unveil_openbsd.go index 168d5ae77..cb7e598ce 100644 --- a/tools/vendor/golang.org/x/sys/unix/unveil_openbsd.go +++ b/tools/vendor/golang.org/x/sys/unix/unveil_openbsd.go @@ -4,39 +4,48 @@ package unix -import ( - "syscall" - "unsafe" -) +import "fmt" // Unveil implements the unveil syscall. // For more information see unveil(2). // Note that the special case of blocking further // unveil calls is handled by UnveilBlock. func Unveil(path string, flags string) error { - pathPtr, err := syscall.BytePtrFromString(path) - if err != nil { + if err := supportsUnveil(); err != nil { return err } - flagsPtr, err := syscall.BytePtrFromString(flags) + pathPtr, err := BytePtrFromString(path) if err != nil { return err } - _, _, e := syscall.Syscall(SYS_UNVEIL, uintptr(unsafe.Pointer(pathPtr)), uintptr(unsafe.Pointer(flagsPtr)), 0) - if e != 0 { - return e + flagsPtr, err := BytePtrFromString(flags) + if err != nil { + return err } - return nil + return unveil(pathPtr, flagsPtr) } // UnveilBlock blocks future unveil calls. // For more information see unveil(2). func UnveilBlock() error { - // Both pointers must be nil. - var pathUnsafe, flagsUnsafe unsafe.Pointer - _, _, e := syscall.Syscall(SYS_UNVEIL, uintptr(pathUnsafe), uintptr(flagsUnsafe), 0) - if e != 0 { - return e + if err := supportsUnveil(); err != nil { + return err } + return unveil(nil, nil) +} + +// supportsUnveil checks for availability of the unveil(2) system call based +// on the running OpenBSD version. +func supportsUnveil() error { + maj, min, err := majmin() + if err != nil { + return err + } + + // unveil is not available before 6.4 + if maj < 6 || (maj == 6 && min <= 3) { + return fmt.Errorf("cannot call Unveil on OpenBSD %d.%d", maj, min) + } + return nil } diff --git a/tools/vendor/golang.org/x/sys/unix/xattr_bsd.go b/tools/vendor/golang.org/x/sys/unix/xattr_bsd.go index f5f8e9f36..e16879396 100644 --- a/tools/vendor/golang.org/x/sys/unix/xattr_bsd.go +++ b/tools/vendor/golang.org/x/sys/unix/xattr_bsd.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build freebsd || netbsd -// +build freebsd netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go b/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go index ca9799b79..2fb219d78 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && aix -// +build ppc,aix // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -maix32 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go index 200c8c26f..b0e6f5c85 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && aix -// +build ppc64,aix // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -maix64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go index 143007627..4308ac177 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && darwin -// +build amd64,darwin // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go @@ -1170,6 +1169,11 @@ const ( PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 + RENAME_EXCL = 0x4 + RENAME_NOFOLLOW_ANY = 0x10 + RENAME_RESERVED1 = 0x8 + RENAME_SECLUDE = 0x1 + RENAME_SWAP = 0x2 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go index ab044a742..c8068a7a1 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && darwin -// +build arm64,darwin // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go @@ -1170,6 +1169,11 @@ const ( PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 + RENAME_EXCL = 0x4 + RENAME_NOFOLLOW_ANY = 0x10 + RENAME_RESERVED1 = 0x8 + RENAME_SECLUDE = 0x1 + RENAME_SWAP = 0x2 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go index 17bba0e44..c0e0f8694 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && dragonfly -// +build amd64,dragonfly // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go index f8c2c5138..6c6923906 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && freebsd -// +build 386,freebsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m32 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go index 96310c3be..dd9163f8e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && freebsd -// +build amd64,freebsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go index 777b69def..493a2a793 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && freebsd -// +build arm,freebsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go index c557ac2db..8b437b307 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && freebsd -// +build arm64,freebsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_riscv64.go index 341b4d962..67c02dd57 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_freebsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && freebsd -// +build riscv64,freebsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux.go index f9c7f479b..01a70b246 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -1,7 +1,6 @@ // Code generated by mkmerge; DO NOT EDIT. //go:build linux -// +build linux package unix @@ -458,6 +457,7 @@ const ( B600 = 0x8 B75 = 0x2 B9600 = 0xd + BCACHEFS_SUPER_MAGIC = 0xca451a4e BDEVFS_MAGIC = 0x62646576 BINDERFS_SUPER_MAGIC = 0x6c6f6f70 BINFMTFS_MAGIC = 0x42494e4d @@ -481,14 +481,18 @@ const ( BPF_FROM_BE = 0x8 BPF_FROM_LE = 0x0 BPF_FS_MAGIC = 0xcafe4a11 + BPF_F_AFTER = 0x10 BPF_F_ALLOW_MULTI = 0x2 BPF_F_ALLOW_OVERRIDE = 0x1 BPF_F_ANY_ALIGNMENT = 0x2 - BPF_F_KPROBE_MULTI_RETURN = 0x1 + BPF_F_BEFORE = 0x8 + BPF_F_ID = 0x20 + BPF_F_NETFILTER_IP_DEFRAG = 0x1 BPF_F_QUERY_EFFECTIVE = 0x1 BPF_F_REPLACE = 0x4 BPF_F_SLEEPABLE = 0x10 BPF_F_STRICT_ALIGNMENT = 0x1 + BPF_F_TEST_REG_INVARIANTS = 0x80 BPF_F_TEST_RND_HI32 = 0x4 BPF_F_TEST_RUN_ON_CPU = 0x1 BPF_F_TEST_STATE_FREQ = 0x8 @@ -499,6 +503,7 @@ const ( BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 + BPF_JCOND = 0xe0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 @@ -521,6 +526,7 @@ const ( BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 + BPF_MEMSX = 0x80 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 @@ -653,6 +659,9 @@ const ( CAN_NPROTO = 0x8 CAN_RAW = 0x1 CAN_RAW_FILTER_MAX = 0x200 + CAN_RAW_XL_VCID_RX_FILTER = 0x4 + CAN_RAW_XL_VCID_TX_PASS = 0x2 + CAN_RAW_XL_VCID_TX_SET = 0x1 CAN_RTR_FLAG = 0x40000000 CAN_SFF_ID_BITS = 0xb CAN_SFF_MASK = 0x7ff @@ -776,6 +785,8 @@ const ( DEVLINK_GENL_MCGRP_CONFIG_NAME = "config" DEVLINK_GENL_NAME = "devlink" DEVLINK_GENL_VERSION = 0x1 + DEVLINK_PORT_FN_CAP_IPSEC_CRYPTO = 0x4 + DEVLINK_PORT_FN_CAP_IPSEC_PACKET = 0x8 DEVLINK_PORT_FN_CAP_MIGRATABLE = 0x2 DEVLINK_PORT_FN_CAP_ROCE = 0x1 DEVLINK_SB_THRESHOLD_TO_ALPHA_MAX = 0x14 @@ -918,6 +929,7 @@ const ( EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 + EPOLL_IOC_TYPE = 0x8a EROFS_SUPER_MAGIC_V1 = 0xe0f5e1e2 ESP_V4_FLOW = 0xa ESP_V6_FLOW = 0xc @@ -931,9 +943,6 @@ const ( ETHTOOL_FEC_OFF = 0x4 ETHTOOL_FEC_RS = 0x8 ETHTOOL_FLAG_ALL = 0x7 - ETHTOOL_FLAG_COMPACT_BITSETS = 0x1 - ETHTOOL_FLAG_OMIT_REPLY = 0x2 - ETHTOOL_FLAG_STATS = 0x4 ETHTOOL_FLASHDEV = 0x33 ETHTOOL_FLASH_MAX_FILENAME = 0x80 ETHTOOL_FWVERS_LEN = 0x20 @@ -1333,6 +1342,7 @@ const ( F_OFD_SETLK = 0x25 F_OFD_SETLKW = 0x26 F_OK = 0x0 + F_SEAL_EXEC = 0x20 F_SEAL_FUTURE_WRITE = 0x10 F_SEAL_GROW = 0x4 F_SEAL_SEAL = 0x1 @@ -1621,6 +1631,7 @@ const ( IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 + IP_LOCAL_PORT_RANGE = 0x33 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 @@ -1647,6 +1658,7 @@ const ( IP_PMTUDISC_OMIT = 0x5 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 + IP_PROTOCOL = 0x34 IP_RECVERR = 0xb IP_RECVERR_RFC4884 = 0x1a IP_RECVFRAGSIZE = 0x19 @@ -1692,12 +1704,15 @@ const ( KEXEC_ARCH_S390 = 0x160000 KEXEC_ARCH_SH = 0x2a0000 KEXEC_ARCH_X86_64 = 0x3e0000 + KEXEC_CRASH_HOTPLUG_SUPPORT = 0x8 + KEXEC_FILE_DEBUG = 0x8 KEXEC_FILE_NO_INITRAMFS = 0x4 KEXEC_FILE_ON_CRASH = 0x2 KEXEC_FILE_UNLOAD = 0x1 KEXEC_ON_CRASH = 0x1 KEXEC_PRESERVE_CONTEXT = 0x2 KEXEC_SEGMENT_MAX = 0x10 + KEXEC_UPDATE_ELFCOREHDR = 0x4 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CAPABILITIES = 0x1f KEYCTL_CAPS0_BIG_KEY = 0x10 @@ -1765,6 +1780,7 @@ const ( KEY_SPEC_USER_KEYRING = -0x4 KEY_SPEC_USER_SESSION_KEYRING = -0x5 LANDLOCK_ACCESS_FS_EXECUTE = 0x1 + LANDLOCK_ACCESS_FS_IOCTL_DEV = 0x8000 LANDLOCK_ACCESS_FS_MAKE_BLOCK = 0x800 LANDLOCK_ACCESS_FS_MAKE_CHAR = 0x40 LANDLOCK_ACCESS_FS_MAKE_DIR = 0x80 @@ -1779,6 +1795,8 @@ const ( LANDLOCK_ACCESS_FS_REMOVE_FILE = 0x20 LANDLOCK_ACCESS_FS_TRUNCATE = 0x4000 LANDLOCK_ACCESS_FS_WRITE_FILE = 0x2 + LANDLOCK_ACCESS_NET_BIND_TCP = 0x1 + LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2 LANDLOCK_CREATE_RULESET_VERSION = 0x1 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef @@ -1795,6 +1813,7 @@ const ( LOCK_SH = 0x1 LOCK_UN = 0x8 LOOP_CLR_FD = 0x4c01 + LOOP_CONFIGURE = 0x4c0a LOOP_CTL_ADD = 0x4c80 LOOP_CTL_GET_FREE = 0x4c82 LOOP_CTL_REMOVE = 0x4c81 @@ -1843,6 +1862,19 @@ const ( MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FIXED_NOREPLACE = 0x100000 + MAP_HUGE_16GB = 0x88000000 + MAP_HUGE_16KB = 0x38000000 + MAP_HUGE_16MB = 0x60000000 + MAP_HUGE_1GB = 0x78000000 + MAP_HUGE_1MB = 0x50000000 + MAP_HUGE_256MB = 0x70000000 + MAP_HUGE_2GB = 0x7c000000 + MAP_HUGE_2MB = 0x54000000 + MAP_HUGE_32MB = 0x64000000 + MAP_HUGE_512KB = 0x4c000000 + MAP_HUGE_512MB = 0x74000000 + MAP_HUGE_64KB = 0x40000000 + MAP_HUGE_8MB = 0x5c000000 MAP_HUGE_MASK = 0x3f MAP_HUGE_SHIFT = 0x1a MAP_PRIVATE = 0x2 @@ -1889,6 +1921,7 @@ const ( MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MNT_ID_REQ_SIZE_VER0 = 0x18 MODULE_INIT_COMPRESSED_FILE = 0x4 MODULE_INIT_IGNORE_MODVERSIONS = 0x1 MODULE_INIT_IGNORE_VERMAGIC = 0x2 @@ -2120,6 +2153,60 @@ const ( NFNL_SUBSYS_QUEUE = 0x3 NFNL_SUBSYS_ULOG = 0x4 NFS_SUPER_MAGIC = 0x6969 + NFT_CHAIN_FLAGS = 0x7 + NFT_CHAIN_MAXNAMELEN = 0x100 + NFT_CT_MAX = 0x17 + NFT_DATA_RESERVED_MASK = 0xffffff00 + NFT_DATA_VALUE_MAXLEN = 0x40 + NFT_EXTHDR_OP_MAX = 0x4 + NFT_FIB_RESULT_MAX = 0x3 + NFT_INNER_MASK = 0xf + NFT_LOGLEVEL_MAX = 0x8 + NFT_NAME_MAXLEN = 0x100 + NFT_NG_MAX = 0x1 + NFT_OBJECT_CONNLIMIT = 0x5 + NFT_OBJECT_COUNTER = 0x1 + NFT_OBJECT_CT_EXPECT = 0x9 + NFT_OBJECT_CT_HELPER = 0x3 + NFT_OBJECT_CT_TIMEOUT = 0x7 + NFT_OBJECT_LIMIT = 0x4 + NFT_OBJECT_MAX = 0xa + NFT_OBJECT_QUOTA = 0x2 + NFT_OBJECT_SECMARK = 0x8 + NFT_OBJECT_SYNPROXY = 0xa + NFT_OBJECT_TUNNEL = 0x6 + NFT_OBJECT_UNSPEC = 0x0 + NFT_OBJ_MAXNAMELEN = 0x100 + NFT_OSF_MAXGENRELEN = 0x10 + NFT_QUEUE_FLAG_BYPASS = 0x1 + NFT_QUEUE_FLAG_CPU_FANOUT = 0x2 + NFT_QUEUE_FLAG_MASK = 0x3 + NFT_REG32_COUNT = 0x10 + NFT_REG32_SIZE = 0x4 + NFT_REG_MAX = 0x4 + NFT_REG_SIZE = 0x10 + NFT_REJECT_ICMPX_MAX = 0x3 + NFT_RT_MAX = 0x4 + NFT_SECMARK_CTX_MAXLEN = 0x100 + NFT_SET_MAXNAMELEN = 0x100 + NFT_SOCKET_MAX = 0x3 + NFT_TABLE_F_MASK = 0x7 + NFT_TABLE_MAXNAMELEN = 0x100 + NFT_TRACETYPE_MAX = 0x3 + NFT_TUNNEL_F_MASK = 0x7 + NFT_TUNNEL_MAX = 0x1 + NFT_TUNNEL_MODE_MAX = 0x2 + NFT_USERDATA_MAXLEN = 0x100 + NFT_XFRM_KEY_MAX = 0x6 + NF_NAT_RANGE_MAP_IPS = 0x1 + NF_NAT_RANGE_MASK = 0x7f + NF_NAT_RANGE_NETMAP = 0x40 + NF_NAT_RANGE_PERSISTENT = 0x8 + NF_NAT_RANGE_PROTO_OFFSET = 0x20 + NF_NAT_RANGE_PROTO_RANDOM = 0x4 + NF_NAT_RANGE_PROTO_RANDOM_ALL = 0x14 + NF_NAT_RANGE_PROTO_RANDOM_FULLY = 0x10 + NF_NAT_RANGE_PROTO_SPECIFIED = 0x2 NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 @@ -2239,6 +2326,7 @@ const ( PERF_AUX_FLAG_PARTIAL = 0x4 PERF_AUX_FLAG_PMU_FORMAT_TYPE_MASK = 0xff00 PERF_AUX_FLAG_TRUNCATED = 0x1 + PERF_BRANCH_ENTRY_INFO_BITS_MAX = 0x21 PERF_BR_ARM64_DEBUG_DATA = 0x7 PERF_BR_ARM64_DEBUG_EXIT = 0x5 PERF_BR_ARM64_DEBUG_HALT = 0x4 @@ -2275,6 +2363,7 @@ const ( PERF_MEM_LVLNUM_PMEM = 0xe PERF_MEM_LVLNUM_RAM = 0xd PERF_MEM_LVLNUM_SHIFT = 0x21 + PERF_MEM_LVLNUM_UNC = 0x8 PERF_MEM_LVL_HIT = 0x2 PERF_MEM_LVL_IO = 0x1000 PERF_MEM_LVL_L1 = 0x8 @@ -2335,6 +2424,7 @@ const ( PERF_RECORD_MISC_USER = 0x2 PERF_SAMPLE_BRANCH_PLM_ALL = 0x7 PERF_SAMPLE_WEIGHT_TYPE = 0x1004000 + PID_FS_MAGIC = 0x50494446 PIPEFS_MAGIC = 0x50495045 PPPIOCGNPMODE = 0xc008744c PPPIOCNEWUNIT = 0xc004743e @@ -2403,6 +2493,7 @@ const ( PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 + PR_MDWE_NO_INHERIT = 0x2 PR_MDWE_REFUSE_EXEC_GAIN = 0x1 PR_MPX_DISABLE_MANAGEMENT = 0x2c PR_MPX_ENABLE_MANAGEMENT = 0x2b @@ -2421,6 +2512,23 @@ const ( PR_PAC_GET_ENABLED_KEYS = 0x3d PR_PAC_RESET_KEYS = 0x36 PR_PAC_SET_ENABLED_KEYS = 0x3c + PR_PPC_DEXCR_CTRL_CLEAR = 0x4 + PR_PPC_DEXCR_CTRL_CLEAR_ONEXEC = 0x10 + PR_PPC_DEXCR_CTRL_EDITABLE = 0x1 + PR_PPC_DEXCR_CTRL_MASK = 0x1f + PR_PPC_DEXCR_CTRL_SET = 0x2 + PR_PPC_DEXCR_CTRL_SET_ONEXEC = 0x8 + PR_PPC_DEXCR_IBRTPD = 0x1 + PR_PPC_DEXCR_NPHIE = 0x3 + PR_PPC_DEXCR_SBHE = 0x0 + PR_PPC_DEXCR_SRAPD = 0x2 + PR_PPC_GET_DEXCR = 0x48 + PR_PPC_SET_DEXCR = 0x49 + PR_RISCV_CTX_SW_FENCEI_OFF = 0x1 + PR_RISCV_CTX_SW_FENCEI_ON = 0x0 + PR_RISCV_SCOPE_PER_PROCESS = 0x0 + PR_RISCV_SCOPE_PER_THREAD = 0x1 + PR_RISCV_SET_ICACHE_FLUSH_CTX = 0x47 PR_RISCV_V_GET_CONTROL = 0x46 PR_RISCV_V_SET_CONTROL = 0x45 PR_RISCV_V_VSTATE_CTRL_CUR_MASK = 0x3 @@ -2607,8 +2715,9 @@ const ( RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 - RTAX_FEATURE_MASK = 0xf + RTAX_FEATURE_MASK = 0x1f RTAX_FEATURE_SACK = 0x2 + RTAX_FEATURE_TCP_USEC_TS = 0x10 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb @@ -2826,8 +2935,9 @@ const ( RWF_APPEND = 0x10 RWF_DSYNC = 0x2 RWF_HIPRI = 0x1 + RWF_NOAPPEND = 0x20 RWF_NOWAIT = 0x8 - RWF_SUPPORTED = 0x1f + RWF_SUPPORTED = 0x3f RWF_SYNC = 0x4 RWF_WRITE_LIFE_NOT_SET = 0x0 SCHED_BATCH = 0x3 @@ -2848,12 +2958,43 @@ const ( SCHED_RESET_ON_FORK = 0x40000000 SCHED_RR = 0x2 SCM_CREDENTIALS = 0x2 + SCM_PIDFD = 0x4 SCM_RIGHTS = 0x1 + SCM_SECURITY = 0x3 SCM_TIMESTAMP = 0x1d SC_LOG_FLUSH = 0x100000 + SECCOMP_ADDFD_FLAG_SEND = 0x2 + SECCOMP_ADDFD_FLAG_SETFD = 0x1 + SECCOMP_FILTER_FLAG_LOG = 0x2 + SECCOMP_FILTER_FLAG_NEW_LISTENER = 0x8 + SECCOMP_FILTER_FLAG_SPEC_ALLOW = 0x4 + SECCOMP_FILTER_FLAG_TSYNC = 0x1 + SECCOMP_FILTER_FLAG_TSYNC_ESRCH = 0x10 + SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV = 0x20 + SECCOMP_GET_ACTION_AVAIL = 0x2 + SECCOMP_GET_NOTIF_SIZES = 0x3 + SECCOMP_IOCTL_NOTIF_RECV = 0xc0502100 + SECCOMP_IOCTL_NOTIF_SEND = 0xc0182101 + SECCOMP_IOC_MAGIC = '!' SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECCOMP_RET_ACTION = 0x7fff0000 + SECCOMP_RET_ACTION_FULL = 0xffff0000 + SECCOMP_RET_ALLOW = 0x7fff0000 + SECCOMP_RET_DATA = 0xffff + SECCOMP_RET_ERRNO = 0x50000 + SECCOMP_RET_KILL = 0x0 + SECCOMP_RET_KILL_PROCESS = 0x80000000 + SECCOMP_RET_KILL_THREAD = 0x0 + SECCOMP_RET_LOG = 0x7ffc0000 + SECCOMP_RET_TRACE = 0x7ff00000 + SECCOMP_RET_TRAP = 0x30000 + SECCOMP_RET_USER_NOTIF = 0x7fc00000 + SECCOMP_SET_MODE_FILTER = 0x1 + SECCOMP_SET_MODE_STRICT = 0x0 + SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP = 0x1 + SECCOMP_USER_NOTIF_FLAG_CONTINUE = 0x1 SECRETMEM_MAGIC = 0x5345434d SECURITYFS_MAGIC = 0x73636673 SEEK_CUR = 0x1 @@ -2952,6 +3093,8 @@ const ( SIOCSMIIREG = 0x8949 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SK_DIAG_BPF_STORAGE_MAX = 0x3 + SK_DIAG_BPF_STORAGE_REQ_MAX = 0x1 SMACK_MAGIC = 0x43415d53 SMART_AUTOSAVE = 0xd2 SMART_AUTO_OFFLINE = 0xdb @@ -2972,6 +3115,8 @@ const ( SOCKFS_MAGIC = 0x534f434b SOCK_BUF_LOCK_MASK = 0x3 SOCK_DCCP = 0x6 + SOCK_DESTROY = 0x15 + SOCK_DIAG_BY_FAMILY = 0x14 SOCK_IOC_TYPE = 0x89 SOCK_PACKET = 0xa SOCK_RAW = 0x3 @@ -3013,6 +3158,7 @@ const ( SOL_TIPC = 0x10f SOL_TLS = 0x11a SOL_UDP = 0x11 + SOL_VSOCK = 0x11f SOL_X25 = 0x106 SOL_XDP = 0x11b SOMAXCONN = 0x1000 @@ -3072,10 +3218,12 @@ const ( STATX_GID = 0x10 STATX_INO = 0x100 STATX_MNT_ID = 0x1000 + STATX_MNT_ID_UNIQUE = 0x4000 STATX_MODE = 0x2 STATX_MTIME = 0x40 STATX_NLINK = 0x4 STATX_SIZE = 0x200 + STATX_SUBVOL = 0x8000 STATX_TYPE = 0x1 STATX_UID = 0x8 STATX__RESERVED = 0x80000000 @@ -3159,6 +3307,7 @@ const ( TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_IFINDEX = 0x2 TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 @@ -3461,18 +3610,24 @@ const ( XDP_PACKET_HEADROOM = 0x100 XDP_PGOFF_RX_RING = 0x0 XDP_PGOFF_TX_RING = 0x80000000 + XDP_PKT_CONTD = 0x1 XDP_RING_NEED_WAKEUP = 0x1 XDP_RX_RING = 0x2 XDP_SHARED_UMEM = 0x1 XDP_STATISTICS = 0x7 + XDP_TXMD_FLAGS_CHECKSUM = 0x2 + XDP_TXMD_FLAGS_TIMESTAMP = 0x1 + XDP_TX_METADATA = 0x2 XDP_TX_RING = 0x3 XDP_UMEM_COMPLETION_RING = 0x6 XDP_UMEM_FILL_RING = 0x5 XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000 XDP_UMEM_PGOFF_FILL_RING = 0x100000000 XDP_UMEM_REG = 0x4 + XDP_UMEM_TX_SW_CSUM = 0x2 XDP_UMEM_UNALIGNED_CHUNK_FLAG = 0x1 XDP_USE_NEED_WAKEUP = 0x8 + XDP_USE_SG = 0x10 XDP_ZEROCOPY = 0x4 XENFS_SUPER_MAGIC = 0xabba1974 XFS_SUPER_MAGIC = 0x58465342 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 30aee00a5..684a5168d 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && linux -// +build 386,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/386/include -m32 _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -119,6 +120,7 @@ const ( IXOFF = 0x1000 IXON = 0x400 MAP_32BIT = 0x40 + MAP_ABOVE4G = 0x80 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -282,6 +284,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 8ebfa5127..61d74b592 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && linux -// +build amd64,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/amd64/include -m64 _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -119,6 +120,7 @@ const ( IXOFF = 0x1000 IXON = 0x400 MAP_32BIT = 0x40 + MAP_ABOVE4G = 0x80 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -283,6 +285,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index 271a21cdc..a28c9e3e8 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && linux -// +build arm,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/arm/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -289,6 +290,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 910c330a3..ab5d1fe8e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && linux -// +build arm64,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/arm64/include -fsigned-char _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 ESR_MAGIC = 0x45535201 EXTPROC = 0x10000 @@ -88,6 +89,7 @@ const ( FICLONE = 0x40049409 FICLONERANGE = 0x4020940d FLUSHO = 0x1000 + FPMR_MAGIC = 0x46504d52 FPSIMD_MAGIC = 0x46508001 FS_IOC_ENABLE_VERITY = 0x40806685 FS_IOC_GETFLAGS = 0x80086601 @@ -279,6 +281,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index a640798c9..c523090e7 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build loong64 && linux -// +build loong64,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/loong64/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -119,6 +120,7 @@ const ( IXOFF = 0x1000 IXON = 0x400 LASX_CTX_MAGIC = 0x41535801 + LBT_CTX_MAGIC = 0x42540001 LSX_CTX_MAGIC = 0x53580001 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 @@ -275,6 +277,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 0d5925d34..01e6ea780 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips && linux -// +build mips,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/mips/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -282,6 +283,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index d72a00e0b..7aa610b1e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && linux -// +build mips64,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/mips64/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -282,6 +283,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index 02ba129f8..92af771b4 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64le && linux -// +build mips64le,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/mips64le/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -282,6 +283,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 8daa6dd96..b27ef5e6f 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mipsle && linux -// +build mipsle,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/mipsle/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -282,6 +283,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x80 SIOCATMARK = 0x40047307 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index 63c8fa2f7..237a2cefb 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && linux -// +build ppc,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/ppc/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000000 FF1 = 0x4000 @@ -337,6 +338,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 930799ec1..4a5c555a3 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && linux -// +build ppc64,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/ppc64/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000000 FF1 = 0x4000 @@ -341,6 +342,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 8605a7dd7..a02fb49a5 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64le && linux -// +build ppc64le,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/ppc64le/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x20 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000000 FF1 = 0x4000 @@ -341,6 +342,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index 95a016f1c..e26a7c61b 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && linux -// +build riscv64,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/riscv64/include _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -228,6 +229,9 @@ const ( PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCXFERUNIT = 0x744e PR_SET_PTRACER_ANY = 0xffffffffffffffff + PTRACE_GETFDPIC = 0x21 + PTRACE_GETFDPIC_EXEC = 0x0 + PTRACE_GETFDPIC_INTERP = 0x1 RLIMIT_AS = 0x9 RLIMIT_MEMLOCK = 0x8 RLIMIT_NOFILE = 0x7 @@ -270,6 +274,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 1ae0108f5..c48f7c210 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build s390x && linux -// +build s390x,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/s390x/include -fsigned-char _const.go @@ -79,6 +78,8 @@ const ( ECHOPRT = 0x400 EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 + EPIOCGPARAMS = 0x80088a02 + EPIOCSPARAMS = 0x40088a01 EPOLL_CLOEXEC = 0x80000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -345,6 +346,9 @@ const ( SCM_TIMESTAMPNS = 0x23 SCM_TXTIME = 0x3d SCM_WIFI_STATUS = 0x29 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x40082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x40082104 SFD_CLOEXEC = 0x80000 SFD_NONBLOCK = 0x800 SIOCATMARK = 0x8905 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 1bb7c6333..ad4b9aace 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build sparc64 && linux -// +build sparc64,linux // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -Wall -Werror -static -I/tmp/sparc64/include _const.go @@ -83,6 +82,8 @@ const ( EFD_CLOEXEC = 0x400000 EFD_NONBLOCK = 0x4000 EMT_TAGOVF = 0x1 + EPIOCGPARAMS = 0x40088a02 + EPIOCSPARAMS = 0x80088a01 EPOLL_CLOEXEC = 0x400000 EXTPROC = 0x10000 FF1 = 0x8000 @@ -336,6 +337,9 @@ const ( SCM_TIMESTAMPNS = 0x21 SCM_TXTIME = 0x3f SCM_WIFI_STATUS = 0x25 + SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 + SECCOMP_IOCTL_NOTIF_ID_VALID = 0x80082102 + SECCOMP_IOCTL_NOTIF_SET_FLAGS = 0x80082104 SFD_CLOEXEC = 0x400000 SFD_NONBLOCK = 0x4000 SF_FP = 0x38 diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go index 72f7420d2..130085df4 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && netbsd -// +build 386,netbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m32 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go index 8d4eb0c08..84769a1a3 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && netbsd -// +build amd64,netbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go index 9eef9749f..602ded003 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && netbsd -// +build arm,netbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -marm _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go index 3b62ba192..efc0406ee 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && netbsd -// +build arm64,netbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go index af20e474b..5a6500f83 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && openbsd -// +build 386,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m32 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go index 6015fcb2b..a5aeeb979 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && openbsd -// +build amd64,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go index 8d44955e4..0e9748a72 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && openbsd -// +build arm,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go index ae16fe754..4f4449abc 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && openbsd -// +build arm64,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go index 03d90fe35..76a363f0f 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && openbsd -// +build mips64,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_ppc64.go index 8e2c51b1e..43ca0cdfd 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && openbsd -// +build ppc64,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_riscv64.go index 13d403031..b1b8bb200 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_openbsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && openbsd -// +build riscv64,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go b/tools/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go index 1afee6a08..d2ddd3176 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && solaris -// +build amd64,solaris // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m64 _const.go diff --git a/tools/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go b/tools/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go index fc7d0506f..da08b2ab3 100644 --- a/tools/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build zos && s390x -// +build zos,s390x // Hand edited based on zerrors_linux_s390x.go // TODO: auto-generate. @@ -11,41 +10,99 @@ package unix const ( - BRKINT = 0x0001 - CLOCK_MONOTONIC = 0x1 - CLOCK_PROCESS_CPUTIME_ID = 0x2 - CLOCK_REALTIME = 0x0 - CLOCK_THREAD_CPUTIME_ID = 0x3 - CS8 = 0x0030 - CSIZE = 0x0030 - ECHO = 0x00000008 - ECHONL = 0x00000001 - FD_CLOEXEC = 0x01 - FD_CLOFORK = 0x02 - FNDELAY = 0x04 - F_CLOSFD = 9 - F_CONTROL_CVT = 13 - F_DUPFD = 0 - F_DUPFD2 = 8 - F_GETFD = 1 - F_GETFL = 259 - F_GETLK = 5 - F_GETOWN = 10 - F_OK = 0x0 - F_RDLCK = 1 - F_SETFD = 2 - F_SETFL = 4 - F_SETLK = 6 - F_SETLKW = 7 - F_SETOWN = 11 - F_SETTAG = 12 - F_UNLCK = 3 - F_WRLCK = 2 - FSTYPE_ZFS = 0xe9 //"Z" - FSTYPE_HFS = 0xc8 //"H" - FSTYPE_NFS = 0xd5 //"N" - FSTYPE_TFS = 0xe3 //"T" - FSTYPE_AUTOMOUNT = 0xc1 //"A" + BRKINT = 0x0001 + CLOCAL = 0x1 + CLOCK_MONOTONIC = 0x1 + CLOCK_PROCESS_CPUTIME_ID = 0x2 + CLOCK_REALTIME = 0x0 + CLOCK_THREAD_CPUTIME_ID = 0x3 + CLONE_NEWIPC = 0x08000000 + CLONE_NEWNET = 0x40000000 + CLONE_NEWNS = 0x00020000 + CLONE_NEWPID = 0x20000000 + CLONE_NEWUTS = 0x04000000 + CLONE_PARENT = 0x00008000 + CS8 = 0x0030 + CSIZE = 0x0030 + ECHO = 0x00000008 + ECHONL = 0x00000001 + EFD_SEMAPHORE = 0x00002000 + EFD_CLOEXEC = 0x00001000 + EFD_NONBLOCK = 0x00000004 + EPOLL_CLOEXEC = 0x00001000 + EPOLL_CTL_ADD = 0 + EPOLL_CTL_MOD = 1 + EPOLL_CTL_DEL = 2 + EPOLLRDNORM = 0x0001 + EPOLLRDBAND = 0x0002 + EPOLLIN = 0x0003 + EPOLLOUT = 0x0004 + EPOLLWRBAND = 0x0008 + EPOLLPRI = 0x0010 + EPOLLERR = 0x0020 + EPOLLHUP = 0x0040 + EPOLLEXCLUSIVE = 0x20000000 + EPOLLONESHOT = 0x40000000 + FD_CLOEXEC = 0x01 + FD_CLOFORK = 0x02 + FD_SETSIZE = 0x800 + FNDELAY = 0x04 + F_CLOSFD = 9 + F_CONTROL_CVT = 13 + F_DUPFD = 0 + F_DUPFD2 = 8 + F_GETFD = 1 + F_GETFL = 259 + F_GETLK = 5 + F_GETOWN = 10 + F_OK = 0x0 + F_RDLCK = 1 + F_SETFD = 2 + F_SETFL = 4 + F_SETLK = 6 + F_SETLKW = 7 + F_SETOWN = 11 + F_SETTAG = 12 + F_UNLCK = 3 + F_WRLCK = 2 + FSTYPE_ZFS = 0xe9 //"Z" + FSTYPE_HFS = 0xc8 //"H" + FSTYPE_NFS = 0xd5 //"N" + FSTYPE_TFS = 0xe3 //"T" + FSTYPE_AUTOMOUNT = 0xc1 //"A" + GRND_NONBLOCK = 1 + GRND_RANDOM = 2 + HUPCL = 0x0100 // Hang up on last close + IN_CLOEXEC = 0x00001000 + IN_NONBLOCK = 0x00000004 + IN_ACCESS = 0x00000001 + IN_MODIFY = 0x00000002 + IN_ATTRIB = 0x00000004 + IN_CLOSE_WRITE = 0x00000008 + IN_CLOSE_NOWRITE = 0x00000010 + IN_OPEN = 0x00000020 + IN_MOVED_FROM = 0x00000040 + IN_MOVED_TO = 0x00000080 + IN_CREATE = 0x00000100 + IN_DELETE = 0x00000200 + IN_DELETE_SELF = 0x00000400 + IN_MOVE_SELF = 0x00000800 + IN_UNMOUNT = 0x00002000 + IN_Q_OVERFLOW = 0x00004000 + IN_IGNORED = 0x00008000 + IN_CLOSE = (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) + IN_MOVE = (IN_MOVED_FROM | IN_MOVED_TO) + IN_ALL_EVENTS = (IN_ACCESS | IN_MODIFY | IN_ATTRIB | + IN_CLOSE | IN_OPEN | IN_MOVE | + IN_CREATE | IN_DELETE | IN_DELETE_SELF | + IN_MOVE_SELF) + IN_ONLYDIR = 0x01000000 + IN_DONT_FOLLOW = 0x02000000 + IN_EXCL_UNLINK = 0x04000000 + IN_MASK_CREATE = 0x10000000 + IN_MASK_ADD = 0x20000000 + IN_ISDIR = 0x40000000 + IN_ONESHOT = 0x80000000 IP6F_MORE_FRAG = 0x0001 IP6F_OFF_MASK = 0xfff8 IP6F_RESERVED_MASK = 0x0006 @@ -153,10 +210,18 @@ const ( IP_PKTINFO = 101 IP_RECVPKTINFO = 102 IP_TOS = 2 - IP_TTL = 3 + IP_TTL = 14 IP_UNBLOCK_SOURCE = 11 + ICMP6_FILTER = 1 + MCAST_INCLUDE = 0 + MCAST_EXCLUDE = 1 + MCAST_JOIN_GROUP = 40 + MCAST_LEAVE_GROUP = 41 + MCAST_JOIN_SOURCE_GROUP = 42 + MCAST_LEAVE_SOURCE_GROUP = 43 + MCAST_BLOCK_SOURCE = 44 + MCAST_UNBLOCK_SOURCE = 46 ICANON = 0x0010 - ICMP6_FILTER = 0x26 ICRNL = 0x0002 IEXTEN = 0x0020 IGNBRK = 0x0004 @@ -166,10 +231,10 @@ const ( ISTRIP = 0x0080 IXON = 0x0200 IXOFF = 0x0100 - LOCK_SH = 0x1 // Not exist on zOS - LOCK_EX = 0x2 // Not exist on zOS - LOCK_NB = 0x4 // Not exist on zOS - LOCK_UN = 0x8 // Not exist on zOS + LOCK_SH = 0x1 + LOCK_EX = 0x2 + LOCK_NB = 0x4 + LOCK_UN = 0x8 POLLIN = 0x0003 POLLOUT = 0x0004 POLLPRI = 0x0010 @@ -183,15 +248,29 @@ const ( MAP_PRIVATE = 0x1 // changes are private MAP_SHARED = 0x2 // changes are shared MAP_FIXED = 0x4 // place exactly - MCAST_JOIN_GROUP = 40 - MCAST_LEAVE_GROUP = 41 - MCAST_JOIN_SOURCE_GROUP = 42 - MCAST_LEAVE_SOURCE_GROUP = 43 - MCAST_BLOCK_SOURCE = 44 - MCAST_UNBLOCK_SOURCE = 45 + __MAP_MEGA = 0x8 + __MAP_64 = 0x10 + MAP_ANON = 0x20 + MAP_ANONYMOUS = 0x20 MS_SYNC = 0x1 // msync - synchronous writes MS_ASYNC = 0x2 // asynchronous writes MS_INVALIDATE = 0x4 // invalidate mappings + MS_BIND = 0x00001000 + MS_MOVE = 0x00002000 + MS_NOSUID = 0x00000002 + MS_PRIVATE = 0x00040000 + MS_REC = 0x00004000 + MS_REMOUNT = 0x00008000 + MS_RDONLY = 0x00000001 + MS_UNBINDABLE = 0x00020000 + MNT_DETACH = 0x00000004 + ZOSDSFS_SUPER_MAGIC = 0x44534653 // zOS DSFS + NFS_SUPER_MAGIC = 0x6969 // NFS + NSFS_MAGIC = 0x6e736673 // PROCNS + PROC_SUPER_MAGIC = 0x9fa0 // proc FS + ZOSTFS_SUPER_MAGIC = 0x544653 // zOS TFS + ZOSUFS_SUPER_MAGIC = 0x554653 // zOS UFS + ZOSZFS_SUPER_MAGIC = 0x5A4653 // zOS ZFS MTM_RDONLY = 0x80000000 MTM_RDWR = 0x40000000 MTM_UMOUNT = 0x10000000 @@ -206,13 +285,20 @@ const ( MTM_REMOUNT = 0x00000100 MTM_NOSECURITY = 0x00000080 NFDBITS = 0x20 + ONLRET = 0x0020 // NL performs CR function O_ACCMODE = 0x03 O_APPEND = 0x08 O_ASYNCSIG = 0x0200 O_CREAT = 0x80 + O_DIRECT = 0x00002000 + O_NOFOLLOW = 0x00004000 + O_DIRECTORY = 0x00008000 + O_PATH = 0x00080000 + O_CLOEXEC = 0x00001000 O_EXCL = 0x40 O_GETFL = 0x0F O_LARGEFILE = 0x0400 + O_NDELAY = 0x4 O_NONBLOCK = 0x04 O_RDONLY = 0x02 O_RDWR = 0x03 @@ -249,6 +335,7 @@ const ( AF_IUCV = 17 AF_LAT = 14 AF_LINK = 18 + AF_LOCAL = AF_UNIX // AF_LOCAL is an alias for AF_UNIX AF_MAX = 30 AF_NBS = 7 AF_NDD = 23 @@ -286,15 +373,33 @@ const ( RLIMIT_AS = 5 RLIMIT_NOFILE = 6 RLIMIT_MEMLIMIT = 7 + RLIMIT_MEMLOCK = 0x8 RLIM_INFINITY = 2147483647 + SCHED_FIFO = 0x2 + SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x01 SF_CLOSE = 0x00000002 SF_REUSE = 0x00000001 + SHM_RND = 0x2 + SHM_RDONLY = 0x1 + SHMLBA = 0x1000 + IPC_STAT = 0x3 + IPC_SET = 0x2 + IPC_RMID = 0x1 + IPC_PRIVATE = 0x0 + IPC_CREAT = 0x1000000 + __IPC_MEGA = 0x4000000 + __IPC_SHAREAS = 0x20000000 + __IPC_BELOWBAR = 0x10000000 + IPC_EXCL = 0x2000000 + __IPC_GIGA = 0x8000000 SHUT_RD = 0 SHUT_RDWR = 2 SHUT_WR = 1 + SOCK_CLOEXEC = 0x00001000 SOCK_CONN_DGRAM = 6 SOCK_DGRAM = 2 + SOCK_NONBLOCK = 0x800 SOCK_RAW = 3 SOCK_RDM = 4 SOCK_SEQPACKET = 5 @@ -379,8 +484,6 @@ const ( S_IFMST = 0x00FF0000 TCP_KEEPALIVE = 0x8 TCP_NODELAY = 0x1 - TCP_INFO = 0xb - TCP_USER_TIMEOUT = 0x1 TIOCGWINSZ = 0x4008a368 TIOCSWINSZ = 0x8008a367 TIOCSBRK = 0x2000a77b @@ -428,7 +531,10 @@ const ( VSUSP = 9 VTIME = 10 WCONTINUED = 0x4 + WEXITED = 0x8 WNOHANG = 0x1 + WNOWAIT = 0x20 + WSTOPPED = 0x10 WUNTRACED = 0x2 _BPX_SWAP = 1 _BPX_NONSWAP = 2 @@ -453,8 +559,28 @@ const ( MADV_FREE = 15 // for Linux compatibility -- no zos semantics MADV_WIPEONFORK = 16 // for Linux compatibility -- no zos semantics MADV_KEEPONFORK = 17 // for Linux compatibility -- no zos semantics - AT_SYMLINK_NOFOLLOW = 1 // for Unix compatibility -- no zos semantics - AT_FDCWD = 2 // for Unix compatibility -- no zos semantics + AT_SYMLINK_FOLLOW = 0x400 + AT_SYMLINK_NOFOLLOW = 0x100 + XATTR_CREATE = 0x1 + XATTR_REPLACE = 0x2 + P_PID = 0 + P_PGID = 1 + P_ALL = 2 + PR_SET_NAME = 15 + PR_GET_NAME = 16 + PR_SET_NO_NEW_PRIVS = 38 + PR_GET_NO_NEW_PRIVS = 39 + PR_SET_DUMPABLE = 4 + PR_GET_DUMPABLE = 3 + PR_SET_PDEATHSIG = 1 + PR_GET_PDEATHSIG = 2 + PR_SET_CHILD_SUBREAPER = 36 + PR_GET_CHILD_SUBREAPER = 37 + AT_FDCWD = -100 + AT_EACCESS = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_REMOVEDIR = 0x200 + RENAME_NOREPLACE = 1 << 0 ) const ( @@ -477,6 +603,7 @@ const ( EMLINK = Errno(125) ENAMETOOLONG = Errno(126) ENFILE = Errno(127) + ENOATTR = Errno(265) ENODEV = Errno(128) ENOENT = Errno(129) ENOEXEC = Errno(130) @@ -701,7 +828,7 @@ var errorList = [...]struct { {145, "EDC5145I", "The parameter list is too long, or the message to receive was too large for the buffer."}, {146, "EDC5146I", "Too many levels of symbolic links."}, {147, "EDC5147I", "Illegal byte sequence."}, - {148, "", ""}, + {148, "EDC5148I", "The named attribute or data not available."}, {149, "EDC5149I", "Value Overflow Error."}, {150, "EDC5150I", "UNIX System Services is not active."}, {151, "EDC5151I", "Dynamic allocation error."}, @@ -744,6 +871,7 @@ var errorList = [...]struct { {259, "EDC5259I", "A CUN_RS_NO_CONVERSION error was issued by Unicode Services."}, {260, "EDC5260I", "A CUN_RS_TABLE_NOT_ALIGNED error was issued by Unicode Services."}, {262, "EDC5262I", "An iconv() function encountered an unexpected error while using Unicode Services."}, + {265, "EDC5265I", "The named attribute not available."}, {1000, "EDC8000I", "A bad socket-call constant was found in the IUCV header."}, {1001, "EDC8001I", "An error was found in the IUCV header."}, {1002, "EDC8002I", "A socket descriptor is out of range."}, diff --git a/tools/vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go b/tools/vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go index 97f20ca28..586317c78 100644 --- a/tools/vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go @@ -1,8 +1,6 @@ // Code generated by linux/mkall.go generatePtracePair("arm", "arm64"). DO NOT EDIT. //go:build linux && (arm || arm64) -// +build linux -// +build arm arm64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go b/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go index 0b5f79430..d7c881be7 100644 --- a/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go @@ -1,8 +1,6 @@ // Code generated by linux/mkall.go generatePtracePair("mips", "mips64"). DO NOT EDIT. //go:build linux && (mips || mips64) -// +build linux -// +build mips mips64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go b/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go index 2807f7e64..2d2de5d29 100644 --- a/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go @@ -1,8 +1,6 @@ // Code generated by linux/mkall.go generatePtracePair("mipsle", "mips64le"). DO NOT EDIT. //go:build linux && (mipsle || mips64le) -// +build linux -// +build mipsle mips64le package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zptrace_x86_linux.go b/tools/vendor/golang.org/x/sys/unix/zptrace_x86_linux.go index 281ea64e3..5adc79fb5 100644 --- a/tools/vendor/golang.org/x/sys/unix/zptrace_x86_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/zptrace_x86_linux.go @@ -1,8 +1,6 @@ // Code generated by linux/mkall.go generatePtracePair("386", "amd64"). DO NOT EDIT. //go:build linux && (386 || amd64) -// +build linux -// +build 386 amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s b/tools/vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s new file mode 100644 index 000000000..b77ff5db9 --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s @@ -0,0 +1,364 @@ +// go run mksyscall_zos_s390x.go -o_sysnum zsysnum_zos_s390x.go -o_syscall zsyscall_zos_s390x.go -i_syscall syscall_zos_s390x.go -o_asm zsymaddr_zos_s390x.s +// Code generated by the command above; see README.md. DO NOT EDIT. + +//go:build zos && s390x +#include "textflag.h" + +// provide the address of function variable to be fixed up. + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FlistxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Flistxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FremovexattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fremovexattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FgetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fgetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FsetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fsetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_accept4Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·accept4(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_RemovexattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Removexattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_Dup3Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Dup3(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_DirfdAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Dirfd(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollCreateAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollCreate(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollCreate1Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollCreate1(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollCtlAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollCtl(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollPwaitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollPwait(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EpollWaitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·EpollWait(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_EventfdAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Eventfd(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FaccessatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Faccessat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FchmodatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fchmodat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FchownatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fchownat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FdatasyncAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fdatasync(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_fstatatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·fstatat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LgetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lgetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LsetxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lsetxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FstatfsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Fstatfs(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FutimesAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Futimes(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_FutimesatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Futimesat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_GetrandomAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Getrandom(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyInitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyInit(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyInit1Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyInit1(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyAddWatchAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyAddWatch(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_InotifyRmWatchAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·InotifyRmWatch(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_ListxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Listxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LlistxattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Llistxattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LremovexattrAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lremovexattr(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LutimesAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Lutimes(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_StatfsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Statfs(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SyncfsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Syncfs(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_UnshareAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Unshare(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_LinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Linkat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_MkdiratAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mkdirat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_MknodatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Mknodat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_PivotRootAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·PivotRoot(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_PrctlAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Prctl(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_PrlimitAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Prlimit(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_RenameatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Renameat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_Renameat2Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Renameat2(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SethostnameAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Sethostname(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SetnsAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Setns(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_SymlinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Symlinkat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_UnlinkatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·Unlinkat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_openatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·openat(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_openat2Addr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·openat2(SB), R8 + MOVD R8, ret+0(FP) + RET + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +TEXT ·get_utimensatAddr(SB), NOSPLIT|NOFRAME, $0-8 + MOVD $·utimensat(SB), R8 + MOVD R8, ret+0(FP) + RET diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go index d1d1d2331..6ea64a3c0 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build aix && ppc -// +build aix,ppc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go index f99a18adc..99ee4399a 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build aix && ppc64 -// +build aix,ppc64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go index c4d50ae50..b68a78362 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build aix && ppc64 && gc -// +build aix,ppc64,gc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go index 6903d3b09..0a87450bf 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build aix && ppc64 && gccgo -// +build aix,ppc64,gccgo package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index 1cad561e9..b622533ef 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build darwin && amd64 -// +build darwin,amd64 package unix @@ -741,6 +740,54 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func renamexNp(from string, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_renamex_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renamex_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renamex_np renamex_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func renameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameatx_np_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), uintptr(flag), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renameatx_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renameatx_np renameatx_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { @@ -761,6 +808,39 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func pthread_chdir_np(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_pthread_chdir_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_chdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_chdir_np pthread_chdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pthread_fchdir_np(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_pthread_fchdir_np_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_fchdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_fchdir_np pthread_fchdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) { _, _, e1 := syscall_syscall6(libc_sendfile_trampoline_addr, uintptr(infd), uintptr(outfd), uintptr(offset), uintptr(unsafe.Pointer(len)), uintptr(hdtr), uintptr(flags)) if e1 != 0 { diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s index 8b8bb2840..cfe6646ba 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s @@ -223,11 +223,31 @@ TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_trampoline<>(SB) +TEXT libc_renamex_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renamex_np(SB) +GLOBL ·libc_renamex_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renamex_np_trampoline_addr(SB)/8, $libc_renamex_np_trampoline<>(SB) + +TEXT libc_renameatx_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renameatx_np(SB) +GLOBL ·libc_renameatx_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renameatx_np_trampoline_addr(SB)/8, $libc_renameatx_np_trampoline<>(SB) + TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sysctl(SB) GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_pthread_chdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_chdir_np(SB) +GLOBL ·libc_pthread_chdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_chdir_np_trampoline_addr(SB)/8, $libc_pthread_chdir_np_trampoline<>(SB) + +TEXT libc_pthread_fchdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_fchdir_np(SB) +GLOBL ·libc_pthread_fchdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_fchdir_np_trampoline_addr(SB)/8, $libc_pthread_fchdir_np_trampoline<>(SB) + TEXT libc_sendfile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendfile(SB) GLOBL ·libc_sendfile_trampoline_addr(SB), RODATA, $8 diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index b18edbd0e..13f624f69 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build darwin && arm64 -// +build darwin,arm64 package unix @@ -741,6 +740,54 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func renamexNp(from string, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_renamex_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renamex_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renamex_np renamex_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func renameatxNp(fromfd int, from string, tofd int, to string, flag uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_renameatx_np_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), uintptr(flag), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_renameatx_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renameatx_np renameatx_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { @@ -761,6 +808,39 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func pthread_chdir_np(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall_syscall(libc_pthread_chdir_np_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_chdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_chdir_np pthread_chdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pthread_fchdir_np(fd int) (err error) { + _, _, e1 := syscall_syscall(libc_pthread_fchdir_np_trampoline_addr, uintptr(fd), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pthread_fchdir_np_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pthread_fchdir_np pthread_fchdir_np "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) { _, _, e1 := syscall_syscall6(libc_sendfile_trampoline_addr, uintptr(infd), uintptr(outfd), uintptr(offset), uintptr(unsafe.Pointer(len)), uintptr(hdtr), uintptr(flags)) if e1 != 0 { diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s index 08362c1ab..fe222b75d 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s @@ -223,11 +223,31 @@ TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_trampoline<>(SB) +TEXT libc_renamex_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renamex_np(SB) +GLOBL ·libc_renamex_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renamex_np_trampoline_addr(SB)/8, $libc_renamex_np_trampoline<>(SB) + +TEXT libc_renameatx_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renameatx_np(SB) +GLOBL ·libc_renameatx_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renameatx_np_trampoline_addr(SB)/8, $libc_renameatx_np_trampoline<>(SB) + TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sysctl(SB) GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_pthread_chdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_chdir_np(SB) +GLOBL ·libc_pthread_chdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_chdir_np_trampoline_addr(SB)/8, $libc_pthread_chdir_np_trampoline<>(SB) + +TEXT libc_pthread_fchdir_np_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pthread_fchdir_np(SB) +GLOBL ·libc_pthread_fchdir_np_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pthread_fchdir_np_trampoline_addr(SB)/8, $libc_pthread_fchdir_np_trampoline<>(SB) + TEXT libc_sendfile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendfile(SB) GLOBL ·libc_sendfile_trampoline_addr(SB), RODATA, $8 diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go index 0c67df64a..aad65fc79 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build dragonfly && amd64 -// +build dragonfly,amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index e6e05d145..c0096391a 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && 386 -// +build freebsd,386 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 7508accac..7664df749 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && amd64 -// +build freebsd,amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go index 7b56aead4..ae099182c 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && arm -// +build freebsd,arm package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go index cc623dcaa..11fd5d45b 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && arm64 -// +build freebsd,arm64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go index 581849197..c3d2d6530 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build freebsd && riscv64 -// +build freebsd,riscv64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go index 6be25cd19..c698cbc01 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build illumos && amd64 -// +build illumos,amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 1ff3aec74..1bc1a5adb 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -1,7 +1,6 @@ // Code generated by mkmerge; DO NOT EDIT. //go:build linux -// +build linux package unix @@ -38,6 +37,21 @@ func fchmodat(dirfd int, path string, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fchmodat2(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -892,6 +906,16 @@ func Fspick(dirfd int, pathName string, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) { + _, _, e1 := Syscall6(SYS_FSCONFIG, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(value)), uintptr(aux), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { @@ -2195,3 +2219,29 @@ func schedGetattr(pid int, attr *SchedAttr, size uint, flags uint) (err error) { } return } + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) (err error) { + _, _, e1 := Syscall6(SYS_CACHESTAT, uintptr(fd), uintptr(unsafe.Pointer(crange)), uintptr(unsafe.Pointer(cstat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mseal(b []byte, flags uint) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall(SYS_MSEAL, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go index 07b549cc2..4def3e9fc 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && 386 -// +build linux,386 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go index 5f481bf83..fef2bc8ba 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && amd64 -// +build linux,amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go index 824cd52c7..a9fd76a88 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && arm -// +build linux,arm package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go index e77aecfe9..460065028 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && arm64 -// +build linux,arm64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go index 806ffd1e1..c8987d264 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && loong64 -// +build linux,loong64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go index 961a3afb7..921f43061 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mips -// +build linux,mips package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go index ed05005e9..44f067829 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mips64 -// +build linux,mips64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go index d365b718f..e7fa0abf0 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mips64le -// +build linux,mips64le package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go index c3f1b8bbd..8c5125675 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && mipsle -// +build linux,mipsle package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go index a6574cf98..7392fd45e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && ppc -// +build linux,ppc package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index f40990264..41180434e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && ppc64 -// +build linux,ppc64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index 9dfcc2997..40c6ce7ae 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && ppc64le -// +build linux,ppc64le package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go index 0ab4f2ed7..2cfe34adb 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && riscv64 -// +build linux,riscv64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go index 6cde32237..61e6f0709 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && s390x -// +build linux,s390x package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 5253d65bf..834b84204 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build linux && sparc64 -// +build linux,sparc64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go index 2df3c5bac..e91ebc14a 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && 386 -// +build netbsd,386 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go index a60556bab..be28babbc 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && amd64 -// +build netbsd,amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go index 9f788917a..fb587e826 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && arm -// +build netbsd,arm package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go index 82a4cb2dc..d576438bb 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build netbsd && arm64 -// +build netbsd,arm64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go index 66b3b6456..1851df14e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && 386 -// +build openbsd,386 package unix @@ -585,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1468,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2213,6 +2262,21 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_getfsstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getfsstat getfsstat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -2229,3 +2293,31 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error var libc_utimensat_trampoline_addr uintptr //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pledge_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pledge pledge "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_unveil_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unveil unveil "libc.so" diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s index 3dcacd30d..0b43c6936 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $4 DATA ·libc_sysctl_trampoline_addr(SB)/4, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fcntl_trampoline_addr(SB)/4, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $4 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $4 DATA ·libc_mknodat_trampoline_addr(SB)/4, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mount_trampoline_addr(SB)/4, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $4 @@ -668,7 +678,22 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $4 DATA ·libc_munmap_trampoline_addr(SB)/4, $libc_munmap_trampoline<>(SB) +TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getfsstat(SB) +GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getfsstat_trampoline_addr(SB)/4, $libc_getfsstat_trampoline<>(SB) + TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $4 DATA ·libc_utimensat_trampoline_addr(SB)/4, $libc_utimensat_trampoline<>(SB) + +TEXT libc_pledge_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pledge(SB) +GLOBL ·libc_pledge_trampoline_addr(SB), RODATA, $4 +DATA ·libc_pledge_trampoline_addr(SB)/4, $libc_pledge_trampoline<>(SB) + +TEXT libc_unveil_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unveil(SB) +GLOBL ·libc_unveil_trampoline_addr(SB), RODATA, $4 +DATA ·libc_unveil_trampoline_addr(SB)/4, $libc_unveil_trampoline<>(SB) diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go index c5c4cc112..e1ec0dbe4 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && amd64 -// +build openbsd,amd64 package unix @@ -585,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1468,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2213,6 +2262,21 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_getfsstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getfsstat getfsstat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -2229,3 +2293,31 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error var libc_utimensat_trampoline_addr uintptr //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pledge_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pledge pledge "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_unveil_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unveil unveil "libc.so" diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s index 2763620b0..880c6d6e3 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 @@ -668,7 +678,22 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) +TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getfsstat(SB) +GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getfsstat_trampoline_addr(SB)/8, $libc_getfsstat_trampoline<>(SB) + TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimensat_trampoline_addr(SB)/8, $libc_utimensat_trampoline<>(SB) + +TEXT libc_pledge_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pledge(SB) +GLOBL ·libc_pledge_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pledge_trampoline_addr(SB)/8, $libc_pledge_trampoline<>(SB) + +TEXT libc_unveil_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unveil(SB) +GLOBL ·libc_unveil_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unveil_trampoline_addr(SB)/8, $libc_unveil_trampoline<>(SB) diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go index 93bfbb328..7c8452a63 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && arm -// +build openbsd,arm package unix @@ -585,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1468,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2213,6 +2262,21 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_getfsstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getfsstat getfsstat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -2229,3 +2293,31 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error var libc_utimensat_trampoline_addr uintptr //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pledge_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pledge pledge "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_unveil_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unveil unveil "libc.so" diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s index c92231404..b8ef95b0f 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $4 DATA ·libc_sysctl_trampoline_addr(SB)/4, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fcntl_trampoline_addr(SB)/4, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $4 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $4 DATA ·libc_mknodat_trampoline_addr(SB)/4, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mount_trampoline_addr(SB)/4, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $4 @@ -668,7 +678,22 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $4 DATA ·libc_munmap_trampoline_addr(SB)/4, $libc_munmap_trampoline<>(SB) +TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getfsstat(SB) +GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getfsstat_trampoline_addr(SB)/4, $libc_getfsstat_trampoline<>(SB) + TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $4 DATA ·libc_utimensat_trampoline_addr(SB)/4, $libc_utimensat_trampoline<>(SB) + +TEXT libc_pledge_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pledge(SB) +GLOBL ·libc_pledge_trampoline_addr(SB), RODATA, $4 +DATA ·libc_pledge_trampoline_addr(SB)/4, $libc_pledge_trampoline<>(SB) + +TEXT libc_unveil_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unveil(SB) +GLOBL ·libc_unveil_trampoline_addr(SB), RODATA, $4 +DATA ·libc_unveil_trampoline_addr(SB)/4, $libc_unveil_trampoline<>(SB) diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go index a107b8fda..2ffdf861f 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && arm64 -// +build openbsd,arm64 package unix @@ -585,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1468,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2213,6 +2262,21 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_getfsstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getfsstat getfsstat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -2229,3 +2293,31 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error var libc_utimensat_trampoline_addr uintptr //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pledge_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pledge pledge "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_unveil_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unveil unveil "libc.so" diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s index a6bc32c92..2af3b5c76 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 @@ -668,7 +678,22 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) +TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getfsstat(SB) +GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getfsstat_trampoline_addr(SB)/8, $libc_getfsstat_trampoline<>(SB) + TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimensat_trampoline_addr(SB)/8, $libc_utimensat_trampoline<>(SB) + +TEXT libc_pledge_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pledge(SB) +GLOBL ·libc_pledge_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pledge_trampoline_addr(SB)/8, $libc_pledge_trampoline<>(SB) + +TEXT libc_unveil_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unveil(SB) +GLOBL ·libc_unveil_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unveil_trampoline_addr(SB)/8, $libc_unveil_trampoline<>(SB) diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go index c427de509..1da08d526 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && mips64 -// +build openbsd,mips64 package unix @@ -585,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1468,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2213,6 +2262,21 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_getfsstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getfsstat getfsstat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -2229,3 +2293,31 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error var libc_utimensat_trampoline_addr uintptr //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pledge_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pledge pledge "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_unveil_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unveil unveil "libc.so" diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s index b4e7bceab..b7a251353 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 @@ -668,7 +678,22 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) +TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getfsstat(SB) +GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getfsstat_trampoline_addr(SB)/8, $libc_getfsstat_trampoline<>(SB) + TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimensat_trampoline_addr(SB)/8, $libc_utimensat_trampoline<>(SB) + +TEXT libc_pledge_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pledge(SB) +GLOBL ·libc_pledge_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pledge_trampoline_addr(SB)/8, $libc_pledge_trampoline<>(SB) + +TEXT libc_unveil_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unveil(SB) +GLOBL ·libc_unveil_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unveil_trampoline_addr(SB)/8, $libc_unveil_trampoline<>(SB) diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go index 60c1a99ae..6e85b0aac 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && ppc64 -// +build openbsd,ppc64 package unix @@ -585,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1468,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2213,6 +2262,21 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_getfsstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getfsstat getfsstat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -2229,3 +2293,31 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error var libc_utimensat_trampoline_addr uintptr //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pledge_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pledge pledge "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_unveil_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unveil unveil "libc.so" diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s index ca3f76600..f15dadf05 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s @@ -213,6 +213,12 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + CALL libc_fcntl(SB) + RET +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 CALL libc_ppoll(SB) RET @@ -549,6 +555,12 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + CALL libc_mount(SB) + RET +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 CALL libc_nanosleep(SB) RET @@ -801,8 +813,26 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) +TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 + CALL libc_getfsstat(SB) + RET +GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getfsstat_trampoline_addr(SB)/8, $libc_getfsstat_trampoline<>(SB) + TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 CALL libc_utimensat(SB) RET GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimensat_trampoline_addr(SB)/8, $libc_utimensat_trampoline<>(SB) + +TEXT libc_pledge_trampoline<>(SB),NOSPLIT,$0-0 + CALL libc_pledge(SB) + RET +GLOBL ·libc_pledge_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pledge_trampoline_addr(SB)/8, $libc_pledge_trampoline<>(SB) + +TEXT libc_unveil_trampoline<>(SB),NOSPLIT,$0-0 + CALL libc_unveil(SB) + RET +GLOBL ·libc_unveil_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unveil_trampoline_addr(SB)/8, $libc_unveil_trampoline<>(SB) diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go index 52eba360f..28b487df2 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && riscv64 -// +build openbsd,riscv64 package unix @@ -585,6 +584,32 @@ var libc_sysctl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntl(fd int, cmd int, arg int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_fcntl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error) { r0, _, e1 := syscall_syscall6(libc_ppoll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) n = int(r0) @@ -1468,6 +1493,30 @@ var libc_mknodat_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Mount(fsType string, dir string, flags int, data unsafe.Pointer) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(fsType) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(dir) + if err != nil { + return + } + _, _, e1 := syscall_syscall6(libc_mount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flags), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_mount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mount mount "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { @@ -2213,6 +2262,21 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getfsstat(stat *Statfs_t, bufsize uintptr, flags int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_getfsstat_trampoline_addr, uintptr(unsafe.Pointer(stat)), uintptr(bufsize), uintptr(flags)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_getfsstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getfsstat getfsstat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -2229,3 +2293,31 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error var libc_utimensat_trampoline_addr uintptr //go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pledge(promises *byte, execpromises *byte) (err error) { + _, _, e1 := syscall_syscall(libc_pledge_trampoline_addr, uintptr(unsafe.Pointer(promises)), uintptr(unsafe.Pointer(execpromises)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_pledge_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pledge pledge "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unveil(path *byte, flags *byte) (err error) { + _, _, e1 := syscall_syscall(libc_unveil_trampoline_addr, uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(flags)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +var libc_unveil_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unveil unveil "libc.so" diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s index 477a7d5b2..1e7f321e4 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s @@ -178,6 +178,11 @@ TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) +TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) + TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ppoll(SB) GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 @@ -458,6 +463,11 @@ TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) +TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mount(SB) +GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) + TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_nanosleep(SB) GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 @@ -668,7 +678,22 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) +TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getfsstat(SB) +GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getfsstat_trampoline_addr(SB)/8, $libc_getfsstat_trampoline<>(SB) + TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimensat_trampoline_addr(SB)/8, $libc_utimensat_trampoline<>(SB) + +TEXT libc_pledge_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pledge(SB) +GLOBL ·libc_pledge_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pledge_trampoline_addr(SB)/8, $libc_pledge_trampoline<>(SB) + +TEXT libc_unveil_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unveil(SB) +GLOBL ·libc_unveil_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unveil_trampoline_addr(SB)/8, $libc_unveil_trampoline<>(SB) diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go index b40189464..829b87feb 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build solaris && amd64 -// +build solaris,amd64 package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go b/tools/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go index 1d8fe1d4b..7ccf66b7e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go @@ -1,23 +1,105 @@ -// go run mksyscall.go -tags zos,s390x syscall_zos_s390x.go +// go run mksyscall_zos_s390x.go -o_sysnum zsysnum_zos_s390x.go -o_syscall zsyscall_zos_s390x.go -i_syscall syscall_zos_s390x.go -o_asm zsymaddr_zos_s390x.s // Code generated by the command above; see README.md. DO NOT EDIT. //go:build zos && s390x -// +build zos,s390x package unix import ( + "runtime" + "syscall" "unsafe" ) +var _ syscall.Errno + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := syscall_syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.ExitSyscall() val = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Flistxattr(fd int, dest []byte) (sz int, err error) { + var _p0 unsafe.Pointer + if len(dest) > 0 { + _p0 = unsafe.Pointer(&dest[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FLISTXATTR_A<<4, uintptr(fd), uintptr(_p0), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FlistxattrAddr() *(func(fd int, dest []byte) (sz int, err error)) + +var Flistxattr = enter_Flistxattr + +func enter_Flistxattr(fd int, dest []byte) (sz int, err error) { + funcref := get_FlistxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FLISTXATTR_A<<4, "") == 0 { + *funcref = impl_Flistxattr + } else { + *funcref = error_Flistxattr + } + return (*funcref)(fd, dest) +} + +func error_Flistxattr(fd int, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fremovexattr(fd int, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FREMOVEXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FremovexattrAddr() *(func(fd int, attr string) (err error)) + +var Fremovexattr = enter_Fremovexattr + +func enter_Fremovexattr(fd int, attr string) (err error) { + funcref := get_FremovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FREMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Fremovexattr + } else { + *funcref = error_Fremovexattr } + return (*funcref)(fd, attr) +} + +func error_Fremovexattr(fd int, attr string) (err error) { + err = ENOSYS return } @@ -30,10 +112,12 @@ func read(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_READ<<4, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -47,31 +131,159 @@ func write(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WRITE<<4, uintptr(fd), uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FGETXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FgetxattrAddr() *(func(fd int, attr string, dest []byte) (sz int, err error)) + +var Fgetxattr = enter_Fgetxattr + +func enter_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + funcref := get_FgetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FGETXATTR_A<<4, "") == 0 { + *funcref = impl_Fgetxattr + } else { + *funcref = error_Fgetxattr + } + return (*funcref)(fd, attr, dest) +} + +func error_Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(data) > 0 { + _p1 = unsafe.Pointer(&data[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FSETXATTR_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(data)), uintptr(flag)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FsetxattrAddr() *(func(fd int, attr string, data []byte, flag int) (err error)) + +var Fsetxattr = enter_Fsetxattr + +func enter_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + funcref := get_FsetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___FSETXATTR_A<<4, "") == 0 { + *funcref = impl_Fsetxattr + } else { + *funcref = error_Fsetxattr } + return (*funcref)(fd, attr, data, flag) +} + +func error_Fsetxattr(fd int, attr string, data []byte, flag int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := syscall_syscall(SYS___ACCEPT_A, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCEPT_A<<4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCEPT4_A<<4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_accept4Addr() *(func(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)) + +var accept4 = enter_accept4 + +func enter_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + funcref := get_accept4Addr() + if funcptrtest(GetZosLibVec()+SYS___ACCEPT4_A<<4, "") == 0 { + *funcref = impl_accept4 + } else { + *funcref = error_accept4 } + return (*funcref)(s, rsa, addrlen, flags) +} + +func error_accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := syscall_syscall(SYS___BIND_A, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___BIND_A<<4, uintptr(s), uintptr(addr), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -79,9 +291,11 @@ func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := syscall_syscall(SYS___CONNECT_A, uintptr(s), uintptr(addr), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CONNECT_A<<4, uintptr(s), uintptr(addr), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -89,10 +303,10 @@ func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETGROUPS<<4, uintptr(n), uintptr(unsafe.Pointer(list))) nn = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -100,9 +314,9 @@ func getgroups(n int, list *_Gid_t) (nn int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETGROUPS<<4, uintptr(n), uintptr(unsafe.Pointer(list))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -110,9 +324,11 @@ func setgroups(n int, list *_Gid_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := syscall_syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETSOCKOPT<<4, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -120,9 +336,11 @@ func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := syscall_syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETSOCKOPT<<4, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -130,10 +348,10 @@ func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SOCKET<<4, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -141,9 +359,9 @@ func socket(domain int, typ int, proto int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := syscall_rawsyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SOCKETPAIR<<4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -151,9 +369,9 @@ func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := syscall_rawsyscall(SYS___GETPEERNAME_A, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETPEERNAME_A<<4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -161,10 +379,52 @@ func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := syscall_rawsyscall(SYS___GETSOCKNAME_A, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETSOCKNAME_A<<4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Removexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___REMOVEXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_RemovexattrAddr() *(func(path string, attr string) (err error)) + +var Removexattr = enter_Removexattr + +func enter_Removexattr(path string, attr string) (err error) { + funcref := get_RemovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___REMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Removexattr + } else { + *funcref = error_Removexattr } + return (*funcref)(path, attr) +} + +func error_Removexattr(path string, attr string) (err error) { + err = ENOSYS return } @@ -177,10 +437,12 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall6(SYS___RECVFROM_A, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RECVFROM_A<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -194,9 +456,11 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := syscall_syscall6(SYS___SENDTO_A, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SENDTO_A<<4, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -204,10 +468,12 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := syscall_syscall(SYS___RECVMSG_A, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RECVMSG_A<<4, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -215,10 +481,12 @@ func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := syscall_syscall(SYS___SENDMSG_A, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SENDMSG_A<<4, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -226,10 +494,12 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := syscall_syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MMAP<<4, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) + runtime.ExitSyscall() ret = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -237,9 +507,11 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := syscall_syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MUNMAP<<4, uintptr(addr), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -247,9 +519,11 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctl(fd int, req int, arg uintptr) (err error) { - _, _, e1 := syscall_syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_IOCTL<<4, uintptr(fd), uintptr(req), uintptr(arg)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -257,9 +531,62 @@ func ioctl(fd int, req int, arg uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ioctlPtr(fd int, req int, arg unsafe.Pointer) (err error) { - _, _, e1 := syscall_syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_IOCTL<<4, uintptr(fd), uintptr(req), uintptr(arg)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmat(id int, addr uintptr, flag int) (ret uintptr, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMAT<<4, uintptr(id), uintptr(addr), uintptr(flag)) + runtime.ExitSyscall() + ret = uintptr(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMCTL64<<4, uintptr(id), uintptr(cmd), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + result = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmdt(addr uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMDT<<4, uintptr(addr)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func shmget(key int, size int, flag int) (id int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHMGET<<4, uintptr(key), uintptr(size), uintptr(flag)) + runtime.ExitSyscall() + id = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -272,9 +599,11 @@ func Access(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___ACCESS_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___ACCESS_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -287,9 +616,11 @@ func Chdir(path string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHDIR_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHDIR_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -302,9 +633,11 @@ func Chown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHOWN_A, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHOWN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -317,9 +650,11 @@ func Chmod(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHMOD_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHMOD_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -332,10 +667,12 @@ func Creat(path string, mode uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := syscall_syscall(SYS___CREAT_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CREAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -343,10 +680,12 @@ func Creat(path string, mode uint32) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { - r0, _, e1 := syscall_syscall(SYS_DUP, uintptr(oldfd), 0, 0) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP<<4, uintptr(oldfd)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -354,617 +693,2216 @@ func Dup(oldfd int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { - _, _, e1 := syscall_syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP2<<4, uintptr(oldfd), uintptr(newfd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Errno2() (er2 int) { - uer2, _, _ := syscall_syscall(SYS___ERRNO2, 0, 0, 0) - er2 = int(uer2) +func impl_Dup3(oldfd int, newfd int, flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DUP3<<4, uintptr(oldfd), uintptr(newfd), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_Dup3Addr() *(func(oldfd int, newfd int, flags int) (err error)) -func Err2ad() (eadd *int) { - ueadd, _, _ := syscall_syscall(SYS___ERR2AD, 0, 0, 0) - eadd = (*int)(unsafe.Pointer(ueadd)) - return -} +var Dup3 = enter_Dup3 -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func enter_Dup3(oldfd int, newfd int, flags int) (err error) { + funcref := get_Dup3Addr() + if funcptrtest(GetZosLibVec()+SYS_DUP3<<4, "") == 0 { + *funcref = impl_Dup3 + } else { + *funcref = error_Dup3 + } + return (*funcref)(oldfd, newfd, flags) +} -func Exit(code int) { - syscall_syscall(SYS_EXIT, uintptr(code), 0, 0) +func error_Dup3(oldfd int, newfd int, flags int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Fchdir(fd int) (err error) { - _, _, e1 := syscall_syscall(SYS_FCHDIR, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Dirfd(dirp uintptr) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_DIRFD<<4, uintptr(dirp)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_DirfdAddr() *(func(dirp uintptr) (fd int, err error)) -func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := syscall_syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) +var Dirfd = enter_Dirfd + +func enter_Dirfd(dirp uintptr) (fd int, err error) { + funcref := get_DirfdAddr() + if funcptrtest(GetZosLibVec()+SYS_DIRFD<<4, "") == 0 { + *funcref = impl_Dirfd + } else { + *funcref = error_Dirfd } + return (*funcref)(dirp) +} + +func error_Dirfd(dirp uintptr) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := syscall_syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) +func impl_EpollCreate(size int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CREATE<<4, uintptr(size)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollCreateAddr() *(func(size int) (fd int, err error)) -func FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) { - r0, _, e1 := syscall_syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) - retval = int(r0) - if e1 != 0 { - err = errnoErr(e1) +var EpollCreate = enter_EpollCreate + +func enter_EpollCreate(size int) (fd int, err error) { + funcref := get_EpollCreateAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CREATE<<4, "") == 0 { + *funcref = impl_EpollCreate + } else { + *funcref = error_EpollCreate } + return (*funcref)(size) +} + +func error_EpollCreate(size int) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func fstat(fd int, stat *Stat_LE_t) (err error) { - _, _, e1 := syscall_syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_EpollCreate1(flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CREATE1<<4, uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollCreate1Addr() *(func(flags int) (fd int, err error)) -func Fstatvfs(fd int, stat *Statvfs_t) (err error) { - _, _, e1 := syscall_syscall(SYS_FSTATVFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) +var EpollCreate1 = enter_EpollCreate1 + +func enter_EpollCreate1(flags int) (fd int, err error) { + funcref := get_EpollCreate1Addr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CREATE1<<4, "") == 0 { + *funcref = impl_EpollCreate1 + } else { + *funcref = error_EpollCreate1 } + return (*funcref)(flags) +} + +func error_EpollCreate1(flags int) (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Fsync(fd int) (err error) { - _, _, e1 := syscall_syscall(SYS_FSYNC, uintptr(fd), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_CTL<<4, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollCtlAddr() *(func(epfd int, op int, fd int, event *EpollEvent) (err error)) -func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := syscall_syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) +var EpollCtl = enter_EpollCtl + +func enter_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + funcref := get_EpollCtlAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_CTL<<4, "") == 0 { + *funcref = impl_EpollCtl + } else { + *funcref = error_EpollCtl } - return + return (*funcref)(epfd, op, fd, event) } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getpagesize() (pgsize int) { - r0, _, _ := syscall_syscall(SYS_GETPAGESIZE, 0, 0, 0) - pgsize = int(r0) +func error_EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mprotect(b []byte, prot int) (err error) { +func impl_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := syscall_syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_PWAIT<<4, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec), uintptr(unsafe.Pointer(sigmask))) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollPwaitAddr() *(func(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error)) -func Msync(b []byte, flags int) (err error) { - var _p0 unsafe.Pointer - if len(b) > 0 { - _p0 = unsafe.Pointer(&b[0]) +var EpollPwait = enter_EpollPwait + +func enter_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { + funcref := get_EpollPwaitAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_PWAIT<<4, "") == 0 { + *funcref = impl_EpollPwait } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := syscall_syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) + *funcref = error_EpollPwait } + return (*funcref)(epfd, events, msec, sigmask) +} + +func error_EpollPwait(epfd int, events []EpollEvent, msec int, sigmask *int) (n int, err error) { + n = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Poll(fds []PollFd, timeout int) (n int, err error) { +func impl_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { var _p0 unsafe.Pointer - if len(fds) > 0 { - _p0 = unsafe.Pointer(&fds[0]) + if len(events) > 0 { + _p0 = unsafe.Pointer(&events[0]) } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall(SYS_POLL, uintptr(_p0), uintptr(len(fds)), uintptr(timeout)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EPOLL_WAIT<<4, uintptr(epfd), uintptr(_p0), uintptr(len(events)), uintptr(msec)) + runtime.ExitSyscall() n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_EpollWaitAddr() *(func(epfd int, events []EpollEvent, msec int) (n int, err error)) -func Times(tms *Tms) (ticks uintptr, err error) { - r0, _, e1 := syscall_syscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) - ticks = uintptr(r0) - if e1 != 0 { - err = errnoErr(e1) +var EpollWait = enter_EpollWait + +func enter_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + funcref := get_EpollWaitAddr() + if funcptrtest(GetZosLibVec()+SYS_EPOLL_WAIT<<4, "") == 0 { + *funcref = impl_EpollWait + } else { + *funcref = error_EpollWait } + return (*funcref)(epfd, events, msec) +} + +func error_EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { + n = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func W_Getmntent(buff *byte, size int) (lastsys int, err error) { - r0, _, e1 := syscall_syscall(SYS_W_GETMNTENT, uintptr(unsafe.Pointer(buff)), uintptr(size), 0) - lastsys = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } +func Errno2() (er2 int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS___ERRNO2<<4) + runtime.ExitSyscall() + er2 = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func W_Getmntent_A(buff *byte, size int) (lastsys int, err error) { - r0, _, e1 := syscall_syscall(SYS___W_GETMNTENT_A, uintptr(unsafe.Pointer(buff)), uintptr(size), 0) - lastsys = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Eventfd(initval uint, flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_EVENTFD<<4, uintptr(initval), uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } +//go:nosplit +func get_EventfdAddr() *(func(initval uint, flags int) (fd int, err error)) + +var Eventfd = enter_Eventfd + +func enter_Eventfd(initval uint, flags int) (fd int, err error) { + funcref := get_EventfdAddr() + if funcptrtest(GetZosLibVec()+SYS_EVENTFD<<4, "") == 0 { + *funcref = impl_Eventfd + } else { + *funcref = error_Eventfd + } + return (*funcref)(initval, flags) +} + +func error_Eventfd(initval uint, flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return +} + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) { +func Exit(code int) { + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec()+SYS_EXIT<<4, uintptr(code)) + runtime.ExitSyscall() + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } - var _p1 *byte - _p1, err = BytePtrFromString(filesystem) - if err != nil { - return - } - var _p2 *byte - _p2, err = BytePtrFromString(fstype) - if err != nil { - return - } - var _p3 *byte - _p3, err = BytePtrFromString(parm) - if err != nil { - return - } - _, _, e1 := syscall_syscall6(SYS___MOUNT_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(mtm), uintptr(parmlen), uintptr(unsafe.Pointer(_p3))) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FACCESSAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_FaccessatAddr() *(func(dirfd int, path string, mode uint32, flags int) (err error)) -func unmount(filesystem string, mtm int) (err error) { +var Faccessat = enter_Faccessat + +func enter_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + funcref := get_FaccessatAddr() + if funcptrtest(GetZosLibVec()+SYS___FACCESSAT_A<<4, "") == 0 { + *funcref = impl_Faccessat + } else { + *funcref = error_Faccessat + } + return (*funcref)(dirfd, path, mode, flags) +} + +func error_Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchdir(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHDIR<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchmod(fd int, mode uint32) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHMOD<<4, uintptr(fd), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(filesystem) + _p0, err = BytePtrFromString(path) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UMOUNT_A, uintptr(unsafe.Pointer(_p0)), uintptr(mtm), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FCHMODAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FchmodatAddr() *(func(dirfd int, path string, mode uint32, flags int) (err error)) + +var Fchmodat = enter_Fchmodat + +func enter_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + funcref := get_FchmodatAddr() + if funcptrtest(GetZosLibVec()+SYS___FCHMODAT_A<<4, "") == 0 { + *funcref = impl_Fchmodat + } else { + *funcref = error_Fchmodat + } + return (*funcref)(dirfd, path, mode, flags) +} + +func error_Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fchown(fd int, uid int, gid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCHOWN<<4, uintptr(fd), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Chroot(path string) (err error) { +func impl_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___CHROOT_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FCHOWNAT_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FchownatAddr() *(func(fd int, path string, uid int, gid int, flags int) (err error)) + +var Fchownat = enter_Fchownat + +func enter_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { + funcref := get_FchownatAddr() + if funcptrtest(GetZosLibVec()+SYS___FCHOWNAT_A<<4, "") == 0 { + *funcref = impl_Fchownat + } else { + *funcref = error_Fchownat } + return (*funcref)(fd, path, uid, gid, flags) +} + +func error_Fchownat(fd int, path string, uid int, gid int, flags int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Uname(buf *Utsname) (err error) { - _, _, e1 := syscall_rawsyscall(SYS___UNAME_A, uintptr(unsafe.Pointer(buf)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func FcntlInt(fd uintptr, cmd int, arg int) (retval int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), uintptr(arg)) + runtime.ExitSyscall() + retval = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Gethostname(buf []byte) (err error) { +func impl_Fdatasync(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FDATASYNC<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FdatasyncAddr() *(func(fd int) (err error)) + +var Fdatasync = enter_Fdatasync + +func enter_Fdatasync(fd int) (err error) { + funcref := get_FdatasyncAddr() + if funcptrtest(GetZosLibVec()+SYS_FDATASYNC<<4, "") == 0 { + *funcref = impl_Fdatasync + } else { + *funcref = error_Fdatasync + } + return (*funcref)(fd) +} + +func error_Fdatasync(fd int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fstat(fd int, stat *Stat_LE_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTAT<<4, uintptr(fd), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FSTATAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_fstatatAddr() *(func(dirfd int, path string, stat *Stat_LE_t, flags int) (err error)) + +var fstatat = enter_fstatat + +func enter_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + funcref := get_fstatatAddr() + if funcptrtest(GetZosLibVec()+SYS___FSTATAT_A<<4, "") == 0 { + *funcref = impl_fstatat + } else { + *funcref = error_fstatat + } + return (*funcref)(dirfd, path, stat, flags) +} + +func error_fstatat(dirfd int, path string, stat *Stat_LE_t, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(dest) > 0 { + _p2 = unsafe.Pointer(&dest[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LGETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LgetxattrAddr() *(func(link string, attr string, dest []byte) (sz int, err error)) + +var Lgetxattr = enter_Lgetxattr + +func enter_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + funcref := get_LgetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LGETXATTR_A<<4, "") == 0 { + *funcref = impl_Lgetxattr + } else { + *funcref = error_Lgetxattr + } + return (*funcref)(link, attr, dest) +} + +func error_Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + var _p2 unsafe.Pointer + if len(data) > 0 { + _p2 = unsafe.Pointer(&data[0]) + } else { + _p2 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LSETXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LsetxattrAddr() *(func(path string, attr string, data []byte, flags int) (err error)) + +var Lsetxattr = enter_Lsetxattr + +func enter_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + funcref := get_LsetxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LSETXATTR_A<<4, "") == 0 { + *funcref = impl_Lsetxattr + } else { + *funcref = error_Lsetxattr + } + return (*funcref)(path, attr, data, flags) +} + +func error_Lsetxattr(path string, attr string, data []byte, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Fstatfs(fd int, buf *Statfs_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTATFS<<4, uintptr(fd), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FstatfsAddr() *(func(fd int, buf *Statfs_t) (err error)) + +var Fstatfs = enter_Fstatfs + +func enter_Fstatfs(fd int, buf *Statfs_t) (err error) { + funcref := get_FstatfsAddr() + if funcptrtest(GetZosLibVec()+SYS_FSTATFS<<4, "") == 0 { + *funcref = impl_Fstatfs + } else { + *funcref = error_Fstatfs + } + return (*funcref)(fd, buf) +} + +func error_Fstatfs(fd int, buf *Statfs_t) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fstatvfs(fd int, stat *Statvfs_t) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSTATVFS<<4, uintptr(fd), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Fsync(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FSYNC<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Futimes(fd int, tv []Timeval) (err error) { var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) + if len(tv) > 0 { + _p0 = unsafe.Pointer(&tv[0]) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := syscall_syscall(SYS___GETHOSTNAME_A, uintptr(_p0), uintptr(len(buf)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FUTIMES<<4, uintptr(fd), uintptr(_p0), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_FutimesAddr() *(func(fd int, tv []Timeval) (err error)) -func Getegid() (egid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETEGID, 0, 0, 0) - egid = int(r0) +var Futimes = enter_Futimes + +func enter_Futimes(fd int, tv []Timeval) (err error) { + funcref := get_FutimesAddr() + if funcptrtest(GetZosLibVec()+SYS_FUTIMES<<4, "") == 0 { + *funcref = impl_Futimes + } else { + *funcref = error_Futimes + } + return (*funcref)(fd, tv) +} + +func error_Futimes(fd int, tv []Timeval) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Geteuid() (uid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETEUID, 0, 0, 0) - uid = int(r0) +func impl_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(tv) > 0 { + _p1 = unsafe.Pointer(&tv[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___FUTIMESAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_FutimesatAddr() *(func(dirfd int, path string, tv []Timeval) (err error)) + +var Futimesat = enter_Futimesat + +func enter_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + funcref := get_FutimesatAddr() + if funcptrtest(GetZosLibVec()+SYS___FUTIMESAT_A<<4, "") == 0 { + *funcref = impl_Futimesat + } else { + *funcref = error_Futimesat + } + return (*funcref)(dirfd, path, tv) +} + +func error_Futimesat(dirfd int, path string, tv []Timeval) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getgid() (gid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETGID, 0, 0, 0) - gid = int(r0) +func Ftruncate(fd int, length int64) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FTRUNCATE<<4, uintptr(fd), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getpid() (pid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETPID, 0, 0, 0) - pid = int(r0) +func impl_Getrandom(buf []byte, flags int) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRANDOM<<4, uintptr(_p0), uintptr(len(buf)), uintptr(flags)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_GetrandomAddr() *(func(buf []byte, flags int) (n int, err error)) + +var Getrandom = enter_Getrandom + +func enter_Getrandom(buf []byte, flags int) (n int, err error) { + funcref := get_GetrandomAddr() + if funcptrtest(GetZosLibVec()+SYS_GETRANDOM<<4, "") == 0 { + *funcref = impl_Getrandom + } else { + *funcref = error_Getrandom + } + return (*funcref)(buf, flags) +} + +func error_Getrandom(buf []byte, flags int) (n int, err error) { + n = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_GETPGID, uintptr(pid), 0, 0) - pgid = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func impl_InotifyInit() (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec() + SYS_INOTIFY_INIT<<4) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyInitAddr() *(func() (fd int, err error)) + +var InotifyInit = enter_InotifyInit + +func enter_InotifyInit() (fd int, err error) { + funcref := get_InotifyInitAddr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_INIT<<4, "") == 0 { + *funcref = impl_InotifyInit + } else { + *funcref = error_InotifyInit } + return (*funcref)() +} + +func error_InotifyInit() (fd int, err error) { + fd = -1 + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getppid() (pid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETPPID, 0, 0, 0) - pid = int(r0) +func impl_InotifyInit1(flags int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_INOTIFY_INIT1<<4, uintptr(flags)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyInit1Addr() *(func(flags int) (fd int, err error)) + +var InotifyInit1 = enter_InotifyInit1 + +func enter_InotifyInit1(flags int) (fd int, err error) { + funcref := get_InotifyInit1Addr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_INIT1<<4, "") == 0 { + *funcref = impl_InotifyInit1 + } else { + *funcref = error_InotifyInit1 + } + return (*funcref)(flags) +} + +func error_InotifyInit1(flags int) (fd int, err error) { + fd = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(pathname) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___INOTIFY_ADD_WATCH_A<<4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) + runtime.ExitSyscall() + watchdesc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyAddWatchAddr() *(func(fd int, pathname string, mask uint32) (watchdesc int, err error)) + +var InotifyAddWatch = enter_InotifyAddWatch + +func enter_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + funcref := get_InotifyAddWatchAddr() + if funcptrtest(GetZosLibVec()+SYS___INOTIFY_ADD_WATCH_A<<4, "") == 0 { + *funcref = impl_InotifyAddWatch + } else { + *funcref = error_InotifyAddWatch + } + return (*funcref)(fd, pathname, mask) +} + +func error_InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { + watchdesc = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_INOTIFY_RM_WATCH<<4, uintptr(fd), uintptr(watchdesc)) + runtime.ExitSyscall() + success = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_InotifyRmWatchAddr() *(func(fd int, watchdesc uint32) (success int, err error)) + +var InotifyRmWatch = enter_InotifyRmWatch + +func enter_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + funcref := get_InotifyRmWatchAddr() + if funcptrtest(GetZosLibVec()+SYS_INOTIFY_RM_WATCH<<4, "") == 0 { + *funcref = impl_InotifyRmWatch + } else { + *funcref = error_InotifyRmWatch + } + return (*funcref)(fd, watchdesc) +} + +func error_InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { + success = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Listxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LISTXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_ListxattrAddr() *(func(path string, dest []byte) (sz int, err error)) + +var Listxattr = enter_Listxattr + +func enter_Listxattr(path string, dest []byte) (sz int, err error) { + funcref := get_ListxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LISTXATTR_A<<4, "") == 0 { + *funcref = impl_Listxattr + } else { + *funcref = error_Listxattr + } + return (*funcref)(path, dest) +} + +func error_Listxattr(path string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Llistxattr(path string, dest []byte) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(dest) > 0 { + _p1 = unsafe.Pointer(&dest[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LLISTXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) + runtime.ExitSyscall() + sz = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LlistxattrAddr() *(func(path string, dest []byte) (sz int, err error)) + +var Llistxattr = enter_Llistxattr + +func enter_Llistxattr(path string, dest []byte) (sz int, err error) { + funcref := get_LlistxattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LLISTXATTR_A<<4, "") == 0 { + *funcref = impl_Llistxattr + } else { + *funcref = error_Llistxattr + } + return (*funcref)(path, dest) +} + +func error_Llistxattr(path string, dest []byte) (sz int, err error) { + sz = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lremovexattr(path string, attr string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LREMOVEXATTR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LremovexattrAddr() *(func(path string, attr string) (err error)) + +var Lremovexattr = enter_Lremovexattr + +func enter_Lremovexattr(path string, attr string) (err error) { + funcref := get_LremovexattrAddr() + if funcptrtest(GetZosLibVec()+SYS___LREMOVEXATTR_A<<4, "") == 0 { + *funcref = impl_Lremovexattr + } else { + *funcref = error_Lremovexattr + } + return (*funcref)(path, attr) +} + +func error_Lremovexattr(path string, attr string) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Lutimes(path string, tv []Timeval) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 unsafe.Pointer + if len(tv) > 0 { + _p1 = unsafe.Pointer(&tv[0]) + } else { + _p1 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LUTIMES_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(tv))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LutimesAddr() *(func(path string, tv []Timeval) (err error)) + +var Lutimes = enter_Lutimes + +func enter_Lutimes(path string, tv []Timeval) (err error) { + funcref := get_LutimesAddr() + if funcptrtest(GetZosLibVec()+SYS___LUTIMES_A<<4, "") == 0 { + *funcref = impl_Lutimes + } else { + *funcref = error_Lutimes + } + return (*funcref)(path, tv) +} + +func error_Lutimes(path string, tv []Timeval) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mprotect(b []byte, prot int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MPROTECT<<4, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Msync(b []byte, flags int) (err error) { + var _p0 unsafe.Pointer + if len(b) > 0 { + _p0 = unsafe.Pointer(&b[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_MSYNC<<4, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Console2(cmsg *ConsMsg2, modstr *byte, concmd *uint32) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CONSOLE2<<4, uintptr(unsafe.Pointer(cmsg)), uintptr(unsafe.Pointer(modstr)), uintptr(unsafe.Pointer(concmd))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Poll(fds []PollFd, timeout int) (n int, err error) { + var _p0 unsafe.Pointer + if len(fds) > 0 { + _p0 = unsafe.Pointer(&fds[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_POLL<<4, uintptr(_p0), uintptr(len(fds)), uintptr(timeout)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Readdir_r(dirp uintptr, entry *direntLE, result **direntLE) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___READDIR_R_A<<4, uintptr(dirp), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Statfs(path string, buf *Statfs_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___STATFS_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_StatfsAddr() *(func(path string, buf *Statfs_t) (err error)) + +var Statfs = enter_Statfs + +func enter_Statfs(path string, buf *Statfs_t) (err error) { + funcref := get_StatfsAddr() + if funcptrtest(GetZosLibVec()+SYS___STATFS_A<<4, "") == 0 { + *funcref = impl_Statfs + } else { + *funcref = error_Statfs + } + return (*funcref)(path, buf) +} + +func error_Statfs(path string, buf *Statfs_t) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Syncfs(fd int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SYNCFS<<4, uintptr(fd)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_SyncfsAddr() *(func(fd int) (err error)) + +var Syncfs = enter_Syncfs + +func enter_Syncfs(fd int) (err error) { + funcref := get_SyncfsAddr() + if funcptrtest(GetZosLibVec()+SYS_SYNCFS<<4, "") == 0 { + *funcref = impl_Syncfs + } else { + *funcref = error_Syncfs + } + return (*funcref)(fd) +} + +func error_Syncfs(fd int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Times(tms *Tms) (ticks uintptr, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TIMES<<4, uintptr(unsafe.Pointer(tms))) + runtime.ExitSyscall() + ticks = uintptr(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func W_Getmntent(buff *byte, size int) (lastsys int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_W_GETMNTENT<<4, uintptr(unsafe.Pointer(buff)), uintptr(size)) + runtime.ExitSyscall() + lastsys = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func W_Getmntent_A(buff *byte, size int) (lastsys int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___W_GETMNTENT_A<<4, uintptr(unsafe.Pointer(buff)), uintptr(size)) + runtime.ExitSyscall() + lastsys = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func mount_LE(path string, filesystem string, fstype string, mtm uint32, parmlen int32, parm string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(filesystem) + if err != nil { + return + } + var _p2 *byte + _p2, err = BytePtrFromString(fstype) + if err != nil { + return + } + var _p3 *byte + _p3, err = BytePtrFromString(parm) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MOUNT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(mtm), uintptr(parmlen), uintptr(unsafe.Pointer(_p3))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unmount_LE(filesystem string, mtm int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(filesystem) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UMOUNT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mtm)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Chroot(path string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___CHROOT_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SELECT<<4, uintptr(nmsgsfds), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout))) + runtime.ExitSyscall() + ret = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Uname(buf *Utsname) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_____OSNAME_A<<4, uintptr(unsafe.Pointer(buf))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Unshare(flags int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_UNSHARE<<4, uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_UnshareAddr() *(func(flags int) (err error)) + +var Unshare = enter_Unshare + +func enter_Unshare(flags int) (err error) { + funcref := get_UnshareAddr() + if funcptrtest(GetZosLibVec()+SYS_UNSHARE<<4, "") == 0 { + *funcref = impl_Unshare + } else { + *funcref = error_Unshare + } + return (*funcref)(flags) +} + +func error_Unshare(flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Gethostname(buf []byte) (err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___GETHOSTNAME_A<<4, uintptr(_p0), uintptr(len(buf))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getgid() (gid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETGID<<4) + gid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpid() (pid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETPID<<4) + pid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpgid(pid int) (pgid int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETPGID<<4, uintptr(pid)) + pgid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getppid() (pid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETPPID<<4) + pid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getpriority(which int, who int) (prio int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETPRIORITY<<4, uintptr(which), uintptr(who)) + runtime.ExitSyscall() + prio = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getrlimit(resource int, rlim *Rlimit) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRLIMIT<<4, uintptr(resource), uintptr(unsafe.Pointer(rlim))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getrusage(who int, rusage *rusage_zos) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETRUSAGE<<4, uintptr(who), uintptr(unsafe.Pointer(rusage))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getegid() (egid int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETEGID<<4) + runtime.ExitSyscall() + egid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Geteuid() (euid int) { + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETEUID<<4) + runtime.ExitSyscall() + euid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getsid(pid int) (sid int, err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETSID<<4, uintptr(pid)) + sid = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Getuid() (uid int) { + r0, _, _ := CallLeFuncWithErr(GetZosLibVec() + SYS_GETUID<<4) + uid = int(r0) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Kill(pid int, sig Signal) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_KILL<<4, uintptr(pid), uintptr(sig)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Lchown(path string, uid int, gid int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LCHOWN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Link(path string, link string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(link) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LINK_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldPath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newPath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LINKAT_A<<4, uintptr(oldDirFd), uintptr(unsafe.Pointer(_p0)), uintptr(newDirFd), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_LinkatAddr() *(func(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error)) + +var Linkat = enter_Linkat + +func enter_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + funcref := get_LinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___LINKAT_A<<4, "") == 0 { + *funcref = impl_Linkat + } else { + *funcref = error_Linkat + } + return (*funcref)(oldDirFd, oldPath, newDirFd, newPath, flags) +} + +func error_Linkat(oldDirFd int, oldPath string, newDirFd int, newPath string, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Listen(s int, n int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_LISTEN<<4, uintptr(s), uintptr(n)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func lstat(path string, stat *Stat_LE_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___LSTAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mkdir(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKDIR_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Mkdirat(dirfd int, path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKDIRAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MkdiratAddr() *(func(dirfd int, path string, mode uint32) (err error)) + +var Mkdirat = enter_Mkdirat + +func enter_Mkdirat(dirfd int, path string, mode uint32) (err error) { + funcref := get_MkdiratAddr() + if funcptrtest(GetZosLibVec()+SYS___MKDIRAT_A<<4, "") == 0 { + *funcref = impl_Mkdirat + } else { + *funcref = error_Mkdirat + } + return (*funcref)(dirfd, path, mode) +} + +func error_Mkdirat(dirfd int, path string, mode uint32) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mkfifo(path string, mode uint32) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKFIFO_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Mknod(path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKNOD_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___MKNODAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_MknodatAddr() *(func(dirfd int, path string, mode uint32, dev int) (err error)) + +var Mknodat = enter_Mknodat + +func enter_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + funcref := get_MknodatAddr() + if funcptrtest(GetZosLibVec()+SYS___MKNODAT_A<<4, "") == 0 { + *funcref = impl_Mknodat + } else { + *funcref = error_Mknodat + } + return (*funcref)(dirfd, path, mode, dev) +} + +func error_Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_PivotRoot(newroot string, oldroot string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(newroot) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(oldroot) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___PIVOT_ROOT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_PivotRootAddr() *(func(newroot string, oldroot string) (err error)) + +var PivotRoot = enter_PivotRoot + +func enter_PivotRoot(newroot string, oldroot string) (err error) { + funcref := get_PivotRootAddr() + if funcptrtest(GetZosLibVec()+SYS___PIVOT_ROOT_A<<4, "") == 0 { + *funcref = impl_PivotRoot + } else { + *funcref = error_PivotRoot + } + return (*funcref)(newroot, oldroot) +} + +func error_PivotRoot(newroot string, oldroot string) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Pread(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PREAD<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := syscall_syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) - prio = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func Pwrite(fd int, p []byte, offset int64) (n int, err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PWRITE<<4, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset)) + runtime.ExitSyscall() + n = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getrlimit(resource int, rlim *Rlimit) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___PRCTL_A<<4, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_PrctlAddr() *(func(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)) -func getrusage(who int, rusage *rusage_zos) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) - if e1 != 0 { - err = errnoErr(e1) +var Prctl = enter_Prctl + +func enter_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + funcref := get_PrctlAddr() + if funcptrtest(GetZosLibVec()+SYS___PRCTL_A<<4, "") == 0 { + *funcref = impl_Prctl + } else { + *funcref = error_Prctl } - return + return (*funcref)(option, arg2, arg3, arg4, arg5) } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Getsid(pid int) (sid int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_GETSID, uintptr(pid), 0, 0) - sid = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } +func error_Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getuid() (uid int) { - r0, _, _ := syscall_rawsyscall(SYS_GETUID, 0, 0, 0) - uid = int(r0) +func impl_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PRLIMIT<<4, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(newlimit)), uintptr(unsafe.Pointer(old))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_PrlimitAddr() *(func(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error)) -func Kill(pid int, sig Signal) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) - if e1 != 0 { - err = errnoErr(e1) +var Prlimit = enter_Prlimit + +func enter_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + funcref := get_PrlimitAddr() + if funcptrtest(GetZosLibVec()+SYS_PRLIMIT<<4, "") == 0 { + *funcref = impl_Prlimit + } else { + *funcref = error_Prlimit } + return (*funcref)(pid, resource, newlimit, old) +} + +func error_Prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Lchown(path string, uid int, gid int) (err error) { +func Rename(from string, to string) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(path) + _p0, err = BytePtrFromString(from) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(to) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___LCHOWN_A, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAME_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Link(path string, link string) (err error) { +func impl_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(path) + _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte - _p1, err = BytePtrFromString(link) + _p1, err = BytePtrFromString(newpath) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___LINK_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAMEAT_A<<4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_RenameatAddr() *(func(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)) -func Listen(s int, n int) (err error) { - _, _, e1 := syscall_syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) - if e1 != 0 { - err = errnoErr(e1) +var Renameat = enter_Renameat + +func enter_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + funcref := get_RenameatAddr() + if funcptrtest(GetZosLibVec()+SYS___RENAMEAT_A<<4, "") == 0 { + *funcref = impl_Renameat + } else { + *funcref = error_Renameat } + return (*funcref)(olddirfd, oldpath, newdirfd, newpath) +} + +func error_Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func lstat(path string, stat *Stat_LE_t) (err error) { +func impl_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { var _p0 *byte - _p0, err = BytePtrFromString(path) + _p0, err = BytePtrFromString(oldpath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newpath) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___LSTAT_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RENAMEAT2_A<<4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_Renameat2Addr() *(func(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)) -func Mkdir(path string, mode uint32) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___MKDIR_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) +var Renameat2 = enter_Renameat2 + +func enter_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + funcref := get_Renameat2Addr() + if funcptrtest(GetZosLibVec()+SYS___RENAMEAT2_A<<4, "") == 0 { + *funcref = impl_Renameat2 + } else { + *funcref = error_Renameat2 } + return (*funcref)(olddirfd, oldpath, newdirfd, newpath, flags) +} + +func error_Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mkfifo(path string, mode uint32) (err error) { +func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } - _, _, e1 := syscall_syscall(SYS___MKFIFO_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___RMDIR_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Mknod(path string, mode uint32, dev int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___MKNOD_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) - if e1 != 0 { - err = errnoErr(e1) +func Seek(fd int, offset int64, whence int) (off int64, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_LSEEK<<4, uintptr(fd), uintptr(offset), uintptr(whence)) + runtime.ExitSyscall() + off = int64(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Pread(fd int, p []byte, offset int64) (n int, err error) { - var _p0 unsafe.Pointer - if len(p) > 0 { - _p0 = unsafe.Pointer(&p[0]) - } else { - _p0 = unsafe.Pointer(&_zero) +func Setegid(egid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETEGID<<4, uintptr(egid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } - r0, _, e1 := syscall_syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Seteuid(euid int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETEUID<<4, uintptr(euid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Pwrite(fd int, p []byte, offset int64) (n int, err error) { +func impl_Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := syscall_syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SETHOSTNAME_A<<4, uintptr(_p0), uintptr(len(p))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_SethostnameAddr() *(func(p []byte) (err error)) -func Readlink(path string, buf []byte) (n int, err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - var _p1 unsafe.Pointer - if len(buf) > 0 { - _p1 = unsafe.Pointer(&buf[0]) +var Sethostname = enter_Sethostname + +func enter_Sethostname(p []byte) (err error) { + funcref := get_SethostnameAddr() + if funcptrtest(GetZosLibVec()+SYS___SETHOSTNAME_A<<4, "") == 0 { + *funcref = impl_Sethostname } else { - _p1 = unsafe.Pointer(&_zero) + *funcref = error_Sethostname } - r0, _, e1 := syscall_syscall(SYS___READLINK_A, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return + return (*funcref)(p) } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func Rename(from string, to string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(from) - if err != nil { - return - } - var _p1 *byte - _p1, err = BytePtrFromString(to) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___RENAME_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - if e1 != 0 { - err = errnoErr(e1) - } +func error_Sethostname(p []byte) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Rmdir(path string) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := syscall_syscall(SYS___RMDIR_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) +func impl_Setns(fd int, nstype int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETNS<<4, uintptr(fd), uintptr(nstype)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +//go:nosplit +func get_SetnsAddr() *(func(fd int, nstype int) (err error)) -func Seek(fd int, offset int64, whence int) (off int64, err error) { - r0, _, e1 := syscall_syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence)) - off = int64(r0) - if e1 != 0 { - err = errnoErr(e1) +var Setns = enter_Setns + +func enter_Setns(fd int, nstype int) (err error) { + funcref := get_SetnsAddr() + if funcptrtest(GetZosLibVec()+SYS_SETNS<<4, "") == 0 { + *funcref = impl_Setns + } else { + *funcref = error_Setns } + return (*funcref)(fd, nstype) +} + +func error_Setns(fd int, nstype int) (err error) { + err = ENOSYS return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := syscall_syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETPRIORITY<<4, uintptr(which), uintptr(who), uintptr(prio)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -972,9 +2910,9 @@ func Setpriority(which int, who int, prio int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETPGID<<4, uintptr(pid), uintptr(pgid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -982,9 +2920,9 @@ func Setpgid(pid int, pgid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(resource int, lim *Rlimit) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(lim)), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETRLIMIT<<4, uintptr(resource), uintptr(unsafe.Pointer(lim))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -992,9 +2930,9 @@ func Setrlimit(resource int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETREGID<<4, uintptr(rgid), uintptr(egid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1002,9 +2940,9 @@ func Setregid(rgid int, egid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETREUID<<4, uintptr(ruid), uintptr(euid)) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1012,10 +2950,10 @@ func Setreuid(ruid int, euid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { - r0, _, e1 := syscall_rawsyscall(SYS_SETSID, 0, 0, 0) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec() + SYS_SETSID<<4) pid = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1023,9 +2961,11 @@ func Setsid() (pid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { - _, _, e1 := syscall_syscall(SYS_SETUID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETUID<<4, uintptr(uid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1033,9 +2973,11 @@ func Setuid(uid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(uid int) (err error) { - _, _, e1 := syscall_syscall(SYS_SETGID, uintptr(uid), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SETGID<<4, uintptr(uid)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1043,9 +2985,11 @@ func Setgid(uid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(fd int, how int) (err error) { - _, _, e1 := syscall_syscall(SYS_SHUTDOWN, uintptr(fd), uintptr(how), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_SHUTDOWN<<4, uintptr(fd), uintptr(how)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1058,9 +3002,11 @@ func stat(path string, statLE *Stat_LE_t) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___STAT_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(statLE)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___STAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(statLE))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1078,17 +3024,63 @@ func Symlink(path string, link string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___SYMLINK_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SYMLINK_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(oldPath) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(newPath) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___SYMLINKAT_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(dirfd), uintptr(unsafe.Pointer(_p1))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } +//go:nosplit +func get_SymlinkatAddr() *(func(oldPath string, dirfd int, newPath string) (err error)) + +var Symlinkat = enter_Symlinkat + +func enter_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + funcref := get_SymlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___SYMLINKAT_A<<4, "") == 0 { + *funcref = impl_Symlinkat + } else { + *funcref = error_Symlinkat + } + return (*funcref)(oldPath, dirfd, newPath) +} + +func error_Symlinkat(oldPath string, dirfd int, newPath string) (err error) { + err = ENOSYS + return +} + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { - syscall_syscall(SYS_SYNC, 0, 0, 0) + runtime.EnterSyscall() + CallLeFuncWithErr(GetZosLibVec() + SYS_SYNC<<4) + runtime.ExitSyscall() return } @@ -1100,9 +3092,11 @@ func Truncate(path string, length int64) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___TRUNCATE_A, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___TRUNCATE_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(length)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1110,9 +3104,11 @@ func Truncate(path string, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tcgetattr(fildes int, termptr *Termios) (err error) { - _, _, e1 := syscall_syscall(SYS_TCGETATTR, uintptr(fildes), uintptr(unsafe.Pointer(termptr)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TCGETATTR<<4, uintptr(fildes), uintptr(unsafe.Pointer(termptr))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1120,9 +3116,11 @@ func Tcgetattr(fildes int, termptr *Termios) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tcsetattr(fildes int, when int, termptr *Termios) (err error) { - _, _, e1 := syscall_syscall(SYS_TCSETATTR, uintptr(fildes), uintptr(when), uintptr(unsafe.Pointer(termptr))) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_TCSETATTR<<4, uintptr(fildes), uintptr(when), uintptr(unsafe.Pointer(termptr))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1130,7 +3128,9 @@ func Tcsetattr(fildes int, when int, termptr *Termios) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := syscall_syscall(SYS_UMASK, uintptr(mask), 0, 0) + runtime.EnterSyscall() + r0, _, _ := CallLeFuncWithErr(GetZosLibVec()+SYS_UMASK<<4, uintptr(mask)) + runtime.ExitSyscall() oldmask = int(r0) return } @@ -1143,10 +3143,49 @@ func Unlink(path string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UNLINK_A, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UNLINK_A<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_Unlinkat(dirfd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UNLINKAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_UnlinkatAddr() *(func(dirfd int, path string, flags int) (err error)) + +var Unlinkat = enter_Unlinkat + +func enter_Unlinkat(dirfd int, path string, flags int) (err error) { + funcref := get_UnlinkatAddr() + if funcptrtest(GetZosLibVec()+SYS___UNLINKAT_A<<4, "") == 0 { + *funcref = impl_Unlinkat + } else { + *funcref = error_Unlinkat } + return (*funcref)(dirfd, path, flags) +} + +func error_Unlinkat(dirfd int, path string, flags int) (err error) { + err = ENOSYS return } @@ -1158,9 +3197,11 @@ func Utime(path string, utim *Utimbuf) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UTIME_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(utim)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIME_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(utim))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1173,11 +3214,91 @@ func open(path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := syscall_syscall(SYS___OPEN_A, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPEN_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPENAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_openatAddr() *(func(dirfd int, path string, flags int, mode uint32) (fd int, err error)) + +var openat = enter_openat + +func enter_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + funcref := get_openatAddr() + if funcptrtest(GetZosLibVec()+SYS___OPENAT_A<<4, "") == 0 { + *funcref = impl_openat + } else { + *funcref = error_openat + } + return (*funcref)(dirfd, path, flags, mode) +} + +func error_openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { + fd = -1 + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func impl_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___OPENAT2_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(open_how)), uintptr(size)) + runtime.ExitSyscall() fd = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_openat2Addr() *(func(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error)) + +var openat2 = enter_openat2 + +func enter_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + funcref := get_openat2Addr() + if funcptrtest(GetZosLibVec()+SYS___OPENAT2_A<<4, "") == 0 { + *funcref = impl_openat2 + } else { + *funcref = error_openat2 } + return (*funcref)(dirfd, path, open_how, size) +} + +func error_openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error) { + fd = -1 + err = ENOSYS return } @@ -1189,9 +3310,23 @@ func remove(path string) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS_REMOVE, uintptr(unsafe.Pointer(_p0)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_REMOVE<<4, uintptr(unsafe.Pointer(_p0))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func waitid(idType int, id int, info *Siginfo, options int) (err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAITID<<4, uintptr(idType), uintptr(id), uintptr(unsafe.Pointer(info)), uintptr(options)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1199,10 +3334,12 @@ func remove(path string) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) { - r0, _, e1 := syscall_syscall(SYS_WAITPID, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options)) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_WAITPID<<4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options)) + runtime.ExitSyscall() wpid = int(r0) - if e1 != 0 { - err = errnoErr(e1) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1210,9 +3347,9 @@ func waitpid(pid int, wstatus *_C_int, options int) (wpid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func gettimeofday(tv *timeval_zos) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GETTIMEOFDAY<<4, uintptr(unsafe.Pointer(tv))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1220,9 +3357,9 @@ func gettimeofday(tv *timeval_zos) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]_C_int) (err error) { - _, _, e1 := syscall_rawsyscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) - if e1 != 0 { - err = errnoErr(e1) + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_PIPE<<4, uintptr(unsafe.Pointer(p))) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } @@ -1235,20 +3372,87 @@ func utimes(path string, timeval *[2]Timeval) (err error) { if err != nil { return } - _, _, e1 := syscall_syscall(SYS___UTIMES_A, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) - if e1 != 0 { - err = errnoErr(e1) + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIMES_A<<4, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval))) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Select(nmsgsfds int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (ret int, err error) { - r0, _, e1 := syscall_syscall6(SYS_SELECT, uintptr(nmsgsfds), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - ret = int(r0) - if e1 != 0 { - err = errnoErr(e1) +func impl_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS___UTIMENSAT_A<<4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(ts)), uintptr(flags)) + runtime.ExitSyscall() + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +//go:nosplit +func get_utimensatAddr() *(func(dirfd int, path string, ts *[2]Timespec, flags int) (err error)) + +var utimensat = enter_utimensat + +func enter_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + funcref := get_utimensatAddr() + if funcptrtest(GetZosLibVec()+SYS___UTIMENSAT_A<<4, "") == 0 { + *funcref = impl_utimensat + } else { + *funcref = error_utimensat + } + return (*funcref)(dirfd, path, ts, flags) +} + +func error_utimensat(dirfd int, path string, ts *[2]Timespec, flags int) (err error) { + err = ENOSYS + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Posix_openpt(oflag int) (fd int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_POSIX_OPENPT<<4, uintptr(oflag)) + runtime.ExitSyscall() + fd = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Grantpt(fildes int) (rc int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_GRANTPT<<4, uintptr(fildes)) + runtime.ExitSyscall() + rc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func Unlockpt(fildes int) (rc int, err error) { + runtime.EnterSyscall() + r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_UNLOCKPT<<4, uintptr(fildes)) + runtime.ExitSyscall() + rc = int(r0) + if int64(r0) == -1 { + err = errnoErr2(e1, e2) } return } diff --git a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go index 55e048471..3a58ae819 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build 386 && openbsd -// +build 386,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go index d2243cf83..dcb7a0eb7 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build amd64 && openbsd -// +build amd64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go index 82dc51bd8..db5a7bf13 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build arm && openbsd -// +build arm,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go index cbdda1a4a..7be575a77 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build arm64 && openbsd -// +build arm64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go index f55eae1a8..d6e3174c6 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build mips64 && openbsd -// +build mips64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_ppc64.go index e44054470..ee97157d0 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build ppc64 && openbsd -// +build ppc64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_riscv64.go index a0db82fce..35c3b91d0 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysctl_openbsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build riscv64 && openbsd -// +build riscv64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go index f8298ff9b..5edda7687 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && darwin -// +build amd64,darwin package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go index 5eb433bbf..0dc9e8b4d 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && darwin -// +build arm64,darwin package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go index 703675c0c..308ddf3a1 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && dragonfly -// +build amd64,dragonfly package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go index 4e0d96107..418664e3d 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && freebsd -// +build 386,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go index 01636b838..34d0b86d7 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && freebsd -// +build amd64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go index ad99bc106..b71cf45e2 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && freebsd -// +build arm,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go index 89dcc4274..e32df1c1e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && freebsd -// +build arm64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_riscv64.go index ee37aaa0c..15ad6111f 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_freebsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && freebsd -// +build riscv64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go index 9862853d3..524b0820c 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && linux -// +build 386,linux package unix @@ -448,4 +447,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go index 8901f0f4e..d3e38f681 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && linux -// +build amd64,linux package unix @@ -370,4 +369,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go index 6902c37ee..70b35bf3b 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && linux -// +build arm,linux package unix @@ -412,4 +411,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go index a6d3dff81..6c778c232 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && linux -// +build arm64,linux package unix @@ -315,4 +314,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go index b18f3f710..37281cf51 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build loong64 && linux -// +build loong64,linux package unix @@ -309,4 +308,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go index 0302e5e3d..7e567f1ef 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips && linux -// +build mips,linux package unix @@ -432,4 +431,15 @@ const ( SYS_FUTEX_WAITV = 4449 SYS_SET_MEMPOLICY_HOME_NODE = 4450 SYS_CACHESTAT = 4451 + SYS_FCHMODAT2 = 4452 + SYS_MAP_SHADOW_STACK = 4453 + SYS_FUTEX_WAKE = 4454 + SYS_FUTEX_WAIT = 4455 + SYS_FUTEX_REQUEUE = 4456 + SYS_STATMOUNT = 4457 + SYS_LISTMOUNT = 4458 + SYS_LSM_GET_SELF_ATTR = 4459 + SYS_LSM_SET_SELF_ATTR = 4460 + SYS_LSM_LIST_MODULES = 4461 + SYS_MSEAL = 4462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go index 6693ba4a0..38ae55e5e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && linux -// +build mips64,linux package unix @@ -362,4 +361,15 @@ const ( SYS_FUTEX_WAITV = 5449 SYS_SET_MEMPOLICY_HOME_NODE = 5450 SYS_CACHESTAT = 5451 + SYS_FCHMODAT2 = 5452 + SYS_MAP_SHADOW_STACK = 5453 + SYS_FUTEX_WAKE = 5454 + SYS_FUTEX_WAIT = 5455 + SYS_FUTEX_REQUEUE = 5456 + SYS_STATMOUNT = 5457 + SYS_LISTMOUNT = 5458 + SYS_LSM_GET_SELF_ATTR = 5459 + SYS_LSM_SET_SELF_ATTR = 5460 + SYS_LSM_LIST_MODULES = 5461 + SYS_MSEAL = 5462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go index fd93f4987..55e92e60a 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64le && linux -// +build mips64le,linux package unix @@ -362,4 +361,15 @@ const ( SYS_FUTEX_WAITV = 5449 SYS_SET_MEMPOLICY_HOME_NODE = 5450 SYS_CACHESTAT = 5451 + SYS_FCHMODAT2 = 5452 + SYS_MAP_SHADOW_STACK = 5453 + SYS_FUTEX_WAKE = 5454 + SYS_FUTEX_WAIT = 5455 + SYS_FUTEX_REQUEUE = 5456 + SYS_STATMOUNT = 5457 + SYS_LISTMOUNT = 5458 + SYS_LSM_GET_SELF_ATTR = 5459 + SYS_LSM_SET_SELF_ATTR = 5460 + SYS_LSM_LIST_MODULES = 5461 + SYS_MSEAL = 5462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go index 760ddcadc..60658d6a0 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mipsle && linux -// +build mipsle,linux package unix @@ -432,4 +431,15 @@ const ( SYS_FUTEX_WAITV = 4449 SYS_SET_MEMPOLICY_HOME_NODE = 4450 SYS_CACHESTAT = 4451 + SYS_FCHMODAT2 = 4452 + SYS_MAP_SHADOW_STACK = 4453 + SYS_FUTEX_WAKE = 4454 + SYS_FUTEX_WAIT = 4455 + SYS_FUTEX_REQUEUE = 4456 + SYS_STATMOUNT = 4457 + SYS_LISTMOUNT = 4458 + SYS_LSM_GET_SELF_ATTR = 4459 + SYS_LSM_SET_SELF_ATTR = 4460 + SYS_LSM_LIST_MODULES = 4461 + SYS_MSEAL = 4462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go index cff2b2555..e203e8a7e 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && linux -// +build ppc,linux package unix @@ -439,4 +438,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go index a4b2405d0..5944b97d5 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && linux -// +build ppc64,linux package unix @@ -411,4 +410,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go index aca54b4e3..c66d416da 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64le && linux -// +build ppc64le,linux package unix @@ -411,4 +410,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 9d1738d64..9889f6a55 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && linux -// +build riscv64,linux package unix @@ -316,4 +315,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go index 022878dc8..01d86825b 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build s390x && linux -// +build s390x,linux package unix @@ -377,4 +376,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go index 4100a761c..7b703e77c 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build sparc64 && linux -// +build sparc64,linux package unix @@ -390,4 +389,15 @@ const ( SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 SYS_CACHESTAT = 451 + SYS_FCHMODAT2 = 452 + SYS_MAP_SHADOW_STACK = 453 + SYS_FUTEX_WAKE = 454 + SYS_FUTEX_WAIT = 455 + SYS_FUTEX_REQUEUE = 456 + SYS_STATMOUNT = 457 + SYS_LISTMOUNT = 458 + SYS_LSM_GET_SELF_ATTR = 459 + SYS_LSM_SET_SELF_ATTR = 460 + SYS_LSM_LIST_MODULES = 461 + SYS_MSEAL = 462 ) diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go index 3a6699eba..b2aa8cd49 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && netbsd -// +build 386,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go index 5677cd4f1..524a1b1c9 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && netbsd -// +build amd64,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go index e784cb6db..d59b943ac 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && netbsd -// +build arm,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go index bd4952efa..31e771d53 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; DO NOT EDIT. //go:build arm64 && netbsd -// +build arm64,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go index 597733813..9fd77c6cb 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && openbsd -// +build 386,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go index 16af29189..af10af28c 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && openbsd -// +build amd64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go index f59b18a97..cc2028af4 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && openbsd -// +build arm,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go index 721ef5910..c06dd4415 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && openbsd -// +build arm64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go index 01c43a01f..9ddbf3e08 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && openbsd -// +build mips64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_ppc64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_ppc64.go index f258cfa24..19a6ee413 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && openbsd -// +build ppc64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_riscv64.go index 07919e0ec..05192a782 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_openbsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && openbsd -// +build riscv64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go b/tools/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go index 073daad43..5e8c263ca 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go @@ -1,2670 +1,2852 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. +// go run mksyscall_zos_s390x.go -o_sysnum zsysnum_zos_s390x.go -o_syscall zsyscall_zos_s390x.go -i_syscall syscall_zos_s390x.go -o_asm zsymaddr_zos_s390x.s +// Code generated by the command above; see README.md. DO NOT EDIT. //go:build zos && s390x -// +build zos,s390x package unix -// TODO: auto-generate. - const ( - SYS_ACOSD128 = 0xB80 - SYS_ACOSD32 = 0xB7E - SYS_ACOSD64 = 0xB7F - SYS_ACOSHD128 = 0xB83 - SYS_ACOSHD32 = 0xB81 - SYS_ACOSHD64 = 0xB82 - SYS_AIO_FSYNC = 0xC69 - SYS_ASCTIME = 0x0AE - SYS_ASCTIME64 = 0xCD7 - SYS_ASCTIME64_R = 0xCD8 - SYS_ASIND128 = 0xB86 - SYS_ASIND32 = 0xB84 - SYS_ASIND64 = 0xB85 - SYS_ASINHD128 = 0xB89 - SYS_ASINHD32 = 0xB87 - SYS_ASINHD64 = 0xB88 - SYS_ATAN2D128 = 0xB8F - SYS_ATAN2D32 = 0xB8D - SYS_ATAN2D64 = 0xB8E - SYS_ATAND128 = 0xB8C - SYS_ATAND32 = 0xB8A - SYS_ATAND64 = 0xB8B - SYS_ATANHD128 = 0xB92 - SYS_ATANHD32 = 0xB90 - SYS_ATANHD64 = 0xB91 - SYS_BIND2ADDRSEL = 0xD59 - SYS_C16RTOMB = 0xD40 - SYS_C32RTOMB = 0xD41 - SYS_CBRTD128 = 0xB95 - SYS_CBRTD32 = 0xB93 - SYS_CBRTD64 = 0xB94 - SYS_CEILD128 = 0xB98 - SYS_CEILD32 = 0xB96 - SYS_CEILD64 = 0xB97 - SYS_CLEARENV = 0x0C9 - SYS_CLEARERR_UNLOCKED = 0xCA1 - SYS_CLOCK = 0x0AA - SYS_CLOGL = 0xA00 - SYS_CLRMEMF = 0x0BD - SYS_CONJ = 0xA03 - SYS_CONJF = 0xA06 - SYS_CONJL = 0xA09 - SYS_COPYSIGND128 = 0xB9E - SYS_COPYSIGND32 = 0xB9C - SYS_COPYSIGND64 = 0xB9D - SYS_COSD128 = 0xBA1 - SYS_COSD32 = 0xB9F - SYS_COSD64 = 0xBA0 - SYS_COSHD128 = 0xBA4 - SYS_COSHD32 = 0xBA2 - SYS_COSHD64 = 0xBA3 - SYS_CPOW = 0xA0C - SYS_CPOWF = 0xA0F - SYS_CPOWL = 0xA12 - SYS_CPROJ = 0xA15 - SYS_CPROJF = 0xA18 - SYS_CPROJL = 0xA1B - SYS_CREAL = 0xA1E - SYS_CREALF = 0xA21 - SYS_CREALL = 0xA24 - SYS_CSIN = 0xA27 - SYS_CSINF = 0xA2A - SYS_CSINH = 0xA30 - SYS_CSINHF = 0xA33 - SYS_CSINHL = 0xA36 - SYS_CSINL = 0xA2D - SYS_CSNAP = 0x0C5 - SYS_CSQRT = 0xA39 - SYS_CSQRTF = 0xA3C - SYS_CSQRTL = 0xA3F - SYS_CTAN = 0xA42 - SYS_CTANF = 0xA45 - SYS_CTANH = 0xA4B - SYS_CTANHF = 0xA4E - SYS_CTANHL = 0xA51 - SYS_CTANL = 0xA48 - SYS_CTIME = 0x0AB - SYS_CTIME64 = 0xCD9 - SYS_CTIME64_R = 0xCDA - SYS_CTRACE = 0x0C6 - SYS_DIFFTIME = 0x0A7 - SYS_DIFFTIME64 = 0xCDB - SYS_DLADDR = 0xC82 - SYS_DYNALLOC = 0x0C3 - SYS_DYNFREE = 0x0C2 - SYS_ERFCD128 = 0xBAA - SYS_ERFCD32 = 0xBA8 - SYS_ERFCD64 = 0xBA9 - SYS_ERFD128 = 0xBA7 - SYS_ERFD32 = 0xBA5 - SYS_ERFD64 = 0xBA6 - SYS_EXP2D128 = 0xBB0 - SYS_EXP2D32 = 0xBAE - SYS_EXP2D64 = 0xBAF - SYS_EXPD128 = 0xBAD - SYS_EXPD32 = 0xBAB - SYS_EXPD64 = 0xBAC - SYS_EXPM1D128 = 0xBB3 - SYS_EXPM1D32 = 0xBB1 - SYS_EXPM1D64 = 0xBB2 - SYS_FABSD128 = 0xBB6 - SYS_FABSD32 = 0xBB4 - SYS_FABSD64 = 0xBB5 - SYS_FDELREC_UNLOCKED = 0xCA2 - SYS_FDIMD128 = 0xBB9 - SYS_FDIMD32 = 0xBB7 - SYS_FDIMD64 = 0xBB8 - SYS_FDOPEN_UNLOCKED = 0xCFC - SYS_FECLEAREXCEPT = 0xAEA - SYS_FEGETENV = 0xAEB - SYS_FEGETEXCEPTFLAG = 0xAEC - SYS_FEGETROUND = 0xAED - SYS_FEHOLDEXCEPT = 0xAEE - SYS_FEOF_UNLOCKED = 0xCA3 - SYS_FERAISEEXCEPT = 0xAEF - SYS_FERROR_UNLOCKED = 0xCA4 - SYS_FESETENV = 0xAF0 - SYS_FESETEXCEPTFLAG = 0xAF1 - SYS_FESETROUND = 0xAF2 - SYS_FETCHEP = 0x0BF - SYS_FETESTEXCEPT = 0xAF3 - SYS_FEUPDATEENV = 0xAF4 - SYS_FE_DEC_GETROUND = 0xBBA - SYS_FE_DEC_SETROUND = 0xBBB - SYS_FFLUSH_UNLOCKED = 0xCA5 - SYS_FGETC_UNLOCKED = 0xC80 - SYS_FGETPOS64 = 0xCEE - SYS_FGETPOS64_UNLOCKED = 0xCF4 - SYS_FGETPOS_UNLOCKED = 0xCA6 - SYS_FGETS_UNLOCKED = 0xC7C - SYS_FGETWC_UNLOCKED = 0xCA7 - SYS_FGETWS_UNLOCKED = 0xCA8 - SYS_FILENO_UNLOCKED = 0xCA9 - SYS_FLDATA = 0x0C1 - SYS_FLDATA_UNLOCKED = 0xCAA - SYS_FLOCATE_UNLOCKED = 0xCAB - SYS_FLOORD128 = 0xBBE - SYS_FLOORD32 = 0xBBC - SYS_FLOORD64 = 0xBBD - SYS_FMA = 0xA63 - SYS_FMAD128 = 0xBC1 - SYS_FMAD32 = 0xBBF - SYS_FMAD64 = 0xBC0 - SYS_FMAF = 0xA66 - SYS_FMAL = 0xA69 - SYS_FMAX = 0xA6C - SYS_FMAXD128 = 0xBC4 - SYS_FMAXD32 = 0xBC2 - SYS_FMAXD64 = 0xBC3 - SYS_FMAXF = 0xA6F - SYS_FMAXL = 0xA72 - SYS_FMIN = 0xA75 - SYS_FMIND128 = 0xBC7 - SYS_FMIND32 = 0xBC5 - SYS_FMIND64 = 0xBC6 - SYS_FMINF = 0xA78 - SYS_FMINL = 0xA7B - SYS_FMODD128 = 0xBCA - SYS_FMODD32 = 0xBC8 - SYS_FMODD64 = 0xBC9 - SYS_FOPEN64 = 0xD49 - SYS_FOPEN64_UNLOCKED = 0xD4A - SYS_FOPEN_UNLOCKED = 0xCFA - SYS_FPRINTF_UNLOCKED = 0xCAC - SYS_FPUTC_UNLOCKED = 0xC81 - SYS_FPUTS_UNLOCKED = 0xC7E - SYS_FPUTWC_UNLOCKED = 0xCAD - SYS_FPUTWS_UNLOCKED = 0xCAE - SYS_FREAD_NOUPDATE = 0xCEC - SYS_FREAD_NOUPDATE_UNLOCKED = 0xCED - SYS_FREAD_UNLOCKED = 0xC7B - SYS_FREEIFADDRS = 0xCE6 - SYS_FREOPEN64 = 0xD4B - SYS_FREOPEN64_UNLOCKED = 0xD4C - SYS_FREOPEN_UNLOCKED = 0xCFB - SYS_FREXPD128 = 0xBCE - SYS_FREXPD32 = 0xBCC - SYS_FREXPD64 = 0xBCD - SYS_FSCANF_UNLOCKED = 0xCAF - SYS_FSEEK64 = 0xCEF - SYS_FSEEK64_UNLOCKED = 0xCF5 - SYS_FSEEKO64 = 0xCF0 - SYS_FSEEKO64_UNLOCKED = 0xCF6 - SYS_FSEEKO_UNLOCKED = 0xCB1 - SYS_FSEEK_UNLOCKED = 0xCB0 - SYS_FSETPOS64 = 0xCF1 - SYS_FSETPOS64_UNLOCKED = 0xCF7 - SYS_FSETPOS_UNLOCKED = 0xCB3 - SYS_FTELL64 = 0xCF2 - SYS_FTELL64_UNLOCKED = 0xCF8 - SYS_FTELLO64 = 0xCF3 - SYS_FTELLO64_UNLOCKED = 0xCF9 - SYS_FTELLO_UNLOCKED = 0xCB5 - SYS_FTELL_UNLOCKED = 0xCB4 - SYS_FUPDATE = 0x0B5 - SYS_FUPDATE_UNLOCKED = 0xCB7 - SYS_FWIDE_UNLOCKED = 0xCB8 - SYS_FWPRINTF_UNLOCKED = 0xCB9 - SYS_FWRITE_UNLOCKED = 0xC7A - SYS_FWSCANF_UNLOCKED = 0xCBA - SYS_GETDATE64 = 0xD4F - SYS_GETIFADDRS = 0xCE7 - SYS_GETIPV4SOURCEFILTER = 0xC77 - SYS_GETSOURCEFILTER = 0xC79 - SYS_GETSYNTX = 0x0FD - SYS_GETS_UNLOCKED = 0xC7D - SYS_GETTIMEOFDAY64 = 0xD50 - SYS_GETWCHAR_UNLOCKED = 0xCBC - SYS_GETWC_UNLOCKED = 0xCBB - SYS_GMTIME = 0x0B0 - SYS_GMTIME64 = 0xCDC - SYS_GMTIME64_R = 0xCDD - SYS_HYPOTD128 = 0xBD1 - SYS_HYPOTD32 = 0xBCF - SYS_HYPOTD64 = 0xBD0 - SYS_ILOGBD128 = 0xBD4 - SYS_ILOGBD32 = 0xBD2 - SYS_ILOGBD64 = 0xBD3 - SYS_ILOGBF = 0xA7E - SYS_ILOGBL = 0xA81 - SYS_INET6_IS_SRCADDR = 0xD5A - SYS_ISBLANK = 0x0FE - SYS_ISWALNUM = 0x0FF - SYS_LDEXPD128 = 0xBD7 - SYS_LDEXPD32 = 0xBD5 - SYS_LDEXPD64 = 0xBD6 - SYS_LGAMMAD128 = 0xBDA - SYS_LGAMMAD32 = 0xBD8 - SYS_LGAMMAD64 = 0xBD9 - SYS_LIO_LISTIO = 0xC6A - SYS_LLRINT = 0xA84 - SYS_LLRINTD128 = 0xBDD - SYS_LLRINTD32 = 0xBDB - SYS_LLRINTD64 = 0xBDC - SYS_LLRINTF = 0xA87 - SYS_LLRINTL = 0xA8A - SYS_LLROUND = 0xA8D - SYS_LLROUNDD128 = 0xBE0 - SYS_LLROUNDD32 = 0xBDE - SYS_LLROUNDD64 = 0xBDF - SYS_LLROUNDF = 0xA90 - SYS_LLROUNDL = 0xA93 - SYS_LOCALTIM = 0x0B1 - SYS_LOCALTIME = 0x0B1 - SYS_LOCALTIME64 = 0xCDE - SYS_LOCALTIME64_R = 0xCDF - SYS_LOG10D128 = 0xBE6 - SYS_LOG10D32 = 0xBE4 - SYS_LOG10D64 = 0xBE5 - SYS_LOG1PD128 = 0xBE9 - SYS_LOG1PD32 = 0xBE7 - SYS_LOG1PD64 = 0xBE8 - SYS_LOG2D128 = 0xBEC - SYS_LOG2D32 = 0xBEA - SYS_LOG2D64 = 0xBEB - SYS_LOGBD128 = 0xBEF - SYS_LOGBD32 = 0xBED - SYS_LOGBD64 = 0xBEE - SYS_LOGBF = 0xA96 - SYS_LOGBL = 0xA99 - SYS_LOGD128 = 0xBE3 - SYS_LOGD32 = 0xBE1 - SYS_LOGD64 = 0xBE2 - SYS_LRINT = 0xA9C - SYS_LRINTD128 = 0xBF2 - SYS_LRINTD32 = 0xBF0 - SYS_LRINTD64 = 0xBF1 - SYS_LRINTF = 0xA9F - SYS_LRINTL = 0xAA2 - SYS_LROUNDD128 = 0xBF5 - SYS_LROUNDD32 = 0xBF3 - SYS_LROUNDD64 = 0xBF4 - SYS_LROUNDL = 0xAA5 - SYS_MBLEN = 0x0AF - SYS_MBRTOC16 = 0xD42 - SYS_MBRTOC32 = 0xD43 - SYS_MEMSET = 0x0A3 - SYS_MKTIME = 0x0AC - SYS_MKTIME64 = 0xCE0 - SYS_MODFD128 = 0xBF8 - SYS_MODFD32 = 0xBF6 - SYS_MODFD64 = 0xBF7 - SYS_NAN = 0xAA8 - SYS_NAND128 = 0xBFB - SYS_NAND32 = 0xBF9 - SYS_NAND64 = 0xBFA - SYS_NANF = 0xAAA - SYS_NANL = 0xAAC - SYS_NEARBYINT = 0xAAE - SYS_NEARBYINTD128 = 0xBFE - SYS_NEARBYINTD32 = 0xBFC - SYS_NEARBYINTD64 = 0xBFD - SYS_NEARBYINTF = 0xAB1 - SYS_NEARBYINTL = 0xAB4 - SYS_NEXTAFTERD128 = 0xC01 - SYS_NEXTAFTERD32 = 0xBFF - SYS_NEXTAFTERD64 = 0xC00 - SYS_NEXTAFTERF = 0xAB7 - SYS_NEXTAFTERL = 0xABA - SYS_NEXTTOWARD = 0xABD - SYS_NEXTTOWARDD128 = 0xC04 - SYS_NEXTTOWARDD32 = 0xC02 - SYS_NEXTTOWARDD64 = 0xC03 - SYS_NEXTTOWARDF = 0xAC0 - SYS_NEXTTOWARDL = 0xAC3 - SYS_NL_LANGINFO = 0x0FC - SYS_PERROR_UNLOCKED = 0xCBD - SYS_POSIX_FALLOCATE = 0xCE8 - SYS_POSIX_MEMALIGN = 0xCE9 - SYS_POSIX_OPENPT = 0xC66 - SYS_POWD128 = 0xC07 - SYS_POWD32 = 0xC05 - SYS_POWD64 = 0xC06 - SYS_PRINTF_UNLOCKED = 0xCBE - SYS_PSELECT = 0xC67 - SYS_PTHREAD_ATTR_GETSTACK = 0xB3E - SYS_PTHREAD_ATTR_SETSTACK = 0xB3F - SYS_PTHREAD_SECURITY_APPLID_NP = 0xCE4 - SYS_PUTS_UNLOCKED = 0xC7F - SYS_PUTWCHAR_UNLOCKED = 0xCC0 - SYS_PUTWC_UNLOCKED = 0xCBF - SYS_QUANTEXPD128 = 0xD46 - SYS_QUANTEXPD32 = 0xD44 - SYS_QUANTEXPD64 = 0xD45 - SYS_QUANTIZED128 = 0xC0A - SYS_QUANTIZED32 = 0xC08 - SYS_QUANTIZED64 = 0xC09 - SYS_REMAINDERD128 = 0xC0D - SYS_REMAINDERD32 = 0xC0B - SYS_REMAINDERD64 = 0xC0C - SYS_RESIZE_ALLOC = 0xCEB - SYS_REWIND_UNLOCKED = 0xCC1 - SYS_RINTD128 = 0xC13 - SYS_RINTD32 = 0xC11 - SYS_RINTD64 = 0xC12 - SYS_RINTF = 0xACB - SYS_RINTL = 0xACD - SYS_ROUND = 0xACF - SYS_ROUNDD128 = 0xC16 - SYS_ROUNDD32 = 0xC14 - SYS_ROUNDD64 = 0xC15 - SYS_ROUNDF = 0xAD2 - SYS_ROUNDL = 0xAD5 - SYS_SAMEQUANTUMD128 = 0xC19 - SYS_SAMEQUANTUMD32 = 0xC17 - SYS_SAMEQUANTUMD64 = 0xC18 - SYS_SCALBLN = 0xAD8 - SYS_SCALBLND128 = 0xC1C - SYS_SCALBLND32 = 0xC1A - SYS_SCALBLND64 = 0xC1B - SYS_SCALBLNF = 0xADB - SYS_SCALBLNL = 0xADE - SYS_SCALBND128 = 0xC1F - SYS_SCALBND32 = 0xC1D - SYS_SCALBND64 = 0xC1E - SYS_SCALBNF = 0xAE3 - SYS_SCALBNL = 0xAE6 - SYS_SCANF_UNLOCKED = 0xCC2 - SYS_SCHED_YIELD = 0xB32 - SYS_SETENV = 0x0C8 - SYS_SETIPV4SOURCEFILTER = 0xC76 - SYS_SETSOURCEFILTER = 0xC78 - SYS_SHM_OPEN = 0xC8C - SYS_SHM_UNLINK = 0xC8D - SYS_SIND128 = 0xC22 - SYS_SIND32 = 0xC20 - SYS_SIND64 = 0xC21 - SYS_SINHD128 = 0xC25 - SYS_SINHD32 = 0xC23 - SYS_SINHD64 = 0xC24 - SYS_SIZEOF_ALLOC = 0xCEA - SYS_SOCKATMARK = 0xC68 - SYS_SQRTD128 = 0xC28 - SYS_SQRTD32 = 0xC26 - SYS_SQRTD64 = 0xC27 - SYS_STRCHR = 0x0A0 - SYS_STRCSPN = 0x0A1 - SYS_STRERROR = 0x0A8 - SYS_STRERROR_R = 0xB33 - SYS_STRFTIME = 0x0B2 - SYS_STRLEN = 0x0A9 - SYS_STRPBRK = 0x0A2 - SYS_STRSPN = 0x0A4 - SYS_STRSTR = 0x0A5 - SYS_STRTOD128 = 0xC2B - SYS_STRTOD32 = 0xC29 - SYS_STRTOD64 = 0xC2A - SYS_STRTOK = 0x0A6 - SYS_TAND128 = 0xC2E - SYS_TAND32 = 0xC2C - SYS_TAND64 = 0xC2D - SYS_TANHD128 = 0xC31 - SYS_TANHD32 = 0xC2F - SYS_TANHD64 = 0xC30 - SYS_TGAMMAD128 = 0xC34 - SYS_TGAMMAD32 = 0xC32 - SYS_TGAMMAD64 = 0xC33 - SYS_TIME = 0x0AD - SYS_TIME64 = 0xCE1 - SYS_TMPFILE64 = 0xD4D - SYS_TMPFILE64_UNLOCKED = 0xD4E - SYS_TMPFILE_UNLOCKED = 0xCFD - SYS_TRUNCD128 = 0xC40 - SYS_TRUNCD32 = 0xC3E - SYS_TRUNCD64 = 0xC3F - SYS_UNGETC_UNLOCKED = 0xCC3 - SYS_UNGETWC_UNLOCKED = 0xCC4 - SYS_UNSETENV = 0xB34 - SYS_VFPRINTF_UNLOCKED = 0xCC5 - SYS_VFSCANF_UNLOCKED = 0xCC7 - SYS_VFWPRINTF_UNLOCKED = 0xCC9 - SYS_VFWSCANF_UNLOCKED = 0xCCB - SYS_VPRINTF_UNLOCKED = 0xCCD - SYS_VSCANF_UNLOCKED = 0xCCF - SYS_VWPRINTF_UNLOCKED = 0xCD1 - SYS_VWSCANF_UNLOCKED = 0xCD3 - SYS_WCSTOD128 = 0xC43 - SYS_WCSTOD32 = 0xC41 - SYS_WCSTOD64 = 0xC42 - SYS_WPRINTF_UNLOCKED = 0xCD5 - SYS_WSCANF_UNLOCKED = 0xCD6 - SYS__FLUSHLBF = 0xD68 - SYS__FLUSHLBF_UNLOCKED = 0xD6F - SYS___ACOSHF_H = 0xA54 - SYS___ACOSHL_H = 0xA55 - SYS___ASINHF_H = 0xA56 - SYS___ASINHL_H = 0xA57 - SYS___ATANPID128 = 0xC6D - SYS___ATANPID32 = 0xC6B - SYS___ATANPID64 = 0xC6C - SYS___CBRTF_H = 0xA58 - SYS___CBRTL_H = 0xA59 - SYS___CDUMP = 0x0C4 - SYS___CLASS = 0xAFA - SYS___CLASS2 = 0xB99 - SYS___CLASS2D128 = 0xC99 - SYS___CLASS2D32 = 0xC97 - SYS___CLASS2D64 = 0xC98 - SYS___CLASS2F = 0xC91 - SYS___CLASS2F_B = 0xC93 - SYS___CLASS2F_H = 0xC94 - SYS___CLASS2L = 0xC92 - SYS___CLASS2L_B = 0xC95 - SYS___CLASS2L_H = 0xC96 - SYS___CLASS2_B = 0xB9A - SYS___CLASS2_H = 0xB9B - SYS___CLASS_B = 0xAFB - SYS___CLASS_H = 0xAFC - SYS___CLOGL_B = 0xA01 - SYS___CLOGL_H = 0xA02 - SYS___CLRENV = 0x0C9 - SYS___CLRMF = 0x0BD - SYS___CODEPAGE_INFO = 0xC64 - SYS___CONJF_B = 0xA07 - SYS___CONJF_H = 0xA08 - SYS___CONJL_B = 0xA0A - SYS___CONJL_H = 0xA0B - SYS___CONJ_B = 0xA04 - SYS___CONJ_H = 0xA05 - SYS___COPYSIGN_B = 0xA5A - SYS___COPYSIGN_H = 0xAF5 - SYS___COSPID128 = 0xC70 - SYS___COSPID32 = 0xC6E - SYS___COSPID64 = 0xC6F - SYS___CPOWF_B = 0xA10 - SYS___CPOWF_H = 0xA11 - SYS___CPOWL_B = 0xA13 - SYS___CPOWL_H = 0xA14 - SYS___CPOW_B = 0xA0D - SYS___CPOW_H = 0xA0E - SYS___CPROJF_B = 0xA19 - SYS___CPROJF_H = 0xA1A - SYS___CPROJL_B = 0xA1C - SYS___CPROJL_H = 0xA1D - SYS___CPROJ_B = 0xA16 - SYS___CPROJ_H = 0xA17 - SYS___CREALF_B = 0xA22 - SYS___CREALF_H = 0xA23 - SYS___CREALL_B = 0xA25 - SYS___CREALL_H = 0xA26 - SYS___CREAL_B = 0xA1F - SYS___CREAL_H = 0xA20 - SYS___CSINF_B = 0xA2B - SYS___CSINF_H = 0xA2C - SYS___CSINHF_B = 0xA34 - SYS___CSINHF_H = 0xA35 - SYS___CSINHL_B = 0xA37 - SYS___CSINHL_H = 0xA38 - SYS___CSINH_B = 0xA31 - SYS___CSINH_H = 0xA32 - SYS___CSINL_B = 0xA2E - SYS___CSINL_H = 0xA2F - SYS___CSIN_B = 0xA28 - SYS___CSIN_H = 0xA29 - SYS___CSNAP = 0x0C5 - SYS___CSQRTF_B = 0xA3D - SYS___CSQRTF_H = 0xA3E - SYS___CSQRTL_B = 0xA40 - SYS___CSQRTL_H = 0xA41 - SYS___CSQRT_B = 0xA3A - SYS___CSQRT_H = 0xA3B - SYS___CTANF_B = 0xA46 - SYS___CTANF_H = 0xA47 - SYS___CTANHF_B = 0xA4F - SYS___CTANHF_H = 0xA50 - SYS___CTANHL_B = 0xA52 - SYS___CTANHL_H = 0xA53 - SYS___CTANH_B = 0xA4C - SYS___CTANH_H = 0xA4D - SYS___CTANL_B = 0xA49 - SYS___CTANL_H = 0xA4A - SYS___CTAN_B = 0xA43 - SYS___CTAN_H = 0xA44 - SYS___CTEST = 0x0C7 - SYS___CTRACE = 0x0C6 - SYS___D1TOP = 0xC9B - SYS___D2TOP = 0xC9C - SYS___D4TOP = 0xC9D - SYS___DYNALL = 0x0C3 - SYS___DYNFRE = 0x0C2 - SYS___EXP2F_H = 0xA5E - SYS___EXP2L_H = 0xA5F - SYS___EXP2_H = 0xA5D - SYS___EXPM1F_H = 0xA5B - SYS___EXPM1L_H = 0xA5C - SYS___FBUFSIZE = 0xD60 - SYS___FLBF = 0xD62 - SYS___FLDATA = 0x0C1 - SYS___FMAF_B = 0xA67 - SYS___FMAF_H = 0xA68 - SYS___FMAL_B = 0xA6A - SYS___FMAL_H = 0xA6B - SYS___FMAXF_B = 0xA70 - SYS___FMAXF_H = 0xA71 - SYS___FMAXL_B = 0xA73 - SYS___FMAXL_H = 0xA74 - SYS___FMAX_B = 0xA6D - SYS___FMAX_H = 0xA6E - SYS___FMA_B = 0xA64 - SYS___FMA_H = 0xA65 - SYS___FMINF_B = 0xA79 - SYS___FMINF_H = 0xA7A - SYS___FMINL_B = 0xA7C - SYS___FMINL_H = 0xA7D - SYS___FMIN_B = 0xA76 - SYS___FMIN_H = 0xA77 - SYS___FPENDING = 0xD61 - SYS___FPENDING_UNLOCKED = 0xD6C - SYS___FPURGE = 0xD69 - SYS___FPURGE_UNLOCKED = 0xD70 - SYS___FP_CAST_D = 0xBCB - SYS___FREADABLE = 0xD63 - SYS___FREADAHEAD = 0xD6A - SYS___FREADAHEAD_UNLOCKED = 0xD71 - SYS___FREADING = 0xD65 - SYS___FREADING_UNLOCKED = 0xD6D - SYS___FSEEK2 = 0xB3C - SYS___FSETERR = 0xD6B - SYS___FSETLOCKING = 0xD67 - SYS___FTCHEP = 0x0BF - SYS___FTELL2 = 0xB3B - SYS___FUPDT = 0x0B5 - SYS___FWRITABLE = 0xD64 - SYS___FWRITING = 0xD66 - SYS___FWRITING_UNLOCKED = 0xD6E - SYS___GETCB = 0x0B4 - SYS___GETGRGID1 = 0xD5B - SYS___GETGRNAM1 = 0xD5C - SYS___GETTHENT = 0xCE5 - SYS___GETTOD = 0xD3E - SYS___HYPOTF_H = 0xAF6 - SYS___HYPOTL_H = 0xAF7 - SYS___ILOGBF_B = 0xA7F - SYS___ILOGBF_H = 0xA80 - SYS___ILOGBL_B = 0xA82 - SYS___ILOGBL_H = 0xA83 - SYS___ISBLANK_A = 0xB2E - SYS___ISBLNK = 0x0FE - SYS___ISWBLANK_A = 0xB2F - SYS___LE_CEEGTJS = 0xD72 - SYS___LE_TRACEBACK = 0xB7A - SYS___LGAMMAL_H = 0xA62 - SYS___LGAMMA_B_C99 = 0xB39 - SYS___LGAMMA_H_C99 = 0xB38 - SYS___LGAMMA_R_C99 = 0xB3A - SYS___LLRINTF_B = 0xA88 - SYS___LLRINTF_H = 0xA89 - SYS___LLRINTL_B = 0xA8B - SYS___LLRINTL_H = 0xA8C - SYS___LLRINT_B = 0xA85 - SYS___LLRINT_H = 0xA86 - SYS___LLROUNDF_B = 0xA91 - SYS___LLROUNDF_H = 0xA92 - SYS___LLROUNDL_B = 0xA94 - SYS___LLROUNDL_H = 0xA95 - SYS___LLROUND_B = 0xA8E - SYS___LLROUND_H = 0xA8F - SYS___LOCALE_CTL = 0xD47 - SYS___LOG1PF_H = 0xA60 - SYS___LOG1PL_H = 0xA61 - SYS___LOGBF_B = 0xA97 - SYS___LOGBF_H = 0xA98 - SYS___LOGBL_B = 0xA9A - SYS___LOGBL_H = 0xA9B - SYS___LOGIN_APPLID = 0xCE2 - SYS___LRINTF_B = 0xAA0 - SYS___LRINTF_H = 0xAA1 - SYS___LRINTL_B = 0xAA3 - SYS___LRINTL_H = 0xAA4 - SYS___LRINT_B = 0xA9D - SYS___LRINT_H = 0xA9E - SYS___LROUNDF_FIXUP = 0xB31 - SYS___LROUNDL_B = 0xAA6 - SYS___LROUNDL_H = 0xAA7 - SYS___LROUND_FIXUP = 0xB30 - SYS___MOSERVICES = 0xD3D - SYS___MUST_STAY_CLEAN = 0xB7C - SYS___NANF_B = 0xAAB - SYS___NANL_B = 0xAAD - SYS___NAN_B = 0xAA9 - SYS___NEARBYINTF_B = 0xAB2 - SYS___NEARBYINTF_H = 0xAB3 - SYS___NEARBYINTL_B = 0xAB5 - SYS___NEARBYINTL_H = 0xAB6 - SYS___NEARBYINT_B = 0xAAF - SYS___NEARBYINT_H = 0xAB0 - SYS___NEXTAFTERF_B = 0xAB8 - SYS___NEXTAFTERF_H = 0xAB9 - SYS___NEXTAFTERL_B = 0xABB - SYS___NEXTAFTERL_H = 0xABC - SYS___NEXTTOWARDF_B = 0xAC1 - SYS___NEXTTOWARDF_H = 0xAC2 - SYS___NEXTTOWARDL_B = 0xAC4 - SYS___NEXTTOWARDL_H = 0xAC5 - SYS___NEXTTOWARD_B = 0xABE - SYS___NEXTTOWARD_H = 0xABF - SYS___O_ENV = 0xB7D - SYS___PASSWD_APPLID = 0xCE3 - SYS___PTOD1 = 0xC9E - SYS___PTOD2 = 0xC9F - SYS___PTOD4 = 0xCA0 - SYS___REGCOMP_STD = 0x0EA - SYS___REMAINDERF_H = 0xAC6 - SYS___REMAINDERL_H = 0xAC7 - SYS___REMQUOD128 = 0xC10 - SYS___REMQUOD32 = 0xC0E - SYS___REMQUOD64 = 0xC0F - SYS___REMQUOF_H = 0xAC9 - SYS___REMQUOL_H = 0xACA - SYS___REMQUO_H = 0xAC8 - SYS___RINTF_B = 0xACC - SYS___RINTL_B = 0xACE - SYS___ROUNDF_B = 0xAD3 - SYS___ROUNDF_H = 0xAD4 - SYS___ROUNDL_B = 0xAD6 - SYS___ROUNDL_H = 0xAD7 - SYS___ROUND_B = 0xAD0 - SYS___ROUND_H = 0xAD1 - SYS___SCALBLNF_B = 0xADC - SYS___SCALBLNF_H = 0xADD - SYS___SCALBLNL_B = 0xADF - SYS___SCALBLNL_H = 0xAE0 - SYS___SCALBLN_B = 0xAD9 - SYS___SCALBLN_H = 0xADA - SYS___SCALBNF_B = 0xAE4 - SYS___SCALBNF_H = 0xAE5 - SYS___SCALBNL_B = 0xAE7 - SYS___SCALBNL_H = 0xAE8 - SYS___SCALBN_B = 0xAE1 - SYS___SCALBN_H = 0xAE2 - SYS___SETENV = 0x0C8 - SYS___SINPID128 = 0xC73 - SYS___SINPID32 = 0xC71 - SYS___SINPID64 = 0xC72 - SYS___SMF_RECORD2 = 0xD48 - SYS___STATIC_REINIT = 0xB3D - SYS___TGAMMAF_H_C99 = 0xB79 - SYS___TGAMMAL_H = 0xAE9 - SYS___TGAMMA_H_C99 = 0xB78 - SYS___TOCSNAME2 = 0xC9A - SYS_CEIL = 0x01F - SYS_CHAUDIT = 0x1E0 - SYS_EXP = 0x01A - SYS_FCHAUDIT = 0x1E1 - SYS_FREXP = 0x01D - SYS_GETGROUPSBYNAME = 0x1E2 - SYS_GETPWUID = 0x1A0 - SYS_GETUID = 0x1A1 - SYS_ISATTY = 0x1A3 - SYS_KILL = 0x1A4 - SYS_LDEXP = 0x01E - SYS_LINK = 0x1A5 - SYS_LOG10 = 0x01C - SYS_LSEEK = 0x1A6 - SYS_LSTAT = 0x1A7 - SYS_MKDIR = 0x1A8 - SYS_MKFIFO = 0x1A9 - SYS_MKNOD = 0x1AA - SYS_MODF = 0x01B - SYS_MOUNT = 0x1AB - SYS_OPEN = 0x1AC - SYS_OPENDIR = 0x1AD - SYS_PATHCONF = 0x1AE - SYS_PAUSE = 0x1AF - SYS_PIPE = 0x1B0 - SYS_PTHREAD_ATTR_DESTROY = 0x1E7 - SYS_PTHREAD_ATTR_GETDETACHSTATE = 0x1EB - SYS_PTHREAD_ATTR_GETSTACKSIZE = 0x1E9 - SYS_PTHREAD_ATTR_GETWEIGHT_NP = 0x1ED - SYS_PTHREAD_ATTR_INIT = 0x1E6 - SYS_PTHREAD_ATTR_SETDETACHSTATE = 0x1EA - SYS_PTHREAD_ATTR_SETSTACKSIZE = 0x1E8 - SYS_PTHREAD_ATTR_SETWEIGHT_NP = 0x1EC - SYS_PTHREAD_CANCEL = 0x1EE - SYS_PTHREAD_CLEANUP_POP = 0x1F0 - SYS_PTHREAD_CLEANUP_PUSH = 0x1EF - SYS_PTHREAD_CONDATTR_DESTROY = 0x1F2 - SYS_PTHREAD_CONDATTR_INIT = 0x1F1 - SYS_PTHREAD_COND_BROADCAST = 0x1F6 - SYS_PTHREAD_COND_DESTROY = 0x1F4 - SYS_PTHREAD_COND_INIT = 0x1F3 - SYS_PTHREAD_COND_SIGNAL = 0x1F5 - SYS_PTHREAD_COND_TIMEDWAIT = 0x1F8 - SYS_PTHREAD_COND_WAIT = 0x1F7 - SYS_PTHREAD_CREATE = 0x1F9 - SYS_PTHREAD_DETACH = 0x1FA - SYS_PTHREAD_EQUAL = 0x1FB - SYS_PTHREAD_EXIT = 0x1E4 - SYS_PTHREAD_GETSPECIFIC = 0x1FC - SYS_PTHREAD_JOIN = 0x1FD - SYS_PTHREAD_KEY_CREATE = 0x1FE - SYS_PTHREAD_KILL = 0x1E5 - SYS_PTHREAD_MUTEXATTR_INIT = 0x1FF - SYS_READ = 0x1B2 - SYS_READDIR = 0x1B3 - SYS_READLINK = 0x1B4 - SYS_REWINDDIR = 0x1B5 - SYS_RMDIR = 0x1B6 - SYS_SETEGID = 0x1B7 - SYS_SETEUID = 0x1B8 - SYS_SETGID = 0x1B9 - SYS_SETPGID = 0x1BA - SYS_SETSID = 0x1BB - SYS_SETUID = 0x1BC - SYS_SIGACTION = 0x1BD - SYS_SIGADDSET = 0x1BE - SYS_SIGDELSET = 0x1BF - SYS_SIGEMPTYSET = 0x1C0 - SYS_SIGFILLSET = 0x1C1 - SYS_SIGISMEMBER = 0x1C2 - SYS_SIGLONGJMP = 0x1C3 - SYS_SIGPENDING = 0x1C4 - SYS_SIGPROCMASK = 0x1C5 - SYS_SIGSETJMP = 0x1C6 - SYS_SIGSUSPEND = 0x1C7 - SYS_SIGWAIT = 0x1E3 - SYS_SLEEP = 0x1C8 - SYS_STAT = 0x1C9 - SYS_SYMLINK = 0x1CB - SYS_SYSCONF = 0x1CC - SYS_TCDRAIN = 0x1CD - SYS_TCFLOW = 0x1CE - SYS_TCFLUSH = 0x1CF - SYS_TCGETATTR = 0x1D0 - SYS_TCGETPGRP = 0x1D1 - SYS_TCSENDBREAK = 0x1D2 - SYS_TCSETATTR = 0x1D3 - SYS_TCSETPGRP = 0x1D4 - SYS_TIMES = 0x1D5 - SYS_TTYNAME = 0x1D6 - SYS_TZSET = 0x1D7 - SYS_UMASK = 0x1D8 - SYS_UMOUNT = 0x1D9 - SYS_UNAME = 0x1DA - SYS_UNLINK = 0x1DB - SYS_UTIME = 0x1DC - SYS_WAIT = 0x1DD - SYS_WAITPID = 0x1DE - SYS_WRITE = 0x1DF - SYS_W_GETPSENT = 0x1B1 - SYS_W_IOCTL = 0x1A2 - SYS_W_STATFS = 0x1CA - SYS_A64L = 0x2EF - SYS_BCMP = 0x2B9 - SYS_BCOPY = 0x2BA - SYS_BZERO = 0x2BB - SYS_CATCLOSE = 0x2B6 - SYS_CATGETS = 0x2B7 - SYS_CATOPEN = 0x2B8 - SYS_CRYPT = 0x2AC - SYS_DBM_CLEARERR = 0x2F7 - SYS_DBM_CLOSE = 0x2F8 - SYS_DBM_DELETE = 0x2F9 - SYS_DBM_ERROR = 0x2FA - SYS_DBM_FETCH = 0x2FB - SYS_DBM_FIRSTKEY = 0x2FC - SYS_DBM_NEXTKEY = 0x2FD - SYS_DBM_OPEN = 0x2FE - SYS_DBM_STORE = 0x2FF - SYS_DRAND48 = 0x2B2 - SYS_ENCRYPT = 0x2AD - SYS_ENDUTXENT = 0x2E1 - SYS_ERAND48 = 0x2B3 - SYS_ERF = 0x02C - SYS_ERFC = 0x02D - SYS_FCHDIR = 0x2D9 - SYS_FFS = 0x2BC - SYS_FMTMSG = 0x2E5 - SYS_FSTATVFS = 0x2B4 - SYS_FTIME = 0x2F5 - SYS_GAMMA = 0x02E - SYS_GETDATE = 0x2A6 - SYS_GETPAGESIZE = 0x2D8 - SYS_GETTIMEOFDAY = 0x2F6 - SYS_GETUTXENT = 0x2E0 - SYS_GETUTXID = 0x2E2 - SYS_GETUTXLINE = 0x2E3 - SYS_HCREATE = 0x2C6 - SYS_HDESTROY = 0x2C7 - SYS_HSEARCH = 0x2C8 - SYS_HYPOT = 0x02B - SYS_INDEX = 0x2BD - SYS_INITSTATE = 0x2C2 - SYS_INSQUE = 0x2CF - SYS_ISASCII = 0x2ED - SYS_JRAND48 = 0x2E6 - SYS_L64A = 0x2F0 - SYS_LCONG48 = 0x2EA - SYS_LFIND = 0x2C9 - SYS_LRAND48 = 0x2E7 - SYS_LSEARCH = 0x2CA - SYS_MEMCCPY = 0x2D4 - SYS_MRAND48 = 0x2E8 - SYS_NRAND48 = 0x2E9 - SYS_PCLOSE = 0x2D2 - SYS_POPEN = 0x2D1 - SYS_PUTUTXLINE = 0x2E4 - SYS_RANDOM = 0x2C4 - SYS_REMQUE = 0x2D0 - SYS_RINDEX = 0x2BE - SYS_SEED48 = 0x2EC - SYS_SETKEY = 0x2AE - SYS_SETSTATE = 0x2C3 - SYS_SETUTXENT = 0x2DF - SYS_SRAND48 = 0x2EB - SYS_SRANDOM = 0x2C5 - SYS_STATVFS = 0x2B5 - SYS_STRCASECMP = 0x2BF - SYS_STRDUP = 0x2C0 - SYS_STRNCASECMP = 0x2C1 - SYS_SWAB = 0x2D3 - SYS_TDELETE = 0x2CB - SYS_TFIND = 0x2CC - SYS_TOASCII = 0x2EE - SYS_TSEARCH = 0x2CD - SYS_TWALK = 0x2CE - SYS_UALARM = 0x2F1 - SYS_USLEEP = 0x2F2 - SYS_WAIT3 = 0x2A7 - SYS_WAITID = 0x2A8 - SYS_Y1 = 0x02A - SYS___ATOE = 0x2DB - SYS___ATOE_L = 0x2DC - SYS___CATTRM = 0x2A9 - SYS___CNVBLK = 0x2AF - SYS___CRYTRM = 0x2B0 - SYS___DLGHT = 0x2A1 - SYS___ECRTRM = 0x2B1 - SYS___ETOA = 0x2DD - SYS___ETOA_L = 0x2DE - SYS___GDTRM = 0x2AA - SYS___OCLCK = 0x2DA - SYS___OPARGF = 0x2A2 - SYS___OPERRF = 0x2A5 - SYS___OPINDF = 0x2A4 - SYS___OPOPTF = 0x2A3 - SYS___RNDTRM = 0x2AB - SYS___SRCTRM = 0x2F4 - SYS___TZONE = 0x2A0 - SYS___UTXTRM = 0x2F3 - SYS_ASIN = 0x03E - SYS_ISXDIGIT = 0x03B - SYS_SETLOCAL = 0x03A - SYS_SETLOCALE = 0x03A - SYS_SIN = 0x03F - SYS_TOLOWER = 0x03C - SYS_TOUPPER = 0x03D - SYS_ACCEPT_AND_RECV = 0x4F7 - SYS_ATOL = 0x04E - SYS_CHECKSCH = 0x4BC - SYS_CHECKSCHENV = 0x4BC - SYS_CLEARERR = 0x04C - SYS_CONNECTS = 0x4B5 - SYS_CONNECTSERVER = 0x4B5 - SYS_CONNECTW = 0x4B4 - SYS_CONNECTWORKMGR = 0x4B4 - SYS_CONTINUE = 0x4B3 - SYS_CONTINUEWORKUNIT = 0x4B3 - SYS_COPYSIGN = 0x4C2 - SYS_CREATEWO = 0x4B2 - SYS_CREATEWORKUNIT = 0x4B2 - SYS_DELETEWO = 0x4B9 - SYS_DELETEWORKUNIT = 0x4B9 - SYS_DISCONNE = 0x4B6 - SYS_DISCONNECTSERVER = 0x4B6 - SYS_FEOF = 0x04D - SYS_FERROR = 0x04A - SYS_FINITE = 0x4C8 - SYS_GAMMA_R = 0x4E2 - SYS_JOINWORK = 0x4B7 - SYS_JOINWORKUNIT = 0x4B7 - SYS_LEAVEWOR = 0x4B8 - SYS_LEAVEWORKUNIT = 0x4B8 - SYS_LGAMMA_R = 0x4EB - SYS_MATHERR = 0x4D0 - SYS_PERROR = 0x04F - SYS_QUERYMET = 0x4BA - SYS_QUERYMETRICS = 0x4BA - SYS_QUERYSCH = 0x4BB - SYS_QUERYSCHENV = 0x4BB - SYS_REWIND = 0x04B - SYS_SCALBN = 0x4D4 - SYS_SIGNIFIC = 0x4D5 - SYS_SIGNIFICAND = 0x4D5 - SYS___ACOSH_B = 0x4DA - SYS___ACOS_B = 0x4D9 - SYS___ASINH_B = 0x4BE - SYS___ASIN_B = 0x4DB - SYS___ATAN2_B = 0x4DC - SYS___ATANH_B = 0x4DD - SYS___ATAN_B = 0x4BF - SYS___CBRT_B = 0x4C0 - SYS___CEIL_B = 0x4C1 - SYS___COSH_B = 0x4DE - SYS___COS_B = 0x4C3 - SYS___DGHT = 0x4A8 - SYS___ENVN = 0x4B0 - SYS___ERFC_B = 0x4C5 - SYS___ERF_B = 0x4C4 - SYS___EXPM1_B = 0x4C6 - SYS___EXP_B = 0x4DF - SYS___FABS_B = 0x4C7 - SYS___FLOOR_B = 0x4C9 - SYS___FMOD_B = 0x4E0 - SYS___FP_SETMODE = 0x4F8 - SYS___FREXP_B = 0x4CA - SYS___GAMMA_B = 0x4E1 - SYS___GDRR = 0x4A1 - SYS___HRRNO = 0x4A2 - SYS___HYPOT_B = 0x4E3 - SYS___ILOGB_B = 0x4CB - SYS___ISNAN_B = 0x4CC - SYS___J0_B = 0x4E4 - SYS___J1_B = 0x4E6 - SYS___JN_B = 0x4E8 - SYS___LDEXP_B = 0x4CD - SYS___LGAMMA_B = 0x4EA - SYS___LOG10_B = 0x4ED - SYS___LOG1P_B = 0x4CE - SYS___LOGB_B = 0x4CF - SYS___LOGIN = 0x4F5 - SYS___LOG_B = 0x4EC - SYS___MLOCKALL = 0x4B1 - SYS___MODF_B = 0x4D1 - SYS___NEXTAFTER_B = 0x4D2 - SYS___OPENDIR2 = 0x4F3 - SYS___OPEN_STAT = 0x4F6 - SYS___OPND = 0x4A5 - SYS___OPPT = 0x4A6 - SYS___OPRG = 0x4A3 - SYS___OPRR = 0x4A4 - SYS___PID_AFFINITY = 0x4BD - SYS___POW_B = 0x4EE - SYS___READDIR2 = 0x4F4 - SYS___REMAINDER_B = 0x4EF - SYS___RINT_B = 0x4D3 - SYS___SCALB_B = 0x4F0 - SYS___SIGACTIONSET = 0x4FB - SYS___SIGGM = 0x4A7 - SYS___SINH_B = 0x4F1 - SYS___SIN_B = 0x4D6 - SYS___SQRT_B = 0x4F2 - SYS___TANH_B = 0x4D8 - SYS___TAN_B = 0x4D7 - SYS___TRRNO = 0x4AF - SYS___TZNE = 0x4A9 - SYS___TZZN = 0x4AA - SYS___UCREATE = 0x4FC - SYS___UFREE = 0x4FE - SYS___UHEAPREPORT = 0x4FF - SYS___UMALLOC = 0x4FD - SYS___Y0_B = 0x4E5 - SYS___Y1_B = 0x4E7 - SYS___YN_B = 0x4E9 - SYS_ABORT = 0x05C - SYS_ASCTIME_R = 0x5E0 - SYS_ATEXIT = 0x05D - SYS_CONNECTE = 0x5AE - SYS_CONNECTEXPORTIMPORT = 0x5AE - SYS_CTIME_R = 0x5E1 - SYS_DN_COMP = 0x5DF - SYS_DN_EXPAND = 0x5DD - SYS_DN_SKIPNAME = 0x5DE - SYS_EXIT = 0x05A - SYS_EXPORTWO = 0x5A1 - SYS_EXPORTWORKUNIT = 0x5A1 - SYS_EXTRACTW = 0x5A5 - SYS_EXTRACTWORKUNIT = 0x5A5 - SYS_FSEEKO = 0x5C9 - SYS_FTELLO = 0x5C8 - SYS_GETGRGID_R = 0x5E7 - SYS_GETGRNAM_R = 0x5E8 - SYS_GETLOGIN_R = 0x5E9 - SYS_GETPWNAM_R = 0x5EA - SYS_GETPWUID_R = 0x5EB - SYS_GMTIME_R = 0x5E2 - SYS_IMPORTWO = 0x5A3 - SYS_IMPORTWORKUNIT = 0x5A3 - SYS_INET_NTOP = 0x5D3 - SYS_INET_PTON = 0x5D4 - SYS_LLABS = 0x5CE - SYS_LLDIV = 0x5CB - SYS_LOCALTIME_R = 0x5E3 - SYS_PTHREAD_ATFORK = 0x5ED - SYS_PTHREAD_ATTR_GETDETACHSTATE_U98 = 0x5FB - SYS_PTHREAD_ATTR_GETGUARDSIZE = 0x5EE - SYS_PTHREAD_ATTR_GETSCHEDPARAM = 0x5F9 - SYS_PTHREAD_ATTR_GETSTACKADDR = 0x5EF - SYS_PTHREAD_ATTR_SETDETACHSTATE_U98 = 0x5FC - SYS_PTHREAD_ATTR_SETGUARDSIZE = 0x5F0 - SYS_PTHREAD_ATTR_SETSCHEDPARAM = 0x5FA - SYS_PTHREAD_ATTR_SETSTACKADDR = 0x5F1 - SYS_PTHREAD_CONDATTR_GETPSHARED = 0x5F2 - SYS_PTHREAD_CONDATTR_SETPSHARED = 0x5F3 - SYS_PTHREAD_DETACH_U98 = 0x5FD - SYS_PTHREAD_GETCONCURRENCY = 0x5F4 - SYS_PTHREAD_GETSPECIFIC_U98 = 0x5FE - SYS_PTHREAD_KEY_DELETE = 0x5F5 - SYS_PTHREAD_SETCANCELSTATE = 0x5FF - SYS_PTHREAD_SETCONCURRENCY = 0x5F6 - SYS_PTHREAD_SIGMASK = 0x5F7 - SYS_QUERYENC = 0x5AD - SYS_QUERYWORKUNITCLASSIFICATION = 0x5AD - SYS_RAISE = 0x05E - SYS_RAND_R = 0x5E4 - SYS_READDIR_R = 0x5E6 - SYS_REALLOC = 0x05B - SYS_RES_INIT = 0x5D8 - SYS_RES_MKQUERY = 0x5D7 - SYS_RES_QUERY = 0x5D9 - SYS_RES_QUERYDOMAIN = 0x5DC - SYS_RES_SEARCH = 0x5DA - SYS_RES_SEND = 0x5DB - SYS_SETJMP = 0x05F - SYS_SIGQUEUE = 0x5A9 - SYS_STRTOK_R = 0x5E5 - SYS_STRTOLL = 0x5B0 - SYS_STRTOULL = 0x5B1 - SYS_TTYNAME_R = 0x5EC - SYS_UNDOEXPO = 0x5A2 - SYS_UNDOEXPORTWORKUNIT = 0x5A2 - SYS_UNDOIMPO = 0x5A4 - SYS_UNDOIMPORTWORKUNIT = 0x5A4 - SYS_WCSTOLL = 0x5CC - SYS_WCSTOULL = 0x5CD - SYS___ABORT = 0x05C - SYS___CONSOLE2 = 0x5D2 - SYS___CPL = 0x5A6 - SYS___DISCARDDATA = 0x5F8 - SYS___DSA_PREV = 0x5B2 - SYS___EP_FIND = 0x5B3 - SYS___FP_SWAPMODE = 0x5AF - SYS___GETUSERID = 0x5AB - SYS___GET_CPUID = 0x5B9 - SYS___GET_SYSTEM_SETTINGS = 0x5BA - SYS___IPDOMAINNAME = 0x5AC - SYS___MAP_INIT = 0x5A7 - SYS___MAP_SERVICE = 0x5A8 - SYS___MOUNT = 0x5AA - SYS___MSGRCV_TIMED = 0x5B7 - SYS___RES = 0x5D6 - SYS___SEMOP_TIMED = 0x5B8 - SYS___SERVER_THREADS_QUERY = 0x5B4 - SYS_FPRINTF = 0x06D - SYS_FSCANF = 0x06A - SYS_PRINTF = 0x06F - SYS_SETBUF = 0x06B - SYS_SETVBUF = 0x06C - SYS_SSCANF = 0x06E - SYS___CATGETS_A = 0x6C0 - SYS___CHAUDIT_A = 0x6F4 - SYS___CHMOD_A = 0x6E8 - SYS___COLLATE_INIT_A = 0x6AC - SYS___CREAT_A = 0x6F6 - SYS___CTYPE_INIT_A = 0x6AF - SYS___DLLLOAD_A = 0x6DF - SYS___DLLQUERYFN_A = 0x6E0 - SYS___DLLQUERYVAR_A = 0x6E1 - SYS___E2A_L = 0x6E3 - SYS___EXECLE_A = 0x6A0 - SYS___EXECLP_A = 0x6A4 - SYS___EXECVE_A = 0x6C1 - SYS___EXECVP_A = 0x6C2 - SYS___EXECV_A = 0x6B1 - SYS___FPRINTF_A = 0x6FA - SYS___GETADDRINFO_A = 0x6BF - SYS___GETNAMEINFO_A = 0x6C4 - SYS___GET_WCTYPE_STD_A = 0x6AE - SYS___ICONV_OPEN_A = 0x6DE - SYS___IF_INDEXTONAME_A = 0x6DC - SYS___IF_NAMETOINDEX_A = 0x6DB - SYS___ISWCTYPE_A = 0x6B0 - SYS___IS_WCTYPE_STD_A = 0x6B2 - SYS___LOCALECONV_A = 0x6B8 - SYS___LOCALECONV_STD_A = 0x6B9 - SYS___LOCALE_INIT_A = 0x6B7 - SYS___LSTAT_A = 0x6EE - SYS___LSTAT_O_A = 0x6EF - SYS___MKDIR_A = 0x6E9 - SYS___MKFIFO_A = 0x6EC - SYS___MKNOD_A = 0x6F0 - SYS___MONETARY_INIT_A = 0x6BC - SYS___MOUNT_A = 0x6F1 - SYS___NL_CSINFO_A = 0x6D6 - SYS___NL_LANGINFO_A = 0x6BA - SYS___NL_LNAGINFO_STD_A = 0x6BB - SYS___NL_MONINFO_A = 0x6D7 - SYS___NL_NUMINFO_A = 0x6D8 - SYS___NL_RESPINFO_A = 0x6D9 - SYS___NL_TIMINFO_A = 0x6DA - SYS___NUMERIC_INIT_A = 0x6C6 - SYS___OPEN_A = 0x6F7 - SYS___PRINTF_A = 0x6DD - SYS___RESP_INIT_A = 0x6C7 - SYS___RPMATCH_A = 0x6C8 - SYS___RPMATCH_C_A = 0x6C9 - SYS___RPMATCH_STD_A = 0x6CA - SYS___SETLOCALE_A = 0x6F9 - SYS___SPAWNP_A = 0x6C5 - SYS___SPAWN_A = 0x6C3 - SYS___SPRINTF_A = 0x6FB - SYS___STAT_A = 0x6EA - SYS___STAT_O_A = 0x6EB - SYS___STRCOLL_STD_A = 0x6A1 - SYS___STRFMON_A = 0x6BD - SYS___STRFMON_STD_A = 0x6BE - SYS___STRFTIME_A = 0x6CC - SYS___STRFTIME_STD_A = 0x6CD - SYS___STRPTIME_A = 0x6CE - SYS___STRPTIME_STD_A = 0x6CF - SYS___STRXFRM_A = 0x6A2 - SYS___STRXFRM_C_A = 0x6A3 - SYS___STRXFRM_STD_A = 0x6A5 - SYS___SYNTAX_INIT_A = 0x6D4 - SYS___TIME_INIT_A = 0x6CB - SYS___TOD_INIT_A = 0x6D5 - SYS___TOWLOWER_A = 0x6B3 - SYS___TOWLOWER_STD_A = 0x6B4 - SYS___TOWUPPER_A = 0x6B5 - SYS___TOWUPPER_STD_A = 0x6B6 - SYS___UMOUNT_A = 0x6F2 - SYS___VFPRINTF_A = 0x6FC - SYS___VPRINTF_A = 0x6FD - SYS___VSPRINTF_A = 0x6FE - SYS___VSWPRINTF_A = 0x6FF - SYS___WCSCOLL_A = 0x6A6 - SYS___WCSCOLL_C_A = 0x6A7 - SYS___WCSCOLL_STD_A = 0x6A8 - SYS___WCSFTIME_A = 0x6D0 - SYS___WCSFTIME_STD_A = 0x6D1 - SYS___WCSXFRM_A = 0x6A9 - SYS___WCSXFRM_C_A = 0x6AA - SYS___WCSXFRM_STD_A = 0x6AB - SYS___WCTYPE_A = 0x6AD - SYS___W_GETMNTENT_A = 0x6F5 - SYS_____CCSIDTYPE_A = 0x6E6 - SYS_____CHATTR_A = 0x6E2 - SYS_____CSNAMETYPE_A = 0x6E7 - SYS_____OPEN_STAT_A = 0x6ED - SYS_____SPAWN2_A = 0x6D2 - SYS_____SPAWNP2_A = 0x6D3 - SYS_____TOCCSID_A = 0x6E4 - SYS_____TOCSNAME_A = 0x6E5 - SYS_ACL_FREE = 0x7FF - SYS_ACL_INIT = 0x7FE - SYS_FWIDE = 0x7DF - SYS_FWPRINTF = 0x7D1 - SYS_FWRITE = 0x07E - SYS_FWSCANF = 0x7D5 - SYS_GETCHAR = 0x07B - SYS_GETS = 0x07C - SYS_M_CREATE_LAYOUT = 0x7C9 - SYS_M_DESTROY_LAYOUT = 0x7CA - SYS_M_GETVALUES_LAYOUT = 0x7CB - SYS_M_SETVALUES_LAYOUT = 0x7CC - SYS_M_TRANSFORM_LAYOUT = 0x7CD - SYS_M_WTRANSFORM_LAYOUT = 0x7CE - SYS_PREAD = 0x7C7 - SYS_PUTC = 0x07D - SYS_PUTCHAR = 0x07A - SYS_PUTS = 0x07F - SYS_PWRITE = 0x7C8 - SYS_TOWCTRAN = 0x7D8 - SYS_TOWCTRANS = 0x7D8 - SYS_UNATEXIT = 0x7B5 - SYS_VFWPRINT = 0x7D3 - SYS_VFWPRINTF = 0x7D3 - SYS_VWPRINTF = 0x7D4 - SYS_WCTRANS = 0x7D7 - SYS_WPRINTF = 0x7D2 - SYS_WSCANF = 0x7D6 - SYS___ASCTIME_R_A = 0x7A1 - SYS___BASENAME_A = 0x7DC - SYS___BTOWC_A = 0x7E4 - SYS___CDUMP_A = 0x7B7 - SYS___CEE3DMP_A = 0x7B6 - SYS___CEILF_H = 0x7F4 - SYS___CEILL_H = 0x7F5 - SYS___CEIL_H = 0x7EA - SYS___CRYPT_A = 0x7BE - SYS___CSNAP_A = 0x7B8 - SYS___CTEST_A = 0x7B9 - SYS___CTIME_R_A = 0x7A2 - SYS___CTRACE_A = 0x7BA - SYS___DBM_OPEN_A = 0x7E6 - SYS___DIRNAME_A = 0x7DD - SYS___FABSF_H = 0x7FA - SYS___FABSL_H = 0x7FB - SYS___FABS_H = 0x7ED - SYS___FGETWC_A = 0x7AA - SYS___FGETWS_A = 0x7AD - SYS___FLOORF_H = 0x7F6 - SYS___FLOORL_H = 0x7F7 - SYS___FLOOR_H = 0x7EB - SYS___FPUTWC_A = 0x7A5 - SYS___FPUTWS_A = 0x7A8 - SYS___GETTIMEOFDAY_A = 0x7AE - SYS___GETWCHAR_A = 0x7AC - SYS___GETWC_A = 0x7AB - SYS___GLOB_A = 0x7DE - SYS___GMTIME_A = 0x7AF - SYS___GMTIME_R_A = 0x7B0 - SYS___INET_PTON_A = 0x7BC - SYS___J0_H = 0x7EE - SYS___J1_H = 0x7EF - SYS___JN_H = 0x7F0 - SYS___LOCALTIME_A = 0x7B1 - SYS___LOCALTIME_R_A = 0x7B2 - SYS___MALLOC24 = 0x7FC - SYS___MALLOC31 = 0x7FD - SYS___MKTIME_A = 0x7B3 - SYS___MODFF_H = 0x7F8 - SYS___MODFL_H = 0x7F9 - SYS___MODF_H = 0x7EC - SYS___OPENDIR_A = 0x7C2 - SYS___OSNAME = 0x7E0 - SYS___PUTWCHAR_A = 0x7A7 - SYS___PUTWC_A = 0x7A6 - SYS___READDIR_A = 0x7C3 - SYS___STRTOLL_A = 0x7A3 - SYS___STRTOULL_A = 0x7A4 - SYS___SYSLOG_A = 0x7BD - SYS___TZZNA = 0x7B4 - SYS___UNGETWC_A = 0x7A9 - SYS___UTIME_A = 0x7A0 - SYS___VFPRINTF2_A = 0x7E7 - SYS___VPRINTF2_A = 0x7E8 - SYS___VSPRINTF2_A = 0x7E9 - SYS___VSWPRNTF2_A = 0x7BB - SYS___WCSTOD_A = 0x7D9 - SYS___WCSTOL_A = 0x7DA - SYS___WCSTOUL_A = 0x7DB - SYS___WCTOB_A = 0x7E5 - SYS___Y0_H = 0x7F1 - SYS___Y1_H = 0x7F2 - SYS___YN_H = 0x7F3 - SYS_____OPENDIR2_A = 0x7BF - SYS_____OSNAME_A = 0x7E1 - SYS_____READDIR2_A = 0x7C0 - SYS_DLCLOSE = 0x8DF - SYS_DLERROR = 0x8E0 - SYS_DLOPEN = 0x8DD - SYS_DLSYM = 0x8DE - SYS_FLOCKFILE = 0x8D3 - SYS_FTRYLOCKFILE = 0x8D4 - SYS_FUNLOCKFILE = 0x8D5 - SYS_GETCHAR_UNLOCKED = 0x8D7 - SYS_GETC_UNLOCKED = 0x8D6 - SYS_PUTCHAR_UNLOCKED = 0x8D9 - SYS_PUTC_UNLOCKED = 0x8D8 - SYS_SNPRINTF = 0x8DA - SYS_VSNPRINTF = 0x8DB - SYS_WCSCSPN = 0x08B - SYS_WCSLEN = 0x08C - SYS_WCSNCAT = 0x08D - SYS_WCSNCMP = 0x08A - SYS_WCSNCPY = 0x08F - SYS_WCSSPN = 0x08E - SYS___ABSF_H = 0x8E7 - SYS___ABSL_H = 0x8E8 - SYS___ABS_H = 0x8E6 - SYS___ACOSF_H = 0x8EA - SYS___ACOSH_H = 0x8EC - SYS___ACOSL_H = 0x8EB - SYS___ACOS_H = 0x8E9 - SYS___ASINF_H = 0x8EE - SYS___ASINH_H = 0x8F0 - SYS___ASINL_H = 0x8EF - SYS___ASIN_H = 0x8ED - SYS___ATAN2F_H = 0x8F8 - SYS___ATAN2L_H = 0x8F9 - SYS___ATAN2_H = 0x8F7 - SYS___ATANF_H = 0x8F2 - SYS___ATANHF_H = 0x8F5 - SYS___ATANHL_H = 0x8F6 - SYS___ATANH_H = 0x8F4 - SYS___ATANL_H = 0x8F3 - SYS___ATAN_H = 0x8F1 - SYS___CBRT_H = 0x8FA - SYS___COPYSIGNF_H = 0x8FB - SYS___COPYSIGNL_H = 0x8FC - SYS___COSF_H = 0x8FE - SYS___COSL_H = 0x8FF - SYS___COS_H = 0x8FD - SYS___DLERROR_A = 0x8D2 - SYS___DLOPEN_A = 0x8D0 - SYS___DLSYM_A = 0x8D1 - SYS___GETUTXENT_A = 0x8C6 - SYS___GETUTXID_A = 0x8C7 - SYS___GETUTXLINE_A = 0x8C8 - SYS___ITOA = 0x8AA - SYS___ITOA_A = 0x8B0 - SYS___LE_CONDITION_TOKEN_BUILD = 0x8A5 - SYS___LE_MSG_ADD_INSERT = 0x8A6 - SYS___LE_MSG_GET = 0x8A7 - SYS___LE_MSG_GET_AND_WRITE = 0x8A8 - SYS___LE_MSG_WRITE = 0x8A9 - SYS___LLTOA = 0x8AE - SYS___LLTOA_A = 0x8B4 - SYS___LTOA = 0x8AC - SYS___LTOA_A = 0x8B2 - SYS___PUTCHAR_UNLOCKED_A = 0x8CC - SYS___PUTC_UNLOCKED_A = 0x8CB - SYS___PUTUTXLINE_A = 0x8C9 - SYS___RESET_EXCEPTION_HANDLER = 0x8E3 - SYS___REXEC_A = 0x8C4 - SYS___REXEC_AF_A = 0x8C5 - SYS___SET_EXCEPTION_HANDLER = 0x8E2 - SYS___SNPRINTF_A = 0x8CD - SYS___SUPERKILL = 0x8A4 - SYS___TCGETATTR_A = 0x8A1 - SYS___TCSETATTR_A = 0x8A2 - SYS___ULLTOA = 0x8AF - SYS___ULLTOA_A = 0x8B5 - SYS___ULTOA = 0x8AD - SYS___ULTOA_A = 0x8B3 - SYS___UTOA = 0x8AB - SYS___UTOA_A = 0x8B1 - SYS___VHM_EVENT = 0x8E4 - SYS___VSNPRINTF_A = 0x8CE - SYS_____GETENV_A = 0x8C3 - SYS_____UTMPXNAME_A = 0x8CA - SYS_CACOSH = 0x9A0 - SYS_CACOSHF = 0x9A3 - SYS_CACOSHL = 0x9A6 - SYS_CARG = 0x9A9 - SYS_CARGF = 0x9AC - SYS_CARGL = 0x9AF - SYS_CASIN = 0x9B2 - SYS_CASINF = 0x9B5 - SYS_CASINH = 0x9BB - SYS_CASINHF = 0x9BE - SYS_CASINHL = 0x9C1 - SYS_CASINL = 0x9B8 - SYS_CATAN = 0x9C4 - SYS_CATANF = 0x9C7 - SYS_CATANH = 0x9CD - SYS_CATANHF = 0x9D0 - SYS_CATANHL = 0x9D3 - SYS_CATANL = 0x9CA - SYS_CCOS = 0x9D6 - SYS_CCOSF = 0x9D9 - SYS_CCOSH = 0x9DF - SYS_CCOSHF = 0x9E2 - SYS_CCOSHL = 0x9E5 - SYS_CCOSL = 0x9DC - SYS_CEXP = 0x9E8 - SYS_CEXPF = 0x9EB - SYS_CEXPL = 0x9EE - SYS_CIMAG = 0x9F1 - SYS_CIMAGF = 0x9F4 - SYS_CIMAGL = 0x9F7 - SYS_CLOGF = 0x9FD - SYS_MEMCHR = 0x09B - SYS_MEMCMP = 0x09A - SYS_STRCOLL = 0x09C - SYS_STRNCMP = 0x09D - SYS_STRRCHR = 0x09F - SYS_STRXFRM = 0x09E - SYS___CACOSHF_B = 0x9A4 - SYS___CACOSHF_H = 0x9A5 - SYS___CACOSHL_B = 0x9A7 - SYS___CACOSHL_H = 0x9A8 - SYS___CACOSH_B = 0x9A1 - SYS___CACOSH_H = 0x9A2 - SYS___CARGF_B = 0x9AD - SYS___CARGF_H = 0x9AE - SYS___CARGL_B = 0x9B0 - SYS___CARGL_H = 0x9B1 - SYS___CARG_B = 0x9AA - SYS___CARG_H = 0x9AB - SYS___CASINF_B = 0x9B6 - SYS___CASINF_H = 0x9B7 - SYS___CASINHF_B = 0x9BF - SYS___CASINHF_H = 0x9C0 - SYS___CASINHL_B = 0x9C2 - SYS___CASINHL_H = 0x9C3 - SYS___CASINH_B = 0x9BC - SYS___CASINH_H = 0x9BD - SYS___CASINL_B = 0x9B9 - SYS___CASINL_H = 0x9BA - SYS___CASIN_B = 0x9B3 - SYS___CASIN_H = 0x9B4 - SYS___CATANF_B = 0x9C8 - SYS___CATANF_H = 0x9C9 - SYS___CATANHF_B = 0x9D1 - SYS___CATANHF_H = 0x9D2 - SYS___CATANHL_B = 0x9D4 - SYS___CATANHL_H = 0x9D5 - SYS___CATANH_B = 0x9CE - SYS___CATANH_H = 0x9CF - SYS___CATANL_B = 0x9CB - SYS___CATANL_H = 0x9CC - SYS___CATAN_B = 0x9C5 - SYS___CATAN_H = 0x9C6 - SYS___CCOSF_B = 0x9DA - SYS___CCOSF_H = 0x9DB - SYS___CCOSHF_B = 0x9E3 - SYS___CCOSHF_H = 0x9E4 - SYS___CCOSHL_B = 0x9E6 - SYS___CCOSHL_H = 0x9E7 - SYS___CCOSH_B = 0x9E0 - SYS___CCOSH_H = 0x9E1 - SYS___CCOSL_B = 0x9DD - SYS___CCOSL_H = 0x9DE - SYS___CCOS_B = 0x9D7 - SYS___CCOS_H = 0x9D8 - SYS___CEXPF_B = 0x9EC - SYS___CEXPF_H = 0x9ED - SYS___CEXPL_B = 0x9EF - SYS___CEXPL_H = 0x9F0 - SYS___CEXP_B = 0x9E9 - SYS___CEXP_H = 0x9EA - SYS___CIMAGF_B = 0x9F5 - SYS___CIMAGF_H = 0x9F6 - SYS___CIMAGL_B = 0x9F8 - SYS___CIMAGL_H = 0x9F9 - SYS___CIMAG_B = 0x9F2 - SYS___CIMAG_H = 0x9F3 - SYS___CLOG = 0x9FA - SYS___CLOGF_B = 0x9FE - SYS___CLOGF_H = 0x9FF - SYS___CLOG_B = 0x9FB - SYS___CLOG_H = 0x9FC - SYS_ISWCTYPE = 0x10C - SYS_ISWXDIGI = 0x10A - SYS_ISWXDIGIT = 0x10A - SYS_MBSINIT = 0x10F - SYS_TOWLOWER = 0x10D - SYS_TOWUPPER = 0x10E - SYS_WCTYPE = 0x10B - SYS_WCSSTR = 0x11B - SYS___RPMTCH = 0x11A - SYS_WCSTOD = 0x12E - SYS_WCSTOK = 0x12C - SYS_WCSTOL = 0x12D - SYS_WCSTOUL = 0x12F - SYS_FGETWC = 0x13C - SYS_FGETWS = 0x13D - SYS_FPUTWC = 0x13E - SYS_FPUTWS = 0x13F - SYS_REGERROR = 0x13B - SYS_REGFREE = 0x13A - SYS_COLLEQUIV = 0x14F - SYS_COLLTOSTR = 0x14E - SYS_ISMCCOLLEL = 0x14C - SYS_STRTOCOLL = 0x14D - SYS_DLLFREE = 0x16F - SYS_DLLQUERYFN = 0x16D - SYS_DLLQUERYVAR = 0x16E - SYS_GETMCCOLL = 0x16A - SYS_GETWMCCOLL = 0x16B - SYS___ERR2AD = 0x16C - SYS_CFSETOSPEED = 0x17A - SYS_CHDIR = 0x17B - SYS_CHMOD = 0x17C - SYS_CHOWN = 0x17D - SYS_CLOSE = 0x17E - SYS_CLOSEDIR = 0x17F - SYS_LOG = 0x017 - SYS_COSH = 0x018 - SYS_FCHMOD = 0x18A - SYS_FCHOWN = 0x18B - SYS_FCNTL = 0x18C - SYS_FILENO = 0x18D - SYS_FORK = 0x18E - SYS_FPATHCONF = 0x18F - SYS_GETLOGIN = 0x19A - SYS_GETPGRP = 0x19C - SYS_GETPID = 0x19D - SYS_GETPPID = 0x19E - SYS_GETPWNAM = 0x19F - SYS_TANH = 0x019 - SYS_W_GETMNTENT = 0x19B - SYS_POW = 0x020 - SYS_PTHREAD_SELF = 0x20A - SYS_PTHREAD_SETINTR = 0x20B - SYS_PTHREAD_SETINTRTYPE = 0x20C - SYS_PTHREAD_SETSPECIFIC = 0x20D - SYS_PTHREAD_TESTINTR = 0x20E - SYS_PTHREAD_YIELD = 0x20F - SYS_SQRT = 0x021 - SYS_FLOOR = 0x022 - SYS_J1 = 0x023 - SYS_WCSPBRK = 0x23F - SYS_BSEARCH = 0x24C - SYS_FABS = 0x024 - SYS_GETENV = 0x24A - SYS_LDIV = 0x24D - SYS_SYSTEM = 0x24B - SYS_FMOD = 0x025 - SYS___RETHROW = 0x25F - SYS___THROW = 0x25E - SYS_J0 = 0x026 - SYS_PUTENV = 0x26A - SYS___GETENV = 0x26F - SYS_SEMCTL = 0x27A - SYS_SEMGET = 0x27B - SYS_SEMOP = 0x27C - SYS_SHMAT = 0x27D - SYS_SHMCTL = 0x27E - SYS_SHMDT = 0x27F - SYS_YN = 0x027 - SYS_JN = 0x028 - SYS_SIGALTSTACK = 0x28A - SYS_SIGHOLD = 0x28B - SYS_SIGIGNORE = 0x28C - SYS_SIGINTERRUPT = 0x28D - SYS_SIGPAUSE = 0x28E - SYS_SIGRELSE = 0x28F - SYS_GETOPT = 0x29A - SYS_GETSUBOPT = 0x29D - SYS_LCHOWN = 0x29B - SYS_SETPGRP = 0x29E - SYS_TRUNCATE = 0x29C - SYS_Y0 = 0x029 - SYS___GDERR = 0x29F - SYS_ISALPHA = 0x030 - SYS_VFORK = 0x30F - SYS__LONGJMP = 0x30D - SYS__SETJMP = 0x30E - SYS_GLOB = 0x31A - SYS_GLOBFREE = 0x31B - SYS_ISALNUM = 0x031 - SYS_PUTW = 0x31C - SYS_SEEKDIR = 0x31D - SYS_TELLDIR = 0x31E - SYS_TEMPNAM = 0x31F - SYS_GETTIMEOFDAY_R = 0x32E - SYS_ISLOWER = 0x032 - SYS_LGAMMA = 0x32C - SYS_REMAINDER = 0x32A - SYS_SCALB = 0x32B - SYS_SYNC = 0x32F - SYS_TTYSLOT = 0x32D - SYS_ENDPROTOENT = 0x33A - SYS_ENDSERVENT = 0x33B - SYS_GETHOSTBYADDR = 0x33D - SYS_GETHOSTBYADDR_R = 0x33C - SYS_GETHOSTBYNAME = 0x33F - SYS_GETHOSTBYNAME_R = 0x33E - SYS_ISCNTRL = 0x033 - SYS_GETSERVBYNAME = 0x34A - SYS_GETSERVBYPORT = 0x34B - SYS_GETSERVENT = 0x34C - SYS_GETSOCKNAME = 0x34D - SYS_GETSOCKOPT = 0x34E - SYS_INET_ADDR = 0x34F - SYS_ISDIGIT = 0x034 - SYS_ISGRAPH = 0x035 - SYS_SELECT = 0x35B - SYS_SELECTEX = 0x35C - SYS_SEND = 0x35D - SYS_SENDTO = 0x35F - SYS_CHROOT = 0x36A - SYS_ISNAN = 0x36D - SYS_ISUPPER = 0x036 - SYS_ULIMIT = 0x36C - SYS_UTIMES = 0x36E - SYS_W_STATVFS = 0x36B - SYS___H_ERRNO = 0x36F - SYS_GRANTPT = 0x37A - SYS_ISPRINT = 0x037 - SYS_TCGETSID = 0x37C - SYS_UNLOCKPT = 0x37B - SYS___TCGETCP = 0x37D - SYS___TCSETCP = 0x37E - SYS___TCSETTABLES = 0x37F - SYS_ISPUNCT = 0x038 - SYS_NLIST = 0x38C - SYS___IPDBCS = 0x38D - SYS___IPDSPX = 0x38E - SYS___IPMSGC = 0x38F - SYS___STHOSTENT = 0x38B - SYS___STSERVENT = 0x38A - SYS_ISSPACE = 0x039 - SYS_COS = 0x040 - SYS_T_ALLOC = 0x40A - SYS_T_BIND = 0x40B - SYS_T_CLOSE = 0x40C - SYS_T_CONNECT = 0x40D - SYS_T_ERROR = 0x40E - SYS_T_FREE = 0x40F - SYS_TAN = 0x041 - SYS_T_RCVREL = 0x41A - SYS_T_RCVUDATA = 0x41B - SYS_T_RCVUDERR = 0x41C - SYS_T_SND = 0x41D - SYS_T_SNDDIS = 0x41E - SYS_T_SNDREL = 0x41F - SYS_GETPMSG = 0x42A - SYS_ISASTREAM = 0x42B - SYS_PUTMSG = 0x42C - SYS_PUTPMSG = 0x42D - SYS_SINH = 0x042 - SYS___ISPOSIXON = 0x42E - SYS___OPENMVSREL = 0x42F - SYS_ACOS = 0x043 - SYS_ATAN = 0x044 - SYS_ATAN2 = 0x045 - SYS_FTELL = 0x046 - SYS_FGETPOS = 0x047 - SYS_SOCK_DEBUG = 0x47A - SYS_SOCK_DO_TESTSTOR = 0x47D - SYS_TAKESOCKET = 0x47E - SYS___SERVER_INIT = 0x47F - SYS_FSEEK = 0x048 - SYS___IPHOST = 0x48B - SYS___IPNODE = 0x48C - SYS___SERVER_CLASSIFY_CREATE = 0x48D - SYS___SERVER_CLASSIFY_DESTROY = 0x48E - SYS___SERVER_CLASSIFY_RESET = 0x48F - SYS___SMF_RECORD = 0x48A - SYS_FSETPOS = 0x049 - SYS___FNWSA = 0x49B - SYS___SPAWN2 = 0x49D - SYS___SPAWNP2 = 0x49E - SYS_ATOF = 0x050 - SYS_PTHREAD_MUTEXATTR_GETPSHARED = 0x50A - SYS_PTHREAD_MUTEXATTR_SETPSHARED = 0x50B - SYS_PTHREAD_RWLOCK_DESTROY = 0x50C - SYS_PTHREAD_RWLOCK_INIT = 0x50D - SYS_PTHREAD_RWLOCK_RDLOCK = 0x50E - SYS_PTHREAD_RWLOCK_TRYRDLOCK = 0x50F - SYS_ATOI = 0x051 - SYS___FP_CLASS = 0x51D - SYS___FP_CLR_FLAG = 0x51A - SYS___FP_FINITE = 0x51E - SYS___FP_ISNAN = 0x51F - SYS___FP_RAISE_XCP = 0x51C - SYS___FP_READ_FLAG = 0x51B - SYS_RAND = 0x052 - SYS_SIGTIMEDWAIT = 0x52D - SYS_SIGWAITINFO = 0x52E - SYS___CHKBFP = 0x52F - SYS___FPC_RS = 0x52C - SYS___FPC_RW = 0x52A - SYS___FPC_SM = 0x52B - SYS_STRTOD = 0x053 - SYS_STRTOL = 0x054 - SYS_STRTOUL = 0x055 - SYS_MALLOC = 0x056 - SYS_SRAND = 0x057 - SYS_CALLOC = 0x058 - SYS_FREE = 0x059 - SYS___OSENV = 0x59F - SYS___W_PIOCTL = 0x59E - SYS_LONGJMP = 0x060 - SYS___FLOORF_B = 0x60A - SYS___FLOORL_B = 0x60B - SYS___FREXPF_B = 0x60C - SYS___FREXPL_B = 0x60D - SYS___LDEXPF_B = 0x60E - SYS___LDEXPL_B = 0x60F - SYS_SIGNAL = 0x061 - SYS___ATAN2F_B = 0x61A - SYS___ATAN2L_B = 0x61B - SYS___COSHF_B = 0x61C - SYS___COSHL_B = 0x61D - SYS___EXPF_B = 0x61E - SYS___EXPL_B = 0x61F - SYS_TMPNAM = 0x062 - SYS___ABSF_B = 0x62A - SYS___ABSL_B = 0x62C - SYS___ABS_B = 0x62B - SYS___FMODF_B = 0x62D - SYS___FMODL_B = 0x62E - SYS___MODFF_B = 0x62F - SYS_ATANL = 0x63A - SYS_CEILF = 0x63B - SYS_CEILL = 0x63C - SYS_COSF = 0x63D - SYS_COSHF = 0x63F - SYS_COSL = 0x63E - SYS_REMOVE = 0x063 - SYS_POWL = 0x64A - SYS_RENAME = 0x064 - SYS_SINF = 0x64B - SYS_SINHF = 0x64F - SYS_SINL = 0x64C - SYS_SQRTF = 0x64D - SYS_SQRTL = 0x64E - SYS_BTOWC = 0x65F - SYS_FREXPL = 0x65A - SYS_LDEXPF = 0x65B - SYS_LDEXPL = 0x65C - SYS_MODFF = 0x65D - SYS_MODFL = 0x65E - SYS_TMPFILE = 0x065 - SYS_FREOPEN = 0x066 - SYS___CHARMAP_INIT_A = 0x66E - SYS___GETHOSTBYADDR_R_A = 0x66C - SYS___GETHOSTBYNAME_A = 0x66A - SYS___GETHOSTBYNAME_R_A = 0x66D - SYS___MBLEN_A = 0x66F - SYS___RES_INIT_A = 0x66B - SYS_FCLOSE = 0x067 - SYS___GETGRGID_R_A = 0x67D - SYS___WCSTOMBS_A = 0x67A - SYS___WCSTOMBS_STD_A = 0x67B - SYS___WCSWIDTH_A = 0x67C - SYS___WCSWIDTH_ASIA = 0x67F - SYS___WCSWIDTH_STD_A = 0x67E - SYS_FFLUSH = 0x068 - SYS___GETLOGIN_R_A = 0x68E - SYS___GETPWNAM_R_A = 0x68C - SYS___GETPWUID_R_A = 0x68D - SYS___TTYNAME_R_A = 0x68F - SYS___WCWIDTH_ASIA = 0x68B - SYS___WCWIDTH_STD_A = 0x68A - SYS_FOPEN = 0x069 - SYS___REGEXEC_A = 0x69A - SYS___REGEXEC_STD_A = 0x69B - SYS___REGFREE_A = 0x69C - SYS___REGFREE_STD_A = 0x69D - SYS___STRCOLL_A = 0x69E - SYS___STRCOLL_C_A = 0x69F - SYS_SCANF = 0x070 - SYS___A64L_A = 0x70C - SYS___ECVT_A = 0x70D - SYS___FCVT_A = 0x70E - SYS___GCVT_A = 0x70F - SYS___STRTOUL_A = 0x70A - SYS_____AE_CORRESTBL_QUERY_A = 0x70B - SYS_SPRINTF = 0x071 - SYS___ACCESS_A = 0x71F - SYS___CATOPEN_A = 0x71E - SYS___GETOPT_A = 0x71D - SYS___REALPATH_A = 0x71A - SYS___SETENV_A = 0x71B - SYS___SYSTEM_A = 0x71C - SYS_FGETC = 0x072 - SYS___GAI_STRERROR_A = 0x72F - SYS___RMDIR_A = 0x72A - SYS___STATVFS_A = 0x72B - SYS___SYMLINK_A = 0x72C - SYS___TRUNCATE_A = 0x72D - SYS___UNLINK_A = 0x72E - SYS_VFPRINTF = 0x073 - SYS___ISSPACE_A = 0x73A - SYS___ISUPPER_A = 0x73B - SYS___ISWALNUM_A = 0x73F - SYS___ISXDIGIT_A = 0x73C - SYS___TOLOWER_A = 0x73D - SYS___TOUPPER_A = 0x73E - SYS_VPRINTF = 0x074 - SYS___CONFSTR_A = 0x74B - SYS___FDOPEN_A = 0x74E - SYS___FLDATA_A = 0x74F - SYS___FTOK_A = 0x74C - SYS___ISWXDIGIT_A = 0x74A - SYS___MKTEMP_A = 0x74D - SYS_VSPRINTF = 0x075 - SYS___GETGRGID_A = 0x75A - SYS___GETGRNAM_A = 0x75B - SYS___GETGROUPSBYNAME_A = 0x75C - SYS___GETHOSTENT_A = 0x75D - SYS___GETHOSTNAME_A = 0x75E - SYS___GETLOGIN_A = 0x75F - SYS_GETC = 0x076 - SYS___CREATEWORKUNIT_A = 0x76A - SYS___CTERMID_A = 0x76B - SYS___FMTMSG_A = 0x76C - SYS___INITGROUPS_A = 0x76D - SYS___MSGRCV_A = 0x76F - SYS_____LOGIN_A = 0x76E - SYS_FGETS = 0x077 - SYS___STRCASECMP_A = 0x77B - SYS___STRNCASECMP_A = 0x77C - SYS___TTYNAME_A = 0x77D - SYS___UNAME_A = 0x77E - SYS___UTIMES_A = 0x77F - SYS_____SERVER_PWU_A = 0x77A - SYS_FPUTC = 0x078 - SYS___CREAT_O_A = 0x78E - SYS___ENVNA = 0x78F - SYS___FREAD_A = 0x78A - SYS___FWRITE_A = 0x78B - SYS___ISASCII = 0x78D - SYS___OPEN_O_A = 0x78C - SYS_FPUTS = 0x079 - SYS___ASCTIME_A = 0x79C - SYS___CTIME_A = 0x79D - SYS___GETDATE_A = 0x79E - SYS___GETSERVBYPORT_A = 0x79A - SYS___GETSERVENT_A = 0x79B - SYS___TZSET_A = 0x79F - SYS_ACL_FROM_TEXT = 0x80C - SYS_ACL_SET_FD = 0x80A - SYS_ACL_SET_FILE = 0x80B - SYS_ACL_SORT = 0x80E - SYS_ACL_TO_TEXT = 0x80D - SYS_UNGETC = 0x080 - SYS___SHUTDOWN_REGISTRATION = 0x80F - SYS_FREAD = 0x081 - SYS_FREEADDRINFO = 0x81A - SYS_GAI_STRERROR = 0x81B - SYS_REXEC_AF = 0x81C - SYS___DYNALLOC_A = 0x81F - SYS___POE = 0x81D - SYS_WCSTOMBS = 0x082 - SYS___INET_ADDR_A = 0x82F - SYS___NLIST_A = 0x82A - SYS_____TCGETCP_A = 0x82B - SYS_____TCSETCP_A = 0x82C - SYS_____W_PIOCTL_A = 0x82E - SYS_MBTOWC = 0x083 - SYS___CABEND = 0x83D - SYS___LE_CIB_GET = 0x83E - SYS___RECVMSG_A = 0x83B - SYS___SENDMSG_A = 0x83A - SYS___SET_LAA_FOR_JIT = 0x83F - SYS_____LCHATTR_A = 0x83C - SYS_WCTOMB = 0x084 - SYS___CBRTL_B = 0x84A - SYS___COPYSIGNF_B = 0x84B - SYS___COPYSIGNL_B = 0x84C - SYS___COTANF_B = 0x84D - SYS___COTANL_B = 0x84F - SYS___COTAN_B = 0x84E - SYS_MBSTOWCS = 0x085 - SYS___LOG1PL_B = 0x85A - SYS___LOG2F_B = 0x85B - SYS___LOG2L_B = 0x85D - SYS___LOG2_B = 0x85C - SYS___REMAINDERF_B = 0x85E - SYS___REMAINDERL_B = 0x85F - SYS_ACOSHF = 0x86E - SYS_ACOSHL = 0x86F - SYS_WCSCPY = 0x086 - SYS___ERFCF_B = 0x86D - SYS___ERFF_B = 0x86C - SYS___LROUNDF_B = 0x86A - SYS___LROUND_B = 0x86B - SYS_COTANL = 0x87A - SYS_EXP2F = 0x87B - SYS_EXP2L = 0x87C - SYS_EXPM1F = 0x87D - SYS_EXPM1L = 0x87E - SYS_FDIMF = 0x87F - SYS_WCSCAT = 0x087 - SYS___COTANL = 0x87A - SYS_REMAINDERF = 0x88A - SYS_REMAINDERL = 0x88B - SYS_REMAINDF = 0x88A - SYS_REMAINDL = 0x88B - SYS_REMQUO = 0x88D - SYS_REMQUOF = 0x88C - SYS_REMQUOL = 0x88E - SYS_TGAMMAF = 0x88F - SYS_WCSCHR = 0x088 - SYS_ERFCF = 0x89B - SYS_ERFCL = 0x89C - SYS_ERFL = 0x89A - SYS_EXP2 = 0x89E - SYS_WCSCMP = 0x089 - SYS___EXP2_B = 0x89D - SYS___FAR_JUMP = 0x89F - SYS_ABS = 0x090 - SYS___ERFCL_H = 0x90A - SYS___EXPF_H = 0x90C - SYS___EXPL_H = 0x90D - SYS___EXPM1_H = 0x90E - SYS___EXP_H = 0x90B - SYS___FDIM_H = 0x90F - SYS_DIV = 0x091 - SYS___LOG2F_H = 0x91F - SYS___LOG2_H = 0x91E - SYS___LOGB_H = 0x91D - SYS___LOGF_H = 0x91B - SYS___LOGL_H = 0x91C - SYS___LOG_H = 0x91A - SYS_LABS = 0x092 - SYS___POWL_H = 0x92A - SYS___REMAINDER_H = 0x92B - SYS___RINT_H = 0x92C - SYS___SCALB_H = 0x92D - SYS___SINF_H = 0x92F - SYS___SIN_H = 0x92E - SYS_STRNCPY = 0x093 - SYS___TANHF_H = 0x93B - SYS___TANHL_H = 0x93C - SYS___TANH_H = 0x93A - SYS___TGAMMAF_H = 0x93E - SYS___TGAMMA_H = 0x93D - SYS___TRUNC_H = 0x93F - SYS_MEMCPY = 0x094 - SYS_VFWSCANF = 0x94A - SYS_VSWSCANF = 0x94E - SYS_VWSCANF = 0x94C - SYS_INET6_RTH_ADD = 0x95D - SYS_INET6_RTH_INIT = 0x95C - SYS_INET6_RTH_REVERSE = 0x95E - SYS_INET6_RTH_SEGMENTS = 0x95F - SYS_INET6_RTH_SPACE = 0x95B - SYS_MEMMOVE = 0x095 - SYS_WCSTOLD = 0x95A - SYS_STRCPY = 0x096 - SYS_STRCMP = 0x097 - SYS_CABS = 0x98E - SYS_STRCAT = 0x098 - SYS___CABS_B = 0x98F - SYS___POW_II = 0x98A - SYS___POW_II_B = 0x98B - SYS___POW_II_H = 0x98C - SYS_CACOSF = 0x99A - SYS_CACOSL = 0x99D - SYS_STRNCAT = 0x099 - SYS___CACOSF_B = 0x99B - SYS___CACOSF_H = 0x99C - SYS___CACOSL_B = 0x99E - SYS___CACOSL_H = 0x99F - SYS_ISWALPHA = 0x100 - SYS_ISWBLANK = 0x101 - SYS___ISWBLK = 0x101 - SYS_ISWCNTRL = 0x102 - SYS_ISWDIGIT = 0x103 - SYS_ISWGRAPH = 0x104 - SYS_ISWLOWER = 0x105 - SYS_ISWPRINT = 0x106 - SYS_ISWPUNCT = 0x107 - SYS_ISWSPACE = 0x108 - SYS_ISWUPPER = 0x109 - SYS_WCTOB = 0x110 - SYS_MBRLEN = 0x111 - SYS_MBRTOWC = 0x112 - SYS_MBSRTOWC = 0x113 - SYS_MBSRTOWCS = 0x113 - SYS_WCRTOMB = 0x114 - SYS_WCSRTOMB = 0x115 - SYS_WCSRTOMBS = 0x115 - SYS___CSID = 0x116 - SYS___WCSID = 0x117 - SYS_STRPTIME = 0x118 - SYS___STRPTM = 0x118 - SYS_STRFMON = 0x119 - SYS_WCSCOLL = 0x130 - SYS_WCSXFRM = 0x131 - SYS_WCSWIDTH = 0x132 - SYS_WCWIDTH = 0x133 - SYS_WCSFTIME = 0x134 - SYS_SWPRINTF = 0x135 - SYS_VSWPRINT = 0x136 - SYS_VSWPRINTF = 0x136 - SYS_SWSCANF = 0x137 - SYS_REGCOMP = 0x138 - SYS_REGEXEC = 0x139 - SYS_GETWC = 0x140 - SYS_GETWCHAR = 0x141 - SYS_PUTWC = 0x142 - SYS_PUTWCHAR = 0x143 - SYS_UNGETWC = 0x144 - SYS_ICONV_OPEN = 0x145 - SYS_ICONV = 0x146 - SYS_ICONV_CLOSE = 0x147 - SYS_COLLRANGE = 0x150 - SYS_CCLASS = 0x151 - SYS_COLLORDER = 0x152 - SYS___DEMANGLE = 0x154 - SYS_FDOPEN = 0x155 - SYS___ERRNO = 0x156 - SYS___ERRNO2 = 0x157 - SYS___TERROR = 0x158 - SYS_MAXCOLL = 0x169 - SYS_DLLLOAD = 0x170 - SYS__EXIT = 0x174 - SYS_ACCESS = 0x175 - SYS_ALARM = 0x176 - SYS_CFGETISPEED = 0x177 - SYS_CFGETOSPEED = 0x178 - SYS_CFSETISPEED = 0x179 - SYS_CREAT = 0x180 - SYS_CTERMID = 0x181 - SYS_DUP = 0x182 - SYS_DUP2 = 0x183 - SYS_EXECL = 0x184 - SYS_EXECLE = 0x185 - SYS_EXECLP = 0x186 - SYS_EXECV = 0x187 - SYS_EXECVE = 0x188 - SYS_EXECVP = 0x189 - SYS_FSTAT = 0x190 - SYS_FSYNC = 0x191 - SYS_FTRUNCATE = 0x192 - SYS_GETCWD = 0x193 - SYS_GETEGID = 0x194 - SYS_GETEUID = 0x195 - SYS_GETGID = 0x196 - SYS_GETGRGID = 0x197 - SYS_GETGRNAM = 0x198 - SYS_GETGROUPS = 0x199 - SYS_PTHREAD_MUTEXATTR_DESTROY = 0x200 - SYS_PTHREAD_MUTEXATTR_SETKIND_NP = 0x201 - SYS_PTHREAD_MUTEXATTR_GETKIND_NP = 0x202 - SYS_PTHREAD_MUTEX_INIT = 0x203 - SYS_PTHREAD_MUTEX_DESTROY = 0x204 - SYS_PTHREAD_MUTEX_LOCK = 0x205 - SYS_PTHREAD_MUTEX_TRYLOCK = 0x206 - SYS_PTHREAD_MUTEX_UNLOCK = 0x207 - SYS_PTHREAD_ONCE = 0x209 - SYS_TW_OPEN = 0x210 - SYS_TW_FCNTL = 0x211 - SYS_PTHREAD_JOIN_D4_NP = 0x212 - SYS_PTHREAD_CONDATTR_SETKIND_NP = 0x213 - SYS_PTHREAD_CONDATTR_GETKIND_NP = 0x214 - SYS_EXTLINK_NP = 0x215 - SYS___PASSWD = 0x216 - SYS_SETGROUPS = 0x217 - SYS_INITGROUPS = 0x218 - SYS_WCSRCHR = 0x240 - SYS_SVC99 = 0x241 - SYS___SVC99 = 0x241 - SYS_WCSWCS = 0x242 - SYS_LOCALECO = 0x243 - SYS_LOCALECONV = 0x243 - SYS___LIBREL = 0x244 - SYS_RELEASE = 0x245 - SYS___RLSE = 0x245 - SYS_FLOCATE = 0x246 - SYS___FLOCT = 0x246 - SYS_FDELREC = 0x247 - SYS___FDLREC = 0x247 - SYS_FETCH = 0x248 - SYS___FETCH = 0x248 - SYS_QSORT = 0x249 - SYS___CLEANUPCATCH = 0x260 - SYS___CATCHMATCH = 0x261 - SYS___CLEAN2UPCATCH = 0x262 - SYS_GETPRIORITY = 0x270 - SYS_NICE = 0x271 - SYS_SETPRIORITY = 0x272 - SYS_GETITIMER = 0x273 - SYS_SETITIMER = 0x274 - SYS_MSGCTL = 0x275 - SYS_MSGGET = 0x276 - SYS_MSGRCV = 0x277 - SYS_MSGSND = 0x278 - SYS_MSGXRCV = 0x279 - SYS___MSGXR = 0x279 - SYS_SHMGET = 0x280 - SYS___GETIPC = 0x281 - SYS_SETGRENT = 0x282 - SYS_GETGRENT = 0x283 - SYS_ENDGRENT = 0x284 - SYS_SETPWENT = 0x285 - SYS_GETPWENT = 0x286 - SYS_ENDPWENT = 0x287 - SYS_BSD_SIGNAL = 0x288 - SYS_KILLPG = 0x289 - SYS_SIGSET = 0x290 - SYS_SIGSTACK = 0x291 - SYS_GETRLIMIT = 0x292 - SYS_SETRLIMIT = 0x293 - SYS_GETRUSAGE = 0x294 - SYS_MMAP = 0x295 - SYS_MPROTECT = 0x296 - SYS_MSYNC = 0x297 - SYS_MUNMAP = 0x298 - SYS_CONFSTR = 0x299 - SYS___NDMTRM = 0x300 - SYS_FTOK = 0x301 - SYS_BASENAME = 0x302 - SYS_DIRNAME = 0x303 - SYS_GETDTABLESIZE = 0x304 - SYS_MKSTEMP = 0x305 - SYS_MKTEMP = 0x306 - SYS_NFTW = 0x307 - SYS_GETWD = 0x308 - SYS_LOCKF = 0x309 - SYS_WORDEXP = 0x310 - SYS_WORDFREE = 0x311 - SYS_GETPGID = 0x312 - SYS_GETSID = 0x313 - SYS___UTMPXNAME = 0x314 - SYS_CUSERID = 0x315 - SYS_GETPASS = 0x316 - SYS_FNMATCH = 0x317 - SYS_FTW = 0x318 - SYS_GETW = 0x319 - SYS_ACOSH = 0x320 - SYS_ASINH = 0x321 - SYS_ATANH = 0x322 - SYS_CBRT = 0x323 - SYS_EXPM1 = 0x324 - SYS_ILOGB = 0x325 - SYS_LOGB = 0x326 - SYS_LOG1P = 0x327 - SYS_NEXTAFTER = 0x328 - SYS_RINT = 0x329 - SYS_SPAWN = 0x330 - SYS_SPAWNP = 0x331 - SYS_GETLOGIN_UU = 0x332 - SYS_ECVT = 0x333 - SYS_FCVT = 0x334 - SYS_GCVT = 0x335 - SYS_ACCEPT = 0x336 - SYS_BIND = 0x337 - SYS_CONNECT = 0x338 - SYS_ENDHOSTENT = 0x339 - SYS_GETHOSTENT = 0x340 - SYS_GETHOSTID = 0x341 - SYS_GETHOSTNAME = 0x342 - SYS_GETNETBYADDR = 0x343 - SYS_GETNETBYNAME = 0x344 - SYS_GETNETENT = 0x345 - SYS_GETPEERNAME = 0x346 - SYS_GETPROTOBYNAME = 0x347 - SYS_GETPROTOBYNUMBER = 0x348 - SYS_GETPROTOENT = 0x349 - SYS_INET_LNAOF = 0x350 - SYS_INET_MAKEADDR = 0x351 - SYS_INET_NETOF = 0x352 - SYS_INET_NETWORK = 0x353 - SYS_INET_NTOA = 0x354 - SYS_IOCTL = 0x355 - SYS_LISTEN = 0x356 - SYS_READV = 0x357 - SYS_RECV = 0x358 - SYS_RECVFROM = 0x359 - SYS_SETHOSTENT = 0x360 - SYS_SETNETENT = 0x361 - SYS_SETPEER = 0x362 - SYS_SETPROTOENT = 0x363 - SYS_SETSERVENT = 0x364 - SYS_SETSOCKOPT = 0x365 - SYS_SHUTDOWN = 0x366 - SYS_SOCKET = 0x367 - SYS_SOCKETPAIR = 0x368 - SYS_WRITEV = 0x369 - SYS_ENDNETENT = 0x370 - SYS_CLOSELOG = 0x371 - SYS_OPENLOG = 0x372 - SYS_SETLOGMASK = 0x373 - SYS_SYSLOG = 0x374 - SYS_PTSNAME = 0x375 - SYS_SETREUID = 0x376 - SYS_SETREGID = 0x377 - SYS_REALPATH = 0x378 - SYS___SIGNGAM = 0x379 - SYS_POLL = 0x380 - SYS_REXEC = 0x381 - SYS___ISASCII2 = 0x382 - SYS___TOASCII2 = 0x383 - SYS_CHPRIORITY = 0x384 - SYS_PTHREAD_ATTR_SETSYNCTYPE_NP = 0x385 - SYS_PTHREAD_ATTR_GETSYNCTYPE_NP = 0x386 - SYS_PTHREAD_SET_LIMIT_NP = 0x387 - SYS___STNETENT = 0x388 - SYS___STPROTOENT = 0x389 - SYS___SELECT1 = 0x390 - SYS_PTHREAD_SECURITY_NP = 0x391 - SYS___CHECK_RESOURCE_AUTH_NP = 0x392 - SYS___CONVERT_ID_NP = 0x393 - SYS___OPENVMREL = 0x394 - SYS_WMEMCHR = 0x395 - SYS_WMEMCMP = 0x396 - SYS_WMEMCPY = 0x397 - SYS_WMEMMOVE = 0x398 - SYS_WMEMSET = 0x399 - SYS___FPUTWC = 0x400 - SYS___PUTWC = 0x401 - SYS___PWCHAR = 0x402 - SYS___WCSFTM = 0x403 - SYS___WCSTOK = 0x404 - SYS___WCWDTH = 0x405 - SYS_T_ACCEPT = 0x409 - SYS_T_GETINFO = 0x410 - SYS_T_GETPROTADDR = 0x411 - SYS_T_GETSTATE = 0x412 - SYS_T_LISTEN = 0x413 - SYS_T_LOOK = 0x414 - SYS_T_OPEN = 0x415 - SYS_T_OPTMGMT = 0x416 - SYS_T_RCV = 0x417 - SYS_T_RCVCONNECT = 0x418 - SYS_T_RCVDIS = 0x419 - SYS_T_SNDUDATA = 0x420 - SYS_T_STRERROR = 0x421 - SYS_T_SYNC = 0x422 - SYS_T_UNBIND = 0x423 - SYS___T_ERRNO = 0x424 - SYS___RECVMSG2 = 0x425 - SYS___SENDMSG2 = 0x426 - SYS_FATTACH = 0x427 - SYS_FDETACH = 0x428 - SYS_GETMSG = 0x429 - SYS_GETCONTEXT = 0x430 - SYS_SETCONTEXT = 0x431 - SYS_MAKECONTEXT = 0x432 - SYS_SWAPCONTEXT = 0x433 - SYS_PTHREAD_GETSPECIFIC_D8_NP = 0x434 - SYS_GETCLIENTID = 0x470 - SYS___GETCLIENTID = 0x471 - SYS_GETSTABLESIZE = 0x472 - SYS_GETIBMOPT = 0x473 - SYS_GETIBMSOCKOPT = 0x474 - SYS_GIVESOCKET = 0x475 - SYS_IBMSFLUSH = 0x476 - SYS_MAXDESC = 0x477 - SYS_SETIBMOPT = 0x478 - SYS_SETIBMSOCKOPT = 0x479 - SYS___SERVER_PWU = 0x480 - SYS_PTHREAD_TAG_NP = 0x481 - SYS___CONSOLE = 0x482 - SYS___WSINIT = 0x483 - SYS___IPTCPN = 0x489 - SYS___SERVER_CLASSIFY = 0x490 - SYS___HEAPRPT = 0x496 - SYS___ISBFP = 0x500 - SYS___FP_CAST = 0x501 - SYS___CERTIFICATE = 0x502 - SYS_SEND_FILE = 0x503 - SYS_AIO_CANCEL = 0x504 - SYS_AIO_ERROR = 0x505 - SYS_AIO_READ = 0x506 - SYS_AIO_RETURN = 0x507 - SYS_AIO_SUSPEND = 0x508 - SYS_AIO_WRITE = 0x509 - SYS_PTHREAD_RWLOCK_TRYWRLOCK = 0x510 - SYS_PTHREAD_RWLOCK_UNLOCK = 0x511 - SYS_PTHREAD_RWLOCK_WRLOCK = 0x512 - SYS_PTHREAD_RWLOCKATTR_GETPSHARED = 0x513 - SYS_PTHREAD_RWLOCKATTR_SETPSHARED = 0x514 - SYS_PTHREAD_RWLOCKATTR_INIT = 0x515 - SYS_PTHREAD_RWLOCKATTR_DESTROY = 0x516 - SYS___CTTBL = 0x517 - SYS_PTHREAD_MUTEXATTR_SETTYPE = 0x518 - SYS_PTHREAD_MUTEXATTR_GETTYPE = 0x519 - SYS___FP_UNORDERED = 0x520 - SYS___FP_READ_RND = 0x521 - SYS___FP_READ_RND_B = 0x522 - SYS___FP_SWAP_RND = 0x523 - SYS___FP_SWAP_RND_B = 0x524 - SYS___FP_LEVEL = 0x525 - SYS___FP_BTOH = 0x526 - SYS___FP_HTOB = 0x527 - SYS___FPC_RD = 0x528 - SYS___FPC_WR = 0x529 - SYS_PTHREAD_SETCANCELTYPE = 0x600 - SYS_PTHREAD_TESTCANCEL = 0x601 - SYS___ATANF_B = 0x602 - SYS___ATANL_B = 0x603 - SYS___CEILF_B = 0x604 - SYS___CEILL_B = 0x605 - SYS___COSF_B = 0x606 - SYS___COSL_B = 0x607 - SYS___FABSF_B = 0x608 - SYS___FABSL_B = 0x609 - SYS___SINF_B = 0x610 - SYS___SINL_B = 0x611 - SYS___TANF_B = 0x612 - SYS___TANL_B = 0x613 - SYS___TANHF_B = 0x614 - SYS___TANHL_B = 0x615 - SYS___ACOSF_B = 0x616 - SYS___ACOSL_B = 0x617 - SYS___ASINF_B = 0x618 - SYS___ASINL_B = 0x619 - SYS___LOGF_B = 0x620 - SYS___LOGL_B = 0x621 - SYS___LOG10F_B = 0x622 - SYS___LOG10L_B = 0x623 - SYS___POWF_B = 0x624 - SYS___POWL_B = 0x625 - SYS___SINHF_B = 0x626 - SYS___SINHL_B = 0x627 - SYS___SQRTF_B = 0x628 - SYS___SQRTL_B = 0x629 - SYS___MODFL_B = 0x630 - SYS_ABSF = 0x631 - SYS_ABSL = 0x632 - SYS_ACOSF = 0x633 - SYS_ACOSL = 0x634 - SYS_ASINF = 0x635 - SYS_ASINL = 0x636 - SYS_ATAN2F = 0x637 - SYS_ATAN2L = 0x638 - SYS_ATANF = 0x639 - SYS_COSHL = 0x640 - SYS_EXPF = 0x641 - SYS_EXPL = 0x642 - SYS_TANHF = 0x643 - SYS_TANHL = 0x644 - SYS_LOG10F = 0x645 - SYS_LOG10L = 0x646 - SYS_LOGF = 0x647 - SYS_LOGL = 0x648 - SYS_POWF = 0x649 - SYS_SINHL = 0x650 - SYS_TANF = 0x651 - SYS_TANL = 0x652 - SYS_FABSF = 0x653 - SYS_FABSL = 0x654 - SYS_FLOORF = 0x655 - SYS_FLOORL = 0x656 - SYS_FMODF = 0x657 - SYS_FMODL = 0x658 - SYS_FREXPF = 0x659 - SYS___CHATTR = 0x660 - SYS___FCHATTR = 0x661 - SYS___TOCCSID = 0x662 - SYS___CSNAMETYPE = 0x663 - SYS___TOCSNAME = 0x664 - SYS___CCSIDTYPE = 0x665 - SYS___AE_CORRESTBL_QUERY = 0x666 - SYS___AE_AUTOCONVERT_STATE = 0x667 - SYS_DN_FIND = 0x668 - SYS___GETHOSTBYADDR_A = 0x669 - SYS___MBLEN_SB_A = 0x670 - SYS___MBLEN_STD_A = 0x671 - SYS___MBLEN_UTF = 0x672 - SYS___MBSTOWCS_A = 0x673 - SYS___MBSTOWCS_STD_A = 0x674 - SYS___MBTOWC_A = 0x675 - SYS___MBTOWC_ISO1 = 0x676 - SYS___MBTOWC_SBCS = 0x677 - SYS___MBTOWC_MBCS = 0x678 - SYS___MBTOWC_UTF = 0x679 - SYS___CSID_A = 0x680 - SYS___CSID_STD_A = 0x681 - SYS___WCSID_A = 0x682 - SYS___WCSID_STD_A = 0x683 - SYS___WCTOMB_A = 0x684 - SYS___WCTOMB_ISO1 = 0x685 - SYS___WCTOMB_STD_A = 0x686 - SYS___WCTOMB_UTF = 0x687 - SYS___WCWIDTH_A = 0x688 - SYS___GETGRNAM_R_A = 0x689 - SYS___READDIR_R_A = 0x690 - SYS___E2A_S = 0x691 - SYS___FNMATCH_A = 0x692 - SYS___FNMATCH_C_A = 0x693 - SYS___EXECL_A = 0x694 - SYS___FNMATCH_STD_A = 0x695 - SYS___REGCOMP_A = 0x696 - SYS___REGCOMP_STD_A = 0x697 - SYS___REGERROR_A = 0x698 - SYS___REGERROR_STD_A = 0x699 - SYS___SWPRINTF_A = 0x700 - SYS___FSCANF_A = 0x701 - SYS___SCANF_A = 0x702 - SYS___SSCANF_A = 0x703 - SYS___SWSCANF_A = 0x704 - SYS___ATOF_A = 0x705 - SYS___ATOI_A = 0x706 - SYS___ATOL_A = 0x707 - SYS___STRTOD_A = 0x708 - SYS___STRTOL_A = 0x709 - SYS___L64A_A = 0x710 - SYS___STRERROR_A = 0x711 - SYS___PERROR_A = 0x712 - SYS___FETCH_A = 0x713 - SYS___GETENV_A = 0x714 - SYS___MKSTEMP_A = 0x717 - SYS___PTSNAME_A = 0x718 - SYS___PUTENV_A = 0x719 - SYS___CHDIR_A = 0x720 - SYS___CHOWN_A = 0x721 - SYS___CHROOT_A = 0x722 - SYS___GETCWD_A = 0x723 - SYS___GETWD_A = 0x724 - SYS___LCHOWN_A = 0x725 - SYS___LINK_A = 0x726 - SYS___PATHCONF_A = 0x727 - SYS___IF_NAMEINDEX_A = 0x728 - SYS___READLINK_A = 0x729 - SYS___EXTLINK_NP_A = 0x730 - SYS___ISALNUM_A = 0x731 - SYS___ISALPHA_A = 0x732 - SYS___A2E_S = 0x733 - SYS___ISCNTRL_A = 0x734 - SYS___ISDIGIT_A = 0x735 - SYS___ISGRAPH_A = 0x736 - SYS___ISLOWER_A = 0x737 - SYS___ISPRINT_A = 0x738 - SYS___ISPUNCT_A = 0x739 - SYS___ISWALPHA_A = 0x740 - SYS___A2E_L = 0x741 - SYS___ISWCNTRL_A = 0x742 - SYS___ISWDIGIT_A = 0x743 - SYS___ISWGRAPH_A = 0x744 - SYS___ISWLOWER_A = 0x745 - SYS___ISWPRINT_A = 0x746 - SYS___ISWPUNCT_A = 0x747 - SYS___ISWSPACE_A = 0x748 - SYS___ISWUPPER_A = 0x749 - SYS___REMOVE_A = 0x750 - SYS___RENAME_A = 0x751 - SYS___TMPNAM_A = 0x752 - SYS___FOPEN_A = 0x753 - SYS___FREOPEN_A = 0x754 - SYS___CUSERID_A = 0x755 - SYS___POPEN_A = 0x756 - SYS___TEMPNAM_A = 0x757 - SYS___FTW_A = 0x758 - SYS___GETGRENT_A = 0x759 - SYS___INET_NTOP_A = 0x760 - SYS___GETPASS_A = 0x761 - SYS___GETPWENT_A = 0x762 - SYS___GETPWNAM_A = 0x763 - SYS___GETPWUID_A = 0x764 - SYS_____CHECK_RESOURCE_AUTH_NP_A = 0x765 - SYS___CHECKSCHENV_A = 0x766 - SYS___CONNECTSERVER_A = 0x767 - SYS___CONNECTWORKMGR_A = 0x768 - SYS_____CONSOLE_A = 0x769 - SYS___MSGSND_A = 0x770 - SYS___MSGXRCV_A = 0x771 - SYS___NFTW_A = 0x772 - SYS_____PASSWD_A = 0x773 - SYS___PTHREAD_SECURITY_NP_A = 0x774 - SYS___QUERYMETRICS_A = 0x775 - SYS___QUERYSCHENV = 0x776 - SYS___READV_A = 0x777 - SYS_____SERVER_CLASSIFY_A = 0x778 - SYS_____SERVER_INIT_A = 0x779 - SYS___W_GETPSENT_A = 0x780 - SYS___WRITEV_A = 0x781 - SYS___W_STATFS_A = 0x782 - SYS___W_STATVFS_A = 0x783 - SYS___FPUTC_A = 0x784 - SYS___PUTCHAR_A = 0x785 - SYS___PUTS_A = 0x786 - SYS___FGETS_A = 0x787 - SYS___GETS_A = 0x788 - SYS___FPUTS_A = 0x789 - SYS___PUTC_A = 0x790 - SYS___AE_THREAD_SETMODE = 0x791 - SYS___AE_THREAD_SWAPMODE = 0x792 - SYS___GETNETBYADDR_A = 0x793 - SYS___GETNETBYNAME_A = 0x794 - SYS___GETNETENT_A = 0x795 - SYS___GETPROTOBYNAME_A = 0x796 - SYS___GETPROTOBYNUMBER_A = 0x797 - SYS___GETPROTOENT_A = 0x798 - SYS___GETSERVBYNAME_A = 0x799 - SYS_ACL_FIRST_ENTRY = 0x800 - SYS_ACL_GET_ENTRY = 0x801 - SYS_ACL_VALID = 0x802 - SYS_ACL_CREATE_ENTRY = 0x803 - SYS_ACL_DELETE_ENTRY = 0x804 - SYS_ACL_UPDATE_ENTRY = 0x805 - SYS_ACL_DELETE_FD = 0x806 - SYS_ACL_DELETE_FILE = 0x807 - SYS_ACL_GET_FD = 0x808 - SYS_ACL_GET_FILE = 0x809 - SYS___ERFL_B = 0x810 - SYS___ERFCL_B = 0x811 - SYS___LGAMMAL_B = 0x812 - SYS___SETHOOKEVENTS = 0x813 - SYS_IF_NAMETOINDEX = 0x814 - SYS_IF_INDEXTONAME = 0x815 - SYS_IF_NAMEINDEX = 0x816 - SYS_IF_FREENAMEINDEX = 0x817 - SYS_GETADDRINFO = 0x818 - SYS_GETNAMEINFO = 0x819 - SYS___DYNFREE_A = 0x820 - SYS___RES_QUERY_A = 0x821 - SYS___RES_SEARCH_A = 0x822 - SYS___RES_QUERYDOMAIN_A = 0x823 - SYS___RES_MKQUERY_A = 0x824 - SYS___RES_SEND_A = 0x825 - SYS___DN_EXPAND_A = 0x826 - SYS___DN_SKIPNAME_A = 0x827 - SYS___DN_COMP_A = 0x828 - SYS___DN_FIND_A = 0x829 - SYS___INET_NTOA_A = 0x830 - SYS___INET_NETWORK_A = 0x831 - SYS___ACCEPT_A = 0x832 - SYS___ACCEPT_AND_RECV_A = 0x833 - SYS___BIND_A = 0x834 - SYS___CONNECT_A = 0x835 - SYS___GETPEERNAME_A = 0x836 - SYS___GETSOCKNAME_A = 0x837 - SYS___RECVFROM_A = 0x838 - SYS___SENDTO_A = 0x839 - SYS___LCHATTR = 0x840 - SYS___WRITEDOWN = 0x841 - SYS_PTHREAD_MUTEX_INIT2 = 0x842 - SYS___ACOSHF_B = 0x843 - SYS___ACOSHL_B = 0x844 - SYS___ASINHF_B = 0x845 - SYS___ASINHL_B = 0x846 - SYS___ATANHF_B = 0x847 - SYS___ATANHL_B = 0x848 - SYS___CBRTF_B = 0x849 - SYS___EXP2F_B = 0x850 - SYS___EXP2L_B = 0x851 - SYS___EXPM1F_B = 0x852 - SYS___EXPM1L_B = 0x853 - SYS___FDIMF_B = 0x854 - SYS___FDIM_B = 0x855 - SYS___FDIML_B = 0x856 - SYS___HYPOTF_B = 0x857 - SYS___HYPOTL_B = 0x858 - SYS___LOG1PF_B = 0x859 - SYS___REMQUOF_B = 0x860 - SYS___REMQUO_B = 0x861 - SYS___REMQUOL_B = 0x862 - SYS___TGAMMAF_B = 0x863 - SYS___TGAMMA_B = 0x864 - SYS___TGAMMAL_B = 0x865 - SYS___TRUNCF_B = 0x866 - SYS___TRUNC_B = 0x867 - SYS___TRUNCL_B = 0x868 - SYS___LGAMMAF_B = 0x869 - SYS_ASINHF = 0x870 - SYS_ASINHL = 0x871 - SYS_ATANHF = 0x872 - SYS_ATANHL = 0x873 - SYS_CBRTF = 0x874 - SYS_CBRTL = 0x875 - SYS_COPYSIGNF = 0x876 - SYS_CPYSIGNF = 0x876 - SYS_COPYSIGNL = 0x877 - SYS_CPYSIGNL = 0x877 - SYS_COTANF = 0x878 - SYS___COTANF = 0x878 - SYS_COTAN = 0x879 - SYS___COTAN = 0x879 - SYS_FDIM = 0x881 - SYS_FDIML = 0x882 - SYS_HYPOTF = 0x883 - SYS_HYPOTL = 0x884 - SYS_LOG1PF = 0x885 - SYS_LOG1PL = 0x886 - SYS_LOG2F = 0x887 - SYS_LOG2 = 0x888 - SYS_LOG2L = 0x889 - SYS_TGAMMA = 0x890 - SYS_TGAMMAL = 0x891 - SYS_TRUNCF = 0x892 - SYS_TRUNC = 0x893 - SYS_TRUNCL = 0x894 - SYS_LGAMMAF = 0x895 - SYS_LGAMMAL = 0x896 - SYS_LROUNDF = 0x897 - SYS_LROUND = 0x898 - SYS_ERFF = 0x899 - SYS___COSHF_H = 0x900 - SYS___COSHL_H = 0x901 - SYS___COTAN_H = 0x902 - SYS___COTANF_H = 0x903 - SYS___COTANL_H = 0x904 - SYS___ERF_H = 0x905 - SYS___ERFF_H = 0x906 - SYS___ERFL_H = 0x907 - SYS___ERFC_H = 0x908 - SYS___ERFCF_H = 0x909 - SYS___FDIMF_H = 0x910 - SYS___FDIML_H = 0x911 - SYS___FMOD_H = 0x912 - SYS___FMODF_H = 0x913 - SYS___FMODL_H = 0x914 - SYS___GAMMA_H = 0x915 - SYS___HYPOT_H = 0x916 - SYS___ILOGB_H = 0x917 - SYS___LGAMMA_H = 0x918 - SYS___LGAMMAF_H = 0x919 - SYS___LOG2L_H = 0x920 - SYS___LOG1P_H = 0x921 - SYS___LOG10_H = 0x922 - SYS___LOG10F_H = 0x923 - SYS___LOG10L_H = 0x924 - SYS___LROUND_H = 0x925 - SYS___LROUNDF_H = 0x926 - SYS___NEXTAFTER_H = 0x927 - SYS___POW_H = 0x928 - SYS___POWF_H = 0x929 - SYS___SINL_H = 0x930 - SYS___SINH_H = 0x931 - SYS___SINHF_H = 0x932 - SYS___SINHL_H = 0x933 - SYS___SQRT_H = 0x934 - SYS___SQRTF_H = 0x935 - SYS___SQRTL_H = 0x936 - SYS___TAN_H = 0x937 - SYS___TANF_H = 0x938 - SYS___TANL_H = 0x939 - SYS___TRUNCF_H = 0x940 - SYS___TRUNCL_H = 0x941 - SYS___COSH_H = 0x942 - SYS___LE_DEBUG_SET_RESUME_MCH = 0x943 - SYS_VFSCANF = 0x944 - SYS_VSCANF = 0x946 - SYS_VSSCANF = 0x948 - SYS_IMAXABS = 0x950 - SYS_IMAXDIV = 0x951 - SYS_STRTOIMAX = 0x952 - SYS_STRTOUMAX = 0x953 - SYS_WCSTOIMAX = 0x954 - SYS_WCSTOUMAX = 0x955 - SYS_ATOLL = 0x956 - SYS_STRTOF = 0x957 - SYS_STRTOLD = 0x958 - SYS_WCSTOF = 0x959 - SYS_INET6_RTH_GETADDR = 0x960 - SYS_INET6_OPT_INIT = 0x961 - SYS_INET6_OPT_APPEND = 0x962 - SYS_INET6_OPT_FINISH = 0x963 - SYS_INET6_OPT_SET_VAL = 0x964 - SYS_INET6_OPT_NEXT = 0x965 - SYS_INET6_OPT_FIND = 0x966 - SYS_INET6_OPT_GET_VAL = 0x967 - SYS___POW_I = 0x987 - SYS___POW_I_B = 0x988 - SYS___POW_I_H = 0x989 - SYS___CABS_H = 0x990 - SYS_CABSF = 0x991 - SYS___CABSF_B = 0x992 - SYS___CABSF_H = 0x993 - SYS_CABSL = 0x994 - SYS___CABSL_B = 0x995 - SYS___CABSL_H = 0x996 - SYS_CACOS = 0x997 - SYS___CACOS_B = 0x998 - SYS___CACOS_H = 0x999 + SYS_LOG = 0x17 // 23 + SYS_COSH = 0x18 // 24 + SYS_TANH = 0x19 // 25 + SYS_EXP = 0x1A // 26 + SYS_MODF = 0x1B // 27 + SYS_LOG10 = 0x1C // 28 + SYS_FREXP = 0x1D // 29 + SYS_LDEXP = 0x1E // 30 + SYS_CEIL = 0x1F // 31 + SYS_POW = 0x20 // 32 + SYS_SQRT = 0x21 // 33 + SYS_FLOOR = 0x22 // 34 + SYS_J1 = 0x23 // 35 + SYS_FABS = 0x24 // 36 + SYS_FMOD = 0x25 // 37 + SYS_J0 = 0x26 // 38 + SYS_YN = 0x27 // 39 + SYS_JN = 0x28 // 40 + SYS_Y0 = 0x29 // 41 + SYS_Y1 = 0x2A // 42 + SYS_HYPOT = 0x2B // 43 + SYS_ERF = 0x2C // 44 + SYS_ERFC = 0x2D // 45 + SYS_GAMMA = 0x2E // 46 + SYS_ISALPHA = 0x30 // 48 + SYS_ISALNUM = 0x31 // 49 + SYS_ISLOWER = 0x32 // 50 + SYS_ISCNTRL = 0x33 // 51 + SYS_ISDIGIT = 0x34 // 52 + SYS_ISGRAPH = 0x35 // 53 + SYS_ISUPPER = 0x36 // 54 + SYS_ISPRINT = 0x37 // 55 + SYS_ISPUNCT = 0x38 // 56 + SYS_ISSPACE = 0x39 // 57 + SYS_SETLOCAL = 0x3A // 58 + SYS_SETLOCALE = 0x3A // 58 + SYS_ISXDIGIT = 0x3B // 59 + SYS_TOLOWER = 0x3C // 60 + SYS_TOUPPER = 0x3D // 61 + SYS_ASIN = 0x3E // 62 + SYS_SIN = 0x3F // 63 + SYS_COS = 0x40 // 64 + SYS_TAN = 0x41 // 65 + SYS_SINH = 0x42 // 66 + SYS_ACOS = 0x43 // 67 + SYS_ATAN = 0x44 // 68 + SYS_ATAN2 = 0x45 // 69 + SYS_FTELL = 0x46 // 70 + SYS_FGETPOS = 0x47 // 71 + SYS_FSEEK = 0x48 // 72 + SYS_FSETPOS = 0x49 // 73 + SYS_FERROR = 0x4A // 74 + SYS_REWIND = 0x4B // 75 + SYS_CLEARERR = 0x4C // 76 + SYS_FEOF = 0x4D // 77 + SYS_ATOL = 0x4E // 78 + SYS_PERROR = 0x4F // 79 + SYS_ATOF = 0x50 // 80 + SYS_ATOI = 0x51 // 81 + SYS_RAND = 0x52 // 82 + SYS_STRTOD = 0x53 // 83 + SYS_STRTOL = 0x54 // 84 + SYS_STRTOUL = 0x55 // 85 + SYS_MALLOC = 0x56 // 86 + SYS_SRAND = 0x57 // 87 + SYS_CALLOC = 0x58 // 88 + SYS_FREE = 0x59 // 89 + SYS_EXIT = 0x5A // 90 + SYS_REALLOC = 0x5B // 91 + SYS_ABORT = 0x5C // 92 + SYS___ABORT = 0x5C // 92 + SYS_ATEXIT = 0x5D // 93 + SYS_RAISE = 0x5E // 94 + SYS_SETJMP = 0x5F // 95 + SYS_LONGJMP = 0x60 // 96 + SYS_SIGNAL = 0x61 // 97 + SYS_TMPNAM = 0x62 // 98 + SYS_REMOVE = 0x63 // 99 + SYS_RENAME = 0x64 // 100 + SYS_TMPFILE = 0x65 // 101 + SYS_FREOPEN = 0x66 // 102 + SYS_FCLOSE = 0x67 // 103 + SYS_FFLUSH = 0x68 // 104 + SYS_FOPEN = 0x69 // 105 + SYS_FSCANF = 0x6A // 106 + SYS_SETBUF = 0x6B // 107 + SYS_SETVBUF = 0x6C // 108 + SYS_FPRINTF = 0x6D // 109 + SYS_SSCANF = 0x6E // 110 + SYS_PRINTF = 0x6F // 111 + SYS_SCANF = 0x70 // 112 + SYS_SPRINTF = 0x71 // 113 + SYS_FGETC = 0x72 // 114 + SYS_VFPRINTF = 0x73 // 115 + SYS_VPRINTF = 0x74 // 116 + SYS_VSPRINTF = 0x75 // 117 + SYS_GETC = 0x76 // 118 + SYS_FGETS = 0x77 // 119 + SYS_FPUTC = 0x78 // 120 + SYS_FPUTS = 0x79 // 121 + SYS_PUTCHAR = 0x7A // 122 + SYS_GETCHAR = 0x7B // 123 + SYS_GETS = 0x7C // 124 + SYS_PUTC = 0x7D // 125 + SYS_FWRITE = 0x7E // 126 + SYS_PUTS = 0x7F // 127 + SYS_UNGETC = 0x80 // 128 + SYS_FREAD = 0x81 // 129 + SYS_WCSTOMBS = 0x82 // 130 + SYS_MBTOWC = 0x83 // 131 + SYS_WCTOMB = 0x84 // 132 + SYS_MBSTOWCS = 0x85 // 133 + SYS_WCSCPY = 0x86 // 134 + SYS_WCSCAT = 0x87 // 135 + SYS_WCSCHR = 0x88 // 136 + SYS_WCSCMP = 0x89 // 137 + SYS_WCSNCMP = 0x8A // 138 + SYS_WCSCSPN = 0x8B // 139 + SYS_WCSLEN = 0x8C // 140 + SYS_WCSNCAT = 0x8D // 141 + SYS_WCSSPN = 0x8E // 142 + SYS_WCSNCPY = 0x8F // 143 + SYS_ABS = 0x90 // 144 + SYS_DIV = 0x91 // 145 + SYS_LABS = 0x92 // 146 + SYS_STRNCPY = 0x93 // 147 + SYS_MEMCPY = 0x94 // 148 + SYS_MEMMOVE = 0x95 // 149 + SYS_STRCPY = 0x96 // 150 + SYS_STRCMP = 0x97 // 151 + SYS_STRCAT = 0x98 // 152 + SYS_STRNCAT = 0x99 // 153 + SYS_MEMCMP = 0x9A // 154 + SYS_MEMCHR = 0x9B // 155 + SYS_STRCOLL = 0x9C // 156 + SYS_STRNCMP = 0x9D // 157 + SYS_STRXFRM = 0x9E // 158 + SYS_STRRCHR = 0x9F // 159 + SYS_STRCHR = 0xA0 // 160 + SYS_STRCSPN = 0xA1 // 161 + SYS_STRPBRK = 0xA2 // 162 + SYS_MEMSET = 0xA3 // 163 + SYS_STRSPN = 0xA4 // 164 + SYS_STRSTR = 0xA5 // 165 + SYS_STRTOK = 0xA6 // 166 + SYS_DIFFTIME = 0xA7 // 167 + SYS_STRERROR = 0xA8 // 168 + SYS_STRLEN = 0xA9 // 169 + SYS_CLOCK = 0xAA // 170 + SYS_CTIME = 0xAB // 171 + SYS_MKTIME = 0xAC // 172 + SYS_TIME = 0xAD // 173 + SYS_ASCTIME = 0xAE // 174 + SYS_MBLEN = 0xAF // 175 + SYS_GMTIME = 0xB0 // 176 + SYS_LOCALTIM = 0xB1 // 177 + SYS_LOCALTIME = 0xB1 // 177 + SYS_STRFTIME = 0xB2 // 178 + SYS___GETCB = 0xB4 // 180 + SYS_FUPDATE = 0xB5 // 181 + SYS___FUPDT = 0xB5 // 181 + SYS_CLRMEMF = 0xBD // 189 + SYS___CLRMF = 0xBD // 189 + SYS_FETCHEP = 0xBF // 191 + SYS___FTCHEP = 0xBF // 191 + SYS_FLDATA = 0xC1 // 193 + SYS___FLDATA = 0xC1 // 193 + SYS_DYNFREE = 0xC2 // 194 + SYS___DYNFRE = 0xC2 // 194 + SYS_DYNALLOC = 0xC3 // 195 + SYS___DYNALL = 0xC3 // 195 + SYS___CDUMP = 0xC4 // 196 + SYS_CSNAP = 0xC5 // 197 + SYS___CSNAP = 0xC5 // 197 + SYS_CTRACE = 0xC6 // 198 + SYS___CTRACE = 0xC6 // 198 + SYS___CTEST = 0xC7 // 199 + SYS_SETENV = 0xC8 // 200 + SYS___SETENV = 0xC8 // 200 + SYS_CLEARENV = 0xC9 // 201 + SYS___CLRENV = 0xC9 // 201 + SYS___REGCOMP_STD = 0xEA // 234 + SYS_NL_LANGINFO = 0xFC // 252 + SYS_GETSYNTX = 0xFD // 253 + SYS_ISBLANK = 0xFE // 254 + SYS___ISBLNK = 0xFE // 254 + SYS_ISWALNUM = 0xFF // 255 + SYS_ISWALPHA = 0x100 // 256 + SYS_ISWBLANK = 0x101 // 257 + SYS___ISWBLK = 0x101 // 257 + SYS_ISWCNTRL = 0x102 // 258 + SYS_ISWDIGIT = 0x103 // 259 + SYS_ISWGRAPH = 0x104 // 260 + SYS_ISWLOWER = 0x105 // 261 + SYS_ISWPRINT = 0x106 // 262 + SYS_ISWPUNCT = 0x107 // 263 + SYS_ISWSPACE = 0x108 // 264 + SYS_ISWUPPER = 0x109 // 265 + SYS_ISWXDIGI = 0x10A // 266 + SYS_ISWXDIGIT = 0x10A // 266 + SYS_WCTYPE = 0x10B // 267 + SYS_ISWCTYPE = 0x10C // 268 + SYS_TOWLOWER = 0x10D // 269 + SYS_TOWUPPER = 0x10E // 270 + SYS_MBSINIT = 0x10F // 271 + SYS_WCTOB = 0x110 // 272 + SYS_MBRLEN = 0x111 // 273 + SYS_MBRTOWC = 0x112 // 274 + SYS_MBSRTOWC = 0x113 // 275 + SYS_MBSRTOWCS = 0x113 // 275 + SYS_WCRTOMB = 0x114 // 276 + SYS_WCSRTOMB = 0x115 // 277 + SYS_WCSRTOMBS = 0x115 // 277 + SYS___CSID = 0x116 // 278 + SYS___WCSID = 0x117 // 279 + SYS_STRPTIME = 0x118 // 280 + SYS___STRPTM = 0x118 // 280 + SYS_STRFMON = 0x119 // 281 + SYS___RPMTCH = 0x11A // 282 + SYS_WCSSTR = 0x11B // 283 + SYS_WCSTOK = 0x12C // 300 + SYS_WCSTOL = 0x12D // 301 + SYS_WCSTOD = 0x12E // 302 + SYS_WCSTOUL = 0x12F // 303 + SYS_WCSCOLL = 0x130 // 304 + SYS_WCSXFRM = 0x131 // 305 + SYS_WCSWIDTH = 0x132 // 306 + SYS_WCWIDTH = 0x133 // 307 + SYS_WCSFTIME = 0x134 // 308 + SYS_SWPRINTF = 0x135 // 309 + SYS_VSWPRINT = 0x136 // 310 + SYS_VSWPRINTF = 0x136 // 310 + SYS_SWSCANF = 0x137 // 311 + SYS_REGCOMP = 0x138 // 312 + SYS_REGEXEC = 0x139 // 313 + SYS_REGFREE = 0x13A // 314 + SYS_REGERROR = 0x13B // 315 + SYS_FGETWC = 0x13C // 316 + SYS_FGETWS = 0x13D // 317 + SYS_FPUTWC = 0x13E // 318 + SYS_FPUTWS = 0x13F // 319 + SYS_GETWC = 0x140 // 320 + SYS_GETWCHAR = 0x141 // 321 + SYS_PUTWC = 0x142 // 322 + SYS_PUTWCHAR = 0x143 // 323 + SYS_UNGETWC = 0x144 // 324 + SYS_ICONV_OPEN = 0x145 // 325 + SYS_ICONV = 0x146 // 326 + SYS_ICONV_CLOSE = 0x147 // 327 + SYS_ISMCCOLLEL = 0x14C // 332 + SYS_STRTOCOLL = 0x14D // 333 + SYS_COLLTOSTR = 0x14E // 334 + SYS_COLLEQUIV = 0x14F // 335 + SYS_COLLRANGE = 0x150 // 336 + SYS_CCLASS = 0x151 // 337 + SYS_COLLORDER = 0x152 // 338 + SYS___DEMANGLE = 0x154 // 340 + SYS_FDOPEN = 0x155 // 341 + SYS___ERRNO = 0x156 // 342 + SYS___ERRNO2 = 0x157 // 343 + SYS___TERROR = 0x158 // 344 + SYS_MAXCOLL = 0x169 // 361 + SYS_GETMCCOLL = 0x16A // 362 + SYS_GETWMCCOLL = 0x16B // 363 + SYS___ERR2AD = 0x16C // 364 + SYS_DLLQUERYFN = 0x16D // 365 + SYS_DLLQUERYVAR = 0x16E // 366 + SYS_DLLFREE = 0x16F // 367 + SYS_DLLLOAD = 0x170 // 368 + SYS__EXIT = 0x174 // 372 + SYS_ACCESS = 0x175 // 373 + SYS_ALARM = 0x176 // 374 + SYS_CFGETISPEED = 0x177 // 375 + SYS_CFGETOSPEED = 0x178 // 376 + SYS_CFSETISPEED = 0x179 // 377 + SYS_CFSETOSPEED = 0x17A // 378 + SYS_CHDIR = 0x17B // 379 + SYS_CHMOD = 0x17C // 380 + SYS_CHOWN = 0x17D // 381 + SYS_CLOSE = 0x17E // 382 + SYS_CLOSEDIR = 0x17F // 383 + SYS_CREAT = 0x180 // 384 + SYS_CTERMID = 0x181 // 385 + SYS_DUP = 0x182 // 386 + SYS_DUP2 = 0x183 // 387 + SYS_EXECL = 0x184 // 388 + SYS_EXECLE = 0x185 // 389 + SYS_EXECLP = 0x186 // 390 + SYS_EXECV = 0x187 // 391 + SYS_EXECVE = 0x188 // 392 + SYS_EXECVP = 0x189 // 393 + SYS_FCHMOD = 0x18A // 394 + SYS_FCHOWN = 0x18B // 395 + SYS_FCNTL = 0x18C // 396 + SYS_FILENO = 0x18D // 397 + SYS_FORK = 0x18E // 398 + SYS_FPATHCONF = 0x18F // 399 + SYS_FSTAT = 0x190 // 400 + SYS_FSYNC = 0x191 // 401 + SYS_FTRUNCATE = 0x192 // 402 + SYS_GETCWD = 0x193 // 403 + SYS_GETEGID = 0x194 // 404 + SYS_GETEUID = 0x195 // 405 + SYS_GETGID = 0x196 // 406 + SYS_GETGRGID = 0x197 // 407 + SYS_GETGRNAM = 0x198 // 408 + SYS_GETGROUPS = 0x199 // 409 + SYS_GETLOGIN = 0x19A // 410 + SYS_W_GETMNTENT = 0x19B // 411 + SYS_GETPGRP = 0x19C // 412 + SYS_GETPID = 0x19D // 413 + SYS_GETPPID = 0x19E // 414 + SYS_GETPWNAM = 0x19F // 415 + SYS_GETPWUID = 0x1A0 // 416 + SYS_GETUID = 0x1A1 // 417 + SYS_W_IOCTL = 0x1A2 // 418 + SYS_ISATTY = 0x1A3 // 419 + SYS_KILL = 0x1A4 // 420 + SYS_LINK = 0x1A5 // 421 + SYS_LSEEK = 0x1A6 // 422 + SYS_LSTAT = 0x1A7 // 423 + SYS_MKDIR = 0x1A8 // 424 + SYS_MKFIFO = 0x1A9 // 425 + SYS_MKNOD = 0x1AA // 426 + SYS_MOUNT = 0x1AB // 427 + SYS_OPEN = 0x1AC // 428 + SYS_OPENDIR = 0x1AD // 429 + SYS_PATHCONF = 0x1AE // 430 + SYS_PAUSE = 0x1AF // 431 + SYS_PIPE = 0x1B0 // 432 + SYS_W_GETPSENT = 0x1B1 // 433 + SYS_READ = 0x1B2 // 434 + SYS_READDIR = 0x1B3 // 435 + SYS_READLINK = 0x1B4 // 436 + SYS_REWINDDIR = 0x1B5 // 437 + SYS_RMDIR = 0x1B6 // 438 + SYS_SETEGID = 0x1B7 // 439 + SYS_SETEUID = 0x1B8 // 440 + SYS_SETGID = 0x1B9 // 441 + SYS_SETPGID = 0x1BA // 442 + SYS_SETSID = 0x1BB // 443 + SYS_SETUID = 0x1BC // 444 + SYS_SIGACTION = 0x1BD // 445 + SYS_SIGADDSET = 0x1BE // 446 + SYS_SIGDELSET = 0x1BF // 447 + SYS_SIGEMPTYSET = 0x1C0 // 448 + SYS_SIGFILLSET = 0x1C1 // 449 + SYS_SIGISMEMBER = 0x1C2 // 450 + SYS_SIGLONGJMP = 0x1C3 // 451 + SYS_SIGPENDING = 0x1C4 // 452 + SYS_SIGPROCMASK = 0x1C5 // 453 + SYS_SIGSETJMP = 0x1C6 // 454 + SYS_SIGSUSPEND = 0x1C7 // 455 + SYS_SLEEP = 0x1C8 // 456 + SYS_STAT = 0x1C9 // 457 + SYS_W_STATFS = 0x1CA // 458 + SYS_SYMLINK = 0x1CB // 459 + SYS_SYSCONF = 0x1CC // 460 + SYS_TCDRAIN = 0x1CD // 461 + SYS_TCFLOW = 0x1CE // 462 + SYS_TCFLUSH = 0x1CF // 463 + SYS_TCGETATTR = 0x1D0 // 464 + SYS_TCGETPGRP = 0x1D1 // 465 + SYS_TCSENDBREAK = 0x1D2 // 466 + SYS_TCSETATTR = 0x1D3 // 467 + SYS_TCSETPGRP = 0x1D4 // 468 + SYS_TIMES = 0x1D5 // 469 + SYS_TTYNAME = 0x1D6 // 470 + SYS_TZSET = 0x1D7 // 471 + SYS_UMASK = 0x1D8 // 472 + SYS_UMOUNT = 0x1D9 // 473 + SYS_UNAME = 0x1DA // 474 + SYS_UNLINK = 0x1DB // 475 + SYS_UTIME = 0x1DC // 476 + SYS_WAIT = 0x1DD // 477 + SYS_WAITPID = 0x1DE // 478 + SYS_WRITE = 0x1DF // 479 + SYS_CHAUDIT = 0x1E0 // 480 + SYS_FCHAUDIT = 0x1E1 // 481 + SYS_GETGROUPSBYNAME = 0x1E2 // 482 + SYS_SIGWAIT = 0x1E3 // 483 + SYS_PTHREAD_EXIT = 0x1E4 // 484 + SYS_PTHREAD_KILL = 0x1E5 // 485 + SYS_PTHREAD_ATTR_INIT = 0x1E6 // 486 + SYS_PTHREAD_ATTR_DESTROY = 0x1E7 // 487 + SYS_PTHREAD_ATTR_SETSTACKSIZE = 0x1E8 // 488 + SYS_PTHREAD_ATTR_GETSTACKSIZE = 0x1E9 // 489 + SYS_PTHREAD_ATTR_SETDETACHSTATE = 0x1EA // 490 + SYS_PTHREAD_ATTR_GETDETACHSTATE = 0x1EB // 491 + SYS_PTHREAD_ATTR_SETWEIGHT_NP = 0x1EC // 492 + SYS_PTHREAD_ATTR_GETWEIGHT_NP = 0x1ED // 493 + SYS_PTHREAD_CANCEL = 0x1EE // 494 + SYS_PTHREAD_CLEANUP_PUSH = 0x1EF // 495 + SYS_PTHREAD_CLEANUP_POP = 0x1F0 // 496 + SYS_PTHREAD_CONDATTR_INIT = 0x1F1 // 497 + SYS_PTHREAD_CONDATTR_DESTROY = 0x1F2 // 498 + SYS_PTHREAD_COND_INIT = 0x1F3 // 499 + SYS_PTHREAD_COND_DESTROY = 0x1F4 // 500 + SYS_PTHREAD_COND_SIGNAL = 0x1F5 // 501 + SYS_PTHREAD_COND_BROADCAST = 0x1F6 // 502 + SYS_PTHREAD_COND_WAIT = 0x1F7 // 503 + SYS_PTHREAD_COND_TIMEDWAIT = 0x1F8 // 504 + SYS_PTHREAD_CREATE = 0x1F9 // 505 + SYS_PTHREAD_DETACH = 0x1FA // 506 + SYS_PTHREAD_EQUAL = 0x1FB // 507 + SYS_PTHREAD_GETSPECIFIC = 0x1FC // 508 + SYS_PTHREAD_JOIN = 0x1FD // 509 + SYS_PTHREAD_KEY_CREATE = 0x1FE // 510 + SYS_PTHREAD_MUTEXATTR_INIT = 0x1FF // 511 + SYS_PTHREAD_MUTEXATTR_DESTROY = 0x200 // 512 + SYS_PTHREAD_MUTEXATTR_SETKIND_NP = 0x201 // 513 + SYS_PTHREAD_MUTEXATTR_GETKIND_NP = 0x202 // 514 + SYS_PTHREAD_MUTEX_INIT = 0x203 // 515 + SYS_PTHREAD_MUTEX_DESTROY = 0x204 // 516 + SYS_PTHREAD_MUTEX_LOCK = 0x205 // 517 + SYS_PTHREAD_MUTEX_TRYLOCK = 0x206 // 518 + SYS_PTHREAD_MUTEX_UNLOCK = 0x207 // 519 + SYS_PTHREAD_ONCE = 0x209 // 521 + SYS_PTHREAD_SELF = 0x20A // 522 + SYS_PTHREAD_SETINTR = 0x20B // 523 + SYS_PTHREAD_SETINTRTYPE = 0x20C // 524 + SYS_PTHREAD_SETSPECIFIC = 0x20D // 525 + SYS_PTHREAD_TESTINTR = 0x20E // 526 + SYS_PTHREAD_YIELD = 0x20F // 527 + SYS_TW_OPEN = 0x210 // 528 + SYS_TW_FCNTL = 0x211 // 529 + SYS_PTHREAD_JOIN_D4_NP = 0x212 // 530 + SYS_PTHREAD_CONDATTR_SETKIND_NP = 0x213 // 531 + SYS_PTHREAD_CONDATTR_GETKIND_NP = 0x214 // 532 + SYS_EXTLINK_NP = 0x215 // 533 + SYS___PASSWD = 0x216 // 534 + SYS_SETGROUPS = 0x217 // 535 + SYS_INITGROUPS = 0x218 // 536 + SYS_WCSPBRK = 0x23F // 575 + SYS_WCSRCHR = 0x240 // 576 + SYS_SVC99 = 0x241 // 577 + SYS___SVC99 = 0x241 // 577 + SYS_WCSWCS = 0x242 // 578 + SYS_LOCALECO = 0x243 // 579 + SYS_LOCALECONV = 0x243 // 579 + SYS___LIBREL = 0x244 // 580 + SYS_RELEASE = 0x245 // 581 + SYS___RLSE = 0x245 // 581 + SYS_FLOCATE = 0x246 // 582 + SYS___FLOCT = 0x246 // 582 + SYS_FDELREC = 0x247 // 583 + SYS___FDLREC = 0x247 // 583 + SYS_FETCH = 0x248 // 584 + SYS___FETCH = 0x248 // 584 + SYS_QSORT = 0x249 // 585 + SYS_GETENV = 0x24A // 586 + SYS_SYSTEM = 0x24B // 587 + SYS_BSEARCH = 0x24C // 588 + SYS_LDIV = 0x24D // 589 + SYS___THROW = 0x25E // 606 + SYS___RETHROW = 0x25F // 607 + SYS___CLEANUPCATCH = 0x260 // 608 + SYS___CATCHMATCH = 0x261 // 609 + SYS___CLEAN2UPCATCH = 0x262 // 610 + SYS_PUTENV = 0x26A // 618 + SYS___GETENV = 0x26F // 623 + SYS_GETPRIORITY = 0x270 // 624 + SYS_NICE = 0x271 // 625 + SYS_SETPRIORITY = 0x272 // 626 + SYS_GETITIMER = 0x273 // 627 + SYS_SETITIMER = 0x274 // 628 + SYS_MSGCTL = 0x275 // 629 + SYS_MSGGET = 0x276 // 630 + SYS_MSGRCV = 0x277 // 631 + SYS_MSGSND = 0x278 // 632 + SYS_MSGXRCV = 0x279 // 633 + SYS___MSGXR = 0x279 // 633 + SYS_SEMCTL = 0x27A // 634 + SYS_SEMGET = 0x27B // 635 + SYS_SEMOP = 0x27C // 636 + SYS_SHMAT = 0x27D // 637 + SYS_SHMCTL = 0x27E // 638 + SYS_SHMDT = 0x27F // 639 + SYS_SHMGET = 0x280 // 640 + SYS___GETIPC = 0x281 // 641 + SYS_SETGRENT = 0x282 // 642 + SYS_GETGRENT = 0x283 // 643 + SYS_ENDGRENT = 0x284 // 644 + SYS_SETPWENT = 0x285 // 645 + SYS_GETPWENT = 0x286 // 646 + SYS_ENDPWENT = 0x287 // 647 + SYS_BSD_SIGNAL = 0x288 // 648 + SYS_KILLPG = 0x289 // 649 + SYS_SIGALTSTACK = 0x28A // 650 + SYS_SIGHOLD = 0x28B // 651 + SYS_SIGIGNORE = 0x28C // 652 + SYS_SIGINTERRUPT = 0x28D // 653 + SYS_SIGPAUSE = 0x28E // 654 + SYS_SIGRELSE = 0x28F // 655 + SYS_SIGSET = 0x290 // 656 + SYS_SIGSTACK = 0x291 // 657 + SYS_GETRLIMIT = 0x292 // 658 + SYS_SETRLIMIT = 0x293 // 659 + SYS_GETRUSAGE = 0x294 // 660 + SYS_MMAP = 0x295 // 661 + SYS_MPROTECT = 0x296 // 662 + SYS_MSYNC = 0x297 // 663 + SYS_MUNMAP = 0x298 // 664 + SYS_CONFSTR = 0x299 // 665 + SYS_GETOPT = 0x29A // 666 + SYS_LCHOWN = 0x29B // 667 + SYS_TRUNCATE = 0x29C // 668 + SYS_GETSUBOPT = 0x29D // 669 + SYS_SETPGRP = 0x29E // 670 + SYS___GDERR = 0x29F // 671 + SYS___TZONE = 0x2A0 // 672 + SYS___DLGHT = 0x2A1 // 673 + SYS___OPARGF = 0x2A2 // 674 + SYS___OPOPTF = 0x2A3 // 675 + SYS___OPINDF = 0x2A4 // 676 + SYS___OPERRF = 0x2A5 // 677 + SYS_GETDATE = 0x2A6 // 678 + SYS_WAIT3 = 0x2A7 // 679 + SYS_WAITID = 0x2A8 // 680 + SYS___CATTRM = 0x2A9 // 681 + SYS___GDTRM = 0x2AA // 682 + SYS___RNDTRM = 0x2AB // 683 + SYS_CRYPT = 0x2AC // 684 + SYS_ENCRYPT = 0x2AD // 685 + SYS_SETKEY = 0x2AE // 686 + SYS___CNVBLK = 0x2AF // 687 + SYS___CRYTRM = 0x2B0 // 688 + SYS___ECRTRM = 0x2B1 // 689 + SYS_DRAND48 = 0x2B2 // 690 + SYS_ERAND48 = 0x2B3 // 691 + SYS_FSTATVFS = 0x2B4 // 692 + SYS_STATVFS = 0x2B5 // 693 + SYS_CATCLOSE = 0x2B6 // 694 + SYS_CATGETS = 0x2B7 // 695 + SYS_CATOPEN = 0x2B8 // 696 + SYS_BCMP = 0x2B9 // 697 + SYS_BCOPY = 0x2BA // 698 + SYS_BZERO = 0x2BB // 699 + SYS_FFS = 0x2BC // 700 + SYS_INDEX = 0x2BD // 701 + SYS_RINDEX = 0x2BE // 702 + SYS_STRCASECMP = 0x2BF // 703 + SYS_STRDUP = 0x2C0 // 704 + SYS_STRNCASECMP = 0x2C1 // 705 + SYS_INITSTATE = 0x2C2 // 706 + SYS_SETSTATE = 0x2C3 // 707 + SYS_RANDOM = 0x2C4 // 708 + SYS_SRANDOM = 0x2C5 // 709 + SYS_HCREATE = 0x2C6 // 710 + SYS_HDESTROY = 0x2C7 // 711 + SYS_HSEARCH = 0x2C8 // 712 + SYS_LFIND = 0x2C9 // 713 + SYS_LSEARCH = 0x2CA // 714 + SYS_TDELETE = 0x2CB // 715 + SYS_TFIND = 0x2CC // 716 + SYS_TSEARCH = 0x2CD // 717 + SYS_TWALK = 0x2CE // 718 + SYS_INSQUE = 0x2CF // 719 + SYS_REMQUE = 0x2D0 // 720 + SYS_POPEN = 0x2D1 // 721 + SYS_PCLOSE = 0x2D2 // 722 + SYS_SWAB = 0x2D3 // 723 + SYS_MEMCCPY = 0x2D4 // 724 + SYS_GETPAGESIZE = 0x2D8 // 728 + SYS_FCHDIR = 0x2D9 // 729 + SYS___OCLCK = 0x2DA // 730 + SYS___ATOE = 0x2DB // 731 + SYS___ATOE_L = 0x2DC // 732 + SYS___ETOA = 0x2DD // 733 + SYS___ETOA_L = 0x2DE // 734 + SYS_SETUTXENT = 0x2DF // 735 + SYS_GETUTXENT = 0x2E0 // 736 + SYS_ENDUTXENT = 0x2E1 // 737 + SYS_GETUTXID = 0x2E2 // 738 + SYS_GETUTXLINE = 0x2E3 // 739 + SYS_PUTUTXLINE = 0x2E4 // 740 + SYS_FMTMSG = 0x2E5 // 741 + SYS_JRAND48 = 0x2E6 // 742 + SYS_LRAND48 = 0x2E7 // 743 + SYS_MRAND48 = 0x2E8 // 744 + SYS_NRAND48 = 0x2E9 // 745 + SYS_LCONG48 = 0x2EA // 746 + SYS_SRAND48 = 0x2EB // 747 + SYS_SEED48 = 0x2EC // 748 + SYS_ISASCII = 0x2ED // 749 + SYS_TOASCII = 0x2EE // 750 + SYS_A64L = 0x2EF // 751 + SYS_L64A = 0x2F0 // 752 + SYS_UALARM = 0x2F1 // 753 + SYS_USLEEP = 0x2F2 // 754 + SYS___UTXTRM = 0x2F3 // 755 + SYS___SRCTRM = 0x2F4 // 756 + SYS_FTIME = 0x2F5 // 757 + SYS_GETTIMEOFDAY = 0x2F6 // 758 + SYS_DBM_CLEARERR = 0x2F7 // 759 + SYS_DBM_CLOSE = 0x2F8 // 760 + SYS_DBM_DELETE = 0x2F9 // 761 + SYS_DBM_ERROR = 0x2FA // 762 + SYS_DBM_FETCH = 0x2FB // 763 + SYS_DBM_FIRSTKEY = 0x2FC // 764 + SYS_DBM_NEXTKEY = 0x2FD // 765 + SYS_DBM_OPEN = 0x2FE // 766 + SYS_DBM_STORE = 0x2FF // 767 + SYS___NDMTRM = 0x300 // 768 + SYS_FTOK = 0x301 // 769 + SYS_BASENAME = 0x302 // 770 + SYS_DIRNAME = 0x303 // 771 + SYS_GETDTABLESIZE = 0x304 // 772 + SYS_MKSTEMP = 0x305 // 773 + SYS_MKTEMP = 0x306 // 774 + SYS_NFTW = 0x307 // 775 + SYS_GETWD = 0x308 // 776 + SYS_LOCKF = 0x309 // 777 + SYS__LONGJMP = 0x30D // 781 + SYS__SETJMP = 0x30E // 782 + SYS_VFORK = 0x30F // 783 + SYS_WORDEXP = 0x310 // 784 + SYS_WORDFREE = 0x311 // 785 + SYS_GETPGID = 0x312 // 786 + SYS_GETSID = 0x313 // 787 + SYS___UTMPXNAME = 0x314 // 788 + SYS_CUSERID = 0x315 // 789 + SYS_GETPASS = 0x316 // 790 + SYS_FNMATCH = 0x317 // 791 + SYS_FTW = 0x318 // 792 + SYS_GETW = 0x319 // 793 + SYS_GLOB = 0x31A // 794 + SYS_GLOBFREE = 0x31B // 795 + SYS_PUTW = 0x31C // 796 + SYS_SEEKDIR = 0x31D // 797 + SYS_TELLDIR = 0x31E // 798 + SYS_TEMPNAM = 0x31F // 799 + SYS_ACOSH = 0x320 // 800 + SYS_ASINH = 0x321 // 801 + SYS_ATANH = 0x322 // 802 + SYS_CBRT = 0x323 // 803 + SYS_EXPM1 = 0x324 // 804 + SYS_ILOGB = 0x325 // 805 + SYS_LOGB = 0x326 // 806 + SYS_LOG1P = 0x327 // 807 + SYS_NEXTAFTER = 0x328 // 808 + SYS_RINT = 0x329 // 809 + SYS_REMAINDER = 0x32A // 810 + SYS_SCALB = 0x32B // 811 + SYS_LGAMMA = 0x32C // 812 + SYS_TTYSLOT = 0x32D // 813 + SYS_GETTIMEOFDAY_R = 0x32E // 814 + SYS_SYNC = 0x32F // 815 + SYS_SPAWN = 0x330 // 816 + SYS_SPAWNP = 0x331 // 817 + SYS_GETLOGIN_UU = 0x332 // 818 + SYS_ECVT = 0x333 // 819 + SYS_FCVT = 0x334 // 820 + SYS_GCVT = 0x335 // 821 + SYS_ACCEPT = 0x336 // 822 + SYS_BIND = 0x337 // 823 + SYS_CONNECT = 0x338 // 824 + SYS_ENDHOSTENT = 0x339 // 825 + SYS_ENDPROTOENT = 0x33A // 826 + SYS_ENDSERVENT = 0x33B // 827 + SYS_GETHOSTBYADDR_R = 0x33C // 828 + SYS_GETHOSTBYADDR = 0x33D // 829 + SYS_GETHOSTBYNAME_R = 0x33E // 830 + SYS_GETHOSTBYNAME = 0x33F // 831 + SYS_GETHOSTENT = 0x340 // 832 + SYS_GETHOSTID = 0x341 // 833 + SYS_GETHOSTNAME = 0x342 // 834 + SYS_GETNETBYADDR = 0x343 // 835 + SYS_GETNETBYNAME = 0x344 // 836 + SYS_GETNETENT = 0x345 // 837 + SYS_GETPEERNAME = 0x346 // 838 + SYS_GETPROTOBYNAME = 0x347 // 839 + SYS_GETPROTOBYNUMBER = 0x348 // 840 + SYS_GETPROTOENT = 0x349 // 841 + SYS_GETSERVBYNAME = 0x34A // 842 + SYS_GETSERVBYPORT = 0x34B // 843 + SYS_GETSERVENT = 0x34C // 844 + SYS_GETSOCKNAME = 0x34D // 845 + SYS_GETSOCKOPT = 0x34E // 846 + SYS_INET_ADDR = 0x34F // 847 + SYS_INET_LNAOF = 0x350 // 848 + SYS_INET_MAKEADDR = 0x351 // 849 + SYS_INET_NETOF = 0x352 // 850 + SYS_INET_NETWORK = 0x353 // 851 + SYS_INET_NTOA = 0x354 // 852 + SYS_IOCTL = 0x355 // 853 + SYS_LISTEN = 0x356 // 854 + SYS_READV = 0x357 // 855 + SYS_RECV = 0x358 // 856 + SYS_RECVFROM = 0x359 // 857 + SYS_SELECT = 0x35B // 859 + SYS_SELECTEX = 0x35C // 860 + SYS_SEND = 0x35D // 861 + SYS_SENDTO = 0x35F // 863 + SYS_SETHOSTENT = 0x360 // 864 + SYS_SETNETENT = 0x361 // 865 + SYS_SETPEER = 0x362 // 866 + SYS_SETPROTOENT = 0x363 // 867 + SYS_SETSERVENT = 0x364 // 868 + SYS_SETSOCKOPT = 0x365 // 869 + SYS_SHUTDOWN = 0x366 // 870 + SYS_SOCKET = 0x367 // 871 + SYS_SOCKETPAIR = 0x368 // 872 + SYS_WRITEV = 0x369 // 873 + SYS_CHROOT = 0x36A // 874 + SYS_W_STATVFS = 0x36B // 875 + SYS_ULIMIT = 0x36C // 876 + SYS_ISNAN = 0x36D // 877 + SYS_UTIMES = 0x36E // 878 + SYS___H_ERRNO = 0x36F // 879 + SYS_ENDNETENT = 0x370 // 880 + SYS_CLOSELOG = 0x371 // 881 + SYS_OPENLOG = 0x372 // 882 + SYS_SETLOGMASK = 0x373 // 883 + SYS_SYSLOG = 0x374 // 884 + SYS_PTSNAME = 0x375 // 885 + SYS_SETREUID = 0x376 // 886 + SYS_SETREGID = 0x377 // 887 + SYS_REALPATH = 0x378 // 888 + SYS___SIGNGAM = 0x379 // 889 + SYS_GRANTPT = 0x37A // 890 + SYS_UNLOCKPT = 0x37B // 891 + SYS_TCGETSID = 0x37C // 892 + SYS___TCGETCP = 0x37D // 893 + SYS___TCSETCP = 0x37E // 894 + SYS___TCSETTABLES = 0x37F // 895 + SYS_POLL = 0x380 // 896 + SYS_REXEC = 0x381 // 897 + SYS___ISASCII2 = 0x382 // 898 + SYS___TOASCII2 = 0x383 // 899 + SYS_CHPRIORITY = 0x384 // 900 + SYS_PTHREAD_ATTR_SETSYNCTYPE_NP = 0x385 // 901 + SYS_PTHREAD_ATTR_GETSYNCTYPE_NP = 0x386 // 902 + SYS_PTHREAD_SET_LIMIT_NP = 0x387 // 903 + SYS___STNETENT = 0x388 // 904 + SYS___STPROTOENT = 0x389 // 905 + SYS___STSERVENT = 0x38A // 906 + SYS___STHOSTENT = 0x38B // 907 + SYS_NLIST = 0x38C // 908 + SYS___IPDBCS = 0x38D // 909 + SYS___IPDSPX = 0x38E // 910 + SYS___IPMSGC = 0x38F // 911 + SYS___SELECT1 = 0x390 // 912 + SYS_PTHREAD_SECURITY_NP = 0x391 // 913 + SYS___CHECK_RESOURCE_AUTH_NP = 0x392 // 914 + SYS___CONVERT_ID_NP = 0x393 // 915 + SYS___OPENVMREL = 0x394 // 916 + SYS_WMEMCHR = 0x395 // 917 + SYS_WMEMCMP = 0x396 // 918 + SYS_WMEMCPY = 0x397 // 919 + SYS_WMEMMOVE = 0x398 // 920 + SYS_WMEMSET = 0x399 // 921 + SYS___FPUTWC = 0x400 // 1024 + SYS___PUTWC = 0x401 // 1025 + SYS___PWCHAR = 0x402 // 1026 + SYS___WCSFTM = 0x403 // 1027 + SYS___WCSTOK = 0x404 // 1028 + SYS___WCWDTH = 0x405 // 1029 + SYS_T_ACCEPT = 0x409 // 1033 + SYS_T_ALLOC = 0x40A // 1034 + SYS_T_BIND = 0x40B // 1035 + SYS_T_CLOSE = 0x40C // 1036 + SYS_T_CONNECT = 0x40D // 1037 + SYS_T_ERROR = 0x40E // 1038 + SYS_T_FREE = 0x40F // 1039 + SYS_T_GETINFO = 0x410 // 1040 + SYS_T_GETPROTADDR = 0x411 // 1041 + SYS_T_GETSTATE = 0x412 // 1042 + SYS_T_LISTEN = 0x413 // 1043 + SYS_T_LOOK = 0x414 // 1044 + SYS_T_OPEN = 0x415 // 1045 + SYS_T_OPTMGMT = 0x416 // 1046 + SYS_T_RCV = 0x417 // 1047 + SYS_T_RCVCONNECT = 0x418 // 1048 + SYS_T_RCVDIS = 0x419 // 1049 + SYS_T_RCVREL = 0x41A // 1050 + SYS_T_RCVUDATA = 0x41B // 1051 + SYS_T_RCVUDERR = 0x41C // 1052 + SYS_T_SND = 0x41D // 1053 + SYS_T_SNDDIS = 0x41E // 1054 + SYS_T_SNDREL = 0x41F // 1055 + SYS_T_SNDUDATA = 0x420 // 1056 + SYS_T_STRERROR = 0x421 // 1057 + SYS_T_SYNC = 0x422 // 1058 + SYS_T_UNBIND = 0x423 // 1059 + SYS___T_ERRNO = 0x424 // 1060 + SYS___RECVMSG2 = 0x425 // 1061 + SYS___SENDMSG2 = 0x426 // 1062 + SYS_FATTACH = 0x427 // 1063 + SYS_FDETACH = 0x428 // 1064 + SYS_GETMSG = 0x429 // 1065 + SYS_GETPMSG = 0x42A // 1066 + SYS_ISASTREAM = 0x42B // 1067 + SYS_PUTMSG = 0x42C // 1068 + SYS_PUTPMSG = 0x42D // 1069 + SYS___ISPOSIXON = 0x42E // 1070 + SYS___OPENMVSREL = 0x42F // 1071 + SYS_GETCONTEXT = 0x430 // 1072 + SYS_SETCONTEXT = 0x431 // 1073 + SYS_MAKECONTEXT = 0x432 // 1074 + SYS_SWAPCONTEXT = 0x433 // 1075 + SYS_PTHREAD_GETSPECIFIC_D8_NP = 0x434 // 1076 + SYS_GETCLIENTID = 0x470 // 1136 + SYS___GETCLIENTID = 0x471 // 1137 + SYS_GETSTABLESIZE = 0x472 // 1138 + SYS_GETIBMOPT = 0x473 // 1139 + SYS_GETIBMSOCKOPT = 0x474 // 1140 + SYS_GIVESOCKET = 0x475 // 1141 + SYS_IBMSFLUSH = 0x476 // 1142 + SYS_MAXDESC = 0x477 // 1143 + SYS_SETIBMOPT = 0x478 // 1144 + SYS_SETIBMSOCKOPT = 0x479 // 1145 + SYS_SOCK_DEBUG = 0x47A // 1146 + SYS_SOCK_DO_TESTSTOR = 0x47D // 1149 + SYS_TAKESOCKET = 0x47E // 1150 + SYS___SERVER_INIT = 0x47F // 1151 + SYS___SERVER_PWU = 0x480 // 1152 + SYS_PTHREAD_TAG_NP = 0x481 // 1153 + SYS___CONSOLE = 0x482 // 1154 + SYS___WSINIT = 0x483 // 1155 + SYS___IPTCPN = 0x489 // 1161 + SYS___SMF_RECORD = 0x48A // 1162 + SYS___IPHOST = 0x48B // 1163 + SYS___IPNODE = 0x48C // 1164 + SYS___SERVER_CLASSIFY_CREATE = 0x48D // 1165 + SYS___SERVER_CLASSIFY_DESTROY = 0x48E // 1166 + SYS___SERVER_CLASSIFY_RESET = 0x48F // 1167 + SYS___SERVER_CLASSIFY = 0x490 // 1168 + SYS___HEAPRPT = 0x496 // 1174 + SYS___FNWSA = 0x49B // 1179 + SYS___SPAWN2 = 0x49D // 1181 + SYS___SPAWNP2 = 0x49E // 1182 + SYS___GDRR = 0x4A1 // 1185 + SYS___HRRNO = 0x4A2 // 1186 + SYS___OPRG = 0x4A3 // 1187 + SYS___OPRR = 0x4A4 // 1188 + SYS___OPND = 0x4A5 // 1189 + SYS___OPPT = 0x4A6 // 1190 + SYS___SIGGM = 0x4A7 // 1191 + SYS___DGHT = 0x4A8 // 1192 + SYS___TZNE = 0x4A9 // 1193 + SYS___TZZN = 0x4AA // 1194 + SYS___TRRNO = 0x4AF // 1199 + SYS___ENVN = 0x4B0 // 1200 + SYS___MLOCKALL = 0x4B1 // 1201 + SYS_CREATEWO = 0x4B2 // 1202 + SYS_CREATEWORKUNIT = 0x4B2 // 1202 + SYS_CONTINUE = 0x4B3 // 1203 + SYS_CONTINUEWORKUNIT = 0x4B3 // 1203 + SYS_CONNECTW = 0x4B4 // 1204 + SYS_CONNECTWORKMGR = 0x4B4 // 1204 + SYS_CONNECTS = 0x4B5 // 1205 + SYS_CONNECTSERVER = 0x4B5 // 1205 + SYS_DISCONNE = 0x4B6 // 1206 + SYS_DISCONNECTSERVER = 0x4B6 // 1206 + SYS_JOINWORK = 0x4B7 // 1207 + SYS_JOINWORKUNIT = 0x4B7 // 1207 + SYS_LEAVEWOR = 0x4B8 // 1208 + SYS_LEAVEWORKUNIT = 0x4B8 // 1208 + SYS_DELETEWO = 0x4B9 // 1209 + SYS_DELETEWORKUNIT = 0x4B9 // 1209 + SYS_QUERYMET = 0x4BA // 1210 + SYS_QUERYMETRICS = 0x4BA // 1210 + SYS_QUERYSCH = 0x4BB // 1211 + SYS_QUERYSCHENV = 0x4BB // 1211 + SYS_CHECKSCH = 0x4BC // 1212 + SYS_CHECKSCHENV = 0x4BC // 1212 + SYS___PID_AFFINITY = 0x4BD // 1213 + SYS___ASINH_B = 0x4BE // 1214 + SYS___ATAN_B = 0x4BF // 1215 + SYS___CBRT_B = 0x4C0 // 1216 + SYS___CEIL_B = 0x4C1 // 1217 + SYS_COPYSIGN = 0x4C2 // 1218 + SYS___COS_B = 0x4C3 // 1219 + SYS___ERF_B = 0x4C4 // 1220 + SYS___ERFC_B = 0x4C5 // 1221 + SYS___EXPM1_B = 0x4C6 // 1222 + SYS___FABS_B = 0x4C7 // 1223 + SYS_FINITE = 0x4C8 // 1224 + SYS___FLOOR_B = 0x4C9 // 1225 + SYS___FREXP_B = 0x4CA // 1226 + SYS___ILOGB_B = 0x4CB // 1227 + SYS___ISNAN_B = 0x4CC // 1228 + SYS___LDEXP_B = 0x4CD // 1229 + SYS___LOG1P_B = 0x4CE // 1230 + SYS___LOGB_B = 0x4CF // 1231 + SYS_MATHERR = 0x4D0 // 1232 + SYS___MODF_B = 0x4D1 // 1233 + SYS___NEXTAFTER_B = 0x4D2 // 1234 + SYS___RINT_B = 0x4D3 // 1235 + SYS_SCALBN = 0x4D4 // 1236 + SYS_SIGNIFIC = 0x4D5 // 1237 + SYS_SIGNIFICAND = 0x4D5 // 1237 + SYS___SIN_B = 0x4D6 // 1238 + SYS___TAN_B = 0x4D7 // 1239 + SYS___TANH_B = 0x4D8 // 1240 + SYS___ACOS_B = 0x4D9 // 1241 + SYS___ACOSH_B = 0x4DA // 1242 + SYS___ASIN_B = 0x4DB // 1243 + SYS___ATAN2_B = 0x4DC // 1244 + SYS___ATANH_B = 0x4DD // 1245 + SYS___COSH_B = 0x4DE // 1246 + SYS___EXP_B = 0x4DF // 1247 + SYS___FMOD_B = 0x4E0 // 1248 + SYS___GAMMA_B = 0x4E1 // 1249 + SYS_GAMMA_R = 0x4E2 // 1250 + SYS___HYPOT_B = 0x4E3 // 1251 + SYS___J0_B = 0x4E4 // 1252 + SYS___Y0_B = 0x4E5 // 1253 + SYS___J1_B = 0x4E6 // 1254 + SYS___Y1_B = 0x4E7 // 1255 + SYS___JN_B = 0x4E8 // 1256 + SYS___YN_B = 0x4E9 // 1257 + SYS___LGAMMA_B = 0x4EA // 1258 + SYS_LGAMMA_R = 0x4EB // 1259 + SYS___LOG_B = 0x4EC // 1260 + SYS___LOG10_B = 0x4ED // 1261 + SYS___POW_B = 0x4EE // 1262 + SYS___REMAINDER_B = 0x4EF // 1263 + SYS___SCALB_B = 0x4F0 // 1264 + SYS___SINH_B = 0x4F1 // 1265 + SYS___SQRT_B = 0x4F2 // 1266 + SYS___OPENDIR2 = 0x4F3 // 1267 + SYS___READDIR2 = 0x4F4 // 1268 + SYS___LOGIN = 0x4F5 // 1269 + SYS___OPEN_STAT = 0x4F6 // 1270 + SYS_ACCEPT_AND_RECV = 0x4F7 // 1271 + SYS___FP_SETMODE = 0x4F8 // 1272 + SYS___SIGACTIONSET = 0x4FB // 1275 + SYS___UCREATE = 0x4FC // 1276 + SYS___UMALLOC = 0x4FD // 1277 + SYS___UFREE = 0x4FE // 1278 + SYS___UHEAPREPORT = 0x4FF // 1279 + SYS___ISBFP = 0x500 // 1280 + SYS___FP_CAST = 0x501 // 1281 + SYS___CERTIFICATE = 0x502 // 1282 + SYS_SEND_FILE = 0x503 // 1283 + SYS_AIO_CANCEL = 0x504 // 1284 + SYS_AIO_ERROR = 0x505 // 1285 + SYS_AIO_READ = 0x506 // 1286 + SYS_AIO_RETURN = 0x507 // 1287 + SYS_AIO_SUSPEND = 0x508 // 1288 + SYS_AIO_WRITE = 0x509 // 1289 + SYS_PTHREAD_MUTEXATTR_GETPSHARED = 0x50A // 1290 + SYS_PTHREAD_MUTEXATTR_SETPSHARED = 0x50B // 1291 + SYS_PTHREAD_RWLOCK_DESTROY = 0x50C // 1292 + SYS_PTHREAD_RWLOCK_INIT = 0x50D // 1293 + SYS_PTHREAD_RWLOCK_RDLOCK = 0x50E // 1294 + SYS_PTHREAD_RWLOCK_TRYRDLOCK = 0x50F // 1295 + SYS_PTHREAD_RWLOCK_TRYWRLOCK = 0x510 // 1296 + SYS_PTHREAD_RWLOCK_UNLOCK = 0x511 // 1297 + SYS_PTHREAD_RWLOCK_WRLOCK = 0x512 // 1298 + SYS_PTHREAD_RWLOCKATTR_GETPSHARED = 0x513 // 1299 + SYS_PTHREAD_RWLOCKATTR_SETPSHARED = 0x514 // 1300 + SYS_PTHREAD_RWLOCKATTR_INIT = 0x515 // 1301 + SYS_PTHREAD_RWLOCKATTR_DESTROY = 0x516 // 1302 + SYS___CTTBL = 0x517 // 1303 + SYS_PTHREAD_MUTEXATTR_SETTYPE = 0x518 // 1304 + SYS_PTHREAD_MUTEXATTR_GETTYPE = 0x519 // 1305 + SYS___FP_CLR_FLAG = 0x51A // 1306 + SYS___FP_READ_FLAG = 0x51B // 1307 + SYS___FP_RAISE_XCP = 0x51C // 1308 + SYS___FP_CLASS = 0x51D // 1309 + SYS___FP_FINITE = 0x51E // 1310 + SYS___FP_ISNAN = 0x51F // 1311 + SYS___FP_UNORDERED = 0x520 // 1312 + SYS___FP_READ_RND = 0x521 // 1313 + SYS___FP_READ_RND_B = 0x522 // 1314 + SYS___FP_SWAP_RND = 0x523 // 1315 + SYS___FP_SWAP_RND_B = 0x524 // 1316 + SYS___FP_LEVEL = 0x525 // 1317 + SYS___FP_BTOH = 0x526 // 1318 + SYS___FP_HTOB = 0x527 // 1319 + SYS___FPC_RD = 0x528 // 1320 + SYS___FPC_WR = 0x529 // 1321 + SYS___FPC_RW = 0x52A // 1322 + SYS___FPC_SM = 0x52B // 1323 + SYS___FPC_RS = 0x52C // 1324 + SYS_SIGTIMEDWAIT = 0x52D // 1325 + SYS_SIGWAITINFO = 0x52E // 1326 + SYS___CHKBFP = 0x52F // 1327 + SYS___W_PIOCTL = 0x59E // 1438 + SYS___OSENV = 0x59F // 1439 + SYS_EXPORTWO = 0x5A1 // 1441 + SYS_EXPORTWORKUNIT = 0x5A1 // 1441 + SYS_UNDOEXPO = 0x5A2 // 1442 + SYS_UNDOEXPORTWORKUNIT = 0x5A2 // 1442 + SYS_IMPORTWO = 0x5A3 // 1443 + SYS_IMPORTWORKUNIT = 0x5A3 // 1443 + SYS_UNDOIMPO = 0x5A4 // 1444 + SYS_UNDOIMPORTWORKUNIT = 0x5A4 // 1444 + SYS_EXTRACTW = 0x5A5 // 1445 + SYS_EXTRACTWORKUNIT = 0x5A5 // 1445 + SYS___CPL = 0x5A6 // 1446 + SYS___MAP_INIT = 0x5A7 // 1447 + SYS___MAP_SERVICE = 0x5A8 // 1448 + SYS_SIGQUEUE = 0x5A9 // 1449 + SYS___MOUNT = 0x5AA // 1450 + SYS___GETUSERID = 0x5AB // 1451 + SYS___IPDOMAINNAME = 0x5AC // 1452 + SYS_QUERYENC = 0x5AD // 1453 + SYS_QUERYWORKUNITCLASSIFICATION = 0x5AD // 1453 + SYS_CONNECTE = 0x5AE // 1454 + SYS_CONNECTEXPORTIMPORT = 0x5AE // 1454 + SYS___FP_SWAPMODE = 0x5AF // 1455 + SYS_STRTOLL = 0x5B0 // 1456 + SYS_STRTOULL = 0x5B1 // 1457 + SYS___DSA_PREV = 0x5B2 // 1458 + SYS___EP_FIND = 0x5B3 // 1459 + SYS___SERVER_THREADS_QUERY = 0x5B4 // 1460 + SYS___MSGRCV_TIMED = 0x5B7 // 1463 + SYS___SEMOP_TIMED = 0x5B8 // 1464 + SYS___GET_CPUID = 0x5B9 // 1465 + SYS___GET_SYSTEM_SETTINGS = 0x5BA // 1466 + SYS_FTELLO = 0x5C8 // 1480 + SYS_FSEEKO = 0x5C9 // 1481 + SYS_LLDIV = 0x5CB // 1483 + SYS_WCSTOLL = 0x5CC // 1484 + SYS_WCSTOULL = 0x5CD // 1485 + SYS_LLABS = 0x5CE // 1486 + SYS___CONSOLE2 = 0x5D2 // 1490 + SYS_INET_NTOP = 0x5D3 // 1491 + SYS_INET_PTON = 0x5D4 // 1492 + SYS___RES = 0x5D6 // 1494 + SYS_RES_MKQUERY = 0x5D7 // 1495 + SYS_RES_INIT = 0x5D8 // 1496 + SYS_RES_QUERY = 0x5D9 // 1497 + SYS_RES_SEARCH = 0x5DA // 1498 + SYS_RES_SEND = 0x5DB // 1499 + SYS_RES_QUERYDOMAIN = 0x5DC // 1500 + SYS_DN_EXPAND = 0x5DD // 1501 + SYS_DN_SKIPNAME = 0x5DE // 1502 + SYS_DN_COMP = 0x5DF // 1503 + SYS_ASCTIME_R = 0x5E0 // 1504 + SYS_CTIME_R = 0x5E1 // 1505 + SYS_GMTIME_R = 0x5E2 // 1506 + SYS_LOCALTIME_R = 0x5E3 // 1507 + SYS_RAND_R = 0x5E4 // 1508 + SYS_STRTOK_R = 0x5E5 // 1509 + SYS_READDIR_R = 0x5E6 // 1510 + SYS_GETGRGID_R = 0x5E7 // 1511 + SYS_GETGRNAM_R = 0x5E8 // 1512 + SYS_GETLOGIN_R = 0x5E9 // 1513 + SYS_GETPWNAM_R = 0x5EA // 1514 + SYS_GETPWUID_R = 0x5EB // 1515 + SYS_TTYNAME_R = 0x5EC // 1516 + SYS_PTHREAD_ATFORK = 0x5ED // 1517 + SYS_PTHREAD_ATTR_GETGUARDSIZE = 0x5EE // 1518 + SYS_PTHREAD_ATTR_GETSTACKADDR = 0x5EF // 1519 + SYS_PTHREAD_ATTR_SETGUARDSIZE = 0x5F0 // 1520 + SYS_PTHREAD_ATTR_SETSTACKADDR = 0x5F1 // 1521 + SYS_PTHREAD_CONDATTR_GETPSHARED = 0x5F2 // 1522 + SYS_PTHREAD_CONDATTR_SETPSHARED = 0x5F3 // 1523 + SYS_PTHREAD_GETCONCURRENCY = 0x5F4 // 1524 + SYS_PTHREAD_KEY_DELETE = 0x5F5 // 1525 + SYS_PTHREAD_SETCONCURRENCY = 0x5F6 // 1526 + SYS_PTHREAD_SIGMASK = 0x5F7 // 1527 + SYS___DISCARDDATA = 0x5F8 // 1528 + SYS_PTHREAD_ATTR_GETSCHEDPARAM = 0x5F9 // 1529 + SYS_PTHREAD_ATTR_SETSCHEDPARAM = 0x5FA // 1530 + SYS_PTHREAD_ATTR_GETDETACHSTATE_U98 = 0x5FB // 1531 + SYS_PTHREAD_ATTR_SETDETACHSTATE_U98 = 0x5FC // 1532 + SYS_PTHREAD_DETACH_U98 = 0x5FD // 1533 + SYS_PTHREAD_GETSPECIFIC_U98 = 0x5FE // 1534 + SYS_PTHREAD_SETCANCELSTATE = 0x5FF // 1535 + SYS_PTHREAD_SETCANCELTYPE = 0x600 // 1536 + SYS_PTHREAD_TESTCANCEL = 0x601 // 1537 + SYS___ATANF_B = 0x602 // 1538 + SYS___ATANL_B = 0x603 // 1539 + SYS___CEILF_B = 0x604 // 1540 + SYS___CEILL_B = 0x605 // 1541 + SYS___COSF_B = 0x606 // 1542 + SYS___COSL_B = 0x607 // 1543 + SYS___FABSF_B = 0x608 // 1544 + SYS___FABSL_B = 0x609 // 1545 + SYS___FLOORF_B = 0x60A // 1546 + SYS___FLOORL_B = 0x60B // 1547 + SYS___FREXPF_B = 0x60C // 1548 + SYS___FREXPL_B = 0x60D // 1549 + SYS___LDEXPF_B = 0x60E // 1550 + SYS___LDEXPL_B = 0x60F // 1551 + SYS___SINF_B = 0x610 // 1552 + SYS___SINL_B = 0x611 // 1553 + SYS___TANF_B = 0x612 // 1554 + SYS___TANL_B = 0x613 // 1555 + SYS___TANHF_B = 0x614 // 1556 + SYS___TANHL_B = 0x615 // 1557 + SYS___ACOSF_B = 0x616 // 1558 + SYS___ACOSL_B = 0x617 // 1559 + SYS___ASINF_B = 0x618 // 1560 + SYS___ASINL_B = 0x619 // 1561 + SYS___ATAN2F_B = 0x61A // 1562 + SYS___ATAN2L_B = 0x61B // 1563 + SYS___COSHF_B = 0x61C // 1564 + SYS___COSHL_B = 0x61D // 1565 + SYS___EXPF_B = 0x61E // 1566 + SYS___EXPL_B = 0x61F // 1567 + SYS___LOGF_B = 0x620 // 1568 + SYS___LOGL_B = 0x621 // 1569 + SYS___LOG10F_B = 0x622 // 1570 + SYS___LOG10L_B = 0x623 // 1571 + SYS___POWF_B = 0x624 // 1572 + SYS___POWL_B = 0x625 // 1573 + SYS___SINHF_B = 0x626 // 1574 + SYS___SINHL_B = 0x627 // 1575 + SYS___SQRTF_B = 0x628 // 1576 + SYS___SQRTL_B = 0x629 // 1577 + SYS___ABSF_B = 0x62A // 1578 + SYS___ABS_B = 0x62B // 1579 + SYS___ABSL_B = 0x62C // 1580 + SYS___FMODF_B = 0x62D // 1581 + SYS___FMODL_B = 0x62E // 1582 + SYS___MODFF_B = 0x62F // 1583 + SYS___MODFL_B = 0x630 // 1584 + SYS_ABSF = 0x631 // 1585 + SYS_ABSL = 0x632 // 1586 + SYS_ACOSF = 0x633 // 1587 + SYS_ACOSL = 0x634 // 1588 + SYS_ASINF = 0x635 // 1589 + SYS_ASINL = 0x636 // 1590 + SYS_ATAN2F = 0x637 // 1591 + SYS_ATAN2L = 0x638 // 1592 + SYS_ATANF = 0x639 // 1593 + SYS_ATANL = 0x63A // 1594 + SYS_CEILF = 0x63B // 1595 + SYS_CEILL = 0x63C // 1596 + SYS_COSF = 0x63D // 1597 + SYS_COSL = 0x63E // 1598 + SYS_COSHF = 0x63F // 1599 + SYS_COSHL = 0x640 // 1600 + SYS_EXPF = 0x641 // 1601 + SYS_EXPL = 0x642 // 1602 + SYS_TANHF = 0x643 // 1603 + SYS_TANHL = 0x644 // 1604 + SYS_LOG10F = 0x645 // 1605 + SYS_LOG10L = 0x646 // 1606 + SYS_LOGF = 0x647 // 1607 + SYS_LOGL = 0x648 // 1608 + SYS_POWF = 0x649 // 1609 + SYS_POWL = 0x64A // 1610 + SYS_SINF = 0x64B // 1611 + SYS_SINL = 0x64C // 1612 + SYS_SQRTF = 0x64D // 1613 + SYS_SQRTL = 0x64E // 1614 + SYS_SINHF = 0x64F // 1615 + SYS_SINHL = 0x650 // 1616 + SYS_TANF = 0x651 // 1617 + SYS_TANL = 0x652 // 1618 + SYS_FABSF = 0x653 // 1619 + SYS_FABSL = 0x654 // 1620 + SYS_FLOORF = 0x655 // 1621 + SYS_FLOORL = 0x656 // 1622 + SYS_FMODF = 0x657 // 1623 + SYS_FMODL = 0x658 // 1624 + SYS_FREXPF = 0x659 // 1625 + SYS_FREXPL = 0x65A // 1626 + SYS_LDEXPF = 0x65B // 1627 + SYS_LDEXPL = 0x65C // 1628 + SYS_MODFF = 0x65D // 1629 + SYS_MODFL = 0x65E // 1630 + SYS_BTOWC = 0x65F // 1631 + SYS___CHATTR = 0x660 // 1632 + SYS___FCHATTR = 0x661 // 1633 + SYS___TOCCSID = 0x662 // 1634 + SYS___CSNAMETYPE = 0x663 // 1635 + SYS___TOCSNAME = 0x664 // 1636 + SYS___CCSIDTYPE = 0x665 // 1637 + SYS___AE_CORRESTBL_QUERY = 0x666 // 1638 + SYS___AE_AUTOCONVERT_STATE = 0x667 // 1639 + SYS_DN_FIND = 0x668 // 1640 + SYS___GETHOSTBYADDR_A = 0x669 // 1641 + SYS___GETHOSTBYNAME_A = 0x66A // 1642 + SYS___RES_INIT_A = 0x66B // 1643 + SYS___GETHOSTBYADDR_R_A = 0x66C // 1644 + SYS___GETHOSTBYNAME_R_A = 0x66D // 1645 + SYS___CHARMAP_INIT_A = 0x66E // 1646 + SYS___MBLEN_A = 0x66F // 1647 + SYS___MBLEN_SB_A = 0x670 // 1648 + SYS___MBLEN_STD_A = 0x671 // 1649 + SYS___MBLEN_UTF = 0x672 // 1650 + SYS___MBSTOWCS_A = 0x673 // 1651 + SYS___MBSTOWCS_STD_A = 0x674 // 1652 + SYS___MBTOWC_A = 0x675 // 1653 + SYS___MBTOWC_ISO1 = 0x676 // 1654 + SYS___MBTOWC_SBCS = 0x677 // 1655 + SYS___MBTOWC_MBCS = 0x678 // 1656 + SYS___MBTOWC_UTF = 0x679 // 1657 + SYS___WCSTOMBS_A = 0x67A // 1658 + SYS___WCSTOMBS_STD_A = 0x67B // 1659 + SYS___WCSWIDTH_A = 0x67C // 1660 + SYS___GETGRGID_R_A = 0x67D // 1661 + SYS___WCSWIDTH_STD_A = 0x67E // 1662 + SYS___WCSWIDTH_ASIA = 0x67F // 1663 + SYS___CSID_A = 0x680 // 1664 + SYS___CSID_STD_A = 0x681 // 1665 + SYS___WCSID_A = 0x682 // 1666 + SYS___WCSID_STD_A = 0x683 // 1667 + SYS___WCTOMB_A = 0x684 // 1668 + SYS___WCTOMB_ISO1 = 0x685 // 1669 + SYS___WCTOMB_STD_A = 0x686 // 1670 + SYS___WCTOMB_UTF = 0x687 // 1671 + SYS___WCWIDTH_A = 0x688 // 1672 + SYS___GETGRNAM_R_A = 0x689 // 1673 + SYS___WCWIDTH_STD_A = 0x68A // 1674 + SYS___WCWIDTH_ASIA = 0x68B // 1675 + SYS___GETPWNAM_R_A = 0x68C // 1676 + SYS___GETPWUID_R_A = 0x68D // 1677 + SYS___GETLOGIN_R_A = 0x68E // 1678 + SYS___TTYNAME_R_A = 0x68F // 1679 + SYS___READDIR_R_A = 0x690 // 1680 + SYS___E2A_S = 0x691 // 1681 + SYS___FNMATCH_A = 0x692 // 1682 + SYS___FNMATCH_C_A = 0x693 // 1683 + SYS___EXECL_A = 0x694 // 1684 + SYS___FNMATCH_STD_A = 0x695 // 1685 + SYS___REGCOMP_A = 0x696 // 1686 + SYS___REGCOMP_STD_A = 0x697 // 1687 + SYS___REGERROR_A = 0x698 // 1688 + SYS___REGERROR_STD_A = 0x699 // 1689 + SYS___REGEXEC_A = 0x69A // 1690 + SYS___REGEXEC_STD_A = 0x69B // 1691 + SYS___REGFREE_A = 0x69C // 1692 + SYS___REGFREE_STD_A = 0x69D // 1693 + SYS___STRCOLL_A = 0x69E // 1694 + SYS___STRCOLL_C_A = 0x69F // 1695 + SYS___EXECLE_A = 0x6A0 // 1696 + SYS___STRCOLL_STD_A = 0x6A1 // 1697 + SYS___STRXFRM_A = 0x6A2 // 1698 + SYS___STRXFRM_C_A = 0x6A3 // 1699 + SYS___EXECLP_A = 0x6A4 // 1700 + SYS___STRXFRM_STD_A = 0x6A5 // 1701 + SYS___WCSCOLL_A = 0x6A6 // 1702 + SYS___WCSCOLL_C_A = 0x6A7 // 1703 + SYS___WCSCOLL_STD_A = 0x6A8 // 1704 + SYS___WCSXFRM_A = 0x6A9 // 1705 + SYS___WCSXFRM_C_A = 0x6AA // 1706 + SYS___WCSXFRM_STD_A = 0x6AB // 1707 + SYS___COLLATE_INIT_A = 0x6AC // 1708 + SYS___WCTYPE_A = 0x6AD // 1709 + SYS___GET_WCTYPE_STD_A = 0x6AE // 1710 + SYS___CTYPE_INIT_A = 0x6AF // 1711 + SYS___ISWCTYPE_A = 0x6B0 // 1712 + SYS___EXECV_A = 0x6B1 // 1713 + SYS___IS_WCTYPE_STD_A = 0x6B2 // 1714 + SYS___TOWLOWER_A = 0x6B3 // 1715 + SYS___TOWLOWER_STD_A = 0x6B4 // 1716 + SYS___TOWUPPER_A = 0x6B5 // 1717 + SYS___TOWUPPER_STD_A = 0x6B6 // 1718 + SYS___LOCALE_INIT_A = 0x6B7 // 1719 + SYS___LOCALECONV_A = 0x6B8 // 1720 + SYS___LOCALECONV_STD_A = 0x6B9 // 1721 + SYS___NL_LANGINFO_A = 0x6BA // 1722 + SYS___NL_LNAGINFO_STD_A = 0x6BB // 1723 + SYS___MONETARY_INIT_A = 0x6BC // 1724 + SYS___STRFMON_A = 0x6BD // 1725 + SYS___STRFMON_STD_A = 0x6BE // 1726 + SYS___GETADDRINFO_A = 0x6BF // 1727 + SYS___CATGETS_A = 0x6C0 // 1728 + SYS___EXECVE_A = 0x6C1 // 1729 + SYS___EXECVP_A = 0x6C2 // 1730 + SYS___SPAWN_A = 0x6C3 // 1731 + SYS___GETNAMEINFO_A = 0x6C4 // 1732 + SYS___SPAWNP_A = 0x6C5 // 1733 + SYS___NUMERIC_INIT_A = 0x6C6 // 1734 + SYS___RESP_INIT_A = 0x6C7 // 1735 + SYS___RPMATCH_A = 0x6C8 // 1736 + SYS___RPMATCH_C_A = 0x6C9 // 1737 + SYS___RPMATCH_STD_A = 0x6CA // 1738 + SYS___TIME_INIT_A = 0x6CB // 1739 + SYS___STRFTIME_A = 0x6CC // 1740 + SYS___STRFTIME_STD_A = 0x6CD // 1741 + SYS___STRPTIME_A = 0x6CE // 1742 + SYS___STRPTIME_STD_A = 0x6CF // 1743 + SYS___WCSFTIME_A = 0x6D0 // 1744 + SYS___WCSFTIME_STD_A = 0x6D1 // 1745 + SYS_____SPAWN2_A = 0x6D2 // 1746 + SYS_____SPAWNP2_A = 0x6D3 // 1747 + SYS___SYNTAX_INIT_A = 0x6D4 // 1748 + SYS___TOD_INIT_A = 0x6D5 // 1749 + SYS___NL_CSINFO_A = 0x6D6 // 1750 + SYS___NL_MONINFO_A = 0x6D7 // 1751 + SYS___NL_NUMINFO_A = 0x6D8 // 1752 + SYS___NL_RESPINFO_A = 0x6D9 // 1753 + SYS___NL_TIMINFO_A = 0x6DA // 1754 + SYS___IF_NAMETOINDEX_A = 0x6DB // 1755 + SYS___IF_INDEXTONAME_A = 0x6DC // 1756 + SYS___PRINTF_A = 0x6DD // 1757 + SYS___ICONV_OPEN_A = 0x6DE // 1758 + SYS___DLLLOAD_A = 0x6DF // 1759 + SYS___DLLQUERYFN_A = 0x6E0 // 1760 + SYS___DLLQUERYVAR_A = 0x6E1 // 1761 + SYS_____CHATTR_A = 0x6E2 // 1762 + SYS___E2A_L = 0x6E3 // 1763 + SYS_____TOCCSID_A = 0x6E4 // 1764 + SYS_____TOCSNAME_A = 0x6E5 // 1765 + SYS_____CCSIDTYPE_A = 0x6E6 // 1766 + SYS_____CSNAMETYPE_A = 0x6E7 // 1767 + SYS___CHMOD_A = 0x6E8 // 1768 + SYS___MKDIR_A = 0x6E9 // 1769 + SYS___STAT_A = 0x6EA // 1770 + SYS___STAT_O_A = 0x6EB // 1771 + SYS___MKFIFO_A = 0x6EC // 1772 + SYS_____OPEN_STAT_A = 0x6ED // 1773 + SYS___LSTAT_A = 0x6EE // 1774 + SYS___LSTAT_O_A = 0x6EF // 1775 + SYS___MKNOD_A = 0x6F0 // 1776 + SYS___MOUNT_A = 0x6F1 // 1777 + SYS___UMOUNT_A = 0x6F2 // 1778 + SYS___CHAUDIT_A = 0x6F4 // 1780 + SYS___W_GETMNTENT_A = 0x6F5 // 1781 + SYS___CREAT_A = 0x6F6 // 1782 + SYS___OPEN_A = 0x6F7 // 1783 + SYS___SETLOCALE_A = 0x6F9 // 1785 + SYS___FPRINTF_A = 0x6FA // 1786 + SYS___SPRINTF_A = 0x6FB // 1787 + SYS___VFPRINTF_A = 0x6FC // 1788 + SYS___VPRINTF_A = 0x6FD // 1789 + SYS___VSPRINTF_A = 0x6FE // 1790 + SYS___VSWPRINTF_A = 0x6FF // 1791 + SYS___SWPRINTF_A = 0x700 // 1792 + SYS___FSCANF_A = 0x701 // 1793 + SYS___SCANF_A = 0x702 // 1794 + SYS___SSCANF_A = 0x703 // 1795 + SYS___SWSCANF_A = 0x704 // 1796 + SYS___ATOF_A = 0x705 // 1797 + SYS___ATOI_A = 0x706 // 1798 + SYS___ATOL_A = 0x707 // 1799 + SYS___STRTOD_A = 0x708 // 1800 + SYS___STRTOL_A = 0x709 // 1801 + SYS___STRTOUL_A = 0x70A // 1802 + SYS_____AE_CORRESTBL_QUERY_A = 0x70B // 1803 + SYS___A64L_A = 0x70C // 1804 + SYS___ECVT_A = 0x70D // 1805 + SYS___FCVT_A = 0x70E // 1806 + SYS___GCVT_A = 0x70F // 1807 + SYS___L64A_A = 0x710 // 1808 + SYS___STRERROR_A = 0x711 // 1809 + SYS___PERROR_A = 0x712 // 1810 + SYS___FETCH_A = 0x713 // 1811 + SYS___GETENV_A = 0x714 // 1812 + SYS___MKSTEMP_A = 0x717 // 1815 + SYS___PTSNAME_A = 0x718 // 1816 + SYS___PUTENV_A = 0x719 // 1817 + SYS___REALPATH_A = 0x71A // 1818 + SYS___SETENV_A = 0x71B // 1819 + SYS___SYSTEM_A = 0x71C // 1820 + SYS___GETOPT_A = 0x71D // 1821 + SYS___CATOPEN_A = 0x71E // 1822 + SYS___ACCESS_A = 0x71F // 1823 + SYS___CHDIR_A = 0x720 // 1824 + SYS___CHOWN_A = 0x721 // 1825 + SYS___CHROOT_A = 0x722 // 1826 + SYS___GETCWD_A = 0x723 // 1827 + SYS___GETWD_A = 0x724 // 1828 + SYS___LCHOWN_A = 0x725 // 1829 + SYS___LINK_A = 0x726 // 1830 + SYS___PATHCONF_A = 0x727 // 1831 + SYS___IF_NAMEINDEX_A = 0x728 // 1832 + SYS___READLINK_A = 0x729 // 1833 + SYS___RMDIR_A = 0x72A // 1834 + SYS___STATVFS_A = 0x72B // 1835 + SYS___SYMLINK_A = 0x72C // 1836 + SYS___TRUNCATE_A = 0x72D // 1837 + SYS___UNLINK_A = 0x72E // 1838 + SYS___GAI_STRERROR_A = 0x72F // 1839 + SYS___EXTLINK_NP_A = 0x730 // 1840 + SYS___ISALNUM_A = 0x731 // 1841 + SYS___ISALPHA_A = 0x732 // 1842 + SYS___A2E_S = 0x733 // 1843 + SYS___ISCNTRL_A = 0x734 // 1844 + SYS___ISDIGIT_A = 0x735 // 1845 + SYS___ISGRAPH_A = 0x736 // 1846 + SYS___ISLOWER_A = 0x737 // 1847 + SYS___ISPRINT_A = 0x738 // 1848 + SYS___ISPUNCT_A = 0x739 // 1849 + SYS___ISSPACE_A = 0x73A // 1850 + SYS___ISUPPER_A = 0x73B // 1851 + SYS___ISXDIGIT_A = 0x73C // 1852 + SYS___TOLOWER_A = 0x73D // 1853 + SYS___TOUPPER_A = 0x73E // 1854 + SYS___ISWALNUM_A = 0x73F // 1855 + SYS___ISWALPHA_A = 0x740 // 1856 + SYS___A2E_L = 0x741 // 1857 + SYS___ISWCNTRL_A = 0x742 // 1858 + SYS___ISWDIGIT_A = 0x743 // 1859 + SYS___ISWGRAPH_A = 0x744 // 1860 + SYS___ISWLOWER_A = 0x745 // 1861 + SYS___ISWPRINT_A = 0x746 // 1862 + SYS___ISWPUNCT_A = 0x747 // 1863 + SYS___ISWSPACE_A = 0x748 // 1864 + SYS___ISWUPPER_A = 0x749 // 1865 + SYS___ISWXDIGIT_A = 0x74A // 1866 + SYS___CONFSTR_A = 0x74B // 1867 + SYS___FTOK_A = 0x74C // 1868 + SYS___MKTEMP_A = 0x74D // 1869 + SYS___FDOPEN_A = 0x74E // 1870 + SYS___FLDATA_A = 0x74F // 1871 + SYS___REMOVE_A = 0x750 // 1872 + SYS___RENAME_A = 0x751 // 1873 + SYS___TMPNAM_A = 0x752 // 1874 + SYS___FOPEN_A = 0x753 // 1875 + SYS___FREOPEN_A = 0x754 // 1876 + SYS___CUSERID_A = 0x755 // 1877 + SYS___POPEN_A = 0x756 // 1878 + SYS___TEMPNAM_A = 0x757 // 1879 + SYS___FTW_A = 0x758 // 1880 + SYS___GETGRENT_A = 0x759 // 1881 + SYS___GETGRGID_A = 0x75A // 1882 + SYS___GETGRNAM_A = 0x75B // 1883 + SYS___GETGROUPSBYNAME_A = 0x75C // 1884 + SYS___GETHOSTENT_A = 0x75D // 1885 + SYS___GETHOSTNAME_A = 0x75E // 1886 + SYS___GETLOGIN_A = 0x75F // 1887 + SYS___INET_NTOP_A = 0x760 // 1888 + SYS___GETPASS_A = 0x761 // 1889 + SYS___GETPWENT_A = 0x762 // 1890 + SYS___GETPWNAM_A = 0x763 // 1891 + SYS___GETPWUID_A = 0x764 // 1892 + SYS_____CHECK_RESOURCE_AUTH_NP_A = 0x765 // 1893 + SYS___CHECKSCHENV_A = 0x766 // 1894 + SYS___CONNECTSERVER_A = 0x767 // 1895 + SYS___CONNECTWORKMGR_A = 0x768 // 1896 + SYS_____CONSOLE_A = 0x769 // 1897 + SYS___CREATEWORKUNIT_A = 0x76A // 1898 + SYS___CTERMID_A = 0x76B // 1899 + SYS___FMTMSG_A = 0x76C // 1900 + SYS___INITGROUPS_A = 0x76D // 1901 + SYS_____LOGIN_A = 0x76E // 1902 + SYS___MSGRCV_A = 0x76F // 1903 + SYS___MSGSND_A = 0x770 // 1904 + SYS___MSGXRCV_A = 0x771 // 1905 + SYS___NFTW_A = 0x772 // 1906 + SYS_____PASSWD_A = 0x773 // 1907 + SYS___PTHREAD_SECURITY_NP_A = 0x774 // 1908 + SYS___QUERYMETRICS_A = 0x775 // 1909 + SYS___QUERYSCHENV = 0x776 // 1910 + SYS___READV_A = 0x777 // 1911 + SYS_____SERVER_CLASSIFY_A = 0x778 // 1912 + SYS_____SERVER_INIT_A = 0x779 // 1913 + SYS_____SERVER_PWU_A = 0x77A // 1914 + SYS___STRCASECMP_A = 0x77B // 1915 + SYS___STRNCASECMP_A = 0x77C // 1916 + SYS___TTYNAME_A = 0x77D // 1917 + SYS___UNAME_A = 0x77E // 1918 + SYS___UTIMES_A = 0x77F // 1919 + SYS___W_GETPSENT_A = 0x780 // 1920 + SYS___WRITEV_A = 0x781 // 1921 + SYS___W_STATFS_A = 0x782 // 1922 + SYS___W_STATVFS_A = 0x783 // 1923 + SYS___FPUTC_A = 0x784 // 1924 + SYS___PUTCHAR_A = 0x785 // 1925 + SYS___PUTS_A = 0x786 // 1926 + SYS___FGETS_A = 0x787 // 1927 + SYS___GETS_A = 0x788 // 1928 + SYS___FPUTS_A = 0x789 // 1929 + SYS___FREAD_A = 0x78A // 1930 + SYS___FWRITE_A = 0x78B // 1931 + SYS___OPEN_O_A = 0x78C // 1932 + SYS___ISASCII = 0x78D // 1933 + SYS___CREAT_O_A = 0x78E // 1934 + SYS___ENVNA = 0x78F // 1935 + SYS___PUTC_A = 0x790 // 1936 + SYS___AE_THREAD_SETMODE = 0x791 // 1937 + SYS___AE_THREAD_SWAPMODE = 0x792 // 1938 + SYS___GETNETBYADDR_A = 0x793 // 1939 + SYS___GETNETBYNAME_A = 0x794 // 1940 + SYS___GETNETENT_A = 0x795 // 1941 + SYS___GETPROTOBYNAME_A = 0x796 // 1942 + SYS___GETPROTOBYNUMBER_A = 0x797 // 1943 + SYS___GETPROTOENT_A = 0x798 // 1944 + SYS___GETSERVBYNAME_A = 0x799 // 1945 + SYS___GETSERVBYPORT_A = 0x79A // 1946 + SYS___GETSERVENT_A = 0x79B // 1947 + SYS___ASCTIME_A = 0x79C // 1948 + SYS___CTIME_A = 0x79D // 1949 + SYS___GETDATE_A = 0x79E // 1950 + SYS___TZSET_A = 0x79F // 1951 + SYS___UTIME_A = 0x7A0 // 1952 + SYS___ASCTIME_R_A = 0x7A1 // 1953 + SYS___CTIME_R_A = 0x7A2 // 1954 + SYS___STRTOLL_A = 0x7A3 // 1955 + SYS___STRTOULL_A = 0x7A4 // 1956 + SYS___FPUTWC_A = 0x7A5 // 1957 + SYS___PUTWC_A = 0x7A6 // 1958 + SYS___PUTWCHAR_A = 0x7A7 // 1959 + SYS___FPUTWS_A = 0x7A8 // 1960 + SYS___UNGETWC_A = 0x7A9 // 1961 + SYS___FGETWC_A = 0x7AA // 1962 + SYS___GETWC_A = 0x7AB // 1963 + SYS___GETWCHAR_A = 0x7AC // 1964 + SYS___FGETWS_A = 0x7AD // 1965 + SYS___GETTIMEOFDAY_A = 0x7AE // 1966 + SYS___GMTIME_A = 0x7AF // 1967 + SYS___GMTIME_R_A = 0x7B0 // 1968 + SYS___LOCALTIME_A = 0x7B1 // 1969 + SYS___LOCALTIME_R_A = 0x7B2 // 1970 + SYS___MKTIME_A = 0x7B3 // 1971 + SYS___TZZNA = 0x7B4 // 1972 + SYS_UNATEXIT = 0x7B5 // 1973 + SYS___CEE3DMP_A = 0x7B6 // 1974 + SYS___CDUMP_A = 0x7B7 // 1975 + SYS___CSNAP_A = 0x7B8 // 1976 + SYS___CTEST_A = 0x7B9 // 1977 + SYS___CTRACE_A = 0x7BA // 1978 + SYS___VSWPRNTF2_A = 0x7BB // 1979 + SYS___INET_PTON_A = 0x7BC // 1980 + SYS___SYSLOG_A = 0x7BD // 1981 + SYS___CRYPT_A = 0x7BE // 1982 + SYS_____OPENDIR2_A = 0x7BF // 1983 + SYS_____READDIR2_A = 0x7C0 // 1984 + SYS___OPENDIR_A = 0x7C2 // 1986 + SYS___READDIR_A = 0x7C3 // 1987 + SYS_PREAD = 0x7C7 // 1991 + SYS_PWRITE = 0x7C8 // 1992 + SYS_M_CREATE_LAYOUT = 0x7C9 // 1993 + SYS_M_DESTROY_LAYOUT = 0x7CA // 1994 + SYS_M_GETVALUES_LAYOUT = 0x7CB // 1995 + SYS_M_SETVALUES_LAYOUT = 0x7CC // 1996 + SYS_M_TRANSFORM_LAYOUT = 0x7CD // 1997 + SYS_M_WTRANSFORM_LAYOUT = 0x7CE // 1998 + SYS_FWPRINTF = 0x7D1 // 2001 + SYS_WPRINTF = 0x7D2 // 2002 + SYS_VFWPRINT = 0x7D3 // 2003 + SYS_VFWPRINTF = 0x7D3 // 2003 + SYS_VWPRINTF = 0x7D4 // 2004 + SYS_FWSCANF = 0x7D5 // 2005 + SYS_WSCANF = 0x7D6 // 2006 + SYS_WCTRANS = 0x7D7 // 2007 + SYS_TOWCTRAN = 0x7D8 // 2008 + SYS_TOWCTRANS = 0x7D8 // 2008 + SYS___WCSTOD_A = 0x7D9 // 2009 + SYS___WCSTOL_A = 0x7DA // 2010 + SYS___WCSTOUL_A = 0x7DB // 2011 + SYS___BASENAME_A = 0x7DC // 2012 + SYS___DIRNAME_A = 0x7DD // 2013 + SYS___GLOB_A = 0x7DE // 2014 + SYS_FWIDE = 0x7DF // 2015 + SYS___OSNAME = 0x7E0 // 2016 + SYS_____OSNAME_A = 0x7E1 // 2017 + SYS___BTOWC_A = 0x7E4 // 2020 + SYS___WCTOB_A = 0x7E5 // 2021 + SYS___DBM_OPEN_A = 0x7E6 // 2022 + SYS___VFPRINTF2_A = 0x7E7 // 2023 + SYS___VPRINTF2_A = 0x7E8 // 2024 + SYS___VSPRINTF2_A = 0x7E9 // 2025 + SYS___CEIL_H = 0x7EA // 2026 + SYS___FLOOR_H = 0x7EB // 2027 + SYS___MODF_H = 0x7EC // 2028 + SYS___FABS_H = 0x7ED // 2029 + SYS___J0_H = 0x7EE // 2030 + SYS___J1_H = 0x7EF // 2031 + SYS___JN_H = 0x7F0 // 2032 + SYS___Y0_H = 0x7F1 // 2033 + SYS___Y1_H = 0x7F2 // 2034 + SYS___YN_H = 0x7F3 // 2035 + SYS___CEILF_H = 0x7F4 // 2036 + SYS___CEILL_H = 0x7F5 // 2037 + SYS___FLOORF_H = 0x7F6 // 2038 + SYS___FLOORL_H = 0x7F7 // 2039 + SYS___MODFF_H = 0x7F8 // 2040 + SYS___MODFL_H = 0x7F9 // 2041 + SYS___FABSF_H = 0x7FA // 2042 + SYS___FABSL_H = 0x7FB // 2043 + SYS___MALLOC24 = 0x7FC // 2044 + SYS___MALLOC31 = 0x7FD // 2045 + SYS_ACL_INIT = 0x7FE // 2046 + SYS_ACL_FREE = 0x7FF // 2047 + SYS_ACL_FIRST_ENTRY = 0x800 // 2048 + SYS_ACL_GET_ENTRY = 0x801 // 2049 + SYS_ACL_VALID = 0x802 // 2050 + SYS_ACL_CREATE_ENTRY = 0x803 // 2051 + SYS_ACL_DELETE_ENTRY = 0x804 // 2052 + SYS_ACL_UPDATE_ENTRY = 0x805 // 2053 + SYS_ACL_DELETE_FD = 0x806 // 2054 + SYS_ACL_DELETE_FILE = 0x807 // 2055 + SYS_ACL_GET_FD = 0x808 // 2056 + SYS_ACL_GET_FILE = 0x809 // 2057 + SYS_ACL_SET_FD = 0x80A // 2058 + SYS_ACL_SET_FILE = 0x80B // 2059 + SYS_ACL_FROM_TEXT = 0x80C // 2060 + SYS_ACL_TO_TEXT = 0x80D // 2061 + SYS_ACL_SORT = 0x80E // 2062 + SYS___SHUTDOWN_REGISTRATION = 0x80F // 2063 + SYS___ERFL_B = 0x810 // 2064 + SYS___ERFCL_B = 0x811 // 2065 + SYS___LGAMMAL_B = 0x812 // 2066 + SYS___SETHOOKEVENTS = 0x813 // 2067 + SYS_IF_NAMETOINDEX = 0x814 // 2068 + SYS_IF_INDEXTONAME = 0x815 // 2069 + SYS_IF_NAMEINDEX = 0x816 // 2070 + SYS_IF_FREENAMEINDEX = 0x817 // 2071 + SYS_GETADDRINFO = 0x818 // 2072 + SYS_GETNAMEINFO = 0x819 // 2073 + SYS_FREEADDRINFO = 0x81A // 2074 + SYS_GAI_STRERROR = 0x81B // 2075 + SYS_REXEC_AF = 0x81C // 2076 + SYS___POE = 0x81D // 2077 + SYS___DYNALLOC_A = 0x81F // 2079 + SYS___DYNFREE_A = 0x820 // 2080 + SYS___RES_QUERY_A = 0x821 // 2081 + SYS___RES_SEARCH_A = 0x822 // 2082 + SYS___RES_QUERYDOMAIN_A = 0x823 // 2083 + SYS___RES_MKQUERY_A = 0x824 // 2084 + SYS___RES_SEND_A = 0x825 // 2085 + SYS___DN_EXPAND_A = 0x826 // 2086 + SYS___DN_SKIPNAME_A = 0x827 // 2087 + SYS___DN_COMP_A = 0x828 // 2088 + SYS___DN_FIND_A = 0x829 // 2089 + SYS___NLIST_A = 0x82A // 2090 + SYS_____TCGETCP_A = 0x82B // 2091 + SYS_____TCSETCP_A = 0x82C // 2092 + SYS_____W_PIOCTL_A = 0x82E // 2094 + SYS___INET_ADDR_A = 0x82F // 2095 + SYS___INET_NTOA_A = 0x830 // 2096 + SYS___INET_NETWORK_A = 0x831 // 2097 + SYS___ACCEPT_A = 0x832 // 2098 + SYS___ACCEPT_AND_RECV_A = 0x833 // 2099 + SYS___BIND_A = 0x834 // 2100 + SYS___CONNECT_A = 0x835 // 2101 + SYS___GETPEERNAME_A = 0x836 // 2102 + SYS___GETSOCKNAME_A = 0x837 // 2103 + SYS___RECVFROM_A = 0x838 // 2104 + SYS___SENDTO_A = 0x839 // 2105 + SYS___SENDMSG_A = 0x83A // 2106 + SYS___RECVMSG_A = 0x83B // 2107 + SYS_____LCHATTR_A = 0x83C // 2108 + SYS___CABEND = 0x83D // 2109 + SYS___LE_CIB_GET = 0x83E // 2110 + SYS___SET_LAA_FOR_JIT = 0x83F // 2111 + SYS___LCHATTR = 0x840 // 2112 + SYS___WRITEDOWN = 0x841 // 2113 + SYS_PTHREAD_MUTEX_INIT2 = 0x842 // 2114 + SYS___ACOSHF_B = 0x843 // 2115 + SYS___ACOSHL_B = 0x844 // 2116 + SYS___ASINHF_B = 0x845 // 2117 + SYS___ASINHL_B = 0x846 // 2118 + SYS___ATANHF_B = 0x847 // 2119 + SYS___ATANHL_B = 0x848 // 2120 + SYS___CBRTF_B = 0x849 // 2121 + SYS___CBRTL_B = 0x84A // 2122 + SYS___COPYSIGNF_B = 0x84B // 2123 + SYS___COPYSIGNL_B = 0x84C // 2124 + SYS___COTANF_B = 0x84D // 2125 + SYS___COTAN_B = 0x84E // 2126 + SYS___COTANL_B = 0x84F // 2127 + SYS___EXP2F_B = 0x850 // 2128 + SYS___EXP2L_B = 0x851 // 2129 + SYS___EXPM1F_B = 0x852 // 2130 + SYS___EXPM1L_B = 0x853 // 2131 + SYS___FDIMF_B = 0x854 // 2132 + SYS___FDIM_B = 0x855 // 2133 + SYS___FDIML_B = 0x856 // 2134 + SYS___HYPOTF_B = 0x857 // 2135 + SYS___HYPOTL_B = 0x858 // 2136 + SYS___LOG1PF_B = 0x859 // 2137 + SYS___LOG1PL_B = 0x85A // 2138 + SYS___LOG2F_B = 0x85B // 2139 + SYS___LOG2_B = 0x85C // 2140 + SYS___LOG2L_B = 0x85D // 2141 + SYS___REMAINDERF_B = 0x85E // 2142 + SYS___REMAINDERL_B = 0x85F // 2143 + SYS___REMQUOF_B = 0x860 // 2144 + SYS___REMQUO_B = 0x861 // 2145 + SYS___REMQUOL_B = 0x862 // 2146 + SYS___TGAMMAF_B = 0x863 // 2147 + SYS___TGAMMA_B = 0x864 // 2148 + SYS___TGAMMAL_B = 0x865 // 2149 + SYS___TRUNCF_B = 0x866 // 2150 + SYS___TRUNC_B = 0x867 // 2151 + SYS___TRUNCL_B = 0x868 // 2152 + SYS___LGAMMAF_B = 0x869 // 2153 + SYS___LROUNDF_B = 0x86A // 2154 + SYS___LROUND_B = 0x86B // 2155 + SYS___ERFF_B = 0x86C // 2156 + SYS___ERFCF_B = 0x86D // 2157 + SYS_ACOSHF = 0x86E // 2158 + SYS_ACOSHL = 0x86F // 2159 + SYS_ASINHF = 0x870 // 2160 + SYS_ASINHL = 0x871 // 2161 + SYS_ATANHF = 0x872 // 2162 + SYS_ATANHL = 0x873 // 2163 + SYS_CBRTF = 0x874 // 2164 + SYS_CBRTL = 0x875 // 2165 + SYS_COPYSIGNF = 0x876 // 2166 + SYS_CPYSIGNF = 0x876 // 2166 + SYS_COPYSIGNL = 0x877 // 2167 + SYS_CPYSIGNL = 0x877 // 2167 + SYS_COTANF = 0x878 // 2168 + SYS___COTANF = 0x878 // 2168 + SYS_COTAN = 0x879 // 2169 + SYS___COTAN = 0x879 // 2169 + SYS_COTANL = 0x87A // 2170 + SYS___COTANL = 0x87A // 2170 + SYS_EXP2F = 0x87B // 2171 + SYS_EXP2L = 0x87C // 2172 + SYS_EXPM1F = 0x87D // 2173 + SYS_EXPM1L = 0x87E // 2174 + SYS_FDIMF = 0x87F // 2175 + SYS_FDIM = 0x881 // 2177 + SYS_FDIML = 0x882 // 2178 + SYS_HYPOTF = 0x883 // 2179 + SYS_HYPOTL = 0x884 // 2180 + SYS_LOG1PF = 0x885 // 2181 + SYS_LOG1PL = 0x886 // 2182 + SYS_LOG2F = 0x887 // 2183 + SYS_LOG2 = 0x888 // 2184 + SYS_LOG2L = 0x889 // 2185 + SYS_REMAINDERF = 0x88A // 2186 + SYS_REMAINDF = 0x88A // 2186 + SYS_REMAINDERL = 0x88B // 2187 + SYS_REMAINDL = 0x88B // 2187 + SYS_REMQUOF = 0x88C // 2188 + SYS_REMQUO = 0x88D // 2189 + SYS_REMQUOL = 0x88E // 2190 + SYS_TGAMMAF = 0x88F // 2191 + SYS_TGAMMA = 0x890 // 2192 + SYS_TGAMMAL = 0x891 // 2193 + SYS_TRUNCF = 0x892 // 2194 + SYS_TRUNC = 0x893 // 2195 + SYS_TRUNCL = 0x894 // 2196 + SYS_LGAMMAF = 0x895 // 2197 + SYS_LGAMMAL = 0x896 // 2198 + SYS_LROUNDF = 0x897 // 2199 + SYS_LROUND = 0x898 // 2200 + SYS_ERFF = 0x899 // 2201 + SYS_ERFL = 0x89A // 2202 + SYS_ERFCF = 0x89B // 2203 + SYS_ERFCL = 0x89C // 2204 + SYS___EXP2_B = 0x89D // 2205 + SYS_EXP2 = 0x89E // 2206 + SYS___FAR_JUMP = 0x89F // 2207 + SYS___TCGETATTR_A = 0x8A1 // 2209 + SYS___TCSETATTR_A = 0x8A2 // 2210 + SYS___SUPERKILL = 0x8A4 // 2212 + SYS___LE_CONDITION_TOKEN_BUILD = 0x8A5 // 2213 + SYS___LE_MSG_ADD_INSERT = 0x8A6 // 2214 + SYS___LE_MSG_GET = 0x8A7 // 2215 + SYS___LE_MSG_GET_AND_WRITE = 0x8A8 // 2216 + SYS___LE_MSG_WRITE = 0x8A9 // 2217 + SYS___ITOA = 0x8AA // 2218 + SYS___UTOA = 0x8AB // 2219 + SYS___LTOA = 0x8AC // 2220 + SYS___ULTOA = 0x8AD // 2221 + SYS___LLTOA = 0x8AE // 2222 + SYS___ULLTOA = 0x8AF // 2223 + SYS___ITOA_A = 0x8B0 // 2224 + SYS___UTOA_A = 0x8B1 // 2225 + SYS___LTOA_A = 0x8B2 // 2226 + SYS___ULTOA_A = 0x8B3 // 2227 + SYS___LLTOA_A = 0x8B4 // 2228 + SYS___ULLTOA_A = 0x8B5 // 2229 + SYS_____GETENV_A = 0x8C3 // 2243 + SYS___REXEC_A = 0x8C4 // 2244 + SYS___REXEC_AF_A = 0x8C5 // 2245 + SYS___GETUTXENT_A = 0x8C6 // 2246 + SYS___GETUTXID_A = 0x8C7 // 2247 + SYS___GETUTXLINE_A = 0x8C8 // 2248 + SYS___PUTUTXLINE_A = 0x8C9 // 2249 + SYS_____UTMPXNAME_A = 0x8CA // 2250 + SYS___PUTC_UNLOCKED_A = 0x8CB // 2251 + SYS___PUTCHAR_UNLOCKED_A = 0x8CC // 2252 + SYS___SNPRINTF_A = 0x8CD // 2253 + SYS___VSNPRINTF_A = 0x8CE // 2254 + SYS___DLOPEN_A = 0x8D0 // 2256 + SYS___DLSYM_A = 0x8D1 // 2257 + SYS___DLERROR_A = 0x8D2 // 2258 + SYS_FLOCKFILE = 0x8D3 // 2259 + SYS_FTRYLOCKFILE = 0x8D4 // 2260 + SYS_FUNLOCKFILE = 0x8D5 // 2261 + SYS_GETC_UNLOCKED = 0x8D6 // 2262 + SYS_GETCHAR_UNLOCKED = 0x8D7 // 2263 + SYS_PUTC_UNLOCKED = 0x8D8 // 2264 + SYS_PUTCHAR_UNLOCKED = 0x8D9 // 2265 + SYS_SNPRINTF = 0x8DA // 2266 + SYS_VSNPRINTF = 0x8DB // 2267 + SYS_DLOPEN = 0x8DD // 2269 + SYS_DLSYM = 0x8DE // 2270 + SYS_DLCLOSE = 0x8DF // 2271 + SYS_DLERROR = 0x8E0 // 2272 + SYS___SET_EXCEPTION_HANDLER = 0x8E2 // 2274 + SYS___RESET_EXCEPTION_HANDLER = 0x8E3 // 2275 + SYS___VHM_EVENT = 0x8E4 // 2276 + SYS___ABS_H = 0x8E6 // 2278 + SYS___ABSF_H = 0x8E7 // 2279 + SYS___ABSL_H = 0x8E8 // 2280 + SYS___ACOS_H = 0x8E9 // 2281 + SYS___ACOSF_H = 0x8EA // 2282 + SYS___ACOSL_H = 0x8EB // 2283 + SYS___ACOSH_H = 0x8EC // 2284 + SYS___ASIN_H = 0x8ED // 2285 + SYS___ASINF_H = 0x8EE // 2286 + SYS___ASINL_H = 0x8EF // 2287 + SYS___ASINH_H = 0x8F0 // 2288 + SYS___ATAN_H = 0x8F1 // 2289 + SYS___ATANF_H = 0x8F2 // 2290 + SYS___ATANL_H = 0x8F3 // 2291 + SYS___ATANH_H = 0x8F4 // 2292 + SYS___ATANHF_H = 0x8F5 // 2293 + SYS___ATANHL_H = 0x8F6 // 2294 + SYS___ATAN2_H = 0x8F7 // 2295 + SYS___ATAN2F_H = 0x8F8 // 2296 + SYS___ATAN2L_H = 0x8F9 // 2297 + SYS___CBRT_H = 0x8FA // 2298 + SYS___COPYSIGNF_H = 0x8FB // 2299 + SYS___COPYSIGNL_H = 0x8FC // 2300 + SYS___COS_H = 0x8FD // 2301 + SYS___COSF_H = 0x8FE // 2302 + SYS___COSL_H = 0x8FF // 2303 + SYS___COSHF_H = 0x900 // 2304 + SYS___COSHL_H = 0x901 // 2305 + SYS___COTAN_H = 0x902 // 2306 + SYS___COTANF_H = 0x903 // 2307 + SYS___COTANL_H = 0x904 // 2308 + SYS___ERF_H = 0x905 // 2309 + SYS___ERFF_H = 0x906 // 2310 + SYS___ERFL_H = 0x907 // 2311 + SYS___ERFC_H = 0x908 // 2312 + SYS___ERFCF_H = 0x909 // 2313 + SYS___ERFCL_H = 0x90A // 2314 + SYS___EXP_H = 0x90B // 2315 + SYS___EXPF_H = 0x90C // 2316 + SYS___EXPL_H = 0x90D // 2317 + SYS___EXPM1_H = 0x90E // 2318 + SYS___FDIM_H = 0x90F // 2319 + SYS___FDIMF_H = 0x910 // 2320 + SYS___FDIML_H = 0x911 // 2321 + SYS___FMOD_H = 0x912 // 2322 + SYS___FMODF_H = 0x913 // 2323 + SYS___FMODL_H = 0x914 // 2324 + SYS___GAMMA_H = 0x915 // 2325 + SYS___HYPOT_H = 0x916 // 2326 + SYS___ILOGB_H = 0x917 // 2327 + SYS___LGAMMA_H = 0x918 // 2328 + SYS___LGAMMAF_H = 0x919 // 2329 + SYS___LOG_H = 0x91A // 2330 + SYS___LOGF_H = 0x91B // 2331 + SYS___LOGL_H = 0x91C // 2332 + SYS___LOGB_H = 0x91D // 2333 + SYS___LOG2_H = 0x91E // 2334 + SYS___LOG2F_H = 0x91F // 2335 + SYS___LOG2L_H = 0x920 // 2336 + SYS___LOG1P_H = 0x921 // 2337 + SYS___LOG10_H = 0x922 // 2338 + SYS___LOG10F_H = 0x923 // 2339 + SYS___LOG10L_H = 0x924 // 2340 + SYS___LROUND_H = 0x925 // 2341 + SYS___LROUNDF_H = 0x926 // 2342 + SYS___NEXTAFTER_H = 0x927 // 2343 + SYS___POW_H = 0x928 // 2344 + SYS___POWF_H = 0x929 // 2345 + SYS___POWL_H = 0x92A // 2346 + SYS___REMAINDER_H = 0x92B // 2347 + SYS___RINT_H = 0x92C // 2348 + SYS___SCALB_H = 0x92D // 2349 + SYS___SIN_H = 0x92E // 2350 + SYS___SINF_H = 0x92F // 2351 + SYS___SINL_H = 0x930 // 2352 + SYS___SINH_H = 0x931 // 2353 + SYS___SINHF_H = 0x932 // 2354 + SYS___SINHL_H = 0x933 // 2355 + SYS___SQRT_H = 0x934 // 2356 + SYS___SQRTF_H = 0x935 // 2357 + SYS___SQRTL_H = 0x936 // 2358 + SYS___TAN_H = 0x937 // 2359 + SYS___TANF_H = 0x938 // 2360 + SYS___TANL_H = 0x939 // 2361 + SYS___TANH_H = 0x93A // 2362 + SYS___TANHF_H = 0x93B // 2363 + SYS___TANHL_H = 0x93C // 2364 + SYS___TGAMMA_H = 0x93D // 2365 + SYS___TGAMMAF_H = 0x93E // 2366 + SYS___TRUNC_H = 0x93F // 2367 + SYS___TRUNCF_H = 0x940 // 2368 + SYS___TRUNCL_H = 0x941 // 2369 + SYS___COSH_H = 0x942 // 2370 + SYS___LE_DEBUG_SET_RESUME_MCH = 0x943 // 2371 + SYS_VFSCANF = 0x944 // 2372 + SYS_VSCANF = 0x946 // 2374 + SYS_VSSCANF = 0x948 // 2376 + SYS_VFWSCANF = 0x94A // 2378 + SYS_VWSCANF = 0x94C // 2380 + SYS_VSWSCANF = 0x94E // 2382 + SYS_IMAXABS = 0x950 // 2384 + SYS_IMAXDIV = 0x951 // 2385 + SYS_STRTOIMAX = 0x952 // 2386 + SYS_STRTOUMAX = 0x953 // 2387 + SYS_WCSTOIMAX = 0x954 // 2388 + SYS_WCSTOUMAX = 0x955 // 2389 + SYS_ATOLL = 0x956 // 2390 + SYS_STRTOF = 0x957 // 2391 + SYS_STRTOLD = 0x958 // 2392 + SYS_WCSTOF = 0x959 // 2393 + SYS_WCSTOLD = 0x95A // 2394 + SYS_INET6_RTH_SPACE = 0x95B // 2395 + SYS_INET6_RTH_INIT = 0x95C // 2396 + SYS_INET6_RTH_ADD = 0x95D // 2397 + SYS_INET6_RTH_REVERSE = 0x95E // 2398 + SYS_INET6_RTH_SEGMENTS = 0x95F // 2399 + SYS_INET6_RTH_GETADDR = 0x960 // 2400 + SYS_INET6_OPT_INIT = 0x961 // 2401 + SYS_INET6_OPT_APPEND = 0x962 // 2402 + SYS_INET6_OPT_FINISH = 0x963 // 2403 + SYS_INET6_OPT_SET_VAL = 0x964 // 2404 + SYS_INET6_OPT_NEXT = 0x965 // 2405 + SYS_INET6_OPT_FIND = 0x966 // 2406 + SYS_INET6_OPT_GET_VAL = 0x967 // 2407 + SYS___POW_I = 0x987 // 2439 + SYS___POW_I_B = 0x988 // 2440 + SYS___POW_I_H = 0x989 // 2441 + SYS___POW_II = 0x98A // 2442 + SYS___POW_II_B = 0x98B // 2443 + SYS___POW_II_H = 0x98C // 2444 + SYS_CABS = 0x98E // 2446 + SYS___CABS_B = 0x98F // 2447 + SYS___CABS_H = 0x990 // 2448 + SYS_CABSF = 0x991 // 2449 + SYS___CABSF_B = 0x992 // 2450 + SYS___CABSF_H = 0x993 // 2451 + SYS_CABSL = 0x994 // 2452 + SYS___CABSL_B = 0x995 // 2453 + SYS___CABSL_H = 0x996 // 2454 + SYS_CACOS = 0x997 // 2455 + SYS___CACOS_B = 0x998 // 2456 + SYS___CACOS_H = 0x999 // 2457 + SYS_CACOSF = 0x99A // 2458 + SYS___CACOSF_B = 0x99B // 2459 + SYS___CACOSF_H = 0x99C // 2460 + SYS_CACOSL = 0x99D // 2461 + SYS___CACOSL_B = 0x99E // 2462 + SYS___CACOSL_H = 0x99F // 2463 + SYS_CACOSH = 0x9A0 // 2464 + SYS___CACOSH_B = 0x9A1 // 2465 + SYS___CACOSH_H = 0x9A2 // 2466 + SYS_CACOSHF = 0x9A3 // 2467 + SYS___CACOSHF_B = 0x9A4 // 2468 + SYS___CACOSHF_H = 0x9A5 // 2469 + SYS_CACOSHL = 0x9A6 // 2470 + SYS___CACOSHL_B = 0x9A7 // 2471 + SYS___CACOSHL_H = 0x9A8 // 2472 + SYS_CARG = 0x9A9 // 2473 + SYS___CARG_B = 0x9AA // 2474 + SYS___CARG_H = 0x9AB // 2475 + SYS_CARGF = 0x9AC // 2476 + SYS___CARGF_B = 0x9AD // 2477 + SYS___CARGF_H = 0x9AE // 2478 + SYS_CARGL = 0x9AF // 2479 + SYS___CARGL_B = 0x9B0 // 2480 + SYS___CARGL_H = 0x9B1 // 2481 + SYS_CASIN = 0x9B2 // 2482 + SYS___CASIN_B = 0x9B3 // 2483 + SYS___CASIN_H = 0x9B4 // 2484 + SYS_CASINF = 0x9B5 // 2485 + SYS___CASINF_B = 0x9B6 // 2486 + SYS___CASINF_H = 0x9B7 // 2487 + SYS_CASINL = 0x9B8 // 2488 + SYS___CASINL_B = 0x9B9 // 2489 + SYS___CASINL_H = 0x9BA // 2490 + SYS_CASINH = 0x9BB // 2491 + SYS___CASINH_B = 0x9BC // 2492 + SYS___CASINH_H = 0x9BD // 2493 + SYS_CASINHF = 0x9BE // 2494 + SYS___CASINHF_B = 0x9BF // 2495 + SYS___CASINHF_H = 0x9C0 // 2496 + SYS_CASINHL = 0x9C1 // 2497 + SYS___CASINHL_B = 0x9C2 // 2498 + SYS___CASINHL_H = 0x9C3 // 2499 + SYS_CATAN = 0x9C4 // 2500 + SYS___CATAN_B = 0x9C5 // 2501 + SYS___CATAN_H = 0x9C6 // 2502 + SYS_CATANF = 0x9C7 // 2503 + SYS___CATANF_B = 0x9C8 // 2504 + SYS___CATANF_H = 0x9C9 // 2505 + SYS_CATANL = 0x9CA // 2506 + SYS___CATANL_B = 0x9CB // 2507 + SYS___CATANL_H = 0x9CC // 2508 + SYS_CATANH = 0x9CD // 2509 + SYS___CATANH_B = 0x9CE // 2510 + SYS___CATANH_H = 0x9CF // 2511 + SYS_CATANHF = 0x9D0 // 2512 + SYS___CATANHF_B = 0x9D1 // 2513 + SYS___CATANHF_H = 0x9D2 // 2514 + SYS_CATANHL = 0x9D3 // 2515 + SYS___CATANHL_B = 0x9D4 // 2516 + SYS___CATANHL_H = 0x9D5 // 2517 + SYS_CCOS = 0x9D6 // 2518 + SYS___CCOS_B = 0x9D7 // 2519 + SYS___CCOS_H = 0x9D8 // 2520 + SYS_CCOSF = 0x9D9 // 2521 + SYS___CCOSF_B = 0x9DA // 2522 + SYS___CCOSF_H = 0x9DB // 2523 + SYS_CCOSL = 0x9DC // 2524 + SYS___CCOSL_B = 0x9DD // 2525 + SYS___CCOSL_H = 0x9DE // 2526 + SYS_CCOSH = 0x9DF // 2527 + SYS___CCOSH_B = 0x9E0 // 2528 + SYS___CCOSH_H = 0x9E1 // 2529 + SYS_CCOSHF = 0x9E2 // 2530 + SYS___CCOSHF_B = 0x9E3 // 2531 + SYS___CCOSHF_H = 0x9E4 // 2532 + SYS_CCOSHL = 0x9E5 // 2533 + SYS___CCOSHL_B = 0x9E6 // 2534 + SYS___CCOSHL_H = 0x9E7 // 2535 + SYS_CEXP = 0x9E8 // 2536 + SYS___CEXP_B = 0x9E9 // 2537 + SYS___CEXP_H = 0x9EA // 2538 + SYS_CEXPF = 0x9EB // 2539 + SYS___CEXPF_B = 0x9EC // 2540 + SYS___CEXPF_H = 0x9ED // 2541 + SYS_CEXPL = 0x9EE // 2542 + SYS___CEXPL_B = 0x9EF // 2543 + SYS___CEXPL_H = 0x9F0 // 2544 + SYS_CIMAG = 0x9F1 // 2545 + SYS___CIMAG_B = 0x9F2 // 2546 + SYS___CIMAG_H = 0x9F3 // 2547 + SYS_CIMAGF = 0x9F4 // 2548 + SYS___CIMAGF_B = 0x9F5 // 2549 + SYS___CIMAGF_H = 0x9F6 // 2550 + SYS_CIMAGL = 0x9F7 // 2551 + SYS___CIMAGL_B = 0x9F8 // 2552 + SYS___CIMAGL_H = 0x9F9 // 2553 + SYS___CLOG = 0x9FA // 2554 + SYS___CLOG_B = 0x9FB // 2555 + SYS___CLOG_H = 0x9FC // 2556 + SYS_CLOGF = 0x9FD // 2557 + SYS___CLOGF_B = 0x9FE // 2558 + SYS___CLOGF_H = 0x9FF // 2559 + SYS_CLOGL = 0xA00 // 2560 + SYS___CLOGL_B = 0xA01 // 2561 + SYS___CLOGL_H = 0xA02 // 2562 + SYS_CONJ = 0xA03 // 2563 + SYS___CONJ_B = 0xA04 // 2564 + SYS___CONJ_H = 0xA05 // 2565 + SYS_CONJF = 0xA06 // 2566 + SYS___CONJF_B = 0xA07 // 2567 + SYS___CONJF_H = 0xA08 // 2568 + SYS_CONJL = 0xA09 // 2569 + SYS___CONJL_B = 0xA0A // 2570 + SYS___CONJL_H = 0xA0B // 2571 + SYS_CPOW = 0xA0C // 2572 + SYS___CPOW_B = 0xA0D // 2573 + SYS___CPOW_H = 0xA0E // 2574 + SYS_CPOWF = 0xA0F // 2575 + SYS___CPOWF_B = 0xA10 // 2576 + SYS___CPOWF_H = 0xA11 // 2577 + SYS_CPOWL = 0xA12 // 2578 + SYS___CPOWL_B = 0xA13 // 2579 + SYS___CPOWL_H = 0xA14 // 2580 + SYS_CPROJ = 0xA15 // 2581 + SYS___CPROJ_B = 0xA16 // 2582 + SYS___CPROJ_H = 0xA17 // 2583 + SYS_CPROJF = 0xA18 // 2584 + SYS___CPROJF_B = 0xA19 // 2585 + SYS___CPROJF_H = 0xA1A // 2586 + SYS_CPROJL = 0xA1B // 2587 + SYS___CPROJL_B = 0xA1C // 2588 + SYS___CPROJL_H = 0xA1D // 2589 + SYS_CREAL = 0xA1E // 2590 + SYS___CREAL_B = 0xA1F // 2591 + SYS___CREAL_H = 0xA20 // 2592 + SYS_CREALF = 0xA21 // 2593 + SYS___CREALF_B = 0xA22 // 2594 + SYS___CREALF_H = 0xA23 // 2595 + SYS_CREALL = 0xA24 // 2596 + SYS___CREALL_B = 0xA25 // 2597 + SYS___CREALL_H = 0xA26 // 2598 + SYS_CSIN = 0xA27 // 2599 + SYS___CSIN_B = 0xA28 // 2600 + SYS___CSIN_H = 0xA29 // 2601 + SYS_CSINF = 0xA2A // 2602 + SYS___CSINF_B = 0xA2B // 2603 + SYS___CSINF_H = 0xA2C // 2604 + SYS_CSINL = 0xA2D // 2605 + SYS___CSINL_B = 0xA2E // 2606 + SYS___CSINL_H = 0xA2F // 2607 + SYS_CSINH = 0xA30 // 2608 + SYS___CSINH_B = 0xA31 // 2609 + SYS___CSINH_H = 0xA32 // 2610 + SYS_CSINHF = 0xA33 // 2611 + SYS___CSINHF_B = 0xA34 // 2612 + SYS___CSINHF_H = 0xA35 // 2613 + SYS_CSINHL = 0xA36 // 2614 + SYS___CSINHL_B = 0xA37 // 2615 + SYS___CSINHL_H = 0xA38 // 2616 + SYS_CSQRT = 0xA39 // 2617 + SYS___CSQRT_B = 0xA3A // 2618 + SYS___CSQRT_H = 0xA3B // 2619 + SYS_CSQRTF = 0xA3C // 2620 + SYS___CSQRTF_B = 0xA3D // 2621 + SYS___CSQRTF_H = 0xA3E // 2622 + SYS_CSQRTL = 0xA3F // 2623 + SYS___CSQRTL_B = 0xA40 // 2624 + SYS___CSQRTL_H = 0xA41 // 2625 + SYS_CTAN = 0xA42 // 2626 + SYS___CTAN_B = 0xA43 // 2627 + SYS___CTAN_H = 0xA44 // 2628 + SYS_CTANF = 0xA45 // 2629 + SYS___CTANF_B = 0xA46 // 2630 + SYS___CTANF_H = 0xA47 // 2631 + SYS_CTANL = 0xA48 // 2632 + SYS___CTANL_B = 0xA49 // 2633 + SYS___CTANL_H = 0xA4A // 2634 + SYS_CTANH = 0xA4B // 2635 + SYS___CTANH_B = 0xA4C // 2636 + SYS___CTANH_H = 0xA4D // 2637 + SYS_CTANHF = 0xA4E // 2638 + SYS___CTANHF_B = 0xA4F // 2639 + SYS___CTANHF_H = 0xA50 // 2640 + SYS_CTANHL = 0xA51 // 2641 + SYS___CTANHL_B = 0xA52 // 2642 + SYS___CTANHL_H = 0xA53 // 2643 + SYS___ACOSHF_H = 0xA54 // 2644 + SYS___ACOSHL_H = 0xA55 // 2645 + SYS___ASINHF_H = 0xA56 // 2646 + SYS___ASINHL_H = 0xA57 // 2647 + SYS___CBRTF_H = 0xA58 // 2648 + SYS___CBRTL_H = 0xA59 // 2649 + SYS___COPYSIGN_B = 0xA5A // 2650 + SYS___EXPM1F_H = 0xA5B // 2651 + SYS___EXPM1L_H = 0xA5C // 2652 + SYS___EXP2_H = 0xA5D // 2653 + SYS___EXP2F_H = 0xA5E // 2654 + SYS___EXP2L_H = 0xA5F // 2655 + SYS___LOG1PF_H = 0xA60 // 2656 + SYS___LOG1PL_H = 0xA61 // 2657 + SYS___LGAMMAL_H = 0xA62 // 2658 + SYS_FMA = 0xA63 // 2659 + SYS___FMA_B = 0xA64 // 2660 + SYS___FMA_H = 0xA65 // 2661 + SYS_FMAF = 0xA66 // 2662 + SYS___FMAF_B = 0xA67 // 2663 + SYS___FMAF_H = 0xA68 // 2664 + SYS_FMAL = 0xA69 // 2665 + SYS___FMAL_B = 0xA6A // 2666 + SYS___FMAL_H = 0xA6B // 2667 + SYS_FMAX = 0xA6C // 2668 + SYS___FMAX_B = 0xA6D // 2669 + SYS___FMAX_H = 0xA6E // 2670 + SYS_FMAXF = 0xA6F // 2671 + SYS___FMAXF_B = 0xA70 // 2672 + SYS___FMAXF_H = 0xA71 // 2673 + SYS_FMAXL = 0xA72 // 2674 + SYS___FMAXL_B = 0xA73 // 2675 + SYS___FMAXL_H = 0xA74 // 2676 + SYS_FMIN = 0xA75 // 2677 + SYS___FMIN_B = 0xA76 // 2678 + SYS___FMIN_H = 0xA77 // 2679 + SYS_FMINF = 0xA78 // 2680 + SYS___FMINF_B = 0xA79 // 2681 + SYS___FMINF_H = 0xA7A // 2682 + SYS_FMINL = 0xA7B // 2683 + SYS___FMINL_B = 0xA7C // 2684 + SYS___FMINL_H = 0xA7D // 2685 + SYS_ILOGBF = 0xA7E // 2686 + SYS___ILOGBF_B = 0xA7F // 2687 + SYS___ILOGBF_H = 0xA80 // 2688 + SYS_ILOGBL = 0xA81 // 2689 + SYS___ILOGBL_B = 0xA82 // 2690 + SYS___ILOGBL_H = 0xA83 // 2691 + SYS_LLRINT = 0xA84 // 2692 + SYS___LLRINT_B = 0xA85 // 2693 + SYS___LLRINT_H = 0xA86 // 2694 + SYS_LLRINTF = 0xA87 // 2695 + SYS___LLRINTF_B = 0xA88 // 2696 + SYS___LLRINTF_H = 0xA89 // 2697 + SYS_LLRINTL = 0xA8A // 2698 + SYS___LLRINTL_B = 0xA8B // 2699 + SYS___LLRINTL_H = 0xA8C // 2700 + SYS_LLROUND = 0xA8D // 2701 + SYS___LLROUND_B = 0xA8E // 2702 + SYS___LLROUND_H = 0xA8F // 2703 + SYS_LLROUNDF = 0xA90 // 2704 + SYS___LLROUNDF_B = 0xA91 // 2705 + SYS___LLROUNDF_H = 0xA92 // 2706 + SYS_LLROUNDL = 0xA93 // 2707 + SYS___LLROUNDL_B = 0xA94 // 2708 + SYS___LLROUNDL_H = 0xA95 // 2709 + SYS_LOGBF = 0xA96 // 2710 + SYS___LOGBF_B = 0xA97 // 2711 + SYS___LOGBF_H = 0xA98 // 2712 + SYS_LOGBL = 0xA99 // 2713 + SYS___LOGBL_B = 0xA9A // 2714 + SYS___LOGBL_H = 0xA9B // 2715 + SYS_LRINT = 0xA9C // 2716 + SYS___LRINT_B = 0xA9D // 2717 + SYS___LRINT_H = 0xA9E // 2718 + SYS_LRINTF = 0xA9F // 2719 + SYS___LRINTF_B = 0xAA0 // 2720 + SYS___LRINTF_H = 0xAA1 // 2721 + SYS_LRINTL = 0xAA2 // 2722 + SYS___LRINTL_B = 0xAA3 // 2723 + SYS___LRINTL_H = 0xAA4 // 2724 + SYS_LROUNDL = 0xAA5 // 2725 + SYS___LROUNDL_B = 0xAA6 // 2726 + SYS___LROUNDL_H = 0xAA7 // 2727 + SYS_NAN = 0xAA8 // 2728 + SYS___NAN_B = 0xAA9 // 2729 + SYS_NANF = 0xAAA // 2730 + SYS___NANF_B = 0xAAB // 2731 + SYS_NANL = 0xAAC // 2732 + SYS___NANL_B = 0xAAD // 2733 + SYS_NEARBYINT = 0xAAE // 2734 + SYS___NEARBYINT_B = 0xAAF // 2735 + SYS___NEARBYINT_H = 0xAB0 // 2736 + SYS_NEARBYINTF = 0xAB1 // 2737 + SYS___NEARBYINTF_B = 0xAB2 // 2738 + SYS___NEARBYINTF_H = 0xAB3 // 2739 + SYS_NEARBYINTL = 0xAB4 // 2740 + SYS___NEARBYINTL_B = 0xAB5 // 2741 + SYS___NEARBYINTL_H = 0xAB6 // 2742 + SYS_NEXTAFTERF = 0xAB7 // 2743 + SYS___NEXTAFTERF_B = 0xAB8 // 2744 + SYS___NEXTAFTERF_H = 0xAB9 // 2745 + SYS_NEXTAFTERL = 0xABA // 2746 + SYS___NEXTAFTERL_B = 0xABB // 2747 + SYS___NEXTAFTERL_H = 0xABC // 2748 + SYS_NEXTTOWARD = 0xABD // 2749 + SYS___NEXTTOWARD_B = 0xABE // 2750 + SYS___NEXTTOWARD_H = 0xABF // 2751 + SYS_NEXTTOWARDF = 0xAC0 // 2752 + SYS___NEXTTOWARDF_B = 0xAC1 // 2753 + SYS___NEXTTOWARDF_H = 0xAC2 // 2754 + SYS_NEXTTOWARDL = 0xAC3 // 2755 + SYS___NEXTTOWARDL_B = 0xAC4 // 2756 + SYS___NEXTTOWARDL_H = 0xAC5 // 2757 + SYS___REMAINDERF_H = 0xAC6 // 2758 + SYS___REMAINDERL_H = 0xAC7 // 2759 + SYS___REMQUO_H = 0xAC8 // 2760 + SYS___REMQUOF_H = 0xAC9 // 2761 + SYS___REMQUOL_H = 0xACA // 2762 + SYS_RINTF = 0xACB // 2763 + SYS___RINTF_B = 0xACC // 2764 + SYS_RINTL = 0xACD // 2765 + SYS___RINTL_B = 0xACE // 2766 + SYS_ROUND = 0xACF // 2767 + SYS___ROUND_B = 0xAD0 // 2768 + SYS___ROUND_H = 0xAD1 // 2769 + SYS_ROUNDF = 0xAD2 // 2770 + SYS___ROUNDF_B = 0xAD3 // 2771 + SYS___ROUNDF_H = 0xAD4 // 2772 + SYS_ROUNDL = 0xAD5 // 2773 + SYS___ROUNDL_B = 0xAD6 // 2774 + SYS___ROUNDL_H = 0xAD7 // 2775 + SYS_SCALBLN = 0xAD8 // 2776 + SYS___SCALBLN_B = 0xAD9 // 2777 + SYS___SCALBLN_H = 0xADA // 2778 + SYS_SCALBLNF = 0xADB // 2779 + SYS___SCALBLNF_B = 0xADC // 2780 + SYS___SCALBLNF_H = 0xADD // 2781 + SYS_SCALBLNL = 0xADE // 2782 + SYS___SCALBLNL_B = 0xADF // 2783 + SYS___SCALBLNL_H = 0xAE0 // 2784 + SYS___SCALBN_B = 0xAE1 // 2785 + SYS___SCALBN_H = 0xAE2 // 2786 + SYS_SCALBNF = 0xAE3 // 2787 + SYS___SCALBNF_B = 0xAE4 // 2788 + SYS___SCALBNF_H = 0xAE5 // 2789 + SYS_SCALBNL = 0xAE6 // 2790 + SYS___SCALBNL_B = 0xAE7 // 2791 + SYS___SCALBNL_H = 0xAE8 // 2792 + SYS___TGAMMAL_H = 0xAE9 // 2793 + SYS_FECLEAREXCEPT = 0xAEA // 2794 + SYS_FEGETENV = 0xAEB // 2795 + SYS_FEGETEXCEPTFLAG = 0xAEC // 2796 + SYS_FEGETROUND = 0xAED // 2797 + SYS_FEHOLDEXCEPT = 0xAEE // 2798 + SYS_FERAISEEXCEPT = 0xAEF // 2799 + SYS_FESETENV = 0xAF0 // 2800 + SYS_FESETEXCEPTFLAG = 0xAF1 // 2801 + SYS_FESETROUND = 0xAF2 // 2802 + SYS_FETESTEXCEPT = 0xAF3 // 2803 + SYS_FEUPDATEENV = 0xAF4 // 2804 + SYS___COPYSIGN_H = 0xAF5 // 2805 + SYS___HYPOTF_H = 0xAF6 // 2806 + SYS___HYPOTL_H = 0xAF7 // 2807 + SYS___CLASS = 0xAFA // 2810 + SYS___CLASS_B = 0xAFB // 2811 + SYS___CLASS_H = 0xAFC // 2812 + SYS___ISBLANK_A = 0xB2E // 2862 + SYS___ISWBLANK_A = 0xB2F // 2863 + SYS___LROUND_FIXUP = 0xB30 // 2864 + SYS___LROUNDF_FIXUP = 0xB31 // 2865 + SYS_SCHED_YIELD = 0xB32 // 2866 + SYS_STRERROR_R = 0xB33 // 2867 + SYS_UNSETENV = 0xB34 // 2868 + SYS___LGAMMA_H_C99 = 0xB38 // 2872 + SYS___LGAMMA_B_C99 = 0xB39 // 2873 + SYS___LGAMMA_R_C99 = 0xB3A // 2874 + SYS___FTELL2 = 0xB3B // 2875 + SYS___FSEEK2 = 0xB3C // 2876 + SYS___STATIC_REINIT = 0xB3D // 2877 + SYS_PTHREAD_ATTR_GETSTACK = 0xB3E // 2878 + SYS_PTHREAD_ATTR_SETSTACK = 0xB3F // 2879 + SYS___TGAMMA_H_C99 = 0xB78 // 2936 + SYS___TGAMMAF_H_C99 = 0xB79 // 2937 + SYS___LE_TRACEBACK = 0xB7A // 2938 + SYS___MUST_STAY_CLEAN = 0xB7C // 2940 + SYS___O_ENV = 0xB7D // 2941 + SYS_ACOSD32 = 0xB7E // 2942 + SYS_ACOSD64 = 0xB7F // 2943 + SYS_ACOSD128 = 0xB80 // 2944 + SYS_ACOSHD32 = 0xB81 // 2945 + SYS_ACOSHD64 = 0xB82 // 2946 + SYS_ACOSHD128 = 0xB83 // 2947 + SYS_ASIND32 = 0xB84 // 2948 + SYS_ASIND64 = 0xB85 // 2949 + SYS_ASIND128 = 0xB86 // 2950 + SYS_ASINHD32 = 0xB87 // 2951 + SYS_ASINHD64 = 0xB88 // 2952 + SYS_ASINHD128 = 0xB89 // 2953 + SYS_ATAND32 = 0xB8A // 2954 + SYS_ATAND64 = 0xB8B // 2955 + SYS_ATAND128 = 0xB8C // 2956 + SYS_ATAN2D32 = 0xB8D // 2957 + SYS_ATAN2D64 = 0xB8E // 2958 + SYS_ATAN2D128 = 0xB8F // 2959 + SYS_ATANHD32 = 0xB90 // 2960 + SYS_ATANHD64 = 0xB91 // 2961 + SYS_ATANHD128 = 0xB92 // 2962 + SYS_CBRTD32 = 0xB93 // 2963 + SYS_CBRTD64 = 0xB94 // 2964 + SYS_CBRTD128 = 0xB95 // 2965 + SYS_CEILD32 = 0xB96 // 2966 + SYS_CEILD64 = 0xB97 // 2967 + SYS_CEILD128 = 0xB98 // 2968 + SYS___CLASS2 = 0xB99 // 2969 + SYS___CLASS2_B = 0xB9A // 2970 + SYS___CLASS2_H = 0xB9B // 2971 + SYS_COPYSIGND32 = 0xB9C // 2972 + SYS_COPYSIGND64 = 0xB9D // 2973 + SYS_COPYSIGND128 = 0xB9E // 2974 + SYS_COSD32 = 0xB9F // 2975 + SYS_COSD64 = 0xBA0 // 2976 + SYS_COSD128 = 0xBA1 // 2977 + SYS_COSHD32 = 0xBA2 // 2978 + SYS_COSHD64 = 0xBA3 // 2979 + SYS_COSHD128 = 0xBA4 // 2980 + SYS_ERFD32 = 0xBA5 // 2981 + SYS_ERFD64 = 0xBA6 // 2982 + SYS_ERFD128 = 0xBA7 // 2983 + SYS_ERFCD32 = 0xBA8 // 2984 + SYS_ERFCD64 = 0xBA9 // 2985 + SYS_ERFCD128 = 0xBAA // 2986 + SYS_EXPD32 = 0xBAB // 2987 + SYS_EXPD64 = 0xBAC // 2988 + SYS_EXPD128 = 0xBAD // 2989 + SYS_EXP2D32 = 0xBAE // 2990 + SYS_EXP2D64 = 0xBAF // 2991 + SYS_EXP2D128 = 0xBB0 // 2992 + SYS_EXPM1D32 = 0xBB1 // 2993 + SYS_EXPM1D64 = 0xBB2 // 2994 + SYS_EXPM1D128 = 0xBB3 // 2995 + SYS_FABSD32 = 0xBB4 // 2996 + SYS_FABSD64 = 0xBB5 // 2997 + SYS_FABSD128 = 0xBB6 // 2998 + SYS_FDIMD32 = 0xBB7 // 2999 + SYS_FDIMD64 = 0xBB8 // 3000 + SYS_FDIMD128 = 0xBB9 // 3001 + SYS_FE_DEC_GETROUND = 0xBBA // 3002 + SYS_FE_DEC_SETROUND = 0xBBB // 3003 + SYS_FLOORD32 = 0xBBC // 3004 + SYS_FLOORD64 = 0xBBD // 3005 + SYS_FLOORD128 = 0xBBE // 3006 + SYS_FMAD32 = 0xBBF // 3007 + SYS_FMAD64 = 0xBC0 // 3008 + SYS_FMAD128 = 0xBC1 // 3009 + SYS_FMAXD32 = 0xBC2 // 3010 + SYS_FMAXD64 = 0xBC3 // 3011 + SYS_FMAXD128 = 0xBC4 // 3012 + SYS_FMIND32 = 0xBC5 // 3013 + SYS_FMIND64 = 0xBC6 // 3014 + SYS_FMIND128 = 0xBC7 // 3015 + SYS_FMODD32 = 0xBC8 // 3016 + SYS_FMODD64 = 0xBC9 // 3017 + SYS_FMODD128 = 0xBCA // 3018 + SYS___FP_CAST_D = 0xBCB // 3019 + SYS_FREXPD32 = 0xBCC // 3020 + SYS_FREXPD64 = 0xBCD // 3021 + SYS_FREXPD128 = 0xBCE // 3022 + SYS_HYPOTD32 = 0xBCF // 3023 + SYS_HYPOTD64 = 0xBD0 // 3024 + SYS_HYPOTD128 = 0xBD1 // 3025 + SYS_ILOGBD32 = 0xBD2 // 3026 + SYS_ILOGBD64 = 0xBD3 // 3027 + SYS_ILOGBD128 = 0xBD4 // 3028 + SYS_LDEXPD32 = 0xBD5 // 3029 + SYS_LDEXPD64 = 0xBD6 // 3030 + SYS_LDEXPD128 = 0xBD7 // 3031 + SYS_LGAMMAD32 = 0xBD8 // 3032 + SYS_LGAMMAD64 = 0xBD9 // 3033 + SYS_LGAMMAD128 = 0xBDA // 3034 + SYS_LLRINTD32 = 0xBDB // 3035 + SYS_LLRINTD64 = 0xBDC // 3036 + SYS_LLRINTD128 = 0xBDD // 3037 + SYS_LLROUNDD32 = 0xBDE // 3038 + SYS_LLROUNDD64 = 0xBDF // 3039 + SYS_LLROUNDD128 = 0xBE0 // 3040 + SYS_LOGD32 = 0xBE1 // 3041 + SYS_LOGD64 = 0xBE2 // 3042 + SYS_LOGD128 = 0xBE3 // 3043 + SYS_LOG10D32 = 0xBE4 // 3044 + SYS_LOG10D64 = 0xBE5 // 3045 + SYS_LOG10D128 = 0xBE6 // 3046 + SYS_LOG1PD32 = 0xBE7 // 3047 + SYS_LOG1PD64 = 0xBE8 // 3048 + SYS_LOG1PD128 = 0xBE9 // 3049 + SYS_LOG2D32 = 0xBEA // 3050 + SYS_LOG2D64 = 0xBEB // 3051 + SYS_LOG2D128 = 0xBEC // 3052 + SYS_LOGBD32 = 0xBED // 3053 + SYS_LOGBD64 = 0xBEE // 3054 + SYS_LOGBD128 = 0xBEF // 3055 + SYS_LRINTD32 = 0xBF0 // 3056 + SYS_LRINTD64 = 0xBF1 // 3057 + SYS_LRINTD128 = 0xBF2 // 3058 + SYS_LROUNDD32 = 0xBF3 // 3059 + SYS_LROUNDD64 = 0xBF4 // 3060 + SYS_LROUNDD128 = 0xBF5 // 3061 + SYS_MODFD32 = 0xBF6 // 3062 + SYS_MODFD64 = 0xBF7 // 3063 + SYS_MODFD128 = 0xBF8 // 3064 + SYS_NAND32 = 0xBF9 // 3065 + SYS_NAND64 = 0xBFA // 3066 + SYS_NAND128 = 0xBFB // 3067 + SYS_NEARBYINTD32 = 0xBFC // 3068 + SYS_NEARBYINTD64 = 0xBFD // 3069 + SYS_NEARBYINTD128 = 0xBFE // 3070 + SYS_NEXTAFTERD32 = 0xBFF // 3071 + SYS_NEXTAFTERD64 = 0xC00 // 3072 + SYS_NEXTAFTERD128 = 0xC01 // 3073 + SYS_NEXTTOWARDD32 = 0xC02 // 3074 + SYS_NEXTTOWARDD64 = 0xC03 // 3075 + SYS_NEXTTOWARDD128 = 0xC04 // 3076 + SYS_POWD32 = 0xC05 // 3077 + SYS_POWD64 = 0xC06 // 3078 + SYS_POWD128 = 0xC07 // 3079 + SYS_QUANTIZED32 = 0xC08 // 3080 + SYS_QUANTIZED64 = 0xC09 // 3081 + SYS_QUANTIZED128 = 0xC0A // 3082 + SYS_REMAINDERD32 = 0xC0B // 3083 + SYS_REMAINDERD64 = 0xC0C // 3084 + SYS_REMAINDERD128 = 0xC0D // 3085 + SYS___REMQUOD32 = 0xC0E // 3086 + SYS___REMQUOD64 = 0xC0F // 3087 + SYS___REMQUOD128 = 0xC10 // 3088 + SYS_RINTD32 = 0xC11 // 3089 + SYS_RINTD64 = 0xC12 // 3090 + SYS_RINTD128 = 0xC13 // 3091 + SYS_ROUNDD32 = 0xC14 // 3092 + SYS_ROUNDD64 = 0xC15 // 3093 + SYS_ROUNDD128 = 0xC16 // 3094 + SYS_SAMEQUANTUMD32 = 0xC17 // 3095 + SYS_SAMEQUANTUMD64 = 0xC18 // 3096 + SYS_SAMEQUANTUMD128 = 0xC19 // 3097 + SYS_SCALBLND32 = 0xC1A // 3098 + SYS_SCALBLND64 = 0xC1B // 3099 + SYS_SCALBLND128 = 0xC1C // 3100 + SYS_SCALBND32 = 0xC1D // 3101 + SYS_SCALBND64 = 0xC1E // 3102 + SYS_SCALBND128 = 0xC1F // 3103 + SYS_SIND32 = 0xC20 // 3104 + SYS_SIND64 = 0xC21 // 3105 + SYS_SIND128 = 0xC22 // 3106 + SYS_SINHD32 = 0xC23 // 3107 + SYS_SINHD64 = 0xC24 // 3108 + SYS_SINHD128 = 0xC25 // 3109 + SYS_SQRTD32 = 0xC26 // 3110 + SYS_SQRTD64 = 0xC27 // 3111 + SYS_SQRTD128 = 0xC28 // 3112 + SYS_STRTOD32 = 0xC29 // 3113 + SYS_STRTOD64 = 0xC2A // 3114 + SYS_STRTOD128 = 0xC2B // 3115 + SYS_TAND32 = 0xC2C // 3116 + SYS_TAND64 = 0xC2D // 3117 + SYS_TAND128 = 0xC2E // 3118 + SYS_TANHD32 = 0xC2F // 3119 + SYS_TANHD64 = 0xC30 // 3120 + SYS_TANHD128 = 0xC31 // 3121 + SYS_TGAMMAD32 = 0xC32 // 3122 + SYS_TGAMMAD64 = 0xC33 // 3123 + SYS_TGAMMAD128 = 0xC34 // 3124 + SYS_TRUNCD32 = 0xC3E // 3134 + SYS_TRUNCD64 = 0xC3F // 3135 + SYS_TRUNCD128 = 0xC40 // 3136 + SYS_WCSTOD32 = 0xC41 // 3137 + SYS_WCSTOD64 = 0xC42 // 3138 + SYS_WCSTOD128 = 0xC43 // 3139 + SYS___CODEPAGE_INFO = 0xC64 // 3172 + SYS_POSIX_OPENPT = 0xC66 // 3174 + SYS_PSELECT = 0xC67 // 3175 + SYS_SOCKATMARK = 0xC68 // 3176 + SYS_AIO_FSYNC = 0xC69 // 3177 + SYS_LIO_LISTIO = 0xC6A // 3178 + SYS___ATANPID32 = 0xC6B // 3179 + SYS___ATANPID64 = 0xC6C // 3180 + SYS___ATANPID128 = 0xC6D // 3181 + SYS___COSPID32 = 0xC6E // 3182 + SYS___COSPID64 = 0xC6F // 3183 + SYS___COSPID128 = 0xC70 // 3184 + SYS___SINPID32 = 0xC71 // 3185 + SYS___SINPID64 = 0xC72 // 3186 + SYS___SINPID128 = 0xC73 // 3187 + SYS_SETIPV4SOURCEFILTER = 0xC76 // 3190 + SYS_GETIPV4SOURCEFILTER = 0xC77 // 3191 + SYS_SETSOURCEFILTER = 0xC78 // 3192 + SYS_GETSOURCEFILTER = 0xC79 // 3193 + SYS_FWRITE_UNLOCKED = 0xC7A // 3194 + SYS_FREAD_UNLOCKED = 0xC7B // 3195 + SYS_FGETS_UNLOCKED = 0xC7C // 3196 + SYS_GETS_UNLOCKED = 0xC7D // 3197 + SYS_FPUTS_UNLOCKED = 0xC7E // 3198 + SYS_PUTS_UNLOCKED = 0xC7F // 3199 + SYS_FGETC_UNLOCKED = 0xC80 // 3200 + SYS_FPUTC_UNLOCKED = 0xC81 // 3201 + SYS_DLADDR = 0xC82 // 3202 + SYS_SHM_OPEN = 0xC8C // 3212 + SYS_SHM_UNLINK = 0xC8D // 3213 + SYS___CLASS2F = 0xC91 // 3217 + SYS___CLASS2L = 0xC92 // 3218 + SYS___CLASS2F_B = 0xC93 // 3219 + SYS___CLASS2F_H = 0xC94 // 3220 + SYS___CLASS2L_B = 0xC95 // 3221 + SYS___CLASS2L_H = 0xC96 // 3222 + SYS___CLASS2D32 = 0xC97 // 3223 + SYS___CLASS2D64 = 0xC98 // 3224 + SYS___CLASS2D128 = 0xC99 // 3225 + SYS___TOCSNAME2 = 0xC9A // 3226 + SYS___D1TOP = 0xC9B // 3227 + SYS___D2TOP = 0xC9C // 3228 + SYS___D4TOP = 0xC9D // 3229 + SYS___PTOD1 = 0xC9E // 3230 + SYS___PTOD2 = 0xC9F // 3231 + SYS___PTOD4 = 0xCA0 // 3232 + SYS_CLEARERR_UNLOCKED = 0xCA1 // 3233 + SYS_FDELREC_UNLOCKED = 0xCA2 // 3234 + SYS_FEOF_UNLOCKED = 0xCA3 // 3235 + SYS_FERROR_UNLOCKED = 0xCA4 // 3236 + SYS_FFLUSH_UNLOCKED = 0xCA5 // 3237 + SYS_FGETPOS_UNLOCKED = 0xCA6 // 3238 + SYS_FGETWC_UNLOCKED = 0xCA7 // 3239 + SYS_FGETWS_UNLOCKED = 0xCA8 // 3240 + SYS_FILENO_UNLOCKED = 0xCA9 // 3241 + SYS_FLDATA_UNLOCKED = 0xCAA // 3242 + SYS_FLOCATE_UNLOCKED = 0xCAB // 3243 + SYS_FPRINTF_UNLOCKED = 0xCAC // 3244 + SYS_FPUTWC_UNLOCKED = 0xCAD // 3245 + SYS_FPUTWS_UNLOCKED = 0xCAE // 3246 + SYS_FSCANF_UNLOCKED = 0xCAF // 3247 + SYS_FSEEK_UNLOCKED = 0xCB0 // 3248 + SYS_FSEEKO_UNLOCKED = 0xCB1 // 3249 + SYS_FSETPOS_UNLOCKED = 0xCB3 // 3251 + SYS_FTELL_UNLOCKED = 0xCB4 // 3252 + SYS_FTELLO_UNLOCKED = 0xCB5 // 3253 + SYS_FUPDATE_UNLOCKED = 0xCB7 // 3255 + SYS_FWIDE_UNLOCKED = 0xCB8 // 3256 + SYS_FWPRINTF_UNLOCKED = 0xCB9 // 3257 + SYS_FWSCANF_UNLOCKED = 0xCBA // 3258 + SYS_GETWC_UNLOCKED = 0xCBB // 3259 + SYS_GETWCHAR_UNLOCKED = 0xCBC // 3260 + SYS_PERROR_UNLOCKED = 0xCBD // 3261 + SYS_PRINTF_UNLOCKED = 0xCBE // 3262 + SYS_PUTWC_UNLOCKED = 0xCBF // 3263 + SYS_PUTWCHAR_UNLOCKED = 0xCC0 // 3264 + SYS_REWIND_UNLOCKED = 0xCC1 // 3265 + SYS_SCANF_UNLOCKED = 0xCC2 // 3266 + SYS_UNGETC_UNLOCKED = 0xCC3 // 3267 + SYS_UNGETWC_UNLOCKED = 0xCC4 // 3268 + SYS_VFPRINTF_UNLOCKED = 0xCC5 // 3269 + SYS_VFSCANF_UNLOCKED = 0xCC7 // 3271 + SYS_VFWPRINTF_UNLOCKED = 0xCC9 // 3273 + SYS_VFWSCANF_UNLOCKED = 0xCCB // 3275 + SYS_VPRINTF_UNLOCKED = 0xCCD // 3277 + SYS_VSCANF_UNLOCKED = 0xCCF // 3279 + SYS_VWPRINTF_UNLOCKED = 0xCD1 // 3281 + SYS_VWSCANF_UNLOCKED = 0xCD3 // 3283 + SYS_WPRINTF_UNLOCKED = 0xCD5 // 3285 + SYS_WSCANF_UNLOCKED = 0xCD6 // 3286 + SYS_ASCTIME64 = 0xCD7 // 3287 + SYS_ASCTIME64_R = 0xCD8 // 3288 + SYS_CTIME64 = 0xCD9 // 3289 + SYS_CTIME64_R = 0xCDA // 3290 + SYS_DIFFTIME64 = 0xCDB // 3291 + SYS_GMTIME64 = 0xCDC // 3292 + SYS_GMTIME64_R = 0xCDD // 3293 + SYS_LOCALTIME64 = 0xCDE // 3294 + SYS_LOCALTIME64_R = 0xCDF // 3295 + SYS_MKTIME64 = 0xCE0 // 3296 + SYS_TIME64 = 0xCE1 // 3297 + SYS___LOGIN_APPLID = 0xCE2 // 3298 + SYS___PASSWD_APPLID = 0xCE3 // 3299 + SYS_PTHREAD_SECURITY_APPLID_NP = 0xCE4 // 3300 + SYS___GETTHENT = 0xCE5 // 3301 + SYS_FREEIFADDRS = 0xCE6 // 3302 + SYS_GETIFADDRS = 0xCE7 // 3303 + SYS_POSIX_FALLOCATE = 0xCE8 // 3304 + SYS_POSIX_MEMALIGN = 0xCE9 // 3305 + SYS_SIZEOF_ALLOC = 0xCEA // 3306 + SYS_RESIZE_ALLOC = 0xCEB // 3307 + SYS_FREAD_NOUPDATE = 0xCEC // 3308 + SYS_FREAD_NOUPDATE_UNLOCKED = 0xCED // 3309 + SYS_FGETPOS64 = 0xCEE // 3310 + SYS_FSEEK64 = 0xCEF // 3311 + SYS_FSEEKO64 = 0xCF0 // 3312 + SYS_FSETPOS64 = 0xCF1 // 3313 + SYS_FTELL64 = 0xCF2 // 3314 + SYS_FTELLO64 = 0xCF3 // 3315 + SYS_FGETPOS64_UNLOCKED = 0xCF4 // 3316 + SYS_FSEEK64_UNLOCKED = 0xCF5 // 3317 + SYS_FSEEKO64_UNLOCKED = 0xCF6 // 3318 + SYS_FSETPOS64_UNLOCKED = 0xCF7 // 3319 + SYS_FTELL64_UNLOCKED = 0xCF8 // 3320 + SYS_FTELLO64_UNLOCKED = 0xCF9 // 3321 + SYS_FOPEN_UNLOCKED = 0xCFA // 3322 + SYS_FREOPEN_UNLOCKED = 0xCFB // 3323 + SYS_FDOPEN_UNLOCKED = 0xCFC // 3324 + SYS_TMPFILE_UNLOCKED = 0xCFD // 3325 + SYS___MOSERVICES = 0xD3D // 3389 + SYS___GETTOD = 0xD3E // 3390 + SYS_C16RTOMB = 0xD40 // 3392 + SYS_C32RTOMB = 0xD41 // 3393 + SYS_MBRTOC16 = 0xD42 // 3394 + SYS_MBRTOC32 = 0xD43 // 3395 + SYS_QUANTEXPD32 = 0xD44 // 3396 + SYS_QUANTEXPD64 = 0xD45 // 3397 + SYS_QUANTEXPD128 = 0xD46 // 3398 + SYS___LOCALE_CTL = 0xD47 // 3399 + SYS___SMF_RECORD2 = 0xD48 // 3400 + SYS_FOPEN64 = 0xD49 // 3401 + SYS_FOPEN64_UNLOCKED = 0xD4A // 3402 + SYS_FREOPEN64 = 0xD4B // 3403 + SYS_FREOPEN64_UNLOCKED = 0xD4C // 3404 + SYS_TMPFILE64 = 0xD4D // 3405 + SYS_TMPFILE64_UNLOCKED = 0xD4E // 3406 + SYS_GETDATE64 = 0xD4F // 3407 + SYS_GETTIMEOFDAY64 = 0xD50 // 3408 + SYS_BIND2ADDRSEL = 0xD59 // 3417 + SYS_INET6_IS_SRCADDR = 0xD5A // 3418 + SYS___GETGRGID1 = 0xD5B // 3419 + SYS___GETGRNAM1 = 0xD5C // 3420 + SYS___FBUFSIZE = 0xD60 // 3424 + SYS___FPENDING = 0xD61 // 3425 + SYS___FLBF = 0xD62 // 3426 + SYS___FREADABLE = 0xD63 // 3427 + SYS___FWRITABLE = 0xD64 // 3428 + SYS___FREADING = 0xD65 // 3429 + SYS___FWRITING = 0xD66 // 3430 + SYS___FSETLOCKING = 0xD67 // 3431 + SYS__FLUSHLBF = 0xD68 // 3432 + SYS___FPURGE = 0xD69 // 3433 + SYS___FREADAHEAD = 0xD6A // 3434 + SYS___FSETERR = 0xD6B // 3435 + SYS___FPENDING_UNLOCKED = 0xD6C // 3436 + SYS___FREADING_UNLOCKED = 0xD6D // 3437 + SYS___FWRITING_UNLOCKED = 0xD6E // 3438 + SYS__FLUSHLBF_UNLOCKED = 0xD6F // 3439 + SYS___FPURGE_UNLOCKED = 0xD70 // 3440 + SYS___FREADAHEAD_UNLOCKED = 0xD71 // 3441 + SYS___LE_CEEGTJS = 0xD72 // 3442 + SYS___LE_RECORD_DUMP = 0xD73 // 3443 + SYS_FSTAT64 = 0xD74 // 3444 + SYS_LSTAT64 = 0xD75 // 3445 + SYS_STAT64 = 0xD76 // 3446 + SYS___READDIR2_64 = 0xD77 // 3447 + SYS___OPEN_STAT64 = 0xD78 // 3448 + SYS_FTW64 = 0xD79 // 3449 + SYS_NFTW64 = 0xD7A // 3450 + SYS_UTIME64 = 0xD7B // 3451 + SYS_UTIMES64 = 0xD7C // 3452 + SYS___GETIPC64 = 0xD7D // 3453 + SYS_MSGCTL64 = 0xD7E // 3454 + SYS_SEMCTL64 = 0xD7F // 3455 + SYS_SHMCTL64 = 0xD80 // 3456 + SYS_MSGXRCV64 = 0xD81 // 3457 + SYS___MGXR64 = 0xD81 // 3457 + SYS_W_GETPSENT64 = 0xD82 // 3458 + SYS_PTHREAD_COND_TIMEDWAIT64 = 0xD83 // 3459 + SYS_FTIME64 = 0xD85 // 3461 + SYS_GETUTXENT64 = 0xD86 // 3462 + SYS_GETUTXID64 = 0xD87 // 3463 + SYS_GETUTXLINE64 = 0xD88 // 3464 + SYS_PUTUTXLINE64 = 0xD89 // 3465 + SYS_NEWLOCALE = 0xD8A // 3466 + SYS_FREELOCALE = 0xD8B // 3467 + SYS_USELOCALE = 0xD8C // 3468 + SYS_DUPLOCALE = 0xD8D // 3469 + SYS___CHATTR64 = 0xD9C // 3484 + SYS___LCHATTR64 = 0xD9D // 3485 + SYS___FCHATTR64 = 0xD9E // 3486 + SYS_____CHATTR64_A = 0xD9F // 3487 + SYS_____LCHATTR64_A = 0xDA0 // 3488 + SYS___LE_CEEUSGD = 0xDA1 // 3489 + SYS___LE_IFAM_CON = 0xDA2 // 3490 + SYS___LE_IFAM_DSC = 0xDA3 // 3491 + SYS___LE_IFAM_GET = 0xDA4 // 3492 + SYS___LE_IFAM_QRY = 0xDA5 // 3493 + SYS_ALIGNED_ALLOC = 0xDA6 // 3494 + SYS_ACCEPT4 = 0xDA7 // 3495 + SYS___ACCEPT4_A = 0xDA8 // 3496 + SYS_COPYFILERANGE = 0xDA9 // 3497 + SYS_GETLINE = 0xDAA // 3498 + SYS___GETLINE_A = 0xDAB // 3499 + SYS_DIRFD = 0xDAC // 3500 + SYS_CLOCK_GETTIME = 0xDAD // 3501 + SYS_DUP3 = 0xDAE // 3502 + SYS_EPOLL_CREATE = 0xDAF // 3503 + SYS_EPOLL_CREATE1 = 0xDB0 // 3504 + SYS_EPOLL_CTL = 0xDB1 // 3505 + SYS_EPOLL_WAIT = 0xDB2 // 3506 + SYS_EPOLL_PWAIT = 0xDB3 // 3507 + SYS_EVENTFD = 0xDB4 // 3508 + SYS_STATFS = 0xDB5 // 3509 + SYS___STATFS_A = 0xDB6 // 3510 + SYS_FSTATFS = 0xDB7 // 3511 + SYS_INOTIFY_INIT = 0xDB8 // 3512 + SYS_INOTIFY_INIT1 = 0xDB9 // 3513 + SYS_INOTIFY_ADD_WATCH = 0xDBA // 3514 + SYS___INOTIFY_ADD_WATCH_A = 0xDBB // 3515 + SYS_INOTIFY_RM_WATCH = 0xDBC // 3516 + SYS_PIPE2 = 0xDBD // 3517 + SYS_PIVOT_ROOT = 0xDBE // 3518 + SYS___PIVOT_ROOT_A = 0xDBF // 3519 + SYS_PRCTL = 0xDC0 // 3520 + SYS_PRLIMIT = 0xDC1 // 3521 + SYS_SETHOSTNAME = 0xDC2 // 3522 + SYS___SETHOSTNAME_A = 0xDC3 // 3523 + SYS_SETRESUID = 0xDC4 // 3524 + SYS_SETRESGID = 0xDC5 // 3525 + SYS_PTHREAD_CONDATTR_GETCLOCK = 0xDC6 // 3526 + SYS_FLOCK = 0xDC7 // 3527 + SYS_FGETXATTR = 0xDC8 // 3528 + SYS___FGETXATTR_A = 0xDC9 // 3529 + SYS_FLISTXATTR = 0xDCA // 3530 + SYS___FLISTXATTR_A = 0xDCB // 3531 + SYS_FREMOVEXATTR = 0xDCC // 3532 + SYS___FREMOVEXATTR_A = 0xDCD // 3533 + SYS_FSETXATTR = 0xDCE // 3534 + SYS___FSETXATTR_A = 0xDCF // 3535 + SYS_GETXATTR = 0xDD0 // 3536 + SYS___GETXATTR_A = 0xDD1 // 3537 + SYS_LGETXATTR = 0xDD2 // 3538 + SYS___LGETXATTR_A = 0xDD3 // 3539 + SYS_LISTXATTR = 0xDD4 // 3540 + SYS___LISTXATTR_A = 0xDD5 // 3541 + SYS_LLISTXATTR = 0xDD6 // 3542 + SYS___LLISTXATTR_A = 0xDD7 // 3543 + SYS_LREMOVEXATTR = 0xDD8 // 3544 + SYS___LREMOVEXATTR_A = 0xDD9 // 3545 + SYS_LSETXATTR = 0xDDA // 3546 + SYS___LSETXATTR_A = 0xDDB // 3547 + SYS_REMOVEXATTR = 0xDDC // 3548 + SYS___REMOVEXATTR_A = 0xDDD // 3549 + SYS_SETXATTR = 0xDDE // 3550 + SYS___SETXATTR_A = 0xDDF // 3551 + SYS_FDATASYNC = 0xDE0 // 3552 + SYS_SYNCFS = 0xDE1 // 3553 + SYS_FUTIMES = 0xDE2 // 3554 + SYS_FUTIMESAT = 0xDE3 // 3555 + SYS___FUTIMESAT_A = 0xDE4 // 3556 + SYS_LUTIMES = 0xDE5 // 3557 + SYS___LUTIMES_A = 0xDE6 // 3558 + SYS_INET_ATON = 0xDE7 // 3559 + SYS_GETRANDOM = 0xDE8 // 3560 + SYS_GETTID = 0xDE9 // 3561 + SYS_MEMFD_CREATE = 0xDEA // 3562 + SYS___MEMFD_CREATE_A = 0xDEB // 3563 + SYS_FACCESSAT = 0xDEC // 3564 + SYS___FACCESSAT_A = 0xDED // 3565 + SYS_FCHMODAT = 0xDEE // 3566 + SYS___FCHMODAT_A = 0xDEF // 3567 + SYS_FCHOWNAT = 0xDF0 // 3568 + SYS___FCHOWNAT_A = 0xDF1 // 3569 + SYS_FSTATAT = 0xDF2 // 3570 + SYS___FSTATAT_A = 0xDF3 // 3571 + SYS_LINKAT = 0xDF4 // 3572 + SYS___LINKAT_A = 0xDF5 // 3573 + SYS_MKDIRAT = 0xDF6 // 3574 + SYS___MKDIRAT_A = 0xDF7 // 3575 + SYS_MKFIFOAT = 0xDF8 // 3576 + SYS___MKFIFOAT_A = 0xDF9 // 3577 + SYS_MKNODAT = 0xDFA // 3578 + SYS___MKNODAT_A = 0xDFB // 3579 + SYS_OPENAT = 0xDFC // 3580 + SYS___OPENAT_A = 0xDFD // 3581 + SYS_READLINKAT = 0xDFE // 3582 + SYS___READLINKAT_A = 0xDFF // 3583 + SYS_RENAMEAT = 0xE00 // 3584 + SYS___RENAMEAT_A = 0xE01 // 3585 + SYS_RENAMEAT2 = 0xE02 // 3586 + SYS___RENAMEAT2_A = 0xE03 // 3587 + SYS_SYMLINKAT = 0xE04 // 3588 + SYS___SYMLINKAT_A = 0xE05 // 3589 + SYS_UNLINKAT = 0xE06 // 3590 + SYS___UNLINKAT_A = 0xE07 // 3591 + SYS_SYSINFO = 0xE08 // 3592 + SYS_WAIT4 = 0xE0A // 3594 + SYS_CLONE = 0xE0B // 3595 + SYS_UNSHARE = 0xE0C // 3596 + SYS_SETNS = 0xE0D // 3597 + SYS_CAPGET = 0xE0E // 3598 + SYS_CAPSET = 0xE0F // 3599 + SYS_STRCHRNUL = 0xE10 // 3600 + SYS_PTHREAD_CONDATTR_SETCLOCK = 0xE12 // 3602 + SYS_OPEN_BY_HANDLE_AT = 0xE13 // 3603 + SYS___OPEN_BY_HANDLE_AT_A = 0xE14 // 3604 + SYS___INET_ATON_A = 0xE15 // 3605 + SYS_MOUNT1 = 0xE16 // 3606 + SYS___MOUNT1_A = 0xE17 // 3607 + SYS_UMOUNT1 = 0xE18 // 3608 + SYS___UMOUNT1_A = 0xE19 // 3609 + SYS_UMOUNT2 = 0xE1A // 3610 + SYS___UMOUNT2_A = 0xE1B // 3611 + SYS___PRCTL_A = 0xE1C // 3612 + SYS_LOCALTIME_R2 = 0xE1D // 3613 + SYS___LOCALTIME_R2_A = 0xE1E // 3614 + SYS_OPENAT2 = 0xE1F // 3615 + SYS___OPENAT2_A = 0xE20 // 3616 + SYS___LE_CEEMICT = 0xE21 // 3617 + SYS_GETENTROPY = 0xE22 // 3618 + SYS_NANOSLEEP = 0xE23 // 3619 + SYS_UTIMENSAT = 0xE24 // 3620 + SYS___UTIMENSAT_A = 0xE25 // 3621 + SYS_ASPRINTF = 0xE26 // 3622 + SYS___ASPRINTF_A = 0xE27 // 3623 + SYS_VASPRINTF = 0xE28 // 3624 + SYS___VASPRINTF_A = 0xE29 // 3625 + SYS_DPRINTF = 0xE2A // 3626 + SYS___DPRINTF_A = 0xE2B // 3627 + SYS_GETOPT_LONG = 0xE2C // 3628 + SYS___GETOPT_LONG_A = 0xE2D // 3629 + SYS_PSIGNAL = 0xE2E // 3630 + SYS___PSIGNAL_A = 0xE2F // 3631 + SYS_PSIGNAL_UNLOCKED = 0xE30 // 3632 + SYS___PSIGNAL_UNLOCKED_A = 0xE31 // 3633 + SYS_FSTATAT_O = 0xE32 // 3634 + SYS___FSTATAT_O_A = 0xE33 // 3635 + SYS_FSTATAT64 = 0xE34 // 3636 + SYS___FSTATAT64_A = 0xE35 // 3637 + SYS___CHATTRAT = 0xE36 // 3638 + SYS_____CHATTRAT_A = 0xE37 // 3639 + SYS___CHATTRAT64 = 0xE38 // 3640 + SYS_____CHATTRAT64_A = 0xE39 // 3641 + SYS_MADVISE = 0xE3A // 3642 + SYS___AUTHENTICATE = 0xE3B // 3643 + ) diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go b/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go index 7a8161c1d..3e6d57cae 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && aix -// +build ppc,aix package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go index 07ed733c5..3a219bdce 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && aix -// +build ppc64,aix package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go index 690cefc3d..091d107f3 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && darwin -// +build amd64,darwin package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go index 5bffc10ea..28ff4ef74 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && darwin -// +build arm64,darwin package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go index d0ba8e9b8..30e405bb4 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && dragonfly -// +build amd64,dragonfly package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go index 29dc48337..6cbd094a3 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && freebsd -// +build 386,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go index 0a89b2890..7c03b6ee7 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && freebsd -// +build amd64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go index c8666bb15..422107ee8 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && freebsd -// +build arm,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go index 88fb48a88..505a12acf 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && freebsd -// +build arm64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go index 698dc975e..cc986c790 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && freebsd -// +build riscv64,freebsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go index 18aa70b42..b102b95a0 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -1,7 +1,6 @@ // Code generated by mkmerge; DO NOT EDIT. //go:build linux -// +build linux package unix @@ -111,7 +110,8 @@ type Statx_t struct { Mnt_id uint64 Dio_mem_align uint32 Dio_offset_align uint32 - _ [12]uint64 + Subvol uint64 + _ [11]uint64 } type Fsid struct { @@ -175,7 +175,8 @@ type FscryptPolicyV2 struct { Contents_encryption_mode uint8 Filenames_encryption_mode uint8 Flags uint8 - _ [4]uint8 + Log2_data_unit_size uint8 + _ [3]uint8 Master_key_identifier [16]uint8 } @@ -456,60 +457,63 @@ type Ucred struct { } type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 - Pacing_rate uint64 - Max_pacing_rate uint64 - Bytes_acked uint64 - Bytes_received uint64 - Segs_out uint32 - Segs_in uint32 - Notsent_bytes uint32 - Min_rtt uint32 - Data_segs_in uint32 - Data_segs_out uint32 - Delivery_rate uint64 - Busy_time uint64 - Rwnd_limited uint64 - Sndbuf_limited uint64 - Delivered uint32 - Delivered_ce uint32 - Bytes_sent uint64 - Bytes_retrans uint64 - Dsack_dups uint32 - Reord_seen uint32 - Rcv_ooopack uint32 - Snd_wnd uint32 - Rcv_wnd uint32 - Rehash uint32 + State uint8 + Ca_state uint8 + Retransmits uint8 + Probes uint8 + Backoff uint8 + Options uint8 + Rto uint32 + Ato uint32 + Snd_mss uint32 + Rcv_mss uint32 + Unacked uint32 + Sacked uint32 + Lost uint32 + Retrans uint32 + Fackets uint32 + Last_data_sent uint32 + Last_ack_sent uint32 + Last_data_recv uint32 + Last_ack_recv uint32 + Pmtu uint32 + Rcv_ssthresh uint32 + Rtt uint32 + Rttvar uint32 + Snd_ssthresh uint32 + Snd_cwnd uint32 + Advmss uint32 + Reordering uint32 + Rcv_rtt uint32 + Rcv_space uint32 + Total_retrans uint32 + Pacing_rate uint64 + Max_pacing_rate uint64 + Bytes_acked uint64 + Bytes_received uint64 + Segs_out uint32 + Segs_in uint32 + Notsent_bytes uint32 + Min_rtt uint32 + Data_segs_in uint32 + Data_segs_out uint32 + Delivery_rate uint64 + Busy_time uint64 + Rwnd_limited uint64 + Sndbuf_limited uint64 + Delivered uint32 + Delivered_ce uint32 + Bytes_sent uint64 + Bytes_retrans uint64 + Dsack_dups uint32 + Reord_seen uint32 + Rcv_ooopack uint32 + Snd_wnd uint32 + Rcv_wnd uint32 + Rehash uint32 + Total_rto uint16 + Total_rto_recoveries uint16 + Total_rto_time uint32 } type CanFilter struct { @@ -552,7 +556,7 @@ const ( SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc - SizeofTCPInfo = 0xf0 + SizeofTCPInfo = 0xf8 SizeofCanFilter = 0x8 SizeofTCPRepairOpt = 0x8 ) @@ -833,6 +837,15 @@ const ( FSPICK_EMPTY_PATH = 0x8 FSMOUNT_CLOEXEC = 0x1 + + FSCONFIG_SET_FLAG = 0x0 + FSCONFIG_SET_STRING = 0x1 + FSCONFIG_SET_BINARY = 0x2 + FSCONFIG_SET_PATH = 0x3 + FSCONFIG_SET_PATH_EMPTY = 0x4 + FSCONFIG_SET_FD = 0x5 + FSCONFIG_CMD_CREATE = 0x6 + FSCONFIG_CMD_RECONFIGURE = 0x7 ) type OpenHow struct { @@ -1166,7 +1179,8 @@ const ( PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT = 0x10 PERF_SAMPLE_BRANCH_HW_INDEX_SHIFT = 0x11 PERF_SAMPLE_BRANCH_PRIV_SAVE_SHIFT = 0x12 - PERF_SAMPLE_BRANCH_MAX_SHIFT = 0x13 + PERF_SAMPLE_BRANCH_COUNTERS = 0x80000 + PERF_SAMPLE_BRANCH_MAX_SHIFT = 0x14 PERF_SAMPLE_BRANCH_USER = 0x1 PERF_SAMPLE_BRANCH_KERNEL = 0x2 PERF_SAMPLE_BRANCH_HV = 0x4 @@ -1186,7 +1200,7 @@ const ( PERF_SAMPLE_BRANCH_TYPE_SAVE = 0x10000 PERF_SAMPLE_BRANCH_HW_INDEX = 0x20000 PERF_SAMPLE_BRANCH_PRIV_SAVE = 0x40000 - PERF_SAMPLE_BRANCH_MAX = 0x80000 + PERF_SAMPLE_BRANCH_MAX = 0x100000 PERF_BR_UNKNOWN = 0x0 PERF_BR_COND = 0x1 PERF_BR_UNCOND = 0x2 @@ -1547,6 +1561,7 @@ const ( IFLA_DEVLINK_PORT = 0x3e IFLA_GSO_IPV4_MAX_SIZE = 0x3f IFLA_GRO_IPV4_MAX_SIZE = 0x40 + IFLA_DPLL_PIN = 0x41 IFLA_PROTO_DOWN_REASON_UNSPEC = 0x0 IFLA_PROTO_DOWN_REASON_MASK = 0x1 IFLA_PROTO_DOWN_REASON_VALUE = 0x2 @@ -1562,6 +1577,7 @@ const ( IFLA_INET6_ICMP6STATS = 0x6 IFLA_INET6_TOKEN = 0x7 IFLA_INET6_ADDR_GEN_MODE = 0x8 + IFLA_INET6_RA_MTU = 0x9 IFLA_BR_UNSPEC = 0x0 IFLA_BR_FORWARD_DELAY = 0x1 IFLA_BR_HELLO_TIME = 0x2 @@ -1609,6 +1625,9 @@ const ( IFLA_BR_MCAST_MLD_VERSION = 0x2c IFLA_BR_VLAN_STATS_PER_PORT = 0x2d IFLA_BR_MULTI_BOOLOPT = 0x2e + IFLA_BR_MCAST_QUERIER_STATE = 0x2f + IFLA_BR_FDB_N_LEARNED = 0x30 + IFLA_BR_FDB_MAX_LEARNED = 0x31 IFLA_BRPORT_UNSPEC = 0x0 IFLA_BRPORT_STATE = 0x1 IFLA_BRPORT_PRIORITY = 0x2 @@ -1646,6 +1665,14 @@ const ( IFLA_BRPORT_BACKUP_PORT = 0x22 IFLA_BRPORT_MRP_RING_OPEN = 0x23 IFLA_BRPORT_MRP_IN_OPEN = 0x24 + IFLA_BRPORT_MCAST_EHT_HOSTS_LIMIT = 0x25 + IFLA_BRPORT_MCAST_EHT_HOSTS_CNT = 0x26 + IFLA_BRPORT_LOCKED = 0x27 + IFLA_BRPORT_MAB = 0x28 + IFLA_BRPORT_MCAST_N_GROUPS = 0x29 + IFLA_BRPORT_MCAST_MAX_GROUPS = 0x2a + IFLA_BRPORT_NEIGH_VLAN_SUPPRESS = 0x2b + IFLA_BRPORT_BACKUP_NHID = 0x2c IFLA_INFO_UNSPEC = 0x0 IFLA_INFO_KIND = 0x1 IFLA_INFO_DATA = 0x2 @@ -1667,6 +1694,9 @@ const ( IFLA_MACVLAN_MACADDR = 0x4 IFLA_MACVLAN_MACADDR_DATA = 0x5 IFLA_MACVLAN_MACADDR_COUNT = 0x6 + IFLA_MACVLAN_BC_QUEUE_LEN = 0x7 + IFLA_MACVLAN_BC_QUEUE_LEN_USED = 0x8 + IFLA_MACVLAN_BC_CUTOFF = 0x9 IFLA_VRF_UNSPEC = 0x0 IFLA_VRF_TABLE = 0x1 IFLA_VRF_PORT_UNSPEC = 0x0 @@ -1690,9 +1720,22 @@ const ( IFLA_XFRM_UNSPEC = 0x0 IFLA_XFRM_LINK = 0x1 IFLA_XFRM_IF_ID = 0x2 + IFLA_XFRM_COLLECT_METADATA = 0x3 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 + IFLA_NETKIT_POLICY = 0x3 + IFLA_NETKIT_PEER_POLICY = 0x4 + IFLA_NETKIT_MODE = 0x5 IFLA_VXLAN_UNSPEC = 0x0 IFLA_VXLAN_ID = 0x1 IFLA_VXLAN_GROUP = 0x2 @@ -1723,6 +1766,8 @@ const ( IFLA_VXLAN_GPE = 0x1b IFLA_VXLAN_TTL_INHERIT = 0x1c IFLA_VXLAN_DF = 0x1d + IFLA_VXLAN_VNIFILTER = 0x1e + IFLA_VXLAN_LOCALBYPASS = 0x1f IFLA_GENEVE_UNSPEC = 0x0 IFLA_GENEVE_ID = 0x1 IFLA_GENEVE_REMOTE = 0x2 @@ -1737,6 +1782,7 @@ const ( IFLA_GENEVE_LABEL = 0xb IFLA_GENEVE_TTL_INHERIT = 0xc IFLA_GENEVE_DF = 0xd + IFLA_GENEVE_INNER_PROTO_INHERIT = 0xe IFLA_BAREUDP_UNSPEC = 0x0 IFLA_BAREUDP_PORT = 0x1 IFLA_BAREUDP_ETHERTYPE = 0x2 @@ -1749,6 +1795,8 @@ const ( IFLA_GTP_FD1 = 0x2 IFLA_GTP_PDP_HASHSIZE = 0x3 IFLA_GTP_ROLE = 0x4 + IFLA_GTP_CREATE_SOCKETS = 0x5 + IFLA_GTP_RESTART_COUNT = 0x6 IFLA_BOND_UNSPEC = 0x0 IFLA_BOND_MODE = 0x1 IFLA_BOND_ACTIVE_SLAVE = 0x2 @@ -1778,6 +1826,9 @@ const ( IFLA_BOND_AD_ACTOR_SYSTEM = 0x1a IFLA_BOND_TLB_DYNAMIC_LB = 0x1b IFLA_BOND_PEER_NOTIF_DELAY = 0x1c + IFLA_BOND_AD_LACP_ACTIVE = 0x1d + IFLA_BOND_MISSED_MAX = 0x1e + IFLA_BOND_NS_IP6_TARGET = 0x1f IFLA_BOND_AD_INFO_UNSPEC = 0x0 IFLA_BOND_AD_INFO_AGGREGATOR = 0x1 IFLA_BOND_AD_INFO_NUM_PORTS = 0x2 @@ -1793,6 +1844,7 @@ const ( IFLA_BOND_SLAVE_AD_AGGREGATOR_ID = 0x6 IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE = 0x7 IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE = 0x8 + IFLA_BOND_SLAVE_PRIO = 0x9 IFLA_VF_INFO_UNSPEC = 0x0 IFLA_VF_INFO = 0x1 IFLA_VF_UNSPEC = 0x0 @@ -1851,8 +1903,16 @@ const ( IFLA_STATS_LINK_XSTATS_SLAVE = 0x3 IFLA_STATS_LINK_OFFLOAD_XSTATS = 0x4 IFLA_STATS_AF_SPEC = 0x5 + IFLA_STATS_GETSET_UNSPEC = 0x0 + IFLA_STATS_GET_FILTERS = 0x1 + IFLA_STATS_SET_OFFLOAD_XSTATS_L3_STATS = 0x2 IFLA_OFFLOAD_XSTATS_UNSPEC = 0x0 IFLA_OFFLOAD_XSTATS_CPU_HIT = 0x1 + IFLA_OFFLOAD_XSTATS_HW_S_INFO = 0x2 + IFLA_OFFLOAD_XSTATS_L3_STATS = 0x3 + IFLA_OFFLOAD_XSTATS_HW_S_INFO_UNSPEC = 0x0 + IFLA_OFFLOAD_XSTATS_HW_S_INFO_REQUEST = 0x1 + IFLA_OFFLOAD_XSTATS_HW_S_INFO_USED = 0x2 IFLA_XDP_UNSPEC = 0x0 IFLA_XDP_FD = 0x1 IFLA_XDP_ATTACHED = 0x2 @@ -1882,6 +1942,11 @@ const ( IFLA_RMNET_UNSPEC = 0x0 IFLA_RMNET_MUX_ID = 0x1 IFLA_RMNET_FLAGS = 0x2 + IFLA_MCTP_UNSPEC = 0x0 + IFLA_MCTP_NET = 0x1 + IFLA_DSA_UNSPEC = 0x0 + IFLA_DSA_CONDUIT = 0x1 + IFLA_DSA_MASTER = 0x1 ) const ( @@ -2418,6 +2483,15 @@ type XDPMmapOffsets struct { Cr XDPRingOffset } +type XDPUmemReg struct { + Addr uint64 + Len uint64 + Chunk_size uint32 + Headroom uint32 + Flags uint32 + Tx_metadata_len uint32 +} + type XDPStatistics struct { Rx_dropped uint64 Rx_invalid_descs uint64 @@ -2672,6 +2746,7 @@ const ( BPF_PROG_TYPE_LSM = 0x1d BPF_PROG_TYPE_SK_LOOKUP = 0x1e BPF_PROG_TYPE_SYSCALL = 0x1f + BPF_PROG_TYPE_NETFILTER = 0x20 BPF_CGROUP_INET_INGRESS = 0x0 BPF_CGROUP_INET_EGRESS = 0x1 BPF_CGROUP_INET_SOCK_CREATE = 0x2 @@ -2716,6 +2791,11 @@ const ( BPF_PERF_EVENT = 0x29 BPF_TRACE_KPROBE_MULTI = 0x2a BPF_LSM_CGROUP = 0x2b + BPF_STRUCT_OPS = 0x2c + BPF_NETFILTER = 0x2d + BPF_TCX_INGRESS = 0x2e + BPF_TCX_EGRESS = 0x2f + BPF_TRACE_UPROBE_MULTI = 0x30 BPF_LINK_TYPE_UNSPEC = 0x0 BPF_LINK_TYPE_RAW_TRACEPOINT = 0x1 BPF_LINK_TYPE_TRACING = 0x2 @@ -2726,6 +2806,18 @@ const ( BPF_LINK_TYPE_PERF_EVENT = 0x7 BPF_LINK_TYPE_KPROBE_MULTI = 0x8 BPF_LINK_TYPE_STRUCT_OPS = 0x9 + BPF_LINK_TYPE_NETFILTER = 0xa + BPF_LINK_TYPE_TCX = 0xb + BPF_LINK_TYPE_UPROBE_MULTI = 0xc + BPF_PERF_EVENT_UNSPEC = 0x0 + BPF_PERF_EVENT_UPROBE = 0x1 + BPF_PERF_EVENT_URETPROBE = 0x2 + BPF_PERF_EVENT_KPROBE = 0x3 + BPF_PERF_EVENT_KRETPROBE = 0x4 + BPF_PERF_EVENT_TRACEPOINT = 0x5 + BPF_PERF_EVENT_EVENT = 0x6 + BPF_F_KPROBE_MULTI_RETURN = 0x1 + BPF_F_UPROBE_MULTI_RETURN = 0x1 BPF_ANY = 0x0 BPF_NOEXIST = 0x1 BPF_EXIST = 0x2 @@ -2743,6 +2835,8 @@ const ( BPF_F_MMAPABLE = 0x400 BPF_F_PRESERVE_ELEMS = 0x800 BPF_F_INNER_MAP = 0x1000 + BPF_F_LINK = 0x2000 + BPF_F_PATH_FD = 0x4000 BPF_STATS_RUN_TIME = 0x0 BPF_STACK_BUILD_ID_EMPTY = 0x0 BPF_STACK_BUILD_ID_VALID = 0x1 @@ -2763,6 +2857,7 @@ const ( BPF_F_ZERO_CSUM_TX = 0x2 BPF_F_DONT_FRAGMENT = 0x4 BPF_F_SEQ_NUMBER = 0x8 + BPF_F_NO_TUNNEL_KEY = 0x10 BPF_F_TUNINFO_FLAGS = 0x10 BPF_F_INDEX_MASK = 0xffffffff BPF_F_CURRENT_CPU = 0xffffffff @@ -2779,6 +2874,8 @@ const ( BPF_F_ADJ_ROOM_ENCAP_L4_UDP = 0x10 BPF_F_ADJ_ROOM_NO_CSUM_RESET = 0x20 BPF_F_ADJ_ROOM_ENCAP_L2_ETH = 0x40 + BPF_F_ADJ_ROOM_DECAP_L3_IPV4 = 0x80 + BPF_F_ADJ_ROOM_DECAP_L3_IPV6 = 0x100 BPF_ADJ_ROOM_ENCAP_L2_MASK = 0xff BPF_ADJ_ROOM_ENCAP_L2_SHIFT = 0x38 BPF_F_SYSCTL_BASE_NAME = 0x1 @@ -2849,7 +2946,7 @@ const ( BPF_TCP_LISTEN = 0xa BPF_TCP_CLOSING = 0xb BPF_TCP_NEW_SYN_RECV = 0xc - BPF_TCP_MAX_STATES = 0xd + BPF_TCP_MAX_STATES = 0xe TCP_BPF_IW = 0x3e9 TCP_BPF_SNDCWND_CLAMP = 0x3ea TCP_BPF_DELACK_MAX = 0x3eb @@ -2867,6 +2964,8 @@ const ( BPF_DEVCG_DEV_CHAR = 0x2 BPF_FIB_LOOKUP_DIRECT = 0x1 BPF_FIB_LOOKUP_OUTPUT = 0x2 + BPF_FIB_LOOKUP_SKIP_NEIGH = 0x4 + BPF_FIB_LOOKUP_TBID = 0x8 BPF_FIB_LKUP_RET_SUCCESS = 0x0 BPF_FIB_LKUP_RET_BLACKHOLE = 0x1 BPF_FIB_LKUP_RET_UNREACHABLE = 0x2 @@ -2902,6 +3001,7 @@ const ( BPF_CORE_ENUMVAL_EXISTS = 0xa BPF_CORE_ENUMVAL_VALUE = 0xb BPF_CORE_TYPE_MATCHES = 0xc + BPF_F_TIMER_ABS = 0x1 ) const ( @@ -2980,6 +3080,12 @@ type LoopInfo64 struct { Encrypt_key [32]uint8 Init [2]uint64 } +type LoopConfig struct { + Fd uint32 + Size uint32 + Info LoopInfo64 + _ [8]uint64 +} type TIPCSocketAddr struct { Ref uint32 @@ -3116,7 +3222,7 @@ const ( DEVLINK_CMD_LINECARD_NEW = 0x50 DEVLINK_CMD_LINECARD_DEL = 0x51 DEVLINK_CMD_SELFTESTS_GET = 0x52 - DEVLINK_CMD_MAX = 0x53 + DEVLINK_CMD_MAX = 0x54 DEVLINK_PORT_TYPE_NOTSET = 0x0 DEVLINK_PORT_TYPE_AUTO = 0x1 DEVLINK_PORT_TYPE_ETH = 0x2 @@ -3368,7 +3474,7 @@ const ( DEVLINK_PORT_FN_ATTR_STATE = 0x2 DEVLINK_PORT_FN_ATTR_OPSTATE = 0x3 DEVLINK_PORT_FN_ATTR_CAPS = 0x4 - DEVLINK_PORT_FUNCTION_ATTR_MAX = 0x4 + DEVLINK_PORT_FUNCTION_ATTR_MAX = 0x6 ) type FsverityDigest struct { @@ -3870,7 +3976,7 @@ const ( ETHTOOL_A_TSINFO_TX_TYPES = 0x3 ETHTOOL_A_TSINFO_RX_FILTERS = 0x4 ETHTOOL_A_TSINFO_PHC_INDEX = 0x5 - ETHTOOL_A_TSINFO_MAX = 0x5 + ETHTOOL_A_TSINFO_MAX = 0x6 ETHTOOL_A_CABLE_TEST_UNSPEC = 0x0 ETHTOOL_A_CABLE_TEST_HEADER = 0x1 ETHTOOL_A_CABLE_TEST_MAX = 0x1 @@ -4152,7 +4258,8 @@ const ( ) type LandlockRulesetAttr struct { - Access_fs uint64 + Access_fs uint64 + Access_net uint64 } type LandlockPathBeneathAttr struct { @@ -4499,7 +4606,7 @@ const ( NL80211_ATTR_MAC_HINT = 0xc8 NL80211_ATTR_MAC_MASK = 0xd7 NL80211_ATTR_MAX_AP_ASSOC_STA = 0xca - NL80211_ATTR_MAX = 0x146 + NL80211_ATTR_MAX = 0x14a NL80211_ATTR_MAX_CRIT_PROT_DURATION = 0xb4 NL80211_ATTR_MAX_CSA_COUNTERS = 0xce NL80211_ATTR_MAX_MATCH_SETS = 0x85 @@ -4765,7 +4872,7 @@ const ( NL80211_BSS_FREQUENCY_OFFSET = 0x14 NL80211_BSS_INFORMATION_ELEMENTS = 0x6 NL80211_BSS_LAST_SEEN_BOOTTIME = 0xf - NL80211_BSS_MAX = 0x16 + NL80211_BSS_MAX = 0x18 NL80211_BSS_MLD_ADDR = 0x16 NL80211_BSS_MLO_LINK_ID = 0x15 NL80211_BSS_PAD = 0x10 @@ -4869,7 +4976,7 @@ const ( NL80211_CMD_LEAVE_IBSS = 0x2c NL80211_CMD_LEAVE_MESH = 0x45 NL80211_CMD_LEAVE_OCB = 0x6d - NL80211_CMD_MAX = 0x9a + NL80211_CMD_MAX = 0x9b NL80211_CMD_MICHAEL_MIC_FAILURE = 0x29 NL80211_CMD_MODIFY_LINK_STA = 0x97 NL80211_CMD_NAN_MATCH = 0x78 @@ -5103,7 +5210,7 @@ const ( NL80211_FREQUENCY_ATTR_GO_CONCURRENT = 0xf NL80211_FREQUENCY_ATTR_INDOOR_ONLY = 0xe NL80211_FREQUENCY_ATTR_IR_CONCURRENT = 0xf - NL80211_FREQUENCY_ATTR_MAX = 0x1b + NL80211_FREQUENCY_ATTR_MAX = 0x20 NL80211_FREQUENCY_ATTR_MAX_TX_POWER = 0x6 NL80211_FREQUENCY_ATTR_NO_10MHZ = 0x11 NL80211_FREQUENCY_ATTR_NO_160MHZ = 0xc @@ -5516,7 +5623,7 @@ const ( NL80211_REGDOM_TYPE_CUSTOM_WORLD = 0x2 NL80211_REGDOM_TYPE_INTERSECTION = 0x3 NL80211_REGDOM_TYPE_WORLD = 0x1 - NL80211_REG_RULE_ATTR_MAX = 0x7 + NL80211_REG_RULE_ATTR_MAX = 0x8 NL80211_REKEY_DATA_AKM = 0x4 NL80211_REKEY_DATA_KCK = 0x2 NL80211_REKEY_DATA_KEK = 0x1 @@ -5597,7 +5704,7 @@ const ( NL80211_STA_FLAG_ASSOCIATED = 0x7 NL80211_STA_FLAG_AUTHENTICATED = 0x5 NL80211_STA_FLAG_AUTHORIZED = 0x1 - NL80211_STA_FLAG_MAX = 0x7 + NL80211_STA_FLAG_MAX = 0x8 NL80211_STA_FLAG_MAX_OLD_API = 0x6 NL80211_STA_FLAG_MFP = 0x4 NL80211_STA_FLAG_SHORT_PREAMBLE = 0x2 @@ -5883,3 +5990,46 @@ type SchedAttr struct { } const SizeofSchedAttr = 0x38 + +type Cachestat_t struct { + Cache uint64 + Dirty uint64 + Writeback uint64 + Evicted uint64 + Recently_evicted uint64 +} +type CachestatRange struct { + Off uint64 + Len uint64 +} + +const ( + SK_MEMINFO_RMEM_ALLOC = 0x0 + SK_MEMINFO_RCVBUF = 0x1 + SK_MEMINFO_WMEM_ALLOC = 0x2 + SK_MEMINFO_SNDBUF = 0x3 + SK_MEMINFO_FWD_ALLOC = 0x4 + SK_MEMINFO_WMEM_QUEUED = 0x5 + SK_MEMINFO_OPTMEM = 0x6 + SK_MEMINFO_BACKLOG = 0x7 + SK_MEMINFO_DROPS = 0x8 + SK_MEMINFO_VARS = 0x9 + SKNLGRP_NONE = 0x0 + SKNLGRP_INET_TCP_DESTROY = 0x1 + SKNLGRP_INET_UDP_DESTROY = 0x2 + SKNLGRP_INET6_TCP_DESTROY = 0x3 + SKNLGRP_INET6_UDP_DESTROY = 0x4 + SK_DIAG_BPF_STORAGE_REQ_NONE = 0x0 + SK_DIAG_BPF_STORAGE_REQ_MAP_FD = 0x1 + SK_DIAG_BPF_STORAGE_REP_NONE = 0x0 + SK_DIAG_BPF_STORAGE = 0x1 + SK_DIAG_BPF_STORAGE_NONE = 0x0 + SK_DIAG_BPF_STORAGE_PAD = 0x1 + SK_DIAG_BPF_STORAGE_MAP_ID = 0x2 + SK_DIAG_BPF_STORAGE_MAP_VALUE = 0x3 +) + +type SockDiagReq struct { + Family uint8 + Protocol uint8 +} diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index 6d8acbcc5..fd402da43 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && linux -// +build 386,linux package unix @@ -478,14 +477,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index 59293c688..eb7a5e186 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && linux -// +build amd64,linux package unix @@ -493,15 +492,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index 40cfa38c2..d78ac108b 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && linux -// +build arm,linux package unix @@ -471,15 +470,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index 055bc4216..cd06d47f1 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && linux -// +build arm64,linux package unix @@ -472,15 +471,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go index f28affbc6..2f28fe26c 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build loong64 && linux -// +build loong64,linux package unix @@ -473,15 +472,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index 9d71e7ccd..71d6cac2f 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips && linux -// +build mips,linux package unix @@ -477,15 +476,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index fd5ccd332..8596d4535 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && linux -// +build mips64,linux package unix @@ -475,15 +474,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 7704de77a..cd60ea186 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64le && linux -// +build mips64le,linux package unix @@ -475,15 +474,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index df00b8757..b0ae420c4 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mipsle && linux -// +build mipsle,linux package unix @@ -477,15 +476,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go index 0942840db..835972875 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && linux -// +build ppc,linux package unix @@ -483,15 +482,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index 034874395..69eb6a5c6 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && linux -// +build ppc64,linux package unix @@ -482,15 +481,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index bad067047..5f583cb62 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64le && linux -// +build ppc64le,linux package unix @@ -482,15 +481,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index 1b4c97c32..15adc0414 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && linux -// +build riscv64,linux package unix @@ -500,15 +499,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]uint8 Driver_name [64]uint8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index aa268d025..cf3ce9003 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build s390x && linux -// +build s390x,linux package unix @@ -496,15 +495,6 @@ const ( BLKPG = 0x1269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index 444045b6c..590b56739 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build sparc64 && linux -// +build sparc64,linux package unix @@ -477,15 +476,6 @@ const ( BLKPG = 0x20001269 ) -type XDPUmemReg struct { - Addr uint64 - Len uint64 - Size uint32 - Headroom uint32 - Flags uint32 - _ [4]byte -} - type CryptoUserAlg struct { Name [64]int8 Driver_name [64]int8 diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go index 9bc4c8f9d..f22e7947d 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && netbsd -// +build 386,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go index bb05f655d..066a7d83d 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && netbsd -// +build amd64,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go index db40e3a19..439548ec9 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && netbsd -// +build arm,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go index 11121151c..16085d3bb 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && netbsd -// +build arm64,netbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go index 26eba23b7..afd13a3af 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && openbsd -// +build 386,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go index 5a5479886..5d97f1f9b 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && openbsd -// +build amd64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go index be58c4e1f..34871cdc1 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && openbsd -// +build arm,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go index 52338266c..5911bceb3 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && openbsd -// +build arm64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go index 605cfdb12..e4f24f3bc 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && openbsd -// +build mips64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_ppc64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_ppc64.go index d6724c010..ca50a7930 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_ppc64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_ppc64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && openbsd -// +build ppc64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_riscv64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_riscv64.go index ddfd27a43..d7d7f7902 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_riscv64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_openbsd_riscv64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && openbsd -// +build riscv64,openbsd package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go b/tools/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go index 0400747c6..14160576d 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go @@ -2,7 +2,6 @@ // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && solaris -// +build amd64,solaris package unix diff --git a/tools/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go b/tools/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go index aec1efcb3..d9a13af46 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build zos && s390x -// +build zos,s390x // Hand edited based on ztypes_linux_s390x.go // TODO: auto-generate. @@ -26,10 +25,13 @@ const ( SizeofIPv6Mreq = 20 SizeofICMPv6Filter = 32 SizeofIPv6MTUInfo = 32 + SizeofInet4Pktinfo = 8 + SizeofInet6Pktinfo = 20 SizeofLinger = 8 SizeofSockaddrInet4 = 16 SizeofSockaddrInet6 = 28 SizeofTCPInfo = 0x68 + SizeofUcred = 12 ) type ( @@ -70,12 +72,17 @@ type Utimbuf struct { } type Utsname struct { - Sysname [65]byte - Nodename [65]byte - Release [65]byte - Version [65]byte - Machine [65]byte - Domainname [65]byte + Sysname [16]byte + Nodename [32]byte + Release [8]byte + Version [8]byte + Machine [16]byte +} + +type Ucred struct { + Pid int32 + Uid uint32 + Gid uint32 } type RawSockaddrInet4 struct { @@ -326,7 +333,7 @@ type Statvfs_t struct { } type Statfs_t struct { - Type uint32 + Type uint64 Bsize uint64 Blocks uint64 Bfree uint64 @@ -337,6 +344,7 @@ type Statfs_t struct { Namelen uint64 Frsize uint64 Flags uint64 + _ [4]uint64 } type direntLE struct { @@ -413,3 +421,126 @@ type W_Mntent struct { Quiesceowner [8]byte _ [38]byte } + +type EpollEvent struct { + Events uint32 + _ int32 + Fd int32 + Pad int32 +} + +type InotifyEvent struct { + Wd int32 + Mask uint32 + Cookie uint32 + Len uint32 + Name string +} + +const ( + SizeofInotifyEvent = 0x10 +) + +type ConsMsg2 struct { + Cm2Format uint16 + Cm2R1 uint16 + Cm2Msglength uint32 + Cm2Msg *byte + Cm2R2 [4]byte + Cm2R3 [4]byte + Cm2Routcde *uint32 + Cm2Descr *uint32 + Cm2Msgflag uint32 + Cm2Token uint32 + Cm2Msgid *uint32 + Cm2R4 [4]byte + Cm2DomToken uint32 + Cm2DomMsgid *uint32 + Cm2ModCartptr *byte + Cm2ModConsidptr *byte + Cm2MsgCart [8]byte + Cm2MsgConsid [4]byte + Cm2R5 [12]byte +} + +const ( + CC_modify = 1 + CC_stop = 2 + CONSOLE_FORMAT_2 = 2 + CONSOLE_FORMAT_3 = 3 + CONSOLE_HRDCPY = 0x80000000 +) + +type OpenHow struct { + Flags uint64 + Mode uint64 + Resolve uint64 +} + +const SizeofOpenHow = 0x18 + +const ( + RESOLVE_CACHED = 0x20 + RESOLVE_BENEATH = 0x8 + RESOLVE_IN_ROOT = 0x10 + RESOLVE_NO_MAGICLINKS = 0x2 + RESOLVE_NO_SYMLINKS = 0x4 + RESOLVE_NO_XDEV = 0x1 +) + +type Siginfo struct { + Signo int32 + Errno int32 + Code int32 + Pid int32 + Uid uint32 + _ [44]byte +} + +type SysvIpcPerm struct { + Uid uint32 + Gid uint32 + Cuid uint32 + Cgid uint32 + Mode int32 +} + +type SysvShmDesc struct { + Perm SysvIpcPerm + _ [4]byte + Lpid int32 + Cpid int32 + Nattch uint32 + _ [4]byte + _ [4]byte + _ [4]byte + _ int32 + _ uint8 + _ uint8 + _ uint16 + _ *byte + Segsz uint64 + Atime Time_t + Dtime Time_t + Ctime Time_t +} + +type SysvShmDesc64 struct { + Perm SysvIpcPerm + _ [4]byte + Lpid int32 + Cpid int32 + Nattch uint32 + _ [4]byte + _ [4]byte + _ [4]byte + _ int32 + _ byte + _ uint8 + _ uint16 + _ *byte + Segsz uint64 + Atime int64 + Dtime int64 + Ctime int64 +} diff --git a/tools/vendor/golang.org/x/sys/windows/aliases.go b/tools/vendor/golang.org/x/sys/windows/aliases.go index a20ebea63..16f90560a 100644 --- a/tools/vendor/golang.org/x/sys/windows/aliases.go +++ b/tools/vendor/golang.org/x/sys/windows/aliases.go @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build windows && go1.9 -// +build windows,go1.9 +//go:build windows package windows diff --git a/tools/vendor/golang.org/x/sys/windows/empty.s b/tools/vendor/golang.org/x/sys/windows/empty.s deleted file mode 100644 index fdbbbcd31..000000000 --- a/tools/vendor/golang.org/x/sys/windows/empty.s +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.12 -// +build !go1.12 - -// This file is here to allow bodyless functions with go:linkname for Go 1.11 -// and earlier (see https://golang.org/issue/23311). diff --git a/tools/vendor/golang.org/x/sys/windows/env_windows.go b/tools/vendor/golang.org/x/sys/windows/env_windows.go index b8ad19250..d4577a423 100644 --- a/tools/vendor/golang.org/x/sys/windows/env_windows.go +++ b/tools/vendor/golang.org/x/sys/windows/env_windows.go @@ -37,14 +37,17 @@ func (token Token) Environ(inheritExisting bool) (env []string, err error) { return nil, err } defer DestroyEnvironmentBlock(block) - blockp := unsafe.Pointer(block) - for { - entry := UTF16PtrToString((*uint16)(blockp)) - if len(entry) == 0 { - break + size := unsafe.Sizeof(*block) + for *block != 0 { + // find NUL terminator + end := unsafe.Pointer(block) + for *(*uint16)(end) != 0 { + end = unsafe.Add(end, size) } - env = append(env, entry) - blockp = unsafe.Add(blockp, 2*(len(entry)+1)) + + entry := unsafe.Slice(block, (uintptr(end)-uintptr(unsafe.Pointer(block)))/size) + env = append(env, UTF16ToString(entry)) + block = (*uint16)(unsafe.Add(end, size)) } return env, nil } diff --git a/tools/vendor/golang.org/x/sys/windows/eventlog.go b/tools/vendor/golang.org/x/sys/windows/eventlog.go index 2cd60645e..6c366955d 100644 --- a/tools/vendor/golang.org/x/sys/windows/eventlog.go +++ b/tools/vendor/golang.org/x/sys/windows/eventlog.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build windows -// +build windows package windows diff --git a/tools/vendor/golang.org/x/sys/windows/mksyscall.go b/tools/vendor/golang.org/x/sys/windows/mksyscall.go index 8563f79c5..dbcdb090c 100644 --- a/tools/vendor/golang.org/x/sys/windows/mksyscall.go +++ b/tools/vendor/golang.org/x/sys/windows/mksyscall.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build generate -// +build generate package windows diff --git a/tools/vendor/golang.org/x/sys/windows/race.go b/tools/vendor/golang.org/x/sys/windows/race.go index 9196b089c..0f1bdc386 100644 --- a/tools/vendor/golang.org/x/sys/windows/race.go +++ b/tools/vendor/golang.org/x/sys/windows/race.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build windows && race -// +build windows,race package windows diff --git a/tools/vendor/golang.org/x/sys/windows/race0.go b/tools/vendor/golang.org/x/sys/windows/race0.go index 7bae4817a..0c78da78b 100644 --- a/tools/vendor/golang.org/x/sys/windows/race0.go +++ b/tools/vendor/golang.org/x/sys/windows/race0.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build windows && !race -// +build windows,!race package windows diff --git a/tools/vendor/golang.org/x/sys/windows/security_windows.go b/tools/vendor/golang.org/x/sys/windows/security_windows.go index 26be94a8a..b6e1ab76f 100644 --- a/tools/vendor/golang.org/x/sys/windows/security_windows.go +++ b/tools/vendor/golang.org/x/sys/windows/security_windows.go @@ -68,6 +68,7 @@ type UserInfo10 struct { //sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo //sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation //sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree +//sys NetUserEnum(serverName *uint16, level uint32, filter uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32, resumeHandle *uint32) (neterr error) = netapi32.NetUserEnum const ( // do not reorder @@ -893,7 +894,7 @@ type ACL struct { aclRevision byte sbz1 byte aclSize uint16 - aceCount uint16 + AceCount uint16 sbz2 uint16 } @@ -1086,6 +1087,27 @@ type EXPLICIT_ACCESS struct { Trustee TRUSTEE } +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-ace_header +type ACE_HEADER struct { + AceType uint8 + AceFlags uint8 + AceSize uint16 +} + +// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-access_allowed_ace +type ACCESS_ALLOWED_ACE struct { + Header ACE_HEADER + Mask ACCESS_MASK + SidStart uint32 +} + +const ( + // Constants for AceType + // https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-ace_header + ACCESS_ALLOWED_ACE_TYPE = 0 + ACCESS_DENIED_ACE_TYPE = 1 +) + // This type is the union inside of TRUSTEE and must be created using one of the TrusteeValueFrom* functions. type TrusteeValue uintptr @@ -1157,6 +1179,7 @@ type OBJECTS_AND_NAME struct { //sys makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURITY_DESCRIPTOR, selfRelativeSDSize *uint32) (err error) = advapi32.MakeSelfRelativeSD //sys setEntriesInAcl(countExplicitEntries uint32, explicitEntries *EXPLICIT_ACCESS, oldACL *ACL, newACL **ACL) (ret error) = advapi32.SetEntriesInAclW +//sys GetAce(acl *ACL, aceIndex uint32, pAce **ACCESS_ALLOWED_ACE) (err error) = advapi32.GetAce // Control returns the security descriptor control bits. func (sd *SECURITY_DESCRIPTOR) Control() (control SECURITY_DESCRIPTOR_CONTROL, revision uint32, err error) { diff --git a/tools/vendor/golang.org/x/sys/windows/service.go b/tools/vendor/golang.org/x/sys/windows/service.go index c44a1b963..a9dc6308d 100644 --- a/tools/vendor/golang.org/x/sys/windows/service.go +++ b/tools/vendor/golang.org/x/sys/windows/service.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build windows -// +build windows package windows diff --git a/tools/vendor/golang.org/x/sys/windows/str.go b/tools/vendor/golang.org/x/sys/windows/str.go index 4fc01434e..6a4f9ce6a 100644 --- a/tools/vendor/golang.org/x/sys/windows/str.go +++ b/tools/vendor/golang.org/x/sys/windows/str.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build windows -// +build windows package windows diff --git a/tools/vendor/golang.org/x/sys/windows/syscall.go b/tools/vendor/golang.org/x/sys/windows/syscall.go index 8732cdb95..e85ed6b9c 100644 --- a/tools/vendor/golang.org/x/sys/windows/syscall.go +++ b/tools/vendor/golang.org/x/sys/windows/syscall.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build windows -// +build windows // Package windows contains an interface to the low-level operating system // primitives. OS details vary depending on the underlying system, and diff --git a/tools/vendor/golang.org/x/sys/windows/syscall_windows.go b/tools/vendor/golang.org/x/sys/windows/syscall_windows.go index 35cfc57ca..1fa34fd17 100644 --- a/tools/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/tools/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -17,8 +17,10 @@ import ( "unsafe" ) -type Handle uintptr -type HWND uintptr +type ( + Handle uintptr + HWND uintptr +) const ( InvalidHandle = ^Handle(0) @@ -125,8 +127,7 @@ func UTF16PtrToString(p *uint16) string { for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ { ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p)) } - - return string(utf16.Decode(unsafe.Slice(p, n))) + return UTF16ToString(unsafe.Slice(p, n)) } func Getpagesize() int { return 4096 } @@ -155,6 +156,8 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW //sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW //sys SetDefaultDllDirectories(directoryFlags uint32) (err error) +//sys AddDllDirectory(path *uint16) (cookie uintptr, err error) = kernel32.AddDllDirectory +//sys RemoveDllDirectory(cookie uintptr) (err error) = kernel32.RemoveDllDirectory //sys SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW //sys GetVersion() (ver uint32, err error) //sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW @@ -164,6 +167,7 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW //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 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 @@ -192,6 +196,7 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW //sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW //sys SetEndOfFile(handle Handle) (err error) +//sys SetFileValidData(handle Handle, validDataLength int64) (err error) //sys GetSystemTimeAsFileTime(time *Filetime) //sys GetSystemTimePreciseAsFileTime(time *Filetime) //sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff] @@ -208,6 +213,10 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error) //sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW //sys GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) = user32.GetWindowThreadProcessId +//sys LoadKeyboardLayout(name *uint16, flags uint32) (hkl Handle, err error) [failretval==0] = user32.LoadKeyboardLayoutW +//sys UnloadKeyboardLayout(hkl Handle) (err error) = user32.UnloadKeyboardLayout +//sys GetKeyboardLayout(tid uint32) (hkl Handle) = user32.GetKeyboardLayout +//sys ToUnicodeEx(vkey uint32, scancode uint32, keystate *byte, pwszBuff *uint16, cchBuff int32, flags uint32, hkl Handle) (ret int32) = user32.ToUnicodeEx //sys GetShellWindow() (shellWindow HWND) = user32.GetShellWindow //sys MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW //sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx @@ -233,6 +242,7 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock //sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock //sys getTickCount64() (ms uint64) = kernel32.GetTickCount64 +//sys GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) //sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) //sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW //sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW @@ -345,8 +355,19 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost //sys GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32) //sys SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error) +//sys ClearCommBreak(handle Handle) (err error) +//sys ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error) +//sys EscapeCommFunction(handle Handle, dwFunc uint32) (err error) +//sys GetCommState(handle Handle, lpDCB *DCB) (err error) +//sys GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) //sys GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) +//sys PurgeComm(handle Handle, dwFlags uint32) (err error) +//sys SetCommBreak(handle Handle) (err error) +//sys SetCommMask(handle Handle, dwEvtMask uint32) (err error) +//sys SetCommState(handle Handle, lpDCB *DCB) (err error) //sys SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) +//sys SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error) +//sys WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error) //sys GetActiveProcessorCount(groupNumber uint16) (ret uint32) //sys GetMaximumProcessorCount(groupNumber uint16) (ret uint32) //sys EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) = user32.EnumWindows @@ -969,7 +990,8 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) { if n > 0 { sl += int32(n) + 1 } - if sa.raw.Path[0] == '@' { + if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) { + // Check sl > 3 so we don't change unnamed socket behavior. sa.raw.Path[0] = 0 // Don't count trailing NUL for abstract address. sl-- @@ -1352,9 +1374,11 @@ func SetsockoptLinger(fd Handle, level, opt int, l *Linger) (err error) { func SetsockoptInet4Addr(fd Handle, level, opt int, value [4]byte) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(&value[0])), 4) } + func SetsockoptIPMreq(fd Handle, level, opt int, mreq *IPMreq) (err error) { return Setsockopt(fd, int32(level), int32(opt), (*byte)(unsafe.Pointer(mreq)), int32(unsafe.Sizeof(*mreq))) } + func SetsockoptIPv6Mreq(fd Handle, level, opt int, mreq *IPv6Mreq) (err error) { return syscall.EWINDOWS } @@ -1830,3 +1854,73 @@ func ResizePseudoConsole(pconsole Handle, size Coord) error { // accept arguments that can be casted to uintptr, and Coord can't. return resizePseudoConsole(pconsole, *((*uint32)(unsafe.Pointer(&size)))) } + +// DCB constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-dcb. +const ( + CBR_110 = 110 + CBR_300 = 300 + CBR_600 = 600 + CBR_1200 = 1200 + CBR_2400 = 2400 + CBR_4800 = 4800 + CBR_9600 = 9600 + CBR_14400 = 14400 + CBR_19200 = 19200 + CBR_38400 = 38400 + CBR_57600 = 57600 + CBR_115200 = 115200 + CBR_128000 = 128000 + CBR_256000 = 256000 + + DTR_CONTROL_DISABLE = 0x00000000 + DTR_CONTROL_ENABLE = 0x00000010 + DTR_CONTROL_HANDSHAKE = 0x00000020 + + RTS_CONTROL_DISABLE = 0x00000000 + RTS_CONTROL_ENABLE = 0x00001000 + RTS_CONTROL_HANDSHAKE = 0x00002000 + RTS_CONTROL_TOGGLE = 0x00003000 + + NOPARITY = 0 + ODDPARITY = 1 + EVENPARITY = 2 + MARKPARITY = 3 + SPACEPARITY = 4 + + ONESTOPBIT = 0 + ONE5STOPBITS = 1 + TWOSTOPBITS = 2 +) + +// EscapeCommFunction constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-escapecommfunction. +const ( + SETXOFF = 1 + SETXON = 2 + SETRTS = 3 + CLRRTS = 4 + SETDTR = 5 + CLRDTR = 6 + SETBREAK = 8 + CLRBREAK = 9 +) + +// PurgeComm constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-purgecomm. +const ( + PURGE_TXABORT = 0x0001 + PURGE_RXABORT = 0x0002 + PURGE_TXCLEAR = 0x0004 + PURGE_RXCLEAR = 0x0008 +) + +// SetCommMask constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setcommmask. +const ( + EV_RXCHAR = 0x0001 + EV_RXFLAG = 0x0002 + EV_TXEMPTY = 0x0004 + EV_CTS = 0x0008 + EV_DSR = 0x0010 + EV_RLSD = 0x0020 + EV_BREAK = 0x0040 + EV_ERR = 0x0080 + EV_RING = 0x0100 +) diff --git a/tools/vendor/golang.org/x/sys/windows/types_windows.go b/tools/vendor/golang.org/x/sys/windows/types_windows.go index b88dc7c85..4d0c15745 100644 --- a/tools/vendor/golang.org/x/sys/windows/types_windows.go +++ b/tools/vendor/golang.org/x/sys/windows/types_windows.go @@ -1094,7 +1094,33 @@ const ( SOMAXCONN = 0x7fffffff - TCP_NODELAY = 1 + TCP_NODELAY = 1 + TCP_EXPEDITED_1122 = 2 + TCP_KEEPALIVE = 3 + TCP_MAXSEG = 4 + TCP_MAXRT = 5 + TCP_STDURG = 6 + TCP_NOURG = 7 + TCP_ATMARK = 8 + TCP_NOSYNRETRIES = 9 + TCP_TIMESTAMPS = 10 + TCP_OFFLOAD_PREFERENCE = 11 + TCP_CONGESTION_ALGORITHM = 12 + TCP_DELAY_FIN_ACK = 13 + TCP_MAXRTMS = 14 + TCP_FASTOPEN = 15 + TCP_KEEPCNT = 16 + TCP_KEEPIDLE = TCP_KEEPALIVE + TCP_KEEPINTVL = 17 + TCP_FAIL_CONNECT_ON_ICMP_ERROR = 18 + TCP_ICMP_ERROR_INFO = 19 + + UDP_NOCHECKSUM = 1 + UDP_SEND_MSG_SIZE = 2 + UDP_RECV_MAX_COALESCED_SIZE = 3 + UDP_CHECKSUM_COVERAGE = 20 + + UDP_COALESCED_INFO = 3 SHUT_RD = 0 SHUT_WR = 1 @@ -1977,7 +2003,21 @@ const ( MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20 ) -const GAA_FLAG_INCLUDE_PREFIX = 0x00000010 +// Flags for GetAdaptersAddresses, see +// https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses. +const ( + GAA_FLAG_SKIP_UNICAST = 0x1 + GAA_FLAG_SKIP_ANYCAST = 0x2 + GAA_FLAG_SKIP_MULTICAST = 0x4 + GAA_FLAG_SKIP_DNS_SERVER = 0x8 + GAA_FLAG_INCLUDE_PREFIX = 0x10 + GAA_FLAG_SKIP_FRIENDLY_NAME = 0x20 + GAA_FLAG_INCLUDE_WINS_INFO = 0x40 + GAA_FLAG_INCLUDE_GATEWAYS = 0x80 + GAA_FLAG_INCLUDE_ALL_INTERFACES = 0x100 + GAA_FLAG_INCLUDE_ALL_COMPARTMENTS = 0x200 + GAA_FLAG_INCLUDE_TUNNEL_BINDINGORDER = 0x400 +) const ( IF_TYPE_OTHER = 1 @@ -3354,3 +3394,38 @@ type BLOB struct { Size uint32 BlobData *byte } + +type ComStat struct { + Flags uint32 + CBInQue uint32 + CBOutQue uint32 +} + +type DCB struct { + DCBlength uint32 + BaudRate uint32 + Flags uint32 + wReserved uint16 + XonLim uint16 + XoffLim uint16 + ByteSize uint8 + Parity uint8 + StopBits uint8 + XonChar byte + XoffChar byte + ErrorChar byte + EofChar byte + EvtChar byte + wReserved1 uint16 +} + +// Keyboard Layout Flags. +// See https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadkeyboardlayoutw +const ( + KLF_ACTIVATE = 0x00000001 + KLF_SUBSTITUTE_OK = 0x00000002 + KLF_REORDER = 0x00000008 + KLF_REPLACELANG = 0x00000010 + KLF_NOTELLSHELL = 0x00000080 + KLF_SETFORPROCESS = 0x00000100 +) diff --git a/tools/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/tools/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 8b1688de4..9bb979a3e 100644 --- a/tools/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/tools/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -91,6 +91,7 @@ var ( procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW") procEqualSid = modadvapi32.NewProc("EqualSid") procFreeSid = modadvapi32.NewProc("FreeSid") + procGetAce = modadvapi32.NewProc("GetAce") procGetLengthSid = modadvapi32.NewProc("GetLengthSid") procGetNamedSecurityInfoW = modadvapi32.NewProc("GetNamedSecurityInfoW") procGetSecurityDescriptorControl = modadvapi32.NewProc("GetSecurityDescriptorControl") @@ -184,9 +185,12 @@ var ( procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo") procGetBestInterfaceEx = modiphlpapi.NewProc("GetBestInterfaceEx") procGetIfEntry = modiphlpapi.NewProc("GetIfEntry") + procAddDllDirectory = modkernel32.NewProc("AddDllDirectory") procAssignProcessToJobObject = modkernel32.NewProc("AssignProcessToJobObject") procCancelIo = modkernel32.NewProc("CancelIo") procCancelIoEx = modkernel32.NewProc("CancelIoEx") + procClearCommBreak = modkernel32.NewProc("ClearCommBreak") + procClearCommError = modkernel32.NewProc("ClearCommError") procCloseHandle = modkernel32.NewProc("CloseHandle") procClosePseudoConsole = modkernel32.NewProc("ClosePseudoConsole") procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") @@ -211,7 +215,9 @@ var ( procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList") procDeleteVolumeMountPointW = modkernel32.NewProc("DeleteVolumeMountPointW") procDeviceIoControl = modkernel32.NewProc("DeviceIoControl") + procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") procDuplicateHandle = modkernel32.NewProc("DuplicateHandle") + procEscapeCommFunction = modkernel32.NewProc("EscapeCommFunction") procExitProcess = modkernel32.NewProc("ExitProcess") procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW") procFindClose = modkernel32.NewProc("FindClose") @@ -235,6 +241,8 @@ var ( procGenerateConsoleCtrlEvent = modkernel32.NewProc("GenerateConsoleCtrlEvent") procGetACP = modkernel32.NewProc("GetACP") procGetActiveProcessorCount = modkernel32.NewProc("GetActiveProcessorCount") + procGetCommModemStatus = modkernel32.NewProc("GetCommModemStatus") + procGetCommState = modkernel32.NewProc("GetCommState") procGetCommTimeouts = modkernel32.NewProc("GetCommTimeouts") procGetCommandLineW = modkernel32.NewProc("GetCommandLineW") procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW") @@ -253,6 +261,7 @@ var ( procGetFileAttributesW = modkernel32.NewProc("GetFileAttributesW") procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle") procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx") + procGetFileTime = modkernel32.NewProc("GetFileTime") procGetFileType = modkernel32.NewProc("GetFileType") procGetFinalPathNameByHandleW = modkernel32.NewProc("GetFinalPathNameByHandleW") procGetFullPathNameW = modkernel32.NewProc("GetFullPathNameW") @@ -320,6 +329,7 @@ var ( procProcess32NextW = modkernel32.NewProc("Process32NextW") procProcessIdToSessionId = modkernel32.NewProc("ProcessIdToSessionId") procPulseEvent = modkernel32.NewProc("PulseEvent") + procPurgeComm = modkernel32.NewProc("PurgeComm") procQueryDosDeviceW = modkernel32.NewProc("QueryDosDeviceW") procQueryFullProcessImageNameW = modkernel32.NewProc("QueryFullProcessImageNameW") procQueryInformationJobObject = modkernel32.NewProc("QueryInformationJobObject") @@ -329,9 +339,13 @@ var ( procReadProcessMemory = modkernel32.NewProc("ReadProcessMemory") procReleaseMutex = modkernel32.NewProc("ReleaseMutex") procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW") + procRemoveDllDirectory = modkernel32.NewProc("RemoveDllDirectory") procResetEvent = modkernel32.NewProc("ResetEvent") procResizePseudoConsole = modkernel32.NewProc("ResizePseudoConsole") procResumeThread = modkernel32.NewProc("ResumeThread") + procSetCommBreak = modkernel32.NewProc("SetCommBreak") + procSetCommMask = modkernel32.NewProc("SetCommMask") + procSetCommState = modkernel32.NewProc("SetCommState") procSetCommTimeouts = modkernel32.NewProc("SetCommTimeouts") procSetConsoleCursorPosition = modkernel32.NewProc("SetConsoleCursorPosition") procSetConsoleMode = modkernel32.NewProc("SetConsoleMode") @@ -347,6 +361,7 @@ var ( procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle") procSetFilePointer = modkernel32.NewProc("SetFilePointer") procSetFileTime = modkernel32.NewProc("SetFileTime") + procSetFileValidData = modkernel32.NewProc("SetFileValidData") procSetHandleInformation = modkernel32.NewProc("SetHandleInformation") procSetInformationJobObject = modkernel32.NewProc("SetInformationJobObject") procSetNamedPipeHandleState = modkernel32.NewProc("SetNamedPipeHandleState") @@ -357,6 +372,7 @@ var ( procSetStdHandle = modkernel32.NewProc("SetStdHandle") procSetVolumeLabelW = modkernel32.NewProc("SetVolumeLabelW") procSetVolumeMountPointW = modkernel32.NewProc("SetVolumeMountPointW") + procSetupComm = modkernel32.NewProc("SetupComm") procSizeofResource = modkernel32.NewProc("SizeofResource") procSleepEx = modkernel32.NewProc("SleepEx") procTerminateJobObject = modkernel32.NewProc("TerminateJobObject") @@ -375,6 +391,7 @@ var ( procVirtualQueryEx = modkernel32.NewProc("VirtualQueryEx") procVirtualUnlock = modkernel32.NewProc("VirtualUnlock") procWTSGetActiveConsoleSessionId = modkernel32.NewProc("WTSGetActiveConsoleSessionId") + procWaitCommEvent = modkernel32.NewProc("WaitCommEvent") procWaitForMultipleObjects = modkernel32.NewProc("WaitForMultipleObjects") procWaitForSingleObject = modkernel32.NewProc("WaitForSingleObject") procWriteConsoleW = modkernel32.NewProc("WriteConsoleW") @@ -385,6 +402,7 @@ var ( procTransmitFile = modmswsock.NewProc("TransmitFile") procNetApiBufferFree = modnetapi32.NewProc("NetApiBufferFree") procNetGetJoinInformation = modnetapi32.NewProc("NetGetJoinInformation") + procNetUserEnum = modnetapi32.NewProc("NetUserEnum") procNetUserGetInfo = modnetapi32.NewProc("NetUserGetInfo") procNtCreateFile = modntdll.NewProc("NtCreateFile") procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") @@ -460,12 +478,16 @@ var ( procGetDesktopWindow = moduser32.NewProc("GetDesktopWindow") procGetForegroundWindow = moduser32.NewProc("GetForegroundWindow") procGetGUIThreadInfo = moduser32.NewProc("GetGUIThreadInfo") + procGetKeyboardLayout = moduser32.NewProc("GetKeyboardLayout") procGetShellWindow = moduser32.NewProc("GetShellWindow") procGetWindowThreadProcessId = moduser32.NewProc("GetWindowThreadProcessId") procIsWindow = moduser32.NewProc("IsWindow") procIsWindowUnicode = moduser32.NewProc("IsWindowUnicode") procIsWindowVisible = moduser32.NewProc("IsWindowVisible") + procLoadKeyboardLayoutW = moduser32.NewProc("LoadKeyboardLayoutW") procMessageBoxW = moduser32.NewProc("MessageBoxW") + procToUnicodeEx = moduser32.NewProc("ToUnicodeEx") + procUnloadKeyboardLayout = moduser32.NewProc("UnloadKeyboardLayout") procCreateEnvironmentBlock = moduserenv.NewProc("CreateEnvironmentBlock") procDestroyEnvironmentBlock = moduserenv.NewProc("DestroyEnvironmentBlock") procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW") @@ -771,6 +793,14 @@ func FreeSid(sid *SID) (err error) { return } +func GetAce(acl *ACL, aceIndex uint32, pAce **ACCESS_ALLOWED_ACE) (err error) { + r1, _, e1 := syscall.Syscall(procGetAce.Addr(), 3, uintptr(unsafe.Pointer(acl)), uintptr(aceIndex), uintptr(unsafe.Pointer(pAce))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetLengthSid(sid *SID) (len uint32) { r0, _, _ := syscall.Syscall(procGetLengthSid.Addr(), 1, uintptr(unsafe.Pointer(sid)), 0, 0) len = uint32(r0) @@ -1604,6 +1634,15 @@ func GetIfEntry(pIfRow *MibIfRow) (errcode error) { 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) + if cookie == 0 { + err = errnoErr(e1) + } + return +} + func AssignProcessToJobObject(job Handle, process Handle) (err error) { r1, _, e1 := syscall.Syscall(procAssignProcessToJobObject.Addr(), 2, uintptr(job), uintptr(process), 0) if r1 == 0 { @@ -1628,6 +1667,22 @@ func CancelIoEx(s Handle, o *Overlapped) (err error) { return } +func ClearCommBreak(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procClearCommBreak.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error) { + r1, _, e1 := syscall.Syscall(procClearCommError.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(lpErrors)), uintptr(unsafe.Pointer(lpStat))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func CloseHandle(handle Handle) (err error) { r1, _, e1 := syscall.Syscall(procCloseHandle.Addr(), 1, uintptr(handle), 0, 0) if r1 == 0 { @@ -1832,6 +1887,14 @@ func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBuff return } +func DisconnectNamedPipe(pipe Handle) (err error) { + r1, _, e1 := syscall.Syscall(procDisconnectNamedPipe.Addr(), 1, uintptr(pipe), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) { var _p0 uint32 if bInheritHandle { @@ -1844,6 +1907,14 @@ func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetP return } +func EscapeCommFunction(handle Handle, dwFunc uint32) (err error) { + r1, _, e1 := syscall.Syscall(procEscapeCommFunction.Addr(), 2, uintptr(handle), uintptr(dwFunc), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func ExitProcess(exitcode uint32) { syscall.Syscall(procExitProcess.Addr(), 1, uintptr(exitcode), 0, 0) return @@ -2045,6 +2116,22 @@ func GetActiveProcessorCount(groupNumber uint16) (ret uint32) { return } +func GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetCommModemStatus.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpModemStat)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func GetCommState(handle Handle, lpDCB *DCB) (err error) { + r1, _, e1 := syscall.Syscall(procGetCommState.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpDCB)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { r1, _, e1 := syscall.Syscall(procGetCommTimeouts.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(timeouts)), 0) if r1 == 0 { @@ -2185,6 +2272,14 @@ func GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, return } +func GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) { + r1, _, e1 := syscall.Syscall6(procGetFileTime.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func GetFileType(filehandle Handle) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procGetFileType.Addr(), 1, uintptr(filehandle), 0, 0) n = uint32(r0) @@ -2789,6 +2884,14 @@ func PulseEvent(event Handle) (err error) { return } +func PurgeComm(handle Handle, dwFlags uint32) (err error) { + r1, _, e1 := syscall.Syscall(procPurgeComm.Addr(), 2, uintptr(handle), uintptr(dwFlags), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) { r0, _, e1 := syscall.Syscall(procQueryDosDeviceW.Addr(), 3, uintptr(unsafe.Pointer(deviceName)), uintptr(unsafe.Pointer(targetPath)), uintptr(max)) n = uint32(r0) @@ -2870,6 +2973,14 @@ func RemoveDirectory(path *uint16) (err error) { return } +func RemoveDllDirectory(cookie uintptr) (err error) { + r1, _, e1 := syscall.Syscall(procRemoveDllDirectory.Addr(), 1, uintptr(cookie), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func ResetEvent(event Handle) (err error) { r1, _, e1 := syscall.Syscall(procResetEvent.Addr(), 1, uintptr(event), 0, 0) if r1 == 0 { @@ -2895,6 +3006,30 @@ func ResumeThread(thread Handle) (ret uint32, err error) { return } +func SetCommBreak(handle Handle) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommBreak.Addr(), 1, uintptr(handle), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func SetCommMask(handle Handle, dwEvtMask uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommMask.Addr(), 2, uintptr(handle), uintptr(dwEvtMask), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + +func SetCommState(handle Handle, lpDCB *DCB) (err error) { + r1, _, e1 := syscall.Syscall(procSetCommState.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(lpDCB)), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { r1, _, e1 := syscall.Syscall(procSetCommTimeouts.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(timeouts)), 0) if r1 == 0 { @@ -3023,6 +3158,14 @@ func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetim return } +func SetFileValidData(handle Handle, validDataLength int64) (err error) { + r1, _, e1 := syscall.Syscall(procSetFileValidData.Addr(), 2, uintptr(handle), uintptr(validDataLength), 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procSetHandleInformation.Addr(), 3, uintptr(handle), uintptr(mask), uintptr(flags)) if r1 == 0 { @@ -3108,6 +3251,14 @@ func SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err erro return } +func SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error) { + r1, _, e1 := syscall.Syscall(procSetupComm.Addr(), 3, uintptr(handle), uintptr(dwInQueue), uintptr(dwOutQueue)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SizeofResource(module Handle, resInfo Handle) (size uint32, err error) { r0, _, e1 := syscall.Syscall(procSizeofResource.Addr(), 2, uintptr(module), uintptr(resInfo), 0) size = uint32(r0) @@ -3254,6 +3405,14 @@ func WTSGetActiveConsoleSessionId() (sessionID uint32) { return } +func WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error) { + r1, _, e1 := syscall.Syscall(procWaitCommEvent.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(lpEvtMask)), uintptr(unsafe.Pointer(lpOverlapped))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) { var _p0 uint32 if waitAll { @@ -3341,6 +3500,14 @@ func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (nete return } +func NetUserEnum(serverName *uint16, level uint32, filter uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32, resumeHandle *uint32) (neterr error) { + r0, _, _ := syscall.Syscall9(procNetUserEnum.Addr(), 8, uintptr(unsafe.Pointer(serverName)), uintptr(level), uintptr(filter), uintptr(unsafe.Pointer(buf)), uintptr(prefMaxLen), uintptr(unsafe.Pointer(entriesRead)), uintptr(unsafe.Pointer(totalEntries)), uintptr(unsafe.Pointer(resumeHandle)), 0) + if r0 != 0 { + neterr = syscall.Errno(r0) + } + return +} + func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) { r0, _, _ := syscall.Syscall6(procNetUserGetInfo.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf)), 0, 0) if r0 != 0 { @@ -3919,6 +4086,12 @@ func GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) { return } +func GetKeyboardLayout(tid uint32) (hkl Handle) { + r0, _, _ := syscall.Syscall(procGetKeyboardLayout.Addr(), 1, uintptr(tid), 0, 0) + hkl = Handle(r0) + return +} + func GetShellWindow() (shellWindow HWND) { r0, _, _ := syscall.Syscall(procGetShellWindow.Addr(), 0, 0, 0, 0) shellWindow = HWND(r0) @@ -3952,6 +4125,15 @@ func IsWindowVisible(hwnd HWND) (isVisible bool) { return } +func LoadKeyboardLayout(name *uint16, flags uint32) (hkl Handle, err error) { + r0, _, e1 := syscall.Syscall(procLoadKeyboardLayoutW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(flags), 0) + hkl = Handle(r0) + if hkl == 0 { + err = errnoErr(e1) + } + return +} + func MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) { r0, _, e1 := syscall.Syscall6(procMessageBoxW.Addr(), 4, uintptr(hwnd), uintptr(unsafe.Pointer(text)), uintptr(unsafe.Pointer(caption)), uintptr(boxtype), 0, 0) ret = int32(r0) @@ -3961,6 +4143,20 @@ func MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret i return } +func ToUnicodeEx(vkey uint32, scancode uint32, keystate *byte, pwszBuff *uint16, cchBuff int32, flags uint32, hkl Handle) (ret int32) { + r0, _, _ := syscall.Syscall9(procToUnicodeEx.Addr(), 7, uintptr(vkey), uintptr(scancode), uintptr(unsafe.Pointer(keystate)), uintptr(unsafe.Pointer(pwszBuff)), uintptr(cchBuff), uintptr(flags), uintptr(hkl), 0, 0) + ret = int32(r0) + return +} + +func UnloadKeyboardLayout(hkl Handle) (err error) { + r1, _, e1 := syscall.Syscall(procUnloadKeyboardLayout.Addr(), 1, uintptr(hkl), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) { var _p0 uint32 if inheritExisting { diff --git a/tools/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go b/tools/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go index f5a078827..1af161c75 100644 --- a/tools/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go +++ b/tools/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.10 && !go1.13 -// +build go1.10,!go1.13 package norm diff --git a/tools/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go b/tools/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go index cb7239c43..eb73ecc37 100644 --- a/tools/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go +++ b/tools/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.13 && !go1.14 -// +build go1.13,!go1.14 package norm diff --git a/tools/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go b/tools/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go index 11b273300..276cb8d8c 100644 --- a/tools/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go +++ b/tools/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.14 && !go1.16 -// +build go1.14,!go1.16 package norm diff --git a/tools/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go b/tools/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go index f65785e8a..0cceffd73 100644 --- a/tools/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go +++ b/tools/vendor/golang.org/x/text/unicode/norm/tables13.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.16 && !go1.21 -// +build go1.16,!go1.21 package norm diff --git a/tools/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go b/tools/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go index e1858b879..b0819e42d 100644 --- a/tools/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go +++ b/tools/vendor/golang.org/x/text/unicode/norm/tables15.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.21 -// +build go1.21 package norm diff --git a/tools/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go b/tools/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go index 0175eae50..bf65457d9 100644 --- a/tools/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go +++ b/tools/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build !go1.10 -// +build !go1.10 package norm diff --git a/tools/vendor/golang.org/x/text/width/tables10.0.0.go b/tools/vendor/golang.org/x/text/width/tables10.0.0.go index cd9d91caf..07c1cb17a 100644 --- a/tools/vendor/golang.org/x/text/width/tables10.0.0.go +++ b/tools/vendor/golang.org/x/text/width/tables10.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.10 && !go1.13 -// +build go1.10,!go1.13 package width diff --git a/tools/vendor/golang.org/x/text/width/tables11.0.0.go b/tools/vendor/golang.org/x/text/width/tables11.0.0.go index 327eaef9b..89288b3da 100644 --- a/tools/vendor/golang.org/x/text/width/tables11.0.0.go +++ b/tools/vendor/golang.org/x/text/width/tables11.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.13 && !go1.14 -// +build go1.13,!go1.14 package width diff --git a/tools/vendor/golang.org/x/text/width/tables12.0.0.go b/tools/vendor/golang.org/x/text/width/tables12.0.0.go index 5c14ade6d..755ee9122 100644 --- a/tools/vendor/golang.org/x/text/width/tables12.0.0.go +++ b/tools/vendor/golang.org/x/text/width/tables12.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.14 && !go1.16 -// +build go1.14,!go1.16 package width diff --git a/tools/vendor/golang.org/x/text/width/tables13.0.0.go b/tools/vendor/golang.org/x/text/width/tables13.0.0.go index b1fcb522c..40c169edf 100644 --- a/tools/vendor/golang.org/x/text/width/tables13.0.0.go +++ b/tools/vendor/golang.org/x/text/width/tables13.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.16 && !go1.21 -// +build go1.16,!go1.21 package width diff --git a/tools/vendor/golang.org/x/text/width/tables15.0.0.go b/tools/vendor/golang.org/x/text/width/tables15.0.0.go index 4b91e3384..2b8528967 100644 --- a/tools/vendor/golang.org/x/text/width/tables15.0.0.go +++ b/tools/vendor/golang.org/x/text/width/tables15.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build go1.21 -// +build go1.21 package width diff --git a/tools/vendor/golang.org/x/text/width/tables9.0.0.go b/tools/vendor/golang.org/x/text/width/tables9.0.0.go index 6781f3d96..d981330a9 100644 --- a/tools/vendor/golang.org/x/text/width/tables9.0.0.go +++ b/tools/vendor/golang.org/x/text/width/tables9.0.0.go @@ -1,7 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. //go:build !go1.10 -// +build !go1.10 package width diff --git a/tools/vendor/golang.org/x/tools/LICENSE b/tools/vendor/golang.org/x/tools/LICENSE index 6a66aea5e..2a7cf70da 100644 --- a/tools/vendor/golang.org/x/tools/LICENSE +++ b/tools/vendor/golang.org/x/tools/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are @@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Google Inc. nor the names of its + * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/tools/vendor/golang.org/x/tools/go/analysis/analysis.go b/tools/vendor/golang.org/x/tools/go/analysis/analysis.go index 5da33c7e6..aa02eeda6 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/analysis.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/analysis.go @@ -91,7 +91,7 @@ type Pass struct { Analyzer *Analyzer // the identity of the current analyzer // syntax and type information - Fset *token.FileSet // file position information + Fset *token.FileSet // file position information; Run may add new files Files []*ast.File // the abstract syntax tree of each file OtherFiles []string // names of non-Go files of this package IgnoredFiles []string // names of ignored source files in this package @@ -100,6 +100,8 @@ type Pass struct { TypesSizes types.Sizes // function for computing sizes of types TypeErrors []types.Error // type errors (only if Analyzer.RunDespiteErrors) + Module *Module // the package's enclosing module (possibly nil in some drivers) + // Report reports a Diagnostic, a finding about a specific location // in the analyzed source code such as a potential mistake. // It may be called by the Run function. @@ -112,6 +114,19 @@ type Pass struct { // analysis's ResultType. ResultOf map[*Analyzer]interface{} + // ReadFile returns the contents of the named file. + // + // The only valid file names are the elements of OtherFiles + // and IgnoredFiles, and names returned by + // Fset.File(f.FileStart).Name() for each f in Files. + // + // Analyzers must use this function (if provided) instead of + // accessing the file system directly. This allows a driver to + // provide a virtualized file tree (including, for example, + // unsaved editor buffers) and to track dependencies precisely + // to avoid unnecessary recomputation. + ReadFile func(filename string) ([]byte, error) + // -- facts -- // ImportObjectFact retrieves a fact associated with obj. @@ -225,3 +240,10 @@ func (pass *Pass) String() string { type Fact interface { AFact() // dummy method to avoid type errors } + +// A Module describes the module to which a package belongs. +type Module struct { + Path string // module path + Version string // module version ("" if unknown, such as for workspace modules) + GoVersion string // go version used in module (e.g. "go1.22.0") +} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/diagnostic.go b/tools/vendor/golang.org/x/tools/go/analysis/diagnostic.go index f67c97294..ee083a2d6 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/diagnostic.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/diagnostic.go @@ -12,7 +12,8 @@ import "go/token" // which should be a constant, may be used to classify them. // It is primarily intended to make it easy to look up documentation. // -// If End is provided, the diagnostic is specified to apply to the range between +// All Pos values are interpreted relative to Pass.Fset. If End is +// provided, the diagnostic is specified to apply to the range between // Pos and End. type Diagnostic struct { Pos token.Pos @@ -31,14 +32,23 @@ type Diagnostic struct { // see https://pkg.go.dev/net/url#URL.ResolveReference. URL string - // SuggestedFixes contains suggested fixes for a diagnostic - // which can be used to perform edits to a file that address - // the diagnostic. + // SuggestedFixes is an optional list of fixes to address the + // problem described by the diagnostic. Each one represents + // an alternative strategy; at most one may be applied. // - // Diagnostics should not contain SuggestedFixes that overlap. - SuggestedFixes []SuggestedFix // optional + // Fixes for different diagnostics should be treated as + // independent changes to the same baseline file state, + // analogous to a set of git commits all with the same parent. + // Combining fixes requires resolving any conflicts that + // arise, analogous to a git merge. + // Any conflicts that remain may be dealt with, depending on + // the tool, by discarding fixes, consulting the user, or + // aborting the operation. + SuggestedFixes []SuggestedFix - Related []RelatedInformation // optional + // Related contains optional secondary positions and messages + // related to the primary diagnostic. + Related []RelatedInformation } // RelatedInformation contains information related to a diagnostic. @@ -55,11 +65,12 @@ type RelatedInformation struct { // user can choose to apply to their code. Usually the SuggestedFix is // meant to fix the issue flagged by the diagnostic. // -// TextEdits for a SuggestedFix should not overlap, -// nor contain edits for other packages. +// The TextEdits must not overlap, nor contain edits for other packages. type SuggestedFix struct { - // A description for this suggested fix to be shown to a user deciding - // whether to accept it. + // A verb phrase describing the fix, to be shown to + // a user trying to decide whether to accept it. + // + // Example: "Remove the surplus argument" Message string TextEdits []TextEdit } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/doc.go b/tools/vendor/golang.org/x/tools/go/analysis/doc.go index 44867d599..2a0aa5771 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/doc.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/doc.go @@ -32,7 +32,7 @@ bases, and so on. # Analyzer -The primary type in the API is Analyzer. An Analyzer statically +The primary type in the API is [Analyzer]. An Analyzer statically describes an analysis function: its name, documentation, flags, relationship to other analyzers, and of course, its logic. @@ -72,7 +72,7 @@ help that describes the analyses it performs. The doc comment contains a brief one-line summary, optionally followed by paragraphs of explanation. -The Analyzer type has more fields besides those shown above: +The [Analyzer] type has more fields besides those shown above: type Analyzer struct { Name string @@ -114,7 +114,7 @@ instance of the Pass type. # Pass -A Pass describes a single unit of work: the application of a particular +A [Pass] describes a single unit of work: the application of a particular Analyzer to a particular package of Go code. The Pass provides information to the Analyzer's Run function about the package being analyzed, and provides operations to the Run function for @@ -135,16 +135,14 @@ reporting diagnostics and other information back to the driver. The Fset, Files, Pkg, and TypesInfo fields provide the syntax trees, type information, and source positions for a single package of Go code. -The OtherFiles field provides the names, but not the contents, of non-Go -files such as assembly that are part of this package. See the "asmdecl" -or "buildtags" analyzers for examples of loading non-Go files and reporting -diagnostics against them. - -The IgnoredFiles field provides the names, but not the contents, -of ignored Go and non-Go source files that are not part of this package -with the current build configuration but may be part of other build -configurations. See the "buildtags" analyzer for an example of loading -and checking IgnoredFiles. +The OtherFiles field provides the names of non-Go +files such as assembly that are part of this package. +Similarly, the IgnoredFiles field provides the names of Go and non-Go +source files that are not part of this package with the current build +configuration but may be part of other build configurations. +The contents of these files may be read using Pass.ReadFile; +see the "asmdecl" or "buildtags" analyzers for examples of loading +non-Go files and reporting diagnostics against them. The ResultOf field provides the results computed by the analyzers required by this one, as expressed in its Analyzer.Requires field. The @@ -177,7 +175,7 @@ Diagnostic is defined as: The optional Category field is a short identifier that classifies the kind of message when an analysis produces several kinds of diagnostic. -The Diagnostic struct does not have a field to indicate its severity +The [Diagnostic] struct does not have a field to indicate its severity because opinions about the relative importance of Analyzers and their diagnostics vary widely among users. The design of this framework does not hold each Analyzer responsible for identifying the severity of its @@ -191,7 +189,7 @@ and buildtag, inspect the raw text of Go source files or even non-Go files such as assembly. To report a diagnostic against a line of a raw text file, use the following sequence: - content, err := os.ReadFile(filename) + content, err := pass.ReadFile(filename) if err != nil { ... } tf := fset.AddFile(filename, -1, len(content)) tf.SetLinesForContent(content) @@ -216,7 +214,7 @@ addition, it records which functions are printf wrappers for use by later analysis passes to identify other printf wrappers by induction. A result such as “f is a printf wrapper” that is not interesting by itself but serves as a stepping stone to an interesting result (such as -a diagnostic) is called a "fact". +a diagnostic) is called a [Fact]. The analysis API allows an analysis to define new types of facts, to associate facts of these types with objects (named entities) declared diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/appends/appends.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/appends/appends.go index f0b90a492..6976f0d90 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/appends/appends.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/appends/appends.go @@ -15,6 +15,7 @@ import ( "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/go/types/typeutil" ) //go:embed doc.go @@ -36,12 +37,9 @@ func run(pass *analysis.Pass) (interface{}, error) { } inspect.Preorder(nodeFilter, func(n ast.Node) { call := n.(*ast.CallExpr) - if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "append" { - if _, ok := pass.TypesInfo.Uses[ident].(*types.Builtin); ok { - if len(call.Args) == 1 { - pass.ReportRangef(call, "append with no values") - } - } + b, ok := typeutil.Callee(pass.TypesInfo, call).(*types.Builtin) + if ok && b.Name() == "append" && len(call.Args) == 1 { + pass.ReportRangef(call, "append with no values") } }) diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go118.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go118.go deleted file mode 100644 index d8211afdc..000000000 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go118.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.19 -// +build !go1.19 - -package asmdecl - -func additionalArches() []*asmArch { - return nil -} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go119.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go119.go deleted file mode 100644 index 3018383e7..000000000 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go119.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.19 -// +build go1.19 - -package asmdecl - -var asmArchLoong64 = asmArch{name: "loong64", bigEndian: false, stack: "R3", lr: true} - -func additionalArches() []*asmArch { - return []*asmArch{&asmArchLoong64} -} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/asmdecl.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/asmdecl.go index e24dac986..c9ba1a375 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/asmdecl.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/asmdecl.go @@ -96,6 +96,7 @@ var ( asmArchRISCV64 = asmArch{name: "riscv64", bigEndian: false, stack: "SP", lr: true, retRegs: []string{"X10", "F10"}} asmArchS390X = asmArch{name: "s390x", bigEndian: true, stack: "R15", lr: true} asmArchWasm = asmArch{name: "wasm", bigEndian: false, stack: "SP", lr: false} + asmArchLoong64 = asmArch{name: "loong64", bigEndian: false, stack: "R3", lr: true, retRegs: []string{"R4", "F0"}} arches = []*asmArch{ &asmArch386, @@ -111,11 +112,11 @@ var ( &asmArchRISCV64, &asmArchS390X, &asmArchWasm, + &asmArchLoong64, } ) func init() { - arches = append(arches, additionalArches()...) for _, arch := range arches { arch.sizes = types.SizesFor("gc", arch.name) if arch.sizes == nil { @@ -172,7 +173,7 @@ func run(pass *analysis.Pass) (interface{}, error) { Files: for _, fname := range sfiles { - content, tf, err := analysisutil.ReadFile(pass.Fset, fname) + content, tf, err := analysisutil.ReadFile(pass, fname) if err != nil { return nil, err } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/assign/assign.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/assign/assign.go index 10489bea1..3bfd50122 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/assign/assign.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/assign/assign.go @@ -18,6 +18,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/inspector" ) @@ -77,7 +78,7 @@ func run(pass *analysis.Pass) (interface{}, error) { // isMapIndex returns true if e is a map index expression. func isMapIndex(info *types.Info, e ast.Expr) bool { - if idx, ok := analysisutil.Unparen(e).(*ast.IndexExpr); ok { + if idx, ok := astutil.Unparen(e).(*ast.IndexExpr); ok { if typ := info.Types[idx.X].Type; typ != nil { _, ok := typ.Underlying().(*types.Map) return ok diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/atomic/atomic.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/atomic/atomic.go index b40e081ec..931f9ca75 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/atomic/atomic.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/atomic/atomic.go @@ -8,12 +8,12 @@ import ( _ "embed" "go/ast" "go/token" - "go/types" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/go/types/typeutil" ) //go:embed doc.go @@ -52,18 +52,8 @@ func run(pass *analysis.Pass) (interface{}, error) { if !ok { continue } - sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok { - continue - } - pkgIdent, _ := sel.X.(*ast.Ident) - pkgName, ok := pass.TypesInfo.Uses[pkgIdent].(*types.PkgName) - if !ok || pkgName.Imported().Path() != "sync/atomic" { - continue - } - - switch sel.Sel.Name { - case "AddInt32", "AddInt64", "AddUint32", "AddUint64", "AddUintptr": + fn := typeutil.StaticCallee(pass.TypesInfo, call) + if analysisutil.IsFunctionNamed(fn, "sync/atomic", "AddInt32", "AddInt64", "AddUint32", "AddUint64", "AddUintptr") { checkAtomicAddAssignment(pass, n.Lhs[i], call) } } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/atomicalign/atomicalign.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/atomicalign/atomicalign.go index 01683e45a..aff6d25b3 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/atomicalign/atomicalign.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/atomicalign/atomicalign.go @@ -18,6 +18,7 @@ import ( "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/go/types/typeutil" ) const Doc = "check for non-64-bits-aligned arguments to sync/atomic functions" @@ -42,31 +43,20 @@ func run(pass *analysis.Pass) (interface{}, error) { nodeFilter := []ast.Node{ (*ast.CallExpr)(nil), } + funcNames := []string{ + "AddInt64", "AddUint64", + "LoadInt64", "LoadUint64", + "StoreInt64", "StoreUint64", + "SwapInt64", "SwapUint64", + "CompareAndSwapInt64", "CompareAndSwapUint64", + } inspect.Preorder(nodeFilter, func(node ast.Node) { call := node.(*ast.CallExpr) - sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok { - return - } - pkgIdent, ok := sel.X.(*ast.Ident) - if !ok { - return - } - pkgName, ok := pass.TypesInfo.Uses[pkgIdent].(*types.PkgName) - if !ok || pkgName.Imported().Path() != "sync/atomic" { - return - } - - switch sel.Sel.Name { - case "AddInt64", "AddUint64", - "LoadInt64", "LoadUint64", - "StoreInt64", "StoreUint64", - "SwapInt64", "SwapUint64", - "CompareAndSwapInt64", "CompareAndSwapUint64": - + fn := typeutil.StaticCallee(pass.TypesInfo, call) + if analysisutil.IsFunctionNamed(fn, "sync/atomic", funcNames...) { // For all the listed functions, the expression to check is always the first function argument. - check64BitAlignment(pass, sel.Sel.Name, call.Args[0]) + check64BitAlignment(pass, fn.Name(), call.Args[0]) } }) diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/bools/bools.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/bools/bools.go index 4219f087b..564329774 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/bools/bools.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/bools/bools.go @@ -14,6 +14,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/inspector" ) @@ -83,7 +84,7 @@ func (op boolOp) commutativeSets(info *types.Info, e *ast.BinaryExpr, seen map[* i := 0 var sets [][]ast.Expr for j := 0; j <= len(exprs); j++ { - if j == len(exprs) || hasSideEffects(info, exprs[j]) { + if j == len(exprs) || analysisutil.HasSideEffects(info, exprs[j]) { if i < j { sets = append(sets, exprs[i:j]) } @@ -162,46 +163,13 @@ func (op boolOp) checkSuspect(pass *analysis.Pass, exprs []ast.Expr) { } } -// hasSideEffects reports whether evaluation of e has side effects. -func hasSideEffects(info *types.Info, e ast.Expr) bool { - safe := true - ast.Inspect(e, func(node ast.Node) bool { - switch n := node.(type) { - case *ast.CallExpr: - typVal := info.Types[n.Fun] - switch { - case typVal.IsType(): - // Type conversion, which is safe. - case typVal.IsBuiltin(): - // Builtin func, conservatively assumed to not - // be safe for now. - safe = false - return false - default: - // A non-builtin func or method call. - // Conservatively assume that all of them have - // side effects for now. - safe = false - return false - } - case *ast.UnaryExpr: - if n.Op == token.ARROW { - safe = false - return false - } - } - return true - }) - return !safe -} - // split returns a slice of all subexpressions in e that are connected by op. // For example, given 'a || (b || c) || d' with the or op, // split returns []{d, c, b, a}. // seen[e] is already true; any newly processed exprs are added to seen. func (op boolOp) split(e ast.Expr, seen map[*ast.BinaryExpr]bool) (exprs []ast.Expr) { for { - e = unparen(e) + e = astutil.Unparen(e) if b, ok := e.(*ast.BinaryExpr); ok && b.Op == op.tok { seen[b] = true exprs = append(exprs, op.split(b.Y, seen)...) @@ -213,14 +181,3 @@ func (op boolOp) split(e ast.Expr, seen map[*ast.BinaryExpr]bool) (exprs []ast.E } return } - -// unparen returns e with any enclosing parentheses stripped. -func unparen(e ast.Expr) ast.Expr { - for { - p, ok := e.(*ast.ParenExpr) - if !ok { - return e - } - e = p.X - } -} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/buildssa/buildssa.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/buildssa/buildssa.go index 881b8fd67..f077ea282 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/buildssa/buildssa.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/buildssa/buildssa.go @@ -26,15 +26,13 @@ var Analyzer = &analysis.Analyzer{ } // SSA provides SSA-form intermediate representation for all the -// non-blank source functions in the current package. +// source functions in the current package. type SSA struct { Pkg *ssa.Package SrcFuncs []*ssa.Function } func run(pass *analysis.Pass) (interface{}, error) { - // Plundered from ssautil.BuildPackage. - // We must create a new Program for each Package because the // analysis API provides no place to hang a Program shared by // all Packages. Consequently, SSA Packages and Functions do not @@ -51,20 +49,10 @@ func run(pass *analysis.Pass) (interface{}, error) { prog := ssa.NewProgram(pass.Fset, mode) - // Create SSA packages for all imports. - // Order is not significant. - created := make(map[*types.Package]bool) - var createAll func(pkgs []*types.Package) - createAll = func(pkgs []*types.Package) { - for _, p := range pkgs { - if !created[p] { - created[p] = true - prog.CreatePackage(p, nil, nil, true) - createAll(p.Imports()) - } - } + // Create SSA packages for direct imports. + for _, p := range pass.Pkg.Imports() { + prog.CreatePackage(p, nil, nil, true) } - createAll(pass.Pkg.Imports()) // Create and build the primary package. ssapkg := prog.CreatePackage(pass.Pkg, pass.Files, pass.TypesInfo, false) @@ -76,16 +64,6 @@ func run(pass *analysis.Pass) (interface{}, error) { for _, f := range pass.Files { for _, decl := range f.Decls { if fdecl, ok := decl.(*ast.FuncDecl); ok { - - // SSA will not build a Function - // for a FuncDecl named blank. - // That's arguably too strict but - // relaxing it would break uniqueness of - // names of package members. - if fdecl.Name.Name == "_" { - continue - } - // (init functions have distinct Func // objects named "init" and distinct // ssa.Functions named "init#1", ...) diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag.go index 55bdad78b..b5a2d2775 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag.go @@ -2,9 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build go1.16 -// +build go1.16 - // Package buildtag defines an Analyzer that checks build tags. package buildtag @@ -18,6 +15,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/internal/versions" ) const Doc = "check //go:build and // +build directives" @@ -89,7 +87,7 @@ func checkOtherFile(pass *analysis.Pass, filename string) error { // We cannot use the Go parser, since this may not be a Go source file. // Read the raw bytes instead. - content, tf, err := analysisutil.ReadFile(pass.Fset, filename) + content, tf, err := analysisutil.ReadFile(pass, filename) if err != nil { return err } @@ -267,6 +265,8 @@ func (check *checker) goBuildLine(pos token.Pos, line string) { return } + check.tags(pos, x) + if check.goBuild == nil { check.goBuild = x } @@ -326,6 +326,8 @@ func (check *checker) plusBuildLine(pos token.Pos, line string) { check.crossCheck = false return } + check.tags(pos, y) + if check.plusBuild == nil { check.plusBuild = y } else { @@ -366,3 +368,51 @@ func (check *checker) finish() { return } } + +// tags reports issues in go versions in tags within the expression e. +func (check *checker) tags(pos token.Pos, e constraint.Expr) { + // Check that constraint.GoVersion is meaningful (>= go1.21). + if versions.ConstraintGoVersion == nil { + return + } + + // Use Eval to visit each tag. + _ = e.Eval(func(tag string) bool { + if malformedGoTag(tag) { + check.pass.Reportf(pos, "invalid go version %q in build constraint", tag) + } + return false // result is immaterial as Eval does not short-circuit + }) +} + +// malformedGoTag returns true if a tag is likely to be a malformed +// go version constraint. +func malformedGoTag(tag string) bool { + // Not a go version? + if !strings.HasPrefix(tag, "go1") { + // Check for close misspellings of the "go1." prefix. + for _, pre := range []string{"go.", "g1.", "go"} { + suffix := strings.TrimPrefix(tag, pre) + if suffix != tag { + if valid, ok := validTag("go1." + suffix); ok && valid { + return true + } + } + } + return false + } + + // The tag starts with "go1" so it is almost certainly a GoVersion. + // Report it if it is not a valid build constraint. + valid, ok := validTag(tag) + return ok && !valid +} + +// validTag returns (valid, ok) where valid reports when a tag is valid, +// and ok reports determining if the tag is valid succeeded. +func validTag(tag string) (valid bool, ok bool) { + if versions.ConstraintGoVersion != nil { + return versions.ConstraintGoVersion(&constraint.TagExpr{Tag: tag}) != "", true + } + return false, false +} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag_old.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag_old.go deleted file mode 100644 index 0001ba536..000000000 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/buildtag/buildtag_old.go +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// TODO(rsc): Delete this file once Go 1.17 comes out and we can retire Go 1.15 support. - -//go:build !go1.16 -// +build !go1.16 - -// Package buildtag defines an Analyzer that checks build tags. -package buildtag - -import ( - "bytes" - "fmt" - "go/ast" - "go/parser" - "strings" - "unicode" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/internal/analysisutil" -) - -const Doc = "check // +build directives" - -var Analyzer = &analysis.Analyzer{ - Name: "buildtag", - Doc: Doc, - Run: runBuildTag, -} - -func runBuildTag(pass *analysis.Pass) (interface{}, error) { - for _, f := range pass.Files { - checkGoFile(pass, f) - } - for _, name := range pass.OtherFiles { - if err := checkOtherFile(pass, name); err != nil { - return nil, err - } - } - for _, name := range pass.IgnoredFiles { - if strings.HasSuffix(name, ".go") { - f, err := parser.ParseFile(pass.Fset, name, nil, parser.ParseComments) - if err != nil { - // Not valid Go source code - not our job to diagnose, so ignore. - return nil, nil - } - checkGoFile(pass, f) - } else { - if err := checkOtherFile(pass, name); err != nil { - return nil, err - } - } - } - return nil, nil -} - -func checkGoFile(pass *analysis.Pass, f *ast.File) { - pastCutoff := false - for _, group := range f.Comments { - // A +build comment is ignored after or adjoining the package declaration. - if group.End()+1 >= f.Package { - pastCutoff = true - } - - // "+build" is ignored within or after a /*...*/ comment. - if !strings.HasPrefix(group.List[0].Text, "//") { - pastCutoff = true - continue - } - - // Check each line of a //-comment. - for _, c := range group.List { - if !strings.Contains(c.Text, "+build") { - continue - } - if err := checkLine(c.Text, pastCutoff); err != nil { - pass.Reportf(c.Pos(), "%s", err) - } - } - } -} - -func checkOtherFile(pass *analysis.Pass, filename string) error { - content, tf, err := analysisutil.ReadFile(pass.Fset, filename) - if err != nil { - return err - } - - // We must look at the raw lines, as build tags may appear in non-Go - // files such as assembly files. - lines := bytes.SplitAfter(content, nl) - - // Determine cutpoint where +build comments are no longer valid. - // They are valid in leading // comments in the file followed by - // a blank line. - // - // This must be done as a separate pass because of the - // requirement that the comment be followed by a blank line. - var cutoff int - for i, line := range lines { - line = bytes.TrimSpace(line) - if !bytes.HasPrefix(line, slashSlash) { - if len(line) > 0 { - break - } - cutoff = i - } - } - - for i, line := range lines { - line = bytes.TrimSpace(line) - if !bytes.HasPrefix(line, slashSlash) { - continue - } - if !bytes.Contains(line, []byte("+build")) { - continue - } - if err := checkLine(string(line), i >= cutoff); err != nil { - pass.Reportf(analysisutil.LineStart(tf, i+1), "%s", err) - continue - } - } - return nil -} - -// checkLine checks a line that starts with "//" and contains "+build". -func checkLine(line string, pastCutoff bool) error { - line = strings.TrimPrefix(line, "//") - line = strings.TrimSpace(line) - - if strings.HasPrefix(line, "+build") { - fields := strings.Fields(line) - if fields[0] != "+build" { - // Comment is something like +buildasdf not +build. - return fmt.Errorf("possible malformed +build comment") - } - if pastCutoff { - return fmt.Errorf("+build comment must appear before package clause and be followed by a blank line") - } - if err := checkArguments(fields); err != nil { - return err - } - } else { - // Comment with +build but not at beginning. - if !pastCutoff { - return fmt.Errorf("possible malformed +build comment") - } - } - return nil -} - -func checkArguments(fields []string) error { - for _, arg := range fields[1:] { - for _, elem := range strings.Split(arg, ",") { - if strings.HasPrefix(elem, "!!") { - return fmt.Errorf("invalid double negative in build constraint: %s", arg) - } - elem = strings.TrimPrefix(elem, "!") - for _, c := range elem { - if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' { - return fmt.Errorf("invalid non-alphanumeric build constraint: %s", arg) - } - } - } - } - return nil -} - -var ( - nl = []byte("\n") - slashSlash = []byte("//") -) diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/cgocall/cgocall.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/cgocall/cgocall.go index 98d9a777a..4e8643975 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/cgocall/cgocall.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/cgocall/cgocall.go @@ -19,6 +19,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/go/ast/astutil" ) const debug = false @@ -64,7 +65,7 @@ func checkCgo(fset *token.FileSet, f *ast.File, info *types.Info, reportf func(t // Is this a C.f() call? var name string - if sel, ok := analysisutil.Unparen(call.Fun).(*ast.SelectorExpr); ok { + if sel, ok := astutil.Unparen(call.Fun).(*ast.SelectorExpr); ok { if id, ok := sel.X.(*ast.Ident); ok && id.Name == "C" { name = sel.Sel.Name } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/composite/composite.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/composite/composite.go index c7a49776f..8cc6c4a05 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/composite/composite.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/composite/composite.go @@ -15,6 +15,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -71,8 +72,8 @@ func run(pass *analysis.Pass) (interface{}, error) { return } var structuralTypes []types.Type - switch typ := typ.(type) { - case *typeparams.TypeParam: + switch typ := aliases.Unalias(typ).(type) { + case *types.TypeParam: terms, err := typeparams.StructuralTerms(typ) if err != nil { return // invalid type @@ -83,9 +84,9 @@ func run(pass *analysis.Pass) (interface{}, error) { default: structuralTypes = append(structuralTypes, typ) } + for _, typ := range structuralTypes { - under := deref(typ.Underlying()) - strct, ok := under.(*types.Struct) + strct, ok := typeparams.Deref(typ).Underlying().(*types.Struct) if !ok { // skip non-struct composite literals continue @@ -142,29 +143,18 @@ func run(pass *analysis.Pass) (interface{}, error) { return nil, nil } -func deref(typ types.Type) types.Type { - for { - ptr, ok := typ.(*types.Pointer) - if !ok { - break - } - typ = ptr.Elem().Underlying() - } - return typ -} - +// isLocalType reports whether typ belongs to the same package as pass. +// TODO(adonovan): local means "internal to a function"; rename to isSamePackageType. func isLocalType(pass *analysis.Pass, typ types.Type) bool { - switch x := typ.(type) { + switch x := aliases.Unalias(typ).(type) { case *types.Struct: // struct literals are local types return true case *types.Pointer: return isLocalType(pass, x.Elem()) - case *types.Named: + case interface{ Obj() *types.TypeName }: // *Named or *TypeParam (aliases were removed already) // names in package foo are local to foo_test too return strings.TrimSuffix(x.Obj().Pkg().Path(), "_test") == strings.TrimSuffix(pass.Pkg.Path(), "_test") - case *typeparams.TypeParam: - return strings.TrimSuffix(x.Obj().Pkg().Path(), "_test") == strings.TrimSuffix(pass.Pkg.Path(), "_test") } return false } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/copylock/copylock.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/copylock/copylock.go index ec7727de7..8f6e7db6a 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/copylock/copylock.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/copylock/copylock.go @@ -16,7 +16,9 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -29,7 +31,7 @@ values should be referred to through a pointer.` var Analyzer = &analysis.Analyzer{ Name: "copylocks", Doc: Doc, - URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/copylocks", + URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/copylock", Requires: []*analysis.Analyzer{inspect.Analyzer}, RunDespiteErrors: true, Run: run, @@ -223,7 +225,7 @@ func (path typePath) String() string { } func lockPathRhs(pass *analysis.Pass, x ast.Expr) typePath { - x = analysisutil.Unparen(x) // ignore parens on rhs + x = astutil.Unparen(x) // ignore parens on rhs if _, ok := x.(*ast.CompositeLit); ok { return nil @@ -233,12 +235,15 @@ func lockPathRhs(pass *analysis.Pass, x ast.Expr) typePath { return nil } if star, ok := x.(*ast.StarExpr); ok { - if _, ok := analysisutil.Unparen(star.X).(*ast.CallExpr); ok { + if _, ok := astutil.Unparen(star.X).(*ast.CallExpr); ok { // A call may return a pointer to a zero value. return nil } } - return lockPath(pass.Pkg, pass.TypesInfo.Types[x].Type, nil) + if tv, ok := pass.TypesInfo.Types[x]; ok && tv.IsValue() { + return lockPath(pass.Pkg, tv.Type, nil) + } + return nil } // lockPath returns a typePath describing the location of a lock value @@ -254,7 +259,7 @@ func lockPath(tpkg *types.Package, typ types.Type, seen map[types.Type]bool) typ } seen[typ] = true - if tpar, ok := typ.(*typeparams.TypeParam); ok { + if tpar, ok := aliases.Unalias(typ).(*types.TypeParam); ok { terms, err := typeparams.StructuralTerms(tpar) if err != nil { return nil // invalid type @@ -319,9 +324,7 @@ func lockPath(tpkg *types.Package, typ types.Type, seen map[types.Type]bool) typ // In go1.10, sync.noCopy did not implement Locker. // (The Unlock method was added only in CL 121876.) // TODO(adonovan): remove workaround when we drop go1.10. - if named, ok := typ.(*types.Named); ok && - named.Obj().Name() == "noCopy" && - named.Obj().Pkg().Path() == "sync" { + if analysisutil.IsNamedType(typ, "sync", "noCopy") { return []string{typ.String()} } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/deepequalerrors/deepequalerrors.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/deepequalerrors/deepequalerrors.go index 3a1818764..95cd9a061 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/deepequalerrors/deepequalerrors.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/deepequalerrors/deepequalerrors.go @@ -15,6 +15,7 @@ import ( "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/aliases" ) const Doc = `check for calls of reflect.DeepEqual on error values @@ -46,11 +47,8 @@ func run(pass *analysis.Pass) (interface{}, error) { } inspect.Preorder(nodeFilter, func(n ast.Node) { call := n.(*ast.CallExpr) - fn, ok := typeutil.Callee(pass.TypesInfo, call).(*types.Func) - if !ok { - return - } - if fn.FullName() == "reflect.DeepEqual" && hasError(pass, call.Args[0]) && hasError(pass, call.Args[1]) { + fn, _ := typeutil.Callee(pass.TypesInfo, call).(*types.Func) + if analysisutil.IsFunctionNamed(fn, "reflect", "DeepEqual") && hasError(pass, call.Args[0]) && hasError(pass, call.Args[1]) { pass.ReportRangef(call, "avoid using reflect.DeepEqual with errors") } }) @@ -104,7 +102,7 @@ func containsError(typ types.Type) bool { return true } } - case *types.Named: + case *types.Named, *aliases.Alias: return check(t.Underlying()) // We list the remaining valid type kinds for completeness. diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/defers/defers.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/defers/defers.go index ed2a122f2..5e8e80a6a 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/defers/defers.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/defers/defers.go @@ -7,7 +7,6 @@ package defers import ( _ "embed" "go/ast" - "go/types" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" @@ -36,8 +35,7 @@ func run(pass *analysis.Pass) (interface{}, error) { checkDeferCall := func(node ast.Node) bool { switch v := node.(type) { case *ast.CallExpr: - fn, ok := typeutil.Callee(pass.TypesInfo, v).(*types.Func) - if ok && fn.Name() == "Since" && fn.Pkg().Path() == "time" { + if analysisutil.IsFunctionNamed(typeutil.StaticCallee(pass.TypesInfo, v), "time", "Since") { pass.Reportf(v.Pos(), "call to time.Since is not deferred") } case *ast.FuncLit: diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/directive/directive.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/directive/directive.go index 2691f189a..b20540238 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/directive/directive.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/directive/directive.go @@ -70,11 +70,7 @@ func checkGoFile(pass *analysis.Pass, f *ast.File) { check := newChecker(pass, pass.Fset.File(f.Package).Name(), f) for _, group := range f.Comments { - // A +build comment is ignored after or adjoining the package declaration. - if group.End()+1 >= f.Package { - check.inHeader = false - } - // A //go:build comment is ignored after the package declaration + // A //go:build or a //go:debug comment is ignored after the package declaration // (but adjoining it is OK, in contrast to +build comments). if group.Pos() >= f.Package { check.inHeader = false @@ -90,7 +86,7 @@ func checkGoFile(pass *analysis.Pass, f *ast.File) { func checkOtherFile(pass *analysis.Pass, filename string) error { // We cannot use the Go parser, since is not a Go source file. // Read the raw bytes instead. - content, tf, err := analysisutil.ReadFile(pass.Fset, filename) + content, tf, err := analysisutil.ReadFile(pass, filename) if err != nil { return err } @@ -104,8 +100,7 @@ type checker struct { pass *analysis.Pass filename string file *ast.File // nil for non-Go file - inHeader bool // in file header (before package declaration) - inStar bool // currently in a /* */ comment + inHeader bool // in file header (before or adjoining package declaration) } func newChecker(pass *analysis.Pass, filename string, file *ast.File) *checker { diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/errorsas/errorsas.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/errorsas/errorsas.go index 2fcbdfafb..7f62ad4c8 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/errorsas/errorsas.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/errorsas/errorsas.go @@ -51,15 +51,12 @@ func run(pass *analysis.Pass) (interface{}, error) { inspect.Preorder(nodeFilter, func(n ast.Node) { call := n.(*ast.CallExpr) fn := typeutil.StaticCallee(pass.TypesInfo, call) - if fn == nil { - return // not a static call + if !analysisutil.IsFunctionNamed(fn, "errors", "As") { + return } if len(call.Args) < 2 { return // not enough arguments, e.g. called with return values of another function } - if fn.FullName() != "errors.As" { - return - } if err := checkAsTarget(pass, call.Args[1]); err != nil { pass.ReportRangef(call, "%v", err) } @@ -69,9 +66,6 @@ func run(pass *analysis.Pass) (interface{}, error) { var errorType = types.Universe.Lookup("error").Type() -// pointerToInterfaceOrError reports whether the type of e is a pointer to an interface or a type implementing error, -// or is the empty interface. - // checkAsTarget reports an error if the second argument to errors.As is invalid. func checkAsTarget(pass *analysis.Pass, e ast.Expr) error { t := pass.TypesInfo.Types[e].Type diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/fieldalignment/fieldalignment.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/fieldalignment/fieldalignment.go index 012e2ecd0..8af717b4c 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/fieldalignment/fieldalignment.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/fieldalignment/fieldalignment.go @@ -46,6 +46,15 @@ Be aware that the most compact order is not always the most efficient. In rare cases it may cause two variables each updated by its own goroutine to occupy the same CPU cache line, inducing a form of memory contention known as "false sharing" that slows down both goroutines. + +Unlike most analyzers, which report likely mistakes, the diagnostics +produced by fieldanalyzer very rarely indicate a significant problem, +so the analyzer is not included in typical suites such as vet or +gopls. Use this standalone command to run it on your code: + + $ go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest + $ go fieldalignment [packages] + ` var Analyzer = &analysis.Analyzer{ diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/framepointer/framepointer.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/framepointer/framepointer.go index 0b3ded47e..6eff3a20f 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/framepointer/framepointer.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/framepointer/framepointer.go @@ -48,7 +48,7 @@ func run(pass *analysis.Pass) (interface{}, error) { } for _, fname := range sfiles { - content, tf, err := analysisutil.ReadFile(pass.Fset, fname) + content, tf, err := analysisutil.ReadFile(pass, fname) if err != nil { return nil, err } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/httpresponse/httpresponse.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/httpresponse/httpresponse.go index 61c3b764f..e1ca9b2f5 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/httpresponse/httpresponse.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/httpresponse/httpresponse.go @@ -14,6 +14,8 @@ import ( "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/typesinternal" ) const Doc = `check for mistakes using HTTP responses @@ -116,7 +118,8 @@ func isHTTPFuncOrMethodOnClient(info *types.Info, expr *ast.CallExpr) bool { if res.Len() != 2 { return false // the function called does not return two values. } - if ptr, ok := res.At(0).Type().(*types.Pointer); !ok || !isNamedType(ptr.Elem(), "net/http", "Response") { + isPtr, named := typesinternal.ReceiverNamed(res.At(0)) + if !isPtr || named == nil || !analysisutil.IsNamedType(named, "net/http", "Response") { return false // the first return type is not *http.Response. } @@ -131,11 +134,11 @@ func isHTTPFuncOrMethodOnClient(info *types.Info, expr *ast.CallExpr) bool { return ok && id.Name == "http" // function in net/http package. } - if isNamedType(typ, "net/http", "Client") { + if analysisutil.IsNamedType(typ, "net/http", "Client") { return true // method on http.Client. } - ptr, ok := typ.(*types.Pointer) - return ok && isNamedType(ptr.Elem(), "net/http", "Client") // method on *http.Client. + ptr, ok := aliases.Unalias(typ).(*types.Pointer) + return ok && analysisutil.IsNamedType(ptr.Elem(), "net/http", "Client") // method on *http.Client. } // restOfBlock, given a traversal stack, finds the innermost containing @@ -171,13 +174,3 @@ func rootIdent(n ast.Node) *ast.Ident { return nil } } - -// isNamedType reports whether t is the named type path.name. -func isNamedType(t types.Type, path, name string) bool { - n, ok := t.(*types.Named) - if !ok { - return false - } - obj := n.Obj() - return obj.Name() == name && obj.Pkg() != nil && obj.Pkg().Path() == path -} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/ifaceassert.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/ifaceassert.go index cd4a47762..5f07ed3ff 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/ifaceassert.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/ifaceassert.go @@ -13,6 +13,7 @@ import ( "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/typeparams" ) //go:embed doc.go @@ -28,7 +29,7 @@ var Analyzer = &analysis.Analyzer{ // assertableTo checks whether interface v can be asserted into t. It returns // nil on success, or the first conflicting method on failure. -func assertableTo(v, t types.Type) *types.Func { +func assertableTo(free *typeparams.Free, v, t types.Type) *types.Func { if t == nil || v == nil { // not assertable to, but there is no missing method return nil @@ -42,7 +43,7 @@ func assertableTo(v, t types.Type) *types.Func { // Mitigations for interface comparisons and generics. // TODO(https://github.com/golang/go/issues/50658): Support more precise conclusion. - if isParameterized(V) || isParameterized(T) { + if free.Has(V) || free.Has(T) { return nil } if f, wrongType := types.MissingMethod(V, T, false); wrongType { @@ -57,6 +58,7 @@ func run(pass *analysis.Pass) (interface{}, error) { (*ast.TypeAssertExpr)(nil), (*ast.TypeSwitchStmt)(nil), } + var free typeparams.Free inspect.Preorder(nodeFilter, func(n ast.Node) { var ( assert *ast.TypeAssertExpr // v.(T) expression @@ -86,7 +88,7 @@ func run(pass *analysis.Pass) (interface{}, error) { V := pass.TypesInfo.TypeOf(assert.X) for _, target := range targets { T := pass.TypesInfo.TypeOf(target) - if f := assertableTo(V, T); f != nil { + if f := assertableTo(&free, V, T); f != nil { pass.Reportf( target.Pos(), "impossible type assertion: no type can implement both %v and %v (conflicting types for %v method)", diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/parameterized.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/parameterized.go deleted file mode 100644 index b84577fcf..000000000 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/ifaceassert/parameterized.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ifaceassert - -import ( - "go/types" - - "golang.org/x/tools/internal/typeparams" -) - -// isParameterized reports whether typ contains any of the type parameters of tparams. -// -// NOTE: Adapted from go/types/infer.go. If that is exported in a future release remove this copy. -func isParameterized(typ types.Type) bool { - w := tpWalker{ - seen: make(map[types.Type]bool), - } - return w.isParameterized(typ) -} - -type tpWalker struct { - seen map[types.Type]bool -} - -func (w *tpWalker) isParameterized(typ types.Type) (res bool) { - // detect cycles - if x, ok := w.seen[typ]; ok { - return x - } - w.seen[typ] = false - defer func() { - w.seen[typ] = res - }() - - switch t := typ.(type) { - case nil, *types.Basic: // TODO(gri) should nil be handled here? - break - - case *types.Array: - return w.isParameterized(t.Elem()) - - case *types.Slice: - return w.isParameterized(t.Elem()) - - case *types.Struct: - for i, n := 0, t.NumFields(); i < n; i++ { - if w.isParameterized(t.Field(i).Type()) { - return true - } - } - - case *types.Pointer: - return w.isParameterized(t.Elem()) - - case *types.Tuple: - n := t.Len() - for i := 0; i < n; i++ { - if w.isParameterized(t.At(i).Type()) { - return true - } - } - - case *types.Signature: - // t.tparams may not be nil if we are looking at a signature - // of a generic function type (or an interface method) that is - // part of the type we're testing. We don't care about these type - // parameters. - // Similarly, the receiver of a method may declare (rather than - // use) type parameters, we don't care about those either. - // Thus, we only need to look at the input and result parameters. - return w.isParameterized(t.Params()) || w.isParameterized(t.Results()) - - case *types.Interface: - for i, n := 0, t.NumMethods(); i < n; i++ { - if w.isParameterized(t.Method(i).Type()) { - return true - } - } - terms, err := typeparams.InterfaceTermSet(t) - if err != nil { - panic(err) - } - for _, term := range terms { - if w.isParameterized(term.Type()) { - return true - } - } - - case *types.Map: - return w.isParameterized(t.Key()) || w.isParameterized(t.Elem()) - - case *types.Chan: - return w.isParameterized(t.Elem()) - - case *types.Named: - list := typeparams.NamedTypeArgs(t) - for i, n := 0, list.Len(); i < n; i++ { - if w.isParameterized(list.At(i)) { - return true - } - } - - case *typeparams.TypeParam: - return true - - default: - panic(t) // unreachable - } - - return false -} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/internal/analysisutil/util.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/internal/analysisutil/util.go index a8d84034d..f7f071dc8 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/internal/analysisutil/util.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/internal/analysisutil/util.go @@ -13,6 +13,10 @@ import ( "go/token" "go/types" "os" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/analysisinternal" ) // Format returns a string representation of the expression. @@ -55,25 +59,18 @@ func HasSideEffects(info *types.Info, e ast.Expr) bool { return !safe } -// Unparen returns e with any enclosing parentheses stripped. -func Unparen(e ast.Expr) ast.Expr { - for { - p, ok := e.(*ast.ParenExpr) - if !ok { - return e - } - e = p.X - } -} - // ReadFile reads a file and adds it to the FileSet // so that we can report errors against it using lineStart. -func ReadFile(fset *token.FileSet, filename string) ([]byte, *token.File, error) { - content, err := os.ReadFile(filename) +func ReadFile(pass *analysis.Pass, filename string) ([]byte, *token.File, error) { + readFile := pass.ReadFile + if readFile == nil { + readFile = os.ReadFile + } + content, err := readFile(filename) if err != nil { return nil, nil, err } - tf := fset.AddFile(filename, -1, len(content)) + tf := pass.Fset.AddFile(filename, -1, len(content)) tf.SetLinesForContent(content) return content, tf, nil } @@ -118,3 +115,48 @@ func Imports(pkg *types.Package, path string) bool { } return false } + +// IsNamedType reports whether t is the named type with the given package path +// and one of the given names. +// This function avoids allocating the concatenation of "pkg.Name", +// which is important for the performance of syntax matching. +func IsNamedType(t types.Type, pkgPath string, names ...string) bool { + n, ok := aliases.Unalias(t).(*types.Named) + if !ok { + return false + } + obj := n.Obj() + if obj == nil || obj.Pkg() == nil || obj.Pkg().Path() != pkgPath { + return false + } + name := obj.Name() + for _, n := range names { + if name == n { + return true + } + } + return false +} + +// IsFunctionNamed reports whether f is a top-level function defined in the +// given package and has one of the given names. +// It returns false if f is nil or a method. +func IsFunctionNamed(f *types.Func, pkgPath string, names ...string) bool { + if f == nil { + return false + } + if f.Pkg() == nil || f.Pkg().Path() != pkgPath { + return false + } + if f.Type().(*types.Signature).Recv() != nil { + return false + } + for _, n := range names { + if f.Name() == n { + return true + } + } + return false +} + +var MustExtractDoc = analysisinternal.MustExtractDoc diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/doc.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/doc.go index dc544df1b..c95b1c1c9 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/doc.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/doc.go @@ -14,8 +14,12 @@ // in such a way (e.g. with go or defer) that it may outlive the loop // iteration and possibly observe the wrong value of the variable. // +// Note: An iteration variable can only outlive a loop iteration in Go versions <=1.21. +// In Go 1.22 and later, the loop variable lifetimes changed to create a new +// iteration variable per loop iteration. (See go.dev/issue/60078.) +// // In this example, all the deferred functions run after the loop has -// completed, so all observe the final value of v. +// completed, so all observe the final value of v [. or // *.. - rtype := recv.Type() - if ptr, ok := recv.Type().(*types.Pointer); ok { - rtype = ptr.Elem() - } - named, ok := rtype.(*types.Named) - if !ok { - return false - } - if named.Obj().Name() != typeName { - return false - } - pkg := f.Pkg() - if pkg == nil { - return false - } - if pkg.Path() != pkgPath { - return false - } - - return true + _, named := typesinternal.ReceiverNamed(recv) + return analysisutil.IsNamedType(named, pkgPath, typeName) } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go index 2bccb6750..bf56a5c06 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go @@ -172,7 +172,18 @@ func runFunc(pass *analysis.Pass, node ast.Node) { if ret := lostCancelPath(pass, g, v, stmt, sig); ret != nil { lineno := pass.Fset.Position(stmt.Pos()).Line pass.ReportRangef(stmt, "the %s function is not used on all paths (possible context leak)", v.Name()) - pass.ReportRangef(ret, "this return statement may be reached without using the %s var defined on line %d", v.Name(), lineno) + + pos, end := ret.Pos(), ret.End() + // golang/go#64547: cfg.Block.Return may return a synthetic + // ReturnStmt that overflows the file. + if pass.Fset.File(pos) != pass.Fset.File(end) { + end = pos + } + pass.Report(analysis.Diagnostic{ + Pos: pos, + End: end, + Message: fmt.Sprintf("this return statement may be reached without using the %s var defined on line %d", v.Name(), lineno), + }) } } } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/nilfunc/nilfunc.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/nilfunc/nilfunc.go index 6df134399..778f7f1f8 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/nilfunc/nilfunc.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/nilfunc/nilfunc.go @@ -62,7 +62,7 @@ func run(pass *analysis.Pass) (interface{}, error) { obj = pass.TypesInfo.Uses[v] case *ast.SelectorExpr: obj = pass.TypesInfo.Uses[v.Sel] - case *ast.IndexExpr, *typeparams.IndexListExpr: + case *ast.IndexExpr, *ast.IndexListExpr: // Check generic functions such as "f[T1,T2]". x, _, _, _ := typeparams.UnpackIndexExpr(v) if id, ok := x.(*ast.Ident); ok { diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/doc.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/doc.go index 212263741..e27863e83 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/doc.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/doc.go @@ -42,4 +42,31 @@ // if p == nil { // panic(p) // } +// +// Sometimes the control flow may be quite complex, making bugs hard +// to spot. In the example below, the err.Error expression is +// guaranteed to panic because, after the first return, err must be +// nil. The intervening loop is just a distraction. +// +// ... +// err := g.Wait() +// if err != nil { +// return err +// } +// partialSuccess := false +// for _, err := range errs { +// if err == nil { +// partialSuccess = true +// break +// } +// } +// if partialSuccess { +// reportStatus(StatusMessage{ +// Code: code.ERROR, +// Detail: err.Error(), // "nil dereference in dynamic method call" +// }) +// return nil +// } +// +// ... package nilness diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/nilness.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/nilness.go index d1ca0748e..0c7e9c5d0 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/nilness.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/nilness/nilness.go @@ -14,6 +14,7 @@ import ( "golang.org/x/tools/go/analysis/passes/buildssa" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ssa" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -38,17 +39,21 @@ func run(pass *analysis.Pass) (interface{}, error) { func runFunc(pass *analysis.Pass, fn *ssa.Function) { reportf := func(category string, pos token.Pos, format string, args ...interface{}) { - pass.Report(analysis.Diagnostic{ - Pos: pos, - Category: category, - Message: fmt.Sprintf(format, args...), - }) + // We ignore nil-checking ssa.Instructions + // that don't correspond to syntax. + if pos.IsValid() { + pass.Report(analysis.Diagnostic{ + Pos: pos, + Category: category, + Message: fmt.Sprintf(format, args...), + }) + } } // notNil reports an error if v is provably nil. notNil := func(stack []fact, instr ssa.Instruction, v ssa.Value, descr string) { if nilnessOf(stack, v) == isnil { - reportf("nilderef", instr.Pos(), "nil dereference in "+descr) + reportf("nilderef", instr.Pos(), descr) } } @@ -73,29 +78,50 @@ func runFunc(pass *analysis.Pass, fn *ssa.Function) { // A nil receiver may be okay for type params. cc := instr.Common() if !(cc.IsInvoke() && typeparams.IsTypeParam(cc.Value.Type())) { - notNil(stack, instr, cc.Value, cc.Description()) + notNil(stack, instr, cc.Value, "nil dereference in "+cc.Description()) } case *ssa.FieldAddr: - notNil(stack, instr, instr.X, "field selection") + notNil(stack, instr, instr.X, "nil dereference in field selection") case *ssa.IndexAddr: - notNil(stack, instr, instr.X, "index operation") + switch typeparams.CoreType(instr.X.Type()).(type) { + case *types.Pointer: // *array + notNil(stack, instr, instr.X, "nil dereference in array index operation") + case *types.Slice: + // This is not necessarily a runtime error, because + // it is usually dominated by a bounds check. + if isRangeIndex(instr) { + notNil(stack, instr, instr.X, "range of nil slice") + } else { + notNil(stack, instr, instr.X, "index of nil slice") + } + } case *ssa.MapUpdate: - notNil(stack, instr, instr.Map, "map update") + notNil(stack, instr, instr.Map, "nil dereference in map update") + case *ssa.Range: + // (Not a runtime error, but a likely mistake.) + notNil(stack, instr, instr.X, "range over nil map") case *ssa.Slice: // A nilcheck occurs in ptr[:] iff ptr is a pointer to an array. - if _, ok := instr.X.Type().Underlying().(*types.Pointer); ok { - notNil(stack, instr, instr.X, "slice operation") + if is[*types.Pointer](instr.X.Type().Underlying()) { + notNil(stack, instr, instr.X, "nil dereference in slice operation") } case *ssa.Store: - notNil(stack, instr, instr.Addr, "store") + notNil(stack, instr, instr.Addr, "nil dereference in store") case *ssa.TypeAssert: if !instr.CommaOk { - notNil(stack, instr, instr.X, "type assertion") + notNil(stack, instr, instr.X, "nil dereference in type assertion") } case *ssa.UnOp: - if instr.Op == token.MUL { // *X - notNil(stack, instr, instr.X, "load") + switch instr.Op { + case token.MUL: // *X + notNil(stack, instr, instr.X, "nil dereference in load") + case token.ARROW: // <-ch + // (Not a runtime error, but a likely mistake.) + notNil(stack, instr, instr.X, "receive from nil channel") } + case *ssa.Send: + // (Not a runtime error, but a likely mistake.) + notNil(stack, instr, instr.Chan, "send to nil channel") } } @@ -161,7 +187,7 @@ func runFunc(pass *analysis.Pass, fn *ssa.Function) { // t successor learns y is nil. newFacts = expandFacts(fact{binop.Y, isnil}) } else { - // x is nil, y is unknown: + // y is nil, x is unknown: // t successor learns x is nil. newFacts = expandFacts(fact{binop.X, isnil}) } @@ -185,6 +211,42 @@ func runFunc(pass *analysis.Pass, fn *ssa.Function) { } } + // In code of the form: + // + // if ptr, ok := x.(*T); ok { ... } else { fsucc } + // + // the fsucc block learns that ptr == nil, + // since that's its zero value. + if If, ok := b.Instrs[len(b.Instrs)-1].(*ssa.If); ok { + // Handle "if ok" and "if !ok" variants. + cond, fsucc := If.Cond, b.Succs[1] + if unop, ok := cond.(*ssa.UnOp); ok && unop.Op == token.NOT { + cond, fsucc = unop.X, b.Succs[0] + } + + // Match pattern: + // t0 = typeassert (pointerlike) + // t1 = extract t0 #0 // ptr + // t2 = extract t0 #1 // ok + // if t2 goto tsucc, fsucc + if extract1, ok := cond.(*ssa.Extract); ok && extract1.Index == 1 { + if assert, ok := extract1.Tuple.(*ssa.TypeAssert); ok && + isNillable(assert.AssertedType) { + for _, pinstr := range *assert.Referrers() { + if extract0, ok := pinstr.(*ssa.Extract); ok && + extract0.Index == 0 && + extract0.Tuple == extract1.Tuple { + for _, d := range b.Dominees() { + if len(d.Preds) == 1 && d == fsucc { + visit(d, append(stack, fact{extract0, isnil})) + } + } + } + } + } + } + } + for _, d := range b.Dominees() { visit(d, stack) } @@ -220,6 +282,7 @@ func (n nilness) String() string { return nilnessStrings[n+1] } // nilnessOf reports whether v is definitely nil, definitely not nil, // or unknown given the dominating stack of facts. func nilnessOf(stack []fact, v ssa.Value) nilness { + switch v := v.(type) { // unwrap ChangeInterface and Slice values recursively, to detect if underlying // values have any facts recorded or are otherwise known with regard to nilness. @@ -235,6 +298,24 @@ func nilnessOf(stack []fact, v ssa.Value) nilness { if underlying := nilnessOf(stack, v.X); underlying != unknown { return underlying } + case *ssa.MakeInterface: + // A MakeInterface is non-nil unless its operand is a type parameter. + tparam, ok := aliases.Unalias(v.X.Type()).(*types.TypeParam) + if !ok { + return isnonnil + } + + // A MakeInterface of a type parameter is non-nil if + // the type parameter cannot be instantiated as an + // interface type (#66835). + if terms, err := typeparams.NormalTerms(tparam.Constraint()); err == nil && len(terms) > 0 { + return isnonnil + } + + // If the type parameter can be instantiated as an + // interface (and thus also as a concrete type), + // we can't determine the nilness. + case *ssa.Slice: if underlying := nilnessOf(stack, v.X); underlying != unknown { return underlying @@ -271,10 +352,10 @@ func nilnessOf(stack []fact, v ssa.Value) nilness { *ssa.IndexAddr, *ssa.MakeChan, *ssa.MakeClosure, - *ssa.MakeInterface, *ssa.MakeMap, *ssa.MakeSlice: return isnonnil + case *ssa.Const: if v.IsNil() { return isnil // nil or zero value of a pointer-like type @@ -356,3 +437,62 @@ func (ff facts) negate() facts { } return nn } + +func is[T any](x any) bool { + _, ok := x.(T) + return ok +} + +func isNillable(t types.Type) bool { + // TODO(adonovan): CoreType (+ case *Interface) looks wrong. + // This should probably use Underlying, and handle TypeParam + // by computing the union across its normal terms. + switch t := typeparams.CoreType(t).(type) { + case *types.Pointer, + *types.Map, + *types.Signature, + *types.Chan, + *types.Interface, + *types.Slice: + return true + case *types.Basic: + return t == types.Typ[types.UnsafePointer] + } + return false +} + +// isRangeIndex reports whether the instruction is a slice indexing +// operation slice[i] within a "for range slice" loop. The operation +// could be explicit, such as slice[i] within (or even after) the +// loop, or it could be implicit, such as "for i, v := range slice {}". +// (These cannot be reliably distinguished.) +func isRangeIndex(instr *ssa.IndexAddr) bool { + // Here we reverse-engineer the go/ssa lowering of range-over-slice: + // + // n = len(x) + // jump loop + // loop: "rangeindex.loop" + // phi = φ(-1, incr) #rangeindex + // incr = phi + 1 + // cond = incr < n + // if cond goto body else done + // body: "rangeindex.body" + // instr = &x[incr] + // ... + // done: + if incr, ok := instr.Index.(*ssa.BinOp); ok && incr.Op == token.ADD { + if b := incr.Block(); b.Comment == "rangeindex.loop" { + if If, ok := b.Instrs[len(b.Instrs)-1].(*ssa.If); ok { + if cond := If.Cond.(*ssa.BinOp); cond.X == incr && cond.Op == token.LSS { + if call, ok := cond.Y.(*ssa.Call); ok { + common := call.Common() + if blt, ok := common.Value.(*ssa.Builtin); ok && blt.Name() == "len" { + return common.Args[0] == instr.X + } + } + } + } + } + } + return false +} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/doc.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/doc.go index 1ee16126a..eebf40208 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/doc.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/doc.go @@ -11,14 +11,65 @@ // // The check applies to calls of the formatting functions such as // [fmt.Printf] and [fmt.Sprintf], as well as any detected wrappers of -// those functions. +// those functions such as [log.Printf]. It reports a variety of +// mistakes such as syntax errors in the format string and mismatches +// (of number and type) between the verbs and their arguments. // -// In this example, the %d format operator requires an integer operand: +// See the documentation of the fmt package for the complete set of +// format operators and their operand types. +// +// # Examples +// +// The %d format operator requires an integer operand. +// Here it is incorrectly applied to a string: // // fmt.Printf("%d", "hello") // fmt.Printf format %d has arg "hello" of wrong type string // -// See the documentation of the fmt package for the complete set of -// format operators and their operand types. +// A call to Printf must have as many operands as there are "verbs" in +// the format string, not too few: +// +// fmt.Printf("%d") // fmt.Printf format reads arg 1, but call has 0 args +// +// nor too many: +// +// fmt.Printf("%d", 1, 2) // fmt.Printf call needs 1 arg, but has 2 args +// +// Explicit argument indexes must be no greater than the number of +// arguments: +// +// fmt.Printf("%[3]d", 1, 2) // fmt.Printf call has invalid argument index 3 +// +// The checker also uses a heuristic to report calls to Print-like +// functions that appear to have been intended for their Printf-like +// counterpart: +// +// log.Print("%d", 123) // log.Print call has possible formatting directive %d +// +// Conversely, it also reports calls to Printf-like functions with a +// non-constant format string and no other arguments: +// +// fmt.Printf(message) // non-constant format string in call to fmt.Printf +// +// Such calls may have been intended for the function's Print-like +// counterpart: if the value of message happens to contain "%", +// misformatting will occur. In this case, the checker additionally +// suggests a fix to turn the call into: +// +// fmt.Printf("%s", message) +// +// # Inferred printf wrappers +// +// Functions that delegate their arguments to fmt.Printf are +// considered "printf wrappers"; calls to them are subject to the same +// checking. In this example, logf is a printf wrapper: +// +// func logf(level int, format string, args ...any) { +// if enabled(level) { +// log.Printf(format, args...) +// } +// } +// +// logf(3, "invalid request: %v") // logf format reads arg 1, but call has 0 args // // To enable printf checking on a function that is not found by this // analyzer's heuristics (for example, because control is obscured by @@ -26,14 +77,19 @@ // // func MyPrintf(format string, args ...any) { // if false { -// _ = fmt.Sprintf(format, args...) // enable printf checker +// _ = fmt.Sprintf(format, args...) // enable printf checking // } // ... // } // -// The -funcs flag specifies a comma-separated list of names of additional -// known formatting functions or methods. If the name contains a period, -// it must denote a specific function using one of the following forms: +// # Specifying printf wrappers by flag +// +// The -funcs flag specifies a comma-separated list of names of +// additional known formatting functions or methods. (This legacy flag +// is rarely used due to the automatic inference described above.) +// +// If the name contains a period, it must denote a specific function +// using one of the following forms: // // dir/pkg.Function // dir/pkg.Type.Method diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go index b2b8c67c7..b3453f8fc 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go @@ -24,6 +24,7 @@ import ( "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -371,64 +372,29 @@ var isPrint = stringSet{ "(testing.TB).Skipf": true, } -// formatString returns the format string argument and its index within -// the given printf-like call expression. -// -// The last parameter before variadic arguments is assumed to be -// a format string. -// -// The first string literal or string constant is assumed to be a format string -// if the call's signature cannot be determined. -// -// If it cannot find any format string parameter, it returns ("", -1). -func formatString(pass *analysis.Pass, call *ast.CallExpr) (format string, idx int) { +// formatStringIndex returns the index of the format string (the last +// non-variadic parameter) within the given printf-like call +// expression, or -1 if unknown. +func formatStringIndex(pass *analysis.Pass, call *ast.CallExpr) int { typ := pass.TypesInfo.Types[call.Fun].Type - if typ != nil { - if sig, ok := typ.(*types.Signature); ok { - if !sig.Variadic() { - // Skip checking non-variadic functions. - return "", -1 - } - idx := sig.Params().Len() - 2 - if idx < 0 { - // Skip checking variadic functions without - // fixed arguments. - return "", -1 - } - s, ok := stringConstantArg(pass, call, idx) - if !ok { - // The last argument before variadic args isn't a string. - return "", -1 - } - return s, idx - } + if typ == nil { + return -1 // missing type } - - // Cannot determine call's signature. Fall back to scanning for the first - // string constant in the call. - for idx := range call.Args { - if s, ok := stringConstantArg(pass, call, idx); ok { - return s, idx - } - if pass.TypesInfo.Types[call.Args[idx]].Type == types.Typ[types.String] { - // Skip checking a call with a non-constant format - // string argument, since its contents are unavailable - // for validation. - return "", -1 - } + sig, ok := typ.(*types.Signature) + if !ok { + return -1 // ill-typed } - return "", -1 -} - -// stringConstantArg returns call's string constant argument at the index idx. -// -// ("", false) is returned if call's argument at the index idx isn't a string -// constant. -func stringConstantArg(pass *analysis.Pass, call *ast.CallExpr, idx int) (string, bool) { - if idx >= len(call.Args) { - return "", false + if !sig.Variadic() { + // Skip checking non-variadic functions. + return -1 + } + idx := sig.Params().Len() - 2 + if idx < 0 { + // Skip checking variadic functions without + // fixed arguments. + return -1 } - return stringConstantExpr(pass, call.Args[idx]) + return idx } // stringConstantExpr returns expression's string constant value. @@ -511,15 +477,10 @@ func isFormatter(typ types.Type) bool { sig := fn.Type().(*types.Signature) return sig.Params().Len() == 2 && sig.Results().Len() == 0 && - isNamed(sig.Params().At(0).Type(), "fmt", "State") && + analysisutil.IsNamedType(sig.Params().At(0).Type(), "fmt", "State") && types.Identical(sig.Params().At(1).Type(), types.Typ[types.Rune]) } -func isNamed(T types.Type, pkgpath, name string) bool { - named, ok := T.(*types.Named) - return ok && named.Obj().Pkg().Path() == pkgpath && named.Obj().Name() == name -} - // formatState holds the parsed representation of a printf directive such as "%3.*[4]d". // It is constructed by parsePrintfVerb. type formatState struct { @@ -540,10 +501,34 @@ type formatState struct { // checkPrintf checks a call to a formatted print routine such as Printf. func checkPrintf(pass *analysis.Pass, kind Kind, call *ast.CallExpr, fn *types.Func) { - format, idx := formatString(pass, call) - if idx < 0 { - if false { - pass.Reportf(call.Lparen, "can't check non-constant format in call to %s", fn.FullName()) + idx := formatStringIndex(pass, call) + if idx < 0 || idx >= len(call.Args) { + return + } + formatArg := call.Args[idx] + format, ok := stringConstantExpr(pass, formatArg) + if !ok { + // Format string argument is non-constant. + + // It is a common mistake to call fmt.Printf(msg) with a + // non-constant format string and no arguments: + // if msg contains "%", misformatting occurs. + // Report the problem and suggest a fix: fmt.Printf("%s", msg). + if idx == len(call.Args)-1 { + pass.Report(analysis.Diagnostic{ + Pos: formatArg.Pos(), + End: formatArg.End(), + Message: fmt.Sprintf("non-constant format string in call to %s", + fn.FullName()), + SuggestedFixes: []analysis.SuggestedFix{{ + Message: `Insert "%s" format string`, + TextEdits: []analysis.TextEdit{{ + Pos: formatArg.Pos(), + End: formatArg.Pos(), + NewText: []byte(`"%s", `), + }}, + }}, + }) } return } @@ -964,6 +949,8 @@ func isStringer(sig *types.Signature) bool { // It is almost always a mistake to print a function value. func isFunctionValue(pass *analysis.Pass, e ast.Expr) bool { if typ := pass.TypesInfo.Types[e].Type; typ != nil { + // Don't call Underlying: a named func type with a String method is ok. + // TODO(adonovan): it would be more precise to check isStringer. _, ok := typ.(*types.Signature) return ok } @@ -1015,7 +1002,7 @@ func checkPrint(pass *analysis.Pass, call *ast.CallExpr, fn *types.Func) { // Skip checking functions with unknown type. return } - if sig, ok := typ.(*types.Signature); ok { + if sig, ok := typ.Underlying().(*types.Signature); ok { if !sig.Variadic() { // Skip checking non-variadic functions. return @@ -1025,7 +1012,7 @@ func checkPrint(pass *analysis.Pass, call *ast.CallExpr, fn *types.Func) { typ := params.At(firstArg).Type() typ = typ.(*types.Slice).Elem() - it, ok := typ.(*types.Interface) + it, ok := aliases.Unalias(typ).(*types.Interface) if !ok || !it.Empty() { // Skip variadic functions accepting non-interface{} args. return diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/types.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/types.go index 7cbb0bdbf..017c8a247 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/types.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/printf/types.go @@ -10,6 +10,7 @@ import ( "go/types" "golang.org/x/tools/go/analysis" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -72,7 +73,7 @@ func (m *argMatcher) match(typ types.Type, topLevel bool) bool { return true } - if typ, _ := typ.(*typeparams.TypeParam); typ != nil { + if typ, _ := aliases.Unalias(typ).(*types.TypeParam); typ != nil { // Avoid infinite recursion through type parameters. if m.seen[typ] { return true @@ -275,7 +276,7 @@ func (m *argMatcher) match(typ types.Type, topLevel bool) bool { } func isConvertibleToString(typ types.Type) bool { - if bt, ok := typ.(*types.Basic); ok && bt.Kind() == types.UntypedNil { + if bt, ok := aliases.Unalias(typ).(*types.Basic); ok && bt.Kind() == types.UntypedNil { // We explicitly don't want untyped nil, which is // convertible to both of the interfaces below, as it // would just panic anyway. diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/reflectvaluecompare/reflectvaluecompare.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/reflectvaluecompare/reflectvaluecompare.go index 27677139e..6789d7357 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/reflectvaluecompare/reflectvaluecompare.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/reflectvaluecompare/reflectvaluecompare.go @@ -49,11 +49,8 @@ func run(pass *analysis.Pass) (interface{}, error) { } } case *ast.CallExpr: - fn, ok := typeutil.Callee(pass.TypesInfo, n).(*types.Func) - if !ok { - return - } - if fn.FullName() == "reflect.DeepEqual" && (isReflectValue(pass, n.Args[0]) || isReflectValue(pass, n.Args[1])) { + fn, _ := typeutil.Callee(pass.TypesInfo, n).(*types.Func) + if analysisutil.IsFunctionNamed(fn, "reflect", "DeepEqual") && (isReflectValue(pass, n.Args[0]) || isReflectValue(pass, n.Args[1])) { pass.ReportRangef(n, "avoid using reflect.DeepEqual with reflect.Value") } } @@ -68,11 +65,7 @@ func isReflectValue(pass *analysis.Pass, e ast.Expr) bool { return false } // See if the type is reflect.Value - named, ok := tv.Type.(*types.Named) - if !ok { - return false - } - if obj := named.Obj(); obj == nil || obj.Pkg() == nil || obj.Pkg().Path() != "reflect" || obj.Name() != "Value" { + if !analysisutil.IsNamedType(tv.Type, "reflect", "Value") { return false } if _, ok := e.(*ast.CompositeLit); ok { diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/shift/shift.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/shift/shift.go index bafb9112e..d01eb1eeb 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/shift/shift.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/shift/shift.go @@ -21,6 +21,7 @@ import ( "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -89,7 +90,8 @@ func checkLongShift(pass *analysis.Pass, node ast.Node, x, y ast.Expr) { if v == nil { return } - amt, ok := constant.Int64Val(v) + u := constant.ToInt(v) // either an Int or Unknown + amt, ok := constant.Int64Val(u) if !ok { return } @@ -98,8 +100,8 @@ func checkLongShift(pass *analysis.Pass, node ast.Node, x, y ast.Expr) { return } var structuralTypes []types.Type - switch t := t.(type) { - case *typeparams.TypeParam: + switch t := aliases.Unalias(t).(type) { + case *types.TypeParam: terms, err := typeparams.StructuralTerms(t) if err != nil { return // invalid type diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/slog/slog.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/slog/slog.go index 92c1da8ef..0cade7bad 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/slog/slog.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/slog/slog.go @@ -20,6 +20,7 @@ import ( "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/typesinternal" ) //go:embed doc.go @@ -48,6 +49,7 @@ const ( ) func run(pass *analysis.Pass) (any, error) { + var attrType types.Type // The type of slog.Attr inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) nodeFilter := []ast.Node{ (*ast.CallExpr)(nil), @@ -66,6 +68,11 @@ func run(pass *analysis.Pass) (any, error) { // Not a slog function that takes key-value pairs. return } + // Here we know that fn.Pkg() is "log/slog". + if attrType == nil { + attrType = fn.Pkg().Scope().Lookup("Attr").Type() + } + if isMethodExpr(pass.TypesInfo, call) { // Call is to a method value. Skip the first argument. skipArgs++ @@ -91,8 +98,19 @@ func run(pass *analysis.Pass) (any, error) { pos = key case types.IsInterface(t): // As we do not do dataflow, we do not know what the dynamic type is. - // It could be a string or an Attr so we don't know what to expect next. - pos = unknown + // But we might be able to learn enough to make a decision. + if types.AssignableTo(stringType, t) { + // t must be an empty interface. So it can also be an Attr. + // We don't know enough to make an assumption. + pos = unknown + continue + } else if attrType != nil && types.AssignableTo(attrType, t) { + // Assume it is an Attr. + pos = key + continue + } + // Can't be either a string or Attr. Definitely an error. + fallthrough default: if unknownArg == nil { pass.ReportRangef(arg, "%s arg %q should be a string or a slog.Attr (possible missing key or value)", @@ -139,7 +157,7 @@ func run(pass *analysis.Pass) (any, error) { } func isAttr(t types.Type) bool { - return isNamed(t, "log/slog", "Attr") + return analysisutil.IsNamedType(t, "log/slog", "Attr") } // shortName returns a name for the function that is shorter than FullName. @@ -150,14 +168,10 @@ func isAttr(t types.Type) bool { func shortName(fn *types.Func) string { var r string if recv := fn.Type().(*types.Signature).Recv(); recv != nil { - t := recv.Type() - if pt, ok := t.(*types.Pointer); ok { - t = pt.Elem() - } - if nt, ok := t.(*types.Named); ok { - r = nt.Obj().Name() + if _, named := typesinternal.ReceiverNamed(recv); named != nil { + r = named.Obj().Name() } else { - r = recv.Type().String() + r = recv.Type().String() // anon struct/interface } r += "." } @@ -173,17 +187,12 @@ func kvFuncSkipArgs(fn *types.Func) (int, bool) { return 0, false } var recvName string // by default a slog package function - recv := fn.Type().(*types.Signature).Recv() - if recv != nil { - t := recv.Type() - if pt, ok := t.(*types.Pointer); ok { - t = pt.Elem() - } - if nt, ok := t.(*types.Named); !ok { - return 0, false - } else { - recvName = nt.Obj().Name() + if recv := fn.Type().(*types.Signature).Recv(); recv != nil { + _, named := typesinternal.ReceiverNamed(recv) + if named == nil { + return 0, false // anon struct/interface } + recvName = named.Obj().Name() } skip, ok := kvFuncs[recvName][fn.Name()] return skip, ok @@ -232,12 +241,3 @@ func isMethodExpr(info *types.Info, c *ast.CallExpr) bool { sel := info.Selections[s] return sel != nil && sel.Kind() == types.MethodExpr } - -// isNamed reports whether t is exactly a named type in a package with a given path. -func isNamed(t types.Type, path, name string) bool { - if n, ok := t.(*types.Named); ok { - obj := n.Obj() - return obj.Pkg() != nil && obj.Pkg().Path() == path && obj.Name() == name - } - return false -} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/sortslice/analyzer.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/sortslice/analyzer.go index 1fe206b0f..6c151a02c 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/sortslice/analyzer.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/sortslice/analyzer.go @@ -47,12 +47,7 @@ func run(pass *analysis.Pass) (interface{}, error) { inspect.Preorder(nodeFilter, func(n ast.Node) { call := n.(*ast.CallExpr) fn, _ := typeutil.Callee(pass.TypesInfo, call).(*types.Func) - if fn == nil { - return - } - - fnName := fn.FullName() - if fnName != "sort.Slice" && fnName != "sort.SliceStable" && fnName != "sort.SliceIsSorted" { + if !analysisutil.IsFunctionNamed(fn, "sort", "Slice", "SliceStable", "SliceIsSorted") { return } @@ -131,7 +126,7 @@ func run(pass *analysis.Pass) (interface{}, error) { pass.Report(analysis.Diagnostic{ Pos: call.Pos(), End: call.End(), - Message: fmt.Sprintf("%s's argument must be a slice; is called with %s", fnName, typ.String()), + Message: fmt.Sprintf("%s's argument must be a slice; is called with %s", fn.FullName(), typ.String()), SuggestedFixes: fixes, }) }) diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/stringintconv/string.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/stringintconv/string.go index bb04dae62..a3afbf696 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/stringintconv/string.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/stringintconv/string.go @@ -15,6 +15,8 @@ import ( "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/analysisinternal" "golang.org/x/tools/internal/typeparams" ) @@ -58,12 +60,13 @@ func describe(typ, inType types.Type, inName string) string { return name } -func typeName(typ types.Type) string { - if v, _ := typ.(interface{ Name() string }); v != nil { - return v.Name() - } - if v, _ := typ.(interface{ Obj() *types.TypeName }); v != nil { - return v.Obj().Name() +func typeName(t types.Type) string { + type hasTypeName interface{ Obj() *types.TypeName } // Alias, Named, TypeParam + switch t := t.(type) { + case *types.Basic: + return t.Name() + case hasTypeName: + return t.Obj().Name() } return "" } @@ -71,9 +74,15 @@ func typeName(typ types.Type) string { func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) nodeFilter := []ast.Node{ + (*ast.File)(nil), (*ast.CallExpr)(nil), } + var file *ast.File inspect.Preorder(nodeFilter, func(n ast.Node) { + if n, ok := n.(*ast.File); ok { + file = n + return + } call := n.(*ast.CallExpr) if len(call.Args) != 1 { @@ -165,27 +174,72 @@ func run(pass *analysis.Pass) (interface{}, error) { diag := analysis.Diagnostic{ Pos: n.Pos(), - Message: fmt.Sprintf("conversion from %s to %s yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)", source, target), + Message: fmt.Sprintf("conversion from %s to %s yields a string of one rune, not a string of digits", source, target), + } + addFix := func(message string, edits []analysis.TextEdit) { + diag.SuggestedFixes = append(diag.SuggestedFixes, analysis.SuggestedFix{ + Message: message, + TextEdits: edits, + }) + } + + // Fix 1: use fmt.Sprint(x) + // + // Prefer fmt.Sprint over strconv.Itoa, FormatInt, + // or FormatUint, as it works for any type. + // Add an import of "fmt" as needed. + // + // Unless the type is exactly string, we must retain the conversion. + // + // Do not offer this fix if type parameters are involved, + // as there are too many combinations and subtleties. + // Consider x = rune | int16 | []byte: in all cases, + // string(x) is legal, but the appropriate diagnostic + // and fix differs. Similarly, don't offer the fix if + // the type has methods, as some {String,GoString,Format} + // may change the behavior of fmt.Sprint. + if len(ttypes) == 1 && len(vtypes) == 1 && types.NewMethodSet(V0).Len() == 0 { + fmtName, importEdits := analysisinternal.AddImport(pass.TypesInfo, file, arg.Pos(), "fmt", "fmt") + if types.Identical(T0, types.Typ[types.String]) { + // string(x) -> fmt.Sprint(x) + addFix("Format the number as a decimal", append(importEdits, + analysis.TextEdit{ + Pos: call.Fun.Pos(), + End: call.Fun.End(), + NewText: []byte(fmtName + ".Sprint"), + }), + ) + } else { + // mystring(x) -> mystring(fmt.Sprint(x)) + addFix("Format the number as a decimal", append(importEdits, + analysis.TextEdit{ + Pos: call.Lparen + 1, + End: call.Lparen + 1, + NewText: []byte(fmtName + ".Sprint("), + }, + analysis.TextEdit{ + Pos: call.Rparen, + End: call.Rparen, + NewText: []byte(")"), + }), + ) + } } + // Fix 2: use string(rune(x)) if convertibleToRune { - diag.SuggestedFixes = []analysis.SuggestedFix{ + addFix("Convert a single rune to a string", []analysis.TextEdit{ { - Message: "Did you mean to convert a rune to a string?", - TextEdits: []analysis.TextEdit{ - { - Pos: arg.Pos(), - End: arg.Pos(), - NewText: []byte("rune("), - }, - { - Pos: arg.End(), - End: arg.End(), - NewText: []byte(")"), - }, - }, + Pos: arg.Pos(), + End: arg.Pos(), + NewText: []byte("rune("), }, - } + { + Pos: arg.End(), + End: arg.End(), + NewText: []byte(")"), + }, + }) } pass.Report(diag) }) @@ -194,16 +248,15 @@ func run(pass *analysis.Pass) (interface{}, error) { func structuralTypes(t types.Type) ([]types.Type, error) { var structuralTypes []types.Type - switch t := t.(type) { - case *typeparams.TypeParam: - terms, err := typeparams.StructuralTerms(t) + if tp, ok := aliases.Unalias(t).(*types.TypeParam); ok { + terms, err := typeparams.StructuralTerms(tp) if err != nil { return nil, err } for _, term := range terms { structuralTypes = append(structuralTypes, term.Type()) } - default: + } else { structuralTypes = append(structuralTypes, t) } return structuralTypes, nil diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/doc.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/doc.go index a68adb12b..4cd5b71e9 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/doc.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/doc.go @@ -7,7 +7,7 @@ // // # Analyzer testinggoroutine // -// testinggoroutine: report calls to (*testing.T).Fatal from goroutines started by a test. +// testinggoroutine: report calls to (*testing.T).Fatal from goroutines started by a test // // Functions that abruptly terminate a test, such as the Fatal, Fatalf, FailNow, and // Skip{,f,Now} methods of *testing.T, must be called from the test goroutine itself. diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/testinggoroutine.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/testinggoroutine.go index 907b71503..828f95bc8 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/testinggoroutine.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/testinggoroutine.go @@ -6,18 +6,29 @@ package testinggoroutine import ( _ "embed" + "fmt" "go/ast" + "go/token" + "go/types" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/inspector" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/aliases" ) //go:embed doc.go var doc string +var reportSubtest bool + +func init() { + Analyzer.Flags.BoolVar(&reportSubtest, "subtest", false, "whether to check if t.Run subtest is terminated correctly; experimental") +} + var Analyzer = &analysis.Analyzer{ Name: "testinggoroutine", Doc: analysisutil.MustExtractDoc(doc, "testinggoroutine"), @@ -26,15 +37,6 @@ var Analyzer = &analysis.Analyzer{ Run: run, } -var forbidden = map[string]bool{ - "FailNow": true, - "Fatal": true, - "Fatalf": true, - "Skip": true, - "Skipf": true, - "SkipNow": true, -} - func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) @@ -42,38 +44,90 @@ func run(pass *analysis.Pass) (interface{}, error) { return nil, nil } - // Filter out anything that isn't a function declaration. - onlyFuncs := []ast.Node{ - (*ast.FuncDecl)(nil), + toDecl := localFunctionDecls(pass.TypesInfo, pass.Files) + + // asyncs maps nodes whose statements will be executed concurrently + // with respect to some test function, to the call sites where they + // are invoked asynchronously. There may be multiple such call sites + // for e.g. test helpers. + asyncs := make(map[ast.Node][]*asyncCall) + var regions []ast.Node + addCall := func(c *asyncCall) { + if c != nil { + r := c.region + if asyncs[r] == nil { + regions = append(regions, r) + } + asyncs[r] = append(asyncs[r], c) + } } - inspect.Nodes(onlyFuncs, func(node ast.Node, push bool) bool { - fnDecl, ok := node.(*ast.FuncDecl) - if !ok { + // Collect all of the go callee() and t.Run(name, callee) extents. + inspect.Nodes([]ast.Node{ + (*ast.FuncDecl)(nil), + (*ast.GoStmt)(nil), + (*ast.CallExpr)(nil), + }, func(node ast.Node, push bool) bool { + if !push { return false } + switch node := node.(type) { + case *ast.FuncDecl: + return hasBenchmarkOrTestParams(node) - if !hasBenchmarkOrTestParams(fnDecl) { - return false + case *ast.GoStmt: + c := goAsyncCall(pass.TypesInfo, node, toDecl) + addCall(c) + + case *ast.CallExpr: + c := tRunAsyncCall(pass.TypesInfo, node) + addCall(c) } + return true + }) - // Now traverse the benchmark/test's body and check that none of the - // forbidden methods are invoked in the goroutines within the body. - ast.Inspect(fnDecl, func(n ast.Node) bool { - goStmt, ok := n.(*ast.GoStmt) + // Check for t.Forbidden() calls within each region r that is a + // callee in some go r() or a t.Run("name", r). + // + // Also considers a special case when r is a go t.Forbidden() call. + for _, region := range regions { + ast.Inspect(region, func(n ast.Node) bool { + if n == region { + return true // always descend into the region itself. + } else if asyncs[n] != nil { + return false // will be visited by another region. + } + + call, ok := n.(*ast.CallExpr) if !ok { return true } + x, sel, fn := forbiddenMethod(pass.TypesInfo, call) + if x == nil { + return true + } - checkGoStmt(pass, goStmt) + for _, e := range asyncs[region] { + if !withinScope(e.scope, x) { + forbidden := formatMethod(sel, fn) // e.g. "(*testing.T).Forbidden - // No need to further traverse the GoStmt since right - // above we manually traversed it in the ast.Inspect(goStmt, ...) - return false + var context string + var where analysis.Range = e.async // Put the report at the go fun() or t.Run(name, fun). + if _, local := e.fun.(*ast.FuncLit); local { + where = call // Put the report at the t.Forbidden() call. + } else if id, ok := e.fun.(*ast.Ident); ok { + context = fmt.Sprintf(" (%s calls %s)", id.Name, forbidden) + } + if _, ok := e.async.(*ast.GoStmt); ok { + pass.ReportRangef(where, "call to %s from a non-test goroutine%s", forbidden, context) + } else if reportSubtest { + pass.ReportRangef(where, "call to %s on %s defined outside of the subtest%s", forbidden, x.Name(), context) + } + } + } + return true }) - - return false - }) + } return nil, nil } @@ -100,7 +154,6 @@ func typeIsTestingDotTOrB(expr ast.Expr) (string, bool) { if !ok { return "", false } - varPkg := selExpr.X.(*ast.Ident) if varPkg.Name != "testing" { return "", false @@ -111,73 +164,116 @@ func typeIsTestingDotTOrB(expr ast.Expr) (string, bool) { return varTypeName, ok } -// goStmtFunc returns the ast.Node of a call expression -// that was invoked as a go statement. Currently, only -// function literals declared in the same function, and -// static calls within the same package are supported. -func goStmtFun(goStmt *ast.GoStmt) ast.Node { - switch fun := goStmt.Call.Fun.(type) { - case *ast.IndexExpr, *typeparams.IndexListExpr: - x, _, _, _ := typeparams.UnpackIndexExpr(fun) - id, _ := x.(*ast.Ident) - if id == nil { - break - } - if id.Obj == nil { - break - } - if funDecl, ok := id.Obj.Decl.(ast.Node); ok { - return funDecl - } - case *ast.Ident: - // TODO(cuonglm): improve this once golang/go#48141 resolved. - if fun.Obj == nil { - break - } - if funDecl, ok := fun.Obj.Decl.(ast.Node); ok { - return funDecl - } - case *ast.FuncLit: - return goStmt.Call.Fun +// asyncCall describes a region of code that needs to be checked for +// t.Forbidden() calls as it is started asynchronously from an async +// node go fun() or t.Run(name, fun). +type asyncCall struct { + region ast.Node // region of code to check for t.Forbidden() calls. + async ast.Node // *ast.GoStmt or *ast.CallExpr (for t.Run) + scope ast.Node // Report t.Forbidden() if t is not declared within scope. + fun ast.Expr // fun in go fun() or t.Run(name, fun) +} + +// withinScope returns true if x.Pos() is in [scope.Pos(), scope.End()]. +func withinScope(scope ast.Node, x *types.Var) bool { + if scope != nil { + return x.Pos() != token.NoPos && scope.Pos() <= x.Pos() && x.Pos() <= scope.End() } - return goStmt.Call + return false } -// checkGoStmt traverses the goroutine and checks for the -// use of the forbidden *testing.(B, T) methods. -func checkGoStmt(pass *analysis.Pass, goStmt *ast.GoStmt) { - fn := goStmtFun(goStmt) - // Otherwise examine the goroutine to check for the forbidden methods. - ast.Inspect(fn, func(n ast.Node) bool { - selExpr, ok := n.(*ast.SelectorExpr) - if !ok { - return true - } +// goAsyncCall returns the extent of a call from a go fun() statement. +func goAsyncCall(info *types.Info, goStmt *ast.GoStmt, toDecl func(*types.Func) *ast.FuncDecl) *asyncCall { + call := goStmt.Call - _, bad := forbidden[selExpr.Sel.Name] - if !bad { - return true + fun := astutil.Unparen(call.Fun) + if id := funcIdent(fun); id != nil { + if lit := funcLitInScope(id); lit != nil { + return &asyncCall{region: lit, async: goStmt, scope: nil, fun: fun} } + } - // Now filter out false positives by the import-path/type. - ident, ok := selExpr.X.(*ast.Ident) - if !ok { - return true + if fn := typeutil.StaticCallee(info, call); fn != nil { // static call or method in the package? + if decl := toDecl(fn); decl != nil { + return &asyncCall{region: decl, async: goStmt, scope: nil, fun: fun} } - if ident.Obj == nil || ident.Obj.Decl == nil { - return true - } - field, ok := ident.Obj.Decl.(*ast.Field) - if !ok { - return true - } - if typeName, ok := typeIsTestingDotTOrB(field.Type); ok { - var fnRange analysis.Range = goStmt - if _, ok := fn.(*ast.FuncLit); ok { - fnRange = selExpr - } - pass.ReportRangef(fnRange, "call to (*%s).%s from a non-test goroutine", typeName, selExpr.Sel) + } + + // Check go statement for go t.Forbidden() or go func(){t.Forbidden()}(). + return &asyncCall{region: goStmt, async: goStmt, scope: nil, fun: fun} +} + +// tRunAsyncCall returns the extent of a call from a t.Run("name", fun) expression. +func tRunAsyncCall(info *types.Info, call *ast.CallExpr) *asyncCall { + if len(call.Args) != 2 { + return nil + } + run := typeutil.Callee(info, call) + if run, ok := run.(*types.Func); !ok || !isMethodNamed(run, "testing", "Run") { + return nil + } + + fun := astutil.Unparen(call.Args[1]) + if lit, ok := fun.(*ast.FuncLit); ok { // function lit? + return &asyncCall{region: lit, async: call, scope: lit, fun: fun} + } + + if id := funcIdent(fun); id != nil { + if lit := funcLitInScope(id); lit != nil { // function lit in variable? + return &asyncCall{region: lit, async: call, scope: lit, fun: fun} } - return true - }) + } + + // Check within t.Run(name, fun) for calls to t.Forbidden, + // e.g. t.Run(name, func(t *testing.T){ t.Forbidden() }) + return &asyncCall{region: call, async: call, scope: fun, fun: fun} +} + +var forbidden = []string{ + "FailNow", + "Fatal", + "Fatalf", + "Skip", + "Skipf", + "SkipNow", +} + +// forbiddenMethod decomposes a call x.m() into (x, x.m, m) where +// x is a variable, x.m is a selection, and m is the static callee m. +// Returns (nil, nil, nil) if call is not of this form. +func forbiddenMethod(info *types.Info, call *ast.CallExpr) (*types.Var, *types.Selection, *types.Func) { + // Compare to typeutil.StaticCallee. + fun := astutil.Unparen(call.Fun) + selExpr, ok := fun.(*ast.SelectorExpr) + if !ok { + return nil, nil, nil + } + sel := info.Selections[selExpr] + if sel == nil { + return nil, nil, nil + } + + var x *types.Var + if id, ok := astutil.Unparen(selExpr.X).(*ast.Ident); ok { + x, _ = info.Uses[id].(*types.Var) + } + if x == nil { + return nil, nil, nil + } + + fn, _ := sel.Obj().(*types.Func) + if fn == nil || !isMethodNamed(fn, "testing", forbidden...) { + return nil, nil, nil + } + return x, sel, fn +} + +func formatMethod(sel *types.Selection, fn *types.Func) string { + var ptr string + rtype := sel.Recv() + if p, ok := aliases.Unalias(rtype).(*types.Pointer); ok { + ptr = "*" + rtype = p.Elem() + } + return fmt.Sprintf("(%s%s).%s", ptr, rtype.String(), fn.Name()) } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/util.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/util.go new file mode 100644 index 000000000..ad815f190 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/testinggoroutine/util.go @@ -0,0 +1,96 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package testinggoroutine + +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/internal/typeparams" +) + +// AST and types utilities that not specific to testinggoroutines. + +// localFunctionDecls returns a mapping from *types.Func to *ast.FuncDecl in files. +func localFunctionDecls(info *types.Info, files []*ast.File) func(*types.Func) *ast.FuncDecl { + var fnDecls map[*types.Func]*ast.FuncDecl // computed lazily + return func(f *types.Func) *ast.FuncDecl { + if f != nil && fnDecls == nil { + fnDecls = make(map[*types.Func]*ast.FuncDecl) + for _, file := range files { + for _, decl := range file.Decls { + if fnDecl, ok := decl.(*ast.FuncDecl); ok { + if fn, ok := info.Defs[fnDecl.Name].(*types.Func); ok { + fnDecls[fn] = fnDecl + } + } + } + } + } + // TODO: set f = f.Origin() here. + return fnDecls[f] + } +} + +// isMethodNamed returns true if f is a method defined +// in package with the path pkgPath with a name in names. +func isMethodNamed(f *types.Func, pkgPath string, names ...string) bool { + if f == nil { + return false + } + if f.Pkg() == nil || f.Pkg().Path() != pkgPath { + return false + } + if f.Type().(*types.Signature).Recv() == nil { + return false + } + for _, n := range names { + if f.Name() == n { + return true + } + } + return false +} + +func funcIdent(fun ast.Expr) *ast.Ident { + switch fun := astutil.Unparen(fun).(type) { + case *ast.IndexExpr, *ast.IndexListExpr: + x, _, _, _ := typeparams.UnpackIndexExpr(fun) // necessary? + id, _ := x.(*ast.Ident) + return id + case *ast.Ident: + return fun + default: + return nil + } +} + +// funcLitInScope returns a FuncLit that id is at least initially assigned to. +// +// TODO: This is closely tied to id.Obj which is deprecated. +func funcLitInScope(id *ast.Ident) *ast.FuncLit { + // Compare to (*ast.Object).Pos(). + if id.Obj == nil { + return nil + } + var rhs ast.Expr + switch d := id.Obj.Decl.(type) { + case *ast.AssignStmt: + for i, x := range d.Lhs { + if ident, isIdent := x.(*ast.Ident); isIdent && ident.Name == id.Name && i < len(d.Rhs) { + rhs = d.Rhs[i] + } + } + case *ast.ValueSpec: + for i, n := range d.Names { + if n.Name == id.Name && i < len(d.Values) { + rhs = d.Values[i] + } + } + } + lit, _ := rhs.(*ast.FuncLit) + return lit +} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/tests/tests.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/tests/tests.go index 9589a46a5..5b4598235 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/tests/tests.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/tests/tests.go @@ -6,7 +6,6 @@ package tests import ( _ "embed" - "fmt" "go/ast" "go/token" "go/types" @@ -17,7 +16,6 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" - "golang.org/x/tools/internal/typeparams" ) //go:embed doc.go @@ -185,13 +183,13 @@ func checkAddCalls(pass *analysis.Pass, fn *ast.FuncDecl, params *types.Tuple) { i := mismatched[0] expr := call.Args[i] t := pass.TypesInfo.Types[expr].Type - pass.ReportRangef(expr, fmt.Sprintf("mismatched type in call to (*testing.F).Add: %v, fuzz target expects %v", t, params.At(i+1).Type())) + pass.ReportRangef(expr, "mismatched type in call to (*testing.F).Add: %v, fuzz target expects %v", t, params.At(i+1).Type()) } else if len(mismatched) > 1 { var gotArgs, wantArgs []types.Type for i := 0; i < len(call.Args); i++ { gotArgs, wantArgs = append(gotArgs, pass.TypesInfo.Types[call.Args[i]].Type), append(wantArgs, params.At(i+1).Type()) } - pass.ReportRangef(call, fmt.Sprintf("mismatched types in call to (*testing.F).Add: %v, fuzz target expects %v", gotArgs, wantArgs)) + pass.ReportRangef(call, "mismatched types in call to (*testing.F).Add: %v, fuzz target expects %v", gotArgs, wantArgs) } } return true @@ -245,7 +243,7 @@ func validateFuzzArgs(pass *analysis.Pass, params *types.Tuple, expr ast.Expr) b } } } - pass.ReportRangef(exprRange, "fuzzing arguments can only have the following types: "+formatAcceptedFuzzType()) + pass.ReportRangef(exprRange, "fuzzing arguments can only have the following types: %s", formatAcceptedFuzzType()) ok = false } } @@ -253,17 +251,13 @@ func validateFuzzArgs(pass *analysis.Pass, params *types.Tuple, expr ast.Expr) b } func isTestingType(typ types.Type, testingType string) bool { + // No Unalias here: I doubt "go test" recognizes + // "type A = *testing.T; func Test(A) {}" as a test. ptr, ok := typ.(*types.Pointer) if !ok { return false } - named, ok := ptr.Elem().(*types.Named) - if !ok { - return false - } - obj := named.Obj() - // obj.Pkg is nil for the error type. - return obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "testing" && obj.Name() == testingType + return analysisutil.IsNamedType(ptr.Elem(), "testing", testingType) } // Validate that fuzz target function's arguments are of accepted types. @@ -397,7 +391,7 @@ func checkExampleName(pass *analysis.Pass, fn *ast.FuncDecl) { if results := fn.Type.Results; results != nil && len(results.List) != 0 { pass.Reportf(fn.Pos(), "%s should return nothing", fnName) } - if tparams := typeparams.ForFuncType(fn.Type); tparams != nil && len(tparams.List) > 0 { + if tparams := fn.Type.TypeParams; tparams != nil && len(tparams.List) > 0 { pass.Reportf(fn.Pos(), "%s should not have type params", fnName) } @@ -452,6 +446,18 @@ func checkExampleName(pass *analysis.Pass, fn *ast.FuncDecl) { } } +type tokenRange struct { + p, e token.Pos +} + +func (r tokenRange) Pos() token.Pos { + return r.p +} + +func (r tokenRange) End() token.Pos { + return r.e +} + func checkTest(pass *analysis.Pass, fn *ast.FuncDecl, prefix string) { // Want functions with 0 results and 1 parameter. if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 || @@ -466,15 +472,14 @@ func checkTest(pass *analysis.Pass, fn *ast.FuncDecl, prefix string) { return } - if tparams := typeparams.ForFuncType(fn.Type); tparams != nil && len(tparams.List) > 0 { + if tparams := fn.Type.TypeParams; tparams != nil && len(tparams.List) > 0 { // Note: cmd/go/internal/load also errors about TestXXX and BenchmarkXXX functions with type parameters. // We have currently decided to also warn before compilation/package loading. This can help users in IDEs. - // TODO(adonovan): use ReportRangef(tparams). - pass.Reportf(fn.Pos(), "%s has type parameters: it will not be run by go test as a %sXXX function", fn.Name.Name, prefix) + at := tokenRange{tparams.Opening, tparams.Closing} + pass.ReportRangef(at, "%s has type parameters: it will not be run by go test as a %sXXX function", fn.Name.Name, prefix) } if !isTestSuffix(fn.Name.Name[len(prefix):]) { - // TODO(adonovan): use ReportRangef(fn.Name). - pass.Reportf(fn.Pos(), "%s has malformed name: first letter after '%s' must not be lowercase", fn.Name.Name, prefix) + pass.ReportRangef(fn.Name, "%s has malformed name: first letter after '%s' must not be lowercase", fn.Name.Name, prefix) } } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/timeformat/timeformat.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/timeformat/timeformat.go index c45b9fa54..4a6c6b8bc 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/timeformat/timeformat.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/timeformat/timeformat.go @@ -88,29 +88,16 @@ func run(pass *analysis.Pass) (interface{}, error) { } func isTimeDotFormat(f *types.Func) bool { - if f.Name() != "Format" || f.Pkg().Path() != "time" { - return false - } - sig, ok := f.Type().(*types.Signature) - if !ok { + if f.Name() != "Format" || f.Pkg() == nil || f.Pkg().Path() != "time" { return false } // Verify that the receiver is time.Time. - recv := sig.Recv() - if recv == nil { - return false - } - named, ok := recv.Type().(*types.Named) - return ok && named.Obj().Name() == "Time" + recv := f.Type().(*types.Signature).Recv() + return recv != nil && analysisutil.IsNamedType(recv.Type(), "time", "Time") } func isTimeDotParse(f *types.Func) bool { - if f.Name() != "Parse" || f.Pkg().Path() != "time" { - return false - } - // Verify that there is no receiver. - sig, ok := f.Type().(*types.Signature) - return ok && sig.Recv() == nil + return analysisutil.IsFunctionNamed(f, "time", "Parse") } // badFormatAt return the start of a bad format in e or -1 if no bad format is found. @@ -120,7 +107,7 @@ func badFormatAt(info *types.Info, e ast.Expr) int { return -1 } - t, ok := tv.Type.(*types.Basic) + t, ok := tv.Type.(*types.Basic) // sic, no unalias if !ok || t.Info()&types.IsString == 0 { return -1 } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/unmarshal/unmarshal.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/unmarshal/unmarshal.go index 7043baa89..a7889fa45 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/unmarshal/unmarshal.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/unmarshal/unmarshal.go @@ -14,7 +14,7 @@ import ( "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/go/types/typeutil" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/typesinternal" ) //go:embed doc.go @@ -70,12 +70,8 @@ func run(pass *analysis.Pass) (interface{}, error) { // (*"encoding/json".Decoder).Decode // (* "encoding/gob".Decoder).Decode // (* "encoding/xml".Decoder).Decode - t := recv.Type() - if ptr, ok := t.(*types.Pointer); ok { - t = ptr.Elem() - } - tname := t.(*types.Named).Obj() - if tname.Name() == "Decoder" { + _, named := typesinternal.ReceiverNamed(recv) + if tname := named.Obj(); tname.Name() == "Decoder" { switch tname.Pkg().Path() { case "encoding/json", "encoding/xml", "encoding/gob": argidx = 0 // func(interface{}) @@ -92,7 +88,7 @@ func run(pass *analysis.Pass) (interface{}, error) { t := pass.TypesInfo.Types[call.Args[argidx]].Type switch t.Underlying().(type) { - case *types.Pointer, *types.Interface, *typeparams.TypeParam: + case *types.Pointer, *types.Interface, *types.TypeParam: return } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/unsafeptr/unsafeptr.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/unsafeptr/unsafeptr.go index e43ac2078..14e4a6c1e 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/unsafeptr/unsafeptr.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/unsafeptr/unsafeptr.go @@ -15,7 +15,9 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/aliases" ) //go:embed doc.go @@ -68,7 +70,7 @@ func isSafeUintptr(info *types.Info, x ast.Expr) bool { // Check unsafe.Pointer safety rules according to // https://golang.org/pkg/unsafe/#Pointer. - switch x := analysisutil.Unparen(x).(type) { + switch x := astutil.Unparen(x).(type) { case *ast.SelectorExpr: // "(6) Conversion of a reflect.SliceHeader or // reflect.StringHeader Data field to or from Pointer." @@ -87,7 +89,7 @@ func isSafeUintptr(info *types.Info, x ast.Expr) bool { // by the time we get to the conversion at the end. // For now approximate by saying that *Header is okay // but Header is not. - pt, ok := info.Types[x.X].Type.(*types.Pointer) + pt, ok := aliases.Unalias(info.Types[x.X].Type).(*types.Pointer) if ok && isReflectHeader(pt.Elem()) { return true } @@ -104,8 +106,7 @@ func isSafeUintptr(info *types.Info, x ast.Expr) bool { } switch sel.Sel.Name { case "Pointer", "UnsafeAddr": - t, ok := info.Types[sel.X].Type.(*types.Named) - if ok && t.Obj().Pkg().Path() == "reflect" && t.Obj().Name() == "Value" { + if analysisutil.IsNamedType(info.Types[sel.X].Type, "reflect", "Value") { return true } } @@ -118,7 +119,7 @@ func isSafeUintptr(info *types.Info, x ast.Expr) bool { // isSafeArith reports whether x is a pointer arithmetic expression that is safe // to convert to unsafe.Pointer. func isSafeArith(info *types.Info, x ast.Expr) bool { - switch x := analysisutil.Unparen(x).(type) { + switch x := astutil.Unparen(x).(type) { case *ast.CallExpr: // Base case: initial conversion from unsafe.Pointer to uintptr. return len(x.Args) == 1 && @@ -153,13 +154,5 @@ func hasBasicType(info *types.Info, x ast.Expr, kind types.BasicKind) bool { // isReflectHeader reports whether t is reflect.SliceHeader or reflect.StringHeader. func isReflectHeader(t types.Type) bool { - if named, ok := t.(*types.Named); ok { - if obj := named.Obj(); obj.Pkg() != nil && obj.Pkg().Path() == "reflect" { - switch obj.Name() { - case "SliceHeader", "StringHeader": - return true - } - } - } - return false + return analysisutil.IsNamedType(t, "reflect", "SliceHeader", "StringHeader") } diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedresult/unusedresult.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedresult/unusedresult.go index cb487a217..76f42b052 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedresult/unusedresult.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedresult/unusedresult.go @@ -24,6 +24,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/go/types/typeutil" ) @@ -58,7 +59,25 @@ func init() { // List standard library functions here. // The context.With{Cancel,Deadline,Timeout} entries are // effectively redundant wrt the lostcancel analyzer. - funcs.Set("errors.New,fmt.Errorf,fmt.Sprintf,fmt.Sprint,sort.Reverse,context.WithValue,context.WithCancel,context.WithDeadline,context.WithTimeout") + funcs = stringSetFlag{ + "context.WithCancel": true, + "context.WithDeadline": true, + "context.WithTimeout": true, + "context.WithValue": true, + "errors.New": true, + "fmt.Errorf": true, + "fmt.Sprint": true, + "fmt.Sprintf": true, + "slices.Clip": true, + "slices.Compact": true, + "slices.CompactFunc": true, + "slices.Delete": true, + "slices.DeleteFunc": true, + "slices.Grow": true, + "slices.Insert": true, + "slices.Replace": true, + "sort.Reverse": true, + } Analyzer.Flags.Var(&funcs, "funcs", "comma-separated list of functions whose results must be used") @@ -82,7 +101,7 @@ func run(pass *analysis.Pass) (interface{}, error) { (*ast.ExprStmt)(nil), } inspect.Preorder(nodeFilter, func(n ast.Node) { - call, ok := analysisutil.Unparen(n.(*ast.ExprStmt).X).(*ast.CallExpr) + call, ok := astutil.Unparen(n.(*ast.ExprStmt).X).(*ast.CallExpr) if !ok { return // not a call statement } @@ -92,7 +111,6 @@ func run(pass *analysis.Pass) (interface{}, error) { if !ok { return // e.g. var or builtin } - if sig := fn.Type().(*types.Signature); sig.Recv() != nil { // method (e.g. foo.String()) if types.Identical(sig, sigNoArgsStringResult) { diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedwrite/unusedwrite.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedwrite/unusedwrite.go index f5d0f116c..a99c54833 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedwrite/unusedwrite.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/unusedwrite/unusedwrite.go @@ -6,13 +6,14 @@ package unusedwrite import ( _ "embed" - "fmt" "go/types" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/buildssa" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" "golang.org/x/tools/go/ssa" + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/typeparams" ) //go:embed doc.go @@ -36,9 +37,9 @@ func run(pass *analysis.Pass) (interface{}, error) { for _, store := range reports { switch addr := store.Addr.(type) { case *ssa.FieldAddr: + field := typeparams.CoreType(typeparams.MustDeref(addr.X.Type())).(*types.Struct).Field(addr.Field) pass.Reportf(store.Pos(), - "unused write to field %s", - getFieldName(addr.X.Type(), addr.Field)) + "unused write to field %s", field.Name()) case *ssa.IndexAddr: pass.Reportf(store.Pos(), "unused write to array index %s", addr.Index) @@ -124,10 +125,7 @@ func isDeadStore(store *ssa.Store, obj ssa.Value, addr ssa.Instruction) bool { // isStructOrArray returns whether the underlying type is struct or array. func isStructOrArray(tp types.Type) bool { - if named, ok := tp.(*types.Named); ok { - tp = named.Underlying() - } - switch tp.(type) { + switch tp.Underlying().(type) { case *types.Array: return true case *types.Struct: @@ -145,7 +143,7 @@ func hasStructOrArrayType(v ssa.Value) bool { // func (t T) f() { ...} // the receiver object is of type *T: // t0 = local T (t) *T - if tp, ok := alloc.Type().(*types.Pointer); ok { + if tp, ok := aliases.Unalias(alloc.Type()).(*types.Pointer); ok { return isStructOrArray(tp.Elem()) } return false @@ -153,20 +151,3 @@ func hasStructOrArrayType(v ssa.Value) bool { } return isStructOrArray(v.Type()) } - -// getFieldName returns the name of a field in a struct. -// It the field is not found, then it returns the string format of the index. -// -// For example, for struct T {x int, y int), getFieldName(*T, 1) returns "y". -func getFieldName(tp types.Type, index int) string { - if pt, ok := tp.(*types.Pointer); ok { - tp = pt.Elem() - } - if named, ok := tp.(*types.Named); ok { - tp = named.Underlying() - } - if stp, ok := tp.(*types.Struct); ok { - return stp.Field(index).Name() - } - return fmt.Sprintf("%d", index) -} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/validate.go b/tools/vendor/golang.org/x/tools/go/analysis/validate.go index 9da5692af..4f2c40456 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/validate.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/validate.go @@ -19,6 +19,8 @@ import ( // that the Requires graph is acyclic; // that analyzer fact types are unique; // that each fact type is a pointer. +// +// Analyzer names need not be unique, though this may be confusing. func Validate(analyzers []*Analyzer) error { // Map each fact type to its sole generating analyzer. factTypes := make(map[reflect.Type]*Analyzer) diff --git a/tools/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go b/tools/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go index 9fa5aa192..6e34df461 100644 --- a/tools/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go +++ b/tools/vendor/golang.org/x/tools/go/ast/astutil/enclosing.go @@ -11,8 +11,6 @@ import ( "go/ast" "go/token" "sort" - - "golang.org/x/tools/internal/typeparams" ) // PathEnclosingInterval returns the node that encloses the source @@ -108,8 +106,21 @@ func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Nod // Does augmented child strictly contain [start, end)? if augPos <= start && end <= augEnd { - _, isToken := child.(tokenNode) - return isToken || visit(child) + if is[tokenNode](child) { + return true + } + + // childrenOf elides the FuncType node beneath FuncDecl. + // Add it back here for TypeParams, Params, Results, + // all FieldLists). But we don't add it back for the "func" token + // even though it is is the tree at FuncDecl.Type.Func. + if decl, ok := node.(*ast.FuncDecl); ok { + if fields, ok := child.(*ast.FieldList); ok && fields != decl.Recv { + path = append(path, decl.Type) + } + } + + return visit(child) } // Does [start, end) overlap multiple children? @@ -315,6 +326,8 @@ func childrenOf(n ast.Node) []ast.Node { // // As a workaround, we inline the case for FuncType // here and order things correctly. + // We also need to insert the elided FuncType just + // before the 'visit' recursion. // children = nil // discard ast.Walk(FuncDecl) info subtrees children = append(children, tok(n.Type.Func, len("func"))) @@ -322,7 +335,7 @@ func childrenOf(n ast.Node) []ast.Node { children = append(children, n.Recv) } children = append(children, n.Name) - if tparams := typeparams.ForFuncType(n.Type); tparams != nil { + if tparams := n.Type.TypeParams; tparams != nil { children = append(children, tparams) } if n.Type.Params != nil { @@ -377,7 +390,7 @@ func childrenOf(n ast.Node) []ast.Node { tok(n.Lbrack, len("[")), tok(n.Rbrack, len("]"))) - case *typeparams.IndexListExpr: + case *ast.IndexListExpr: children = append(children, tok(n.Lbrack, len("[")), tok(n.Rbrack, len("]"))) @@ -588,7 +601,7 @@ func NodeDescription(n ast.Node) string { return "decrement statement" case *ast.IndexExpr: return "index expression" - case *typeparams.IndexListExpr: + case *ast.IndexListExpr: return "index list expression" case *ast.InterfaceType: return "interface type" @@ -634,3 +647,8 @@ func NodeDescription(n ast.Node) string { } panic(fmt.Sprintf("unexpected node type: %T", n)) } + +func is[T any](x any) bool { + _, ok := x.(T) + return ok +} diff --git a/tools/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go b/tools/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go index f430b21b9..58934f766 100644 --- a/tools/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go +++ b/tools/vendor/golang.org/x/tools/go/ast/astutil/rewrite.go @@ -9,8 +9,6 @@ import ( "go/ast" "reflect" "sort" - - "golang.org/x/tools/internal/typeparams" ) // An ApplyFunc is invoked by Apply for each node n, even if n is nil, @@ -252,7 +250,7 @@ func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast. a.apply(n, "X", nil, n.X) a.apply(n, "Index", nil, n.Index) - case *typeparams.IndexListExpr: + case *ast.IndexListExpr: a.apply(n, "X", nil, n.X) a.applyList(n, "Indices") @@ -293,7 +291,7 @@ func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast. a.apply(n, "Fields", nil, n.Fields) case *ast.FuncType: - if tparams := typeparams.ForFuncType(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { a.apply(n, "TypeParams", nil, tparams) } a.apply(n, "Params", nil, n.Params) @@ -408,7 +406,7 @@ func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast. case *ast.TypeSpec: a.apply(n, "Doc", nil, n.Doc) a.apply(n, "Name", nil, n.Name) - if tparams := typeparams.ForTypeSpec(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { a.apply(n, "TypeParams", nil, tparams) } a.apply(n, "Type", nil, n.Type) diff --git a/tools/vendor/golang.org/x/tools/go/ast/astutil/util.go b/tools/vendor/golang.org/x/tools/go/ast/astutil/util.go index 919d5305a..6bdcf70ac 100644 --- a/tools/vendor/golang.org/x/tools/go/ast/astutil/util.go +++ b/tools/vendor/golang.org/x/tools/go/ast/astutil/util.go @@ -7,6 +7,7 @@ package astutil import "go/ast" // Unparen returns e with any enclosing parentheses stripped. +// TODO(adonovan): use go1.22's ast.Unparen. func Unparen(e ast.Expr) ast.Expr { for { p, ok := e.(*ast.ParenExpr) diff --git a/tools/vendor/golang.org/x/tools/go/ast/inspector/typeof.go b/tools/vendor/golang.org/x/tools/go/ast/inspector/typeof.go index 703c81395..2a872f89d 100644 --- a/tools/vendor/golang.org/x/tools/go/ast/inspector/typeof.go +++ b/tools/vendor/golang.org/x/tools/go/ast/inspector/typeof.go @@ -12,8 +12,6 @@ package inspector import ( "go/ast" "math" - - "golang.org/x/tools/internal/typeparams" ) const ( @@ -171,7 +169,7 @@ func typeOf(n ast.Node) uint64 { return 1 << nIncDecStmt case *ast.IndexExpr: return 1 << nIndexExpr - case *typeparams.IndexListExpr: + case *ast.IndexListExpr: return 1 << nIndexListExpr case *ast.InterfaceType: return 1 << nInterfaceType diff --git a/tools/vendor/golang.org/x/tools/go/buildutil/tags.go b/tools/vendor/golang.org/x/tools/go/buildutil/tags.go index 7cf523bca..32c8d1424 100644 --- a/tools/vendor/golang.org/x/tools/go/buildutil/tags.go +++ b/tools/vendor/golang.org/x/tools/go/buildutil/tags.go @@ -4,17 +4,22 @@ package buildutil -// This logic was copied from stringsFlag from $GOROOT/src/cmd/go/build.go. +// This duplicated logic must be kept in sync with that from go build: +// $GOROOT/src/cmd/go/internal/work/build.go (tagsFlag.Set) +// $GOROOT/src/cmd/go/internal/base/flag.go (StringsFlag.Set) +// $GOROOT/src/cmd/internal/quoted/quoted.go (isSpaceByte, Split) -import "fmt" +import ( + "fmt" + "strings" +) const TagsFlagDoc = "a list of `build tags` to consider satisfied during the build. " + "For more information about build tags, see the description of " + "build constraints in the documentation for the go/build package" // TagsFlag is an implementation of the flag.Value and flag.Getter interfaces that parses -// a flag value in the same manner as go build's -tags flag and -// populates a []string slice. +// a flag value the same as go build's -tags flag and populates a []string slice. // // See $GOROOT/src/go/build/doc.go for description of build tags. // See $GOROOT/src/cmd/go/doc.go for description of 'go build -tags' flag. @@ -25,19 +30,32 @@ const TagsFlagDoc = "a list of `build tags` to consider satisfied during the bui type TagsFlag []string func (v *TagsFlag) Set(s string) error { - var err error - *v, err = splitQuotedFields(s) - if *v == nil { - *v = []string{} + // See $GOROOT/src/cmd/go/internal/work/build.go (tagsFlag.Set) + // For compatibility with Go 1.12 and earlier, allow "-tags='a b c'" or even just "-tags='a'". + if strings.Contains(s, " ") || strings.Contains(s, "'") { + var err error + *v, err = splitQuotedFields(s) + if *v == nil { + *v = []string{} + } + return err + } + + // Starting in Go 1.13, the -tags flag is a comma-separated list of build tags. + *v = []string{} + for _, s := range strings.Split(s, ",") { + if s != "" { + *v = append(*v, s) + } } - return err + return nil } func (v *TagsFlag) Get() interface{} { return *v } func splitQuotedFields(s string) ([]string, error) { - // Split fields allowing '' or "" around elements. - // Quotes further inside the string do not count. + // See $GOROOT/src/cmd/internal/quoted/quoted.go (Split) + // This must remain in sync with that logic. var f []string for len(s) > 0 { for len(s) > 0 && isSpaceByte(s[0]) { @@ -76,5 +94,7 @@ func (v *TagsFlag) String() string { } func isSpaceByte(c byte) bool { + // See $GOROOT/src/cmd/internal/quoted/quoted.go (isSpaceByte, Split) + // This list must remain in sync with that. return c == ' ' || c == '\t' || c == '\n' || c == '\r' } diff --git a/tools/vendor/golang.org/x/tools/go/cfg/builder.go b/tools/vendor/golang.org/x/tools/go/cfg/builder.go index dad6a444d..ac4d63c40 100644 --- a/tools/vendor/golang.org/x/tools/go/cfg/builder.go +++ b/tools/vendor/golang.org/x/tools/go/cfg/builder.go @@ -16,8 +16,8 @@ type builder struct { cfg *CFG mayReturn func(*ast.CallExpr) bool current *Block - lblocks map[*ast.Object]*lblock // labeled blocks - targets *targets // linked stack of branch targets + lblocks map[string]*lblock // labeled blocks + targets *targets // linked stack of branch targets } func (b *builder) stmt(_s ast.Stmt) { @@ -42,7 +42,7 @@ start: b.add(s) if call, ok := s.X.(*ast.CallExpr); ok && !b.mayReturn(call) { // Calls to panic, os.Exit, etc, never return. - b.current = b.newBlock("unreachable.call") + b.current = b.newBlock(KindUnreachable, s) } case *ast.DeclStmt: @@ -57,7 +57,7 @@ start: } case *ast.LabeledStmt: - label = b.labeledBlock(s.Label) + label = b.labeledBlock(s.Label, s) b.jump(label._goto) b.current = label._goto _s = s.Stmt @@ -65,7 +65,7 @@ start: case *ast.ReturnStmt: b.add(s) - b.current = b.newBlock("unreachable.return") + b.current = b.newBlock(KindUnreachable, s) case *ast.BranchStmt: b.branchStmt(s) @@ -77,11 +77,11 @@ start: if s.Init != nil { b.stmt(s.Init) } - then := b.newBlock("if.then") - done := b.newBlock("if.done") + then := b.newBlock(KindIfThen, s) + done := b.newBlock(KindIfDone, s) _else := done if s.Else != nil { - _else = b.newBlock("if.else") + _else = b.newBlock(KindIfElse, s) } b.add(s.Cond) b.ifelse(then, _else) @@ -128,7 +128,7 @@ func (b *builder) branchStmt(s *ast.BranchStmt) { switch s.Tok { case token.BREAK: if s.Label != nil { - if lb := b.labeledBlock(s.Label); lb != nil { + if lb := b.labeledBlock(s.Label, nil); lb != nil { block = lb._break } } else { @@ -139,7 +139,7 @@ func (b *builder) branchStmt(s *ast.BranchStmt) { case token.CONTINUE: if s.Label != nil { - if lb := b.labeledBlock(s.Label); lb != nil { + if lb := b.labeledBlock(s.Label, nil); lb != nil { block = lb._continue } } else { @@ -155,14 +155,14 @@ func (b *builder) branchStmt(s *ast.BranchStmt) { case token.GOTO: if s.Label != nil { - block = b.labeledBlock(s.Label)._goto + block = b.labeledBlock(s.Label, nil)._goto } } - if block == nil { - block = b.newBlock("undefined.branch") + if block == nil { // ill-typed (e.g. undefined label) + block = b.newBlock(KindUnreachable, s) } b.jump(block) - b.current = b.newBlock("unreachable.branch") + b.current = b.newBlock(KindUnreachable, s) } func (b *builder) switchStmt(s *ast.SwitchStmt, label *lblock) { @@ -172,7 +172,7 @@ func (b *builder) switchStmt(s *ast.SwitchStmt, label *lblock) { if s.Tag != nil { b.add(s.Tag) } - done := b.newBlock("switch.done") + done := b.newBlock(KindSwitchDone, s) if label != nil { label._break = done } @@ -188,13 +188,13 @@ func (b *builder) switchStmt(s *ast.SwitchStmt, label *lblock) { for i, clause := range s.Body.List { body := fallthru if body == nil { - body = b.newBlock("switch.body") // first case only + body = b.newBlock(KindSwitchCaseBody, clause) // first case only } // Preallocate body block for the next case. fallthru = done if i+1 < ncases { - fallthru = b.newBlock("switch.body") + fallthru = b.newBlock(KindSwitchCaseBody, s.Body.List[i+1]) } cc := clause.(*ast.CaseClause) @@ -208,7 +208,7 @@ func (b *builder) switchStmt(s *ast.SwitchStmt, label *lblock) { var nextCond *Block for _, cond := range cc.List { - nextCond = b.newBlock("switch.next") + nextCond = b.newBlock(KindSwitchNextCase, cc) b.add(cond) // one half of the tag==cond condition b.ifelse(body, nextCond) b.current = nextCond @@ -247,7 +247,7 @@ func (b *builder) typeSwitchStmt(s *ast.TypeSwitchStmt, label *lblock) { b.add(s.Assign) } - done := b.newBlock("typeswitch.done") + done := b.newBlock(KindSwitchDone, s) if label != nil { label._break = done } @@ -258,10 +258,10 @@ func (b *builder) typeSwitchStmt(s *ast.TypeSwitchStmt, label *lblock) { default_ = cc continue } - body := b.newBlock("typeswitch.body") + body := b.newBlock(KindSwitchCaseBody, cc) var next *Block for _, casetype := range cc.List { - next = b.newBlock("typeswitch.next") + next = b.newBlock(KindSwitchNextCase, cc) // casetype is a type, so don't call b.add(casetype). // This block logically contains a type assertion, // x.(casetype), but it's unclear how to represent x. @@ -300,7 +300,7 @@ func (b *builder) selectStmt(s *ast.SelectStmt, label *lblock) { } } - done := b.newBlock("select.done") + done := b.newBlock(KindSelectDone, s) if label != nil { label._break = done } @@ -312,8 +312,8 @@ func (b *builder) selectStmt(s *ast.SelectStmt, label *lblock) { defaultBody = &clause.Body continue } - body := b.newBlock("select.body") - next := b.newBlock("select.next") + body := b.newBlock(KindSelectCaseBody, clause) + next := b.newBlock(KindSelectAfterCase, clause) b.ifelse(body, next) b.current = body b.targets = &targets{ @@ -358,15 +358,15 @@ func (b *builder) forStmt(s *ast.ForStmt, label *lblock) { if s.Init != nil { b.stmt(s.Init) } - body := b.newBlock("for.body") - done := b.newBlock("for.done") // target of 'break' - loop := body // target of back-edge + body := b.newBlock(KindForBody, s) + done := b.newBlock(KindForDone, s) // target of 'break' + loop := body // target of back-edge if s.Cond != nil { - loop = b.newBlock("for.loop") + loop = b.newBlock(KindForLoop, s) } cont := loop // target of 'continue' if s.Post != nil { - cont = b.newBlock("for.post") + cont = b.newBlock(KindForPost, s) } if label != nil { label._break = done @@ -414,12 +414,12 @@ func (b *builder) rangeStmt(s *ast.RangeStmt, label *lblock) { // jump loop // done: (target of break) - loop := b.newBlock("range.loop") + loop := b.newBlock(KindRangeLoop, s) b.jump(loop) b.current = loop - body := b.newBlock("range.body") - done := b.newBlock("range.done") + body := b.newBlock(KindRangeBody, s) + done := b.newBlock(KindRangeDone, s) b.ifelse(body, done) b.current = body @@ -461,14 +461,19 @@ type lblock struct { // labeledBlock returns the branch target associated with the // specified label, creating it if needed. -func (b *builder) labeledBlock(label *ast.Ident) *lblock { - lb := b.lblocks[label.Obj] +func (b *builder) labeledBlock(label *ast.Ident, stmt *ast.LabeledStmt) *lblock { + lb := b.lblocks[label.Name] if lb == nil { - lb = &lblock{_goto: b.newBlock(label.Name)} + lb = &lblock{_goto: b.newBlock(KindLabel, nil)} if b.lblocks == nil { - b.lblocks = make(map[*ast.Object]*lblock) + b.lblocks = make(map[string]*lblock) } - b.lblocks[label.Obj] = lb + b.lblocks[label.Name] = lb + } + // Fill in the label later (in case of forward goto). + // Stmt may be set already if labels are duplicated (ill-typed). + if stmt != nil && lb._goto.Stmt == nil { + lb._goto.Stmt = stmt } return lb } @@ -477,11 +482,12 @@ func (b *builder) labeledBlock(label *ast.Ident) *lblock { // slice and returns it. // It does not automatically become the current block. // comment is an optional string for more readable debugging output. -func (b *builder) newBlock(comment string) *Block { +func (b *builder) newBlock(kind BlockKind, stmt ast.Stmt) *Block { g := b.cfg block := &Block{ - Index: int32(len(g.Blocks)), - comment: comment, + Index: int32(len(g.Blocks)), + Kind: kind, + Stmt: stmt, } block.Succs = block.succs2[:0] g.Blocks = append(g.Blocks, block) diff --git a/tools/vendor/golang.org/x/tools/go/cfg/cfg.go b/tools/vendor/golang.org/x/tools/go/cfg/cfg.go index 37d799f4b..fad4530ff 100644 --- a/tools/vendor/golang.org/x/tools/go/cfg/cfg.go +++ b/tools/vendor/golang.org/x/tools/go/cfg/cfg.go @@ -9,7 +9,10 @@ // // The blocks of the CFG contain all the function's non-control // statements. The CFG does not contain control statements such as If, -// Switch, Select, and Branch, but does contain their subexpressions. +// Switch, Select, and Branch, but does contain their subexpressions; +// also, each block records the control statement (Block.Stmt) that +// gave rise to it and its relationship (Block.Kind) to that statement. +// // For example, this source code: // // if x := f(); x != nil { @@ -20,14 +23,14 @@ // // produces this CFG: // -// 1: x := f() +// 1: x := f() Body // x != nil // succs: 2, 3 -// 2: T() +// 2: T() IfThen // succs: 4 -// 3: F() +// 3: F() IfElse // succs: 4 -// 4: +// 4: IfDone // // The CFG does contain Return statements; even implicit returns are // materialized (at the position of the function's closing brace). @@ -50,6 +53,7 @@ import ( // // The entry point is Blocks[0]; there may be multiple return blocks. type CFG struct { + fset *token.FileSet Blocks []*Block // block[0] is entry; order otherwise undefined } @@ -64,9 +68,63 @@ type Block struct { Succs []*Block // successor nodes in the graph Index int32 // index within CFG.Blocks Live bool // block is reachable from entry + Kind BlockKind // block kind + Stmt ast.Stmt // statement that gave rise to this block (see BlockKind for details) - comment string // for debugging - succs2 [2]*Block // underlying array for Succs + succs2 [2]*Block // underlying array for Succs +} + +// A BlockKind identifies the purpose of a block. +// It also determines the possible types of its Stmt field. +type BlockKind uint8 + +const ( + KindInvalid BlockKind = iota // Stmt=nil + + KindUnreachable // unreachable block after {Branch,Return}Stmt / no-return call ExprStmt + KindBody // function body BlockStmt + KindForBody // body of ForStmt + KindForDone // block after ForStmt + KindForLoop // head of ForStmt + KindForPost // post condition of ForStmt + KindIfDone // block after IfStmt + KindIfElse // else block of IfStmt + KindIfThen // then block of IfStmt + KindLabel // labeled block of BranchStmt (Stmt may be nil for dangling label) + KindRangeBody // body of RangeStmt + KindRangeDone // block after RangeStmt + KindRangeLoop // head of RangeStmt + KindSelectCaseBody // body of SelectStmt + KindSelectDone // block after SelectStmt + KindSelectAfterCase // block after a CommClause + KindSwitchCaseBody // body of CaseClause + KindSwitchDone // block after {Type.}SwitchStmt + KindSwitchNextCase // secondary expression of a multi-expression CaseClause +) + +func (kind BlockKind) String() string { + return [...]string{ + KindInvalid: "Invalid", + KindUnreachable: "Unreachable", + KindBody: "Body", + KindForBody: "ForBody", + KindForDone: "ForDone", + KindForLoop: "ForLoop", + KindForPost: "ForPost", + KindIfDone: "IfDone", + KindIfElse: "IfElse", + KindIfThen: "IfThen", + KindLabel: "Label", + KindRangeBody: "RangeBody", + KindRangeDone: "RangeDone", + KindRangeLoop: "RangeLoop", + KindSelectCaseBody: "SelectCaseBody", + KindSelectDone: "SelectDone", + KindSelectAfterCase: "SelectAfterCase", + KindSwitchCaseBody: "SwitchCaseBody", + KindSwitchDone: "SwitchDone", + KindSwitchNextCase: "SwitchNextCase", + }[kind] } // New returns a new control-flow graph for the specified function body, @@ -82,7 +140,7 @@ func New(body *ast.BlockStmt, mayReturn func(*ast.CallExpr) bool) *CFG { mayReturn: mayReturn, cfg: new(CFG), } - b.current = b.newBlock("entry") + b.current = b.newBlock(KindBody, body) b.stmt(body) // Compute liveness (reachability from entry point), breadth-first. @@ -110,10 +168,22 @@ func New(body *ast.BlockStmt, mayReturn func(*ast.CallExpr) bool) *CFG { } func (b *Block) String() string { - return fmt.Sprintf("block %d (%s)", b.Index, b.comment) + return fmt.Sprintf("block %d (%s)", b.Index, b.comment(nil)) } -// Return returns the return statement at the end of this block if present, nil otherwise. +func (b *Block) comment(fset *token.FileSet) string { + s := b.Kind.String() + if fset != nil && b.Stmt != nil { + s = fmt.Sprintf("%s@L%d", s, fset.Position(b.Stmt.Pos()).Line) + } + return s +} + +// Return returns the return statement at the end of this block if present, nil +// otherwise. +// +// When control falls off the end of the function, the ReturnStmt is synthetic +// and its [ast.Node.End] position may be beyond the end of the file. func (b *Block) Return() (ret *ast.ReturnStmt) { if len(b.Nodes) > 0 { ret, _ = b.Nodes[len(b.Nodes)-1].(*ast.ReturnStmt) @@ -125,7 +195,7 @@ func (b *Block) Return() (ret *ast.ReturnStmt) { func (g *CFG) Format(fset *token.FileSet) string { var buf bytes.Buffer for _, b := range g.Blocks { - fmt.Fprintf(&buf, ".%d: # %s\n", b.Index, b.comment) + fmt.Fprintf(&buf, ".%d: # %s\n", b.Index, b.comment(fset)) for _, n := range b.Nodes { fmt.Fprintf(&buf, "\t%s\n", formatNode(fset, n)) } @@ -141,6 +211,34 @@ func (g *CFG) Format(fset *token.FileSet) string { return buf.String() } +// Dot returns the control-flow graph in the [Dot graph description language]. +// Use a command such as 'dot -Tsvg' to render it in a form viewable in a browser. +// This method is provided as a debugging aid; the details of the +// output are unspecified and may change. +// +// [Dot graph description language]: ​​https://en.wikipedia.org/wiki/DOT_(graph_description_language) +func (g *CFG) Dot(fset *token.FileSet) string { + var buf bytes.Buffer + buf.WriteString("digraph CFG {\n") + buf.WriteString(" node [shape=box];\n") + for _, b := range g.Blocks { + // node label + var text bytes.Buffer + text.WriteString(b.comment(fset)) + for _, n := range b.Nodes { + fmt.Fprintf(&text, "\n%s", formatNode(fset, n)) + } + + // node and edges + fmt.Fprintf(&buf, " n%d [label=%q];\n", b.Index, &text) + for _, succ := range b.Succs { + fmt.Fprintf(&buf, " n%d -> n%d;\n", b.Index, succ.Index) + } + } + buf.WriteString("}\n") + return buf.String() +} + func formatNode(fset *token.FileSet, n ast.Node) string { var buf bytes.Buffer format.Node(&buf, fset, n) diff --git a/tools/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go b/tools/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go index 03543bd4b..137cc8df1 100644 --- a/tools/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go +++ b/tools/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go @@ -47,7 +47,7 @@ import ( func Find(importPath, srcDir string) (filename, path string) { cmd := exec.Command("go", "list", "-json", "-export", "--", importPath) cmd.Dir = srcDir - out, err := cmd.CombinedOutput() + out, err := cmd.Output() if err != nil { return "", "" } diff --git a/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo.go b/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo.go index 38d5c6c7c..697974bb9 100644 --- a/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo.go +++ b/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo.go @@ -59,11 +59,10 @@ import ( "go/token" "log" "os" + "os/exec" "path/filepath" "regexp" "strings" - - exec "golang.org/x/sys/execabs" ) // ProcessFiles invokes the cgo preprocessor on bp.CgoFiles, parses diff --git a/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go b/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go index 7d94bbc1e..2455be54f 100644 --- a/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go +++ b/tools/vendor/golang.org/x/tools/go/internal/cgo/cgo_pkgconfig.go @@ -8,19 +8,22 @@ import ( "errors" "fmt" "go/build" - exec "golang.org/x/sys/execabs" + "os/exec" "strings" ) // pkgConfig runs pkg-config with the specified arguments and returns the flags it prints. func pkgConfig(mode string, pkgs []string) (flags []string, err error) { cmd := exec.Command("pkg-config", append([]string{mode}, pkgs...)...) - out, err := cmd.CombinedOutput() + out, err := cmd.Output() if err != nil { s := fmt.Sprintf("%s failed: %v", strings.Join(cmd.Args, " "), err) if len(out) > 0 { s = fmt.Sprintf("%s: %s", s, out) } + if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { + s = fmt.Sprintf("%s\nstderr:\n%s", s, err.Stderr) + } return nil, errors.New(s) } if len(out) > 0 { diff --git a/tools/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go b/tools/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go deleted file mode 100644 index 0454cdd78..000000000 --- a/tools/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package packagesdriver fetches type sizes for go/packages and go/analysis. -package packagesdriver - -import ( - "context" - "fmt" - "strings" - - "golang.org/x/tools/internal/gocommand" -) - -var debug = false - -func GetSizesForArgsGolist(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (string, string, error) { - inv.Verb = "list" - inv.Args = []string{"-f", "{{context.GOARCH}} {{context.Compiler}}", "--", "unsafe"} - stdout, stderr, friendlyErr, rawErr := gocmdRunner.RunRaw(ctx, inv) - var goarch, compiler string - if rawErr != nil { - if rawErrMsg := rawErr.Error(); strings.Contains(rawErrMsg, "cannot find main module") || strings.Contains(rawErrMsg, "go.mod file not found") { - // User's running outside of a module. All bets are off. Get GOARCH and guess compiler is gc. - // TODO(matloob): Is this a problem in practice? - inv.Verb = "env" - inv.Args = []string{"GOARCH"} - envout, enverr := gocmdRunner.Run(ctx, inv) - if enverr != nil { - return "", "", enverr - } - goarch = strings.TrimSpace(envout.String()) - compiler = "gc" - } else { - return "", "", friendlyErr - } - } else { - fields := strings.Fields(stdout.String()) - if len(fields) < 2 { - return "", "", fmt.Errorf("could not parse GOARCH and Go compiler in format \" \":\nstdout: <<%s>>\nstderr: <<%s>>", - stdout.String(), stderr.String()) - } - goarch = fields[0] - compiler = fields[1] - } - return compiler, goarch, nil -} diff --git a/tools/vendor/golang.org/x/tools/go/loader/loader.go b/tools/vendor/golang.org/x/tools/go/loader/loader.go index edf62c2cc..013c0f505 100644 --- a/tools/vendor/golang.org/x/tools/go/loader/loader.go +++ b/tools/vendor/golang.org/x/tools/go/loader/loader.go @@ -23,7 +23,7 @@ import ( "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/internal/cgo" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/versions" ) var ignoreVendor build.ImportMode @@ -1033,13 +1033,14 @@ func (imp *importer) newPackageInfo(path, dir string) *PackageInfo { Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), }, errorFunc: imp.conf.TypeChecker.Error, dir: dir, } - typeparams.InitInstanceInfo(&info.Info) + versions.InitFileVersions(&info.Info) // Copy the types.Config so we can vary it across PackageInfos. tc := imp.conf.TypeChecker diff --git a/tools/vendor/golang.org/x/tools/go/packages/doc.go b/tools/vendor/golang.org/x/tools/go/packages/doc.go index a7a8f73e3..3531ac8f5 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/doc.go +++ b/tools/vendor/golang.org/x/tools/go/packages/doc.go @@ -5,12 +5,20 @@ /* Package packages loads Go packages for inspection and analysis. -The Load function takes as input a list of patterns and return a list of Package -structs describing individual packages matched by those patterns. -The LoadMode controls the amount of detail in the loaded packages. - -Load passes most patterns directly to the underlying build tool, -but all patterns with the prefix "query=", where query is a +The [Load] function takes as input a list of patterns and returns a +list of [Package] values describing individual packages matched by those +patterns. +A [Config] specifies configuration options, the most important of which is +the [LoadMode], which controls the amount of detail in the loaded packages. + +Load passes most patterns directly to the underlying build tool. +The default build tool is the go command. +Its supported patterns are described at +https://pkg.go.dev/cmd/go#hdr-Package_lists_and_patterns. +Other build systems may be supported by providing a "driver"; +see [The driver protocol]. + +All patterns with the prefix "query=", where query is a non-empty string of letters from [a-z], are reserved and may be interpreted as query operators. @@ -64,9 +72,31 @@ reported about the loaded packages. See the documentation for type LoadMode for details. Most tools should pass their command-line arguments (after any flags) -uninterpreted to the loader, so that the loader can interpret them +uninterpreted to [Load], so that it can interpret them according to the conventions of the underlying build system. + See the Example function for typical usage. + +# The driver protocol + +[Load] may be used to load Go packages even in Go projects that use +alternative build systems, by installing an appropriate "driver" +program for the build system and specifying its location in the +GOPACKAGESDRIVER environment variable. +For example, +https://github.com/bazelbuild/rules_go/wiki/Editor-and-tool-integration +explains how to use the driver for Bazel. + +The driver program is responsible for interpreting patterns in its +preferred notation and reporting information about the packages that +those patterns identify. Drivers must also support the special "file=" +and "pattern=" patterns described above. + +The patterns are provided as positional command-line arguments. A +JSON-encoded [DriverRequest] message providing additional information +is written to the driver's standard input. The driver must write a +JSON-encoded [DriverResponse] message to its standard output. (This +message differs from the JSON schema produced by 'go list'.) */ package packages // import "golang.org/x/tools/go/packages" @@ -168,14 +198,6 @@ Instead, ssadump no longer requests the runtime package, but seeks it among the dependencies of the user-specified packages, and emits an error if it is not found. -Overlays: The Overlay field in the Config allows providing alternate contents -for Go source files, by providing a mapping from file path to contents. -go/packages will pull in new imports added in overlay files when go/packages -is run in LoadImports mode or greater. -Overlay support for the go list driver isn't complete yet: if the file doesn't -exist on disk, it will only be recognized in an overlay if it is a non-test file -and the package would be reported even without the overlay. - Questions & Tasks - Add GOARCH/GOOS? diff --git a/tools/vendor/golang.org/x/tools/go/packages/external.go b/tools/vendor/golang.org/x/tools/go/packages/external.go index 7242a0a7d..c2b4b711b 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/external.go +++ b/tools/vendor/golang.org/x/tools/go/packages/external.go @@ -2,46 +2,85 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// This file enables an external tool to intercept package requests. -// If the tool is present then its results are used in preference to -// the go list command. - package packages +// This file defines the protocol that enables an external "driver" +// tool to supply package metadata in place of 'go list'. + import ( "bytes" "encoding/json" "fmt" - exec "golang.org/x/sys/execabs" "os" + "os/exec" "strings" ) -// The Driver Protocol +// DriverRequest defines the schema of a request for package metadata +// from an external driver program. The JSON-encoded DriverRequest +// message is provided to the driver program's standard input. The +// query patterns are provided as command-line arguments. // -// The driver, given the inputs to a call to Load, returns metadata about the packages specified. -// This allows for different build systems to support go/packages by telling go/packages how the -// packages' source is organized. -// The driver is a binary, either specified by the GOPACKAGESDRIVER environment variable or in -// the path as gopackagesdriver. It's given the inputs to load in its argv. See the package -// documentation in doc.go for the full description of the patterns that need to be supported. -// A driver receives as a JSON-serialized driverRequest struct in standard input and will -// produce a JSON-serialized driverResponse (see definition in packages.go) in its standard output. - -// driverRequest is used to provide the portion of Load's Config that is needed by a driver. -type driverRequest struct { +// See the package documentation for an overview. +type DriverRequest struct { Mode LoadMode `json:"mode"` + // Env specifies the environment the underlying build system should be run in. Env []string `json:"env"` + // BuildFlags are flags that should be passed to the underlying build system. BuildFlags []string `json:"build_flags"` + // Tests specifies whether the patterns should also return test packages. Tests bool `json:"tests"` - // Overlay maps file paths (relative to the driver's working directory) to the byte contents - // of overlay files. + + // Overlay maps file paths (relative to the driver's working directory) + // to the contents of overlay files (see Config.Overlay). Overlay map[string][]byte `json:"overlay"` } +// DriverResponse defines the schema of a response from an external +// driver program, providing the results of a query for package +// metadata. The driver program must write a JSON-encoded +// DriverResponse message to its standard output. +// +// See the package documentation for an overview. +type DriverResponse struct { + // NotHandled is returned if the request can't be handled by the current + // driver. If an external driver returns a response with NotHandled, the + // rest of the DriverResponse is ignored, and go/packages will fallback + // to the next driver. If go/packages is extended in the future to support + // lists of multiple drivers, go/packages will fall back to the next driver. + NotHandled bool + + // Compiler and Arch are the arguments pass of types.SizesFor + // to get a types.Sizes to use when type checking. + Compiler string + Arch string + + // Roots is the set of package IDs that make up the root packages. + // We have to encode this separately because when we encode a single package + // we cannot know if it is one of the roots as that requires knowledge of the + // graph it is part of. + Roots []string `json:",omitempty"` + + // Packages is the full set of packages in the graph. + // The packages are not connected into a graph. + // The Imports if populated will be stubs that only have their ID set. + // Imports will be connected and then type and syntax information added in a + // later pass (see refine). + Packages []*Package + + // GoVersion is the minor version number used by the driver + // (e.g. the go command on the PATH) when selecting .go files. + // Zero means unknown. + GoVersion int +} + +// driver is the type for functions that query the build system for the +// packages named by the patterns. +type driver func(cfg *Config, patterns ...string) (*DriverResponse, error) + // findExternalDriver returns the file path of a tool that supplies // the build system package structure, or "" if not found." // If GOPACKAGESDRIVER is set in the environment findExternalTool returns its @@ -64,8 +103,8 @@ func findExternalDriver(cfg *Config) driver { return nil } } - return func(cfg *Config, words ...string) (*driverResponse, error) { - req, err := json.Marshal(driverRequest{ + return func(cfg *Config, words ...string) (*DriverResponse, error) { + req, err := json.Marshal(DriverRequest{ Mode: cfg.Mode, Env: cfg.Env, BuildFlags: cfg.BuildFlags, @@ -80,7 +119,19 @@ func findExternalDriver(cfg *Config) driver { stderr := new(bytes.Buffer) cmd := exec.CommandContext(cfg.Context, tool, words...) cmd.Dir = cfg.Dir - cmd.Env = cfg.Env + // The cwd gets resolved to the real path. On Darwin, where + // /tmp is a symlink, this breaks anything that expects the + // working directory to keep the original path, including the + // go command when dealing with modules. + // + // os.Getwd stdlib has a special feature where if the + // cwd and the PWD are the same node then it trusts + // the PWD, so by setting it in the env for the child + // process we fix up all the paths returned by the go + // command. + // + // (See similar trick in Invocation.run in ../../internal/gocommand/invoke.go) + cmd.Env = append(slicesClip(cfg.Env), "PWD="+cfg.Dir) cmd.Stdin = bytes.NewReader(req) cmd.Stdout = buf cmd.Stderr = stderr @@ -92,10 +143,14 @@ func findExternalDriver(cfg *Config) driver { fmt.Fprintf(os.Stderr, "%s stderr: <<%s>>\n", cmdDebugStr(cmd), stderr) } - var response driverResponse + var response DriverResponse if err := json.Unmarshal(buf.Bytes(), &response); err != nil { return nil, err } return &response, nil } } + +// slicesClip removes unused capacity from the slice, returning s[:len(s):len(s)]. +// TODO(adonovan): use go1.21 slices.Clip. +func slicesClip[S ~[]E, E any](s S) S { return s[:len(s):len(s)] } diff --git a/tools/vendor/golang.org/x/tools/go/packages/golist.go b/tools/vendor/golang.org/x/tools/go/packages/golist.go index 1f1eade0a..1a3a5b44f 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/golist.go +++ b/tools/vendor/golang.org/x/tools/go/packages/golist.go @@ -11,6 +11,7 @@ import ( "fmt" "log" "os" + "os/exec" "path" "path/filepath" "reflect" @@ -20,8 +21,6 @@ import ( "sync" "unicode" - exec "golang.org/x/sys/execabs" - "golang.org/x/tools/go/internal/packagesdriver" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/packagesinternal" ) @@ -35,23 +34,23 @@ type goTooOldError struct { error } -// responseDeduper wraps a driverResponse, deduplicating its contents. +// responseDeduper wraps a DriverResponse, deduplicating its contents. type responseDeduper struct { seenRoots map[string]bool seenPackages map[string]*Package - dr *driverResponse + dr *DriverResponse } func newDeduper() *responseDeduper { return &responseDeduper{ - dr: &driverResponse{}, + dr: &DriverResponse{}, seenRoots: map[string]bool{}, seenPackages: map[string]*Package{}, } } -// addAll fills in r with a driverResponse. -func (r *responseDeduper) addAll(dr *driverResponse) { +// addAll fills in r with a DriverResponse. +func (r *responseDeduper) addAll(dr *DriverResponse) { for _, pkg := range dr.Packages { r.addPackage(pkg) } @@ -128,7 +127,7 @@ func (state *golistState) mustGetEnv() map[string]string { // goListDriver uses the go list command to interpret the patterns and produce // the build system package structure. // See driver for more details. -func goListDriver(cfg *Config, patterns ...string) (*driverResponse, error) { +func goListDriver(cfg *Config, patterns ...string) (_ *DriverResponse, err error) { // Make sure that any asynchronous go commands are killed when we return. parentCtx := cfg.Context if parentCtx == nil { @@ -146,16 +145,18 @@ func goListDriver(cfg *Config, patterns ...string) (*driverResponse, error) { } // Fill in response.Sizes asynchronously if necessary. - var sizeserr error - var sizeswg sync.WaitGroup if cfg.Mode&NeedTypesSizes != 0 || cfg.Mode&NeedTypes != 0 { - sizeswg.Add(1) + errCh := make(chan error) go func() { - compiler, arch, err := packagesdriver.GetSizesForArgsGolist(ctx, state.cfgInvocation(), cfg.gocmdRunner) - sizeserr = err + compiler, arch, err := getSizesForArgs(ctx, state.cfgInvocation(), cfg.gocmdRunner) response.dr.Compiler = compiler response.dr.Arch = arch - sizeswg.Done() + errCh <- err + }() + defer func() { + if sizesErr := <-errCh; sizesErr != nil { + err = sizesErr + } }() } @@ -208,87 +209,10 @@ extractQueries: } } - // Only use go/packages' overlay processing if we're using a Go version - // below 1.16. Otherwise, go list handles it. - if goVersion, err := state.getGoVersion(); err == nil && goVersion < 16 { - modifiedPkgs, needPkgs, err := state.processGolistOverlay(response) - if err != nil { - return nil, err - } - - var containsCandidates []string - if len(containFiles) > 0 { - containsCandidates = append(containsCandidates, modifiedPkgs...) - containsCandidates = append(containsCandidates, needPkgs...) - } - if err := state.addNeededOverlayPackages(response, needPkgs); err != nil { - return nil, err - } - // Check candidate packages for containFiles. - if len(containFiles) > 0 { - for _, id := range containsCandidates { - pkg, ok := response.seenPackages[id] - if !ok { - response.addPackage(&Package{ - ID: id, - Errors: []Error{{ - Kind: ListError, - Msg: fmt.Sprintf("package %s expected but not seen", id), - }}, - }) - continue - } - for _, f := range containFiles { - for _, g := range pkg.GoFiles { - if sameFile(f, g) { - response.addRoot(id) - } - } - } - } - } - // Add root for any package that matches a pattern. This applies only to - // packages that are modified by overlays, since they are not added as - // roots automatically. - for _, pattern := range restPatterns { - match := matchPattern(pattern) - for _, pkgID := range modifiedPkgs { - pkg, ok := response.seenPackages[pkgID] - if !ok { - continue - } - if match(pkg.PkgPath) { - response.addRoot(pkg.ID) - } - } - } - } - - sizeswg.Wait() - if sizeserr != nil { - return nil, sizeserr - } + // (We may yet return an error due to defer.) return response.dr, nil } -func (state *golistState) addNeededOverlayPackages(response *responseDeduper, pkgs []string) error { - if len(pkgs) == 0 { - return nil - } - dr, err := state.createDriverResponse(pkgs...) - if err != nil { - return err - } - for _, pkg := range dr.Packages { - response.addPackage(pkg) - } - _, needPkgs, err := state.processGolistOverlay(response) - if err != nil { - return err - } - return state.addNeededOverlayPackages(response, needPkgs) -} - func (state *golistState) runContainsQueries(response *responseDeduper, queries []string) error { for _, query := range queries { // TODO(matloob): Do only one query per directory. @@ -340,7 +264,7 @@ func (state *golistState) runContainsQueries(response *responseDeduper, queries // adhocPackage attempts to load or construct an ad-hoc package for a given // query, if the original call to the driver produced inadequate results. -func (state *golistState) adhocPackage(pattern, query string) (*driverResponse, error) { +func (state *golistState) adhocPackage(pattern, query string) (*DriverResponse, error) { response, err := state.createDriverResponse(query) if err != nil { return nil, err @@ -431,7 +355,7 @@ func otherFiles(p *jsonPackage) [][]string { // createDriverResponse uses the "go list" command to expand the pattern // words and return a response for the specified packages. -func (state *golistState) createDriverResponse(words ...string) (*driverResponse, error) { +func (state *golistState) createDriverResponse(words ...string) (*DriverResponse, error) { // go list uses the following identifiers in ImportPath and Imports: // // "p" -- importable package or main (command) @@ -458,7 +382,7 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse pkgs := make(map[string]*Package) additionalErrors := make(map[string][]Error) // Decode the JSON and convert it to Package form. - response := &driverResponse{ + response := &DriverResponse{ GoVersion: goVersion, } for dec := json.NewDecoder(buf); dec.More(); { @@ -916,6 +840,7 @@ func (state *golistState) cfgInvocation() gocommand.Invocation { Env: cfg.Env, Logf: cfg.Logf, WorkingDir: cfg.Dir, + Overlay: cfg.goListOverlayFile, } } @@ -924,26 +849,6 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, cfg := state.cfg inv := state.cfgInvocation() - - // For Go versions 1.16 and above, `go list` accepts overlays directly via - // the -overlay flag. Set it, if it's available. - // - // The check for "list" is not necessarily required, but we should avoid - // getting the go version if possible. - if verb == "list" { - goVersion, err := state.getGoVersion() - if err != nil { - return nil, err - } - if goVersion >= 16 { - filename, cleanup, err := state.writeOverlays() - if err != nil { - return nil, err - } - defer cleanup() - inv.Overlay = filename - } - } inv.Verb = verb inv.Args = args gocmdRunner := cfg.gocmdRunner @@ -1090,67 +995,6 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, return stdout, nil } -// OverlayJSON is the format overlay files are expected to be in. -// The Replace map maps from overlaid paths to replacement paths: -// the Go command will forward all reads trying to open -// each overlaid path to its replacement path, or consider the overlaid -// path not to exist if the replacement path is empty. -// -// From golang/go#39958. -type OverlayJSON struct { - Replace map[string]string `json:"replace,omitempty"` -} - -// writeOverlays writes out files for go list's -overlay flag, as described -// above. -func (state *golistState) writeOverlays() (filename string, cleanup func(), err error) { - // Do nothing if there are no overlays in the config. - if len(state.cfg.Overlay) == 0 { - return "", func() {}, nil - } - dir, err := os.MkdirTemp("", "gopackages-*") - if err != nil { - return "", nil, err - } - // The caller must clean up this directory, unless this function returns an - // error. - cleanup = func() { - os.RemoveAll(dir) - } - defer func() { - if err != nil { - cleanup() - } - }() - overlays := map[string]string{} - for k, v := range state.cfg.Overlay { - // Create a unique filename for the overlaid files, to avoid - // creating nested directories. - noSeparator := strings.Join(strings.Split(filepath.ToSlash(k), "/"), "") - f, err := os.CreateTemp(dir, fmt.Sprintf("*-%s", noSeparator)) - if err != nil { - return "", func() {}, err - } - if _, err := f.Write(v); err != nil { - return "", func() {}, err - } - if err := f.Close(); err != nil { - return "", func() {}, err - } - overlays[k] = f.Name() - } - b, err := json.Marshal(OverlayJSON{Replace: overlays}) - if err != nil { - return "", func() {}, err - } - // Write out the overlay file that contains the filepath mappings. - filename = filepath.Join(dir, "overlay.json") - if err := os.WriteFile(filename, b, 0665); err != nil { - return "", func() {}, err - } - return filename, cleanup, nil -} - func containsGoFile(s []string) bool { for _, f := range s { if strings.HasSuffix(f, ".go") { @@ -1179,3 +1023,44 @@ func cmdDebugStr(cmd *exec.Cmd) string { } return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " ")) } + +// getSizesForArgs queries 'go list' for the appropriate +// Compiler and GOARCH arguments to pass to [types.SizesFor]. +func getSizesForArgs(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (string, string, error) { + inv.Verb = "list" + inv.Args = []string{"-f", "{{context.GOARCH}} {{context.Compiler}}", "--", "unsafe"} + stdout, stderr, friendlyErr, rawErr := gocmdRunner.RunRaw(ctx, inv) + var goarch, compiler string + if rawErr != nil { + rawErrMsg := rawErr.Error() + if strings.Contains(rawErrMsg, "cannot find main module") || + strings.Contains(rawErrMsg, "go.mod file not found") { + // User's running outside of a module. + // All bets are off. Get GOARCH and guess compiler is gc. + // TODO(matloob): Is this a problem in practice? + inv.Verb = "env" + inv.Args = []string{"GOARCH"} + envout, enverr := gocmdRunner.Run(ctx, inv) + if enverr != nil { + return "", "", enverr + } + goarch = strings.TrimSpace(envout.String()) + compiler = "gc" + } else if friendlyErr != nil { + return "", "", friendlyErr + } else { + // This should be unreachable, but be defensive + // in case RunRaw's error results are inconsistent. + return "", "", rawErr + } + } else { + fields := strings.Fields(stdout.String()) + if len(fields) < 2 { + return "", "", fmt.Errorf("could not parse GOARCH and Go compiler in format \" \":\nstdout: <<%s>>\nstderr: <<%s>>", + stdout.String(), stderr.String()) + } + goarch = fields[0] + compiler = fields[1] + } + return compiler, goarch, nil +} diff --git a/tools/vendor/golang.org/x/tools/go/packages/golist_overlay.go b/tools/vendor/golang.org/x/tools/go/packages/golist_overlay.go index 9576b472f..d823c474a 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/golist_overlay.go +++ b/tools/vendor/golang.org/x/tools/go/packages/golist_overlay.go @@ -6,314 +6,11 @@ package packages import ( "encoding/json" - "fmt" - "go/parser" - "go/token" - "os" "path/filepath" - "regexp" - "sort" - "strconv" - "strings" "golang.org/x/tools/internal/gocommand" ) -// processGolistOverlay provides rudimentary support for adding -// files that don't exist on disk to an overlay. The results can be -// sometimes incorrect. -// TODO(matloob): Handle unsupported cases, including the following: -// - determining the correct package to add given a new import path -func (state *golistState) processGolistOverlay(response *responseDeduper) (modifiedPkgs, needPkgs []string, err error) { - havePkgs := make(map[string]string) // importPath -> non-test package ID - needPkgsSet := make(map[string]bool) - modifiedPkgsSet := make(map[string]bool) - - pkgOfDir := make(map[string][]*Package) - for _, pkg := range response.dr.Packages { - // This is an approximation of import path to id. This can be - // wrong for tests, vendored packages, and a number of other cases. - havePkgs[pkg.PkgPath] = pkg.ID - dir, err := commonDir(pkg.GoFiles) - if err != nil { - return nil, nil, err - } - if dir != "" { - pkgOfDir[dir] = append(pkgOfDir[dir], pkg) - } - } - - // If no new imports are added, it is safe to avoid loading any needPkgs. - // Otherwise, it's hard to tell which package is actually being loaded - // (due to vendoring) and whether any modified package will show up - // in the transitive set of dependencies (because new imports are added, - // potentially modifying the transitive set of dependencies). - var overlayAddsImports bool - - // If both a package and its test package are created by the overlay, we - // need the real package first. Process all non-test files before test - // files, and make the whole process deterministic while we're at it. - var overlayFiles []string - for opath := range state.cfg.Overlay { - overlayFiles = append(overlayFiles, opath) - } - sort.Slice(overlayFiles, func(i, j int) bool { - iTest := strings.HasSuffix(overlayFiles[i], "_test.go") - jTest := strings.HasSuffix(overlayFiles[j], "_test.go") - if iTest != jTest { - return !iTest // non-tests are before tests. - } - return overlayFiles[i] < overlayFiles[j] - }) - for _, opath := range overlayFiles { - contents := state.cfg.Overlay[opath] - base := filepath.Base(opath) - dir := filepath.Dir(opath) - var pkg *Package // if opath belongs to both a package and its test variant, this will be the test variant - var testVariantOf *Package // if opath is a test file, this is the package it is testing - var fileExists bool - isTestFile := strings.HasSuffix(opath, "_test.go") - pkgName, ok := extractPackageName(opath, contents) - if !ok { - // Don't bother adding a file that doesn't even have a parsable package statement - // to the overlay. - continue - } - // If all the overlay files belong to a different package, change the - // package name to that package. - maybeFixPackageName(pkgName, isTestFile, pkgOfDir[dir]) - nextPackage: - for _, p := range response.dr.Packages { - if pkgName != p.Name && p.ID != "command-line-arguments" { - continue - } - for _, f := range p.GoFiles { - if !sameFile(filepath.Dir(f), dir) { - continue - } - // Make sure to capture information on the package's test variant, if needed. - if isTestFile && !hasTestFiles(p) { - // TODO(matloob): Are there packages other than the 'production' variant - // of a package that this can match? This shouldn't match the test main package - // because the file is generated in another directory. - testVariantOf = p - continue nextPackage - } else if !isTestFile && hasTestFiles(p) { - // We're examining a test variant, but the overlaid file is - // a non-test file. Because the overlay implementation - // (currently) only adds a file to one package, skip this - // package, so that we can add the file to the production - // variant of the package. (https://golang.org/issue/36857 - // tracks handling overlays on both the production and test - // variant of a package). - continue nextPackage - } - if pkg != nil && p != pkg && pkg.PkgPath == p.PkgPath { - // We have already seen the production version of the - // for which p is a test variant. - if hasTestFiles(p) { - testVariantOf = pkg - } - } - pkg = p - if filepath.Base(f) == base { - fileExists = true - } - } - } - // The overlay could have included an entirely new package or an - // ad-hoc package. An ad-hoc package is one that we have manually - // constructed from inadequate `go list` results for a file= query. - // It will have the ID command-line-arguments. - if pkg == nil || pkg.ID == "command-line-arguments" { - // Try to find the module or gopath dir the file is contained in. - // Then for modules, add the module opath to the beginning. - pkgPath, ok, err := state.getPkgPath(dir) - if err != nil { - return nil, nil, err - } - if !ok { - break - } - var forTest string // only set for x tests - isXTest := strings.HasSuffix(pkgName, "_test") - if isXTest { - forTest = pkgPath - pkgPath += "_test" - } - id := pkgPath - if isTestFile { - if isXTest { - id = fmt.Sprintf("%s [%s.test]", pkgPath, forTest) - } else { - id = fmt.Sprintf("%s [%s.test]", pkgPath, pkgPath) - } - } - if pkg != nil { - // TODO(rstambler): We should change the package's path and ID - // here. The only issue is that this messes with the roots. - } else { - // Try to reclaim a package with the same ID, if it exists in the response. - for _, p := range response.dr.Packages { - if reclaimPackage(p, id, opath, contents) { - pkg = p - break - } - } - // Otherwise, create a new package. - if pkg == nil { - pkg = &Package{ - PkgPath: pkgPath, - ID: id, - Name: pkgName, - Imports: make(map[string]*Package), - } - response.addPackage(pkg) - havePkgs[pkg.PkgPath] = id - // Add the production package's sources for a test variant. - if isTestFile && !isXTest && testVariantOf != nil { - pkg.GoFiles = append(pkg.GoFiles, testVariantOf.GoFiles...) - pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, testVariantOf.CompiledGoFiles...) - // Add the package under test and its imports to the test variant. - pkg.forTest = testVariantOf.PkgPath - for k, v := range testVariantOf.Imports { - pkg.Imports[k] = &Package{ID: v.ID} - } - } - if isXTest { - pkg.forTest = forTest - } - } - } - } - if !fileExists { - pkg.GoFiles = append(pkg.GoFiles, opath) - // TODO(matloob): Adding the file to CompiledGoFiles can exhibit the wrong behavior - // if the file will be ignored due to its build tags. - pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, opath) - modifiedPkgsSet[pkg.ID] = true - } - imports, err := extractImports(opath, contents) - if err != nil { - // Let the parser or type checker report errors later. - continue - } - for _, imp := range imports { - // TODO(rstambler): If the package is an x test and the import has - // a test variant, make sure to replace it. - if _, found := pkg.Imports[imp]; found { - continue - } - overlayAddsImports = true - id, ok := havePkgs[imp] - if !ok { - var err error - id, err = state.resolveImport(dir, imp) - if err != nil { - return nil, nil, err - } - } - pkg.Imports[imp] = &Package{ID: id} - // Add dependencies to the non-test variant version of this package as well. - if testVariantOf != nil { - testVariantOf.Imports[imp] = &Package{ID: id} - } - } - } - - // toPkgPath guesses the package path given the id. - toPkgPath := func(sourceDir, id string) (string, error) { - if i := strings.IndexByte(id, ' '); i >= 0 { - return state.resolveImport(sourceDir, id[:i]) - } - return state.resolveImport(sourceDir, id) - } - - // Now that new packages have been created, do another pass to determine - // the new set of missing packages. - for _, pkg := range response.dr.Packages { - for _, imp := range pkg.Imports { - if len(pkg.GoFiles) == 0 { - return nil, nil, fmt.Errorf("cannot resolve imports for package %q with no Go files", pkg.PkgPath) - } - pkgPath, err := toPkgPath(filepath.Dir(pkg.GoFiles[0]), imp.ID) - if err != nil { - return nil, nil, err - } - if _, ok := havePkgs[pkgPath]; !ok { - needPkgsSet[pkgPath] = true - } - } - } - - if overlayAddsImports { - needPkgs = make([]string, 0, len(needPkgsSet)) - for pkg := range needPkgsSet { - needPkgs = append(needPkgs, pkg) - } - } - modifiedPkgs = make([]string, 0, len(modifiedPkgsSet)) - for pkg := range modifiedPkgsSet { - modifiedPkgs = append(modifiedPkgs, pkg) - } - return modifiedPkgs, needPkgs, err -} - -// resolveImport finds the ID of a package given its import path. -// In particular, it will find the right vendored copy when in GOPATH mode. -func (state *golistState) resolveImport(sourceDir, importPath string) (string, error) { - env, err := state.getEnv() - if err != nil { - return "", err - } - if env["GOMOD"] != "" { - return importPath, nil - } - - searchDir := sourceDir - for { - vendorDir := filepath.Join(searchDir, "vendor") - exists, ok := state.vendorDirs[vendorDir] - if !ok { - info, err := os.Stat(vendorDir) - exists = err == nil && info.IsDir() - state.vendorDirs[vendorDir] = exists - } - - if exists { - vendoredPath := filepath.Join(vendorDir, importPath) - if info, err := os.Stat(vendoredPath); err == nil && info.IsDir() { - // We should probably check for .go files here, but shame on anyone who fools us. - path, ok, err := state.getPkgPath(vendoredPath) - if err != nil { - return "", err - } - if ok { - return path, nil - } - } - } - - // We know we've hit the top of the filesystem when we Dir / and get /, - // or C:\ and get C:\, etc. - next := filepath.Dir(searchDir) - if next == searchDir { - break - } - searchDir = next - } - return importPath, nil -} - -func hasTestFiles(p *Package) bool { - for _, f := range p.GoFiles { - if strings.HasSuffix(f, "_test.go") { - return true - } - } - return false -} - // determineRootDirs returns a mapping from absolute directories that could // contain code to their corresponding import path prefixes. func (state *golistState) determineRootDirs() (map[string]string, error) { @@ -384,192 +81,3 @@ func (state *golistState) determineRootDirsGOPATH() (map[string]string, error) { } return m, nil } - -func extractImports(filename string, contents []byte) ([]string, error) { - f, err := parser.ParseFile(token.NewFileSet(), filename, contents, parser.ImportsOnly) // TODO(matloob): reuse fileset? - if err != nil { - return nil, err - } - var res []string - for _, imp := range f.Imports { - quotedPath := imp.Path.Value - path, err := strconv.Unquote(quotedPath) - if err != nil { - return nil, err - } - res = append(res, path) - } - return res, nil -} - -// reclaimPackage attempts to reuse a package that failed to load in an overlay. -// -// If the package has errors and has no Name, GoFiles, or Imports, -// then it's possible that it doesn't yet exist on disk. -func reclaimPackage(pkg *Package, id string, filename string, contents []byte) bool { - // TODO(rstambler): Check the message of the actual error? - // It differs between $GOPATH and module mode. - if pkg.ID != id { - return false - } - if len(pkg.Errors) != 1 { - return false - } - if pkg.Name != "" || pkg.ExportFile != "" { - return false - } - if len(pkg.GoFiles) > 0 || len(pkg.CompiledGoFiles) > 0 || len(pkg.OtherFiles) > 0 { - return false - } - if len(pkg.Imports) > 0 { - return false - } - pkgName, ok := extractPackageName(filename, contents) - if !ok { - return false - } - pkg.Name = pkgName - pkg.Errors = nil - return true -} - -func extractPackageName(filename string, contents []byte) (string, bool) { - // TODO(rstambler): Check the message of the actual error? - // It differs between $GOPATH and module mode. - f, err := parser.ParseFile(token.NewFileSet(), filename, contents, parser.PackageClauseOnly) // TODO(matloob): reuse fileset? - if err != nil { - return "", false - } - return f.Name.Name, true -} - -// commonDir returns the directory that all files are in, "" if files is empty, -// or an error if they aren't in the same directory. -func commonDir(files []string) (string, error) { - seen := make(map[string]bool) - for _, f := range files { - seen[filepath.Dir(f)] = true - } - if len(seen) > 1 { - return "", fmt.Errorf("files (%v) are in more than one directory: %v", files, seen) - } - for k := range seen { - // seen has only one element; return it. - return k, nil - } - return "", nil // no files -} - -// It is possible that the files in the disk directory dir have a different package -// name from newName, which is deduced from the overlays. If they all have a different -// package name, and they all have the same package name, then that name becomes -// the package name. -// It returns true if it changes the package name, false otherwise. -func maybeFixPackageName(newName string, isTestFile bool, pkgsOfDir []*Package) { - names := make(map[string]int) - for _, p := range pkgsOfDir { - names[p.Name]++ - } - if len(names) != 1 { - // some files are in different packages - return - } - var oldName string - for k := range names { - oldName = k - } - if newName == oldName { - return - } - // We might have a case where all of the package names in the directory are - // the same, but the overlay file is for an x test, which belongs to its - // own package. If the x test does not yet exist on disk, we may not yet - // have its package name on disk, but we should not rename the packages. - // - // We use a heuristic to determine if this file belongs to an x test: - // The test file should have a package name whose package name has a _test - // suffix or looks like "newName_test". - maybeXTest := strings.HasPrefix(oldName+"_test", newName) || strings.HasSuffix(newName, "_test") - if isTestFile && maybeXTest { - return - } - for _, p := range pkgsOfDir { - p.Name = newName - } -} - -// This function is copy-pasted from -// https://github.com/golang/go/blob/9706f510a5e2754595d716bd64be8375997311fb/src/cmd/go/internal/search/search.go#L360. -// It should be deleted when we remove support for overlays from go/packages. -// -// NOTE: This does not handle any ./... or ./ style queries, as this function -// doesn't know the working directory. -// -// matchPattern(pattern)(name) reports whether -// name matches pattern. Pattern is a limited glob -// pattern in which '...' means 'any string' and there -// is no other special syntax. -// Unfortunately, there are two special cases. Quoting "go help packages": -// -// First, /... at the end of the pattern can match an empty string, -// so that net/... matches both net and packages in its subdirectories, like net/http. -// Second, any slash-separated pattern element containing a wildcard never -// participates in a match of the "vendor" element in the path of a vendored -// package, so that ./... does not match packages in subdirectories of -// ./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do. -// Note, however, that a directory named vendor that itself contains code -// is not a vendored package: cmd/vendor would be a command named vendor, -// and the pattern cmd/... matches it. -func matchPattern(pattern string) func(name string) bool { - // Convert pattern to regular expression. - // The strategy for the trailing /... is to nest it in an explicit ? expression. - // The strategy for the vendor exclusion is to change the unmatchable - // vendor strings to a disallowed code point (vendorChar) and to use - // "(anything but that codepoint)*" as the implementation of the ... wildcard. - // This is a bit complicated but the obvious alternative, - // namely a hand-written search like in most shell glob matchers, - // is too easy to make accidentally exponential. - // Using package regexp guarantees linear-time matching. - - const vendorChar = "\x00" - - if strings.Contains(pattern, vendorChar) { - return func(name string) bool { return false } - } - - re := regexp.QuoteMeta(pattern) - re = replaceVendor(re, vendorChar) - switch { - case strings.HasSuffix(re, `/`+vendorChar+`/\.\.\.`): - re = strings.TrimSuffix(re, `/`+vendorChar+`/\.\.\.`) + `(/vendor|/` + vendorChar + `/\.\.\.)` - case re == vendorChar+`/\.\.\.`: - re = `(/vendor|/` + vendorChar + `/\.\.\.)` - case strings.HasSuffix(re, `/\.\.\.`): - re = strings.TrimSuffix(re, `/\.\.\.`) + `(/\.\.\.)?` - } - re = strings.ReplaceAll(re, `\.\.\.`, `[^`+vendorChar+`]*`) - - reg := regexp.MustCompile(`^` + re + `$`) - - return func(name string) bool { - if strings.Contains(name, vendorChar) { - return false - } - return reg.MatchString(replaceVendor(name, vendorChar)) - } -} - -// replaceVendor returns the result of replacing -// non-trailing vendor path elements in x with repl. -func replaceVendor(x, repl string) string { - if !strings.Contains(x, "vendor") { - return x - } - elem := strings.Split(x, "/") - for i := 0; i < len(elem)-1; i++ { - if elem[i] == "vendor" { - elem[i] = repl - } - } - return strings.Join(elem, "/") -} diff --git a/tools/vendor/golang.org/x/tools/go/packages/packages.go b/tools/vendor/golang.org/x/tools/go/packages/packages.go index ece0e7c60..0b6bfaff8 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/packages.go +++ b/tools/vendor/golang.org/x/tools/go/packages/packages.go @@ -9,6 +9,7 @@ package packages import ( "context" "encoding/json" + "errors" "fmt" "go/ast" "go/parser" @@ -24,20 +25,31 @@ import ( "sync" "time" + "golang.org/x/sync/errgroup" + "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/packagesinternal" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/typesinternal" + "golang.org/x/tools/internal/versions" ) // A LoadMode controls the amount of detail to return when loading. // The bits below can be combined to specify which fields should be // filled in the result packages. +// // The zero value is a special case, equivalent to combining // the NeedName, NeedFiles, and NeedCompiledGoFiles bits. +// // ID and Errors (if present) will always be filled. -// Load may return more information than requested. +// [Load] may return more information than requested. +// +// Unfortunately there are a number of open bugs related to +// interactions among the LoadMode bits: +// - https://github.com/golang/go/issues/56633 +// - https://github.com/golang/go/issues/56677 +// - https://github.com/golang/go/issues/58726 +// - https://github.com/golang/go/issues/63517 type LoadMode int const ( @@ -63,7 +75,7 @@ const ( // NeedTypes adds Types, Fset, and IllTyped. NeedTypes - // NeedSyntax adds Syntax. + // NeedSyntax adds Syntax and Fset. NeedSyntax // NeedTypesInfo adds TypesInfo. @@ -120,15 +132,21 @@ const ( // A Config specifies details about how packages should be loaded. // The zero value is a valid configuration. +// // Calls to Load do not modify this struct. +// +// TODO(adonovan): #67702: this is currently false: in fact, +// calls to [Load] do not modify the public fields of this struct, but +// may modify hidden fields, so concurrent calls to [Load] must not +// use the same Config. But perhaps we should reestablish the +// documented invariant. type Config struct { // Mode controls the level of information returned for each package. Mode LoadMode // Context specifies the context for the load operation. - // If the context is cancelled, the loader may stop early - // and return an ErrCancelled error. - // If Context is nil, the load cannot be cancelled. + // Cancelling the context may cause [Load] to abort and + // return an error. Context context.Context // Logf is the logger for the config. @@ -197,50 +215,23 @@ type Config struct { // setting Tests may have no effect. Tests bool - // Overlay provides a mapping of absolute file paths to file contents. - // If the file with the given path already exists, the parser will use the - // alternative file contents provided by the map. + // Overlay is a mapping from absolute file paths to file contents. // - // Overlays provide incomplete support for when a given file doesn't - // already exist on disk. See the package doc above for more details. + // For each map entry, [Load] uses the alternative file + // contents provided by the overlay mapping instead of reading + // from the file system. This mechanism can be used to enable + // editor-integrated tools to correctly analyze the contents + // of modified but unsaved buffers, for example. + // + // The overlay mapping is passed to the build system's driver + // (see "The driver protocol") so that it too can report + // consistent package metadata about unsaved files. However, + // drivers may vary in their level of support for overlays. Overlay map[string][]byte -} -// driver is the type for functions that query the build system for the -// packages named by the patterns. -type driver func(cfg *Config, patterns ...string) (*driverResponse, error) - -// driverResponse contains the results for a driver query. -type driverResponse struct { - // NotHandled is returned if the request can't be handled by the current - // driver. If an external driver returns a response with NotHandled, the - // rest of the driverResponse is ignored, and go/packages will fallback - // to the next driver. If go/packages is extended in the future to support - // lists of multiple drivers, go/packages will fall back to the next driver. - NotHandled bool - - // Compiler and Arch are the arguments pass of types.SizesFor - // to get a types.Sizes to use when type checking. - Compiler string - Arch string - - // Roots is the set of package IDs that make up the root packages. - // We have to encode this separately because when we encode a single package - // we cannot know if it is one of the roots as that requires knowledge of the - // graph it is part of. - Roots []string `json:",omitempty"` - - // Packages is the full set of packages in the graph. - // The packages are not connected into a graph. - // The Imports if populated will be stubs that only have their ID set. - // Imports will be connected and then type and syntax information added in a - // later pass (see refine). - Packages []*Package - - // GoVersion is the minor version number used by the driver - // (e.g. the go command on the PATH) when selecting .go files. - // Zero means unknown. - GoVersion int + // goListOverlayFile is the JSON file that encodes the Overlay + // mapping, used by 'go list -overlay=...' + goListOverlayFile string } // Load loads and returns the Go packages named by the given patterns. @@ -248,8 +239,22 @@ type driverResponse struct { // Config specifies loading options; // nil behaves the same as an empty Config. // -// Load returns an error if any of the patterns was invalid -// as defined by the underlying build system. +// The [Config.Mode] field is a set of bits that determine what kinds +// of information should be computed and returned. Modes that require +// more information tend to be slower. See [LoadMode] for details +// and important caveats. Its zero value is equivalent to +// NeedName | NeedFiles | NeedCompiledGoFiles. +// +// Each call to Load returns a new set of [Package] instances. +// The Packages and their Imports form a directed acyclic graph. +// +// If the [NeedTypes] mode flag was set, each call to Load uses a new +// [types.Importer], so [types.Object] and [types.Type] values from +// different calls to Load must not be mixed as they will have +// inconsistent notions of type identity. +// +// If any of the patterns was invalid as defined by the +// underlying build system, Load returns an error. // It may return an empty list of packages without an error, // for instance for an empty expansion of a valid wildcard. // Errors associated with a particular package are recorded in the @@ -258,34 +263,162 @@ type driverResponse struct { // proceeding with further analysis. The PrintErrors function is // provided for convenient display of all errors. func Load(cfg *Config, patterns ...string) ([]*Package, error) { - l := newLoader(cfg) - response, err := defaultDriver(&l.Config, patterns...) + ld := newLoader(cfg) + response, external, err := defaultDriver(&ld.Config, patterns...) if err != nil { return nil, err } - l.sizes = types.SizesFor(response.Compiler, response.Arch) - return l.refine(response) + + ld.sizes = types.SizesFor(response.Compiler, response.Arch) + if ld.sizes == nil && ld.Config.Mode&(NeedTypes|NeedTypesSizes|NeedTypesInfo) != 0 { + // Type size information is needed but unavailable. + if external { + // An external driver may fail to populate the Compiler/GOARCH fields, + // especially since they are relatively new (see #63700). + // Provide a sensible fallback in this case. + ld.sizes = types.SizesFor("gc", runtime.GOARCH) + if ld.sizes == nil { // gccgo-only arch + ld.sizes = types.SizesFor("gc", "amd64") + } + } else { + // Go list should never fail to deliver accurate size information. + // Reject the whole Load since the error is the same for every package. + return nil, fmt.Errorf("can't determine type sizes for compiler %q on GOARCH %q", + response.Compiler, response.Arch) + } + } + + return ld.refine(response) } // defaultDriver is a driver that implements go/packages' fallback behavior. // It will try to request to an external driver, if one exists. If there's // no external driver, or the driver returns a response with NotHandled set, // defaultDriver will fall back to the go list driver. -func defaultDriver(cfg *Config, patterns ...string) (*driverResponse, error) { - driver := findExternalDriver(cfg) - if driver == nil { - driver = goListDriver +// The boolean result indicates that an external driver handled the request. +func defaultDriver(cfg *Config, patterns ...string) (*DriverResponse, bool, error) { + const ( + // windowsArgMax specifies the maximum command line length for + // the Windows' CreateProcess function. + windowsArgMax = 32767 + // maxEnvSize is a very rough estimation of the maximum environment + // size of a user. + maxEnvSize = 16384 + // safeArgMax specifies the maximum safe command line length to use + // by the underlying driver excl. the environment. We choose the Windows' + // ARG_MAX as the starting point because it's one of the lowest ARG_MAX + // constants out of the different supported platforms, + // e.g., https://www.in-ulm.de/~mascheck/various/argmax/#results. + safeArgMax = windowsArgMax - maxEnvSize + ) + chunks, err := splitIntoChunks(patterns, safeArgMax) + if err != nil { + return nil, false, err + } + + if driver := findExternalDriver(cfg); driver != nil { + response, err := callDriverOnChunks(driver, cfg, chunks) + if err != nil { + return nil, false, err + } else if !response.NotHandled { + return response, true, nil + } + // (fall through) } - response, err := driver(cfg, patterns...) + + // go list fallback + // + // Write overlays once, as there are many calls + // to 'go list' (one per chunk plus others too). + overlay, cleanupOverlay, err := gocommand.WriteOverlays(cfg.Overlay) + if err != nil { + return nil, false, err + } + defer cleanupOverlay() + cfg.goListOverlayFile = overlay + + response, err := callDriverOnChunks(goListDriver, cfg, chunks) if err != nil { - return response, err - } else if response.NotHandled { - return goListDriver(cfg, patterns...) + return nil, false, err } - return response, nil + return response, false, err +} + +// splitIntoChunks chunks the slice so that the total number of characters +// in a chunk is no longer than argMax. +func splitIntoChunks(patterns []string, argMax int) ([][]string, error) { + if argMax <= 0 { + return nil, errors.New("failed to split patterns into chunks, negative safe argMax value") + } + var chunks [][]string + charsInChunk := 0 + nextChunkStart := 0 + for i, v := range patterns { + vChars := len(v) + if vChars > argMax { + // a single pattern is longer than the maximum safe ARG_MAX, hardly should happen + return nil, errors.New("failed to split patterns into chunks, a pattern is too long") + } + charsInChunk += vChars + 1 // +1 is for a whitespace between patterns that has to be counted too + if charsInChunk > argMax { + chunks = append(chunks, patterns[nextChunkStart:i]) + nextChunkStart = i + charsInChunk = vChars + } + } + // add the last chunk + if nextChunkStart < len(patterns) { + chunks = append(chunks, patterns[nextChunkStart:]) + } + return chunks, nil +} + +func callDriverOnChunks(driver driver, cfg *Config, chunks [][]string) (*DriverResponse, error) { + if len(chunks) == 0 { + return driver(cfg) + } + responses := make([]*DriverResponse, len(chunks)) + errNotHandled := errors.New("driver returned NotHandled") + var g errgroup.Group + for i, chunk := range chunks { + i := i + chunk := chunk + g.Go(func() (err error) { + responses[i], err = driver(cfg, chunk...) + if responses[i] != nil && responses[i].NotHandled { + err = errNotHandled + } + return err + }) + } + if err := g.Wait(); err != nil { + if errors.Is(err, errNotHandled) { + return &DriverResponse{NotHandled: true}, nil + } + return nil, err + } + return mergeResponses(responses...), nil +} + +func mergeResponses(responses ...*DriverResponse) *DriverResponse { + if len(responses) == 0 { + return nil + } + response := newDeduper() + response.dr.NotHandled = false + response.dr.Compiler = responses[0].Compiler + response.dr.Arch = responses[0].Arch + response.dr.GoVersion = responses[0].GoVersion + for _, v := range responses { + response.addAll(v) + } + return response.dr } // A Package describes a loaded Go package. +// +// It also defines part of the JSON schema of [DriverResponse]. +// See the package documentation for an overview. type Package struct { // ID is a unique identifier for a package, // in a syntax provided by the underlying build system. @@ -344,19 +477,30 @@ type Package struct { // to corresponding loaded Packages. Imports map[string]*Package + // Module is the module information for the package if it exists. + // + // Note: it may be missing for std and cmd; see Go issue #65816. + Module *Module + + // -- The following fields are not part of the driver JSON schema. -- + // Types provides type information for the package. // The NeedTypes LoadMode bit sets this field for packages matching the // patterns; type information for dependencies may be missing or incomplete, // unless NeedDeps and NeedImports are also set. - Types *types.Package + // + // Each call to [Load] returns a consistent set of type + // symbols, as defined by the comment at [types.Identical]. + // Avoid mixing type information from two or more calls to [Load]. + Types *types.Package `json:"-"` // Fset provides position information for Types, TypesInfo, and Syntax. // It is set only when Types is set. - Fset *token.FileSet + Fset *token.FileSet `json:"-"` // IllTyped indicates whether the package or any dependency contains errors. // It is set only when Types is set. - IllTyped bool + IllTyped bool `json:"-"` // Syntax is the package's syntax trees, for the files listed in CompiledGoFiles. // @@ -366,26 +510,28 @@ type Package struct { // // Syntax is kept in the same order as CompiledGoFiles, with the caveat that nils are // removed. If parsing returned nil, Syntax may be shorter than CompiledGoFiles. - Syntax []*ast.File + Syntax []*ast.File `json:"-"` // TypesInfo provides type information about the package's syntax trees. // It is set only when Syntax is set. - TypesInfo *types.Info + TypesInfo *types.Info `json:"-"` // TypesSizes provides the effective size function for types in TypesInfo. - TypesSizes types.Sizes + TypesSizes types.Sizes `json:"-"` + + // -- internal -- // forTest is the package under test, if any. forTest string // depsErrors is the DepsErrors field from the go list response, if any. depsErrors []*packagesinternal.PackageError - - // module is the module information for the package if it exists. - Module *Module } // Module provides module information for a package. +// +// It also defines part of the JSON schema of [DriverResponse]. +// See the package documentation for an overview. type Module struct { Path string // module path Version string // module version @@ -411,12 +557,6 @@ func init() { packagesinternal.GetDepsErrors = func(p interface{}) []*packagesinternal.PackageError { return p.(*Package).depsErrors } - packagesinternal.GetGoCmdRunner = func(config interface{}) *gocommand.Runner { - return config.(*Config).gocmdRunner - } - packagesinternal.SetGoCmdRunner = func(config interface{}, runner *gocommand.Runner) { - config.(*Config).gocmdRunner = runner - } packagesinternal.SetModFile = func(config interface{}, value string) { config.(*Config).modFile = value } @@ -524,6 +664,7 @@ func (p *Package) UnmarshalJSON(b []byte) error { OtherFiles: flat.OtherFiles, EmbedFiles: flat.EmbedFiles, EmbedPatterns: flat.EmbedPatterns, + IgnoredFiles: flat.IgnoredFiles, ExportFile: flat.ExportFile, } if len(flat.Imports) > 0 { @@ -553,7 +694,7 @@ type loaderPackage struct { type loader struct { pkgs map[string]*loaderPackage Config - sizes types.Sizes + sizes types.Sizes // non-nil if needed by mode parseCache map[string]*parseValue parseCacheMu sync.Mutex exportMu sync.Mutex // enforces mutual exclusion of exportdata operations @@ -633,7 +774,7 @@ func newLoader(cfg *Config) *loader { // refine connects the supplied packages into a graph and then adds type // and syntax information as requested by the LoadMode. -func (ld *loader) refine(response *driverResponse) ([]*Package, error) { +func (ld *loader) refine(response *DriverResponse) ([]*Package, error) { roots := response.Roots rootMap := make(map[string]int, len(roots)) for i, root := range roots { @@ -678,39 +819,38 @@ func (ld *loader) refine(response *driverResponse) ([]*Package, error) { } } - // Materialize the import graph. - - const ( - white = 0 // new - grey = 1 // in progress - black = 2 // complete - ) - - // visit traverses the import graph, depth-first, - // and materializes the graph as Packages.Imports. - // - // Valid imports are saved in the Packages.Import map. - // Invalid imports (cycles and missing nodes) are saved in the importErrors map. - // Thus, even in the presence of both kinds of errors, the Import graph remains a DAG. - // - // visit returns whether the package needs src or has a transitive - // dependency on a package that does. These are the only packages - // for which we load source code. - var stack []*loaderPackage - var visit func(lpkg *loaderPackage) bool - var srcPkgs []*loaderPackage - visit = func(lpkg *loaderPackage) bool { - switch lpkg.color { - case black: - return lpkg.needsrc - case grey: - panic("internal error: grey node") - } - lpkg.color = grey - stack = append(stack, lpkg) // push - stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports - // If NeedImports isn't set, the imports fields will all be zeroed out. - if ld.Mode&NeedImports != 0 { + if ld.Mode&NeedImports != 0 { + // Materialize the import graph. + + const ( + white = 0 // new + grey = 1 // in progress + black = 2 // complete + ) + + // visit traverses the import graph, depth-first, + // and materializes the graph as Packages.Imports. + // + // Valid imports are saved in the Packages.Import map. + // Invalid imports (cycles and missing nodes) are saved in the importErrors map. + // Thus, even in the presence of both kinds of errors, + // the Import graph remains a DAG. + // + // visit returns whether the package needs src or has a transitive + // dependency on a package that does. These are the only packages + // for which we load source code. + var stack []*loaderPackage + var visit func(lpkg *loaderPackage) bool + visit = func(lpkg *loaderPackage) bool { + switch lpkg.color { + case black: + return lpkg.needsrc + case grey: + panic("internal error: grey node") + } + lpkg.color = grey + stack = append(stack, lpkg) // push + stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports lpkg.Imports = make(map[string]*Package, len(stubs)) for importPath, ipkg := range stubs { var importErr error @@ -734,40 +874,39 @@ func (ld *loader) refine(response *driverResponse) ([]*Package, error) { } lpkg.Imports[importPath] = imp.Package } - } - if lpkg.needsrc { - srcPkgs = append(srcPkgs, lpkg) - } - if ld.Mode&NeedTypesSizes != 0 { - lpkg.TypesSizes = ld.sizes - } - stack = stack[:len(stack)-1] // pop - lpkg.color = black - return lpkg.needsrc - } + // Complete type information is required for the + // immediate dependencies of each source package. + if lpkg.needsrc && ld.Mode&NeedTypes != 0 { + for _, ipkg := range lpkg.Imports { + ld.pkgs[ipkg.ID].needtypes = true + } + } - if ld.Mode&NeedImports == 0 { - // We do this to drop the stub import packages that we are not even going to try to resolve. - for _, lpkg := range initial { - lpkg.Imports = nil + // NeedTypeSizes causes TypeSizes to be set even + // on packages for which types aren't needed. + if ld.Mode&NeedTypesSizes != 0 { + lpkg.TypesSizes = ld.sizes + } + stack = stack[:len(stack)-1] // pop + lpkg.color = black + + return lpkg.needsrc } - } else { + // For each initial package, create its import DAG. for _, lpkg := range initial { visit(lpkg) } - } - if ld.Mode&NeedImports != 0 && ld.Mode&NeedTypes != 0 { - for _, lpkg := range srcPkgs { - // Complete type information is required for the - // immediate dependencies of each source package. - for _, ipkg := range lpkg.Imports { - imp := ld.pkgs[ipkg.ID] - imp.needtypes = true - } + + } else { + // !NeedImports: drop the stub (ID-only) import packages + // that we are not even going to try to resolve. + for _, lpkg := range initial { + lpkg.Imports = nil } } + // Load type data and syntax if needed, starting at // the initial packages (roots of the import DAG). if ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 { @@ -782,6 +921,12 @@ func (ld *loader) refine(response *driverResponse) ([]*Package, error) { wg.Wait() } + // If the context is done, return its error and + // throw out [likely] incomplete packages. + if err := ld.Context.Err(); err != nil { + return nil, err + } + result := make([]*Package, len(initial)) for i, lpkg := range initial { result[i] = lpkg.Package @@ -815,12 +960,14 @@ func (ld *loader) refine(response *driverResponse) ([]*Package, error) { } if ld.requestedMode&NeedTypes == 0 { ld.pkgs[i].Types = nil - ld.pkgs[i].Fset = nil ld.pkgs[i].IllTyped = false } if ld.requestedMode&NeedSyntax == 0 { ld.pkgs[i].Syntax = nil } + if ld.requestedMode&NeedTypes == 0 && ld.requestedMode&NeedSyntax == 0 { + ld.pkgs[i].Fset = nil + } if ld.requestedMode&NeedTypesInfo == 0 { ld.pkgs[i].TypesInfo = nil } @@ -877,6 +1024,14 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { lpkg.Types = types.NewPackage(lpkg.PkgPath, lpkg.Name) lpkg.Fset = ld.Fset + // Start shutting down if the context is done and do not load + // source or export data files. + // Packages that import this one will have ld.Context.Err() != nil. + // ld.Context.Err() will be returned later by refine. + if ld.Context.Err() != nil { + return + } + // Subtle: we populate all Types fields with an empty Package // before loading export data so that export data processing // never has to create a types.Package for an indirect dependency, @@ -996,15 +1151,23 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { return } + // Start shutting down if the context is done and do not type check. + // Packages that import this one will have ld.Context.Err() != nil. + // ld.Context.Err() will be returned later by refine. + if ld.Context.Err() != nil { + return + } + lpkg.TypesInfo = &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } - typeparams.InitInstanceInfo(lpkg.TypesInfo) + versions.InitFileVersions(lpkg.TypesInfo) lpkg.TypesSizes = ld.sizes importer := importerFunc(func(path string) (*types.Package, error) { @@ -1042,10 +1205,10 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { IgnoreFuncBodies: ld.Mode&NeedDeps == 0 && !lpkg.initial, Error: appendError, - Sizes: ld.sizes, + Sizes: ld.sizes, // may be nil } if lpkg.Module != nil && lpkg.Module.GoVersion != "" { - typesinternal.SetGoVersion(tc, "go"+lpkg.Module.GoVersion) + tc.GoVersion = "go" + lpkg.Module.GoVersion } if (ld.Mode & typecheckCgo) != 0 { if !typesinternal.SetUsesCgo(tc) { @@ -1056,10 +1219,24 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { return } } - types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax) + typErr := types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax) lpkg.importErrors = nil // no longer needed + // In go/types go1.21 and go1.22, Checker.Files failed fast with a + // a "too new" error, without calling tc.Error and without + // proceeding to type-check the package (#66525). + // We rely on the runtimeVersion error to give the suggested remedy. + if typErr != nil && len(lpkg.Errors) == 0 && len(lpkg.Syntax) > 0 { + if msg := typErr.Error(); strings.HasPrefix(msg, "package requires newer Go version") { + appendError(types.Error{ + Fset: ld.Fset, + Pos: lpkg.Syntax[0].Package, + Msg: msg, + }) + } + } + // If !Cgo, the type-checker uses FakeImportC mode, so // it doesn't invoke the importer for import "C", // nor report an error for the import, @@ -1081,6 +1258,12 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { } } + // If types.Checker.Files had an error that was unreported, + // make sure to report the unknown error so the package is illTyped. + if typErr != nil && len(lpkg.Errors) == 0 { + appendError(typErr) + } + // Record accumulated errors. illTyped := len(lpkg.Errors) > 0 if !illTyped { @@ -1152,11 +1335,6 @@ func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) { parsed := make([]*ast.File, n) errors := make([]error, n) for i, file := range filenames { - if ld.Config.Context.Err() != nil { - parsed[i] = nil - errors[i] = ld.Config.Context.Err() - continue - } wg.Add(1) go func(i int, filename string) { parsed[i], errors[i] = ld.parseFile(filename) @@ -1322,6 +1500,10 @@ func impliedLoadMode(loadMode LoadMode) LoadMode { // All these things require knowing the import graph. loadMode |= NeedImports } + if loadMode&NeedTypes != 0 { + // Types require the GoVersion from Module. + loadMode |= NeedModule + } return loadMode } diff --git a/tools/vendor/golang.org/x/tools/go/packages/visit.go b/tools/vendor/golang.org/x/tools/go/packages/visit.go index a1dcc40b7..df14ffd94 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/visit.go +++ b/tools/vendor/golang.org/x/tools/go/packages/visit.go @@ -49,11 +49,20 @@ func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { // PrintErrors returns the number of errors printed. func PrintErrors(pkgs []*Package) int { var n int + errModules := make(map[*Module]bool) Visit(pkgs, nil, func(pkg *Package) { for _, err := range pkg.Errors { fmt.Fprintln(os.Stderr, err) n++ } + + // Print pkg.Module.Error once if present. + mod := pkg.Module + if mod != nil && mod.Error != nil && !errModules[mod] { + errModules[mod] = true + fmt.Fprintln(os.Stderr, mod.Error.Err) + n++ + } }) return n } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/builder.go b/tools/vendor/golang.org/x/tools/go/ssa/builder.go index 0e49537d0..55943e45d 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/builder.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/builder.go @@ -4,106 +4,73 @@ package ssa -// This file implements the BUILD phase of SSA construction. +// This file defines the builder, which builds SSA-form IR for function bodies. // -// SSA construction has two phases, CREATE and BUILD. In the CREATE phase -// (create.go), all packages are constructed and type-checked and -// definitions of all package members are created, method-sets are -// computed, and wrapper methods are synthesized. -// ssa.Packages are created in arbitrary order. +// SSA construction has two phases, "create" and "build". First, one +// or more packages are created in any order by a sequence of calls to +// CreatePackage, either from syntax or from mere type information. +// Each created package has a complete set of Members (const, var, +// type, func) that can be accessed through methods like +// Program.FuncValue. // -// In the BUILD phase (builder.go), the builder traverses the AST of -// each Go source function and generates SSA instructions for the -// function body. Initializer expressions for package-level variables -// are emitted to the package's init() function in the order specified -// by go/types.Info.InitOrder, then code for each function in the -// package is generated in lexical order. -// The BUILD phases for distinct packages are independent and are -// executed in parallel. +// It is not necessary to call CreatePackage for all dependencies of +// each syntax package, only for its direct imports. (In future +// perhaps even this restriction may be lifted.) // -// TODO(adonovan): indeed, building functions is now embarrassingly parallel. -// Audit for concurrency then benchmark using more goroutines. +// Second, packages created from syntax are built, by one or more +// calls to Package.Build, which may be concurrent; or by a call to +// Program.Build, which builds all packages in parallel. Building +// traverses the type-annotated syntax tree of each function body and +// creates SSA-form IR, a control-flow graph of instructions, +// populating fields such as Function.Body, .Params, and others. // -// State: +// Building may create additional methods, including: +// - wrapper methods (e.g. for embeddding, or implicit &recv) +// - bound method closures (e.g. for use(recv.f)) +// - thunks (e.g. for use(I.f) or use(T.f)) +// - generic instances (e.g. to produce f[int] from f[any]). +// As these methods are created, they are added to the build queue, +// and then processed in turn, until a fixed point is reached, +// Since these methods might belong to packages that were not +// created (by a call to CreatePackage), their Pkg field is unset. // -// The Package's and Program's indices (maps) are populated and -// mutated during the CREATE phase, but during the BUILD phase they -// remain constant. The sole exception is Prog.methodSets and its -// related maps, which are protected by a dedicated mutex. +// Instances of generic functions may be either instantiated (f[int] +// is a copy of f[T] with substitutions) or wrapped (f[int] delegates +// to f[T]), depending on the availability of generic syntax and the +// InstantiateGenerics mode flag. // -// Generic functions declared in a package P can be instantiated from functions -// outside of P. This happens independently of the CREATE and BUILD phase of P. +// Each package has an initializer function named "init" that calls +// the initializer functions of each direct import, computes and +// assigns the initial value of each global variable, and calls each +// source-level function named "init". (These generate SSA functions +// named "init#1", "init#2", etc.) // -// Locks: +// Runtime types // -// Mutexes are currently acquired according to the following order: -// Prog.methodsMu ⊃ canonizer.mu ⊃ printMu -// where x ⊃ y denotes that y can be acquired while x is held -// and x cannot be acquired while y is held. +// Each MakeInterface operation is a conversion from a non-interface +// type to an interface type. The semantics of this operation requires +// a runtime type descriptor, which is the type portion of an +// interface, and the value abstracted by reflect.Type. // -// Synthetics: +// The program accumulates all non-parameterized types that are +// encountered as MakeInterface operands, along with all types that +// may be derived from them using reflection. This set is available as +// Program.RuntimeTypes, and the methods of these types may be +// reachable via interface calls or reflection even if they are never +// referenced from the SSA IR. (In practice, algorithms such as RTA +// that compute reachability from package main perform their own +// tracking of runtime types at a finer grain, so this feature is not +// very useful.) // -// During the BUILD phase new functions can be created and built. These include: -// - wrappers (wrappers, bounds, thunks) -// - generic function instantiations -// These functions do not belong to a specific Pkg (Pkg==nil). Instead the -// Package that led to them being CREATED is obligated to ensure these -// are BUILT during the BUILD phase of the Package. +// Function literals // -// Runtime types: +// Anonymous functions must be built as soon as they are encountered, +// as it may affect locals of the enclosing function, but they are not +// marked 'built' until the end of the outermost enclosing function. +// (Among other things, this causes them to be logged in top-down order.) // -// A concrete type is a type that is fully monomorphized with concrete types, -// i.e. it cannot reach a TypeParam type. -// Some concrete types require full runtime type information. Cases -// include checking whether a type implements an interface or -// interpretation by the reflect package. All such types that may require -// this information will have all of their method sets built and will be added to Prog.methodSets. -// A type T is considered to require runtime type information if it is -// a runtime type and has a non-empty method set and either: -// - T flows into a MakeInterface instructions, -// - T appears in a concrete exported member, or -// - T is a type reachable from a type S that has non-empty method set. -// For any such type T, method sets must be created before the BUILD -// phase of the package is done. -// -// Function literals: -// -// The BUILD phase of a function literal (anonymous function) is tied to the -// BUILD phase of the enclosing parent function. The FreeVars of an anonymous -// function are discovered by building the anonymous function. This in turn -// changes which variables must be bound in a MakeClosure instruction in the -// parent. Anonymous functions also track where they are referred to in their -// parent function. -// -// Happens-before: -// -// The above discussion leads to the following happens-before relation for -// the BUILD and CREATE phases. -// The happens-before relation (with X 0 { targs := fn.subst.types(instanceArgs(fn.info, e)) - callee = fn.Prog.needsInstance(callee, targs, b.created) + callee = callee.instance(targs, b) } return callee } // Local var. - return emitLoad(fn, fn.lookup(obj, false)) // var (address) + return emitLoad(fn, fn.lookup(obj.(*types.Var), false)) // var (address) case *ast.SelectorExpr: sel := fn.selection(e) @@ -821,7 +838,8 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { case types.MethodExpr: // (*T).f or T.f, the method f from the method-set of type T. // The result is a "thunk". - thunk := makeThunk(fn.Prog, sel, b.created) + thunk := createThunk(fn.Prog, sel) + b.enqueue(thunk) return emitConv(fn, thunk, fn.typ(tv.Type)) case types.MethodVal: @@ -829,14 +847,14 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { // The result is a "bound". obj := sel.obj.(*types.Func) rt := fn.typ(recvType(obj)) - _, wantAddr := deref(rt) + wantAddr := isPointer(rt) escaping := true v := b.receiver(fn, e.X, wantAddr, escaping, sel) if types.IsInterface(rt) { // If v may be an interface type I (after instantiating), // we must emit a check that v is non-nil. - if recv, ok := sel.recv.(*typeparams.TypeParam); ok { + if recv, ok := aliases.Unalias(sel.recv).(*types.TypeParam); ok { // Emit a nil check if any possible instantiation of the // type parameter is an interface type. if typeSetOf(recv).Len() > 0 { @@ -856,15 +874,18 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { } else { // non-type param interface // Emit nil check: typeassert v.(I). - emitTypeAssert(fn, v, rt, token.NoPos) + emitTypeAssert(fn, v, rt, e.Sel.Pos()) } } if targs := receiverTypeArgs(obj); len(targs) > 0 { // obj is generic. obj = fn.Prog.canon.instantiateMethod(obj, fn.subst.types(targs), fn.Prog.ctxt) } + bound := createBound(fn.Prog, obj) + b.enqueue(bound) + c := &MakeClosure{ - Fn: makeBound(fn.Prog, obj, b.created), + Fn: bound, Bindings: []Value{v}, } c.setPos(e.Sel.Pos()) @@ -882,7 +903,7 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { panic("unexpected expression-relative selector") - case *typeparams.IndexListExpr: + case *ast.IndexListExpr: // f[X, Y] must be a generic function if !instance(fn.info, e.X) { panic("unexpected expression-could not match index list to instantiation") @@ -957,7 +978,7 @@ func (b *builder) stmtList(fn *Function, list []ast.Stmt) { // escaping is defined as per builder.addr(). func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *selection) Value { var v Value - if _, eptr := deref(fn.typeOf(e)); wantAddr && !sel.indirect && !eptr { + if wantAddr && !sel.indirect && !isPointerCore(fn.typeOf(e)) { v = b.addr(fn, e, escaping).address(fn) } else { v = b.expr(fn, e) @@ -966,7 +987,10 @@ func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, se last := len(sel.index) - 1 // The position of implicit selection is the position of the inducing receiver expression. v = emitImplicitSelections(fn, v, sel.index[:last], e.Pos()) - if _, vptr := deref(v.Type()); !wantAddr && vptr { + if types.IsInterface(v.Type()) { + // When v is an interface, sel.Kind()==MethodValue and v.f is invoked. + // So v is not loaded, even if v has a pointer core type. + } else if !wantAddr && isPointerCore(v.Type()) { v = emitLoad(fn, v) } return v @@ -985,7 +1009,7 @@ func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) { obj := sel.obj.(*types.Func) recv := recvType(obj) - _, wantAddr := deref(recv) + wantAddr := isPointer(recv) escaping := true v := b.receiver(fn, selector.X, wantAddr, escaping, sel) if types.IsInterface(recv) { @@ -994,11 +1018,7 @@ func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) { c.Method = obj } else { // "Call"-mode call. - callee := fn.Prog.originFunc(obj) - if callee.typeparams.Len() > 0 { - callee = fn.Prog.needsInstance(callee, receiverTypeArgs(obj), b.created) - } - c.Value = callee + c.Value = fn.Prog.objectMethod(obj, b) c.Args = append(c.Args, v) } return @@ -1090,9 +1110,8 @@ func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallEx } else { // Replace a suffix of args with a slice containing it. at := types.NewArray(vt, int64(len(varargs))) - a := emitNew(fn, at, token.NoPos) + a := emitNew(fn, at, token.NoPos, "varargs") a.setPos(e.Rparen) - a.Comment = "varargs" for i, arg := range varargs { iaddr := &IndexAddr{ X: a, @@ -1139,7 +1158,7 @@ func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { // 1:1 assignment for i, id := range spec.Names { if !isBlankIdent(id) { - fn.addLocalForIdent(id) + emitLocalVar(fn, identVar(fn, id)) } lval := b.addr(fn, id, false) // non-escaping b.assign(fn, lval, spec.Values[i], true, nil) @@ -1150,7 +1169,7 @@ func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { // Locals are implicitly zero-initialized. for _, id := range spec.Names { if !isBlankIdent(id) { - lhs := fn.addLocalForIdent(id) + lhs := emitLocalVar(fn, identVar(fn, id)) if fn.debugInfo() { emitDebugRef(fn, id, lhs, true) } @@ -1162,7 +1181,7 @@ func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { tuple := b.exprN(fn, spec.Values[0]) for i, id := range spec.Names { if !isBlankIdent(id) { - fn.addLocalForIdent(id) + emitLocalVar(fn, identVar(fn, id)) lhs := b.addr(fn, id, false) // non-escaping lhs.store(fn, emitExtract(fn, tuple, i)) } @@ -1182,8 +1201,8 @@ func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool) { var lval lvalue = blank{} if !isBlankIdent(lhs) { if isDef { - if obj := fn.info.Defs[lhs.(*ast.Ident)]; obj != nil { - fn.addNamedLocal(obj) + if obj, ok := fn.info.Defs[lhs.(*ast.Ident)].(*types.Var); ok { + emitLocalVar(fn, obj) isZero[i] = true } } @@ -1251,12 +1270,12 @@ func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 { // literal has type *T behaves like &T{}. // In that case, addr must hold a T, not a *T. func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero bool, sb *storebuf) { - typ, _ := deref(fn.typeOf(e)) // type with name [may be type param] + typ := typeparams.Deref(fn.typeOf(e)) // retain the named/alias/param type, if any switch t := typeparams.CoreType(typ).(type) { case *types.Struct: if !isZero && len(e.Elts) != t.NumFields() { // memclear - zt, _ := deref(addr.Type()) + zt := typeparams.MustDeref(addr.Type()) sb.store(&address{addr, e.Lbrace, nil}, zeroConst(zt)) isZero = true } @@ -1292,16 +1311,14 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero switch t := t.(type) { case *types.Slice: at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts)) - alloc := emitNew(fn, at, e.Lbrace) - alloc.Comment = "slicelit" - array = alloc + array = emitNew(fn, at, e.Lbrace, "slicelit") case *types.Array: at = t array = addr if !isZero && int64(len(e.Elts)) != at.Len() { // memclear - zt, _ := deref(array.Type()) + zt := typeparams.MustDeref(array.Type()) sb.store(&address{array, e.Lbrace, nil}, zeroConst(zt)) } } @@ -1357,7 +1374,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero // map[*struct{}]bool{&struct{}{}: true} wantAddr := false if _, ok := unparen(e.Key).(*ast.CompositeLit); ok { - _, wantAddr = deref(t.Key()) + wantAddr = isPointerCore(t.Key()) } var key Value @@ -1582,13 +1599,13 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl } func (b *builder) typeCaseBody(fn *Function, cc *ast.CaseClause, x Value, done *BasicBlock) { - if obj := fn.info.Implicits[cc]; obj != nil { + if obj, ok := fn.info.Implicits[cc].(*types.Var); ok { // In a switch y := x.(type), each case clause // implicitly declares a distinct object y. // In a single-type case, y has that type. // In multi-type cases, 'case nil' and default, // y has the same type as the interface operand. - emitStore(fn, fn.addNamedLocal(obj), x, obj.Pos()) + emitStore(fn, emitLocalVar(fn, obj), x, obj.Pos()) } fn.targets = &targets{ tail: fn.targets, @@ -1737,7 +1754,7 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) { case *ast.AssignStmt: // x := <-states[state].Chan if comm.Tok == token.DEFINE { - fn.addLocalForIdent(comm.Lhs[0].(*ast.Ident)) + emitLocalVar(fn, identVar(fn, comm.Lhs[0].(*ast.Ident))) } x := b.addr(fn, comm.Lhs[0], false) // non-escaping v := emitExtract(fn, sel, r) @@ -1748,7 +1765,7 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) { if len(comm.Lhs) == 2 { // x, ok := ... if comm.Tok == token.DEFINE { - fn.addLocalForIdent(comm.Lhs[1].(*ast.Ident)) + emitLocalVar(fn, identVar(fn, comm.Lhs[1].(*ast.Ident))) } ok := b.addr(fn, comm.Lhs[1], false) // non-escaping ok.store(fn, emitExtract(fn, sel, 1)) @@ -1783,20 +1800,31 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) { // forStmt emits to fn code for the for statement s, optionally // labelled by label. func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) { - // ...init... - // jump loop + // Use forStmtGo122 instead if it applies. + if s.Init != nil { + if assign, ok := s.Init.(*ast.AssignStmt); ok && assign.Tok == token.DEFINE { + if versions.AtLeast(fn.goversion, versions.Go1_22) { + b.forStmtGo122(fn, s, label) + return + } + } + } + + // ...init... + // jump loop // loop: - // if cond goto body else done + // if cond goto body else done // body: - // ...body... - // jump post - // post: (target of continue) - // ...post... - // jump loop + // ...body... + // jump post + // post: (target of continue) + // ...post... + // jump loop // done: (target of break) if s.Init != nil { b.stmt(fn, s.Init) } + body := fn.newBasicBlock("for.body") done := fn.newBasicBlock("for.done") // target of 'break' loop := body // target of back-edge @@ -1834,27 +1862,192 @@ func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) { fn.currentBlock = done } +// forStmtGo122 emits to fn code for the for statement s, optionally +// labelled by label. s must define its variables. +// +// This allocates once per loop iteration. This is only correct in +// GoVersions >= go1.22. +func (b *builder) forStmtGo122(fn *Function, s *ast.ForStmt, label *lblock) { + // i_outer = alloc[T] + // *i_outer = ...init... // under objects[i] = i_outer + // jump loop + // loop: + // i = phi [head: i_outer, loop: i_next] + // ...cond... // under objects[i] = i + // if cond goto body else done + // body: + // ...body... // under objects[i] = i (same as loop) + // jump post + // post: + // tmp = *i + // i_next = alloc[T] + // *i_next = tmp + // ...post... // under objects[i] = i_next + // goto loop + // done: + + init := s.Init.(*ast.AssignStmt) + startingBlocks := len(fn.Blocks) + + pre := fn.currentBlock // current block before starting + loop := fn.newBasicBlock("for.loop") // target of back-edge + body := fn.newBasicBlock("for.body") + post := fn.newBasicBlock("for.post") // target of 'continue' + done := fn.newBasicBlock("for.done") // target of 'break' + + // For each of the n loop variables, we create five SSA values, + // outer, phi, next, load, and store in pre, loop, and post. + // There is no limit on n. + type loopVar struct { + obj *types.Var + outer *Alloc + phi *Phi + load *UnOp + next *Alloc + store *Store + } + vars := make([]loopVar, len(init.Lhs)) + for i, lhs := range init.Lhs { + v := identVar(fn, lhs.(*ast.Ident)) + typ := fn.typ(v.Type()) + + fn.currentBlock = pre + outer := emitLocal(fn, typ, v.Pos(), v.Name()) + + fn.currentBlock = loop + phi := &Phi{Comment: v.Name()} + phi.pos = v.Pos() + phi.typ = outer.Type() + fn.emit(phi) + + fn.currentBlock = post + // If next is local, it reuses the address and zeroes the old value so + // load before allocating next. + load := emitLoad(fn, phi) + next := emitLocal(fn, typ, v.Pos(), v.Name()) + store := emitStore(fn, next, load, token.NoPos) + + phi.Edges = []Value{outer, next} // pre edge is emitted before post edge. + + vars[i] = loopVar{v, outer, phi, load, next, store} + } + + // ...init... under fn.objects[v] = i_outer + fn.currentBlock = pre + for _, v := range vars { + fn.vars[v.obj] = v.outer + } + const isDef = false // assign to already-allocated outers + b.assignStmt(fn, init.Lhs, init.Rhs, isDef) + if label != nil { + label._break = done + label._continue = post + } + emitJump(fn, loop) + + // ...cond... under fn.objects[v] = i + fn.currentBlock = loop + for _, v := range vars { + fn.vars[v.obj] = v.phi + } + if s.Cond != nil { + b.cond(fn, s.Cond, body, done) + } else { + emitJump(fn, body) + } + + // ...body... under fn.objects[v] = i + fn.currentBlock = body + fn.targets = &targets{ + tail: fn.targets, + _break: done, + _continue: post, + } + b.stmt(fn, s.Body) + fn.targets = fn.targets.tail + emitJump(fn, post) + + // ...post... under fn.objects[v] = i_next + for _, v := range vars { + fn.vars[v.obj] = v.next + } + fn.currentBlock = post + if s.Post != nil { + b.stmt(fn, s.Post) + } + emitJump(fn, loop) // back-edge + fn.currentBlock = done + + // For each loop variable that does not escape, + // (the common case), fuse its next cells into its + // (local) outer cell as they have disjoint live ranges. + // + // It is sufficient to test whether i_next escapes, + // because its Heap flag will be marked true if either + // the cond or post expression causes i to escape + // (because escape distributes over phi). + var nlocals int + for _, v := range vars { + if !v.next.Heap { + nlocals++ + } + } + if nlocals > 0 { + replace := make(map[Value]Value, 2*nlocals) + dead := make(map[Instruction]bool, 4*nlocals) + for _, v := range vars { + if !v.next.Heap { + replace[v.next] = v.outer + replace[v.phi] = v.outer + dead[v.phi], dead[v.next], dead[v.load], dead[v.store] = true, true, true, true + } + } + + // Replace all uses of i_next and phi with i_outer. + // Referrers have not been built for fn yet so only update Instruction operands. + // We need only look within the blocks added by the loop. + var operands []*Value // recycle storage + for _, b := range fn.Blocks[startingBlocks:] { + for _, instr := range b.Instrs { + operands = instr.Operands(operands[:0]) + for _, ptr := range operands { + k := *ptr + if v := replace[k]; v != nil { + *ptr = v + } + } + } + } + + // Remove instructions for phi, load, and store. + // lift() will remove the unused i_next *Alloc. + isDead := func(i Instruction) bool { return dead[i] } + loop.Instrs = removeInstrsIf(loop.Instrs, isDead) + post.Instrs = removeInstrsIf(post.Instrs, isDead) + } +} + // rangeIndexed emits to fn the header for an integer-indexed loop // over array, *array or slice value x. // The v result is defined only if tv is non-nil. // forPos is the position of the "for" token. func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) { // - // length = len(x) - // index = -1 - // loop: (target of continue) - // index++ - // if index < length goto body else done + // length = len(x) + // index = -1 + // loop: (target of continue) + // index++ + // if index < length goto body else done // body: - // k = index - // v = x[index] - // ...body... - // jump loop - // done: (target of break) + // k = index + // v = x[index] + // ...body... + // jump loop + // done: (target of break) // Determine number of iterations. var length Value - dt, _ := deref(x.Type()) + dt := typeparams.Deref(x.Type()) if arr, ok := typeparams.CoreType(dt).(*types.Array); ok { // For array or *array, the number of iterations is // known statically thanks to the type. We avoid a @@ -1872,7 +2065,7 @@ func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.P length = fn.emit(&c) } - index := fn.addLocal(tInt, token.NoPos) + index := emitLocal(fn, tInt, token.NoPos, "rangeindex") emitStore(fn, index, intConst(-1), pos) loop = fn.newBasicBlock("rangeindex.loop") @@ -1935,16 +2128,16 @@ func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.P // if the respective component is not wanted. func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) { // - // it = range x + // it = range x // loop: (target of continue) - // okv = next it (ok, key, value) - // ok = extract okv #0 - // if ok goto body else done + // okv = next it (ok, key, value) + // ok = extract okv #0 + // if ok goto body else done // body: - // k = extract okv #1 - // v = extract okv #2 - // ...body... - // jump loop + // k = extract okv #1 + // v = extract okv #2 + // ...body... + // jump loop // done: (target of break) // @@ -1997,13 +2190,13 @@ func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token. func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) { // // loop: (target of continue) - // ko = <-x (key, ok) - // ok = extract ko #1 - // if ok goto body else done + // ko = <-x (key, ok) + // ok = extract ko #1 + // if ok goto body else done // body: - // k = extract ko #0 - // ... - // goto loop + // k = extract ko #0 + // ...body... + // goto loop // done: (target of break) loop = fn.newBasicBlock("rangechan.loop") @@ -2030,6 +2223,57 @@ func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) return } +// rangeInt emits to fn the header for a range loop with an integer operand. +// tk is the key value's type, or nil if the k result is not wanted. +// pos is the position of the "for" token. +func (b *builder) rangeInt(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) { + // + // iter = 0 + // if 0 < x goto body else done + // loop: (target of continue) + // iter++ + // if iter < x goto body else done + // body: + // k = x + // ...body... + // jump loop + // done: (target of break) + + if isUntyped(x.Type()) { + x = emitConv(fn, x, tInt) + } + + T := x.Type() + iter := emitLocal(fn, T, token.NoPos, "rangeint.iter") + // x may be unsigned. Avoid initializing x to -1. + + body := fn.newBasicBlock("rangeint.body") + done = fn.newBasicBlock("rangeint.done") + emitIf(fn, emitCompare(fn, token.LSS, zeroConst(T), x, token.NoPos), body, done) + + loop = fn.newBasicBlock("rangeint.loop") + fn.currentBlock = loop + + incr := &BinOp{ + Op: token.ADD, + X: emitLoad(fn, iter), + Y: emitConv(fn, vOne, T), + } + incr.setType(T) + emitStore(fn, iter, fn.emit(incr), pos) + emitIf(fn, emitCompare(fn, token.LSS, incr, x, token.NoPos), body, done) + fn.currentBlock = body + + if tk != nil { + // Integer types (int, uint8, etc.) are named and + // we know that k is assignable to x when tk != nil. + // This implies tk and T are identical so no conversion is needed. + k = emitLoad(fn, iter) + } + + return +} + // rangeStmt emits to fn code for the range statement s, optionally // labelled by label. func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) { @@ -2041,21 +2285,26 @@ func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) { tv = fn.typeOf(s.Value) } - // If iteration variables are defined (:=), this - // occurs once outside the loop. - // - // Unlike a short variable declaration, a RangeStmt - // using := never redeclares an existing variable; it - // always creates a new one. - if s.Tok == token.DEFINE { + // create locals for s.Key and s.Value. + createVars := func() { + // Unlike a short variable declaration, a RangeStmt + // using := never redeclares an existing variable; it + // always creates a new one. if tk != nil { - fn.addLocalForIdent(s.Key.(*ast.Ident)) + emitLocalVar(fn, identVar(fn, s.Key.(*ast.Ident))) } if tv != nil { - fn.addLocalForIdent(s.Value.(*ast.Ident)) + emitLocalVar(fn, identVar(fn, s.Value.(*ast.Ident))) } } + afterGo122 := versions.AtLeast(fn.goversion, versions.Go1_22) + if s.Tok == token.DEFINE && !afterGo122 { + // pre-go1.22: If iteration variables are defined (:=), this + // occurs once outside the loop. + createVars() + } + x := b.expr(fn, s.X) var k, v Value @@ -2067,13 +2316,38 @@ func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) { case *types.Chan: k, loop, done = b.rangeChan(fn, x, tk, s.For) - case *types.Map, *types.Basic: // string + case *types.Map: k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For) + case *types.Basic: + switch { + case rt.Info()&types.IsString != 0: + k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For) + + case rt.Info()&types.IsInteger != 0: + k, loop, done = b.rangeInt(fn, x, tk, s.For) + + default: + panic("Cannot range over basic type: " + rt.String()) + } + + case *types.Signature: + // Special case rewrite (fn.goversion >= go1.23): + // for x := range f { ... } + // into + // f(func(x T) bool { ... }) + b.rangeFunc(fn, x, tk, tv, s, label) + return + default: panic("Cannot range over: " + rt.String()) } + if s.Tok == token.DEFINE && afterGo122 { + // go1.22: If iteration variables are defined (:=), this occurs inside the loop. + createVars() + } + // Evaluate both LHS expressions before we update either. var kl, vl lvalue if tk != nil { @@ -2105,6 +2379,277 @@ func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) { fn.currentBlock = done } +// rangeFunc emits to fn code for the range-over-func rng.Body of the iterator +// function x, optionally labelled by label. It creates a new anonymous function +// yield for rng and builds the function. +func (b *builder) rangeFunc(fn *Function, x Value, tk, tv types.Type, rng *ast.RangeStmt, label *lblock) { + // Consider the SSA code for the outermost range-over-func in fn: + // + // func fn(...) (ret R) { + // ... + // for k, v = range x { + // ... + // } + // ... + // } + // + // The code emitted into fn will look something like this. + // + // loop: + // jump := READY + // y := make closure yield [ret, deferstack, jump, k, v] + // x(y) + // switch jump { + // [see resuming execution] + // } + // goto done + // done: + // ... + // + // where yield is a new synthetic yield function: + // + // func yield(_k tk, _v tv) bool + // free variables: [ret, stack, jump, k, v] + // { + // entry: + // if jump != READY then goto invalid else valid + // invalid: + // panic("iterator called when it is not in a ready state") + // valid: + // jump = BUSY + // k = _k + // v = _v + // ... + // cont: + // jump = READY + // return true + // } + // + // Yield state: + // + // Each range loop has an associated jump variable that records + // the state of the iterator. A yield function is initially + // in a READY (0) and callable state. If the yield function is called + // and is not in READY state, it panics. When it is called in a callable + // state, it becomes BUSY. When execution reaches the end of the body + // of the loop (or a continue statement targeting the loop is executed), + // the yield function returns true and resumes being in a READY state. + // After the iterator function x(y) returns, then if the yield function + // is in a READY state, the yield enters the DONE state. + // + // Each lowered control statement (break X, continue X, goto Z, or return) + // that exits the loop sets the variable to a unique positive EXIT value, + // before returning false from the yield function. + // + // If the yield function returns abruptly due to a panic or GoExit, + // it remains in a BUSY state. The generated code asserts that, after + // the iterator call x(y) returns normally, the jump variable state + // is DONE. + // + // Resuming execution: + // + // The code generated for the range statement checks the jump + // variable to determine how to resume execution. + // + // switch jump { + // case BUSY: panic("...") + // case DONE: goto done + // case READY: state = DONE; goto done + // case 123: ... // action for exit 123. + // case 456: ... // action for exit 456. + // ... + // } + // + // Forward goto statements within a yield are jumps to labels that + // have not yet been traversed in fn. They may be in the Body of the + // function. What we emit for these is: + // + // goto target + // target: + // ... + // + // We leave an unresolved exit in yield.exits to check at the end + // of building yield if it encountered target in the body. If it + // encountered target, no additional work is required. Otherwise, + // the yield emits a new early exit in the basic block for target. + // We expect that blockopt will fuse the early exit into the case + // block later. The unresolved exit is then added to yield.parent.exits. + + loop := fn.newBasicBlock("rangefunc.loop") + done := fn.newBasicBlock("rangefunc.done") + + // These are targets within y. + fn.targets = &targets{ + tail: fn.targets, + _break: done, + // _continue is within y. + } + if label != nil { + label._break = done + // _continue is within y + } + + emitJump(fn, loop) + fn.currentBlock = loop + + // loop: + // jump := READY + + anonIdx := len(fn.AnonFuncs) + + jump := newVar(fmt.Sprintf("jump$%d", anonIdx+1), tInt) + emitLocalVar(fn, jump) // zero value is READY + + xsig := typeparams.CoreType(x.Type()).(*types.Signature) + ysig := typeparams.CoreType(xsig.Params().At(0).Type()).(*types.Signature) + + /* synthetic yield function for body of range-over-func loop */ + y := &Function{ + name: fmt.Sprintf("%s$%d", fn.Name(), anonIdx+1), + Signature: ysig, + Synthetic: "range-over-func yield", + pos: rangePosition(rng), + parent: fn, + anonIdx: int32(len(fn.AnonFuncs)), + Pkg: fn.Pkg, + Prog: fn.Prog, + syntax: rng, + info: fn.info, + goversion: fn.goversion, + build: (*builder).buildYieldFunc, + topLevelOrigin: nil, + typeparams: fn.typeparams, + typeargs: fn.typeargs, + subst: fn.subst, + jump: jump, + deferstack: fn.deferstack, + returnVars: fn.returnVars, // use the parent's return variables + uniq: fn.uniq, // start from parent's unique values + } + + // If the RangeStmt has a label, this is how it is passed to buildYieldFunc. + if label != nil { + y.lblocks = map[*types.Label]*lblock{label.label: nil} + } + fn.AnonFuncs = append(fn.AnonFuncs, y) + + // Build y immediately. It may: + // * cause fn's locals to escape, and + // * create new exit nodes in exits. + // (y is not marked 'built' until the end of the enclosing FuncDecl.) + unresolved := len(fn.exits) + y.build(b, y) + fn.uniq = y.uniq // resume after y's unique values + + // Emit the call of y. + // c := MakeClosure y + // x(c) + c := &MakeClosure{Fn: y} + c.setType(ysig) + for _, fv := range y.FreeVars { + c.Bindings = append(c.Bindings, fv.outer) + fv.outer = nil + } + fn.emit(c) + call := Call{ + Call: CallCommon{ + Value: x, + Args: []Value{c}, + pos: token.NoPos, + }, + } + call.setType(xsig.Results()) + fn.emit(&call) + + exits := fn.exits[unresolved:] + b.buildYieldResume(fn, jump, exits, done) + + emitJump(fn, done) + fn.currentBlock = done +} + +// buildYieldResume emits to fn code for how to resume execution once a call to +// the iterator function over the yield function returns x(y). It does this by building +// a switch over the value of jump for when it is READY, BUSY, or EXIT(id). +func (b *builder) buildYieldResume(fn *Function, jump *types.Var, exits []*exit, done *BasicBlock) { + // v := *jump + // switch v { + // case BUSY: panic("...") + // case READY: jump = DONE; goto done + // case EXIT(a): ... + // case EXIT(b): ... + // ... + // } + v := emitLoad(fn, fn.lookup(jump, false)) + + // case BUSY: panic("...") + isbusy := fn.newBasicBlock("rangefunc.resume.busy") + ifready := fn.newBasicBlock("rangefunc.resume.ready.check") + emitIf(fn, emitCompare(fn, token.EQL, v, jBusy, token.NoPos), isbusy, ifready) + fn.currentBlock = isbusy + fn.emit(&Panic{ + X: emitConv(fn, stringConst("iterator call did not preserve panic"), tEface), + }) + fn.currentBlock = ifready + + // case READY: jump = DONE; goto done + isready := fn.newBasicBlock("rangefunc.resume.ready") + ifexit := fn.newBasicBlock("rangefunc.resume.exits") + emitIf(fn, emitCompare(fn, token.EQL, v, jReady, token.NoPos), isready, ifexit) + fn.currentBlock = isready + storeVar(fn, jump, jDone, token.NoPos) + emitJump(fn, done) + fn.currentBlock = ifexit + + for _, e := range exits { + id := intConst(e.id) + + // case EXIT(id): { /* do e */ } + cond := emitCompare(fn, token.EQL, v, id, e.pos) + matchb := fn.newBasicBlock("rangefunc.resume.match") + cndb := fn.newBasicBlock("rangefunc.resume.cnd") + emitIf(fn, cond, matchb, cndb) + fn.currentBlock = matchb + + // Cases to fill in the { /* do e */ } bit. + switch { + case e.label != nil: // forward goto? + // case EXIT(id): goto lb // label + lb := fn.lblockOf(e.label) + // Do not mark lb as resolved. + // If fn does not contain label, lb remains unresolved and + // fn must itself be a range-over-func function. lb will be: + // lb: + // fn.jump = id + // return false + emitJump(fn, lb._goto) + + case e.to != fn: // e jumps to an ancestor of fn? + // case EXIT(id): { fn.jump = id; return false } + // fn is a range-over-func function. + storeVar(fn, fn.jump, id, token.NoPos) + fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos}) + + case e.block == nil && e.label == nil: // return from fn? + // case EXIT(id): { return ... } + fn.emit(new(RunDefers)) + results := make([]Value, len(fn.results)) + for i, r := range fn.results { + results[i] = emitLoad(fn, r) + } + fn.emit(&Return{Results: results, pos: e.pos}) + + case e.block != nil: + // case EXIT(id): goto block + emitJump(fn, e.block) + + default: + panic("unreachable") + } + fn.currentBlock = cndb + } +} + // stmt lowers statement s to SSA form, emitting code to fn. func (b *builder) stmt(fn *Function, _s ast.Stmt) { // The label of the current statement. If non-nil, its _goto @@ -2128,7 +2673,14 @@ start: } case *ast.LabeledStmt: - label = fn.labelledBlock(s.Label) + if s.Label.Name == "_" { + // Blank labels can't be the target of a goto, break, + // or continue statement, so we don't need a new block. + _s = s.Stmt + goto start + } + label = fn.lblockOf(fn.label(s.Label)) + label.resolved = true emitJump(fn, label._goto) fn.currentBlock = label._goto _s = s.Stmt @@ -2173,83 +2725,20 @@ start: case *ast.DeferStmt: // The "intrinsics" new/make/len/cap are forbidden here. // panic is treated like an ordinary function call. - v := Defer{pos: s.Defer} + deferstack := emitLoad(fn, fn.lookup(fn.deferstack, false)) + v := Defer{pos: s.Defer, DeferStack: deferstack} b.setCall(fn, s.Call, &v.Call) fn.emit(&v) // A deferred call can cause recovery from panic, // and control resumes at the Recover block. - createRecoverBlock(fn) + createRecoverBlock(fn.source) case *ast.ReturnStmt: - var results []Value - if len(s.Results) == 1 && fn.Signature.Results().Len() > 1 { - // Return of one expression in a multi-valued function. - tuple := b.exprN(fn, s.Results[0]) - ttuple := tuple.Type().(*types.Tuple) - for i, n := 0, ttuple.Len(); i < n; i++ { - results = append(results, - emitConv(fn, emitExtract(fn, tuple, i), - fn.Signature.Results().At(i).Type())) - } - } else { - // 1:1 return, or no-arg return in non-void function. - for i, r := range s.Results { - v := emitConv(fn, b.expr(fn, r), fn.Signature.Results().At(i).Type()) - results = append(results, v) - } - } - if fn.namedResults != nil { - // Function has named result parameters (NRPs). - // Perform parallel assignment of return operands to NRPs. - for i, r := range results { - emitStore(fn, fn.namedResults[i], r, s.Return) - } - } - // Run function calls deferred in this - // function when explicitly returning from it. - fn.emit(new(RunDefers)) - if fn.namedResults != nil { - // Reload NRPs to form the result tuple. - results = results[:0] - for _, r := range fn.namedResults { - results = append(results, emitLoad(fn, r)) - } - } - fn.emit(&Return{Results: results, pos: s.Return}) - fn.currentBlock = fn.newBasicBlock("unreachable") + b.returnStmt(fn, s) case *ast.BranchStmt: - var block *BasicBlock - switch s.Tok { - case token.BREAK: - if s.Label != nil { - block = fn.labelledBlock(s.Label)._break - } else { - for t := fn.targets; t != nil && block == nil; t = t.tail { - block = t._break - } - } - - case token.CONTINUE: - if s.Label != nil { - block = fn.labelledBlock(s.Label)._continue - } else { - for t := fn.targets; t != nil && block == nil; t = t.tail { - block = t._continue - } - } - - case token.FALLTHROUGH: - for t := fn.targets; t != nil && block == nil; t = t.tail { - block = t._fallthrough - } - - case token.GOTO: - block = fn.labelledBlock(s.Label)._goto - } - emitJump(fn, block) - fn.currentBlock = fn.newBasicBlock("unreachable") + b.branchStmt(fn, s) case *ast.BlockStmt: b.stmtList(fn, s.List) @@ -2297,75 +2786,167 @@ start: } } -// buildFunction builds SSA code for the body of function fn. Idempotent. -func (b *builder) buildFunction(fn *Function) { - if !fn.built { - assert(fn.parent == nil, "anonymous functions should not be built by buildFunction()") - b.buildFunctionBody(fn) - fn.done() +func (b *builder) branchStmt(fn *Function, s *ast.BranchStmt) { + var block *BasicBlock + if s.Label == nil { + block = targetedBlock(fn, s.Tok) + } else { + target := fn.label(s.Label) + block = labelledBlock(fn, target, s.Tok) + if block == nil { // forward goto + lb := fn.lblockOf(target) + block = lb._goto // jump to lb._goto + if fn.jump != nil { + // fn is a range-over-func and the goto may exit fn. + // Create an exit and resolve it at the end of + // builder.buildYieldFunc. + labelExit(fn, target, s.Pos()) + } + } + } + to := block.parent + + if to == fn { + emitJump(fn, block) + } else { // break outside of fn. + // fn must be a range-over-func + e := blockExit(fn, block, s.Pos()) + storeVar(fn, fn.jump, intConst(e.id), e.pos) + fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos}) } + fn.currentBlock = fn.newBasicBlock("unreachable") } -// buildFunctionBody builds SSA code for the body of function fn. -// -// fn is not done building until fn.done() is called. -func (b *builder) buildFunctionBody(fn *Function) { - // TODO(taking): see if this check is reachable. - if fn.Blocks != nil { - return // building already started +func (b *builder) returnStmt(fn *Function, s *ast.ReturnStmt) { + var results []Value + + sig := fn.source.Signature // signature of the enclosing source function + + // Convert return operands to result type. + if len(s.Results) == 1 && sig.Results().Len() > 1 { + // Return of one expression in a multi-valued function. + tuple := b.exprN(fn, s.Results[0]) + ttuple := tuple.Type().(*types.Tuple) + for i, n := 0, ttuple.Len(); i < n; i++ { + results = append(results, + emitConv(fn, emitExtract(fn, tuple, i), + sig.Results().At(i).Type())) + } + } else { + // 1:1 return, or no-arg return in non-void function. + for i, r := range s.Results { + v := emitConv(fn, b.expr(fn, r), sig.Results().At(i).Type()) + results = append(results, v) + } } - var recvField *ast.FieldList - var body *ast.BlockStmt - var functype *ast.FuncType - switch n := fn.syntax.(type) { - case nil: - if fn.Params != nil { - return // not a Go source function. (Synthetic, or from object file.) + // Store the results. + for i, r := range results { + var result Value // fn.source.result[i] conceptually + if fn == fn.source { + result = fn.results[i] + } else { // lookup needed? + result = fn.lookup(fn.returnVars[i], false) } - case *ast.FuncDecl: - functype = n.Type - recvField = n.Recv - body = n.Body - case *ast.FuncLit: - functype = n.Type - body = n.Body - default: - panic(n) + emitStore(fn, result, r, s.Return) } - if body == nil { - // External function. - if fn.Params == nil { - // This condition ensures we add a non-empty - // params list once only, but we may attempt - // the degenerate empty case repeatedly. - // TODO(adonovan): opt: don't do that. + if fn.jump != nil { + // Return from body of a range-over-func. + // The return statement is syntactically within the loop, + // but the generated code is in the 'switch jump {...}' after it. + e := returnExit(fn, s.Pos()) + storeVar(fn, fn.jump, intConst(e.id), e.pos) + fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos}) + fn.currentBlock = fn.newBasicBlock("unreachable") + return + } - // We set Function.Params even though there is no body - // code to reference them. This simplifies clients. - if recv := fn.Signature.Recv(); recv != nil { - fn.addParamObj(recv) - } - params := fn.Signature.Params() - for i, n := 0, params.Len(); i < n; i++ { - fn.addParamObj(params.At(i)) - } + // Run function calls deferred in this + // function when explicitly returning from it. + fn.emit(new(RunDefers)) + // Reload (potentially) named result variables to form the result tuple. + results = results[:0] + for _, nr := range fn.results { + results = append(results, emitLoad(fn, nr)) + } + fn.emit(&Return{Results: results, pos: s.Return}) + fn.currentBlock = fn.newBasicBlock("unreachable") +} + +// A buildFunc is a strategy for building the SSA body for a function. +type buildFunc = func(*builder, *Function) + +// iterate causes all created but unbuilt functions to be built. As +// this may create new methods, the process is iterated until it +// converges. +// +// Waits for any dependencies to finish building. +func (b *builder) iterate() { + for ; b.finished < len(b.fns); b.finished++ { + fn := b.fns[b.finished] + b.buildFunction(fn) + } + + b.buildshared.markDone() + b.buildshared.wait() +} + +// buildFunction builds SSA code for the body of function fn. Idempotent. +func (b *builder) buildFunction(fn *Function) { + if fn.build != nil { + assert(fn.parent == nil, "anonymous functions should not be built by buildFunction()") + + if fn.Prog.mode&LogSource != 0 { + defer logStack("build %s @ %s", fn, fn.Prog.Fset.Position(fn.pos))() } - return + fn.build(b, fn) + fn.done() } +} - // Build instantiation wrapper around generic body? - if fn.topLevelOrigin != nil && fn.subst == nil { - buildInstantiationWrapper(fn) - return +// buildParamsOnly builds fn.Params from fn.Signature, but does not build fn.Body. +func (b *builder) buildParamsOnly(fn *Function) { + // For external (C, asm) functions or functions loaded from + // export data, we must set fn.Params even though there is no + // body code to reference them. + if recv := fn.Signature.Recv(); recv != nil { + fn.addParamVar(recv) + } + params := fn.Signature.Params() + for i, n := 0, params.Len(); i < n; i++ { + fn.addParamVar(params.At(i)) } +} - if fn.Prog.mode&LogSource != 0 { - defer logStack("build function %s @ %s", fn, fn.Prog.Fset.Position(fn.pos))() +// buildFromSyntax builds fn.Body from fn.syntax, which must be non-nil. +func (b *builder) buildFromSyntax(fn *Function) { + var ( + recvField *ast.FieldList + body *ast.BlockStmt + functype *ast.FuncType + ) + switch syntax := fn.syntax.(type) { + case *ast.FuncDecl: + functype = syntax.Type + recvField = syntax.Recv + body = syntax.Body + if body == nil { + b.buildParamsOnly(fn) // no body (non-Go function) + return + } + case *ast.FuncLit: + functype = syntax.Type + body = syntax.Body + case nil: + panic("no syntax") + default: + panic(syntax) // unexpected syntax } + fn.source = fn fn.startBody() fn.createSyntacticParams(recvField, functype) + fn.createDeferStack() b.stmt(fn, body) if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) { // Control fell off the end of the function's body block. @@ -2381,45 +2962,159 @@ func (b *builder) buildFunctionBody(fn *Function) { fn.finishBody() } -// buildCreated does the BUILD phase for each function created by builder that is not yet BUILT. -// Functions are built using buildFunction. -// -// May add types that require runtime type information to builder. -func (b *builder) buildCreated() { - for ; b.finished < b.created.Len(); b.finished++ { - fn := b.created.At(b.finished) - b.buildFunction(fn) +// buildYieldFunc builds the body of the yield function created +// from a range-over-func *ast.RangeStmt. +func (b *builder) buildYieldFunc(fn *Function) { + // See builder.rangeFunc for detailed documentation on how fn is set up. + // + // In psuedo-Go this roughly builds: + // func yield(_k tk, _v tv) bool { + // if jump != READY { panic("yield function called after range loop exit") } + // jump = BUSY + // k, v = _k, _v // assign the iterator variable (if needed) + // ... // rng.Body + // continue: + // jump = READY + // return true + // } + s := fn.syntax.(*ast.RangeStmt) + fn.source = fn.parent.source + fn.startBody() + params := fn.Signature.Params() + for i := 0; i < params.Len(); i++ { + fn.addParamVar(params.At(i)) } -} -// Adds any needed runtime type information for the created functions. -// -// May add newly CREATEd functions that may need to be built or runtime type information. -// -// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) -func (b *builder) needsRuntimeTypes() { - if b.created.Len() == 0 { - return + // Initial targets + ycont := fn.newBasicBlock("yield-continue") + // lblocks is either {} or is {label: nil} where label is the label of syntax. + for label := range fn.lblocks { + fn.lblocks[label] = &lblock{ + label: label, + resolved: true, + _goto: ycont, + _continue: ycont, + // `break label` statement targets fn.parent.targets._break + } } - prog := b.created.At(0).Prog + fn.targets = &targets{ + _continue: ycont, + // `break` statement targets fn.parent.targets._break. + } + + // continue: + // jump = READY + // return true + saved := fn.currentBlock + fn.currentBlock = ycont + storeVar(fn, fn.jump, jReady, s.Body.Rbrace) + // A yield function's own deferstack is always empty, so rundefers is not needed. + fn.emit(&Return{Results: []Value{vTrue}, pos: token.NoPos}) - var rtypes []types.Type - for ; b.rtypes < b.finished; b.rtypes++ { - fn := b.created.At(b.rtypes) - rtypes = append(rtypes, mayNeedRuntimeTypes(fn)...) + // Emit header: + // + // if jump != READY { panic("yield iterator accessed after exit") } + // jump = BUSY + // k, v = _k, _v + fn.currentBlock = saved + yloop := fn.newBasicBlock("yield-loop") + invalid := fn.newBasicBlock("yield-invalid") + + jumpVal := emitLoad(fn, fn.lookup(fn.jump, true)) + emitIf(fn, emitCompare(fn, token.EQL, jumpVal, jReady, token.NoPos), yloop, invalid) + fn.currentBlock = invalid + fn.emit(&Panic{ + X: emitConv(fn, stringConst("yield function called after range loop exit"), tEface), + }) + + fn.currentBlock = yloop + storeVar(fn, fn.jump, jBusy, s.Body.Rbrace) + + // Initialize k and v from params. + var tk, tv types.Type + if s.Key != nil && !isBlankIdent(s.Key) { + tk = fn.typeOf(s.Key) // fn.parent.typeOf is identical + } + if s.Value != nil && !isBlankIdent(s.Value) { + tv = fn.typeOf(s.Value) + } + if s.Tok == token.DEFINE { + if tk != nil { + emitLocalVar(fn, identVar(fn, s.Key.(*ast.Ident))) + } + if tv != nil { + emitLocalVar(fn, identVar(fn, s.Value.(*ast.Ident))) + } + } + var k, v Value + if len(fn.Params) > 0 { + k = fn.Params[0] + } + if len(fn.Params) > 1 { + v = fn.Params[1] + } + var kl, vl lvalue + if tk != nil { + kl = b.addr(fn, s.Key, false) // non-escaping + } + if tv != nil { + vl = b.addr(fn, s.Value, false) // non-escaping + } + if tk != nil { + kl.store(fn, k) + } + if tv != nil { + vl.store(fn, v) } - // Calling prog.needMethodsOf(T) on a basic type T is a no-op. - // Filter out the basic types to reduce acquiring prog.methodsMu. - rtypes = nonbasicTypes(rtypes) + // Build the body of the range loop. + b.stmt(fn, s.Body) + if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) { + // Control fell off the end of the function's body block. + // Block optimizations eliminate the current block, if + // unreachable. + emitJump(fn, ycont) + } + + // Clean up exits and promote any unresolved exits to fn.parent. + for _, e := range fn.exits { + if e.label != nil { + lb := fn.lblocks[e.label] + if lb.resolved { + // label was resolved. Do not turn lb into an exit. + // e does not need to be handled by the parent. + continue + } + + // _goto becomes an exit. + // _goto: + // jump = id + // return false + fn.currentBlock = lb._goto + id := intConst(e.id) + storeVar(fn, fn.jump, id, e.pos) + fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos}) + } - for _, T := range rtypes { - prog.needMethodsOf(T, b.created) + if e.to != fn { // e needs to be handled by the parent too. + fn.parent.exits = append(fn.parent.exits, e) + } } + + fn.finishBody() } -func (b *builder) done() bool { - return b.rtypes >= b.created.Len() +// addRuntimeType records t as a runtime type, +// along with all types derivable from it using reflection. +// +// Acquires prog.runtimeTypesMu. +func addRuntimeType(prog *Program, t types.Type) { + prog.runtimeTypesMu.Lock() + defer prog.runtimeTypesMu.Unlock() + forEachReachable(&prog.MethodSets, t, func(t types.Type) bool { + prev, _ := prog.runtimeTypes.Set(t, true).(bool) + return !prev // already seen? + }) } // Build calls Package.Build for each package in prog. @@ -2436,20 +3131,27 @@ func (prog *Program) Build() { p.Build() } else { wg.Add(1) + cpuLimit <- unit{} // acquire a token go func(p *Package) { p.Build() wg.Done() + <-cpuLimit // release a token }(p) } } wg.Wait() } +// cpuLimit is a counting semaphore to limit CPU parallelism. +var cpuLimit = make(chan unit, runtime.GOMAXPROCS(0)) + // Build builds SSA code for all functions and vars in package p. // -// Precondition: CreatePackage must have been called for all of p's -// direct imports (and hence its direct imports must have been -// error-free). +// CreatePackage must have been called for all of p's direct imports +// (and hence its direct imports must have been error-free). It is not +// necessary to call CreatePackage for indirect dependencies. +// Functions will be created for all necessary methods in those +// packages on demand. // // Build is idempotent and thread-safe. func (p *Package) Build() { p.buildOnce.Do(p.build) } @@ -2458,45 +3160,39 @@ func (p *Package) build() { if p.info == nil { return // synthetic package, e.g. "testmain" } - - // Ensure we have runtime type info for all exported members. - // Additionally filter for just concrete types that can be runtime types. - // - // TODO(adonovan): ideally belongs in memberFromObject, but - // that would require package creation in topological order. - for name, mem := range p.Members { - isGround := func(m Member) bool { - switch m := m.(type) { - case *Type: - named, _ := m.Type().(*types.Named) - return named == nil || typeparams.ForNamed(named) == nil - case *Function: - return m.typeparams.Len() == 0 - } - return true // *NamedConst, *Global - } - if ast.IsExported(name) && isGround(mem) { - p.Prog.needMethodsOf(mem.Type(), &p.created) - } - } if p.Prog.mode&LogSource != 0 { defer logStack("build %s", p)() } - b := builder{created: &p.created} - init := p.init - init.startBody() + b := builder{fns: p.created} + b.iterate() + + // We no longer need transient information: ASTs or go/types deductions. + p.info = nil + p.created = nil + p.files = nil + p.initVersion = nil + + if p.Prog.mode&SanityCheckFunctions != 0 { + sanityCheckPackage(p) + } +} + +// buildPackageInit builds fn.Body for the synthetic package initializer. +func (b *builder) buildPackageInit(fn *Function) { + p := fn.Pkg + fn.startBody() var done *BasicBlock if p.Prog.mode&BareInits == 0 { // Make init() skip if package is already initialized. initguard := p.Var("init$guard") - doinit := init.newBasicBlock("init.start") - done = init.newBasicBlock("init.done") - emitIf(init, emitLoad(init, initguard), done, doinit) - init.currentBlock = doinit - emitStore(init, initguard, vTrue, token.NoPos) + doinit := fn.newBasicBlock("init.start") + done = fn.newBasicBlock("init.done") + emitIf(fn, emitLoad(fn, initguard), done, doinit) + fn.currentBlock = doinit + emitStore(fn, initguard, vTrue, token.NoPos) // Call the init() function of each package we import. for _, pkg := range p.Pkg.Imports() { @@ -2506,9 +3202,9 @@ func (p *Package) build() { } var v Call v.Call.Value = prereq.init - v.Call.pos = init.pos + v.Call.pos = fn.pos v.setType(types.NewTuple()) - init.emit(&v) + fn.emit(&v) } } @@ -2516,11 +3212,18 @@ func (p *Package) build() { if len(p.info.InitOrder) > 0 && len(p.files) == 0 { panic("no source files provided for package. cannot initialize globals") } + for _, varinit := range p.info.InitOrder { - if init.Prog.mode&LogSource != 0 { + if fn.Prog.mode&LogSource != 0 { fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n", varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos())) } + // Initializers for global vars are evaluated in dependency + // order, but may come from arbitrary files of the package + // with different versions, so we transiently update + // fn.goversion for each one. (Since init is a synthetic + // function it has no syntax of its own that needs a version.) + fn.goversion = p.initVersion[varinit.Rhs] if len(varinit.Lhs) == 1 { // 1:1 initialization: var x, y = a(), b() var lval lvalue @@ -2529,28 +3232,33 @@ func (p *Package) build() { } else { lval = blank{} } - b.assign(init, lval, varinit.Rhs, true, nil) + b.assign(fn, lval, varinit.Rhs, true, nil) } else { // n:1 initialization: var x, y := f() - tuple := b.exprN(init, varinit.Rhs) + tuple := b.exprN(fn, varinit.Rhs) for i, v := range varinit.Lhs { if v.Name() == "_" { continue } - emitStore(init, p.objects[v].(*Global), emitExtract(init, tuple, i), v.Pos()) + emitStore(fn, p.objects[v].(*Global), emitExtract(fn, tuple, i), v.Pos()) } } } + // The rest of the init function is synthetic: + // no syntax, info, goversion. + fn.info = nil + fn.goversion = "" + // Call all of the declared init() functions in source order. for _, file := range p.files { for _, decl := range file.Decls { if decl, ok := decl.(*ast.FuncDecl); ok { id := decl.Name if !isBlankIdent(id) && id.Name == "init" && decl.Recv == nil { - fn := p.objects[p.info.Defs[id]].(*Function) + declaredInit := p.objects[p.info.Defs[id]].(*Function) var v Call - v.Call.Value = fn + v.Call.Value = declaredInit v.setType(types.NewTuple()) p.init.emit(&v) } @@ -2560,35 +3268,9 @@ func (p *Package) build() { // Finish up init(). if p.Prog.mode&BareInits == 0 { - emitJump(init, done) - init.currentBlock = done - } - init.emit(new(Return)) - init.finishBody() - init.done() - - // Build all CREATEd functions and add runtime types. - // These Functions include package-level functions, init functions, methods, and synthetic (including unreachable/blank ones). - // Builds any functions CREATEd while building this package. - // - // Initially the created functions for the package are: - // [init, decl0, ... , declN] - // Where decl0, ..., declN are declared functions in source order, but it's not significant. - // - // As these are built, more functions (function literals, wrappers, etc.) can be CREATEd. - // Iterate until we reach a fixed point. - // - // Wait for init() to be BUILT as that cannot be built by buildFunction(). - // - for !b.done() { - b.buildCreated() // build any CREATEd and not BUILT function. May add runtime types. - b.needsRuntimeTypes() // Add all of the runtime type information. May CREATE Functions. - } - - p.info = nil // We no longer need ASTs or go/types deductions. - p.created = nil // We no longer need created functions. - - if p.Prog.mode&SanityCheckFunctions != 0 { - sanityCheckPackage(p) + emitJump(fn, done) + fn.currentBlock = done } + fn.emit(new(Return)) + fn.finishBody() } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/const.go b/tools/vendor/golang.org/x/tools/go/ssa/const.go index 4a51a2cb4..2a4e0dde2 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/const.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/const.go @@ -14,6 +14,7 @@ import ( "strconv" "strings" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -45,9 +46,9 @@ func soleTypeKind(typ types.Type) types.BasicInfo { // Candidates (perhaps all) are eliminated during the type-set // iteration, which executes at least once. state := types.IsBoolean | types.IsInteger | types.IsString - underIs(typeSetOf(typ), func(t types.Type) bool { + underIs(typeSetOf(typ), func(ut types.Type) bool { var c types.BasicInfo - if t, ok := t.(*types.Basic); ok { + if t, ok := ut.(*types.Basic); ok { c = t.Info() } if c&types.IsNumeric != 0 { // int/float/complex @@ -113,7 +114,7 @@ func zeroString(t types.Type, from *types.Package) string { } case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature: return "nil" - case *types.Named: + case *types.Named, *aliases.Alias: return zeroString(t.Underlying(), from) case *types.Array, *types.Struct: return relType(t, from) + "{}" @@ -125,7 +126,7 @@ func zeroString(t types.Type, from *types.Package) string { components[i] = zeroString(t.At(i).Type(), from) } return "(" + strings.Join(components, ", ") + ")" - case *typeparams.TypeParam: + case *types.TypeParam: return "*new(" + relType(t, from) + ")" } panic(fmt.Sprint("zeroString: unexpected ", t)) diff --git a/tools/vendor/golang.org/x/tools/go/ssa/coretype.go b/tools/vendor/golang.org/x/tools/go/ssa/coretype.go index 128d61e42..8c218f919 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/coretype.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/coretype.go @@ -7,6 +7,7 @@ package ssa import ( "go/types" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) @@ -40,19 +41,20 @@ func isBytestring(T types.Type) bool { } // termList is a list of types. -type termList []*typeparams.Term // type terms of the type set +type termList []*types.Term // type terms of the type set func (s termList) Len() int { return len(s) } func (s termList) At(i int) types.Type { return s[i].Type() } // typeSetOf returns the type set of typ. Returns an empty typeset on an error. func typeSetOf(typ types.Type) termList { // This is a adaptation of x/exp/typeparams.NormalTerms which x/tools cannot depend on. - var terms []*typeparams.Term + var terms []*types.Term var err error - switch typ := typ.(type) { - case *typeparams.TypeParam: + // typeSetOf(t) == typeSetOf(Unalias(t)) + switch typ := aliases.Unalias(typ).(type) { + case *types.TypeParam: terms, err = typeparams.StructuralTerms(typ) - case *typeparams.Union: + case *types.Union: terms, err = typeparams.UnionTermSet(typ) case *types.Interface: terms, err = typeparams.InterfaceTermSet(typ) @@ -60,7 +62,7 @@ func typeSetOf(typ types.Type) termList { // Common case. // Specializing the len=1 case to avoid a slice // had no measurable space/time benefit. - terms = []*typeparams.Term{typeparams.NewTerm(false, typ)} + terms = []*types.Term{types.NewTerm(false, typ)} } if err != nil { diff --git a/tools/vendor/golang.org/x/tools/go/ssa/create.go b/tools/vendor/golang.org/x/tools/go/ssa/create.go index 1bf88c83e..423bce871 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/create.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/create.go @@ -15,41 +15,42 @@ import ( "os" "sync" - "golang.org/x/tools/go/types/typeutil" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/versions" ) // NewProgram returns a new SSA Program. // // mode controls diagnostics and checking during SSA construction. +// +// To construct an SSA program: +// +// - Call NewProgram to create an empty Program. +// - Call CreatePackage providing typed syntax for each package +// you want to build, and call it with types but not +// syntax for each of those package's direct dependencies. +// - Call [Package.Build] on each syntax package you wish to build, +// or [Program.Build] to build all of them. +// +// See the Example tests for simple examples. func NewProgram(fset *token.FileSet, mode BuilderMode) *Program { - prog := &Program{ - Fset: fset, - imported: make(map[string]*Package), - packages: make(map[*types.Package]*Package), - thunks: make(map[selectionKey]*Function), - bounds: make(map[boundsKey]*Function), - mode: mode, - canon: newCanonizer(), - ctxt: typeparams.NewContext(), - instances: make(map[*Function]*instanceSet), - parameterized: tpWalker{seen: make(map[types.Type]bool)}, + return &Program{ + Fset: fset, + imported: make(map[string]*Package), + packages: make(map[*types.Package]*Package), + mode: mode, + canon: newCanonizer(), + ctxt: types.NewContext(), } - - h := typeutil.MakeHasher() // protected by methodsMu, in effect - prog.methodSets.SetHasher(h) - prog.runtimeTypes.SetHasher(h) - - return prog } // memberFromObject populates package pkg with a member for the // typechecker object obj. // // For objects from Go source code, syntax is the associated syntax -// tree (for funcs and vars only); it will be used during the build +// tree (for funcs and vars only) and goversion defines the +// appropriate interpretation; they will be used during the build // phase. -func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { +func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node, goversion string) { name := obj.Name() switch obj := obj.(type) { case *types.Builtin: @@ -58,9 +59,11 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { } case *types.TypeName: - pkg.Members[name] = &Type{ - object: obj, - pkg: pkg, + if name != "_" { + pkg.Members[name] = &Type{ + object: obj, + pkg: pkg, + } } case *types.Const: @@ -70,7 +73,9 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { pkg: pkg, } pkg.objects[obj] = c - pkg.Members[name] = c + if name != "_" { + pkg.Members[name] = c + } case *types.Var: g := &Global{ @@ -81,7 +86,9 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { pos: obj.Pos(), } pkg.objects[obj] = g - pkg.Members[name] = g + if name != "_" { + pkg.Members[name] = g + } case *types.Func: sig := obj.Type().(*types.Signature) @@ -89,36 +96,11 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { pkg.ninit++ name = fmt.Sprintf("init#%d", pkg.ninit) } - - // Collect type parameters if this is a generic function/method. - var tparams *typeparams.TypeParamList - if rtparams := typeparams.RecvTypeParams(sig); rtparams.Len() > 0 { - tparams = rtparams - } else if sigparams := typeparams.ForSignature(sig); sigparams.Len() > 0 { - tparams = sigparams - } - - fn := &Function{ - name: name, - object: obj, - Signature: sig, - syntax: syntax, - pos: obj.Pos(), - Pkg: pkg, - Prog: pkg.Prog, - typeparams: tparams, - info: pkg.info, - } - pkg.created.Add(fn) - if syntax == nil { - fn.Synthetic = "loaded from gc object file" - } - if tparams.Len() > 0 { - fn.Prog.createInstanceSet(fn) - } - + fn := createFunction(pkg.Prog, obj, name, syntax, pkg.info, goversion) + fn.Pkg = pkg + pkg.created = append(pkg.created, fn) pkg.objects[obj] = fn - if sig.Recv() == nil { + if name != "_" && sig.Recv() == nil { pkg.Members[name] = fn // package-level function } @@ -127,62 +109,82 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { } } +// createFunction creates a function or method. It supports both +// CreatePackage (with or without syntax) and the on-demand creation +// of methods in non-created packages based on their types.Func. +func createFunction(prog *Program, obj *types.Func, name string, syntax ast.Node, info *types.Info, goversion string) *Function { + sig := obj.Type().(*types.Signature) + + // Collect type parameters. + var tparams *types.TypeParamList + if rtparams := sig.RecvTypeParams(); rtparams.Len() > 0 { + tparams = rtparams // method of generic type + } else if sigparams := sig.TypeParams(); sigparams.Len() > 0 { + tparams = sigparams // generic function + } + + /* declared function/method (from syntax or export data) */ + fn := &Function{ + name: name, + object: obj, + Signature: sig, + build: (*builder).buildFromSyntax, + syntax: syntax, + info: info, + goversion: goversion, + pos: obj.Pos(), + Pkg: nil, // may be set by caller + Prog: prog, + typeparams: tparams, + } + if fn.syntax == nil { + fn.Synthetic = "from type information" + fn.build = (*builder).buildParamsOnly + } + if tparams.Len() > 0 { + fn.generic = new(generic) + } + return fn +} + // membersFromDecl populates package pkg with members for each // typechecker object (var, func, const or type) associated with the // specified decl. -func membersFromDecl(pkg *Package, decl ast.Decl) { +func membersFromDecl(pkg *Package, decl ast.Decl, goversion string) { switch decl := decl.(type) { case *ast.GenDecl: // import, const, type or var switch decl.Tok { case token.CONST: for _, spec := range decl.Specs { for _, id := range spec.(*ast.ValueSpec).Names { - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], nil) - } + memberFromObject(pkg, pkg.info.Defs[id], nil, "") } } case token.VAR: for _, spec := range decl.Specs { + for _, rhs := range spec.(*ast.ValueSpec).Values { + pkg.initVersion[rhs] = goversion + } for _, id := range spec.(*ast.ValueSpec).Names { - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], spec) - } + memberFromObject(pkg, pkg.info.Defs[id], spec, goversion) } } case token.TYPE: for _, spec := range decl.Specs { id := spec.(*ast.TypeSpec).Name - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], nil) - } + memberFromObject(pkg, pkg.info.Defs[id], nil, "") } } case *ast.FuncDecl: id := decl.Name - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], decl) - } + memberFromObject(pkg, pkg.info.Defs[id], decl, goversion) } } -// creator tracks functions that have finished their CREATE phases. -// -// All Functions belong to the same Program. May have differing packages. -// -// creators are not thread-safe. -type creator []*Function - -func (c *creator) Add(fn *Function) { - *c = append(*c, fn) -} -func (c *creator) At(i int) *Function { return (*c)[i] } -func (c *creator) Len() int { return len(*c) } - -// CreatePackage constructs and returns an SSA Package from the +// CreatePackage creates and returns an SSA Package from the // specified type-checked, error-free file ASTs, and populates its // Members mapping. // @@ -190,36 +192,48 @@ func (c *creator) Len() int { return len(*c) } // subsequent call to ImportedPackage(pkg.Path()). // // The real work of building SSA form for each function is not done -// until a subsequent call to Package.Build(). +// until a subsequent call to Package.Build. +// +// CreatePackage should not be called after building any package in +// the program. func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info *types.Info, importable bool) *Package { + // TODO(adonovan): assert that no package has yet been built. + if pkg == nil { + panic("nil pkg") // otherwise pkg.Scope below returns types.Universe! + } p := &Package{ Prog: prog, Members: make(map[string]Member), objects: make(map[types.Object]Member), Pkg: pkg, - info: info, // transient (CREATE and BUILD phases) - files: files, // transient (CREATE and BUILD phases) + syntax: info != nil, + // transient values (cleared after Package.Build) + info: info, + files: files, + initVersion: make(map[ast.Expr]string), } - // Add init() function. + /* synthesized package initializer */ p.init = &Function{ name: "init", Signature: new(types.Signature), Synthetic: "package initializer", Pkg: p, Prog: prog, + build: (*builder).buildPackageInit, info: p.info, + goversion: "", // See Package.build for details. } p.Members[p.init.name] = p.init - p.created.Add(p.init) + p.created = append(p.created, p.init) - // CREATE phase. // Allocate all package members: vars, funcs, consts and types. if len(files) > 0 { // Go source package. for _, file := range files { + goversion := versions.Lang(versions.FileVersion(p.info, file)) for _, decl := range file.Decls { - membersFromDecl(p, decl) + membersFromDecl(p, decl, goversion) } } } else { @@ -229,11 +243,12 @@ func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info * scope := p.Pkg.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) - memberFromObject(p, obj, nil) + memberFromObject(p, obj, nil, "") if obj, ok := obj.(*types.TypeName); ok { + // No Unalias: aliases should not duplicate methods. if named, ok := obj.Type().(*types.Named); ok { for i, n := 0, named.NumMethods(); i < n; i++ { - memberFromObject(p, named.Method(i), nil) + memberFromObject(p, named.Method(i), nil, "") } } } @@ -271,8 +286,8 @@ func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info * // printMu serializes printing of Packages/Functions to stdout. var printMu sync.Mutex -// AllPackages returns a new slice containing all packages in the -// program prog in unspecified order. +// AllPackages returns a new slice containing all packages created by +// prog.CreatePackage in unspecified order. func (prog *Program) AllPackages() []*Package { pkgs := make([]*Package, 0, len(prog.packages)) for _, pkg := range prog.packages { diff --git a/tools/vendor/golang.org/x/tools/go/ssa/doc.go b/tools/vendor/golang.org/x/tools/go/ssa/doc.go index a687de45e..3310b5509 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/doc.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/doc.go @@ -7,8 +7,6 @@ // static single-assignment (SSA) form intermediate representation // (IR) for the bodies of functions. // -// THIS INTERFACE IS EXPERIMENTAL AND IS LIKELY TO CHANGE. -// // For an introduction to SSA form, see // http://en.wikipedia.org/wiki/Static_single_assignment_form. // This page provides a broader reading list: @@ -21,15 +19,15 @@ // All looping, branching and switching constructs are replaced with // unstructured control flow. Higher-level control flow constructs // such as multi-way branch can be reconstructed as needed; see -// ssautil.Switches() for an example. +// [golang.org/x/tools/go/ssa/ssautil.Switches] for an example. // // The simplest way to create the SSA representation of a package is -// to load typed syntax trees using golang.org/x/tools/go/packages, then -// invoke the ssautil.Packages helper function. See Example_loadPackages -// and Example_loadWholeProgram for examples. -// The resulting ssa.Program contains all the packages and their +// to load typed syntax trees using [golang.org/x/tools/go/packages], then +// invoke the [golang.org/x/tools/go/ssa/ssautil.Packages] helper function. +// (See the package-level Examples named LoadPackages and LoadWholeProgram.) +// The resulting [ssa.Program] contains all the packages and their // members, but SSA code is not created for function bodies until a -// subsequent call to (*Package).Build or (*Program).Build. +// subsequent call to [Package.Build] or [Program.Build]. // // The builder initially builds a naive SSA form in which all local // variables are addresses of stack locations with explicit loads and @@ -41,13 +39,13 @@ // // The primary interfaces of this package are: // -// - Member: a named member of a Go package. -// - Value: an expression that yields a value. -// - Instruction: a statement that consumes values and performs computation. -// - Node: a Value or Instruction (emphasizing its membership in the SSA value graph) +// - [Member]: a named member of a Go package. +// - [Value]: an expression that yields a value. +// - [Instruction]: a statement that consumes values and performs computation. +// - [Node]: a [Value] or [Instruction] (emphasizing its membership in the SSA value graph) // -// A computation that yields a result implements both the Value and -// Instruction interfaces. The following table shows for each +// A computation that yields a result implements both the [Value] and +// [Instruction] interfaces. The following table shows for each // concrete type which of these interfaces it implements. // // Value? Instruction? Member? @@ -97,15 +95,15 @@ // *TypeAssert ✔ ✔ // *UnOp ✔ ✔ // -// Other key types in this package include: Program, Package, Function -// and BasicBlock. +// Other key types in this package include: [Program], [Package], [Function] +// and [BasicBlock]. // // The program representation constructed by this package is fully // resolved internally, i.e. it does not rely on the names of Values, // Packages, Functions, Types or BasicBlocks for the correct // interpretation of the program. Only the identities of objects and // the topology of the SSA and type graphs are semantically -// significant. (There is one exception: Ids, used to identify field +// significant. (There is one exception: [types.Id] values, which identify field // and method names, contain strings.) Avoidance of name-based // operations simplifies the implementation of subsequent passes and // can make them very efficient. Many objects are nonetheless named @@ -113,11 +111,9 @@ // either accurate or unambiguous. The public API exposes a number of // name-based maps for client convenience. // -// The ssa/ssautil package provides various utilities that depend only -// on the public API of this package. -// -// TODO(adonovan): Consider the exceptional control-flow implications -// of defer and recover(). +// The [golang.org/x/tools/go/ssa/ssautil] package provides various +// helper functions, for example to simplify loading a Go program into +// SSA form. // // TODO(adonovan): write a how-to document for all the various cases // of trying to determine corresponding elements across the four diff --git a/tools/vendor/golang.org/x/tools/go/ssa/dom.go b/tools/vendor/golang.org/x/tools/go/ssa/dom.go index 66a2f5e6e..02c1ae83a 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/dom.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/dom.go @@ -40,20 +40,25 @@ func (b *BasicBlock) Dominates(c *BasicBlock) bool { return b.dom.pre <= c.dom.pre && c.dom.post <= b.dom.post } -type byDomPreorder []*BasicBlock - -func (a byDomPreorder) Len() int { return len(a) } -func (a byDomPreorder) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byDomPreorder) Less(i, j int) bool { return a[i].dom.pre < a[j].dom.pre } - -// DomPreorder returns a new slice containing the blocks of f in -// dominator tree preorder. +// DomPreorder returns a new slice containing the blocks of f +// in a preorder traversal of the dominator tree. func (f *Function) DomPreorder() []*BasicBlock { - n := len(f.Blocks) - order := make(byDomPreorder, n) - copy(order, f.Blocks) - sort.Sort(order) - return order + slice := append([]*BasicBlock(nil), f.Blocks...) + sort.Slice(slice, func(i, j int) bool { + return slice[i].dom.pre < slice[j].dom.pre + }) + return slice +} + +// DomPostorder returns a new slice containing the blocks of f +// in a postorder traversal of the dominator tree. +// (This is not the same as a postdominance order.) +func (f *Function) DomPostorder() []*BasicBlock { + slice := append([]*BasicBlock(nil), f.Blocks...) + sort.Slice(slice, func(i, j int) bool { + return slice[i].dom.post < slice[j].dom.post + }) + return slice } // domInfo contains a BasicBlock's dominance information. diff --git a/tools/vendor/golang.org/x/tools/go/ssa/emit.go b/tools/vendor/golang.org/x/tools/go/ssa/emit.go index abb617e6d..c664ff85a 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/emit.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/emit.go @@ -11,23 +11,62 @@ import ( "go/ast" "go/token" "go/types" + + "golang.org/x/tools/internal/typeparams" ) -// emitNew emits to f a new (heap Alloc) instruction allocating an -// object of type typ. pos is the optional source location. -func emitNew(f *Function, typ types.Type, pos token.Pos) *Alloc { - v := &Alloc{Heap: true} +// emitAlloc emits to f a new Alloc instruction allocating a variable +// of type typ. +// +// The caller must set Alloc.Heap=true (for an heap-allocated variable) +// or add the Alloc to f.Locals (for a frame-allocated variable). +// +// During building, a variable in f.Locals may have its Heap flag +// set when it is discovered that its address is taken. +// These Allocs are removed from f.Locals at the end. +// +// The builder should generally call one of the emit{New,Local,LocalVar} wrappers instead. +func emitAlloc(f *Function, typ types.Type, pos token.Pos, comment string) *Alloc { + v := &Alloc{Comment: comment} v.setType(types.NewPointer(typ)) v.setPos(pos) f.emit(v) return v } +// emitNew emits to f a new Alloc instruction heap-allocating a +// variable of type typ. pos is the optional source location. +func emitNew(f *Function, typ types.Type, pos token.Pos, comment string) *Alloc { + alloc := emitAlloc(f, typ, pos, comment) + alloc.Heap = true + return alloc +} + +// emitLocal creates a local var for (t, pos, comment) and +// emits an Alloc instruction for it. +// +// (Use this function or emitNew for synthetic variables; +// for source-level variables in the same function, use emitLocalVar.) +func emitLocal(f *Function, t types.Type, pos token.Pos, comment string) *Alloc { + local := emitAlloc(f, t, pos, comment) + f.Locals = append(f.Locals, local) + return local +} + +// emitLocalVar creates a local var for v and emits an Alloc instruction for it. +// Subsequent calls to f.lookup(v) return it. +// It applies the appropriate generic instantiation to the type. +func emitLocalVar(f *Function, v *types.Var) *Alloc { + alloc := emitLocal(f, f.typ(v.Type()), v.Pos(), v.Name()) + f.vars[v] = alloc + return alloc +} + // emitLoad emits to f an instruction to load the address addr into a // new temporary, and returns the value so defined. func emitLoad(f *Function, addr Value) *UnOp { v := &UnOp{Op: token.MUL, X: addr} - v.setType(mustDeref(addr.Type())) + v.setType(typeparams.MustDeref(addr.Type())) f.emit(v) return v } @@ -145,10 +184,10 @@ func emitCompare(f *Function, op token.Token, x, y Value, pos token.Pos) Value { // isValuePreserving returns true if a conversion from ut_src to // ut_dst is value-preserving, i.e. just a change of type. -// Precondition: neither argument is a named type. +// Precondition: neither argument is a named or alias type. func isValuePreserving(ut_src, ut_dst types.Type) bool { // Identical underlying types? - if structTypesIdentical(ut_dst, ut_src) { + if types.IdenticalIgnoreTags(ut_dst, ut_src) { return true } @@ -206,6 +245,13 @@ func emitConv(f *Function, val Value, typ types.Type) Value { val = emitConv(f, val, types.Default(ut_src)) } + // Record the types of operands to MakeInterface, if + // non-parameterized, as they are the set of runtime types. + t := val.Type() + if f.typeparams.Len() == 0 || !f.Prog.isParameterized(t) { + addRuntimeType(f.Prog, t) + } + mi := &MakeInterface{X: val} mi.setType(typ) return f.emit(mi) @@ -230,18 +276,20 @@ func emitConv(f *Function, val Value, typ types.Type) Value { sliceTo0ArrayPtr convert ) - classify := func(s, d types.Type) conversionCase { + // classify the conversion case of a source type us to a destination type ud. + // us and ud are underlying types (not *Named or *Alias) + classify := func(us, ud types.Type) conversionCase { // Just a change of type, but not value or representation? - if isValuePreserving(s, d) { + if isValuePreserving(us, ud) { return changeType } // Conversion from slice to array or slice to array pointer? - if slice, ok := s.(*types.Slice); ok { + if slice, ok := us.(*types.Slice); ok { var arr *types.Array var ptr bool // Conversion from slice to array pointer? - switch d := d.(type) { + switch d := ud.(type) { case *types.Array: arr = d case *types.Pointer: @@ -266,8 +314,8 @@ func emitConv(f *Function, val Value, typ types.Type) Value { // The only remaining case in well-typed code is a representation- // changing conversion of basic types (possibly with []byte/[]rune). - if !isBasic(s) && !isBasic(d) { - panic(fmt.Sprintf("in %s: cannot convert term %s (%s [within %s]) to type %s [within %s]", f, val, val.Type(), s, typ, d)) + if !isBasic(us) && !isBasic(ud) { + panic(fmt.Sprintf("in %s: cannot convert term %s (%s [within %s]) to type %s [within %s]", f, val, val.Type(), us, typ, ud)) } return convert } @@ -370,7 +418,7 @@ func emitTypeCoercion(f *Function, v Value, typ types.Type) Value { // emitStore emits to f an instruction to store value val at location // addr, applying implicit conversions as required by assignability rules. func emitStore(f *Function, addr, val Value, pos token.Pos) *Store { - typ := mustDeref(addr.Type()) + typ := typeparams.MustDeref(addr.Type()) s := &Store{ Addr: addr, Val: emitConv(f, val, typ), @@ -476,8 +524,8 @@ func emitTailCall(f *Function, call *Call) { // value of a field. func emitImplicitSelections(f *Function, v Value, indices []int, pos token.Pos) Value { for _, index := range indices { - if st, vptr := deref(v.Type()); vptr { - fld := fieldOf(st, index) + if isPointerCore(v.Type()) { + fld := fieldOf(typeparams.MustDeref(v.Type()), index) instr := &FieldAddr{ X: v, Field: index, @@ -486,7 +534,7 @@ func emitImplicitSelections(f *Function, v Value, indices []int, pos token.Pos) instr.setType(types.NewPointer(fld.Type())) v = f.emit(instr) // Load the field's value iff indirectly embedded. - if _, fldptr := deref(fld.Type()); fldptr { + if isPointerCore(fld.Type()) { v = emitLoad(f, v) } } else { @@ -510,8 +558,8 @@ func emitImplicitSelections(f *Function, v Value, indices []int, pos token.Pos) // field's value. // Ident id is used for position and debug info. func emitFieldSelection(f *Function, v Value, index int, wantAddr bool, id *ast.Ident) Value { - if st, vptr := deref(v.Type()); vptr { - fld := fieldOf(st, index) + if isPointerCore(v.Type()) { + fld := fieldOf(typeparams.MustDeref(v.Type()), index) instr := &FieldAddr{ X: v, Field: index, @@ -537,48 +585,6 @@ func emitFieldSelection(f *Function, v Value, index int, wantAddr bool, id *ast. return v } -// emitSliceToArray emits to f code to convert a slice value to an array value. -// -// Precondition: all types in type set of typ are arrays and convertible to all -// types in the type set of val.Type(). -func emitSliceToArray(f *Function, val Value, typ types.Type) Value { - // Emit the following: - // if val == nil && len(typ) == 0 { - // ptr = &[0]T{} - // } else { - // ptr = SliceToArrayPointer(val) - // } - // v = *ptr - - ptype := types.NewPointer(typ) - p := &SliceToArrayPointer{X: val} - p.setType(ptype) - ptr := f.emit(p) - - nilb := f.newBasicBlock("slicetoarray.nil") - nonnilb := f.newBasicBlock("slicetoarray.nonnil") - done := f.newBasicBlock("slicetoarray.done") - - cond := emitCompare(f, token.EQL, ptr, zeroConst(ptype), token.NoPos) - emitIf(f, cond, nilb, nonnilb) - f.currentBlock = nilb - - zero := f.addLocal(typ, token.NoPos) - emitJump(f, done) - f.currentBlock = nonnilb - - emitJump(f, done) - f.currentBlock = done - - phi := &Phi{Edges: []Value{zero, ptr}, Comment: "slicetoarray"} - phi.pos = val.Pos() - phi.setType(typ) - x := f.emit(phi) - unOp := &UnOp{Op: token.MUL, X: x} - unOp.setType(typ) - return f.emit(unOp) -} - // createRecoverBlock emits to f a block of code to return after a // recovered panic, and sets f.Recover to it. // @@ -597,20 +603,11 @@ func createRecoverBlock(f *Function) { f.currentBlock = f.Recover var results []Value - if f.namedResults != nil { - // Reload NRPs to form value tuple. - for _, r := range f.namedResults { - results = append(results, emitLoad(f, r)) - } - } else { - R := f.Signature.Results() - for i, n := 0, R.Len(); i < n; i++ { - T := R.At(i).Type() - - // Return zero value of each result type. - results = append(results, zeroConst(T)) - } + // Reload NRPs to form value tuple. + for _, nr := range f.results { + results = append(results, emitLoad(f, nr)) } + f.emit(&Return{Results: results}) f.currentBlock = saved diff --git a/tools/vendor/golang.org/x/tools/go/ssa/func.go b/tools/vendor/golang.org/x/tools/go/ssa/func.go index 38c3e31ba..2ed63bfd5 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/func.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/func.go @@ -38,7 +38,8 @@ func (f *Function) typeOf(e ast.Expr) types.Type { panic(fmt.Sprintf("no type for %T @ %s", e, f.Prog.Fset.Position(e.Pos()))) } -// typ is the locally instantiated type of T. T==typ(T) if f is not an instantiation. +// typ is the locally instantiated type of T. +// If f is not an instantiation, then f.typ(T)==T. func (f *Function) typ(T types.Type) types.Type { return f.subst.typ(T) } @@ -46,7 +47,7 @@ func (f *Function) typ(T types.Type) types.Type { // If id is an Instance, returns info.Instances[id].Type. // Otherwise returns f.typeOf(id). func (f *Function) instanceType(id *ast.Ident) types.Type { - if t, ok := typeparams.GetInstances(f.info)[id]; ok { + if t, ok := f.info.Instances[id]; ok { return t.Type } return f.typeOf(id) @@ -99,61 +100,121 @@ type targets struct { // Destinations associated with a labelled block. // We populate these as labels are encountered in forward gotos or // labelled statements. +// Forward gotos are resolved once it is known which statement they +// are associated with inside the Function. type lblock struct { + label *types.Label // Label targeted by the blocks. + resolved bool // _goto block encountered (back jump or resolved fwd jump) _goto *BasicBlock _break *BasicBlock _continue *BasicBlock } -// labelledBlock returns the branch target associated with the +// label returns the symbol denoted by a label identifier. +// +// label should be a non-blank identifier (label.Name != "_"). +func (f *Function) label(label *ast.Ident) *types.Label { + return f.objectOf(label).(*types.Label) +} + +// lblockOf returns the branch target associated with the // specified label, creating it if needed. -func (f *Function) labelledBlock(label *ast.Ident) *lblock { - obj := f.objectOf(label) - lb := f.lblocks[obj] +func (f *Function) lblockOf(label *types.Label) *lblock { + lb := f.lblocks[label] if lb == nil { - lb = &lblock{_goto: f.newBasicBlock(label.Name)} + lb = &lblock{ + label: label, + _goto: f.newBasicBlock(label.Name()), + } if f.lblocks == nil { - f.lblocks = make(map[types.Object]*lblock) + f.lblocks = make(map[*types.Label]*lblock) } - f.lblocks[obj] = lb + f.lblocks[label] = lb } return lb } -// addParam adds a (non-escaping) parameter to f.Params of the -// specified name, type and source position. -func (f *Function) addParam(name string, typ types.Type, pos token.Pos) *Parameter { - v := &Parameter{ - name: name, - typ: typ, - pos: pos, - parent: f, +// labelledBlock searches f for the block of the specified label. +// +// If f is a yield function, it additionally searches ancestor Functions +// corresponding to enclosing range-over-func statements within the +// same source function, so the returned block may belong to a different Function. +func labelledBlock(f *Function, label *types.Label, tok token.Token) *BasicBlock { + if lb := f.lblocks[label]; lb != nil { + var block *BasicBlock + switch tok { + case token.BREAK: + block = lb._break + case token.CONTINUE: + block = lb._continue + case token.GOTO: + block = lb._goto + } + if block != nil { + return block + } } - f.Params = append(f.Params, v) - return v + // Search ancestors if this is a yield function. + if f.jump != nil { + return labelledBlock(f.parent, label, tok) + } + return nil +} + +// targetedBlock looks for the nearest block in f.targets +// (and f's ancestors) that matches tok's type, and returns +// the block and function it was found in. +func targetedBlock(f *Function, tok token.Token) *BasicBlock { + if f == nil { + return nil + } + for t := f.targets; t != nil; t = t.tail { + var block *BasicBlock + switch tok { + case token.BREAK: + block = t._break + case token.CONTINUE: + block = t._continue + case token.FALLTHROUGH: + block = t._fallthrough + } + if block != nil { + return block + } + } + // Search f's ancestors (in case f is a yield function). + return targetedBlock(f.parent, tok) } -func (f *Function) addParamObj(obj types.Object) *Parameter { - name := obj.Name() +// addResultVar adds a result for a variable v to f.results and v to f.returnVars. +func (f *Function) addResultVar(v *types.Var) { + result := emitLocalVar(f, v) + f.results = append(f.results, result) + f.returnVars = append(f.returnVars, v) +} + +// addParamVar adds a parameter to f.Params. +func (f *Function) addParamVar(v *types.Var) *Parameter { + name := v.Name() if name == "" { name = fmt.Sprintf("arg%d", len(f.Params)) } - param := f.addParam(name, f.typ(obj.Type()), obj.Pos()) - param.object = obj + param := &Parameter{ + name: name, + object: v, + typ: f.typ(v.Type()), + parent: f, + } + f.Params = append(f.Params, param) return param } // addSpilledParam declares a parameter that is pre-spilled to the // stack; the function body will load/store the spilled location. // Subsequent lifting will eliminate spills where possible. -func (f *Function) addSpilledParam(obj types.Object) { - param := f.addParamObj(obj) - spill := &Alloc{Comment: obj.Name()} - spill.setType(types.NewPointer(param.Type())) - spill.setPos(obj.Pos()) - f.objects[obj] = spill - f.Locals = append(f.Locals, spill) - f.emit(spill) +func (f *Function) addSpilledParam(obj *types.Var) { + param := f.addParamVar(obj) + spill := emitLocalVar(f, obj) f.emit(&Store{Addr: spill, Val: param}) } @@ -161,7 +222,7 @@ func (f *Function) addSpilledParam(obj types.Object) { // Precondition: f.Type() already set. func (f *Function) startBody() { f.currentBlock = f.newBasicBlock("entry") - f.objects = make(map[types.Object]Value) // needed for some synthetics, e.g. init + f.vars = make(map[*types.Var]Value) // needed for some synthetics, e.g. init } // createSyntacticParams populates f.Params and generates code (spills @@ -177,11 +238,11 @@ func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.Func if recv != nil { for _, field := range recv.List { for _, n := range field.Names { - f.addSpilledParam(f.info.Defs[n]) + f.addSpilledParam(identVar(f, n)) } // Anonymous receiver? No need to spill. if field.Names == nil { - f.addParamObj(f.Signature.Recv()) + f.addParamVar(f.Signature.Recv()) } } } @@ -191,26 +252,45 @@ func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.Func n := len(f.Params) // 1 if has recv, 0 otherwise for _, field := range functype.Params.List { for _, n := range field.Names { - f.addSpilledParam(f.info.Defs[n]) + f.addSpilledParam(identVar(f, n)) } // Anonymous parameter? No need to spill. if field.Names == nil { - f.addParamObj(f.Signature.Params().At(len(f.Params) - n)) + f.addParamVar(f.Signature.Params().At(len(f.Params) - n)) } } } - // Named results. + // Results. if functype.Results != nil { for _, field := range functype.Results.List { // Implicit "var" decl of locals for named results. for _, n := range field.Names { - f.namedResults = append(f.namedResults, f.addLocalForIdent(n)) + v := identVar(f, n) + f.addResultVar(v) + } + // Implicit "var" decl of local for an unnamed result. + if field.Names == nil { + v := f.Signature.Results().At(len(f.results)) + f.addResultVar(v) } } } } +// createDeferStack initializes fn.deferstack to local variable +// initialized to a ssa:deferstack() call. +func (fn *Function) createDeferStack() { + // Each syntactic function makes a call to ssa:deferstack, + // which is spilled to a local. Unused ones are later removed. + fn.deferstack = newVar("defer$stack", tDeferStack) + call := &Call{Call: CallCommon{Value: vDeferStack}} + call.setType(tDeferStack) + deferstack := fn.emit(call) + spill := emitLocalVar(fn, fn.deferstack) + emitStore(fn, spill, deferstack, token.NoPos) +} + type setNumable interface { setNum(int) } @@ -250,48 +330,16 @@ func buildReferrers(f *Function) { } } -// mayNeedRuntimeTypes returns all of the types in the body of fn that might need runtime types. -// -// EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu) -func mayNeedRuntimeTypes(fn *Function) []types.Type { - // Collect all types that may need rtypes, i.e. those that flow into an interface. - var ts []types.Type - for _, bb := range fn.Blocks { - for _, instr := range bb.Instrs { - if mi, ok := instr.(*MakeInterface); ok { - ts = append(ts, mi.X.Type()) - } - } - } - - // Types that contain a parameterized type are considered to not be runtime types. - if fn.typeparams.Len() == 0 { - return ts // No potentially parameterized types. - } - // Filter parameterized types, in place. - fn.Prog.methodsMu.Lock() - defer fn.Prog.methodsMu.Unlock() - filtered := ts[:0] - for _, t := range ts { - if !fn.Prog.parameterized.isParameterized(t) { - filtered = append(filtered, t) - } - } - return filtered -} - // finishBody() finalizes the contents of the function after SSA code generation of its body. // // The function is not done being built until done() is called. func (f *Function) finishBody() { - f.objects = nil f.currentBlock = nil f.lblocks = nil - - // Don't pin the AST in memory (except in debug mode). - if n := f.syntax; n != nil && !f.debugInfo() { - f.syntax = extentNode{n.Pos(), n.End()} - } + f.returnVars = nil + f.jump = nil + f.source = nil + f.exits = nil // Remove from f.Locals any Allocs that escape to the heap. j := 0 @@ -320,15 +368,17 @@ func (f *Function) finishBody() { lift(f) } - // clear remaining stateful variables - f.namedResults = nil // (used by lifting) - f.info = nil + // clear remaining builder state + f.results = nil // (used by lifting) + f.deferstack = nil // (used by lifting) + f.vars = nil // (used by lifting) f.subst = nil numberRegisters(f) // uses f.namedRegisters } -// After this, function is done with BUILD phase. +// done marks the building of f's SSA body complete, +// along with any nested functions, and optionally prints them. func (f *Function) done() { assert(f.parent == nil, "done called on an anonymous function") @@ -338,7 +388,8 @@ func (f *Function) done() { visit(anon) // anon is done building before f. } - f.built = true // function is done with BUILD phase + f.uniq = 0 // done with uniq + f.build = nil // function is built if f.Prog.mode&PrintFunctions != 0 { printMu.Lock() @@ -376,7 +427,6 @@ func (f *Function) removeNilBlocks() { // size of the instruction stream, and causes Functions to depend upon // the ASTs, potentially keeping them live in memory for longer. func (pkg *Package) SetDebugMode(debug bool) { - // TODO(adonovan): do we want ast.File granularity? pkg.debug = debug } @@ -387,40 +437,25 @@ func (f *Function) debugInfo() bool { return p != nil && p.debug } -// addNamedLocal creates a local variable, adds it to function f and -// returns it. Its name and type are taken from obj. Subsequent -// calls to f.lookup(obj) will return the same local. -func (f *Function) addNamedLocal(obj types.Object) *Alloc { - l := f.addLocal(obj.Type(), obj.Pos()) - l.Comment = obj.Name() - f.objects[obj] = l - return l -} - -func (f *Function) addLocalForIdent(id *ast.Ident) *Alloc { - return f.addNamedLocal(f.info.Defs[id]) -} - -// addLocal creates an anonymous local variable of type typ, adds it -// to function f and returns it. pos is the optional source location. -func (f *Function) addLocal(typ types.Type, pos token.Pos) *Alloc { - typ = f.typ(typ) - v := &Alloc{} - v.setType(types.NewPointer(typ)) - v.setPos(pos) - f.Locals = append(f.Locals, v) - f.emit(v) - return v -} - // lookup returns the address of the named variable identified by obj // that is local to function f or one of its enclosing functions. // If escaping, the reference comes from a potentially escaping pointer // expression and the referent must be heap-allocated. -func (f *Function) lookup(obj types.Object, escaping bool) Value { - if v, ok := f.objects[obj]; ok { - if alloc, ok := v.(*Alloc); ok && escaping { - alloc.Heap = true +// We assume the referent is a *Alloc or *Phi. +// (The only Phis at this stage are those created directly by go1.22 "for" loops.) +func (f *Function) lookup(obj *types.Var, escaping bool) Value { + if v, ok := f.vars[obj]; ok { + if escaping { + switch v := v.(type) { + case *Alloc: + v.Heap = true + case *Phi: + for _, edge := range v.Edges { + if alloc, ok := edge.(*Alloc); ok { + alloc.Heap = true + } + } + } } return v // function-local var (address) } @@ -438,7 +473,7 @@ func (f *Function) lookup(obj types.Object, escaping bool) Value { outer: outer, parent: f, } - f.objects[obj] = v + f.vars[obj] = v f.FreeVars = append(f.FreeVars, v) return v } @@ -536,7 +571,7 @@ func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *ty func (fn *Function) declaredPackage() *Package { switch { case fn.Pkg != nil: - return fn.Pkg // non-generic function + return fn.Pkg // non-generic function (does that follow??) case fn.topLevelOrigin != nil: return fn.topLevelOrigin.Pkg // instance of a named generic function case fn.parent != nil: @@ -596,7 +631,7 @@ func WriteFunction(buf *bytes.Buffer, f *Function) { if len(f.Locals) > 0 { buf.WriteString("# Locals:\n") for i, l := range f.Locals { - fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(mustDeref(l.Type()), from)) + fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(typeparams.MustDeref(l.Type()), from)) } } writeSignature(buf, from, f.Name(), f.Signature) @@ -651,6 +686,12 @@ func WriteFunction(buf *bytes.Buffer, f *Function) { default: buf.WriteString(instr.String()) } + // -mode=S: show line numbers + if f.Prog.mode&LogSource != 0 { + if pos := instr.Pos(); pos.IsValid() { + fmt.Fprintf(buf, " L%d", f.Prog.Fset.Position(pos).Line) + } + } buf.WriteString("\n") } } @@ -689,17 +730,87 @@ func (prog *Program) NewFunction(name string, sig *types.Signature, provenance s return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance} } -type extentNode [2]token.Pos +// Syntax returns the function's syntax (*ast.Func{Decl,Lit}) +// if it was produced from syntax or an *ast.RangeStmt if +// it is a range-over-func yield function. +func (f *Function) Syntax() ast.Node { return f.syntax } + +// identVar returns the variable defined by id. +func identVar(fn *Function, id *ast.Ident) *types.Var { + return fn.info.Defs[id].(*types.Var) +} -func (n extentNode) Pos() token.Pos { return n[0] } -func (n extentNode) End() token.Pos { return n[1] } +// unique returns a unique positive int within the source tree of f. +// The source tree of f includes all of f's ancestors by parent and all +// of the AnonFuncs contained within these. +func unique(f *Function) int64 { + f.uniq++ + return f.uniq +} -// Syntax returns an ast.Node whose Pos/End methods provide the -// lexical extent of the function if it was defined by Go source code -// (f.Synthetic==""), or nil otherwise. +// exit is a change of control flow going from a range-over-func +// yield function to an ancestor function caused by a break, continue, +// goto, or return statement. // -// If f was built with debug information (see Package.SetDebugRef), -// the result is the *ast.FuncDecl or *ast.FuncLit that declared the -// function. Otherwise, it is an opaque Node providing only position -// information; this avoids pinning the AST in memory. -func (f *Function) Syntax() ast.Node { return f.syntax } +// There are 3 types of exits: +// * return from the source function (from ReturnStmt), +// * jump to a block (from break and continue statements [labelled/unlabelled]), +// * go to a label (from goto statements). +// +// As the builder does one pass over the ast, it is unclear whether +// a forward goto statement will leave a range-over-func body. +// The function being exited to is unresolved until the end +// of building the range-over-func body. +type exit struct { + id int64 // unique value for exit within from and to + from *Function // the function the exit starts from + to *Function // the function being exited to (nil if unresolved) + pos token.Pos + + block *BasicBlock // basic block within to being jumped to. + label *types.Label // forward label being jumped to via goto. + // block == nil && label == nil => return +} + +// storeVar emits to function f code to store a value v to a *types.Var x. +func storeVar(f *Function, x *types.Var, v Value, pos token.Pos) { + emitStore(f, f.lookup(x, true), v, pos) +} + +// labelExit creates a new exit to a yield fn to exit the function using a label. +func labelExit(fn *Function, label *types.Label, pos token.Pos) *exit { + e := &exit{ + id: unique(fn), + from: fn, + to: nil, + pos: pos, + label: label, + } + fn.exits = append(fn.exits, e) + return e +} + +// blockExit creates a new exit to a yield fn that jumps to a basic block. +func blockExit(fn *Function, block *BasicBlock, pos token.Pos) *exit { + e := &exit{ + id: unique(fn), + from: fn, + to: block.parent, + pos: pos, + block: block, + } + fn.exits = append(fn.exits, e) + return e +} + +// blockExit creates a new exit to a yield fn that returns the source function. +func returnExit(fn *Function, pos token.Pos) *exit { + e := &exit{ + id: unique(fn), + from: fn, + to: fn.source, + pos: pos, + } + fn.exits = append(fn.exits, e) + return e +} diff --git a/tools/vendor/golang.org/x/tools/go/ssa/identical.go b/tools/vendor/golang.org/x/tools/go/ssa/identical.go deleted file mode 100644 index e8026967b..000000000 --- a/tools/vendor/golang.org/x/tools/go/ssa/identical.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.8 -// +build go1.8 - -package ssa - -import "go/types" - -var structTypesIdentical = types.IdenticalIgnoreTags diff --git a/tools/vendor/golang.org/x/tools/go/ssa/identical_17.go b/tools/vendor/golang.org/x/tools/go/ssa/identical_17.go deleted file mode 100644 index 575aa5dfc..000000000 --- a/tools/vendor/golang.org/x/tools/go/ssa/identical_17.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.8 -// +build !go1.8 - -package ssa - -import "go/types" - -var structTypesIdentical = types.Identical diff --git a/tools/vendor/golang.org/x/tools/go/ssa/instantiate.go b/tools/vendor/golang.org/x/tools/go/ssa/instantiate.go index 38249dea2..2512f3297 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/instantiate.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/instantiate.go @@ -6,130 +6,62 @@ package ssa import ( "fmt" - "go/ast" "go/types" - - "golang.org/x/tools/internal/typeparams" + "sync" ) -// _Instances returns all of the instances generated by runtime types for this function in an unspecified order. -// -// Thread-safe. -// -// This is an experimental interface! It may change without warning. -func (prog *Program) _Instances(fn *Function) []*Function { - if fn.typeparams.Len() == 0 || len(fn.typeargs) > 0 { - return nil - } - - prog.methodsMu.Lock() - defer prog.methodsMu.Unlock() - return prog.instances[fn].list() -} - -// A set of instantiations of a generic function fn. -type instanceSet struct { - fn *Function // fn.typeparams.Len() > 0 and len(fn.typeargs) == 0. - instances map[*typeList]*Function // canonical type arguments to an instance. - syntax *ast.FuncDecl // fn.syntax copy for instantiating after fn is done. nil on synthetic packages. - info *types.Info // fn.pkg.info copy for building after fn is done.. nil on synthetic packages. - - // TODO(taking): Consider ways to allow for clearing syntax and info when done building. - // May require a public API change as MethodValue can request these be built after prog.Build() is done. -} - -func (insts *instanceSet) list() []*Function { - if insts == nil { - return nil - } - - fns := make([]*Function, 0, len(insts.instances)) - for _, fn := range insts.instances { - fns = append(fns, fn) - } - return fns +// A generic records information about a generic origin function, +// including a cache of existing instantiations. +type generic struct { + instancesMu sync.Mutex + instances map[*typeList]*Function // canonical type arguments to an instance. } -// createInstanceSet adds a new instanceSet for a generic function fn if one does not exist. +// instance returns a Function that is the instantiation of generic +// origin function fn with the type arguments targs. // -// Precondition: fn is a package level declaration (function or method). +// Any created instance is added to cr. // -// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodMu) -func (prog *Program) createInstanceSet(fn *Function) { - assert(fn.typeparams.Len() > 0 && len(fn.typeargs) == 0, "Can only create instance sets for generic functions") - - prog.methodsMu.Lock() - defer prog.methodsMu.Unlock() - - syntax, _ := fn.syntax.(*ast.FuncDecl) - assert((syntax == nil) == (fn.syntax == nil), "fn.syntax is either nil or a *ast.FuncDecl") - - if _, ok := prog.instances[fn]; !ok { - prog.instances[fn] = &instanceSet{ - fn: fn, - syntax: syntax, - info: fn.info, +// Acquires fn.generic.instancesMu. +func (fn *Function) instance(targs []types.Type, b *builder) *Function { + key := fn.Prog.canon.List(targs) + + gen := fn.generic + + gen.instancesMu.Lock() + defer gen.instancesMu.Unlock() + inst, ok := gen.instances[key] + if !ok { + inst = createInstance(fn, targs) + inst.buildshared = b.shared() + b.enqueue(inst) + + if gen.instances == nil { + gen.instances = make(map[*typeList]*Function) } + gen.instances[key] = inst + } else { + b.waitForSharedFunction(inst) } + return inst } -// needsInstance returns a Function that is the instantiation of fn with the type arguments targs. -// -// Any CREATEd instance is added to cr. +// createInstance returns the instantiation of generic function fn using targs. // -// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodMu) -func (prog *Program) needsInstance(fn *Function, targs []types.Type, cr *creator) *Function { - prog.methodsMu.Lock() - defer prog.methodsMu.Unlock() - - return prog.lookupOrCreateInstance(fn, targs, cr) -} - -// lookupOrCreateInstance returns a Function that is the instantiation of fn with the type arguments targs. -// -// Any CREATEd instance is added to cr. -// -// EXCLUSIVE_LOCKS_REQUIRED(prog.methodMu) -func (prog *Program) lookupOrCreateInstance(fn *Function, targs []types.Type, cr *creator) *Function { - return prog.instances[fn].lookupOrCreate(targs, &prog.parameterized, cr) -} - -// lookupOrCreate returns the instantiation of insts.fn using targs. -// If the instantiation is created, this is added to cr. -func (insts *instanceSet) lookupOrCreate(targs []types.Type, parameterized *tpWalker, cr *creator) *Function { - if insts.instances == nil { - insts.instances = make(map[*typeList]*Function) - } - - fn := insts.fn +// Requires fn.generic.instancesMu. +func createInstance(fn *Function, targs []types.Type) *Function { prog := fn.Prog - // canonicalize on a tuple of targs. Sig is not unique. - // - // func A[T any]() { - // var x T - // fmt.Println("%T", x) - // } - key := prog.canon.List(targs) - if inst, ok := insts.instances[key]; ok { - return inst - } - - // CREATE instance/instantiation wrapper - var syntax ast.Node - if insts.syntax != nil { - syntax = insts.syntax - } - + // Compute signature. var sig *types.Signature var obj *types.Func if recv := fn.Signature.Recv(); recv != nil { // method - m := fn.object.(*types.Func) - obj = prog.canon.instantiateMethod(m, targs, prog.ctxt) + obj = prog.canon.instantiateMethod(fn.object, targs, prog.ctxt) sig = obj.Type().(*types.Signature) } else { - instSig, err := typeparams.Instantiate(prog.ctxt, fn.Signature, targs, false) + // function + instSig, err := types.Instantiate(prog.ctxt, fn.Signature, targs, false) if err != nil { panic(err) } @@ -137,41 +69,63 @@ func (insts *instanceSet) lookupOrCreate(targs []types.Type, parameterized *tpWa if !ok { panic("Instantiate of a Signature returned a non-signature") } - obj = fn.object.(*types.Func) // instantiation does not exist yet + obj = fn.object // instantiation does not exist yet sig = prog.canon.Type(instance).(*types.Signature) } - var synthetic string - var subst *subster - - concrete := !parameterized.anyParameterized(targs) - - if prog.mode&InstantiateGenerics != 0 && concrete { + // Choose strategy (instance or wrapper). + var ( + synthetic string + subst *subster + build buildFunc + ) + if prog.mode&InstantiateGenerics != 0 && !prog.isParameterized(targs...) { synthetic = fmt.Sprintf("instance of %s", fn.Name()) - scope := typeparams.OriginMethod(obj).Scope() - subst = makeSubster(prog.ctxt, scope, fn.typeparams, targs, false) + if fn.syntax != nil { + subst = makeSubster(prog.ctxt, obj, fn.typeparams, targs, false) + build = (*builder).buildFromSyntax + } else { + build = (*builder).buildParamsOnly + } } else { synthetic = fmt.Sprintf("instantiation wrapper of %s", fn.Name()) + build = (*builder).buildInstantiationWrapper } - name := fmt.Sprintf("%s%s", fn.Name(), targs) // may not be unique - instance := &Function{ - name: name, + /* generic instance or instantiation wrapper */ + return &Function{ + name: fmt.Sprintf("%s%s", fn.Name(), targs), // may not be unique object: obj, Signature: sig, Synthetic: synthetic, - syntax: syntax, + syntax: fn.syntax, // \ + info: fn.info, // } empty for non-created packages + goversion: fn.goversion, // / + build: build, topLevelOrigin: fn, pos: obj.Pos(), Pkg: nil, Prog: fn.Prog, typeparams: fn.typeparams, // share with origin typeargs: targs, - info: insts.info, // on synthetic packages info is nil. subst: subst, } +} - cr.Add(instance) - insts.instances[key] = instance - return instance +// isParameterized reports whether any of the specified types contains +// a free type parameter. It is safe to call concurrently. +func (prog *Program) isParameterized(ts ...types.Type) bool { + prog.hasParamsMu.Lock() + defer prog.hasParamsMu.Unlock() + + // TODO(adonovan): profile. If this operation is expensive, + // handle the most common but shallow cases such as T, pkg.T, + // *T without consulting the cache under the lock. + + for _, t := range ts { + if prog.hasParams.Has(t) { + return true + } + } + return false } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/lift.go b/tools/vendor/golang.org/x/tools/go/ssa/lift.go index dbd8790c6..aada3dc32 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/lift.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/lift.go @@ -43,6 +43,8 @@ import ( "go/token" "math/big" "os" + + "golang.org/x/tools/internal/typeparams" ) // If true, show diagnostic information at each step of lifting. @@ -103,9 +105,14 @@ func buildDomFrontier(fn *Function) domFrontier { } func removeInstr(refs []Instruction, instr Instruction) []Instruction { + return removeInstrsIf(refs, func(i Instruction) bool { return i == instr }) +} + +func removeInstrsIf(refs []Instruction, p func(Instruction) bool) []Instruction { + // TODO(taking): replace with go1.22 slices.DeleteFunc. i := 0 for _, ref := range refs { - if ref == instr { + if p(ref) { continue } refs[i] = ref @@ -168,9 +175,16 @@ func lift(fn *Function) { // for the block, reusing the original array if space permits. // While we're here, we also eliminate 'rundefers' - // instructions in functions that contain no 'defer' - // instructions. + // instructions and ssa:deferstack() in functions that contain no + // 'defer' instructions. For now, we also eliminate + // 's = ssa:deferstack()' calls if s doesn't escape, replacing s + // with nil in Defer{DeferStack: s}. This has the same meaning, + // but allows eliminating the intrinsic function `ssa:deferstack()` + // (unless it is needed due to range-over-func instances). This gives + // ssa users more time to support range-over-func. usesDefer := false + deferstackAlloc, deferstackCall := deferstackPreamble(fn) + eliminateDeferStack := deferstackAlloc != nil && !deferstackAlloc.Heap // A counter used to generate ~unique ids for Phi nodes, as an // aid to debugging. We use large numbers to make them highly @@ -194,6 +208,15 @@ func lift(fn *Function) { instr.index = index case *Defer: usesDefer = true + if eliminateDeferStack { + // Clear DeferStack and remove references to loads + if instr.DeferStack != nil { + if refs := instr.DeferStack.Referrers(); refs != nil { + *refs = removeInstr(*refs, instr) + } + instr.DeferStack = nil + } + } case *RunDefers: b.rundefers++ } @@ -213,6 +236,18 @@ func lift(fn *Function) { // Eliminate dead φ-nodes. removeDeadPhis(fn.Blocks, newPhis) + // Eliminate ssa:deferstack() call. + if eliminateDeferStack { + b := deferstackCall.block + for i, instr := range b.Instrs { + if instr == deferstackCall { + b.Instrs[i] = nil + b.gaps++ + break + } + } + } + // Prepend remaining live φ-nodes to each block. for _, b := range fn.Blocks { nps := newPhis[b] @@ -380,10 +415,10 @@ type newPhiMap map[*BasicBlock][]newPhi // // fresh is a source of fresh ids for phi nodes. func liftAlloc(df domFrontier, alloc *Alloc, newPhis newPhiMap, fresh *int) bool { - // Don't lift named return values in functions that defer + // Don't lift result values in functions that defer // calls that may recover from panic. if fn := alloc.Parent(); fn.Recover != nil { - for _, nr := range fn.namedResults { + for _, nr := range fn.results { if nr == alloc { return false } @@ -460,7 +495,7 @@ func liftAlloc(df domFrontier, alloc *Alloc, newPhis newPhiMap, fresh *int) bool *fresh++ phi.pos = alloc.Pos() - phi.setType(mustDeref(alloc.Type())) + phi.setType(typeparams.MustDeref(alloc.Type())) phi.block = v if debugLifting { fmt.Fprintf(os.Stderr, "\tplace %s = %s at block %s\n", phi.Name(), phi, v) @@ -505,7 +540,7 @@ func replaceAll(x, y Value) { func renamed(renaming []Value, alloc *Alloc) Value { v := renaming[alloc.index] if v == nil { - v = zeroConst(mustDeref(alloc.Type())) + v = zeroConst(typeparams.MustDeref(alloc.Type())) renaming[alloc.index] = v } return v @@ -637,3 +672,17 @@ func rename(u *BasicBlock, renaming []Value, newPhis newPhiMap) { } } + +// deferstackPreamble returns the *Alloc and ssa:deferstack() call for fn.deferstack. +func deferstackPreamble(fn *Function) (*Alloc, *Call) { + if alloc, _ := fn.vars[fn.deferstack].(*Alloc); alloc != nil { + for _, ref := range *alloc.Referrers() { + if ref, _ := ref.(*Store); ref != nil && ref.Addr == alloc { + if call, _ := ref.Val.(*Call); call != nil { + return alloc, call + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/golang.org/x/tools/go/ssa/lvalue.go b/tools/vendor/golang.org/x/tools/go/ssa/lvalue.go index 186cfcae7..eede307ea 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/lvalue.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/lvalue.go @@ -11,6 +11,8 @@ import ( "go/ast" "go/token" "go/types" + + "golang.org/x/tools/internal/typeparams" ) // An lvalue represents an assignable location that may appear on the @@ -52,7 +54,7 @@ func (a *address) address(fn *Function) Value { } func (a *address) typ() types.Type { - return mustDeref(a.addr.Type()) + return typeparams.MustDeref(a.addr.Type()) } // An element is an lvalue represented by m[k], the location of an diff --git a/tools/vendor/golang.org/x/tools/go/ssa/methods.go b/tools/vendor/golang.org/x/tools/go/ssa/methods.go index 294498371..b9560183a 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/methods.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/methods.go @@ -10,54 +10,129 @@ import ( "fmt" "go/types" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/aliases" ) // MethodValue returns the Function implementing method sel, building -// wrapper methods on demand. It returns nil if sel denotes an -// abstract (interface or parameterized) method. +// wrapper methods on demand. It returns nil if sel denotes an +// interface or generic method. // // Precondition: sel.Kind() == MethodVal. // // Thread-safe. // -// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) +// Acquires prog.methodsMu. func (prog *Program) MethodValue(sel *types.Selection) *Function { if sel.Kind() != types.MethodVal { panic(fmt.Sprintf("MethodValue(%s) kind != MethodVal", sel)) } T := sel.Recv() if types.IsInterface(T) { - return nil // abstract method (interface, possibly type param) + return nil // interface method or type parameter } + + if prog.isParameterized(T) { + return nil // generic method + } + if prog.mode&LogSource != 0 { defer logStack("MethodValue %s %v", T, sel)() } - var m *Function - b := builder{created: &creator{}} + var b builder + + m := func() *Function { + prog.methodsMu.Lock() + defer prog.methodsMu.Unlock() + + // Get or create SSA method set. + mset, ok := prog.methodSets.At(T).(*methodSet) + if !ok { + mset = &methodSet{mapping: make(map[string]*Function)} + prog.methodSets.Set(T, mset) + } + + // Get or create SSA method. + id := sel.Obj().Id() + fn, ok := mset.mapping[id] + if !ok { + obj := sel.Obj().(*types.Func) + needsPromotion := len(sel.Index()) > 1 + needsIndirection := !isPointer(recvType(obj)) && isPointer(T) + if needsPromotion || needsIndirection { + fn = createWrapper(prog, toSelection(sel)) + fn.buildshared = b.shared() + b.enqueue(fn) + } else { + fn = prog.objectMethod(obj, &b) + } + if fn.Signature.Recv() == nil { + panic(fn) + } + mset.mapping[id] = fn + } else { + b.waitForSharedFunction(fn) + } + + return fn + }() + + b.iterate() + + return m +} + +// objectMethod returns the Function for a given method symbol. +// The symbol may be an instance of a generic function. It need not +// belong to an existing SSA package created by a call to +// prog.CreatePackage. +// +// objectMethod panics if the function is not a method. +// +// Acquires prog.objectMethodsMu. +func (prog *Program) objectMethod(obj *types.Func, b *builder) *Function { + sig := obj.Type().(*types.Signature) + if sig.Recv() == nil { + panic("not a method: " + obj.String()) + } - prog.methodsMu.Lock() - // Checks whether a type param is reachable from T. - // This is an expensive check. May need to be optimized later. - if !prog.parameterized.isParameterized(T) { - m = prog.addMethod(prog.createMethodSet(T), sel, b.created) + // Belongs to a created package? + if fn := prog.FuncValue(obj); fn != nil { + return fn } - prog.methodsMu.Unlock() - if m == nil { - return nil // abstract method (generic) + // Instantiation of generic? + if originObj := obj.Origin(); originObj != obj { + origin := prog.objectMethod(originObj, b) + assert(origin.typeparams.Len() > 0, "origin is not generic") + targs := receiverTypeArgs(obj) + return origin.instance(targs, b) } - for !b.done() { - b.buildCreated() - b.needsRuntimeTypes() + + // Consult/update cache of methods created from types.Func. + prog.objectMethodsMu.Lock() + defer prog.objectMethodsMu.Unlock() + fn, ok := prog.objectMethods[obj] + if !ok { + fn = createFunction(prog, obj, obj.Name(), nil, nil, "") + fn.Synthetic = "from type information (on demand)" + fn.buildshared = b.shared() + b.enqueue(fn) + + if prog.objectMethods == nil { + prog.objectMethods = make(map[*types.Func]*Function) + } + prog.objectMethods[obj] = fn + } else { + b.waitForSharedFunction(fn) } - return m + return fn } // LookupMethod returns the implementation of the method of type T // identified by (pkg, name). It returns nil if the method exists but -// is abstract, and panics if T has no such method. +// is an interface method or generic method, and panics if T has no such method. func (prog *Program) LookupMethod(T types.Type, pkg *types.Package, name string) *Function { sel := prog.MethodSets.MethodSet(T).Lookup(pkg, name) if sel == nil { @@ -68,208 +143,139 @@ func (prog *Program) LookupMethod(T types.Type, pkg *types.Package, name string) // methodSet contains the (concrete) methods of a concrete type (non-interface, non-parameterized). type methodSet struct { - mapping map[string]*Function // populated lazily - complete bool // mapping contains all methods + mapping map[string]*Function // populated lazily } -// Precondition: T is a concrete type, e.g. !isInterface(T) and not parameterized. -// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) -func (prog *Program) createMethodSet(T types.Type) *methodSet { - if prog.mode&SanityCheckFunctions != 0 { - if types.IsInterface(T) || prog.parameterized.isParameterized(T) { - panic("type is interface or parameterized") - } - } - mset, ok := prog.methodSets.At(T).(*methodSet) - if !ok { - mset = &methodSet{mapping: make(map[string]*Function)} - prog.methodSets.Set(T, mset) - } - return mset -} - -// Adds any created functions to cr. -// Precondition: T is a concrete type, e.g. !isInterface(T) and not parameterized. -// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) -func (prog *Program) addMethod(mset *methodSet, sel *types.Selection, cr *creator) *Function { - if sel.Kind() == types.MethodExpr { - panic(sel) - } - id := sel.Obj().Id() - fn := mset.mapping[id] - if fn == nil { - sel := toSelection(sel) - obj := sel.obj.(*types.Func) - - _, ptrObj := deptr(recvType(obj)) - _, ptrRecv := deptr(sel.recv) - - needsPromotion := len(sel.index) > 1 - needsIndirection := !ptrObj && ptrRecv - if needsPromotion || needsIndirection { - fn = makeWrapper(prog, sel, cr) - } else { - fn = prog.originFunc(obj) - if fn.typeparams.Len() > 0 { // instantiate - targs := receiverTypeArgs(obj) - fn = prog.lookupOrCreateInstance(fn, targs, cr) - } - } - if fn.Signature.Recv() == nil { - panic(fn) // missing receiver - } - mset.mapping[id] = fn - } - return fn -} - -// RuntimeTypes returns a new unordered slice containing all -// concrete types in the program for which a complete (non-empty) -// method set is required at run-time. +// RuntimeTypes returns a new unordered slice containing all types in +// the program for which a runtime type is required. +// +// A runtime type is required for any non-parameterized, non-interface +// type that is converted to an interface, or for any type (including +// interface types) derivable from one through reflection. +// +// The methods of such types may be reachable through reflection or +// interface calls even if they are never called directly. // // Thread-safe. // -// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) +// Acquires prog.runtimeTypesMu. func (prog *Program) RuntimeTypes() []types.Type { - prog.methodsMu.Lock() - defer prog.methodsMu.Unlock() - - var res []types.Type - prog.methodSets.Iterate(func(T types.Type, v interface{}) { - if v.(*methodSet).complete { - res = append(res, T) - } - }) - return res -} - -// declaredFunc returns the concrete function/method denoted by obj. -// Panic ensues if there is none. -func (prog *Program) declaredFunc(obj *types.Func) *Function { - if v := prog.packageLevelMember(obj); v != nil { - return v.(*Function) - } - panic("no concrete method: " + obj.String()) + prog.runtimeTypesMu.Lock() + defer prog.runtimeTypesMu.Unlock() + return prog.runtimeTypes.Keys() } -// needMethodsOf ensures that runtime type information (including the -// complete method set) is available for the specified type T and all -// its subcomponents. -// -// needMethodsOf must be called for at least every type that is an -// operand of some MakeInterface instruction, and for the type of -// every exported package member. -// -// Adds any created functions to cr. -// -// Precondition: T is not a method signature (*Signature with Recv()!=nil). -// Precondition: T is not parameterized. +// forEachReachable calls f for type T and each type reachable from +// its type through reflection. // -// Thread-safe. (Called via Package.build from multiple builder goroutines.) +// The function f must use memoization to break cycles and +// return false when the type has already been visited. // -// TODO(adonovan): make this faster. It accounts for 20% of SSA build time. -// -// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) -func (prog *Program) needMethodsOf(T types.Type, cr *creator) { - prog.methodsMu.Lock() - prog.needMethods(T, false, cr) - prog.methodsMu.Unlock() -} - -// Precondition: T is not a method signature (*Signature with Recv()!=nil). -// Precondition: T is not parameterized. -// Recursive case: skip => don't create methods for T. -// -// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) -func (prog *Program) needMethods(T types.Type, skip bool, cr *creator) { - // Each package maintains its own set of types it has visited. - if prevSkip, ok := prog.runtimeTypes.At(T).(bool); ok { - // needMethods(T) was previously called - if !prevSkip || skip { - return // already seen, with same or false 'skip' value - } - } - prog.runtimeTypes.Set(T, skip) - - tmset := prog.MethodSets.MethodSet(T) - - if !skip && !types.IsInterface(T) && tmset.Len() > 0 { - // Create methods of T. - mset := prog.createMethodSet(T) - if !mset.complete { - mset.complete = true - n := tmset.Len() - for i := 0; i < n; i++ { - prog.addMethod(mset, tmset.At(i), cr) +// TODO(adonovan): publish in typeutil and share with go/callgraph/rta. +func forEachReachable(msets *typeutil.MethodSetCache, T types.Type, f func(types.Type) bool) { + var visit func(T types.Type, skip bool) + visit = func(T types.Type, skip bool) { + if !skip { + if !f(T) { + return } } - } - // Recursion over signatures of each method. - for i := 0; i < tmset.Len(); i++ { - sig := tmset.At(i).Type().(*types.Signature) - prog.needMethods(sig.Params(), false, cr) - prog.needMethods(sig.Results(), false, cr) - } + // Recursion over signatures of each method. + tmset := msets.MethodSet(T) + for i := 0; i < tmset.Len(); i++ { + sig := tmset.At(i).Type().(*types.Signature) + // It is tempting to call visit(sig, false) + // but, as noted in golang.org/cl/65450043, + // the Signature.Recv field is ignored by + // types.Identical and typeutil.Map, which + // is confusing at best. + // + // More importantly, the true signature rtype + // reachable from a method using reflection + // has no receiver but an extra ordinary parameter. + // For the Read method of io.Reader we want: + // func(Reader, []byte) (int, error) + // but here sig is: + // func([]byte) (int, error) + // with .Recv = Reader (though it is hard to + // notice because it doesn't affect Signature.String + // or types.Identical). + // + // TODO(adonovan): construct and visit the correct + // non-method signature with an extra parameter + // (though since unnamed func types have no methods + // there is essentially no actual demand for this). + // + // TODO(adonovan): document whether or not it is + // safe to skip non-exported methods (as RTA does). + visit(sig.Params(), true) // skip the Tuple + visit(sig.Results(), true) // skip the Tuple + } - switch t := T.(type) { - case *types.Basic: - // nop + switch T := T.(type) { + case *aliases.Alias: + visit(aliases.Unalias(T), skip) // emulates the pre-Alias behavior - case *types.Interface: - // nop---handled by recursion over method set. + case *types.Basic: + // nop - case *types.Pointer: - prog.needMethods(t.Elem(), false, cr) + case *types.Interface: + // nop---handled by recursion over method set. - case *types.Slice: - prog.needMethods(t.Elem(), false, cr) + case *types.Pointer: + visit(T.Elem(), false) - case *types.Chan: - prog.needMethods(t.Elem(), false, cr) + case *types.Slice: + visit(T.Elem(), false) - case *types.Map: - prog.needMethods(t.Key(), false, cr) - prog.needMethods(t.Elem(), false, cr) + case *types.Chan: + visit(T.Elem(), false) - case *types.Signature: - if t.Recv() != nil { - panic(fmt.Sprintf("Signature %s has Recv %s", t, t.Recv())) - } - prog.needMethods(t.Params(), false, cr) - prog.needMethods(t.Results(), false, cr) - - case *types.Named: - // A pointer-to-named type can be derived from a named - // type via reflection. It may have methods too. - prog.needMethods(types.NewPointer(T), false, cr) - - // Consider 'type T struct{S}' where S has methods. - // Reflection provides no way to get from T to struct{S}, - // only to S, so the method set of struct{S} is unwanted, - // so set 'skip' flag during recursion. - prog.needMethods(t.Underlying(), true, cr) - - case *types.Array: - prog.needMethods(t.Elem(), false, cr) - - case *types.Struct: - for i, n := 0, t.NumFields(); i < n; i++ { - prog.needMethods(t.Field(i).Type(), false, cr) - } + case *types.Map: + visit(T.Key(), false) + visit(T.Elem(), false) - case *types.Tuple: - for i, n := 0, t.Len(); i < n; i++ { - prog.needMethods(t.At(i).Type(), false, cr) - } + case *types.Signature: + if T.Recv() != nil { + panic(fmt.Sprintf("Signature %s has Recv %s", T, T.Recv())) + } + visit(T.Params(), true) // skip the Tuple + visit(T.Results(), true) // skip the Tuple + + case *types.Named: + // A pointer-to-named type can be derived from a named + // type via reflection. It may have methods too. + visit(types.NewPointer(T), false) + + // Consider 'type T struct{S}' where S has methods. + // Reflection provides no way to get from T to struct{S}, + // only to S, so the method set of struct{S} is unwanted, + // so set 'skip' flag during recursion. + visit(T.Underlying(), true) // skip the unnamed type + + case *types.Array: + visit(T.Elem(), false) + + case *types.Struct: + for i, n := 0, T.NumFields(); i < n; i++ { + // TODO(adonovan): document whether or not + // it is safe to skip non-exported fields. + visit(T.Field(i).Type(), false) + } - case *typeparams.TypeParam: - panic(T) // type parameters are always abstract. + case *types.Tuple: + for i, n := 0, T.Len(); i < n; i++ { + visit(T.At(i).Type(), false) + } - case *typeparams.Union: - // nop + case *types.TypeParam, *types.Union: + // forEachReachable must not be called on parameterized types. + panic(T) - default: - panic(T) + default: + panic(T) + } } + visit(T, false) } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/print.go b/tools/vendor/golang.org/x/tools/go/ssa/print.go index 7f34a7b58..c890d7ee5 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/print.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/print.go @@ -39,7 +39,7 @@ func relName(v Value, i Instruction) string { return v.Name() } -// normalizeAnyFortesting controls whether we replace occurrences of +// normalizeAnyForTesting controls whether we replace occurrences of // interface{} with any. It is only used for normalizing test output. var normalizeAnyForTesting bool @@ -51,7 +51,7 @@ func relType(t types.Type, from *types.Package) string { return s } -func relTerm(term *typeparams.Term, from *types.Package) string { +func relTerm(term *types.Term, from *types.Package) string { s := relType(term.Type(), from) if term.Tilde() { return "~" + s @@ -95,7 +95,7 @@ func (v *Alloc) String() string { op = "new" } from := v.Parent().relPkg() - return fmt.Sprintf("%s %s (%s)", op, relType(mustDeref(v.Type()), from), v.Comment) + return fmt.Sprintf("%s %s (%s)", op, relType(typeparams.MustDeref(v.Type()), from), v.Comment) } func (v *Phi) String() string { @@ -261,7 +261,7 @@ func (v *MakeChan) String() string { func (v *FieldAddr) String() string { // Be robust against a bad index. name := "?" - if fld := fieldOf(mustDeref(v.X.Type()), v.Field); fld != nil { + if fld := fieldOf(typeparams.MustDeref(v.X.Type()), v.Field); fld != nil { name = fld.Name() } return fmt.Sprintf("&%s.%s [#%d]", relName(v.X, v), name, v.Field) @@ -355,7 +355,12 @@ func (s *Send) String() string { } func (s *Defer) String() string { - return printCall(&s.Call, "defer ", s) + prefix := "defer " + if s.DeferStack != nil { + prefix += "[" + relName(s.DeferStack, s) + "] " + } + c := printCall(&s.Call, prefix, s) + return c } func (s *Select) String() string { @@ -450,7 +455,7 @@ func WritePackage(buf *bytes.Buffer, p *Package) { case *Global: fmt.Fprintf(buf, " var %-*s %s\n", - maxname, name, relType(mustDeref(mem.Type()), from)) + maxname, name, relType(typeparams.MustDeref(mem.Type()), from)) } } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/sanity.go b/tools/vendor/golang.org/x/tools/go/ssa/sanity.go index 886be0532..285cba04a 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/sanity.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/sanity.go @@ -10,6 +10,7 @@ package ssa import ( "bytes" "fmt" + "go/ast" "go/types" "io" "os" @@ -20,7 +21,7 @@ type sanity struct { reporter io.Writer fn *Function block *BasicBlock - instrs map[Instruction]struct{} + instrs map[Instruction]unit insane bool } @@ -132,6 +133,11 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { case *BinOp: case *Call: + if common := instr.Call; common.IsInvoke() { + if !types.IsInterface(common.Value.Type()) { + s.errorf("invoke on %s (%s) which is not an interface type (or type param)", common.Value, common.Value.Type()) + } + } case *ChangeInterface: case *ChangeType: case *SliceToArrayPointer: @@ -194,7 +200,7 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { t := v.Type() if t == nil { s.errorf("no type: %s = %s", v.Name(), v) - } else if t == tRangeIter { + } else if t == tRangeIter || t == tDeferStack { // not a proper type; ignore. } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 { s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t) @@ -344,7 +350,7 @@ func (s *sanity) checkBlock(b *BasicBlock, index int) { // Check that "untyped" types only appear on constant operands. if _, ok := (*op).(*Const); !ok { - if basic, ok := (*op).Type().(*types.Basic); ok { + if basic, ok := (*op).Type().Underlying().(*types.Basic); ok { if basic.Info()&types.IsUntyped != 0 { s.errorf("operand #%d of %s is untyped: %s", i, instr, basic) } @@ -422,7 +428,8 @@ func (s *sanity) checkFunction(fn *Function) bool { // shared across packages, or duplicated as weak symbols in a // separate-compilation model), and error.Error. if fn.Pkg == nil { - if strings.HasPrefix(fn.Synthetic, "wrapper ") || + if strings.HasPrefix(fn.Synthetic, "from type information (on demand)") || + strings.HasPrefix(fn.Synthetic, "wrapper ") || strings.HasPrefix(fn.Synthetic, "bound ") || strings.HasPrefix(fn.Synthetic, "thunk ") || strings.HasSuffix(fn.name, "Error") || @@ -439,6 +446,8 @@ func (s *sanity) checkFunction(fn *Function) bool { // ok (instantiation with InstantiateGenerics on) } else if fn.topLevelOrigin != nil && len(fn.typeargs) > 0 { // ok (we always have the syntax set for instantiation) + } else if _, rng := fn.syntax.(*ast.RangeStmt); rng && fn.Synthetic == "range-over-func yield" { + // ok (range-func-yields are both synthetic and keep syntax) } else { s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn) } @@ -452,10 +461,10 @@ func (s *sanity) checkFunction(fn *Function) bool { } } // Build the set of valid referrers. - s.instrs = make(map[Instruction]struct{}) + s.instrs = make(map[Instruction]unit) for _, b := range fn.Blocks { for _, instr := range b.Instrs { - s.instrs[instr] = struct{}{} + s.instrs[instr] = unit{} } } for i, p := range fn.Params { diff --git a/tools/vendor/golang.org/x/tools/go/ssa/source.go b/tools/vendor/golang.org/x/tools/go/ssa/source.go index 9c900e3aa..7b71c88d1 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/source.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/source.go @@ -14,8 +14,6 @@ import ( "go/ast" "go/token" "go/types" - - "golang.org/x/tools/internal/typeparams" ) // EnclosingFunction returns the function that contains the syntax @@ -122,7 +120,7 @@ func findNamedFunc(pkg *Package, pos token.Pos) *Function { obj := mset.At(i).Obj().(*types.Func) if obj.Pos() == pos { // obj from MethodSet may not be the origin type. - m := typeparams.OriginMethod(obj) + m := obj.Origin() return pkg.objects[m].(*Function) } } @@ -172,16 +170,19 @@ func (f *Function) ValueForExpr(e ast.Expr) (value Value, isAddr bool) { // --- Lookup functions for source-level named entities (types.Objects) --- // Package returns the SSA Package corresponding to the specified -// type-checker package object. -// It returns nil if no such SSA package has been created. -func (prog *Program) Package(obj *types.Package) *Package { - return prog.packages[obj] +// type-checker package. It returns nil if no such Package was +// created by a prior call to prog.CreatePackage. +func (prog *Program) Package(pkg *types.Package) *Package { + return prog.packages[pkg] } -// packageLevelMember returns the package-level member corresponding to -// the specified named object, which may be a package-level const -// (*NamedConst), var (*Global) or func (*Function) of some package in -// prog. It returns nil if the object is not found. +// packageLevelMember returns the package-level member corresponding +// to the specified symbol, which may be a package-level const +// (*NamedConst), var (*Global) or func/method (*Function) of some +// package in prog. +// +// It returns nil if the object belongs to a package that has not been +// created by prog.CreatePackage. func (prog *Program) packageLevelMember(obj types.Object) Member { if pkg, ok := prog.packages[obj.Pkg()]; ok { return pkg.objects[obj] @@ -189,24 +190,16 @@ func (prog *Program) packageLevelMember(obj types.Object) Member { return nil } -// originFunc returns the package-level generic function that is the -// origin of obj. If returns nil if the generic function is not found. -func (prog *Program) originFunc(obj *types.Func) *Function { - return prog.declaredFunc(typeparams.OriginMethod(obj)) -} - -// FuncValue returns the concrete Function denoted by the source-level -// named function obj, or nil if obj denotes an interface method. -// -// TODO(adonovan): check the invariant that obj.Type() matches the -// result's Signature, both in the params/results and in the receiver. +// FuncValue returns the SSA function or (non-interface) method +// denoted by the specified func symbol. It returns nil id the symbol +// denotes an interface method, or belongs to a package that was not +// created by prog.CreatePackage. func (prog *Program) FuncValue(obj *types.Func) *Function { fn, _ := prog.packageLevelMember(obj).(*Function) return fn } -// ConstValue returns the SSA Value denoted by the source-level named -// constant obj. +// ConstValue returns the SSA constant denoted by the specified const symbol. func (prog *Program) ConstValue(obj *types.Const) *Const { // TODO(adonovan): opt: share (don't reallocate) // Consts for const objects and constant ast.Exprs. @@ -223,7 +216,7 @@ func (prog *Program) ConstValue(obj *types.Const) *Const { } // VarValue returns the SSA Value that corresponds to a specific -// identifier denoting the source-level named variable obj. +// identifier denoting the specified var symbol. // // VarValue returns nil if a local variable was not found, perhaps // because its package was not built, the debug information was not diff --git a/tools/vendor/golang.org/x/tools/go/ssa/ssa.go b/tools/vendor/golang.org/x/tools/go/ssa/ssa.go index bd42f2e0a..1231afd9e 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/ssa.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/ssa.go @@ -23,20 +23,27 @@ import ( type Program struct { Fset *token.FileSet // position information for the files of this Program imported map[string]*Package // all importable Packages, keyed by import path - packages map[*types.Package]*Package // all loaded Packages, keyed by object + packages map[*types.Package]*Package // all created Packages mode BuilderMode // set of mode bits for SSA construction MethodSets typeutil.MethodSetCache // cache of type-checker's method-sets - canon *canonizer // type canonicalization map - ctxt *typeparams.Context // cache for type checking instantiations + canon *canonizer // type canonicalization map + ctxt *types.Context // cache for type checking instantiations - methodsMu sync.Mutex // guards the following maps: - methodSets typeutil.Map // maps type to its concrete methodSet - runtimeTypes typeutil.Map // types for which rtypes are needed - bounds map[boundsKey]*Function // bounds for curried x.Method closures - thunks map[selectionKey]*Function // thunks for T.Method expressions - instances map[*Function]*instanceSet // instances of generic functions - parameterized tpWalker // determines whether a type reaches a type parameter. + methodsMu sync.Mutex + methodSets typeutil.Map // maps type to its concrete *methodSet + + // memoization of whether a type refers to type parameters + hasParamsMu sync.Mutex + hasParams typeparams.Free + + runtimeTypesMu sync.Mutex + runtimeTypes typeutil.Map // set of runtime types (from MakeInterface) + + // objectMethods is a memoization of objectMethod + // to avoid creation of duplicate methods from type information. + objectMethodsMu sync.Mutex + objectMethods map[*types.Func]*Function } // A Package is a single analyzed Go package containing Members for @@ -51,17 +58,19 @@ type Package struct { Prog *Program // the owning program Pkg *types.Package // the corresponding go/types.Package Members map[string]Member // all package members keyed by name (incl. init and init#%d) - objects map[types.Object]Member // mapping of package objects to members (incl. methods). Contains *NamedConst, *Global, *Function. + objects map[types.Object]Member // mapping of package objects to members (incl. methods). Contains *NamedConst, *Global, *Function (values but not types) init *Function // Func("init"); the package's init function debug bool // include full debug info in this package + syntax bool // package was loaded from syntax // The following fields are set transiently, then cleared // after building. - buildOnce sync.Once // ensures package building occurs once - ninit int32 // number of init functions - info *types.Info // package type information - files []*ast.File // package ASTs - created creator // members created as a result of building this package (includes declared functions, wrappers) + buildOnce sync.Once // ensures package building occurs once + ninit int32 // number of init functions + info *types.Info // package type information + files []*ast.File // package ASTs + created []*Function // members created as a result of building this package (includes declared functions, wrappers) + initVersion map[ast.Expr]string // goversion to use for each global var init expr } // A Member is a member of a Go package, implemented by *NamedConst, @@ -288,16 +297,35 @@ type Node interface { // // Pos() returns the declaring ast.FuncLit.Type.Func or the position // of the ast.FuncDecl.Name, if the function was explicit in the -// source. Synthetic wrappers, for which Synthetic != "", may share +// source. Synthetic wrappers, for which Synthetic != "", may share // the same position as the function they wrap. // Syntax.Pos() always returns the position of the declaring "func" token. // +// When the operand of a range statement is an iterator function, +// the loop body is transformed into a synthetic anonymous function +// that is passed as the yield argument in a call to the iterator. +// In that case, Function.Pos is the position of the "range" token, +// and Function.Syntax is the ast.RangeStmt. +// +// Synthetic functions, for which Synthetic != "", are functions +// that do not appear in the source AST. These include: +// - method wrappers, +// - thunks, +// - bound functions, +// - empty functions built from loaded type information, +// - yield functions created from range-over-func loops, +// - package init functions, and +// - instantiations of generic functions. +// +// Synthetic wrapper functions may share the same position +// as the function they wrap. +// // Type() returns the function's Signature. // // A generic function is a function or method that has uninstantiated type // parameters (TypeParams() != nil). Consider a hypothetical generic -// method, (*Map[K,V]).Get. It may be instantiated with all ground -// (non-parameterized) types as (*Map[string,int]).Get or with +// method, (*Map[K,V]).Get. It may be instantiated with all +// non-parameterized types as (*Map[string,int]).Get or with // parameterized types as (*Map[string,U]).Get, where U is a type parameter. // In both instantiations, Origin() refers to the instantiated generic // method, (*Map[K,V]).Get, TypeParams() refers to the parameters [K,V] of @@ -305,39 +333,53 @@ type Node interface { // respectively, and is nil in the generic method. type Function struct { name string - object types.Object // a declared *types.Func or one of its wrappers - method *selection // info about provenance of synthetic methods; thunk => non-nil + object *types.Func // symbol for declared function (nil for FuncLit or synthetic init) + method *selection // info about provenance of synthetic methods; thunk => non-nil Signature *types.Signature pos token.Pos - Synthetic string // provenance of synthetic function; "" for true source functions - syntax ast.Node // *ast.Func{Decl,Lit}; replaced with simple ast.Node after build, unless debug mode - parent *Function // enclosing function if anon; nil if global - Pkg *Package // enclosing package; nil for shared funcs (wrappers and error.Error) - Prog *Program // enclosing program + // source information + Synthetic string // provenance of synthetic function; "" for true source functions + syntax ast.Node // *ast.Func{Decl,Lit}, if from syntax (incl. generic instances) or (*ast.RangeStmt if a yield function) + info *types.Info // type annotations (iff syntax != nil) + goversion string // Go version of syntax (NB: init is special) + + parent *Function // enclosing function if anon; nil if global + Pkg *Package // enclosing package; nil for shared funcs (wrappers and error.Error) + Prog *Program // enclosing program + + buildshared *task // wait for a shared function to be done building (may be nil if <=1 builder ever needs to wait) + + // These fields are populated only when the function body is built: + Params []*Parameter // function parameters; for methods, includes receiver FreeVars []*FreeVar // free variables whose values must be supplied by closure - Locals []*Alloc // local variables of this function + Locals []*Alloc // frame-allocated variables of this function Blocks []*BasicBlock // basic blocks of the function; nil => external Recover *BasicBlock // optional; control transfers here after recovered panic - AnonFuncs []*Function // anonymous functions directly beneath this one + AnonFuncs []*Function // anonymous functions (from FuncLit,RangeStmt) directly beneath this one referrers []Instruction // referring instructions (iff Parent() != nil) - built bool // function has completed both CREATE and BUILD phase. anonIdx int32 // position of a nested function in parent's AnonFuncs. fn.Parent()!=nil => fn.Parent().AnonFunc[fn.anonIdx] == fn. - typeparams *typeparams.TypeParamList // type parameters of this function. typeparams.Len() > 0 => generic or instance of generic function - typeargs []types.Type // type arguments that instantiated typeparams. len(typeargs) > 0 => instance of generic function - topLevelOrigin *Function // the origin function if this is an instance of a source function. nil if Parent()!=nil. + typeparams *types.TypeParamList // type parameters of this function. typeparams.Len() > 0 => generic or instance of generic function + typeargs []types.Type // type arguments that instantiated typeparams. len(typeargs) > 0 => instance of generic function + topLevelOrigin *Function // the origin function if this is an instance of a source function. nil if Parent()!=nil. + generic *generic // instances of this function, if generic - // The following fields are set transiently during building, - // then cleared. + // The following fields are cleared after building. + build buildFunc // algorithm to build function body (nil => built) currentBlock *BasicBlock // where to emit code - objects map[types.Object]Value // addresses of local variables - namedResults []*Alloc // tuple of named results + vars map[*types.Var]Value // addresses of local variables + results []*Alloc // result allocations of the current function + returnVars []*types.Var // variables for a return statement. Either results or for range-over-func a parent's results targets *targets // linked stack of branch targets - lblocks map[types.Object]*lblock // labelled blocks - info *types.Info // *types.Info to build from. nil for wrappers. - subst *subster // non-nil => expand generic body using this type substitution of ground types + lblocks map[*types.Label]*lblock // labelled blocks + subst *subster // type parameter substitutions (if non-nil) + jump *types.Var // synthetic variable for the yield state (non-nil => range-over-func) + deferstack *types.Var // synthetic variable holding enclosing ssa:deferstack() + source *Function // nearest enclosing source function + exits []*exit // exits of the function that need to be resolved + uniq int64 // source of unique ints within the source tree while building } // BasicBlock represents an SSA basic block. @@ -402,9 +444,8 @@ type FreeVar struct { // A Parameter represents an input parameter of a function. type Parameter struct { name string - object types.Object // a *types.Var; nil for non-source locals + object *types.Var // non-nil typ types.Type - pos token.Pos parent *Function referrers []Instruction } @@ -482,15 +523,12 @@ type Builtin struct { // type of the allocated variable is actually // Type().Underlying().(*types.Pointer).Elem(). // -// If Heap is false, Alloc allocates space in the function's -// activation record (frame); we refer to an Alloc(Heap=false) as a -// "local" alloc. Each local Alloc returns the same address each time -// it is executed within the same activation; the space is -// re-initialized to zero. +// If Heap is false, Alloc zero-initializes the same local variable in +// the call frame and returns its address; in this case the Alloc must +// be present in Function.Locals. We call this a "local" alloc. // -// If Heap is true, Alloc allocates space in the heap; we -// refer to an Alloc(Heap=true) as a "new" alloc. Each new Alloc -// returns a different address each time it is executed. +// If Heap is true, Alloc allocates a new zero-initialized variable +// each time the instruction is executed. We call this a "new" alloc. // // When Alloc is applied to a channel, map or slice type, it returns // the address of an uninitialized (nil) reference of that kind; store @@ -681,8 +719,8 @@ type Convert struct { type MultiConvert struct { register X Value - from []*typeparams.Term - to []*typeparams.Term + from []*types.Term + to []*types.Term } // ChangeInterface constructs a value of one interface type from a @@ -1068,11 +1106,12 @@ type Next struct { // Type() reflects the actual type of the result, possibly a // 2-types.Tuple; AssertedType is the asserted type. // -// Pos() returns the ast.CallExpr.Lparen if the instruction arose from -// an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the -// instruction arose from an explicit e.(T) operation; or the -// ast.CaseClause.Case if the instruction arose from a case of a -// type-switch statement. +// Depending on the TypeAssert's purpose, Pos may return: +// - the ast.CallExpr.Lparen of an explicit T(e) conversion; +// - the ast.TypeAssertExpr.Lparen of an explicit e.(T) operation; +// - the ast.CaseClause.Case of a case of a type-switch statement; +// - the Ident(m).NamePos of an interface method value i.m +// (for which TypeAssert may be used to effect the nil check). // // Example printed form: // @@ -1218,6 +1257,12 @@ type Go struct { // The Defer instruction pushes the specified call onto a stack of // functions to be called by a RunDefers instruction or by a panic. // +// If DeferStack != nil, it indicates the defer list that the defer is +// added to. Defer list values come from the Builtin function +// ssa:deferstack. Calls to ssa:deferstack() produces the defer stack +// of the current function frame. DeferStack allows for deferring into an +// alternative function stack than the current function. +// // See CallCommon for generic function call documentation. // // Pos() returns the ast.DeferStmt.Defer. @@ -1229,8 +1274,9 @@ type Go struct { // defer invoke t5.Println(...t6) type Defer struct { anInstruction - Call CallCommon - pos token.Pos + Call CallCommon + DeferStack Value // stack of deferred functions (from ssa:deferstack() intrinsic) onto which this function is pushed + pos token.Pos } // The Send instruction sends X on channel Chan. @@ -1390,7 +1436,7 @@ type anInstruction struct { // represents a dynamically dispatched call to an interface method. // In this mode, Value is the interface value and Method is the // interface's abstract method. The interface value may be a type -// parameter. Note: an abstract method may be shared by multiple +// parameter. Note: an interface method may be shared by multiple // interfaces due to embedding; Value.Type() provides the specific // interface used for this call. // @@ -1408,7 +1454,7 @@ type anInstruction struct { // the last element of Args is a slice. type CallCommon struct { Value Value // receiver (invoke mode) or func value (call mode) - Method *types.Func // abstract method (invoke mode) + Method *types.Func // interface method (invoke mode) Args []Value // actual parameters (in static method call, includes receiver) pos token.Pos // position of CallExpr.Lparen, iff explicit in source } @@ -1507,14 +1553,19 @@ func (v *Global) String() string { return v.RelString(nil) func (v *Global) Package() *Package { return v.Pkg } func (v *Global) RelString(from *types.Package) string { return relString(v, from) } -func (v *Function) Name() string { return v.name } -func (v *Function) Type() types.Type { return v.Signature } -func (v *Function) Pos() token.Pos { return v.pos } -func (v *Function) Token() token.Token { return token.FUNC } -func (v *Function) Object() types.Object { return v.object } -func (v *Function) String() string { return v.RelString(nil) } -func (v *Function) Package() *Package { return v.Pkg } -func (v *Function) Parent() *Function { return v.parent } +func (v *Function) Name() string { return v.name } +func (v *Function) Type() types.Type { return v.Signature } +func (v *Function) Pos() token.Pos { return v.pos } +func (v *Function) Token() token.Token { return token.FUNC } +func (v *Function) Object() types.Object { + if v.object != nil { + return types.Object(v.object) + } + return nil +} +func (v *Function) String() string { return v.RelString(nil) } +func (v *Function) Package() *Package { return v.Pkg } +func (v *Function) Parent() *Function { return v.parent } func (v *Function) Referrers() *[]Instruction { if v.parent != nil { return &v.referrers @@ -1524,10 +1575,7 @@ func (v *Function) Referrers() *[]Instruction { // TypeParams are the function's type parameters if generic or the // type parameters that were instantiated if fn is an instantiation. -// -// TODO(taking): declare result type as *types.TypeParamList -// after we drop support for go1.17. -func (fn *Function) TypeParams() *typeparams.TypeParamList { +func (fn *Function) TypeParams() *types.TypeParamList { return fn.typeparams } @@ -1562,7 +1610,7 @@ func (v *Parameter) Type() types.Type { return v.typ } func (v *Parameter) Name() string { return v.name } func (v *Parameter) Object() types.Object { return v.object } func (v *Parameter) Referrers() *[]Instruction { return &v.referrers } -func (v *Parameter) Pos() token.Pos { return v.pos } +func (v *Parameter) Pos() token.Pos { return v.object.Pos() } func (v *Parameter) Parent() *Function { return v.parent } func (v *Alloc) Type() types.Type { return v.typ } @@ -1670,7 +1718,7 @@ func (s *Call) Operands(rands []*Value) []*Value { } func (s *Defer) Operands(rands []*Value) []*Value { - return s.Call.Operands(rands) + return append(s.Call.Operands(rands), &s.DeferStack) } func (v *ChangeInterface) Operands(rands []*Value) []*Value { diff --git a/tools/vendor/golang.org/x/tools/go/ssa/ssautil/load.go b/tools/vendor/golang.org/x/tools/go/ssa/ssautil/load.go index 96d69a20a..3daa67a07 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/ssautil/load.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/ssautil/load.go @@ -14,14 +14,14 @@ import ( "golang.org/x/tools/go/loader" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/ssa" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/versions" ) // Packages creates an SSA program for a set of packages. // // The packages must have been loaded from source syntax using the -// golang.org/x/tools/go/packages.Load function in LoadSyntax or -// LoadAllSyntax mode. +// [packages.Load] function in [packages.LoadSyntax] or +// [packages.LoadAllSyntax] mode. // // Packages creates an SSA package for each well-typed package in the // initial list, plus all their dependencies. The resulting list of @@ -29,12 +29,30 @@ import ( // a nil if SSA code could not be constructed for the corresponding initial // package due to type errors. // -// Code for bodies of functions is not built until Build is called on -// the resulting Program. SSA code is constructed only for the initial -// packages with well-typed syntax trees. +// Code for bodies of functions is not built until [Program.Build] is +// called on the resulting Program. SSA code is constructed only for +// the initial packages with well-typed syntax trees. // // The mode parameter controls diagnostics and checking during SSA construction. func Packages(initial []*packages.Package, mode ssa.BuilderMode) (*ssa.Program, []*ssa.Package) { + // TODO(adonovan): opt: this calls CreatePackage far more than + // necessary: for all dependencies, not just the (non-initial) + // direct dependencies of the initial packages. + // + // But can it reasonably be changed without breaking the + // spirit and/or letter of the law above? Clients may notice + // if we call CreatePackage less, as methods like + // Program.FuncValue will return nil. Or must we provide a new + // function (and perhaps deprecate this one)? Is it worth it? + // + // Tim King makes the interesting point that it would be + // possible to entirely alleviate the client from the burden + // of calling CreatePackage for non-syntax packages, if we + // were to treat vars and funcs lazily in the same way we now + // treat methods. (In essence, try to move away from the + // notion of ssa.Packages, and make the Program answer + // all reasonable questions about any types.Object.) + return doPackages(initial, mode, false) } @@ -42,7 +60,7 @@ func Packages(initial []*packages.Package, mode ssa.BuilderMode) (*ssa.Program, // their dependencies. // // The packages must have been loaded from source syntax using the -// golang.org/x/tools/go/packages.Load function in LoadAllSyntax mode. +// [packages.Load] function in [packages.LoadAllSyntax] mode. // // AllPackages creates an SSA package for each well-typed package in the // initial list, plus all their dependencies. The resulting list of @@ -102,7 +120,7 @@ func doPackages(initial []*packages.Package, mode ssa.BuilderMode, deps bool) (* // // The mode parameter controls diagnostics and checking during SSA construction. // -// Deprecated: Use golang.org/x/tools/go/packages and the Packages +// Deprecated: Use [golang.org/x/tools/go/packages] and the [Packages] // function instead; see ssa.Example_loadPackages. func CreateProgram(lprog *loader.Program, mode ssa.BuilderMode) *ssa.Program { prog := ssa.NewProgram(lprog.Fset, mode) @@ -116,16 +134,17 @@ func CreateProgram(lprog *loader.Program, mode ssa.BuilderMode) *ssa.Program { return prog } -// BuildPackage builds an SSA program with IR for a single package. +// BuildPackage builds an SSA program with SSA intermediate +// representation (IR) for all functions of a single package. // -// It populates pkg by type-checking the specified file ASTs. All +// It populates pkg by type-checking the specified file syntax trees. All // dependencies are loaded using the importer specified by tc, which // typically loads compiler export data; SSA code cannot be built for -// those packages. BuildPackage then constructs an ssa.Program with all +// those packages. BuildPackage then constructs an [ssa.Program] with all // dependency packages created, and builds and returns the SSA package // corresponding to pkg. // -// The caller must have set pkg.Path() to the import path. +// The caller must have set pkg.Path to the import path. // // The operation fails if there were any type-checking or import errors. // @@ -143,10 +162,11 @@ func BuildPackage(tc *types.Config, fset *token.FileSet, pkg *types.Package, fil Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } - typeparams.InitInstanceInfo(info) + versions.InitFileVersions(info) if err := types.NewChecker(tc, fset, pkg, info).Files(files); err != nil { return nil, nil, err } @@ -168,6 +188,25 @@ func BuildPackage(tc *types.Config, fset *token.FileSet, pkg *types.Package, fil } createAll(pkg.Imports()) + // TODO(adonovan): we could replace createAll with just: + // + // // Create SSA packages for all imports. + // for _, p := range pkg.Imports() { + // prog.CreatePackage(p, nil, nil, true) + // } + // + // (with minor changes to changes to ../builder_test.go as + // shown in CL 511715 PS 10.) But this would strictly violate + // the letter of the doc comment above, which says "all + // dependencies created". + // + // Tim makes the good point with some extra work we could + // remove the need for any CreatePackage calls except the + // ones with syntax (i.e. primary packages). Of course + // You wouldn't have ssa.Packages and Members for as + // many things but no-one really uses that anyway. + // I wish I had done this from the outset. + // Create and build the primary package. ssapkg := prog.CreatePackage(pkg, files, info, false) ssapkg.Build() diff --git a/tools/vendor/golang.org/x/tools/go/ssa/ssautil/visit.go b/tools/vendor/golang.org/x/tools/go/ssa/ssautil/visit.go index 5f27050b0..b4feb42cb 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/ssautil/visit.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/ssautil/visit.go @@ -4,7 +4,14 @@ package ssautil // import "golang.org/x/tools/go/ssa/ssautil" -import "golang.org/x/tools/go/ssa" +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/go/ssa" + + _ "unsafe" // for linkname hack +) // This file defines utilities for visiting the SSA representation of // a Program. @@ -18,50 +25,113 @@ import "golang.org/x/tools/go/ssa" // synthetic wrappers. // // Precondition: all packages are built. +// +// TODO(adonovan): this function is underspecified. It doesn't +// actually work like a linker, which computes reachability from main +// using something like go/callgraph/cha (without materializing the +// call graph). In fact, it treats all public functions and all +// methods of public non-parameterized types as roots, even though +// they may be unreachable--but only in packages created from syntax. +// +// I think we should deprecate AllFunctions function in favor of two +// clearly defined ones: +// +// 1. The first would efficiently compute CHA reachability from a set +// of main packages, making it suitable for a whole-program +// analysis context with InstantiateGenerics, in conjunction with +// Program.Build. +// +// 2. The second would return only the set of functions corresponding +// to source Func{Decl,Lit} syntax, like SrcFunctions in +// go/analysis/passes/buildssa; this is suitable for +// package-at-a-time (or handful of packages) context. +// ssa.Package could easily expose it as a field. +// +// We could add them unexported for now and use them via the linkname hack. func AllFunctions(prog *ssa.Program) map[*ssa.Function]bool { - visit := visitor{ - prog: prog, - seen: make(map[*ssa.Function]bool), + seen := make(map[*ssa.Function]bool) + + var function func(fn *ssa.Function) + function = func(fn *ssa.Function) { + if !seen[fn] { + seen[fn] = true + var buf [10]*ssa.Value // avoid alloc in common case + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + for _, op := range instr.Operands(buf[:0]) { + if fn, ok := (*op).(*ssa.Function); ok { + function(fn) + } + } + } + } + } } - visit.program() - return visit.seen -} -type visitor struct { - prog *ssa.Program - seen map[*ssa.Function]bool -} + // TODO(adonovan): opt: provide a way to share a builder + // across a sequence of MethodValue calls. -func (visit *visitor) program() { - for _, pkg := range visit.prog.AllPackages() { - for _, mem := range pkg.Members { - if fn, ok := mem.(*ssa.Function); ok { - visit.function(fn) + methodsOf := func(T types.Type) { + if !types.IsInterface(T) { + mset := prog.MethodSets.MethodSet(T) + for i := 0; i < mset.Len(); i++ { + function(prog.MethodValue(mset.At(i))) } } } - for _, T := range visit.prog.RuntimeTypes() { - mset := visit.prog.MethodSets.MethodSet(T) - for i, n := 0, mset.Len(); i < n; i++ { - visit.function(visit.prog.MethodValue(mset.At(i))) + + // Historically, Program.RuntimeTypes used to include the type + // of any exported member of a package loaded from syntax that + // has a non-parameterized type, plus all types + // reachable from that type using reflection, even though + // these runtime types may not be required for them. + // + // Rather than break existing programs that rely on + // AllFunctions visiting extra methods that are unreferenced + // by IR and unreachable via reflection, we moved the logic + // here, unprincipled though it is. + // (See doc comment for better ideas.) + // + // Nonetheless, after the move, we no longer visit every + // method of any type recursively reachable from T, only the + // methods of T and *T themselves, and we only apply this to + // named types T, and not to the type of every exported + // package member. + exportedTypeHack := func(t *ssa.Type) { + if isSyntactic(t.Package()) && + ast.IsExported(t.Name()) && + !types.IsInterface(t.Type()) { + // Consider only named types. + // (Ignore aliases and unsafe.Pointer.) + if named, ok := t.Type().(*types.Named); ok { + if named.TypeParams() == nil { + methodsOf(named) // T + methodsOf(types.NewPointer(named)) // *T + } + } } } -} -func (visit *visitor) function(fn *ssa.Function) { - if !visit.seen[fn] { - visit.seen[fn] = true - var buf [10]*ssa.Value // avoid alloc in common case - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - for _, op := range instr.Operands(buf[:0]) { - if fn, ok := (*op).(*ssa.Function); ok { - visit.function(fn) - } - } + for _, pkg := range prog.AllPackages() { + for _, mem := range pkg.Members { + switch mem := mem.(type) { + case *ssa.Function: + // Visit all package-level declared functions. + function(mem) + + case *ssa.Type: + exportedTypeHack(mem) } } } + + // Visit all methods of types for which runtime types were + // materialized, as they are reachable through reflection. + for _, T := range prog.RuntimeTypes() { + methodsOf(T) + } + + return seen } // MainPackages returns the subset of the specified packages @@ -76,3 +146,12 @@ func MainPackages(pkgs []*ssa.Package) []*ssa.Package { } return mains } + +// TODO(adonovan): propose a principled API for this. One possibility +// is a new field, Package.SrcFunctions []*Function, which would +// contain the list of SrcFunctions described in point 2 of the +// AllFunctions doc comment, or nil if the package is not from syntax. +// But perhaps overloading nil vs empty slice is too subtle. +// +//go:linkname isSyntactic golang.org/x/tools/go/ssa.isSyntactic +func isSyntactic(pkg *ssa.Package) bool diff --git a/tools/vendor/golang.org/x/tools/go/ssa/subst.go b/tools/vendor/golang.org/x/tools/go/ssa/subst.go index 23d19ae73..4dcb87157 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/subst.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/subst.go @@ -7,66 +7,73 @@ package ssa import ( "go/types" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/aliases" ) -// Type substituter for a fixed set of replacement types. +// subster defines a type substitution operation of a set of type parameters +// to type parameter free replacement types. Substitution is done within +// the context of a package-level function instantiation. *Named types +// declared in the function are unique to the instantiation. // -// A nil *subster is an valid, empty substitution map. It always acts as +// For example, given a parameterized function F +// +// func F[S, T any]() any { +// type X struct{ s S; next *X } +// var p *X +// return p +// } +// +// calling the instantiation F[string, int]() returns an interface +// value (*X[string,int], nil) where the underlying value of +// X[string,int] is a struct{s string; next *X[string,int]}. +// +// A nil *subster is a valid, empty substitution map. It always acts as // the identity function. This allows for treating parameterized and // non-parameterized functions identically while compiling to ssa. // // Not concurrency-safe. +// +// Note: Some may find it helpful to think through some of the most +// complex substitution cases using lambda calculus inspired notation. +// subst.typ() solves evaluating a type expression E +// within the body of a function Fn[m] with the type parameters m +// once we have applied the type arguments N. +// We can succinctly write this as a function application: +// +// ((λm. E) N) +// +// go/types does not provide this interface directly. +// So what subster provides is a type substitution operation +// +// E[m:=N] type subster struct { - replacements map[*typeparams.TypeParam]types.Type // values should contain no type params - cache map[types.Type]types.Type // cache of subst results - ctxt *typeparams.Context // cache for instantiation - scope *types.Scope // *types.Named declared within this scope can be substituted (optional) - debug bool // perform extra debugging checks + replacements map[*types.TypeParam]types.Type // values should contain no type params + cache map[types.Type]types.Type // cache of subst results + origin *types.Func // types.Objects declared within this origin function are unique within this context + ctxt *types.Context // speeds up repeated instantiations + uniqueness typeutil.Map // determines the uniqueness of the instantiations within the function // TODO(taking): consider adding Pos - // TODO(zpavlinovic): replacements can contain type params - // when generating instances inside of a generic function body. } // Returns a subster that replaces tparams[i] with targs[i]. Uses ctxt as a cache. // targs should not contain any types in tparams. -// scope is the (optional) lexical block of the generic function for which we are substituting. -func makeSubster(ctxt *typeparams.Context, scope *types.Scope, tparams *typeparams.TypeParamList, targs []types.Type, debug bool) *subster { +// fn is the generic function for which we are substituting. +func makeSubster(ctxt *types.Context, fn *types.Func, tparams *types.TypeParamList, targs []types.Type, debug bool) *subster { assert(tparams.Len() == len(targs), "makeSubster argument count must match") subst := &subster{ - replacements: make(map[*typeparams.TypeParam]types.Type, tparams.Len()), + replacements: make(map[*types.TypeParam]types.Type, tparams.Len()), cache: make(map[types.Type]types.Type), + origin: fn.Origin(), ctxt: ctxt, - scope: scope, - debug: debug, } for i := 0; i < tparams.Len(); i++ { subst.replacements[tparams.At(i)] = targs[i] } - if subst.debug { - subst.wellFormed() - } return subst } -// wellFormed asserts that subst was properly initialized. -func (subst *subster) wellFormed() { - if subst == nil { - return - } - // Check that all of the type params do not appear in the arguments. - s := make(map[types.Type]bool, len(subst.replacements)) - for tparam := range subst.replacements { - s[tparam] = true - } - for _, r := range subst.replacements { - if reaches(r, s) { - panic(subst) - } - } -} - // typ returns the type of t with the type parameter tparams[i] substituted // for the type targs[i] where subst was created using tparams and targs. func (subst *subster) typ(t types.Type) (res types.Type) { @@ -80,12 +87,12 @@ func (subst *subster) typ(t types.Type) (res types.Type) { subst.cache[t] = res }() - // fall through if result r will be identical to t, types.Identical(r, t). switch t := t.(type) { - case *typeparams.TypeParam: - r := subst.replacements[t] - assert(r != nil, "type param without replacement encountered") - return r + case *types.TypeParam: + if r := subst.replacements[t]; r != nil { + return r + } + return t case *types.Basic: return t @@ -131,15 +138,21 @@ func (subst *subster) typ(t types.Type) (res types.Type) { case *types.Signature: return subst.signature(t) - case *typeparams.Union: + case *types.Union: return subst.union(t) case *types.Interface: return subst.interface_(t) + case *aliases.Alias: + return subst.alias(t) + case *types.Named: return subst.named(t) + case *opaqueType: + return t // opaque types are never substituted + default: panic("unreachable") } @@ -189,7 +202,7 @@ func (subst *subster) struct_(t *types.Struct) *types.Struct { return t } -// varlist reutrns subst(in[i]) or return nils if subst(v[i]) == v[i] for all i. +// varlist returns subst(in[i]) or return nils if subst(v[i]) == v[i] for all i. func (subst *subster) varlist(in varlist) []*types.Var { var out []*types.Var // nil => no updates for i, n := 0, in.Len(); i < n; i++ { @@ -220,25 +233,25 @@ func (subst *subster) var_(v *types.Var) *types.Var { return v } -func (subst *subster) union(u *typeparams.Union) *typeparams.Union { - var out []*typeparams.Term // nil => no updates +func (subst *subster) union(u *types.Union) *types.Union { + var out []*types.Term // nil => no updates for i, n := 0, u.Len(); i < n; i++ { t := u.Term(i) r := subst.typ(t.Type()) if r != t.Type() && out == nil { - out = make([]*typeparams.Term, n) + out = make([]*types.Term, n) for j := 0; j < i; j++ { out[j] = u.Term(j) } } if out != nil { - out[i] = typeparams.NewTerm(t.Tilde(), r) + out[i] = types.NewTerm(t.Tilde(), r) } } if out != nil { - return typeparams.NewUnion(out) + return types.NewUnion(out) } return u } @@ -304,76 +317,228 @@ func (subst *subster) interface_(iface *types.Interface) *types.Interface { return types.NewInterfaceType(methods, embeds).Complete() } +func (subst *subster) alias(t *aliases.Alias) types.Type { + // See subster.named. This follows the same strategy. + tparams := aliases.TypeParams(t) + targs := aliases.TypeArgs(t) + tname := t.Obj() + torigin := aliases.Origin(t) + + if !declaredWithin(tname, subst.origin) { + // t is declared outside of the function origin. So t is a package level type alias. + if targs.Len() == 0 { + // No type arguments so no instantiation needed. + return t + } + + // Instantiate with the substituted type arguments. + newTArgs := subst.typelist(targs) + return subst.instantiate(torigin, newTArgs) + } + + if targs.Len() == 0 { + // t is declared within the function origin and has no type arguments. + // + // Example: This corresponds to A or B in F, but not A[int]: + // + // func F[T any]() { + // type A[S any] = struct{t T, s S} + // type B = T + // var x A[int] + // ... + // } + // + // This is somewhat different than *Named as *Alias cannot be created recursively. + + // Copy and substitute type params. + var newTParams []*types.TypeParam + for i := 0; i < tparams.Len(); i++ { + cur := tparams.At(i) + cobj := cur.Obj() + cname := types.NewTypeName(cobj.Pos(), cobj.Pkg(), cobj.Name(), nil) + ntp := types.NewTypeParam(cname, nil) + subst.cache[cur] = ntp // See the comment "Note: Subtle" in subster.named. + newTParams = append(newTParams, ntp) + } + + // Substitute rhs. + rhs := subst.typ(aliases.Rhs(t)) + + // Create the fresh alias. + obj := aliases.NewAlias(true, tname.Pos(), tname.Pkg(), tname.Name(), rhs) + fresh := obj.Type() + if fresh, ok := fresh.(*aliases.Alias); ok { + // TODO: assume ok when aliases are always materialized (go1.27). + aliases.SetTypeParams(fresh, newTParams) + } + + // Substitute into all of the constraints after they are created. + for i, ntp := range newTParams { + bound := tparams.At(i).Constraint() + ntp.SetConstraint(subst.typ(bound)) + } + return fresh + } + + // t is declared within the function origin and has type arguments. + // + // Example: This corresponds to A[int] in F. Cases A and B are handled above. + // func F[T any]() { + // type A[S any] = struct{t T, s S} + // type B = T + // var x A[int] + // ... + // } + subOrigin := subst.typ(torigin) + subTArgs := subst.typelist(targs) + return subst.instantiate(subOrigin, subTArgs) +} + func (subst *subster) named(t *types.Named) types.Type { - // A named type may be: - // (1) ordinary named type (non-local scope, no type parameters, no type arguments), - // (2) locally scoped type, - // (3) generic (type parameters but no type arguments), or - // (4) instantiated (type parameters and type arguments). - tparams := typeparams.ForNamed(t) - if tparams.Len() == 0 { - if subst.scope != nil && !subst.scope.Contains(t.Obj().Pos()) { - // Outside the current function scope? - return t // case (1) ordinary - } - - // case (2) locally scoped type. - // Create a new named type to represent this instantiation. - // We assume that local types of distinct instantiations of a - // generic function are distinct, even if they don't refer to - // type parameters, but the spec is unclear; see golang/go#58573. + // A Named type is a user defined type. + // Ignoring generics, Named types are canonical: they are identical if + // and only if they have the same defining symbol. + // Generics complicate things, both if the type definition itself is + // parameterized, and if the type is defined within the scope of a + // parameterized function. In this case, two named types are identical if + // and only if their identifying symbols are identical, and all type + // arguments bindings in scope of the named type definition (including the + // type parameters of the definition itself) are equivalent. + // + // Notably: + // 1. For type definition type T[P1 any] struct{}, T[A] and T[B] are identical + // only if A and B are identical. + // 2. Inside the generic func Fn[m any]() any { type T struct{}; return T{} }, + // the result of Fn[A] and Fn[B] have identical type if and only if A and + // B are identical. + // 3. Both 1 and 2 could apply, such as in + // func F[m any]() any { type T[x any] struct{}; return T{} } + // + // A subster replaces type parameters within a function scope, and therefore must + // also replace free type parameters in the definitions of local types. + // + // Note: There are some detailed notes sprinkled throughout that borrow from + // lambda calculus notation. These contain some over simplifying math. + // + // LC: One way to think about subster is that it is a way of evaluating + // ((λm. E) N) as E[m:=N]. + // Each Named type t has an object *TypeName within a scope S that binds an + // underlying type expression U. U can refer to symbols within S (+ S's ancestors). + // Let x = t.TypeParams() and A = t.TypeArgs(). + // Each Named type t is then either: + // U where len(x) == 0 && len(A) == 0 + // λx. U where len(x) != 0 && len(A) == 0 + // ((λx. U) A) where len(x) == len(A) + // In each case, we will evaluate t[m:=N]. + tparams := t.TypeParams() // x + targs := t.TypeArgs() // A + + if !declaredWithin(t.Obj(), subst.origin) { + // t is declared outside of Fn[m]. + // + // In this case, we can skip substituting t.Underlying(). + // The underlying type cannot refer to the type parameters. + // + // LC: Let free(E) be the set of free type parameters in an expression E. + // Then whenever m ∉ free(E), then E = E[m:=N]. + // t ∉ Scope(fn) so therefore m ∉ free(U) and m ∩ x = ∅. + if targs.Len() == 0 { + // t has no type arguments. So it does not need to be instantiated. + // + // This is the normal case in real Go code, where t is not parameterized, + // declared at some package scope, and m is a TypeParam from a parameterized + // function F[m] or method. + // + // LC: m ∉ free(A) lets us conclude m ∉ free(t). So t=t[m:=N]. + return t + } + + // t is declared outside of Fn[m] and has type arguments. + // The type arguments may contain type parameters m so + // substitute the type arguments, and instantiate the substituted + // type arguments. + // + // LC: Evaluate this as ((λx. U) A') where A' = A[m := N]. + newTArgs := subst.typelist(targs) + return subst.instantiate(t.Origin(), newTArgs) + } + + // t is declared within Fn[m]. + + if targs.Len() == 0 { // no type arguments? + assert(t == t.Origin(), "local parameterized type abstraction must be an origin type") + + // t has no type arguments. + // The underlying type of t may contain the function's type parameters, + // replace these, and create a new type. // // Subtle: We short circuit substitution and use a newly created type in - // subst, i.e. cache[t]=n, to pre-emptively replace t with n in recursive - // types during traversal. This both breaks infinite cycles and allows for - // constructing types with the replacement applied in subst.typ(under). + // subst, i.e. cache[t]=fresh, to preemptively replace t with fresh + // in recursive types during traversal. This both breaks infinite cycles + // and allows for constructing types with the replacement applied in + // subst.typ(U). // - // Example: - // func foo[T any]() { - // type linkedlist struct { - // next *linkedlist - // val T - // } - // } + // A new copy of the Named and Typename (and constraints) per function + // instantiation matches the semantics of Go, which treats all function + // instantiations F[N] as having distinct local types. // - // When the field `next *linkedlist` is visited during subst.typ(under), - // we want the substituted type for the field `next` to be `*n`. - n := types.NewNamed(t.Obj(), nil, nil) - subst.cache[t] = n - subst.cache[n] = n - n.SetUnderlying(subst.typ(t.Underlying())) - return n + // LC: x.Len()=0 can be thought of as a special case of λx. U. + // LC: Evaluate (λx. U)[m:=N] as (λx'. U') where U'=U[x:=x',m:=N]. + tname := t.Obj() + obj := types.NewTypeName(tname.Pos(), tname.Pkg(), tname.Name(), nil) + fresh := types.NewNamed(obj, nil, nil) + var newTParams []*types.TypeParam + for i := 0; i < tparams.Len(); i++ { + cur := tparams.At(i) + cobj := cur.Obj() + cname := types.NewTypeName(cobj.Pos(), cobj.Pkg(), cobj.Name(), nil) + ntp := types.NewTypeParam(cname, nil) + subst.cache[cur] = ntp + newTParams = append(newTParams, ntp) + } + fresh.SetTypeParams(newTParams) + subst.cache[t] = fresh + subst.cache[fresh] = fresh + fresh.SetUnderlying(subst.typ(t.Underlying())) + // Substitute into all of the constraints after they are created. + for i, ntp := range newTParams { + bound := tparams.At(i).Constraint() + ntp.SetConstraint(subst.typ(bound)) + } + return fresh } - targs := typeparams.NamedTypeArgs(t) - - // insts are arguments to instantiate using. - insts := make([]types.Type, tparams.Len()) - - // case (3) generic ==> targs.Len() == 0 - // Instantiating a generic with no type arguments should be unreachable. - // Please report a bug if you encounter this. - assert(targs.Len() != 0, "substition into a generic Named type is currently unsupported") - - // case (4) instantiated. - // Substitute into the type arguments and instantiate the replacements/ - // Example: - // type N[A any] func() A - // func Foo[T](g N[T]) {} - // To instantiate Foo[string], one goes through {T->string}. To get the type of g - // one subsitutes T with string in {N with typeargs == {T} and typeparams == {A} } - // to get {N with TypeArgs == {string} and typeparams == {A} }. - assert(targs.Len() == tparams.Len(), "typeargs.Len() must match typeparams.Len() if present") - for i, n := 0, targs.Len(); i < n; i++ { - inst := subst.typ(targs.At(i)) // TODO(generic): Check with rfindley for mutual recursion - insts[i] = inst + + // t is defined within Fn[m] and t has type arguments (an instantiation). + // We reduce this to the two cases above: + // (1) substitute the function's type parameters into t.Origin(). + // (2) substitute t's type arguments A and instantiate the updated t.Origin() with these. + // + // LC: Evaluate ((λx. U) A)[m:=N] as (t' A') where t' = (λx. U)[m:=N] and A'=A [m:=N] + subOrigin := subst.typ(t.Origin()) + subTArgs := subst.typelist(targs) + return subst.instantiate(subOrigin, subTArgs) +} + +func (subst *subster) instantiate(orig types.Type, targs []types.Type) types.Type { + i, err := types.Instantiate(subst.ctxt, orig, targs, false) + assert(err == nil, "failed to Instantiate named (Named or Alias) type") + if c, _ := subst.uniqueness.At(i).(types.Type); c != nil { + return c.(types.Type) } - r, err := typeparams.Instantiate(subst.ctxt, typeparams.NamedTypeOrigin(t), insts, false) - assert(err == nil, "failed to Instantiate Named type") - return r + subst.uniqueness.Set(i, i) + return i +} + +func (subst *subster) typelist(l *types.TypeList) []types.Type { + res := make([]types.Type, l.Len()) + for i := 0; i < l.Len(); i++ { + res[i] = subst.typ(l.At(i)) + } + return res } func (subst *subster) signature(t *types.Signature) types.Type { - tparams := typeparams.ForSignature(t) + tparams := t.TypeParams() // We are choosing not to support tparams.Len() > 0 until a need has been observed in practice. // @@ -398,7 +563,7 @@ func (subst *subster) signature(t *types.Signature) types.Type { params := subst.tuple(t.Params()) results := subst.tuple(t.Results()) if recv != t.Recv() || params != t.Params() || results != t.Results() { - return typeparams.NewSignatureType(recv, nil, nil, params, results, t.Variadic()) + return types.NewSignatureType(recv, nil, nil, params, results, t.Variadic()) } return t } @@ -422,7 +587,7 @@ func reaches(t types.Type, c map[types.Type]bool) (res bool) { }() switch t := t.(type) { - case *typeparams.TypeParam, *types.Basic: + case *types.TypeParam, *types.Basic: return false case *types.Array: return reaches(t.Elem(), c) @@ -451,7 +616,7 @@ func reaches(t types.Type, c map[types.Type]bool) (res bool) { return true } return reaches(t.Params(), c) || reaches(t.Results(), c) - case *typeparams.Union: + case *types.Union: for i := 0; i < t.Len(); i++ { if reaches(t.Term(i).Type(), c) { return true @@ -468,7 +633,7 @@ func reaches(t types.Type, c map[types.Type]bool) (res bool) { return true } } - case *types.Named: + case *types.Named, *aliases.Alias: return reaches(t.Underlying(), c) default: panic("unreachable") diff --git a/tools/vendor/golang.org/x/tools/go/ssa/task.go b/tools/vendor/golang.org/x/tools/go/ssa/task.go new file mode 100644 index 000000000..502498526 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/ssa/task.go @@ -0,0 +1,103 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ssa + +import ( + "sync/atomic" +) + +// Each task has two states: it is initially "active", +// and transitions to "done". +// +// tasks form a directed graph. An edge from x to y (with y in x.edges) +// indicates that the task x waits on the task y to be done. +// Cycles are permitted. +// +// Calling x.wait() blocks the calling goroutine until task x, +// and all the tasks transitively reachable from x are done. +// +// The nil *task is always considered done. +type task struct { + done chan unit // close when the task is done. + edges map[*task]unit // set of predecessors of this task. + transitive atomic.Bool // true once it is known all predecessors are done. +} + +func (x *task) isTransitivelyDone() bool { return x == nil || x.transitive.Load() } + +// addEdge creates an edge from x to y, indicating that +// x.wait() will not return before y is done. +// All calls to x.addEdge(...) should happen before x.markDone(). +func (x *task) addEdge(y *task) { + if x == y || y.isTransitivelyDone() { + return // no work remaining + } + + // heuristic done check + select { + case <-x.done: + panic("cannot add an edge to a done task") + default: + } + + if x.edges == nil { + x.edges = make(map[*task]unit) + } + x.edges[y] = unit{} +} + +// markDone changes the task's state to markDone. +func (x *task) markDone() { + if x != nil { + close(x.done) + } +} + +// wait blocks until x and all the tasks it can reach through edges are done. +func (x *task) wait() { + if x.isTransitivelyDone() { + return // already known to be done. Skip allocations. + } + + // Use BFS to wait on u.done to be closed, for all u transitively + // reachable from x via edges. + // + // This work can be repeated by multiple workers doing wait(). + // + // Note: Tarjan's SCC algorithm is able to mark SCCs as transitively done + // as soon as the SCC has been visited. This is theoretically faster, but is + // a more complex algorithm. Until we have evidence, we need the more complex + // algorithm, the simpler algorithm BFS is implemented. + // + // In Go 1.23, ssa/TestStdlib reaches <=3 *tasks per wait() in most schedules + // On some schedules, there is a cycle building net/http and internal/trace/testtrace + // due to slices functions. + work := []*task{x} + enqueued := map[*task]unit{x: {}} + for i := 0; i < len(work); i++ { + u := work[i] + if u.isTransitivelyDone() { // already transitively done + work[i] = nil + continue + } + <-u.done // wait for u to be marked done. + + for v := range u.edges { + if _, ok := enqueued[v]; !ok { + enqueued[v] = unit{} + work = append(work, v) + } + } + } + + // work is transitively closed over dependencies. + // u in work is done (or transitively done and skipped). + // u is transitively done. + for _, u := range work { + if u != nil { + x.transitive.Store(true) + } + } +} diff --git a/tools/vendor/golang.org/x/tools/go/ssa/util.go b/tools/vendor/golang.org/x/tools/go/ssa/util.go index 68cc971b3..549c9c819 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/util.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/util.go @@ -17,9 +17,13 @@ import ( "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/typesinternal" ) +type unit struct{} + //// Sanity checking utilities // assert panics with the mesage msg if p is false. @@ -41,6 +45,13 @@ func isBlankIdent(e ast.Expr) bool { return ok && id.Name == "_" } +// rangePosition is the position to give for the `range` token in a RangeStmt. +var rangePosition = func(rng *ast.RangeStmt) token.Pos { + // Before 1.20, this is unreachable. + // rng.For is a close, but incorrect position. + return rng.For +} + //// Type utilities. Some of these belong in go/types. // isNonTypeParamInterface reports whether t is an interface type but not a type parameter. @@ -49,17 +60,21 @@ func isNonTypeParamInterface(t types.Type) bool { } // isBasic reports whether t is a basic type. +// t is assumed to be an Underlying type (not Named or Alias). func isBasic(t types.Type) bool { _, ok := t.(*types.Basic) return ok } // isString reports whether t is exactly a string type. +// t is assumed to be an Underlying type (not Named or Alias). func isString(t types.Type) bool { - return isBasic(t) && t.(*types.Basic).Info()&types.IsString != 0 + basic, ok := t.(*types.Basic) + return ok && basic.Info()&types.IsString != 0 } // isByteSlice reports whether t is of the form []~bytes. +// t is assumed to be an Underlying type (not Named or Alias). func isByteSlice(t types.Type) bool { if b, ok := t.(*types.Slice); ok { e, _ := b.Elem().Underlying().(*types.Basic) @@ -69,6 +84,7 @@ func isByteSlice(t types.Type) bool { } // isRuneSlice reports whether t is of the form []~runes. +// t is assumed to be an Underlying type (not Named or Alias). func isRuneSlice(t types.Type) bool { if b, ok := t.(*types.Slice); ok { e, _ := b.Elem().Underlying().(*types.Basic) @@ -94,33 +110,22 @@ func isBasicConvTypes(tset termList) bool { return all && basics >= 1 && tset.Len()-basics <= 1 } -// deptr returns a pointer's element type and true; otherwise it returns (typ, false). -// This function is oblivious to core types and is not suitable for generics. -// -// TODO: Deprecate this function once all usages have been audited. -func deptr(typ types.Type) (types.Type, bool) { - if p, ok := typ.Underlying().(*types.Pointer); ok { - return p.Elem(), true - } - return typ, false +// isPointer reports whether t's underlying type is a pointer. +func isPointer(t types.Type) bool { + return is[*types.Pointer](t.Underlying()) } -// deref returns the element type of a type with a pointer core type and true; -// otherwise it returns (typ, false). -func deref(typ types.Type) (types.Type, bool) { - if p, ok := typeparams.CoreType(typ).(*types.Pointer); ok { - return p.Elem(), true - } - return typ, false +// isPointerCore reports whether t's core type is a pointer. +// +// (Most pointer manipulation is related to receivers, in which case +// isPointer is appropriate. tecallers can use isPointer(t). +func isPointerCore(t types.Type) bool { + return is[*types.Pointer](typeparams.CoreType(t)) } -// mustDeref returns the element type of a type with a pointer core type. -// Panics on failure. -func mustDeref(typ types.Type) types.Type { - if et, ok := deref(typ); ok { - return et - } - panic("cannot dereference type " + typ.String()) +func is[T any](x any) bool { + _, ok := x.(T) + return ok } // recvType returns the receiver type of method obj. @@ -139,12 +144,33 @@ func fieldOf(typ types.Type, index int) *types.Var { return nil } -// isUntyped returns true for types that are untyped. +// isUntyped reports whether typ is the type of an untyped constant. func isUntyped(typ types.Type) bool { + // No Underlying/Unalias: untyped constant types cannot be Named or Alias. b, ok := typ.(*types.Basic) return ok && b.Info()&types.IsUntyped != 0 } +// declaredWithin reports whether an object is declared within a function. +// +// obj must not be a method or a field. +func declaredWithin(obj types.Object, fn *types.Func) bool { + if obj.Pos() != token.NoPos { + return fn.Scope().Contains(obj.Pos()) // trust the positions if they exist. + } + if fn.Pkg() != obj.Pkg() { + return false // fast path for different packages + } + + // Traverse Parent() scopes for fn.Scope(). + for p := obj.Parent(); p != nil; p = p.Parent() { + if p == fn.Scope() { + return true + } + } + return false +} + // logStack prints the formatted "start" message to stderr and // returns a closure that prints the corresponding "end" message. // Call using 'defer logStack(...)()' to show builder stack on panic. @@ -180,37 +206,15 @@ func makeLen(T types.Type) *Builtin { } } -// nonbasicTypes returns a list containing all of the types T in ts that are non-basic. -func nonbasicTypes(ts []types.Type) []types.Type { - if len(ts) == 0 { - return nil - } - added := make(map[types.Type]bool) // additionally filter duplicates - var filtered []types.Type - for _, T := range ts { - if !isBasic(T) { - if !added[T] { - added[T] = true - filtered = append(filtered, T) - } - } - } - return filtered -} - -// receiverTypeArgs returns the type arguments to a function's receiver. -// Returns an empty list if obj does not have a receiver or its receiver does not have type arguments. -func receiverTypeArgs(obj *types.Func) []types.Type { - rtype := recvType(obj) - if rtype == nil { - return nil +// receiverTypeArgs returns the type arguments to a method's receiver. +// Returns an empty list if the receiver does not have type arguments. +func receiverTypeArgs(method *types.Func) []types.Type { + recv := method.Type().(*types.Signature).Recv() + _, named := typesinternal.ReceiverNamed(recv) + if named == nil { + return nil // recv is anonymous struct/interface } - rtype, _ = deptr(rtype) - named, ok := rtype.(*types.Named) - if !ok { - return nil - } - ts := typeparams.NamedTypeArgs(named) + ts := named.TypeArgs() if ts.Len() == 0 { return nil } @@ -229,7 +233,7 @@ func recvAsFirstArg(sig *types.Signature) *types.Signature { for i := 0; i < sig.Params().Len(); i++ { params = append(params, sig.Params().At(i)) } - return typeparams.NewSignatureType(nil, nil, nil, types.NewTuple(params...), sig.Results(), sig.Variadic()) + return types.NewSignatureType(nil, nil, nil, types.NewTuple(params...), sig.Results(), sig.Variadic()) } // instance returns whether an expression is a simple or qualified identifier @@ -246,13 +250,13 @@ func instance(info *types.Info, expr ast.Expr) bool { default: return false } - _, ok := typeparams.GetInstances(info)[id] + _, ok := info.Instances[id] return ok } // instanceArgs returns the Instance[id].TypeArgs as a slice. func instanceArgs(info *types.Info, id *ast.Ident) []types.Type { - targList := typeparams.GetInstances(info)[id].TypeArgs + targList := info.Instances[id].TypeArgs if targList == nil { return nil } @@ -287,13 +291,40 @@ func (c *canonizer) List(ts []types.Type) *typeList { return nil } + unaliasAll := func(ts []types.Type) []types.Type { + // Is there some top level alias? + var found bool + for _, t := range ts { + if _, ok := t.(*aliases.Alias); ok { + found = true + break + } + } + if !found { + return ts // no top level alias + } + + cp := make([]types.Type, len(ts)) // copy with top level aliases removed. + for i, t := range ts { + cp[i] = aliases.Unalias(t) + } + return cp + } + l := unaliasAll(ts) + c.mu.Lock() defer c.mu.Unlock() - return c.lists.rep(ts) + return c.lists.rep(l) } // Type returns a canonical representative of type T. +// Removes top-level aliases. +// +// For performance, reasons the canonical instance is order-dependent, +// and may contain deeply nested aliases. func (c *canonizer) Type(T types.Type) types.Type { + T = aliases.Unalias(T) // remove the top level alias. + c.mu.Lock() defer c.mu.Unlock() @@ -370,13 +401,13 @@ func (m *typeListMap) hash(ts []types.Type) uint32 { } // instantiateMethod instantiates m with targs and returns a canonical representative for this method. -func (canon *canonizer) instantiateMethod(m *types.Func, targs []types.Type, ctxt *typeparams.Context) *types.Func { +func (canon *canonizer) instantiateMethod(m *types.Func, targs []types.Type, ctxt *types.Context) *types.Func { recv := recvType(m) - if p, ok := recv.(*types.Pointer); ok { + if p, ok := aliases.Unalias(recv).(*types.Pointer); ok { recv = p.Elem() } - named := recv.(*types.Named) - inst, err := typeparams.Instantiate(ctxt, typeparams.NamedTypeOrigin(named), targs, false) + named := aliases.Unalias(recv).(*types.Named) + inst, err := types.Instantiate(ctxt, named.Origin(), targs, false) if err != nil { panic(err) } @@ -384,3 +415,16 @@ func (canon *canonizer) instantiateMethod(m *types.Func, targs []types.Type, ctx obj, _, _ := types.LookupFieldOrMethod(rep, true, m.Pkg(), m.Name()) return obj.(*types.Func) } + +// Exposed to ssautil using the linkname hack. +func isSyntactic(pkg *Package) bool { return pkg.syntax } + +// mapValues returns a new unordered array of map values. +func mapValues[K comparable, V any](m map[K]V) []V { + vals := make([]V, 0, len(m)) + for _, fn := range m { + vals = append(vals, fn) + } + return vals + +} diff --git a/tools/vendor/golang.org/x/tools/go/ssa/util_go120.go b/tools/vendor/golang.org/x/tools/go/ssa/util_go120.go new file mode 100644 index 000000000..9e8ea874e --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/ssa/util_go120.go @@ -0,0 +1,17 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.20 +// +build go1.20 + +package ssa + +import ( + "go/ast" + "go/token" +) + +func init() { + rangePosition = func(rng *ast.RangeStmt) token.Pos { return rng.Range } +} diff --git a/tools/vendor/golang.org/x/tools/go/ssa/wrappers.go b/tools/vendor/golang.org/x/tools/go/ssa/wrappers.go index 123ea6858..d09b4f250 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/wrappers.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/wrappers.go @@ -24,11 +24,13 @@ import ( "go/token" "go/types" + + "golang.org/x/tools/internal/typeparams" ) // -- wrappers ----------------------------------------------------------- -// makeWrapper returns a synthetic method that delegates to the +// createWrapper returns a synthetic method that delegates to the // declared method denoted by meth.Obj(), first performing any // necessary pointer indirections or field selections implied by meth. // @@ -40,21 +42,17 @@ import ( // - optional implicit field selections // - meth.Obj() may denote a concrete or an interface method // - the result may be a thunk or a wrapper. -// -// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) -func makeWrapper(prog *Program, sel *selection, cr *creator) *Function { +func createWrapper(prog *Program, sel *selection) *Function { obj := sel.obj.(*types.Func) // the declared function sig := sel.typ.(*types.Signature) // type of this wrapper var recv *types.Var // wrapper's receiver or thunk's params[0] name := obj.Name() var description string - var start int // first regular param if sel.kind == types.MethodExpr { name += "$thunk" description = "thunk" recv = sig.Params().At(0) - start = 1 } else { description = "wrapper" recv = sig.Recv() @@ -62,9 +60,10 @@ func makeWrapper(prog *Program, sel *selection, cr *creator) *Function { description = fmt.Sprintf("%s for %s", description, sel.obj) if prog.mode&LogSource != 0 { - defer logStack("make %s to (%s)", description, recv.Type())() + defer logStack("create %s to (%s)", description, recv.Type())() } - fn := &Function{ + /* method wrapper */ + return &Function{ name: name, method: sel, object: obj, @@ -72,35 +71,49 @@ func makeWrapper(prog *Program, sel *selection, cr *creator) *Function { Synthetic: description, Prog: prog, pos: obj.Pos(), - info: nil, // info is not set on wrappers. + // wrappers have no syntax + build: (*builder).buildWrapper, + syntax: nil, + info: nil, + goversion: "", } - cr.Add(fn) +} + +// buildWrapper builds fn.Body for a method wrapper. +func (b *builder) buildWrapper(fn *Function) { + var recv *types.Var // wrapper's receiver or thunk's params[0] + var start int // first regular param + if fn.method.kind == types.MethodExpr { + recv = fn.Signature.Params().At(0) + start = 1 + } else { + recv = fn.Signature.Recv() + } + fn.startBody() fn.addSpilledParam(recv) createParams(fn, start) - indices := sel.index + indices := fn.method.index var v Value = fn.Locals[0] // spilled receiver - srdt, ptrRecv := deptr(sel.recv) - if ptrRecv { + if isPointer(fn.method.recv) { v = emitLoad(fn, v) // For simple indirection wrappers, perform an informative nil-check: // "value method (T).f called using nil *T pointer" - _, ptrObj := deptr(recvType(obj)) - if len(indices) == 1 && !ptrObj { + if len(indices) == 1 && !isPointer(recvType(fn.object)) { var c Call c.Call.Value = &Builtin{ name: "ssa:wrapnilchk", sig: types.NewSignature(nil, - types.NewTuple(anonVar(sel.recv), anonVar(tString), anonVar(tString)), - types.NewTuple(anonVar(sel.recv)), false), + types.NewTuple(anonVar(fn.method.recv), anonVar(tString), anonVar(tString)), + types.NewTuple(anonVar(fn.method.recv)), false), } c.Call.Args = []Value{ v, - stringConst(srdt.String()), - stringConst(sel.obj.Name()), + stringConst(typeparams.MustDeref(fn.method.recv).String()), + stringConst(fn.method.obj.Name()), } c.setType(v.Type()) v = fn.emit(&c) @@ -122,18 +135,14 @@ func makeWrapper(prog *Program, sel *selection, cr *creator) *Function { // address of implicit C field. var c Call - if r := recvType(obj); !types.IsInterface(r) { // concrete method - if _, ptrObj := deptr(r); !ptrObj { + if r := recvType(fn.object); !types.IsInterface(r) { // concrete method + if !isPointer(r) { v = emitLoad(fn, v) } - callee := prog.originFunc(obj) - if callee.typeparams.Len() > 0 { - callee = prog.lookupOrCreateInstance(callee, receiverTypeArgs(obj), cr) - } - c.Call.Value = callee + c.Call.Value = fn.Prog.objectMethod(fn.object, b) c.Call.Args = append(c.Call.Args, v) } else { - c.Call.Method = obj + c.Call.Method = fn.object c.Call.Value = emitLoad(fn, v) // interface (possibly a typeparam) } for _, arg := range fn.Params[1:] { @@ -141,8 +150,6 @@ func makeWrapper(prog *Program, sel *selection, cr *creator) *Function { } emitTailCall(fn, &c) fn.finishBody() - fn.done() - return fn } // createParams creates parameters for wrapper method fn based on its @@ -151,13 +158,13 @@ func makeWrapper(prog *Program, sel *selection, cr *creator) *Function { func createParams(fn *Function, start int) { tparams := fn.Signature.Params() for i, n := start, tparams.Len(); i < n; i++ { - fn.addParamObj(tparams.At(i)) + fn.addParamVar(tparams.At(i)) } } // -- bounds ----------------------------------------------------------- -// makeBound returns a bound method wrapper (or "bound"), a synthetic +// createBound returns a bound method wrapper (or "bound"), a synthetic // function that delegates to a concrete or interface method denoted // by obj. The resulting function has no receiver, but has one free // variable which will be used as the method's receiver in the @@ -176,66 +183,56 @@ func createParams(fn *Function, start int) { // // f := func() { return t.meth() } // -// Unlike makeWrapper, makeBound need perform no indirection or field +// Unlike createWrapper, createBound need perform no indirection or field // selections because that can be done before the closure is // constructed. -// -// EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu) -func makeBound(prog *Program, obj *types.Func, cr *creator) *Function { - targs := receiverTypeArgs(obj) - key := boundsKey{obj, prog.canon.List(targs)} - - prog.methodsMu.Lock() - defer prog.methodsMu.Unlock() - fn, ok := prog.bounds[key] - if !ok { - description := fmt.Sprintf("bound method wrapper for %s", obj) - if prog.mode&LogSource != 0 { - defer logStack("%s", description)() - } - fn = &Function{ - name: obj.Name() + "$bound", - object: obj, - Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver - Synthetic: description, - Prog: prog, - pos: obj.Pos(), - info: nil, // info is not set on wrappers. - } - cr.Add(fn) - - fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn} - fn.FreeVars = []*FreeVar{fv} - fn.startBody() - createParams(fn, 0) - var c Call - - if !types.IsInterface(recvType(obj)) { // concrete - callee := prog.originFunc(obj) - if callee.typeparams.Len() > 0 { - callee = prog.lookupOrCreateInstance(callee, targs, cr) - } - c.Call.Value = callee - c.Call.Args = []Value{fv} - } else { - c.Call.Method = obj - c.Call.Value = fv // interface (possibly a typeparam) - } - for _, arg := range fn.Params { - c.Call.Args = append(c.Call.Args, arg) - } - emitTailCall(fn, &c) - fn.finishBody() - fn.done() - - prog.bounds[key] = fn +func createBound(prog *Program, obj *types.Func) *Function { + description := fmt.Sprintf("bound method wrapper for %s", obj) + if prog.mode&LogSource != 0 { + defer logStack("%s", description)() + } + /* bound method wrapper */ + fn := &Function{ + name: obj.Name() + "$bound", + object: obj, + Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver + Synthetic: description, + Prog: prog, + pos: obj.Pos(), + // wrappers have no syntax + build: (*builder).buildBound, + syntax: nil, + info: nil, + goversion: "", } + fn.FreeVars = []*FreeVar{{name: "recv", typ: recvType(obj), parent: fn}} // (cyclic) return fn } +// buildBound builds fn.Body for a bound method closure. +func (b *builder) buildBound(fn *Function) { + fn.startBody() + createParams(fn, 0) + var c Call + + recv := fn.FreeVars[0] + if !types.IsInterface(recvType(fn.object)) { // concrete + c.Call.Value = fn.Prog.objectMethod(fn.object, b) + c.Call.Args = []Value{recv} + } else { + c.Call.Method = fn.object + c.Call.Value = recv // interface (possibly a typeparam) + } + for _, arg := range fn.Params { + c.Call.Args = append(c.Call.Args, arg) + } + emitTailCall(fn, &c) + fn.finishBody() +} + // -- thunks ----------------------------------------------------------- -// makeThunk returns a thunk, a synthetic function that delegates to a +// createThunk returns a thunk, a synthetic function that delegates to a // concrete or interface method denoted by sel.obj. The resulting // function has no receiver, but has an additional (first) regular // parameter. @@ -251,38 +248,16 @@ func makeBound(prog *Program, obj *types.Func, cr *creator) *Function { // f is a synthetic wrapper defined as if by: // // f := func(t T) { return t.meth() } -// -// TODO(adonovan): opt: currently the stub is created even when used -// directly in a function call: C.f(i, 0). This is less efficient -// than inlining the stub. -// -// EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu) -func makeThunk(prog *Program, sel *selection, cr *creator) *Function { +func createThunk(prog *Program, sel *selection) *Function { if sel.kind != types.MethodExpr { panic(sel) } - // Canonicalize sel.recv to avoid constructing duplicate thunks. - canonRecv := prog.canon.Type(sel.recv) - key := selectionKey{ - kind: sel.kind, - recv: canonRecv, - obj: sel.obj, - index: fmt.Sprint(sel.index), - indirect: sel.indirect, + fn := createWrapper(prog, sel) + if fn.Signature.Recv() != nil { + panic(fn) // unexpected receiver } - prog.methodsMu.Lock() - defer prog.methodsMu.Unlock() - - fn, ok := prog.thunks[key] - if !ok { - fn = makeWrapper(prog, sel, cr) - if fn.Signature.Recv() != nil { - panic(fn) // unexpected receiver - } - prog.thunks[key] = fn - } return fn } @@ -290,21 +265,6 @@ func changeRecv(s *types.Signature, recv *types.Var) *types.Signature { return types.NewSignature(recv, s.Params(), s.Results(), s.Variadic()) } -// selectionKey is like types.Selection but a usable map key. -type selectionKey struct { - kind types.SelectionKind - recv types.Type // canonicalized via Program.canon - obj types.Object - index string - indirect bool -} - -// boundsKey is a unique for the object and a type instantiation. -type boundsKey struct { - obj types.Object // t.meth - inst *typeList // canonical type instantiation list. -} - // A local version of *types.Selection. // Needed for some additional control, such as creating a MethodExpr for an instantiation. type selection struct { @@ -329,16 +289,16 @@ func toSelection(sel *types.Selection) *selection { // -- instantiations -------------------------------------------------- -// buildInstantiationWrapper creates a body for an instantiation +// buildInstantiationWrapper builds the body of an instantiation // wrapper fn. The body calls the original generic function, // bracketed by ChangeType conversions on its arguments and results. -func buildInstantiationWrapper(fn *Function) { +func (b *builder) buildInstantiationWrapper(fn *Function) { orig := fn.topLevelOrigin sig := fn.Signature fn.startBody() if sig.Recv() != nil { - fn.addParamObj(sig.Recv()) + fn.addParamVar(sig.Recv()) } createParams(fn, 0) diff --git a/tools/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go b/tools/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go index fa5834baf..9ada17775 100644 --- a/tools/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go +++ b/tools/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go @@ -26,15 +26,15 @@ package objectpath import ( "fmt" "go/types" - "sort" "strconv" "strings" - _ "unsafe" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typesinternal" ) +// TODO(adonovan): think about generic aliases. + // A Path is an opaque name that identifies a types.Object // relative to its package. Conceptually, the name consists of a // sequence of destructuring operations applied to the package scope @@ -51,7 +51,7 @@ type Path string // // PO package->object Package.Scope.Lookup // OT object->type Object.Type -// TT type->type Type.{Elem,Key,Params,Results,Underlying} [EKPRU] +// TT type->type Type.{Elem,Key,{,{,Recv}Type}Params,Results,Underlying,Rhs} [EKPRUTrCa] // TO type->object Type.{At,Field,Method,Obj} [AFMO] // // All valid paths start with a package and end at an object @@ -63,8 +63,8 @@ type Path string // - The only PO operator is Package.Scope.Lookup, which requires an identifier. // - The only OT operator is Object.Type, // which we encode as '.' because dot cannot appear in an identifier. -// - The TT operators are encoded as [EKPRUTC]; -// one of these (TypeParam) requires an integer operand, +// - The TT operators are encoded as [EKPRUTrCa]; +// two of these ({,Recv}TypeParams) require an integer operand, // which is encoded as a string of decimal digits. // - The TO operators are encoded as [AFMO]; // three of these (At,Field,Method) require an integer operand, @@ -98,19 +98,21 @@ const ( opType = '.' // .Type() (Object) // type->type operators - opElem = 'E' // .Elem() (Pointer, Slice, Array, Chan, Map) - opKey = 'K' // .Key() (Map) - opParams = 'P' // .Params() (Signature) - opResults = 'R' // .Results() (Signature) - opUnderlying = 'U' // .Underlying() (Named) - opTypeParam = 'T' // .TypeParams.At(i) (Named, Signature) - opConstraint = 'C' // .Constraint() (TypeParam) + opElem = 'E' // .Elem() (Pointer, Slice, Array, Chan, Map) + opKey = 'K' // .Key() (Map) + opParams = 'P' // .Params() (Signature) + opResults = 'R' // .Results() (Signature) + opUnderlying = 'U' // .Underlying() (Named) + opTypeParam = 'T' // .TypeParams.At(i) (Named, Signature) + opRecvTypeParam = 'r' // .RecvTypeParams.At(i) (Signature) + opConstraint = 'C' // .Constraint() (TypeParam) + opRhs = 'a' // .Rhs() (Alias) // type->object operators - opAt = 'A' // .At(i) (Tuple) - opField = 'F' // .Field(i) (Struct) - opMethod = 'M' // .Method(i) (Named or Interface; not Struct: "promoted" names are ignored) - opObj = 'O' // .Obj() (Named, TypeParam) + opAt = 'A' // .At(i) (Tuple) + opField = 'F' // .Field(i) (Struct) + opMethod = 'M' // .Method(i) (Named or Interface; not Struct: "promoted" names are ignored) + opObj = 'O' // .Obj() (Named, TypeParam) ) // For is equivalent to new(Encoder).For(obj). @@ -123,20 +125,7 @@ func For(obj types.Object) (Path, error) { // An Encoder amortizes the cost of encoding the paths of multiple objects. // The zero value of an Encoder is ready to use. type Encoder struct { - scopeMemo map[*types.Scope][]types.Object // memoization of scopeObjects - namedMethodsMemo map[*types.Named][]*types.Func // memoization of namedMethods() - skipMethodSorting bool -} - -// Expose back doors so that gopls can avoid method sorting, which can dominate -// analysis on certain repositories. -// -// TODO(golang/go#61443): remove this. -func init() { - typesinternal.SkipEncoderMethodSorting = func(enc interface{}) { - enc.(*Encoder).skipMethodSorting = true - } - typesinternal.ObjectpathObject = object + scopeMemo map[*types.Scope][]types.Object // memoization of scopeObjects } // For returns the path to an object relative to its package, @@ -239,7 +228,7 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { // Reject obviously non-viable cases. switch obj := obj.(type) { case *types.TypeName: - if _, ok := obj.Type().(*typeparams.TypeParam); !ok { + if _, ok := aliases.Unalias(obj.Type()).(*types.TypeParam); !ok { // With the exception of type parameters, only package-level type names // have a path. return "", fmt.Errorf("no path for %v", obj) @@ -291,21 +280,26 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { path = append(path, opType) T := o.Type() + if alias, ok := T.(*aliases.Alias); ok { + if r := findTypeParam(obj, aliases.TypeParams(alias), path, opTypeParam, nil); r != nil { + return Path(r), nil + } + if r := find(obj, aliases.Rhs(alias), append(path, opRhs), nil); r != nil { + return Path(r), nil + } - if tname.IsAlias() { - // type alias + } else if tname.IsAlias() { + // legacy alias if r := find(obj, T, path, nil); r != nil { return Path(r), nil } - } else { - if named, _ := T.(*types.Named); named != nil { - if r := findTypeParam(obj, typeparams.ForNamed(named), path, nil); r != nil { - // generic named type - return Path(r), nil - } - } + + } else if named, ok := T.(*types.Named); ok { // defined (named) type - if r := find(obj, T.Underlying(), append(path, opUnderlying), nil); r != nil { + if r := findTypeParam(obj, named.TypeParams(), path, opTypeParam, nil); r != nil { + return Path(r), nil + } + if r := find(obj, named.Underlying(), append(path, opUnderlying), nil); r != nil { return Path(r), nil } } @@ -326,33 +320,20 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { } // Inspect declared methods of defined types. - if T, ok := o.Type().(*types.Named); ok { + if T, ok := aliases.Unalias(o.Type()).(*types.Named); ok { path = append(path, opType) - if !enc.skipMethodSorting { - // Note that method index here is always with respect - // to canonical ordering of methods, regardless of how - // they appear in the underlying type. - for i, m := range enc.namedMethods(T) { - path2 := appendOpArg(path, opMethod, i) - if m == obj { - return Path(path2), nil // found declared method - } - if r := find(obj, m.Type(), append(path2, opType), nil); r != nil { - return Path(r), nil - } + // The method index here is always with respect + // to the underlying go/types data structures, + // which ultimately derives from source order + // and must be preserved by export data. + for i := 0; i < T.NumMethods(); i++ { + m := T.Method(i) + path2 := appendOpArg(path, opMethod, i) + if m == obj { + return Path(path2), nil // found declared method } - } else { - // This branch must match the logic in the branch above, using go/types - // APIs without sorting. - for i := 0; i < T.NumMethods(); i++ { - m := T.Method(i) - path2 := appendOpArg(path, opMethod, i) - if m == obj { - return Path(path2), nil // found declared method - } - if r := find(obj, m.Type(), append(path2, opType), nil); r != nil { - return Path(r), nil - } + if r := find(obj, m.Type(), append(path2, opType), nil); r != nil { + return Path(r), nil } } } @@ -420,17 +401,12 @@ func (enc *Encoder) concreteMethod(meth *types.Func) (Path, bool) { // of objectpath will only be giving us origin methods, anyway, as referring // to instantiated methods is usually not useful. - if typeparams.OriginMethod(meth) != meth { + if meth.Origin() != meth { return "", false } - recvT := meth.Type().(*types.Signature).Recv().Type() - if ptr, ok := recvT.(*types.Pointer); ok { - recvT = ptr.Elem() - } - - named, ok := recvT.(*types.Named) - if !ok { + _, named := typesinternal.ReceiverNamed(meth.Type().(*types.Signature).Recv()) + if named == nil { return "", false } @@ -448,22 +424,13 @@ func (enc *Encoder) concreteMethod(meth *types.Func) (Path, bool) { path = append(path, name...) path = append(path, opType) - if !enc.skipMethodSorting { - for i, m := range enc.namedMethods(named) { - if m == meth { - path = appendOpArg(path, opMethod, i) - return Path(path), true - } - } - } else { - // This branch must match the logic of the branch above, using go/types - // APIs without sorting. - for i := 0; i < named.NumMethods(); i++ { - m := named.Method(i) - if m == meth { - path = appendOpArg(path, opMethod, i) - return Path(path), true - } + // Method indices are w.r.t. the go/types data structures, + // ultimately deriving from source order, + // which is preserved by export data. + for i := 0; i < named.NumMethods(); i++ { + if named.Method(i) == meth { + path = appendOpArg(path, opMethod, i) + return Path(path), true } } @@ -482,6 +449,8 @@ func (enc *Encoder) concreteMethod(meth *types.Func) (Path, bool) { // nil, it will be allocated as necessary. func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName]bool) []byte { switch T := T.(type) { + case *aliases.Alias: + return find(obj, aliases.Unalias(T), path, seen) case *types.Basic, *types.Named: // Named types belonging to pkg were handled already, // so T must belong to another package. No path. @@ -500,7 +469,10 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName] } return find(obj, T.Elem(), append(path, opElem), seen) case *types.Signature: - if r := findTypeParam(obj, typeparams.ForSignature(T), path, seen); r != nil { + if r := findTypeParam(obj, T.RecvTypeParams(), path, opRecvTypeParam, nil); r != nil { + return r + } + if r := findTypeParam(obj, T.TypeParams(), path, opTypeParam, seen); r != nil { return r } if r := find(obj, T.Params(), append(path, opParams), seen); r != nil { @@ -543,7 +515,7 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName] } } return nil - case *typeparams.TypeParam: + case *types.TypeParam: name := T.Obj() if name == obj { return append(path, opObj) @@ -563,10 +535,10 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName] panic(T) } -func findTypeParam(obj types.Object, list *typeparams.TypeParamList, path []byte, seen map[*types.TypeName]bool) []byte { +func findTypeParam(obj types.Object, list *types.TypeParamList, path []byte, op byte, seen map[*types.TypeName]bool) []byte { for i := 0; i < list.Len(); i++ { tparam := list.At(i) - path2 := appendOpArg(path, opTypeParam, i) + path2 := appendOpArg(path, op, i) if r := find(obj, tparam, path2, seen); r != nil { return r } @@ -576,12 +548,7 @@ func findTypeParam(obj types.Object, list *typeparams.TypeParamList, path []byte // Object returns the object denoted by path p within the package pkg. func Object(pkg *types.Package, p Path) (types.Object, error) { - return object(pkg, string(p), false) -} - -// Note: the skipMethodSorting parameter must match the value of -// Encoder.skipMethodSorting used during encoding. -func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.Object, error) { + pathstr := string(p) if pathstr == "" { return nil, fmt.Errorf("empty path") } @@ -605,7 +572,7 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O } // abstraction of *types.{Named,Signature} type hasTypeParams interface { - TypeParams() *typeparams.TypeParamList + TypeParams() *types.TypeParamList } // abstraction of *types.{Named,TypeParam} type hasObj interface { @@ -623,10 +590,10 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O code := suffix[0] suffix = suffix[1:] - // Codes [AFM] have an integer operand. + // Codes [AFMTr] have an integer operand. var index int switch code { - case opAt, opField, opMethod, opTypeParam: + case opAt, opField, opMethod, opTypeParam, opRecvTypeParam: rest := strings.TrimLeft(suffix, "0123456789") numerals := suffix[:len(suffix)-len(rest)] suffix = rest @@ -659,6 +626,7 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O // Inv: t != nil, obj == nil + t = aliases.Unalias(t) switch code { case opElem: hasElem, ok := t.(hasElem) // Pointer, Slice, Array, Chan, Map @@ -695,6 +663,16 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O } t = named.Underlying() + case opRhs: + if alias, ok := t.(*aliases.Alias); ok { + t = aliases.Rhs(alias) + } else if false && aliases.Enabled() { + // The Enabled check is too expensive, so for now we + // simply assume that aliases are not enabled. + // TODO(adonovan): replace with "if true {" when go1.24 is assured. + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want alias)", code, t, t) + } + case opTypeParam: hasTypeParams, ok := t.(hasTypeParams) // Named, Signature if !ok { @@ -706,8 +684,19 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O } t = tparams.At(index) + case opRecvTypeParam: + sig, ok := t.(*types.Signature) // Signature + if !ok { + return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) + } + rtparams := sig.RecvTypeParams() + if n := rtparams.Len(); index >= n { + return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n) + } + t = rtparams.At(index) + case opConstraint: - tparam, ok := t.(*typeparams.TypeParam) + tparam, ok := t.(*types.TypeParam) if !ok { return nil, fmt.Errorf("cannot apply %q to %s (got %T, want type parameter)", code, t, t) } @@ -747,12 +736,7 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O if index >= t.NumMethods() { return nil, fmt.Errorf("method index %d out of range [0-%d)", index, t.NumMethods()) } - if skipMethodSorting { - obj = t.Method(index) - } else { - methods := namedMethods(t) // (unmemoized) - obj = methods[index] // Id-ordered - } + obj = t.Method(index) default: return nil, fmt.Errorf("cannot apply %q to %s (got %T, want interface or named)", code, t, t) @@ -772,6 +756,10 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O } } + if obj == nil { + panic(p) // path does not end in an object-valued operator + } + if obj.Pkg() != pkg { return nil, fmt.Errorf("path denotes %s, which belongs to a different package", obj) } @@ -779,33 +767,6 @@ func object(pkg *types.Package, pathstr string, skipMethodSorting bool) (types.O return obj, nil // success } -// namedMethods returns the methods of a Named type in ascending Id order. -func namedMethods(named *types.Named) []*types.Func { - methods := make([]*types.Func, named.NumMethods()) - for i := range methods { - methods[i] = named.Method(i) - } - sort.Slice(methods, func(i, j int) bool { - return methods[i].Id() < methods[j].Id() - }) - return methods -} - -// namedMethods is a memoization of the namedMethods function. Callers must not modify the result. -func (enc *Encoder) namedMethods(named *types.Named) []*types.Func { - m := enc.namedMethodsMemo - if m == nil { - m = make(map[*types.Named][]*types.Func) - enc.namedMethodsMemo = m - } - methods, ok := m[named] - if !ok { - methods = namedMethods(named) // allocates and sorts - m[named] = methods - } - return methods -} - // scopeObjects is a memoization of scope objects. // Callers must not modify the result. func (enc *Encoder) scopeObjects(scope *types.Scope) []types.Object { diff --git a/tools/vendor/golang.org/x/tools/go/types/typeutil/callee.go b/tools/vendor/golang.org/x/tools/go/types/typeutil/callee.go index 90b3ab0e2..90dc541ad 100644 --- a/tools/vendor/golang.org/x/tools/go/types/typeutil/callee.go +++ b/tools/vendor/golang.org/x/tools/go/types/typeutil/callee.go @@ -22,7 +22,7 @@ func Callee(info *types.Info, call *ast.CallExpr) types.Object { // Look through type instantiation if necessary. isInstance := false switch fun.(type) { - case *ast.IndexExpr, *typeparams.IndexListExpr: + case *ast.IndexExpr, *ast.IndexListExpr: // When extracting the callee from an *IndexExpr, we need to check that // it is a *types.Func and not a *types.Var. // Example: Don't match a slice m within the expression `m[0]()`. diff --git a/tools/vendor/golang.org/x/tools/go/types/typeutil/map.go b/tools/vendor/golang.org/x/tools/go/types/typeutil/map.go index 7bd2fdb38..a92f80dd2 100644 --- a/tools/vendor/golang.org/x/tools/go/types/typeutil/map.go +++ b/tools/vendor/golang.org/x/tools/go/types/typeutil/map.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package typeutil defines various utilities for types, such as Map, -// a mapping from types.Type to interface{} values. +// a mapping from types.Type to any values. package typeutil // import "golang.org/x/tools/go/types/typeutil" import ( @@ -12,11 +12,12 @@ import ( "go/types" "reflect" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) // Map is a hash-table-based mapping from types (types.Type) to -// arbitrary interface{} values. The concrete types that implement +// arbitrary any values. The concrete types that implement // the Type interface are pointers. Since they are not canonicalized, // == cannot be used to check for equivalence, and thus we cannot // simply use a Go map. @@ -33,7 +34,7 @@ type Map struct { // entry is an entry (key/value association) in a hash bucket. type entry struct { key types.Type - value interface{} + value any } // SetHasher sets the hasher used by Map. @@ -81,7 +82,7 @@ func (m *Map) Delete(key types.Type) bool { // At returns the map entry for the given key. // The result is nil if the entry is not present. -func (m *Map) At(key types.Type) interface{} { +func (m *Map) At(key types.Type) any { if m != nil && m.table != nil { for _, e := range m.table[m.hasher.Hash(key)] { if e.key != nil && types.Identical(key, e.key) { @@ -94,7 +95,7 @@ func (m *Map) At(key types.Type) interface{} { // Set sets the map entry for key to val, // and returns the previous entry, if any. -func (m *Map) Set(key types.Type, value interface{}) (prev interface{}) { +func (m *Map) Set(key types.Type, value any) (prev any) { if m.table != nil { hash := m.hasher.Hash(key) bucket := m.table[hash] @@ -141,7 +142,7 @@ func (m *Map) Len() int { // f will not be invoked for it, but if f inserts a map entry that // Iterate has not yet reached, whether or not f will be invoked for // it is unspecified. -func (m *Map) Iterate(f func(key types.Type, value interface{})) { +func (m *Map) Iterate(f func(key types.Type, value any)) { if m != nil { for _, bucket := range m.table { for _, e := range bucket { @@ -157,7 +158,7 @@ func (m *Map) Iterate(f func(key types.Type, value interface{})) { // The order is unspecified. func (m *Map) Keys() []types.Type { keys := make([]types.Type, 0, m.Len()) - m.Iterate(func(key types.Type, _ interface{}) { + m.Iterate(func(key types.Type, _ any) { keys = append(keys, key) }) return keys @@ -170,7 +171,7 @@ func (m *Map) toString(values bool) string { var buf bytes.Buffer fmt.Fprint(&buf, "{") sep := "" - m.Iterate(func(key types.Type, value interface{}) { + m.Iterate(func(key types.Type, value any) { fmt.Fprint(&buf, sep) sep = ", " fmt.Fprint(&buf, key) @@ -208,7 +209,7 @@ type Hasher struct { memo map[types.Type]uint32 // ptrMap records pointer identity. - ptrMap map[interface{}]uint32 + ptrMap map[any]uint32 // sigTParams holds type parameters from the signature being hashed. // Signatures are considered identical modulo renaming of type parameters, so @@ -219,14 +220,14 @@ type Hasher struct { // generic types or functions, and instantiated signatures do not have type // parameter lists, we should never encounter a second non-empty type // parameter list when hashing a generic signature. - sigTParams *typeparams.TypeParamList + sigTParams *types.TypeParamList } // MakeHasher returns a new Hasher instance. func MakeHasher() Hasher { return Hasher{ memo: make(map[types.Type]uint32), - ptrMap: make(map[interface{}]uint32), + ptrMap: make(map[any]uint32), sigTParams: nil, } } @@ -259,6 +260,9 @@ func (h Hasher) hashFor(t types.Type) uint32 { case *types.Basic: return uint32(t.Kind()) + case *aliases.Alias: + return h.Hash(aliases.Unalias(t)) + case *types.Array: return 9043 + 2*uint32(t.Len()) + 3*h.Hash(t.Elem()) @@ -297,7 +301,7 @@ func (h Hasher) hashFor(t types.Type) uint32 { // We should never encounter a generic signature while hashing another // generic signature, but defensively set sigTParams only if h.mask is // unset. - tparams := typeparams.ForSignature(t) + tparams := t.TypeParams() if h.sigTParams == nil && tparams.Len() != 0 { h = Hasher{ // There may be something more efficient than discarding the existing @@ -318,7 +322,7 @@ func (h Hasher) hashFor(t types.Type) uint32 { return hash + 3*h.hashTuple(t.Params()) + 5*h.hashTuple(t.Results()) - case *typeparams.Union: + case *types.Union: return h.hashUnion(t) case *types.Interface: @@ -354,14 +358,14 @@ func (h Hasher) hashFor(t types.Type) uint32 { case *types.Named: hash := h.hashPtr(t.Obj()) - targs := typeparams.NamedTypeArgs(t) + targs := t.TypeArgs() for i := 0; i < targs.Len(); i++ { targ := targs.At(i) hash += 2 * h.Hash(targ) } return hash - case *typeparams.TypeParam: + case *types.TypeParam: return h.hashTypeParam(t) case *types.Tuple: @@ -381,7 +385,7 @@ func (h Hasher) hashTuple(tuple *types.Tuple) uint32 { return hash } -func (h Hasher) hashUnion(t *typeparams.Union) uint32 { +func (h Hasher) hashUnion(t *types.Union) uint32 { // Hash type restrictions. terms, err := typeparams.UnionTermSet(t) // if err != nil t has invalid type restrictions. Fall back on a non-zero @@ -392,7 +396,7 @@ func (h Hasher) hashUnion(t *typeparams.Union) uint32 { return h.hashTermSet(terms) } -func (h Hasher) hashTermSet(terms []*typeparams.Term) uint32 { +func (h Hasher) hashTermSet(terms []*types.Term) uint32 { hash := 9157 + 2*uint32(len(terms)) for _, term := range terms { // term order is not significant. @@ -416,7 +420,7 @@ func (h Hasher) hashTermSet(terms []*typeparams.Term) uint32 { // are not identical. // // Otherwise the hash of t depends only on t's pointer identity. -func (h Hasher) hashTypeParam(t *typeparams.TypeParam) uint32 { +func (h Hasher) hashTypeParam(t *types.TypeParam) uint32 { if h.sigTParams != nil { i := t.Index() if i >= 0 && i < h.sigTParams.Len() && t == h.sigTParams.At(i) { @@ -428,7 +432,7 @@ func (h Hasher) hashTypeParam(t *typeparams.TypeParam) uint32 { // hashPtr hashes the pointer identity of ptr. It uses h.ptrMap to ensure that // pointers values are not dependent on the GC. -func (h Hasher) hashPtr(ptr interface{}) uint32 { +func (h Hasher) hashPtr(ptr any) uint32 { if hash, ok := h.ptrMap[ptr]; ok { return hash } @@ -457,6 +461,9 @@ func (h Hasher) shallowHash(t types.Type) uint32 { // elements (mostly Slice, Pointer, Basic, Named), // so there's no need to optimize anything else. switch t := t.(type) { + case *aliases.Alias: + return h.shallowHash(aliases.Unalias(t)) + case *types.Signature: var hash uint32 = 604171 if t.Variadic() { @@ -489,7 +496,7 @@ func (h Hasher) shallowHash(t types.Type) uint32 { case *types.Pointer: return 4393139 - case *typeparams.Union: + case *types.Union: return 562448657 case *types.Interface: @@ -504,7 +511,7 @@ func (h Hasher) shallowHash(t types.Type) uint32 { case *types.Named: return h.hashPtr(t.Obj()) - case *typeparams.TypeParam: + case *types.TypeParam: return h.hashPtr(t.Obj()) } panic(fmt.Sprintf("shallowHash: %T: %v", t, t)) diff --git a/tools/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go b/tools/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go index a5d931083..bd71aafaa 100644 --- a/tools/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go +++ b/tools/vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go @@ -9,6 +9,8 @@ package typeutil import ( "go/types" "sync" + + "golang.org/x/tools/internal/aliases" ) // A MethodSetCache records the method set of each type T for which @@ -32,12 +34,12 @@ func (cache *MethodSetCache) MethodSet(T types.Type) *types.MethodSet { cache.mu.Lock() defer cache.mu.Unlock() - switch T := T.(type) { + switch T := aliases.Unalias(T).(type) { case *types.Named: return cache.lookupNamed(T).value case *types.Pointer: - if N, ok := T.Elem().(*types.Named); ok { + if N, ok := aliases.Unalias(T.Elem()).(*types.Named); ok { return cache.lookupNamed(N).pointer } } diff --git a/tools/vendor/golang.org/x/tools/go/types/typeutil/ui.go b/tools/vendor/golang.org/x/tools/go/types/typeutil/ui.go index fa55b0a1e..a0c1a60ac 100644 --- a/tools/vendor/golang.org/x/tools/go/types/typeutil/ui.go +++ b/tools/vendor/golang.org/x/tools/go/types/typeutil/ui.go @@ -6,7 +6,11 @@ package typeutil // This file defines utilities for user interfaces that display types. -import "go/types" +import ( + "go/types" + + "golang.org/x/tools/internal/aliases" +) // IntuitiveMethodSet returns the intuitive method set of a type T, // which is the set of methods you can call on an addressable value of @@ -24,7 +28,7 @@ import "go/types" // The order of the result is as for types.MethodSet(T). func IntuitiveMethodSet(T types.Type, msets *MethodSetCache) []*types.Selection { isPointerToConcrete := func(T types.Type) bool { - ptr, ok := T.(*types.Pointer) + ptr, ok := aliases.Unalias(T).(*types.Pointer) return ok && !types.IsInterface(ptr.Elem()) } diff --git a/tools/vendor/golang.org/x/tools/internal/aliases/aliases.go b/tools/vendor/golang.org/x/tools/internal/aliases/aliases.go new file mode 100644 index 000000000..c24c2eee4 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/aliases/aliases.go @@ -0,0 +1,32 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package aliases + +import ( + "go/token" + "go/types" +) + +// Package aliases defines backward compatible shims +// for the types.Alias type representation added in 1.22. +// This defines placeholders for x/tools until 1.26. + +// NewAlias creates a new TypeName in Package pkg that +// is an alias for the type rhs. +// +// The enabled parameter determines whether the resulting [TypeName]'s +// type is an [types.Alias]. Its value must be the result of a call to +// [Enabled], which computes the effective value of +// GODEBUG=gotypesalias=... by invoking the type checker. The Enabled +// function is expensive and should be called once per task (e.g. +// package import), not once per call to NewAlias. +func NewAlias(enabled bool, pos token.Pos, pkg *types.Package, name string, rhs types.Type) *types.TypeName { + if enabled { + tname := types.NewTypeName(pos, pkg, name, nil) + newAlias(tname, rhs) + return tname + } + return types.NewTypeName(pos, pkg, name, rhs) +} diff --git a/tools/vendor/golang.org/x/tools/internal/aliases/aliases_go121.go b/tools/vendor/golang.org/x/tools/internal/aliases/aliases_go121.go new file mode 100644 index 000000000..6652f7db0 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/aliases/aliases_go121.go @@ -0,0 +1,35 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !go1.22 +// +build !go1.22 + +package aliases + +import ( + "go/types" +) + +// Alias is a placeholder for a go/types.Alias for <=1.21. +// It will never be created by go/types. +type Alias struct{} + +func (*Alias) String() string { panic("unreachable") } +func (*Alias) Underlying() types.Type { panic("unreachable") } +func (*Alias) Obj() *types.TypeName { panic("unreachable") } +func Rhs(alias *Alias) types.Type { panic("unreachable") } +func TypeParams(alias *Alias) *types.TypeParamList { panic("unreachable") } +func SetTypeParams(alias *Alias, tparams []*types.TypeParam) { panic("unreachable") } +func TypeArgs(alias *Alias) *types.TypeList { panic("unreachable") } +func Origin(alias *Alias) *Alias { panic("unreachable") } + +// Unalias returns the type t for go <=1.21. +func Unalias(t types.Type) types.Type { return t } + +func newAlias(name *types.TypeName, rhs types.Type) *Alias { panic("unreachable") } + +// Enabled reports whether [NewAlias] should create [types.Alias] types. +// +// Before go1.22, this function always returns false. +func Enabled() bool { return false } diff --git a/tools/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go b/tools/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go new file mode 100644 index 000000000..3ef1afeb4 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/aliases/aliases_go122.go @@ -0,0 +1,99 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.22 +// +build go1.22 + +package aliases + +import ( + "go/ast" + "go/parser" + "go/token" + "go/types" +) + +// Alias is an alias of types.Alias. +type Alias = types.Alias + +// Rhs returns the type on the right-hand side of the alias declaration. +func Rhs(alias *Alias) types.Type { + if alias, ok := any(alias).(interface{ Rhs() types.Type }); ok { + return alias.Rhs() // go1.23+ + } + + // go1.22's Alias didn't have the Rhs method, + // so Unalias is the best we can do. + return Unalias(alias) +} + +// TypeParams returns the type parameter list of the alias. +func TypeParams(alias *Alias) *types.TypeParamList { + if alias, ok := any(alias).(interface{ TypeParams() *types.TypeParamList }); ok { + return alias.TypeParams() // go1.23+ + } + return nil +} + +// SetTypeParams sets the type parameters of the alias type. +func SetTypeParams(alias *Alias, tparams []*types.TypeParam) { + if alias, ok := any(alias).(interface { + SetTypeParams(tparams []*types.TypeParam) + }); ok { + alias.SetTypeParams(tparams) // go1.23+ + } else if len(tparams) > 0 { + panic("cannot set type parameters of an Alias type in go1.22") + } +} + +// TypeArgs returns the type arguments used to instantiate the Alias type. +func TypeArgs(alias *Alias) *types.TypeList { + if alias, ok := any(alias).(interface{ TypeArgs() *types.TypeList }); ok { + return alias.TypeArgs() // go1.23+ + } + return nil // empty (go1.22) +} + +// Origin returns the generic Alias type of which alias is an instance. +// If alias is not an instance of a generic alias, Origin returns alias. +func Origin(alias *Alias) *Alias { + if alias, ok := any(alias).(interface{ Origin() *types.Alias }); ok { + return alias.Origin() // go1.23+ + } + return alias // not an instance of a generic alias (go1.22) +} + +// Unalias is a wrapper of types.Unalias. +func Unalias(t types.Type) types.Type { return types.Unalias(t) } + +// newAlias is an internal alias around types.NewAlias. +// Direct usage is discouraged as the moment. +// Try to use NewAlias instead. +func newAlias(tname *types.TypeName, rhs types.Type) *Alias { + a := types.NewAlias(tname, rhs) + // TODO(go.dev/issue/65455): Remove kludgy workaround to set a.actual as a side-effect. + Unalias(a) + return a +} + +// Enabled reports whether [NewAlias] should create [types.Alias] types. +// +// This function is expensive! Call it sparingly. +func Enabled() bool { + // The only reliable way to compute the answer is to invoke go/types. + // We don't parse the GODEBUG environment variable, because + // (a) it's tricky to do so in a manner that is consistent + // with the godebug package; in particular, a simple + // substring check is not good enough. The value is a + // rightmost-wins list of options. But more importantly: + // (b) it is impossible to detect changes to the effective + // setting caused by os.Setenv("GODEBUG"), as happens in + // many tests. Therefore any attempt to cache the result + // is just incorrect. + fset := token.NewFileSet() + f, _ := parser.ParseFile(fset, "a.go", "package p; type A = int", 0) + pkg, _ := new(types.Config).Check("p", fset, []*ast.File{f}, nil) + _, enabled := pkg.Scope().Lookup("A").Type().(*types.Alias) + return enabled +} diff --git a/tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go b/tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go new file mode 100644 index 000000000..e0b13e70a --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go @@ -0,0 +1,513 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package analysisinternal provides gopls' internal analyses with a +// number of helper functions that operate on typed syntax trees. +package analysisinternal + +import ( + "bytes" + "fmt" + "go/ast" + "go/token" + "go/types" + "os" + pathpkg "path" + "strconv" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/internal/aliases" +) + +func TypeErrorEndPos(fset *token.FileSet, src []byte, start token.Pos) token.Pos { + // Get the end position for the type error. + offset, end := fset.PositionFor(start, false).Offset, start + if offset >= len(src) { + return end + } + if width := bytes.IndexAny(src[offset:], " \n,():;[]+-*"); width > 0 { + end = start + token.Pos(width) + } + return end +} + +func ZeroValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { + // TODO(adonovan): think about generics, and also generic aliases. + under := aliases.Unalias(typ) + // Don't call Underlying unconditionally: although it removes + // Named and Alias, it also removes TypeParam. + if n, ok := under.(*types.Named); ok { + under = n.Underlying() + } + switch under := under.(type) { + case *types.Basic: + switch { + case under.Info()&types.IsNumeric != 0: + return &ast.BasicLit{Kind: token.INT, Value: "0"} + case under.Info()&types.IsBoolean != 0: + return &ast.Ident{Name: "false"} + case under.Info()&types.IsString != 0: + return &ast.BasicLit{Kind: token.STRING, Value: `""`} + default: + panic(fmt.Sprintf("unknown basic type %v", under)) + } + case *types.Chan, *types.Interface, *types.Map, *types.Pointer, *types.Signature, *types.Slice, *types.Array: + return ast.NewIdent("nil") + case *types.Struct: + texpr := TypeExpr(f, pkg, typ) // typ because we want the name here. + if texpr == nil { + return nil + } + return &ast.CompositeLit{ + Type: texpr, + } + } + return nil +} + +// IsZeroValue checks whether the given expression is a 'zero value' (as determined by output of +// analysisinternal.ZeroValue) +func IsZeroValue(expr ast.Expr) bool { + switch e := expr.(type) { + case *ast.BasicLit: + return e.Value == "0" || e.Value == `""` + case *ast.Ident: + return e.Name == "nil" || e.Name == "false" + default: + return false + } +} + +// TypeExpr returns syntax for the specified type. References to +// named types from packages other than pkg are qualified by an appropriate +// package name, as defined by the import environment of file. +func TypeExpr(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { + switch t := typ.(type) { + case *types.Basic: + switch t.Kind() { + case types.UnsafePointer: + return &ast.SelectorExpr{X: ast.NewIdent("unsafe"), Sel: ast.NewIdent("Pointer")} + default: + return ast.NewIdent(t.Name()) + } + case *types.Pointer: + x := TypeExpr(f, pkg, t.Elem()) + if x == nil { + return nil + } + return &ast.UnaryExpr{ + Op: token.MUL, + X: x, + } + case *types.Array: + elt := TypeExpr(f, pkg, t.Elem()) + if elt == nil { + return nil + } + return &ast.ArrayType{ + Len: &ast.BasicLit{ + Kind: token.INT, + Value: fmt.Sprintf("%d", t.Len()), + }, + Elt: elt, + } + case *types.Slice: + elt := TypeExpr(f, pkg, t.Elem()) + if elt == nil { + return nil + } + return &ast.ArrayType{ + Elt: elt, + } + case *types.Map: + key := TypeExpr(f, pkg, t.Key()) + value := TypeExpr(f, pkg, t.Elem()) + if key == nil || value == nil { + return nil + } + return &ast.MapType{ + Key: key, + Value: value, + } + case *types.Chan: + dir := ast.ChanDir(t.Dir()) + if t.Dir() == types.SendRecv { + dir = ast.SEND | ast.RECV + } + value := TypeExpr(f, pkg, t.Elem()) + if value == nil { + return nil + } + return &ast.ChanType{ + Dir: dir, + Value: value, + } + case *types.Signature: + var params []*ast.Field + for i := 0; i < t.Params().Len(); i++ { + p := TypeExpr(f, pkg, t.Params().At(i).Type()) + if p == nil { + return nil + } + params = append(params, &ast.Field{ + Type: p, + Names: []*ast.Ident{ + { + Name: t.Params().At(i).Name(), + }, + }, + }) + } + if t.Variadic() { + last := params[len(params)-1] + last.Type = &ast.Ellipsis{Elt: last.Type.(*ast.ArrayType).Elt} + } + var returns []*ast.Field + for i := 0; i < t.Results().Len(); i++ { + r := TypeExpr(f, pkg, t.Results().At(i).Type()) + if r == nil { + return nil + } + returns = append(returns, &ast.Field{ + Type: r, + }) + } + return &ast.FuncType{ + Params: &ast.FieldList{ + List: params, + }, + Results: &ast.FieldList{ + List: returns, + }, + } + case interface{ Obj() *types.TypeName }: // *types.{Alias,Named,TypeParam} + if t.Obj().Pkg() == nil { + return ast.NewIdent(t.Obj().Name()) + } + if t.Obj().Pkg() == pkg { + return ast.NewIdent(t.Obj().Name()) + } + pkgName := t.Obj().Pkg().Name() + + // If the file already imports the package under another name, use that. + for _, cand := range f.Imports { + if path, _ := strconv.Unquote(cand.Path.Value); path == t.Obj().Pkg().Path() { + if cand.Name != nil && cand.Name.Name != "" { + pkgName = cand.Name.Name + } + } + } + if pkgName == "." { + return ast.NewIdent(t.Obj().Name()) + } + return &ast.SelectorExpr{ + X: ast.NewIdent(pkgName), + Sel: ast.NewIdent(t.Obj().Name()), + } + case *types.Struct: + return ast.NewIdent(t.String()) + case *types.Interface: + return ast.NewIdent(t.String()) + default: + return nil + } +} + +// StmtToInsertVarBefore returns the ast.Stmt before which we can safely insert a new variable. +// Some examples: +// +// Basic Example: +// z := 1 +// y := z + x +// If x is undeclared, then this function would return `y := z + x`, so that we +// can insert `x := ` on the line before `y := z + x`. +// +// If stmt example: +// if z == 1 { +// } else if z == y {} +// If y is undeclared, then this function would return `if z == 1 {`, because we cannot +// insert a statement between an if and an else if statement. As a result, we need to find +// the top of the if chain to insert `y := ` before. +func StmtToInsertVarBefore(path []ast.Node) ast.Stmt { + enclosingIndex := -1 + for i, p := range path { + if _, ok := p.(ast.Stmt); ok { + enclosingIndex = i + break + } + } + if enclosingIndex == -1 { + return nil + } + enclosingStmt := path[enclosingIndex] + switch enclosingStmt.(type) { + case *ast.IfStmt: + // The enclosingStmt is inside of the if declaration, + // We need to check if we are in an else-if stmt and + // get the base if statement. + return baseIfStmt(path, enclosingIndex) + case *ast.CaseClause: + // Get the enclosing switch stmt if the enclosingStmt is + // inside of the case statement. + for i := enclosingIndex + 1; i < len(path); i++ { + if node, ok := path[i].(*ast.SwitchStmt); ok { + return node + } else if node, ok := path[i].(*ast.TypeSwitchStmt); ok { + return node + } + } + } + if len(path) <= enclosingIndex+1 { + return enclosingStmt.(ast.Stmt) + } + // Check if the enclosing statement is inside another node. + switch expr := path[enclosingIndex+1].(type) { + case *ast.IfStmt: + // Get the base if statement. + return baseIfStmt(path, enclosingIndex+1) + case *ast.ForStmt: + if expr.Init == enclosingStmt || expr.Post == enclosingStmt { + return expr + } + case *ast.SwitchStmt, *ast.TypeSwitchStmt: + return expr.(ast.Stmt) + } + return enclosingStmt.(ast.Stmt) +} + +// baseIfStmt walks up the if/else-if chain until we get to +// the top of the current if chain. +func baseIfStmt(path []ast.Node, index int) ast.Stmt { + stmt := path[index] + for i := index + 1; i < len(path); i++ { + if node, ok := path[i].(*ast.IfStmt); ok && node.Else == stmt { + stmt = node + continue + } + break + } + return stmt.(ast.Stmt) +} + +// WalkASTWithParent walks the AST rooted at n. The semantics are +// similar to ast.Inspect except it does not call f(nil). +func WalkASTWithParent(n ast.Node, f func(n ast.Node, parent ast.Node) bool) { + var ancestors []ast.Node + ast.Inspect(n, func(n ast.Node) (recurse bool) { + if n == nil { + ancestors = ancestors[:len(ancestors)-1] + return false + } + + var parent ast.Node + if len(ancestors) > 0 { + parent = ancestors[len(ancestors)-1] + } + ancestors = append(ancestors, n) + return f(n, parent) + }) +} + +// MatchingIdents finds the names of all identifiers in 'node' that match any of the given types. +// 'pos' represents the position at which the identifiers may be inserted. 'pos' must be within +// the scope of each of identifier we select. Otherwise, we will insert a variable at 'pos' that +// is unrecognized. +func MatchingIdents(typs []types.Type, node ast.Node, pos token.Pos, info *types.Info, pkg *types.Package) map[types.Type][]string { + + // Initialize matches to contain the variable types we are searching for. + matches := make(map[types.Type][]string) + for _, typ := range typs { + if typ == nil { + continue // TODO(adonovan): is this reachable? + } + matches[typ] = nil // create entry + } + + seen := map[types.Object]struct{}{} + ast.Inspect(node, func(n ast.Node) bool { + if n == nil { + return false + } + // Prevent circular definitions. If 'pos' is within an assignment statement, do not + // allow any identifiers in that assignment statement to be selected. Otherwise, + // we could do the following, where 'x' satisfies the type of 'f0': + // + // x := fakeStruct{f0: x} + // + if assign, ok := n.(*ast.AssignStmt); ok && pos > assign.Pos() && pos <= assign.End() { + return false + } + if n.End() > pos { + return n.Pos() <= pos + } + ident, ok := n.(*ast.Ident) + if !ok || ident.Name == "_" { + return true + } + obj := info.Defs[ident] + if obj == nil || obj.Type() == nil { + return true + } + if _, ok := obj.(*types.TypeName); ok { + return true + } + // Prevent duplicates in matches' values. + if _, ok = seen[obj]; ok { + return true + } + seen[obj] = struct{}{} + // Find the scope for the given position. Then, check whether the object + // exists within the scope. + innerScope := pkg.Scope().Innermost(pos) + if innerScope == nil { + return true + } + _, foundObj := innerScope.LookupParent(ident.Name, pos) + if foundObj != obj { + return true + } + // The object must match one of the types that we are searching for. + // TODO(adonovan): opt: use typeutil.Map? + if names, ok := matches[obj.Type()]; ok { + matches[obj.Type()] = append(names, ident.Name) + } else { + // If the object type does not exactly match + // any of the target types, greedily find the first + // target type that the object type can satisfy. + for typ := range matches { + if equivalentTypes(obj.Type(), typ) { + matches[typ] = append(matches[typ], ident.Name) + } + } + } + return true + }) + return matches +} + +func equivalentTypes(want, got types.Type) bool { + if types.Identical(want, got) { + return true + } + // Code segment to help check for untyped equality from (golang/go#32146). + if rhs, ok := want.(*types.Basic); ok && rhs.Info()&types.IsUntyped > 0 { + if lhs, ok := got.Underlying().(*types.Basic); ok { + return rhs.Info()&types.IsConstType == lhs.Info()&types.IsConstType + } + } + return types.AssignableTo(want, got) +} + +// MakeReadFile returns a simple implementation of the Pass.ReadFile function. +func MakeReadFile(pass *analysis.Pass) func(filename string) ([]byte, error) { + return func(filename string) ([]byte, error) { + if err := CheckReadable(pass, filename); err != nil { + return nil, err + } + return os.ReadFile(filename) + } +} + +// CheckReadable enforces the access policy defined by the ReadFile field of [analysis.Pass]. +func CheckReadable(pass *analysis.Pass, filename string) error { + if slicesContains(pass.OtherFiles, filename) || + slicesContains(pass.IgnoredFiles, filename) { + return nil + } + for _, f := range pass.Files { + // TODO(adonovan): use go1.20 f.FileStart + if pass.Fset.File(f.Pos()).Name() == filename { + return nil + } + } + return fmt.Errorf("Pass.ReadFile: %s is not among OtherFiles, IgnoredFiles, or names of Files", filename) +} + +// TODO(adonovan): use go1.21 slices.Contains. +func slicesContains[S ~[]E, E comparable](slice S, x E) bool { + for _, elem := range slice { + if elem == x { + return true + } + } + return false +} + +// AddImport checks whether this file already imports pkgpath and +// that import is in scope at pos. If so, it returns the name under +// which it was imported and a zero edit. Otherwise, it adds a new +// import of pkgpath, using a name derived from the preferred name, +// and returns the chosen name along with the edit for the new import. +// +// It does not mutate its arguments. +func AddImport(info *types.Info, file *ast.File, pos token.Pos, pkgpath, preferredName string) (name string, newImport []analysis.TextEdit) { + // Find innermost enclosing lexical block. + scope := info.Scopes[file].Innermost(pos) + if scope == nil { + panic("no enclosing lexical block") + } + + // Is there an existing import of this package? + // If so, are we in its scope? (not shadowed) + for _, spec := range file.Imports { + pkgname, ok := importedPkgName(info, spec) + if ok && pkgname.Imported().Path() == pkgpath { + if _, obj := scope.LookupParent(pkgname.Name(), pos); obj == pkgname { + return pkgname.Name(), nil + } + } + } + + // We must add a new import. + // Ensure we have a fresh name. + newName := preferredName + for i := 0; ; i++ { + if _, obj := scope.LookupParent(newName, pos); obj == nil { + break // fresh + } + newName = fmt.Sprintf("%s%d", preferredName, i) + } + + // For now, keep it real simple: create a new import + // declaration before the first existing declaration (which + // must exist), including its comments, and let goimports tidy it up. + // + // Use a renaming import whenever the preferred name is not + // available, or the chosen name does not match the last + // segment of its path. + newText := fmt.Sprintf("import %q\n\n", pkgpath) + if newName != preferredName || newName != pathpkg.Base(pkgpath) { + newText = fmt.Sprintf("import %s %q\n\n", newName, pkgpath) + } + decl0 := file.Decls[0] + var before ast.Node = decl0 + switch decl0 := decl0.(type) { + case *ast.GenDecl: + if decl0.Doc != nil { + before = decl0.Doc + } + case *ast.FuncDecl: + if decl0.Doc != nil { + before = decl0.Doc + } + } + return newName, []analysis.TextEdit{{ + Pos: before.Pos(), + End: before.Pos(), + NewText: []byte(newText), + }} +} + +// importedPkgName returns the PkgName object declared by an ImportSpec. +// TODO(adonovan): use go1.22's Info.PkgNameOf. +func importedPkgName(info *types.Info, imp *ast.ImportSpec) (*types.PkgName, bool) { + var obj types.Object + if imp.Name != nil { + obj = info.Defs[imp.Name] + } else { + obj = info.Implicits[imp] + } + pkgname, ok := obj.(*types.PkgName) + return pkgname, ok +} diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/internal/analysisutil/extractdoc.go b/tools/vendor/golang.org/x/tools/internal/analysisinternal/extractdoc.go similarity index 99% rename from tools/vendor/golang.org/x/tools/go/analysis/passes/internal/analysisutil/extractdoc.go rename to tools/vendor/golang.org/x/tools/internal/analysisinternal/extractdoc.go index 0e175ca06..39507723d 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/internal/analysisutil/extractdoc.go +++ b/tools/vendor/golang.org/x/tools/internal/analysisinternal/extractdoc.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package analysisutil +package analysisinternal import ( "fmt" diff --git a/tools/vendor/golang.org/x/tools/internal/event/keys/util.go b/tools/vendor/golang.org/x/tools/internal/event/keys/util.go new file mode 100644 index 000000000..c0e8e731c --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/event/keys/util.go @@ -0,0 +1,21 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package keys + +import ( + "sort" + "strings" +) + +// Join returns a canonical join of the keys in S: +// a sorted comma-separated string list. +func Join[S ~[]T, T ~string](s S) string { + strs := make([]string, 0, len(s)) + for _, v := range s { + strs = append(strs, string(v)) + } + sort.Strings(strs) + return strings.Join(strs, ",") +} diff --git a/tools/vendor/golang.org/x/tools/internal/event/tag/tag.go b/tools/vendor/golang.org/x/tools/internal/event/tag/tag.go deleted file mode 100644 index 581b26c20..000000000 --- a/tools/vendor/golang.org/x/tools/internal/event/tag/tag.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package tag provides the labels used for telemetry throughout gopls. -package tag - -import ( - "golang.org/x/tools/internal/event/keys" -) - -var ( - // create the label keys we use - Method = keys.NewString("method", "") - StatusCode = keys.NewString("status.code", "") - StatusMessage = keys.NewString("status.message", "") - RPCID = keys.NewString("id", "") - RPCDirection = keys.NewString("direction", "") - File = keys.NewString("file", "") - Directory = keys.New("directory", "") - URI = keys.New("URI", "") - Package = keys.NewString("package", "") // sorted comma-separated list of Package IDs - PackagePath = keys.NewString("package_path", "") - Query = keys.New("query", "") - Snapshot = keys.NewUInt64("snapshot", "") - Operation = keys.NewString("operation", "") - - Position = keys.New("position", "") - Category = keys.NewString("category", "") - PackageCount = keys.NewInt("packages", "") - Files = keys.New("files", "") - Port = keys.NewInt("port", "") - Type = keys.New("type", "") - HoverKind = keys.NewString("hoverkind", "") - - NewServer = keys.NewString("new_server", "A new server was added") - EndServer = keys.NewString("end_server", "A server was shut down") - - ServerID = keys.NewString("server", "The server ID an event is related to") - Logfile = keys.NewString("logfile", "") - DebugAddress = keys.NewString("debug_address", "") - GoplsPath = keys.NewString("gopls_path", "") - ClientID = keys.NewString("client_id", "") - - Level = keys.NewInt("level", "The logging level") -) - -var ( - // create the stats we measure - Started = keys.NewInt64("started", "Count of started RPCs.") - ReceivedBytes = keys.NewInt64("received_bytes", "Bytes received.") //, unit.Bytes) - SentBytes = keys.NewInt64("sent_bytes", "Bytes sent.") //, unit.Bytes) - Latency = keys.NewFloat64("latency_ms", "Elapsed time in milliseconds") //, unit.Milliseconds) -) - -const ( - Inbound = "in" - Outbound = "out" -) diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go deleted file mode 100644 index c40c7e931..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package fastwalk provides a faster version of [filepath.Walk] for file system -// scanning tools. -package fastwalk - -import ( - "errors" - "os" - "path/filepath" - "runtime" - "sync" -) - -// ErrTraverseLink is used as a return value from WalkFuncs to indicate that the -// symlink named in the call may be traversed. -var ErrTraverseLink = errors.New("fastwalk: traverse symlink, assuming target is a directory") - -// ErrSkipFiles is a used as a return value from WalkFuncs to indicate that the -// callback should not be called for any other files in the current directory. -// Child directories will still be traversed. -var ErrSkipFiles = errors.New("fastwalk: skip remaining files in directory") - -// Walk is a faster implementation of [filepath.Walk]. -// -// [filepath.Walk]'s design necessarily calls [os.Lstat] on each file, -// even if the caller needs less info. -// Many tools need only the type of each file. -// On some platforms, this information is provided directly by the readdir -// system call, avoiding the need to stat each file individually. -// fastwalk_unix.go contains a fork of the syscall routines. -// -// See golang.org/issue/16399. -// -// Walk walks the file tree rooted at root, calling walkFn for -// each file or directory in the tree, including root. -// -// If Walk returns [filepath.SkipDir], the directory is skipped. -// -// Unlike [filepath.Walk]: -// - file stat calls must be done by the user. -// The only provided metadata is the file type, which does not include -// any permission bits. -// - multiple goroutines stat the filesystem concurrently. The provided -// walkFn must be safe for concurrent use. -// - Walk can follow symlinks if walkFn returns the TraverseLink -// sentinel error. It is the walkFn's responsibility to prevent -// Walk from going into symlink cycles. -func Walk(root string, walkFn func(path string, typ os.FileMode) error) error { - // TODO(bradfitz): make numWorkers configurable? We used a - // minimum of 4 to give the kernel more info about multiple - // things we want, in hopes its I/O scheduling can take - // advantage of that. Hopefully most are in cache. Maybe 4 is - // even too low of a minimum. Profile more. - numWorkers := 4 - if n := runtime.NumCPU(); n > numWorkers { - numWorkers = n - } - - // Make sure to wait for all workers to finish, otherwise - // walkFn could still be called after returning. This Wait call - // runs after close(e.donec) below. - var wg sync.WaitGroup - defer wg.Wait() - - w := &walker{ - fn: walkFn, - enqueuec: make(chan walkItem, numWorkers), // buffered for performance - workc: make(chan walkItem, numWorkers), // buffered for performance - donec: make(chan struct{}), - - // buffered for correctness & not leaking goroutines: - resc: make(chan error, numWorkers), - } - defer close(w.donec) - - for i := 0; i < numWorkers; i++ { - wg.Add(1) - go w.doWork(&wg) - } - todo := []walkItem{{dir: root}} - out := 0 - for { - workc := w.workc - var workItem walkItem - if len(todo) == 0 { - workc = nil - } else { - workItem = todo[len(todo)-1] - } - select { - case workc <- workItem: - todo = todo[:len(todo)-1] - out++ - case it := <-w.enqueuec: - todo = append(todo, it) - case err := <-w.resc: - out-- - if err != nil { - return err - } - if out == 0 && len(todo) == 0 { - // It's safe to quit here, as long as the buffered - // enqueue channel isn't also readable, which might - // happen if the worker sends both another unit of - // work and its result before the other select was - // scheduled and both w.resc and w.enqueuec were - // readable. - select { - case it := <-w.enqueuec: - todo = append(todo, it) - default: - return nil - } - } - } - } -} - -// doWork reads directories as instructed (via workc) and runs the -// user's callback function. -func (w *walker) doWork(wg *sync.WaitGroup) { - defer wg.Done() - for { - select { - case <-w.donec: - return - case it := <-w.workc: - select { - case <-w.donec: - return - case w.resc <- w.walk(it.dir, !it.callbackDone): - } - } - } -} - -type walker struct { - fn func(path string, typ os.FileMode) error - - donec chan struct{} // closed on fastWalk's return - workc chan walkItem // to workers - enqueuec chan walkItem // from workers - resc chan error // from workers -} - -type walkItem struct { - dir string - callbackDone bool // callback already called; don't do it again -} - -func (w *walker) enqueue(it walkItem) { - select { - case w.enqueuec <- it: - case <-w.donec: - } -} - -func (w *walker) onDirEnt(dirName, baseName string, typ os.FileMode) error { - joined := dirName + string(os.PathSeparator) + baseName - if typ == os.ModeDir { - w.enqueue(walkItem{dir: joined}) - return nil - } - - err := w.fn(joined, typ) - if typ == os.ModeSymlink { - if err == ErrTraverseLink { - // Set callbackDone so we don't call it twice for both the - // symlink-as-symlink and the symlink-as-directory later: - w.enqueue(walkItem{dir: joined, callbackDone: true}) - return nil - } - if err == filepath.SkipDir { - // Permit SkipDir on symlinks too. - return nil - } - } - return err -} - -func (w *walker) walk(root string, runUserCallback bool) error { - if runUserCallback { - err := w.fn(root, os.ModeDir) - if err == filepath.SkipDir { - return nil - } - if err != nil { - return err - } - } - - return readDir(root, w.onDirEnt) -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_darwin.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_darwin.go deleted file mode 100644 index 0ca55e0d5..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_darwin.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build darwin && cgo -// +build darwin,cgo - -package fastwalk - -/* -#include - -// fastwalk_readdir_r wraps readdir_r so that we don't have to pass a dirent** -// result pointer which triggers CGO's "Go pointer to Go pointer" check unless -// we allocat the result dirent* with malloc. -// -// fastwalk_readdir_r returns 0 on success, -1 upon reaching the end of the -// directory, or a positive error number to indicate failure. -static int fastwalk_readdir_r(DIR *fd, struct dirent *entry) { - struct dirent *result; - int ret = readdir_r(fd, entry, &result); - if (ret == 0 && result == NULL) { - ret = -1; // EOF - } - return ret; -} -*/ -import "C" - -import ( - "os" - "syscall" - "unsafe" -) - -func readDir(dirName string, fn func(dirName, entName string, typ os.FileMode) error) error { - fd, err := openDir(dirName) - if err != nil { - return &os.PathError{Op: "opendir", Path: dirName, Err: err} - } - defer C.closedir(fd) - - skipFiles := false - var dirent syscall.Dirent - for { - ret := int(C.fastwalk_readdir_r(fd, (*C.struct_dirent)(unsafe.Pointer(&dirent)))) - if ret != 0 { - if ret == -1 { - break // EOF - } - if ret == int(syscall.EINTR) { - continue - } - return &os.PathError{Op: "readdir", Path: dirName, Err: syscall.Errno(ret)} - } - if dirent.Ino == 0 { - continue - } - typ := dtToType(dirent.Type) - if skipFiles && typ.IsRegular() { - continue - } - name := (*[len(syscall.Dirent{}.Name)]byte)(unsafe.Pointer(&dirent.Name))[:] - name = name[:dirent.Namlen] - for i, c := range name { - if c == 0 { - name = name[:i] - break - } - } - // Check for useless names before allocating a string. - if string(name) == "." || string(name) == ".." { - continue - } - if err := fn(dirName, string(name), typ); err != nil { - if err != ErrSkipFiles { - return err - } - skipFiles = true - } - } - - return nil -} - -func dtToType(typ uint8) os.FileMode { - switch typ { - case syscall.DT_BLK: - return os.ModeDevice - case syscall.DT_CHR: - return os.ModeDevice | os.ModeCharDevice - case syscall.DT_DIR: - return os.ModeDir - case syscall.DT_FIFO: - return os.ModeNamedPipe - case syscall.DT_LNK: - return os.ModeSymlink - case syscall.DT_REG: - return 0 - case syscall.DT_SOCK: - return os.ModeSocket - } - return ^os.FileMode(0) -} - -// openDir wraps opendir(3) and handles any EINTR errors. The returned *DIR -// needs to be closed with closedir(3). -func openDir(path string) (*C.DIR, error) { - name, err := syscall.BytePtrFromString(path) - if err != nil { - return nil, err - } - for { - fd, err := C.opendir((*C.char)(unsafe.Pointer(name))) - if err != syscall.EINTR { - return fd, err - } - } -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_fileno.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_fileno.go deleted file mode 100644 index d58595dbd..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_fileno.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build freebsd || openbsd || netbsd -// +build freebsd openbsd netbsd - -package fastwalk - -import "syscall" - -func direntInode(dirent *syscall.Dirent) uint64 { - return uint64(dirent.Fileno) -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_ino.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_ino.go deleted file mode 100644 index d3922890b..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_ino.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build (linux || (darwin && !cgo)) && !appengine -// +build linux darwin,!cgo -// +build !appengine - -package fastwalk - -import "syscall" - -func direntInode(dirent *syscall.Dirent) uint64 { - return dirent.Ino -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_bsd.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_bsd.go deleted file mode 100644 index 38a4db6af..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_bsd.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build (darwin && !cgo) || freebsd || openbsd || netbsd -// +build darwin,!cgo freebsd openbsd netbsd - -package fastwalk - -import "syscall" - -func direntNamlen(dirent *syscall.Dirent) uint64 { - return uint64(dirent.Namlen) -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_linux.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_linux.go deleted file mode 100644 index c82e57df8..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_dirent_namlen_linux.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux && !appengine -// +build linux,!appengine - -package fastwalk - -import ( - "bytes" - "syscall" - "unsafe" -) - -func direntNamlen(dirent *syscall.Dirent) uint64 { - const fixedHdr = uint16(unsafe.Offsetof(syscall.Dirent{}.Name)) - nameBuf := (*[unsafe.Sizeof(dirent.Name)]byte)(unsafe.Pointer(&dirent.Name[0])) - const nameBufLen = uint16(len(nameBuf)) - limit := dirent.Reclen - fixedHdr - if limit > nameBufLen { - limit = nameBufLen - } - nameLen := bytes.IndexByte(nameBuf[:limit], 0) - if nameLen < 0 { - panic("failed to find terminating 0 byte in dirent") - } - return uint64(nameLen) -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go deleted file mode 100644 index 27e860243..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build appengine || (!linux && !darwin && !freebsd && !openbsd && !netbsd) -// +build appengine !linux,!darwin,!freebsd,!openbsd,!netbsd - -package fastwalk - -import ( - "os" -) - -// readDir calls fn for each directory entry in dirName. -// It does not descend into directories or follow symlinks. -// If fn returns a non-nil error, readDir returns with that error -// immediately. -func readDir(dirName string, fn func(dirName, entName string, typ os.FileMode) error) error { - fis, err := os.ReadDir(dirName) - if err != nil { - return err - } - skipFiles := false - for _, fi := range fis { - info, err := fi.Info() - if err != nil { - return err - } - if info.Mode().IsRegular() && skipFiles { - continue - } - if err := fn(dirName, fi.Name(), info.Mode()&os.ModeType); err != nil { - if err == ErrSkipFiles { - skipFiles = true - continue - } - return err - } - } - return nil -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_unix.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_unix.go deleted file mode 100644 index f12f1a734..000000000 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_unix.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build (linux || freebsd || openbsd || netbsd || (darwin && !cgo)) && !appengine -// +build linux freebsd openbsd netbsd darwin,!cgo -// +build !appengine - -package fastwalk - -import ( - "fmt" - "os" - "syscall" - "unsafe" -) - -const blockSize = 8 << 10 - -// unknownFileMode is a sentinel (and bogus) os.FileMode -// value used to represent a syscall.DT_UNKNOWN Dirent.Type. -const unknownFileMode os.FileMode = os.ModeNamedPipe | os.ModeSocket | os.ModeDevice - -func readDir(dirName string, fn func(dirName, entName string, typ os.FileMode) error) error { - fd, err := open(dirName, 0, 0) - if err != nil { - return &os.PathError{Op: "open", Path: dirName, Err: err} - } - defer syscall.Close(fd) - - // The buffer must be at least a block long. - buf := make([]byte, blockSize) // stack-allocated; doesn't escape - bufp := 0 // starting read position in buf - nbuf := 0 // end valid data in buf - skipFiles := false - for { - if bufp >= nbuf { - bufp = 0 - nbuf, err = readDirent(fd, buf) - if err != nil { - return os.NewSyscallError("readdirent", err) - } - if nbuf <= 0 { - return nil - } - } - consumed, name, typ := parseDirEnt(buf[bufp:nbuf]) - bufp += consumed - if name == "" || name == "." || name == ".." { - continue - } - // Fallback for filesystems (like old XFS) that don't - // support Dirent.Type and have DT_UNKNOWN (0) there - // instead. - if typ == unknownFileMode { - fi, err := os.Lstat(dirName + "/" + name) - if err != nil { - // It got deleted in the meantime. - if os.IsNotExist(err) { - continue - } - return err - } - typ = fi.Mode() & os.ModeType - } - if skipFiles && typ.IsRegular() { - continue - } - if err := fn(dirName, name, typ); err != nil { - if err == ErrSkipFiles { - skipFiles = true - continue - } - return err - } - } -} - -func parseDirEnt(buf []byte) (consumed int, name string, typ os.FileMode) { - // golang.org/issue/37269 - dirent := &syscall.Dirent{} - copy((*[unsafe.Sizeof(syscall.Dirent{})]byte)(unsafe.Pointer(dirent))[:], buf) - if v := unsafe.Offsetof(dirent.Reclen) + unsafe.Sizeof(dirent.Reclen); uintptr(len(buf)) < v { - panic(fmt.Sprintf("buf size of %d smaller than dirent header size %d", len(buf), v)) - } - if len(buf) < int(dirent.Reclen) { - panic(fmt.Sprintf("buf size %d < record length %d", len(buf), dirent.Reclen)) - } - consumed = int(dirent.Reclen) - if direntInode(dirent) == 0 { // File absent in directory. - return - } - switch dirent.Type { - case syscall.DT_REG: - typ = 0 - case syscall.DT_DIR: - typ = os.ModeDir - case syscall.DT_LNK: - typ = os.ModeSymlink - case syscall.DT_BLK: - typ = os.ModeDevice - case syscall.DT_FIFO: - typ = os.ModeNamedPipe - case syscall.DT_SOCK: - typ = os.ModeSocket - case syscall.DT_UNKNOWN: - typ = unknownFileMode - default: - // Skip weird things. - // It's probably a DT_WHT (http://lwn.net/Articles/325369/) - // or something. Revisit if/when this package is moved outside - // of goimports. goimports only cares about regular files, - // symlinks, and directories. - return - } - - nameBuf := (*[unsafe.Sizeof(dirent.Name)]byte)(unsafe.Pointer(&dirent.Name[0])) - nameLen := direntNamlen(dirent) - - // Special cases for common things: - if nameLen == 1 && nameBuf[0] == '.' { - name = "." - } else if nameLen == 2 && nameBuf[0] == '.' && nameBuf[1] == '.' { - name = ".." - } else { - name = string(nameBuf[:nameLen]) - } - return -} - -// According to https://golang.org/doc/go1.14#runtime -// A consequence of the implementation of preemption is that on Unix systems, including Linux and macOS -// systems, programs built with Go 1.14 will receive more signals than programs built with earlier releases. -// -// This causes syscall.Open and syscall.ReadDirent sometimes fail with EINTR errors. -// We need to retry in this case. -func open(path string, mode int, perm uint32) (fd int, err error) { - for { - fd, err := syscall.Open(path, mode, perm) - if err != syscall.EINTR { - return fd, err - } - } -} - -func readDirent(fd int, buf []byte) (n int, err error) { - for { - nbuf, err := syscall.ReadDirent(fd, buf) - if err != syscall.EINTR { - return nbuf, err - } - } -} diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go index 2d078ccb1..39df91124 100644 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go +++ b/tools/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go @@ -259,13 +259,6 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func return } -func deref(typ types.Type) types.Type { - if p, _ := typ.(*types.Pointer); p != nil { - return p.Elem() - } - return typ -} - type byPath []*types.Package func (a byPath) Len() int { return len(a) } diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/iexport.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/iexport.go index 6103dd710..deeb67f31 100644 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/iexport.go +++ b/tools/vendor/golang.org/x/tools/internal/gcimporter/iexport.go @@ -23,8 +23,8 @@ import ( "strings" "golang.org/x/tools/go/types/objectpath" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/tokeninternal" - "golang.org/x/tools/internal/typeparams" ) // IExportShallow encodes "shallow" export data for the specified package. @@ -464,7 +464,7 @@ func (p *iexporter) doDecl(obj types.Object) { switch obj := obj.(type) { case *types.Var: - w.tag('V') + w.tag(varTag) w.pos(obj.Pos()) w.typ(obj.Type(), obj.Pkg()) @@ -481,10 +481,10 @@ func (p *iexporter) doDecl(obj types.Object) { } // Function. - if typeparams.ForSignature(sig).Len() == 0 { - w.tag('F') + if sig.TypeParams().Len() == 0 { + w.tag(funcTag) } else { - w.tag('G') + w.tag(genericFuncTag) } w.pos(obj.Pos()) // The tparam list of the function type is the declaration of the type @@ -494,27 +494,27 @@ func (p *iexporter) doDecl(obj types.Object) { // // While importing the type parameters, tparamList computes and records // their export name, so that it can be later used when writing the index. - if tparams := typeparams.ForSignature(sig); tparams.Len() > 0 { + if tparams := sig.TypeParams(); tparams.Len() > 0 { w.tparamList(obj.Name(), tparams, obj.Pkg()) } w.signature(sig) case *types.Const: - w.tag('C') + w.tag(constTag) w.pos(obj.Pos()) w.value(obj.Type(), obj.Val()) case *types.TypeName: t := obj.Type() - if tparam, ok := t.(*typeparams.TypeParam); ok { - w.tag('P') + if tparam, ok := aliases.Unalias(t).(*types.TypeParam); ok { + w.tag(typeParamTag) w.pos(obj.Pos()) constraint := tparam.Constraint() if p.version >= iexportVersionGo1_18 { implicit := false - if iface, _ := constraint.(*types.Interface); iface != nil { - implicit = typeparams.IsImplicit(iface) + if iface, _ := aliases.Unalias(constraint).(*types.Interface); iface != nil { + implicit = iface.IsImplicit() } w.bool(implicit) } @@ -523,8 +523,13 @@ func (p *iexporter) doDecl(obj types.Object) { } if obj.IsAlias() { - w.tag('A') + w.tag(aliasTag) w.pos(obj.Pos()) + if alias, ok := t.(*aliases.Alias); ok { + // Preserve materialized aliases, + // even of non-exported types. + t = aliases.Rhs(alias) + } w.typ(t, obj.Pkg()) break } @@ -535,20 +540,20 @@ func (p *iexporter) doDecl(obj types.Object) { panic(internalErrorf("%s is not a defined type", t)) } - if typeparams.ForNamed(named).Len() == 0 { - w.tag('T') + if named.TypeParams().Len() == 0 { + w.tag(typeTag) } else { - w.tag('U') + w.tag(genericTypeTag) } w.pos(obj.Pos()) - if typeparams.ForNamed(named).Len() > 0 { + if named.TypeParams().Len() > 0 { // While importing the type parameters, tparamList computes and records // their export name, so that it can be later used when writing the index. - w.tparamList(obj.Name(), typeparams.ForNamed(named), obj.Pkg()) + w.tparamList(obj.Name(), named.TypeParams(), obj.Pkg()) } - underlying := obj.Type().Underlying() + underlying := named.Underlying() w.typ(underlying, obj.Pkg()) if types.IsInterface(t) { @@ -565,7 +570,7 @@ func (p *iexporter) doDecl(obj types.Object) { // Receiver type parameters are type arguments of the receiver type, so // their name must be qualified before exporting recv. - if rparams := typeparams.RecvTypeParams(sig); rparams.Len() > 0 { + if rparams := sig.RecvTypeParams(); rparams.Len() > 0 { prefix := obj.Name() + "." + m.Name() for i := 0; i < rparams.Len(); i++ { rparam := rparams.At(i) @@ -739,20 +744,25 @@ func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { }() } switch t := t.(type) { + case *aliases.Alias: + // TODO(adonovan): support parameterized aliases, following *types.Named. + w.startType(aliasType) + w.qualifiedType(t.Obj()) + case *types.Named: - if targs := typeparams.NamedTypeArgs(t); targs.Len() > 0 { + if targs := t.TypeArgs(); targs.Len() > 0 { w.startType(instanceType) // TODO(rfindley): investigate if this position is correct, and if it // matters. w.pos(t.Obj().Pos()) w.typeList(targs, pkg) - w.typ(typeparams.NamedTypeOrigin(t), pkg) + w.typ(t.Origin(), pkg) return } w.startType(definedType) w.qualifiedType(t.Obj()) - case *typeparams.TypeParam: + case *types.TypeParam: w.startType(typeParamType) w.qualifiedType(t.Obj()) @@ -844,7 +854,7 @@ func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { for i := 0; i < n; i++ { ft := t.EmbeddedType(i) tPkg := pkg - if named, _ := ft.(*types.Named); named != nil { + if named, _ := aliases.Unalias(ft).(*types.Named); named != nil { w.pos(named.Obj().Pos()) } else { w.pos(token.NoPos) @@ -868,7 +878,7 @@ func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { w.signature(sig) } - case *typeparams.Union: + case *types.Union: w.startType(unionType) nt := t.Len() w.uint64(uint64(nt)) @@ -948,14 +958,14 @@ func (w *exportWriter) signature(sig *types.Signature) { } } -func (w *exportWriter) typeList(ts *typeparams.TypeList, pkg *types.Package) { +func (w *exportWriter) typeList(ts *types.TypeList, pkg *types.Package) { w.uint64(uint64(ts.Len())) for i := 0; i < ts.Len(); i++ { w.typ(ts.At(i), pkg) } } -func (w *exportWriter) tparamList(prefix string, list *typeparams.TypeParamList, pkg *types.Package) { +func (w *exportWriter) tparamList(prefix string, list *types.TypeParamList, pkg *types.Package) { ll := uint64(list.Len()) w.uint64(ll) for i := 0; i < list.Len(); i++ { @@ -973,7 +983,7 @@ const blankMarker = "$" // differs from its actual object name: it is prefixed with a qualifier, and // blank type parameter names are disambiguated by their index in the type // parameter list. -func tparamExportName(prefix string, tparam *typeparams.TypeParam) string { +func tparamExportName(prefix string, tparam *types.TypeParam) string { assert(prefix != "") name := tparam.Obj().Name() if name == "_" { diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/iimport.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/iimport.go index 8e64cf644..136aa0365 100644 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/iimport.go +++ b/tools/vendor/golang.org/x/tools/internal/gcimporter/iimport.go @@ -22,7 +22,8 @@ import ( "strings" "golang.org/x/tools/go/types/objectpath" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/aliases" + "golang.org/x/tools/internal/typesinternal" ) type intReader struct { @@ -79,6 +80,20 @@ const ( typeParamType instanceType unionType + aliasType +) + +// Object tags +const ( + varTag = 'V' + funcTag = 'F' + genericFuncTag = 'G' + constTag = 'C' + aliasTag = 'A' + genericAliasTag = 'B' + typeParamTag = 'P' + typeTag = 'T' + genericTypeTag = 'U' ) // IImportData imports a package from the serialized package data @@ -195,6 +210,7 @@ func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte p := iimporter{ version: int(version), ipath: path, + aliases: aliases.Enabled(), shallow: shallow, reportf: reportf, @@ -225,6 +241,7 @@ func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte // Gather the relevant packages from the manifest. items := make([]GetPackagesItem, r.uint64()) + uniquePkgPaths := make(map[string]bool) for i := range items { pkgPathOff := r.uint64() pkgPath := p.stringAt(pkgPathOff) @@ -249,6 +266,12 @@ func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte } items[i].nameIndex = nameIndex + + uniquePkgPaths[pkgPath] = true + } + // Debugging #63822; hypothesis: there are duplicate PkgPaths. + if len(uniquePkgPaths) != len(items) { + reportf("found duplicate PkgPaths while reading export data manifest: %v", items) } // Request packages all at once from the client, @@ -316,12 +339,12 @@ func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte } // SetConstraint can't be called if the constraint type is not yet complete. - // When type params are created in the 'P' case of (*importReader).obj(), + // When type params are created in the typeParamTag case of (*importReader).obj(), // the associated constraint type may not be complete due to recursion. // Therefore, we defer calling SetConstraint there, and call it here instead // after all types are complete. for _, d := range p.later { - typeparams.SetTypeParamConstraint(d.t, d.constraint) + d.t.SetConstraint(d.constraint) } for _, typ := range p.interfaceList { @@ -339,7 +362,7 @@ func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte } type setConstraintArgs struct { - t *typeparams.TypeParam + t *types.TypeParam constraint types.Type } @@ -347,6 +370,7 @@ type iimporter struct { version int ipath string + aliases bool shallow bool reportf ReportFunc // if non-nil, used to report bugs @@ -516,7 +540,7 @@ func canReuse(def *types.Named, rhs types.Type) bool { if def == nil { return true } - iface, _ := rhs.(*types.Interface) + iface, _ := aliases.Unalias(rhs).(*types.Interface) if iface == nil { return true } @@ -538,25 +562,29 @@ func (r *importReader) obj(name string) { pos := r.pos() switch tag { - case 'A': + case aliasTag: typ := r.typ() - - r.declare(types.NewTypeName(pos, r.currPkg, name, typ)) - - case 'C': + // TODO(adonovan): support generic aliases: + // if tag == genericAliasTag { + // tparams := r.tparamList() + // alias.SetTypeParams(tparams) + // } + r.declare(aliases.NewAlias(r.p.aliases, pos, r.currPkg, name, typ)) + + case constTag: typ, val := r.value() r.declare(types.NewConst(pos, r.currPkg, name, typ, val)) - case 'F', 'G': - var tparams []*typeparams.TypeParam - if tag == 'G' { + case funcTag, genericFuncTag: + var tparams []*types.TypeParam + if tag == genericFuncTag { tparams = r.tparamList() } sig := r.signature(nil, nil, tparams) r.declare(types.NewFunc(pos, r.currPkg, name, sig)) - case 'T', 'U': + case typeTag, genericTypeTag: // Types can be recursive. We need to setup a stub // declaration before recursing. obj := types.NewTypeName(pos, r.currPkg, name, nil) @@ -564,9 +592,9 @@ func (r *importReader) obj(name string) { // Declare obj before calling r.tparamList, so the new type name is recognized // if used in the constraint of one of its own typeparams (see #48280). r.declare(obj) - if tag == 'U' { + if tag == genericTypeTag { tparams := r.tparamList() - typeparams.SetForNamed(named, tparams) + named.SetTypeParams(tparams) } underlying := r.p.typAt(r.uint64(), named).Underlying() @@ -581,14 +609,13 @@ func (r *importReader) obj(name string) { // If the receiver has any targs, set those as the // rparams of the method (since those are the // typeparams being used in the method sig/body). - base := baseType(recv.Type()) - assert(base != nil) - targs := typeparams.NamedTypeArgs(base) - var rparams []*typeparams.TypeParam + _, recvNamed := typesinternal.ReceiverNamed(recv) + targs := recvNamed.TypeArgs() + var rparams []*types.TypeParam if targs.Len() > 0 { - rparams = make([]*typeparams.TypeParam, targs.Len()) + rparams = make([]*types.TypeParam, targs.Len()) for i := range rparams { - rparams[i] = targs.At(i).(*typeparams.TypeParam) + rparams[i] = aliases.Unalias(targs.At(i)).(*types.TypeParam) } } msig := r.signature(recv, rparams, nil) @@ -597,7 +624,7 @@ func (r *importReader) obj(name string) { } } - case 'P': + case typeParamTag: // We need to "declare" a typeparam in order to have a name that // can be referenced recursively (if needed) in the type param's // bound. @@ -606,7 +633,7 @@ func (r *importReader) obj(name string) { } name0 := tparamName(name) tn := types.NewTypeName(pos, r.currPkg, name0, nil) - t := typeparams.NewTypeParam(tn, nil) + t := types.NewTypeParam(tn, nil) // To handle recursive references to the typeparam within its // bound, save the partial type in tparamIndex before reading the bounds. @@ -618,11 +645,11 @@ func (r *importReader) obj(name string) { } constraint := r.typ() if implicit { - iface, _ := constraint.(*types.Interface) + iface, _ := aliases.Unalias(constraint).(*types.Interface) if iface == nil { errorf("non-interface constraint marked implicit") } - typeparams.MarkImplicit(iface) + iface.MarkImplicit() } // The constraint type may not be complete, if we // are in the middle of a type recursion involving type @@ -630,7 +657,7 @@ func (r *importReader) obj(name string) { // completely set up all types in ImportData. r.p.later = append(r.p.later, setConstraintArgs{t: t, constraint: constraint}) - case 'V': + case varTag: typ := r.typ() r.declare(types.NewVar(pos, r.currPkg, name, typ)) @@ -825,7 +852,7 @@ func (r *importReader) typ() types.Type { } func isInterface(t types.Type) bool { - _, ok := t.(*types.Interface) + _, ok := aliases.Unalias(t).(*types.Interface) return ok } @@ -847,7 +874,7 @@ func (r *importReader) doType(base *types.Named) (res types.Type) { errorf("unexpected kind tag in %q: %v", r.p.ipath, k) return nil - case definedType: + case aliasType, definedType: pkg, name := r.qualifiedIdent() r.p.doDecl(pkg, name) return pkg.Scope().Lookup(name).(*types.TypeName).Type() @@ -966,7 +993,7 @@ func (r *importReader) doType(base *types.Named) (res types.Type) { // The imported instantiated type doesn't include any methods, so // we must always use the methods of the base (orig) type. // TODO provide a non-nil *Environment - t, _ := typeparams.Instantiate(nil, baseType, targs, false) + t, _ := types.Instantiate(nil, baseType, targs, false) // Workaround for golang/go#61561. See the doc for instanceList for details. r.p.instanceList = append(r.p.instanceList, t) @@ -976,11 +1003,11 @@ func (r *importReader) doType(base *types.Named) (res types.Type) { if r.p.version < iexportVersionGenerics { errorf("unexpected instantiation type") } - terms := make([]*typeparams.Term, r.uint64()) + terms := make([]*types.Term, r.uint64()) for i := range terms { - terms[i] = typeparams.NewTerm(r.bool(), r.typ()) + terms[i] = types.NewTerm(r.bool(), r.typ()) } - return typeparams.NewUnion(terms) + return types.NewUnion(terms) } } @@ -1008,23 +1035,23 @@ func (r *importReader) objectPathObject() types.Object { return obj } -func (r *importReader) signature(recv *types.Var, rparams []*typeparams.TypeParam, tparams []*typeparams.TypeParam) *types.Signature { +func (r *importReader) signature(recv *types.Var, rparams []*types.TypeParam, tparams []*types.TypeParam) *types.Signature { params := r.paramList() results := r.paramList() variadic := params.Len() > 0 && r.bool() - return typeparams.NewSignatureType(recv, rparams, tparams, params, results, variadic) + return types.NewSignatureType(recv, rparams, tparams, params, results, variadic) } -func (r *importReader) tparamList() []*typeparams.TypeParam { +func (r *importReader) tparamList() []*types.TypeParam { n := r.uint64() if n == 0 { return nil } - xs := make([]*typeparams.TypeParam, n) + xs := make([]*types.TypeParam, n) for i := range xs { // Note: the standard library importer is tolerant of nil types here, // though would panic in SetTypeParams. - xs[i] = r.typ().(*typeparams.TypeParam) + xs[i] = aliases.Unalias(r.typ()).(*types.TypeParam) } return xs } @@ -1071,13 +1098,3 @@ func (r *importReader) byte() byte { } return x } - -func baseType(typ types.Type) *types.Named { - // pointer receivers are never types.Named types - if p, _ := typ.(*types.Pointer); p != nil { - typ = p.Elem() - } - // receiver base types are always (possibly generic) types.Named types - n, _ := typ.(*types.Named) - return n -} diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/support_go117.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/support_go117.go deleted file mode 100644 index d892273ef..000000000 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/support_go117.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.18 -// +build !go1.18 - -package gcimporter - -import "go/types" - -const iexportVersion = iexportVersionGo1_11 - -func additionalPredeclared() []types.Type { - return nil -} diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/support_go118.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/support_go118.go index edbe6ea70..0cd3b91b6 100644 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/support_go118.go +++ b/tools/vendor/golang.org/x/tools/internal/gcimporter/support_go118.go @@ -2,9 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build go1.18 -// +build go1.18 - package gcimporter import "go/types" diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_no.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_no.go index 286bf4454..38b624cad 100644 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_no.go +++ b/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_no.go @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build !(go1.18 && goexperiment.unified) -// +build !go1.18 !goexperiment.unified +//go:build !goexperiment.unified +// +build !goexperiment.unified package gcimporter diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_yes.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_yes.go index b5d69ffbe..b5118d0b3 100644 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_yes.go +++ b/tools/vendor/golang.org/x/tools/internal/gcimporter/unified_yes.go @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build go1.18 && goexperiment.unified -// +build go1.18,goexperiment.unified +//go:build goexperiment.unified +// +build goexperiment.unified package gcimporter diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_no.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_no.go deleted file mode 100644 index 8eb20729c..000000000 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_no.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.18 -// +build !go1.18 - -package gcimporter - -import ( - "fmt" - "go/token" - "go/types" -) - -func UImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { - err = fmt.Errorf("go/tools compiled with a Go version earlier than 1.18 cannot read unified IR export data") - return -} diff --git a/tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go b/tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go index b977435f6..2c0770688 100644 --- a/tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go +++ b/tools/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go @@ -4,9 +4,6 @@ // Derived from go/internal/gcimporter/ureader.go -//go:build go1.18 -// +build go1.18 - package gcimporter import ( @@ -16,6 +13,7 @@ import ( "sort" "strings" + "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/pkgbits" ) @@ -28,6 +26,7 @@ type pkgReader struct { ctxt *types.Context imports map[string]*types.Package // previously imported packages, indexed by path + aliases bool // create types.Alias nodes // lazily initialized arrays corresponding to the unified IR // PosBase, Pkg, and Type sections, respectively. @@ -101,6 +100,7 @@ func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[st ctxt: ctxt, imports: imports, + aliases: aliases.Enabled(), posBases: make([]string, input.NumElems(pkgbits.RelocPosBase)), pkgs: make([]*types.Package, input.NumElems(pkgbits.RelocPkg)), @@ -526,7 +526,7 @@ func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) { case pkgbits.ObjAlias: pos := r.pos() typ := r.typ() - declare(types.NewTypeName(pos, objPkg, objName, typ)) + declare(aliases.NewAlias(r.p.aliases, pos, objPkg, objName, typ)) case pkgbits.ObjConst: pos := r.pos() @@ -553,7 +553,7 @@ func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) { // If the underlying type is an interface, we need to // duplicate its methods so we can replace the receiver // parameter's type (#49906). - if iface, ok := underlying.(*types.Interface); ok && iface.NumExplicitMethods() != 0 { + if iface, ok := aliases.Unalias(underlying).(*types.Interface); ok && iface.NumExplicitMethods() != 0 { methods := make([]*types.Func, iface.NumExplicitMethods()) for i := range methods { fn := iface.ExplicitMethod(i) diff --git a/tools/vendor/golang.org/x/tools/internal/gocommand/invoke.go b/tools/vendor/golang.org/x/tools/internal/gocommand/invoke.go index 53cf66da0..2e59ff855 100644 --- a/tools/vendor/golang.org/x/tools/internal/gocommand/invoke.go +++ b/tools/vendor/golang.org/x/tools/internal/gocommand/invoke.go @@ -8,11 +8,14 @@ package gocommand import ( "bytes" "context" + "encoding/json" "errors" "fmt" "io" "log" "os" + "os/exec" + "path/filepath" "reflect" "regexp" "runtime" @@ -21,12 +24,9 @@ import ( "sync" "time" - exec "golang.org/x/sys/execabs" - "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/event/keys" "golang.org/x/tools/internal/event/label" - "golang.org/x/tools/internal/event/tag" ) // An Runner will run go command invocations and serialize @@ -56,11 +56,14 @@ func (runner *Runner) initialize() { // 1.14: go: updating go.mod: existing contents have changed since last read var modConcurrencyError = regexp.MustCompile(`go:.*go.mod.*contents have changed`) -// verb is an event label for the go command verb. -var verb = keys.NewString("verb", "go command verb") +// event keys for go command invocations +var ( + verb = keys.NewString("verb", "go command verb") + directory = keys.NewString("directory", "") +) func invLabels(inv Invocation) []label.Label { - return []label.Label{verb.Of(inv.Verb), tag.Directory.Of(inv.WorkingDir)} + return []label.Label{verb.Of(inv.Verb), directory.Of(inv.WorkingDir)} } // Run is a convenience wrapper around RunRaw. @@ -85,6 +88,7 @@ func (runner *Runner) RunPiped(ctx context.Context, inv Invocation, stdout, stde // RunRaw runs the invocation, serializing requests only if they fight over // go.mod changes. +// Postcondition: both error results have same nilness. func (runner *Runner) RunRaw(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) { ctx, done := event.Start(ctx, "gocommand.Runner.RunRaw", invLabels(inv)...) defer done() @@ -95,23 +99,24 @@ func (runner *Runner) RunRaw(ctx context.Context, inv Invocation) (*bytes.Buffer stdout, stderr, friendlyErr, err := runner.runConcurrent(ctx, inv) // If we encounter a load concurrency error, we need to retry serially. - if friendlyErr == nil || !modConcurrencyError.MatchString(friendlyErr.Error()) { - return stdout, stderr, friendlyErr, err + if friendlyErr != nil && modConcurrencyError.MatchString(friendlyErr.Error()) { + event.Error(ctx, "Load concurrency error, will retry serially", err) + + // Run serially by calling runPiped. + stdout.Reset() + stderr.Reset() + friendlyErr, err = runner.runPiped(ctx, inv, stdout, stderr) } - event.Error(ctx, "Load concurrency error, will retry serially", err) - // Run serially by calling runPiped. - stdout.Reset() - stderr.Reset() - friendlyErr, err = runner.runPiped(ctx, inv, stdout, stderr) return stdout, stderr, friendlyErr, err } +// Postcondition: both error results have same nilness. func (runner *Runner) runConcurrent(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) { // Wait for 1 worker to become available. select { case <-ctx.Done(): - return nil, nil, nil, ctx.Err() + return nil, nil, ctx.Err(), ctx.Err() case runner.inFlight <- struct{}{}: defer func() { <-runner.inFlight }() } @@ -121,6 +126,7 @@ func (runner *Runner) runConcurrent(ctx context.Context, inv Invocation) (*bytes return stdout, stderr, friendlyErr, err } +// Postcondition: both error results have same nilness. func (runner *Runner) runPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) (error, error) { // Make sure the runner is always initialized. runner.initialize() @@ -129,7 +135,7 @@ func (runner *Runner) runPiped(ctx context.Context, inv Invocation, stdout, stde // runPiped commands. select { case <-ctx.Done(): - return nil, ctx.Err() + return ctx.Err(), ctx.Err() case runner.serialized <- struct{}{}: defer func() { <-runner.serialized }() } @@ -139,7 +145,7 @@ func (runner *Runner) runPiped(ctx context.Context, inv Invocation, stdout, stde for i := 0; i < maxInFlight; i++ { select { case <-ctx.Done(): - return nil, ctx.Err() + return ctx.Err(), ctx.Err() case runner.inFlight <- struct{}{}: // Make sure we always "return" any workers we took. defer func() { <-runner.inFlight }() @@ -156,12 +162,17 @@ type Invocation struct { BuildFlags []string // If ModFlag is set, the go command is invoked with -mod=ModFlag. + // TODO(rfindley): remove, in favor of Args. ModFlag string // If ModFile is set, the go command is invoked with -modfile=ModFile. + // TODO(rfindley): remove, in favor of Args. ModFile string - // If Overlay is set, the go command is invoked with -overlay=Overlay. + // Overlay is the name of the JSON overlay file that describes + // unsaved editor buffers; see [WriteOverlays]. + // If set, the go command is invoked with -overlay=Overlay. + // TODO(rfindley): remove, in favor of Args. Overlay string // If CleanEnv is set, the invocation will run only with the environment @@ -172,6 +183,7 @@ type Invocation struct { Logf func(format string, args ...interface{}) } +// Postcondition: both error results have same nilness. func (i *Invocation) runWithFriendlyError(ctx context.Context, stdout, stderr io.Writer) (friendlyError error, rawError error) { rawError = i.run(ctx, stdout, stderr) if rawError != nil { @@ -188,12 +200,14 @@ func (i *Invocation) runWithFriendlyError(ctx context.Context, stdout, stderr io return } -func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { - log := i.Logf - if log == nil { - log = func(string, ...interface{}) {} +// logf logs if i.Logf is non-nil. +func (i *Invocation) logf(format string, args ...any) { + if i.Logf != nil { + i.Logf(format, args...) } +} +func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { goArgs := []string{i.Verb} appendModFile := func() { @@ -247,12 +261,15 @@ func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { waitDelay.Set(reflect.ValueOf(30 * time.Second)) } - // On darwin the cwd gets resolved to the real path, which breaks anything that - // expects the working directory to keep the original path, including the + // The cwd gets resolved to the real path. On Darwin, where + // /tmp is a symlink, this breaks anything that expects the + // working directory to keep the original path, including the // go command when dealing with modules. - // The Go stdlib has a special feature where if the cwd and the PWD are the - // same node then it trusts the PWD, so by setting it in the env for the child - // process we fix up all the paths returned by the go command. + // + // os.Getwd has a special feature where if the cwd and the PWD + // are the same node then it trusts the PWD, so by setting it + // in the env for the child process we fix up all the paths + // returned by the go command. if !i.CleanEnv { cmd.Env = os.Environ() } @@ -262,7 +279,12 @@ func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { cmd.Dir = i.WorkingDir } - defer func(start time.Time) { log("%s for %v", time.Since(start), cmdDebugStr(cmd)) }(time.Now()) + debugStr := cmdDebugStr(cmd) + i.logf("starting %v", debugStr) + start := time.Now() + defer func() { + i.logf("%s for %v", time.Since(start), debugStr) + }() return runCmdContext(ctx, cmd) } @@ -343,6 +365,7 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) { } } + startTime := time.Now() err = cmd.Start() if stdoutW != nil { // The child process has inherited the pipe file, @@ -369,7 +392,7 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) { case err := <-resChan: return err case <-timer.C: - HandleHangingGoCommand(cmd.Process) + HandleHangingGoCommand(startTime, cmd) case <-ctx.Done(): } } else { @@ -403,7 +426,7 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) { return <-resChan } -func HandleHangingGoCommand(proc *os.Process) { +func HandleHangingGoCommand(start time.Time, cmd *exec.Cmd) { switch runtime.GOOS { case "linux", "darwin", "freebsd", "netbsd": fmt.Fprintln(os.Stderr, `DETECTED A HANGING GO COMMAND @@ -436,7 +459,7 @@ See golang/go#54461 for more details.`) panic(fmt.Sprintf("running %s: %v", listFiles, err)) } } - panic(fmt.Sprintf("detected hanging go command (pid %d): see golang/go#54461 for more details", proc.Pid)) + panic(fmt.Sprintf("detected hanging go command (golang/go#54461); waited %s\n\tcommand:%s\n\tpid:%d", time.Since(start), cmd, cmd.Process.Pid)) } func cmdDebugStr(cmd *exec.Cmd) string { @@ -460,3 +483,73 @@ func cmdDebugStr(cmd *exec.Cmd) string { } return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " ")) } + +// WriteOverlays writes each value in the overlay (see the Overlay +// field of go/packages.Config) to a temporary file and returns the name +// of a JSON file describing the mapping that is suitable for the "go +// list -overlay" flag. +// +// On success, the caller must call the cleanup function exactly once +// when the files are no longer needed. +func WriteOverlays(overlay map[string][]byte) (filename string, cleanup func(), err error) { + // Do nothing if there are no overlays in the config. + if len(overlay) == 0 { + return "", func() {}, nil + } + + dir, err := os.MkdirTemp("", "gocommand-*") + if err != nil { + return "", nil, err + } + + // The caller must clean up this directory, + // unless this function returns an error. + // (The cleanup operand of each return + // statement below is ignored.) + defer func() { + cleanup = func() { + os.RemoveAll(dir) + } + if err != nil { + cleanup() + cleanup = nil + } + }() + + // Write each map entry to a temporary file. + overlays := make(map[string]string) + for k, v := range overlay { + // Use a unique basename for each file (001-foo.go), + // to avoid creating nested directories. + base := fmt.Sprintf("%d-%s", 1+len(overlays), filepath.Base(k)) + filename := filepath.Join(dir, base) + err := os.WriteFile(filename, v, 0666) + if err != nil { + return "", nil, err + } + overlays[k] = filename + } + + // Write the JSON overlay file that maps logical file names to temp files. + // + // OverlayJSON is the format overlay files are expected to be in. + // The Replace map maps from overlaid paths to replacement paths: + // the Go command will forward all reads trying to open + // each overlaid path to its replacement path, or consider the overlaid + // path not to exist if the replacement path is empty. + // + // From golang/go#39958. + type OverlayJSON struct { + Replace map[string]string `json:"replace,omitempty"` + } + b, err := json.Marshal(OverlayJSON{Replace: overlays}) + if err != nil { + return "", nil, err + } + filename = filepath.Join(dir, "overlay.json") + if err := os.WriteFile(filename, b, 0666); err != nil { + return "", nil, err + } + + return filename, nil, nil +} diff --git a/tools/vendor/golang.org/x/tools/internal/gocommand/vendor.go b/tools/vendor/golang.org/x/tools/internal/gocommand/vendor.go index 2d3d408c0..e38d1fb48 100644 --- a/tools/vendor/golang.org/x/tools/internal/gocommand/vendor.go +++ b/tools/vendor/golang.org/x/tools/internal/gocommand/vendor.go @@ -107,3 +107,57 @@ func getMainModuleAnd114(ctx context.Context, inv Invocation, r *Runner) (*Modul } return mod, lines[4] == "go1.14", nil } + +// WorkspaceVendorEnabled reports whether workspace vendoring is enabled. It takes a *Runner to execute Go commands +// with the supplied context.Context and Invocation. The Invocation can contain pre-defined fields, +// of which only Verb and Args are modified to run the appropriate Go command. +// Inspired by setDefaultBuildMod in modload/init.go +func WorkspaceVendorEnabled(ctx context.Context, inv Invocation, r *Runner) (bool, []*ModuleJSON, error) { + inv.Verb = "env" + inv.Args = []string{"GOWORK"} + stdout, err := r.Run(ctx, inv) + if err != nil { + return false, nil, err + } + goWork := string(bytes.TrimSpace(stdout.Bytes())) + if fi, err := os.Stat(filepath.Join(filepath.Dir(goWork), "vendor")); err == nil && fi.IsDir() { + mainMods, err := getWorkspaceMainModules(ctx, inv, r) + if err != nil { + return false, nil, err + } + return true, mainMods, nil + } + return false, nil, nil +} + +// getWorkspaceMainModules gets the main modules' information. +// This is the information needed to figure out if vendoring should be enabled. +func getWorkspaceMainModules(ctx context.Context, inv Invocation, r *Runner) ([]*ModuleJSON, error) { + const format = `{{.Path}} +{{.Dir}} +{{.GoMod}} +{{.GoVersion}} +` + inv.Verb = "list" + inv.Args = []string{"-m", "-f", format} + stdout, err := r.Run(ctx, inv) + if err != nil { + return nil, err + } + + lines := strings.Split(strings.TrimSuffix(stdout.String(), "\n"), "\n") + if len(lines) < 4 { + return nil, fmt.Errorf("unexpected stdout: %q", stdout.String()) + } + mods := make([]*ModuleJSON, 0, len(lines)/4) + for i := 0; i < len(lines); i += 4 { + mods = append(mods, &ModuleJSON{ + Path: lines[i], + Dir: lines[i+1], + GoMod: lines[i+2], + GoVersion: lines[i+3], + Main: true, + }) + } + return mods, nil +} diff --git a/tools/vendor/golang.org/x/tools/internal/gopathwalk/walk.go b/tools/vendor/golang.org/x/tools/internal/gopathwalk/walk.go index 452e342c5..836151551 100644 --- a/tools/vendor/golang.org/x/tools/internal/gopathwalk/walk.go +++ b/tools/vendor/golang.org/x/tools/internal/gopathwalk/walk.go @@ -9,21 +9,27 @@ package gopathwalk import ( "bufio" "bytes" - "log" + "io" + "io/fs" "os" "path/filepath" + "runtime" "strings" + "sync" "time" - - "golang.org/x/tools/internal/fastwalk" ) // Options controls the behavior of a Walk call. type Options struct { // If Logf is non-nil, debug logging is enabled through this function. Logf func(format string, args ...interface{}) + // Search module caches. Also disables legacy goimports ignore rules. ModulesEnabled bool + + // Maximum number of concurrent calls to user-provided callbacks, + // or 0 for GOMAXPROCS. + Concurrency int } // RootType indicates the type of a Root. @@ -44,22 +50,28 @@ type Root struct { Type RootType } -// Walk walks Go source directories ($GOROOT, $GOPATH, etc) to find packages. -// For each package found, add will be called (concurrently) with the absolute +// Walk concurrently walks Go source directories ($GOROOT, $GOPATH, etc) to find packages. +// +// For each package found, add will be called with the absolute // paths of the containing source directory and the package directory. -// add will be called concurrently. +// +// Unlike filepath.WalkDir, Walk follows symbolic links +// (while guarding against cycles). func Walk(roots []Root, add func(root Root, dir string), opts Options) { WalkSkip(roots, add, func(Root, string) bool { return false }, opts) } -// WalkSkip walks Go source directories ($GOROOT, $GOPATH, etc) to find packages. -// For each package found, add will be called (concurrently) with the absolute +// WalkSkip concurrently walks Go source directories ($GOROOT, $GOPATH, etc) to +// find packages. +// +// For each package found, add will be called with the absolute // paths of the containing source directory and the package directory. -// For each directory that will be scanned, skip will be called (concurrently) +// For each directory that will be scanned, skip will be called // with the absolute paths of the containing source directory and the directory. // If skip returns false on a directory it will be processed. -// add will be called concurrently. -// skip will be called concurrently. +// +// Unlike filepath.WalkDir, WalkSkip follows symbolic links +// (while guarding against cycles). func WalkSkip(roots []Root, add func(root Root, dir string), skip func(root Root, dir string) bool, opts Options) { for _, root := range roots { walkDir(root, add, skip, opts) @@ -68,34 +80,51 @@ func WalkSkip(roots []Root, add func(root Root, dir string), skip func(root Root // walkDir creates a walker and starts fastwalk with this walker. func walkDir(root Root, add func(Root, string), skip func(root Root, dir string) bool, opts Options) { + if opts.Logf == nil { + opts.Logf = func(format string, args ...interface{}) {} + } if _, err := os.Stat(root.Path); os.IsNotExist(err) { - if opts.Logf != nil { - opts.Logf("skipping nonexistent directory: %v", root.Path) - } + opts.Logf("skipping nonexistent directory: %v", root.Path) return } start := time.Now() - if opts.Logf != nil { - opts.Logf("scanning %s", root.Path) + opts.Logf("scanning %s", root.Path) + + concurrency := opts.Concurrency + if concurrency == 0 { + // The walk be either CPU-bound or I/O-bound, depending on what the + // caller-supplied add function does and the details of the user's platform + // and machine. Rather than trying to fine-tune the concurrency level for a + // specific environment, we default to GOMAXPROCS: it is likely to be a good + // choice for a CPU-bound add function, and if it is instead I/O-bound, then + // dealing with I/O saturation is arguably the job of the kernel and/or + // runtime. (Oversaturating I/O seems unlikely to harm performance as badly + // as failing to saturate would.) + concurrency = runtime.GOMAXPROCS(0) } w := &walker{ root: root, add: add, skip: skip, opts: opts, + sem: make(chan struct{}, concurrency), } w.init() - if err := fastwalk.Walk(root.Path, w.walk); err != nil { - logf := opts.Logf - if logf == nil { - logf = log.Printf - } - logf("scanning directory %v: %v", root.Path, err) - } - if opts.Logf != nil { - opts.Logf("scanned %s in %v", root.Path, time.Since(start)) + w.sem <- struct{}{} + path := root.Path + if path == "" { + path = "." } + if fi, err := os.Lstat(path); err == nil { + w.walk(path, nil, fs.FileInfoToDirEntry(fi)) + } else { + w.opts.Logf("scanning directory %v: %v", root.Path, err) + } + <-w.sem + w.walking.Wait() + + opts.Logf("scanned %s in %v", root.Path, time.Since(start)) } // walker is the callback for fastwalk.Walk. @@ -105,7 +134,18 @@ type walker struct { skip func(Root, string) bool // The callback that will be invoked for every dir. dir is skipped if it returns true. opts Options // Options passed to Walk by the user. - ignoredDirs []os.FileInfo // The ignored directories, loaded from .goimportsignore files. + walking sync.WaitGroup + sem chan struct{} // Channel of semaphore tokens; send to acquire, receive to release. + ignoredDirs []string + + added sync.Map // map[string]bool +} + +// A symlinkList is a linked list of os.FileInfos for parent directories +// reached via symlinks. +type symlinkList struct { + info os.FileInfo + prev *symlinkList } // init initializes the walker based on its Options @@ -121,14 +161,8 @@ func (w *walker) init() { for _, p := range ignoredPaths { full := filepath.Join(w.root.Path, p) - if fi, err := os.Stat(full); err == nil { - w.ignoredDirs = append(w.ignoredDirs, fi) - if w.opts.Logf != nil { - w.opts.Logf("Directory added to ignore list: %s", full) - } - } else if w.opts.Logf != nil { - w.opts.Logf("Error statting ignored directory: %v", err) - } + w.ignoredDirs = append(w.ignoredDirs, full) + w.opts.Logf("Directory added to ignore list: %s", full) } } @@ -138,12 +172,10 @@ func (w *walker) init() { func (w *walker) getIgnoredDirs(path string) []string { file := filepath.Join(path, ".goimportsignore") slurp, err := os.ReadFile(file) - if w.opts.Logf != nil { - if err != nil { - w.opts.Logf("%v", err) - } else { - w.opts.Logf("Read %s", file) - } + if err != nil { + w.opts.Logf("%v", err) + } else { + w.opts.Logf("Read %s", file) } if err != nil { return nil @@ -162,9 +194,9 @@ func (w *walker) getIgnoredDirs(path string) []string { } // shouldSkipDir reports whether the file should be skipped or not. -func (w *walker) shouldSkipDir(fi os.FileInfo, dir string) bool { +func (w *walker) shouldSkipDir(dir string) bool { for _, ignoredDir := range w.ignoredDirs { - if os.SameFile(fi, ignoredDir) { + if dir == ignoredDir { return true } } @@ -176,85 +208,130 @@ func (w *walker) shouldSkipDir(fi os.FileInfo, dir string) bool { } // walk walks through the given path. -func (w *walker) walk(path string, typ os.FileMode) error { - if typ.IsRegular() { - dir := filepath.Dir(path) - if dir == w.root.Path && (w.root.Type == RootGOROOT || w.root.Type == RootGOPATH) { - // Doesn't make sense to have regular files - // directly in your $GOPATH/src or $GOROOT/src. - return fastwalk.ErrSkipFiles - } - if !strings.HasSuffix(path, ".go") { - return nil +// +// Errors are logged if w.opts.Logf is non-nil, but otherwise ignored. +func (w *walker) walk(path string, pathSymlinks *symlinkList, d fs.DirEntry) { + if d.Type()&os.ModeSymlink != 0 { + // Walk the symlink's target rather than the symlink itself. + // + // (Note that os.Stat, unlike the lower-lever os.Readlink, + // follows arbitrarily many layers of symlinks, so it will eventually + // reach either a non-symlink or a nonexistent target.) + // + // TODO(bcmills): 'go list all' itself ignores symlinks within GOROOT/src + // and GOPATH/src. Do we really need to traverse them here? If so, why? + + fi, err := os.Stat(path) + if err != nil { + w.opts.Logf("%v", err) + return } - w.add(w.root, dir) - return fastwalk.ErrSkipFiles - } - if typ == os.ModeDir { - base := filepath.Base(path) - if base == "" || base[0] == '.' || base[0] == '_' || - base == "testdata" || - (w.root.Type == RootGOROOT && w.opts.ModulesEnabled && base == "vendor") || - (!w.opts.ModulesEnabled && base == "node_modules") { - return filepath.SkipDir + // Avoid walking symlink cycles: if we have already followed a symlink to + // this directory as a parent of itself, don't follow it again. + // + // This doesn't catch the first time through a cycle, but it also minimizes + // the number of extra stat calls we make if we *don't* encounter a cycle. + // Since we don't actually expect to encounter symlink cycles in practice, + // this seems like the right tradeoff. + for parent := pathSymlinks; parent != nil; parent = parent.prev { + if os.SameFile(fi, parent.info) { + return + } } - fi, err := os.Lstat(path) - if err == nil && w.shouldSkipDir(fi, path) { - return filepath.SkipDir + + pathSymlinks = &symlinkList{ + info: fi, + prev: pathSymlinks, } - return nil + d = fs.FileInfoToDirEntry(fi) } - if typ == os.ModeSymlink { - base := filepath.Base(path) - if strings.HasPrefix(base, ".#") { - // Emacs noise. - return nil + + if d.Type().IsRegular() { + if !strings.HasSuffix(path, ".go") { + return } - if w.shouldTraverse(path) { - return fastwalk.ErrTraverseLink + + dir := filepath.Dir(path) + if dir == w.root.Path && (w.root.Type == RootGOROOT || w.root.Type == RootGOPATH) { + // Doesn't make sense to have regular files + // directly in your $GOPATH/src or $GOROOT/src. + // + // TODO(bcmills): there are many levels of directory within + // RootModuleCache where this also wouldn't make sense, + // Can we generalize this to any directory without a corresponding + // import path? + return } - } - return nil -} -// shouldTraverse reports whether the symlink fi, found in dir, -// should be followed. It makes sure symlinks were never visited -// before to avoid symlink loops. -func (w *walker) shouldTraverse(path string) bool { - ts, err := os.Stat(path) - if err != nil { - logf := w.opts.Logf - if logf == nil { - logf = log.Printf + if _, dup := w.added.LoadOrStore(dir, true); !dup { + w.add(w.root, dir) } - logf("%v", err) - return false } - if !ts.IsDir() { - return false + + if !d.IsDir() { + return + } + + base := filepath.Base(path) + if base == "" || base[0] == '.' || base[0] == '_' || + base == "testdata" || + (w.root.Type == RootGOROOT && w.opts.ModulesEnabled && base == "vendor") || + (!w.opts.ModulesEnabled && base == "node_modules") || + w.shouldSkipDir(path) { + return } - if w.shouldSkipDir(ts, filepath.Dir(path)) { - return false + + // Read the directory and walk its entries. + + f, err := os.Open(path) + if err != nil { + w.opts.Logf("%v", err) + return } - // Check for symlink loops by statting each directory component - // and seeing if any are the same file as ts. + defer f.Close() + for { - parent := filepath.Dir(path) - if parent == path { - // Made it to the root without seeing a cycle. - // Use this symlink. - return true - } - parentInfo, err := os.Stat(parent) + // We impose an arbitrary limit on the number of ReadDir results per + // directory to limit the amount of memory consumed for stale or upcoming + // directory entries. The limit trades off CPU (number of syscalls to read + // the whole directory) against RAM (reachable directory entries other than + // the one currently being processed). + // + // Since we process the directories recursively, we will end up maintaining + // a slice of entries for each level of the directory tree. + // (Compare https://go.dev/issue/36197.) + ents, err := f.ReadDir(1024) if err != nil { - return false + if err != io.EOF { + w.opts.Logf("%v", err) + } + break } - if os.SameFile(ts, parentInfo) { - // Cycle. Don't traverse. - return false + + for _, d := range ents { + nextPath := filepath.Join(path, d.Name()) + if d.IsDir() { + select { + case w.sem <- struct{}{}: + // Got a new semaphore token, so we can traverse the directory concurrently. + d := d + w.walking.Add(1) + go func() { + defer func() { + <-w.sem + w.walking.Done() + }() + w.walk(nextPath, pathSymlinks, d) + }() + continue + + default: + // No tokens available, so traverse serially. + } + } + + w.walk(nextPath, pathSymlinks, d) } - path = parent } - } diff --git a/tools/vendor/golang.org/x/tools/internal/imports/fix.go b/tools/vendor/golang.org/x/tools/internal/imports/fix.go index 01e8ba5fa..dc7d50a7a 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/fix.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/fix.go @@ -13,6 +13,7 @@ import ( "go/build" "go/parser" "go/token" + "go/types" "io/fs" "io/ioutil" "os" @@ -26,10 +27,12 @@ import ( "unicode" "unicode/utf8" + "golang.org/x/sync/errgroup" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/gopathwalk" + "golang.org/x/tools/internal/stdlib" ) // importToGroup is a list of functions which map from an import path to @@ -102,7 +105,10 @@ type packageInfo struct { // parseOtherFiles parses all the Go files in srcDir except filename, including // test files if filename looks like a test. -func parseOtherFiles(fset *token.FileSet, srcDir, filename string) []*ast.File { +// +// It returns an error only if ctx is cancelled. Files with parse errors are +// ignored. +func parseOtherFiles(ctx context.Context, fset *token.FileSet, srcDir, filename string) ([]*ast.File, error) { // This could use go/packages but it doesn't buy much, and it fails // with https://golang.org/issue/26296 in LoadFiles mode in some cases. considerTests := strings.HasSuffix(filename, "_test.go") @@ -110,11 +116,14 @@ func parseOtherFiles(fset *token.FileSet, srcDir, filename string) []*ast.File { fileBase := filepath.Base(filename) packageFileInfos, err := os.ReadDir(srcDir) if err != nil { - return nil + return nil, ctx.Err() } var files []*ast.File for _, fi := range packageFileInfos { + if ctx.Err() != nil { + return nil, ctx.Err() + } if fi.Name() == fileBase || !strings.HasSuffix(fi.Name(), ".go") { continue } @@ -130,7 +139,7 @@ func parseOtherFiles(fset *token.FileSet, srcDir, filename string) []*ast.File { files = append(files, f) } - return files + return files, ctx.Err() } // addGlobals puts the names of package vars into the provided map. @@ -254,7 +263,7 @@ type pass struct { otherFiles []*ast.File // sibling files. // Intermediate state, generated by load. - existingImports map[string]*ImportInfo + existingImports map[string][]*ImportInfo allRefs references missingRefs references @@ -299,6 +308,20 @@ func (p *pass) loadPackageNames(imports []*ImportInfo) error { return nil } +// if there is a trailing major version, remove it +func withoutVersion(nm string) string { + if v := path.Base(nm); len(v) > 0 && v[0] == 'v' { + if _, err := strconv.Atoi(v[1:]); err == nil { + // this is, for instance, called with rand/v2 and returns rand + if len(v) < len(nm) { + xnm := nm[:len(nm)-len(v)-1] + return path.Base(xnm) + } + } + } + return nm +} + // importIdentifier returns the identifier that imp will introduce. It will // guess if the package name has not been loaded, e.g. because the source // is not available. @@ -308,7 +331,7 @@ func (p *pass) importIdentifier(imp *ImportInfo) string { } known := p.knownPackages[imp.ImportPath] if known != nil && known.name != "" { - return known.name + return withoutVersion(known.name) } return ImportPathToAssumedName(imp.ImportPath) } @@ -319,7 +342,7 @@ func (p *pass) importIdentifier(imp *ImportInfo) string { func (p *pass) load() ([]*ImportFix, bool) { p.knownPackages = map[string]*packageInfo{} p.missingRefs = references{} - p.existingImports = map[string]*ImportInfo{} + p.existingImports = map[string][]*ImportInfo{} // Load basic information about the file in question. p.allRefs = collectReferences(p.f) @@ -343,14 +366,12 @@ func (p *pass) load() ([]*ImportFix, bool) { if p.loadRealPackageNames { err := p.loadPackageNames(append(imports, p.candidates...)) if err != nil { - if p.env.Logf != nil { - p.env.Logf("loading package names: %v", err) - } + p.env.logf("loading package names: %v", err) return nil, false } } for _, imp := range imports { - p.existingImports[p.importIdentifier(imp)] = imp + p.existingImports[p.importIdentifier(imp)] = append(p.existingImports[p.importIdentifier(imp)], imp) } // Find missing references. @@ -389,31 +410,33 @@ func (p *pass) fix() ([]*ImportFix, bool) { // Found everything, or giving up. Add the new imports and remove any unused. var fixes []*ImportFix - for _, imp := range p.existingImports { - // We deliberately ignore globals here, because we can't be sure - // they're in the same package. People do things like put multiple - // main packages in the same directory, and we don't want to - // remove imports if they happen to have the same name as a var in - // a different package. - if _, ok := p.allRefs[p.importIdentifier(imp)]; !ok { - fixes = append(fixes, &ImportFix{ - StmtInfo: *imp, - IdentName: p.importIdentifier(imp), - FixType: DeleteImport, - }) - continue - } + for _, identifierImports := range p.existingImports { + for _, imp := range identifierImports { + // We deliberately ignore globals here, because we can't be sure + // they're in the same package. People do things like put multiple + // main packages in the same directory, and we don't want to + // remove imports if they happen to have the same name as a var in + // a different package. + if _, ok := p.allRefs[p.importIdentifier(imp)]; !ok { + fixes = append(fixes, &ImportFix{ + StmtInfo: *imp, + IdentName: p.importIdentifier(imp), + FixType: DeleteImport, + }) + continue + } - // An existing import may need to update its import name to be correct. - if name := p.importSpecName(imp); name != imp.Name { - fixes = append(fixes, &ImportFix{ - StmtInfo: ImportInfo{ - Name: name, - ImportPath: imp.ImportPath, - }, - IdentName: p.importIdentifier(imp), - FixType: SetImportName, - }) + // An existing import may need to update its import name to be correct. + if name := p.importSpecName(imp); name != imp.Name { + fixes = append(fixes, &ImportFix{ + StmtInfo: ImportInfo{ + Name: name, + ImportPath: imp.ImportPath, + }, + IdentName: p.importIdentifier(imp), + FixType: SetImportName, + }) + } } } // Collecting fixes involved map iteration, so sort for stability. See @@ -508,9 +531,9 @@ func (p *pass) assumeSiblingImportsValid() { } for left, rights := range refs { if imp, ok := importsByName[left]; ok { - if m, ok := stdlib[imp.ImportPath]; ok { + if m, ok := stdlib.PackageSymbols[imp.ImportPath]; ok { // We have the stdlib in memory; no need to guess. - rights = copyExports(m) + rights = symbolNameSet(m) } p.addCandidate(imp, &packageInfo{ // no name; we already know it. @@ -542,6 +565,8 @@ func (p *pass) addCandidate(imp *ImportInfo, pkg *packageInfo) { // // This is declared as a variable rather than a function so goimports can // easily be extended by adding a file with an init function. +// +// DO NOT REMOVE: used internally at Google. var fixImports = fixImportsDefault func fixImportsDefault(fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) error { @@ -561,9 +586,7 @@ func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename st return nil, err } srcDir := filepath.Dir(abs) - if env.Logf != nil { - env.Logf("fixImports(filename=%q), abs=%q, srcDir=%q ...", filename, abs, srcDir) - } + env.logf("fixImports(filename=%q), abs=%q, srcDir=%q ...", filename, abs, srcDir) // First pass: looking only at f, and using the naive algorithm to // derive package names from import paths, see if the file is already @@ -574,7 +597,10 @@ func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename st return fixes, nil } - otherFiles := parseOtherFiles(fset, srcDir, filename) + otherFiles, err := parseOtherFiles(ctx, fset, srcDir, filename) + if err != nil { + return nil, err + } // Second pass: add information from other files in the same package, // like their package vars and imports. @@ -638,7 +664,7 @@ func getCandidatePkgs(ctx context.Context, wrappedCallback *scanCallback, filena dupCheck := map[string]struct{}{} // Start off with the standard library. - for importPath, exports := range stdlib { + for importPath, symbols := range stdlib.PackageSymbols { p := &pkg{ dir: filepath.Join(goenv["GOROOT"], "src", importPath), importPathShort: importPath, @@ -647,6 +673,13 @@ func getCandidatePkgs(ctx context.Context, wrappedCallback *scanCallback, filena } dupCheck[importPath] = struct{}{} if notSelf(p) && wrappedCallback.dirFound(p) && wrappedCallback.packageNameLoaded(p) { + var exports []stdlib.Symbol + for _, sym := range symbols { + switch sym.Kind { + case stdlib.Func, stdlib.Type, stdlib.Var, stdlib.Const: + exports = append(exports, sym) + } + } wrappedCallback.exportsLoaded(p, exports) } } @@ -667,7 +700,7 @@ func getCandidatePkgs(ctx context.Context, wrappedCallback *scanCallback, filena dupCheck[pkg.importPathShort] = struct{}{} return notSelf(pkg) && wrappedCallback.packageNameLoaded(pkg) }, - exportsLoaded: func(pkg *pkg, exports []string) { + exportsLoaded: func(pkg *pkg, exports []stdlib.Symbol) { // If we're an x_test, load the package under test's test variant. if strings.HasSuffix(filePkg, "_test") && pkg.dir == filepath.Dir(filename) { var err error @@ -698,20 +731,21 @@ func ScoreImportPaths(ctx context.Context, env *ProcessEnv, paths []string) (map return result, nil } -func PrimeCache(ctx context.Context, env *ProcessEnv) error { +func PrimeCache(ctx context.Context, resolver Resolver) error { // Fully scan the disk for directories, but don't actually read any Go files. callback := &scanCallback{ - rootFound: func(gopathwalk.Root) bool { - return true + rootFound: func(root gopathwalk.Root) bool { + // See getCandidatePkgs: walking GOROOT is apparently expensive and + // unnecessary. + return root.Type != gopathwalk.RootGOROOT }, dirFound: func(pkg *pkg) bool { return false }, - packageNameLoaded: func(pkg *pkg) bool { - return false - }, + // packageNameLoaded and exportsLoaded must never be called. } - return getCandidatePkgs(ctx, callback, "", "", env) + + return resolver.scan(ctx, callback) } func candidateImportName(pkg *pkg) string { @@ -791,7 +825,7 @@ func GetImportPaths(ctx context.Context, wrapped func(ImportFix), searchPrefix, // A PackageExport is a package and its exports. type PackageExport struct { Fix *ImportFix - Exports []string + Exports []stdlib.Symbol } // GetPackageExports returns all known packages with name pkg and their exports. @@ -806,8 +840,8 @@ func GetPackageExports(ctx context.Context, wrapped func(PackageExport), searchP packageNameLoaded: func(pkg *pkg) bool { return pkg.packageName == searchPkg }, - exportsLoaded: func(pkg *pkg, exports []string) { - sort.Strings(exports) + exportsLoaded: func(pkg *pkg, exports []stdlib.Symbol) { + sortSymbols(exports) wrapped(PackageExport{ Fix: &ImportFix{ StmtInfo: ImportInfo{ @@ -825,16 +859,45 @@ func GetPackageExports(ctx context.Context, wrapped func(PackageExport), searchP return getCandidatePkgs(ctx, callback, filename, filePkg, env) } -var requiredGoEnvVars = []string{"GO111MODULE", "GOFLAGS", "GOINSECURE", "GOMOD", "GOMODCACHE", "GONOPROXY", "GONOSUMDB", "GOPATH", "GOPROXY", "GOROOT", "GOSUMDB", "GOWORK"} +// TODO(rfindley): we should depend on GOOS and GOARCH, to provide accurate +// imports when doing cross-platform development. +var requiredGoEnvVars = []string{ + "GO111MODULE", + "GOFLAGS", + "GOINSECURE", + "GOMOD", + "GOMODCACHE", + "GONOPROXY", + "GONOSUMDB", + "GOPATH", + "GOPROXY", + "GOROOT", + "GOSUMDB", + "GOWORK", +} // ProcessEnv contains environment variables and settings that affect the use of // the go command, the go/build package, etc. +// +// ...a ProcessEnv *also* overwrites its Env along with derived state in the +// form of the resolver. And because it is lazily initialized, an env may just +// be broken and unusable, but there is no way for the caller to detect that: +// all queries will just fail. +// +// TODO(rfindley): refactor this package so that this type (perhaps renamed to +// just Env or Config) is an immutable configuration struct, to be exchanged +// for an initialized object via a constructor that returns an error. Perhaps +// the signature should be `func NewResolver(*Env) (*Resolver, error)`, where +// resolver is a concrete type used for resolving imports. Via this +// refactoring, we can avoid the need to call ProcessEnv.init and +// ProcessEnv.GoEnv everywhere, and implicitly fix all the places where this +// these are misused. Also, we'd delegate the caller the decision of how to +// handle a broken environment. type ProcessEnv struct { GocmdRunner *gocommand.Runner BuildFlags []string ModFlag string - ModFile string // SkipPathInScan returns true if the path should be skipped from scans of // the RootCurrentModule root type. The function argument is a clean, @@ -844,7 +907,7 @@ type ProcessEnv struct { // Env overrides the OS environment, and can be used to specify // GOPROXY, GO111MODULE, etc. PATH cannot be set here, because // exec.Command will not honor it. - // Specifying all of RequiredGoEnvVars avoids a call to `go env`. + // Specifying all of requiredGoEnvVars avoids a call to `go env`. Env map[string]string WorkingDir string @@ -852,9 +915,17 @@ type ProcessEnv struct { // If Logf is non-nil, debug logging is enabled through this function. Logf func(format string, args ...interface{}) - initialized bool + // If set, ModCache holds a shared cache of directory info to use across + // multiple ProcessEnvs. + ModCache *DirInfoCache + + initialized bool // see TODO above - resolver Resolver + // resolver and resolverErr are lazily evaluated (see GetResolver). + // This is unclean, but see the big TODO in the docstring for ProcessEnv + // above: for now, we can't be sure that the ProcessEnv is fully initialized. + resolver Resolver + resolverErr error } func (e *ProcessEnv) goEnv() (map[string]string, error) { @@ -934,20 +1005,43 @@ func (e *ProcessEnv) env() []string { } func (e *ProcessEnv) GetResolver() (Resolver, error) { - if e.resolver != nil { - return e.resolver, nil - } if err := e.init(); err != nil { return nil, err } - if len(e.Env["GOMOD"]) == 0 && len(e.Env["GOWORK"]) == 0 { - e.resolver = newGopathResolver(e) - return e.resolver, nil + + if e.resolver == nil && e.resolverErr == nil { + // TODO(rfindley): we should only use a gopathResolver here if the working + // directory is actually *in* GOPATH. (I seem to recall an open gopls issue + // for this behavior, but I can't find it). + // + // For gopls, we can optionally explicitly choose a resolver type, since we + // already know the view type. + if len(e.Env["GOMOD"]) == 0 && len(e.Env["GOWORK"]) == 0 { + e.resolver = newGopathResolver(e) + e.logf("created gopath resolver") + } else if r, err := newModuleResolver(e, e.ModCache); err != nil { + e.resolverErr = err + e.logf("failed to create module resolver: %v", err) + } else { + e.resolver = Resolver(r) + e.logf("created module resolver") + } + } + + return e.resolver, e.resolverErr +} + +// logf logs if e.Logf is non-nil. +func (e *ProcessEnv) logf(format string, args ...any) { + if e.Logf != nil { + e.Logf(format, args...) } - e.resolver = newModuleResolver(e) - return e.resolver, nil } +// buildContext returns the build.Context to use for matching files. +// +// TODO(rfindley): support dynamic GOOS, GOARCH here, when doing cross-platform +// development. func (e *ProcessEnv) buildContext() (*build.Context, error) { ctx := build.Default goenv, err := e.goEnv() @@ -997,24 +1091,40 @@ func addStdlibCandidates(pass *pass, refs references) error { if err != nil { return err } + localbase := func(nm string) string { + ans := path.Base(nm) + if ans[0] == 'v' { + // this is called, for instance, with math/rand/v2 and returns rand/v2 + if _, err := strconv.Atoi(ans[1:]); err == nil { + ix := strings.LastIndex(nm, ans) + more := path.Base(nm[:ix]) + ans = path.Join(more, ans) + } + } + return ans + } add := func(pkg string) { // Prevent self-imports. if path.Base(pkg) == pass.f.Name.Name && filepath.Join(goenv["GOROOT"], "src", pkg) == pass.srcDir { return } - exports := copyExports(stdlib[pkg]) + exports := symbolNameSet(stdlib.PackageSymbols[pkg]) pass.addCandidate( &ImportInfo{ImportPath: pkg}, - &packageInfo{name: path.Base(pkg), exports: exports}) + &packageInfo{name: localbase(pkg), exports: exports}) } for left := range refs { if left == "rand" { - // Make sure we try crypto/rand before math/rand. + // Make sure we try crypto/rand before any version of math/rand as both have Int() + // and our policy is to recommend crypto add("crypto/rand") - add("math/rand") + // if the user's no later than go1.21, this should be "math/rand" + // but we have no way of figuring out what the user is using + // TODO: investigate using the toolchain version to disambiguate in the stdlib + add("math/rand/v2") continue } - for importPath := range stdlib { + for importPath := range stdlib.PackageSymbols { if path.Base(importPath) == left { add(importPath) } @@ -1027,15 +1137,23 @@ func addStdlibCandidates(pass *pass, refs references) error { type Resolver interface { // loadPackageNames loads the package names in importPaths. loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) + // scan works with callback to search for packages. See scanCallback for details. scan(ctx context.Context, callback *scanCallback) error - // loadExports returns the set of exported symbols in the package at dir. - // loadExports may be called concurrently. - loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []string, error) + + // loadExports returns the package name and set of exported symbols in the + // package at dir. loadExports may be called concurrently. + loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) + // scoreImportPath returns the relevance for an import path. scoreImportPath(ctx context.Context, path string) float64 - ClearForNewScan() + // ClearForNewScan returns a new Resolver based on the receiver that has + // cleared its internal caches of directory contents. + // + // The new resolver should be primed and then set via + // [ProcessEnv.UpdateResolver]. + ClearForNewScan() Resolver } // A scanCallback controls a call to scan and receives its results. @@ -1054,7 +1172,7 @@ type scanCallback struct { // If it returns true, the package's exports will be loaded. packageNameLoaded func(pkg *pkg) bool // exportsLoaded is called when a package's exports have been loaded. - exportsLoaded func(pkg *pkg, exports []string) + exportsLoaded func(pkg *pkg, exports []stdlib.Symbol) } func addExternalCandidates(ctx context.Context, pass *pass, refs references, filename string) error { @@ -1092,7 +1210,7 @@ func addExternalCandidates(ctx context.Context, pass *pass, refs references, fil if err != nil { return err } - if err = resolver.scan(context.Background(), callback); err != nil { + if err = resolver.scan(ctx, callback); err != nil { return err } @@ -1101,57 +1219,66 @@ func addExternalCandidates(ctx context.Context, pass *pass, refs references, fil imp *ImportInfo pkg *packageInfo } - results := make(chan result, len(refs)) + results := make([]*result, len(refs)) - ctx, cancel := context.WithCancel(context.TODO()) - var wg sync.WaitGroup - defer func() { - cancel() - wg.Wait() - }() - var ( - firstErr error - firstErrOnce sync.Once - ) - for pkgName, symbols := range refs { - wg.Add(1) - go func(pkgName string, symbols map[string]bool) { - defer wg.Done() + g, ctx := errgroup.WithContext(ctx) + + searcher := symbolSearcher{ + logf: pass.env.logf, + srcDir: pass.srcDir, + xtest: strings.HasSuffix(pass.f.Name.Name, "_test"), + loadExports: resolver.loadExports, + } - found, err := findImport(ctx, pass, found[pkgName], pkgName, symbols, filename) + i := 0 + for pkgName, symbols := range refs { + index := i // claim an index in results + i++ + pkgName := pkgName + symbols := symbols + g.Go(func() error { + found, err := searcher.search(ctx, found[pkgName], pkgName, symbols) if err != nil { - firstErrOnce.Do(func() { - firstErr = err - cancel() - }) - return + return err } - if found == nil { - return // No matching package. + return nil // No matching package. } imp := &ImportInfo{ ImportPath: found.importPathShort, } - pkg := &packageInfo{ name: pkgName, exports: symbols, } - results <- result{imp, pkg} - }(pkgName, symbols) + results[index] = &result{imp, pkg} + return nil + }) + } + if err := g.Wait(); err != nil { + return err } - go func() { - wg.Wait() - close(results) - }() - for result := range results { + for _, result := range results { + if result == nil { + continue + } + // Don't offer completions that would shadow predeclared + // names, such as github.com/coreos/etcd/error. + if types.Universe.Lookup(result.pkg.name) != nil { // predeclared + // Ideally we would skip this candidate only + // if the predeclared name is actually + // referenced by the file, but that's a lot + // trickier to compute and would still create + // an import that is likely to surprise the + // user before long. + continue + } pass.addCandidate(result.imp, result.pkg) } - return firstErr + return nil } // notIdentifier reports whether ch is an invalid identifier character. @@ -1191,31 +1318,22 @@ func ImportPathToAssumedName(importPath string) string { type gopathResolver struct { env *ProcessEnv walked bool - cache *dirInfoCache + cache *DirInfoCache scanSema chan struct{} // scanSema prevents concurrent scans. } func newGopathResolver(env *ProcessEnv) *gopathResolver { r := &gopathResolver{ - env: env, - cache: &dirInfoCache{ - dirs: map[string]*directoryPackageInfo{}, - listeners: map[*int]cacheListener{}, - }, + env: env, + cache: NewDirInfoCache(), scanSema: make(chan struct{}, 1), } r.scanSema <- struct{}{} return r } -func (r *gopathResolver) ClearForNewScan() { - <-r.scanSema - r.cache = &dirInfoCache{ - dirs: map[string]*directoryPackageInfo{}, - listeners: map[*int]cacheListener{}, - } - r.walked = false - r.scanSema <- struct{}{} +func (r *gopathResolver) ClearForNewScan() Resolver { + return newGopathResolver(r.env) } func (r *gopathResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) { @@ -1233,7 +1351,7 @@ func (r *gopathResolver) loadPackageNames(importPaths []string, srcDir string) ( // importPathToName finds out the actual package name, as declared in its .go files. func importPathToName(bctx *build.Context, importPath, srcDir string) string { // Fast path for standard library without going to disk. - if _, ok := stdlib[importPath]; ok { + if stdlib.HasPackage(importPath) { return path.Base(importPath) // stdlib packages always match their paths. } @@ -1431,7 +1549,7 @@ func (r *gopathResolver) scan(ctx context.Context, callback *scanCallback) error } func (r *gopathResolver) scoreImportPath(ctx context.Context, path string) float64 { - if _, ok := stdlib[path]; ok { + if stdlib.HasPackage(path) { return MaxRelevance } return MaxRelevance - 1 @@ -1448,7 +1566,7 @@ func filterRoots(roots []gopathwalk.Root, include func(gopathwalk.Root) bool) [] return result } -func (r *gopathResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []string, error) { +func (r *gopathResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) { if info, ok := r.cache.Load(pkg.dir); ok && !includeTest { return r.cache.CacheExports(ctx, r.env, info) } @@ -1468,7 +1586,7 @@ func VendorlessPath(ipath string) string { return ipath } -func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, includeTest bool) (string, []string, error) { +func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, includeTest bool) (string, []stdlib.Symbol, error) { // Look for non-test, buildable .go files which could provide exports. all, err := os.ReadDir(dir) if err != nil { @@ -1492,7 +1610,7 @@ func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, incl } var pkgName string - var exports []string + var exports []stdlib.Symbol fset := token.NewFileSet() for _, fi := range files { select { @@ -1504,9 +1622,7 @@ func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, incl fullFile := filepath.Join(dir, fi.Name()) f, err := parser.ParseFile(fset, fullFile, nil, 0) if err != nil { - if env.Logf != nil { - env.Logf("error parsing %v: %v", fullFile, err) - } + env.logf("error parsing %v: %v", fullFile, err) continue } if f.Name.Name == "documentation" { @@ -1519,40 +1635,72 @@ func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, incl continue } pkgName = f.Name.Name - for name := range f.Scope.Objects { + for name, obj := range f.Scope.Objects { if ast.IsExported(name) { - exports = append(exports, name) + var kind stdlib.Kind + switch obj.Kind { + case ast.Con: + kind = stdlib.Const + case ast.Typ: + kind = stdlib.Type + case ast.Var: + kind = stdlib.Var + case ast.Fun: + kind = stdlib.Func + } + exports = append(exports, stdlib.Symbol{ + Name: name, + Kind: kind, + Version: 0, // unknown; be permissive + }) } } } + sortSymbols(exports) - if env.Logf != nil { - sortedExports := append([]string(nil), exports...) - sort.Strings(sortedExports) - env.Logf("loaded exports in dir %v (package %v): %v", dir, pkgName, strings.Join(sortedExports, ", ")) - } + env.logf("loaded exports in dir %v (package %v): %v", dir, pkgName, exports) return pkgName, exports, nil } -// findImport searches for a package with the given symbols. -// If no package is found, findImport returns ("", false, nil) -func findImport(ctx context.Context, pass *pass, candidates []pkgDistance, pkgName string, symbols map[string]bool, filename string) (*pkg, error) { +func sortSymbols(syms []stdlib.Symbol) { + sort.Slice(syms, func(i, j int) bool { + return syms[i].Name < syms[j].Name + }) +} + +// A symbolSearcher searches for a package with a set of symbols, among a set +// of candidates. See [symbolSearcher.search]. +// +// The search occurs within the scope of a single file, with context captured +// in srcDir and xtest. +type symbolSearcher struct { + logf func(string, ...any) + srcDir string // directory containing the file + xtest bool // if set, the file containing is an x_test file + loadExports func(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) +} + +// search searches the provided candidates for a package containing all +// exported symbols. +// +// If successful, returns the resulting package. +func (s *symbolSearcher) search(ctx context.Context, candidates []pkgDistance, pkgName string, symbols map[string]bool) (*pkg, error) { // Sort the candidates by their import package length, // assuming that shorter package names are better than long // ones. Note that this sorts by the de-vendored name, so // there's no "penalty" for vendoring. sort.Sort(byDistanceOrImportPathShortLength(candidates)) - if pass.env.Logf != nil { + if s.logf != nil { for i, c := range candidates { - pass.env.Logf("%s candidate %d/%d: %v in %v", pkgName, i+1, len(candidates), c.pkg.importPathShort, c.pkg.dir) + s.logf("%s candidate %d/%d: %v in %v", pkgName, i+1, len(candidates), c.pkg.importPathShort, c.pkg.dir) } } - resolver, err := pass.env.GetResolver() - if err != nil { - return nil, err - } - // Collect exports for packages with matching names. + // Arrange rescv so that we can we can await results in order of relevance + // and exit as soon as we find the first match. + // + // Search with bounded concurrency, returning as soon as the first result + // among rescv is non-nil. rescv := make([]chan *pkg, len(candidates)) for i := range candidates { rescv[i] = make(chan *pkg, 1) @@ -1560,6 +1708,7 @@ func findImport(ctx context.Context, pass *pass, candidates []pkgDistance, pkgNa const maxConcurrentPackageImport = 4 loadExportsSem := make(chan struct{}, maxConcurrentPackageImport) + // Ensure that all work is completed at exit. ctx, cancel := context.WithCancel(ctx) var wg sync.WaitGroup defer func() { @@ -1567,6 +1716,7 @@ func findImport(ctx context.Context, pass *pass, candidates []pkgDistance, pkgNa wg.Wait() }() + // Start the search. wg.Add(1) go func() { defer wg.Done() @@ -1577,55 +1727,67 @@ func findImport(ctx context.Context, pass *pass, candidates []pkgDistance, pkgNa return } + i := i + c := c wg.Add(1) - go func(c pkgDistance, resc chan<- *pkg) { + go func() { defer func() { <-loadExportsSem wg.Done() }() - - if pass.env.Logf != nil { - pass.env.Logf("loading exports in dir %s (seeking package %s)", c.pkg.dir, pkgName) + if s.logf != nil { + s.logf("loading exports in dir %s (seeking package %s)", c.pkg.dir, pkgName) } - // If we're an x_test, load the package under test's test variant. - includeTest := strings.HasSuffix(pass.f.Name.Name, "_test") && c.pkg.dir == pass.srcDir - _, exports, err := resolver.loadExports(ctx, c.pkg, includeTest) + pkg, err := s.searchOne(ctx, c, symbols) if err != nil { - if pass.env.Logf != nil { - pass.env.Logf("loading exports in dir %s (seeking package %s): %v", c.pkg.dir, pkgName, err) - } - resc <- nil - return - } - - exportsMap := make(map[string]bool, len(exports)) - for _, sym := range exports { - exportsMap[sym] = true - } - - // If it doesn't have the right - // symbols, send nil to mean no match. - for symbol := range symbols { - if !exportsMap[symbol] { - resc <- nil - return + if s.logf != nil && ctx.Err() == nil { + s.logf("loading exports in dir %s (seeking package %s): %v", c.pkg.dir, pkgName, err) } + pkg = nil } - resc <- c.pkg - }(c, rescv[i]) + rescv[i] <- pkg // may be nil + }() } }() + // Await the first (best) result. for _, resc := range rescv { - pkg := <-resc - if pkg == nil { - continue + select { + case r := <-resc: + if r != nil { + return r, nil + } + case <-ctx.Done(): + return nil, ctx.Err() } - return pkg, nil } return nil, nil } +func (s *symbolSearcher) searchOne(ctx context.Context, c pkgDistance, symbols map[string]bool) (*pkg, error) { + if ctx.Err() != nil { + return nil, ctx.Err() + } + // If we're considering the package under test from an x_test, load the + // test variant. + includeTest := s.xtest && c.pkg.dir == s.srcDir + _, exports, err := s.loadExports(ctx, c.pkg, includeTest) + if err != nil { + return nil, err + } + + exportsMap := make(map[string]bool, len(exports)) + for _, sym := range exports { + exportsMap[sym.Name] = true + } + for symbol := range symbols { + if !exportsMap[symbol] { + return nil, nil // no match + } + } + return c.pkg, nil +} + // pkgIsCandidate reports whether pkg is a candidate for satisfying the // finding which package pkgIdent in the file named by filename is trying // to refer to. @@ -1645,58 +1807,24 @@ func pkgIsCandidate(filename string, refs references, pkg *pkg) bool { } // Speed optimization to minimize disk I/O: - // the last two components on disk must contain the - // package name somewhere. // - // This permits mismatch naming like directory - // "go-foo" being package "foo", or "pkg.v3" being "pkg", - // or directory "google.golang.org/api/cloudbilling/v1" - // being package "cloudbilling", but doesn't - // permit a directory "foo" to be package - // "bar", which is strongly discouraged - // anyway. There's no reason goimports needs - // to be slow just to accommodate that. + // Use the matchesPath heuristic to filter to package paths that could + // reasonably match a dangling reference. + // + // This permits mismatch naming like directory "go-foo" being package "foo", + // or "pkg.v3" being "pkg", or directory + // "google.golang.org/api/cloudbilling/v1" being package "cloudbilling", but + // doesn't permit a directory "foo" to be package "bar", which is strongly + // discouraged anyway. There's no reason goimports needs to be slow just to + // accommodate that. for pkgIdent := range refs { - lastTwo := lastTwoComponents(pkg.importPathShort) - if strings.Contains(lastTwo, pkgIdent) { + if matchesPath(pkgIdent, pkg.importPathShort) { return true } - if hasHyphenOrUpperASCII(lastTwo) && !hasHyphenOrUpperASCII(pkgIdent) { - lastTwo = lowerASCIIAndRemoveHyphen(lastTwo) - if strings.Contains(lastTwo, pkgIdent) { - return true - } - } } return false } -func hasHyphenOrUpperASCII(s string) bool { - for i := 0; i < len(s); i++ { - b := s[i] - if b == '-' || ('A' <= b && b <= 'Z') { - return true - } - } - return false -} - -func lowerASCIIAndRemoveHyphen(s string) (ret string) { - buf := make([]byte, 0, len(s)) - for i := 0; i < len(s); i++ { - b := s[i] - switch { - case b == '-': - continue - case 'A' <= b && b <= 'Z': - buf = append(buf, b+('a'-'A')) - default: - buf = append(buf, b) - } - } - return string(buf) -} - // canUse reports whether the package in dir is usable from filename, // respecting the Go "internal" and "vendor" visibility rules. func canUse(filename, dir string) bool { @@ -1737,19 +1865,84 @@ func canUse(filename, dir string) bool { return !strings.Contains(relSlash, "/vendor/") && !strings.Contains(relSlash, "/internal/") && !strings.HasSuffix(relSlash, "/internal") } -// lastTwoComponents returns at most the last two path components -// of v, using either / or \ as the path separator. -func lastTwoComponents(v string) string { +// matchesPath reports whether ident may match a potential package name +// referred to by path, using heuristics to filter out unidiomatic package +// names. +// +// Specifically, it checks whether either of the last two '/'- or '\'-delimited +// path segments matches the identifier. The segment-matching heuristic must +// allow for various conventions around segment naming, including go-foo, +// foo-go, and foo.v3. To handle all of these, matching considers both (1) the +// entire segment, ignoring '-' and '.', as well as (2) the last subsegment +// separated by '-' or '.'. So the segment foo-go matches all of the following +// identifiers: foo, go, and foogo. All matches are case insensitive (for ASCII +// identifiers). +// +// See the docstring for [pkgIsCandidate] for an explanation of how this +// heuristic filters potential candidate packages. +func matchesPath(ident, path string) bool { + // Ignore case, for ASCII. + lowerIfASCII := func(b byte) byte { + if 'A' <= b && b <= 'Z' { + return b + ('a' - 'A') + } + return b + } + + // match reports whether path[start:end] matches ident, ignoring [.-]. + match := func(start, end int) bool { + ii := len(ident) - 1 // current byte in ident + pi := end - 1 // current byte in path + for ; pi >= start && ii >= 0; pi-- { + pb := path[pi] + if pb == '-' || pb == '.' { + continue + } + pb = lowerIfASCII(pb) + ib := lowerIfASCII(ident[ii]) + if pb != ib { + return false + } + ii-- + } + return ii < 0 && pi < start // all bytes matched + } + + // segmentEnd and subsegmentEnd hold the end points of the current segment + // and subsegment intervals. + segmentEnd := len(path) + subsegmentEnd := len(path) + + // Count slashes; we only care about the last two segments. nslash := 0 - for i := len(v) - 1; i >= 0; i-- { - if v[i] == '/' || v[i] == '\\' { + + for i := len(path) - 1; i >= 0; i-- { + switch b := path[i]; b { + // TODO(rfindley): we handle backlashes here only because the previous + // heuristic handled backslashes. This is perhaps overly defensive, but is + // the result of many lessons regarding Chesterton's fence and the + // goimports codebase. + // + // However, this function is only ever called with something called an + // 'importPath'. Is it possible that this is a real import path, and + // therefore we need only consider forward slashes? + case '/', '\\': + if match(i+1, segmentEnd) || match(i+1, subsegmentEnd) { + return true + } nslash++ if nslash == 2 { - return v[i:] + return false // did not match above + } + segmentEnd, subsegmentEnd = i, i // reset + case '-', '.': + if match(i+1, subsegmentEnd) { + return true } + subsegmentEnd = i } } - return v + return match(0, segmentEnd) || match(0, subsegmentEnd) } type visitFn func(node ast.Node) ast.Visitor @@ -1758,10 +1951,13 @@ func (fn visitFn) Visit(node ast.Node) ast.Visitor { return fn(node) } -func copyExports(pkg []string) map[string]bool { - m := make(map[string]bool, len(pkg)) - for _, v := range pkg { - m[v] = true +func symbolNameSet(symbols []stdlib.Symbol) map[string]bool { + names := make(map[string]bool) + for _, sym := range symbols { + switch sym.Kind { + case stdlib.Const, stdlib.Var, stdlib.Type, stdlib.Func: + names[sym.Name] = true + } } - return m + return names } diff --git a/tools/vendor/golang.org/x/tools/internal/imports/imports.go b/tools/vendor/golang.org/x/tools/internal/imports/imports.go index 58e637b90..f83465520 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/imports.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/imports.go @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:generate go run mkstdlib.go - // Package imports implements a Go pretty-printer (like package "go/format") // that also adds or removes import statements as necessary. package imports @@ -109,7 +107,7 @@ func ApplyFixes(fixes []*ImportFix, filename string, src []byte, opt *Options, e } // formatFile formats the file syntax tree. -// It may mutate the token.FileSet. +// It may mutate the token.FileSet and the ast.File. // // If an adjust function is provided, it is called after formatting // with the original source (formatFile's src parameter) and the @@ -236,7 +234,7 @@ func parse(fset *token.FileSet, filename string, src []byte, opt *Options) (*ast src = src[:len(src)-len("}\n")] // Gofmt has also indented the function body one level. // Remove that indent. - src = bytes.Replace(src, []byte("\n\t"), []byte("\n"), -1) + src = bytes.ReplaceAll(src, []byte("\n\t"), []byte("\n")) return matchSpace(orig, src) } return file, adjust, nil diff --git a/tools/vendor/golang.org/x/tools/internal/imports/mod.go b/tools/vendor/golang.org/x/tools/internal/imports/mod.go index 5f4d435d3..91221fda3 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/mod.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/mod.go @@ -21,78 +21,138 @@ import ( "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/gopathwalk" + "golang.org/x/tools/internal/stdlib" ) -// ModuleResolver implements resolver for modules using the go command as little -// as feasible. +// Notes(rfindley): ModuleResolver appears to be heavily optimized for scanning +// as fast as possible, which is desirable for a call to goimports from the +// command line, but it doesn't work as well for gopls, where it suffers from +// slow startup (golang/go#44863) and intermittent hanging (golang/go#59216), +// both caused by populating the cache, albeit in slightly different ways. +// +// A high level list of TODOs: +// - Optimize the scan itself, as there is some redundancy statting and +// reading go.mod files. +// - Invert the relationship between ProcessEnv and Resolver (see the +// docstring of ProcessEnv). +// - Make it easier to use an external resolver implementation. +// +// Smaller TODOs are annotated in the code below. + +// ModuleResolver implements the Resolver interface for a workspace using +// modules. +// +// A goal of the ModuleResolver is to invoke the Go command as little as +// possible. To this end, it runs the Go command only for listing module +// information (i.e. `go list -m -e -json ...`). Package scanning, the process +// of loading package information for the modules, is implemented internally +// via the scan method. +// +// It has two types of state: the state derived from the go command, which +// is populated by init, and the state derived from scans, which is populated +// via scan. A root is considered scanned if it has been walked to discover +// directories. However, if the scan did not require additional information +// from the directory (such as package name or exports), the directory +// information itself may be partially populated. It will be lazily filled in +// as needed by scans, using the scanCallback. type ModuleResolver struct { - env *ProcessEnv - moduleCacheDir string - dummyVendorMod *gocommand.ModuleJSON // If vendoring is enabled, the pseudo-module that represents the /vendor directory. - roots []gopathwalk.Root - scanSema chan struct{} // scanSema prevents concurrent scans and guards scannedRoots. - scannedRoots map[gopathwalk.Root]bool - - initialized bool - mains []*gocommand.ModuleJSON - mainByDir map[string]*gocommand.ModuleJSON - modsByModPath []*gocommand.ModuleJSON // All modules, ordered by # of path components in module Path... - modsByDir []*gocommand.ModuleJSON // ...or number of path components in their Dir. - - // moduleCacheCache stores information about the module cache. - moduleCacheCache *dirInfoCache - otherCache *dirInfoCache + env *ProcessEnv + + // Module state, populated during construction + dummyVendorMod *gocommand.ModuleJSON // if vendoring is enabled, a pseudo-module to represent the /vendor directory + moduleCacheDir string // GOMODCACHE, inferred from GOPATH if unset + roots []gopathwalk.Root // roots to scan, in approximate order of importance + mains []*gocommand.ModuleJSON // main modules + mainByDir map[string]*gocommand.ModuleJSON // module information by dir, to join with roots + modsByModPath []*gocommand.ModuleJSON // all modules, ordered by # of path components in their module path + modsByDir []*gocommand.ModuleJSON // ...or by the number of path components in their Dir. + + // Scanning state, populated by scan + + // scanSema prevents concurrent scans, and guards scannedRoots and the cache + // fields below (though the caches themselves are concurrency safe). + // Receive to acquire, send to release. + scanSema chan struct{} + scannedRoots map[gopathwalk.Root]bool // if true, root has been walked + + // Caches of directory info, populated by scans and scan callbacks + // + // moduleCacheCache stores cached information about roots in the module + // cache, which are immutable and therefore do not need to be invalidated. + // + // otherCache stores information about all other roots (even GOROOT), which + // may change. + moduleCacheCache *DirInfoCache + otherCache *DirInfoCache } -func newModuleResolver(e *ProcessEnv) *ModuleResolver { +// newModuleResolver returns a new module-aware goimports resolver. +// +// Note: use caution when modifying this constructor: changes must also be +// reflected in ModuleResolver.ClearForNewScan. +func newModuleResolver(e *ProcessEnv, moduleCacheCache *DirInfoCache) (*ModuleResolver, error) { r := &ModuleResolver{ env: e, scanSema: make(chan struct{}, 1), } - r.scanSema <- struct{}{} - return r -} - -func (r *ModuleResolver) init() error { - if r.initialized { - return nil - } + r.scanSema <- struct{}{} // release goenv, err := r.env.goEnv() if err != nil { - return err + return nil, err } + + // TODO(rfindley): can we refactor to share logic with r.env.invokeGo? inv := gocommand.Invocation{ BuildFlags: r.env.BuildFlags, ModFlag: r.env.ModFlag, - ModFile: r.env.ModFile, Env: r.env.env(), Logf: r.env.Logf, WorkingDir: r.env.WorkingDir, } vendorEnabled := false - var mainModVendor *gocommand.ModuleJSON - - // Module vendor directories are ignored in workspace mode: - // https://go.googlesource.com/proposal/+/master/design/45713-workspace.md - if len(r.env.Env["GOWORK"]) == 0 { + var mainModVendor *gocommand.ModuleJSON // for module vendoring + var mainModsVendor []*gocommand.ModuleJSON // for workspace vendoring + + goWork := r.env.Env["GOWORK"] + if len(goWork) == 0 { + // TODO(rfindley): VendorEnabled runs the go command to get GOFLAGS, but + // they should be available from the ProcessEnv. Can we avoid the redundant + // invocation? vendorEnabled, mainModVendor, err = gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner) if err != nil { - return err + return nil, err + } + } else { + vendorEnabled, mainModsVendor, err = gocommand.WorkspaceVendorEnabled(context.Background(), inv, r.env.GocmdRunner) + if err != nil { + return nil, err } } - if mainModVendor != nil && vendorEnabled { - // Vendor mode is on, so all the non-Main modules are irrelevant, - // and we need to search /vendor for everything. - r.mains = []*gocommand.ModuleJSON{mainModVendor} - r.dummyVendorMod = &gocommand.ModuleJSON{ - Path: "", - Dir: filepath.Join(mainModVendor.Dir, "vendor"), + if vendorEnabled { + if mainModVendor != nil { + // Module vendor mode is on, so all the non-Main modules are irrelevant, + // and we need to search /vendor for everything. + r.mains = []*gocommand.ModuleJSON{mainModVendor} + r.dummyVendorMod = &gocommand.ModuleJSON{ + Path: "", + Dir: filepath.Join(mainModVendor.Dir, "vendor"), + } + r.modsByModPath = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod} + r.modsByDir = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod} + } else { + // Workspace vendor mode is on, so all the non-Main modules are irrelevant, + // and we need to search /vendor for everything. + r.mains = mainModsVendor + r.dummyVendorMod = &gocommand.ModuleJSON{ + Path: "", + Dir: filepath.Join(filepath.Dir(goWork), "vendor"), + } + r.modsByModPath = append(append([]*gocommand.ModuleJSON{}, mainModsVendor...), r.dummyVendorMod) + r.modsByDir = append(append([]*gocommand.ModuleJSON{}, mainModsVendor...), r.dummyVendorMod) } - r.modsByModPath = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod} - r.modsByDir = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod} } else { // Vendor mode is off, so run go list -m ... to find everything. err := r.initAllMods() @@ -100,19 +160,14 @@ func (r *ModuleResolver) init() error { // GO111MODULE=on. Other errors are fatal. if err != nil { if errMsg := err.Error(); !strings.Contains(errMsg, "working directory is not part of a module") && !strings.Contains(errMsg, "go.mod file not found") { - return err + return nil, err } } } - if gmc := r.env.Env["GOMODCACHE"]; gmc != "" { - r.moduleCacheDir = gmc - } else { - gopaths := filepath.SplitList(goenv["GOPATH"]) - if len(gopaths) == 0 { - return fmt.Errorf("empty GOPATH") - } - r.moduleCacheDir = filepath.Join(gopaths[0], "/pkg/mod") + r.moduleCacheDir = gomodcacheForEnv(goenv) + if r.moduleCacheDir == "" { + return nil, fmt.Errorf("cannot resolve GOMODCACHE") } sort.Slice(r.modsByModPath, func(i, j int) bool { @@ -128,8 +183,9 @@ func (r *ModuleResolver) init() error { return count(j) < count(i) // descending order }) - r.roots = []gopathwalk.Root{ - {Path: filepath.Join(goenv["GOROOT"], "/src"), Type: gopathwalk.RootGOROOT}, + r.roots = []gopathwalk.Root{} + if goenv["GOROOT"] != "" { // "" happens in tests + r.roots = append(r.roots, gopathwalk.Root{Path: filepath.Join(goenv["GOROOT"], "/src"), Type: gopathwalk.RootGOROOT}) } r.mainByDir = make(map[string]*gocommand.ModuleJSON) for _, main := range r.mains { @@ -141,7 +197,11 @@ func (r *ModuleResolver) init() error { } else { addDep := func(mod *gocommand.ModuleJSON) { if mod.Replace == nil { - // This is redundant with the cache, but we'll skip it cheaply enough. + // This is redundant with the cache, but we'll skip it cheaply enough + // when we encounter it in the module cache scan. + // + // Including it at a lower index in r.roots than the module cache dir + // helps prioritize matches from within existing dependencies. r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootModuleCache}) } else { r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootOther}) @@ -158,24 +218,40 @@ func (r *ModuleResolver) init() error { addDep(mod) } } + // If provided, share the moduleCacheCache. + // + // TODO(rfindley): The module cache is immutable. However, the loaded + // exports do depend on GOOS and GOARCH. Fortunately, the + // ProcessEnv.buildContext does not adjust these from build.DefaultContext + // (even though it should). So for now, this is OK to share, but we need to + // add logic for handling GOOS/GOARCH. + r.moduleCacheCache = moduleCacheCache r.roots = append(r.roots, gopathwalk.Root{Path: r.moduleCacheDir, Type: gopathwalk.RootModuleCache}) } r.scannedRoots = map[gopathwalk.Root]bool{} if r.moduleCacheCache == nil { - r.moduleCacheCache = &dirInfoCache{ - dirs: map[string]*directoryPackageInfo{}, - listeners: map[*int]cacheListener{}, - } + r.moduleCacheCache = NewDirInfoCache() } - if r.otherCache == nil { - r.otherCache = &dirInfoCache{ - dirs: map[string]*directoryPackageInfo{}, - listeners: map[*int]cacheListener{}, - } - } - r.initialized = true - return nil + r.otherCache = NewDirInfoCache() + return r, nil +} + +// gomodcacheForEnv returns the GOMODCACHE value to use based on the given env +// map, which must have GOMODCACHE and GOPATH populated. +// +// TODO(rfindley): this is defensive refactoring. +// 1. Is this even relevant anymore? Can't we just read GOMODCACHE. +// 2. Use this to separate module cache scanning from other scanning. +func gomodcacheForEnv(goenv map[string]string) string { + if gmc := goenv["GOMODCACHE"]; gmc != "" { + return gmc + } + gopaths := filepath.SplitList(goenv["GOPATH"]) + if len(gopaths) == 0 { + return "" + } + return filepath.Join(gopaths[0], "/pkg/mod") } func (r *ModuleResolver) initAllMods() error { @@ -189,9 +265,7 @@ func (r *ModuleResolver) initAllMods() error { return err } if mod.Dir == "" { - if r.env.Logf != nil { - r.env.Logf("module %v has not been downloaded and will be ignored", mod.Path) - } + r.env.logf("module %v has not been downloaded and will be ignored", mod.Path) // Can't do anything with a module that's not downloaded. continue } @@ -206,30 +280,86 @@ func (r *ModuleResolver) initAllMods() error { return nil } -func (r *ModuleResolver) ClearForNewScan() { - <-r.scanSema - r.scannedRoots = map[gopathwalk.Root]bool{} - r.otherCache = &dirInfoCache{ - dirs: map[string]*directoryPackageInfo{}, - listeners: map[*int]cacheListener{}, +// ClearForNewScan invalidates the last scan. +// +// It preserves the set of roots, but forgets about the set of directories. +// Though it forgets the set of module cache directories, it remembers their +// contents, since they are assumed to be immutable. +func (r *ModuleResolver) ClearForNewScan() Resolver { + <-r.scanSema // acquire r, to guard scannedRoots + r2 := &ModuleResolver{ + env: r.env, + dummyVendorMod: r.dummyVendorMod, + moduleCacheDir: r.moduleCacheDir, + roots: r.roots, + mains: r.mains, + mainByDir: r.mainByDir, + modsByModPath: r.modsByModPath, + + scanSema: make(chan struct{}, 1), + scannedRoots: make(map[gopathwalk.Root]bool), + otherCache: NewDirInfoCache(), + moduleCacheCache: r.moduleCacheCache, + } + r2.scanSema <- struct{}{} // r2 must start released + // Invalidate root scans. We don't need to invalidate module cache roots, + // because they are immutable. + // (We don't support a use case where GOMODCACHE is cleaned in the middle of + // e.g. a gopls session: the user must restart gopls to get accurate + // imports.) + // + // Scanning for new directories in GOMODCACHE should be handled elsewhere, + // via a call to ScanModuleCache. + for _, root := range r.roots { + if root.Type == gopathwalk.RootModuleCache && r.scannedRoots[root] { + r2.scannedRoots[root] = true + } } - r.scanSema <- struct{}{} + r.scanSema <- struct{}{} // release r + return r2 } -func (r *ModuleResolver) ClearForNewMod() { - <-r.scanSema - *r = ModuleResolver{ - env: r.env, - moduleCacheCache: r.moduleCacheCache, - otherCache: r.otherCache, - scanSema: r.scanSema, +// ClearModuleInfo invalidates resolver state that depends on go.mod file +// contents (essentially, the output of go list -m -json ...). +// +// Notably, it does not forget directory contents, which are reset +// asynchronously via ClearForNewScan. +// +// If the ProcessEnv is a GOPATH environment, ClearModuleInfo is a no op. +// +// TODO(rfindley): move this to a new env.go, consolidating ProcessEnv methods. +func (e *ProcessEnv) ClearModuleInfo() { + if r, ok := e.resolver.(*ModuleResolver); ok { + resolver, err := newModuleResolver(e, e.ModCache) + if err != nil { + e.resolver = nil + e.resolverErr = err + return + } + + <-r.scanSema // acquire (guards caches) + resolver.moduleCacheCache = r.moduleCacheCache + resolver.otherCache = r.otherCache + r.scanSema <- struct{}{} // release + + e.UpdateResolver(resolver) } - r.init() - r.scanSema <- struct{}{} } -// findPackage returns the module and directory that contains the package at -// the given import path, or returns nil, "" if no module is in scope. +// UpdateResolver sets the resolver for the ProcessEnv to use in imports +// operations. Only for use with the result of [Resolver.ClearForNewScan]. +// +// TODO(rfindley): this awkward API is a result of the (arguably) inverted +// relationship between configuration and state described in the doc comment +// for [ProcessEnv]. +func (e *ProcessEnv) UpdateResolver(r Resolver) { + e.resolver = r + e.resolverErr = nil +} + +// findPackage returns the module and directory from within the main modules +// and their dependencies that contains the package at the given import path, +// or returns nil, "" if no module is in scope. func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) { // This can't find packages in the stdlib, but that's harmless for all // the existing code paths. @@ -295,10 +425,6 @@ func (r *ModuleResolver) cacheStore(info directoryPackageInfo) { } } -func (r *ModuleResolver) cacheKeys() []string { - return append(r.moduleCacheCache.Keys(), r.otherCache.Keys()...) -} - // cachePackageName caches the package name for a dir already in the cache. func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) { if info.rootType == gopathwalk.RootModuleCache { @@ -307,7 +433,7 @@ func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, er return r.otherCache.CachePackageName(info) } -func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) { +func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []stdlib.Symbol, error) { if info.rootType == gopathwalk.RootModuleCache { return r.moduleCacheCache.CacheExports(ctx, env, info) } @@ -367,15 +493,15 @@ func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON return modDir != mod.Dir } -func (r *ModuleResolver) modInfo(dir string) (modDir string, modName string) { - readModName := func(modFile string) string { - modBytes, err := os.ReadFile(modFile) - if err != nil { - return "" - } - return modulePath(modBytes) +func readModName(modFile string) string { + modBytes, err := os.ReadFile(modFile) + if err != nil { + return "" } + return modulePath(modBytes) +} +func (r *ModuleResolver) modInfo(dir string) (modDir, modName string) { if r.dirInModuleCache(dir) { if matches := modCacheRegexp.FindStringSubmatch(dir); len(matches) == 3 { index := strings.Index(dir, matches[1]+"@"+matches[2]) @@ -409,11 +535,9 @@ func (r *ModuleResolver) dirInModuleCache(dir string) bool { } func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) { - if err := r.init(); err != nil { - return nil, err - } names := map[string]string{} for _, path := range importPaths { + // TODO(rfindley): shouldn't this use the dirInfoCache? _, packageDir := r.findPackage(path) if packageDir == "" { continue @@ -431,10 +555,6 @@ func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error ctx, done := event.Start(ctx, "imports.ModuleResolver.scan") defer done() - if err := r.init(); err != nil { - return err - } - processDir := func(info directoryPackageInfo) { // Skip this directory if we were not able to get the package information successfully. if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil { @@ -444,18 +564,18 @@ func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error if err != nil { return } - if !callback.dirFound(pkg) { return } + pkg.packageName, err = r.cachePackageName(info) if err != nil { return } - if !callback.packageNameLoaded(pkg) { return } + _, exports, err := r.loadExports(ctx, pkg, false) if err != nil { return @@ -494,7 +614,6 @@ func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error return packageScanned } - // Add anything new to the cache, and process it if we're still listening. add := func(root gopathwalk.Root, dir string) { r.cacheStore(r.scanDirForPackage(root, dir)) } @@ -509,9 +628,9 @@ func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error select { case <-ctx.Done(): return - case <-r.scanSema: + case <-r.scanSema: // acquire } - defer func() { r.scanSema <- struct{}{} }() + defer func() { r.scanSema <- struct{}{} }() // release // We have the lock on r.scannedRoots, and no other scans can run. for _, root := range roots { if ctx.Err() != nil { @@ -534,7 +653,7 @@ func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error } func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) float64 { - if _, ok := stdlib[path]; ok { + if stdlib.HasPackage(path) { return MaxRelevance } mod, _ := r.findPackage(path) @@ -612,10 +731,7 @@ func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) { return res, nil } -func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []string, error) { - if err := r.init(); err != nil { - return "", nil, err - } +func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) { if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest { return r.cacheExports(ctx, r.env, info) } @@ -648,9 +764,7 @@ func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) dir } modPath, err := module.UnescapePath(filepath.ToSlash(matches[1])) if err != nil { - if r.env.Logf != nil { - r.env.Logf("decoding module cache path %q: %v", subdir, err) - } + r.env.logf("decoding module cache path %q: %v", subdir, err) return directoryPackageInfo{ status: directoryScanned, err: fmt.Errorf("decoding module cache path %q: %v", subdir, err), diff --git a/tools/vendor/golang.org/x/tools/internal/imports/mod_cache.go b/tools/vendor/golang.org/x/tools/internal/imports/mod_cache.go index 45690abbb..b1192696b 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/mod_cache.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/mod_cache.go @@ -7,9 +7,14 @@ package imports import ( "context" "fmt" + "path" + "path/filepath" + "strings" "sync" + "golang.org/x/mod/module" "golang.org/x/tools/internal/gopathwalk" + "golang.org/x/tools/internal/stdlib" ) // To find packages to import, the resolver needs to know about all of @@ -39,6 +44,8 @@ const ( exportsLoaded ) +// directoryPackageInfo holds (possibly incomplete) information about packages +// contained in a given directory. type directoryPackageInfo struct { // status indicates the extent to which this struct has been filled in. status directoryPackageStatus @@ -63,8 +70,11 @@ type directoryPackageInfo struct { packageName string // the package name, as declared in the source. // Set when status >= exportsLoaded. - - exports []string + // TODO(rfindley): it's hard to see this, but exports depend implicitly on + // the default build context GOOS and GOARCH. + // + // We can make this explicit, and key exports by GOOS, GOARCH. + exports []stdlib.Symbol } // reachedStatus returns true when info has a status at least target and any error associated with @@ -79,7 +89,7 @@ func (info *directoryPackageInfo) reachedStatus(target directoryPackageStatus) ( return true, nil } -// dirInfoCache is a concurrency safe map for storing information about +// DirInfoCache is a concurrency-safe map for storing information about // directories that may contain packages. // // The information in this cache is built incrementally. Entries are initialized in scan. @@ -92,21 +102,26 @@ func (info *directoryPackageInfo) reachedStatus(target directoryPackageStatus) ( // The information in the cache is not expected to change for the cache's // lifetime, so there is no protection against competing writes. Users should // take care not to hold the cache across changes to the underlying files. -// -// TODO(suzmue): consider other concurrency strategies and data structures (RWLocks, sync.Map, etc) -type dirInfoCache struct { +type DirInfoCache struct { mu sync.Mutex // dirs stores information about packages in directories, keyed by absolute path. dirs map[string]*directoryPackageInfo listeners map[*int]cacheListener } +func NewDirInfoCache() *DirInfoCache { + return &DirInfoCache{ + dirs: make(map[string]*directoryPackageInfo), + listeners: make(map[*int]cacheListener), + } +} + type cacheListener func(directoryPackageInfo) // ScanAndListen calls listener on all the items in the cache, and on anything // newly added. The returned stop function waits for all in-flight callbacks to // finish and blocks new ones. -func (d *dirInfoCache) ScanAndListen(ctx context.Context, listener cacheListener) func() { +func (d *DirInfoCache) ScanAndListen(ctx context.Context, listener cacheListener) func() { ctx, cancel := context.WithCancel(ctx) // Flushing out all the callbacks is tricky without knowing how many there @@ -162,8 +177,10 @@ func (d *dirInfoCache) ScanAndListen(ctx context.Context, listener cacheListener } // Store stores the package info for dir. -func (d *dirInfoCache) Store(dir string, info directoryPackageInfo) { +func (d *DirInfoCache) Store(dir string, info directoryPackageInfo) { d.mu.Lock() + // TODO(rfindley, golang/go#59216): should we overwrite an existing entry? + // That seems incorrect as the cache should be idempotent. _, old := d.dirs[dir] d.dirs[dir] = &info var listeners []cacheListener @@ -180,7 +197,7 @@ func (d *dirInfoCache) Store(dir string, info directoryPackageInfo) { } // Load returns a copy of the directoryPackageInfo for absolute directory dir. -func (d *dirInfoCache) Load(dir string) (directoryPackageInfo, bool) { +func (d *DirInfoCache) Load(dir string) (directoryPackageInfo, bool) { d.mu.Lock() defer d.mu.Unlock() info, ok := d.dirs[dir] @@ -191,7 +208,7 @@ func (d *dirInfoCache) Load(dir string) (directoryPackageInfo, bool) { } // Keys returns the keys currently present in d. -func (d *dirInfoCache) Keys() (keys []string) { +func (d *DirInfoCache) Keys() (keys []string) { d.mu.Lock() defer d.mu.Unlock() for key := range d.dirs { @@ -200,7 +217,7 @@ func (d *dirInfoCache) Keys() (keys []string) { return keys } -func (d *dirInfoCache) CachePackageName(info directoryPackageInfo) (string, error) { +func (d *DirInfoCache) CachePackageName(info directoryPackageInfo) (string, error) { if loaded, err := info.reachedStatus(nameLoaded); loaded { return info.packageName, err } @@ -213,7 +230,7 @@ func (d *dirInfoCache) CachePackageName(info directoryPackageInfo) (string, erro return info.packageName, info.err } -func (d *dirInfoCache) CacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) { +func (d *DirInfoCache) CacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []stdlib.Symbol, error) { if reached, _ := info.reachedStatus(exportsLoaded); reached { return info.packageName, info.exports, info.err } @@ -234,3 +251,81 @@ func (d *dirInfoCache) CacheExports(ctx context.Context, env *ProcessEnv, info d d.Store(info.dir, info) return info.packageName, info.exports, info.err } + +// ScanModuleCache walks the given directory, which must be a GOMODCACHE value, +// for directory package information, storing the results in cache. +func ScanModuleCache(dir string, cache *DirInfoCache, logf func(string, ...any)) { + // Note(rfindley): it's hard to see, but this function attempts to implement + // just the side effects on cache of calling PrimeCache with a ProcessEnv + // that has the given dir as its GOMODCACHE. + // + // Teasing out the control flow, we see that we can avoid any handling of + // vendor/ and can infer module info entirely from the path, simplifying the + // logic here. + + root := gopathwalk.Root{ + Path: filepath.Clean(dir), + Type: gopathwalk.RootModuleCache, + } + + directoryInfo := func(root gopathwalk.Root, dir string) directoryPackageInfo { + // This is a copy of ModuleResolver.scanDirForPackage, trimmed down to + // logic that applies to a module cache directory. + + subdir := "" + if dir != root.Path { + subdir = dir[len(root.Path)+len("/"):] + } + + matches := modCacheRegexp.FindStringSubmatch(subdir) + if len(matches) == 0 { + return directoryPackageInfo{ + status: directoryScanned, + err: fmt.Errorf("invalid module cache path: %v", subdir), + } + } + modPath, err := module.UnescapePath(filepath.ToSlash(matches[1])) + if err != nil { + if logf != nil { + logf("decoding module cache path %q: %v", subdir, err) + } + return directoryPackageInfo{ + status: directoryScanned, + err: fmt.Errorf("decoding module cache path %q: %v", subdir, err), + } + } + importPath := path.Join(modPath, filepath.ToSlash(matches[3])) + index := strings.Index(dir, matches[1]+"@"+matches[2]) + modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2]) + modName := readModName(filepath.Join(modDir, "go.mod")) + return directoryPackageInfo{ + status: directoryScanned, + dir: dir, + rootType: root.Type, + nonCanonicalImportPath: importPath, + moduleDir: modDir, + moduleName: modName, + } + } + + add := func(root gopathwalk.Root, dir string) { + info := directoryInfo(root, dir) + cache.Store(info.dir, info) + } + + skip := func(_ gopathwalk.Root, dir string) bool { + // Skip directories that have already been scanned. + // + // Note that gopathwalk only adds "package" directories, which must contain + // a .go file, and all such package directories in the module cache are + // immutable. So if we can load a dir, it can be skipped. + info, ok := cache.Load(dir) + if !ok { + return false + } + packageScanned, _ := info.reachedStatus(directoryScanned) + return packageScanned + } + + gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: logf, ModulesEnabled: true}) +} diff --git a/tools/vendor/golang.org/x/tools/internal/imports/sortimports.go b/tools/vendor/golang.org/x/tools/internal/imports/sortimports.go index 1a0a7ebd9..da8194fd9 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/sortimports.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/sortimports.go @@ -18,7 +18,7 @@ import ( // sortImports sorts runs of consecutive import lines in import blocks in f. // It also removes duplicate imports when it is possible to do so without data loss. // -// It may mutate the token.File. +// It may mutate the token.File and the ast.File. func sortImports(localPrefix string, tokFile *token.File, f *ast.File) { for i, d := range f.Decls { d, ok := d.(*ast.GenDecl) diff --git a/tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go b/tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go deleted file mode 100644 index 9f992c2be..000000000 --- a/tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go +++ /dev/null @@ -1,11345 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Code generated by mkstdlib.go. DO NOT EDIT. - -package imports - -var stdlib = map[string][]string{ - "archive/tar": { - "ErrFieldTooLong", - "ErrHeader", - "ErrInsecurePath", - "ErrWriteAfterClose", - "ErrWriteTooLong", - "FileInfoHeader", - "Format", - "FormatGNU", - "FormatPAX", - "FormatUSTAR", - "FormatUnknown", - "Header", - "NewReader", - "NewWriter", - "Reader", - "TypeBlock", - "TypeChar", - "TypeCont", - "TypeDir", - "TypeFifo", - "TypeGNULongLink", - "TypeGNULongName", - "TypeGNUSparse", - "TypeLink", - "TypeReg", - "TypeRegA", - "TypeSymlink", - "TypeXGlobalHeader", - "TypeXHeader", - "Writer", - }, - "archive/zip": { - "Compressor", - "Decompressor", - "Deflate", - "ErrAlgorithm", - "ErrChecksum", - "ErrFormat", - "ErrInsecurePath", - "File", - "FileHeader", - "FileInfoHeader", - "NewReader", - "NewWriter", - "OpenReader", - "ReadCloser", - "Reader", - "RegisterCompressor", - "RegisterDecompressor", - "Store", - "Writer", - }, - "bufio": { - "ErrAdvanceTooFar", - "ErrBadReadCount", - "ErrBufferFull", - "ErrFinalToken", - "ErrInvalidUnreadByte", - "ErrInvalidUnreadRune", - "ErrNegativeAdvance", - "ErrNegativeCount", - "ErrTooLong", - "MaxScanTokenSize", - "NewReadWriter", - "NewReader", - "NewReaderSize", - "NewScanner", - "NewWriter", - "NewWriterSize", - "ReadWriter", - "Reader", - "ScanBytes", - "ScanLines", - "ScanRunes", - "ScanWords", - "Scanner", - "SplitFunc", - "Writer", - }, - "bytes": { - "Buffer", - "Clone", - "Compare", - "Contains", - "ContainsAny", - "ContainsFunc", - "ContainsRune", - "Count", - "Cut", - "CutPrefix", - "CutSuffix", - "Equal", - "EqualFold", - "ErrTooLarge", - "Fields", - "FieldsFunc", - "HasPrefix", - "HasSuffix", - "Index", - "IndexAny", - "IndexByte", - "IndexFunc", - "IndexRune", - "Join", - "LastIndex", - "LastIndexAny", - "LastIndexByte", - "LastIndexFunc", - "Map", - "MinRead", - "NewBuffer", - "NewBufferString", - "NewReader", - "Reader", - "Repeat", - "Replace", - "ReplaceAll", - "Runes", - "Split", - "SplitAfter", - "SplitAfterN", - "SplitN", - "Title", - "ToLower", - "ToLowerSpecial", - "ToTitle", - "ToTitleSpecial", - "ToUpper", - "ToUpperSpecial", - "ToValidUTF8", - "Trim", - "TrimFunc", - "TrimLeft", - "TrimLeftFunc", - "TrimPrefix", - "TrimRight", - "TrimRightFunc", - "TrimSpace", - "TrimSuffix", - }, - "cmp": { - "Compare", - "Less", - "Ordered", - }, - "compress/bzip2": { - "NewReader", - "StructuralError", - }, - "compress/flate": { - "BestCompression", - "BestSpeed", - "CorruptInputError", - "DefaultCompression", - "HuffmanOnly", - "InternalError", - "NewReader", - "NewReaderDict", - "NewWriter", - "NewWriterDict", - "NoCompression", - "ReadError", - "Reader", - "Resetter", - "WriteError", - "Writer", - }, - "compress/gzip": { - "BestCompression", - "BestSpeed", - "DefaultCompression", - "ErrChecksum", - "ErrHeader", - "Header", - "HuffmanOnly", - "NewReader", - "NewWriter", - "NewWriterLevel", - "NoCompression", - "Reader", - "Writer", - }, - "compress/lzw": { - "LSB", - "MSB", - "NewReader", - "NewWriter", - "Order", - "Reader", - "Writer", - }, - "compress/zlib": { - "BestCompression", - "BestSpeed", - "DefaultCompression", - "ErrChecksum", - "ErrDictionary", - "ErrHeader", - "HuffmanOnly", - "NewReader", - "NewReaderDict", - "NewWriter", - "NewWriterLevel", - "NewWriterLevelDict", - "NoCompression", - "Resetter", - "Writer", - }, - "container/heap": { - "Fix", - "Init", - "Interface", - "Pop", - "Push", - "Remove", - }, - "container/list": { - "Element", - "List", - "New", - }, - "container/ring": { - "New", - "Ring", - }, - "context": { - "AfterFunc", - "Background", - "CancelCauseFunc", - "CancelFunc", - "Canceled", - "Cause", - "Context", - "DeadlineExceeded", - "TODO", - "WithCancel", - "WithCancelCause", - "WithDeadline", - "WithDeadlineCause", - "WithTimeout", - "WithTimeoutCause", - "WithValue", - "WithoutCancel", - }, - "crypto": { - "BLAKE2b_256", - "BLAKE2b_384", - "BLAKE2b_512", - "BLAKE2s_256", - "Decrypter", - "DecrypterOpts", - "Hash", - "MD4", - "MD5", - "MD5SHA1", - "PrivateKey", - "PublicKey", - "RIPEMD160", - "RegisterHash", - "SHA1", - "SHA224", - "SHA256", - "SHA384", - "SHA3_224", - "SHA3_256", - "SHA3_384", - "SHA3_512", - "SHA512", - "SHA512_224", - "SHA512_256", - "Signer", - "SignerOpts", - }, - "crypto/aes": { - "BlockSize", - "KeySizeError", - "NewCipher", - }, - "crypto/cipher": { - "AEAD", - "Block", - "BlockMode", - "NewCBCDecrypter", - "NewCBCEncrypter", - "NewCFBDecrypter", - "NewCFBEncrypter", - "NewCTR", - "NewGCM", - "NewGCMWithNonceSize", - "NewGCMWithTagSize", - "NewOFB", - "Stream", - "StreamReader", - "StreamWriter", - }, - "crypto/des": { - "BlockSize", - "KeySizeError", - "NewCipher", - "NewTripleDESCipher", - }, - "crypto/dsa": { - "ErrInvalidPublicKey", - "GenerateKey", - "GenerateParameters", - "L1024N160", - "L2048N224", - "L2048N256", - "L3072N256", - "ParameterSizes", - "Parameters", - "PrivateKey", - "PublicKey", - "Sign", - "Verify", - }, - "crypto/ecdh": { - "Curve", - "P256", - "P384", - "P521", - "PrivateKey", - "PublicKey", - "X25519", - }, - "crypto/ecdsa": { - "GenerateKey", - "PrivateKey", - "PublicKey", - "Sign", - "SignASN1", - "Verify", - "VerifyASN1", - }, - "crypto/ed25519": { - "GenerateKey", - "NewKeyFromSeed", - "Options", - "PrivateKey", - "PrivateKeySize", - "PublicKey", - "PublicKeySize", - "SeedSize", - "Sign", - "SignatureSize", - "Verify", - "VerifyWithOptions", - }, - "crypto/elliptic": { - "Curve", - "CurveParams", - "GenerateKey", - "Marshal", - "MarshalCompressed", - "P224", - "P256", - "P384", - "P521", - "Unmarshal", - "UnmarshalCompressed", - }, - "crypto/hmac": { - "Equal", - "New", - }, - "crypto/md5": { - "BlockSize", - "New", - "Size", - "Sum", - }, - "crypto/rand": { - "Int", - "Prime", - "Read", - "Reader", - }, - "crypto/rc4": { - "Cipher", - "KeySizeError", - "NewCipher", - }, - "crypto/rsa": { - "CRTValue", - "DecryptOAEP", - "DecryptPKCS1v15", - "DecryptPKCS1v15SessionKey", - "EncryptOAEP", - "EncryptPKCS1v15", - "ErrDecryption", - "ErrMessageTooLong", - "ErrVerification", - "GenerateKey", - "GenerateMultiPrimeKey", - "OAEPOptions", - "PKCS1v15DecryptOptions", - "PSSOptions", - "PSSSaltLengthAuto", - "PSSSaltLengthEqualsHash", - "PrecomputedValues", - "PrivateKey", - "PublicKey", - "SignPKCS1v15", - "SignPSS", - "VerifyPKCS1v15", - "VerifyPSS", - }, - "crypto/sha1": { - "BlockSize", - "New", - "Size", - "Sum", - }, - "crypto/sha256": { - "BlockSize", - "New", - "New224", - "Size", - "Size224", - "Sum224", - "Sum256", - }, - "crypto/sha512": { - "BlockSize", - "New", - "New384", - "New512_224", - "New512_256", - "Size", - "Size224", - "Size256", - "Size384", - "Sum384", - "Sum512", - "Sum512_224", - "Sum512_256", - }, - "crypto/subtle": { - "ConstantTimeByteEq", - "ConstantTimeCompare", - "ConstantTimeCopy", - "ConstantTimeEq", - "ConstantTimeLessOrEq", - "ConstantTimeSelect", - "XORBytes", - }, - "crypto/tls": { - "AlertError", - "Certificate", - "CertificateRequestInfo", - "CertificateVerificationError", - "CipherSuite", - "CipherSuiteName", - "CipherSuites", - "Client", - "ClientAuthType", - "ClientHelloInfo", - "ClientSessionCache", - "ClientSessionState", - "Config", - "Conn", - "ConnectionState", - "CurveID", - "CurveP256", - "CurveP384", - "CurveP521", - "Dial", - "DialWithDialer", - "Dialer", - "ECDSAWithP256AndSHA256", - "ECDSAWithP384AndSHA384", - "ECDSAWithP521AndSHA512", - "ECDSAWithSHA1", - "Ed25519", - "InsecureCipherSuites", - "Listen", - "LoadX509KeyPair", - "NewLRUClientSessionCache", - "NewListener", - "NewResumptionState", - "NoClientCert", - "PKCS1WithSHA1", - "PKCS1WithSHA256", - "PKCS1WithSHA384", - "PKCS1WithSHA512", - "PSSWithSHA256", - "PSSWithSHA384", - "PSSWithSHA512", - "ParseSessionState", - "QUICClient", - "QUICConfig", - "QUICConn", - "QUICEncryptionLevel", - "QUICEncryptionLevelApplication", - "QUICEncryptionLevelEarly", - "QUICEncryptionLevelHandshake", - "QUICEncryptionLevelInitial", - "QUICEvent", - "QUICEventKind", - "QUICHandshakeDone", - "QUICNoEvent", - "QUICRejectedEarlyData", - "QUICServer", - "QUICSessionTicketOptions", - "QUICSetReadSecret", - "QUICSetWriteSecret", - "QUICTransportParameters", - "QUICTransportParametersRequired", - "QUICWriteData", - "RecordHeaderError", - "RenegotiateFreelyAsClient", - "RenegotiateNever", - "RenegotiateOnceAsClient", - "RenegotiationSupport", - "RequestClientCert", - "RequireAndVerifyClientCert", - "RequireAnyClientCert", - "Server", - "SessionState", - "SignatureScheme", - "TLS_AES_128_GCM_SHA256", - "TLS_AES_256_GCM_SHA384", - "TLS_CHACHA20_POLY1305_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", - "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", - "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", - "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", - "TLS_ECDHE_RSA_WITH_RC4_128_SHA", - "TLS_FALLBACK_SCSV", - "TLS_RSA_WITH_3DES_EDE_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA256", - "TLS_RSA_WITH_AES_128_GCM_SHA256", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_AES_256_GCM_SHA384", - "TLS_RSA_WITH_RC4_128_SHA", - "VerifyClientCertIfGiven", - "VersionName", - "VersionSSL30", - "VersionTLS10", - "VersionTLS11", - "VersionTLS12", - "VersionTLS13", - "X25519", - "X509KeyPair", - }, - "crypto/x509": { - "CANotAuthorizedForExtKeyUsage", - "CANotAuthorizedForThisName", - "CertPool", - "Certificate", - "CertificateInvalidError", - "CertificateRequest", - "ConstraintViolationError", - "CreateCertificate", - "CreateCertificateRequest", - "CreateRevocationList", - "DSA", - "DSAWithSHA1", - "DSAWithSHA256", - "DecryptPEMBlock", - "ECDSA", - "ECDSAWithSHA1", - "ECDSAWithSHA256", - "ECDSAWithSHA384", - "ECDSAWithSHA512", - "Ed25519", - "EncryptPEMBlock", - "ErrUnsupportedAlgorithm", - "Expired", - "ExtKeyUsage", - "ExtKeyUsageAny", - "ExtKeyUsageClientAuth", - "ExtKeyUsageCodeSigning", - "ExtKeyUsageEmailProtection", - "ExtKeyUsageIPSECEndSystem", - "ExtKeyUsageIPSECTunnel", - "ExtKeyUsageIPSECUser", - "ExtKeyUsageMicrosoftCommercialCodeSigning", - "ExtKeyUsageMicrosoftKernelCodeSigning", - "ExtKeyUsageMicrosoftServerGatedCrypto", - "ExtKeyUsageNetscapeServerGatedCrypto", - "ExtKeyUsageOCSPSigning", - "ExtKeyUsageServerAuth", - "ExtKeyUsageTimeStamping", - "HostnameError", - "IncompatibleUsage", - "IncorrectPasswordError", - "InsecureAlgorithmError", - "InvalidReason", - "IsEncryptedPEMBlock", - "KeyUsage", - "KeyUsageCRLSign", - "KeyUsageCertSign", - "KeyUsageContentCommitment", - "KeyUsageDataEncipherment", - "KeyUsageDecipherOnly", - "KeyUsageDigitalSignature", - "KeyUsageEncipherOnly", - "KeyUsageKeyAgreement", - "KeyUsageKeyEncipherment", - "MD2WithRSA", - "MD5WithRSA", - "MarshalECPrivateKey", - "MarshalPKCS1PrivateKey", - "MarshalPKCS1PublicKey", - "MarshalPKCS8PrivateKey", - "MarshalPKIXPublicKey", - "NameConstraintsWithoutSANs", - "NameMismatch", - "NewCertPool", - "NotAuthorizedToSign", - "PEMCipher", - "PEMCipher3DES", - "PEMCipherAES128", - "PEMCipherAES192", - "PEMCipherAES256", - "PEMCipherDES", - "ParseCRL", - "ParseCertificate", - "ParseCertificateRequest", - "ParseCertificates", - "ParseDERCRL", - "ParseECPrivateKey", - "ParsePKCS1PrivateKey", - "ParsePKCS1PublicKey", - "ParsePKCS8PrivateKey", - "ParsePKIXPublicKey", - "ParseRevocationList", - "PublicKeyAlgorithm", - "PureEd25519", - "RSA", - "RevocationList", - "RevocationListEntry", - "SHA1WithRSA", - "SHA256WithRSA", - "SHA256WithRSAPSS", - "SHA384WithRSA", - "SHA384WithRSAPSS", - "SHA512WithRSA", - "SHA512WithRSAPSS", - "SetFallbackRoots", - "SignatureAlgorithm", - "SystemCertPool", - "SystemRootsError", - "TooManyConstraints", - "TooManyIntermediates", - "UnconstrainedName", - "UnhandledCriticalExtension", - "UnknownAuthorityError", - "UnknownPublicKeyAlgorithm", - "UnknownSignatureAlgorithm", - "VerifyOptions", - }, - "crypto/x509/pkix": { - "AlgorithmIdentifier", - "AttributeTypeAndValue", - "AttributeTypeAndValueSET", - "CertificateList", - "Extension", - "Name", - "RDNSequence", - "RelativeDistinguishedNameSET", - "RevokedCertificate", - "TBSCertificateList", - }, - "database/sql": { - "ColumnType", - "Conn", - "DB", - "DBStats", - "Drivers", - "ErrConnDone", - "ErrNoRows", - "ErrTxDone", - "IsolationLevel", - "LevelDefault", - "LevelLinearizable", - "LevelReadCommitted", - "LevelReadUncommitted", - "LevelRepeatableRead", - "LevelSerializable", - "LevelSnapshot", - "LevelWriteCommitted", - "Named", - "NamedArg", - "NullBool", - "NullByte", - "NullFloat64", - "NullInt16", - "NullInt32", - "NullInt64", - "NullString", - "NullTime", - "Open", - "OpenDB", - "Out", - "RawBytes", - "Register", - "Result", - "Row", - "Rows", - "Scanner", - "Stmt", - "Tx", - "TxOptions", - }, - "database/sql/driver": { - "Bool", - "ColumnConverter", - "Conn", - "ConnBeginTx", - "ConnPrepareContext", - "Connector", - "DefaultParameterConverter", - "Driver", - "DriverContext", - "ErrBadConn", - "ErrRemoveArgument", - "ErrSkip", - "Execer", - "ExecerContext", - "Int32", - "IsScanValue", - "IsValue", - "IsolationLevel", - "NamedValue", - "NamedValueChecker", - "NotNull", - "Null", - "Pinger", - "Queryer", - "QueryerContext", - "Result", - "ResultNoRows", - "Rows", - "RowsAffected", - "RowsColumnTypeDatabaseTypeName", - "RowsColumnTypeLength", - "RowsColumnTypeNullable", - "RowsColumnTypePrecisionScale", - "RowsColumnTypeScanType", - "RowsNextResultSet", - "SessionResetter", - "Stmt", - "StmtExecContext", - "StmtQueryContext", - "String", - "Tx", - "TxOptions", - "Validator", - "Value", - "ValueConverter", - "Valuer", - }, - "debug/buildinfo": { - "BuildInfo", - "Read", - "ReadFile", - }, - "debug/dwarf": { - "AddrType", - "ArrayType", - "Attr", - "AttrAbstractOrigin", - "AttrAccessibility", - "AttrAddrBase", - "AttrAddrClass", - "AttrAlignment", - "AttrAllocated", - "AttrArtificial", - "AttrAssociated", - "AttrBaseTypes", - "AttrBinaryScale", - "AttrBitOffset", - "AttrBitSize", - "AttrByteSize", - "AttrCallAllCalls", - "AttrCallAllSourceCalls", - "AttrCallAllTailCalls", - "AttrCallColumn", - "AttrCallDataLocation", - "AttrCallDataValue", - "AttrCallFile", - "AttrCallLine", - "AttrCallOrigin", - "AttrCallPC", - "AttrCallParameter", - "AttrCallReturnPC", - "AttrCallTailCall", - "AttrCallTarget", - "AttrCallTargetClobbered", - "AttrCallValue", - "AttrCalling", - "AttrCommonRef", - "AttrCompDir", - "AttrConstExpr", - "AttrConstValue", - "AttrContainingType", - "AttrCount", - "AttrDataBitOffset", - "AttrDataLocation", - "AttrDataMemberLoc", - "AttrDecimalScale", - "AttrDecimalSign", - "AttrDeclColumn", - "AttrDeclFile", - "AttrDeclLine", - "AttrDeclaration", - "AttrDefaultValue", - "AttrDefaulted", - "AttrDeleted", - "AttrDescription", - "AttrDigitCount", - "AttrDiscr", - "AttrDiscrList", - "AttrDiscrValue", - "AttrDwoName", - "AttrElemental", - "AttrEncoding", - "AttrEndianity", - "AttrEntrypc", - "AttrEnumClass", - "AttrExplicit", - "AttrExportSymbols", - "AttrExtension", - "AttrExternal", - "AttrFrameBase", - "AttrFriend", - "AttrHighpc", - "AttrIdentifierCase", - "AttrImport", - "AttrInline", - "AttrIsOptional", - "AttrLanguage", - "AttrLinkageName", - "AttrLocation", - "AttrLoclistsBase", - "AttrLowerBound", - "AttrLowpc", - "AttrMacroInfo", - "AttrMacros", - "AttrMainSubprogram", - "AttrMutable", - "AttrName", - "AttrNamelistItem", - "AttrNoreturn", - "AttrObjectPointer", - "AttrOrdering", - "AttrPictureString", - "AttrPriority", - "AttrProducer", - "AttrPrototyped", - "AttrPure", - "AttrRanges", - "AttrRank", - "AttrRecursive", - "AttrReference", - "AttrReturnAddr", - "AttrRnglistsBase", - "AttrRvalueReference", - "AttrSegment", - "AttrSibling", - "AttrSignature", - "AttrSmall", - "AttrSpecification", - "AttrStartScope", - "AttrStaticLink", - "AttrStmtList", - "AttrStrOffsetsBase", - "AttrStride", - "AttrStrideSize", - "AttrStringLength", - "AttrStringLengthBitSize", - "AttrStringLengthByteSize", - "AttrThreadsScaled", - "AttrTrampoline", - "AttrType", - "AttrUpperBound", - "AttrUseLocation", - "AttrUseUTF8", - "AttrVarParam", - "AttrVirtuality", - "AttrVisibility", - "AttrVtableElemLoc", - "BasicType", - "BoolType", - "CharType", - "Class", - "ClassAddrPtr", - "ClassAddress", - "ClassBlock", - "ClassConstant", - "ClassExprLoc", - "ClassFlag", - "ClassLinePtr", - "ClassLocList", - "ClassLocListPtr", - "ClassMacPtr", - "ClassRangeListPtr", - "ClassReference", - "ClassReferenceAlt", - "ClassReferenceSig", - "ClassRngList", - "ClassRngListsPtr", - "ClassStrOffsetsPtr", - "ClassString", - "ClassStringAlt", - "ClassUnknown", - "CommonType", - "ComplexType", - "Data", - "DecodeError", - "DotDotDotType", - "Entry", - "EnumType", - "EnumValue", - "ErrUnknownPC", - "Field", - "FloatType", - "FuncType", - "IntType", - "LineEntry", - "LineFile", - "LineReader", - "LineReaderPos", - "New", - "Offset", - "PtrType", - "QualType", - "Reader", - "StructField", - "StructType", - "Tag", - "TagAccessDeclaration", - "TagArrayType", - "TagAtomicType", - "TagBaseType", - "TagCallSite", - "TagCallSiteParameter", - "TagCatchDwarfBlock", - "TagClassType", - "TagCoarrayType", - "TagCommonDwarfBlock", - "TagCommonInclusion", - "TagCompileUnit", - "TagCondition", - "TagConstType", - "TagConstant", - "TagDwarfProcedure", - "TagDynamicType", - "TagEntryPoint", - "TagEnumerationType", - "TagEnumerator", - "TagFileType", - "TagFormalParameter", - "TagFriend", - "TagGenericSubrange", - "TagImmutableType", - "TagImportedDeclaration", - "TagImportedModule", - "TagImportedUnit", - "TagInheritance", - "TagInlinedSubroutine", - "TagInterfaceType", - "TagLabel", - "TagLexDwarfBlock", - "TagMember", - "TagModule", - "TagMutableType", - "TagNamelist", - "TagNamelistItem", - "TagNamespace", - "TagPackedType", - "TagPartialUnit", - "TagPointerType", - "TagPtrToMemberType", - "TagReferenceType", - "TagRestrictType", - "TagRvalueReferenceType", - "TagSetType", - "TagSharedType", - "TagSkeletonUnit", - "TagStringType", - "TagStructType", - "TagSubprogram", - "TagSubrangeType", - "TagSubroutineType", - "TagTemplateAlias", - "TagTemplateTypeParameter", - "TagTemplateValueParameter", - "TagThrownType", - "TagTryDwarfBlock", - "TagTypeUnit", - "TagTypedef", - "TagUnionType", - "TagUnspecifiedParameters", - "TagUnspecifiedType", - "TagVariable", - "TagVariant", - "TagVariantPart", - "TagVolatileType", - "TagWithStmt", - "Type", - "TypedefType", - "UcharType", - "UintType", - "UnspecifiedType", - "UnsupportedType", - "VoidType", - }, - "debug/elf": { - "ARM_MAGIC_TRAMP_NUMBER", - "COMPRESS_HIOS", - "COMPRESS_HIPROC", - "COMPRESS_LOOS", - "COMPRESS_LOPROC", - "COMPRESS_ZLIB", - "COMPRESS_ZSTD", - "Chdr32", - "Chdr64", - "Class", - "CompressionType", - "DF_1_CONFALT", - "DF_1_DIRECT", - "DF_1_DISPRELDNE", - "DF_1_DISPRELPND", - "DF_1_EDITED", - "DF_1_ENDFILTEE", - "DF_1_GLOBAL", - "DF_1_GLOBAUDIT", - "DF_1_GROUP", - "DF_1_IGNMULDEF", - "DF_1_INITFIRST", - "DF_1_INTERPOSE", - "DF_1_KMOD", - "DF_1_LOADFLTR", - "DF_1_NOCOMMON", - "DF_1_NODEFLIB", - "DF_1_NODELETE", - "DF_1_NODIRECT", - "DF_1_NODUMP", - "DF_1_NOHDR", - "DF_1_NOKSYMS", - "DF_1_NOOPEN", - "DF_1_NORELOC", - "DF_1_NOW", - "DF_1_ORIGIN", - "DF_1_PIE", - "DF_1_SINGLETON", - "DF_1_STUB", - "DF_1_SYMINTPOSE", - "DF_1_TRANS", - "DF_1_WEAKFILTER", - "DF_BIND_NOW", - "DF_ORIGIN", - "DF_STATIC_TLS", - "DF_SYMBOLIC", - "DF_TEXTREL", - "DT_ADDRRNGHI", - "DT_ADDRRNGLO", - "DT_AUDIT", - "DT_AUXILIARY", - "DT_BIND_NOW", - "DT_CHECKSUM", - "DT_CONFIG", - "DT_DEBUG", - "DT_DEPAUDIT", - "DT_ENCODING", - "DT_FEATURE", - "DT_FILTER", - "DT_FINI", - "DT_FINI_ARRAY", - "DT_FINI_ARRAYSZ", - "DT_FLAGS", - "DT_FLAGS_1", - "DT_GNU_CONFLICT", - "DT_GNU_CONFLICTSZ", - "DT_GNU_HASH", - "DT_GNU_LIBLIST", - "DT_GNU_LIBLISTSZ", - "DT_GNU_PRELINKED", - "DT_HASH", - "DT_HIOS", - "DT_HIPROC", - "DT_INIT", - "DT_INIT_ARRAY", - "DT_INIT_ARRAYSZ", - "DT_JMPREL", - "DT_LOOS", - "DT_LOPROC", - "DT_MIPS_AUX_DYNAMIC", - "DT_MIPS_BASE_ADDRESS", - "DT_MIPS_COMPACT_SIZE", - "DT_MIPS_CONFLICT", - "DT_MIPS_CONFLICTNO", - "DT_MIPS_CXX_FLAGS", - "DT_MIPS_DELTA_CLASS", - "DT_MIPS_DELTA_CLASSSYM", - "DT_MIPS_DELTA_CLASSSYM_NO", - "DT_MIPS_DELTA_CLASS_NO", - "DT_MIPS_DELTA_INSTANCE", - "DT_MIPS_DELTA_INSTANCE_NO", - "DT_MIPS_DELTA_RELOC", - "DT_MIPS_DELTA_RELOC_NO", - "DT_MIPS_DELTA_SYM", - "DT_MIPS_DELTA_SYM_NO", - "DT_MIPS_DYNSTR_ALIGN", - "DT_MIPS_FLAGS", - "DT_MIPS_GOTSYM", - "DT_MIPS_GP_VALUE", - "DT_MIPS_HIDDEN_GOTIDX", - "DT_MIPS_HIPAGENO", - "DT_MIPS_ICHECKSUM", - "DT_MIPS_INTERFACE", - "DT_MIPS_INTERFACE_SIZE", - "DT_MIPS_IVERSION", - "DT_MIPS_LIBLIST", - "DT_MIPS_LIBLISTNO", - "DT_MIPS_LOCALPAGE_GOTIDX", - "DT_MIPS_LOCAL_GOTIDX", - "DT_MIPS_LOCAL_GOTNO", - "DT_MIPS_MSYM", - "DT_MIPS_OPTIONS", - "DT_MIPS_PERF_SUFFIX", - "DT_MIPS_PIXIE_INIT", - "DT_MIPS_PLTGOT", - "DT_MIPS_PROTECTED_GOTIDX", - "DT_MIPS_RLD_MAP", - "DT_MIPS_RLD_MAP_REL", - "DT_MIPS_RLD_TEXT_RESOLVE_ADDR", - "DT_MIPS_RLD_VERSION", - "DT_MIPS_RWPLT", - "DT_MIPS_SYMBOL_LIB", - "DT_MIPS_SYMTABNO", - "DT_MIPS_TIME_STAMP", - "DT_MIPS_UNREFEXTNO", - "DT_MOVEENT", - "DT_MOVESZ", - "DT_MOVETAB", - "DT_NEEDED", - "DT_NULL", - "DT_PLTGOT", - "DT_PLTPAD", - "DT_PLTPADSZ", - "DT_PLTREL", - "DT_PLTRELSZ", - "DT_POSFLAG_1", - "DT_PPC64_GLINK", - "DT_PPC64_OPD", - "DT_PPC64_OPDSZ", - "DT_PPC64_OPT", - "DT_PPC_GOT", - "DT_PPC_OPT", - "DT_PREINIT_ARRAY", - "DT_PREINIT_ARRAYSZ", - "DT_REL", - "DT_RELA", - "DT_RELACOUNT", - "DT_RELAENT", - "DT_RELASZ", - "DT_RELCOUNT", - "DT_RELENT", - "DT_RELSZ", - "DT_RPATH", - "DT_RUNPATH", - "DT_SONAME", - "DT_SPARC_REGISTER", - "DT_STRSZ", - "DT_STRTAB", - "DT_SYMBOLIC", - "DT_SYMENT", - "DT_SYMINENT", - "DT_SYMINFO", - "DT_SYMINSZ", - "DT_SYMTAB", - "DT_SYMTAB_SHNDX", - "DT_TEXTREL", - "DT_TLSDESC_GOT", - "DT_TLSDESC_PLT", - "DT_USED", - "DT_VALRNGHI", - "DT_VALRNGLO", - "DT_VERDEF", - "DT_VERDEFNUM", - "DT_VERNEED", - "DT_VERNEEDNUM", - "DT_VERSYM", - "Data", - "Dyn32", - "Dyn64", - "DynFlag", - "DynFlag1", - "DynTag", - "EI_ABIVERSION", - "EI_CLASS", - "EI_DATA", - "EI_NIDENT", - "EI_OSABI", - "EI_PAD", - "EI_VERSION", - "ELFCLASS32", - "ELFCLASS64", - "ELFCLASSNONE", - "ELFDATA2LSB", - "ELFDATA2MSB", - "ELFDATANONE", - "ELFMAG", - "ELFOSABI_86OPEN", - "ELFOSABI_AIX", - "ELFOSABI_ARM", - "ELFOSABI_AROS", - "ELFOSABI_CLOUDABI", - "ELFOSABI_FENIXOS", - "ELFOSABI_FREEBSD", - "ELFOSABI_HPUX", - "ELFOSABI_HURD", - "ELFOSABI_IRIX", - "ELFOSABI_LINUX", - "ELFOSABI_MODESTO", - "ELFOSABI_NETBSD", - "ELFOSABI_NONE", - "ELFOSABI_NSK", - "ELFOSABI_OPENBSD", - "ELFOSABI_OPENVMS", - "ELFOSABI_SOLARIS", - "ELFOSABI_STANDALONE", - "ELFOSABI_TRU64", - "EM_386", - "EM_486", - "EM_56800EX", - "EM_68HC05", - "EM_68HC08", - "EM_68HC11", - "EM_68HC12", - "EM_68HC16", - "EM_68K", - "EM_78KOR", - "EM_8051", - "EM_860", - "EM_88K", - "EM_960", - "EM_AARCH64", - "EM_ALPHA", - "EM_ALPHA_STD", - "EM_ALTERA_NIOS2", - "EM_AMDGPU", - "EM_ARC", - "EM_ARCA", - "EM_ARC_COMPACT", - "EM_ARC_COMPACT2", - "EM_ARM", - "EM_AVR", - "EM_AVR32", - "EM_BA1", - "EM_BA2", - "EM_BLACKFIN", - "EM_BPF", - "EM_C166", - "EM_CDP", - "EM_CE", - "EM_CLOUDSHIELD", - "EM_COGE", - "EM_COLDFIRE", - "EM_COOL", - "EM_COREA_1ST", - "EM_COREA_2ND", - "EM_CR", - "EM_CR16", - "EM_CRAYNV2", - "EM_CRIS", - "EM_CRX", - "EM_CSR_KALIMBA", - "EM_CUDA", - "EM_CYPRESS_M8C", - "EM_D10V", - "EM_D30V", - "EM_DSP24", - "EM_DSPIC30F", - "EM_DXP", - "EM_ECOG1", - "EM_ECOG16", - "EM_ECOG1X", - "EM_ECOG2", - "EM_ETPU", - "EM_EXCESS", - "EM_F2MC16", - "EM_FIREPATH", - "EM_FR20", - "EM_FR30", - "EM_FT32", - "EM_FX66", - "EM_H8S", - "EM_H8_300", - "EM_H8_300H", - "EM_H8_500", - "EM_HUANY", - "EM_IA_64", - "EM_INTEL205", - "EM_INTEL206", - "EM_INTEL207", - "EM_INTEL208", - "EM_INTEL209", - "EM_IP2K", - "EM_JAVELIN", - "EM_K10M", - "EM_KM32", - "EM_KMX16", - "EM_KMX32", - "EM_KMX8", - "EM_KVARC", - "EM_L10M", - "EM_LANAI", - "EM_LATTICEMICO32", - "EM_LOONGARCH", - "EM_M16C", - "EM_M32", - "EM_M32C", - "EM_M32R", - "EM_MANIK", - "EM_MAX", - "EM_MAXQ30", - "EM_MCHP_PIC", - "EM_MCST_ELBRUS", - "EM_ME16", - "EM_METAG", - "EM_MICROBLAZE", - "EM_MIPS", - "EM_MIPS_RS3_LE", - "EM_MIPS_RS4_BE", - "EM_MIPS_X", - "EM_MMA", - "EM_MMDSP_PLUS", - "EM_MMIX", - "EM_MN10200", - "EM_MN10300", - "EM_MOXIE", - "EM_MSP430", - "EM_NCPU", - "EM_NDR1", - "EM_NDS32", - "EM_NONE", - "EM_NORC", - "EM_NS32K", - "EM_OPEN8", - "EM_OPENRISC", - "EM_PARISC", - "EM_PCP", - "EM_PDP10", - "EM_PDP11", - "EM_PDSP", - "EM_PJ", - "EM_PPC", - "EM_PPC64", - "EM_PRISM", - "EM_QDSP6", - "EM_R32C", - "EM_RCE", - "EM_RH32", - "EM_RISCV", - "EM_RL78", - "EM_RS08", - "EM_RX", - "EM_S370", - "EM_S390", - "EM_SCORE7", - "EM_SEP", - "EM_SE_C17", - "EM_SE_C33", - "EM_SH", - "EM_SHARC", - "EM_SLE9X", - "EM_SNP1K", - "EM_SPARC", - "EM_SPARC32PLUS", - "EM_SPARCV9", - "EM_ST100", - "EM_ST19", - "EM_ST200", - "EM_ST7", - "EM_ST9PLUS", - "EM_STARCORE", - "EM_STM8", - "EM_STXP7X", - "EM_SVX", - "EM_TILE64", - "EM_TILEGX", - "EM_TILEPRO", - "EM_TINYJ", - "EM_TI_ARP32", - "EM_TI_C2000", - "EM_TI_C5500", - "EM_TI_C6000", - "EM_TI_PRU", - "EM_TMM_GPP", - "EM_TPC", - "EM_TRICORE", - "EM_TRIMEDIA", - "EM_TSK3000", - "EM_UNICORE", - "EM_V800", - "EM_V850", - "EM_VAX", - "EM_VIDEOCORE", - "EM_VIDEOCORE3", - "EM_VIDEOCORE5", - "EM_VISIUM", - "EM_VPP500", - "EM_X86_64", - "EM_XCORE", - "EM_XGATE", - "EM_XIMO16", - "EM_XTENSA", - "EM_Z80", - "EM_ZSP", - "ET_CORE", - "ET_DYN", - "ET_EXEC", - "ET_HIOS", - "ET_HIPROC", - "ET_LOOS", - "ET_LOPROC", - "ET_NONE", - "ET_REL", - "EV_CURRENT", - "EV_NONE", - "ErrNoSymbols", - "File", - "FileHeader", - "FormatError", - "Header32", - "Header64", - "ImportedSymbol", - "Machine", - "NT_FPREGSET", - "NT_PRPSINFO", - "NT_PRSTATUS", - "NType", - "NewFile", - "OSABI", - "Open", - "PF_MASKOS", - "PF_MASKPROC", - "PF_R", - "PF_W", - "PF_X", - "PT_AARCH64_ARCHEXT", - "PT_AARCH64_UNWIND", - "PT_ARM_ARCHEXT", - "PT_ARM_EXIDX", - "PT_DYNAMIC", - "PT_GNU_EH_FRAME", - "PT_GNU_MBIND_HI", - "PT_GNU_MBIND_LO", - "PT_GNU_PROPERTY", - "PT_GNU_RELRO", - "PT_GNU_STACK", - "PT_HIOS", - "PT_HIPROC", - "PT_INTERP", - "PT_LOAD", - "PT_LOOS", - "PT_LOPROC", - "PT_MIPS_ABIFLAGS", - "PT_MIPS_OPTIONS", - "PT_MIPS_REGINFO", - "PT_MIPS_RTPROC", - "PT_NOTE", - "PT_NULL", - "PT_OPENBSD_BOOTDATA", - "PT_OPENBSD_RANDOMIZE", - "PT_OPENBSD_WXNEEDED", - "PT_PAX_FLAGS", - "PT_PHDR", - "PT_S390_PGSTE", - "PT_SHLIB", - "PT_SUNWSTACK", - "PT_SUNW_EH_FRAME", - "PT_TLS", - "Prog", - "Prog32", - "Prog64", - "ProgFlag", - "ProgHeader", - "ProgType", - "R_386", - "R_386_16", - "R_386_32", - "R_386_32PLT", - "R_386_8", - "R_386_COPY", - "R_386_GLOB_DAT", - "R_386_GOT32", - "R_386_GOT32X", - "R_386_GOTOFF", - "R_386_GOTPC", - "R_386_IRELATIVE", - "R_386_JMP_SLOT", - "R_386_NONE", - "R_386_PC16", - "R_386_PC32", - "R_386_PC8", - "R_386_PLT32", - "R_386_RELATIVE", - "R_386_SIZE32", - "R_386_TLS_DESC", - "R_386_TLS_DESC_CALL", - "R_386_TLS_DTPMOD32", - "R_386_TLS_DTPOFF32", - "R_386_TLS_GD", - "R_386_TLS_GD_32", - "R_386_TLS_GD_CALL", - "R_386_TLS_GD_POP", - "R_386_TLS_GD_PUSH", - "R_386_TLS_GOTDESC", - "R_386_TLS_GOTIE", - "R_386_TLS_IE", - "R_386_TLS_IE_32", - "R_386_TLS_LDM", - "R_386_TLS_LDM_32", - "R_386_TLS_LDM_CALL", - "R_386_TLS_LDM_POP", - "R_386_TLS_LDM_PUSH", - "R_386_TLS_LDO_32", - "R_386_TLS_LE", - "R_386_TLS_LE_32", - "R_386_TLS_TPOFF", - "R_386_TLS_TPOFF32", - "R_390", - "R_390_12", - "R_390_16", - "R_390_20", - "R_390_32", - "R_390_64", - "R_390_8", - "R_390_COPY", - "R_390_GLOB_DAT", - "R_390_GOT12", - "R_390_GOT16", - "R_390_GOT20", - "R_390_GOT32", - "R_390_GOT64", - "R_390_GOTENT", - "R_390_GOTOFF", - "R_390_GOTOFF16", - "R_390_GOTOFF64", - "R_390_GOTPC", - "R_390_GOTPCDBL", - "R_390_GOTPLT12", - "R_390_GOTPLT16", - "R_390_GOTPLT20", - "R_390_GOTPLT32", - "R_390_GOTPLT64", - "R_390_GOTPLTENT", - "R_390_GOTPLTOFF16", - "R_390_GOTPLTOFF32", - "R_390_GOTPLTOFF64", - "R_390_JMP_SLOT", - "R_390_NONE", - "R_390_PC16", - "R_390_PC16DBL", - "R_390_PC32", - "R_390_PC32DBL", - "R_390_PC64", - "R_390_PLT16DBL", - "R_390_PLT32", - "R_390_PLT32DBL", - "R_390_PLT64", - "R_390_RELATIVE", - "R_390_TLS_DTPMOD", - "R_390_TLS_DTPOFF", - "R_390_TLS_GD32", - "R_390_TLS_GD64", - "R_390_TLS_GDCALL", - "R_390_TLS_GOTIE12", - "R_390_TLS_GOTIE20", - "R_390_TLS_GOTIE32", - "R_390_TLS_GOTIE64", - "R_390_TLS_IE32", - "R_390_TLS_IE64", - "R_390_TLS_IEENT", - "R_390_TLS_LDCALL", - "R_390_TLS_LDM32", - "R_390_TLS_LDM64", - "R_390_TLS_LDO32", - "R_390_TLS_LDO64", - "R_390_TLS_LE32", - "R_390_TLS_LE64", - "R_390_TLS_LOAD", - "R_390_TLS_TPOFF", - "R_AARCH64", - "R_AARCH64_ABS16", - "R_AARCH64_ABS32", - "R_AARCH64_ABS64", - "R_AARCH64_ADD_ABS_LO12_NC", - "R_AARCH64_ADR_GOT_PAGE", - "R_AARCH64_ADR_PREL_LO21", - "R_AARCH64_ADR_PREL_PG_HI21", - "R_AARCH64_ADR_PREL_PG_HI21_NC", - "R_AARCH64_CALL26", - "R_AARCH64_CONDBR19", - "R_AARCH64_COPY", - "R_AARCH64_GLOB_DAT", - "R_AARCH64_GOT_LD_PREL19", - "R_AARCH64_IRELATIVE", - "R_AARCH64_JUMP26", - "R_AARCH64_JUMP_SLOT", - "R_AARCH64_LD64_GOTOFF_LO15", - "R_AARCH64_LD64_GOTPAGE_LO15", - "R_AARCH64_LD64_GOT_LO12_NC", - "R_AARCH64_LDST128_ABS_LO12_NC", - "R_AARCH64_LDST16_ABS_LO12_NC", - "R_AARCH64_LDST32_ABS_LO12_NC", - "R_AARCH64_LDST64_ABS_LO12_NC", - "R_AARCH64_LDST8_ABS_LO12_NC", - "R_AARCH64_LD_PREL_LO19", - "R_AARCH64_MOVW_SABS_G0", - "R_AARCH64_MOVW_SABS_G1", - "R_AARCH64_MOVW_SABS_G2", - "R_AARCH64_MOVW_UABS_G0", - "R_AARCH64_MOVW_UABS_G0_NC", - "R_AARCH64_MOVW_UABS_G1", - "R_AARCH64_MOVW_UABS_G1_NC", - "R_AARCH64_MOVW_UABS_G2", - "R_AARCH64_MOVW_UABS_G2_NC", - "R_AARCH64_MOVW_UABS_G3", - "R_AARCH64_NONE", - "R_AARCH64_NULL", - "R_AARCH64_P32_ABS16", - "R_AARCH64_P32_ABS32", - "R_AARCH64_P32_ADD_ABS_LO12_NC", - "R_AARCH64_P32_ADR_GOT_PAGE", - "R_AARCH64_P32_ADR_PREL_LO21", - "R_AARCH64_P32_ADR_PREL_PG_HI21", - "R_AARCH64_P32_CALL26", - "R_AARCH64_P32_CONDBR19", - "R_AARCH64_P32_COPY", - "R_AARCH64_P32_GLOB_DAT", - "R_AARCH64_P32_GOT_LD_PREL19", - "R_AARCH64_P32_IRELATIVE", - "R_AARCH64_P32_JUMP26", - "R_AARCH64_P32_JUMP_SLOT", - "R_AARCH64_P32_LD32_GOT_LO12_NC", - "R_AARCH64_P32_LDST128_ABS_LO12_NC", - "R_AARCH64_P32_LDST16_ABS_LO12_NC", - "R_AARCH64_P32_LDST32_ABS_LO12_NC", - "R_AARCH64_P32_LDST64_ABS_LO12_NC", - "R_AARCH64_P32_LDST8_ABS_LO12_NC", - "R_AARCH64_P32_LD_PREL_LO19", - "R_AARCH64_P32_MOVW_SABS_G0", - "R_AARCH64_P32_MOVW_UABS_G0", - "R_AARCH64_P32_MOVW_UABS_G0_NC", - "R_AARCH64_P32_MOVW_UABS_G1", - "R_AARCH64_P32_PREL16", - "R_AARCH64_P32_PREL32", - "R_AARCH64_P32_RELATIVE", - "R_AARCH64_P32_TLSDESC", - "R_AARCH64_P32_TLSDESC_ADD_LO12_NC", - "R_AARCH64_P32_TLSDESC_ADR_PAGE21", - "R_AARCH64_P32_TLSDESC_ADR_PREL21", - "R_AARCH64_P32_TLSDESC_CALL", - "R_AARCH64_P32_TLSDESC_LD32_LO12_NC", - "R_AARCH64_P32_TLSDESC_LD_PREL19", - "R_AARCH64_P32_TLSGD_ADD_LO12_NC", - "R_AARCH64_P32_TLSGD_ADR_PAGE21", - "R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21", - "R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC", - "R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19", - "R_AARCH64_P32_TLSLE_ADD_TPREL_HI12", - "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12", - "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC", - "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0", - "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC", - "R_AARCH64_P32_TLSLE_MOVW_TPREL_G1", - "R_AARCH64_P32_TLS_DTPMOD", - "R_AARCH64_P32_TLS_DTPREL", - "R_AARCH64_P32_TLS_TPREL", - "R_AARCH64_P32_TSTBR14", - "R_AARCH64_PREL16", - "R_AARCH64_PREL32", - "R_AARCH64_PREL64", - "R_AARCH64_RELATIVE", - "R_AARCH64_TLSDESC", - "R_AARCH64_TLSDESC_ADD", - "R_AARCH64_TLSDESC_ADD_LO12_NC", - "R_AARCH64_TLSDESC_ADR_PAGE21", - "R_AARCH64_TLSDESC_ADR_PREL21", - "R_AARCH64_TLSDESC_CALL", - "R_AARCH64_TLSDESC_LD64_LO12_NC", - "R_AARCH64_TLSDESC_LDR", - "R_AARCH64_TLSDESC_LD_PREL19", - "R_AARCH64_TLSDESC_OFF_G0_NC", - "R_AARCH64_TLSDESC_OFF_G1", - "R_AARCH64_TLSGD_ADD_LO12_NC", - "R_AARCH64_TLSGD_ADR_PAGE21", - "R_AARCH64_TLSGD_ADR_PREL21", - "R_AARCH64_TLSGD_MOVW_G0_NC", - "R_AARCH64_TLSGD_MOVW_G1", - "R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21", - "R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC", - "R_AARCH64_TLSIE_LD_GOTTPREL_PREL19", - "R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC", - "R_AARCH64_TLSIE_MOVW_GOTTPREL_G1", - "R_AARCH64_TLSLD_ADR_PAGE21", - "R_AARCH64_TLSLD_ADR_PREL21", - "R_AARCH64_TLSLD_LDST128_DTPREL_LO12", - "R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC", - "R_AARCH64_TLSLE_ADD_TPREL_HI12", - "R_AARCH64_TLSLE_ADD_TPREL_LO12", - "R_AARCH64_TLSLE_ADD_TPREL_LO12_NC", - "R_AARCH64_TLSLE_LDST128_TPREL_LO12", - "R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC", - "R_AARCH64_TLSLE_MOVW_TPREL_G0", - "R_AARCH64_TLSLE_MOVW_TPREL_G0_NC", - "R_AARCH64_TLSLE_MOVW_TPREL_G1", - "R_AARCH64_TLSLE_MOVW_TPREL_G1_NC", - "R_AARCH64_TLSLE_MOVW_TPREL_G2", - "R_AARCH64_TLS_DTPMOD64", - "R_AARCH64_TLS_DTPREL64", - "R_AARCH64_TLS_TPREL64", - "R_AARCH64_TSTBR14", - "R_ALPHA", - "R_ALPHA_BRADDR", - "R_ALPHA_COPY", - "R_ALPHA_GLOB_DAT", - "R_ALPHA_GPDISP", - "R_ALPHA_GPREL32", - "R_ALPHA_GPRELHIGH", - "R_ALPHA_GPRELLOW", - "R_ALPHA_GPVALUE", - "R_ALPHA_HINT", - "R_ALPHA_IMMED_BR_HI32", - "R_ALPHA_IMMED_GP_16", - "R_ALPHA_IMMED_GP_HI32", - "R_ALPHA_IMMED_LO32", - "R_ALPHA_IMMED_SCN_HI32", - "R_ALPHA_JMP_SLOT", - "R_ALPHA_LITERAL", - "R_ALPHA_LITUSE", - "R_ALPHA_NONE", - "R_ALPHA_OP_PRSHIFT", - "R_ALPHA_OP_PSUB", - "R_ALPHA_OP_PUSH", - "R_ALPHA_OP_STORE", - "R_ALPHA_REFLONG", - "R_ALPHA_REFQUAD", - "R_ALPHA_RELATIVE", - "R_ALPHA_SREL16", - "R_ALPHA_SREL32", - "R_ALPHA_SREL64", - "R_ARM", - "R_ARM_ABS12", - "R_ARM_ABS16", - "R_ARM_ABS32", - "R_ARM_ABS32_NOI", - "R_ARM_ABS8", - "R_ARM_ALU_PCREL_15_8", - "R_ARM_ALU_PCREL_23_15", - "R_ARM_ALU_PCREL_7_0", - "R_ARM_ALU_PC_G0", - "R_ARM_ALU_PC_G0_NC", - "R_ARM_ALU_PC_G1", - "R_ARM_ALU_PC_G1_NC", - "R_ARM_ALU_PC_G2", - "R_ARM_ALU_SBREL_19_12_NC", - "R_ARM_ALU_SBREL_27_20_CK", - "R_ARM_ALU_SB_G0", - "R_ARM_ALU_SB_G0_NC", - "R_ARM_ALU_SB_G1", - "R_ARM_ALU_SB_G1_NC", - "R_ARM_ALU_SB_G2", - "R_ARM_AMP_VCALL9", - "R_ARM_BASE_ABS", - "R_ARM_CALL", - "R_ARM_COPY", - "R_ARM_GLOB_DAT", - "R_ARM_GNU_VTENTRY", - "R_ARM_GNU_VTINHERIT", - "R_ARM_GOT32", - "R_ARM_GOTOFF", - "R_ARM_GOTOFF12", - "R_ARM_GOTPC", - "R_ARM_GOTRELAX", - "R_ARM_GOT_ABS", - "R_ARM_GOT_BREL12", - "R_ARM_GOT_PREL", - "R_ARM_IRELATIVE", - "R_ARM_JUMP24", - "R_ARM_JUMP_SLOT", - "R_ARM_LDC_PC_G0", - "R_ARM_LDC_PC_G1", - "R_ARM_LDC_PC_G2", - "R_ARM_LDC_SB_G0", - "R_ARM_LDC_SB_G1", - "R_ARM_LDC_SB_G2", - "R_ARM_LDRS_PC_G0", - "R_ARM_LDRS_PC_G1", - "R_ARM_LDRS_PC_G2", - "R_ARM_LDRS_SB_G0", - "R_ARM_LDRS_SB_G1", - "R_ARM_LDRS_SB_G2", - "R_ARM_LDR_PC_G1", - "R_ARM_LDR_PC_G2", - "R_ARM_LDR_SBREL_11_10_NC", - "R_ARM_LDR_SB_G0", - "R_ARM_LDR_SB_G1", - "R_ARM_LDR_SB_G2", - "R_ARM_ME_TOO", - "R_ARM_MOVT_ABS", - "R_ARM_MOVT_BREL", - "R_ARM_MOVT_PREL", - "R_ARM_MOVW_ABS_NC", - "R_ARM_MOVW_BREL", - "R_ARM_MOVW_BREL_NC", - "R_ARM_MOVW_PREL_NC", - "R_ARM_NONE", - "R_ARM_PC13", - "R_ARM_PC24", - "R_ARM_PLT32", - "R_ARM_PLT32_ABS", - "R_ARM_PREL31", - "R_ARM_PRIVATE_0", - "R_ARM_PRIVATE_1", - "R_ARM_PRIVATE_10", - "R_ARM_PRIVATE_11", - "R_ARM_PRIVATE_12", - "R_ARM_PRIVATE_13", - "R_ARM_PRIVATE_14", - "R_ARM_PRIVATE_15", - "R_ARM_PRIVATE_2", - "R_ARM_PRIVATE_3", - "R_ARM_PRIVATE_4", - "R_ARM_PRIVATE_5", - "R_ARM_PRIVATE_6", - "R_ARM_PRIVATE_7", - "R_ARM_PRIVATE_8", - "R_ARM_PRIVATE_9", - "R_ARM_RABS32", - "R_ARM_RBASE", - "R_ARM_REL32", - "R_ARM_REL32_NOI", - "R_ARM_RELATIVE", - "R_ARM_RPC24", - "R_ARM_RREL32", - "R_ARM_RSBREL32", - "R_ARM_RXPC25", - "R_ARM_SBREL31", - "R_ARM_SBREL32", - "R_ARM_SWI24", - "R_ARM_TARGET1", - "R_ARM_TARGET2", - "R_ARM_THM_ABS5", - "R_ARM_THM_ALU_ABS_G0_NC", - "R_ARM_THM_ALU_ABS_G1_NC", - "R_ARM_THM_ALU_ABS_G2_NC", - "R_ARM_THM_ALU_ABS_G3", - "R_ARM_THM_ALU_PREL_11_0", - "R_ARM_THM_GOT_BREL12", - "R_ARM_THM_JUMP11", - "R_ARM_THM_JUMP19", - "R_ARM_THM_JUMP24", - "R_ARM_THM_JUMP6", - "R_ARM_THM_JUMP8", - "R_ARM_THM_MOVT_ABS", - "R_ARM_THM_MOVT_BREL", - "R_ARM_THM_MOVT_PREL", - "R_ARM_THM_MOVW_ABS_NC", - "R_ARM_THM_MOVW_BREL", - "R_ARM_THM_MOVW_BREL_NC", - "R_ARM_THM_MOVW_PREL_NC", - "R_ARM_THM_PC12", - "R_ARM_THM_PC22", - "R_ARM_THM_PC8", - "R_ARM_THM_RPC22", - "R_ARM_THM_SWI8", - "R_ARM_THM_TLS_CALL", - "R_ARM_THM_TLS_DESCSEQ16", - "R_ARM_THM_TLS_DESCSEQ32", - "R_ARM_THM_XPC22", - "R_ARM_TLS_CALL", - "R_ARM_TLS_DESCSEQ", - "R_ARM_TLS_DTPMOD32", - "R_ARM_TLS_DTPOFF32", - "R_ARM_TLS_GD32", - "R_ARM_TLS_GOTDESC", - "R_ARM_TLS_IE12GP", - "R_ARM_TLS_IE32", - "R_ARM_TLS_LDM32", - "R_ARM_TLS_LDO12", - "R_ARM_TLS_LDO32", - "R_ARM_TLS_LE12", - "R_ARM_TLS_LE32", - "R_ARM_TLS_TPOFF32", - "R_ARM_V4BX", - "R_ARM_XPC25", - "R_INFO", - "R_INFO32", - "R_LARCH", - "R_LARCH_32", - "R_LARCH_32_PCREL", - "R_LARCH_64", - "R_LARCH_ABS64_HI12", - "R_LARCH_ABS64_LO20", - "R_LARCH_ABS_HI20", - "R_LARCH_ABS_LO12", - "R_LARCH_ADD16", - "R_LARCH_ADD24", - "R_LARCH_ADD32", - "R_LARCH_ADD64", - "R_LARCH_ADD8", - "R_LARCH_B16", - "R_LARCH_B21", - "R_LARCH_B26", - "R_LARCH_COPY", - "R_LARCH_GNU_VTENTRY", - "R_LARCH_GNU_VTINHERIT", - "R_LARCH_GOT64_HI12", - "R_LARCH_GOT64_LO20", - "R_LARCH_GOT64_PC_HI12", - "R_LARCH_GOT64_PC_LO20", - "R_LARCH_GOT_HI20", - "R_LARCH_GOT_LO12", - "R_LARCH_GOT_PC_HI20", - "R_LARCH_GOT_PC_LO12", - "R_LARCH_IRELATIVE", - "R_LARCH_JUMP_SLOT", - "R_LARCH_MARK_LA", - "R_LARCH_MARK_PCREL", - "R_LARCH_NONE", - "R_LARCH_PCALA64_HI12", - "R_LARCH_PCALA64_LO20", - "R_LARCH_PCALA_HI20", - "R_LARCH_PCALA_LO12", - "R_LARCH_RELATIVE", - "R_LARCH_RELAX", - "R_LARCH_SOP_ADD", - "R_LARCH_SOP_AND", - "R_LARCH_SOP_ASSERT", - "R_LARCH_SOP_IF_ELSE", - "R_LARCH_SOP_NOT", - "R_LARCH_SOP_POP_32_S_0_10_10_16_S2", - "R_LARCH_SOP_POP_32_S_0_5_10_16_S2", - "R_LARCH_SOP_POP_32_S_10_12", - "R_LARCH_SOP_POP_32_S_10_16", - "R_LARCH_SOP_POP_32_S_10_16_S2", - "R_LARCH_SOP_POP_32_S_10_5", - "R_LARCH_SOP_POP_32_S_5_20", - "R_LARCH_SOP_POP_32_U", - "R_LARCH_SOP_POP_32_U_10_12", - "R_LARCH_SOP_PUSH_ABSOLUTE", - "R_LARCH_SOP_PUSH_DUP", - "R_LARCH_SOP_PUSH_GPREL", - "R_LARCH_SOP_PUSH_PCREL", - "R_LARCH_SOP_PUSH_PLT_PCREL", - "R_LARCH_SOP_PUSH_TLS_GD", - "R_LARCH_SOP_PUSH_TLS_GOT", - "R_LARCH_SOP_PUSH_TLS_TPREL", - "R_LARCH_SOP_SL", - "R_LARCH_SOP_SR", - "R_LARCH_SOP_SUB", - "R_LARCH_SUB16", - "R_LARCH_SUB24", - "R_LARCH_SUB32", - "R_LARCH_SUB64", - "R_LARCH_SUB8", - "R_LARCH_TLS_DTPMOD32", - "R_LARCH_TLS_DTPMOD64", - "R_LARCH_TLS_DTPREL32", - "R_LARCH_TLS_DTPREL64", - "R_LARCH_TLS_GD_HI20", - "R_LARCH_TLS_GD_PC_HI20", - "R_LARCH_TLS_IE64_HI12", - "R_LARCH_TLS_IE64_LO20", - "R_LARCH_TLS_IE64_PC_HI12", - "R_LARCH_TLS_IE64_PC_LO20", - "R_LARCH_TLS_IE_HI20", - "R_LARCH_TLS_IE_LO12", - "R_LARCH_TLS_IE_PC_HI20", - "R_LARCH_TLS_IE_PC_LO12", - "R_LARCH_TLS_LD_HI20", - "R_LARCH_TLS_LD_PC_HI20", - "R_LARCH_TLS_LE64_HI12", - "R_LARCH_TLS_LE64_LO20", - "R_LARCH_TLS_LE_HI20", - "R_LARCH_TLS_LE_LO12", - "R_LARCH_TLS_TPREL32", - "R_LARCH_TLS_TPREL64", - "R_MIPS", - "R_MIPS_16", - "R_MIPS_26", - "R_MIPS_32", - "R_MIPS_64", - "R_MIPS_ADD_IMMEDIATE", - "R_MIPS_CALL16", - "R_MIPS_CALL_HI16", - "R_MIPS_CALL_LO16", - "R_MIPS_DELETE", - "R_MIPS_GOT16", - "R_MIPS_GOT_DISP", - "R_MIPS_GOT_HI16", - "R_MIPS_GOT_LO16", - "R_MIPS_GOT_OFST", - "R_MIPS_GOT_PAGE", - "R_MIPS_GPREL16", - "R_MIPS_GPREL32", - "R_MIPS_HI16", - "R_MIPS_HIGHER", - "R_MIPS_HIGHEST", - "R_MIPS_INSERT_A", - "R_MIPS_INSERT_B", - "R_MIPS_JALR", - "R_MIPS_LITERAL", - "R_MIPS_LO16", - "R_MIPS_NONE", - "R_MIPS_PC16", - "R_MIPS_PJUMP", - "R_MIPS_REL16", - "R_MIPS_REL32", - "R_MIPS_RELGOT", - "R_MIPS_SCN_DISP", - "R_MIPS_SHIFT5", - "R_MIPS_SHIFT6", - "R_MIPS_SUB", - "R_MIPS_TLS_DTPMOD32", - "R_MIPS_TLS_DTPMOD64", - "R_MIPS_TLS_DTPREL32", - "R_MIPS_TLS_DTPREL64", - "R_MIPS_TLS_DTPREL_HI16", - "R_MIPS_TLS_DTPREL_LO16", - "R_MIPS_TLS_GD", - "R_MIPS_TLS_GOTTPREL", - "R_MIPS_TLS_LDM", - "R_MIPS_TLS_TPREL32", - "R_MIPS_TLS_TPREL64", - "R_MIPS_TLS_TPREL_HI16", - "R_MIPS_TLS_TPREL_LO16", - "R_PPC", - "R_PPC64", - "R_PPC64_ADDR14", - "R_PPC64_ADDR14_BRNTAKEN", - "R_PPC64_ADDR14_BRTAKEN", - "R_PPC64_ADDR16", - "R_PPC64_ADDR16_DS", - "R_PPC64_ADDR16_HA", - "R_PPC64_ADDR16_HI", - "R_PPC64_ADDR16_HIGH", - "R_PPC64_ADDR16_HIGHA", - "R_PPC64_ADDR16_HIGHER", - "R_PPC64_ADDR16_HIGHER34", - "R_PPC64_ADDR16_HIGHERA", - "R_PPC64_ADDR16_HIGHERA34", - "R_PPC64_ADDR16_HIGHEST", - "R_PPC64_ADDR16_HIGHEST34", - "R_PPC64_ADDR16_HIGHESTA", - "R_PPC64_ADDR16_HIGHESTA34", - "R_PPC64_ADDR16_LO", - "R_PPC64_ADDR16_LO_DS", - "R_PPC64_ADDR24", - "R_PPC64_ADDR32", - "R_PPC64_ADDR64", - "R_PPC64_ADDR64_LOCAL", - "R_PPC64_COPY", - "R_PPC64_D28", - "R_PPC64_D34", - "R_PPC64_D34_HA30", - "R_PPC64_D34_HI30", - "R_PPC64_D34_LO", - "R_PPC64_DTPMOD64", - "R_PPC64_DTPREL16", - "R_PPC64_DTPREL16_DS", - "R_PPC64_DTPREL16_HA", - "R_PPC64_DTPREL16_HI", - "R_PPC64_DTPREL16_HIGH", - "R_PPC64_DTPREL16_HIGHA", - "R_PPC64_DTPREL16_HIGHER", - "R_PPC64_DTPREL16_HIGHERA", - "R_PPC64_DTPREL16_HIGHEST", - "R_PPC64_DTPREL16_HIGHESTA", - "R_PPC64_DTPREL16_LO", - "R_PPC64_DTPREL16_LO_DS", - "R_PPC64_DTPREL34", - "R_PPC64_DTPREL64", - "R_PPC64_ENTRY", - "R_PPC64_GLOB_DAT", - "R_PPC64_GNU_VTENTRY", - "R_PPC64_GNU_VTINHERIT", - "R_PPC64_GOT16", - "R_PPC64_GOT16_DS", - "R_PPC64_GOT16_HA", - "R_PPC64_GOT16_HI", - "R_PPC64_GOT16_LO", - "R_PPC64_GOT16_LO_DS", - "R_PPC64_GOT_DTPREL16_DS", - "R_PPC64_GOT_DTPREL16_HA", - "R_PPC64_GOT_DTPREL16_HI", - "R_PPC64_GOT_DTPREL16_LO_DS", - "R_PPC64_GOT_DTPREL_PCREL34", - "R_PPC64_GOT_PCREL34", - "R_PPC64_GOT_TLSGD16", - "R_PPC64_GOT_TLSGD16_HA", - "R_PPC64_GOT_TLSGD16_HI", - "R_PPC64_GOT_TLSGD16_LO", - "R_PPC64_GOT_TLSGD_PCREL34", - "R_PPC64_GOT_TLSLD16", - "R_PPC64_GOT_TLSLD16_HA", - "R_PPC64_GOT_TLSLD16_HI", - "R_PPC64_GOT_TLSLD16_LO", - "R_PPC64_GOT_TLSLD_PCREL34", - "R_PPC64_GOT_TPREL16_DS", - "R_PPC64_GOT_TPREL16_HA", - "R_PPC64_GOT_TPREL16_HI", - "R_PPC64_GOT_TPREL16_LO_DS", - "R_PPC64_GOT_TPREL_PCREL34", - "R_PPC64_IRELATIVE", - "R_PPC64_JMP_IREL", - "R_PPC64_JMP_SLOT", - "R_PPC64_NONE", - "R_PPC64_PCREL28", - "R_PPC64_PCREL34", - "R_PPC64_PCREL_OPT", - "R_PPC64_PLT16_HA", - "R_PPC64_PLT16_HI", - "R_PPC64_PLT16_LO", - "R_PPC64_PLT16_LO_DS", - "R_PPC64_PLT32", - "R_PPC64_PLT64", - "R_PPC64_PLTCALL", - "R_PPC64_PLTCALL_NOTOC", - "R_PPC64_PLTGOT16", - "R_PPC64_PLTGOT16_DS", - "R_PPC64_PLTGOT16_HA", - "R_PPC64_PLTGOT16_HI", - "R_PPC64_PLTGOT16_LO", - "R_PPC64_PLTGOT_LO_DS", - "R_PPC64_PLTREL32", - "R_PPC64_PLTREL64", - "R_PPC64_PLTSEQ", - "R_PPC64_PLTSEQ_NOTOC", - "R_PPC64_PLT_PCREL34", - "R_PPC64_PLT_PCREL34_NOTOC", - "R_PPC64_REL14", - "R_PPC64_REL14_BRNTAKEN", - "R_PPC64_REL14_BRTAKEN", - "R_PPC64_REL16", - "R_PPC64_REL16DX_HA", - "R_PPC64_REL16_HA", - "R_PPC64_REL16_HI", - "R_PPC64_REL16_HIGH", - "R_PPC64_REL16_HIGHA", - "R_PPC64_REL16_HIGHER", - "R_PPC64_REL16_HIGHER34", - "R_PPC64_REL16_HIGHERA", - "R_PPC64_REL16_HIGHERA34", - "R_PPC64_REL16_HIGHEST", - "R_PPC64_REL16_HIGHEST34", - "R_PPC64_REL16_HIGHESTA", - "R_PPC64_REL16_HIGHESTA34", - "R_PPC64_REL16_LO", - "R_PPC64_REL24", - "R_PPC64_REL24_NOTOC", - "R_PPC64_REL24_P9NOTOC", - "R_PPC64_REL30", - "R_PPC64_REL32", - "R_PPC64_REL64", - "R_PPC64_RELATIVE", - "R_PPC64_SECTOFF", - "R_PPC64_SECTOFF_DS", - "R_PPC64_SECTOFF_HA", - "R_PPC64_SECTOFF_HI", - "R_PPC64_SECTOFF_LO", - "R_PPC64_SECTOFF_LO_DS", - "R_PPC64_TLS", - "R_PPC64_TLSGD", - "R_PPC64_TLSLD", - "R_PPC64_TOC", - "R_PPC64_TOC16", - "R_PPC64_TOC16_DS", - "R_PPC64_TOC16_HA", - "R_PPC64_TOC16_HI", - "R_PPC64_TOC16_LO", - "R_PPC64_TOC16_LO_DS", - "R_PPC64_TOCSAVE", - "R_PPC64_TPREL16", - "R_PPC64_TPREL16_DS", - "R_PPC64_TPREL16_HA", - "R_PPC64_TPREL16_HI", - "R_PPC64_TPREL16_HIGH", - "R_PPC64_TPREL16_HIGHA", - "R_PPC64_TPREL16_HIGHER", - "R_PPC64_TPREL16_HIGHERA", - "R_PPC64_TPREL16_HIGHEST", - "R_PPC64_TPREL16_HIGHESTA", - "R_PPC64_TPREL16_LO", - "R_PPC64_TPREL16_LO_DS", - "R_PPC64_TPREL34", - "R_PPC64_TPREL64", - "R_PPC64_UADDR16", - "R_PPC64_UADDR32", - "R_PPC64_UADDR64", - "R_PPC_ADDR14", - "R_PPC_ADDR14_BRNTAKEN", - "R_PPC_ADDR14_BRTAKEN", - "R_PPC_ADDR16", - "R_PPC_ADDR16_HA", - "R_PPC_ADDR16_HI", - "R_PPC_ADDR16_LO", - "R_PPC_ADDR24", - "R_PPC_ADDR32", - "R_PPC_COPY", - "R_PPC_DTPMOD32", - "R_PPC_DTPREL16", - "R_PPC_DTPREL16_HA", - "R_PPC_DTPREL16_HI", - "R_PPC_DTPREL16_LO", - "R_PPC_DTPREL32", - "R_PPC_EMB_BIT_FLD", - "R_PPC_EMB_MRKREF", - "R_PPC_EMB_NADDR16", - "R_PPC_EMB_NADDR16_HA", - "R_PPC_EMB_NADDR16_HI", - "R_PPC_EMB_NADDR16_LO", - "R_PPC_EMB_NADDR32", - "R_PPC_EMB_RELSDA", - "R_PPC_EMB_RELSEC16", - "R_PPC_EMB_RELST_HA", - "R_PPC_EMB_RELST_HI", - "R_PPC_EMB_RELST_LO", - "R_PPC_EMB_SDA21", - "R_PPC_EMB_SDA2I16", - "R_PPC_EMB_SDA2REL", - "R_PPC_EMB_SDAI16", - "R_PPC_GLOB_DAT", - "R_PPC_GOT16", - "R_PPC_GOT16_HA", - "R_PPC_GOT16_HI", - "R_PPC_GOT16_LO", - "R_PPC_GOT_TLSGD16", - "R_PPC_GOT_TLSGD16_HA", - "R_PPC_GOT_TLSGD16_HI", - "R_PPC_GOT_TLSGD16_LO", - "R_PPC_GOT_TLSLD16", - "R_PPC_GOT_TLSLD16_HA", - "R_PPC_GOT_TLSLD16_HI", - "R_PPC_GOT_TLSLD16_LO", - "R_PPC_GOT_TPREL16", - "R_PPC_GOT_TPREL16_HA", - "R_PPC_GOT_TPREL16_HI", - "R_PPC_GOT_TPREL16_LO", - "R_PPC_JMP_SLOT", - "R_PPC_LOCAL24PC", - "R_PPC_NONE", - "R_PPC_PLT16_HA", - "R_PPC_PLT16_HI", - "R_PPC_PLT16_LO", - "R_PPC_PLT32", - "R_PPC_PLTREL24", - "R_PPC_PLTREL32", - "R_PPC_REL14", - "R_PPC_REL14_BRNTAKEN", - "R_PPC_REL14_BRTAKEN", - "R_PPC_REL24", - "R_PPC_REL32", - "R_PPC_RELATIVE", - "R_PPC_SDAREL16", - "R_PPC_SECTOFF", - "R_PPC_SECTOFF_HA", - "R_PPC_SECTOFF_HI", - "R_PPC_SECTOFF_LO", - "R_PPC_TLS", - "R_PPC_TPREL16", - "R_PPC_TPREL16_HA", - "R_PPC_TPREL16_HI", - "R_PPC_TPREL16_LO", - "R_PPC_TPREL32", - "R_PPC_UADDR16", - "R_PPC_UADDR32", - "R_RISCV", - "R_RISCV_32", - "R_RISCV_32_PCREL", - "R_RISCV_64", - "R_RISCV_ADD16", - "R_RISCV_ADD32", - "R_RISCV_ADD64", - "R_RISCV_ADD8", - "R_RISCV_ALIGN", - "R_RISCV_BRANCH", - "R_RISCV_CALL", - "R_RISCV_CALL_PLT", - "R_RISCV_COPY", - "R_RISCV_GNU_VTENTRY", - "R_RISCV_GNU_VTINHERIT", - "R_RISCV_GOT_HI20", - "R_RISCV_GPREL_I", - "R_RISCV_GPREL_S", - "R_RISCV_HI20", - "R_RISCV_JAL", - "R_RISCV_JUMP_SLOT", - "R_RISCV_LO12_I", - "R_RISCV_LO12_S", - "R_RISCV_NONE", - "R_RISCV_PCREL_HI20", - "R_RISCV_PCREL_LO12_I", - "R_RISCV_PCREL_LO12_S", - "R_RISCV_RELATIVE", - "R_RISCV_RELAX", - "R_RISCV_RVC_BRANCH", - "R_RISCV_RVC_JUMP", - "R_RISCV_RVC_LUI", - "R_RISCV_SET16", - "R_RISCV_SET32", - "R_RISCV_SET6", - "R_RISCV_SET8", - "R_RISCV_SUB16", - "R_RISCV_SUB32", - "R_RISCV_SUB6", - "R_RISCV_SUB64", - "R_RISCV_SUB8", - "R_RISCV_TLS_DTPMOD32", - "R_RISCV_TLS_DTPMOD64", - "R_RISCV_TLS_DTPREL32", - "R_RISCV_TLS_DTPREL64", - "R_RISCV_TLS_GD_HI20", - "R_RISCV_TLS_GOT_HI20", - "R_RISCV_TLS_TPREL32", - "R_RISCV_TLS_TPREL64", - "R_RISCV_TPREL_ADD", - "R_RISCV_TPREL_HI20", - "R_RISCV_TPREL_I", - "R_RISCV_TPREL_LO12_I", - "R_RISCV_TPREL_LO12_S", - "R_RISCV_TPREL_S", - "R_SPARC", - "R_SPARC_10", - "R_SPARC_11", - "R_SPARC_13", - "R_SPARC_16", - "R_SPARC_22", - "R_SPARC_32", - "R_SPARC_5", - "R_SPARC_6", - "R_SPARC_64", - "R_SPARC_7", - "R_SPARC_8", - "R_SPARC_COPY", - "R_SPARC_DISP16", - "R_SPARC_DISP32", - "R_SPARC_DISP64", - "R_SPARC_DISP8", - "R_SPARC_GLOB_DAT", - "R_SPARC_GLOB_JMP", - "R_SPARC_GOT10", - "R_SPARC_GOT13", - "R_SPARC_GOT22", - "R_SPARC_H44", - "R_SPARC_HH22", - "R_SPARC_HI22", - "R_SPARC_HIPLT22", - "R_SPARC_HIX22", - "R_SPARC_HM10", - "R_SPARC_JMP_SLOT", - "R_SPARC_L44", - "R_SPARC_LM22", - "R_SPARC_LO10", - "R_SPARC_LOPLT10", - "R_SPARC_LOX10", - "R_SPARC_M44", - "R_SPARC_NONE", - "R_SPARC_OLO10", - "R_SPARC_PC10", - "R_SPARC_PC22", - "R_SPARC_PCPLT10", - "R_SPARC_PCPLT22", - "R_SPARC_PCPLT32", - "R_SPARC_PC_HH22", - "R_SPARC_PC_HM10", - "R_SPARC_PC_LM22", - "R_SPARC_PLT32", - "R_SPARC_PLT64", - "R_SPARC_REGISTER", - "R_SPARC_RELATIVE", - "R_SPARC_UA16", - "R_SPARC_UA32", - "R_SPARC_UA64", - "R_SPARC_WDISP16", - "R_SPARC_WDISP19", - "R_SPARC_WDISP22", - "R_SPARC_WDISP30", - "R_SPARC_WPLT30", - "R_SYM32", - "R_SYM64", - "R_TYPE32", - "R_TYPE64", - "R_X86_64", - "R_X86_64_16", - "R_X86_64_32", - "R_X86_64_32S", - "R_X86_64_64", - "R_X86_64_8", - "R_X86_64_COPY", - "R_X86_64_DTPMOD64", - "R_X86_64_DTPOFF32", - "R_X86_64_DTPOFF64", - "R_X86_64_GLOB_DAT", - "R_X86_64_GOT32", - "R_X86_64_GOT64", - "R_X86_64_GOTOFF64", - "R_X86_64_GOTPC32", - "R_X86_64_GOTPC32_TLSDESC", - "R_X86_64_GOTPC64", - "R_X86_64_GOTPCREL", - "R_X86_64_GOTPCREL64", - "R_X86_64_GOTPCRELX", - "R_X86_64_GOTPLT64", - "R_X86_64_GOTTPOFF", - "R_X86_64_IRELATIVE", - "R_X86_64_JMP_SLOT", - "R_X86_64_NONE", - "R_X86_64_PC16", - "R_X86_64_PC32", - "R_X86_64_PC32_BND", - "R_X86_64_PC64", - "R_X86_64_PC8", - "R_X86_64_PLT32", - "R_X86_64_PLT32_BND", - "R_X86_64_PLTOFF64", - "R_X86_64_RELATIVE", - "R_X86_64_RELATIVE64", - "R_X86_64_REX_GOTPCRELX", - "R_X86_64_SIZE32", - "R_X86_64_SIZE64", - "R_X86_64_TLSDESC", - "R_X86_64_TLSDESC_CALL", - "R_X86_64_TLSGD", - "R_X86_64_TLSLD", - "R_X86_64_TPOFF32", - "R_X86_64_TPOFF64", - "Rel32", - "Rel64", - "Rela32", - "Rela64", - "SHF_ALLOC", - "SHF_COMPRESSED", - "SHF_EXECINSTR", - "SHF_GROUP", - "SHF_INFO_LINK", - "SHF_LINK_ORDER", - "SHF_MASKOS", - "SHF_MASKPROC", - "SHF_MERGE", - "SHF_OS_NONCONFORMING", - "SHF_STRINGS", - "SHF_TLS", - "SHF_WRITE", - "SHN_ABS", - "SHN_COMMON", - "SHN_HIOS", - "SHN_HIPROC", - "SHN_HIRESERVE", - "SHN_LOOS", - "SHN_LOPROC", - "SHN_LORESERVE", - "SHN_UNDEF", - "SHN_XINDEX", - "SHT_DYNAMIC", - "SHT_DYNSYM", - "SHT_FINI_ARRAY", - "SHT_GNU_ATTRIBUTES", - "SHT_GNU_HASH", - "SHT_GNU_LIBLIST", - "SHT_GNU_VERDEF", - "SHT_GNU_VERNEED", - "SHT_GNU_VERSYM", - "SHT_GROUP", - "SHT_HASH", - "SHT_HIOS", - "SHT_HIPROC", - "SHT_HIUSER", - "SHT_INIT_ARRAY", - "SHT_LOOS", - "SHT_LOPROC", - "SHT_LOUSER", - "SHT_MIPS_ABIFLAGS", - "SHT_NOBITS", - "SHT_NOTE", - "SHT_NULL", - "SHT_PREINIT_ARRAY", - "SHT_PROGBITS", - "SHT_REL", - "SHT_RELA", - "SHT_SHLIB", - "SHT_STRTAB", - "SHT_SYMTAB", - "SHT_SYMTAB_SHNDX", - "STB_GLOBAL", - "STB_HIOS", - "STB_HIPROC", - "STB_LOCAL", - "STB_LOOS", - "STB_LOPROC", - "STB_WEAK", - "STT_COMMON", - "STT_FILE", - "STT_FUNC", - "STT_HIOS", - "STT_HIPROC", - "STT_LOOS", - "STT_LOPROC", - "STT_NOTYPE", - "STT_OBJECT", - "STT_SECTION", - "STT_TLS", - "STV_DEFAULT", - "STV_HIDDEN", - "STV_INTERNAL", - "STV_PROTECTED", - "ST_BIND", - "ST_INFO", - "ST_TYPE", - "ST_VISIBILITY", - "Section", - "Section32", - "Section64", - "SectionFlag", - "SectionHeader", - "SectionIndex", - "SectionType", - "Sym32", - "Sym32Size", - "Sym64", - "Sym64Size", - "SymBind", - "SymType", - "SymVis", - "Symbol", - "Type", - "Version", - }, - "debug/gosym": { - "DecodingError", - "Func", - "LineTable", - "NewLineTable", - "NewTable", - "Obj", - "Sym", - "Table", - "UnknownFileError", - "UnknownLineError", - }, - "debug/macho": { - "ARM64_RELOC_ADDEND", - "ARM64_RELOC_BRANCH26", - "ARM64_RELOC_GOT_LOAD_PAGE21", - "ARM64_RELOC_GOT_LOAD_PAGEOFF12", - "ARM64_RELOC_PAGE21", - "ARM64_RELOC_PAGEOFF12", - "ARM64_RELOC_POINTER_TO_GOT", - "ARM64_RELOC_SUBTRACTOR", - "ARM64_RELOC_TLVP_LOAD_PAGE21", - "ARM64_RELOC_TLVP_LOAD_PAGEOFF12", - "ARM64_RELOC_UNSIGNED", - "ARM_RELOC_BR24", - "ARM_RELOC_HALF", - "ARM_RELOC_HALF_SECTDIFF", - "ARM_RELOC_LOCAL_SECTDIFF", - "ARM_RELOC_PAIR", - "ARM_RELOC_PB_LA_PTR", - "ARM_RELOC_SECTDIFF", - "ARM_RELOC_VANILLA", - "ARM_THUMB_32BIT_BRANCH", - "ARM_THUMB_RELOC_BR22", - "Cpu", - "Cpu386", - "CpuAmd64", - "CpuArm", - "CpuArm64", - "CpuPpc", - "CpuPpc64", - "Dylib", - "DylibCmd", - "Dysymtab", - "DysymtabCmd", - "ErrNotFat", - "FatArch", - "FatArchHeader", - "FatFile", - "File", - "FileHeader", - "FlagAllModsBound", - "FlagAllowStackExecution", - "FlagAppExtensionSafe", - "FlagBindAtLoad", - "FlagBindsToWeak", - "FlagCanonical", - "FlagDeadStrippableDylib", - "FlagDyldLink", - "FlagForceFlat", - "FlagHasTLVDescriptors", - "FlagIncrLink", - "FlagLazyInit", - "FlagNoFixPrebinding", - "FlagNoHeapExecution", - "FlagNoMultiDefs", - "FlagNoReexportedDylibs", - "FlagNoUndefs", - "FlagPIE", - "FlagPrebindable", - "FlagPrebound", - "FlagRootSafe", - "FlagSetuidSafe", - "FlagSplitSegs", - "FlagSubsectionsViaSymbols", - "FlagTwoLevel", - "FlagWeakDefines", - "FormatError", - "GENERIC_RELOC_LOCAL_SECTDIFF", - "GENERIC_RELOC_PAIR", - "GENERIC_RELOC_PB_LA_PTR", - "GENERIC_RELOC_SECTDIFF", - "GENERIC_RELOC_TLV", - "GENERIC_RELOC_VANILLA", - "Load", - "LoadBytes", - "LoadCmd", - "LoadCmdDylib", - "LoadCmdDylinker", - "LoadCmdDysymtab", - "LoadCmdRpath", - "LoadCmdSegment", - "LoadCmdSegment64", - "LoadCmdSymtab", - "LoadCmdThread", - "LoadCmdUnixThread", - "Magic32", - "Magic64", - "MagicFat", - "NewFatFile", - "NewFile", - "Nlist32", - "Nlist64", - "Open", - "OpenFat", - "Regs386", - "RegsAMD64", - "Reloc", - "RelocTypeARM", - "RelocTypeARM64", - "RelocTypeGeneric", - "RelocTypeX86_64", - "Rpath", - "RpathCmd", - "Section", - "Section32", - "Section64", - "SectionHeader", - "Segment", - "Segment32", - "Segment64", - "SegmentHeader", - "Symbol", - "Symtab", - "SymtabCmd", - "Thread", - "Type", - "TypeBundle", - "TypeDylib", - "TypeExec", - "TypeObj", - "X86_64_RELOC_BRANCH", - "X86_64_RELOC_GOT", - "X86_64_RELOC_GOT_LOAD", - "X86_64_RELOC_SIGNED", - "X86_64_RELOC_SIGNED_1", - "X86_64_RELOC_SIGNED_2", - "X86_64_RELOC_SIGNED_4", - "X86_64_RELOC_SUBTRACTOR", - "X86_64_RELOC_TLV", - "X86_64_RELOC_UNSIGNED", - }, - "debug/pe": { - "COFFSymbol", - "COFFSymbolAuxFormat5", - "COFFSymbolSize", - "DataDirectory", - "File", - "FileHeader", - "FormatError", - "IMAGE_COMDAT_SELECT_ANY", - "IMAGE_COMDAT_SELECT_ASSOCIATIVE", - "IMAGE_COMDAT_SELECT_EXACT_MATCH", - "IMAGE_COMDAT_SELECT_LARGEST", - "IMAGE_COMDAT_SELECT_NODUPLICATES", - "IMAGE_COMDAT_SELECT_SAME_SIZE", - "IMAGE_DIRECTORY_ENTRY_ARCHITECTURE", - "IMAGE_DIRECTORY_ENTRY_BASERELOC", - "IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT", - "IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR", - "IMAGE_DIRECTORY_ENTRY_DEBUG", - "IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT", - "IMAGE_DIRECTORY_ENTRY_EXCEPTION", - "IMAGE_DIRECTORY_ENTRY_EXPORT", - "IMAGE_DIRECTORY_ENTRY_GLOBALPTR", - "IMAGE_DIRECTORY_ENTRY_IAT", - "IMAGE_DIRECTORY_ENTRY_IMPORT", - "IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG", - "IMAGE_DIRECTORY_ENTRY_RESOURCE", - "IMAGE_DIRECTORY_ENTRY_SECURITY", - "IMAGE_DIRECTORY_ENTRY_TLS", - "IMAGE_DLLCHARACTERISTICS_APPCONTAINER", - "IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE", - "IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY", - "IMAGE_DLLCHARACTERISTICS_GUARD_CF", - "IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA", - "IMAGE_DLLCHARACTERISTICS_NO_BIND", - "IMAGE_DLLCHARACTERISTICS_NO_ISOLATION", - "IMAGE_DLLCHARACTERISTICS_NO_SEH", - "IMAGE_DLLCHARACTERISTICS_NX_COMPAT", - "IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE", - "IMAGE_DLLCHARACTERISTICS_WDM_DRIVER", - "IMAGE_FILE_32BIT_MACHINE", - "IMAGE_FILE_AGGRESIVE_WS_TRIM", - "IMAGE_FILE_BYTES_REVERSED_HI", - "IMAGE_FILE_BYTES_REVERSED_LO", - "IMAGE_FILE_DEBUG_STRIPPED", - "IMAGE_FILE_DLL", - "IMAGE_FILE_EXECUTABLE_IMAGE", - "IMAGE_FILE_LARGE_ADDRESS_AWARE", - "IMAGE_FILE_LINE_NUMS_STRIPPED", - "IMAGE_FILE_LOCAL_SYMS_STRIPPED", - "IMAGE_FILE_MACHINE_AM33", - "IMAGE_FILE_MACHINE_AMD64", - "IMAGE_FILE_MACHINE_ARM", - "IMAGE_FILE_MACHINE_ARM64", - "IMAGE_FILE_MACHINE_ARMNT", - "IMAGE_FILE_MACHINE_EBC", - "IMAGE_FILE_MACHINE_I386", - "IMAGE_FILE_MACHINE_IA64", - "IMAGE_FILE_MACHINE_LOONGARCH32", - "IMAGE_FILE_MACHINE_LOONGARCH64", - "IMAGE_FILE_MACHINE_M32R", - "IMAGE_FILE_MACHINE_MIPS16", - "IMAGE_FILE_MACHINE_MIPSFPU", - "IMAGE_FILE_MACHINE_MIPSFPU16", - "IMAGE_FILE_MACHINE_POWERPC", - "IMAGE_FILE_MACHINE_POWERPCFP", - "IMAGE_FILE_MACHINE_R4000", - "IMAGE_FILE_MACHINE_RISCV128", - "IMAGE_FILE_MACHINE_RISCV32", - "IMAGE_FILE_MACHINE_RISCV64", - "IMAGE_FILE_MACHINE_SH3", - "IMAGE_FILE_MACHINE_SH3DSP", - "IMAGE_FILE_MACHINE_SH4", - "IMAGE_FILE_MACHINE_SH5", - "IMAGE_FILE_MACHINE_THUMB", - "IMAGE_FILE_MACHINE_UNKNOWN", - "IMAGE_FILE_MACHINE_WCEMIPSV2", - "IMAGE_FILE_NET_RUN_FROM_SWAP", - "IMAGE_FILE_RELOCS_STRIPPED", - "IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP", - "IMAGE_FILE_SYSTEM", - "IMAGE_FILE_UP_SYSTEM_ONLY", - "IMAGE_SCN_CNT_CODE", - "IMAGE_SCN_CNT_INITIALIZED_DATA", - "IMAGE_SCN_CNT_UNINITIALIZED_DATA", - "IMAGE_SCN_LNK_COMDAT", - "IMAGE_SCN_MEM_DISCARDABLE", - "IMAGE_SCN_MEM_EXECUTE", - "IMAGE_SCN_MEM_READ", - "IMAGE_SCN_MEM_WRITE", - "IMAGE_SUBSYSTEM_EFI_APPLICATION", - "IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER", - "IMAGE_SUBSYSTEM_EFI_ROM", - "IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER", - "IMAGE_SUBSYSTEM_NATIVE", - "IMAGE_SUBSYSTEM_NATIVE_WINDOWS", - "IMAGE_SUBSYSTEM_OS2_CUI", - "IMAGE_SUBSYSTEM_POSIX_CUI", - "IMAGE_SUBSYSTEM_UNKNOWN", - "IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION", - "IMAGE_SUBSYSTEM_WINDOWS_CE_GUI", - "IMAGE_SUBSYSTEM_WINDOWS_CUI", - "IMAGE_SUBSYSTEM_WINDOWS_GUI", - "IMAGE_SUBSYSTEM_XBOX", - "ImportDirectory", - "NewFile", - "Open", - "OptionalHeader32", - "OptionalHeader64", - "Reloc", - "Section", - "SectionHeader", - "SectionHeader32", - "StringTable", - "Symbol", - }, - "debug/plan9obj": { - "ErrNoSymbols", - "File", - "FileHeader", - "Magic386", - "Magic64", - "MagicAMD64", - "MagicARM", - "NewFile", - "Open", - "Section", - "SectionHeader", - "Sym", - }, - "embed": { - "FS", - }, - "encoding": { - "BinaryMarshaler", - "BinaryUnmarshaler", - "TextMarshaler", - "TextUnmarshaler", - }, - "encoding/ascii85": { - "CorruptInputError", - "Decode", - "Encode", - "MaxEncodedLen", - "NewDecoder", - "NewEncoder", - }, - "encoding/asn1": { - "BitString", - "ClassApplication", - "ClassContextSpecific", - "ClassPrivate", - "ClassUniversal", - "Enumerated", - "Flag", - "Marshal", - "MarshalWithParams", - "NullBytes", - "NullRawValue", - "ObjectIdentifier", - "RawContent", - "RawValue", - "StructuralError", - "SyntaxError", - "TagBMPString", - "TagBitString", - "TagBoolean", - "TagEnum", - "TagGeneralString", - "TagGeneralizedTime", - "TagIA5String", - "TagInteger", - "TagNull", - "TagNumericString", - "TagOID", - "TagOctetString", - "TagPrintableString", - "TagSequence", - "TagSet", - "TagT61String", - "TagUTCTime", - "TagUTF8String", - "Unmarshal", - "UnmarshalWithParams", - }, - "encoding/base32": { - "CorruptInputError", - "Encoding", - "HexEncoding", - "NewDecoder", - "NewEncoder", - "NewEncoding", - "NoPadding", - "StdEncoding", - "StdPadding", - }, - "encoding/base64": { - "CorruptInputError", - "Encoding", - "NewDecoder", - "NewEncoder", - "NewEncoding", - "NoPadding", - "RawStdEncoding", - "RawURLEncoding", - "StdEncoding", - "StdPadding", - "URLEncoding", - }, - "encoding/binary": { - "AppendByteOrder", - "AppendUvarint", - "AppendVarint", - "BigEndian", - "ByteOrder", - "LittleEndian", - "MaxVarintLen16", - "MaxVarintLen32", - "MaxVarintLen64", - "NativeEndian", - "PutUvarint", - "PutVarint", - "Read", - "ReadUvarint", - "ReadVarint", - "Size", - "Uvarint", - "Varint", - "Write", - }, - "encoding/csv": { - "ErrBareQuote", - "ErrFieldCount", - "ErrQuote", - "ErrTrailingComma", - "NewReader", - "NewWriter", - "ParseError", - "Reader", - "Writer", - }, - "encoding/gob": { - "CommonType", - "Decoder", - "Encoder", - "GobDecoder", - "GobEncoder", - "NewDecoder", - "NewEncoder", - "Register", - "RegisterName", - }, - "encoding/hex": { - "Decode", - "DecodeString", - "DecodedLen", - "Dump", - "Dumper", - "Encode", - "EncodeToString", - "EncodedLen", - "ErrLength", - "InvalidByteError", - "NewDecoder", - "NewEncoder", - }, - "encoding/json": { - "Compact", - "Decoder", - "Delim", - "Encoder", - "HTMLEscape", - "Indent", - "InvalidUTF8Error", - "InvalidUnmarshalError", - "Marshal", - "MarshalIndent", - "Marshaler", - "MarshalerError", - "NewDecoder", - "NewEncoder", - "Number", - "RawMessage", - "SyntaxError", - "Token", - "Unmarshal", - "UnmarshalFieldError", - "UnmarshalTypeError", - "Unmarshaler", - "UnsupportedTypeError", - "UnsupportedValueError", - "Valid", - }, - "encoding/pem": { - "Block", - "Decode", - "Encode", - "EncodeToMemory", - }, - "encoding/xml": { - "Attr", - "CharData", - "Comment", - "CopyToken", - "Decoder", - "Directive", - "Encoder", - "EndElement", - "Escape", - "EscapeText", - "HTMLAutoClose", - "HTMLEntity", - "Header", - "Marshal", - "MarshalIndent", - "Marshaler", - "MarshalerAttr", - "Name", - "NewDecoder", - "NewEncoder", - "NewTokenDecoder", - "ProcInst", - "StartElement", - "SyntaxError", - "TagPathError", - "Token", - "TokenReader", - "Unmarshal", - "UnmarshalError", - "Unmarshaler", - "UnmarshalerAttr", - "UnsupportedTypeError", - }, - "errors": { - "As", - "ErrUnsupported", - "Is", - "Join", - "New", - "Unwrap", - }, - "expvar": { - "Do", - "Float", - "Func", - "Get", - "Handler", - "Int", - "KeyValue", - "Map", - "NewFloat", - "NewInt", - "NewMap", - "NewString", - "Publish", - "String", - "Var", - }, - "flag": { - "Arg", - "Args", - "Bool", - "BoolFunc", - "BoolVar", - "CommandLine", - "ContinueOnError", - "Duration", - "DurationVar", - "ErrHelp", - "ErrorHandling", - "ExitOnError", - "Flag", - "FlagSet", - "Float64", - "Float64Var", - "Func", - "Getter", - "Int", - "Int64", - "Int64Var", - "IntVar", - "Lookup", - "NArg", - "NFlag", - "NewFlagSet", - "PanicOnError", - "Parse", - "Parsed", - "PrintDefaults", - "Set", - "String", - "StringVar", - "TextVar", - "Uint", - "Uint64", - "Uint64Var", - "UintVar", - "UnquoteUsage", - "Usage", - "Value", - "Var", - "Visit", - "VisitAll", - }, - "fmt": { - "Append", - "Appendf", - "Appendln", - "Errorf", - "FormatString", - "Formatter", - "Fprint", - "Fprintf", - "Fprintln", - "Fscan", - "Fscanf", - "Fscanln", - "GoStringer", - "Print", - "Printf", - "Println", - "Scan", - "ScanState", - "Scanf", - "Scanln", - "Scanner", - "Sprint", - "Sprintf", - "Sprintln", - "Sscan", - "Sscanf", - "Sscanln", - "State", - "Stringer", - }, - "go/ast": { - "ArrayType", - "AssignStmt", - "Bad", - "BadDecl", - "BadExpr", - "BadStmt", - "BasicLit", - "BinaryExpr", - "BlockStmt", - "BranchStmt", - "CallExpr", - "CaseClause", - "ChanDir", - "ChanType", - "CommClause", - "Comment", - "CommentGroup", - "CommentMap", - "CompositeLit", - "Con", - "Decl", - "DeclStmt", - "DeferStmt", - "Ellipsis", - "EmptyStmt", - "Expr", - "ExprStmt", - "Field", - "FieldFilter", - "FieldList", - "File", - "FileExports", - "Filter", - "FilterDecl", - "FilterFile", - "FilterFuncDuplicates", - "FilterImportDuplicates", - "FilterPackage", - "FilterUnassociatedComments", - "ForStmt", - "Fprint", - "Fun", - "FuncDecl", - "FuncLit", - "FuncType", - "GenDecl", - "GoStmt", - "Ident", - "IfStmt", - "ImportSpec", - "Importer", - "IncDecStmt", - "IndexExpr", - "IndexListExpr", - "Inspect", - "InterfaceType", - "IsExported", - "IsGenerated", - "KeyValueExpr", - "LabeledStmt", - "Lbl", - "MapType", - "MergeMode", - "MergePackageFiles", - "NewCommentMap", - "NewIdent", - "NewObj", - "NewPackage", - "NewScope", - "Node", - "NotNilFilter", - "ObjKind", - "Object", - "Package", - "PackageExports", - "ParenExpr", - "Pkg", - "Print", - "RECV", - "RangeStmt", - "ReturnStmt", - "SEND", - "Scope", - "SelectStmt", - "SelectorExpr", - "SendStmt", - "SliceExpr", - "SortImports", - "Spec", - "StarExpr", - "Stmt", - "StructType", - "SwitchStmt", - "Typ", - "TypeAssertExpr", - "TypeSpec", - "TypeSwitchStmt", - "UnaryExpr", - "ValueSpec", - "Var", - "Visitor", - "Walk", - }, - "go/build": { - "AllowBinary", - "ArchChar", - "Context", - "Default", - "Directive", - "FindOnly", - "IgnoreVendor", - "Import", - "ImportComment", - "ImportDir", - "ImportMode", - "IsLocalImport", - "MultiplePackageError", - "NoGoError", - "Package", - "ToolDir", - }, - "go/build/constraint": { - "AndExpr", - "Expr", - "GoVersion", - "IsGoBuild", - "IsPlusBuild", - "NotExpr", - "OrExpr", - "Parse", - "PlusBuildLines", - "SyntaxError", - "TagExpr", - }, - "go/constant": { - "BinaryOp", - "BitLen", - "Bool", - "BoolVal", - "Bytes", - "Compare", - "Complex", - "Denom", - "Float", - "Float32Val", - "Float64Val", - "Imag", - "Int", - "Int64Val", - "Kind", - "Make", - "MakeBool", - "MakeFloat64", - "MakeFromBytes", - "MakeFromLiteral", - "MakeImag", - "MakeInt64", - "MakeString", - "MakeUint64", - "MakeUnknown", - "Num", - "Real", - "Shift", - "Sign", - "String", - "StringVal", - "ToComplex", - "ToFloat", - "ToInt", - "Uint64Val", - "UnaryOp", - "Unknown", - "Val", - "Value", - }, - "go/doc": { - "AllDecls", - "AllMethods", - "Example", - "Examples", - "Filter", - "Func", - "IllegalPrefixes", - "IsPredeclared", - "Mode", - "New", - "NewFromFiles", - "Note", - "Package", - "PreserveAST", - "Synopsis", - "ToHTML", - "ToText", - "Type", - "Value", - }, - "go/doc/comment": { - "Block", - "Code", - "DefaultLookupPackage", - "Doc", - "DocLink", - "Heading", - "Italic", - "Link", - "LinkDef", - "List", - "ListItem", - "Paragraph", - "Parser", - "Plain", - "Printer", - "Text", - }, - "go/format": { - "Node", - "Source", - }, - "go/importer": { - "Default", - "For", - "ForCompiler", - "Lookup", - }, - "go/parser": { - "AllErrors", - "DeclarationErrors", - "ImportsOnly", - "Mode", - "PackageClauseOnly", - "ParseComments", - "ParseDir", - "ParseExpr", - "ParseExprFrom", - "ParseFile", - "SkipObjectResolution", - "SpuriousErrors", - "Trace", - }, - "go/printer": { - "CommentedNode", - "Config", - "Fprint", - "Mode", - "RawFormat", - "SourcePos", - "TabIndent", - "UseSpaces", - }, - "go/scanner": { - "Error", - "ErrorHandler", - "ErrorList", - "Mode", - "PrintError", - "ScanComments", - "Scanner", - }, - "go/token": { - "ADD", - "ADD_ASSIGN", - "AND", - "AND_ASSIGN", - "AND_NOT", - "AND_NOT_ASSIGN", - "ARROW", - "ASSIGN", - "BREAK", - "CASE", - "CHAN", - "CHAR", - "COLON", - "COMMA", - "COMMENT", - "CONST", - "CONTINUE", - "DEC", - "DEFAULT", - "DEFER", - "DEFINE", - "ELLIPSIS", - "ELSE", - "EOF", - "EQL", - "FALLTHROUGH", - "FLOAT", - "FOR", - "FUNC", - "File", - "FileSet", - "GEQ", - "GO", - "GOTO", - "GTR", - "HighestPrec", - "IDENT", - "IF", - "ILLEGAL", - "IMAG", - "IMPORT", - "INC", - "INT", - "INTERFACE", - "IsExported", - "IsIdentifier", - "IsKeyword", - "LAND", - "LBRACE", - "LBRACK", - "LEQ", - "LOR", - "LPAREN", - "LSS", - "Lookup", - "LowestPrec", - "MAP", - "MUL", - "MUL_ASSIGN", - "NEQ", - "NOT", - "NewFileSet", - "NoPos", - "OR", - "OR_ASSIGN", - "PACKAGE", - "PERIOD", - "Pos", - "Position", - "QUO", - "QUO_ASSIGN", - "RANGE", - "RBRACE", - "RBRACK", - "REM", - "REM_ASSIGN", - "RETURN", - "RPAREN", - "SELECT", - "SEMICOLON", - "SHL", - "SHL_ASSIGN", - "SHR", - "SHR_ASSIGN", - "STRING", - "STRUCT", - "SUB", - "SUB_ASSIGN", - "SWITCH", - "TILDE", - "TYPE", - "Token", - "UnaryPrec", - "VAR", - "XOR", - "XOR_ASSIGN", - }, - "go/types": { - "ArgumentError", - "Array", - "AssertableTo", - "AssignableTo", - "Basic", - "BasicInfo", - "BasicKind", - "Bool", - "Builtin", - "Byte", - "Chan", - "ChanDir", - "CheckExpr", - "Checker", - "Comparable", - "Complex128", - "Complex64", - "Config", - "Const", - "Context", - "ConvertibleTo", - "DefPredeclaredTestFuncs", - "Default", - "Error", - "Eval", - "ExprString", - "FieldVal", - "Float32", - "Float64", - "Func", - "Id", - "Identical", - "IdenticalIgnoreTags", - "Implements", - "ImportMode", - "Importer", - "ImporterFrom", - "Info", - "Initializer", - "Instance", - "Instantiate", - "Int", - "Int16", - "Int32", - "Int64", - "Int8", - "Interface", - "Invalid", - "IsBoolean", - "IsComplex", - "IsConstType", - "IsFloat", - "IsInteger", - "IsInterface", - "IsNumeric", - "IsOrdered", - "IsString", - "IsUnsigned", - "IsUntyped", - "Label", - "LookupFieldOrMethod", - "Map", - "MethodExpr", - "MethodSet", - "MethodVal", - "MissingMethod", - "Named", - "NewArray", - "NewChan", - "NewChecker", - "NewConst", - "NewContext", - "NewField", - "NewFunc", - "NewInterface", - "NewInterfaceType", - "NewLabel", - "NewMap", - "NewMethodSet", - "NewNamed", - "NewPackage", - "NewParam", - "NewPkgName", - "NewPointer", - "NewScope", - "NewSignature", - "NewSignatureType", - "NewSlice", - "NewStruct", - "NewTerm", - "NewTuple", - "NewTypeName", - "NewTypeParam", - "NewUnion", - "NewVar", - "Nil", - "Object", - "ObjectString", - "Package", - "PkgName", - "Pointer", - "Qualifier", - "RecvOnly", - "RelativeTo", - "Rune", - "Satisfies", - "Scope", - "Selection", - "SelectionKind", - "SelectionString", - "SendOnly", - "SendRecv", - "Signature", - "Sizes", - "SizesFor", - "Slice", - "StdSizes", - "String", - "Struct", - "Term", - "Tuple", - "Typ", - "Type", - "TypeAndValue", - "TypeList", - "TypeName", - "TypeParam", - "TypeParamList", - "TypeString", - "Uint", - "Uint16", - "Uint32", - "Uint64", - "Uint8", - "Uintptr", - "Union", - "Universe", - "Unsafe", - "UnsafePointer", - "UntypedBool", - "UntypedComplex", - "UntypedFloat", - "UntypedInt", - "UntypedNil", - "UntypedRune", - "UntypedString", - "Var", - "WriteExpr", - "WriteSignature", - "WriteType", - }, - "hash": { - "Hash", - "Hash32", - "Hash64", - }, - "hash/adler32": { - "Checksum", - "New", - "Size", - }, - "hash/crc32": { - "Castagnoli", - "Checksum", - "ChecksumIEEE", - "IEEE", - "IEEETable", - "Koopman", - "MakeTable", - "New", - "NewIEEE", - "Size", - "Table", - "Update", - }, - "hash/crc64": { - "Checksum", - "ECMA", - "ISO", - "MakeTable", - "New", - "Size", - "Table", - "Update", - }, - "hash/fnv": { - "New128", - "New128a", - "New32", - "New32a", - "New64", - "New64a", - }, - "hash/maphash": { - "Bytes", - "Hash", - "MakeSeed", - "Seed", - "String", - }, - "html": { - "EscapeString", - "UnescapeString", - }, - "html/template": { - "CSS", - "ErrAmbigContext", - "ErrBadHTML", - "ErrBranchEnd", - "ErrEndContext", - "ErrJSTemplate", - "ErrNoSuchTemplate", - "ErrOutputContext", - "ErrPartialCharset", - "ErrPartialEscape", - "ErrPredefinedEscaper", - "ErrRangeLoopReentry", - "ErrSlashAmbig", - "Error", - "ErrorCode", - "FuncMap", - "HTML", - "HTMLAttr", - "HTMLEscape", - "HTMLEscapeString", - "HTMLEscaper", - "IsTrue", - "JS", - "JSEscape", - "JSEscapeString", - "JSEscaper", - "JSStr", - "Must", - "New", - "OK", - "ParseFS", - "ParseFiles", - "ParseGlob", - "Srcset", - "Template", - "URL", - "URLQueryEscaper", - }, - "image": { - "Alpha", - "Alpha16", - "Black", - "CMYK", - "Config", - "Decode", - "DecodeConfig", - "ErrFormat", - "Gray", - "Gray16", - "Image", - "NRGBA", - "NRGBA64", - "NYCbCrA", - "NewAlpha", - "NewAlpha16", - "NewCMYK", - "NewGray", - "NewGray16", - "NewNRGBA", - "NewNRGBA64", - "NewNYCbCrA", - "NewPaletted", - "NewRGBA", - "NewRGBA64", - "NewUniform", - "NewYCbCr", - "Opaque", - "Paletted", - "PalettedImage", - "Point", - "Pt", - "RGBA", - "RGBA64", - "RGBA64Image", - "Rect", - "Rectangle", - "RegisterFormat", - "Transparent", - "Uniform", - "White", - "YCbCr", - "YCbCrSubsampleRatio", - "YCbCrSubsampleRatio410", - "YCbCrSubsampleRatio411", - "YCbCrSubsampleRatio420", - "YCbCrSubsampleRatio422", - "YCbCrSubsampleRatio440", - "YCbCrSubsampleRatio444", - "ZP", - "ZR", - }, - "image/color": { - "Alpha", - "Alpha16", - "Alpha16Model", - "AlphaModel", - "Black", - "CMYK", - "CMYKModel", - "CMYKToRGB", - "Color", - "Gray", - "Gray16", - "Gray16Model", - "GrayModel", - "Model", - "ModelFunc", - "NRGBA", - "NRGBA64", - "NRGBA64Model", - "NRGBAModel", - "NYCbCrA", - "NYCbCrAModel", - "Opaque", - "Palette", - "RGBA", - "RGBA64", - "RGBA64Model", - "RGBAModel", - "RGBToCMYK", - "RGBToYCbCr", - "Transparent", - "White", - "YCbCr", - "YCbCrModel", - "YCbCrToRGB", - }, - "image/color/palette": { - "Plan9", - "WebSafe", - }, - "image/draw": { - "Draw", - "DrawMask", - "Drawer", - "FloydSteinberg", - "Image", - "Op", - "Over", - "Quantizer", - "RGBA64Image", - "Src", - }, - "image/gif": { - "Decode", - "DecodeAll", - "DecodeConfig", - "DisposalBackground", - "DisposalNone", - "DisposalPrevious", - "Encode", - "EncodeAll", - "GIF", - "Options", - }, - "image/jpeg": { - "Decode", - "DecodeConfig", - "DefaultQuality", - "Encode", - "FormatError", - "Options", - "Reader", - "UnsupportedError", - }, - "image/png": { - "BestCompression", - "BestSpeed", - "CompressionLevel", - "Decode", - "DecodeConfig", - "DefaultCompression", - "Encode", - "Encoder", - "EncoderBuffer", - "EncoderBufferPool", - "FormatError", - "NoCompression", - "UnsupportedError", - }, - "index/suffixarray": { - "Index", - "New", - }, - "io": { - "ByteReader", - "ByteScanner", - "ByteWriter", - "Closer", - "Copy", - "CopyBuffer", - "CopyN", - "Discard", - "EOF", - "ErrClosedPipe", - "ErrNoProgress", - "ErrShortBuffer", - "ErrShortWrite", - "ErrUnexpectedEOF", - "LimitReader", - "LimitedReader", - "MultiReader", - "MultiWriter", - "NewOffsetWriter", - "NewSectionReader", - "NopCloser", - "OffsetWriter", - "Pipe", - "PipeReader", - "PipeWriter", - "ReadAll", - "ReadAtLeast", - "ReadCloser", - "ReadFull", - "ReadSeekCloser", - "ReadSeeker", - "ReadWriteCloser", - "ReadWriteSeeker", - "ReadWriter", - "Reader", - "ReaderAt", - "ReaderFrom", - "RuneReader", - "RuneScanner", - "SectionReader", - "SeekCurrent", - "SeekEnd", - "SeekStart", - "Seeker", - "StringWriter", - "TeeReader", - "WriteCloser", - "WriteSeeker", - "WriteString", - "Writer", - "WriterAt", - "WriterTo", - }, - "io/fs": { - "DirEntry", - "ErrClosed", - "ErrExist", - "ErrInvalid", - "ErrNotExist", - "ErrPermission", - "FS", - "File", - "FileInfo", - "FileInfoToDirEntry", - "FileMode", - "FormatDirEntry", - "FormatFileInfo", - "Glob", - "GlobFS", - "ModeAppend", - "ModeCharDevice", - "ModeDevice", - "ModeDir", - "ModeExclusive", - "ModeIrregular", - "ModeNamedPipe", - "ModePerm", - "ModeSetgid", - "ModeSetuid", - "ModeSocket", - "ModeSticky", - "ModeSymlink", - "ModeTemporary", - "ModeType", - "PathError", - "ReadDir", - "ReadDirFS", - "ReadDirFile", - "ReadFile", - "ReadFileFS", - "SkipAll", - "SkipDir", - "Stat", - "StatFS", - "Sub", - "SubFS", - "ValidPath", - "WalkDir", - "WalkDirFunc", - }, - "io/ioutil": { - "Discard", - "NopCloser", - "ReadAll", - "ReadDir", - "ReadFile", - "TempDir", - "TempFile", - "WriteFile", - }, - "log": { - "Default", - "Fatal", - "Fatalf", - "Fatalln", - "Flags", - "LUTC", - "Ldate", - "Llongfile", - "Lmicroseconds", - "Lmsgprefix", - "Logger", - "Lshortfile", - "LstdFlags", - "Ltime", - "New", - "Output", - "Panic", - "Panicf", - "Panicln", - "Prefix", - "Print", - "Printf", - "Println", - "SetFlags", - "SetOutput", - "SetPrefix", - "Writer", - }, - "log/slog": { - "Any", - "AnyValue", - "Attr", - "Bool", - "BoolValue", - "Debug", - "DebugContext", - "Default", - "Duration", - "DurationValue", - "Error", - "ErrorContext", - "Float64", - "Float64Value", - "Group", - "GroupValue", - "Handler", - "HandlerOptions", - "Info", - "InfoContext", - "Int", - "Int64", - "Int64Value", - "IntValue", - "JSONHandler", - "Kind", - "KindAny", - "KindBool", - "KindDuration", - "KindFloat64", - "KindGroup", - "KindInt64", - "KindLogValuer", - "KindString", - "KindTime", - "KindUint64", - "Level", - "LevelDebug", - "LevelError", - "LevelInfo", - "LevelKey", - "LevelVar", - "LevelWarn", - "Leveler", - "Log", - "LogAttrs", - "LogValuer", - "Logger", - "MessageKey", - "New", - "NewJSONHandler", - "NewLogLogger", - "NewRecord", - "NewTextHandler", - "Record", - "SetDefault", - "Source", - "SourceKey", - "String", - "StringValue", - "TextHandler", - "Time", - "TimeKey", - "TimeValue", - "Uint64", - "Uint64Value", - "Value", - "Warn", - "WarnContext", - "With", - }, - "log/syslog": { - "Dial", - "LOG_ALERT", - "LOG_AUTH", - "LOG_AUTHPRIV", - "LOG_CRIT", - "LOG_CRON", - "LOG_DAEMON", - "LOG_DEBUG", - "LOG_EMERG", - "LOG_ERR", - "LOG_FTP", - "LOG_INFO", - "LOG_KERN", - "LOG_LOCAL0", - "LOG_LOCAL1", - "LOG_LOCAL2", - "LOG_LOCAL3", - "LOG_LOCAL4", - "LOG_LOCAL5", - "LOG_LOCAL6", - "LOG_LOCAL7", - "LOG_LPR", - "LOG_MAIL", - "LOG_NEWS", - "LOG_NOTICE", - "LOG_SYSLOG", - "LOG_USER", - "LOG_UUCP", - "LOG_WARNING", - "New", - "NewLogger", - "Priority", - "Writer", - }, - "maps": { - "Clone", - "Copy", - "DeleteFunc", - "Equal", - "EqualFunc", - }, - "math": { - "Abs", - "Acos", - "Acosh", - "Asin", - "Asinh", - "Atan", - "Atan2", - "Atanh", - "Cbrt", - "Ceil", - "Copysign", - "Cos", - "Cosh", - "Dim", - "E", - "Erf", - "Erfc", - "Erfcinv", - "Erfinv", - "Exp", - "Exp2", - "Expm1", - "FMA", - "Float32bits", - "Float32frombits", - "Float64bits", - "Float64frombits", - "Floor", - "Frexp", - "Gamma", - "Hypot", - "Ilogb", - "Inf", - "IsInf", - "IsNaN", - "J0", - "J1", - "Jn", - "Ldexp", - "Lgamma", - "Ln10", - "Ln2", - "Log", - "Log10", - "Log10E", - "Log1p", - "Log2", - "Log2E", - "Logb", - "Max", - "MaxFloat32", - "MaxFloat64", - "MaxInt", - "MaxInt16", - "MaxInt32", - "MaxInt64", - "MaxInt8", - "MaxUint", - "MaxUint16", - "MaxUint32", - "MaxUint64", - "MaxUint8", - "Min", - "MinInt", - "MinInt16", - "MinInt32", - "MinInt64", - "MinInt8", - "Mod", - "Modf", - "NaN", - "Nextafter", - "Nextafter32", - "Phi", - "Pi", - "Pow", - "Pow10", - "Remainder", - "Round", - "RoundToEven", - "Signbit", - "Sin", - "Sincos", - "Sinh", - "SmallestNonzeroFloat32", - "SmallestNonzeroFloat64", - "Sqrt", - "Sqrt2", - "SqrtE", - "SqrtPhi", - "SqrtPi", - "Tan", - "Tanh", - "Trunc", - "Y0", - "Y1", - "Yn", - }, - "math/big": { - "Above", - "Accuracy", - "AwayFromZero", - "Below", - "ErrNaN", - "Exact", - "Float", - "Int", - "Jacobi", - "MaxBase", - "MaxExp", - "MaxPrec", - "MinExp", - "NewFloat", - "NewInt", - "NewRat", - "ParseFloat", - "Rat", - "RoundingMode", - "ToNearestAway", - "ToNearestEven", - "ToNegativeInf", - "ToPositiveInf", - "ToZero", - "Word", - }, - "math/bits": { - "Add", - "Add32", - "Add64", - "Div", - "Div32", - "Div64", - "LeadingZeros", - "LeadingZeros16", - "LeadingZeros32", - "LeadingZeros64", - "LeadingZeros8", - "Len", - "Len16", - "Len32", - "Len64", - "Len8", - "Mul", - "Mul32", - "Mul64", - "OnesCount", - "OnesCount16", - "OnesCount32", - "OnesCount64", - "OnesCount8", - "Rem", - "Rem32", - "Rem64", - "Reverse", - "Reverse16", - "Reverse32", - "Reverse64", - "Reverse8", - "ReverseBytes", - "ReverseBytes16", - "ReverseBytes32", - "ReverseBytes64", - "RotateLeft", - "RotateLeft16", - "RotateLeft32", - "RotateLeft64", - "RotateLeft8", - "Sub", - "Sub32", - "Sub64", - "TrailingZeros", - "TrailingZeros16", - "TrailingZeros32", - "TrailingZeros64", - "TrailingZeros8", - "UintSize", - }, - "math/cmplx": { - "Abs", - "Acos", - "Acosh", - "Asin", - "Asinh", - "Atan", - "Atanh", - "Conj", - "Cos", - "Cosh", - "Cot", - "Exp", - "Inf", - "IsInf", - "IsNaN", - "Log", - "Log10", - "NaN", - "Phase", - "Polar", - "Pow", - "Rect", - "Sin", - "Sinh", - "Sqrt", - "Tan", - "Tanh", - }, - "math/rand": { - "ExpFloat64", - "Float32", - "Float64", - "Int", - "Int31", - "Int31n", - "Int63", - "Int63n", - "Intn", - "New", - "NewSource", - "NewZipf", - "NormFloat64", - "Perm", - "Rand", - "Read", - "Seed", - "Shuffle", - "Source", - "Source64", - "Uint32", - "Uint64", - "Zipf", - }, - "mime": { - "AddExtensionType", - "BEncoding", - "ErrInvalidMediaParameter", - "ExtensionsByType", - "FormatMediaType", - "ParseMediaType", - "QEncoding", - "TypeByExtension", - "WordDecoder", - "WordEncoder", - }, - "mime/multipart": { - "ErrMessageTooLarge", - "File", - "FileHeader", - "Form", - "NewReader", - "NewWriter", - "Part", - "Reader", - "Writer", - }, - "mime/quotedprintable": { - "NewReader", - "NewWriter", - "Reader", - "Writer", - }, - "net": { - "Addr", - "AddrError", - "Buffers", - "CIDRMask", - "Conn", - "DNSConfigError", - "DNSError", - "DefaultResolver", - "Dial", - "DialIP", - "DialTCP", - "DialTimeout", - "DialUDP", - "DialUnix", - "Dialer", - "ErrClosed", - "ErrWriteToConnected", - "Error", - "FileConn", - "FileListener", - "FilePacketConn", - "FlagBroadcast", - "FlagLoopback", - "FlagMulticast", - "FlagPointToPoint", - "FlagRunning", - "FlagUp", - "Flags", - "HardwareAddr", - "IP", - "IPAddr", - "IPConn", - "IPMask", - "IPNet", - "IPv4", - "IPv4Mask", - "IPv4allrouter", - "IPv4allsys", - "IPv4bcast", - "IPv4len", - "IPv4zero", - "IPv6interfacelocalallnodes", - "IPv6len", - "IPv6linklocalallnodes", - "IPv6linklocalallrouters", - "IPv6loopback", - "IPv6unspecified", - "IPv6zero", - "Interface", - "InterfaceAddrs", - "InterfaceByIndex", - "InterfaceByName", - "Interfaces", - "InvalidAddrError", - "JoinHostPort", - "Listen", - "ListenConfig", - "ListenIP", - "ListenMulticastUDP", - "ListenPacket", - "ListenTCP", - "ListenUDP", - "ListenUnix", - "ListenUnixgram", - "Listener", - "LookupAddr", - "LookupCNAME", - "LookupHost", - "LookupIP", - "LookupMX", - "LookupNS", - "LookupPort", - "LookupSRV", - "LookupTXT", - "MX", - "NS", - "OpError", - "PacketConn", - "ParseCIDR", - "ParseError", - "ParseIP", - "ParseMAC", - "Pipe", - "ResolveIPAddr", - "ResolveTCPAddr", - "ResolveUDPAddr", - "ResolveUnixAddr", - "Resolver", - "SRV", - "SplitHostPort", - "TCPAddr", - "TCPAddrFromAddrPort", - "TCPConn", - "TCPListener", - "UDPAddr", - "UDPAddrFromAddrPort", - "UDPConn", - "UnixAddr", - "UnixConn", - "UnixListener", - "UnknownNetworkError", - }, - "net/http": { - "AllowQuerySemicolons", - "CanonicalHeaderKey", - "Client", - "CloseNotifier", - "ConnState", - "Cookie", - "CookieJar", - "DefaultClient", - "DefaultMaxHeaderBytes", - "DefaultMaxIdleConnsPerHost", - "DefaultServeMux", - "DefaultTransport", - "DetectContentType", - "Dir", - "ErrAbortHandler", - "ErrBodyNotAllowed", - "ErrBodyReadAfterClose", - "ErrContentLength", - "ErrHandlerTimeout", - "ErrHeaderTooLong", - "ErrHijacked", - "ErrLineTooLong", - "ErrMissingBoundary", - "ErrMissingContentLength", - "ErrMissingFile", - "ErrNoCookie", - "ErrNoLocation", - "ErrNotMultipart", - "ErrNotSupported", - "ErrSchemeMismatch", - "ErrServerClosed", - "ErrShortBody", - "ErrSkipAltProtocol", - "ErrUnexpectedTrailer", - "ErrUseLastResponse", - "ErrWriteAfterFlush", - "Error", - "FS", - "File", - "FileServer", - "FileSystem", - "Flusher", - "Get", - "Handle", - "HandleFunc", - "Handler", - "HandlerFunc", - "Head", - "Header", - "Hijacker", - "ListenAndServe", - "ListenAndServeTLS", - "LocalAddrContextKey", - "MaxBytesError", - "MaxBytesHandler", - "MaxBytesReader", - "MethodConnect", - "MethodDelete", - "MethodGet", - "MethodHead", - "MethodOptions", - "MethodPatch", - "MethodPost", - "MethodPut", - "MethodTrace", - "NewFileTransport", - "NewRequest", - "NewRequestWithContext", - "NewResponseController", - "NewServeMux", - "NoBody", - "NotFound", - "NotFoundHandler", - "ParseHTTPVersion", - "ParseTime", - "Post", - "PostForm", - "ProtocolError", - "ProxyFromEnvironment", - "ProxyURL", - "PushOptions", - "Pusher", - "ReadRequest", - "ReadResponse", - "Redirect", - "RedirectHandler", - "Request", - "Response", - "ResponseController", - "ResponseWriter", - "RoundTripper", - "SameSite", - "SameSiteDefaultMode", - "SameSiteLaxMode", - "SameSiteNoneMode", - "SameSiteStrictMode", - "Serve", - "ServeContent", - "ServeFile", - "ServeMux", - "ServeTLS", - "Server", - "ServerContextKey", - "SetCookie", - "StateActive", - "StateClosed", - "StateHijacked", - "StateIdle", - "StateNew", - "StatusAccepted", - "StatusAlreadyReported", - "StatusBadGateway", - "StatusBadRequest", - "StatusConflict", - "StatusContinue", - "StatusCreated", - "StatusEarlyHints", - "StatusExpectationFailed", - "StatusFailedDependency", - "StatusForbidden", - "StatusFound", - "StatusGatewayTimeout", - "StatusGone", - "StatusHTTPVersionNotSupported", - "StatusIMUsed", - "StatusInsufficientStorage", - "StatusInternalServerError", - "StatusLengthRequired", - "StatusLocked", - "StatusLoopDetected", - "StatusMethodNotAllowed", - "StatusMisdirectedRequest", - "StatusMovedPermanently", - "StatusMultiStatus", - "StatusMultipleChoices", - "StatusNetworkAuthenticationRequired", - "StatusNoContent", - "StatusNonAuthoritativeInfo", - "StatusNotAcceptable", - "StatusNotExtended", - "StatusNotFound", - "StatusNotImplemented", - "StatusNotModified", - "StatusOK", - "StatusPartialContent", - "StatusPaymentRequired", - "StatusPermanentRedirect", - "StatusPreconditionFailed", - "StatusPreconditionRequired", - "StatusProcessing", - "StatusProxyAuthRequired", - "StatusRequestEntityTooLarge", - "StatusRequestHeaderFieldsTooLarge", - "StatusRequestTimeout", - "StatusRequestURITooLong", - "StatusRequestedRangeNotSatisfiable", - "StatusResetContent", - "StatusSeeOther", - "StatusServiceUnavailable", - "StatusSwitchingProtocols", - "StatusTeapot", - "StatusTemporaryRedirect", - "StatusText", - "StatusTooEarly", - "StatusTooManyRequests", - "StatusUnauthorized", - "StatusUnavailableForLegalReasons", - "StatusUnprocessableEntity", - "StatusUnsupportedMediaType", - "StatusUpgradeRequired", - "StatusUseProxy", - "StatusVariantAlsoNegotiates", - "StripPrefix", - "TimeFormat", - "TimeoutHandler", - "TrailerPrefix", - "Transport", - }, - "net/http/cgi": { - "Handler", - "Request", - "RequestFromMap", - "Serve", - }, - "net/http/cookiejar": { - "Jar", - "New", - "Options", - "PublicSuffixList", - }, - "net/http/fcgi": { - "ErrConnClosed", - "ErrRequestAborted", - "ProcessEnv", - "Serve", - }, - "net/http/httptest": { - "DefaultRemoteAddr", - "NewRecorder", - "NewRequest", - "NewServer", - "NewTLSServer", - "NewUnstartedServer", - "ResponseRecorder", - "Server", - }, - "net/http/httptrace": { - "ClientTrace", - "ContextClientTrace", - "DNSDoneInfo", - "DNSStartInfo", - "GotConnInfo", - "WithClientTrace", - "WroteRequestInfo", - }, - "net/http/httputil": { - "BufferPool", - "ClientConn", - "DumpRequest", - "DumpRequestOut", - "DumpResponse", - "ErrClosed", - "ErrLineTooLong", - "ErrPersistEOF", - "ErrPipeline", - "NewChunkedReader", - "NewChunkedWriter", - "NewClientConn", - "NewProxyClientConn", - "NewServerConn", - "NewSingleHostReverseProxy", - "ProxyRequest", - "ReverseProxy", - "ServerConn", - }, - "net/http/pprof": { - "Cmdline", - "Handler", - "Index", - "Profile", - "Symbol", - "Trace", - }, - "net/mail": { - "Address", - "AddressParser", - "ErrHeaderNotPresent", - "Header", - "Message", - "ParseAddress", - "ParseAddressList", - "ParseDate", - "ReadMessage", - }, - "net/netip": { - "Addr", - "AddrFrom16", - "AddrFrom4", - "AddrFromSlice", - "AddrPort", - "AddrPortFrom", - "IPv4Unspecified", - "IPv6LinkLocalAllNodes", - "IPv6LinkLocalAllRouters", - "IPv6Loopback", - "IPv6Unspecified", - "MustParseAddr", - "MustParseAddrPort", - "MustParsePrefix", - "ParseAddr", - "ParseAddrPort", - "ParsePrefix", - "Prefix", - "PrefixFrom", - }, - "net/rpc": { - "Accept", - "Call", - "Client", - "ClientCodec", - "DefaultDebugPath", - "DefaultRPCPath", - "DefaultServer", - "Dial", - "DialHTTP", - "DialHTTPPath", - "ErrShutdown", - "HandleHTTP", - "NewClient", - "NewClientWithCodec", - "NewServer", - "Register", - "RegisterName", - "Request", - "Response", - "ServeCodec", - "ServeConn", - "ServeRequest", - "Server", - "ServerCodec", - "ServerError", - }, - "net/rpc/jsonrpc": { - "Dial", - "NewClient", - "NewClientCodec", - "NewServerCodec", - "ServeConn", - }, - "net/smtp": { - "Auth", - "CRAMMD5Auth", - "Client", - "Dial", - "NewClient", - "PlainAuth", - "SendMail", - "ServerInfo", - }, - "net/textproto": { - "CanonicalMIMEHeaderKey", - "Conn", - "Dial", - "Error", - "MIMEHeader", - "NewConn", - "NewReader", - "NewWriter", - "Pipeline", - "ProtocolError", - "Reader", - "TrimBytes", - "TrimString", - "Writer", - }, - "net/url": { - "Error", - "EscapeError", - "InvalidHostError", - "JoinPath", - "Parse", - "ParseQuery", - "ParseRequestURI", - "PathEscape", - "PathUnescape", - "QueryEscape", - "QueryUnescape", - "URL", - "User", - "UserPassword", - "Userinfo", - "Values", - }, - "os": { - "Args", - "Chdir", - "Chmod", - "Chown", - "Chtimes", - "Clearenv", - "Create", - "CreateTemp", - "DevNull", - "DirEntry", - "DirFS", - "Environ", - "ErrClosed", - "ErrDeadlineExceeded", - "ErrExist", - "ErrInvalid", - "ErrNoDeadline", - "ErrNotExist", - "ErrPermission", - "ErrProcessDone", - "Executable", - "Exit", - "Expand", - "ExpandEnv", - "File", - "FileInfo", - "FileMode", - "FindProcess", - "Getegid", - "Getenv", - "Geteuid", - "Getgid", - "Getgroups", - "Getpagesize", - "Getpid", - "Getppid", - "Getuid", - "Getwd", - "Hostname", - "Interrupt", - "IsExist", - "IsNotExist", - "IsPathSeparator", - "IsPermission", - "IsTimeout", - "Kill", - "Lchown", - "Link", - "LinkError", - "LookupEnv", - "Lstat", - "Mkdir", - "MkdirAll", - "MkdirTemp", - "ModeAppend", - "ModeCharDevice", - "ModeDevice", - "ModeDir", - "ModeExclusive", - "ModeIrregular", - "ModeNamedPipe", - "ModePerm", - "ModeSetgid", - "ModeSetuid", - "ModeSocket", - "ModeSticky", - "ModeSymlink", - "ModeTemporary", - "ModeType", - "NewFile", - "NewSyscallError", - "O_APPEND", - "O_CREATE", - "O_EXCL", - "O_RDONLY", - "O_RDWR", - "O_SYNC", - "O_TRUNC", - "O_WRONLY", - "Open", - "OpenFile", - "PathError", - "PathListSeparator", - "PathSeparator", - "Pipe", - "ProcAttr", - "Process", - "ProcessState", - "ReadDir", - "ReadFile", - "Readlink", - "Remove", - "RemoveAll", - "Rename", - "SEEK_CUR", - "SEEK_END", - "SEEK_SET", - "SameFile", - "Setenv", - "Signal", - "StartProcess", - "Stat", - "Stderr", - "Stdin", - "Stdout", - "Symlink", - "SyscallError", - "TempDir", - "Truncate", - "Unsetenv", - "UserCacheDir", - "UserConfigDir", - "UserHomeDir", - "WriteFile", - }, - "os/exec": { - "Cmd", - "Command", - "CommandContext", - "ErrDot", - "ErrNotFound", - "ErrWaitDelay", - "Error", - "ExitError", - "LookPath", - }, - "os/signal": { - "Ignore", - "Ignored", - "Notify", - "NotifyContext", - "Reset", - "Stop", - }, - "os/user": { - "Current", - "Group", - "Lookup", - "LookupGroup", - "LookupGroupId", - "LookupId", - "UnknownGroupError", - "UnknownGroupIdError", - "UnknownUserError", - "UnknownUserIdError", - "User", - }, - "path": { - "Base", - "Clean", - "Dir", - "ErrBadPattern", - "Ext", - "IsAbs", - "Join", - "Match", - "Split", - }, - "path/filepath": { - "Abs", - "Base", - "Clean", - "Dir", - "ErrBadPattern", - "EvalSymlinks", - "Ext", - "FromSlash", - "Glob", - "HasPrefix", - "IsAbs", - "IsLocal", - "Join", - "ListSeparator", - "Match", - "Rel", - "Separator", - "SkipAll", - "SkipDir", - "Split", - "SplitList", - "ToSlash", - "VolumeName", - "Walk", - "WalkDir", - "WalkFunc", - }, - "plugin": { - "Open", - "Plugin", - "Symbol", - }, - "reflect": { - "Append", - "AppendSlice", - "Array", - "ArrayOf", - "Bool", - "BothDir", - "Chan", - "ChanDir", - "ChanOf", - "Complex128", - "Complex64", - "Copy", - "DeepEqual", - "Float32", - "Float64", - "Func", - "FuncOf", - "Indirect", - "Int", - "Int16", - "Int32", - "Int64", - "Int8", - "Interface", - "Invalid", - "Kind", - "MakeChan", - "MakeFunc", - "MakeMap", - "MakeMapWithSize", - "MakeSlice", - "Map", - "MapIter", - "MapOf", - "Method", - "New", - "NewAt", - "Pointer", - "PointerTo", - "Ptr", - "PtrTo", - "RecvDir", - "Select", - "SelectCase", - "SelectDefault", - "SelectDir", - "SelectRecv", - "SelectSend", - "SendDir", - "Slice", - "SliceHeader", - "SliceOf", - "String", - "StringHeader", - "Struct", - "StructField", - "StructOf", - "StructTag", - "Swapper", - "Type", - "TypeOf", - "Uint", - "Uint16", - "Uint32", - "Uint64", - "Uint8", - "Uintptr", - "UnsafePointer", - "Value", - "ValueError", - "ValueOf", - "VisibleFields", - "Zero", - }, - "regexp": { - "Compile", - "CompilePOSIX", - "Match", - "MatchReader", - "MatchString", - "MustCompile", - "MustCompilePOSIX", - "QuoteMeta", - "Regexp", - }, - "regexp/syntax": { - "ClassNL", - "Compile", - "DotNL", - "EmptyBeginLine", - "EmptyBeginText", - "EmptyEndLine", - "EmptyEndText", - "EmptyNoWordBoundary", - "EmptyOp", - "EmptyOpContext", - "EmptyWordBoundary", - "ErrInternalError", - "ErrInvalidCharClass", - "ErrInvalidCharRange", - "ErrInvalidEscape", - "ErrInvalidNamedCapture", - "ErrInvalidPerlOp", - "ErrInvalidRepeatOp", - "ErrInvalidRepeatSize", - "ErrInvalidUTF8", - "ErrLarge", - "ErrMissingBracket", - "ErrMissingParen", - "ErrMissingRepeatArgument", - "ErrNestingDepth", - "ErrTrailingBackslash", - "ErrUnexpectedParen", - "Error", - "ErrorCode", - "Flags", - "FoldCase", - "Inst", - "InstAlt", - "InstAltMatch", - "InstCapture", - "InstEmptyWidth", - "InstFail", - "InstMatch", - "InstNop", - "InstOp", - "InstRune", - "InstRune1", - "InstRuneAny", - "InstRuneAnyNotNL", - "IsWordChar", - "Literal", - "MatchNL", - "NonGreedy", - "OneLine", - "Op", - "OpAlternate", - "OpAnyChar", - "OpAnyCharNotNL", - "OpBeginLine", - "OpBeginText", - "OpCapture", - "OpCharClass", - "OpConcat", - "OpEmptyMatch", - "OpEndLine", - "OpEndText", - "OpLiteral", - "OpNoMatch", - "OpNoWordBoundary", - "OpPlus", - "OpQuest", - "OpRepeat", - "OpStar", - "OpWordBoundary", - "POSIX", - "Parse", - "Perl", - "PerlX", - "Prog", - "Regexp", - "Simple", - "UnicodeGroups", - "WasDollar", - }, - "runtime": { - "BlockProfile", - "BlockProfileRecord", - "Breakpoint", - "CPUProfile", - "Caller", - "Callers", - "CallersFrames", - "Compiler", - "Error", - "Frame", - "Frames", - "Func", - "FuncForPC", - "GC", - "GOARCH", - "GOMAXPROCS", - "GOOS", - "GOROOT", - "Goexit", - "GoroutineProfile", - "Gosched", - "KeepAlive", - "LockOSThread", - "MemProfile", - "MemProfileRate", - "MemProfileRecord", - "MemStats", - "MutexProfile", - "NumCPU", - "NumCgoCall", - "NumGoroutine", - "PanicNilError", - "Pinner", - "ReadMemStats", - "ReadTrace", - "SetBlockProfileRate", - "SetCPUProfileRate", - "SetCgoTraceback", - "SetFinalizer", - "SetMutexProfileFraction", - "Stack", - "StackRecord", - "StartTrace", - "StopTrace", - "ThreadCreateProfile", - "TypeAssertionError", - "UnlockOSThread", - "Version", - }, - "runtime/cgo": { - "Handle", - "Incomplete", - "NewHandle", - }, - "runtime/coverage": { - "ClearCounters", - "WriteCounters", - "WriteCountersDir", - "WriteMeta", - "WriteMetaDir", - }, - "runtime/debug": { - "BuildInfo", - "BuildSetting", - "FreeOSMemory", - "GCStats", - "Module", - "ParseBuildInfo", - "PrintStack", - "ReadBuildInfo", - "ReadGCStats", - "SetGCPercent", - "SetMaxStack", - "SetMaxThreads", - "SetMemoryLimit", - "SetPanicOnFault", - "SetTraceback", - "Stack", - "WriteHeapDump", - }, - "runtime/metrics": { - "All", - "Description", - "Float64Histogram", - "KindBad", - "KindFloat64", - "KindFloat64Histogram", - "KindUint64", - "Read", - "Sample", - "Value", - "ValueKind", - }, - "runtime/pprof": { - "Do", - "ForLabels", - "Label", - "LabelSet", - "Labels", - "Lookup", - "NewProfile", - "Profile", - "Profiles", - "SetGoroutineLabels", - "StartCPUProfile", - "StopCPUProfile", - "WithLabels", - "WriteHeapProfile", - }, - "runtime/trace": { - "IsEnabled", - "Log", - "Logf", - "NewTask", - "Region", - "Start", - "StartRegion", - "Stop", - "Task", - "WithRegion", - }, - "slices": { - "BinarySearch", - "BinarySearchFunc", - "Clip", - "Clone", - "Compact", - "CompactFunc", - "Compare", - "CompareFunc", - "Contains", - "ContainsFunc", - "Delete", - "DeleteFunc", - "Equal", - "EqualFunc", - "Grow", - "Index", - "IndexFunc", - "Insert", - "IsSorted", - "IsSortedFunc", - "Max", - "MaxFunc", - "Min", - "MinFunc", - "Replace", - "Reverse", - "Sort", - "SortFunc", - "SortStableFunc", - }, - "sort": { - "Find", - "Float64Slice", - "Float64s", - "Float64sAreSorted", - "IntSlice", - "Interface", - "Ints", - "IntsAreSorted", - "IsSorted", - "Reverse", - "Search", - "SearchFloat64s", - "SearchInts", - "SearchStrings", - "Slice", - "SliceIsSorted", - "SliceStable", - "Sort", - "Stable", - "StringSlice", - "Strings", - "StringsAreSorted", - }, - "strconv": { - "AppendBool", - "AppendFloat", - "AppendInt", - "AppendQuote", - "AppendQuoteRune", - "AppendQuoteRuneToASCII", - "AppendQuoteRuneToGraphic", - "AppendQuoteToASCII", - "AppendQuoteToGraphic", - "AppendUint", - "Atoi", - "CanBackquote", - "ErrRange", - "ErrSyntax", - "FormatBool", - "FormatComplex", - "FormatFloat", - "FormatInt", - "FormatUint", - "IntSize", - "IsGraphic", - "IsPrint", - "Itoa", - "NumError", - "ParseBool", - "ParseComplex", - "ParseFloat", - "ParseInt", - "ParseUint", - "Quote", - "QuoteRune", - "QuoteRuneToASCII", - "QuoteRuneToGraphic", - "QuoteToASCII", - "QuoteToGraphic", - "QuotedPrefix", - "Unquote", - "UnquoteChar", - }, - "strings": { - "Builder", - "Clone", - "Compare", - "Contains", - "ContainsAny", - "ContainsFunc", - "ContainsRune", - "Count", - "Cut", - "CutPrefix", - "CutSuffix", - "EqualFold", - "Fields", - "FieldsFunc", - "HasPrefix", - "HasSuffix", - "Index", - "IndexAny", - "IndexByte", - "IndexFunc", - "IndexRune", - "Join", - "LastIndex", - "LastIndexAny", - "LastIndexByte", - "LastIndexFunc", - "Map", - "NewReader", - "NewReplacer", - "Reader", - "Repeat", - "Replace", - "ReplaceAll", - "Replacer", - "Split", - "SplitAfter", - "SplitAfterN", - "SplitN", - "Title", - "ToLower", - "ToLowerSpecial", - "ToTitle", - "ToTitleSpecial", - "ToUpper", - "ToUpperSpecial", - "ToValidUTF8", - "Trim", - "TrimFunc", - "TrimLeft", - "TrimLeftFunc", - "TrimPrefix", - "TrimRight", - "TrimRightFunc", - "TrimSpace", - "TrimSuffix", - }, - "sync": { - "Cond", - "Locker", - "Map", - "Mutex", - "NewCond", - "Once", - "OnceFunc", - "OnceValue", - "OnceValues", - "Pool", - "RWMutex", - "WaitGroup", - }, - "sync/atomic": { - "AddInt32", - "AddInt64", - "AddUint32", - "AddUint64", - "AddUintptr", - "Bool", - "CompareAndSwapInt32", - "CompareAndSwapInt64", - "CompareAndSwapPointer", - "CompareAndSwapUint32", - "CompareAndSwapUint64", - "CompareAndSwapUintptr", - "Int32", - "Int64", - "LoadInt32", - "LoadInt64", - "LoadPointer", - "LoadUint32", - "LoadUint64", - "LoadUintptr", - "Pointer", - "StoreInt32", - "StoreInt64", - "StorePointer", - "StoreUint32", - "StoreUint64", - "StoreUintptr", - "SwapInt32", - "SwapInt64", - "SwapPointer", - "SwapUint32", - "SwapUint64", - "SwapUintptr", - "Uint32", - "Uint64", - "Uintptr", - "Value", - }, - "syscall": { - "AF_ALG", - "AF_APPLETALK", - "AF_ARP", - "AF_ASH", - "AF_ATM", - "AF_ATMPVC", - "AF_ATMSVC", - "AF_AX25", - "AF_BLUETOOTH", - "AF_BRIDGE", - "AF_CAIF", - "AF_CAN", - "AF_CCITT", - "AF_CHAOS", - "AF_CNT", - "AF_COIP", - "AF_DATAKIT", - "AF_DECnet", - "AF_DLI", - "AF_E164", - "AF_ECMA", - "AF_ECONET", - "AF_ENCAP", - "AF_FILE", - "AF_HYLINK", - "AF_IEEE80211", - "AF_IEEE802154", - "AF_IMPLINK", - "AF_INET", - "AF_INET6", - "AF_INET6_SDP", - "AF_INET_SDP", - "AF_IPX", - "AF_IRDA", - "AF_ISDN", - "AF_ISO", - "AF_IUCV", - "AF_KEY", - "AF_LAT", - "AF_LINK", - "AF_LLC", - "AF_LOCAL", - "AF_MAX", - "AF_MPLS", - "AF_NATM", - "AF_NDRV", - "AF_NETBEUI", - "AF_NETBIOS", - "AF_NETGRAPH", - "AF_NETLINK", - "AF_NETROM", - "AF_NS", - "AF_OROUTE", - "AF_OSI", - "AF_PACKET", - "AF_PHONET", - "AF_PPP", - "AF_PPPOX", - "AF_PUP", - "AF_RDS", - "AF_RESERVED_36", - "AF_ROSE", - "AF_ROUTE", - "AF_RXRPC", - "AF_SCLUSTER", - "AF_SECURITY", - "AF_SIP", - "AF_SLOW", - "AF_SNA", - "AF_SYSTEM", - "AF_TIPC", - "AF_UNIX", - "AF_UNSPEC", - "AF_UTUN", - "AF_VENDOR00", - "AF_VENDOR01", - "AF_VENDOR02", - "AF_VENDOR03", - "AF_VENDOR04", - "AF_VENDOR05", - "AF_VENDOR06", - "AF_VENDOR07", - "AF_VENDOR08", - "AF_VENDOR09", - "AF_VENDOR10", - "AF_VENDOR11", - "AF_VENDOR12", - "AF_VENDOR13", - "AF_VENDOR14", - "AF_VENDOR15", - "AF_VENDOR16", - "AF_VENDOR17", - "AF_VENDOR18", - "AF_VENDOR19", - "AF_VENDOR20", - "AF_VENDOR21", - "AF_VENDOR22", - "AF_VENDOR23", - "AF_VENDOR24", - "AF_VENDOR25", - "AF_VENDOR26", - "AF_VENDOR27", - "AF_VENDOR28", - "AF_VENDOR29", - "AF_VENDOR30", - "AF_VENDOR31", - "AF_VENDOR32", - "AF_VENDOR33", - "AF_VENDOR34", - "AF_VENDOR35", - "AF_VENDOR36", - "AF_VENDOR37", - "AF_VENDOR38", - "AF_VENDOR39", - "AF_VENDOR40", - "AF_VENDOR41", - "AF_VENDOR42", - "AF_VENDOR43", - "AF_VENDOR44", - "AF_VENDOR45", - "AF_VENDOR46", - "AF_VENDOR47", - "AF_WANPIPE", - "AF_X25", - "AI_CANONNAME", - "AI_NUMERICHOST", - "AI_PASSIVE", - "APPLICATION_ERROR", - "ARPHRD_ADAPT", - "ARPHRD_APPLETLK", - "ARPHRD_ARCNET", - "ARPHRD_ASH", - "ARPHRD_ATM", - "ARPHRD_AX25", - "ARPHRD_BIF", - "ARPHRD_CHAOS", - "ARPHRD_CISCO", - "ARPHRD_CSLIP", - "ARPHRD_CSLIP6", - "ARPHRD_DDCMP", - "ARPHRD_DLCI", - "ARPHRD_ECONET", - "ARPHRD_EETHER", - "ARPHRD_ETHER", - "ARPHRD_EUI64", - "ARPHRD_FCAL", - "ARPHRD_FCFABRIC", - "ARPHRD_FCPL", - "ARPHRD_FCPP", - "ARPHRD_FDDI", - "ARPHRD_FRAD", - "ARPHRD_FRELAY", - "ARPHRD_HDLC", - "ARPHRD_HIPPI", - "ARPHRD_HWX25", - "ARPHRD_IEEE1394", - "ARPHRD_IEEE802", - "ARPHRD_IEEE80211", - "ARPHRD_IEEE80211_PRISM", - "ARPHRD_IEEE80211_RADIOTAP", - "ARPHRD_IEEE802154", - "ARPHRD_IEEE802154_PHY", - "ARPHRD_IEEE802_TR", - "ARPHRD_INFINIBAND", - "ARPHRD_IPDDP", - "ARPHRD_IPGRE", - "ARPHRD_IRDA", - "ARPHRD_LAPB", - "ARPHRD_LOCALTLK", - "ARPHRD_LOOPBACK", - "ARPHRD_METRICOM", - "ARPHRD_NETROM", - "ARPHRD_NONE", - "ARPHRD_PIMREG", - "ARPHRD_PPP", - "ARPHRD_PRONET", - "ARPHRD_RAWHDLC", - "ARPHRD_ROSE", - "ARPHRD_RSRVD", - "ARPHRD_SIT", - "ARPHRD_SKIP", - "ARPHRD_SLIP", - "ARPHRD_SLIP6", - "ARPHRD_STRIP", - "ARPHRD_TUNNEL", - "ARPHRD_TUNNEL6", - "ARPHRD_VOID", - "ARPHRD_X25", - "AUTHTYPE_CLIENT", - "AUTHTYPE_SERVER", - "Accept", - "Accept4", - "AcceptEx", - "Access", - "Acct", - "AddrinfoW", - "Adjtime", - "Adjtimex", - "AllThreadsSyscall", - "AllThreadsSyscall6", - "AttachLsf", - "B0", - "B1000000", - "B110", - "B115200", - "B1152000", - "B1200", - "B134", - "B14400", - "B150", - "B1500000", - "B1800", - "B19200", - "B200", - "B2000000", - "B230400", - "B2400", - "B2500000", - "B28800", - "B300", - "B3000000", - "B3500000", - "B38400", - "B4000000", - "B460800", - "B4800", - "B50", - "B500000", - "B57600", - "B576000", - "B600", - "B7200", - "B75", - "B76800", - "B921600", - "B9600", - "BASE_PROTOCOL", - "BIOCFEEDBACK", - "BIOCFLUSH", - "BIOCGBLEN", - "BIOCGDIRECTION", - "BIOCGDIRFILT", - "BIOCGDLT", - "BIOCGDLTLIST", - "BIOCGETBUFMODE", - "BIOCGETIF", - "BIOCGETZMAX", - "BIOCGFEEDBACK", - "BIOCGFILDROP", - "BIOCGHDRCMPLT", - "BIOCGRSIG", - "BIOCGRTIMEOUT", - "BIOCGSEESENT", - "BIOCGSTATS", - "BIOCGSTATSOLD", - "BIOCGTSTAMP", - "BIOCIMMEDIATE", - "BIOCLOCK", - "BIOCPROMISC", - "BIOCROTZBUF", - "BIOCSBLEN", - "BIOCSDIRECTION", - "BIOCSDIRFILT", - "BIOCSDLT", - "BIOCSETBUFMODE", - "BIOCSETF", - "BIOCSETFNR", - "BIOCSETIF", - "BIOCSETWF", - "BIOCSETZBUF", - "BIOCSFEEDBACK", - "BIOCSFILDROP", - "BIOCSHDRCMPLT", - "BIOCSRSIG", - "BIOCSRTIMEOUT", - "BIOCSSEESENT", - "BIOCSTCPF", - "BIOCSTSTAMP", - "BIOCSUDPF", - "BIOCVERSION", - "BPF_A", - "BPF_ABS", - "BPF_ADD", - "BPF_ALIGNMENT", - "BPF_ALIGNMENT32", - "BPF_ALU", - "BPF_AND", - "BPF_B", - "BPF_BUFMODE_BUFFER", - "BPF_BUFMODE_ZBUF", - "BPF_DFLTBUFSIZE", - "BPF_DIRECTION_IN", - "BPF_DIRECTION_OUT", - "BPF_DIV", - "BPF_H", - "BPF_IMM", - "BPF_IND", - "BPF_JA", - "BPF_JEQ", - "BPF_JGE", - "BPF_JGT", - "BPF_JMP", - "BPF_JSET", - "BPF_K", - "BPF_LD", - "BPF_LDX", - "BPF_LEN", - "BPF_LSH", - "BPF_MAJOR_VERSION", - "BPF_MAXBUFSIZE", - "BPF_MAXINSNS", - "BPF_MEM", - "BPF_MEMWORDS", - "BPF_MINBUFSIZE", - "BPF_MINOR_VERSION", - "BPF_MISC", - "BPF_MSH", - "BPF_MUL", - "BPF_NEG", - "BPF_OR", - "BPF_RELEASE", - "BPF_RET", - "BPF_RSH", - "BPF_ST", - "BPF_STX", - "BPF_SUB", - "BPF_TAX", - "BPF_TXA", - "BPF_T_BINTIME", - "BPF_T_BINTIME_FAST", - "BPF_T_BINTIME_MONOTONIC", - "BPF_T_BINTIME_MONOTONIC_FAST", - "BPF_T_FAST", - "BPF_T_FLAG_MASK", - "BPF_T_FORMAT_MASK", - "BPF_T_MICROTIME", - "BPF_T_MICROTIME_FAST", - "BPF_T_MICROTIME_MONOTONIC", - "BPF_T_MICROTIME_MONOTONIC_FAST", - "BPF_T_MONOTONIC", - "BPF_T_MONOTONIC_FAST", - "BPF_T_NANOTIME", - "BPF_T_NANOTIME_FAST", - "BPF_T_NANOTIME_MONOTONIC", - "BPF_T_NANOTIME_MONOTONIC_FAST", - "BPF_T_NONE", - "BPF_T_NORMAL", - "BPF_W", - "BPF_X", - "BRKINT", - "Bind", - "BindToDevice", - "BpfBuflen", - "BpfDatalink", - "BpfHdr", - "BpfHeadercmpl", - "BpfInsn", - "BpfInterface", - "BpfJump", - "BpfProgram", - "BpfStat", - "BpfStats", - "BpfStmt", - "BpfTimeout", - "BpfTimeval", - "BpfVersion", - "BpfZbuf", - "BpfZbufHeader", - "ByHandleFileInformation", - "BytePtrFromString", - "ByteSliceFromString", - "CCR0_FLUSH", - "CERT_CHAIN_POLICY_AUTHENTICODE", - "CERT_CHAIN_POLICY_AUTHENTICODE_TS", - "CERT_CHAIN_POLICY_BASE", - "CERT_CHAIN_POLICY_BASIC_CONSTRAINTS", - "CERT_CHAIN_POLICY_EV", - "CERT_CHAIN_POLICY_MICROSOFT_ROOT", - "CERT_CHAIN_POLICY_NT_AUTH", - "CERT_CHAIN_POLICY_SSL", - "CERT_E_CN_NO_MATCH", - "CERT_E_EXPIRED", - "CERT_E_PURPOSE", - "CERT_E_ROLE", - "CERT_E_UNTRUSTEDROOT", - "CERT_STORE_ADD_ALWAYS", - "CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG", - "CERT_STORE_PROV_MEMORY", - "CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT", - "CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT", - "CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT", - "CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT", - "CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT", - "CERT_TRUST_INVALID_BASIC_CONSTRAINTS", - "CERT_TRUST_INVALID_EXTENSION", - "CERT_TRUST_INVALID_NAME_CONSTRAINTS", - "CERT_TRUST_INVALID_POLICY_CONSTRAINTS", - "CERT_TRUST_IS_CYCLIC", - "CERT_TRUST_IS_EXPLICIT_DISTRUST", - "CERT_TRUST_IS_NOT_SIGNATURE_VALID", - "CERT_TRUST_IS_NOT_TIME_VALID", - "CERT_TRUST_IS_NOT_VALID_FOR_USAGE", - "CERT_TRUST_IS_OFFLINE_REVOCATION", - "CERT_TRUST_IS_REVOKED", - "CERT_TRUST_IS_UNTRUSTED_ROOT", - "CERT_TRUST_NO_ERROR", - "CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY", - "CERT_TRUST_REVOCATION_STATUS_UNKNOWN", - "CFLUSH", - "CLOCAL", - "CLONE_CHILD_CLEARTID", - "CLONE_CHILD_SETTID", - "CLONE_CLEAR_SIGHAND", - "CLONE_CSIGNAL", - "CLONE_DETACHED", - "CLONE_FILES", - "CLONE_FS", - "CLONE_INTO_CGROUP", - "CLONE_IO", - "CLONE_NEWCGROUP", - "CLONE_NEWIPC", - "CLONE_NEWNET", - "CLONE_NEWNS", - "CLONE_NEWPID", - "CLONE_NEWTIME", - "CLONE_NEWUSER", - "CLONE_NEWUTS", - "CLONE_PARENT", - "CLONE_PARENT_SETTID", - "CLONE_PID", - "CLONE_PIDFD", - "CLONE_PTRACE", - "CLONE_SETTLS", - "CLONE_SIGHAND", - "CLONE_SYSVSEM", - "CLONE_THREAD", - "CLONE_UNTRACED", - "CLONE_VFORK", - "CLONE_VM", - "CPUID_CFLUSH", - "CREAD", - "CREATE_ALWAYS", - "CREATE_NEW", - "CREATE_NEW_PROCESS_GROUP", - "CREATE_UNICODE_ENVIRONMENT", - "CRYPT_DEFAULT_CONTAINER_OPTIONAL", - "CRYPT_DELETEKEYSET", - "CRYPT_MACHINE_KEYSET", - "CRYPT_NEWKEYSET", - "CRYPT_SILENT", - "CRYPT_VERIFYCONTEXT", - "CS5", - "CS6", - "CS7", - "CS8", - "CSIZE", - "CSTART", - "CSTATUS", - "CSTOP", - "CSTOPB", - "CSUSP", - "CTL_MAXNAME", - "CTL_NET", - "CTL_QUERY", - "CTRL_BREAK_EVENT", - "CTRL_CLOSE_EVENT", - "CTRL_C_EVENT", - "CTRL_LOGOFF_EVENT", - "CTRL_SHUTDOWN_EVENT", - "CancelIo", - "CancelIoEx", - "CertAddCertificateContextToStore", - "CertChainContext", - "CertChainElement", - "CertChainPara", - "CertChainPolicyPara", - "CertChainPolicyStatus", - "CertCloseStore", - "CertContext", - "CertCreateCertificateContext", - "CertEnhKeyUsage", - "CertEnumCertificatesInStore", - "CertFreeCertificateChain", - "CertFreeCertificateContext", - "CertGetCertificateChain", - "CertInfo", - "CertOpenStore", - "CertOpenSystemStore", - "CertRevocationCrlInfo", - "CertRevocationInfo", - "CertSimpleChain", - "CertTrustListInfo", - "CertTrustStatus", - "CertUsageMatch", - "CertVerifyCertificateChainPolicy", - "Chdir", - "CheckBpfVersion", - "Chflags", - "Chmod", - "Chown", - "Chroot", - "Clearenv", - "Close", - "CloseHandle", - "CloseOnExec", - "Closesocket", - "CmsgLen", - "CmsgSpace", - "Cmsghdr", - "CommandLineToArgv", - "ComputerName", - "Conn", - "Connect", - "ConnectEx", - "ConvertSidToStringSid", - "ConvertStringSidToSid", - "CopySid", - "Creat", - "CreateDirectory", - "CreateFile", - "CreateFileMapping", - "CreateHardLink", - "CreateIoCompletionPort", - "CreatePipe", - "CreateProcess", - "CreateProcessAsUser", - "CreateSymbolicLink", - "CreateToolhelp32Snapshot", - "Credential", - "CryptAcquireContext", - "CryptGenRandom", - "CryptReleaseContext", - "DIOCBSFLUSH", - "DIOCOSFPFLUSH", - "DLL", - "DLLError", - "DLT_A429", - "DLT_A653_ICM", - "DLT_AIRONET_HEADER", - "DLT_AOS", - "DLT_APPLE_IP_OVER_IEEE1394", - "DLT_ARCNET", - "DLT_ARCNET_LINUX", - "DLT_ATM_CLIP", - "DLT_ATM_RFC1483", - "DLT_AURORA", - "DLT_AX25", - "DLT_AX25_KISS", - "DLT_BACNET_MS_TP", - "DLT_BLUETOOTH_HCI_H4", - "DLT_BLUETOOTH_HCI_H4_WITH_PHDR", - "DLT_CAN20B", - "DLT_CAN_SOCKETCAN", - "DLT_CHAOS", - "DLT_CHDLC", - "DLT_CISCO_IOS", - "DLT_C_HDLC", - "DLT_C_HDLC_WITH_DIR", - "DLT_DBUS", - "DLT_DECT", - "DLT_DOCSIS", - "DLT_DVB_CI", - "DLT_ECONET", - "DLT_EN10MB", - "DLT_EN3MB", - "DLT_ENC", - "DLT_ERF", - "DLT_ERF_ETH", - "DLT_ERF_POS", - "DLT_FC_2", - "DLT_FC_2_WITH_FRAME_DELIMS", - "DLT_FDDI", - "DLT_FLEXRAY", - "DLT_FRELAY", - "DLT_FRELAY_WITH_DIR", - "DLT_GCOM_SERIAL", - "DLT_GCOM_T1E1", - "DLT_GPF_F", - "DLT_GPF_T", - "DLT_GPRS_LLC", - "DLT_GSMTAP_ABIS", - "DLT_GSMTAP_UM", - "DLT_HDLC", - "DLT_HHDLC", - "DLT_HIPPI", - "DLT_IBM_SN", - "DLT_IBM_SP", - "DLT_IEEE802", - "DLT_IEEE802_11", - "DLT_IEEE802_11_RADIO", - "DLT_IEEE802_11_RADIO_AVS", - "DLT_IEEE802_15_4", - "DLT_IEEE802_15_4_LINUX", - "DLT_IEEE802_15_4_NOFCS", - "DLT_IEEE802_15_4_NONASK_PHY", - "DLT_IEEE802_16_MAC_CPS", - "DLT_IEEE802_16_MAC_CPS_RADIO", - "DLT_IPFILTER", - "DLT_IPMB", - "DLT_IPMB_LINUX", - "DLT_IPNET", - "DLT_IPOIB", - "DLT_IPV4", - "DLT_IPV6", - "DLT_IP_OVER_FC", - "DLT_JUNIPER_ATM1", - "DLT_JUNIPER_ATM2", - "DLT_JUNIPER_ATM_CEMIC", - "DLT_JUNIPER_CHDLC", - "DLT_JUNIPER_ES", - "DLT_JUNIPER_ETHER", - "DLT_JUNIPER_FIBRECHANNEL", - "DLT_JUNIPER_FRELAY", - "DLT_JUNIPER_GGSN", - "DLT_JUNIPER_ISM", - "DLT_JUNIPER_MFR", - "DLT_JUNIPER_MLFR", - "DLT_JUNIPER_MLPPP", - "DLT_JUNIPER_MONITOR", - "DLT_JUNIPER_PIC_PEER", - "DLT_JUNIPER_PPP", - "DLT_JUNIPER_PPPOE", - "DLT_JUNIPER_PPPOE_ATM", - "DLT_JUNIPER_SERVICES", - "DLT_JUNIPER_SRX_E2E", - "DLT_JUNIPER_ST", - "DLT_JUNIPER_VP", - "DLT_JUNIPER_VS", - "DLT_LAPB_WITH_DIR", - "DLT_LAPD", - "DLT_LIN", - "DLT_LINUX_EVDEV", - "DLT_LINUX_IRDA", - "DLT_LINUX_LAPD", - "DLT_LINUX_PPP_WITHDIRECTION", - "DLT_LINUX_SLL", - "DLT_LOOP", - "DLT_LTALK", - "DLT_MATCHING_MAX", - "DLT_MATCHING_MIN", - "DLT_MFR", - "DLT_MOST", - "DLT_MPEG_2_TS", - "DLT_MPLS", - "DLT_MTP2", - "DLT_MTP2_WITH_PHDR", - "DLT_MTP3", - "DLT_MUX27010", - "DLT_NETANALYZER", - "DLT_NETANALYZER_TRANSPARENT", - "DLT_NFC_LLCP", - "DLT_NFLOG", - "DLT_NG40", - "DLT_NULL", - "DLT_PCI_EXP", - "DLT_PFLOG", - "DLT_PFSYNC", - "DLT_PPI", - "DLT_PPP", - "DLT_PPP_BSDOS", - "DLT_PPP_ETHER", - "DLT_PPP_PPPD", - "DLT_PPP_SERIAL", - "DLT_PPP_WITH_DIR", - "DLT_PPP_WITH_DIRECTION", - "DLT_PRISM_HEADER", - "DLT_PRONET", - "DLT_RAIF1", - "DLT_RAW", - "DLT_RAWAF_MASK", - "DLT_RIO", - "DLT_SCCP", - "DLT_SITA", - "DLT_SLIP", - "DLT_SLIP_BSDOS", - "DLT_STANAG_5066_D_PDU", - "DLT_SUNATM", - "DLT_SYMANTEC_FIREWALL", - "DLT_TZSP", - "DLT_USB", - "DLT_USB_LINUX", - "DLT_USB_LINUX_MMAPPED", - "DLT_USER0", - "DLT_USER1", - "DLT_USER10", - "DLT_USER11", - "DLT_USER12", - "DLT_USER13", - "DLT_USER14", - "DLT_USER15", - "DLT_USER2", - "DLT_USER3", - "DLT_USER4", - "DLT_USER5", - "DLT_USER6", - "DLT_USER7", - "DLT_USER8", - "DLT_USER9", - "DLT_WIHART", - "DLT_X2E_SERIAL", - "DLT_X2E_XORAYA", - "DNSMXData", - "DNSPTRData", - "DNSRecord", - "DNSSRVData", - "DNSTXTData", - "DNS_INFO_NO_RECORDS", - "DNS_TYPE_A", - "DNS_TYPE_A6", - "DNS_TYPE_AAAA", - "DNS_TYPE_ADDRS", - "DNS_TYPE_AFSDB", - "DNS_TYPE_ALL", - "DNS_TYPE_ANY", - "DNS_TYPE_ATMA", - "DNS_TYPE_AXFR", - "DNS_TYPE_CERT", - "DNS_TYPE_CNAME", - "DNS_TYPE_DHCID", - "DNS_TYPE_DNAME", - "DNS_TYPE_DNSKEY", - "DNS_TYPE_DS", - "DNS_TYPE_EID", - "DNS_TYPE_GID", - "DNS_TYPE_GPOS", - "DNS_TYPE_HINFO", - "DNS_TYPE_ISDN", - "DNS_TYPE_IXFR", - "DNS_TYPE_KEY", - "DNS_TYPE_KX", - "DNS_TYPE_LOC", - "DNS_TYPE_MAILA", - "DNS_TYPE_MAILB", - "DNS_TYPE_MB", - "DNS_TYPE_MD", - "DNS_TYPE_MF", - "DNS_TYPE_MG", - "DNS_TYPE_MINFO", - "DNS_TYPE_MR", - "DNS_TYPE_MX", - "DNS_TYPE_NAPTR", - "DNS_TYPE_NBSTAT", - "DNS_TYPE_NIMLOC", - "DNS_TYPE_NS", - "DNS_TYPE_NSAP", - "DNS_TYPE_NSAPPTR", - "DNS_TYPE_NSEC", - "DNS_TYPE_NULL", - "DNS_TYPE_NXT", - "DNS_TYPE_OPT", - "DNS_TYPE_PTR", - "DNS_TYPE_PX", - "DNS_TYPE_RP", - "DNS_TYPE_RRSIG", - "DNS_TYPE_RT", - "DNS_TYPE_SIG", - "DNS_TYPE_SINK", - "DNS_TYPE_SOA", - "DNS_TYPE_SRV", - "DNS_TYPE_TEXT", - "DNS_TYPE_TKEY", - "DNS_TYPE_TSIG", - "DNS_TYPE_UID", - "DNS_TYPE_UINFO", - "DNS_TYPE_UNSPEC", - "DNS_TYPE_WINS", - "DNS_TYPE_WINSR", - "DNS_TYPE_WKS", - "DNS_TYPE_X25", - "DT_BLK", - "DT_CHR", - "DT_DIR", - "DT_FIFO", - "DT_LNK", - "DT_REG", - "DT_SOCK", - "DT_UNKNOWN", - "DT_WHT", - "DUPLICATE_CLOSE_SOURCE", - "DUPLICATE_SAME_ACCESS", - "DeleteFile", - "DetachLsf", - "DeviceIoControl", - "Dirent", - "DnsNameCompare", - "DnsQuery", - "DnsRecordListFree", - "DnsSectionAdditional", - "DnsSectionAnswer", - "DnsSectionAuthority", - "DnsSectionQuestion", - "Dup", - "Dup2", - "Dup3", - "DuplicateHandle", - "E2BIG", - "EACCES", - "EADDRINUSE", - "EADDRNOTAVAIL", - "EADV", - "EAFNOSUPPORT", - "EAGAIN", - "EALREADY", - "EAUTH", - "EBADARCH", - "EBADE", - "EBADEXEC", - "EBADF", - "EBADFD", - "EBADMACHO", - "EBADMSG", - "EBADR", - "EBADRPC", - "EBADRQC", - "EBADSLT", - "EBFONT", - "EBUSY", - "ECANCELED", - "ECAPMODE", - "ECHILD", - "ECHO", - "ECHOCTL", - "ECHOE", - "ECHOK", - "ECHOKE", - "ECHONL", - "ECHOPRT", - "ECHRNG", - "ECOMM", - "ECONNABORTED", - "ECONNREFUSED", - "ECONNRESET", - "EDEADLK", - "EDEADLOCK", - "EDESTADDRREQ", - "EDEVERR", - "EDOM", - "EDOOFUS", - "EDOTDOT", - "EDQUOT", - "EEXIST", - "EFAULT", - "EFBIG", - "EFER_LMA", - "EFER_LME", - "EFER_NXE", - "EFER_SCE", - "EFTYPE", - "EHOSTDOWN", - "EHOSTUNREACH", - "EHWPOISON", - "EIDRM", - "EILSEQ", - "EINPROGRESS", - "EINTR", - "EINVAL", - "EIO", - "EIPSEC", - "EISCONN", - "EISDIR", - "EISNAM", - "EKEYEXPIRED", - "EKEYREJECTED", - "EKEYREVOKED", - "EL2HLT", - "EL2NSYNC", - "EL3HLT", - "EL3RST", - "ELAST", - "ELF_NGREG", - "ELF_PRARGSZ", - "ELIBACC", - "ELIBBAD", - "ELIBEXEC", - "ELIBMAX", - "ELIBSCN", - "ELNRNG", - "ELOOP", - "EMEDIUMTYPE", - "EMFILE", - "EMLINK", - "EMSGSIZE", - "EMT_TAGOVF", - "EMULTIHOP", - "EMUL_ENABLED", - "EMUL_LINUX", - "EMUL_LINUX32", - "EMUL_MAXID", - "EMUL_NATIVE", - "ENAMETOOLONG", - "ENAVAIL", - "ENDRUNDISC", - "ENEEDAUTH", - "ENETDOWN", - "ENETRESET", - "ENETUNREACH", - "ENFILE", - "ENOANO", - "ENOATTR", - "ENOBUFS", - "ENOCSI", - "ENODATA", - "ENODEV", - "ENOENT", - "ENOEXEC", - "ENOKEY", - "ENOLCK", - "ENOLINK", - "ENOMEDIUM", - "ENOMEM", - "ENOMSG", - "ENONET", - "ENOPKG", - "ENOPOLICY", - "ENOPROTOOPT", - "ENOSPC", - "ENOSR", - "ENOSTR", - "ENOSYS", - "ENOTBLK", - "ENOTCAPABLE", - "ENOTCONN", - "ENOTDIR", - "ENOTEMPTY", - "ENOTNAM", - "ENOTRECOVERABLE", - "ENOTSOCK", - "ENOTSUP", - "ENOTTY", - "ENOTUNIQ", - "ENXIO", - "EN_SW_CTL_INF", - "EN_SW_CTL_PREC", - "EN_SW_CTL_ROUND", - "EN_SW_DATACHAIN", - "EN_SW_DENORM", - "EN_SW_INVOP", - "EN_SW_OVERFLOW", - "EN_SW_PRECLOSS", - "EN_SW_UNDERFLOW", - "EN_SW_ZERODIV", - "EOPNOTSUPP", - "EOVERFLOW", - "EOWNERDEAD", - "EPERM", - "EPFNOSUPPORT", - "EPIPE", - "EPOLLERR", - "EPOLLET", - "EPOLLHUP", - "EPOLLIN", - "EPOLLMSG", - "EPOLLONESHOT", - "EPOLLOUT", - "EPOLLPRI", - "EPOLLRDBAND", - "EPOLLRDHUP", - "EPOLLRDNORM", - "EPOLLWRBAND", - "EPOLLWRNORM", - "EPOLL_CLOEXEC", - "EPOLL_CTL_ADD", - "EPOLL_CTL_DEL", - "EPOLL_CTL_MOD", - "EPOLL_NONBLOCK", - "EPROCLIM", - "EPROCUNAVAIL", - "EPROGMISMATCH", - "EPROGUNAVAIL", - "EPROTO", - "EPROTONOSUPPORT", - "EPROTOTYPE", - "EPWROFF", - "EQFULL", - "ERANGE", - "EREMCHG", - "EREMOTE", - "EREMOTEIO", - "ERESTART", - "ERFKILL", - "EROFS", - "ERPCMISMATCH", - "ERROR_ACCESS_DENIED", - "ERROR_ALREADY_EXISTS", - "ERROR_BROKEN_PIPE", - "ERROR_BUFFER_OVERFLOW", - "ERROR_DIR_NOT_EMPTY", - "ERROR_ENVVAR_NOT_FOUND", - "ERROR_FILE_EXISTS", - "ERROR_FILE_NOT_FOUND", - "ERROR_HANDLE_EOF", - "ERROR_INSUFFICIENT_BUFFER", - "ERROR_IO_PENDING", - "ERROR_MOD_NOT_FOUND", - "ERROR_MORE_DATA", - "ERROR_NETNAME_DELETED", - "ERROR_NOT_FOUND", - "ERROR_NO_MORE_FILES", - "ERROR_OPERATION_ABORTED", - "ERROR_PATH_NOT_FOUND", - "ERROR_PRIVILEGE_NOT_HELD", - "ERROR_PROC_NOT_FOUND", - "ESHLIBVERS", - "ESHUTDOWN", - "ESOCKTNOSUPPORT", - "ESPIPE", - "ESRCH", - "ESRMNT", - "ESTALE", - "ESTRPIPE", - "ETHERCAP_JUMBO_MTU", - "ETHERCAP_VLAN_HWTAGGING", - "ETHERCAP_VLAN_MTU", - "ETHERMIN", - "ETHERMTU", - "ETHERMTU_JUMBO", - "ETHERTYPE_8023", - "ETHERTYPE_AARP", - "ETHERTYPE_ACCTON", - "ETHERTYPE_AEONIC", - "ETHERTYPE_ALPHA", - "ETHERTYPE_AMBER", - "ETHERTYPE_AMOEBA", - "ETHERTYPE_AOE", - "ETHERTYPE_APOLLO", - "ETHERTYPE_APOLLODOMAIN", - "ETHERTYPE_APPLETALK", - "ETHERTYPE_APPLITEK", - "ETHERTYPE_ARGONAUT", - "ETHERTYPE_ARP", - "ETHERTYPE_AT", - "ETHERTYPE_ATALK", - "ETHERTYPE_ATOMIC", - "ETHERTYPE_ATT", - "ETHERTYPE_ATTSTANFORD", - "ETHERTYPE_AUTOPHON", - "ETHERTYPE_AXIS", - "ETHERTYPE_BCLOOP", - "ETHERTYPE_BOFL", - "ETHERTYPE_CABLETRON", - "ETHERTYPE_CHAOS", - "ETHERTYPE_COMDESIGN", - "ETHERTYPE_COMPUGRAPHIC", - "ETHERTYPE_COUNTERPOINT", - "ETHERTYPE_CRONUS", - "ETHERTYPE_CRONUSVLN", - "ETHERTYPE_DCA", - "ETHERTYPE_DDE", - "ETHERTYPE_DEBNI", - "ETHERTYPE_DECAM", - "ETHERTYPE_DECCUST", - "ETHERTYPE_DECDIAG", - "ETHERTYPE_DECDNS", - "ETHERTYPE_DECDTS", - "ETHERTYPE_DECEXPER", - "ETHERTYPE_DECLAST", - "ETHERTYPE_DECLTM", - "ETHERTYPE_DECMUMPS", - "ETHERTYPE_DECNETBIOS", - "ETHERTYPE_DELTACON", - "ETHERTYPE_DIDDLE", - "ETHERTYPE_DLOG1", - "ETHERTYPE_DLOG2", - "ETHERTYPE_DN", - "ETHERTYPE_DOGFIGHT", - "ETHERTYPE_DSMD", - "ETHERTYPE_ECMA", - "ETHERTYPE_ENCRYPT", - "ETHERTYPE_ES", - "ETHERTYPE_EXCELAN", - "ETHERTYPE_EXPERDATA", - "ETHERTYPE_FLIP", - "ETHERTYPE_FLOWCONTROL", - "ETHERTYPE_FRARP", - "ETHERTYPE_GENDYN", - "ETHERTYPE_HAYES", - "ETHERTYPE_HIPPI_FP", - "ETHERTYPE_HITACHI", - "ETHERTYPE_HP", - "ETHERTYPE_IEEEPUP", - "ETHERTYPE_IEEEPUPAT", - "ETHERTYPE_IMLBL", - "ETHERTYPE_IMLBLDIAG", - "ETHERTYPE_IP", - "ETHERTYPE_IPAS", - "ETHERTYPE_IPV6", - "ETHERTYPE_IPX", - "ETHERTYPE_IPXNEW", - "ETHERTYPE_KALPANA", - "ETHERTYPE_LANBRIDGE", - "ETHERTYPE_LANPROBE", - "ETHERTYPE_LAT", - "ETHERTYPE_LBACK", - "ETHERTYPE_LITTLE", - "ETHERTYPE_LLDP", - "ETHERTYPE_LOGICRAFT", - "ETHERTYPE_LOOPBACK", - "ETHERTYPE_MATRA", - "ETHERTYPE_MAX", - "ETHERTYPE_MERIT", - "ETHERTYPE_MICP", - "ETHERTYPE_MOPDL", - "ETHERTYPE_MOPRC", - "ETHERTYPE_MOTOROLA", - "ETHERTYPE_MPLS", - "ETHERTYPE_MPLS_MCAST", - "ETHERTYPE_MUMPS", - "ETHERTYPE_NBPCC", - "ETHERTYPE_NBPCLAIM", - "ETHERTYPE_NBPCLREQ", - "ETHERTYPE_NBPCLRSP", - "ETHERTYPE_NBPCREQ", - "ETHERTYPE_NBPCRSP", - "ETHERTYPE_NBPDG", - "ETHERTYPE_NBPDGB", - "ETHERTYPE_NBPDLTE", - "ETHERTYPE_NBPRAR", - "ETHERTYPE_NBPRAS", - "ETHERTYPE_NBPRST", - "ETHERTYPE_NBPSCD", - "ETHERTYPE_NBPVCD", - "ETHERTYPE_NBS", - "ETHERTYPE_NCD", - "ETHERTYPE_NESTAR", - "ETHERTYPE_NETBEUI", - "ETHERTYPE_NOVELL", - "ETHERTYPE_NS", - "ETHERTYPE_NSAT", - "ETHERTYPE_NSCOMPAT", - "ETHERTYPE_NTRAILER", - "ETHERTYPE_OS9", - "ETHERTYPE_OS9NET", - "ETHERTYPE_PACER", - "ETHERTYPE_PAE", - "ETHERTYPE_PCS", - "ETHERTYPE_PLANNING", - "ETHERTYPE_PPP", - "ETHERTYPE_PPPOE", - "ETHERTYPE_PPPOEDISC", - "ETHERTYPE_PRIMENTS", - "ETHERTYPE_PUP", - "ETHERTYPE_PUPAT", - "ETHERTYPE_QINQ", - "ETHERTYPE_RACAL", - "ETHERTYPE_RATIONAL", - "ETHERTYPE_RAWFR", - "ETHERTYPE_RCL", - "ETHERTYPE_RDP", - "ETHERTYPE_RETIX", - "ETHERTYPE_REVARP", - "ETHERTYPE_SCA", - "ETHERTYPE_SECTRA", - "ETHERTYPE_SECUREDATA", - "ETHERTYPE_SGITW", - "ETHERTYPE_SG_BOUNCE", - "ETHERTYPE_SG_DIAG", - "ETHERTYPE_SG_NETGAMES", - "ETHERTYPE_SG_RESV", - "ETHERTYPE_SIMNET", - "ETHERTYPE_SLOW", - "ETHERTYPE_SLOWPROTOCOLS", - "ETHERTYPE_SNA", - "ETHERTYPE_SNMP", - "ETHERTYPE_SONIX", - "ETHERTYPE_SPIDER", - "ETHERTYPE_SPRITE", - "ETHERTYPE_STP", - "ETHERTYPE_TALARIS", - "ETHERTYPE_TALARISMC", - "ETHERTYPE_TCPCOMP", - "ETHERTYPE_TCPSM", - "ETHERTYPE_TEC", - "ETHERTYPE_TIGAN", - "ETHERTYPE_TRAIL", - "ETHERTYPE_TRANSETHER", - "ETHERTYPE_TYMSHARE", - "ETHERTYPE_UBBST", - "ETHERTYPE_UBDEBUG", - "ETHERTYPE_UBDIAGLOOP", - "ETHERTYPE_UBDL", - "ETHERTYPE_UBNIU", - "ETHERTYPE_UBNMC", - "ETHERTYPE_VALID", - "ETHERTYPE_VARIAN", - "ETHERTYPE_VAXELN", - "ETHERTYPE_VEECO", - "ETHERTYPE_VEXP", - "ETHERTYPE_VGLAB", - "ETHERTYPE_VINES", - "ETHERTYPE_VINESECHO", - "ETHERTYPE_VINESLOOP", - "ETHERTYPE_VITAL", - "ETHERTYPE_VLAN", - "ETHERTYPE_VLTLMAN", - "ETHERTYPE_VPROD", - "ETHERTYPE_VURESERVED", - "ETHERTYPE_WATERLOO", - "ETHERTYPE_WELLFLEET", - "ETHERTYPE_X25", - "ETHERTYPE_X75", - "ETHERTYPE_XNSSM", - "ETHERTYPE_XTP", - "ETHER_ADDR_LEN", - "ETHER_ALIGN", - "ETHER_CRC_LEN", - "ETHER_CRC_POLY_BE", - "ETHER_CRC_POLY_LE", - "ETHER_HDR_LEN", - "ETHER_MAX_DIX_LEN", - "ETHER_MAX_LEN", - "ETHER_MAX_LEN_JUMBO", - "ETHER_MIN_LEN", - "ETHER_PPPOE_ENCAP_LEN", - "ETHER_TYPE_LEN", - "ETHER_VLAN_ENCAP_LEN", - "ETH_P_1588", - "ETH_P_8021Q", - "ETH_P_802_2", - "ETH_P_802_3", - "ETH_P_AARP", - "ETH_P_ALL", - "ETH_P_AOE", - "ETH_P_ARCNET", - "ETH_P_ARP", - "ETH_P_ATALK", - "ETH_P_ATMFATE", - "ETH_P_ATMMPOA", - "ETH_P_AX25", - "ETH_P_BPQ", - "ETH_P_CAIF", - "ETH_P_CAN", - "ETH_P_CONTROL", - "ETH_P_CUST", - "ETH_P_DDCMP", - "ETH_P_DEC", - "ETH_P_DIAG", - "ETH_P_DNA_DL", - "ETH_P_DNA_RC", - "ETH_P_DNA_RT", - "ETH_P_DSA", - "ETH_P_ECONET", - "ETH_P_EDSA", - "ETH_P_FCOE", - "ETH_P_FIP", - "ETH_P_HDLC", - "ETH_P_IEEE802154", - "ETH_P_IEEEPUP", - "ETH_P_IEEEPUPAT", - "ETH_P_IP", - "ETH_P_IPV6", - "ETH_P_IPX", - "ETH_P_IRDA", - "ETH_P_LAT", - "ETH_P_LINK_CTL", - "ETH_P_LOCALTALK", - "ETH_P_LOOP", - "ETH_P_MOBITEX", - "ETH_P_MPLS_MC", - "ETH_P_MPLS_UC", - "ETH_P_PAE", - "ETH_P_PAUSE", - "ETH_P_PHONET", - "ETH_P_PPPTALK", - "ETH_P_PPP_DISC", - "ETH_P_PPP_MP", - "ETH_P_PPP_SES", - "ETH_P_PUP", - "ETH_P_PUPAT", - "ETH_P_RARP", - "ETH_P_SCA", - "ETH_P_SLOW", - "ETH_P_SNAP", - "ETH_P_TEB", - "ETH_P_TIPC", - "ETH_P_TRAILER", - "ETH_P_TR_802_2", - "ETH_P_WAN_PPP", - "ETH_P_WCCP", - "ETH_P_X25", - "ETIME", - "ETIMEDOUT", - "ETOOMANYREFS", - "ETXTBSY", - "EUCLEAN", - "EUNATCH", - "EUSERS", - "EVFILT_AIO", - "EVFILT_FS", - "EVFILT_LIO", - "EVFILT_MACHPORT", - "EVFILT_PROC", - "EVFILT_READ", - "EVFILT_SIGNAL", - "EVFILT_SYSCOUNT", - "EVFILT_THREADMARKER", - "EVFILT_TIMER", - "EVFILT_USER", - "EVFILT_VM", - "EVFILT_VNODE", - "EVFILT_WRITE", - "EV_ADD", - "EV_CLEAR", - "EV_DELETE", - "EV_DISABLE", - "EV_DISPATCH", - "EV_DROP", - "EV_ENABLE", - "EV_EOF", - "EV_ERROR", - "EV_FLAG0", - "EV_FLAG1", - "EV_ONESHOT", - "EV_OOBAND", - "EV_POLL", - "EV_RECEIPT", - "EV_SYSFLAGS", - "EWINDOWS", - "EWOULDBLOCK", - "EXDEV", - "EXFULL", - "EXTA", - "EXTB", - "EXTPROC", - "Environ", - "EpollCreate", - "EpollCreate1", - "EpollCtl", - "EpollEvent", - "EpollWait", - "Errno", - "EscapeArg", - "Exchangedata", - "Exec", - "Exit", - "ExitProcess", - "FD_CLOEXEC", - "FD_SETSIZE", - "FILE_ACTION_ADDED", - "FILE_ACTION_MODIFIED", - "FILE_ACTION_REMOVED", - "FILE_ACTION_RENAMED_NEW_NAME", - "FILE_ACTION_RENAMED_OLD_NAME", - "FILE_APPEND_DATA", - "FILE_ATTRIBUTE_ARCHIVE", - "FILE_ATTRIBUTE_DIRECTORY", - "FILE_ATTRIBUTE_HIDDEN", - "FILE_ATTRIBUTE_NORMAL", - "FILE_ATTRIBUTE_READONLY", - "FILE_ATTRIBUTE_REPARSE_POINT", - "FILE_ATTRIBUTE_SYSTEM", - "FILE_BEGIN", - "FILE_CURRENT", - "FILE_END", - "FILE_FLAG_BACKUP_SEMANTICS", - "FILE_FLAG_OPEN_REPARSE_POINT", - "FILE_FLAG_OVERLAPPED", - "FILE_LIST_DIRECTORY", - "FILE_MAP_COPY", - "FILE_MAP_EXECUTE", - "FILE_MAP_READ", - "FILE_MAP_WRITE", - "FILE_NOTIFY_CHANGE_ATTRIBUTES", - "FILE_NOTIFY_CHANGE_CREATION", - "FILE_NOTIFY_CHANGE_DIR_NAME", - "FILE_NOTIFY_CHANGE_FILE_NAME", - "FILE_NOTIFY_CHANGE_LAST_ACCESS", - "FILE_NOTIFY_CHANGE_LAST_WRITE", - "FILE_NOTIFY_CHANGE_SIZE", - "FILE_SHARE_DELETE", - "FILE_SHARE_READ", - "FILE_SHARE_WRITE", - "FILE_SKIP_COMPLETION_PORT_ON_SUCCESS", - "FILE_SKIP_SET_EVENT_ON_HANDLE", - "FILE_TYPE_CHAR", - "FILE_TYPE_DISK", - "FILE_TYPE_PIPE", - "FILE_TYPE_REMOTE", - "FILE_TYPE_UNKNOWN", - "FILE_WRITE_ATTRIBUTES", - "FLUSHO", - "FORMAT_MESSAGE_ALLOCATE_BUFFER", - "FORMAT_MESSAGE_ARGUMENT_ARRAY", - "FORMAT_MESSAGE_FROM_HMODULE", - "FORMAT_MESSAGE_FROM_STRING", - "FORMAT_MESSAGE_FROM_SYSTEM", - "FORMAT_MESSAGE_IGNORE_INSERTS", - "FORMAT_MESSAGE_MAX_WIDTH_MASK", - "FSCTL_GET_REPARSE_POINT", - "F_ADDFILESIGS", - "F_ADDSIGS", - "F_ALLOCATEALL", - "F_ALLOCATECONTIG", - "F_CANCEL", - "F_CHKCLEAN", - "F_CLOSEM", - "F_DUP2FD", - "F_DUP2FD_CLOEXEC", - "F_DUPFD", - "F_DUPFD_CLOEXEC", - "F_EXLCK", - "F_FINDSIGS", - "F_FLUSH_DATA", - "F_FREEZE_FS", - "F_FSCTL", - "F_FSDIRMASK", - "F_FSIN", - "F_FSINOUT", - "F_FSOUT", - "F_FSPRIV", - "F_FSVOID", - "F_FULLFSYNC", - "F_GETCODEDIR", - "F_GETFD", - "F_GETFL", - "F_GETLEASE", - "F_GETLK", - "F_GETLK64", - "F_GETLKPID", - "F_GETNOSIGPIPE", - "F_GETOWN", - "F_GETOWN_EX", - "F_GETPATH", - "F_GETPATH_MTMINFO", - "F_GETPIPE_SZ", - "F_GETPROTECTIONCLASS", - "F_GETPROTECTIONLEVEL", - "F_GETSIG", - "F_GLOBAL_NOCACHE", - "F_LOCK", - "F_LOG2PHYS", - "F_LOG2PHYS_EXT", - "F_MARKDEPENDENCY", - "F_MAXFD", - "F_NOCACHE", - "F_NODIRECT", - "F_NOTIFY", - "F_OGETLK", - "F_OK", - "F_OSETLK", - "F_OSETLKW", - "F_PARAM_MASK", - "F_PARAM_MAX", - "F_PATHPKG_CHECK", - "F_PEOFPOSMODE", - "F_PREALLOCATE", - "F_RDADVISE", - "F_RDAHEAD", - "F_RDLCK", - "F_READAHEAD", - "F_READBOOTSTRAP", - "F_SETBACKINGSTORE", - "F_SETFD", - "F_SETFL", - "F_SETLEASE", - "F_SETLK", - "F_SETLK64", - "F_SETLKW", - "F_SETLKW64", - "F_SETLKWTIMEOUT", - "F_SETLK_REMOTE", - "F_SETNOSIGPIPE", - "F_SETOWN", - "F_SETOWN_EX", - "F_SETPIPE_SZ", - "F_SETPROTECTIONCLASS", - "F_SETSIG", - "F_SETSIZE", - "F_SHLCK", - "F_SINGLE_WRITER", - "F_TEST", - "F_THAW_FS", - "F_TLOCK", - "F_TRANSCODEKEY", - "F_ULOCK", - "F_UNLCK", - "F_UNLCKSYS", - "F_VOLPOSMODE", - "F_WRITEBOOTSTRAP", - "F_WRLCK", - "Faccessat", - "Fallocate", - "Fbootstraptransfer_t", - "Fchdir", - "Fchflags", - "Fchmod", - "Fchmodat", - "Fchown", - "Fchownat", - "FcntlFlock", - "FdSet", - "Fdatasync", - "FileNotifyInformation", - "Filetime", - "FindClose", - "FindFirstFile", - "FindNextFile", - "Flock", - "Flock_t", - "FlushBpf", - "FlushFileBuffers", - "FlushViewOfFile", - "ForkExec", - "ForkLock", - "FormatMessage", - "Fpathconf", - "FreeAddrInfoW", - "FreeEnvironmentStrings", - "FreeLibrary", - "Fsid", - "Fstat", - "Fstatat", - "Fstatfs", - "Fstore_t", - "Fsync", - "Ftruncate", - "FullPath", - "Futimes", - "Futimesat", - "GENERIC_ALL", - "GENERIC_EXECUTE", - "GENERIC_READ", - "GENERIC_WRITE", - "GUID", - "GetAcceptExSockaddrs", - "GetAdaptersInfo", - "GetAddrInfoW", - "GetCommandLine", - "GetComputerName", - "GetConsoleMode", - "GetCurrentDirectory", - "GetCurrentProcess", - "GetEnvironmentStrings", - "GetEnvironmentVariable", - "GetExitCodeProcess", - "GetFileAttributes", - "GetFileAttributesEx", - "GetFileExInfoStandard", - "GetFileExMaxInfoLevel", - "GetFileInformationByHandle", - "GetFileType", - "GetFullPathName", - "GetHostByName", - "GetIfEntry", - "GetLastError", - "GetLengthSid", - "GetLongPathName", - "GetProcAddress", - "GetProcessTimes", - "GetProtoByName", - "GetQueuedCompletionStatus", - "GetServByName", - "GetShortPathName", - "GetStartupInfo", - "GetStdHandle", - "GetSystemTimeAsFileTime", - "GetTempPath", - "GetTimeZoneInformation", - "GetTokenInformation", - "GetUserNameEx", - "GetUserProfileDirectory", - "GetVersion", - "Getcwd", - "Getdents", - "Getdirentries", - "Getdtablesize", - "Getegid", - "Getenv", - "Geteuid", - "Getfsstat", - "Getgid", - "Getgroups", - "Getpagesize", - "Getpeername", - "Getpgid", - "Getpgrp", - "Getpid", - "Getppid", - "Getpriority", - "Getrlimit", - "Getrusage", - "Getsid", - "Getsockname", - "Getsockopt", - "GetsockoptByte", - "GetsockoptICMPv6Filter", - "GetsockoptIPMreq", - "GetsockoptIPMreqn", - "GetsockoptIPv6MTUInfo", - "GetsockoptIPv6Mreq", - "GetsockoptInet4Addr", - "GetsockoptInt", - "GetsockoptUcred", - "Gettid", - "Gettimeofday", - "Getuid", - "Getwd", - "Getxattr", - "HANDLE_FLAG_INHERIT", - "HKEY_CLASSES_ROOT", - "HKEY_CURRENT_CONFIG", - "HKEY_CURRENT_USER", - "HKEY_DYN_DATA", - "HKEY_LOCAL_MACHINE", - "HKEY_PERFORMANCE_DATA", - "HKEY_USERS", - "HUPCL", - "Handle", - "Hostent", - "ICANON", - "ICMP6_FILTER", - "ICMPV6_FILTER", - "ICMPv6Filter", - "ICRNL", - "IEXTEN", - "IFAN_ARRIVAL", - "IFAN_DEPARTURE", - "IFA_ADDRESS", - "IFA_ANYCAST", - "IFA_BROADCAST", - "IFA_CACHEINFO", - "IFA_F_DADFAILED", - "IFA_F_DEPRECATED", - "IFA_F_HOMEADDRESS", - "IFA_F_NODAD", - "IFA_F_OPTIMISTIC", - "IFA_F_PERMANENT", - "IFA_F_SECONDARY", - "IFA_F_TEMPORARY", - "IFA_F_TENTATIVE", - "IFA_LABEL", - "IFA_LOCAL", - "IFA_MAX", - "IFA_MULTICAST", - "IFA_ROUTE", - "IFA_UNSPEC", - "IFF_ALLMULTI", - "IFF_ALTPHYS", - "IFF_AUTOMEDIA", - "IFF_BROADCAST", - "IFF_CANTCHANGE", - "IFF_CANTCONFIG", - "IFF_DEBUG", - "IFF_DRV_OACTIVE", - "IFF_DRV_RUNNING", - "IFF_DYING", - "IFF_DYNAMIC", - "IFF_LINK0", - "IFF_LINK1", - "IFF_LINK2", - "IFF_LOOPBACK", - "IFF_MASTER", - "IFF_MONITOR", - "IFF_MULTICAST", - "IFF_NOARP", - "IFF_NOTRAILERS", - "IFF_NO_PI", - "IFF_OACTIVE", - "IFF_ONE_QUEUE", - "IFF_POINTOPOINT", - "IFF_POINTTOPOINT", - "IFF_PORTSEL", - "IFF_PPROMISC", - "IFF_PROMISC", - "IFF_RENAMING", - "IFF_RUNNING", - "IFF_SIMPLEX", - "IFF_SLAVE", - "IFF_SMART", - "IFF_STATICARP", - "IFF_TAP", - "IFF_TUN", - "IFF_TUN_EXCL", - "IFF_UP", - "IFF_VNET_HDR", - "IFLA_ADDRESS", - "IFLA_BROADCAST", - "IFLA_COST", - "IFLA_IFALIAS", - "IFLA_IFNAME", - "IFLA_LINK", - "IFLA_LINKINFO", - "IFLA_LINKMODE", - "IFLA_MAP", - "IFLA_MASTER", - "IFLA_MAX", - "IFLA_MTU", - "IFLA_NET_NS_PID", - "IFLA_OPERSTATE", - "IFLA_PRIORITY", - "IFLA_PROTINFO", - "IFLA_QDISC", - "IFLA_STATS", - "IFLA_TXQLEN", - "IFLA_UNSPEC", - "IFLA_WEIGHT", - "IFLA_WIRELESS", - "IFNAMSIZ", - "IFT_1822", - "IFT_A12MPPSWITCH", - "IFT_AAL2", - "IFT_AAL5", - "IFT_ADSL", - "IFT_AFLANE8023", - "IFT_AFLANE8025", - "IFT_ARAP", - "IFT_ARCNET", - "IFT_ARCNETPLUS", - "IFT_ASYNC", - "IFT_ATM", - "IFT_ATMDXI", - "IFT_ATMFUNI", - "IFT_ATMIMA", - "IFT_ATMLOGICAL", - "IFT_ATMRADIO", - "IFT_ATMSUBINTERFACE", - "IFT_ATMVCIENDPT", - "IFT_ATMVIRTUAL", - "IFT_BGPPOLICYACCOUNTING", - "IFT_BLUETOOTH", - "IFT_BRIDGE", - "IFT_BSC", - "IFT_CARP", - "IFT_CCTEMUL", - "IFT_CELLULAR", - "IFT_CEPT", - "IFT_CES", - "IFT_CHANNEL", - "IFT_CNR", - "IFT_COFFEE", - "IFT_COMPOSITELINK", - "IFT_DCN", - "IFT_DIGITALPOWERLINE", - "IFT_DIGITALWRAPPEROVERHEADCHANNEL", - "IFT_DLSW", - "IFT_DOCSCABLEDOWNSTREAM", - "IFT_DOCSCABLEMACLAYER", - "IFT_DOCSCABLEUPSTREAM", - "IFT_DOCSCABLEUPSTREAMCHANNEL", - "IFT_DS0", - "IFT_DS0BUNDLE", - "IFT_DS1FDL", - "IFT_DS3", - "IFT_DTM", - "IFT_DUMMY", - "IFT_DVBASILN", - "IFT_DVBASIOUT", - "IFT_DVBRCCDOWNSTREAM", - "IFT_DVBRCCMACLAYER", - "IFT_DVBRCCUPSTREAM", - "IFT_ECONET", - "IFT_ENC", - "IFT_EON", - "IFT_EPLRS", - "IFT_ESCON", - "IFT_ETHER", - "IFT_FAITH", - "IFT_FAST", - "IFT_FASTETHER", - "IFT_FASTETHERFX", - "IFT_FDDI", - "IFT_FIBRECHANNEL", - "IFT_FRAMERELAYINTERCONNECT", - "IFT_FRAMERELAYMPI", - "IFT_FRDLCIENDPT", - "IFT_FRELAY", - "IFT_FRELAYDCE", - "IFT_FRF16MFRBUNDLE", - "IFT_FRFORWARD", - "IFT_G703AT2MB", - "IFT_G703AT64K", - "IFT_GIF", - "IFT_GIGABITETHERNET", - "IFT_GR303IDT", - "IFT_GR303RDT", - "IFT_H323GATEKEEPER", - "IFT_H323PROXY", - "IFT_HDH1822", - "IFT_HDLC", - "IFT_HDSL2", - "IFT_HIPERLAN2", - "IFT_HIPPI", - "IFT_HIPPIINTERFACE", - "IFT_HOSTPAD", - "IFT_HSSI", - "IFT_HY", - "IFT_IBM370PARCHAN", - "IFT_IDSL", - "IFT_IEEE1394", - "IFT_IEEE80211", - "IFT_IEEE80212", - "IFT_IEEE8023ADLAG", - "IFT_IFGSN", - "IFT_IMT", - "IFT_INFINIBAND", - "IFT_INTERLEAVE", - "IFT_IP", - "IFT_IPFORWARD", - "IFT_IPOVERATM", - "IFT_IPOVERCDLC", - "IFT_IPOVERCLAW", - "IFT_IPSWITCH", - "IFT_IPXIP", - "IFT_ISDN", - "IFT_ISDNBASIC", - "IFT_ISDNPRIMARY", - "IFT_ISDNS", - "IFT_ISDNU", - "IFT_ISO88022LLC", - "IFT_ISO88023", - "IFT_ISO88024", - "IFT_ISO88025", - "IFT_ISO88025CRFPINT", - "IFT_ISO88025DTR", - "IFT_ISO88025FIBER", - "IFT_ISO88026", - "IFT_ISUP", - "IFT_L2VLAN", - "IFT_L3IPVLAN", - "IFT_L3IPXVLAN", - "IFT_LAPB", - "IFT_LAPD", - "IFT_LAPF", - "IFT_LINEGROUP", - "IFT_LOCALTALK", - "IFT_LOOP", - "IFT_MEDIAMAILOVERIP", - "IFT_MFSIGLINK", - "IFT_MIOX25", - "IFT_MODEM", - "IFT_MPC", - "IFT_MPLS", - "IFT_MPLSTUNNEL", - "IFT_MSDSL", - "IFT_MVL", - "IFT_MYRINET", - "IFT_NFAS", - "IFT_NSIP", - "IFT_OPTICALCHANNEL", - "IFT_OPTICALTRANSPORT", - "IFT_OTHER", - "IFT_P10", - "IFT_P80", - "IFT_PARA", - "IFT_PDP", - "IFT_PFLOG", - "IFT_PFLOW", - "IFT_PFSYNC", - "IFT_PLC", - "IFT_PON155", - "IFT_PON622", - "IFT_POS", - "IFT_PPP", - "IFT_PPPMULTILINKBUNDLE", - "IFT_PROPATM", - "IFT_PROPBWAP2MP", - "IFT_PROPCNLS", - "IFT_PROPDOCSWIRELESSDOWNSTREAM", - "IFT_PROPDOCSWIRELESSMACLAYER", - "IFT_PROPDOCSWIRELESSUPSTREAM", - "IFT_PROPMUX", - "IFT_PROPVIRTUAL", - "IFT_PROPWIRELESSP2P", - "IFT_PTPSERIAL", - "IFT_PVC", - "IFT_Q2931", - "IFT_QLLC", - "IFT_RADIOMAC", - "IFT_RADSL", - "IFT_REACHDSL", - "IFT_RFC1483", - "IFT_RS232", - "IFT_RSRB", - "IFT_SDLC", - "IFT_SDSL", - "IFT_SHDSL", - "IFT_SIP", - "IFT_SIPSIG", - "IFT_SIPTG", - "IFT_SLIP", - "IFT_SMDSDXI", - "IFT_SMDSICIP", - "IFT_SONET", - "IFT_SONETOVERHEADCHANNEL", - "IFT_SONETPATH", - "IFT_SONETVT", - "IFT_SRP", - "IFT_SS7SIGLINK", - "IFT_STACKTOSTACK", - "IFT_STARLAN", - "IFT_STF", - "IFT_T1", - "IFT_TDLC", - "IFT_TELINK", - "IFT_TERMPAD", - "IFT_TR008", - "IFT_TRANSPHDLC", - "IFT_TUNNEL", - "IFT_ULTRA", - "IFT_USB", - "IFT_V11", - "IFT_V35", - "IFT_V36", - "IFT_V37", - "IFT_VDSL", - "IFT_VIRTUALIPADDRESS", - "IFT_VIRTUALTG", - "IFT_VOICEDID", - "IFT_VOICEEM", - "IFT_VOICEEMFGD", - "IFT_VOICEENCAP", - "IFT_VOICEFGDEANA", - "IFT_VOICEFXO", - "IFT_VOICEFXS", - "IFT_VOICEOVERATM", - "IFT_VOICEOVERCABLE", - "IFT_VOICEOVERFRAMERELAY", - "IFT_VOICEOVERIP", - "IFT_X213", - "IFT_X25", - "IFT_X25DDN", - "IFT_X25HUNTGROUP", - "IFT_X25MLP", - "IFT_X25PLE", - "IFT_XETHER", - "IGNBRK", - "IGNCR", - "IGNORE", - "IGNPAR", - "IMAXBEL", - "INFINITE", - "INLCR", - "INPCK", - "INVALID_FILE_ATTRIBUTES", - "IN_ACCESS", - "IN_ALL_EVENTS", - "IN_ATTRIB", - "IN_CLASSA_HOST", - "IN_CLASSA_MAX", - "IN_CLASSA_NET", - "IN_CLASSA_NSHIFT", - "IN_CLASSB_HOST", - "IN_CLASSB_MAX", - "IN_CLASSB_NET", - "IN_CLASSB_NSHIFT", - "IN_CLASSC_HOST", - "IN_CLASSC_NET", - "IN_CLASSC_NSHIFT", - "IN_CLASSD_HOST", - "IN_CLASSD_NET", - "IN_CLASSD_NSHIFT", - "IN_CLOEXEC", - "IN_CLOSE", - "IN_CLOSE_NOWRITE", - "IN_CLOSE_WRITE", - "IN_CREATE", - "IN_DELETE", - "IN_DELETE_SELF", - "IN_DONT_FOLLOW", - "IN_EXCL_UNLINK", - "IN_IGNORED", - "IN_ISDIR", - "IN_LINKLOCALNETNUM", - "IN_LOOPBACKNET", - "IN_MASK_ADD", - "IN_MODIFY", - "IN_MOVE", - "IN_MOVED_FROM", - "IN_MOVED_TO", - "IN_MOVE_SELF", - "IN_NONBLOCK", - "IN_ONESHOT", - "IN_ONLYDIR", - "IN_OPEN", - "IN_Q_OVERFLOW", - "IN_RFC3021_HOST", - "IN_RFC3021_MASK", - "IN_RFC3021_NET", - "IN_RFC3021_NSHIFT", - "IN_UNMOUNT", - "IOC_IN", - "IOC_INOUT", - "IOC_OUT", - "IOC_VENDOR", - "IOC_WS2", - "IO_REPARSE_TAG_SYMLINK", - "IPMreq", - "IPMreqn", - "IPPROTO_3PC", - "IPPROTO_ADFS", - "IPPROTO_AH", - "IPPROTO_AHIP", - "IPPROTO_APES", - "IPPROTO_ARGUS", - "IPPROTO_AX25", - "IPPROTO_BHA", - "IPPROTO_BLT", - "IPPROTO_BRSATMON", - "IPPROTO_CARP", - "IPPROTO_CFTP", - "IPPROTO_CHAOS", - "IPPROTO_CMTP", - "IPPROTO_COMP", - "IPPROTO_CPHB", - "IPPROTO_CPNX", - "IPPROTO_DCCP", - "IPPROTO_DDP", - "IPPROTO_DGP", - "IPPROTO_DIVERT", - "IPPROTO_DIVERT_INIT", - "IPPROTO_DIVERT_RESP", - "IPPROTO_DONE", - "IPPROTO_DSTOPTS", - "IPPROTO_EGP", - "IPPROTO_EMCON", - "IPPROTO_ENCAP", - "IPPROTO_EON", - "IPPROTO_ESP", - "IPPROTO_ETHERIP", - "IPPROTO_FRAGMENT", - "IPPROTO_GGP", - "IPPROTO_GMTP", - "IPPROTO_GRE", - "IPPROTO_HELLO", - "IPPROTO_HMP", - "IPPROTO_HOPOPTS", - "IPPROTO_ICMP", - "IPPROTO_ICMPV6", - "IPPROTO_IDP", - "IPPROTO_IDPR", - "IPPROTO_IDRP", - "IPPROTO_IGMP", - "IPPROTO_IGP", - "IPPROTO_IGRP", - "IPPROTO_IL", - "IPPROTO_INLSP", - "IPPROTO_INP", - "IPPROTO_IP", - "IPPROTO_IPCOMP", - "IPPROTO_IPCV", - "IPPROTO_IPEIP", - "IPPROTO_IPIP", - "IPPROTO_IPPC", - "IPPROTO_IPV4", - "IPPROTO_IPV6", - "IPPROTO_IPV6_ICMP", - "IPPROTO_IRTP", - "IPPROTO_KRYPTOLAN", - "IPPROTO_LARP", - "IPPROTO_LEAF1", - "IPPROTO_LEAF2", - "IPPROTO_MAX", - "IPPROTO_MAXID", - "IPPROTO_MEAS", - "IPPROTO_MH", - "IPPROTO_MHRP", - "IPPROTO_MICP", - "IPPROTO_MOBILE", - "IPPROTO_MPLS", - "IPPROTO_MTP", - "IPPROTO_MUX", - "IPPROTO_ND", - "IPPROTO_NHRP", - "IPPROTO_NONE", - "IPPROTO_NSP", - "IPPROTO_NVPII", - "IPPROTO_OLD_DIVERT", - "IPPROTO_OSPFIGP", - "IPPROTO_PFSYNC", - "IPPROTO_PGM", - "IPPROTO_PIGP", - "IPPROTO_PIM", - "IPPROTO_PRM", - "IPPROTO_PUP", - "IPPROTO_PVP", - "IPPROTO_RAW", - "IPPROTO_RCCMON", - "IPPROTO_RDP", - "IPPROTO_ROUTING", - "IPPROTO_RSVP", - "IPPROTO_RVD", - "IPPROTO_SATEXPAK", - "IPPROTO_SATMON", - "IPPROTO_SCCSP", - "IPPROTO_SCTP", - "IPPROTO_SDRP", - "IPPROTO_SEND", - "IPPROTO_SEP", - "IPPROTO_SKIP", - "IPPROTO_SPACER", - "IPPROTO_SRPC", - "IPPROTO_ST", - "IPPROTO_SVMTP", - "IPPROTO_SWIPE", - "IPPROTO_TCF", - "IPPROTO_TCP", - "IPPROTO_TLSP", - "IPPROTO_TP", - "IPPROTO_TPXX", - "IPPROTO_TRUNK1", - "IPPROTO_TRUNK2", - "IPPROTO_TTP", - "IPPROTO_UDP", - "IPPROTO_UDPLITE", - "IPPROTO_VINES", - "IPPROTO_VISA", - "IPPROTO_VMTP", - "IPPROTO_VRRP", - "IPPROTO_WBEXPAK", - "IPPROTO_WBMON", - "IPPROTO_WSN", - "IPPROTO_XNET", - "IPPROTO_XTP", - "IPV6_2292DSTOPTS", - "IPV6_2292HOPLIMIT", - "IPV6_2292HOPOPTS", - "IPV6_2292NEXTHOP", - "IPV6_2292PKTINFO", - "IPV6_2292PKTOPTIONS", - "IPV6_2292RTHDR", - "IPV6_ADDRFORM", - "IPV6_ADD_MEMBERSHIP", - "IPV6_AUTHHDR", - "IPV6_AUTH_LEVEL", - "IPV6_AUTOFLOWLABEL", - "IPV6_BINDANY", - "IPV6_BINDV6ONLY", - "IPV6_BOUND_IF", - "IPV6_CHECKSUM", - "IPV6_DEFAULT_MULTICAST_HOPS", - "IPV6_DEFAULT_MULTICAST_LOOP", - "IPV6_DEFHLIM", - "IPV6_DONTFRAG", - "IPV6_DROP_MEMBERSHIP", - "IPV6_DSTOPTS", - "IPV6_ESP_NETWORK_LEVEL", - "IPV6_ESP_TRANS_LEVEL", - "IPV6_FAITH", - "IPV6_FLOWINFO_MASK", - "IPV6_FLOWLABEL_MASK", - "IPV6_FRAGTTL", - "IPV6_FW_ADD", - "IPV6_FW_DEL", - "IPV6_FW_FLUSH", - "IPV6_FW_GET", - "IPV6_FW_ZERO", - "IPV6_HLIMDEC", - "IPV6_HOPLIMIT", - "IPV6_HOPOPTS", - "IPV6_IPCOMP_LEVEL", - "IPV6_IPSEC_POLICY", - "IPV6_JOIN_ANYCAST", - "IPV6_JOIN_GROUP", - "IPV6_LEAVE_ANYCAST", - "IPV6_LEAVE_GROUP", - "IPV6_MAXHLIM", - "IPV6_MAXOPTHDR", - "IPV6_MAXPACKET", - "IPV6_MAX_GROUP_SRC_FILTER", - "IPV6_MAX_MEMBERSHIPS", - "IPV6_MAX_SOCK_SRC_FILTER", - "IPV6_MIN_MEMBERSHIPS", - "IPV6_MMTU", - "IPV6_MSFILTER", - "IPV6_MTU", - "IPV6_MTU_DISCOVER", - "IPV6_MULTICAST_HOPS", - "IPV6_MULTICAST_IF", - "IPV6_MULTICAST_LOOP", - "IPV6_NEXTHOP", - "IPV6_OPTIONS", - "IPV6_PATHMTU", - "IPV6_PIPEX", - "IPV6_PKTINFO", - "IPV6_PMTUDISC_DO", - "IPV6_PMTUDISC_DONT", - "IPV6_PMTUDISC_PROBE", - "IPV6_PMTUDISC_WANT", - "IPV6_PORTRANGE", - "IPV6_PORTRANGE_DEFAULT", - "IPV6_PORTRANGE_HIGH", - "IPV6_PORTRANGE_LOW", - "IPV6_PREFER_TEMPADDR", - "IPV6_RECVDSTOPTS", - "IPV6_RECVDSTPORT", - "IPV6_RECVERR", - "IPV6_RECVHOPLIMIT", - "IPV6_RECVHOPOPTS", - "IPV6_RECVPATHMTU", - "IPV6_RECVPKTINFO", - "IPV6_RECVRTHDR", - "IPV6_RECVTCLASS", - "IPV6_ROUTER_ALERT", - "IPV6_RTABLE", - "IPV6_RTHDR", - "IPV6_RTHDRDSTOPTS", - "IPV6_RTHDR_LOOSE", - "IPV6_RTHDR_STRICT", - "IPV6_RTHDR_TYPE_0", - "IPV6_RXDSTOPTS", - "IPV6_RXHOPOPTS", - "IPV6_SOCKOPT_RESERVED1", - "IPV6_TCLASS", - "IPV6_UNICAST_HOPS", - "IPV6_USE_MIN_MTU", - "IPV6_V6ONLY", - "IPV6_VERSION", - "IPV6_VERSION_MASK", - "IPV6_XFRM_POLICY", - "IP_ADD_MEMBERSHIP", - "IP_ADD_SOURCE_MEMBERSHIP", - "IP_AUTH_LEVEL", - "IP_BINDANY", - "IP_BLOCK_SOURCE", - "IP_BOUND_IF", - "IP_DEFAULT_MULTICAST_LOOP", - "IP_DEFAULT_MULTICAST_TTL", - "IP_DF", - "IP_DIVERTFL", - "IP_DONTFRAG", - "IP_DROP_MEMBERSHIP", - "IP_DROP_SOURCE_MEMBERSHIP", - "IP_DUMMYNET3", - "IP_DUMMYNET_CONFIGURE", - "IP_DUMMYNET_DEL", - "IP_DUMMYNET_FLUSH", - "IP_DUMMYNET_GET", - "IP_EF", - "IP_ERRORMTU", - "IP_ESP_NETWORK_LEVEL", - "IP_ESP_TRANS_LEVEL", - "IP_FAITH", - "IP_FREEBIND", - "IP_FW3", - "IP_FW_ADD", - "IP_FW_DEL", - "IP_FW_FLUSH", - "IP_FW_GET", - "IP_FW_NAT_CFG", - "IP_FW_NAT_DEL", - "IP_FW_NAT_GET_CONFIG", - "IP_FW_NAT_GET_LOG", - "IP_FW_RESETLOG", - "IP_FW_TABLE_ADD", - "IP_FW_TABLE_DEL", - "IP_FW_TABLE_FLUSH", - "IP_FW_TABLE_GETSIZE", - "IP_FW_TABLE_LIST", - "IP_FW_ZERO", - "IP_HDRINCL", - "IP_IPCOMP_LEVEL", - "IP_IPSECFLOWINFO", - "IP_IPSEC_LOCAL_AUTH", - "IP_IPSEC_LOCAL_CRED", - "IP_IPSEC_LOCAL_ID", - "IP_IPSEC_POLICY", - "IP_IPSEC_REMOTE_AUTH", - "IP_IPSEC_REMOTE_CRED", - "IP_IPSEC_REMOTE_ID", - "IP_MAXPACKET", - "IP_MAX_GROUP_SRC_FILTER", - "IP_MAX_MEMBERSHIPS", - "IP_MAX_SOCK_MUTE_FILTER", - "IP_MAX_SOCK_SRC_FILTER", - "IP_MAX_SOURCE_FILTER", - "IP_MF", - "IP_MINFRAGSIZE", - "IP_MINTTL", - "IP_MIN_MEMBERSHIPS", - "IP_MSFILTER", - "IP_MSS", - "IP_MTU", - "IP_MTU_DISCOVER", - "IP_MULTICAST_IF", - "IP_MULTICAST_IFINDEX", - "IP_MULTICAST_LOOP", - "IP_MULTICAST_TTL", - "IP_MULTICAST_VIF", - "IP_NAT__XXX", - "IP_OFFMASK", - "IP_OLD_FW_ADD", - "IP_OLD_FW_DEL", - "IP_OLD_FW_FLUSH", - "IP_OLD_FW_GET", - "IP_OLD_FW_RESETLOG", - "IP_OLD_FW_ZERO", - "IP_ONESBCAST", - "IP_OPTIONS", - "IP_ORIGDSTADDR", - "IP_PASSSEC", - "IP_PIPEX", - "IP_PKTINFO", - "IP_PKTOPTIONS", - "IP_PMTUDISC", - "IP_PMTUDISC_DO", - "IP_PMTUDISC_DONT", - "IP_PMTUDISC_PROBE", - "IP_PMTUDISC_WANT", - "IP_PORTRANGE", - "IP_PORTRANGE_DEFAULT", - "IP_PORTRANGE_HIGH", - "IP_PORTRANGE_LOW", - "IP_RECVDSTADDR", - "IP_RECVDSTPORT", - "IP_RECVERR", - "IP_RECVIF", - "IP_RECVOPTS", - "IP_RECVORIGDSTADDR", - "IP_RECVPKTINFO", - "IP_RECVRETOPTS", - "IP_RECVRTABLE", - "IP_RECVTOS", - "IP_RECVTTL", - "IP_RETOPTS", - "IP_RF", - "IP_ROUTER_ALERT", - "IP_RSVP_OFF", - "IP_RSVP_ON", - "IP_RSVP_VIF_OFF", - "IP_RSVP_VIF_ON", - "IP_RTABLE", - "IP_SENDSRCADDR", - "IP_STRIPHDR", - "IP_TOS", - "IP_TRAFFIC_MGT_BACKGROUND", - "IP_TRANSPARENT", - "IP_TTL", - "IP_UNBLOCK_SOURCE", - "IP_XFRM_POLICY", - "IPv6MTUInfo", - "IPv6Mreq", - "ISIG", - "ISTRIP", - "IUCLC", - "IUTF8", - "IXANY", - "IXOFF", - "IXON", - "IfAddrmsg", - "IfAnnounceMsghdr", - "IfData", - "IfInfomsg", - "IfMsghdr", - "IfaMsghdr", - "IfmaMsghdr", - "IfmaMsghdr2", - "ImplementsGetwd", - "Inet4Pktinfo", - "Inet6Pktinfo", - "InotifyAddWatch", - "InotifyEvent", - "InotifyInit", - "InotifyInit1", - "InotifyRmWatch", - "InterfaceAddrMessage", - "InterfaceAnnounceMessage", - "InterfaceInfo", - "InterfaceMessage", - "InterfaceMulticastAddrMessage", - "InvalidHandle", - "Ioperm", - "Iopl", - "Iovec", - "IpAdapterInfo", - "IpAddrString", - "IpAddressString", - "IpMaskString", - "Issetugid", - "KEY_ALL_ACCESS", - "KEY_CREATE_LINK", - "KEY_CREATE_SUB_KEY", - "KEY_ENUMERATE_SUB_KEYS", - "KEY_EXECUTE", - "KEY_NOTIFY", - "KEY_QUERY_VALUE", - "KEY_READ", - "KEY_SET_VALUE", - "KEY_WOW64_32KEY", - "KEY_WOW64_64KEY", - "KEY_WRITE", - "Kevent", - "Kevent_t", - "Kill", - "Klogctl", - "Kqueue", - "LANG_ENGLISH", - "LAYERED_PROTOCOL", - "LCNT_OVERLOAD_FLUSH", - "LINUX_REBOOT_CMD_CAD_OFF", - "LINUX_REBOOT_CMD_CAD_ON", - "LINUX_REBOOT_CMD_HALT", - "LINUX_REBOOT_CMD_KEXEC", - "LINUX_REBOOT_CMD_POWER_OFF", - "LINUX_REBOOT_CMD_RESTART", - "LINUX_REBOOT_CMD_RESTART2", - "LINUX_REBOOT_CMD_SW_SUSPEND", - "LINUX_REBOOT_MAGIC1", - "LINUX_REBOOT_MAGIC2", - "LOCK_EX", - "LOCK_NB", - "LOCK_SH", - "LOCK_UN", - "LazyDLL", - "LazyProc", - "Lchown", - "Linger", - "Link", - "Listen", - "Listxattr", - "LoadCancelIoEx", - "LoadConnectEx", - "LoadCreateSymbolicLink", - "LoadDLL", - "LoadGetAddrInfo", - "LoadLibrary", - "LoadSetFileCompletionNotificationModes", - "LocalFree", - "Log2phys_t", - "LookupAccountName", - "LookupAccountSid", - "LookupSID", - "LsfJump", - "LsfSocket", - "LsfStmt", - "Lstat", - "MADV_AUTOSYNC", - "MADV_CAN_REUSE", - "MADV_CORE", - "MADV_DOFORK", - "MADV_DONTFORK", - "MADV_DONTNEED", - "MADV_FREE", - "MADV_FREE_REUSABLE", - "MADV_FREE_REUSE", - "MADV_HUGEPAGE", - "MADV_HWPOISON", - "MADV_MERGEABLE", - "MADV_NOCORE", - "MADV_NOHUGEPAGE", - "MADV_NORMAL", - "MADV_NOSYNC", - "MADV_PROTECT", - "MADV_RANDOM", - "MADV_REMOVE", - "MADV_SEQUENTIAL", - "MADV_SPACEAVAIL", - "MADV_UNMERGEABLE", - "MADV_WILLNEED", - "MADV_ZERO_WIRED_PAGES", - "MAP_32BIT", - "MAP_ALIGNED_SUPER", - "MAP_ALIGNMENT_16MB", - "MAP_ALIGNMENT_1TB", - "MAP_ALIGNMENT_256TB", - "MAP_ALIGNMENT_4GB", - "MAP_ALIGNMENT_64KB", - "MAP_ALIGNMENT_64PB", - "MAP_ALIGNMENT_MASK", - "MAP_ALIGNMENT_SHIFT", - "MAP_ANON", - "MAP_ANONYMOUS", - "MAP_COPY", - "MAP_DENYWRITE", - "MAP_EXECUTABLE", - "MAP_FILE", - "MAP_FIXED", - "MAP_FLAGMASK", - "MAP_GROWSDOWN", - "MAP_HASSEMAPHORE", - "MAP_HUGETLB", - "MAP_INHERIT", - "MAP_INHERIT_COPY", - "MAP_INHERIT_DEFAULT", - "MAP_INHERIT_DONATE_COPY", - "MAP_INHERIT_NONE", - "MAP_INHERIT_SHARE", - "MAP_JIT", - "MAP_LOCKED", - "MAP_NOCACHE", - "MAP_NOCORE", - "MAP_NOEXTEND", - "MAP_NONBLOCK", - "MAP_NORESERVE", - "MAP_NOSYNC", - "MAP_POPULATE", - "MAP_PREFAULT_READ", - "MAP_PRIVATE", - "MAP_RENAME", - "MAP_RESERVED0080", - "MAP_RESERVED0100", - "MAP_SHARED", - "MAP_STACK", - "MAP_TRYFIXED", - "MAP_TYPE", - "MAP_WIRED", - "MAXIMUM_REPARSE_DATA_BUFFER_SIZE", - "MAXLEN_IFDESCR", - "MAXLEN_PHYSADDR", - "MAX_ADAPTER_ADDRESS_LENGTH", - "MAX_ADAPTER_DESCRIPTION_LENGTH", - "MAX_ADAPTER_NAME_LENGTH", - "MAX_COMPUTERNAME_LENGTH", - "MAX_INTERFACE_NAME_LEN", - "MAX_LONG_PATH", - "MAX_PATH", - "MAX_PROTOCOL_CHAIN", - "MCL_CURRENT", - "MCL_FUTURE", - "MNT_DETACH", - "MNT_EXPIRE", - "MNT_FORCE", - "MSG_BCAST", - "MSG_CMSG_CLOEXEC", - "MSG_COMPAT", - "MSG_CONFIRM", - "MSG_CONTROLMBUF", - "MSG_CTRUNC", - "MSG_DONTROUTE", - "MSG_DONTWAIT", - "MSG_EOF", - "MSG_EOR", - "MSG_ERRQUEUE", - "MSG_FASTOPEN", - "MSG_FIN", - "MSG_FLUSH", - "MSG_HAVEMORE", - "MSG_HOLD", - "MSG_IOVUSRSPACE", - "MSG_LENUSRSPACE", - "MSG_MCAST", - "MSG_MORE", - "MSG_NAMEMBUF", - "MSG_NBIO", - "MSG_NEEDSA", - "MSG_NOSIGNAL", - "MSG_NOTIFICATION", - "MSG_OOB", - "MSG_PEEK", - "MSG_PROXY", - "MSG_RCVMORE", - "MSG_RST", - "MSG_SEND", - "MSG_SYN", - "MSG_TRUNC", - "MSG_TRYHARD", - "MSG_USERFLAGS", - "MSG_WAITALL", - "MSG_WAITFORONE", - "MSG_WAITSTREAM", - "MS_ACTIVE", - "MS_ASYNC", - "MS_BIND", - "MS_DEACTIVATE", - "MS_DIRSYNC", - "MS_INVALIDATE", - "MS_I_VERSION", - "MS_KERNMOUNT", - "MS_KILLPAGES", - "MS_MANDLOCK", - "MS_MGC_MSK", - "MS_MGC_VAL", - "MS_MOVE", - "MS_NOATIME", - "MS_NODEV", - "MS_NODIRATIME", - "MS_NOEXEC", - "MS_NOSUID", - "MS_NOUSER", - "MS_POSIXACL", - "MS_PRIVATE", - "MS_RDONLY", - "MS_REC", - "MS_RELATIME", - "MS_REMOUNT", - "MS_RMT_MASK", - "MS_SHARED", - "MS_SILENT", - "MS_SLAVE", - "MS_STRICTATIME", - "MS_SYNC", - "MS_SYNCHRONOUS", - "MS_UNBINDABLE", - "Madvise", - "MapViewOfFile", - "MaxTokenInfoClass", - "Mclpool", - "MibIfRow", - "Mkdir", - "Mkdirat", - "Mkfifo", - "Mknod", - "Mknodat", - "Mlock", - "Mlockall", - "Mmap", - "Mount", - "MoveFile", - "Mprotect", - "Msghdr", - "Munlock", - "Munlockall", - "Munmap", - "MustLoadDLL", - "NAME_MAX", - "NETLINK_ADD_MEMBERSHIP", - "NETLINK_AUDIT", - "NETLINK_BROADCAST_ERROR", - "NETLINK_CONNECTOR", - "NETLINK_DNRTMSG", - "NETLINK_DROP_MEMBERSHIP", - "NETLINK_ECRYPTFS", - "NETLINK_FIB_LOOKUP", - "NETLINK_FIREWALL", - "NETLINK_GENERIC", - "NETLINK_INET_DIAG", - "NETLINK_IP6_FW", - "NETLINK_ISCSI", - "NETLINK_KOBJECT_UEVENT", - "NETLINK_NETFILTER", - "NETLINK_NFLOG", - "NETLINK_NO_ENOBUFS", - "NETLINK_PKTINFO", - "NETLINK_RDMA", - "NETLINK_ROUTE", - "NETLINK_SCSITRANSPORT", - "NETLINK_SELINUX", - "NETLINK_UNUSED", - "NETLINK_USERSOCK", - "NETLINK_XFRM", - "NET_RT_DUMP", - "NET_RT_DUMP2", - "NET_RT_FLAGS", - "NET_RT_IFLIST", - "NET_RT_IFLIST2", - "NET_RT_IFLISTL", - "NET_RT_IFMALIST", - "NET_RT_MAXID", - "NET_RT_OIFLIST", - "NET_RT_OOIFLIST", - "NET_RT_STAT", - "NET_RT_STATS", - "NET_RT_TABLE", - "NET_RT_TRASH", - "NLA_ALIGNTO", - "NLA_F_NESTED", - "NLA_F_NET_BYTEORDER", - "NLA_HDRLEN", - "NLMSG_ALIGNTO", - "NLMSG_DONE", - "NLMSG_ERROR", - "NLMSG_HDRLEN", - "NLMSG_MIN_TYPE", - "NLMSG_NOOP", - "NLMSG_OVERRUN", - "NLM_F_ACK", - "NLM_F_APPEND", - "NLM_F_ATOMIC", - "NLM_F_CREATE", - "NLM_F_DUMP", - "NLM_F_ECHO", - "NLM_F_EXCL", - "NLM_F_MATCH", - "NLM_F_MULTI", - "NLM_F_REPLACE", - "NLM_F_REQUEST", - "NLM_F_ROOT", - "NOFLSH", - "NOTE_ABSOLUTE", - "NOTE_ATTRIB", - "NOTE_BACKGROUND", - "NOTE_CHILD", - "NOTE_CRITICAL", - "NOTE_DELETE", - "NOTE_EOF", - "NOTE_EXEC", - "NOTE_EXIT", - "NOTE_EXITSTATUS", - "NOTE_EXIT_CSERROR", - "NOTE_EXIT_DECRYPTFAIL", - "NOTE_EXIT_DETAIL", - "NOTE_EXIT_DETAIL_MASK", - "NOTE_EXIT_MEMORY", - "NOTE_EXIT_REPARENTED", - "NOTE_EXTEND", - "NOTE_FFAND", - "NOTE_FFCOPY", - "NOTE_FFCTRLMASK", - "NOTE_FFLAGSMASK", - "NOTE_FFNOP", - "NOTE_FFOR", - "NOTE_FORK", - "NOTE_LEEWAY", - "NOTE_LINK", - "NOTE_LOWAT", - "NOTE_NONE", - "NOTE_NSECONDS", - "NOTE_PCTRLMASK", - "NOTE_PDATAMASK", - "NOTE_REAP", - "NOTE_RENAME", - "NOTE_RESOURCEEND", - "NOTE_REVOKE", - "NOTE_SECONDS", - "NOTE_SIGNAL", - "NOTE_TRACK", - "NOTE_TRACKERR", - "NOTE_TRIGGER", - "NOTE_TRUNCATE", - "NOTE_USECONDS", - "NOTE_VM_ERROR", - "NOTE_VM_PRESSURE", - "NOTE_VM_PRESSURE_SUDDEN_TERMINATE", - "NOTE_VM_PRESSURE_TERMINATE", - "NOTE_WRITE", - "NameCanonical", - "NameCanonicalEx", - "NameDisplay", - "NameDnsDomain", - "NameFullyQualifiedDN", - "NameSamCompatible", - "NameServicePrincipal", - "NameUniqueId", - "NameUnknown", - "NameUserPrincipal", - "Nanosleep", - "NetApiBufferFree", - "NetGetJoinInformation", - "NetSetupDomainName", - "NetSetupUnjoined", - "NetSetupUnknownStatus", - "NetSetupWorkgroupName", - "NetUserGetInfo", - "NetlinkMessage", - "NetlinkRIB", - "NetlinkRouteAttr", - "NetlinkRouteRequest", - "NewCallback", - "NewCallbackCDecl", - "NewLazyDLL", - "NlAttr", - "NlMsgerr", - "NlMsghdr", - "NsecToFiletime", - "NsecToTimespec", - "NsecToTimeval", - "Ntohs", - "OCRNL", - "OFDEL", - "OFILL", - "OFIOGETBMAP", - "OID_PKIX_KP_SERVER_AUTH", - "OID_SERVER_GATED_CRYPTO", - "OID_SGC_NETSCAPE", - "OLCUC", - "ONLCR", - "ONLRET", - "ONOCR", - "ONOEOT", - "OPEN_ALWAYS", - "OPEN_EXISTING", - "OPOST", - "O_ACCMODE", - "O_ALERT", - "O_ALT_IO", - "O_APPEND", - "O_ASYNC", - "O_CLOEXEC", - "O_CREAT", - "O_DIRECT", - "O_DIRECTORY", - "O_DP_GETRAWENCRYPTED", - "O_DSYNC", - "O_EVTONLY", - "O_EXCL", - "O_EXEC", - "O_EXLOCK", - "O_FSYNC", - "O_LARGEFILE", - "O_NDELAY", - "O_NOATIME", - "O_NOCTTY", - "O_NOFOLLOW", - "O_NONBLOCK", - "O_NOSIGPIPE", - "O_POPUP", - "O_RDONLY", - "O_RDWR", - "O_RSYNC", - "O_SHLOCK", - "O_SYMLINK", - "O_SYNC", - "O_TRUNC", - "O_TTY_INIT", - "O_WRONLY", - "Open", - "OpenCurrentProcessToken", - "OpenProcess", - "OpenProcessToken", - "Openat", - "Overlapped", - "PACKET_ADD_MEMBERSHIP", - "PACKET_BROADCAST", - "PACKET_DROP_MEMBERSHIP", - "PACKET_FASTROUTE", - "PACKET_HOST", - "PACKET_LOOPBACK", - "PACKET_MR_ALLMULTI", - "PACKET_MR_MULTICAST", - "PACKET_MR_PROMISC", - "PACKET_MULTICAST", - "PACKET_OTHERHOST", - "PACKET_OUTGOING", - "PACKET_RECV_OUTPUT", - "PACKET_RX_RING", - "PACKET_STATISTICS", - "PAGE_EXECUTE_READ", - "PAGE_EXECUTE_READWRITE", - "PAGE_EXECUTE_WRITECOPY", - "PAGE_READONLY", - "PAGE_READWRITE", - "PAGE_WRITECOPY", - "PARENB", - "PARMRK", - "PARODD", - "PENDIN", - "PFL_HIDDEN", - "PFL_MATCHES_PROTOCOL_ZERO", - "PFL_MULTIPLE_PROTO_ENTRIES", - "PFL_NETWORKDIRECT_PROVIDER", - "PFL_RECOMMENDED_PROTO_ENTRY", - "PF_FLUSH", - "PKCS_7_ASN_ENCODING", - "PMC5_PIPELINE_FLUSH", - "PRIO_PGRP", - "PRIO_PROCESS", - "PRIO_USER", - "PRI_IOFLUSH", - "PROCESS_QUERY_INFORMATION", - "PROCESS_TERMINATE", - "PROT_EXEC", - "PROT_GROWSDOWN", - "PROT_GROWSUP", - "PROT_NONE", - "PROT_READ", - "PROT_WRITE", - "PROV_DH_SCHANNEL", - "PROV_DSS", - "PROV_DSS_DH", - "PROV_EC_ECDSA_FULL", - "PROV_EC_ECDSA_SIG", - "PROV_EC_ECNRA_FULL", - "PROV_EC_ECNRA_SIG", - "PROV_FORTEZZA", - "PROV_INTEL_SEC", - "PROV_MS_EXCHANGE", - "PROV_REPLACE_OWF", - "PROV_RNG", - "PROV_RSA_AES", - "PROV_RSA_FULL", - "PROV_RSA_SCHANNEL", - "PROV_RSA_SIG", - "PROV_SPYRUS_LYNKS", - "PROV_SSL", - "PR_CAPBSET_DROP", - "PR_CAPBSET_READ", - "PR_CLEAR_SECCOMP_FILTER", - "PR_ENDIAN_BIG", - "PR_ENDIAN_LITTLE", - "PR_ENDIAN_PPC_LITTLE", - "PR_FPEMU_NOPRINT", - "PR_FPEMU_SIGFPE", - "PR_FP_EXC_ASYNC", - "PR_FP_EXC_DISABLED", - "PR_FP_EXC_DIV", - "PR_FP_EXC_INV", - "PR_FP_EXC_NONRECOV", - "PR_FP_EXC_OVF", - "PR_FP_EXC_PRECISE", - "PR_FP_EXC_RES", - "PR_FP_EXC_SW_ENABLE", - "PR_FP_EXC_UND", - "PR_GET_DUMPABLE", - "PR_GET_ENDIAN", - "PR_GET_FPEMU", - "PR_GET_FPEXC", - "PR_GET_KEEPCAPS", - "PR_GET_NAME", - "PR_GET_PDEATHSIG", - "PR_GET_SECCOMP", - "PR_GET_SECCOMP_FILTER", - "PR_GET_SECUREBITS", - "PR_GET_TIMERSLACK", - "PR_GET_TIMING", - "PR_GET_TSC", - "PR_GET_UNALIGN", - "PR_MCE_KILL", - "PR_MCE_KILL_CLEAR", - "PR_MCE_KILL_DEFAULT", - "PR_MCE_KILL_EARLY", - "PR_MCE_KILL_GET", - "PR_MCE_KILL_LATE", - "PR_MCE_KILL_SET", - "PR_SECCOMP_FILTER_EVENT", - "PR_SECCOMP_FILTER_SYSCALL", - "PR_SET_DUMPABLE", - "PR_SET_ENDIAN", - "PR_SET_FPEMU", - "PR_SET_FPEXC", - "PR_SET_KEEPCAPS", - "PR_SET_NAME", - "PR_SET_PDEATHSIG", - "PR_SET_PTRACER", - "PR_SET_SECCOMP", - "PR_SET_SECCOMP_FILTER", - "PR_SET_SECUREBITS", - "PR_SET_TIMERSLACK", - "PR_SET_TIMING", - "PR_SET_TSC", - "PR_SET_UNALIGN", - "PR_TASK_PERF_EVENTS_DISABLE", - "PR_TASK_PERF_EVENTS_ENABLE", - "PR_TIMING_STATISTICAL", - "PR_TIMING_TIMESTAMP", - "PR_TSC_ENABLE", - "PR_TSC_SIGSEGV", - "PR_UNALIGN_NOPRINT", - "PR_UNALIGN_SIGBUS", - "PTRACE_ARCH_PRCTL", - "PTRACE_ATTACH", - "PTRACE_CONT", - "PTRACE_DETACH", - "PTRACE_EVENT_CLONE", - "PTRACE_EVENT_EXEC", - "PTRACE_EVENT_EXIT", - "PTRACE_EVENT_FORK", - "PTRACE_EVENT_VFORK", - "PTRACE_EVENT_VFORK_DONE", - "PTRACE_GETCRUNCHREGS", - "PTRACE_GETEVENTMSG", - "PTRACE_GETFPREGS", - "PTRACE_GETFPXREGS", - "PTRACE_GETHBPREGS", - "PTRACE_GETREGS", - "PTRACE_GETREGSET", - "PTRACE_GETSIGINFO", - "PTRACE_GETVFPREGS", - "PTRACE_GETWMMXREGS", - "PTRACE_GET_THREAD_AREA", - "PTRACE_KILL", - "PTRACE_OLDSETOPTIONS", - "PTRACE_O_MASK", - "PTRACE_O_TRACECLONE", - "PTRACE_O_TRACEEXEC", - "PTRACE_O_TRACEEXIT", - "PTRACE_O_TRACEFORK", - "PTRACE_O_TRACESYSGOOD", - "PTRACE_O_TRACEVFORK", - "PTRACE_O_TRACEVFORKDONE", - "PTRACE_PEEKDATA", - "PTRACE_PEEKTEXT", - "PTRACE_PEEKUSR", - "PTRACE_POKEDATA", - "PTRACE_POKETEXT", - "PTRACE_POKEUSR", - "PTRACE_SETCRUNCHREGS", - "PTRACE_SETFPREGS", - "PTRACE_SETFPXREGS", - "PTRACE_SETHBPREGS", - "PTRACE_SETOPTIONS", - "PTRACE_SETREGS", - "PTRACE_SETREGSET", - "PTRACE_SETSIGINFO", - "PTRACE_SETVFPREGS", - "PTRACE_SETWMMXREGS", - "PTRACE_SET_SYSCALL", - "PTRACE_SET_THREAD_AREA", - "PTRACE_SINGLEBLOCK", - "PTRACE_SINGLESTEP", - "PTRACE_SYSCALL", - "PTRACE_SYSEMU", - "PTRACE_SYSEMU_SINGLESTEP", - "PTRACE_TRACEME", - "PT_ATTACH", - "PT_ATTACHEXC", - "PT_CONTINUE", - "PT_DATA_ADDR", - "PT_DENY_ATTACH", - "PT_DETACH", - "PT_FIRSTMACH", - "PT_FORCEQUOTA", - "PT_KILL", - "PT_MASK", - "PT_READ_D", - "PT_READ_I", - "PT_READ_U", - "PT_SIGEXC", - "PT_STEP", - "PT_TEXT_ADDR", - "PT_TEXT_END_ADDR", - "PT_THUPDATE", - "PT_TRACE_ME", - "PT_WRITE_D", - "PT_WRITE_I", - "PT_WRITE_U", - "ParseDirent", - "ParseNetlinkMessage", - "ParseNetlinkRouteAttr", - "ParseRoutingMessage", - "ParseRoutingSockaddr", - "ParseSocketControlMessage", - "ParseUnixCredentials", - "ParseUnixRights", - "PathMax", - "Pathconf", - "Pause", - "Pipe", - "Pipe2", - "PivotRoot", - "Pointer", - "PostQueuedCompletionStatus", - "Pread", - "Proc", - "ProcAttr", - "Process32First", - "Process32Next", - "ProcessEntry32", - "ProcessInformation", - "Protoent", - "PtraceAttach", - "PtraceCont", - "PtraceDetach", - "PtraceGetEventMsg", - "PtraceGetRegs", - "PtracePeekData", - "PtracePeekText", - "PtracePokeData", - "PtracePokeText", - "PtraceRegs", - "PtraceSetOptions", - "PtraceSetRegs", - "PtraceSingleStep", - "PtraceSyscall", - "Pwrite", - "REG_BINARY", - "REG_DWORD", - "REG_DWORD_BIG_ENDIAN", - "REG_DWORD_LITTLE_ENDIAN", - "REG_EXPAND_SZ", - "REG_FULL_RESOURCE_DESCRIPTOR", - "REG_LINK", - "REG_MULTI_SZ", - "REG_NONE", - "REG_QWORD", - "REG_QWORD_LITTLE_ENDIAN", - "REG_RESOURCE_LIST", - "REG_RESOURCE_REQUIREMENTS_LIST", - "REG_SZ", - "RLIMIT_AS", - "RLIMIT_CORE", - "RLIMIT_CPU", - "RLIMIT_CPU_USAGE_MONITOR", - "RLIMIT_DATA", - "RLIMIT_FSIZE", - "RLIMIT_NOFILE", - "RLIMIT_STACK", - "RLIM_INFINITY", - "RTAX_ADVMSS", - "RTAX_AUTHOR", - "RTAX_BRD", - "RTAX_CWND", - "RTAX_DST", - "RTAX_FEATURES", - "RTAX_FEATURE_ALLFRAG", - "RTAX_FEATURE_ECN", - "RTAX_FEATURE_SACK", - "RTAX_FEATURE_TIMESTAMP", - "RTAX_GATEWAY", - "RTAX_GENMASK", - "RTAX_HOPLIMIT", - "RTAX_IFA", - "RTAX_IFP", - "RTAX_INITCWND", - "RTAX_INITRWND", - "RTAX_LABEL", - "RTAX_LOCK", - "RTAX_MAX", - "RTAX_MTU", - "RTAX_NETMASK", - "RTAX_REORDERING", - "RTAX_RTO_MIN", - "RTAX_RTT", - "RTAX_RTTVAR", - "RTAX_SRC", - "RTAX_SRCMASK", - "RTAX_SSTHRESH", - "RTAX_TAG", - "RTAX_UNSPEC", - "RTAX_WINDOW", - "RTA_ALIGNTO", - "RTA_AUTHOR", - "RTA_BRD", - "RTA_CACHEINFO", - "RTA_DST", - "RTA_FLOW", - "RTA_GATEWAY", - "RTA_GENMASK", - "RTA_IFA", - "RTA_IFP", - "RTA_IIF", - "RTA_LABEL", - "RTA_MAX", - "RTA_METRICS", - "RTA_MULTIPATH", - "RTA_NETMASK", - "RTA_OIF", - "RTA_PREFSRC", - "RTA_PRIORITY", - "RTA_SRC", - "RTA_SRCMASK", - "RTA_TABLE", - "RTA_TAG", - "RTA_UNSPEC", - "RTCF_DIRECTSRC", - "RTCF_DOREDIRECT", - "RTCF_LOG", - "RTCF_MASQ", - "RTCF_NAT", - "RTCF_VALVE", - "RTF_ADDRCLASSMASK", - "RTF_ADDRCONF", - "RTF_ALLONLINK", - "RTF_ANNOUNCE", - "RTF_BLACKHOLE", - "RTF_BROADCAST", - "RTF_CACHE", - "RTF_CLONED", - "RTF_CLONING", - "RTF_CONDEMNED", - "RTF_DEFAULT", - "RTF_DELCLONE", - "RTF_DONE", - "RTF_DYNAMIC", - "RTF_FLOW", - "RTF_FMASK", - "RTF_GATEWAY", - "RTF_GWFLAG_COMPAT", - "RTF_HOST", - "RTF_IFREF", - "RTF_IFSCOPE", - "RTF_INTERFACE", - "RTF_IRTT", - "RTF_LINKRT", - "RTF_LLDATA", - "RTF_LLINFO", - "RTF_LOCAL", - "RTF_MASK", - "RTF_MODIFIED", - "RTF_MPATH", - "RTF_MPLS", - "RTF_MSS", - "RTF_MTU", - "RTF_MULTICAST", - "RTF_NAT", - "RTF_NOFORWARD", - "RTF_NONEXTHOP", - "RTF_NOPMTUDISC", - "RTF_PERMANENT_ARP", - "RTF_PINNED", - "RTF_POLICY", - "RTF_PRCLONING", - "RTF_PROTO1", - "RTF_PROTO2", - "RTF_PROTO3", - "RTF_PROXY", - "RTF_REINSTATE", - "RTF_REJECT", - "RTF_RNH_LOCKED", - "RTF_ROUTER", - "RTF_SOURCE", - "RTF_SRC", - "RTF_STATIC", - "RTF_STICKY", - "RTF_THROW", - "RTF_TUNNEL", - "RTF_UP", - "RTF_USETRAILERS", - "RTF_WASCLONED", - "RTF_WINDOW", - "RTF_XRESOLVE", - "RTM_ADD", - "RTM_BASE", - "RTM_CHANGE", - "RTM_CHGADDR", - "RTM_DELACTION", - "RTM_DELADDR", - "RTM_DELADDRLABEL", - "RTM_DELETE", - "RTM_DELLINK", - "RTM_DELMADDR", - "RTM_DELNEIGH", - "RTM_DELQDISC", - "RTM_DELROUTE", - "RTM_DELRULE", - "RTM_DELTCLASS", - "RTM_DELTFILTER", - "RTM_DESYNC", - "RTM_F_CLONED", - "RTM_F_EQUALIZE", - "RTM_F_NOTIFY", - "RTM_F_PREFIX", - "RTM_GET", - "RTM_GET2", - "RTM_GETACTION", - "RTM_GETADDR", - "RTM_GETADDRLABEL", - "RTM_GETANYCAST", - "RTM_GETDCB", - "RTM_GETLINK", - "RTM_GETMULTICAST", - "RTM_GETNEIGH", - "RTM_GETNEIGHTBL", - "RTM_GETQDISC", - "RTM_GETROUTE", - "RTM_GETRULE", - "RTM_GETTCLASS", - "RTM_GETTFILTER", - "RTM_IEEE80211", - "RTM_IFANNOUNCE", - "RTM_IFINFO", - "RTM_IFINFO2", - "RTM_LLINFO_UPD", - "RTM_LOCK", - "RTM_LOSING", - "RTM_MAX", - "RTM_MAXSIZE", - "RTM_MISS", - "RTM_NEWACTION", - "RTM_NEWADDR", - "RTM_NEWADDRLABEL", - "RTM_NEWLINK", - "RTM_NEWMADDR", - "RTM_NEWMADDR2", - "RTM_NEWNDUSEROPT", - "RTM_NEWNEIGH", - "RTM_NEWNEIGHTBL", - "RTM_NEWPREFIX", - "RTM_NEWQDISC", - "RTM_NEWROUTE", - "RTM_NEWRULE", - "RTM_NEWTCLASS", - "RTM_NEWTFILTER", - "RTM_NR_FAMILIES", - "RTM_NR_MSGTYPES", - "RTM_OIFINFO", - "RTM_OLDADD", - "RTM_OLDDEL", - "RTM_OOIFINFO", - "RTM_REDIRECT", - "RTM_RESOLVE", - "RTM_RTTUNIT", - "RTM_SETDCB", - "RTM_SETGATE", - "RTM_SETLINK", - "RTM_SETNEIGHTBL", - "RTM_VERSION", - "RTNH_ALIGNTO", - "RTNH_F_DEAD", - "RTNH_F_ONLINK", - "RTNH_F_PERVASIVE", - "RTNLGRP_IPV4_IFADDR", - "RTNLGRP_IPV4_MROUTE", - "RTNLGRP_IPV4_ROUTE", - "RTNLGRP_IPV4_RULE", - "RTNLGRP_IPV6_IFADDR", - "RTNLGRP_IPV6_IFINFO", - "RTNLGRP_IPV6_MROUTE", - "RTNLGRP_IPV6_PREFIX", - "RTNLGRP_IPV6_ROUTE", - "RTNLGRP_IPV6_RULE", - "RTNLGRP_LINK", - "RTNLGRP_ND_USEROPT", - "RTNLGRP_NEIGH", - "RTNLGRP_NONE", - "RTNLGRP_NOTIFY", - "RTNLGRP_TC", - "RTN_ANYCAST", - "RTN_BLACKHOLE", - "RTN_BROADCAST", - "RTN_LOCAL", - "RTN_MAX", - "RTN_MULTICAST", - "RTN_NAT", - "RTN_PROHIBIT", - "RTN_THROW", - "RTN_UNICAST", - "RTN_UNREACHABLE", - "RTN_UNSPEC", - "RTN_XRESOLVE", - "RTPROT_BIRD", - "RTPROT_BOOT", - "RTPROT_DHCP", - "RTPROT_DNROUTED", - "RTPROT_GATED", - "RTPROT_KERNEL", - "RTPROT_MRT", - "RTPROT_NTK", - "RTPROT_RA", - "RTPROT_REDIRECT", - "RTPROT_STATIC", - "RTPROT_UNSPEC", - "RTPROT_XORP", - "RTPROT_ZEBRA", - "RTV_EXPIRE", - "RTV_HOPCOUNT", - "RTV_MTU", - "RTV_RPIPE", - "RTV_RTT", - "RTV_RTTVAR", - "RTV_SPIPE", - "RTV_SSTHRESH", - "RTV_WEIGHT", - "RT_CACHING_CONTEXT", - "RT_CLASS_DEFAULT", - "RT_CLASS_LOCAL", - "RT_CLASS_MAIN", - "RT_CLASS_MAX", - "RT_CLASS_UNSPEC", - "RT_DEFAULT_FIB", - "RT_NORTREF", - "RT_SCOPE_HOST", - "RT_SCOPE_LINK", - "RT_SCOPE_NOWHERE", - "RT_SCOPE_SITE", - "RT_SCOPE_UNIVERSE", - "RT_TABLEID_MAX", - "RT_TABLE_COMPAT", - "RT_TABLE_DEFAULT", - "RT_TABLE_LOCAL", - "RT_TABLE_MAIN", - "RT_TABLE_MAX", - "RT_TABLE_UNSPEC", - "RUSAGE_CHILDREN", - "RUSAGE_SELF", - "RUSAGE_THREAD", - "Radvisory_t", - "RawConn", - "RawSockaddr", - "RawSockaddrAny", - "RawSockaddrDatalink", - "RawSockaddrInet4", - "RawSockaddrInet6", - "RawSockaddrLinklayer", - "RawSockaddrNetlink", - "RawSockaddrUnix", - "RawSyscall", - "RawSyscall6", - "Read", - "ReadConsole", - "ReadDirectoryChanges", - "ReadDirent", - "ReadFile", - "Readlink", - "Reboot", - "Recvfrom", - "Recvmsg", - "RegCloseKey", - "RegEnumKeyEx", - "RegOpenKeyEx", - "RegQueryInfoKey", - "RegQueryValueEx", - "RemoveDirectory", - "Removexattr", - "Rename", - "Renameat", - "Revoke", - "Rlimit", - "Rmdir", - "RouteMessage", - "RouteRIB", - "RoutingMessage", - "RtAttr", - "RtGenmsg", - "RtMetrics", - "RtMsg", - "RtMsghdr", - "RtNexthop", - "Rusage", - "SCM_BINTIME", - "SCM_CREDENTIALS", - "SCM_CREDS", - "SCM_RIGHTS", - "SCM_TIMESTAMP", - "SCM_TIMESTAMPING", - "SCM_TIMESTAMPNS", - "SCM_TIMESTAMP_MONOTONIC", - "SHUT_RD", - "SHUT_RDWR", - "SHUT_WR", - "SID", - "SIDAndAttributes", - "SIGABRT", - "SIGALRM", - "SIGBUS", - "SIGCHLD", - "SIGCLD", - "SIGCONT", - "SIGEMT", - "SIGFPE", - "SIGHUP", - "SIGILL", - "SIGINFO", - "SIGINT", - "SIGIO", - "SIGIOT", - "SIGKILL", - "SIGLIBRT", - "SIGLWP", - "SIGPIPE", - "SIGPOLL", - "SIGPROF", - "SIGPWR", - "SIGQUIT", - "SIGSEGV", - "SIGSTKFLT", - "SIGSTOP", - "SIGSYS", - "SIGTERM", - "SIGTHR", - "SIGTRAP", - "SIGTSTP", - "SIGTTIN", - "SIGTTOU", - "SIGUNUSED", - "SIGURG", - "SIGUSR1", - "SIGUSR2", - "SIGVTALRM", - "SIGWINCH", - "SIGXCPU", - "SIGXFSZ", - "SIOCADDDLCI", - "SIOCADDMULTI", - "SIOCADDRT", - "SIOCAIFADDR", - "SIOCAIFGROUP", - "SIOCALIFADDR", - "SIOCARPIPLL", - "SIOCATMARK", - "SIOCAUTOADDR", - "SIOCAUTONETMASK", - "SIOCBRDGADD", - "SIOCBRDGADDS", - "SIOCBRDGARL", - "SIOCBRDGDADDR", - "SIOCBRDGDEL", - "SIOCBRDGDELS", - "SIOCBRDGFLUSH", - "SIOCBRDGFRL", - "SIOCBRDGGCACHE", - "SIOCBRDGGFD", - "SIOCBRDGGHT", - "SIOCBRDGGIFFLGS", - "SIOCBRDGGMA", - "SIOCBRDGGPARAM", - "SIOCBRDGGPRI", - "SIOCBRDGGRL", - "SIOCBRDGGSIFS", - "SIOCBRDGGTO", - "SIOCBRDGIFS", - "SIOCBRDGRTS", - "SIOCBRDGSADDR", - "SIOCBRDGSCACHE", - "SIOCBRDGSFD", - "SIOCBRDGSHT", - "SIOCBRDGSIFCOST", - "SIOCBRDGSIFFLGS", - "SIOCBRDGSIFPRIO", - "SIOCBRDGSMA", - "SIOCBRDGSPRI", - "SIOCBRDGSPROTO", - "SIOCBRDGSTO", - "SIOCBRDGSTXHC", - "SIOCDARP", - "SIOCDELDLCI", - "SIOCDELMULTI", - "SIOCDELRT", - "SIOCDEVPRIVATE", - "SIOCDIFADDR", - "SIOCDIFGROUP", - "SIOCDIFPHYADDR", - "SIOCDLIFADDR", - "SIOCDRARP", - "SIOCGARP", - "SIOCGDRVSPEC", - "SIOCGETKALIVE", - "SIOCGETLABEL", - "SIOCGETPFLOW", - "SIOCGETPFSYNC", - "SIOCGETSGCNT", - "SIOCGETVIFCNT", - "SIOCGETVLAN", - "SIOCGHIWAT", - "SIOCGIFADDR", - "SIOCGIFADDRPREF", - "SIOCGIFALIAS", - "SIOCGIFALTMTU", - "SIOCGIFASYNCMAP", - "SIOCGIFBOND", - "SIOCGIFBR", - "SIOCGIFBRDADDR", - "SIOCGIFCAP", - "SIOCGIFCONF", - "SIOCGIFCOUNT", - "SIOCGIFDATA", - "SIOCGIFDESCR", - "SIOCGIFDEVMTU", - "SIOCGIFDLT", - "SIOCGIFDSTADDR", - "SIOCGIFENCAP", - "SIOCGIFFIB", - "SIOCGIFFLAGS", - "SIOCGIFGATTR", - "SIOCGIFGENERIC", - "SIOCGIFGMEMB", - "SIOCGIFGROUP", - "SIOCGIFHARDMTU", - "SIOCGIFHWADDR", - "SIOCGIFINDEX", - "SIOCGIFKPI", - "SIOCGIFMAC", - "SIOCGIFMAP", - "SIOCGIFMEDIA", - "SIOCGIFMEM", - "SIOCGIFMETRIC", - "SIOCGIFMTU", - "SIOCGIFNAME", - "SIOCGIFNETMASK", - "SIOCGIFPDSTADDR", - "SIOCGIFPFLAGS", - "SIOCGIFPHYS", - "SIOCGIFPRIORITY", - "SIOCGIFPSRCADDR", - "SIOCGIFRDOMAIN", - "SIOCGIFRTLABEL", - "SIOCGIFSLAVE", - "SIOCGIFSTATUS", - "SIOCGIFTIMESLOT", - "SIOCGIFTXQLEN", - "SIOCGIFVLAN", - "SIOCGIFWAKEFLAGS", - "SIOCGIFXFLAGS", - "SIOCGLIFADDR", - "SIOCGLIFPHYADDR", - "SIOCGLIFPHYRTABLE", - "SIOCGLIFPHYTTL", - "SIOCGLINKSTR", - "SIOCGLOWAT", - "SIOCGPGRP", - "SIOCGPRIVATE_0", - "SIOCGPRIVATE_1", - "SIOCGRARP", - "SIOCGSPPPPARAMS", - "SIOCGSTAMP", - "SIOCGSTAMPNS", - "SIOCGVH", - "SIOCGVNETID", - "SIOCIFCREATE", - "SIOCIFCREATE2", - "SIOCIFDESTROY", - "SIOCIFGCLONERS", - "SIOCINITIFADDR", - "SIOCPROTOPRIVATE", - "SIOCRSLVMULTI", - "SIOCRTMSG", - "SIOCSARP", - "SIOCSDRVSPEC", - "SIOCSETKALIVE", - "SIOCSETLABEL", - "SIOCSETPFLOW", - "SIOCSETPFSYNC", - "SIOCSETVLAN", - "SIOCSHIWAT", - "SIOCSIFADDR", - "SIOCSIFADDRPREF", - "SIOCSIFALTMTU", - "SIOCSIFASYNCMAP", - "SIOCSIFBOND", - "SIOCSIFBR", - "SIOCSIFBRDADDR", - "SIOCSIFCAP", - "SIOCSIFDESCR", - "SIOCSIFDSTADDR", - "SIOCSIFENCAP", - "SIOCSIFFIB", - "SIOCSIFFLAGS", - "SIOCSIFGATTR", - "SIOCSIFGENERIC", - "SIOCSIFHWADDR", - "SIOCSIFHWBROADCAST", - "SIOCSIFKPI", - "SIOCSIFLINK", - "SIOCSIFLLADDR", - "SIOCSIFMAC", - "SIOCSIFMAP", - "SIOCSIFMEDIA", - "SIOCSIFMEM", - "SIOCSIFMETRIC", - "SIOCSIFMTU", - "SIOCSIFNAME", - "SIOCSIFNETMASK", - "SIOCSIFPFLAGS", - "SIOCSIFPHYADDR", - "SIOCSIFPHYS", - "SIOCSIFPRIORITY", - "SIOCSIFRDOMAIN", - "SIOCSIFRTLABEL", - "SIOCSIFRVNET", - "SIOCSIFSLAVE", - "SIOCSIFTIMESLOT", - "SIOCSIFTXQLEN", - "SIOCSIFVLAN", - "SIOCSIFVNET", - "SIOCSIFXFLAGS", - "SIOCSLIFPHYADDR", - "SIOCSLIFPHYRTABLE", - "SIOCSLIFPHYTTL", - "SIOCSLINKSTR", - "SIOCSLOWAT", - "SIOCSPGRP", - "SIOCSRARP", - "SIOCSSPPPPARAMS", - "SIOCSVH", - "SIOCSVNETID", - "SIOCZIFDATA", - "SIO_GET_EXTENSION_FUNCTION_POINTER", - "SIO_GET_INTERFACE_LIST", - "SIO_KEEPALIVE_VALS", - "SIO_UDP_CONNRESET", - "SOCK_CLOEXEC", - "SOCK_DCCP", - "SOCK_DGRAM", - "SOCK_FLAGS_MASK", - "SOCK_MAXADDRLEN", - "SOCK_NONBLOCK", - "SOCK_NOSIGPIPE", - "SOCK_PACKET", - "SOCK_RAW", - "SOCK_RDM", - "SOCK_SEQPACKET", - "SOCK_STREAM", - "SOL_AAL", - "SOL_ATM", - "SOL_DECNET", - "SOL_ICMPV6", - "SOL_IP", - "SOL_IPV6", - "SOL_IRDA", - "SOL_PACKET", - "SOL_RAW", - "SOL_SOCKET", - "SOL_TCP", - "SOL_X25", - "SOMAXCONN", - "SO_ACCEPTCONN", - "SO_ACCEPTFILTER", - "SO_ATTACH_FILTER", - "SO_BINDANY", - "SO_BINDTODEVICE", - "SO_BINTIME", - "SO_BROADCAST", - "SO_BSDCOMPAT", - "SO_DEBUG", - "SO_DETACH_FILTER", - "SO_DOMAIN", - "SO_DONTROUTE", - "SO_DONTTRUNC", - "SO_ERROR", - "SO_KEEPALIVE", - "SO_LABEL", - "SO_LINGER", - "SO_LINGER_SEC", - "SO_LISTENINCQLEN", - "SO_LISTENQLEN", - "SO_LISTENQLIMIT", - "SO_MARK", - "SO_NETPROC", - "SO_NKE", - "SO_NOADDRERR", - "SO_NOHEADER", - "SO_NOSIGPIPE", - "SO_NOTIFYCONFLICT", - "SO_NO_CHECK", - "SO_NO_DDP", - "SO_NO_OFFLOAD", - "SO_NP_EXTENSIONS", - "SO_NREAD", - "SO_NUMRCVPKT", - "SO_NWRITE", - "SO_OOBINLINE", - "SO_OVERFLOWED", - "SO_PASSCRED", - "SO_PASSSEC", - "SO_PEERCRED", - "SO_PEERLABEL", - "SO_PEERNAME", - "SO_PEERSEC", - "SO_PRIORITY", - "SO_PROTOCOL", - "SO_PROTOTYPE", - "SO_RANDOMPORT", - "SO_RCVBUF", - "SO_RCVBUFFORCE", - "SO_RCVLOWAT", - "SO_RCVTIMEO", - "SO_RESTRICTIONS", - "SO_RESTRICT_DENYIN", - "SO_RESTRICT_DENYOUT", - "SO_RESTRICT_DENYSET", - "SO_REUSEADDR", - "SO_REUSEPORT", - "SO_REUSESHAREUID", - "SO_RTABLE", - "SO_RXQ_OVFL", - "SO_SECURITY_AUTHENTICATION", - "SO_SECURITY_ENCRYPTION_NETWORK", - "SO_SECURITY_ENCRYPTION_TRANSPORT", - "SO_SETFIB", - "SO_SNDBUF", - "SO_SNDBUFFORCE", - "SO_SNDLOWAT", - "SO_SNDTIMEO", - "SO_SPLICE", - "SO_TIMESTAMP", - "SO_TIMESTAMPING", - "SO_TIMESTAMPNS", - "SO_TIMESTAMP_MONOTONIC", - "SO_TYPE", - "SO_UPCALLCLOSEWAIT", - "SO_UPDATE_ACCEPT_CONTEXT", - "SO_UPDATE_CONNECT_CONTEXT", - "SO_USELOOPBACK", - "SO_USER_COOKIE", - "SO_VENDOR", - "SO_WANTMORE", - "SO_WANTOOBFLAG", - "SSLExtraCertChainPolicyPara", - "STANDARD_RIGHTS_ALL", - "STANDARD_RIGHTS_EXECUTE", - "STANDARD_RIGHTS_READ", - "STANDARD_RIGHTS_REQUIRED", - "STANDARD_RIGHTS_WRITE", - "STARTF_USESHOWWINDOW", - "STARTF_USESTDHANDLES", - "STD_ERROR_HANDLE", - "STD_INPUT_HANDLE", - "STD_OUTPUT_HANDLE", - "SUBLANG_ENGLISH_US", - "SW_FORCEMINIMIZE", - "SW_HIDE", - "SW_MAXIMIZE", - "SW_MINIMIZE", - "SW_NORMAL", - "SW_RESTORE", - "SW_SHOW", - "SW_SHOWDEFAULT", - "SW_SHOWMAXIMIZED", - "SW_SHOWMINIMIZED", - "SW_SHOWMINNOACTIVE", - "SW_SHOWNA", - "SW_SHOWNOACTIVATE", - "SW_SHOWNORMAL", - "SYMBOLIC_LINK_FLAG_DIRECTORY", - "SYNCHRONIZE", - "SYSCTL_VERSION", - "SYSCTL_VERS_0", - "SYSCTL_VERS_1", - "SYSCTL_VERS_MASK", - "SYS_ABORT2", - "SYS_ACCEPT", - "SYS_ACCEPT4", - "SYS_ACCEPT_NOCANCEL", - "SYS_ACCESS", - "SYS_ACCESS_EXTENDED", - "SYS_ACCT", - "SYS_ADD_KEY", - "SYS_ADD_PROFIL", - "SYS_ADJFREQ", - "SYS_ADJTIME", - "SYS_ADJTIMEX", - "SYS_AFS_SYSCALL", - "SYS_AIO_CANCEL", - "SYS_AIO_ERROR", - "SYS_AIO_FSYNC", - "SYS_AIO_MLOCK", - "SYS_AIO_READ", - "SYS_AIO_RETURN", - "SYS_AIO_SUSPEND", - "SYS_AIO_SUSPEND_NOCANCEL", - "SYS_AIO_WAITCOMPLETE", - "SYS_AIO_WRITE", - "SYS_ALARM", - "SYS_ARCH_PRCTL", - "SYS_ARM_FADVISE64_64", - "SYS_ARM_SYNC_FILE_RANGE", - "SYS_ATGETMSG", - "SYS_ATPGETREQ", - "SYS_ATPGETRSP", - "SYS_ATPSNDREQ", - "SYS_ATPSNDRSP", - "SYS_ATPUTMSG", - "SYS_ATSOCKET", - "SYS_AUDIT", - "SYS_AUDITCTL", - "SYS_AUDITON", - "SYS_AUDIT_SESSION_JOIN", - "SYS_AUDIT_SESSION_PORT", - "SYS_AUDIT_SESSION_SELF", - "SYS_BDFLUSH", - "SYS_BIND", - "SYS_BINDAT", - "SYS_BREAK", - "SYS_BRK", - "SYS_BSDTHREAD_CREATE", - "SYS_BSDTHREAD_REGISTER", - "SYS_BSDTHREAD_TERMINATE", - "SYS_CAPGET", - "SYS_CAPSET", - "SYS_CAP_ENTER", - "SYS_CAP_FCNTLS_GET", - "SYS_CAP_FCNTLS_LIMIT", - "SYS_CAP_GETMODE", - "SYS_CAP_GETRIGHTS", - "SYS_CAP_IOCTLS_GET", - "SYS_CAP_IOCTLS_LIMIT", - "SYS_CAP_NEW", - "SYS_CAP_RIGHTS_GET", - "SYS_CAP_RIGHTS_LIMIT", - "SYS_CHDIR", - "SYS_CHFLAGS", - "SYS_CHFLAGSAT", - "SYS_CHMOD", - "SYS_CHMOD_EXTENDED", - "SYS_CHOWN", - "SYS_CHOWN32", - "SYS_CHROOT", - "SYS_CHUD", - "SYS_CLOCK_ADJTIME", - "SYS_CLOCK_GETCPUCLOCKID2", - "SYS_CLOCK_GETRES", - "SYS_CLOCK_GETTIME", - "SYS_CLOCK_NANOSLEEP", - "SYS_CLOCK_SETTIME", - "SYS_CLONE", - "SYS_CLOSE", - "SYS_CLOSEFROM", - "SYS_CLOSE_NOCANCEL", - "SYS_CONNECT", - "SYS_CONNECTAT", - "SYS_CONNECT_NOCANCEL", - "SYS_COPYFILE", - "SYS_CPUSET", - "SYS_CPUSET_GETAFFINITY", - "SYS_CPUSET_GETID", - "SYS_CPUSET_SETAFFINITY", - "SYS_CPUSET_SETID", - "SYS_CREAT", - "SYS_CREATE_MODULE", - "SYS_CSOPS", - "SYS_CSOPS_AUDITTOKEN", - "SYS_DELETE", - "SYS_DELETE_MODULE", - "SYS_DUP", - "SYS_DUP2", - "SYS_DUP3", - "SYS_EACCESS", - "SYS_EPOLL_CREATE", - "SYS_EPOLL_CREATE1", - "SYS_EPOLL_CTL", - "SYS_EPOLL_CTL_OLD", - "SYS_EPOLL_PWAIT", - "SYS_EPOLL_WAIT", - "SYS_EPOLL_WAIT_OLD", - "SYS_EVENTFD", - "SYS_EVENTFD2", - "SYS_EXCHANGEDATA", - "SYS_EXECVE", - "SYS_EXIT", - "SYS_EXIT_GROUP", - "SYS_EXTATTRCTL", - "SYS_EXTATTR_DELETE_FD", - "SYS_EXTATTR_DELETE_FILE", - "SYS_EXTATTR_DELETE_LINK", - "SYS_EXTATTR_GET_FD", - "SYS_EXTATTR_GET_FILE", - "SYS_EXTATTR_GET_LINK", - "SYS_EXTATTR_LIST_FD", - "SYS_EXTATTR_LIST_FILE", - "SYS_EXTATTR_LIST_LINK", - "SYS_EXTATTR_SET_FD", - "SYS_EXTATTR_SET_FILE", - "SYS_EXTATTR_SET_LINK", - "SYS_FACCESSAT", - "SYS_FADVISE64", - "SYS_FADVISE64_64", - "SYS_FALLOCATE", - "SYS_FANOTIFY_INIT", - "SYS_FANOTIFY_MARK", - "SYS_FCHDIR", - "SYS_FCHFLAGS", - "SYS_FCHMOD", - "SYS_FCHMODAT", - "SYS_FCHMOD_EXTENDED", - "SYS_FCHOWN", - "SYS_FCHOWN32", - "SYS_FCHOWNAT", - "SYS_FCHROOT", - "SYS_FCNTL", - "SYS_FCNTL64", - "SYS_FCNTL_NOCANCEL", - "SYS_FDATASYNC", - "SYS_FEXECVE", - "SYS_FFCLOCK_GETCOUNTER", - "SYS_FFCLOCK_GETESTIMATE", - "SYS_FFCLOCK_SETESTIMATE", - "SYS_FFSCTL", - "SYS_FGETATTRLIST", - "SYS_FGETXATTR", - "SYS_FHOPEN", - "SYS_FHSTAT", - "SYS_FHSTATFS", - "SYS_FILEPORT_MAKEFD", - "SYS_FILEPORT_MAKEPORT", - "SYS_FKTRACE", - "SYS_FLISTXATTR", - "SYS_FLOCK", - "SYS_FORK", - "SYS_FPATHCONF", - "SYS_FREEBSD6_FTRUNCATE", - "SYS_FREEBSD6_LSEEK", - "SYS_FREEBSD6_MMAP", - "SYS_FREEBSD6_PREAD", - "SYS_FREEBSD6_PWRITE", - "SYS_FREEBSD6_TRUNCATE", - "SYS_FREMOVEXATTR", - "SYS_FSCTL", - "SYS_FSETATTRLIST", - "SYS_FSETXATTR", - "SYS_FSGETPATH", - "SYS_FSTAT", - "SYS_FSTAT64", - "SYS_FSTAT64_EXTENDED", - "SYS_FSTATAT", - "SYS_FSTATAT64", - "SYS_FSTATFS", - "SYS_FSTATFS64", - "SYS_FSTATV", - "SYS_FSTATVFS1", - "SYS_FSTAT_EXTENDED", - "SYS_FSYNC", - "SYS_FSYNC_NOCANCEL", - "SYS_FSYNC_RANGE", - "SYS_FTIME", - "SYS_FTRUNCATE", - "SYS_FTRUNCATE64", - "SYS_FUTEX", - "SYS_FUTIMENS", - "SYS_FUTIMES", - "SYS_FUTIMESAT", - "SYS_GETATTRLIST", - "SYS_GETAUDIT", - "SYS_GETAUDIT_ADDR", - "SYS_GETAUID", - "SYS_GETCONTEXT", - "SYS_GETCPU", - "SYS_GETCWD", - "SYS_GETDENTS", - "SYS_GETDENTS64", - "SYS_GETDIRENTRIES", - "SYS_GETDIRENTRIES64", - "SYS_GETDIRENTRIESATTR", - "SYS_GETDTABLECOUNT", - "SYS_GETDTABLESIZE", - "SYS_GETEGID", - "SYS_GETEGID32", - "SYS_GETEUID", - "SYS_GETEUID32", - "SYS_GETFH", - "SYS_GETFSSTAT", - "SYS_GETFSSTAT64", - "SYS_GETGID", - "SYS_GETGID32", - "SYS_GETGROUPS", - "SYS_GETGROUPS32", - "SYS_GETHOSTUUID", - "SYS_GETITIMER", - "SYS_GETLCID", - "SYS_GETLOGIN", - "SYS_GETLOGINCLASS", - "SYS_GETPEERNAME", - "SYS_GETPGID", - "SYS_GETPGRP", - "SYS_GETPID", - "SYS_GETPMSG", - "SYS_GETPPID", - "SYS_GETPRIORITY", - "SYS_GETRESGID", - "SYS_GETRESGID32", - "SYS_GETRESUID", - "SYS_GETRESUID32", - "SYS_GETRLIMIT", - "SYS_GETRTABLE", - "SYS_GETRUSAGE", - "SYS_GETSGROUPS", - "SYS_GETSID", - "SYS_GETSOCKNAME", - "SYS_GETSOCKOPT", - "SYS_GETTHRID", - "SYS_GETTID", - "SYS_GETTIMEOFDAY", - "SYS_GETUID", - "SYS_GETUID32", - "SYS_GETVFSSTAT", - "SYS_GETWGROUPS", - "SYS_GETXATTR", - "SYS_GET_KERNEL_SYMS", - "SYS_GET_MEMPOLICY", - "SYS_GET_ROBUST_LIST", - "SYS_GET_THREAD_AREA", - "SYS_GSSD_SYSCALL", - "SYS_GTTY", - "SYS_IDENTITYSVC", - "SYS_IDLE", - "SYS_INITGROUPS", - "SYS_INIT_MODULE", - "SYS_INOTIFY_ADD_WATCH", - "SYS_INOTIFY_INIT", - "SYS_INOTIFY_INIT1", - "SYS_INOTIFY_RM_WATCH", - "SYS_IOCTL", - "SYS_IOPERM", - "SYS_IOPL", - "SYS_IOPOLICYSYS", - "SYS_IOPRIO_GET", - "SYS_IOPRIO_SET", - "SYS_IO_CANCEL", - "SYS_IO_DESTROY", - "SYS_IO_GETEVENTS", - "SYS_IO_SETUP", - "SYS_IO_SUBMIT", - "SYS_IPC", - "SYS_ISSETUGID", - "SYS_JAIL", - "SYS_JAIL_ATTACH", - "SYS_JAIL_GET", - "SYS_JAIL_REMOVE", - "SYS_JAIL_SET", - "SYS_KAS_INFO", - "SYS_KDEBUG_TRACE", - "SYS_KENV", - "SYS_KEVENT", - "SYS_KEVENT64", - "SYS_KEXEC_LOAD", - "SYS_KEYCTL", - "SYS_KILL", - "SYS_KLDFIND", - "SYS_KLDFIRSTMOD", - "SYS_KLDLOAD", - "SYS_KLDNEXT", - "SYS_KLDSTAT", - "SYS_KLDSYM", - "SYS_KLDUNLOAD", - "SYS_KLDUNLOADF", - "SYS_KMQ_NOTIFY", - "SYS_KMQ_OPEN", - "SYS_KMQ_SETATTR", - "SYS_KMQ_TIMEDRECEIVE", - "SYS_KMQ_TIMEDSEND", - "SYS_KMQ_UNLINK", - "SYS_KQUEUE", - "SYS_KQUEUE1", - "SYS_KSEM_CLOSE", - "SYS_KSEM_DESTROY", - "SYS_KSEM_GETVALUE", - "SYS_KSEM_INIT", - "SYS_KSEM_OPEN", - "SYS_KSEM_POST", - "SYS_KSEM_TIMEDWAIT", - "SYS_KSEM_TRYWAIT", - "SYS_KSEM_UNLINK", - "SYS_KSEM_WAIT", - "SYS_KTIMER_CREATE", - "SYS_KTIMER_DELETE", - "SYS_KTIMER_GETOVERRUN", - "SYS_KTIMER_GETTIME", - "SYS_KTIMER_SETTIME", - "SYS_KTRACE", - "SYS_LCHFLAGS", - "SYS_LCHMOD", - "SYS_LCHOWN", - "SYS_LCHOWN32", - "SYS_LEDGER", - "SYS_LGETFH", - "SYS_LGETXATTR", - "SYS_LINK", - "SYS_LINKAT", - "SYS_LIO_LISTIO", - "SYS_LISTEN", - "SYS_LISTXATTR", - "SYS_LLISTXATTR", - "SYS_LOCK", - "SYS_LOOKUP_DCOOKIE", - "SYS_LPATHCONF", - "SYS_LREMOVEXATTR", - "SYS_LSEEK", - "SYS_LSETXATTR", - "SYS_LSTAT", - "SYS_LSTAT64", - "SYS_LSTAT64_EXTENDED", - "SYS_LSTATV", - "SYS_LSTAT_EXTENDED", - "SYS_LUTIMES", - "SYS_MAC_SYSCALL", - "SYS_MADVISE", - "SYS_MADVISE1", - "SYS_MAXSYSCALL", - "SYS_MBIND", - "SYS_MIGRATE_PAGES", - "SYS_MINCORE", - "SYS_MINHERIT", - "SYS_MKCOMPLEX", - "SYS_MKDIR", - "SYS_MKDIRAT", - "SYS_MKDIR_EXTENDED", - "SYS_MKFIFO", - "SYS_MKFIFOAT", - "SYS_MKFIFO_EXTENDED", - "SYS_MKNOD", - "SYS_MKNODAT", - "SYS_MLOCK", - "SYS_MLOCKALL", - "SYS_MMAP", - "SYS_MMAP2", - "SYS_MODCTL", - "SYS_MODFIND", - "SYS_MODFNEXT", - "SYS_MODIFY_LDT", - "SYS_MODNEXT", - "SYS_MODSTAT", - "SYS_MODWATCH", - "SYS_MOUNT", - "SYS_MOVE_PAGES", - "SYS_MPROTECT", - "SYS_MPX", - "SYS_MQUERY", - "SYS_MQ_GETSETATTR", - "SYS_MQ_NOTIFY", - "SYS_MQ_OPEN", - "SYS_MQ_TIMEDRECEIVE", - "SYS_MQ_TIMEDSEND", - "SYS_MQ_UNLINK", - "SYS_MREMAP", - "SYS_MSGCTL", - "SYS_MSGGET", - "SYS_MSGRCV", - "SYS_MSGRCV_NOCANCEL", - "SYS_MSGSND", - "SYS_MSGSND_NOCANCEL", - "SYS_MSGSYS", - "SYS_MSYNC", - "SYS_MSYNC_NOCANCEL", - "SYS_MUNLOCK", - "SYS_MUNLOCKALL", - "SYS_MUNMAP", - "SYS_NAME_TO_HANDLE_AT", - "SYS_NANOSLEEP", - "SYS_NEWFSTATAT", - "SYS_NFSCLNT", - "SYS_NFSSERVCTL", - "SYS_NFSSVC", - "SYS_NFSTAT", - "SYS_NICE", - "SYS_NLM_SYSCALL", - "SYS_NLSTAT", - "SYS_NMOUNT", - "SYS_NSTAT", - "SYS_NTP_ADJTIME", - "SYS_NTP_GETTIME", - "SYS_NUMA_GETAFFINITY", - "SYS_NUMA_SETAFFINITY", - "SYS_OABI_SYSCALL_BASE", - "SYS_OBREAK", - "SYS_OLDFSTAT", - "SYS_OLDLSTAT", - "SYS_OLDOLDUNAME", - "SYS_OLDSTAT", - "SYS_OLDUNAME", - "SYS_OPEN", - "SYS_OPENAT", - "SYS_OPENBSD_POLL", - "SYS_OPEN_BY_HANDLE_AT", - "SYS_OPEN_DPROTECTED_NP", - "SYS_OPEN_EXTENDED", - "SYS_OPEN_NOCANCEL", - "SYS_OVADVISE", - "SYS_PACCEPT", - "SYS_PATHCONF", - "SYS_PAUSE", - "SYS_PCICONFIG_IOBASE", - "SYS_PCICONFIG_READ", - "SYS_PCICONFIG_WRITE", - "SYS_PDFORK", - "SYS_PDGETPID", - "SYS_PDKILL", - "SYS_PERF_EVENT_OPEN", - "SYS_PERSONALITY", - "SYS_PID_HIBERNATE", - "SYS_PID_RESUME", - "SYS_PID_SHUTDOWN_SOCKETS", - "SYS_PID_SUSPEND", - "SYS_PIPE", - "SYS_PIPE2", - "SYS_PIVOT_ROOT", - "SYS_PMC_CONTROL", - "SYS_PMC_GET_INFO", - "SYS_POLL", - "SYS_POLLTS", - "SYS_POLL_NOCANCEL", - "SYS_POSIX_FADVISE", - "SYS_POSIX_FALLOCATE", - "SYS_POSIX_OPENPT", - "SYS_POSIX_SPAWN", - "SYS_PPOLL", - "SYS_PRCTL", - "SYS_PREAD", - "SYS_PREAD64", - "SYS_PREADV", - "SYS_PREAD_NOCANCEL", - "SYS_PRLIMIT64", - "SYS_PROCCTL", - "SYS_PROCESS_POLICY", - "SYS_PROCESS_VM_READV", - "SYS_PROCESS_VM_WRITEV", - "SYS_PROC_INFO", - "SYS_PROF", - "SYS_PROFIL", - "SYS_PSELECT", - "SYS_PSELECT6", - "SYS_PSET_ASSIGN", - "SYS_PSET_CREATE", - "SYS_PSET_DESTROY", - "SYS_PSYNCH_CVBROAD", - "SYS_PSYNCH_CVCLRPREPOST", - "SYS_PSYNCH_CVSIGNAL", - "SYS_PSYNCH_CVWAIT", - "SYS_PSYNCH_MUTEXDROP", - "SYS_PSYNCH_MUTEXWAIT", - "SYS_PSYNCH_RW_DOWNGRADE", - "SYS_PSYNCH_RW_LONGRDLOCK", - "SYS_PSYNCH_RW_RDLOCK", - "SYS_PSYNCH_RW_UNLOCK", - "SYS_PSYNCH_RW_UNLOCK2", - "SYS_PSYNCH_RW_UPGRADE", - "SYS_PSYNCH_RW_WRLOCK", - "SYS_PSYNCH_RW_YIELDWRLOCK", - "SYS_PTRACE", - "SYS_PUTPMSG", - "SYS_PWRITE", - "SYS_PWRITE64", - "SYS_PWRITEV", - "SYS_PWRITE_NOCANCEL", - "SYS_QUERY_MODULE", - "SYS_QUOTACTL", - "SYS_RASCTL", - "SYS_RCTL_ADD_RULE", - "SYS_RCTL_GET_LIMITS", - "SYS_RCTL_GET_RACCT", - "SYS_RCTL_GET_RULES", - "SYS_RCTL_REMOVE_RULE", - "SYS_READ", - "SYS_READAHEAD", - "SYS_READDIR", - "SYS_READLINK", - "SYS_READLINKAT", - "SYS_READV", - "SYS_READV_NOCANCEL", - "SYS_READ_NOCANCEL", - "SYS_REBOOT", - "SYS_RECV", - "SYS_RECVFROM", - "SYS_RECVFROM_NOCANCEL", - "SYS_RECVMMSG", - "SYS_RECVMSG", - "SYS_RECVMSG_NOCANCEL", - "SYS_REMAP_FILE_PAGES", - "SYS_REMOVEXATTR", - "SYS_RENAME", - "SYS_RENAMEAT", - "SYS_REQUEST_KEY", - "SYS_RESTART_SYSCALL", - "SYS_REVOKE", - "SYS_RFORK", - "SYS_RMDIR", - "SYS_RTPRIO", - "SYS_RTPRIO_THREAD", - "SYS_RT_SIGACTION", - "SYS_RT_SIGPENDING", - "SYS_RT_SIGPROCMASK", - "SYS_RT_SIGQUEUEINFO", - "SYS_RT_SIGRETURN", - "SYS_RT_SIGSUSPEND", - "SYS_RT_SIGTIMEDWAIT", - "SYS_RT_TGSIGQUEUEINFO", - "SYS_SBRK", - "SYS_SCHED_GETAFFINITY", - "SYS_SCHED_GETPARAM", - "SYS_SCHED_GETSCHEDULER", - "SYS_SCHED_GET_PRIORITY_MAX", - "SYS_SCHED_GET_PRIORITY_MIN", - "SYS_SCHED_RR_GET_INTERVAL", - "SYS_SCHED_SETAFFINITY", - "SYS_SCHED_SETPARAM", - "SYS_SCHED_SETSCHEDULER", - "SYS_SCHED_YIELD", - "SYS_SCTP_GENERIC_RECVMSG", - "SYS_SCTP_GENERIC_SENDMSG", - "SYS_SCTP_GENERIC_SENDMSG_IOV", - "SYS_SCTP_PEELOFF", - "SYS_SEARCHFS", - "SYS_SECURITY", - "SYS_SELECT", - "SYS_SELECT_NOCANCEL", - "SYS_SEMCONFIG", - "SYS_SEMCTL", - "SYS_SEMGET", - "SYS_SEMOP", - "SYS_SEMSYS", - "SYS_SEMTIMEDOP", - "SYS_SEM_CLOSE", - "SYS_SEM_DESTROY", - "SYS_SEM_GETVALUE", - "SYS_SEM_INIT", - "SYS_SEM_OPEN", - "SYS_SEM_POST", - "SYS_SEM_TRYWAIT", - "SYS_SEM_UNLINK", - "SYS_SEM_WAIT", - "SYS_SEM_WAIT_NOCANCEL", - "SYS_SEND", - "SYS_SENDFILE", - "SYS_SENDFILE64", - "SYS_SENDMMSG", - "SYS_SENDMSG", - "SYS_SENDMSG_NOCANCEL", - "SYS_SENDTO", - "SYS_SENDTO_NOCANCEL", - "SYS_SETATTRLIST", - "SYS_SETAUDIT", - "SYS_SETAUDIT_ADDR", - "SYS_SETAUID", - "SYS_SETCONTEXT", - "SYS_SETDOMAINNAME", - "SYS_SETEGID", - "SYS_SETEUID", - "SYS_SETFIB", - "SYS_SETFSGID", - "SYS_SETFSGID32", - "SYS_SETFSUID", - "SYS_SETFSUID32", - "SYS_SETGID", - "SYS_SETGID32", - "SYS_SETGROUPS", - "SYS_SETGROUPS32", - "SYS_SETHOSTNAME", - "SYS_SETITIMER", - "SYS_SETLCID", - "SYS_SETLOGIN", - "SYS_SETLOGINCLASS", - "SYS_SETNS", - "SYS_SETPGID", - "SYS_SETPRIORITY", - "SYS_SETPRIVEXEC", - "SYS_SETREGID", - "SYS_SETREGID32", - "SYS_SETRESGID", - "SYS_SETRESGID32", - "SYS_SETRESUID", - "SYS_SETRESUID32", - "SYS_SETREUID", - "SYS_SETREUID32", - "SYS_SETRLIMIT", - "SYS_SETRTABLE", - "SYS_SETSGROUPS", - "SYS_SETSID", - "SYS_SETSOCKOPT", - "SYS_SETTID", - "SYS_SETTID_WITH_PID", - "SYS_SETTIMEOFDAY", - "SYS_SETUID", - "SYS_SETUID32", - "SYS_SETWGROUPS", - "SYS_SETXATTR", - "SYS_SET_MEMPOLICY", - "SYS_SET_ROBUST_LIST", - "SYS_SET_THREAD_AREA", - "SYS_SET_TID_ADDRESS", - "SYS_SGETMASK", - "SYS_SHARED_REGION_CHECK_NP", - "SYS_SHARED_REGION_MAP_AND_SLIDE_NP", - "SYS_SHMAT", - "SYS_SHMCTL", - "SYS_SHMDT", - "SYS_SHMGET", - "SYS_SHMSYS", - "SYS_SHM_OPEN", - "SYS_SHM_UNLINK", - "SYS_SHUTDOWN", - "SYS_SIGACTION", - "SYS_SIGALTSTACK", - "SYS_SIGNAL", - "SYS_SIGNALFD", - "SYS_SIGNALFD4", - "SYS_SIGPENDING", - "SYS_SIGPROCMASK", - "SYS_SIGQUEUE", - "SYS_SIGQUEUEINFO", - "SYS_SIGRETURN", - "SYS_SIGSUSPEND", - "SYS_SIGSUSPEND_NOCANCEL", - "SYS_SIGTIMEDWAIT", - "SYS_SIGWAIT", - "SYS_SIGWAITINFO", - "SYS_SOCKET", - "SYS_SOCKETCALL", - "SYS_SOCKETPAIR", - "SYS_SPLICE", - "SYS_SSETMASK", - "SYS_SSTK", - "SYS_STACK_SNAPSHOT", - "SYS_STAT", - "SYS_STAT64", - "SYS_STAT64_EXTENDED", - "SYS_STATFS", - "SYS_STATFS64", - "SYS_STATV", - "SYS_STATVFS1", - "SYS_STAT_EXTENDED", - "SYS_STIME", - "SYS_STTY", - "SYS_SWAPCONTEXT", - "SYS_SWAPCTL", - "SYS_SWAPOFF", - "SYS_SWAPON", - "SYS_SYMLINK", - "SYS_SYMLINKAT", - "SYS_SYNC", - "SYS_SYNCFS", - "SYS_SYNC_FILE_RANGE", - "SYS_SYSARCH", - "SYS_SYSCALL", - "SYS_SYSCALL_BASE", - "SYS_SYSFS", - "SYS_SYSINFO", - "SYS_SYSLOG", - "SYS_TEE", - "SYS_TGKILL", - "SYS_THREAD_SELFID", - "SYS_THR_CREATE", - "SYS_THR_EXIT", - "SYS_THR_KILL", - "SYS_THR_KILL2", - "SYS_THR_NEW", - "SYS_THR_SELF", - "SYS_THR_SET_NAME", - "SYS_THR_SUSPEND", - "SYS_THR_WAKE", - "SYS_TIME", - "SYS_TIMERFD_CREATE", - "SYS_TIMERFD_GETTIME", - "SYS_TIMERFD_SETTIME", - "SYS_TIMER_CREATE", - "SYS_TIMER_DELETE", - "SYS_TIMER_GETOVERRUN", - "SYS_TIMER_GETTIME", - "SYS_TIMER_SETTIME", - "SYS_TIMES", - "SYS_TKILL", - "SYS_TRUNCATE", - "SYS_TRUNCATE64", - "SYS_TUXCALL", - "SYS_UGETRLIMIT", - "SYS_ULIMIT", - "SYS_UMASK", - "SYS_UMASK_EXTENDED", - "SYS_UMOUNT", - "SYS_UMOUNT2", - "SYS_UNAME", - "SYS_UNDELETE", - "SYS_UNLINK", - "SYS_UNLINKAT", - "SYS_UNMOUNT", - "SYS_UNSHARE", - "SYS_USELIB", - "SYS_USTAT", - "SYS_UTIME", - "SYS_UTIMENSAT", - "SYS_UTIMES", - "SYS_UTRACE", - "SYS_UUIDGEN", - "SYS_VADVISE", - "SYS_VFORK", - "SYS_VHANGUP", - "SYS_VM86", - "SYS_VM86OLD", - "SYS_VMSPLICE", - "SYS_VM_PRESSURE_MONITOR", - "SYS_VSERVER", - "SYS_WAIT4", - "SYS_WAIT4_NOCANCEL", - "SYS_WAIT6", - "SYS_WAITEVENT", - "SYS_WAITID", - "SYS_WAITID_NOCANCEL", - "SYS_WAITPID", - "SYS_WATCHEVENT", - "SYS_WORKQ_KERNRETURN", - "SYS_WORKQ_OPEN", - "SYS_WRITE", - "SYS_WRITEV", - "SYS_WRITEV_NOCANCEL", - "SYS_WRITE_NOCANCEL", - "SYS_YIELD", - "SYS__LLSEEK", - "SYS__LWP_CONTINUE", - "SYS__LWP_CREATE", - "SYS__LWP_CTL", - "SYS__LWP_DETACH", - "SYS__LWP_EXIT", - "SYS__LWP_GETNAME", - "SYS__LWP_GETPRIVATE", - "SYS__LWP_KILL", - "SYS__LWP_PARK", - "SYS__LWP_SELF", - "SYS__LWP_SETNAME", - "SYS__LWP_SETPRIVATE", - "SYS__LWP_SUSPEND", - "SYS__LWP_UNPARK", - "SYS__LWP_UNPARK_ALL", - "SYS__LWP_WAIT", - "SYS__LWP_WAKEUP", - "SYS__NEWSELECT", - "SYS__PSET_BIND", - "SYS__SCHED_GETAFFINITY", - "SYS__SCHED_GETPARAM", - "SYS__SCHED_SETAFFINITY", - "SYS__SCHED_SETPARAM", - "SYS__SYSCTL", - "SYS__UMTX_LOCK", - "SYS__UMTX_OP", - "SYS__UMTX_UNLOCK", - "SYS___ACL_ACLCHECK_FD", - "SYS___ACL_ACLCHECK_FILE", - "SYS___ACL_ACLCHECK_LINK", - "SYS___ACL_DELETE_FD", - "SYS___ACL_DELETE_FILE", - "SYS___ACL_DELETE_LINK", - "SYS___ACL_GET_FD", - "SYS___ACL_GET_FILE", - "SYS___ACL_GET_LINK", - "SYS___ACL_SET_FD", - "SYS___ACL_SET_FILE", - "SYS___ACL_SET_LINK", - "SYS___CAP_RIGHTS_GET", - "SYS___CLONE", - "SYS___DISABLE_THREADSIGNAL", - "SYS___GETCWD", - "SYS___GETLOGIN", - "SYS___GET_TCB", - "SYS___MAC_EXECVE", - "SYS___MAC_GETFSSTAT", - "SYS___MAC_GET_FD", - "SYS___MAC_GET_FILE", - "SYS___MAC_GET_LCID", - "SYS___MAC_GET_LCTX", - "SYS___MAC_GET_LINK", - "SYS___MAC_GET_MOUNT", - "SYS___MAC_GET_PID", - "SYS___MAC_GET_PROC", - "SYS___MAC_MOUNT", - "SYS___MAC_SET_FD", - "SYS___MAC_SET_FILE", - "SYS___MAC_SET_LCTX", - "SYS___MAC_SET_LINK", - "SYS___MAC_SET_PROC", - "SYS___MAC_SYSCALL", - "SYS___OLD_SEMWAIT_SIGNAL", - "SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL", - "SYS___POSIX_CHOWN", - "SYS___POSIX_FCHOWN", - "SYS___POSIX_LCHOWN", - "SYS___POSIX_RENAME", - "SYS___PTHREAD_CANCELED", - "SYS___PTHREAD_CHDIR", - "SYS___PTHREAD_FCHDIR", - "SYS___PTHREAD_KILL", - "SYS___PTHREAD_MARKCANCEL", - "SYS___PTHREAD_SIGMASK", - "SYS___QUOTACTL", - "SYS___SEMCTL", - "SYS___SEMWAIT_SIGNAL", - "SYS___SEMWAIT_SIGNAL_NOCANCEL", - "SYS___SETLOGIN", - "SYS___SETUGID", - "SYS___SET_TCB", - "SYS___SIGACTION_SIGTRAMP", - "SYS___SIGTIMEDWAIT", - "SYS___SIGWAIT", - "SYS___SIGWAIT_NOCANCEL", - "SYS___SYSCTL", - "SYS___TFORK", - "SYS___THREXIT", - "SYS___THRSIGDIVERT", - "SYS___THRSLEEP", - "SYS___THRWAKEUP", - "S_ARCH1", - "S_ARCH2", - "S_BLKSIZE", - "S_IEXEC", - "S_IFBLK", - "S_IFCHR", - "S_IFDIR", - "S_IFIFO", - "S_IFLNK", - "S_IFMT", - "S_IFREG", - "S_IFSOCK", - "S_IFWHT", - "S_IREAD", - "S_IRGRP", - "S_IROTH", - "S_IRUSR", - "S_IRWXG", - "S_IRWXO", - "S_IRWXU", - "S_ISGID", - "S_ISTXT", - "S_ISUID", - "S_ISVTX", - "S_IWGRP", - "S_IWOTH", - "S_IWRITE", - "S_IWUSR", - "S_IXGRP", - "S_IXOTH", - "S_IXUSR", - "S_LOGIN_SET", - "SecurityAttributes", - "Seek", - "Select", - "Sendfile", - "Sendmsg", - "SendmsgN", - "Sendto", - "Servent", - "SetBpf", - "SetBpfBuflen", - "SetBpfDatalink", - "SetBpfHeadercmpl", - "SetBpfImmediate", - "SetBpfInterface", - "SetBpfPromisc", - "SetBpfTimeout", - "SetCurrentDirectory", - "SetEndOfFile", - "SetEnvironmentVariable", - "SetFileAttributes", - "SetFileCompletionNotificationModes", - "SetFilePointer", - "SetFileTime", - "SetHandleInformation", - "SetKevent", - "SetLsfPromisc", - "SetNonblock", - "Setdomainname", - "Setegid", - "Setenv", - "Seteuid", - "Setfsgid", - "Setfsuid", - "Setgid", - "Setgroups", - "Sethostname", - "Setlogin", - "Setpgid", - "Setpriority", - "Setprivexec", - "Setregid", - "Setresgid", - "Setresuid", - "Setreuid", - "Setrlimit", - "Setsid", - "Setsockopt", - "SetsockoptByte", - "SetsockoptICMPv6Filter", - "SetsockoptIPMreq", - "SetsockoptIPMreqn", - "SetsockoptIPv6Mreq", - "SetsockoptInet4Addr", - "SetsockoptInt", - "SetsockoptLinger", - "SetsockoptString", - "SetsockoptTimeval", - "Settimeofday", - "Setuid", - "Setxattr", - "Shutdown", - "SidTypeAlias", - "SidTypeComputer", - "SidTypeDeletedAccount", - "SidTypeDomain", - "SidTypeGroup", - "SidTypeInvalid", - "SidTypeLabel", - "SidTypeUnknown", - "SidTypeUser", - "SidTypeWellKnownGroup", - "Signal", - "SizeofBpfHdr", - "SizeofBpfInsn", - "SizeofBpfProgram", - "SizeofBpfStat", - "SizeofBpfVersion", - "SizeofBpfZbuf", - "SizeofBpfZbufHeader", - "SizeofCmsghdr", - "SizeofICMPv6Filter", - "SizeofIPMreq", - "SizeofIPMreqn", - "SizeofIPv6MTUInfo", - "SizeofIPv6Mreq", - "SizeofIfAddrmsg", - "SizeofIfAnnounceMsghdr", - "SizeofIfData", - "SizeofIfInfomsg", - "SizeofIfMsghdr", - "SizeofIfaMsghdr", - "SizeofIfmaMsghdr", - "SizeofIfmaMsghdr2", - "SizeofInet4Pktinfo", - "SizeofInet6Pktinfo", - "SizeofInotifyEvent", - "SizeofLinger", - "SizeofMsghdr", - "SizeofNlAttr", - "SizeofNlMsgerr", - "SizeofNlMsghdr", - "SizeofRtAttr", - "SizeofRtGenmsg", - "SizeofRtMetrics", - "SizeofRtMsg", - "SizeofRtMsghdr", - "SizeofRtNexthop", - "SizeofSockFilter", - "SizeofSockFprog", - "SizeofSockaddrAny", - "SizeofSockaddrDatalink", - "SizeofSockaddrInet4", - "SizeofSockaddrInet6", - "SizeofSockaddrLinklayer", - "SizeofSockaddrNetlink", - "SizeofSockaddrUnix", - "SizeofTCPInfo", - "SizeofUcred", - "SlicePtrFromStrings", - "SockFilter", - "SockFprog", - "Sockaddr", - "SockaddrDatalink", - "SockaddrGen", - "SockaddrInet4", - "SockaddrInet6", - "SockaddrLinklayer", - "SockaddrNetlink", - "SockaddrUnix", - "Socket", - "SocketControlMessage", - "SocketDisableIPv6", - "Socketpair", - "Splice", - "StartProcess", - "StartupInfo", - "Stat", - "Stat_t", - "Statfs", - "Statfs_t", - "Stderr", - "Stdin", - "Stdout", - "StringBytePtr", - "StringByteSlice", - "StringSlicePtr", - "StringToSid", - "StringToUTF16", - "StringToUTF16Ptr", - "Symlink", - "Sync", - "SyncFileRange", - "SysProcAttr", - "SysProcIDMap", - "Syscall", - "Syscall12", - "Syscall15", - "Syscall18", - "Syscall6", - "Syscall9", - "SyscallN", - "Sysctl", - "SysctlUint32", - "Sysctlnode", - "Sysinfo", - "Sysinfo_t", - "Systemtime", - "TCGETS", - "TCIFLUSH", - "TCIOFLUSH", - "TCOFLUSH", - "TCPInfo", - "TCPKeepalive", - "TCP_CA_NAME_MAX", - "TCP_CONGCTL", - "TCP_CONGESTION", - "TCP_CONNECTIONTIMEOUT", - "TCP_CORK", - "TCP_DEFER_ACCEPT", - "TCP_ENABLE_ECN", - "TCP_INFO", - "TCP_KEEPALIVE", - "TCP_KEEPCNT", - "TCP_KEEPIDLE", - "TCP_KEEPINIT", - "TCP_KEEPINTVL", - "TCP_LINGER2", - "TCP_MAXBURST", - "TCP_MAXHLEN", - "TCP_MAXOLEN", - "TCP_MAXSEG", - "TCP_MAXWIN", - "TCP_MAX_SACK", - "TCP_MAX_WINSHIFT", - "TCP_MD5SIG", - "TCP_MD5SIG_MAXKEYLEN", - "TCP_MINMSS", - "TCP_MINMSSOVERLOAD", - "TCP_MSS", - "TCP_NODELAY", - "TCP_NOOPT", - "TCP_NOPUSH", - "TCP_NOTSENT_LOWAT", - "TCP_NSTATES", - "TCP_QUICKACK", - "TCP_RXT_CONNDROPTIME", - "TCP_RXT_FINDROP", - "TCP_SACK_ENABLE", - "TCP_SENDMOREACKS", - "TCP_SYNCNT", - "TCP_VENDOR", - "TCP_WINDOW_CLAMP", - "TCSAFLUSH", - "TCSETS", - "TF_DISCONNECT", - "TF_REUSE_SOCKET", - "TF_USE_DEFAULT_WORKER", - "TF_USE_KERNEL_APC", - "TF_USE_SYSTEM_THREAD", - "TF_WRITE_BEHIND", - "TH32CS_INHERIT", - "TH32CS_SNAPALL", - "TH32CS_SNAPHEAPLIST", - "TH32CS_SNAPMODULE", - "TH32CS_SNAPMODULE32", - "TH32CS_SNAPPROCESS", - "TH32CS_SNAPTHREAD", - "TIME_ZONE_ID_DAYLIGHT", - "TIME_ZONE_ID_STANDARD", - "TIME_ZONE_ID_UNKNOWN", - "TIOCCBRK", - "TIOCCDTR", - "TIOCCONS", - "TIOCDCDTIMESTAMP", - "TIOCDRAIN", - "TIOCDSIMICROCODE", - "TIOCEXCL", - "TIOCEXT", - "TIOCFLAG_CDTRCTS", - "TIOCFLAG_CLOCAL", - "TIOCFLAG_CRTSCTS", - "TIOCFLAG_MDMBUF", - "TIOCFLAG_PPS", - "TIOCFLAG_SOFTCAR", - "TIOCFLUSH", - "TIOCGDEV", - "TIOCGDRAINWAIT", - "TIOCGETA", - "TIOCGETD", - "TIOCGFLAGS", - "TIOCGICOUNT", - "TIOCGLCKTRMIOS", - "TIOCGLINED", - "TIOCGPGRP", - "TIOCGPTN", - "TIOCGQSIZE", - "TIOCGRANTPT", - "TIOCGRS485", - "TIOCGSERIAL", - "TIOCGSID", - "TIOCGSIZE", - "TIOCGSOFTCAR", - "TIOCGTSTAMP", - "TIOCGWINSZ", - "TIOCINQ", - "TIOCIXOFF", - "TIOCIXON", - "TIOCLINUX", - "TIOCMBIC", - "TIOCMBIS", - "TIOCMGDTRWAIT", - "TIOCMGET", - "TIOCMIWAIT", - "TIOCMODG", - "TIOCMODS", - "TIOCMSDTRWAIT", - "TIOCMSET", - "TIOCM_CAR", - "TIOCM_CD", - "TIOCM_CTS", - "TIOCM_DCD", - "TIOCM_DSR", - "TIOCM_DTR", - "TIOCM_LE", - "TIOCM_RI", - "TIOCM_RNG", - "TIOCM_RTS", - "TIOCM_SR", - "TIOCM_ST", - "TIOCNOTTY", - "TIOCNXCL", - "TIOCOUTQ", - "TIOCPKT", - "TIOCPKT_DATA", - "TIOCPKT_DOSTOP", - "TIOCPKT_FLUSHREAD", - "TIOCPKT_FLUSHWRITE", - "TIOCPKT_IOCTL", - "TIOCPKT_NOSTOP", - "TIOCPKT_START", - "TIOCPKT_STOP", - "TIOCPTMASTER", - "TIOCPTMGET", - "TIOCPTSNAME", - "TIOCPTYGNAME", - "TIOCPTYGRANT", - "TIOCPTYUNLK", - "TIOCRCVFRAME", - "TIOCREMOTE", - "TIOCSBRK", - "TIOCSCONS", - "TIOCSCTTY", - "TIOCSDRAINWAIT", - "TIOCSDTR", - "TIOCSERCONFIG", - "TIOCSERGETLSR", - "TIOCSERGETMULTI", - "TIOCSERGSTRUCT", - "TIOCSERGWILD", - "TIOCSERSETMULTI", - "TIOCSERSWILD", - "TIOCSER_TEMT", - "TIOCSETA", - "TIOCSETAF", - "TIOCSETAW", - "TIOCSETD", - "TIOCSFLAGS", - "TIOCSIG", - "TIOCSLCKTRMIOS", - "TIOCSLINED", - "TIOCSPGRP", - "TIOCSPTLCK", - "TIOCSQSIZE", - "TIOCSRS485", - "TIOCSSERIAL", - "TIOCSSIZE", - "TIOCSSOFTCAR", - "TIOCSTART", - "TIOCSTAT", - "TIOCSTI", - "TIOCSTOP", - "TIOCSTSTAMP", - "TIOCSWINSZ", - "TIOCTIMESTAMP", - "TIOCUCNTL", - "TIOCVHANGUP", - "TIOCXMTFRAME", - "TOKEN_ADJUST_DEFAULT", - "TOKEN_ADJUST_GROUPS", - "TOKEN_ADJUST_PRIVILEGES", - "TOKEN_ADJUST_SESSIONID", - "TOKEN_ALL_ACCESS", - "TOKEN_ASSIGN_PRIMARY", - "TOKEN_DUPLICATE", - "TOKEN_EXECUTE", - "TOKEN_IMPERSONATE", - "TOKEN_QUERY", - "TOKEN_QUERY_SOURCE", - "TOKEN_READ", - "TOKEN_WRITE", - "TOSTOP", - "TRUNCATE_EXISTING", - "TUNATTACHFILTER", - "TUNDETACHFILTER", - "TUNGETFEATURES", - "TUNGETIFF", - "TUNGETSNDBUF", - "TUNGETVNETHDRSZ", - "TUNSETDEBUG", - "TUNSETGROUP", - "TUNSETIFF", - "TUNSETLINK", - "TUNSETNOCSUM", - "TUNSETOFFLOAD", - "TUNSETOWNER", - "TUNSETPERSIST", - "TUNSETSNDBUF", - "TUNSETTXFILTER", - "TUNSETVNETHDRSZ", - "Tee", - "TerminateProcess", - "Termios", - "Tgkill", - "Time", - "Time_t", - "Times", - "Timespec", - "TimespecToNsec", - "Timeval", - "Timeval32", - "TimevalToNsec", - "Timex", - "Timezoneinformation", - "Tms", - "Token", - "TokenAccessInformation", - "TokenAuditPolicy", - "TokenDefaultDacl", - "TokenElevation", - "TokenElevationType", - "TokenGroups", - "TokenGroupsAndPrivileges", - "TokenHasRestrictions", - "TokenImpersonationLevel", - "TokenIntegrityLevel", - "TokenLinkedToken", - "TokenLogonSid", - "TokenMandatoryPolicy", - "TokenOrigin", - "TokenOwner", - "TokenPrimaryGroup", - "TokenPrivileges", - "TokenRestrictedSids", - "TokenSandBoxInert", - "TokenSessionId", - "TokenSessionReference", - "TokenSource", - "TokenStatistics", - "TokenType", - "TokenUIAccess", - "TokenUser", - "TokenVirtualizationAllowed", - "TokenVirtualizationEnabled", - "Tokenprimarygroup", - "Tokenuser", - "TranslateAccountName", - "TranslateName", - "TransmitFile", - "TransmitFileBuffers", - "Truncate", - "UNIX_PATH_MAX", - "USAGE_MATCH_TYPE_AND", - "USAGE_MATCH_TYPE_OR", - "UTF16FromString", - "UTF16PtrFromString", - "UTF16ToString", - "Ucred", - "Umask", - "Uname", - "Undelete", - "UnixCredentials", - "UnixRights", - "Unlink", - "Unlinkat", - "UnmapViewOfFile", - "Unmount", - "Unsetenv", - "Unshare", - "UserInfo10", - "Ustat", - "Ustat_t", - "Utimbuf", - "Utime", - "Utimes", - "UtimesNano", - "Utsname", - "VDISCARD", - "VDSUSP", - "VEOF", - "VEOL", - "VEOL2", - "VERASE", - "VERASE2", - "VINTR", - "VKILL", - "VLNEXT", - "VMIN", - "VQUIT", - "VREPRINT", - "VSTART", - "VSTATUS", - "VSTOP", - "VSUSP", - "VSWTC", - "VT0", - "VT1", - "VTDLY", - "VTIME", - "VWERASE", - "VirtualLock", - "VirtualUnlock", - "WAIT_ABANDONED", - "WAIT_FAILED", - "WAIT_OBJECT_0", - "WAIT_TIMEOUT", - "WALL", - "WALLSIG", - "WALTSIG", - "WCLONE", - "WCONTINUED", - "WCOREFLAG", - "WEXITED", - "WLINUXCLONE", - "WNOHANG", - "WNOTHREAD", - "WNOWAIT", - "WNOZOMBIE", - "WOPTSCHECKED", - "WORDSIZE", - "WSABuf", - "WSACleanup", - "WSADESCRIPTION_LEN", - "WSAData", - "WSAEACCES", - "WSAECONNABORTED", - "WSAECONNRESET", - "WSAEnumProtocols", - "WSAID_CONNECTEX", - "WSAIoctl", - "WSAPROTOCOL_LEN", - "WSAProtocolChain", - "WSAProtocolInfo", - "WSARecv", - "WSARecvFrom", - "WSASYS_STATUS_LEN", - "WSASend", - "WSASendTo", - "WSASendto", - "WSAStartup", - "WSTOPPED", - "WTRAPPED", - "WUNTRACED", - "Wait4", - "WaitForSingleObject", - "WaitStatus", - "Win32FileAttributeData", - "Win32finddata", - "Write", - "WriteConsole", - "WriteFile", - "X509_ASN_ENCODING", - "XCASE", - "XP1_CONNECTIONLESS", - "XP1_CONNECT_DATA", - "XP1_DISCONNECT_DATA", - "XP1_EXPEDITED_DATA", - "XP1_GRACEFUL_CLOSE", - "XP1_GUARANTEED_DELIVERY", - "XP1_GUARANTEED_ORDER", - "XP1_IFS_HANDLES", - "XP1_MESSAGE_ORIENTED", - "XP1_MULTIPOINT_CONTROL_PLANE", - "XP1_MULTIPOINT_DATA_PLANE", - "XP1_PARTIAL_MESSAGE", - "XP1_PSEUDO_STREAM", - "XP1_QOS_SUPPORTED", - "XP1_SAN_SUPPORT_SDP", - "XP1_SUPPORT_BROADCAST", - "XP1_SUPPORT_MULTIPOINT", - "XP1_UNI_RECV", - "XP1_UNI_SEND", - }, - "syscall/js": { - "CopyBytesToGo", - "CopyBytesToJS", - "Error", - "Func", - "FuncOf", - "Global", - "Null", - "Type", - "TypeBoolean", - "TypeFunction", - "TypeNull", - "TypeNumber", - "TypeObject", - "TypeString", - "TypeSymbol", - "TypeUndefined", - "Undefined", - "Value", - "ValueError", - "ValueOf", - }, - "testing": { - "AllocsPerRun", - "B", - "Benchmark", - "BenchmarkResult", - "Cover", - "CoverBlock", - "CoverMode", - "Coverage", - "F", - "Init", - "InternalBenchmark", - "InternalExample", - "InternalFuzzTarget", - "InternalTest", - "M", - "Main", - "MainStart", - "PB", - "RegisterCover", - "RunBenchmarks", - "RunExamples", - "RunTests", - "Short", - "T", - "TB", - "Testing", - "Verbose", - }, - "testing/fstest": { - "MapFS", - "MapFile", - "TestFS", - }, - "testing/iotest": { - "DataErrReader", - "ErrReader", - "ErrTimeout", - "HalfReader", - "NewReadLogger", - "NewWriteLogger", - "OneByteReader", - "TestReader", - "TimeoutReader", - "TruncateWriter", - }, - "testing/quick": { - "Check", - "CheckEqual", - "CheckEqualError", - "CheckError", - "Config", - "Generator", - "SetupError", - "Value", - }, - "testing/slogtest": { - "TestHandler", - }, - "text/scanner": { - "Char", - "Comment", - "EOF", - "Float", - "GoTokens", - "GoWhitespace", - "Ident", - "Int", - "Position", - "RawString", - "ScanChars", - "ScanComments", - "ScanFloats", - "ScanIdents", - "ScanInts", - "ScanRawStrings", - "ScanStrings", - "Scanner", - "SkipComments", - "String", - "TokenString", - }, - "text/tabwriter": { - "AlignRight", - "Debug", - "DiscardEmptyColumns", - "Escape", - "FilterHTML", - "NewWriter", - "StripEscape", - "TabIndent", - "Writer", - }, - "text/template": { - "ExecError", - "FuncMap", - "HTMLEscape", - "HTMLEscapeString", - "HTMLEscaper", - "IsTrue", - "JSEscape", - "JSEscapeString", - "JSEscaper", - "Must", - "New", - "ParseFS", - "ParseFiles", - "ParseGlob", - "Template", - "URLQueryEscaper", - }, - "text/template/parse": { - "ActionNode", - "BoolNode", - "BranchNode", - "BreakNode", - "ChainNode", - "CommandNode", - "CommentNode", - "ContinueNode", - "DotNode", - "FieldNode", - "IdentifierNode", - "IfNode", - "IsEmptyTree", - "ListNode", - "Mode", - "New", - "NewIdentifier", - "NilNode", - "Node", - "NodeAction", - "NodeBool", - "NodeBreak", - "NodeChain", - "NodeCommand", - "NodeComment", - "NodeContinue", - "NodeDot", - "NodeField", - "NodeIdentifier", - "NodeIf", - "NodeList", - "NodeNil", - "NodeNumber", - "NodePipe", - "NodeRange", - "NodeString", - "NodeTemplate", - "NodeText", - "NodeType", - "NodeVariable", - "NodeWith", - "NumberNode", - "Parse", - "ParseComments", - "PipeNode", - "Pos", - "RangeNode", - "SkipFuncCheck", - "StringNode", - "TemplateNode", - "TextNode", - "Tree", - "VariableNode", - "WithNode", - }, - "time": { - "ANSIC", - "After", - "AfterFunc", - "April", - "August", - "Date", - "DateOnly", - "DateTime", - "December", - "Duration", - "February", - "FixedZone", - "Friday", - "Hour", - "January", - "July", - "June", - "Kitchen", - "Layout", - "LoadLocation", - "LoadLocationFromTZData", - "Local", - "Location", - "March", - "May", - "Microsecond", - "Millisecond", - "Minute", - "Monday", - "Month", - "Nanosecond", - "NewTicker", - "NewTimer", - "November", - "Now", - "October", - "Parse", - "ParseDuration", - "ParseError", - "ParseInLocation", - "RFC1123", - "RFC1123Z", - "RFC3339", - "RFC3339Nano", - "RFC822", - "RFC822Z", - "RFC850", - "RubyDate", - "Saturday", - "Second", - "September", - "Since", - "Sleep", - "Stamp", - "StampMicro", - "StampMilli", - "StampNano", - "Sunday", - "Thursday", - "Tick", - "Ticker", - "Time", - "TimeOnly", - "Timer", - "Tuesday", - "UTC", - "Unix", - "UnixDate", - "UnixMicro", - "UnixMilli", - "Until", - "Wednesday", - "Weekday", - }, - "unicode": { - "ASCII_Hex_Digit", - "Adlam", - "Ahom", - "Anatolian_Hieroglyphs", - "Arabic", - "Armenian", - "Avestan", - "AzeriCase", - "Balinese", - "Bamum", - "Bassa_Vah", - "Batak", - "Bengali", - "Bhaiksuki", - "Bidi_Control", - "Bopomofo", - "Brahmi", - "Braille", - "Buginese", - "Buhid", - "C", - "Canadian_Aboriginal", - "Carian", - "CaseRange", - "CaseRanges", - "Categories", - "Caucasian_Albanian", - "Cc", - "Cf", - "Chakma", - "Cham", - "Cherokee", - "Chorasmian", - "Co", - "Common", - "Coptic", - "Cs", - "Cuneiform", - "Cypriot", - "Cypro_Minoan", - "Cyrillic", - "Dash", - "Deprecated", - "Deseret", - "Devanagari", - "Diacritic", - "Digit", - "Dives_Akuru", - "Dogra", - "Duployan", - "Egyptian_Hieroglyphs", - "Elbasan", - "Elymaic", - "Ethiopic", - "Extender", - "FoldCategory", - "FoldScript", - "Georgian", - "Glagolitic", - "Gothic", - "Grantha", - "GraphicRanges", - "Greek", - "Gujarati", - "Gunjala_Gondi", - "Gurmukhi", - "Han", - "Hangul", - "Hanifi_Rohingya", - "Hanunoo", - "Hatran", - "Hebrew", - "Hex_Digit", - "Hiragana", - "Hyphen", - "IDS_Binary_Operator", - "IDS_Trinary_Operator", - "Ideographic", - "Imperial_Aramaic", - "In", - "Inherited", - "Inscriptional_Pahlavi", - "Inscriptional_Parthian", - "Is", - "IsControl", - "IsDigit", - "IsGraphic", - "IsLetter", - "IsLower", - "IsMark", - "IsNumber", - "IsOneOf", - "IsPrint", - "IsPunct", - "IsSpace", - "IsSymbol", - "IsTitle", - "IsUpper", - "Javanese", - "Join_Control", - "Kaithi", - "Kannada", - "Katakana", - "Kawi", - "Kayah_Li", - "Kharoshthi", - "Khitan_Small_Script", - "Khmer", - "Khojki", - "Khudawadi", - "L", - "Lao", - "Latin", - "Lepcha", - "Letter", - "Limbu", - "Linear_A", - "Linear_B", - "Lisu", - "Ll", - "Lm", - "Lo", - "Logical_Order_Exception", - "Lower", - "LowerCase", - "Lt", - "Lu", - "Lycian", - "Lydian", - "M", - "Mahajani", - "Makasar", - "Malayalam", - "Mandaic", - "Manichaean", - "Marchen", - "Mark", - "Masaram_Gondi", - "MaxASCII", - "MaxCase", - "MaxLatin1", - "MaxRune", - "Mc", - "Me", - "Medefaidrin", - "Meetei_Mayek", - "Mende_Kikakui", - "Meroitic_Cursive", - "Meroitic_Hieroglyphs", - "Miao", - "Mn", - "Modi", - "Mongolian", - "Mro", - "Multani", - "Myanmar", - "N", - "Nabataean", - "Nag_Mundari", - "Nandinagari", - "Nd", - "New_Tai_Lue", - "Newa", - "Nko", - "Nl", - "No", - "Noncharacter_Code_Point", - "Number", - "Nushu", - "Nyiakeng_Puachue_Hmong", - "Ogham", - "Ol_Chiki", - "Old_Hungarian", - "Old_Italic", - "Old_North_Arabian", - "Old_Permic", - "Old_Persian", - "Old_Sogdian", - "Old_South_Arabian", - "Old_Turkic", - "Old_Uyghur", - "Oriya", - "Osage", - "Osmanya", - "Other", - "Other_Alphabetic", - "Other_Default_Ignorable_Code_Point", - "Other_Grapheme_Extend", - "Other_ID_Continue", - "Other_ID_Start", - "Other_Lowercase", - "Other_Math", - "Other_Uppercase", - "P", - "Pahawh_Hmong", - "Palmyrene", - "Pattern_Syntax", - "Pattern_White_Space", - "Pau_Cin_Hau", - "Pc", - "Pd", - "Pe", - "Pf", - "Phags_Pa", - "Phoenician", - "Pi", - "Po", - "Prepended_Concatenation_Mark", - "PrintRanges", - "Properties", - "Ps", - "Psalter_Pahlavi", - "Punct", - "Quotation_Mark", - "Radical", - "Range16", - "Range32", - "RangeTable", - "Regional_Indicator", - "Rejang", - "ReplacementChar", - "Runic", - "S", - "STerm", - "Samaritan", - "Saurashtra", - "Sc", - "Scripts", - "Sentence_Terminal", - "Sharada", - "Shavian", - "Siddham", - "SignWriting", - "SimpleFold", - "Sinhala", - "Sk", - "Sm", - "So", - "Soft_Dotted", - "Sogdian", - "Sora_Sompeng", - "Soyombo", - "Space", - "SpecialCase", - "Sundanese", - "Syloti_Nagri", - "Symbol", - "Syriac", - "Tagalog", - "Tagbanwa", - "Tai_Le", - "Tai_Tham", - "Tai_Viet", - "Takri", - "Tamil", - "Tangsa", - "Tangut", - "Telugu", - "Terminal_Punctuation", - "Thaana", - "Thai", - "Tibetan", - "Tifinagh", - "Tirhuta", - "Title", - "TitleCase", - "To", - "ToLower", - "ToTitle", - "ToUpper", - "Toto", - "TurkishCase", - "Ugaritic", - "Unified_Ideograph", - "Upper", - "UpperCase", - "UpperLower", - "Vai", - "Variation_Selector", - "Version", - "Vithkuqi", - "Wancho", - "Warang_Citi", - "White_Space", - "Yezidi", - "Yi", - "Z", - "Zanabazar_Square", - "Zl", - "Zp", - "Zs", - }, - "unicode/utf16": { - "AppendRune", - "Decode", - "DecodeRune", - "Encode", - "EncodeRune", - "IsSurrogate", - }, - "unicode/utf8": { - "AppendRune", - "DecodeLastRune", - "DecodeLastRuneInString", - "DecodeRune", - "DecodeRuneInString", - "EncodeRune", - "FullRune", - "FullRuneInString", - "MaxRune", - "RuneCount", - "RuneCountInString", - "RuneError", - "RuneLen", - "RuneSelf", - "RuneStart", - "UTFMax", - "Valid", - "ValidRune", - "ValidString", - }, - "unsafe": { - "Add", - "Alignof", - "Offsetof", - "Pointer", - "Sizeof", - "Slice", - "SliceData", - "String", - "StringData", - }, -} diff --git a/tools/vendor/golang.org/x/tools/internal/packagesinternal/packages.go b/tools/vendor/golang.org/x/tools/internal/packagesinternal/packages.go index d9950b1f0..44719de17 100644 --- a/tools/vendor/golang.org/x/tools/internal/packagesinternal/packages.go +++ b/tools/vendor/golang.org/x/tools/internal/packagesinternal/packages.go @@ -5,10 +5,6 @@ // Package packagesinternal exposes internal-only fields from go/packages. package packagesinternal -import ( - "golang.org/x/tools/internal/gocommand" -) - var GetForTest = func(p interface{}) string { return "" } var GetDepsErrors = func(p interface{}) []*PackageError { return nil } @@ -18,10 +14,6 @@ type PackageError struct { Err string // the error itself } -var GetGoCmdRunner = func(config interface{}) *gocommand.Runner { return nil } - -var SetGoCmdRunner = func(config interface{}, runner *gocommand.Runner) {} - var TypecheckCgo int var DepsErrors int // must be set as a LoadMode to call GetDepsErrors var ForTest int // must be set as a LoadMode to call GetForTest diff --git a/tools/vendor/golang.org/x/tools/internal/stdlib/manifest.go b/tools/vendor/golang.org/x/tools/internal/stdlib/manifest.go new file mode 100644 index 000000000..a928acf29 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/stdlib/manifest.go @@ -0,0 +1,17431 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate.go. DO NOT EDIT. + +package stdlib + +var PackageSymbols = map[string][]Symbol{ + "archive/tar": { + {"(*Header).FileInfo", Method, 1}, + {"(*Reader).Next", Method, 0}, + {"(*Reader).Read", Method, 0}, + {"(*Writer).AddFS", Method, 22}, + {"(*Writer).Close", Method, 0}, + {"(*Writer).Flush", Method, 0}, + {"(*Writer).Write", Method, 0}, + {"(*Writer).WriteHeader", Method, 0}, + {"(Format).String", Method, 10}, + {"ErrFieldTooLong", Var, 0}, + {"ErrHeader", Var, 0}, + {"ErrInsecurePath", Var, 20}, + {"ErrWriteAfterClose", Var, 0}, + {"ErrWriteTooLong", Var, 0}, + {"FileInfoHeader", Func, 1}, + {"FileInfoNames", Type, 23}, + {"Format", Type, 10}, + {"FormatGNU", Const, 10}, + {"FormatPAX", Const, 10}, + {"FormatUSTAR", Const, 10}, + {"FormatUnknown", Const, 10}, + {"Header", Type, 0}, + {"Header.AccessTime", Field, 0}, + {"Header.ChangeTime", Field, 0}, + {"Header.Devmajor", Field, 0}, + {"Header.Devminor", Field, 0}, + {"Header.Format", Field, 10}, + {"Header.Gid", Field, 0}, + {"Header.Gname", Field, 0}, + {"Header.Linkname", Field, 0}, + {"Header.ModTime", Field, 0}, + {"Header.Mode", Field, 0}, + {"Header.Name", Field, 0}, + {"Header.PAXRecords", Field, 10}, + {"Header.Size", Field, 0}, + {"Header.Typeflag", Field, 0}, + {"Header.Uid", Field, 0}, + {"Header.Uname", Field, 0}, + {"Header.Xattrs", Field, 3}, + {"NewReader", Func, 0}, + {"NewWriter", Func, 0}, + {"Reader", Type, 0}, + {"TypeBlock", Const, 0}, + {"TypeChar", Const, 0}, + {"TypeCont", Const, 0}, + {"TypeDir", Const, 0}, + {"TypeFifo", Const, 0}, + {"TypeGNULongLink", Const, 1}, + {"TypeGNULongName", Const, 1}, + {"TypeGNUSparse", Const, 3}, + {"TypeLink", Const, 0}, + {"TypeReg", Const, 0}, + {"TypeRegA", Const, 0}, + {"TypeSymlink", Const, 0}, + {"TypeXGlobalHeader", Const, 0}, + {"TypeXHeader", Const, 0}, + {"Writer", Type, 0}, + }, + "archive/zip": { + {"(*File).DataOffset", Method, 2}, + {"(*File).FileInfo", Method, 0}, + {"(*File).ModTime", Method, 0}, + {"(*File).Mode", Method, 0}, + {"(*File).Open", Method, 0}, + {"(*File).OpenRaw", Method, 17}, + {"(*File).SetModTime", Method, 0}, + {"(*File).SetMode", Method, 0}, + {"(*FileHeader).FileInfo", Method, 0}, + {"(*FileHeader).ModTime", Method, 0}, + {"(*FileHeader).Mode", Method, 0}, + {"(*FileHeader).SetModTime", Method, 0}, + {"(*FileHeader).SetMode", Method, 0}, + {"(*ReadCloser).Close", Method, 0}, + {"(*ReadCloser).Open", Method, 16}, + {"(*ReadCloser).RegisterDecompressor", Method, 6}, + {"(*Reader).Open", Method, 16}, + {"(*Reader).RegisterDecompressor", Method, 6}, + {"(*Writer).AddFS", Method, 22}, + {"(*Writer).Close", Method, 0}, + {"(*Writer).Copy", Method, 17}, + {"(*Writer).Create", Method, 0}, + {"(*Writer).CreateHeader", Method, 0}, + {"(*Writer).CreateRaw", Method, 17}, + {"(*Writer).Flush", Method, 4}, + {"(*Writer).RegisterCompressor", Method, 6}, + {"(*Writer).SetComment", Method, 10}, + {"(*Writer).SetOffset", Method, 5}, + {"Compressor", Type, 2}, + {"Decompressor", Type, 2}, + {"Deflate", Const, 0}, + {"ErrAlgorithm", Var, 0}, + {"ErrChecksum", Var, 0}, + {"ErrFormat", Var, 0}, + {"ErrInsecurePath", Var, 20}, + {"File", Type, 0}, + {"File.FileHeader", Field, 0}, + {"FileHeader", Type, 0}, + {"FileHeader.CRC32", Field, 0}, + {"FileHeader.Comment", Field, 0}, + {"FileHeader.CompressedSize", Field, 0}, + {"FileHeader.CompressedSize64", Field, 1}, + {"FileHeader.CreatorVersion", Field, 0}, + {"FileHeader.ExternalAttrs", Field, 0}, + {"FileHeader.Extra", Field, 0}, + {"FileHeader.Flags", Field, 0}, + {"FileHeader.Method", Field, 0}, + {"FileHeader.Modified", Field, 10}, + {"FileHeader.ModifiedDate", Field, 0}, + {"FileHeader.ModifiedTime", Field, 0}, + {"FileHeader.Name", Field, 0}, + {"FileHeader.NonUTF8", Field, 10}, + {"FileHeader.ReaderVersion", Field, 0}, + {"FileHeader.UncompressedSize", Field, 0}, + {"FileHeader.UncompressedSize64", Field, 1}, + {"FileInfoHeader", Func, 0}, + {"NewReader", Func, 0}, + {"NewWriter", Func, 0}, + {"OpenReader", Func, 0}, + {"ReadCloser", Type, 0}, + {"ReadCloser.Reader", Field, 0}, + {"Reader", Type, 0}, + {"Reader.Comment", Field, 0}, + {"Reader.File", Field, 0}, + {"RegisterCompressor", Func, 2}, + {"RegisterDecompressor", Func, 2}, + {"Store", Const, 0}, + {"Writer", Type, 0}, + }, + "bufio": { + {"(*Reader).Buffered", Method, 0}, + {"(*Reader).Discard", Method, 5}, + {"(*Reader).Peek", Method, 0}, + {"(*Reader).Read", Method, 0}, + {"(*Reader).ReadByte", Method, 0}, + {"(*Reader).ReadBytes", Method, 0}, + {"(*Reader).ReadLine", Method, 0}, + {"(*Reader).ReadRune", Method, 0}, + {"(*Reader).ReadSlice", Method, 0}, + {"(*Reader).ReadString", Method, 0}, + {"(*Reader).Reset", Method, 2}, + {"(*Reader).Size", Method, 10}, + {"(*Reader).UnreadByte", Method, 0}, + {"(*Reader).UnreadRune", Method, 0}, + {"(*Reader).WriteTo", Method, 1}, + {"(*Scanner).Buffer", Method, 6}, + {"(*Scanner).Bytes", Method, 1}, + {"(*Scanner).Err", Method, 1}, + {"(*Scanner).Scan", Method, 1}, + {"(*Scanner).Split", Method, 1}, + {"(*Scanner).Text", Method, 1}, + {"(*Writer).Available", Method, 0}, + {"(*Writer).AvailableBuffer", Method, 18}, + {"(*Writer).Buffered", Method, 0}, + {"(*Writer).Flush", Method, 0}, + {"(*Writer).ReadFrom", Method, 1}, + {"(*Writer).Reset", Method, 2}, + {"(*Writer).Size", Method, 10}, + {"(*Writer).Write", Method, 0}, + {"(*Writer).WriteByte", Method, 0}, + {"(*Writer).WriteRune", Method, 0}, + {"(*Writer).WriteString", Method, 0}, + {"(ReadWriter).Available", Method, 0}, + {"(ReadWriter).AvailableBuffer", Method, 18}, + {"(ReadWriter).Discard", Method, 5}, + {"(ReadWriter).Flush", Method, 0}, + {"(ReadWriter).Peek", Method, 0}, + {"(ReadWriter).Read", Method, 0}, + {"(ReadWriter).ReadByte", Method, 0}, + {"(ReadWriter).ReadBytes", Method, 0}, + {"(ReadWriter).ReadFrom", Method, 1}, + {"(ReadWriter).ReadLine", Method, 0}, + {"(ReadWriter).ReadRune", Method, 0}, + {"(ReadWriter).ReadSlice", Method, 0}, + {"(ReadWriter).ReadString", Method, 0}, + {"(ReadWriter).UnreadByte", Method, 0}, + {"(ReadWriter).UnreadRune", Method, 0}, + {"(ReadWriter).Write", Method, 0}, + {"(ReadWriter).WriteByte", Method, 0}, + {"(ReadWriter).WriteRune", Method, 0}, + {"(ReadWriter).WriteString", Method, 0}, + {"(ReadWriter).WriteTo", Method, 1}, + {"ErrAdvanceTooFar", Var, 1}, + {"ErrBadReadCount", Var, 15}, + {"ErrBufferFull", Var, 0}, + {"ErrFinalToken", Var, 6}, + {"ErrInvalidUnreadByte", Var, 0}, + {"ErrInvalidUnreadRune", Var, 0}, + {"ErrNegativeAdvance", Var, 1}, + {"ErrNegativeCount", Var, 0}, + {"ErrTooLong", Var, 1}, + {"MaxScanTokenSize", Const, 1}, + {"NewReadWriter", Func, 0}, + {"NewReader", Func, 0}, + {"NewReaderSize", Func, 0}, + {"NewScanner", Func, 1}, + {"NewWriter", Func, 0}, + {"NewWriterSize", Func, 0}, + {"ReadWriter", Type, 0}, + {"ReadWriter.Reader", Field, 0}, + {"ReadWriter.Writer", Field, 0}, + {"Reader", Type, 0}, + {"ScanBytes", Func, 1}, + {"ScanLines", Func, 1}, + {"ScanRunes", Func, 1}, + {"ScanWords", Func, 1}, + {"Scanner", Type, 1}, + {"SplitFunc", Type, 1}, + {"Writer", Type, 0}, + }, + "bytes": { + {"(*Buffer).Available", Method, 21}, + {"(*Buffer).AvailableBuffer", Method, 21}, + {"(*Buffer).Bytes", Method, 0}, + {"(*Buffer).Cap", Method, 5}, + {"(*Buffer).Grow", Method, 1}, + {"(*Buffer).Len", Method, 0}, + {"(*Buffer).Next", Method, 0}, + {"(*Buffer).Read", Method, 0}, + {"(*Buffer).ReadByte", Method, 0}, + {"(*Buffer).ReadBytes", Method, 0}, + {"(*Buffer).ReadFrom", Method, 0}, + {"(*Buffer).ReadRune", Method, 0}, + {"(*Buffer).ReadString", Method, 0}, + {"(*Buffer).Reset", Method, 0}, + {"(*Buffer).String", Method, 0}, + {"(*Buffer).Truncate", Method, 0}, + {"(*Buffer).UnreadByte", Method, 0}, + {"(*Buffer).UnreadRune", Method, 0}, + {"(*Buffer).Write", Method, 0}, + {"(*Buffer).WriteByte", Method, 0}, + {"(*Buffer).WriteRune", Method, 0}, + {"(*Buffer).WriteString", Method, 0}, + {"(*Buffer).WriteTo", Method, 0}, + {"(*Reader).Len", Method, 0}, + {"(*Reader).Read", Method, 0}, + {"(*Reader).ReadAt", Method, 0}, + {"(*Reader).ReadByte", Method, 0}, + {"(*Reader).ReadRune", Method, 0}, + {"(*Reader).Reset", Method, 7}, + {"(*Reader).Seek", Method, 0}, + {"(*Reader).Size", Method, 5}, + {"(*Reader).UnreadByte", Method, 0}, + {"(*Reader).UnreadRune", Method, 0}, + {"(*Reader).WriteTo", Method, 1}, + {"Buffer", Type, 0}, + {"Clone", Func, 20}, + {"Compare", Func, 0}, + {"Contains", Func, 0}, + {"ContainsAny", Func, 7}, + {"ContainsFunc", Func, 21}, + {"ContainsRune", Func, 7}, + {"Count", Func, 0}, + {"Cut", Func, 18}, + {"CutPrefix", Func, 20}, + {"CutSuffix", Func, 20}, + {"Equal", Func, 0}, + {"EqualFold", Func, 0}, + {"ErrTooLarge", Var, 0}, + {"Fields", Func, 0}, + {"FieldsFunc", Func, 0}, + {"HasPrefix", Func, 0}, + {"HasSuffix", Func, 0}, + {"Index", Func, 0}, + {"IndexAny", Func, 0}, + {"IndexByte", Func, 0}, + {"IndexFunc", Func, 0}, + {"IndexRune", Func, 0}, + {"Join", Func, 0}, + {"LastIndex", Func, 0}, + {"LastIndexAny", Func, 0}, + {"LastIndexByte", Func, 5}, + {"LastIndexFunc", Func, 0}, + {"Map", Func, 0}, + {"MinRead", Const, 0}, + {"NewBuffer", Func, 0}, + {"NewBufferString", Func, 0}, + {"NewReader", Func, 0}, + {"Reader", Type, 0}, + {"Repeat", Func, 0}, + {"Replace", Func, 0}, + {"ReplaceAll", Func, 12}, + {"Runes", Func, 0}, + {"Split", Func, 0}, + {"SplitAfter", Func, 0}, + {"SplitAfterN", Func, 0}, + {"SplitN", Func, 0}, + {"Title", Func, 0}, + {"ToLower", Func, 0}, + {"ToLowerSpecial", Func, 0}, + {"ToTitle", Func, 0}, + {"ToTitleSpecial", Func, 0}, + {"ToUpper", Func, 0}, + {"ToUpperSpecial", Func, 0}, + {"ToValidUTF8", Func, 13}, + {"Trim", Func, 0}, + {"TrimFunc", Func, 0}, + {"TrimLeft", Func, 0}, + {"TrimLeftFunc", Func, 0}, + {"TrimPrefix", Func, 1}, + {"TrimRight", Func, 0}, + {"TrimRightFunc", Func, 0}, + {"TrimSpace", Func, 0}, + {"TrimSuffix", Func, 1}, + }, + "cmp": { + {"Compare", Func, 21}, + {"Less", Func, 21}, + {"Or", Func, 22}, + {"Ordered", Type, 21}, + }, + "compress/bzip2": { + {"(StructuralError).Error", Method, 0}, + {"NewReader", Func, 0}, + {"StructuralError", Type, 0}, + }, + "compress/flate": { + {"(*ReadError).Error", Method, 0}, + {"(*WriteError).Error", Method, 0}, + {"(*Writer).Close", Method, 0}, + {"(*Writer).Flush", Method, 0}, + {"(*Writer).Reset", Method, 2}, + {"(*Writer).Write", Method, 0}, + {"(CorruptInputError).Error", Method, 0}, + {"(InternalError).Error", Method, 0}, + {"BestCompression", Const, 0}, + {"BestSpeed", Const, 0}, + {"CorruptInputError", Type, 0}, + {"DefaultCompression", Const, 0}, + {"HuffmanOnly", Const, 7}, + {"InternalError", Type, 0}, + {"NewReader", Func, 0}, + {"NewReaderDict", Func, 0}, + {"NewWriter", Func, 0}, + {"NewWriterDict", Func, 0}, + {"NoCompression", Const, 0}, + {"ReadError", Type, 0}, + {"ReadError.Err", Field, 0}, + {"ReadError.Offset", Field, 0}, + {"Reader", Type, 0}, + {"Resetter", Type, 4}, + {"WriteError", Type, 0}, + {"WriteError.Err", Field, 0}, + {"WriteError.Offset", Field, 0}, + {"Writer", Type, 0}, + }, + "compress/gzip": { + {"(*Reader).Close", Method, 0}, + {"(*Reader).Multistream", Method, 4}, + {"(*Reader).Read", Method, 0}, + {"(*Reader).Reset", Method, 3}, + {"(*Writer).Close", Method, 0}, + {"(*Writer).Flush", Method, 1}, + {"(*Writer).Reset", Method, 2}, + {"(*Writer).Write", Method, 0}, + {"BestCompression", Const, 0}, + {"BestSpeed", Const, 0}, + {"DefaultCompression", Const, 0}, + {"ErrChecksum", Var, 0}, + {"ErrHeader", Var, 0}, + {"Header", Type, 0}, + {"Header.Comment", Field, 0}, + {"Header.Extra", Field, 0}, + {"Header.ModTime", Field, 0}, + {"Header.Name", Field, 0}, + {"Header.OS", Field, 0}, + {"HuffmanOnly", Const, 8}, + {"NewReader", Func, 0}, + {"NewWriter", Func, 0}, + {"NewWriterLevel", Func, 0}, + {"NoCompression", Const, 0}, + {"Reader", Type, 0}, + {"Reader.Header", Field, 0}, + {"Writer", Type, 0}, + {"Writer.Header", Field, 0}, + }, + "compress/lzw": { + {"(*Reader).Close", Method, 17}, + {"(*Reader).Read", Method, 17}, + {"(*Reader).Reset", Method, 17}, + {"(*Writer).Close", Method, 17}, + {"(*Writer).Reset", Method, 17}, + {"(*Writer).Write", Method, 17}, + {"LSB", Const, 0}, + {"MSB", Const, 0}, + {"NewReader", Func, 0}, + {"NewWriter", Func, 0}, + {"Order", Type, 0}, + {"Reader", Type, 17}, + {"Writer", Type, 17}, + }, + "compress/zlib": { + {"(*Writer).Close", Method, 0}, + {"(*Writer).Flush", Method, 0}, + {"(*Writer).Reset", Method, 2}, + {"(*Writer).Write", Method, 0}, + {"BestCompression", Const, 0}, + {"BestSpeed", Const, 0}, + {"DefaultCompression", Const, 0}, + {"ErrChecksum", Var, 0}, + {"ErrDictionary", Var, 0}, + {"ErrHeader", Var, 0}, + {"HuffmanOnly", Const, 8}, + {"NewReader", Func, 0}, + {"NewReaderDict", Func, 0}, + {"NewWriter", Func, 0}, + {"NewWriterLevel", Func, 0}, + {"NewWriterLevelDict", Func, 0}, + {"NoCompression", Const, 0}, + {"Resetter", Type, 4}, + {"Writer", Type, 0}, + }, + "container/heap": { + {"Fix", Func, 2}, + {"Init", Func, 0}, + {"Interface", Type, 0}, + {"Pop", Func, 0}, + {"Push", Func, 0}, + {"Remove", Func, 0}, + }, + "container/list": { + {"(*Element).Next", Method, 0}, + {"(*Element).Prev", Method, 0}, + {"(*List).Back", Method, 0}, + {"(*List).Front", Method, 0}, + {"(*List).Init", Method, 0}, + {"(*List).InsertAfter", Method, 0}, + {"(*List).InsertBefore", Method, 0}, + {"(*List).Len", Method, 0}, + {"(*List).MoveAfter", Method, 2}, + {"(*List).MoveBefore", Method, 2}, + {"(*List).MoveToBack", Method, 0}, + {"(*List).MoveToFront", Method, 0}, + {"(*List).PushBack", Method, 0}, + {"(*List).PushBackList", Method, 0}, + {"(*List).PushFront", Method, 0}, + {"(*List).PushFrontList", Method, 0}, + {"(*List).Remove", Method, 0}, + {"Element", Type, 0}, + {"Element.Value", Field, 0}, + {"List", Type, 0}, + {"New", Func, 0}, + }, + "container/ring": { + {"(*Ring).Do", Method, 0}, + {"(*Ring).Len", Method, 0}, + {"(*Ring).Link", Method, 0}, + {"(*Ring).Move", Method, 0}, + {"(*Ring).Next", Method, 0}, + {"(*Ring).Prev", Method, 0}, + {"(*Ring).Unlink", Method, 0}, + {"New", Func, 0}, + {"Ring", Type, 0}, + {"Ring.Value", Field, 0}, + }, + "context": { + {"AfterFunc", Func, 21}, + {"Background", Func, 7}, + {"CancelCauseFunc", Type, 20}, + {"CancelFunc", Type, 7}, + {"Canceled", Var, 7}, + {"Cause", Func, 20}, + {"Context", Type, 7}, + {"DeadlineExceeded", Var, 7}, + {"TODO", Func, 7}, + {"WithCancel", Func, 7}, + {"WithCancelCause", Func, 20}, + {"WithDeadline", Func, 7}, + {"WithDeadlineCause", Func, 21}, + {"WithTimeout", Func, 7}, + {"WithTimeoutCause", Func, 21}, + {"WithValue", Func, 7}, + {"WithoutCancel", Func, 21}, + }, + "crypto": { + {"(Hash).Available", Method, 0}, + {"(Hash).HashFunc", Method, 4}, + {"(Hash).New", Method, 0}, + {"(Hash).Size", Method, 0}, + {"(Hash).String", Method, 15}, + {"BLAKE2b_256", Const, 9}, + {"BLAKE2b_384", Const, 9}, + {"BLAKE2b_512", Const, 9}, + {"BLAKE2s_256", Const, 9}, + {"Decrypter", Type, 5}, + {"DecrypterOpts", Type, 5}, + {"Hash", Type, 0}, + {"MD4", Const, 0}, + {"MD5", Const, 0}, + {"MD5SHA1", Const, 0}, + {"PrivateKey", Type, 0}, + {"PublicKey", Type, 2}, + {"RIPEMD160", Const, 0}, + {"RegisterHash", Func, 0}, + {"SHA1", Const, 0}, + {"SHA224", Const, 0}, + {"SHA256", Const, 0}, + {"SHA384", Const, 0}, + {"SHA3_224", Const, 4}, + {"SHA3_256", Const, 4}, + {"SHA3_384", Const, 4}, + {"SHA3_512", Const, 4}, + {"SHA512", Const, 0}, + {"SHA512_224", Const, 5}, + {"SHA512_256", Const, 5}, + {"Signer", Type, 4}, + {"SignerOpts", Type, 4}, + }, + "crypto/aes": { + {"(KeySizeError).Error", Method, 0}, + {"BlockSize", Const, 0}, + {"KeySizeError", Type, 0}, + {"NewCipher", Func, 0}, + }, + "crypto/cipher": { + {"(StreamReader).Read", Method, 0}, + {"(StreamWriter).Close", Method, 0}, + {"(StreamWriter).Write", Method, 0}, + {"AEAD", Type, 2}, + {"Block", Type, 0}, + {"BlockMode", Type, 0}, + {"NewCBCDecrypter", Func, 0}, + {"NewCBCEncrypter", Func, 0}, + {"NewCFBDecrypter", Func, 0}, + {"NewCFBEncrypter", Func, 0}, + {"NewCTR", Func, 0}, + {"NewGCM", Func, 2}, + {"NewGCMWithNonceSize", Func, 5}, + {"NewGCMWithTagSize", Func, 11}, + {"NewOFB", Func, 0}, + {"Stream", Type, 0}, + {"StreamReader", Type, 0}, + {"StreamReader.R", Field, 0}, + {"StreamReader.S", Field, 0}, + {"StreamWriter", Type, 0}, + {"StreamWriter.Err", Field, 0}, + {"StreamWriter.S", Field, 0}, + {"StreamWriter.W", Field, 0}, + }, + "crypto/des": { + {"(KeySizeError).Error", Method, 0}, + {"BlockSize", Const, 0}, + {"KeySizeError", Type, 0}, + {"NewCipher", Func, 0}, + {"NewTripleDESCipher", Func, 0}, + }, + "crypto/dsa": { + {"ErrInvalidPublicKey", Var, 0}, + {"GenerateKey", Func, 0}, + {"GenerateParameters", Func, 0}, + {"L1024N160", Const, 0}, + {"L2048N224", Const, 0}, + {"L2048N256", Const, 0}, + {"L3072N256", Const, 0}, + {"ParameterSizes", Type, 0}, + {"Parameters", Type, 0}, + {"Parameters.G", Field, 0}, + {"Parameters.P", Field, 0}, + {"Parameters.Q", Field, 0}, + {"PrivateKey", Type, 0}, + {"PrivateKey.PublicKey", Field, 0}, + {"PrivateKey.X", Field, 0}, + {"PublicKey", Type, 0}, + {"PublicKey.Parameters", Field, 0}, + {"PublicKey.Y", Field, 0}, + {"Sign", Func, 0}, + {"Verify", Func, 0}, + }, + "crypto/ecdh": { + {"(*PrivateKey).Bytes", Method, 20}, + {"(*PrivateKey).Curve", Method, 20}, + {"(*PrivateKey).ECDH", Method, 20}, + {"(*PrivateKey).Equal", Method, 20}, + {"(*PrivateKey).Public", Method, 20}, + {"(*PrivateKey).PublicKey", Method, 20}, + {"(*PublicKey).Bytes", Method, 20}, + {"(*PublicKey).Curve", Method, 20}, + {"(*PublicKey).Equal", Method, 20}, + {"Curve", Type, 20}, + {"P256", Func, 20}, + {"P384", Func, 20}, + {"P521", Func, 20}, + {"PrivateKey", Type, 20}, + {"PublicKey", Type, 20}, + {"X25519", Func, 20}, + }, + "crypto/ecdsa": { + {"(*PrivateKey).ECDH", Method, 20}, + {"(*PrivateKey).Equal", Method, 15}, + {"(*PrivateKey).Public", Method, 4}, + {"(*PrivateKey).Sign", Method, 4}, + {"(*PublicKey).ECDH", Method, 20}, + {"(*PublicKey).Equal", Method, 15}, + {"(PrivateKey).Add", Method, 0}, + {"(PrivateKey).Double", Method, 0}, + {"(PrivateKey).IsOnCurve", Method, 0}, + {"(PrivateKey).Params", Method, 0}, + {"(PrivateKey).ScalarBaseMult", Method, 0}, + {"(PrivateKey).ScalarMult", Method, 0}, + {"(PublicKey).Add", Method, 0}, + {"(PublicKey).Double", Method, 0}, + {"(PublicKey).IsOnCurve", Method, 0}, + {"(PublicKey).Params", Method, 0}, + {"(PublicKey).ScalarBaseMult", Method, 0}, + {"(PublicKey).ScalarMult", Method, 0}, + {"GenerateKey", Func, 0}, + {"PrivateKey", Type, 0}, + {"PrivateKey.D", Field, 0}, + {"PrivateKey.PublicKey", Field, 0}, + {"PublicKey", Type, 0}, + {"PublicKey.Curve", Field, 0}, + {"PublicKey.X", Field, 0}, + {"PublicKey.Y", Field, 0}, + {"Sign", Func, 0}, + {"SignASN1", Func, 15}, + {"Verify", Func, 0}, + {"VerifyASN1", Func, 15}, + }, + "crypto/ed25519": { + {"(*Options).HashFunc", Method, 20}, + {"(PrivateKey).Equal", Method, 15}, + {"(PrivateKey).Public", Method, 13}, + {"(PrivateKey).Seed", Method, 13}, + {"(PrivateKey).Sign", Method, 13}, + {"(PublicKey).Equal", Method, 15}, + {"GenerateKey", Func, 13}, + {"NewKeyFromSeed", Func, 13}, + {"Options", Type, 20}, + {"Options.Context", Field, 20}, + {"Options.Hash", Field, 20}, + {"PrivateKey", Type, 13}, + {"PrivateKeySize", Const, 13}, + {"PublicKey", Type, 13}, + {"PublicKeySize", Const, 13}, + {"SeedSize", Const, 13}, + {"Sign", Func, 13}, + {"SignatureSize", Const, 13}, + {"Verify", Func, 13}, + {"VerifyWithOptions", Func, 20}, + }, + "crypto/elliptic": { + {"(*CurveParams).Add", Method, 0}, + {"(*CurveParams).Double", Method, 0}, + {"(*CurveParams).IsOnCurve", Method, 0}, + {"(*CurveParams).Params", Method, 0}, + {"(*CurveParams).ScalarBaseMult", Method, 0}, + {"(*CurveParams).ScalarMult", Method, 0}, + {"Curve", Type, 0}, + {"CurveParams", Type, 0}, + {"CurveParams.B", Field, 0}, + {"CurveParams.BitSize", Field, 0}, + {"CurveParams.Gx", Field, 0}, + {"CurveParams.Gy", Field, 0}, + {"CurveParams.N", Field, 0}, + {"CurveParams.Name", Field, 5}, + {"CurveParams.P", Field, 0}, + {"GenerateKey", Func, 0}, + {"Marshal", Func, 0}, + {"MarshalCompressed", Func, 15}, + {"P224", Func, 0}, + {"P256", Func, 0}, + {"P384", Func, 0}, + {"P521", Func, 0}, + {"Unmarshal", Func, 0}, + {"UnmarshalCompressed", Func, 15}, + }, + "crypto/hmac": { + {"Equal", Func, 1}, + {"New", Func, 0}, + }, + "crypto/md5": { + {"BlockSize", Const, 0}, + {"New", Func, 0}, + {"Size", Const, 0}, + {"Sum", Func, 2}, + }, + "crypto/rand": { + {"Int", Func, 0}, + {"Prime", Func, 0}, + {"Read", Func, 0}, + {"Reader", Var, 0}, + }, + "crypto/rc4": { + {"(*Cipher).Reset", Method, 0}, + {"(*Cipher).XORKeyStream", Method, 0}, + {"(KeySizeError).Error", Method, 0}, + {"Cipher", Type, 0}, + {"KeySizeError", Type, 0}, + {"NewCipher", Func, 0}, + }, + "crypto/rsa": { + {"(*PSSOptions).HashFunc", Method, 4}, + {"(*PrivateKey).Decrypt", Method, 5}, + {"(*PrivateKey).Equal", Method, 15}, + {"(*PrivateKey).Precompute", Method, 0}, + {"(*PrivateKey).Public", Method, 4}, + {"(*PrivateKey).Sign", Method, 4}, + {"(*PrivateKey).Size", Method, 11}, + {"(*PrivateKey).Validate", Method, 0}, + {"(*PublicKey).Equal", Method, 15}, + {"(*PublicKey).Size", Method, 11}, + {"CRTValue", Type, 0}, + {"CRTValue.Coeff", Field, 0}, + {"CRTValue.Exp", Field, 0}, + {"CRTValue.R", Field, 0}, + {"DecryptOAEP", Func, 0}, + {"DecryptPKCS1v15", Func, 0}, + {"DecryptPKCS1v15SessionKey", Func, 0}, + {"EncryptOAEP", Func, 0}, + {"EncryptPKCS1v15", Func, 0}, + {"ErrDecryption", Var, 0}, + {"ErrMessageTooLong", Var, 0}, + {"ErrVerification", Var, 0}, + {"GenerateKey", Func, 0}, + {"GenerateMultiPrimeKey", Func, 0}, + {"OAEPOptions", Type, 5}, + {"OAEPOptions.Hash", Field, 5}, + {"OAEPOptions.Label", Field, 5}, + {"OAEPOptions.MGFHash", Field, 20}, + {"PKCS1v15DecryptOptions", Type, 5}, + {"PKCS1v15DecryptOptions.SessionKeyLen", Field, 5}, + {"PSSOptions", Type, 2}, + {"PSSOptions.Hash", Field, 4}, + {"PSSOptions.SaltLength", Field, 2}, + {"PSSSaltLengthAuto", Const, 2}, + {"PSSSaltLengthEqualsHash", Const, 2}, + {"PrecomputedValues", Type, 0}, + {"PrecomputedValues.CRTValues", Field, 0}, + {"PrecomputedValues.Dp", Field, 0}, + {"PrecomputedValues.Dq", Field, 0}, + {"PrecomputedValues.Qinv", Field, 0}, + {"PrivateKey", Type, 0}, + {"PrivateKey.D", Field, 0}, + {"PrivateKey.Precomputed", Field, 0}, + {"PrivateKey.Primes", Field, 0}, + {"PrivateKey.PublicKey", Field, 0}, + {"PublicKey", Type, 0}, + {"PublicKey.E", Field, 0}, + {"PublicKey.N", Field, 0}, + {"SignPKCS1v15", Func, 0}, + {"SignPSS", Func, 2}, + {"VerifyPKCS1v15", Func, 0}, + {"VerifyPSS", Func, 2}, + }, + "crypto/sha1": { + {"BlockSize", Const, 0}, + {"New", Func, 0}, + {"Size", Const, 0}, + {"Sum", Func, 2}, + }, + "crypto/sha256": { + {"BlockSize", Const, 0}, + {"New", Func, 0}, + {"New224", Func, 0}, + {"Size", Const, 0}, + {"Size224", Const, 0}, + {"Sum224", Func, 2}, + {"Sum256", Func, 2}, + }, + "crypto/sha512": { + {"BlockSize", Const, 0}, + {"New", Func, 0}, + {"New384", Func, 0}, + {"New512_224", Func, 5}, + {"New512_256", Func, 5}, + {"Size", Const, 0}, + {"Size224", Const, 5}, + {"Size256", Const, 5}, + {"Size384", Const, 0}, + {"Sum384", Func, 2}, + {"Sum512", Func, 2}, + {"Sum512_224", Func, 5}, + {"Sum512_256", Func, 5}, + }, + "crypto/subtle": { + {"ConstantTimeByteEq", Func, 0}, + {"ConstantTimeCompare", Func, 0}, + {"ConstantTimeCopy", Func, 0}, + {"ConstantTimeEq", Func, 0}, + {"ConstantTimeLessOrEq", Func, 2}, + {"ConstantTimeSelect", Func, 0}, + {"XORBytes", Func, 20}, + }, + "crypto/tls": { + {"(*CertificateRequestInfo).Context", Method, 17}, + {"(*CertificateRequestInfo).SupportsCertificate", Method, 14}, + {"(*CertificateVerificationError).Error", Method, 20}, + {"(*CertificateVerificationError).Unwrap", Method, 20}, + {"(*ClientHelloInfo).Context", Method, 17}, + {"(*ClientHelloInfo).SupportsCertificate", Method, 14}, + {"(*ClientSessionState).ResumptionState", Method, 21}, + {"(*Config).BuildNameToCertificate", Method, 0}, + {"(*Config).Clone", Method, 8}, + {"(*Config).DecryptTicket", Method, 21}, + {"(*Config).EncryptTicket", Method, 21}, + {"(*Config).SetSessionTicketKeys", Method, 5}, + {"(*Conn).Close", Method, 0}, + {"(*Conn).CloseWrite", Method, 8}, + {"(*Conn).ConnectionState", Method, 0}, + {"(*Conn).Handshake", Method, 0}, + {"(*Conn).HandshakeContext", Method, 17}, + {"(*Conn).LocalAddr", Method, 0}, + {"(*Conn).NetConn", Method, 18}, + {"(*Conn).OCSPResponse", Method, 0}, + {"(*Conn).Read", Method, 0}, + {"(*Conn).RemoteAddr", Method, 0}, + {"(*Conn).SetDeadline", Method, 0}, + {"(*Conn).SetReadDeadline", Method, 0}, + {"(*Conn).SetWriteDeadline", Method, 0}, + {"(*Conn).VerifyHostname", Method, 0}, + {"(*Conn).Write", Method, 0}, + {"(*ConnectionState).ExportKeyingMaterial", Method, 11}, + {"(*Dialer).Dial", Method, 15}, + {"(*Dialer).DialContext", Method, 15}, + {"(*ECHRejectionError).Error", Method, 23}, + {"(*QUICConn).Close", Method, 21}, + {"(*QUICConn).ConnectionState", Method, 21}, + {"(*QUICConn).HandleData", Method, 21}, + {"(*QUICConn).NextEvent", Method, 21}, + {"(*QUICConn).SendSessionTicket", Method, 21}, + {"(*QUICConn).SetTransportParameters", Method, 21}, + {"(*QUICConn).Start", Method, 21}, + {"(*QUICConn).StoreSession", Method, 23}, + {"(*SessionState).Bytes", Method, 21}, + {"(AlertError).Error", Method, 21}, + {"(ClientAuthType).String", Method, 15}, + {"(CurveID).String", Method, 15}, + {"(QUICEncryptionLevel).String", Method, 21}, + {"(RecordHeaderError).Error", Method, 6}, + {"(SignatureScheme).String", Method, 15}, + {"AlertError", Type, 21}, + {"Certificate", Type, 0}, + {"Certificate.Certificate", Field, 0}, + {"Certificate.Leaf", Field, 0}, + {"Certificate.OCSPStaple", Field, 0}, + {"Certificate.PrivateKey", Field, 0}, + {"Certificate.SignedCertificateTimestamps", Field, 5}, + {"Certificate.SupportedSignatureAlgorithms", Field, 14}, + {"CertificateRequestInfo", Type, 8}, + {"CertificateRequestInfo.AcceptableCAs", Field, 8}, + {"CertificateRequestInfo.SignatureSchemes", Field, 8}, + {"CertificateRequestInfo.Version", Field, 14}, + {"CertificateVerificationError", Type, 20}, + {"CertificateVerificationError.Err", Field, 20}, + {"CertificateVerificationError.UnverifiedCertificates", Field, 20}, + {"CipherSuite", Type, 14}, + {"CipherSuite.ID", Field, 14}, + {"CipherSuite.Insecure", Field, 14}, + {"CipherSuite.Name", Field, 14}, + {"CipherSuite.SupportedVersions", Field, 14}, + {"CipherSuiteName", Func, 14}, + {"CipherSuites", Func, 14}, + {"Client", Func, 0}, + {"ClientAuthType", Type, 0}, + {"ClientHelloInfo", Type, 4}, + {"ClientHelloInfo.CipherSuites", Field, 4}, + {"ClientHelloInfo.Conn", Field, 8}, + {"ClientHelloInfo.ServerName", Field, 4}, + {"ClientHelloInfo.SignatureSchemes", Field, 8}, + {"ClientHelloInfo.SupportedCurves", Field, 4}, + {"ClientHelloInfo.SupportedPoints", Field, 4}, + {"ClientHelloInfo.SupportedProtos", Field, 8}, + {"ClientHelloInfo.SupportedVersions", Field, 8}, + {"ClientSessionCache", Type, 3}, + {"ClientSessionState", Type, 3}, + {"Config", Type, 0}, + {"Config.Certificates", Field, 0}, + {"Config.CipherSuites", Field, 0}, + {"Config.ClientAuth", Field, 0}, + {"Config.ClientCAs", Field, 0}, + {"Config.ClientSessionCache", Field, 3}, + {"Config.CurvePreferences", Field, 3}, + {"Config.DynamicRecordSizingDisabled", Field, 7}, + {"Config.EncryptedClientHelloConfigList", Field, 23}, + {"Config.EncryptedClientHelloRejectionVerify", Field, 23}, + {"Config.GetCertificate", Field, 4}, + {"Config.GetClientCertificate", Field, 8}, + {"Config.GetConfigForClient", Field, 8}, + {"Config.InsecureSkipVerify", Field, 0}, + {"Config.KeyLogWriter", Field, 8}, + {"Config.MaxVersion", Field, 2}, + {"Config.MinVersion", Field, 2}, + {"Config.NameToCertificate", Field, 0}, + {"Config.NextProtos", Field, 0}, + {"Config.PreferServerCipherSuites", Field, 1}, + {"Config.Rand", Field, 0}, + {"Config.Renegotiation", Field, 7}, + {"Config.RootCAs", Field, 0}, + {"Config.ServerName", Field, 0}, + {"Config.SessionTicketKey", Field, 1}, + {"Config.SessionTicketsDisabled", Field, 1}, + {"Config.Time", Field, 0}, + {"Config.UnwrapSession", Field, 21}, + {"Config.VerifyConnection", Field, 15}, + {"Config.VerifyPeerCertificate", Field, 8}, + {"Config.WrapSession", Field, 21}, + {"Conn", Type, 0}, + {"ConnectionState", Type, 0}, + {"ConnectionState.CipherSuite", Field, 0}, + {"ConnectionState.DidResume", Field, 1}, + {"ConnectionState.ECHAccepted", Field, 23}, + {"ConnectionState.HandshakeComplete", Field, 0}, + {"ConnectionState.NegotiatedProtocol", Field, 0}, + {"ConnectionState.NegotiatedProtocolIsMutual", Field, 0}, + {"ConnectionState.OCSPResponse", Field, 5}, + {"ConnectionState.PeerCertificates", Field, 0}, + {"ConnectionState.ServerName", Field, 0}, + {"ConnectionState.SignedCertificateTimestamps", Field, 5}, + {"ConnectionState.TLSUnique", Field, 4}, + {"ConnectionState.VerifiedChains", Field, 0}, + {"ConnectionState.Version", Field, 3}, + {"CurveID", Type, 3}, + {"CurveP256", Const, 3}, + {"CurveP384", Const, 3}, + {"CurveP521", Const, 3}, + {"Dial", Func, 0}, + {"DialWithDialer", Func, 3}, + {"Dialer", Type, 15}, + {"Dialer.Config", Field, 15}, + {"Dialer.NetDialer", Field, 15}, + {"ECDSAWithP256AndSHA256", Const, 8}, + {"ECDSAWithP384AndSHA384", Const, 8}, + {"ECDSAWithP521AndSHA512", Const, 8}, + {"ECDSAWithSHA1", Const, 10}, + {"ECHRejectionError", Type, 23}, + {"ECHRejectionError.RetryConfigList", Field, 23}, + {"Ed25519", Const, 13}, + {"InsecureCipherSuites", Func, 14}, + {"Listen", Func, 0}, + {"LoadX509KeyPair", Func, 0}, + {"NewLRUClientSessionCache", Func, 3}, + {"NewListener", Func, 0}, + {"NewResumptionState", Func, 21}, + {"NoClientCert", Const, 0}, + {"PKCS1WithSHA1", Const, 8}, + {"PKCS1WithSHA256", Const, 8}, + {"PKCS1WithSHA384", Const, 8}, + {"PKCS1WithSHA512", Const, 8}, + {"PSSWithSHA256", Const, 8}, + {"PSSWithSHA384", Const, 8}, + {"PSSWithSHA512", Const, 8}, + {"ParseSessionState", Func, 21}, + {"QUICClient", Func, 21}, + {"QUICConfig", Type, 21}, + {"QUICConfig.EnableStoreSessionEvent", Field, 23}, + {"QUICConfig.TLSConfig", Field, 21}, + {"QUICConn", Type, 21}, + {"QUICEncryptionLevel", Type, 21}, + {"QUICEncryptionLevelApplication", Const, 21}, + {"QUICEncryptionLevelEarly", Const, 21}, + {"QUICEncryptionLevelHandshake", Const, 21}, + {"QUICEncryptionLevelInitial", Const, 21}, + {"QUICEvent", Type, 21}, + {"QUICEvent.Data", Field, 21}, + {"QUICEvent.Kind", Field, 21}, + {"QUICEvent.Level", Field, 21}, + {"QUICEvent.SessionState", Field, 23}, + {"QUICEvent.Suite", Field, 21}, + {"QUICEventKind", Type, 21}, + {"QUICHandshakeDone", Const, 21}, + {"QUICNoEvent", Const, 21}, + {"QUICRejectedEarlyData", Const, 21}, + {"QUICResumeSession", Const, 23}, + {"QUICServer", Func, 21}, + {"QUICSessionTicketOptions", Type, 21}, + {"QUICSessionTicketOptions.EarlyData", Field, 21}, + {"QUICSessionTicketOptions.Extra", Field, 23}, + {"QUICSetReadSecret", Const, 21}, + {"QUICSetWriteSecret", Const, 21}, + {"QUICStoreSession", Const, 23}, + {"QUICTransportParameters", Const, 21}, + {"QUICTransportParametersRequired", Const, 21}, + {"QUICWriteData", Const, 21}, + {"RecordHeaderError", Type, 6}, + {"RecordHeaderError.Conn", Field, 12}, + {"RecordHeaderError.Msg", Field, 6}, + {"RecordHeaderError.RecordHeader", Field, 6}, + {"RenegotiateFreelyAsClient", Const, 7}, + {"RenegotiateNever", Const, 7}, + {"RenegotiateOnceAsClient", Const, 7}, + {"RenegotiationSupport", Type, 7}, + {"RequestClientCert", Const, 0}, + {"RequireAndVerifyClientCert", Const, 0}, + {"RequireAnyClientCert", Const, 0}, + {"Server", Func, 0}, + {"SessionState", Type, 21}, + {"SessionState.EarlyData", Field, 21}, + {"SessionState.Extra", Field, 21}, + {"SignatureScheme", Type, 8}, + {"TLS_AES_128_GCM_SHA256", Const, 12}, + {"TLS_AES_256_GCM_SHA384", Const, 12}, + {"TLS_CHACHA20_POLY1305_SHA256", Const, 12}, + {"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", Const, 2}, + {"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", Const, 8}, + {"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", Const, 2}, + {"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", Const, 2}, + {"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", Const, 5}, + {"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", Const, 8}, + {"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", Const, 14}, + {"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", Const, 2}, + {"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", Const, 0}, + {"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", Const, 0}, + {"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", Const, 8}, + {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", Const, 2}, + {"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", Const, 1}, + {"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", Const, 5}, + {"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", Const, 8}, + {"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", Const, 14}, + {"TLS_ECDHE_RSA_WITH_RC4_128_SHA", Const, 0}, + {"TLS_FALLBACK_SCSV", Const, 4}, + {"TLS_RSA_WITH_3DES_EDE_CBC_SHA", Const, 0}, + {"TLS_RSA_WITH_AES_128_CBC_SHA", Const, 0}, + {"TLS_RSA_WITH_AES_128_CBC_SHA256", Const, 8}, + {"TLS_RSA_WITH_AES_128_GCM_SHA256", Const, 6}, + {"TLS_RSA_WITH_AES_256_CBC_SHA", Const, 1}, + {"TLS_RSA_WITH_AES_256_GCM_SHA384", Const, 6}, + {"TLS_RSA_WITH_RC4_128_SHA", Const, 0}, + {"VerifyClientCertIfGiven", Const, 0}, + {"VersionName", Func, 21}, + {"VersionSSL30", Const, 2}, + {"VersionTLS10", Const, 2}, + {"VersionTLS11", Const, 2}, + {"VersionTLS12", Const, 2}, + {"VersionTLS13", Const, 12}, + {"X25519", Const, 8}, + {"X509KeyPair", Func, 0}, + }, + "crypto/x509": { + {"(*CertPool).AddCert", Method, 0}, + {"(*CertPool).AddCertWithConstraint", Method, 22}, + {"(*CertPool).AppendCertsFromPEM", Method, 0}, + {"(*CertPool).Clone", Method, 19}, + {"(*CertPool).Equal", Method, 19}, + {"(*CertPool).Subjects", Method, 0}, + {"(*Certificate).CheckCRLSignature", Method, 0}, + {"(*Certificate).CheckSignature", Method, 0}, + {"(*Certificate).CheckSignatureFrom", Method, 0}, + {"(*Certificate).CreateCRL", Method, 0}, + {"(*Certificate).Equal", Method, 0}, + {"(*Certificate).Verify", Method, 0}, + {"(*Certificate).VerifyHostname", Method, 0}, + {"(*CertificateRequest).CheckSignature", Method, 5}, + {"(*OID).UnmarshalBinary", Method, 23}, + {"(*OID).UnmarshalText", Method, 23}, + {"(*RevocationList).CheckSignatureFrom", Method, 19}, + {"(CertificateInvalidError).Error", Method, 0}, + {"(ConstraintViolationError).Error", Method, 0}, + {"(HostnameError).Error", Method, 0}, + {"(InsecureAlgorithmError).Error", Method, 6}, + {"(OID).Equal", Method, 22}, + {"(OID).EqualASN1OID", Method, 22}, + {"(OID).MarshalBinary", Method, 23}, + {"(OID).MarshalText", Method, 23}, + {"(OID).String", Method, 22}, + {"(PublicKeyAlgorithm).String", Method, 10}, + {"(SignatureAlgorithm).String", Method, 6}, + {"(SystemRootsError).Error", Method, 1}, + {"(SystemRootsError).Unwrap", Method, 16}, + {"(UnhandledCriticalExtension).Error", Method, 0}, + {"(UnknownAuthorityError).Error", Method, 0}, + {"CANotAuthorizedForExtKeyUsage", Const, 10}, + {"CANotAuthorizedForThisName", Const, 0}, + {"CertPool", Type, 0}, + {"Certificate", Type, 0}, + {"Certificate.AuthorityKeyId", Field, 0}, + {"Certificate.BasicConstraintsValid", Field, 0}, + {"Certificate.CRLDistributionPoints", Field, 2}, + {"Certificate.DNSNames", Field, 0}, + {"Certificate.EmailAddresses", Field, 0}, + {"Certificate.ExcludedDNSDomains", Field, 9}, + {"Certificate.ExcludedEmailAddresses", Field, 10}, + {"Certificate.ExcludedIPRanges", Field, 10}, + {"Certificate.ExcludedURIDomains", Field, 10}, + {"Certificate.ExtKeyUsage", Field, 0}, + {"Certificate.Extensions", Field, 2}, + {"Certificate.ExtraExtensions", Field, 2}, + {"Certificate.IPAddresses", Field, 1}, + {"Certificate.IsCA", Field, 0}, + {"Certificate.Issuer", Field, 0}, + {"Certificate.IssuingCertificateURL", Field, 2}, + {"Certificate.KeyUsage", Field, 0}, + {"Certificate.MaxPathLen", Field, 0}, + {"Certificate.MaxPathLenZero", Field, 4}, + {"Certificate.NotAfter", Field, 0}, + {"Certificate.NotBefore", Field, 0}, + {"Certificate.OCSPServer", Field, 2}, + {"Certificate.PermittedDNSDomains", Field, 0}, + {"Certificate.PermittedDNSDomainsCritical", Field, 0}, + {"Certificate.PermittedEmailAddresses", Field, 10}, + {"Certificate.PermittedIPRanges", Field, 10}, + {"Certificate.PermittedURIDomains", Field, 10}, + {"Certificate.Policies", Field, 22}, + {"Certificate.PolicyIdentifiers", Field, 0}, + {"Certificate.PublicKey", Field, 0}, + {"Certificate.PublicKeyAlgorithm", Field, 0}, + {"Certificate.Raw", Field, 0}, + {"Certificate.RawIssuer", Field, 0}, + {"Certificate.RawSubject", Field, 0}, + {"Certificate.RawSubjectPublicKeyInfo", Field, 0}, + {"Certificate.RawTBSCertificate", Field, 0}, + {"Certificate.SerialNumber", Field, 0}, + {"Certificate.Signature", Field, 0}, + {"Certificate.SignatureAlgorithm", Field, 0}, + {"Certificate.Subject", Field, 0}, + {"Certificate.SubjectKeyId", Field, 0}, + {"Certificate.URIs", Field, 10}, + {"Certificate.UnhandledCriticalExtensions", Field, 5}, + {"Certificate.UnknownExtKeyUsage", Field, 0}, + {"Certificate.Version", Field, 0}, + {"CertificateInvalidError", Type, 0}, + {"CertificateInvalidError.Cert", Field, 0}, + {"CertificateInvalidError.Detail", Field, 10}, + {"CertificateInvalidError.Reason", Field, 0}, + {"CertificateRequest", Type, 3}, + {"CertificateRequest.Attributes", Field, 3}, + {"CertificateRequest.DNSNames", Field, 3}, + {"CertificateRequest.EmailAddresses", Field, 3}, + {"CertificateRequest.Extensions", Field, 3}, + {"CertificateRequest.ExtraExtensions", Field, 3}, + {"CertificateRequest.IPAddresses", Field, 3}, + {"CertificateRequest.PublicKey", Field, 3}, + {"CertificateRequest.PublicKeyAlgorithm", Field, 3}, + {"CertificateRequest.Raw", Field, 3}, + {"CertificateRequest.RawSubject", Field, 3}, + {"CertificateRequest.RawSubjectPublicKeyInfo", Field, 3}, + {"CertificateRequest.RawTBSCertificateRequest", Field, 3}, + {"CertificateRequest.Signature", Field, 3}, + {"CertificateRequest.SignatureAlgorithm", Field, 3}, + {"CertificateRequest.Subject", Field, 3}, + {"CertificateRequest.URIs", Field, 10}, + {"CertificateRequest.Version", Field, 3}, + {"ConstraintViolationError", Type, 0}, + {"CreateCertificate", Func, 0}, + {"CreateCertificateRequest", Func, 3}, + {"CreateRevocationList", Func, 15}, + {"DSA", Const, 0}, + {"DSAWithSHA1", Const, 0}, + {"DSAWithSHA256", Const, 0}, + {"DecryptPEMBlock", Func, 1}, + {"ECDSA", Const, 1}, + {"ECDSAWithSHA1", Const, 1}, + {"ECDSAWithSHA256", Const, 1}, + {"ECDSAWithSHA384", Const, 1}, + {"ECDSAWithSHA512", Const, 1}, + {"Ed25519", Const, 13}, + {"EncryptPEMBlock", Func, 1}, + {"ErrUnsupportedAlgorithm", Var, 0}, + {"Expired", Const, 0}, + {"ExtKeyUsage", Type, 0}, + {"ExtKeyUsageAny", Const, 0}, + {"ExtKeyUsageClientAuth", Const, 0}, + {"ExtKeyUsageCodeSigning", Const, 0}, + {"ExtKeyUsageEmailProtection", Const, 0}, + {"ExtKeyUsageIPSECEndSystem", Const, 1}, + {"ExtKeyUsageIPSECTunnel", Const, 1}, + {"ExtKeyUsageIPSECUser", Const, 1}, + {"ExtKeyUsageMicrosoftCommercialCodeSigning", Const, 10}, + {"ExtKeyUsageMicrosoftKernelCodeSigning", Const, 10}, + {"ExtKeyUsageMicrosoftServerGatedCrypto", Const, 1}, + {"ExtKeyUsageNetscapeServerGatedCrypto", Const, 1}, + {"ExtKeyUsageOCSPSigning", Const, 0}, + {"ExtKeyUsageServerAuth", Const, 0}, + {"ExtKeyUsageTimeStamping", Const, 0}, + {"HostnameError", Type, 0}, + {"HostnameError.Certificate", Field, 0}, + {"HostnameError.Host", Field, 0}, + {"IncompatibleUsage", Const, 1}, + {"IncorrectPasswordError", Var, 1}, + {"InsecureAlgorithmError", Type, 6}, + {"InvalidReason", Type, 0}, + {"IsEncryptedPEMBlock", Func, 1}, + {"KeyUsage", Type, 0}, + {"KeyUsageCRLSign", Const, 0}, + {"KeyUsageCertSign", Const, 0}, + {"KeyUsageContentCommitment", Const, 0}, + {"KeyUsageDataEncipherment", Const, 0}, + {"KeyUsageDecipherOnly", Const, 0}, + {"KeyUsageDigitalSignature", Const, 0}, + {"KeyUsageEncipherOnly", Const, 0}, + {"KeyUsageKeyAgreement", Const, 0}, + {"KeyUsageKeyEncipherment", Const, 0}, + {"MD2WithRSA", Const, 0}, + {"MD5WithRSA", Const, 0}, + {"MarshalECPrivateKey", Func, 2}, + {"MarshalPKCS1PrivateKey", Func, 0}, + {"MarshalPKCS1PublicKey", Func, 10}, + {"MarshalPKCS8PrivateKey", Func, 10}, + {"MarshalPKIXPublicKey", Func, 0}, + {"NameConstraintsWithoutSANs", Const, 10}, + {"NameMismatch", Const, 8}, + {"NewCertPool", Func, 0}, + {"NotAuthorizedToSign", Const, 0}, + {"OID", Type, 22}, + {"OIDFromInts", Func, 22}, + {"PEMCipher", Type, 1}, + {"PEMCipher3DES", Const, 1}, + {"PEMCipherAES128", Const, 1}, + {"PEMCipherAES192", Const, 1}, + {"PEMCipherAES256", Const, 1}, + {"PEMCipherDES", Const, 1}, + {"ParseCRL", Func, 0}, + {"ParseCertificate", Func, 0}, + {"ParseCertificateRequest", Func, 3}, + {"ParseCertificates", Func, 0}, + {"ParseDERCRL", Func, 0}, + {"ParseECPrivateKey", Func, 1}, + {"ParseOID", Func, 23}, + {"ParsePKCS1PrivateKey", Func, 0}, + {"ParsePKCS1PublicKey", Func, 10}, + {"ParsePKCS8PrivateKey", Func, 0}, + {"ParsePKIXPublicKey", Func, 0}, + {"ParseRevocationList", Func, 19}, + {"PublicKeyAlgorithm", Type, 0}, + {"PureEd25519", Const, 13}, + {"RSA", Const, 0}, + {"RevocationList", Type, 15}, + {"RevocationList.AuthorityKeyId", Field, 19}, + {"RevocationList.Extensions", Field, 19}, + {"RevocationList.ExtraExtensions", Field, 15}, + {"RevocationList.Issuer", Field, 19}, + {"RevocationList.NextUpdate", Field, 15}, + {"RevocationList.Number", Field, 15}, + {"RevocationList.Raw", Field, 19}, + {"RevocationList.RawIssuer", Field, 19}, + {"RevocationList.RawTBSRevocationList", Field, 19}, + {"RevocationList.RevokedCertificateEntries", Field, 21}, + {"RevocationList.RevokedCertificates", Field, 15}, + {"RevocationList.Signature", Field, 19}, + {"RevocationList.SignatureAlgorithm", Field, 15}, + {"RevocationList.ThisUpdate", Field, 15}, + {"RevocationListEntry", Type, 21}, + {"RevocationListEntry.Extensions", Field, 21}, + {"RevocationListEntry.ExtraExtensions", Field, 21}, + {"RevocationListEntry.Raw", Field, 21}, + {"RevocationListEntry.ReasonCode", Field, 21}, + {"RevocationListEntry.RevocationTime", Field, 21}, + {"RevocationListEntry.SerialNumber", Field, 21}, + {"SHA1WithRSA", Const, 0}, + {"SHA256WithRSA", Const, 0}, + {"SHA256WithRSAPSS", Const, 8}, + {"SHA384WithRSA", Const, 0}, + {"SHA384WithRSAPSS", Const, 8}, + {"SHA512WithRSA", Const, 0}, + {"SHA512WithRSAPSS", Const, 8}, + {"SetFallbackRoots", Func, 20}, + {"SignatureAlgorithm", Type, 0}, + {"SystemCertPool", Func, 7}, + {"SystemRootsError", Type, 1}, + {"SystemRootsError.Err", Field, 7}, + {"TooManyConstraints", Const, 10}, + {"TooManyIntermediates", Const, 0}, + {"UnconstrainedName", Const, 10}, + {"UnhandledCriticalExtension", Type, 0}, + {"UnknownAuthorityError", Type, 0}, + {"UnknownAuthorityError.Cert", Field, 8}, + {"UnknownPublicKeyAlgorithm", Const, 0}, + {"UnknownSignatureAlgorithm", Const, 0}, + {"VerifyOptions", Type, 0}, + {"VerifyOptions.CurrentTime", Field, 0}, + {"VerifyOptions.DNSName", Field, 0}, + {"VerifyOptions.Intermediates", Field, 0}, + {"VerifyOptions.KeyUsages", Field, 1}, + {"VerifyOptions.MaxConstraintComparisions", Field, 10}, + {"VerifyOptions.Roots", Field, 0}, + }, + "crypto/x509/pkix": { + {"(*CertificateList).HasExpired", Method, 0}, + {"(*Name).FillFromRDNSequence", Method, 0}, + {"(Name).String", Method, 10}, + {"(Name).ToRDNSequence", Method, 0}, + {"(RDNSequence).String", Method, 10}, + {"AlgorithmIdentifier", Type, 0}, + {"AlgorithmIdentifier.Algorithm", Field, 0}, + {"AlgorithmIdentifier.Parameters", Field, 0}, + {"AttributeTypeAndValue", Type, 0}, + {"AttributeTypeAndValue.Type", Field, 0}, + {"AttributeTypeAndValue.Value", Field, 0}, + {"AttributeTypeAndValueSET", Type, 3}, + {"AttributeTypeAndValueSET.Type", Field, 3}, + {"AttributeTypeAndValueSET.Value", Field, 3}, + {"CertificateList", Type, 0}, + {"CertificateList.SignatureAlgorithm", Field, 0}, + {"CertificateList.SignatureValue", Field, 0}, + {"CertificateList.TBSCertList", Field, 0}, + {"Extension", Type, 0}, + {"Extension.Critical", Field, 0}, + {"Extension.Id", Field, 0}, + {"Extension.Value", Field, 0}, + {"Name", Type, 0}, + {"Name.CommonName", Field, 0}, + {"Name.Country", Field, 0}, + {"Name.ExtraNames", Field, 5}, + {"Name.Locality", Field, 0}, + {"Name.Names", Field, 0}, + {"Name.Organization", Field, 0}, + {"Name.OrganizationalUnit", Field, 0}, + {"Name.PostalCode", Field, 0}, + {"Name.Province", Field, 0}, + {"Name.SerialNumber", Field, 0}, + {"Name.StreetAddress", Field, 0}, + {"RDNSequence", Type, 0}, + {"RelativeDistinguishedNameSET", Type, 0}, + {"RevokedCertificate", Type, 0}, + {"RevokedCertificate.Extensions", Field, 0}, + {"RevokedCertificate.RevocationTime", Field, 0}, + {"RevokedCertificate.SerialNumber", Field, 0}, + {"TBSCertificateList", Type, 0}, + {"TBSCertificateList.Extensions", Field, 0}, + {"TBSCertificateList.Issuer", Field, 0}, + {"TBSCertificateList.NextUpdate", Field, 0}, + {"TBSCertificateList.Raw", Field, 0}, + {"TBSCertificateList.RevokedCertificates", Field, 0}, + {"TBSCertificateList.Signature", Field, 0}, + {"TBSCertificateList.ThisUpdate", Field, 0}, + {"TBSCertificateList.Version", Field, 0}, + }, + "database/sql": { + {"(*ColumnType).DatabaseTypeName", Method, 8}, + {"(*ColumnType).DecimalSize", Method, 8}, + {"(*ColumnType).Length", Method, 8}, + {"(*ColumnType).Name", Method, 8}, + {"(*ColumnType).Nullable", Method, 8}, + {"(*ColumnType).ScanType", Method, 8}, + {"(*Conn).BeginTx", Method, 9}, + {"(*Conn).Close", Method, 9}, + {"(*Conn).ExecContext", Method, 9}, + {"(*Conn).PingContext", Method, 9}, + {"(*Conn).PrepareContext", Method, 9}, + {"(*Conn).QueryContext", Method, 9}, + {"(*Conn).QueryRowContext", Method, 9}, + {"(*Conn).Raw", Method, 13}, + {"(*DB).Begin", Method, 0}, + {"(*DB).BeginTx", Method, 8}, + {"(*DB).Close", Method, 0}, + {"(*DB).Conn", Method, 9}, + {"(*DB).Driver", Method, 0}, + {"(*DB).Exec", Method, 0}, + {"(*DB).ExecContext", Method, 8}, + {"(*DB).Ping", Method, 1}, + {"(*DB).PingContext", Method, 8}, + {"(*DB).Prepare", Method, 0}, + {"(*DB).PrepareContext", Method, 8}, + {"(*DB).Query", Method, 0}, + {"(*DB).QueryContext", Method, 8}, + {"(*DB).QueryRow", Method, 0}, + {"(*DB).QueryRowContext", Method, 8}, + {"(*DB).SetConnMaxIdleTime", Method, 15}, + {"(*DB).SetConnMaxLifetime", Method, 6}, + {"(*DB).SetMaxIdleConns", Method, 1}, + {"(*DB).SetMaxOpenConns", Method, 2}, + {"(*DB).Stats", Method, 5}, + {"(*Null).Scan", Method, 22}, + {"(*NullBool).Scan", Method, 0}, + {"(*NullByte).Scan", Method, 17}, + {"(*NullFloat64).Scan", Method, 0}, + {"(*NullInt16).Scan", Method, 17}, + {"(*NullInt32).Scan", Method, 13}, + {"(*NullInt64).Scan", Method, 0}, + {"(*NullString).Scan", Method, 0}, + {"(*NullTime).Scan", Method, 13}, + {"(*Row).Err", Method, 15}, + {"(*Row).Scan", Method, 0}, + {"(*Rows).Close", Method, 0}, + {"(*Rows).ColumnTypes", Method, 8}, + {"(*Rows).Columns", Method, 0}, + {"(*Rows).Err", Method, 0}, + {"(*Rows).Next", Method, 0}, + {"(*Rows).NextResultSet", Method, 8}, + {"(*Rows).Scan", Method, 0}, + {"(*Stmt).Close", Method, 0}, + {"(*Stmt).Exec", Method, 0}, + {"(*Stmt).ExecContext", Method, 8}, + {"(*Stmt).Query", Method, 0}, + {"(*Stmt).QueryContext", Method, 8}, + {"(*Stmt).QueryRow", Method, 0}, + {"(*Stmt).QueryRowContext", Method, 8}, + {"(*Tx).Commit", Method, 0}, + {"(*Tx).Exec", Method, 0}, + {"(*Tx).ExecContext", Method, 8}, + {"(*Tx).Prepare", Method, 0}, + {"(*Tx).PrepareContext", Method, 8}, + {"(*Tx).Query", Method, 0}, + {"(*Tx).QueryContext", Method, 8}, + {"(*Tx).QueryRow", Method, 0}, + {"(*Tx).QueryRowContext", Method, 8}, + {"(*Tx).Rollback", Method, 0}, + {"(*Tx).Stmt", Method, 0}, + {"(*Tx).StmtContext", Method, 8}, + {"(IsolationLevel).String", Method, 11}, + {"(Null).Value", Method, 22}, + {"(NullBool).Value", Method, 0}, + {"(NullByte).Value", Method, 17}, + {"(NullFloat64).Value", Method, 0}, + {"(NullInt16).Value", Method, 17}, + {"(NullInt32).Value", Method, 13}, + {"(NullInt64).Value", Method, 0}, + {"(NullString).Value", Method, 0}, + {"(NullTime).Value", Method, 13}, + {"ColumnType", Type, 8}, + {"Conn", Type, 9}, + {"DB", Type, 0}, + {"DBStats", Type, 5}, + {"DBStats.Idle", Field, 11}, + {"DBStats.InUse", Field, 11}, + {"DBStats.MaxIdleClosed", Field, 11}, + {"DBStats.MaxIdleTimeClosed", Field, 15}, + {"DBStats.MaxLifetimeClosed", Field, 11}, + {"DBStats.MaxOpenConnections", Field, 11}, + {"DBStats.OpenConnections", Field, 5}, + {"DBStats.WaitCount", Field, 11}, + {"DBStats.WaitDuration", Field, 11}, + {"Drivers", Func, 4}, + {"ErrConnDone", Var, 9}, + {"ErrNoRows", Var, 0}, + {"ErrTxDone", Var, 0}, + {"IsolationLevel", Type, 8}, + {"LevelDefault", Const, 8}, + {"LevelLinearizable", Const, 8}, + {"LevelReadCommitted", Const, 8}, + {"LevelReadUncommitted", Const, 8}, + {"LevelRepeatableRead", Const, 8}, + {"LevelSerializable", Const, 8}, + {"LevelSnapshot", Const, 8}, + {"LevelWriteCommitted", Const, 8}, + {"Named", Func, 8}, + {"NamedArg", Type, 8}, + {"NamedArg.Name", Field, 8}, + {"NamedArg.Value", Field, 8}, + {"Null", Type, 22}, + {"Null.V", Field, 22}, + {"Null.Valid", Field, 22}, + {"NullBool", Type, 0}, + {"NullBool.Bool", Field, 0}, + {"NullBool.Valid", Field, 0}, + {"NullByte", Type, 17}, + {"NullByte.Byte", Field, 17}, + {"NullByte.Valid", Field, 17}, + {"NullFloat64", Type, 0}, + {"NullFloat64.Float64", Field, 0}, + {"NullFloat64.Valid", Field, 0}, + {"NullInt16", Type, 17}, + {"NullInt16.Int16", Field, 17}, + {"NullInt16.Valid", Field, 17}, + {"NullInt32", Type, 13}, + {"NullInt32.Int32", Field, 13}, + {"NullInt32.Valid", Field, 13}, + {"NullInt64", Type, 0}, + {"NullInt64.Int64", Field, 0}, + {"NullInt64.Valid", Field, 0}, + {"NullString", Type, 0}, + {"NullString.String", Field, 0}, + {"NullString.Valid", Field, 0}, + {"NullTime", Type, 13}, + {"NullTime.Time", Field, 13}, + {"NullTime.Valid", Field, 13}, + {"Open", Func, 0}, + {"OpenDB", Func, 10}, + {"Out", Type, 9}, + {"Out.Dest", Field, 9}, + {"Out.In", Field, 9}, + {"RawBytes", Type, 0}, + {"Register", Func, 0}, + {"Result", Type, 0}, + {"Row", Type, 0}, + {"Rows", Type, 0}, + {"Scanner", Type, 0}, + {"Stmt", Type, 0}, + {"Tx", Type, 0}, + {"TxOptions", Type, 8}, + {"TxOptions.Isolation", Field, 8}, + {"TxOptions.ReadOnly", Field, 8}, + }, + "database/sql/driver": { + {"(NotNull).ConvertValue", Method, 0}, + {"(Null).ConvertValue", Method, 0}, + {"(RowsAffected).LastInsertId", Method, 0}, + {"(RowsAffected).RowsAffected", Method, 0}, + {"Bool", Var, 0}, + {"ColumnConverter", Type, 0}, + {"Conn", Type, 0}, + {"ConnBeginTx", Type, 8}, + {"ConnPrepareContext", Type, 8}, + {"Connector", Type, 10}, + {"DefaultParameterConverter", Var, 0}, + {"Driver", Type, 0}, + {"DriverContext", Type, 10}, + {"ErrBadConn", Var, 0}, + {"ErrRemoveArgument", Var, 9}, + {"ErrSkip", Var, 0}, + {"Execer", Type, 0}, + {"ExecerContext", Type, 8}, + {"Int32", Var, 0}, + {"IsScanValue", Func, 0}, + {"IsValue", Func, 0}, + {"IsolationLevel", Type, 8}, + {"NamedValue", Type, 8}, + {"NamedValue.Name", Field, 8}, + {"NamedValue.Ordinal", Field, 8}, + {"NamedValue.Value", Field, 8}, + {"NamedValueChecker", Type, 9}, + {"NotNull", Type, 0}, + {"NotNull.Converter", Field, 0}, + {"Null", Type, 0}, + {"Null.Converter", Field, 0}, + {"Pinger", Type, 8}, + {"Queryer", Type, 1}, + {"QueryerContext", Type, 8}, + {"Result", Type, 0}, + {"ResultNoRows", Var, 0}, + {"Rows", Type, 0}, + {"RowsAffected", Type, 0}, + {"RowsColumnTypeDatabaseTypeName", Type, 8}, + {"RowsColumnTypeLength", Type, 8}, + {"RowsColumnTypeNullable", Type, 8}, + {"RowsColumnTypePrecisionScale", Type, 8}, + {"RowsColumnTypeScanType", Type, 8}, + {"RowsNextResultSet", Type, 8}, + {"SessionResetter", Type, 10}, + {"Stmt", Type, 0}, + {"StmtExecContext", Type, 8}, + {"StmtQueryContext", Type, 8}, + {"String", Var, 0}, + {"Tx", Type, 0}, + {"TxOptions", Type, 8}, + {"TxOptions.Isolation", Field, 8}, + {"TxOptions.ReadOnly", Field, 8}, + {"Validator", Type, 15}, + {"Value", Type, 0}, + {"ValueConverter", Type, 0}, + {"Valuer", Type, 0}, + }, + "debug/buildinfo": { + {"BuildInfo", Type, 18}, + {"Read", Func, 18}, + {"ReadFile", Func, 18}, + }, + "debug/dwarf": { + {"(*AddrType).Basic", Method, 0}, + {"(*AddrType).Common", Method, 0}, + {"(*AddrType).Size", Method, 0}, + {"(*AddrType).String", Method, 0}, + {"(*ArrayType).Common", Method, 0}, + {"(*ArrayType).Size", Method, 0}, + {"(*ArrayType).String", Method, 0}, + {"(*BasicType).Basic", Method, 0}, + {"(*BasicType).Common", Method, 0}, + {"(*BasicType).Size", Method, 0}, + {"(*BasicType).String", Method, 0}, + {"(*BoolType).Basic", Method, 0}, + {"(*BoolType).Common", Method, 0}, + {"(*BoolType).Size", Method, 0}, + {"(*BoolType).String", Method, 0}, + {"(*CharType).Basic", Method, 0}, + {"(*CharType).Common", Method, 0}, + {"(*CharType).Size", Method, 0}, + {"(*CharType).String", Method, 0}, + {"(*CommonType).Common", Method, 0}, + {"(*CommonType).Size", Method, 0}, + {"(*ComplexType).Basic", Method, 0}, + {"(*ComplexType).Common", Method, 0}, + {"(*ComplexType).Size", Method, 0}, + {"(*ComplexType).String", Method, 0}, + {"(*Data).AddSection", Method, 14}, + {"(*Data).AddTypes", Method, 3}, + {"(*Data).LineReader", Method, 5}, + {"(*Data).Ranges", Method, 7}, + {"(*Data).Reader", Method, 0}, + {"(*Data).Type", Method, 0}, + {"(*DotDotDotType).Common", Method, 0}, + {"(*DotDotDotType).Size", Method, 0}, + {"(*DotDotDotType).String", Method, 0}, + {"(*Entry).AttrField", Method, 5}, + {"(*Entry).Val", Method, 0}, + {"(*EnumType).Common", Method, 0}, + {"(*EnumType).Size", Method, 0}, + {"(*EnumType).String", Method, 0}, + {"(*FloatType).Basic", Method, 0}, + {"(*FloatType).Common", Method, 0}, + {"(*FloatType).Size", Method, 0}, + {"(*FloatType).String", Method, 0}, + {"(*FuncType).Common", Method, 0}, + {"(*FuncType).Size", Method, 0}, + {"(*FuncType).String", Method, 0}, + {"(*IntType).Basic", Method, 0}, + {"(*IntType).Common", Method, 0}, + {"(*IntType).Size", Method, 0}, + {"(*IntType).String", Method, 0}, + {"(*LineReader).Files", Method, 14}, + {"(*LineReader).Next", Method, 5}, + {"(*LineReader).Reset", Method, 5}, + {"(*LineReader).Seek", Method, 5}, + {"(*LineReader).SeekPC", Method, 5}, + {"(*LineReader).Tell", Method, 5}, + {"(*PtrType).Common", Method, 0}, + {"(*PtrType).Size", Method, 0}, + {"(*PtrType).String", Method, 0}, + {"(*QualType).Common", Method, 0}, + {"(*QualType).Size", Method, 0}, + {"(*QualType).String", Method, 0}, + {"(*Reader).AddressSize", Method, 5}, + {"(*Reader).ByteOrder", Method, 14}, + {"(*Reader).Next", Method, 0}, + {"(*Reader).Seek", Method, 0}, + {"(*Reader).SeekPC", Method, 7}, + {"(*Reader).SkipChildren", Method, 0}, + {"(*StructType).Common", Method, 0}, + {"(*StructType).Defn", Method, 0}, + {"(*StructType).Size", Method, 0}, + {"(*StructType).String", Method, 0}, + {"(*TypedefType).Common", Method, 0}, + {"(*TypedefType).Size", Method, 0}, + {"(*TypedefType).String", Method, 0}, + {"(*UcharType).Basic", Method, 0}, + {"(*UcharType).Common", Method, 0}, + {"(*UcharType).Size", Method, 0}, + {"(*UcharType).String", Method, 0}, + {"(*UintType).Basic", Method, 0}, + {"(*UintType).Common", Method, 0}, + {"(*UintType).Size", Method, 0}, + {"(*UintType).String", Method, 0}, + {"(*UnspecifiedType).Basic", Method, 4}, + {"(*UnspecifiedType).Common", Method, 4}, + {"(*UnspecifiedType).Size", Method, 4}, + {"(*UnspecifiedType).String", Method, 4}, + {"(*UnsupportedType).Common", Method, 13}, + {"(*UnsupportedType).Size", Method, 13}, + {"(*UnsupportedType).String", Method, 13}, + {"(*VoidType).Common", Method, 0}, + {"(*VoidType).Size", Method, 0}, + {"(*VoidType).String", Method, 0}, + {"(Attr).GoString", Method, 0}, + {"(Attr).String", Method, 0}, + {"(Class).GoString", Method, 5}, + {"(Class).String", Method, 5}, + {"(DecodeError).Error", Method, 0}, + {"(Tag).GoString", Method, 0}, + {"(Tag).String", Method, 0}, + {"AddrType", Type, 0}, + {"AddrType.BasicType", Field, 0}, + {"ArrayType", Type, 0}, + {"ArrayType.CommonType", Field, 0}, + {"ArrayType.Count", Field, 0}, + {"ArrayType.StrideBitSize", Field, 0}, + {"ArrayType.Type", Field, 0}, + {"Attr", Type, 0}, + {"AttrAbstractOrigin", Const, 0}, + {"AttrAccessibility", Const, 0}, + {"AttrAddrBase", Const, 14}, + {"AttrAddrClass", Const, 0}, + {"AttrAlignment", Const, 14}, + {"AttrAllocated", Const, 0}, + {"AttrArtificial", Const, 0}, + {"AttrAssociated", Const, 0}, + {"AttrBaseTypes", Const, 0}, + {"AttrBinaryScale", Const, 14}, + {"AttrBitOffset", Const, 0}, + {"AttrBitSize", Const, 0}, + {"AttrByteSize", Const, 0}, + {"AttrCallAllCalls", Const, 14}, + {"AttrCallAllSourceCalls", Const, 14}, + {"AttrCallAllTailCalls", Const, 14}, + {"AttrCallColumn", Const, 0}, + {"AttrCallDataLocation", Const, 14}, + {"AttrCallDataValue", Const, 14}, + {"AttrCallFile", Const, 0}, + {"AttrCallLine", Const, 0}, + {"AttrCallOrigin", Const, 14}, + {"AttrCallPC", Const, 14}, + {"AttrCallParameter", Const, 14}, + {"AttrCallReturnPC", Const, 14}, + {"AttrCallTailCall", Const, 14}, + {"AttrCallTarget", Const, 14}, + {"AttrCallTargetClobbered", Const, 14}, + {"AttrCallValue", Const, 14}, + {"AttrCalling", Const, 0}, + {"AttrCommonRef", Const, 0}, + {"AttrCompDir", Const, 0}, + {"AttrConstExpr", Const, 14}, + {"AttrConstValue", Const, 0}, + {"AttrContainingType", Const, 0}, + {"AttrCount", Const, 0}, + {"AttrDataBitOffset", Const, 14}, + {"AttrDataLocation", Const, 0}, + {"AttrDataMemberLoc", Const, 0}, + {"AttrDecimalScale", Const, 14}, + {"AttrDecimalSign", Const, 14}, + {"AttrDeclColumn", Const, 0}, + {"AttrDeclFile", Const, 0}, + {"AttrDeclLine", Const, 0}, + {"AttrDeclaration", Const, 0}, + {"AttrDefaultValue", Const, 0}, + {"AttrDefaulted", Const, 14}, + {"AttrDeleted", Const, 14}, + {"AttrDescription", Const, 0}, + {"AttrDigitCount", Const, 14}, + {"AttrDiscr", Const, 0}, + {"AttrDiscrList", Const, 0}, + {"AttrDiscrValue", Const, 0}, + {"AttrDwoName", Const, 14}, + {"AttrElemental", Const, 14}, + {"AttrEncoding", Const, 0}, + {"AttrEndianity", Const, 14}, + {"AttrEntrypc", Const, 0}, + {"AttrEnumClass", Const, 14}, + {"AttrExplicit", Const, 14}, + {"AttrExportSymbols", Const, 14}, + {"AttrExtension", Const, 0}, + {"AttrExternal", Const, 0}, + {"AttrFrameBase", Const, 0}, + {"AttrFriend", Const, 0}, + {"AttrHighpc", Const, 0}, + {"AttrIdentifierCase", Const, 0}, + {"AttrImport", Const, 0}, + {"AttrInline", Const, 0}, + {"AttrIsOptional", Const, 0}, + {"AttrLanguage", Const, 0}, + {"AttrLinkageName", Const, 14}, + {"AttrLocation", Const, 0}, + {"AttrLoclistsBase", Const, 14}, + {"AttrLowerBound", Const, 0}, + {"AttrLowpc", Const, 0}, + {"AttrMacroInfo", Const, 0}, + {"AttrMacros", Const, 14}, + {"AttrMainSubprogram", Const, 14}, + {"AttrMutable", Const, 14}, + {"AttrName", Const, 0}, + {"AttrNamelistItem", Const, 0}, + {"AttrNoreturn", Const, 14}, + {"AttrObjectPointer", Const, 14}, + {"AttrOrdering", Const, 0}, + {"AttrPictureString", Const, 14}, + {"AttrPriority", Const, 0}, + {"AttrProducer", Const, 0}, + {"AttrPrototyped", Const, 0}, + {"AttrPure", Const, 14}, + {"AttrRanges", Const, 0}, + {"AttrRank", Const, 14}, + {"AttrRecursive", Const, 14}, + {"AttrReference", Const, 14}, + {"AttrReturnAddr", Const, 0}, + {"AttrRnglistsBase", Const, 14}, + {"AttrRvalueReference", Const, 14}, + {"AttrSegment", Const, 0}, + {"AttrSibling", Const, 0}, + {"AttrSignature", Const, 14}, + {"AttrSmall", Const, 14}, + {"AttrSpecification", Const, 0}, + {"AttrStartScope", Const, 0}, + {"AttrStaticLink", Const, 0}, + {"AttrStmtList", Const, 0}, + {"AttrStrOffsetsBase", Const, 14}, + {"AttrStride", Const, 0}, + {"AttrStrideSize", Const, 0}, + {"AttrStringLength", Const, 0}, + {"AttrStringLengthBitSize", Const, 14}, + {"AttrStringLengthByteSize", Const, 14}, + {"AttrThreadsScaled", Const, 14}, + {"AttrTrampoline", Const, 0}, + {"AttrType", Const, 0}, + {"AttrUpperBound", Const, 0}, + {"AttrUseLocation", Const, 0}, + {"AttrUseUTF8", Const, 0}, + {"AttrVarParam", Const, 0}, + {"AttrVirtuality", Const, 0}, + {"AttrVisibility", Const, 0}, + {"AttrVtableElemLoc", Const, 0}, + {"BasicType", Type, 0}, + {"BasicType.BitOffset", Field, 0}, + {"BasicType.BitSize", Field, 0}, + {"BasicType.CommonType", Field, 0}, + {"BasicType.DataBitOffset", Field, 18}, + {"BoolType", Type, 0}, + {"BoolType.BasicType", Field, 0}, + {"CharType", Type, 0}, + {"CharType.BasicType", Field, 0}, + {"Class", Type, 5}, + {"ClassAddrPtr", Const, 14}, + {"ClassAddress", Const, 5}, + {"ClassBlock", Const, 5}, + {"ClassConstant", Const, 5}, + {"ClassExprLoc", Const, 5}, + {"ClassFlag", Const, 5}, + {"ClassLinePtr", Const, 5}, + {"ClassLocList", Const, 14}, + {"ClassLocListPtr", Const, 5}, + {"ClassMacPtr", Const, 5}, + {"ClassRangeListPtr", Const, 5}, + {"ClassReference", Const, 5}, + {"ClassReferenceAlt", Const, 5}, + {"ClassReferenceSig", Const, 5}, + {"ClassRngList", Const, 14}, + {"ClassRngListsPtr", Const, 14}, + {"ClassStrOffsetsPtr", Const, 14}, + {"ClassString", Const, 5}, + {"ClassStringAlt", Const, 5}, + {"ClassUnknown", Const, 6}, + {"CommonType", Type, 0}, + {"CommonType.ByteSize", Field, 0}, + {"CommonType.Name", Field, 0}, + {"ComplexType", Type, 0}, + {"ComplexType.BasicType", Field, 0}, + {"Data", Type, 0}, + {"DecodeError", Type, 0}, + {"DecodeError.Err", Field, 0}, + {"DecodeError.Name", Field, 0}, + {"DecodeError.Offset", Field, 0}, + {"DotDotDotType", Type, 0}, + {"DotDotDotType.CommonType", Field, 0}, + {"Entry", Type, 0}, + {"Entry.Children", Field, 0}, + {"Entry.Field", Field, 0}, + {"Entry.Offset", Field, 0}, + {"Entry.Tag", Field, 0}, + {"EnumType", Type, 0}, + {"EnumType.CommonType", Field, 0}, + {"EnumType.EnumName", Field, 0}, + {"EnumType.Val", Field, 0}, + {"EnumValue", Type, 0}, + {"EnumValue.Name", Field, 0}, + {"EnumValue.Val", Field, 0}, + {"ErrUnknownPC", Var, 5}, + {"Field", Type, 0}, + {"Field.Attr", Field, 0}, + {"Field.Class", Field, 5}, + {"Field.Val", Field, 0}, + {"FloatType", Type, 0}, + {"FloatType.BasicType", Field, 0}, + {"FuncType", Type, 0}, + {"FuncType.CommonType", Field, 0}, + {"FuncType.ParamType", Field, 0}, + {"FuncType.ReturnType", Field, 0}, + {"IntType", Type, 0}, + {"IntType.BasicType", Field, 0}, + {"LineEntry", Type, 5}, + {"LineEntry.Address", Field, 5}, + {"LineEntry.BasicBlock", Field, 5}, + {"LineEntry.Column", Field, 5}, + {"LineEntry.Discriminator", Field, 5}, + {"LineEntry.EndSequence", Field, 5}, + {"LineEntry.EpilogueBegin", Field, 5}, + {"LineEntry.File", Field, 5}, + {"LineEntry.ISA", Field, 5}, + {"LineEntry.IsStmt", Field, 5}, + {"LineEntry.Line", Field, 5}, + {"LineEntry.OpIndex", Field, 5}, + {"LineEntry.PrologueEnd", Field, 5}, + {"LineFile", Type, 5}, + {"LineFile.Length", Field, 5}, + {"LineFile.Mtime", Field, 5}, + {"LineFile.Name", Field, 5}, + {"LineReader", Type, 5}, + {"LineReaderPos", Type, 5}, + {"New", Func, 0}, + {"Offset", Type, 0}, + {"PtrType", Type, 0}, + {"PtrType.CommonType", Field, 0}, + {"PtrType.Type", Field, 0}, + {"QualType", Type, 0}, + {"QualType.CommonType", Field, 0}, + {"QualType.Qual", Field, 0}, + {"QualType.Type", Field, 0}, + {"Reader", Type, 0}, + {"StructField", Type, 0}, + {"StructField.BitOffset", Field, 0}, + {"StructField.BitSize", Field, 0}, + {"StructField.ByteOffset", Field, 0}, + {"StructField.ByteSize", Field, 0}, + {"StructField.DataBitOffset", Field, 18}, + {"StructField.Name", Field, 0}, + {"StructField.Type", Field, 0}, + {"StructType", Type, 0}, + {"StructType.CommonType", Field, 0}, + {"StructType.Field", Field, 0}, + {"StructType.Incomplete", Field, 0}, + {"StructType.Kind", Field, 0}, + {"StructType.StructName", Field, 0}, + {"Tag", Type, 0}, + {"TagAccessDeclaration", Const, 0}, + {"TagArrayType", Const, 0}, + {"TagAtomicType", Const, 14}, + {"TagBaseType", Const, 0}, + {"TagCallSite", Const, 14}, + {"TagCallSiteParameter", Const, 14}, + {"TagCatchDwarfBlock", Const, 0}, + {"TagClassType", Const, 0}, + {"TagCoarrayType", Const, 14}, + {"TagCommonDwarfBlock", Const, 0}, + {"TagCommonInclusion", Const, 0}, + {"TagCompileUnit", Const, 0}, + {"TagCondition", Const, 3}, + {"TagConstType", Const, 0}, + {"TagConstant", Const, 0}, + {"TagDwarfProcedure", Const, 0}, + {"TagDynamicType", Const, 14}, + {"TagEntryPoint", Const, 0}, + {"TagEnumerationType", Const, 0}, + {"TagEnumerator", Const, 0}, + {"TagFileType", Const, 0}, + {"TagFormalParameter", Const, 0}, + {"TagFriend", Const, 0}, + {"TagGenericSubrange", Const, 14}, + {"TagImmutableType", Const, 14}, + {"TagImportedDeclaration", Const, 0}, + {"TagImportedModule", Const, 0}, + {"TagImportedUnit", Const, 0}, + {"TagInheritance", Const, 0}, + {"TagInlinedSubroutine", Const, 0}, + {"TagInterfaceType", Const, 0}, + {"TagLabel", Const, 0}, + {"TagLexDwarfBlock", Const, 0}, + {"TagMember", Const, 0}, + {"TagModule", Const, 0}, + {"TagMutableType", Const, 0}, + {"TagNamelist", Const, 0}, + {"TagNamelistItem", Const, 0}, + {"TagNamespace", Const, 0}, + {"TagPackedType", Const, 0}, + {"TagPartialUnit", Const, 0}, + {"TagPointerType", Const, 0}, + {"TagPtrToMemberType", Const, 0}, + {"TagReferenceType", Const, 0}, + {"TagRestrictType", Const, 0}, + {"TagRvalueReferenceType", Const, 3}, + {"TagSetType", Const, 0}, + {"TagSharedType", Const, 3}, + {"TagSkeletonUnit", Const, 14}, + {"TagStringType", Const, 0}, + {"TagStructType", Const, 0}, + {"TagSubprogram", Const, 0}, + {"TagSubrangeType", Const, 0}, + {"TagSubroutineType", Const, 0}, + {"TagTemplateAlias", Const, 3}, + {"TagTemplateTypeParameter", Const, 0}, + {"TagTemplateValueParameter", Const, 0}, + {"TagThrownType", Const, 0}, + {"TagTryDwarfBlock", Const, 0}, + {"TagTypeUnit", Const, 3}, + {"TagTypedef", Const, 0}, + {"TagUnionType", Const, 0}, + {"TagUnspecifiedParameters", Const, 0}, + {"TagUnspecifiedType", Const, 0}, + {"TagVariable", Const, 0}, + {"TagVariant", Const, 0}, + {"TagVariantPart", Const, 0}, + {"TagVolatileType", Const, 0}, + {"TagWithStmt", Const, 0}, + {"Type", Type, 0}, + {"TypedefType", Type, 0}, + {"TypedefType.CommonType", Field, 0}, + {"TypedefType.Type", Field, 0}, + {"UcharType", Type, 0}, + {"UcharType.BasicType", Field, 0}, + {"UintType", Type, 0}, + {"UintType.BasicType", Field, 0}, + {"UnspecifiedType", Type, 4}, + {"UnspecifiedType.BasicType", Field, 4}, + {"UnsupportedType", Type, 13}, + {"UnsupportedType.CommonType", Field, 13}, + {"UnsupportedType.Tag", Field, 13}, + {"VoidType", Type, 0}, + {"VoidType.CommonType", Field, 0}, + }, + "debug/elf": { + {"(*File).Close", Method, 0}, + {"(*File).DWARF", Method, 0}, + {"(*File).DynString", Method, 1}, + {"(*File).DynValue", Method, 21}, + {"(*File).DynamicSymbols", Method, 4}, + {"(*File).ImportedLibraries", Method, 0}, + {"(*File).ImportedSymbols", Method, 0}, + {"(*File).Section", Method, 0}, + {"(*File).SectionByType", Method, 0}, + {"(*File).Symbols", Method, 0}, + {"(*FormatError).Error", Method, 0}, + {"(*Prog).Open", Method, 0}, + {"(*Section).Data", Method, 0}, + {"(*Section).Open", Method, 0}, + {"(Class).GoString", Method, 0}, + {"(Class).String", Method, 0}, + {"(CompressionType).GoString", Method, 6}, + {"(CompressionType).String", Method, 6}, + {"(Data).GoString", Method, 0}, + {"(Data).String", Method, 0}, + {"(DynFlag).GoString", Method, 0}, + {"(DynFlag).String", Method, 0}, + {"(DynFlag1).GoString", Method, 21}, + {"(DynFlag1).String", Method, 21}, + {"(DynTag).GoString", Method, 0}, + {"(DynTag).String", Method, 0}, + {"(Machine).GoString", Method, 0}, + {"(Machine).String", Method, 0}, + {"(NType).GoString", Method, 0}, + {"(NType).String", Method, 0}, + {"(OSABI).GoString", Method, 0}, + {"(OSABI).String", Method, 0}, + {"(Prog).ReadAt", Method, 0}, + {"(ProgFlag).GoString", Method, 0}, + {"(ProgFlag).String", Method, 0}, + {"(ProgType).GoString", Method, 0}, + {"(ProgType).String", Method, 0}, + {"(R_386).GoString", Method, 0}, + {"(R_386).String", Method, 0}, + {"(R_390).GoString", Method, 7}, + {"(R_390).String", Method, 7}, + {"(R_AARCH64).GoString", Method, 4}, + {"(R_AARCH64).String", Method, 4}, + {"(R_ALPHA).GoString", Method, 0}, + {"(R_ALPHA).String", Method, 0}, + {"(R_ARM).GoString", Method, 0}, + {"(R_ARM).String", Method, 0}, + {"(R_LARCH).GoString", Method, 19}, + {"(R_LARCH).String", Method, 19}, + {"(R_MIPS).GoString", Method, 6}, + {"(R_MIPS).String", Method, 6}, + {"(R_PPC).GoString", Method, 0}, + {"(R_PPC).String", Method, 0}, + {"(R_PPC64).GoString", Method, 5}, + {"(R_PPC64).String", Method, 5}, + {"(R_RISCV).GoString", Method, 11}, + {"(R_RISCV).String", Method, 11}, + {"(R_SPARC).GoString", Method, 0}, + {"(R_SPARC).String", Method, 0}, + {"(R_X86_64).GoString", Method, 0}, + {"(R_X86_64).String", Method, 0}, + {"(Section).ReadAt", Method, 0}, + {"(SectionFlag).GoString", Method, 0}, + {"(SectionFlag).String", Method, 0}, + {"(SectionIndex).GoString", Method, 0}, + {"(SectionIndex).String", Method, 0}, + {"(SectionType).GoString", Method, 0}, + {"(SectionType).String", Method, 0}, + {"(SymBind).GoString", Method, 0}, + {"(SymBind).String", Method, 0}, + {"(SymType).GoString", Method, 0}, + {"(SymType).String", Method, 0}, + {"(SymVis).GoString", Method, 0}, + {"(SymVis).String", Method, 0}, + {"(Type).GoString", Method, 0}, + {"(Type).String", Method, 0}, + {"(Version).GoString", Method, 0}, + {"(Version).String", Method, 0}, + {"ARM_MAGIC_TRAMP_NUMBER", Const, 0}, + {"COMPRESS_HIOS", Const, 6}, + {"COMPRESS_HIPROC", Const, 6}, + {"COMPRESS_LOOS", Const, 6}, + {"COMPRESS_LOPROC", Const, 6}, + {"COMPRESS_ZLIB", Const, 6}, + {"COMPRESS_ZSTD", Const, 21}, + {"Chdr32", Type, 6}, + {"Chdr32.Addralign", Field, 6}, + {"Chdr32.Size", Field, 6}, + {"Chdr32.Type", Field, 6}, + {"Chdr64", Type, 6}, + {"Chdr64.Addralign", Field, 6}, + {"Chdr64.Size", Field, 6}, + {"Chdr64.Type", Field, 6}, + {"Class", Type, 0}, + {"CompressionType", Type, 6}, + {"DF_1_CONFALT", Const, 21}, + {"DF_1_DIRECT", Const, 21}, + {"DF_1_DISPRELDNE", Const, 21}, + {"DF_1_DISPRELPND", Const, 21}, + {"DF_1_EDITED", Const, 21}, + {"DF_1_ENDFILTEE", Const, 21}, + {"DF_1_GLOBAL", Const, 21}, + {"DF_1_GLOBAUDIT", Const, 21}, + {"DF_1_GROUP", Const, 21}, + {"DF_1_IGNMULDEF", Const, 21}, + {"DF_1_INITFIRST", Const, 21}, + {"DF_1_INTERPOSE", Const, 21}, + {"DF_1_KMOD", Const, 21}, + {"DF_1_LOADFLTR", Const, 21}, + {"DF_1_NOCOMMON", Const, 21}, + {"DF_1_NODEFLIB", Const, 21}, + {"DF_1_NODELETE", Const, 21}, + {"DF_1_NODIRECT", Const, 21}, + {"DF_1_NODUMP", Const, 21}, + {"DF_1_NOHDR", Const, 21}, + {"DF_1_NOKSYMS", Const, 21}, + {"DF_1_NOOPEN", Const, 21}, + {"DF_1_NORELOC", Const, 21}, + {"DF_1_NOW", Const, 21}, + {"DF_1_ORIGIN", Const, 21}, + {"DF_1_PIE", Const, 21}, + {"DF_1_SINGLETON", Const, 21}, + {"DF_1_STUB", Const, 21}, + {"DF_1_SYMINTPOSE", Const, 21}, + {"DF_1_TRANS", Const, 21}, + {"DF_1_WEAKFILTER", Const, 21}, + {"DF_BIND_NOW", Const, 0}, + {"DF_ORIGIN", Const, 0}, + {"DF_STATIC_TLS", Const, 0}, + {"DF_SYMBOLIC", Const, 0}, + {"DF_TEXTREL", Const, 0}, + {"DT_ADDRRNGHI", Const, 16}, + {"DT_ADDRRNGLO", Const, 16}, + {"DT_AUDIT", Const, 16}, + {"DT_AUXILIARY", Const, 16}, + {"DT_BIND_NOW", Const, 0}, + {"DT_CHECKSUM", Const, 16}, + {"DT_CONFIG", Const, 16}, + {"DT_DEBUG", Const, 0}, + {"DT_DEPAUDIT", Const, 16}, + {"DT_ENCODING", Const, 0}, + {"DT_FEATURE", Const, 16}, + {"DT_FILTER", Const, 16}, + {"DT_FINI", Const, 0}, + {"DT_FINI_ARRAY", Const, 0}, + {"DT_FINI_ARRAYSZ", Const, 0}, + {"DT_FLAGS", Const, 0}, + {"DT_FLAGS_1", Const, 16}, + {"DT_GNU_CONFLICT", Const, 16}, + {"DT_GNU_CONFLICTSZ", Const, 16}, + {"DT_GNU_HASH", Const, 16}, + {"DT_GNU_LIBLIST", Const, 16}, + {"DT_GNU_LIBLISTSZ", Const, 16}, + {"DT_GNU_PRELINKED", Const, 16}, + {"DT_HASH", Const, 0}, + {"DT_HIOS", Const, 0}, + {"DT_HIPROC", Const, 0}, + {"DT_INIT", Const, 0}, + {"DT_INIT_ARRAY", Const, 0}, + {"DT_INIT_ARRAYSZ", Const, 0}, + {"DT_JMPREL", Const, 0}, + {"DT_LOOS", Const, 0}, + {"DT_LOPROC", Const, 0}, + {"DT_MIPS_AUX_DYNAMIC", Const, 16}, + {"DT_MIPS_BASE_ADDRESS", Const, 16}, + {"DT_MIPS_COMPACT_SIZE", Const, 16}, + {"DT_MIPS_CONFLICT", Const, 16}, + {"DT_MIPS_CONFLICTNO", Const, 16}, + {"DT_MIPS_CXX_FLAGS", Const, 16}, + {"DT_MIPS_DELTA_CLASS", Const, 16}, + {"DT_MIPS_DELTA_CLASSSYM", Const, 16}, + {"DT_MIPS_DELTA_CLASSSYM_NO", Const, 16}, + {"DT_MIPS_DELTA_CLASS_NO", Const, 16}, + {"DT_MIPS_DELTA_INSTANCE", Const, 16}, + {"DT_MIPS_DELTA_INSTANCE_NO", Const, 16}, + {"DT_MIPS_DELTA_RELOC", Const, 16}, + {"DT_MIPS_DELTA_RELOC_NO", Const, 16}, + {"DT_MIPS_DELTA_SYM", Const, 16}, + {"DT_MIPS_DELTA_SYM_NO", Const, 16}, + {"DT_MIPS_DYNSTR_ALIGN", Const, 16}, + {"DT_MIPS_FLAGS", Const, 16}, + {"DT_MIPS_GOTSYM", Const, 16}, + {"DT_MIPS_GP_VALUE", Const, 16}, + {"DT_MIPS_HIDDEN_GOTIDX", Const, 16}, + {"DT_MIPS_HIPAGENO", Const, 16}, + {"DT_MIPS_ICHECKSUM", Const, 16}, + {"DT_MIPS_INTERFACE", Const, 16}, + {"DT_MIPS_INTERFACE_SIZE", Const, 16}, + {"DT_MIPS_IVERSION", Const, 16}, + {"DT_MIPS_LIBLIST", Const, 16}, + {"DT_MIPS_LIBLISTNO", Const, 16}, + {"DT_MIPS_LOCALPAGE_GOTIDX", Const, 16}, + {"DT_MIPS_LOCAL_GOTIDX", Const, 16}, + {"DT_MIPS_LOCAL_GOTNO", Const, 16}, + {"DT_MIPS_MSYM", Const, 16}, + {"DT_MIPS_OPTIONS", Const, 16}, + {"DT_MIPS_PERF_SUFFIX", Const, 16}, + {"DT_MIPS_PIXIE_INIT", Const, 16}, + {"DT_MIPS_PLTGOT", Const, 16}, + {"DT_MIPS_PROTECTED_GOTIDX", Const, 16}, + {"DT_MIPS_RLD_MAP", Const, 16}, + {"DT_MIPS_RLD_MAP_REL", Const, 16}, + {"DT_MIPS_RLD_TEXT_RESOLVE_ADDR", Const, 16}, + {"DT_MIPS_RLD_VERSION", Const, 16}, + {"DT_MIPS_RWPLT", Const, 16}, + {"DT_MIPS_SYMBOL_LIB", Const, 16}, + {"DT_MIPS_SYMTABNO", Const, 16}, + {"DT_MIPS_TIME_STAMP", Const, 16}, + {"DT_MIPS_UNREFEXTNO", Const, 16}, + {"DT_MOVEENT", Const, 16}, + {"DT_MOVESZ", Const, 16}, + {"DT_MOVETAB", Const, 16}, + {"DT_NEEDED", Const, 0}, + {"DT_NULL", Const, 0}, + {"DT_PLTGOT", Const, 0}, + {"DT_PLTPAD", Const, 16}, + {"DT_PLTPADSZ", Const, 16}, + {"DT_PLTREL", Const, 0}, + {"DT_PLTRELSZ", Const, 0}, + {"DT_POSFLAG_1", Const, 16}, + {"DT_PPC64_GLINK", Const, 16}, + {"DT_PPC64_OPD", Const, 16}, + {"DT_PPC64_OPDSZ", Const, 16}, + {"DT_PPC64_OPT", Const, 16}, + {"DT_PPC_GOT", Const, 16}, + {"DT_PPC_OPT", Const, 16}, + {"DT_PREINIT_ARRAY", Const, 0}, + {"DT_PREINIT_ARRAYSZ", Const, 0}, + {"DT_REL", Const, 0}, + {"DT_RELA", Const, 0}, + {"DT_RELACOUNT", Const, 16}, + {"DT_RELAENT", Const, 0}, + {"DT_RELASZ", Const, 0}, + {"DT_RELCOUNT", Const, 16}, + {"DT_RELENT", Const, 0}, + {"DT_RELSZ", Const, 0}, + {"DT_RPATH", Const, 0}, + {"DT_RUNPATH", Const, 0}, + {"DT_SONAME", Const, 0}, + {"DT_SPARC_REGISTER", Const, 16}, + {"DT_STRSZ", Const, 0}, + {"DT_STRTAB", Const, 0}, + {"DT_SYMBOLIC", Const, 0}, + {"DT_SYMENT", Const, 0}, + {"DT_SYMINENT", Const, 16}, + {"DT_SYMINFO", Const, 16}, + {"DT_SYMINSZ", Const, 16}, + {"DT_SYMTAB", Const, 0}, + {"DT_SYMTAB_SHNDX", Const, 16}, + {"DT_TEXTREL", Const, 0}, + {"DT_TLSDESC_GOT", Const, 16}, + {"DT_TLSDESC_PLT", Const, 16}, + {"DT_USED", Const, 16}, + {"DT_VALRNGHI", Const, 16}, + {"DT_VALRNGLO", Const, 16}, + {"DT_VERDEF", Const, 16}, + {"DT_VERDEFNUM", Const, 16}, + {"DT_VERNEED", Const, 0}, + {"DT_VERNEEDNUM", Const, 0}, + {"DT_VERSYM", Const, 0}, + {"Data", Type, 0}, + {"Dyn32", Type, 0}, + {"Dyn32.Tag", Field, 0}, + {"Dyn32.Val", Field, 0}, + {"Dyn64", Type, 0}, + {"Dyn64.Tag", Field, 0}, + {"Dyn64.Val", Field, 0}, + {"DynFlag", Type, 0}, + {"DynFlag1", Type, 21}, + {"DynTag", Type, 0}, + {"EI_ABIVERSION", Const, 0}, + {"EI_CLASS", Const, 0}, + {"EI_DATA", Const, 0}, + {"EI_NIDENT", Const, 0}, + {"EI_OSABI", Const, 0}, + {"EI_PAD", Const, 0}, + {"EI_VERSION", Const, 0}, + {"ELFCLASS32", Const, 0}, + {"ELFCLASS64", Const, 0}, + {"ELFCLASSNONE", Const, 0}, + {"ELFDATA2LSB", Const, 0}, + {"ELFDATA2MSB", Const, 0}, + {"ELFDATANONE", Const, 0}, + {"ELFMAG", Const, 0}, + {"ELFOSABI_86OPEN", Const, 0}, + {"ELFOSABI_AIX", Const, 0}, + {"ELFOSABI_ARM", Const, 0}, + {"ELFOSABI_AROS", Const, 11}, + {"ELFOSABI_CLOUDABI", Const, 11}, + {"ELFOSABI_FENIXOS", Const, 11}, + {"ELFOSABI_FREEBSD", Const, 0}, + {"ELFOSABI_HPUX", Const, 0}, + {"ELFOSABI_HURD", Const, 0}, + {"ELFOSABI_IRIX", Const, 0}, + {"ELFOSABI_LINUX", Const, 0}, + {"ELFOSABI_MODESTO", Const, 0}, + {"ELFOSABI_NETBSD", Const, 0}, + {"ELFOSABI_NONE", Const, 0}, + {"ELFOSABI_NSK", Const, 0}, + {"ELFOSABI_OPENBSD", Const, 0}, + {"ELFOSABI_OPENVMS", Const, 0}, + {"ELFOSABI_SOLARIS", Const, 0}, + {"ELFOSABI_STANDALONE", Const, 0}, + {"ELFOSABI_TRU64", Const, 0}, + {"EM_386", Const, 0}, + {"EM_486", Const, 0}, + {"EM_56800EX", Const, 11}, + {"EM_68HC05", Const, 11}, + {"EM_68HC08", Const, 11}, + {"EM_68HC11", Const, 11}, + {"EM_68HC12", Const, 0}, + {"EM_68HC16", Const, 11}, + {"EM_68K", Const, 0}, + {"EM_78KOR", Const, 11}, + {"EM_8051", Const, 11}, + {"EM_860", Const, 0}, + {"EM_88K", Const, 0}, + {"EM_960", Const, 0}, + {"EM_AARCH64", Const, 4}, + {"EM_ALPHA", Const, 0}, + {"EM_ALPHA_STD", Const, 0}, + {"EM_ALTERA_NIOS2", Const, 11}, + {"EM_AMDGPU", Const, 11}, + {"EM_ARC", Const, 0}, + {"EM_ARCA", Const, 11}, + {"EM_ARC_COMPACT", Const, 11}, + {"EM_ARC_COMPACT2", Const, 11}, + {"EM_ARM", Const, 0}, + {"EM_AVR", Const, 11}, + {"EM_AVR32", Const, 11}, + {"EM_BA1", Const, 11}, + {"EM_BA2", Const, 11}, + {"EM_BLACKFIN", Const, 11}, + {"EM_BPF", Const, 11}, + {"EM_C166", Const, 11}, + {"EM_CDP", Const, 11}, + {"EM_CE", Const, 11}, + {"EM_CLOUDSHIELD", Const, 11}, + {"EM_COGE", Const, 11}, + {"EM_COLDFIRE", Const, 0}, + {"EM_COOL", Const, 11}, + {"EM_COREA_1ST", Const, 11}, + {"EM_COREA_2ND", Const, 11}, + {"EM_CR", Const, 11}, + {"EM_CR16", Const, 11}, + {"EM_CRAYNV2", Const, 11}, + {"EM_CRIS", Const, 11}, + {"EM_CRX", Const, 11}, + {"EM_CSR_KALIMBA", Const, 11}, + {"EM_CUDA", Const, 11}, + {"EM_CYPRESS_M8C", Const, 11}, + {"EM_D10V", Const, 11}, + {"EM_D30V", Const, 11}, + {"EM_DSP24", Const, 11}, + {"EM_DSPIC30F", Const, 11}, + {"EM_DXP", Const, 11}, + {"EM_ECOG1", Const, 11}, + {"EM_ECOG16", Const, 11}, + {"EM_ECOG1X", Const, 11}, + {"EM_ECOG2", Const, 11}, + {"EM_ETPU", Const, 11}, + {"EM_EXCESS", Const, 11}, + {"EM_F2MC16", Const, 11}, + {"EM_FIREPATH", Const, 11}, + {"EM_FR20", Const, 0}, + {"EM_FR30", Const, 11}, + {"EM_FT32", Const, 11}, + {"EM_FX66", Const, 11}, + {"EM_H8S", Const, 0}, + {"EM_H8_300", Const, 0}, + {"EM_H8_300H", Const, 0}, + {"EM_H8_500", Const, 0}, + {"EM_HUANY", Const, 11}, + {"EM_IA_64", Const, 0}, + {"EM_INTEL205", Const, 11}, + {"EM_INTEL206", Const, 11}, + {"EM_INTEL207", Const, 11}, + {"EM_INTEL208", Const, 11}, + {"EM_INTEL209", Const, 11}, + {"EM_IP2K", Const, 11}, + {"EM_JAVELIN", Const, 11}, + {"EM_K10M", Const, 11}, + {"EM_KM32", Const, 11}, + {"EM_KMX16", Const, 11}, + {"EM_KMX32", Const, 11}, + {"EM_KMX8", Const, 11}, + {"EM_KVARC", Const, 11}, + {"EM_L10M", Const, 11}, + {"EM_LANAI", Const, 11}, + {"EM_LATTICEMICO32", Const, 11}, + {"EM_LOONGARCH", Const, 19}, + {"EM_M16C", Const, 11}, + {"EM_M32", Const, 0}, + {"EM_M32C", Const, 11}, + {"EM_M32R", Const, 11}, + {"EM_MANIK", Const, 11}, + {"EM_MAX", Const, 11}, + {"EM_MAXQ30", Const, 11}, + {"EM_MCHP_PIC", Const, 11}, + {"EM_MCST_ELBRUS", Const, 11}, + {"EM_ME16", Const, 0}, + {"EM_METAG", Const, 11}, + {"EM_MICROBLAZE", Const, 11}, + {"EM_MIPS", Const, 0}, + {"EM_MIPS_RS3_LE", Const, 0}, + {"EM_MIPS_RS4_BE", Const, 0}, + {"EM_MIPS_X", Const, 0}, + {"EM_MMA", Const, 0}, + {"EM_MMDSP_PLUS", Const, 11}, + {"EM_MMIX", Const, 11}, + {"EM_MN10200", Const, 11}, + {"EM_MN10300", Const, 11}, + {"EM_MOXIE", Const, 11}, + {"EM_MSP430", Const, 11}, + {"EM_NCPU", Const, 0}, + {"EM_NDR1", Const, 0}, + {"EM_NDS32", Const, 11}, + {"EM_NONE", Const, 0}, + {"EM_NORC", Const, 11}, + {"EM_NS32K", Const, 11}, + {"EM_OPEN8", Const, 11}, + {"EM_OPENRISC", Const, 11}, + {"EM_PARISC", Const, 0}, + {"EM_PCP", Const, 0}, + {"EM_PDP10", Const, 11}, + {"EM_PDP11", Const, 11}, + {"EM_PDSP", Const, 11}, + {"EM_PJ", Const, 11}, + {"EM_PPC", Const, 0}, + {"EM_PPC64", Const, 0}, + {"EM_PRISM", Const, 11}, + {"EM_QDSP6", Const, 11}, + {"EM_R32C", Const, 11}, + {"EM_RCE", Const, 0}, + {"EM_RH32", Const, 0}, + {"EM_RISCV", Const, 11}, + {"EM_RL78", Const, 11}, + {"EM_RS08", Const, 11}, + {"EM_RX", Const, 11}, + {"EM_S370", Const, 0}, + {"EM_S390", Const, 0}, + {"EM_SCORE7", Const, 11}, + {"EM_SEP", Const, 11}, + {"EM_SE_C17", Const, 11}, + {"EM_SE_C33", Const, 11}, + {"EM_SH", Const, 0}, + {"EM_SHARC", Const, 11}, + {"EM_SLE9X", Const, 11}, + {"EM_SNP1K", Const, 11}, + {"EM_SPARC", Const, 0}, + {"EM_SPARC32PLUS", Const, 0}, + {"EM_SPARCV9", Const, 0}, + {"EM_ST100", Const, 0}, + {"EM_ST19", Const, 11}, + {"EM_ST200", Const, 11}, + {"EM_ST7", Const, 11}, + {"EM_ST9PLUS", Const, 11}, + {"EM_STARCORE", Const, 0}, + {"EM_STM8", Const, 11}, + {"EM_STXP7X", Const, 11}, + {"EM_SVX", Const, 11}, + {"EM_TILE64", Const, 11}, + {"EM_TILEGX", Const, 11}, + {"EM_TILEPRO", Const, 11}, + {"EM_TINYJ", Const, 0}, + {"EM_TI_ARP32", Const, 11}, + {"EM_TI_C2000", Const, 11}, + {"EM_TI_C5500", Const, 11}, + {"EM_TI_C6000", Const, 11}, + {"EM_TI_PRU", Const, 11}, + {"EM_TMM_GPP", Const, 11}, + {"EM_TPC", Const, 11}, + {"EM_TRICORE", Const, 0}, + {"EM_TRIMEDIA", Const, 11}, + {"EM_TSK3000", Const, 11}, + {"EM_UNICORE", Const, 11}, + {"EM_V800", Const, 0}, + {"EM_V850", Const, 11}, + {"EM_VAX", Const, 11}, + {"EM_VIDEOCORE", Const, 11}, + {"EM_VIDEOCORE3", Const, 11}, + {"EM_VIDEOCORE5", Const, 11}, + {"EM_VISIUM", Const, 11}, + {"EM_VPP500", Const, 0}, + {"EM_X86_64", Const, 0}, + {"EM_XCORE", Const, 11}, + {"EM_XGATE", Const, 11}, + {"EM_XIMO16", Const, 11}, + {"EM_XTENSA", Const, 11}, + {"EM_Z80", Const, 11}, + {"EM_ZSP", Const, 11}, + {"ET_CORE", Const, 0}, + {"ET_DYN", Const, 0}, + {"ET_EXEC", Const, 0}, + {"ET_HIOS", Const, 0}, + {"ET_HIPROC", Const, 0}, + {"ET_LOOS", Const, 0}, + {"ET_LOPROC", Const, 0}, + {"ET_NONE", Const, 0}, + {"ET_REL", Const, 0}, + {"EV_CURRENT", Const, 0}, + {"EV_NONE", Const, 0}, + {"ErrNoSymbols", Var, 4}, + {"File", Type, 0}, + {"File.FileHeader", Field, 0}, + {"File.Progs", Field, 0}, + {"File.Sections", Field, 0}, + {"FileHeader", Type, 0}, + {"FileHeader.ABIVersion", Field, 0}, + {"FileHeader.ByteOrder", Field, 0}, + {"FileHeader.Class", Field, 0}, + {"FileHeader.Data", Field, 0}, + {"FileHeader.Entry", Field, 1}, + {"FileHeader.Machine", Field, 0}, + {"FileHeader.OSABI", Field, 0}, + {"FileHeader.Type", Field, 0}, + {"FileHeader.Version", Field, 0}, + {"FormatError", Type, 0}, + {"Header32", Type, 0}, + {"Header32.Ehsize", Field, 0}, + {"Header32.Entry", Field, 0}, + {"Header32.Flags", Field, 0}, + {"Header32.Ident", Field, 0}, + {"Header32.Machine", Field, 0}, + {"Header32.Phentsize", Field, 0}, + {"Header32.Phnum", Field, 0}, + {"Header32.Phoff", Field, 0}, + {"Header32.Shentsize", Field, 0}, + {"Header32.Shnum", Field, 0}, + {"Header32.Shoff", Field, 0}, + {"Header32.Shstrndx", Field, 0}, + {"Header32.Type", Field, 0}, + {"Header32.Version", Field, 0}, + {"Header64", Type, 0}, + {"Header64.Ehsize", Field, 0}, + {"Header64.Entry", Field, 0}, + {"Header64.Flags", Field, 0}, + {"Header64.Ident", Field, 0}, + {"Header64.Machine", Field, 0}, + {"Header64.Phentsize", Field, 0}, + {"Header64.Phnum", Field, 0}, + {"Header64.Phoff", Field, 0}, + {"Header64.Shentsize", Field, 0}, + {"Header64.Shnum", Field, 0}, + {"Header64.Shoff", Field, 0}, + {"Header64.Shstrndx", Field, 0}, + {"Header64.Type", Field, 0}, + {"Header64.Version", Field, 0}, + {"ImportedSymbol", Type, 0}, + {"ImportedSymbol.Library", Field, 0}, + {"ImportedSymbol.Name", Field, 0}, + {"ImportedSymbol.Version", Field, 0}, + {"Machine", Type, 0}, + {"NT_FPREGSET", Const, 0}, + {"NT_PRPSINFO", Const, 0}, + {"NT_PRSTATUS", Const, 0}, + {"NType", Type, 0}, + {"NewFile", Func, 0}, + {"OSABI", Type, 0}, + {"Open", Func, 0}, + {"PF_MASKOS", Const, 0}, + {"PF_MASKPROC", Const, 0}, + {"PF_R", Const, 0}, + {"PF_W", Const, 0}, + {"PF_X", Const, 0}, + {"PT_AARCH64_ARCHEXT", Const, 16}, + {"PT_AARCH64_UNWIND", Const, 16}, + {"PT_ARM_ARCHEXT", Const, 16}, + {"PT_ARM_EXIDX", Const, 16}, + {"PT_DYNAMIC", Const, 0}, + {"PT_GNU_EH_FRAME", Const, 16}, + {"PT_GNU_MBIND_HI", Const, 16}, + {"PT_GNU_MBIND_LO", Const, 16}, + {"PT_GNU_PROPERTY", Const, 16}, + {"PT_GNU_RELRO", Const, 16}, + {"PT_GNU_STACK", Const, 16}, + {"PT_HIOS", Const, 0}, + {"PT_HIPROC", Const, 0}, + {"PT_INTERP", Const, 0}, + {"PT_LOAD", Const, 0}, + {"PT_LOOS", Const, 0}, + {"PT_LOPROC", Const, 0}, + {"PT_MIPS_ABIFLAGS", Const, 16}, + {"PT_MIPS_OPTIONS", Const, 16}, + {"PT_MIPS_REGINFO", Const, 16}, + {"PT_MIPS_RTPROC", Const, 16}, + {"PT_NOTE", Const, 0}, + {"PT_NULL", Const, 0}, + {"PT_OPENBSD_BOOTDATA", Const, 16}, + {"PT_OPENBSD_NOBTCFI", Const, 23}, + {"PT_OPENBSD_RANDOMIZE", Const, 16}, + {"PT_OPENBSD_WXNEEDED", Const, 16}, + {"PT_PAX_FLAGS", Const, 16}, + {"PT_PHDR", Const, 0}, + {"PT_S390_PGSTE", Const, 16}, + {"PT_SHLIB", Const, 0}, + {"PT_SUNWSTACK", Const, 16}, + {"PT_SUNW_EH_FRAME", Const, 16}, + {"PT_TLS", Const, 0}, + {"Prog", Type, 0}, + {"Prog.ProgHeader", Field, 0}, + {"Prog.ReaderAt", Field, 0}, + {"Prog32", Type, 0}, + {"Prog32.Align", Field, 0}, + {"Prog32.Filesz", Field, 0}, + {"Prog32.Flags", Field, 0}, + {"Prog32.Memsz", Field, 0}, + {"Prog32.Off", Field, 0}, + {"Prog32.Paddr", Field, 0}, + {"Prog32.Type", Field, 0}, + {"Prog32.Vaddr", Field, 0}, + {"Prog64", Type, 0}, + {"Prog64.Align", Field, 0}, + {"Prog64.Filesz", Field, 0}, + {"Prog64.Flags", Field, 0}, + {"Prog64.Memsz", Field, 0}, + {"Prog64.Off", Field, 0}, + {"Prog64.Paddr", Field, 0}, + {"Prog64.Type", Field, 0}, + {"Prog64.Vaddr", Field, 0}, + {"ProgFlag", Type, 0}, + {"ProgHeader", Type, 0}, + {"ProgHeader.Align", Field, 0}, + {"ProgHeader.Filesz", Field, 0}, + {"ProgHeader.Flags", Field, 0}, + {"ProgHeader.Memsz", Field, 0}, + {"ProgHeader.Off", Field, 0}, + {"ProgHeader.Paddr", Field, 0}, + {"ProgHeader.Type", Field, 0}, + {"ProgHeader.Vaddr", Field, 0}, + {"ProgType", Type, 0}, + {"R_386", Type, 0}, + {"R_386_16", Const, 10}, + {"R_386_32", Const, 0}, + {"R_386_32PLT", Const, 10}, + {"R_386_8", Const, 10}, + {"R_386_COPY", Const, 0}, + {"R_386_GLOB_DAT", Const, 0}, + {"R_386_GOT32", Const, 0}, + {"R_386_GOT32X", Const, 10}, + {"R_386_GOTOFF", Const, 0}, + {"R_386_GOTPC", Const, 0}, + {"R_386_IRELATIVE", Const, 10}, + {"R_386_JMP_SLOT", Const, 0}, + {"R_386_NONE", Const, 0}, + {"R_386_PC16", Const, 10}, + {"R_386_PC32", Const, 0}, + {"R_386_PC8", Const, 10}, + {"R_386_PLT32", Const, 0}, + {"R_386_RELATIVE", Const, 0}, + {"R_386_SIZE32", Const, 10}, + {"R_386_TLS_DESC", Const, 10}, + {"R_386_TLS_DESC_CALL", Const, 10}, + {"R_386_TLS_DTPMOD32", Const, 0}, + {"R_386_TLS_DTPOFF32", Const, 0}, + {"R_386_TLS_GD", Const, 0}, + {"R_386_TLS_GD_32", Const, 0}, + {"R_386_TLS_GD_CALL", Const, 0}, + {"R_386_TLS_GD_POP", Const, 0}, + {"R_386_TLS_GD_PUSH", Const, 0}, + {"R_386_TLS_GOTDESC", Const, 10}, + {"R_386_TLS_GOTIE", Const, 0}, + {"R_386_TLS_IE", Const, 0}, + {"R_386_TLS_IE_32", Const, 0}, + {"R_386_TLS_LDM", Const, 0}, + {"R_386_TLS_LDM_32", Const, 0}, + {"R_386_TLS_LDM_CALL", Const, 0}, + {"R_386_TLS_LDM_POP", Const, 0}, + {"R_386_TLS_LDM_PUSH", Const, 0}, + {"R_386_TLS_LDO_32", Const, 0}, + {"R_386_TLS_LE", Const, 0}, + {"R_386_TLS_LE_32", Const, 0}, + {"R_386_TLS_TPOFF", Const, 0}, + {"R_386_TLS_TPOFF32", Const, 0}, + {"R_390", Type, 7}, + {"R_390_12", Const, 7}, + {"R_390_16", Const, 7}, + {"R_390_20", Const, 7}, + {"R_390_32", Const, 7}, + {"R_390_64", Const, 7}, + {"R_390_8", Const, 7}, + {"R_390_COPY", Const, 7}, + {"R_390_GLOB_DAT", Const, 7}, + {"R_390_GOT12", Const, 7}, + {"R_390_GOT16", Const, 7}, + {"R_390_GOT20", Const, 7}, + {"R_390_GOT32", Const, 7}, + {"R_390_GOT64", Const, 7}, + {"R_390_GOTENT", Const, 7}, + {"R_390_GOTOFF", Const, 7}, + {"R_390_GOTOFF16", Const, 7}, + {"R_390_GOTOFF64", Const, 7}, + {"R_390_GOTPC", Const, 7}, + {"R_390_GOTPCDBL", Const, 7}, + {"R_390_GOTPLT12", Const, 7}, + {"R_390_GOTPLT16", Const, 7}, + {"R_390_GOTPLT20", Const, 7}, + {"R_390_GOTPLT32", Const, 7}, + {"R_390_GOTPLT64", Const, 7}, + {"R_390_GOTPLTENT", Const, 7}, + {"R_390_GOTPLTOFF16", Const, 7}, + {"R_390_GOTPLTOFF32", Const, 7}, + {"R_390_GOTPLTOFF64", Const, 7}, + {"R_390_JMP_SLOT", Const, 7}, + {"R_390_NONE", Const, 7}, + {"R_390_PC16", Const, 7}, + {"R_390_PC16DBL", Const, 7}, + {"R_390_PC32", Const, 7}, + {"R_390_PC32DBL", Const, 7}, + {"R_390_PC64", Const, 7}, + {"R_390_PLT16DBL", Const, 7}, + {"R_390_PLT32", Const, 7}, + {"R_390_PLT32DBL", Const, 7}, + {"R_390_PLT64", Const, 7}, + {"R_390_RELATIVE", Const, 7}, + {"R_390_TLS_DTPMOD", Const, 7}, + {"R_390_TLS_DTPOFF", Const, 7}, + {"R_390_TLS_GD32", Const, 7}, + {"R_390_TLS_GD64", Const, 7}, + {"R_390_TLS_GDCALL", Const, 7}, + {"R_390_TLS_GOTIE12", Const, 7}, + {"R_390_TLS_GOTIE20", Const, 7}, + {"R_390_TLS_GOTIE32", Const, 7}, + {"R_390_TLS_GOTIE64", Const, 7}, + {"R_390_TLS_IE32", Const, 7}, + {"R_390_TLS_IE64", Const, 7}, + {"R_390_TLS_IEENT", Const, 7}, + {"R_390_TLS_LDCALL", Const, 7}, + {"R_390_TLS_LDM32", Const, 7}, + {"R_390_TLS_LDM64", Const, 7}, + {"R_390_TLS_LDO32", Const, 7}, + {"R_390_TLS_LDO64", Const, 7}, + {"R_390_TLS_LE32", Const, 7}, + {"R_390_TLS_LE64", Const, 7}, + {"R_390_TLS_LOAD", Const, 7}, + {"R_390_TLS_TPOFF", Const, 7}, + {"R_AARCH64", Type, 4}, + {"R_AARCH64_ABS16", Const, 4}, + {"R_AARCH64_ABS32", Const, 4}, + {"R_AARCH64_ABS64", Const, 4}, + {"R_AARCH64_ADD_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_ADR_GOT_PAGE", Const, 4}, + {"R_AARCH64_ADR_PREL_LO21", Const, 4}, + {"R_AARCH64_ADR_PREL_PG_HI21", Const, 4}, + {"R_AARCH64_ADR_PREL_PG_HI21_NC", Const, 4}, + {"R_AARCH64_CALL26", Const, 4}, + {"R_AARCH64_CONDBR19", Const, 4}, + {"R_AARCH64_COPY", Const, 4}, + {"R_AARCH64_GLOB_DAT", Const, 4}, + {"R_AARCH64_GOT_LD_PREL19", Const, 4}, + {"R_AARCH64_IRELATIVE", Const, 4}, + {"R_AARCH64_JUMP26", Const, 4}, + {"R_AARCH64_JUMP_SLOT", Const, 4}, + {"R_AARCH64_LD64_GOTOFF_LO15", Const, 10}, + {"R_AARCH64_LD64_GOTPAGE_LO15", Const, 10}, + {"R_AARCH64_LD64_GOT_LO12_NC", Const, 4}, + {"R_AARCH64_LDST128_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_LDST16_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_LDST32_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_LDST64_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_LDST8_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_LD_PREL_LO19", Const, 4}, + {"R_AARCH64_MOVW_SABS_G0", Const, 4}, + {"R_AARCH64_MOVW_SABS_G1", Const, 4}, + {"R_AARCH64_MOVW_SABS_G2", Const, 4}, + {"R_AARCH64_MOVW_UABS_G0", Const, 4}, + {"R_AARCH64_MOVW_UABS_G0_NC", Const, 4}, + {"R_AARCH64_MOVW_UABS_G1", Const, 4}, + {"R_AARCH64_MOVW_UABS_G1_NC", Const, 4}, + {"R_AARCH64_MOVW_UABS_G2", Const, 4}, + {"R_AARCH64_MOVW_UABS_G2_NC", Const, 4}, + {"R_AARCH64_MOVW_UABS_G3", Const, 4}, + {"R_AARCH64_NONE", Const, 4}, + {"R_AARCH64_NULL", Const, 4}, + {"R_AARCH64_P32_ABS16", Const, 4}, + {"R_AARCH64_P32_ABS32", Const, 4}, + {"R_AARCH64_P32_ADD_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_P32_ADR_GOT_PAGE", Const, 4}, + {"R_AARCH64_P32_ADR_PREL_LO21", Const, 4}, + {"R_AARCH64_P32_ADR_PREL_PG_HI21", Const, 4}, + {"R_AARCH64_P32_CALL26", Const, 4}, + {"R_AARCH64_P32_CONDBR19", Const, 4}, + {"R_AARCH64_P32_COPY", Const, 4}, + {"R_AARCH64_P32_GLOB_DAT", Const, 4}, + {"R_AARCH64_P32_GOT_LD_PREL19", Const, 4}, + {"R_AARCH64_P32_IRELATIVE", Const, 4}, + {"R_AARCH64_P32_JUMP26", Const, 4}, + {"R_AARCH64_P32_JUMP_SLOT", Const, 4}, + {"R_AARCH64_P32_LD32_GOT_LO12_NC", Const, 4}, + {"R_AARCH64_P32_LDST128_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_P32_LDST16_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_P32_LDST32_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_P32_LDST64_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_P32_LDST8_ABS_LO12_NC", Const, 4}, + {"R_AARCH64_P32_LD_PREL_LO19", Const, 4}, + {"R_AARCH64_P32_MOVW_SABS_G0", Const, 4}, + {"R_AARCH64_P32_MOVW_UABS_G0", Const, 4}, + {"R_AARCH64_P32_MOVW_UABS_G0_NC", Const, 4}, + {"R_AARCH64_P32_MOVW_UABS_G1", Const, 4}, + {"R_AARCH64_P32_PREL16", Const, 4}, + {"R_AARCH64_P32_PREL32", Const, 4}, + {"R_AARCH64_P32_RELATIVE", Const, 4}, + {"R_AARCH64_P32_TLSDESC", Const, 4}, + {"R_AARCH64_P32_TLSDESC_ADD_LO12_NC", Const, 4}, + {"R_AARCH64_P32_TLSDESC_ADR_PAGE21", Const, 4}, + {"R_AARCH64_P32_TLSDESC_ADR_PREL21", Const, 4}, + {"R_AARCH64_P32_TLSDESC_CALL", Const, 4}, + {"R_AARCH64_P32_TLSDESC_LD32_LO12_NC", Const, 4}, + {"R_AARCH64_P32_TLSDESC_LD_PREL19", Const, 4}, + {"R_AARCH64_P32_TLSGD_ADD_LO12_NC", Const, 4}, + {"R_AARCH64_P32_TLSGD_ADR_PAGE21", Const, 4}, + {"R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21", Const, 4}, + {"R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC", Const, 4}, + {"R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19", Const, 4}, + {"R_AARCH64_P32_TLSLE_ADD_TPREL_HI12", Const, 4}, + {"R_AARCH64_P32_TLSLE_ADD_TPREL_LO12", Const, 4}, + {"R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC", Const, 4}, + {"R_AARCH64_P32_TLSLE_MOVW_TPREL_G0", Const, 4}, + {"R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC", Const, 4}, + {"R_AARCH64_P32_TLSLE_MOVW_TPREL_G1", Const, 4}, + {"R_AARCH64_P32_TLS_DTPMOD", Const, 4}, + {"R_AARCH64_P32_TLS_DTPREL", Const, 4}, + {"R_AARCH64_P32_TLS_TPREL", Const, 4}, + {"R_AARCH64_P32_TSTBR14", Const, 4}, + {"R_AARCH64_PREL16", Const, 4}, + {"R_AARCH64_PREL32", Const, 4}, + {"R_AARCH64_PREL64", Const, 4}, + {"R_AARCH64_RELATIVE", Const, 4}, + {"R_AARCH64_TLSDESC", Const, 4}, + {"R_AARCH64_TLSDESC_ADD", Const, 4}, + {"R_AARCH64_TLSDESC_ADD_LO12_NC", Const, 4}, + {"R_AARCH64_TLSDESC_ADR_PAGE21", Const, 4}, + {"R_AARCH64_TLSDESC_ADR_PREL21", Const, 4}, + {"R_AARCH64_TLSDESC_CALL", Const, 4}, + {"R_AARCH64_TLSDESC_LD64_LO12_NC", Const, 4}, + {"R_AARCH64_TLSDESC_LDR", Const, 4}, + {"R_AARCH64_TLSDESC_LD_PREL19", Const, 4}, + {"R_AARCH64_TLSDESC_OFF_G0_NC", Const, 4}, + {"R_AARCH64_TLSDESC_OFF_G1", Const, 4}, + {"R_AARCH64_TLSGD_ADD_LO12_NC", Const, 4}, + {"R_AARCH64_TLSGD_ADR_PAGE21", Const, 4}, + {"R_AARCH64_TLSGD_ADR_PREL21", Const, 10}, + {"R_AARCH64_TLSGD_MOVW_G0_NC", Const, 10}, + {"R_AARCH64_TLSGD_MOVW_G1", Const, 10}, + {"R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21", Const, 4}, + {"R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC", Const, 4}, + {"R_AARCH64_TLSIE_LD_GOTTPREL_PREL19", Const, 4}, + {"R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC", Const, 4}, + {"R_AARCH64_TLSIE_MOVW_GOTTPREL_G1", Const, 4}, + {"R_AARCH64_TLSLD_ADR_PAGE21", Const, 10}, + {"R_AARCH64_TLSLD_ADR_PREL21", Const, 10}, + {"R_AARCH64_TLSLD_LDST128_DTPREL_LO12", Const, 10}, + {"R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC", Const, 10}, + {"R_AARCH64_TLSLE_ADD_TPREL_HI12", Const, 4}, + {"R_AARCH64_TLSLE_ADD_TPREL_LO12", Const, 4}, + {"R_AARCH64_TLSLE_ADD_TPREL_LO12_NC", Const, 4}, + {"R_AARCH64_TLSLE_LDST128_TPREL_LO12", Const, 10}, + {"R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC", Const, 10}, + {"R_AARCH64_TLSLE_MOVW_TPREL_G0", Const, 4}, + {"R_AARCH64_TLSLE_MOVW_TPREL_G0_NC", Const, 4}, + {"R_AARCH64_TLSLE_MOVW_TPREL_G1", Const, 4}, + {"R_AARCH64_TLSLE_MOVW_TPREL_G1_NC", Const, 4}, + {"R_AARCH64_TLSLE_MOVW_TPREL_G2", Const, 4}, + {"R_AARCH64_TLS_DTPMOD64", Const, 4}, + {"R_AARCH64_TLS_DTPREL64", Const, 4}, + {"R_AARCH64_TLS_TPREL64", Const, 4}, + {"R_AARCH64_TSTBR14", Const, 4}, + {"R_ALPHA", Type, 0}, + {"R_ALPHA_BRADDR", Const, 0}, + {"R_ALPHA_COPY", Const, 0}, + {"R_ALPHA_GLOB_DAT", Const, 0}, + {"R_ALPHA_GPDISP", Const, 0}, + {"R_ALPHA_GPREL32", Const, 0}, + {"R_ALPHA_GPRELHIGH", Const, 0}, + {"R_ALPHA_GPRELLOW", Const, 0}, + {"R_ALPHA_GPVALUE", Const, 0}, + {"R_ALPHA_HINT", Const, 0}, + {"R_ALPHA_IMMED_BR_HI32", Const, 0}, + {"R_ALPHA_IMMED_GP_16", Const, 0}, + {"R_ALPHA_IMMED_GP_HI32", Const, 0}, + {"R_ALPHA_IMMED_LO32", Const, 0}, + {"R_ALPHA_IMMED_SCN_HI32", Const, 0}, + {"R_ALPHA_JMP_SLOT", Const, 0}, + {"R_ALPHA_LITERAL", Const, 0}, + {"R_ALPHA_LITUSE", Const, 0}, + {"R_ALPHA_NONE", Const, 0}, + {"R_ALPHA_OP_PRSHIFT", Const, 0}, + {"R_ALPHA_OP_PSUB", Const, 0}, + {"R_ALPHA_OP_PUSH", Const, 0}, + {"R_ALPHA_OP_STORE", Const, 0}, + {"R_ALPHA_REFLONG", Const, 0}, + {"R_ALPHA_REFQUAD", Const, 0}, + {"R_ALPHA_RELATIVE", Const, 0}, + {"R_ALPHA_SREL16", Const, 0}, + {"R_ALPHA_SREL32", Const, 0}, + {"R_ALPHA_SREL64", Const, 0}, + {"R_ARM", Type, 0}, + {"R_ARM_ABS12", Const, 0}, + {"R_ARM_ABS16", Const, 0}, + {"R_ARM_ABS32", Const, 0}, + {"R_ARM_ABS32_NOI", Const, 10}, + {"R_ARM_ABS8", Const, 0}, + {"R_ARM_ALU_PCREL_15_8", Const, 10}, + {"R_ARM_ALU_PCREL_23_15", Const, 10}, + {"R_ARM_ALU_PCREL_7_0", Const, 10}, + {"R_ARM_ALU_PC_G0", Const, 10}, + {"R_ARM_ALU_PC_G0_NC", Const, 10}, + {"R_ARM_ALU_PC_G1", Const, 10}, + {"R_ARM_ALU_PC_G1_NC", Const, 10}, + {"R_ARM_ALU_PC_G2", Const, 10}, + {"R_ARM_ALU_SBREL_19_12_NC", Const, 10}, + {"R_ARM_ALU_SBREL_27_20_CK", Const, 10}, + {"R_ARM_ALU_SB_G0", Const, 10}, + {"R_ARM_ALU_SB_G0_NC", Const, 10}, + {"R_ARM_ALU_SB_G1", Const, 10}, + {"R_ARM_ALU_SB_G1_NC", Const, 10}, + {"R_ARM_ALU_SB_G2", Const, 10}, + {"R_ARM_AMP_VCALL9", Const, 0}, + {"R_ARM_BASE_ABS", Const, 10}, + {"R_ARM_CALL", Const, 10}, + {"R_ARM_COPY", Const, 0}, + {"R_ARM_GLOB_DAT", Const, 0}, + {"R_ARM_GNU_VTENTRY", Const, 0}, + {"R_ARM_GNU_VTINHERIT", Const, 0}, + {"R_ARM_GOT32", Const, 0}, + {"R_ARM_GOTOFF", Const, 0}, + {"R_ARM_GOTOFF12", Const, 10}, + {"R_ARM_GOTPC", Const, 0}, + {"R_ARM_GOTRELAX", Const, 10}, + {"R_ARM_GOT_ABS", Const, 10}, + {"R_ARM_GOT_BREL12", Const, 10}, + {"R_ARM_GOT_PREL", Const, 10}, + {"R_ARM_IRELATIVE", Const, 10}, + {"R_ARM_JUMP24", Const, 10}, + {"R_ARM_JUMP_SLOT", Const, 0}, + {"R_ARM_LDC_PC_G0", Const, 10}, + {"R_ARM_LDC_PC_G1", Const, 10}, + {"R_ARM_LDC_PC_G2", Const, 10}, + {"R_ARM_LDC_SB_G0", Const, 10}, + {"R_ARM_LDC_SB_G1", Const, 10}, + {"R_ARM_LDC_SB_G2", Const, 10}, + {"R_ARM_LDRS_PC_G0", Const, 10}, + {"R_ARM_LDRS_PC_G1", Const, 10}, + {"R_ARM_LDRS_PC_G2", Const, 10}, + {"R_ARM_LDRS_SB_G0", Const, 10}, + {"R_ARM_LDRS_SB_G1", Const, 10}, + {"R_ARM_LDRS_SB_G2", Const, 10}, + {"R_ARM_LDR_PC_G1", Const, 10}, + {"R_ARM_LDR_PC_G2", Const, 10}, + {"R_ARM_LDR_SBREL_11_10_NC", Const, 10}, + {"R_ARM_LDR_SB_G0", Const, 10}, + {"R_ARM_LDR_SB_G1", Const, 10}, + {"R_ARM_LDR_SB_G2", Const, 10}, + {"R_ARM_ME_TOO", Const, 10}, + {"R_ARM_MOVT_ABS", Const, 10}, + {"R_ARM_MOVT_BREL", Const, 10}, + {"R_ARM_MOVT_PREL", Const, 10}, + {"R_ARM_MOVW_ABS_NC", Const, 10}, + {"R_ARM_MOVW_BREL", Const, 10}, + {"R_ARM_MOVW_BREL_NC", Const, 10}, + {"R_ARM_MOVW_PREL_NC", Const, 10}, + {"R_ARM_NONE", Const, 0}, + {"R_ARM_PC13", Const, 0}, + {"R_ARM_PC24", Const, 0}, + {"R_ARM_PLT32", Const, 0}, + {"R_ARM_PLT32_ABS", Const, 10}, + {"R_ARM_PREL31", Const, 10}, + {"R_ARM_PRIVATE_0", Const, 10}, + {"R_ARM_PRIVATE_1", Const, 10}, + {"R_ARM_PRIVATE_10", Const, 10}, + {"R_ARM_PRIVATE_11", Const, 10}, + {"R_ARM_PRIVATE_12", Const, 10}, + {"R_ARM_PRIVATE_13", Const, 10}, + {"R_ARM_PRIVATE_14", Const, 10}, + {"R_ARM_PRIVATE_15", Const, 10}, + {"R_ARM_PRIVATE_2", Const, 10}, + {"R_ARM_PRIVATE_3", Const, 10}, + {"R_ARM_PRIVATE_4", Const, 10}, + {"R_ARM_PRIVATE_5", Const, 10}, + {"R_ARM_PRIVATE_6", Const, 10}, + {"R_ARM_PRIVATE_7", Const, 10}, + {"R_ARM_PRIVATE_8", Const, 10}, + {"R_ARM_PRIVATE_9", Const, 10}, + {"R_ARM_RABS32", Const, 0}, + {"R_ARM_RBASE", Const, 0}, + {"R_ARM_REL32", Const, 0}, + {"R_ARM_REL32_NOI", Const, 10}, + {"R_ARM_RELATIVE", Const, 0}, + {"R_ARM_RPC24", Const, 0}, + {"R_ARM_RREL32", Const, 0}, + {"R_ARM_RSBREL32", Const, 0}, + {"R_ARM_RXPC25", Const, 10}, + {"R_ARM_SBREL31", Const, 10}, + {"R_ARM_SBREL32", Const, 0}, + {"R_ARM_SWI24", Const, 0}, + {"R_ARM_TARGET1", Const, 10}, + {"R_ARM_TARGET2", Const, 10}, + {"R_ARM_THM_ABS5", Const, 0}, + {"R_ARM_THM_ALU_ABS_G0_NC", Const, 10}, + {"R_ARM_THM_ALU_ABS_G1_NC", Const, 10}, + {"R_ARM_THM_ALU_ABS_G2_NC", Const, 10}, + {"R_ARM_THM_ALU_ABS_G3", Const, 10}, + {"R_ARM_THM_ALU_PREL_11_0", Const, 10}, + {"R_ARM_THM_GOT_BREL12", Const, 10}, + {"R_ARM_THM_JUMP11", Const, 10}, + {"R_ARM_THM_JUMP19", Const, 10}, + {"R_ARM_THM_JUMP24", Const, 10}, + {"R_ARM_THM_JUMP6", Const, 10}, + {"R_ARM_THM_JUMP8", Const, 10}, + {"R_ARM_THM_MOVT_ABS", Const, 10}, + {"R_ARM_THM_MOVT_BREL", Const, 10}, + {"R_ARM_THM_MOVT_PREL", Const, 10}, + {"R_ARM_THM_MOVW_ABS_NC", Const, 10}, + {"R_ARM_THM_MOVW_BREL", Const, 10}, + {"R_ARM_THM_MOVW_BREL_NC", Const, 10}, + {"R_ARM_THM_MOVW_PREL_NC", Const, 10}, + {"R_ARM_THM_PC12", Const, 10}, + {"R_ARM_THM_PC22", Const, 0}, + {"R_ARM_THM_PC8", Const, 0}, + {"R_ARM_THM_RPC22", Const, 0}, + {"R_ARM_THM_SWI8", Const, 0}, + {"R_ARM_THM_TLS_CALL", Const, 10}, + {"R_ARM_THM_TLS_DESCSEQ16", Const, 10}, + {"R_ARM_THM_TLS_DESCSEQ32", Const, 10}, + {"R_ARM_THM_XPC22", Const, 0}, + {"R_ARM_TLS_CALL", Const, 10}, + {"R_ARM_TLS_DESCSEQ", Const, 10}, + {"R_ARM_TLS_DTPMOD32", Const, 10}, + {"R_ARM_TLS_DTPOFF32", Const, 10}, + {"R_ARM_TLS_GD32", Const, 10}, + {"R_ARM_TLS_GOTDESC", Const, 10}, + {"R_ARM_TLS_IE12GP", Const, 10}, + {"R_ARM_TLS_IE32", Const, 10}, + {"R_ARM_TLS_LDM32", Const, 10}, + {"R_ARM_TLS_LDO12", Const, 10}, + {"R_ARM_TLS_LDO32", Const, 10}, + {"R_ARM_TLS_LE12", Const, 10}, + {"R_ARM_TLS_LE32", Const, 10}, + {"R_ARM_TLS_TPOFF32", Const, 10}, + {"R_ARM_V4BX", Const, 10}, + {"R_ARM_XPC25", Const, 0}, + {"R_INFO", Func, 0}, + {"R_INFO32", Func, 0}, + {"R_LARCH", Type, 19}, + {"R_LARCH_32", Const, 19}, + {"R_LARCH_32_PCREL", Const, 20}, + {"R_LARCH_64", Const, 19}, + {"R_LARCH_64_PCREL", Const, 22}, + {"R_LARCH_ABS64_HI12", Const, 20}, + {"R_LARCH_ABS64_LO20", Const, 20}, + {"R_LARCH_ABS_HI20", Const, 20}, + {"R_LARCH_ABS_LO12", Const, 20}, + {"R_LARCH_ADD16", Const, 19}, + {"R_LARCH_ADD24", Const, 19}, + {"R_LARCH_ADD32", Const, 19}, + {"R_LARCH_ADD6", Const, 22}, + {"R_LARCH_ADD64", Const, 19}, + {"R_LARCH_ADD8", Const, 19}, + {"R_LARCH_ADD_ULEB128", Const, 22}, + {"R_LARCH_ALIGN", Const, 22}, + {"R_LARCH_B16", Const, 20}, + {"R_LARCH_B21", Const, 20}, + {"R_LARCH_B26", Const, 20}, + {"R_LARCH_CFA", Const, 22}, + {"R_LARCH_COPY", Const, 19}, + {"R_LARCH_DELETE", Const, 22}, + {"R_LARCH_GNU_VTENTRY", Const, 20}, + {"R_LARCH_GNU_VTINHERIT", Const, 20}, + {"R_LARCH_GOT64_HI12", Const, 20}, + {"R_LARCH_GOT64_LO20", Const, 20}, + {"R_LARCH_GOT64_PC_HI12", Const, 20}, + {"R_LARCH_GOT64_PC_LO20", Const, 20}, + {"R_LARCH_GOT_HI20", Const, 20}, + {"R_LARCH_GOT_LO12", Const, 20}, + {"R_LARCH_GOT_PC_HI20", Const, 20}, + {"R_LARCH_GOT_PC_LO12", Const, 20}, + {"R_LARCH_IRELATIVE", Const, 19}, + {"R_LARCH_JUMP_SLOT", Const, 19}, + {"R_LARCH_MARK_LA", Const, 19}, + {"R_LARCH_MARK_PCREL", Const, 19}, + {"R_LARCH_NONE", Const, 19}, + {"R_LARCH_PCALA64_HI12", Const, 20}, + {"R_LARCH_PCALA64_LO20", Const, 20}, + {"R_LARCH_PCALA_HI20", Const, 20}, + {"R_LARCH_PCALA_LO12", Const, 20}, + {"R_LARCH_PCREL20_S2", Const, 22}, + {"R_LARCH_RELATIVE", Const, 19}, + {"R_LARCH_RELAX", Const, 20}, + {"R_LARCH_SOP_ADD", Const, 19}, + {"R_LARCH_SOP_AND", Const, 19}, + {"R_LARCH_SOP_ASSERT", Const, 19}, + {"R_LARCH_SOP_IF_ELSE", Const, 19}, + {"R_LARCH_SOP_NOT", Const, 19}, + {"R_LARCH_SOP_POP_32_S_0_10_10_16_S2", Const, 19}, + {"R_LARCH_SOP_POP_32_S_0_5_10_16_S2", Const, 19}, + {"R_LARCH_SOP_POP_32_S_10_12", Const, 19}, + {"R_LARCH_SOP_POP_32_S_10_16", Const, 19}, + {"R_LARCH_SOP_POP_32_S_10_16_S2", Const, 19}, + {"R_LARCH_SOP_POP_32_S_10_5", Const, 19}, + {"R_LARCH_SOP_POP_32_S_5_20", Const, 19}, + {"R_LARCH_SOP_POP_32_U", Const, 19}, + {"R_LARCH_SOP_POP_32_U_10_12", Const, 19}, + {"R_LARCH_SOP_PUSH_ABSOLUTE", Const, 19}, + {"R_LARCH_SOP_PUSH_DUP", Const, 19}, + {"R_LARCH_SOP_PUSH_GPREL", Const, 19}, + {"R_LARCH_SOP_PUSH_PCREL", Const, 19}, + {"R_LARCH_SOP_PUSH_PLT_PCREL", Const, 19}, + {"R_LARCH_SOP_PUSH_TLS_GD", Const, 19}, + {"R_LARCH_SOP_PUSH_TLS_GOT", Const, 19}, + {"R_LARCH_SOP_PUSH_TLS_TPREL", Const, 19}, + {"R_LARCH_SOP_SL", Const, 19}, + {"R_LARCH_SOP_SR", Const, 19}, + {"R_LARCH_SOP_SUB", Const, 19}, + {"R_LARCH_SUB16", Const, 19}, + {"R_LARCH_SUB24", Const, 19}, + {"R_LARCH_SUB32", Const, 19}, + {"R_LARCH_SUB6", Const, 22}, + {"R_LARCH_SUB64", Const, 19}, + {"R_LARCH_SUB8", Const, 19}, + {"R_LARCH_SUB_ULEB128", Const, 22}, + {"R_LARCH_TLS_DTPMOD32", Const, 19}, + {"R_LARCH_TLS_DTPMOD64", Const, 19}, + {"R_LARCH_TLS_DTPREL32", Const, 19}, + {"R_LARCH_TLS_DTPREL64", Const, 19}, + {"R_LARCH_TLS_GD_HI20", Const, 20}, + {"R_LARCH_TLS_GD_PC_HI20", Const, 20}, + {"R_LARCH_TLS_IE64_HI12", Const, 20}, + {"R_LARCH_TLS_IE64_LO20", Const, 20}, + {"R_LARCH_TLS_IE64_PC_HI12", Const, 20}, + {"R_LARCH_TLS_IE64_PC_LO20", Const, 20}, + {"R_LARCH_TLS_IE_HI20", Const, 20}, + {"R_LARCH_TLS_IE_LO12", Const, 20}, + {"R_LARCH_TLS_IE_PC_HI20", Const, 20}, + {"R_LARCH_TLS_IE_PC_LO12", Const, 20}, + {"R_LARCH_TLS_LD_HI20", Const, 20}, + {"R_LARCH_TLS_LD_PC_HI20", Const, 20}, + {"R_LARCH_TLS_LE64_HI12", Const, 20}, + {"R_LARCH_TLS_LE64_LO20", Const, 20}, + {"R_LARCH_TLS_LE_HI20", Const, 20}, + {"R_LARCH_TLS_LE_LO12", Const, 20}, + {"R_LARCH_TLS_TPREL32", Const, 19}, + {"R_LARCH_TLS_TPREL64", Const, 19}, + {"R_MIPS", Type, 6}, + {"R_MIPS_16", Const, 6}, + {"R_MIPS_26", Const, 6}, + {"R_MIPS_32", Const, 6}, + {"R_MIPS_64", Const, 6}, + {"R_MIPS_ADD_IMMEDIATE", Const, 6}, + {"R_MIPS_CALL16", Const, 6}, + {"R_MIPS_CALL_HI16", Const, 6}, + {"R_MIPS_CALL_LO16", Const, 6}, + {"R_MIPS_DELETE", Const, 6}, + {"R_MIPS_GOT16", Const, 6}, + {"R_MIPS_GOT_DISP", Const, 6}, + {"R_MIPS_GOT_HI16", Const, 6}, + {"R_MIPS_GOT_LO16", Const, 6}, + {"R_MIPS_GOT_OFST", Const, 6}, + {"R_MIPS_GOT_PAGE", Const, 6}, + {"R_MIPS_GPREL16", Const, 6}, + {"R_MIPS_GPREL32", Const, 6}, + {"R_MIPS_HI16", Const, 6}, + {"R_MIPS_HIGHER", Const, 6}, + {"R_MIPS_HIGHEST", Const, 6}, + {"R_MIPS_INSERT_A", Const, 6}, + {"R_MIPS_INSERT_B", Const, 6}, + {"R_MIPS_JALR", Const, 6}, + {"R_MIPS_LITERAL", Const, 6}, + {"R_MIPS_LO16", Const, 6}, + {"R_MIPS_NONE", Const, 6}, + {"R_MIPS_PC16", Const, 6}, + {"R_MIPS_PC32", Const, 22}, + {"R_MIPS_PJUMP", Const, 6}, + {"R_MIPS_REL16", Const, 6}, + {"R_MIPS_REL32", Const, 6}, + {"R_MIPS_RELGOT", Const, 6}, + {"R_MIPS_SCN_DISP", Const, 6}, + {"R_MIPS_SHIFT5", Const, 6}, + {"R_MIPS_SHIFT6", Const, 6}, + {"R_MIPS_SUB", Const, 6}, + {"R_MIPS_TLS_DTPMOD32", Const, 6}, + {"R_MIPS_TLS_DTPMOD64", Const, 6}, + {"R_MIPS_TLS_DTPREL32", Const, 6}, + {"R_MIPS_TLS_DTPREL64", Const, 6}, + {"R_MIPS_TLS_DTPREL_HI16", Const, 6}, + {"R_MIPS_TLS_DTPREL_LO16", Const, 6}, + {"R_MIPS_TLS_GD", Const, 6}, + {"R_MIPS_TLS_GOTTPREL", Const, 6}, + {"R_MIPS_TLS_LDM", Const, 6}, + {"R_MIPS_TLS_TPREL32", Const, 6}, + {"R_MIPS_TLS_TPREL64", Const, 6}, + {"R_MIPS_TLS_TPREL_HI16", Const, 6}, + {"R_MIPS_TLS_TPREL_LO16", Const, 6}, + {"R_PPC", Type, 0}, + {"R_PPC64", Type, 5}, + {"R_PPC64_ADDR14", Const, 5}, + {"R_PPC64_ADDR14_BRNTAKEN", Const, 5}, + {"R_PPC64_ADDR14_BRTAKEN", Const, 5}, + {"R_PPC64_ADDR16", Const, 5}, + {"R_PPC64_ADDR16_DS", Const, 5}, + {"R_PPC64_ADDR16_HA", Const, 5}, + {"R_PPC64_ADDR16_HI", Const, 5}, + {"R_PPC64_ADDR16_HIGH", Const, 10}, + {"R_PPC64_ADDR16_HIGHA", Const, 10}, + {"R_PPC64_ADDR16_HIGHER", Const, 5}, + {"R_PPC64_ADDR16_HIGHER34", Const, 20}, + {"R_PPC64_ADDR16_HIGHERA", Const, 5}, + {"R_PPC64_ADDR16_HIGHERA34", Const, 20}, + {"R_PPC64_ADDR16_HIGHEST", Const, 5}, + {"R_PPC64_ADDR16_HIGHEST34", Const, 20}, + {"R_PPC64_ADDR16_HIGHESTA", Const, 5}, + {"R_PPC64_ADDR16_HIGHESTA34", Const, 20}, + {"R_PPC64_ADDR16_LO", Const, 5}, + {"R_PPC64_ADDR16_LO_DS", Const, 5}, + {"R_PPC64_ADDR24", Const, 5}, + {"R_PPC64_ADDR32", Const, 5}, + {"R_PPC64_ADDR64", Const, 5}, + {"R_PPC64_ADDR64_LOCAL", Const, 10}, + {"R_PPC64_COPY", Const, 20}, + {"R_PPC64_D28", Const, 20}, + {"R_PPC64_D34", Const, 20}, + {"R_PPC64_D34_HA30", Const, 20}, + {"R_PPC64_D34_HI30", Const, 20}, + {"R_PPC64_D34_LO", Const, 20}, + {"R_PPC64_DTPMOD64", Const, 5}, + {"R_PPC64_DTPREL16", Const, 5}, + {"R_PPC64_DTPREL16_DS", Const, 5}, + {"R_PPC64_DTPREL16_HA", Const, 5}, + {"R_PPC64_DTPREL16_HI", Const, 5}, + {"R_PPC64_DTPREL16_HIGH", Const, 10}, + {"R_PPC64_DTPREL16_HIGHA", Const, 10}, + {"R_PPC64_DTPREL16_HIGHER", Const, 5}, + {"R_PPC64_DTPREL16_HIGHERA", Const, 5}, + {"R_PPC64_DTPREL16_HIGHEST", Const, 5}, + {"R_PPC64_DTPREL16_HIGHESTA", Const, 5}, + {"R_PPC64_DTPREL16_LO", Const, 5}, + {"R_PPC64_DTPREL16_LO_DS", Const, 5}, + {"R_PPC64_DTPREL34", Const, 20}, + {"R_PPC64_DTPREL64", Const, 5}, + {"R_PPC64_ENTRY", Const, 10}, + {"R_PPC64_GLOB_DAT", Const, 20}, + {"R_PPC64_GNU_VTENTRY", Const, 20}, + {"R_PPC64_GNU_VTINHERIT", Const, 20}, + {"R_PPC64_GOT16", Const, 5}, + {"R_PPC64_GOT16_DS", Const, 5}, + {"R_PPC64_GOT16_HA", Const, 5}, + {"R_PPC64_GOT16_HI", Const, 5}, + {"R_PPC64_GOT16_LO", Const, 5}, + {"R_PPC64_GOT16_LO_DS", Const, 5}, + {"R_PPC64_GOT_DTPREL16_DS", Const, 5}, + {"R_PPC64_GOT_DTPREL16_HA", Const, 5}, + {"R_PPC64_GOT_DTPREL16_HI", Const, 5}, + {"R_PPC64_GOT_DTPREL16_LO_DS", Const, 5}, + {"R_PPC64_GOT_DTPREL_PCREL34", Const, 20}, + {"R_PPC64_GOT_PCREL34", Const, 20}, + {"R_PPC64_GOT_TLSGD16", Const, 5}, + {"R_PPC64_GOT_TLSGD16_HA", Const, 5}, + {"R_PPC64_GOT_TLSGD16_HI", Const, 5}, + {"R_PPC64_GOT_TLSGD16_LO", Const, 5}, + {"R_PPC64_GOT_TLSGD_PCREL34", Const, 20}, + {"R_PPC64_GOT_TLSLD16", Const, 5}, + {"R_PPC64_GOT_TLSLD16_HA", Const, 5}, + {"R_PPC64_GOT_TLSLD16_HI", Const, 5}, + {"R_PPC64_GOT_TLSLD16_LO", Const, 5}, + {"R_PPC64_GOT_TLSLD_PCREL34", Const, 20}, + {"R_PPC64_GOT_TPREL16_DS", Const, 5}, + {"R_PPC64_GOT_TPREL16_HA", Const, 5}, + {"R_PPC64_GOT_TPREL16_HI", Const, 5}, + {"R_PPC64_GOT_TPREL16_LO_DS", Const, 5}, + {"R_PPC64_GOT_TPREL_PCREL34", Const, 20}, + {"R_PPC64_IRELATIVE", Const, 10}, + {"R_PPC64_JMP_IREL", Const, 10}, + {"R_PPC64_JMP_SLOT", Const, 5}, + {"R_PPC64_NONE", Const, 5}, + {"R_PPC64_PCREL28", Const, 20}, + {"R_PPC64_PCREL34", Const, 20}, + {"R_PPC64_PCREL_OPT", Const, 20}, + {"R_PPC64_PLT16_HA", Const, 20}, + {"R_PPC64_PLT16_HI", Const, 20}, + {"R_PPC64_PLT16_LO", Const, 20}, + {"R_PPC64_PLT16_LO_DS", Const, 10}, + {"R_PPC64_PLT32", Const, 20}, + {"R_PPC64_PLT64", Const, 20}, + {"R_PPC64_PLTCALL", Const, 20}, + {"R_PPC64_PLTCALL_NOTOC", Const, 20}, + {"R_PPC64_PLTGOT16", Const, 10}, + {"R_PPC64_PLTGOT16_DS", Const, 10}, + {"R_PPC64_PLTGOT16_HA", Const, 10}, + {"R_PPC64_PLTGOT16_HI", Const, 10}, + {"R_PPC64_PLTGOT16_LO", Const, 10}, + {"R_PPC64_PLTGOT_LO_DS", Const, 10}, + {"R_PPC64_PLTREL32", Const, 20}, + {"R_PPC64_PLTREL64", Const, 20}, + {"R_PPC64_PLTSEQ", Const, 20}, + {"R_PPC64_PLTSEQ_NOTOC", Const, 20}, + {"R_PPC64_PLT_PCREL34", Const, 20}, + {"R_PPC64_PLT_PCREL34_NOTOC", Const, 20}, + {"R_PPC64_REL14", Const, 5}, + {"R_PPC64_REL14_BRNTAKEN", Const, 5}, + {"R_PPC64_REL14_BRTAKEN", Const, 5}, + {"R_PPC64_REL16", Const, 5}, + {"R_PPC64_REL16DX_HA", Const, 10}, + {"R_PPC64_REL16_HA", Const, 5}, + {"R_PPC64_REL16_HI", Const, 5}, + {"R_PPC64_REL16_HIGH", Const, 20}, + {"R_PPC64_REL16_HIGHA", Const, 20}, + {"R_PPC64_REL16_HIGHER", Const, 20}, + {"R_PPC64_REL16_HIGHER34", Const, 20}, + {"R_PPC64_REL16_HIGHERA", Const, 20}, + {"R_PPC64_REL16_HIGHERA34", Const, 20}, + {"R_PPC64_REL16_HIGHEST", Const, 20}, + {"R_PPC64_REL16_HIGHEST34", Const, 20}, + {"R_PPC64_REL16_HIGHESTA", Const, 20}, + {"R_PPC64_REL16_HIGHESTA34", Const, 20}, + {"R_PPC64_REL16_LO", Const, 5}, + {"R_PPC64_REL24", Const, 5}, + {"R_PPC64_REL24_NOTOC", Const, 10}, + {"R_PPC64_REL24_P9NOTOC", Const, 21}, + {"R_PPC64_REL30", Const, 20}, + {"R_PPC64_REL32", Const, 5}, + {"R_PPC64_REL64", Const, 5}, + {"R_PPC64_RELATIVE", Const, 18}, + {"R_PPC64_SECTOFF", Const, 20}, + {"R_PPC64_SECTOFF_DS", Const, 10}, + {"R_PPC64_SECTOFF_HA", Const, 20}, + {"R_PPC64_SECTOFF_HI", Const, 20}, + {"R_PPC64_SECTOFF_LO", Const, 20}, + {"R_PPC64_SECTOFF_LO_DS", Const, 10}, + {"R_PPC64_TLS", Const, 5}, + {"R_PPC64_TLSGD", Const, 5}, + {"R_PPC64_TLSLD", Const, 5}, + {"R_PPC64_TOC", Const, 5}, + {"R_PPC64_TOC16", Const, 5}, + {"R_PPC64_TOC16_DS", Const, 5}, + {"R_PPC64_TOC16_HA", Const, 5}, + {"R_PPC64_TOC16_HI", Const, 5}, + {"R_PPC64_TOC16_LO", Const, 5}, + {"R_PPC64_TOC16_LO_DS", Const, 5}, + {"R_PPC64_TOCSAVE", Const, 10}, + {"R_PPC64_TPREL16", Const, 5}, + {"R_PPC64_TPREL16_DS", Const, 5}, + {"R_PPC64_TPREL16_HA", Const, 5}, + {"R_PPC64_TPREL16_HI", Const, 5}, + {"R_PPC64_TPREL16_HIGH", Const, 10}, + {"R_PPC64_TPREL16_HIGHA", Const, 10}, + {"R_PPC64_TPREL16_HIGHER", Const, 5}, + {"R_PPC64_TPREL16_HIGHERA", Const, 5}, + {"R_PPC64_TPREL16_HIGHEST", Const, 5}, + {"R_PPC64_TPREL16_HIGHESTA", Const, 5}, + {"R_PPC64_TPREL16_LO", Const, 5}, + {"R_PPC64_TPREL16_LO_DS", Const, 5}, + {"R_PPC64_TPREL34", Const, 20}, + {"R_PPC64_TPREL64", Const, 5}, + {"R_PPC64_UADDR16", Const, 20}, + {"R_PPC64_UADDR32", Const, 20}, + {"R_PPC64_UADDR64", Const, 20}, + {"R_PPC_ADDR14", Const, 0}, + {"R_PPC_ADDR14_BRNTAKEN", Const, 0}, + {"R_PPC_ADDR14_BRTAKEN", Const, 0}, + {"R_PPC_ADDR16", Const, 0}, + {"R_PPC_ADDR16_HA", Const, 0}, + {"R_PPC_ADDR16_HI", Const, 0}, + {"R_PPC_ADDR16_LO", Const, 0}, + {"R_PPC_ADDR24", Const, 0}, + {"R_PPC_ADDR32", Const, 0}, + {"R_PPC_COPY", Const, 0}, + {"R_PPC_DTPMOD32", Const, 0}, + {"R_PPC_DTPREL16", Const, 0}, + {"R_PPC_DTPREL16_HA", Const, 0}, + {"R_PPC_DTPREL16_HI", Const, 0}, + {"R_PPC_DTPREL16_LO", Const, 0}, + {"R_PPC_DTPREL32", Const, 0}, + {"R_PPC_EMB_BIT_FLD", Const, 0}, + {"R_PPC_EMB_MRKREF", Const, 0}, + {"R_PPC_EMB_NADDR16", Const, 0}, + {"R_PPC_EMB_NADDR16_HA", Const, 0}, + {"R_PPC_EMB_NADDR16_HI", Const, 0}, + {"R_PPC_EMB_NADDR16_LO", Const, 0}, + {"R_PPC_EMB_NADDR32", Const, 0}, + {"R_PPC_EMB_RELSDA", Const, 0}, + {"R_PPC_EMB_RELSEC16", Const, 0}, + {"R_PPC_EMB_RELST_HA", Const, 0}, + {"R_PPC_EMB_RELST_HI", Const, 0}, + {"R_PPC_EMB_RELST_LO", Const, 0}, + {"R_PPC_EMB_SDA21", Const, 0}, + {"R_PPC_EMB_SDA2I16", Const, 0}, + {"R_PPC_EMB_SDA2REL", Const, 0}, + {"R_PPC_EMB_SDAI16", Const, 0}, + {"R_PPC_GLOB_DAT", Const, 0}, + {"R_PPC_GOT16", Const, 0}, + {"R_PPC_GOT16_HA", Const, 0}, + {"R_PPC_GOT16_HI", Const, 0}, + {"R_PPC_GOT16_LO", Const, 0}, + {"R_PPC_GOT_TLSGD16", Const, 0}, + {"R_PPC_GOT_TLSGD16_HA", Const, 0}, + {"R_PPC_GOT_TLSGD16_HI", Const, 0}, + {"R_PPC_GOT_TLSGD16_LO", Const, 0}, + {"R_PPC_GOT_TLSLD16", Const, 0}, + {"R_PPC_GOT_TLSLD16_HA", Const, 0}, + {"R_PPC_GOT_TLSLD16_HI", Const, 0}, + {"R_PPC_GOT_TLSLD16_LO", Const, 0}, + {"R_PPC_GOT_TPREL16", Const, 0}, + {"R_PPC_GOT_TPREL16_HA", Const, 0}, + {"R_PPC_GOT_TPREL16_HI", Const, 0}, + {"R_PPC_GOT_TPREL16_LO", Const, 0}, + {"R_PPC_JMP_SLOT", Const, 0}, + {"R_PPC_LOCAL24PC", Const, 0}, + {"R_PPC_NONE", Const, 0}, + {"R_PPC_PLT16_HA", Const, 0}, + {"R_PPC_PLT16_HI", Const, 0}, + {"R_PPC_PLT16_LO", Const, 0}, + {"R_PPC_PLT32", Const, 0}, + {"R_PPC_PLTREL24", Const, 0}, + {"R_PPC_PLTREL32", Const, 0}, + {"R_PPC_REL14", Const, 0}, + {"R_PPC_REL14_BRNTAKEN", Const, 0}, + {"R_PPC_REL14_BRTAKEN", Const, 0}, + {"R_PPC_REL24", Const, 0}, + {"R_PPC_REL32", Const, 0}, + {"R_PPC_RELATIVE", Const, 0}, + {"R_PPC_SDAREL16", Const, 0}, + {"R_PPC_SECTOFF", Const, 0}, + {"R_PPC_SECTOFF_HA", Const, 0}, + {"R_PPC_SECTOFF_HI", Const, 0}, + {"R_PPC_SECTOFF_LO", Const, 0}, + {"R_PPC_TLS", Const, 0}, + {"R_PPC_TPREL16", Const, 0}, + {"R_PPC_TPREL16_HA", Const, 0}, + {"R_PPC_TPREL16_HI", Const, 0}, + {"R_PPC_TPREL16_LO", Const, 0}, + {"R_PPC_TPREL32", Const, 0}, + {"R_PPC_UADDR16", Const, 0}, + {"R_PPC_UADDR32", Const, 0}, + {"R_RISCV", Type, 11}, + {"R_RISCV_32", Const, 11}, + {"R_RISCV_32_PCREL", Const, 12}, + {"R_RISCV_64", Const, 11}, + {"R_RISCV_ADD16", Const, 11}, + {"R_RISCV_ADD32", Const, 11}, + {"R_RISCV_ADD64", Const, 11}, + {"R_RISCV_ADD8", Const, 11}, + {"R_RISCV_ALIGN", Const, 11}, + {"R_RISCV_BRANCH", Const, 11}, + {"R_RISCV_CALL", Const, 11}, + {"R_RISCV_CALL_PLT", Const, 11}, + {"R_RISCV_COPY", Const, 11}, + {"R_RISCV_GNU_VTENTRY", Const, 11}, + {"R_RISCV_GNU_VTINHERIT", Const, 11}, + {"R_RISCV_GOT_HI20", Const, 11}, + {"R_RISCV_GPREL_I", Const, 11}, + {"R_RISCV_GPREL_S", Const, 11}, + {"R_RISCV_HI20", Const, 11}, + {"R_RISCV_JAL", Const, 11}, + {"R_RISCV_JUMP_SLOT", Const, 11}, + {"R_RISCV_LO12_I", Const, 11}, + {"R_RISCV_LO12_S", Const, 11}, + {"R_RISCV_NONE", Const, 11}, + {"R_RISCV_PCREL_HI20", Const, 11}, + {"R_RISCV_PCREL_LO12_I", Const, 11}, + {"R_RISCV_PCREL_LO12_S", Const, 11}, + {"R_RISCV_RELATIVE", Const, 11}, + {"R_RISCV_RELAX", Const, 11}, + {"R_RISCV_RVC_BRANCH", Const, 11}, + {"R_RISCV_RVC_JUMP", Const, 11}, + {"R_RISCV_RVC_LUI", Const, 11}, + {"R_RISCV_SET16", Const, 11}, + {"R_RISCV_SET32", Const, 11}, + {"R_RISCV_SET6", Const, 11}, + {"R_RISCV_SET8", Const, 11}, + {"R_RISCV_SUB16", Const, 11}, + {"R_RISCV_SUB32", Const, 11}, + {"R_RISCV_SUB6", Const, 11}, + {"R_RISCV_SUB64", Const, 11}, + {"R_RISCV_SUB8", Const, 11}, + {"R_RISCV_TLS_DTPMOD32", Const, 11}, + {"R_RISCV_TLS_DTPMOD64", Const, 11}, + {"R_RISCV_TLS_DTPREL32", Const, 11}, + {"R_RISCV_TLS_DTPREL64", Const, 11}, + {"R_RISCV_TLS_GD_HI20", Const, 11}, + {"R_RISCV_TLS_GOT_HI20", Const, 11}, + {"R_RISCV_TLS_TPREL32", Const, 11}, + {"R_RISCV_TLS_TPREL64", Const, 11}, + {"R_RISCV_TPREL_ADD", Const, 11}, + {"R_RISCV_TPREL_HI20", Const, 11}, + {"R_RISCV_TPREL_I", Const, 11}, + {"R_RISCV_TPREL_LO12_I", Const, 11}, + {"R_RISCV_TPREL_LO12_S", Const, 11}, + {"R_RISCV_TPREL_S", Const, 11}, + {"R_SPARC", Type, 0}, + {"R_SPARC_10", Const, 0}, + {"R_SPARC_11", Const, 0}, + {"R_SPARC_13", Const, 0}, + {"R_SPARC_16", Const, 0}, + {"R_SPARC_22", Const, 0}, + {"R_SPARC_32", Const, 0}, + {"R_SPARC_5", Const, 0}, + {"R_SPARC_6", Const, 0}, + {"R_SPARC_64", Const, 0}, + {"R_SPARC_7", Const, 0}, + {"R_SPARC_8", Const, 0}, + {"R_SPARC_COPY", Const, 0}, + {"R_SPARC_DISP16", Const, 0}, + {"R_SPARC_DISP32", Const, 0}, + {"R_SPARC_DISP64", Const, 0}, + {"R_SPARC_DISP8", Const, 0}, + {"R_SPARC_GLOB_DAT", Const, 0}, + {"R_SPARC_GLOB_JMP", Const, 0}, + {"R_SPARC_GOT10", Const, 0}, + {"R_SPARC_GOT13", Const, 0}, + {"R_SPARC_GOT22", Const, 0}, + {"R_SPARC_H44", Const, 0}, + {"R_SPARC_HH22", Const, 0}, + {"R_SPARC_HI22", Const, 0}, + {"R_SPARC_HIPLT22", Const, 0}, + {"R_SPARC_HIX22", Const, 0}, + {"R_SPARC_HM10", Const, 0}, + {"R_SPARC_JMP_SLOT", Const, 0}, + {"R_SPARC_L44", Const, 0}, + {"R_SPARC_LM22", Const, 0}, + {"R_SPARC_LO10", Const, 0}, + {"R_SPARC_LOPLT10", Const, 0}, + {"R_SPARC_LOX10", Const, 0}, + {"R_SPARC_M44", Const, 0}, + {"R_SPARC_NONE", Const, 0}, + {"R_SPARC_OLO10", Const, 0}, + {"R_SPARC_PC10", Const, 0}, + {"R_SPARC_PC22", Const, 0}, + {"R_SPARC_PCPLT10", Const, 0}, + {"R_SPARC_PCPLT22", Const, 0}, + {"R_SPARC_PCPLT32", Const, 0}, + {"R_SPARC_PC_HH22", Const, 0}, + {"R_SPARC_PC_HM10", Const, 0}, + {"R_SPARC_PC_LM22", Const, 0}, + {"R_SPARC_PLT32", Const, 0}, + {"R_SPARC_PLT64", Const, 0}, + {"R_SPARC_REGISTER", Const, 0}, + {"R_SPARC_RELATIVE", Const, 0}, + {"R_SPARC_UA16", Const, 0}, + {"R_SPARC_UA32", Const, 0}, + {"R_SPARC_UA64", Const, 0}, + {"R_SPARC_WDISP16", Const, 0}, + {"R_SPARC_WDISP19", Const, 0}, + {"R_SPARC_WDISP22", Const, 0}, + {"R_SPARC_WDISP30", Const, 0}, + {"R_SPARC_WPLT30", Const, 0}, + {"R_SYM32", Func, 0}, + {"R_SYM64", Func, 0}, + {"R_TYPE32", Func, 0}, + {"R_TYPE64", Func, 0}, + {"R_X86_64", Type, 0}, + {"R_X86_64_16", Const, 0}, + {"R_X86_64_32", Const, 0}, + {"R_X86_64_32S", Const, 0}, + {"R_X86_64_64", Const, 0}, + {"R_X86_64_8", Const, 0}, + {"R_X86_64_COPY", Const, 0}, + {"R_X86_64_DTPMOD64", Const, 0}, + {"R_X86_64_DTPOFF32", Const, 0}, + {"R_X86_64_DTPOFF64", Const, 0}, + {"R_X86_64_GLOB_DAT", Const, 0}, + {"R_X86_64_GOT32", Const, 0}, + {"R_X86_64_GOT64", Const, 10}, + {"R_X86_64_GOTOFF64", Const, 10}, + {"R_X86_64_GOTPC32", Const, 10}, + {"R_X86_64_GOTPC32_TLSDESC", Const, 10}, + {"R_X86_64_GOTPC64", Const, 10}, + {"R_X86_64_GOTPCREL", Const, 0}, + {"R_X86_64_GOTPCREL64", Const, 10}, + {"R_X86_64_GOTPCRELX", Const, 10}, + {"R_X86_64_GOTPLT64", Const, 10}, + {"R_X86_64_GOTTPOFF", Const, 0}, + {"R_X86_64_IRELATIVE", Const, 10}, + {"R_X86_64_JMP_SLOT", Const, 0}, + {"R_X86_64_NONE", Const, 0}, + {"R_X86_64_PC16", Const, 0}, + {"R_X86_64_PC32", Const, 0}, + {"R_X86_64_PC32_BND", Const, 10}, + {"R_X86_64_PC64", Const, 10}, + {"R_X86_64_PC8", Const, 0}, + {"R_X86_64_PLT32", Const, 0}, + {"R_X86_64_PLT32_BND", Const, 10}, + {"R_X86_64_PLTOFF64", Const, 10}, + {"R_X86_64_RELATIVE", Const, 0}, + {"R_X86_64_RELATIVE64", Const, 10}, + {"R_X86_64_REX_GOTPCRELX", Const, 10}, + {"R_X86_64_SIZE32", Const, 10}, + {"R_X86_64_SIZE64", Const, 10}, + {"R_X86_64_TLSDESC", Const, 10}, + {"R_X86_64_TLSDESC_CALL", Const, 10}, + {"R_X86_64_TLSGD", Const, 0}, + {"R_X86_64_TLSLD", Const, 0}, + {"R_X86_64_TPOFF32", Const, 0}, + {"R_X86_64_TPOFF64", Const, 0}, + {"Rel32", Type, 0}, + {"Rel32.Info", Field, 0}, + {"Rel32.Off", Field, 0}, + {"Rel64", Type, 0}, + {"Rel64.Info", Field, 0}, + {"Rel64.Off", Field, 0}, + {"Rela32", Type, 0}, + {"Rela32.Addend", Field, 0}, + {"Rela32.Info", Field, 0}, + {"Rela32.Off", Field, 0}, + {"Rela64", Type, 0}, + {"Rela64.Addend", Field, 0}, + {"Rela64.Info", Field, 0}, + {"Rela64.Off", Field, 0}, + {"SHF_ALLOC", Const, 0}, + {"SHF_COMPRESSED", Const, 6}, + {"SHF_EXECINSTR", Const, 0}, + {"SHF_GROUP", Const, 0}, + {"SHF_INFO_LINK", Const, 0}, + {"SHF_LINK_ORDER", Const, 0}, + {"SHF_MASKOS", Const, 0}, + {"SHF_MASKPROC", Const, 0}, + {"SHF_MERGE", Const, 0}, + {"SHF_OS_NONCONFORMING", Const, 0}, + {"SHF_STRINGS", Const, 0}, + {"SHF_TLS", Const, 0}, + {"SHF_WRITE", Const, 0}, + {"SHN_ABS", Const, 0}, + {"SHN_COMMON", Const, 0}, + {"SHN_HIOS", Const, 0}, + {"SHN_HIPROC", Const, 0}, + {"SHN_HIRESERVE", Const, 0}, + {"SHN_LOOS", Const, 0}, + {"SHN_LOPROC", Const, 0}, + {"SHN_LORESERVE", Const, 0}, + {"SHN_UNDEF", Const, 0}, + {"SHN_XINDEX", Const, 0}, + {"SHT_DYNAMIC", Const, 0}, + {"SHT_DYNSYM", Const, 0}, + {"SHT_FINI_ARRAY", Const, 0}, + {"SHT_GNU_ATTRIBUTES", Const, 0}, + {"SHT_GNU_HASH", Const, 0}, + {"SHT_GNU_LIBLIST", Const, 0}, + {"SHT_GNU_VERDEF", Const, 0}, + {"SHT_GNU_VERNEED", Const, 0}, + {"SHT_GNU_VERSYM", Const, 0}, + {"SHT_GROUP", Const, 0}, + {"SHT_HASH", Const, 0}, + {"SHT_HIOS", Const, 0}, + {"SHT_HIPROC", Const, 0}, + {"SHT_HIUSER", Const, 0}, + {"SHT_INIT_ARRAY", Const, 0}, + {"SHT_LOOS", Const, 0}, + {"SHT_LOPROC", Const, 0}, + {"SHT_LOUSER", Const, 0}, + {"SHT_MIPS_ABIFLAGS", Const, 17}, + {"SHT_NOBITS", Const, 0}, + {"SHT_NOTE", Const, 0}, + {"SHT_NULL", Const, 0}, + {"SHT_PREINIT_ARRAY", Const, 0}, + {"SHT_PROGBITS", Const, 0}, + {"SHT_REL", Const, 0}, + {"SHT_RELA", Const, 0}, + {"SHT_SHLIB", Const, 0}, + {"SHT_STRTAB", Const, 0}, + {"SHT_SYMTAB", Const, 0}, + {"SHT_SYMTAB_SHNDX", Const, 0}, + {"STB_GLOBAL", Const, 0}, + {"STB_HIOS", Const, 0}, + {"STB_HIPROC", Const, 0}, + {"STB_LOCAL", Const, 0}, + {"STB_LOOS", Const, 0}, + {"STB_LOPROC", Const, 0}, + {"STB_WEAK", Const, 0}, + {"STT_COMMON", Const, 0}, + {"STT_FILE", Const, 0}, + {"STT_FUNC", Const, 0}, + {"STT_GNU_IFUNC", Const, 23}, + {"STT_HIOS", Const, 0}, + {"STT_HIPROC", Const, 0}, + {"STT_LOOS", Const, 0}, + {"STT_LOPROC", Const, 0}, + {"STT_NOTYPE", Const, 0}, + {"STT_OBJECT", Const, 0}, + {"STT_RELC", Const, 23}, + {"STT_SECTION", Const, 0}, + {"STT_SRELC", Const, 23}, + {"STT_TLS", Const, 0}, + {"STV_DEFAULT", Const, 0}, + {"STV_HIDDEN", Const, 0}, + {"STV_INTERNAL", Const, 0}, + {"STV_PROTECTED", Const, 0}, + {"ST_BIND", Func, 0}, + {"ST_INFO", Func, 0}, + {"ST_TYPE", Func, 0}, + {"ST_VISIBILITY", Func, 0}, + {"Section", Type, 0}, + {"Section.ReaderAt", Field, 0}, + {"Section.SectionHeader", Field, 0}, + {"Section32", Type, 0}, + {"Section32.Addr", Field, 0}, + {"Section32.Addralign", Field, 0}, + {"Section32.Entsize", Field, 0}, + {"Section32.Flags", Field, 0}, + {"Section32.Info", Field, 0}, + {"Section32.Link", Field, 0}, + {"Section32.Name", Field, 0}, + {"Section32.Off", Field, 0}, + {"Section32.Size", Field, 0}, + {"Section32.Type", Field, 0}, + {"Section64", Type, 0}, + {"Section64.Addr", Field, 0}, + {"Section64.Addralign", Field, 0}, + {"Section64.Entsize", Field, 0}, + {"Section64.Flags", Field, 0}, + {"Section64.Info", Field, 0}, + {"Section64.Link", Field, 0}, + {"Section64.Name", Field, 0}, + {"Section64.Off", Field, 0}, + {"Section64.Size", Field, 0}, + {"Section64.Type", Field, 0}, + {"SectionFlag", Type, 0}, + {"SectionHeader", Type, 0}, + {"SectionHeader.Addr", Field, 0}, + {"SectionHeader.Addralign", Field, 0}, + {"SectionHeader.Entsize", Field, 0}, + {"SectionHeader.FileSize", Field, 6}, + {"SectionHeader.Flags", Field, 0}, + {"SectionHeader.Info", Field, 0}, + {"SectionHeader.Link", Field, 0}, + {"SectionHeader.Name", Field, 0}, + {"SectionHeader.Offset", Field, 0}, + {"SectionHeader.Size", Field, 0}, + {"SectionHeader.Type", Field, 0}, + {"SectionIndex", Type, 0}, + {"SectionType", Type, 0}, + {"Sym32", Type, 0}, + {"Sym32.Info", Field, 0}, + {"Sym32.Name", Field, 0}, + {"Sym32.Other", Field, 0}, + {"Sym32.Shndx", Field, 0}, + {"Sym32.Size", Field, 0}, + {"Sym32.Value", Field, 0}, + {"Sym32Size", Const, 0}, + {"Sym64", Type, 0}, + {"Sym64.Info", Field, 0}, + {"Sym64.Name", Field, 0}, + {"Sym64.Other", Field, 0}, + {"Sym64.Shndx", Field, 0}, + {"Sym64.Size", Field, 0}, + {"Sym64.Value", Field, 0}, + {"Sym64Size", Const, 0}, + {"SymBind", Type, 0}, + {"SymType", Type, 0}, + {"SymVis", Type, 0}, + {"Symbol", Type, 0}, + {"Symbol.Info", Field, 0}, + {"Symbol.Library", Field, 13}, + {"Symbol.Name", Field, 0}, + {"Symbol.Other", Field, 0}, + {"Symbol.Section", Field, 0}, + {"Symbol.Size", Field, 0}, + {"Symbol.Value", Field, 0}, + {"Symbol.Version", Field, 13}, + {"Type", Type, 0}, + {"Version", Type, 0}, + }, + "debug/gosym": { + {"(*DecodingError).Error", Method, 0}, + {"(*LineTable).LineToPC", Method, 0}, + {"(*LineTable).PCToLine", Method, 0}, + {"(*Sym).BaseName", Method, 0}, + {"(*Sym).PackageName", Method, 0}, + {"(*Sym).ReceiverName", Method, 0}, + {"(*Sym).Static", Method, 0}, + {"(*Table).LineToPC", Method, 0}, + {"(*Table).LookupFunc", Method, 0}, + {"(*Table).LookupSym", Method, 0}, + {"(*Table).PCToFunc", Method, 0}, + {"(*Table).PCToLine", Method, 0}, + {"(*Table).SymByAddr", Method, 0}, + {"(*UnknownLineError).Error", Method, 0}, + {"(Func).BaseName", Method, 0}, + {"(Func).PackageName", Method, 0}, + {"(Func).ReceiverName", Method, 0}, + {"(Func).Static", Method, 0}, + {"(UnknownFileError).Error", Method, 0}, + {"DecodingError", Type, 0}, + {"Func", Type, 0}, + {"Func.End", Field, 0}, + {"Func.Entry", Field, 0}, + {"Func.FrameSize", Field, 0}, + {"Func.LineTable", Field, 0}, + {"Func.Locals", Field, 0}, + {"Func.Obj", Field, 0}, + {"Func.Params", Field, 0}, + {"Func.Sym", Field, 0}, + {"LineTable", Type, 0}, + {"LineTable.Data", Field, 0}, + {"LineTable.Line", Field, 0}, + {"LineTable.PC", Field, 0}, + {"NewLineTable", Func, 0}, + {"NewTable", Func, 0}, + {"Obj", Type, 0}, + {"Obj.Funcs", Field, 0}, + {"Obj.Paths", Field, 0}, + {"Sym", Type, 0}, + {"Sym.Func", Field, 0}, + {"Sym.GoType", Field, 0}, + {"Sym.Name", Field, 0}, + {"Sym.Type", Field, 0}, + {"Sym.Value", Field, 0}, + {"Table", Type, 0}, + {"Table.Files", Field, 0}, + {"Table.Funcs", Field, 0}, + {"Table.Objs", Field, 0}, + {"Table.Syms", Field, 0}, + {"UnknownFileError", Type, 0}, + {"UnknownLineError", Type, 0}, + {"UnknownLineError.File", Field, 0}, + {"UnknownLineError.Line", Field, 0}, + }, + "debug/macho": { + {"(*FatFile).Close", Method, 3}, + {"(*File).Close", Method, 0}, + {"(*File).DWARF", Method, 0}, + {"(*File).ImportedLibraries", Method, 0}, + {"(*File).ImportedSymbols", Method, 0}, + {"(*File).Section", Method, 0}, + {"(*File).Segment", Method, 0}, + {"(*FormatError).Error", Method, 0}, + {"(*Section).Data", Method, 0}, + {"(*Section).Open", Method, 0}, + {"(*Segment).Data", Method, 0}, + {"(*Segment).Open", Method, 0}, + {"(Cpu).GoString", Method, 0}, + {"(Cpu).String", Method, 0}, + {"(Dylib).Raw", Method, 0}, + {"(Dysymtab).Raw", Method, 0}, + {"(FatArch).Close", Method, 3}, + {"(FatArch).DWARF", Method, 3}, + {"(FatArch).ImportedLibraries", Method, 3}, + {"(FatArch).ImportedSymbols", Method, 3}, + {"(FatArch).Section", Method, 3}, + {"(FatArch).Segment", Method, 3}, + {"(LoadBytes).Raw", Method, 0}, + {"(LoadCmd).GoString", Method, 0}, + {"(LoadCmd).String", Method, 0}, + {"(RelocTypeARM).GoString", Method, 10}, + {"(RelocTypeARM).String", Method, 10}, + {"(RelocTypeARM64).GoString", Method, 10}, + {"(RelocTypeARM64).String", Method, 10}, + {"(RelocTypeGeneric).GoString", Method, 10}, + {"(RelocTypeGeneric).String", Method, 10}, + {"(RelocTypeX86_64).GoString", Method, 10}, + {"(RelocTypeX86_64).String", Method, 10}, + {"(Rpath).Raw", Method, 10}, + {"(Section).ReadAt", Method, 0}, + {"(Segment).Raw", Method, 0}, + {"(Segment).ReadAt", Method, 0}, + {"(Symtab).Raw", Method, 0}, + {"(Type).GoString", Method, 10}, + {"(Type).String", Method, 10}, + {"ARM64_RELOC_ADDEND", Const, 10}, + {"ARM64_RELOC_BRANCH26", Const, 10}, + {"ARM64_RELOC_GOT_LOAD_PAGE21", Const, 10}, + {"ARM64_RELOC_GOT_LOAD_PAGEOFF12", Const, 10}, + {"ARM64_RELOC_PAGE21", Const, 10}, + {"ARM64_RELOC_PAGEOFF12", Const, 10}, + {"ARM64_RELOC_POINTER_TO_GOT", Const, 10}, + {"ARM64_RELOC_SUBTRACTOR", Const, 10}, + {"ARM64_RELOC_TLVP_LOAD_PAGE21", Const, 10}, + {"ARM64_RELOC_TLVP_LOAD_PAGEOFF12", Const, 10}, + {"ARM64_RELOC_UNSIGNED", Const, 10}, + {"ARM_RELOC_BR24", Const, 10}, + {"ARM_RELOC_HALF", Const, 10}, + {"ARM_RELOC_HALF_SECTDIFF", Const, 10}, + {"ARM_RELOC_LOCAL_SECTDIFF", Const, 10}, + {"ARM_RELOC_PAIR", Const, 10}, + {"ARM_RELOC_PB_LA_PTR", Const, 10}, + {"ARM_RELOC_SECTDIFF", Const, 10}, + {"ARM_RELOC_VANILLA", Const, 10}, + {"ARM_THUMB_32BIT_BRANCH", Const, 10}, + {"ARM_THUMB_RELOC_BR22", Const, 10}, + {"Cpu", Type, 0}, + {"Cpu386", Const, 0}, + {"CpuAmd64", Const, 0}, + {"CpuArm", Const, 3}, + {"CpuArm64", Const, 11}, + {"CpuPpc", Const, 3}, + {"CpuPpc64", Const, 3}, + {"Dylib", Type, 0}, + {"Dylib.CompatVersion", Field, 0}, + {"Dylib.CurrentVersion", Field, 0}, + {"Dylib.LoadBytes", Field, 0}, + {"Dylib.Name", Field, 0}, + {"Dylib.Time", Field, 0}, + {"DylibCmd", Type, 0}, + {"DylibCmd.Cmd", Field, 0}, + {"DylibCmd.CompatVersion", Field, 0}, + {"DylibCmd.CurrentVersion", Field, 0}, + {"DylibCmd.Len", Field, 0}, + {"DylibCmd.Name", Field, 0}, + {"DylibCmd.Time", Field, 0}, + {"Dysymtab", Type, 0}, + {"Dysymtab.DysymtabCmd", Field, 0}, + {"Dysymtab.IndirectSyms", Field, 0}, + {"Dysymtab.LoadBytes", Field, 0}, + {"DysymtabCmd", Type, 0}, + {"DysymtabCmd.Cmd", Field, 0}, + {"DysymtabCmd.Extrefsymoff", Field, 0}, + {"DysymtabCmd.Extreloff", Field, 0}, + {"DysymtabCmd.Iextdefsym", Field, 0}, + {"DysymtabCmd.Ilocalsym", Field, 0}, + {"DysymtabCmd.Indirectsymoff", Field, 0}, + {"DysymtabCmd.Iundefsym", Field, 0}, + {"DysymtabCmd.Len", Field, 0}, + {"DysymtabCmd.Locreloff", Field, 0}, + {"DysymtabCmd.Modtaboff", Field, 0}, + {"DysymtabCmd.Nextdefsym", Field, 0}, + {"DysymtabCmd.Nextrefsyms", Field, 0}, + {"DysymtabCmd.Nextrel", Field, 0}, + {"DysymtabCmd.Nindirectsyms", Field, 0}, + {"DysymtabCmd.Nlocalsym", Field, 0}, + {"DysymtabCmd.Nlocrel", Field, 0}, + {"DysymtabCmd.Nmodtab", Field, 0}, + {"DysymtabCmd.Ntoc", Field, 0}, + {"DysymtabCmd.Nundefsym", Field, 0}, + {"DysymtabCmd.Tocoffset", Field, 0}, + {"ErrNotFat", Var, 3}, + {"FatArch", Type, 3}, + {"FatArch.FatArchHeader", Field, 3}, + {"FatArch.File", Field, 3}, + {"FatArchHeader", Type, 3}, + {"FatArchHeader.Align", Field, 3}, + {"FatArchHeader.Cpu", Field, 3}, + {"FatArchHeader.Offset", Field, 3}, + {"FatArchHeader.Size", Field, 3}, + {"FatArchHeader.SubCpu", Field, 3}, + {"FatFile", Type, 3}, + {"FatFile.Arches", Field, 3}, + {"FatFile.Magic", Field, 3}, + {"File", Type, 0}, + {"File.ByteOrder", Field, 0}, + {"File.Dysymtab", Field, 0}, + {"File.FileHeader", Field, 0}, + {"File.Loads", Field, 0}, + {"File.Sections", Field, 0}, + {"File.Symtab", Field, 0}, + {"FileHeader", Type, 0}, + {"FileHeader.Cmdsz", Field, 0}, + {"FileHeader.Cpu", Field, 0}, + {"FileHeader.Flags", Field, 0}, + {"FileHeader.Magic", Field, 0}, + {"FileHeader.Ncmd", Field, 0}, + {"FileHeader.SubCpu", Field, 0}, + {"FileHeader.Type", Field, 0}, + {"FlagAllModsBound", Const, 10}, + {"FlagAllowStackExecution", Const, 10}, + {"FlagAppExtensionSafe", Const, 10}, + {"FlagBindAtLoad", Const, 10}, + {"FlagBindsToWeak", Const, 10}, + {"FlagCanonical", Const, 10}, + {"FlagDeadStrippableDylib", Const, 10}, + {"FlagDyldLink", Const, 10}, + {"FlagForceFlat", Const, 10}, + {"FlagHasTLVDescriptors", Const, 10}, + {"FlagIncrLink", Const, 10}, + {"FlagLazyInit", Const, 10}, + {"FlagNoFixPrebinding", Const, 10}, + {"FlagNoHeapExecution", Const, 10}, + {"FlagNoMultiDefs", Const, 10}, + {"FlagNoReexportedDylibs", Const, 10}, + {"FlagNoUndefs", Const, 10}, + {"FlagPIE", Const, 10}, + {"FlagPrebindable", Const, 10}, + {"FlagPrebound", Const, 10}, + {"FlagRootSafe", Const, 10}, + {"FlagSetuidSafe", Const, 10}, + {"FlagSplitSegs", Const, 10}, + {"FlagSubsectionsViaSymbols", Const, 10}, + {"FlagTwoLevel", Const, 10}, + {"FlagWeakDefines", Const, 10}, + {"FormatError", Type, 0}, + {"GENERIC_RELOC_LOCAL_SECTDIFF", Const, 10}, + {"GENERIC_RELOC_PAIR", Const, 10}, + {"GENERIC_RELOC_PB_LA_PTR", Const, 10}, + {"GENERIC_RELOC_SECTDIFF", Const, 10}, + {"GENERIC_RELOC_TLV", Const, 10}, + {"GENERIC_RELOC_VANILLA", Const, 10}, + {"Load", Type, 0}, + {"LoadBytes", Type, 0}, + {"LoadCmd", Type, 0}, + {"LoadCmdDylib", Const, 0}, + {"LoadCmdDylinker", Const, 0}, + {"LoadCmdDysymtab", Const, 0}, + {"LoadCmdRpath", Const, 10}, + {"LoadCmdSegment", Const, 0}, + {"LoadCmdSegment64", Const, 0}, + {"LoadCmdSymtab", Const, 0}, + {"LoadCmdThread", Const, 0}, + {"LoadCmdUnixThread", Const, 0}, + {"Magic32", Const, 0}, + {"Magic64", Const, 0}, + {"MagicFat", Const, 3}, + {"NewFatFile", Func, 3}, + {"NewFile", Func, 0}, + {"Nlist32", Type, 0}, + {"Nlist32.Desc", Field, 0}, + {"Nlist32.Name", Field, 0}, + {"Nlist32.Sect", Field, 0}, + {"Nlist32.Type", Field, 0}, + {"Nlist32.Value", Field, 0}, + {"Nlist64", Type, 0}, + {"Nlist64.Desc", Field, 0}, + {"Nlist64.Name", Field, 0}, + {"Nlist64.Sect", Field, 0}, + {"Nlist64.Type", Field, 0}, + {"Nlist64.Value", Field, 0}, + {"Open", Func, 0}, + {"OpenFat", Func, 3}, + {"Regs386", Type, 0}, + {"Regs386.AX", Field, 0}, + {"Regs386.BP", Field, 0}, + {"Regs386.BX", Field, 0}, + {"Regs386.CS", Field, 0}, + {"Regs386.CX", Field, 0}, + {"Regs386.DI", Field, 0}, + {"Regs386.DS", Field, 0}, + {"Regs386.DX", Field, 0}, + {"Regs386.ES", Field, 0}, + {"Regs386.FLAGS", Field, 0}, + {"Regs386.FS", Field, 0}, + {"Regs386.GS", Field, 0}, + {"Regs386.IP", Field, 0}, + {"Regs386.SI", Field, 0}, + {"Regs386.SP", Field, 0}, + {"Regs386.SS", Field, 0}, + {"RegsAMD64", Type, 0}, + {"RegsAMD64.AX", Field, 0}, + {"RegsAMD64.BP", Field, 0}, + {"RegsAMD64.BX", Field, 0}, + {"RegsAMD64.CS", Field, 0}, + {"RegsAMD64.CX", Field, 0}, + {"RegsAMD64.DI", Field, 0}, + {"RegsAMD64.DX", Field, 0}, + {"RegsAMD64.FLAGS", Field, 0}, + {"RegsAMD64.FS", Field, 0}, + {"RegsAMD64.GS", Field, 0}, + {"RegsAMD64.IP", Field, 0}, + {"RegsAMD64.R10", Field, 0}, + {"RegsAMD64.R11", Field, 0}, + {"RegsAMD64.R12", Field, 0}, + {"RegsAMD64.R13", Field, 0}, + {"RegsAMD64.R14", Field, 0}, + {"RegsAMD64.R15", Field, 0}, + {"RegsAMD64.R8", Field, 0}, + {"RegsAMD64.R9", Field, 0}, + {"RegsAMD64.SI", Field, 0}, + {"RegsAMD64.SP", Field, 0}, + {"Reloc", Type, 10}, + {"Reloc.Addr", Field, 10}, + {"Reloc.Extern", Field, 10}, + {"Reloc.Len", Field, 10}, + {"Reloc.Pcrel", Field, 10}, + {"Reloc.Scattered", Field, 10}, + {"Reloc.Type", Field, 10}, + {"Reloc.Value", Field, 10}, + {"RelocTypeARM", Type, 10}, + {"RelocTypeARM64", Type, 10}, + {"RelocTypeGeneric", Type, 10}, + {"RelocTypeX86_64", Type, 10}, + {"Rpath", Type, 10}, + {"Rpath.LoadBytes", Field, 10}, + {"Rpath.Path", Field, 10}, + {"RpathCmd", Type, 10}, + {"RpathCmd.Cmd", Field, 10}, + {"RpathCmd.Len", Field, 10}, + {"RpathCmd.Path", Field, 10}, + {"Section", Type, 0}, + {"Section.ReaderAt", Field, 0}, + {"Section.Relocs", Field, 10}, + {"Section.SectionHeader", Field, 0}, + {"Section32", Type, 0}, + {"Section32.Addr", Field, 0}, + {"Section32.Align", Field, 0}, + {"Section32.Flags", Field, 0}, + {"Section32.Name", Field, 0}, + {"Section32.Nreloc", Field, 0}, + {"Section32.Offset", Field, 0}, + {"Section32.Reloff", Field, 0}, + {"Section32.Reserve1", Field, 0}, + {"Section32.Reserve2", Field, 0}, + {"Section32.Seg", Field, 0}, + {"Section32.Size", Field, 0}, + {"Section64", Type, 0}, + {"Section64.Addr", Field, 0}, + {"Section64.Align", Field, 0}, + {"Section64.Flags", Field, 0}, + {"Section64.Name", Field, 0}, + {"Section64.Nreloc", Field, 0}, + {"Section64.Offset", Field, 0}, + {"Section64.Reloff", Field, 0}, + {"Section64.Reserve1", Field, 0}, + {"Section64.Reserve2", Field, 0}, + {"Section64.Reserve3", Field, 0}, + {"Section64.Seg", Field, 0}, + {"Section64.Size", Field, 0}, + {"SectionHeader", Type, 0}, + {"SectionHeader.Addr", Field, 0}, + {"SectionHeader.Align", Field, 0}, + {"SectionHeader.Flags", Field, 0}, + {"SectionHeader.Name", Field, 0}, + {"SectionHeader.Nreloc", Field, 0}, + {"SectionHeader.Offset", Field, 0}, + {"SectionHeader.Reloff", Field, 0}, + {"SectionHeader.Seg", Field, 0}, + {"SectionHeader.Size", Field, 0}, + {"Segment", Type, 0}, + {"Segment.LoadBytes", Field, 0}, + {"Segment.ReaderAt", Field, 0}, + {"Segment.SegmentHeader", Field, 0}, + {"Segment32", Type, 0}, + {"Segment32.Addr", Field, 0}, + {"Segment32.Cmd", Field, 0}, + {"Segment32.Filesz", Field, 0}, + {"Segment32.Flag", Field, 0}, + {"Segment32.Len", Field, 0}, + {"Segment32.Maxprot", Field, 0}, + {"Segment32.Memsz", Field, 0}, + {"Segment32.Name", Field, 0}, + {"Segment32.Nsect", Field, 0}, + {"Segment32.Offset", Field, 0}, + {"Segment32.Prot", Field, 0}, + {"Segment64", Type, 0}, + {"Segment64.Addr", Field, 0}, + {"Segment64.Cmd", Field, 0}, + {"Segment64.Filesz", Field, 0}, + {"Segment64.Flag", Field, 0}, + {"Segment64.Len", Field, 0}, + {"Segment64.Maxprot", Field, 0}, + {"Segment64.Memsz", Field, 0}, + {"Segment64.Name", Field, 0}, + {"Segment64.Nsect", Field, 0}, + {"Segment64.Offset", Field, 0}, + {"Segment64.Prot", Field, 0}, + {"SegmentHeader", Type, 0}, + {"SegmentHeader.Addr", Field, 0}, + {"SegmentHeader.Cmd", Field, 0}, + {"SegmentHeader.Filesz", Field, 0}, + {"SegmentHeader.Flag", Field, 0}, + {"SegmentHeader.Len", Field, 0}, + {"SegmentHeader.Maxprot", Field, 0}, + {"SegmentHeader.Memsz", Field, 0}, + {"SegmentHeader.Name", Field, 0}, + {"SegmentHeader.Nsect", Field, 0}, + {"SegmentHeader.Offset", Field, 0}, + {"SegmentHeader.Prot", Field, 0}, + {"Symbol", Type, 0}, + {"Symbol.Desc", Field, 0}, + {"Symbol.Name", Field, 0}, + {"Symbol.Sect", Field, 0}, + {"Symbol.Type", Field, 0}, + {"Symbol.Value", Field, 0}, + {"Symtab", Type, 0}, + {"Symtab.LoadBytes", Field, 0}, + {"Symtab.Syms", Field, 0}, + {"Symtab.SymtabCmd", Field, 0}, + {"SymtabCmd", Type, 0}, + {"SymtabCmd.Cmd", Field, 0}, + {"SymtabCmd.Len", Field, 0}, + {"SymtabCmd.Nsyms", Field, 0}, + {"SymtabCmd.Stroff", Field, 0}, + {"SymtabCmd.Strsize", Field, 0}, + {"SymtabCmd.Symoff", Field, 0}, + {"Thread", Type, 0}, + {"Thread.Cmd", Field, 0}, + {"Thread.Data", Field, 0}, + {"Thread.Len", Field, 0}, + {"Thread.Type", Field, 0}, + {"Type", Type, 0}, + {"TypeBundle", Const, 3}, + {"TypeDylib", Const, 3}, + {"TypeExec", Const, 0}, + {"TypeObj", Const, 0}, + {"X86_64_RELOC_BRANCH", Const, 10}, + {"X86_64_RELOC_GOT", Const, 10}, + {"X86_64_RELOC_GOT_LOAD", Const, 10}, + {"X86_64_RELOC_SIGNED", Const, 10}, + {"X86_64_RELOC_SIGNED_1", Const, 10}, + {"X86_64_RELOC_SIGNED_2", Const, 10}, + {"X86_64_RELOC_SIGNED_4", Const, 10}, + {"X86_64_RELOC_SUBTRACTOR", Const, 10}, + {"X86_64_RELOC_TLV", Const, 10}, + {"X86_64_RELOC_UNSIGNED", Const, 10}, + }, + "debug/pe": { + {"(*COFFSymbol).FullName", Method, 8}, + {"(*File).COFFSymbolReadSectionDefAux", Method, 19}, + {"(*File).Close", Method, 0}, + {"(*File).DWARF", Method, 0}, + {"(*File).ImportedLibraries", Method, 0}, + {"(*File).ImportedSymbols", Method, 0}, + {"(*File).Section", Method, 0}, + {"(*FormatError).Error", Method, 0}, + {"(*Section).Data", Method, 0}, + {"(*Section).Open", Method, 0}, + {"(Section).ReadAt", Method, 0}, + {"(StringTable).String", Method, 8}, + {"COFFSymbol", Type, 1}, + {"COFFSymbol.Name", Field, 1}, + {"COFFSymbol.NumberOfAuxSymbols", Field, 1}, + {"COFFSymbol.SectionNumber", Field, 1}, + {"COFFSymbol.StorageClass", Field, 1}, + {"COFFSymbol.Type", Field, 1}, + {"COFFSymbol.Value", Field, 1}, + {"COFFSymbolAuxFormat5", Type, 19}, + {"COFFSymbolAuxFormat5.Checksum", Field, 19}, + {"COFFSymbolAuxFormat5.NumLineNumbers", Field, 19}, + {"COFFSymbolAuxFormat5.NumRelocs", Field, 19}, + {"COFFSymbolAuxFormat5.SecNum", Field, 19}, + {"COFFSymbolAuxFormat5.Selection", Field, 19}, + {"COFFSymbolAuxFormat5.Size", Field, 19}, + {"COFFSymbolSize", Const, 1}, + {"DataDirectory", Type, 3}, + {"DataDirectory.Size", Field, 3}, + {"DataDirectory.VirtualAddress", Field, 3}, + {"File", Type, 0}, + {"File.COFFSymbols", Field, 8}, + {"File.FileHeader", Field, 0}, + {"File.OptionalHeader", Field, 3}, + {"File.Sections", Field, 0}, + {"File.StringTable", Field, 8}, + {"File.Symbols", Field, 1}, + {"FileHeader", Type, 0}, + {"FileHeader.Characteristics", Field, 0}, + {"FileHeader.Machine", Field, 0}, + {"FileHeader.NumberOfSections", Field, 0}, + {"FileHeader.NumberOfSymbols", Field, 0}, + {"FileHeader.PointerToSymbolTable", Field, 0}, + {"FileHeader.SizeOfOptionalHeader", Field, 0}, + {"FileHeader.TimeDateStamp", Field, 0}, + {"FormatError", Type, 0}, + {"IMAGE_COMDAT_SELECT_ANY", Const, 19}, + {"IMAGE_COMDAT_SELECT_ASSOCIATIVE", Const, 19}, + {"IMAGE_COMDAT_SELECT_EXACT_MATCH", Const, 19}, + {"IMAGE_COMDAT_SELECT_LARGEST", Const, 19}, + {"IMAGE_COMDAT_SELECT_NODUPLICATES", Const, 19}, + {"IMAGE_COMDAT_SELECT_SAME_SIZE", Const, 19}, + {"IMAGE_DIRECTORY_ENTRY_ARCHITECTURE", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_BASERELOC", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_DEBUG", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_EXCEPTION", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_EXPORT", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_GLOBALPTR", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_IAT", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_IMPORT", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_RESOURCE", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_SECURITY", Const, 11}, + {"IMAGE_DIRECTORY_ENTRY_TLS", Const, 11}, + {"IMAGE_DLLCHARACTERISTICS_APPCONTAINER", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_GUARD_CF", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_NO_BIND", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_NO_ISOLATION", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_NO_SEH", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_NX_COMPAT", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE", Const, 15}, + {"IMAGE_DLLCHARACTERISTICS_WDM_DRIVER", Const, 15}, + {"IMAGE_FILE_32BIT_MACHINE", Const, 15}, + {"IMAGE_FILE_AGGRESIVE_WS_TRIM", Const, 15}, + {"IMAGE_FILE_BYTES_REVERSED_HI", Const, 15}, + {"IMAGE_FILE_BYTES_REVERSED_LO", Const, 15}, + {"IMAGE_FILE_DEBUG_STRIPPED", Const, 15}, + {"IMAGE_FILE_DLL", Const, 15}, + {"IMAGE_FILE_EXECUTABLE_IMAGE", Const, 15}, + {"IMAGE_FILE_LARGE_ADDRESS_AWARE", Const, 15}, + {"IMAGE_FILE_LINE_NUMS_STRIPPED", Const, 15}, + {"IMAGE_FILE_LOCAL_SYMS_STRIPPED", Const, 15}, + {"IMAGE_FILE_MACHINE_AM33", Const, 0}, + {"IMAGE_FILE_MACHINE_AMD64", Const, 0}, + {"IMAGE_FILE_MACHINE_ARM", Const, 0}, + {"IMAGE_FILE_MACHINE_ARM64", Const, 11}, + {"IMAGE_FILE_MACHINE_ARMNT", Const, 12}, + {"IMAGE_FILE_MACHINE_EBC", Const, 0}, + {"IMAGE_FILE_MACHINE_I386", Const, 0}, + {"IMAGE_FILE_MACHINE_IA64", Const, 0}, + {"IMAGE_FILE_MACHINE_LOONGARCH32", Const, 19}, + {"IMAGE_FILE_MACHINE_LOONGARCH64", Const, 19}, + {"IMAGE_FILE_MACHINE_M32R", Const, 0}, + {"IMAGE_FILE_MACHINE_MIPS16", Const, 0}, + {"IMAGE_FILE_MACHINE_MIPSFPU", Const, 0}, + {"IMAGE_FILE_MACHINE_MIPSFPU16", Const, 0}, + {"IMAGE_FILE_MACHINE_POWERPC", Const, 0}, + {"IMAGE_FILE_MACHINE_POWERPCFP", Const, 0}, + {"IMAGE_FILE_MACHINE_R4000", Const, 0}, + {"IMAGE_FILE_MACHINE_RISCV128", Const, 20}, + {"IMAGE_FILE_MACHINE_RISCV32", Const, 20}, + {"IMAGE_FILE_MACHINE_RISCV64", Const, 20}, + {"IMAGE_FILE_MACHINE_SH3", Const, 0}, + {"IMAGE_FILE_MACHINE_SH3DSP", Const, 0}, + {"IMAGE_FILE_MACHINE_SH4", Const, 0}, + {"IMAGE_FILE_MACHINE_SH5", Const, 0}, + {"IMAGE_FILE_MACHINE_THUMB", Const, 0}, + {"IMAGE_FILE_MACHINE_UNKNOWN", Const, 0}, + {"IMAGE_FILE_MACHINE_WCEMIPSV2", Const, 0}, + {"IMAGE_FILE_NET_RUN_FROM_SWAP", Const, 15}, + {"IMAGE_FILE_RELOCS_STRIPPED", Const, 15}, + {"IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP", Const, 15}, + {"IMAGE_FILE_SYSTEM", Const, 15}, + {"IMAGE_FILE_UP_SYSTEM_ONLY", Const, 15}, + {"IMAGE_SCN_CNT_CODE", Const, 19}, + {"IMAGE_SCN_CNT_INITIALIZED_DATA", Const, 19}, + {"IMAGE_SCN_CNT_UNINITIALIZED_DATA", Const, 19}, + {"IMAGE_SCN_LNK_COMDAT", Const, 19}, + {"IMAGE_SCN_MEM_DISCARDABLE", Const, 19}, + {"IMAGE_SCN_MEM_EXECUTE", Const, 19}, + {"IMAGE_SCN_MEM_READ", Const, 19}, + {"IMAGE_SCN_MEM_WRITE", Const, 19}, + {"IMAGE_SUBSYSTEM_EFI_APPLICATION", Const, 15}, + {"IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER", Const, 15}, + {"IMAGE_SUBSYSTEM_EFI_ROM", Const, 15}, + {"IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER", Const, 15}, + {"IMAGE_SUBSYSTEM_NATIVE", Const, 15}, + {"IMAGE_SUBSYSTEM_NATIVE_WINDOWS", Const, 15}, + {"IMAGE_SUBSYSTEM_OS2_CUI", Const, 15}, + {"IMAGE_SUBSYSTEM_POSIX_CUI", Const, 15}, + {"IMAGE_SUBSYSTEM_UNKNOWN", Const, 15}, + {"IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION", Const, 15}, + {"IMAGE_SUBSYSTEM_WINDOWS_CE_GUI", Const, 15}, + {"IMAGE_SUBSYSTEM_WINDOWS_CUI", Const, 15}, + {"IMAGE_SUBSYSTEM_WINDOWS_GUI", Const, 15}, + {"IMAGE_SUBSYSTEM_XBOX", Const, 15}, + {"ImportDirectory", Type, 0}, + {"ImportDirectory.FirstThunk", Field, 0}, + {"ImportDirectory.ForwarderChain", Field, 0}, + {"ImportDirectory.Name", Field, 0}, + {"ImportDirectory.OriginalFirstThunk", Field, 0}, + {"ImportDirectory.TimeDateStamp", Field, 0}, + {"NewFile", Func, 0}, + {"Open", Func, 0}, + {"OptionalHeader32", Type, 3}, + {"OptionalHeader32.AddressOfEntryPoint", Field, 3}, + {"OptionalHeader32.BaseOfCode", Field, 3}, + {"OptionalHeader32.BaseOfData", Field, 3}, + {"OptionalHeader32.CheckSum", Field, 3}, + {"OptionalHeader32.DataDirectory", Field, 3}, + {"OptionalHeader32.DllCharacteristics", Field, 3}, + {"OptionalHeader32.FileAlignment", Field, 3}, + {"OptionalHeader32.ImageBase", Field, 3}, + {"OptionalHeader32.LoaderFlags", Field, 3}, + {"OptionalHeader32.Magic", Field, 3}, + {"OptionalHeader32.MajorImageVersion", Field, 3}, + {"OptionalHeader32.MajorLinkerVersion", Field, 3}, + {"OptionalHeader32.MajorOperatingSystemVersion", Field, 3}, + {"OptionalHeader32.MajorSubsystemVersion", Field, 3}, + {"OptionalHeader32.MinorImageVersion", Field, 3}, + {"OptionalHeader32.MinorLinkerVersion", Field, 3}, + {"OptionalHeader32.MinorOperatingSystemVersion", Field, 3}, + {"OptionalHeader32.MinorSubsystemVersion", Field, 3}, + {"OptionalHeader32.NumberOfRvaAndSizes", Field, 3}, + {"OptionalHeader32.SectionAlignment", Field, 3}, + {"OptionalHeader32.SizeOfCode", Field, 3}, + {"OptionalHeader32.SizeOfHeaders", Field, 3}, + {"OptionalHeader32.SizeOfHeapCommit", Field, 3}, + {"OptionalHeader32.SizeOfHeapReserve", Field, 3}, + {"OptionalHeader32.SizeOfImage", Field, 3}, + {"OptionalHeader32.SizeOfInitializedData", Field, 3}, + {"OptionalHeader32.SizeOfStackCommit", Field, 3}, + {"OptionalHeader32.SizeOfStackReserve", Field, 3}, + {"OptionalHeader32.SizeOfUninitializedData", Field, 3}, + {"OptionalHeader32.Subsystem", Field, 3}, + {"OptionalHeader32.Win32VersionValue", Field, 3}, + {"OptionalHeader64", Type, 3}, + {"OptionalHeader64.AddressOfEntryPoint", Field, 3}, + {"OptionalHeader64.BaseOfCode", Field, 3}, + {"OptionalHeader64.CheckSum", Field, 3}, + {"OptionalHeader64.DataDirectory", Field, 3}, + {"OptionalHeader64.DllCharacteristics", Field, 3}, + {"OptionalHeader64.FileAlignment", Field, 3}, + {"OptionalHeader64.ImageBase", Field, 3}, + {"OptionalHeader64.LoaderFlags", Field, 3}, + {"OptionalHeader64.Magic", Field, 3}, + {"OptionalHeader64.MajorImageVersion", Field, 3}, + {"OptionalHeader64.MajorLinkerVersion", Field, 3}, + {"OptionalHeader64.MajorOperatingSystemVersion", Field, 3}, + {"OptionalHeader64.MajorSubsystemVersion", Field, 3}, + {"OptionalHeader64.MinorImageVersion", Field, 3}, + {"OptionalHeader64.MinorLinkerVersion", Field, 3}, + {"OptionalHeader64.MinorOperatingSystemVersion", Field, 3}, + {"OptionalHeader64.MinorSubsystemVersion", Field, 3}, + {"OptionalHeader64.NumberOfRvaAndSizes", Field, 3}, + {"OptionalHeader64.SectionAlignment", Field, 3}, + {"OptionalHeader64.SizeOfCode", Field, 3}, + {"OptionalHeader64.SizeOfHeaders", Field, 3}, + {"OptionalHeader64.SizeOfHeapCommit", Field, 3}, + {"OptionalHeader64.SizeOfHeapReserve", Field, 3}, + {"OptionalHeader64.SizeOfImage", Field, 3}, + {"OptionalHeader64.SizeOfInitializedData", Field, 3}, + {"OptionalHeader64.SizeOfStackCommit", Field, 3}, + {"OptionalHeader64.SizeOfStackReserve", Field, 3}, + {"OptionalHeader64.SizeOfUninitializedData", Field, 3}, + {"OptionalHeader64.Subsystem", Field, 3}, + {"OptionalHeader64.Win32VersionValue", Field, 3}, + {"Reloc", Type, 8}, + {"Reloc.SymbolTableIndex", Field, 8}, + {"Reloc.Type", Field, 8}, + {"Reloc.VirtualAddress", Field, 8}, + {"Section", Type, 0}, + {"Section.ReaderAt", Field, 0}, + {"Section.Relocs", Field, 8}, + {"Section.SectionHeader", Field, 0}, + {"SectionHeader", Type, 0}, + {"SectionHeader.Characteristics", Field, 0}, + {"SectionHeader.Name", Field, 0}, + {"SectionHeader.NumberOfLineNumbers", Field, 0}, + {"SectionHeader.NumberOfRelocations", Field, 0}, + {"SectionHeader.Offset", Field, 0}, + {"SectionHeader.PointerToLineNumbers", Field, 0}, + {"SectionHeader.PointerToRelocations", Field, 0}, + {"SectionHeader.Size", Field, 0}, + {"SectionHeader.VirtualAddress", Field, 0}, + {"SectionHeader.VirtualSize", Field, 0}, + {"SectionHeader32", Type, 0}, + {"SectionHeader32.Characteristics", Field, 0}, + {"SectionHeader32.Name", Field, 0}, + {"SectionHeader32.NumberOfLineNumbers", Field, 0}, + {"SectionHeader32.NumberOfRelocations", Field, 0}, + {"SectionHeader32.PointerToLineNumbers", Field, 0}, + {"SectionHeader32.PointerToRawData", Field, 0}, + {"SectionHeader32.PointerToRelocations", Field, 0}, + {"SectionHeader32.SizeOfRawData", Field, 0}, + {"SectionHeader32.VirtualAddress", Field, 0}, + {"SectionHeader32.VirtualSize", Field, 0}, + {"StringTable", Type, 8}, + {"Symbol", Type, 1}, + {"Symbol.Name", Field, 1}, + {"Symbol.SectionNumber", Field, 1}, + {"Symbol.StorageClass", Field, 1}, + {"Symbol.Type", Field, 1}, + {"Symbol.Value", Field, 1}, + }, + "debug/plan9obj": { + {"(*File).Close", Method, 3}, + {"(*File).Section", Method, 3}, + {"(*File).Symbols", Method, 3}, + {"(*Section).Data", Method, 3}, + {"(*Section).Open", Method, 3}, + {"(Section).ReadAt", Method, 3}, + {"ErrNoSymbols", Var, 18}, + {"File", Type, 3}, + {"File.FileHeader", Field, 3}, + {"File.Sections", Field, 3}, + {"FileHeader", Type, 3}, + {"FileHeader.Bss", Field, 3}, + {"FileHeader.Entry", Field, 3}, + {"FileHeader.HdrSize", Field, 4}, + {"FileHeader.LoadAddress", Field, 4}, + {"FileHeader.Magic", Field, 3}, + {"FileHeader.PtrSize", Field, 3}, + {"Magic386", Const, 3}, + {"Magic64", Const, 3}, + {"MagicAMD64", Const, 3}, + {"MagicARM", Const, 3}, + {"NewFile", Func, 3}, + {"Open", Func, 3}, + {"Section", Type, 3}, + {"Section.ReaderAt", Field, 3}, + {"Section.SectionHeader", Field, 3}, + {"SectionHeader", Type, 3}, + {"SectionHeader.Name", Field, 3}, + {"SectionHeader.Offset", Field, 3}, + {"SectionHeader.Size", Field, 3}, + {"Sym", Type, 3}, + {"Sym.Name", Field, 3}, + {"Sym.Type", Field, 3}, + {"Sym.Value", Field, 3}, + }, + "embed": { + {"(FS).Open", Method, 16}, + {"(FS).ReadDir", Method, 16}, + {"(FS).ReadFile", Method, 16}, + {"FS", Type, 16}, + }, + "encoding": { + {"BinaryMarshaler", Type, 2}, + {"BinaryUnmarshaler", Type, 2}, + {"TextMarshaler", Type, 2}, + {"TextUnmarshaler", Type, 2}, + }, + "encoding/ascii85": { + {"(CorruptInputError).Error", Method, 0}, + {"CorruptInputError", Type, 0}, + {"Decode", Func, 0}, + {"Encode", Func, 0}, + {"MaxEncodedLen", Func, 0}, + {"NewDecoder", Func, 0}, + {"NewEncoder", Func, 0}, + }, + "encoding/asn1": { + {"(BitString).At", Method, 0}, + {"(BitString).RightAlign", Method, 0}, + {"(ObjectIdentifier).Equal", Method, 0}, + {"(ObjectIdentifier).String", Method, 3}, + {"(StructuralError).Error", Method, 0}, + {"(SyntaxError).Error", Method, 0}, + {"BitString", Type, 0}, + {"BitString.BitLength", Field, 0}, + {"BitString.Bytes", Field, 0}, + {"ClassApplication", Const, 6}, + {"ClassContextSpecific", Const, 6}, + {"ClassPrivate", Const, 6}, + {"ClassUniversal", Const, 6}, + {"Enumerated", Type, 0}, + {"Flag", Type, 0}, + {"Marshal", Func, 0}, + {"MarshalWithParams", Func, 10}, + {"NullBytes", Var, 9}, + {"NullRawValue", Var, 9}, + {"ObjectIdentifier", Type, 0}, + {"RawContent", Type, 0}, + {"RawValue", Type, 0}, + {"RawValue.Bytes", Field, 0}, + {"RawValue.Class", Field, 0}, + {"RawValue.FullBytes", Field, 0}, + {"RawValue.IsCompound", Field, 0}, + {"RawValue.Tag", Field, 0}, + {"StructuralError", Type, 0}, + {"StructuralError.Msg", Field, 0}, + {"SyntaxError", Type, 0}, + {"SyntaxError.Msg", Field, 0}, + {"TagBMPString", Const, 14}, + {"TagBitString", Const, 6}, + {"TagBoolean", Const, 6}, + {"TagEnum", Const, 6}, + {"TagGeneralString", Const, 6}, + {"TagGeneralizedTime", Const, 6}, + {"TagIA5String", Const, 6}, + {"TagInteger", Const, 6}, + {"TagNull", Const, 9}, + {"TagNumericString", Const, 10}, + {"TagOID", Const, 6}, + {"TagOctetString", Const, 6}, + {"TagPrintableString", Const, 6}, + {"TagSequence", Const, 6}, + {"TagSet", Const, 6}, + {"TagT61String", Const, 6}, + {"TagUTCTime", Const, 6}, + {"TagUTF8String", Const, 6}, + {"Unmarshal", Func, 0}, + {"UnmarshalWithParams", Func, 0}, + }, + "encoding/base32": { + {"(*Encoding).AppendDecode", Method, 22}, + {"(*Encoding).AppendEncode", Method, 22}, + {"(*Encoding).Decode", Method, 0}, + {"(*Encoding).DecodeString", Method, 0}, + {"(*Encoding).DecodedLen", Method, 0}, + {"(*Encoding).Encode", Method, 0}, + {"(*Encoding).EncodeToString", Method, 0}, + {"(*Encoding).EncodedLen", Method, 0}, + {"(CorruptInputError).Error", Method, 0}, + {"(Encoding).WithPadding", Method, 9}, + {"CorruptInputError", Type, 0}, + {"Encoding", Type, 0}, + {"HexEncoding", Var, 0}, + {"NewDecoder", Func, 0}, + {"NewEncoder", Func, 0}, + {"NewEncoding", Func, 0}, + {"NoPadding", Const, 9}, + {"StdEncoding", Var, 0}, + {"StdPadding", Const, 9}, + }, + "encoding/base64": { + {"(*Encoding).AppendDecode", Method, 22}, + {"(*Encoding).AppendEncode", Method, 22}, + {"(*Encoding).Decode", Method, 0}, + {"(*Encoding).DecodeString", Method, 0}, + {"(*Encoding).DecodedLen", Method, 0}, + {"(*Encoding).Encode", Method, 0}, + {"(*Encoding).EncodeToString", Method, 0}, + {"(*Encoding).EncodedLen", Method, 0}, + {"(CorruptInputError).Error", Method, 0}, + {"(Encoding).Strict", Method, 8}, + {"(Encoding).WithPadding", Method, 5}, + {"CorruptInputError", Type, 0}, + {"Encoding", Type, 0}, + {"NewDecoder", Func, 0}, + {"NewEncoder", Func, 0}, + {"NewEncoding", Func, 0}, + {"NoPadding", Const, 5}, + {"RawStdEncoding", Var, 5}, + {"RawURLEncoding", Var, 5}, + {"StdEncoding", Var, 0}, + {"StdPadding", Const, 5}, + {"URLEncoding", Var, 0}, + }, + "encoding/binary": { + {"Append", Func, 23}, + {"AppendByteOrder", Type, 19}, + {"AppendUvarint", Func, 19}, + {"AppendVarint", Func, 19}, + {"BigEndian", Var, 0}, + {"ByteOrder", Type, 0}, + {"Decode", Func, 23}, + {"Encode", Func, 23}, + {"LittleEndian", Var, 0}, + {"MaxVarintLen16", Const, 0}, + {"MaxVarintLen32", Const, 0}, + {"MaxVarintLen64", Const, 0}, + {"NativeEndian", Var, 21}, + {"PutUvarint", Func, 0}, + {"PutVarint", Func, 0}, + {"Read", Func, 0}, + {"ReadUvarint", Func, 0}, + {"ReadVarint", Func, 0}, + {"Size", Func, 0}, + {"Uvarint", Func, 0}, + {"Varint", Func, 0}, + {"Write", Func, 0}, + }, + "encoding/csv": { + {"(*ParseError).Error", Method, 0}, + {"(*ParseError).Unwrap", Method, 13}, + {"(*Reader).FieldPos", Method, 17}, + {"(*Reader).InputOffset", Method, 19}, + {"(*Reader).Read", Method, 0}, + {"(*Reader).ReadAll", Method, 0}, + {"(*Writer).Error", Method, 1}, + {"(*Writer).Flush", Method, 0}, + {"(*Writer).Write", Method, 0}, + {"(*Writer).WriteAll", Method, 0}, + {"ErrBareQuote", Var, 0}, + {"ErrFieldCount", Var, 0}, + {"ErrQuote", Var, 0}, + {"ErrTrailingComma", Var, 0}, + {"NewReader", Func, 0}, + {"NewWriter", Func, 0}, + {"ParseError", Type, 0}, + {"ParseError.Column", Field, 0}, + {"ParseError.Err", Field, 0}, + {"ParseError.Line", Field, 0}, + {"ParseError.StartLine", Field, 10}, + {"Reader", Type, 0}, + {"Reader.Comma", Field, 0}, + {"Reader.Comment", Field, 0}, + {"Reader.FieldsPerRecord", Field, 0}, + {"Reader.LazyQuotes", Field, 0}, + {"Reader.ReuseRecord", Field, 9}, + {"Reader.TrailingComma", Field, 0}, + {"Reader.TrimLeadingSpace", Field, 0}, + {"Writer", Type, 0}, + {"Writer.Comma", Field, 0}, + {"Writer.UseCRLF", Field, 0}, + }, + "encoding/gob": { + {"(*Decoder).Decode", Method, 0}, + {"(*Decoder).DecodeValue", Method, 0}, + {"(*Encoder).Encode", Method, 0}, + {"(*Encoder).EncodeValue", Method, 0}, + {"CommonType", Type, 0}, + {"CommonType.Id", Field, 0}, + {"CommonType.Name", Field, 0}, + {"Decoder", Type, 0}, + {"Encoder", Type, 0}, + {"GobDecoder", Type, 0}, + {"GobEncoder", Type, 0}, + {"NewDecoder", Func, 0}, + {"NewEncoder", Func, 0}, + {"Register", Func, 0}, + {"RegisterName", Func, 0}, + }, + "encoding/hex": { + {"(InvalidByteError).Error", Method, 0}, + {"AppendDecode", Func, 22}, + {"AppendEncode", Func, 22}, + {"Decode", Func, 0}, + {"DecodeString", Func, 0}, + {"DecodedLen", Func, 0}, + {"Dump", Func, 0}, + {"Dumper", Func, 0}, + {"Encode", Func, 0}, + {"EncodeToString", Func, 0}, + {"EncodedLen", Func, 0}, + {"ErrLength", Var, 0}, + {"InvalidByteError", Type, 0}, + {"NewDecoder", Func, 10}, + {"NewEncoder", Func, 10}, + }, + "encoding/json": { + {"(*Decoder).Buffered", Method, 1}, + {"(*Decoder).Decode", Method, 0}, + {"(*Decoder).DisallowUnknownFields", Method, 10}, + {"(*Decoder).InputOffset", Method, 14}, + {"(*Decoder).More", Method, 5}, + {"(*Decoder).Token", Method, 5}, + {"(*Decoder).UseNumber", Method, 1}, + {"(*Encoder).Encode", Method, 0}, + {"(*Encoder).SetEscapeHTML", Method, 7}, + {"(*Encoder).SetIndent", Method, 7}, + {"(*InvalidUTF8Error).Error", Method, 0}, + {"(*InvalidUnmarshalError).Error", Method, 0}, + {"(*MarshalerError).Error", Method, 0}, + {"(*MarshalerError).Unwrap", Method, 13}, + {"(*RawMessage).MarshalJSON", Method, 0}, + {"(*RawMessage).UnmarshalJSON", Method, 0}, + {"(*SyntaxError).Error", Method, 0}, + {"(*UnmarshalFieldError).Error", Method, 0}, + {"(*UnmarshalTypeError).Error", Method, 0}, + {"(*UnsupportedTypeError).Error", Method, 0}, + {"(*UnsupportedValueError).Error", Method, 0}, + {"(Delim).String", Method, 5}, + {"(Number).Float64", Method, 1}, + {"(Number).Int64", Method, 1}, + {"(Number).String", Method, 1}, + {"(RawMessage).MarshalJSON", Method, 8}, + {"Compact", Func, 0}, + {"Decoder", Type, 0}, + {"Delim", Type, 5}, + {"Encoder", Type, 0}, + {"HTMLEscape", Func, 0}, + {"Indent", Func, 0}, + {"InvalidUTF8Error", Type, 0}, + {"InvalidUTF8Error.S", Field, 0}, + {"InvalidUnmarshalError", Type, 0}, + {"InvalidUnmarshalError.Type", Field, 0}, + {"Marshal", Func, 0}, + {"MarshalIndent", Func, 0}, + {"Marshaler", Type, 0}, + {"MarshalerError", Type, 0}, + {"MarshalerError.Err", Field, 0}, + {"MarshalerError.Type", Field, 0}, + {"NewDecoder", Func, 0}, + {"NewEncoder", Func, 0}, + {"Number", Type, 1}, + {"RawMessage", Type, 0}, + {"SyntaxError", Type, 0}, + {"SyntaxError.Offset", Field, 0}, + {"Token", Type, 5}, + {"Unmarshal", Func, 0}, + {"UnmarshalFieldError", Type, 0}, + {"UnmarshalFieldError.Field", Field, 0}, + {"UnmarshalFieldError.Key", Field, 0}, + {"UnmarshalFieldError.Type", Field, 0}, + {"UnmarshalTypeError", Type, 0}, + {"UnmarshalTypeError.Field", Field, 8}, + {"UnmarshalTypeError.Offset", Field, 5}, + {"UnmarshalTypeError.Struct", Field, 8}, + {"UnmarshalTypeError.Type", Field, 0}, + {"UnmarshalTypeError.Value", Field, 0}, + {"Unmarshaler", Type, 0}, + {"UnsupportedTypeError", Type, 0}, + {"UnsupportedTypeError.Type", Field, 0}, + {"UnsupportedValueError", Type, 0}, + {"UnsupportedValueError.Str", Field, 0}, + {"UnsupportedValueError.Value", Field, 0}, + {"Valid", Func, 9}, + }, + "encoding/pem": { + {"Block", Type, 0}, + {"Block.Bytes", Field, 0}, + {"Block.Headers", Field, 0}, + {"Block.Type", Field, 0}, + {"Decode", Func, 0}, + {"Encode", Func, 0}, + {"EncodeToMemory", Func, 0}, + }, + "encoding/xml": { + {"(*Decoder).Decode", Method, 0}, + {"(*Decoder).DecodeElement", Method, 0}, + {"(*Decoder).InputOffset", Method, 4}, + {"(*Decoder).InputPos", Method, 19}, + {"(*Decoder).RawToken", Method, 0}, + {"(*Decoder).Skip", Method, 0}, + {"(*Decoder).Token", Method, 0}, + {"(*Encoder).Close", Method, 20}, + {"(*Encoder).Encode", Method, 0}, + {"(*Encoder).EncodeElement", Method, 2}, + {"(*Encoder).EncodeToken", Method, 2}, + {"(*Encoder).Flush", Method, 2}, + {"(*Encoder).Indent", Method, 1}, + {"(*SyntaxError).Error", Method, 0}, + {"(*TagPathError).Error", Method, 0}, + {"(*UnsupportedTypeError).Error", Method, 0}, + {"(CharData).Copy", Method, 0}, + {"(Comment).Copy", Method, 0}, + {"(Directive).Copy", Method, 0}, + {"(ProcInst).Copy", Method, 0}, + {"(StartElement).Copy", Method, 0}, + {"(StartElement).End", Method, 2}, + {"(UnmarshalError).Error", Method, 0}, + {"Attr", Type, 0}, + {"Attr.Name", Field, 0}, + {"Attr.Value", Field, 0}, + {"CharData", Type, 0}, + {"Comment", Type, 0}, + {"CopyToken", Func, 0}, + {"Decoder", Type, 0}, + {"Decoder.AutoClose", Field, 0}, + {"Decoder.CharsetReader", Field, 0}, + {"Decoder.DefaultSpace", Field, 1}, + {"Decoder.Entity", Field, 0}, + {"Decoder.Strict", Field, 0}, + {"Directive", Type, 0}, + {"Encoder", Type, 0}, + {"EndElement", Type, 0}, + {"EndElement.Name", Field, 0}, + {"Escape", Func, 0}, + {"EscapeText", Func, 1}, + {"HTMLAutoClose", Var, 0}, + {"HTMLEntity", Var, 0}, + {"Header", Const, 0}, + {"Marshal", Func, 0}, + {"MarshalIndent", Func, 0}, + {"Marshaler", Type, 2}, + {"MarshalerAttr", Type, 2}, + {"Name", Type, 0}, + {"Name.Local", Field, 0}, + {"Name.Space", Field, 0}, + {"NewDecoder", Func, 0}, + {"NewEncoder", Func, 0}, + {"NewTokenDecoder", Func, 10}, + {"ProcInst", Type, 0}, + {"ProcInst.Inst", Field, 0}, + {"ProcInst.Target", Field, 0}, + {"StartElement", Type, 0}, + {"StartElement.Attr", Field, 0}, + {"StartElement.Name", Field, 0}, + {"SyntaxError", Type, 0}, + {"SyntaxError.Line", Field, 0}, + {"SyntaxError.Msg", Field, 0}, + {"TagPathError", Type, 0}, + {"TagPathError.Field1", Field, 0}, + {"TagPathError.Field2", Field, 0}, + {"TagPathError.Struct", Field, 0}, + {"TagPathError.Tag1", Field, 0}, + {"TagPathError.Tag2", Field, 0}, + {"Token", Type, 0}, + {"TokenReader", Type, 10}, + {"Unmarshal", Func, 0}, + {"UnmarshalError", Type, 0}, + {"Unmarshaler", Type, 2}, + {"UnmarshalerAttr", Type, 2}, + {"UnsupportedTypeError", Type, 0}, + {"UnsupportedTypeError.Type", Field, 0}, + }, + "errors": { + {"As", Func, 13}, + {"ErrUnsupported", Var, 21}, + {"Is", Func, 13}, + {"Join", Func, 20}, + {"New", Func, 0}, + {"Unwrap", Func, 13}, + }, + "expvar": { + {"(*Float).Add", Method, 0}, + {"(*Float).Set", Method, 0}, + {"(*Float).String", Method, 0}, + {"(*Float).Value", Method, 8}, + {"(*Int).Add", Method, 0}, + {"(*Int).Set", Method, 0}, + {"(*Int).String", Method, 0}, + {"(*Int).Value", Method, 8}, + {"(*Map).Add", Method, 0}, + {"(*Map).AddFloat", Method, 0}, + {"(*Map).Delete", Method, 12}, + {"(*Map).Do", Method, 0}, + {"(*Map).Get", Method, 0}, + {"(*Map).Init", Method, 0}, + {"(*Map).Set", Method, 0}, + {"(*Map).String", Method, 0}, + {"(*String).Set", Method, 0}, + {"(*String).String", Method, 0}, + {"(*String).Value", Method, 8}, + {"(Func).String", Method, 0}, + {"(Func).Value", Method, 8}, + {"Do", Func, 0}, + {"Float", Type, 0}, + {"Func", Type, 0}, + {"Get", Func, 0}, + {"Handler", Func, 8}, + {"Int", Type, 0}, + {"KeyValue", Type, 0}, + {"KeyValue.Key", Field, 0}, + {"KeyValue.Value", Field, 0}, + {"Map", Type, 0}, + {"NewFloat", Func, 0}, + {"NewInt", Func, 0}, + {"NewMap", Func, 0}, + {"NewString", Func, 0}, + {"Publish", Func, 0}, + {"String", Type, 0}, + {"Var", Type, 0}, + }, + "flag": { + {"(*FlagSet).Arg", Method, 0}, + {"(*FlagSet).Args", Method, 0}, + {"(*FlagSet).Bool", Method, 0}, + {"(*FlagSet).BoolFunc", Method, 21}, + {"(*FlagSet).BoolVar", Method, 0}, + {"(*FlagSet).Duration", Method, 0}, + {"(*FlagSet).DurationVar", Method, 0}, + {"(*FlagSet).ErrorHandling", Method, 10}, + {"(*FlagSet).Float64", Method, 0}, + {"(*FlagSet).Float64Var", Method, 0}, + {"(*FlagSet).Func", Method, 16}, + {"(*FlagSet).Init", Method, 0}, + {"(*FlagSet).Int", Method, 0}, + {"(*FlagSet).Int64", Method, 0}, + {"(*FlagSet).Int64Var", Method, 0}, + {"(*FlagSet).IntVar", Method, 0}, + {"(*FlagSet).Lookup", Method, 0}, + {"(*FlagSet).NArg", Method, 0}, + {"(*FlagSet).NFlag", Method, 0}, + {"(*FlagSet).Name", Method, 10}, + {"(*FlagSet).Output", Method, 10}, + {"(*FlagSet).Parse", Method, 0}, + {"(*FlagSet).Parsed", Method, 0}, + {"(*FlagSet).PrintDefaults", Method, 0}, + {"(*FlagSet).Set", Method, 0}, + {"(*FlagSet).SetOutput", Method, 0}, + {"(*FlagSet).String", Method, 0}, + {"(*FlagSet).StringVar", Method, 0}, + {"(*FlagSet).TextVar", Method, 19}, + {"(*FlagSet).Uint", Method, 0}, + {"(*FlagSet).Uint64", Method, 0}, + {"(*FlagSet).Uint64Var", Method, 0}, + {"(*FlagSet).UintVar", Method, 0}, + {"(*FlagSet).Var", Method, 0}, + {"(*FlagSet).Visit", Method, 0}, + {"(*FlagSet).VisitAll", Method, 0}, + {"Arg", Func, 0}, + {"Args", Func, 0}, + {"Bool", Func, 0}, + {"BoolFunc", Func, 21}, + {"BoolVar", Func, 0}, + {"CommandLine", Var, 2}, + {"ContinueOnError", Const, 0}, + {"Duration", Func, 0}, + {"DurationVar", Func, 0}, + {"ErrHelp", Var, 0}, + {"ErrorHandling", Type, 0}, + {"ExitOnError", Const, 0}, + {"Flag", Type, 0}, + {"Flag.DefValue", Field, 0}, + {"Flag.Name", Field, 0}, + {"Flag.Usage", Field, 0}, + {"Flag.Value", Field, 0}, + {"FlagSet", Type, 0}, + {"FlagSet.Usage", Field, 0}, + {"Float64", Func, 0}, + {"Float64Var", Func, 0}, + {"Func", Func, 16}, + {"Getter", Type, 2}, + {"Int", Func, 0}, + {"Int64", Func, 0}, + {"Int64Var", Func, 0}, + {"IntVar", Func, 0}, + {"Lookup", Func, 0}, + {"NArg", Func, 0}, + {"NFlag", Func, 0}, + {"NewFlagSet", Func, 0}, + {"PanicOnError", Const, 0}, + {"Parse", Func, 0}, + {"Parsed", Func, 0}, + {"PrintDefaults", Func, 0}, + {"Set", Func, 0}, + {"String", Func, 0}, + {"StringVar", Func, 0}, + {"TextVar", Func, 19}, + {"Uint", Func, 0}, + {"Uint64", Func, 0}, + {"Uint64Var", Func, 0}, + {"UintVar", Func, 0}, + {"UnquoteUsage", Func, 5}, + {"Usage", Var, 0}, + {"Value", Type, 0}, + {"Var", Func, 0}, + {"Visit", Func, 0}, + {"VisitAll", Func, 0}, + }, + "fmt": { + {"Append", Func, 19}, + {"Appendf", Func, 19}, + {"Appendln", Func, 19}, + {"Errorf", Func, 0}, + {"FormatString", Func, 20}, + {"Formatter", Type, 0}, + {"Fprint", Func, 0}, + {"Fprintf", Func, 0}, + {"Fprintln", Func, 0}, + {"Fscan", Func, 0}, + {"Fscanf", Func, 0}, + {"Fscanln", Func, 0}, + {"GoStringer", Type, 0}, + {"Print", Func, 0}, + {"Printf", Func, 0}, + {"Println", Func, 0}, + {"Scan", Func, 0}, + {"ScanState", Type, 0}, + {"Scanf", Func, 0}, + {"Scanln", Func, 0}, + {"Scanner", Type, 0}, + {"Sprint", Func, 0}, + {"Sprintf", Func, 0}, + {"Sprintln", Func, 0}, + {"Sscan", Func, 0}, + {"Sscanf", Func, 0}, + {"Sscanln", Func, 0}, + {"State", Type, 0}, + {"Stringer", Type, 0}, + }, + "go/ast": { + {"(*ArrayType).End", Method, 0}, + {"(*ArrayType).Pos", Method, 0}, + {"(*AssignStmt).End", Method, 0}, + {"(*AssignStmt).Pos", Method, 0}, + {"(*BadDecl).End", Method, 0}, + {"(*BadDecl).Pos", Method, 0}, + {"(*BadExpr).End", Method, 0}, + {"(*BadExpr).Pos", Method, 0}, + {"(*BadStmt).End", Method, 0}, + {"(*BadStmt).Pos", Method, 0}, + {"(*BasicLit).End", Method, 0}, + {"(*BasicLit).Pos", Method, 0}, + {"(*BinaryExpr).End", Method, 0}, + {"(*BinaryExpr).Pos", Method, 0}, + {"(*BlockStmt).End", Method, 0}, + {"(*BlockStmt).Pos", Method, 0}, + {"(*BranchStmt).End", Method, 0}, + {"(*BranchStmt).Pos", Method, 0}, + {"(*CallExpr).End", Method, 0}, + {"(*CallExpr).Pos", Method, 0}, + {"(*CaseClause).End", Method, 0}, + {"(*CaseClause).Pos", Method, 0}, + {"(*ChanType).End", Method, 0}, + {"(*ChanType).Pos", Method, 0}, + {"(*CommClause).End", Method, 0}, + {"(*CommClause).Pos", Method, 0}, + {"(*Comment).End", Method, 0}, + {"(*Comment).Pos", Method, 0}, + {"(*CommentGroup).End", Method, 0}, + {"(*CommentGroup).Pos", Method, 0}, + {"(*CommentGroup).Text", Method, 0}, + {"(*CompositeLit).End", Method, 0}, + {"(*CompositeLit).Pos", Method, 0}, + {"(*DeclStmt).End", Method, 0}, + {"(*DeclStmt).Pos", Method, 0}, + {"(*DeferStmt).End", Method, 0}, + {"(*DeferStmt).Pos", Method, 0}, + {"(*Ellipsis).End", Method, 0}, + {"(*Ellipsis).Pos", Method, 0}, + {"(*EmptyStmt).End", Method, 0}, + {"(*EmptyStmt).Pos", Method, 0}, + {"(*ExprStmt).End", Method, 0}, + {"(*ExprStmt).Pos", Method, 0}, + {"(*Field).End", Method, 0}, + {"(*Field).Pos", Method, 0}, + {"(*FieldList).End", Method, 0}, + {"(*FieldList).NumFields", Method, 0}, + {"(*FieldList).Pos", Method, 0}, + {"(*File).End", Method, 0}, + {"(*File).Pos", Method, 0}, + {"(*ForStmt).End", Method, 0}, + {"(*ForStmt).Pos", Method, 0}, + {"(*FuncDecl).End", Method, 0}, + {"(*FuncDecl).Pos", Method, 0}, + {"(*FuncLit).End", Method, 0}, + {"(*FuncLit).Pos", Method, 0}, + {"(*FuncType).End", Method, 0}, + {"(*FuncType).Pos", Method, 0}, + {"(*GenDecl).End", Method, 0}, + {"(*GenDecl).Pos", Method, 0}, + {"(*GoStmt).End", Method, 0}, + {"(*GoStmt).Pos", Method, 0}, + {"(*Ident).End", Method, 0}, + {"(*Ident).IsExported", Method, 0}, + {"(*Ident).Pos", Method, 0}, + {"(*Ident).String", Method, 0}, + {"(*IfStmt).End", Method, 0}, + {"(*IfStmt).Pos", Method, 0}, + {"(*ImportSpec).End", Method, 0}, + {"(*ImportSpec).Pos", Method, 0}, + {"(*IncDecStmt).End", Method, 0}, + {"(*IncDecStmt).Pos", Method, 0}, + {"(*IndexExpr).End", Method, 0}, + {"(*IndexExpr).Pos", Method, 0}, + {"(*IndexListExpr).End", Method, 18}, + {"(*IndexListExpr).Pos", Method, 18}, + {"(*InterfaceType).End", Method, 0}, + {"(*InterfaceType).Pos", Method, 0}, + {"(*KeyValueExpr).End", Method, 0}, + {"(*KeyValueExpr).Pos", Method, 0}, + {"(*LabeledStmt).End", Method, 0}, + {"(*LabeledStmt).Pos", Method, 0}, + {"(*MapType).End", Method, 0}, + {"(*MapType).Pos", Method, 0}, + {"(*Object).Pos", Method, 0}, + {"(*Package).End", Method, 0}, + {"(*Package).Pos", Method, 0}, + {"(*ParenExpr).End", Method, 0}, + {"(*ParenExpr).Pos", Method, 0}, + {"(*RangeStmt).End", Method, 0}, + {"(*RangeStmt).Pos", Method, 0}, + {"(*ReturnStmt).End", Method, 0}, + {"(*ReturnStmt).Pos", Method, 0}, + {"(*Scope).Insert", Method, 0}, + {"(*Scope).Lookup", Method, 0}, + {"(*Scope).String", Method, 0}, + {"(*SelectStmt).End", Method, 0}, + {"(*SelectStmt).Pos", Method, 0}, + {"(*SelectorExpr).End", Method, 0}, + {"(*SelectorExpr).Pos", Method, 0}, + {"(*SendStmt).End", Method, 0}, + {"(*SendStmt).Pos", Method, 0}, + {"(*SliceExpr).End", Method, 0}, + {"(*SliceExpr).Pos", Method, 0}, + {"(*StarExpr).End", Method, 0}, + {"(*StarExpr).Pos", Method, 0}, + {"(*StructType).End", Method, 0}, + {"(*StructType).Pos", Method, 0}, + {"(*SwitchStmt).End", Method, 0}, + {"(*SwitchStmt).Pos", Method, 0}, + {"(*TypeAssertExpr).End", Method, 0}, + {"(*TypeAssertExpr).Pos", Method, 0}, + {"(*TypeSpec).End", Method, 0}, + {"(*TypeSpec).Pos", Method, 0}, + {"(*TypeSwitchStmt).End", Method, 0}, + {"(*TypeSwitchStmt).Pos", Method, 0}, + {"(*UnaryExpr).End", Method, 0}, + {"(*UnaryExpr).Pos", Method, 0}, + {"(*ValueSpec).End", Method, 0}, + {"(*ValueSpec).Pos", Method, 0}, + {"(CommentMap).Comments", Method, 1}, + {"(CommentMap).Filter", Method, 1}, + {"(CommentMap).String", Method, 1}, + {"(CommentMap).Update", Method, 1}, + {"(ObjKind).String", Method, 0}, + {"ArrayType", Type, 0}, + {"ArrayType.Elt", Field, 0}, + {"ArrayType.Lbrack", Field, 0}, + {"ArrayType.Len", Field, 0}, + {"AssignStmt", Type, 0}, + {"AssignStmt.Lhs", Field, 0}, + {"AssignStmt.Rhs", Field, 0}, + {"AssignStmt.Tok", Field, 0}, + {"AssignStmt.TokPos", Field, 0}, + {"Bad", Const, 0}, + {"BadDecl", Type, 0}, + {"BadDecl.From", Field, 0}, + {"BadDecl.To", Field, 0}, + {"BadExpr", Type, 0}, + {"BadExpr.From", Field, 0}, + {"BadExpr.To", Field, 0}, + {"BadStmt", Type, 0}, + {"BadStmt.From", Field, 0}, + {"BadStmt.To", Field, 0}, + {"BasicLit", Type, 0}, + {"BasicLit.Kind", Field, 0}, + {"BasicLit.Value", Field, 0}, + {"BasicLit.ValuePos", Field, 0}, + {"BinaryExpr", Type, 0}, + {"BinaryExpr.Op", Field, 0}, + {"BinaryExpr.OpPos", Field, 0}, + {"BinaryExpr.X", Field, 0}, + {"BinaryExpr.Y", Field, 0}, + {"BlockStmt", Type, 0}, + {"BlockStmt.Lbrace", Field, 0}, + {"BlockStmt.List", Field, 0}, + {"BlockStmt.Rbrace", Field, 0}, + {"BranchStmt", Type, 0}, + {"BranchStmt.Label", Field, 0}, + {"BranchStmt.Tok", Field, 0}, + {"BranchStmt.TokPos", Field, 0}, + {"CallExpr", Type, 0}, + {"CallExpr.Args", Field, 0}, + {"CallExpr.Ellipsis", Field, 0}, + {"CallExpr.Fun", Field, 0}, + {"CallExpr.Lparen", Field, 0}, + {"CallExpr.Rparen", Field, 0}, + {"CaseClause", Type, 0}, + {"CaseClause.Body", Field, 0}, + {"CaseClause.Case", Field, 0}, + {"CaseClause.Colon", Field, 0}, + {"CaseClause.List", Field, 0}, + {"ChanDir", Type, 0}, + {"ChanType", Type, 0}, + {"ChanType.Arrow", Field, 1}, + {"ChanType.Begin", Field, 0}, + {"ChanType.Dir", Field, 0}, + {"ChanType.Value", Field, 0}, + {"CommClause", Type, 0}, + {"CommClause.Body", Field, 0}, + {"CommClause.Case", Field, 0}, + {"CommClause.Colon", Field, 0}, + {"CommClause.Comm", Field, 0}, + {"Comment", Type, 0}, + {"Comment.Slash", Field, 0}, + {"Comment.Text", Field, 0}, + {"CommentGroup", Type, 0}, + {"CommentGroup.List", Field, 0}, + {"CommentMap", Type, 1}, + {"CompositeLit", Type, 0}, + {"CompositeLit.Elts", Field, 0}, + {"CompositeLit.Incomplete", Field, 11}, + {"CompositeLit.Lbrace", Field, 0}, + {"CompositeLit.Rbrace", Field, 0}, + {"CompositeLit.Type", Field, 0}, + {"Con", Const, 0}, + {"Decl", Type, 0}, + {"DeclStmt", Type, 0}, + {"DeclStmt.Decl", Field, 0}, + {"DeferStmt", Type, 0}, + {"DeferStmt.Call", Field, 0}, + {"DeferStmt.Defer", Field, 0}, + {"Ellipsis", Type, 0}, + {"Ellipsis.Ellipsis", Field, 0}, + {"Ellipsis.Elt", Field, 0}, + {"EmptyStmt", Type, 0}, + {"EmptyStmt.Implicit", Field, 5}, + {"EmptyStmt.Semicolon", Field, 0}, + {"Expr", Type, 0}, + {"ExprStmt", Type, 0}, + {"ExprStmt.X", Field, 0}, + {"Field", Type, 0}, + {"Field.Comment", Field, 0}, + {"Field.Doc", Field, 0}, + {"Field.Names", Field, 0}, + {"Field.Tag", Field, 0}, + {"Field.Type", Field, 0}, + {"FieldFilter", Type, 0}, + {"FieldList", Type, 0}, + {"FieldList.Closing", Field, 0}, + {"FieldList.List", Field, 0}, + {"FieldList.Opening", Field, 0}, + {"File", Type, 0}, + {"File.Comments", Field, 0}, + {"File.Decls", Field, 0}, + {"File.Doc", Field, 0}, + {"File.FileEnd", Field, 20}, + {"File.FileStart", Field, 20}, + {"File.GoVersion", Field, 21}, + {"File.Imports", Field, 0}, + {"File.Name", Field, 0}, + {"File.Package", Field, 0}, + {"File.Scope", Field, 0}, + {"File.Unresolved", Field, 0}, + {"FileExports", Func, 0}, + {"Filter", Type, 0}, + {"FilterDecl", Func, 0}, + {"FilterFile", Func, 0}, + {"FilterFuncDuplicates", Const, 0}, + {"FilterImportDuplicates", Const, 0}, + {"FilterPackage", Func, 0}, + {"FilterUnassociatedComments", Const, 0}, + {"ForStmt", Type, 0}, + {"ForStmt.Body", Field, 0}, + {"ForStmt.Cond", Field, 0}, + {"ForStmt.For", Field, 0}, + {"ForStmt.Init", Field, 0}, + {"ForStmt.Post", Field, 0}, + {"Fprint", Func, 0}, + {"Fun", Const, 0}, + {"FuncDecl", Type, 0}, + {"FuncDecl.Body", Field, 0}, + {"FuncDecl.Doc", Field, 0}, + {"FuncDecl.Name", Field, 0}, + {"FuncDecl.Recv", Field, 0}, + {"FuncDecl.Type", Field, 0}, + {"FuncLit", Type, 0}, + {"FuncLit.Body", Field, 0}, + {"FuncLit.Type", Field, 0}, + {"FuncType", Type, 0}, + {"FuncType.Func", Field, 0}, + {"FuncType.Params", Field, 0}, + {"FuncType.Results", Field, 0}, + {"FuncType.TypeParams", Field, 18}, + {"GenDecl", Type, 0}, + {"GenDecl.Doc", Field, 0}, + {"GenDecl.Lparen", Field, 0}, + {"GenDecl.Rparen", Field, 0}, + {"GenDecl.Specs", Field, 0}, + {"GenDecl.Tok", Field, 0}, + {"GenDecl.TokPos", Field, 0}, + {"GoStmt", Type, 0}, + {"GoStmt.Call", Field, 0}, + {"GoStmt.Go", Field, 0}, + {"Ident", Type, 0}, + {"Ident.Name", Field, 0}, + {"Ident.NamePos", Field, 0}, + {"Ident.Obj", Field, 0}, + {"IfStmt", Type, 0}, + {"IfStmt.Body", Field, 0}, + {"IfStmt.Cond", Field, 0}, + {"IfStmt.Else", Field, 0}, + {"IfStmt.If", Field, 0}, + {"IfStmt.Init", Field, 0}, + {"ImportSpec", Type, 0}, + {"ImportSpec.Comment", Field, 0}, + {"ImportSpec.Doc", Field, 0}, + {"ImportSpec.EndPos", Field, 0}, + {"ImportSpec.Name", Field, 0}, + {"ImportSpec.Path", Field, 0}, + {"Importer", Type, 0}, + {"IncDecStmt", Type, 0}, + {"IncDecStmt.Tok", Field, 0}, + {"IncDecStmt.TokPos", Field, 0}, + {"IncDecStmt.X", Field, 0}, + {"IndexExpr", Type, 0}, + {"IndexExpr.Index", Field, 0}, + {"IndexExpr.Lbrack", Field, 0}, + {"IndexExpr.Rbrack", Field, 0}, + {"IndexExpr.X", Field, 0}, + {"IndexListExpr", Type, 18}, + {"IndexListExpr.Indices", Field, 18}, + {"IndexListExpr.Lbrack", Field, 18}, + {"IndexListExpr.Rbrack", Field, 18}, + {"IndexListExpr.X", Field, 18}, + {"Inspect", Func, 0}, + {"InterfaceType", Type, 0}, + {"InterfaceType.Incomplete", Field, 0}, + {"InterfaceType.Interface", Field, 0}, + {"InterfaceType.Methods", Field, 0}, + {"IsExported", Func, 0}, + {"IsGenerated", Func, 21}, + {"KeyValueExpr", Type, 0}, + {"KeyValueExpr.Colon", Field, 0}, + {"KeyValueExpr.Key", Field, 0}, + {"KeyValueExpr.Value", Field, 0}, + {"LabeledStmt", Type, 0}, + {"LabeledStmt.Colon", Field, 0}, + {"LabeledStmt.Label", Field, 0}, + {"LabeledStmt.Stmt", Field, 0}, + {"Lbl", Const, 0}, + {"MapType", Type, 0}, + {"MapType.Key", Field, 0}, + {"MapType.Map", Field, 0}, + {"MapType.Value", Field, 0}, + {"MergeMode", Type, 0}, + {"MergePackageFiles", Func, 0}, + {"NewCommentMap", Func, 1}, + {"NewIdent", Func, 0}, + {"NewObj", Func, 0}, + {"NewPackage", Func, 0}, + {"NewScope", Func, 0}, + {"Node", Type, 0}, + {"NotNilFilter", Func, 0}, + {"ObjKind", Type, 0}, + {"Object", Type, 0}, + {"Object.Data", Field, 0}, + {"Object.Decl", Field, 0}, + {"Object.Kind", Field, 0}, + {"Object.Name", Field, 0}, + {"Object.Type", Field, 0}, + {"Package", Type, 0}, + {"Package.Files", Field, 0}, + {"Package.Imports", Field, 0}, + {"Package.Name", Field, 0}, + {"Package.Scope", Field, 0}, + {"PackageExports", Func, 0}, + {"ParenExpr", Type, 0}, + {"ParenExpr.Lparen", Field, 0}, + {"ParenExpr.Rparen", Field, 0}, + {"ParenExpr.X", Field, 0}, + {"Pkg", Const, 0}, + {"Preorder", Func, 23}, + {"Print", Func, 0}, + {"RECV", Const, 0}, + {"RangeStmt", Type, 0}, + {"RangeStmt.Body", Field, 0}, + {"RangeStmt.For", Field, 0}, + {"RangeStmt.Key", Field, 0}, + {"RangeStmt.Range", Field, 20}, + {"RangeStmt.Tok", Field, 0}, + {"RangeStmt.TokPos", Field, 0}, + {"RangeStmt.Value", Field, 0}, + {"RangeStmt.X", Field, 0}, + {"ReturnStmt", Type, 0}, + {"ReturnStmt.Results", Field, 0}, + {"ReturnStmt.Return", Field, 0}, + {"SEND", Const, 0}, + {"Scope", Type, 0}, + {"Scope.Objects", Field, 0}, + {"Scope.Outer", Field, 0}, + {"SelectStmt", Type, 0}, + {"SelectStmt.Body", Field, 0}, + {"SelectStmt.Select", Field, 0}, + {"SelectorExpr", Type, 0}, + {"SelectorExpr.Sel", Field, 0}, + {"SelectorExpr.X", Field, 0}, + {"SendStmt", Type, 0}, + {"SendStmt.Arrow", Field, 0}, + {"SendStmt.Chan", Field, 0}, + {"SendStmt.Value", Field, 0}, + {"SliceExpr", Type, 0}, + {"SliceExpr.High", Field, 0}, + {"SliceExpr.Lbrack", Field, 0}, + {"SliceExpr.Low", Field, 0}, + {"SliceExpr.Max", Field, 2}, + {"SliceExpr.Rbrack", Field, 0}, + {"SliceExpr.Slice3", Field, 2}, + {"SliceExpr.X", Field, 0}, + {"SortImports", Func, 0}, + {"Spec", Type, 0}, + {"StarExpr", Type, 0}, + {"StarExpr.Star", Field, 0}, + {"StarExpr.X", Field, 0}, + {"Stmt", Type, 0}, + {"StructType", Type, 0}, + {"StructType.Fields", Field, 0}, + {"StructType.Incomplete", Field, 0}, + {"StructType.Struct", Field, 0}, + {"SwitchStmt", Type, 0}, + {"SwitchStmt.Body", Field, 0}, + {"SwitchStmt.Init", Field, 0}, + {"SwitchStmt.Switch", Field, 0}, + {"SwitchStmt.Tag", Field, 0}, + {"Typ", Const, 0}, + {"TypeAssertExpr", Type, 0}, + {"TypeAssertExpr.Lparen", Field, 2}, + {"TypeAssertExpr.Rparen", Field, 2}, + {"TypeAssertExpr.Type", Field, 0}, + {"TypeAssertExpr.X", Field, 0}, + {"TypeSpec", Type, 0}, + {"TypeSpec.Assign", Field, 9}, + {"TypeSpec.Comment", Field, 0}, + {"TypeSpec.Doc", Field, 0}, + {"TypeSpec.Name", Field, 0}, + {"TypeSpec.Type", Field, 0}, + {"TypeSpec.TypeParams", Field, 18}, + {"TypeSwitchStmt", Type, 0}, + {"TypeSwitchStmt.Assign", Field, 0}, + {"TypeSwitchStmt.Body", Field, 0}, + {"TypeSwitchStmt.Init", Field, 0}, + {"TypeSwitchStmt.Switch", Field, 0}, + {"UnaryExpr", Type, 0}, + {"UnaryExpr.Op", Field, 0}, + {"UnaryExpr.OpPos", Field, 0}, + {"UnaryExpr.X", Field, 0}, + {"Unparen", Func, 22}, + {"ValueSpec", Type, 0}, + {"ValueSpec.Comment", Field, 0}, + {"ValueSpec.Doc", Field, 0}, + {"ValueSpec.Names", Field, 0}, + {"ValueSpec.Type", Field, 0}, + {"ValueSpec.Values", Field, 0}, + {"Var", Const, 0}, + {"Visitor", Type, 0}, + {"Walk", Func, 0}, + }, + "go/build": { + {"(*Context).Import", Method, 0}, + {"(*Context).ImportDir", Method, 0}, + {"(*Context).MatchFile", Method, 2}, + {"(*Context).SrcDirs", Method, 0}, + {"(*MultiplePackageError).Error", Method, 4}, + {"(*NoGoError).Error", Method, 0}, + {"(*Package).IsCommand", Method, 0}, + {"AllowBinary", Const, 0}, + {"ArchChar", Func, 0}, + {"Context", Type, 0}, + {"Context.BuildTags", Field, 0}, + {"Context.CgoEnabled", Field, 0}, + {"Context.Compiler", Field, 0}, + {"Context.Dir", Field, 14}, + {"Context.GOARCH", Field, 0}, + {"Context.GOOS", Field, 0}, + {"Context.GOPATH", Field, 0}, + {"Context.GOROOT", Field, 0}, + {"Context.HasSubdir", Field, 0}, + {"Context.InstallSuffix", Field, 1}, + {"Context.IsAbsPath", Field, 0}, + {"Context.IsDir", Field, 0}, + {"Context.JoinPath", Field, 0}, + {"Context.OpenFile", Field, 0}, + {"Context.ReadDir", Field, 0}, + {"Context.ReleaseTags", Field, 1}, + {"Context.SplitPathList", Field, 0}, + {"Context.ToolTags", Field, 17}, + {"Context.UseAllFiles", Field, 0}, + {"Default", Var, 0}, + {"Directive", Type, 21}, + {"Directive.Pos", Field, 21}, + {"Directive.Text", Field, 21}, + {"FindOnly", Const, 0}, + {"IgnoreVendor", Const, 6}, + {"Import", Func, 0}, + {"ImportComment", Const, 4}, + {"ImportDir", Func, 0}, + {"ImportMode", Type, 0}, + {"IsLocalImport", Func, 0}, + {"MultiplePackageError", Type, 4}, + {"MultiplePackageError.Dir", Field, 4}, + {"MultiplePackageError.Files", Field, 4}, + {"MultiplePackageError.Packages", Field, 4}, + {"NoGoError", Type, 0}, + {"NoGoError.Dir", Field, 0}, + {"Package", Type, 0}, + {"Package.AllTags", Field, 2}, + {"Package.BinDir", Field, 0}, + {"Package.BinaryOnly", Field, 7}, + {"Package.CFiles", Field, 0}, + {"Package.CXXFiles", Field, 2}, + {"Package.CgoCFLAGS", Field, 0}, + {"Package.CgoCPPFLAGS", Field, 2}, + {"Package.CgoCXXFLAGS", Field, 2}, + {"Package.CgoFFLAGS", Field, 7}, + {"Package.CgoFiles", Field, 0}, + {"Package.CgoLDFLAGS", Field, 0}, + {"Package.CgoPkgConfig", Field, 0}, + {"Package.ConflictDir", Field, 2}, + {"Package.Dir", Field, 0}, + {"Package.Directives", Field, 21}, + {"Package.Doc", Field, 0}, + {"Package.EmbedPatternPos", Field, 16}, + {"Package.EmbedPatterns", Field, 16}, + {"Package.FFiles", Field, 7}, + {"Package.GoFiles", Field, 0}, + {"Package.Goroot", Field, 0}, + {"Package.HFiles", Field, 0}, + {"Package.IgnoredGoFiles", Field, 1}, + {"Package.IgnoredOtherFiles", Field, 16}, + {"Package.ImportComment", Field, 4}, + {"Package.ImportPath", Field, 0}, + {"Package.ImportPos", Field, 0}, + {"Package.Imports", Field, 0}, + {"Package.InvalidGoFiles", Field, 6}, + {"Package.MFiles", Field, 3}, + {"Package.Name", Field, 0}, + {"Package.PkgObj", Field, 0}, + {"Package.PkgRoot", Field, 0}, + {"Package.PkgTargetRoot", Field, 5}, + {"Package.Root", Field, 0}, + {"Package.SFiles", Field, 0}, + {"Package.SrcRoot", Field, 0}, + {"Package.SwigCXXFiles", Field, 1}, + {"Package.SwigFiles", Field, 1}, + {"Package.SysoFiles", Field, 0}, + {"Package.TestDirectives", Field, 21}, + {"Package.TestEmbedPatternPos", Field, 16}, + {"Package.TestEmbedPatterns", Field, 16}, + {"Package.TestGoFiles", Field, 0}, + {"Package.TestImportPos", Field, 0}, + {"Package.TestImports", Field, 0}, + {"Package.XTestDirectives", Field, 21}, + {"Package.XTestEmbedPatternPos", Field, 16}, + {"Package.XTestEmbedPatterns", Field, 16}, + {"Package.XTestGoFiles", Field, 0}, + {"Package.XTestImportPos", Field, 0}, + {"Package.XTestImports", Field, 0}, + {"ToolDir", Var, 0}, + }, + "go/build/constraint": { + {"(*AndExpr).Eval", Method, 16}, + {"(*AndExpr).String", Method, 16}, + {"(*NotExpr).Eval", Method, 16}, + {"(*NotExpr).String", Method, 16}, + {"(*OrExpr).Eval", Method, 16}, + {"(*OrExpr).String", Method, 16}, + {"(*SyntaxError).Error", Method, 16}, + {"(*TagExpr).Eval", Method, 16}, + {"(*TagExpr).String", Method, 16}, + {"AndExpr", Type, 16}, + {"AndExpr.X", Field, 16}, + {"AndExpr.Y", Field, 16}, + {"Expr", Type, 16}, + {"GoVersion", Func, 21}, + {"IsGoBuild", Func, 16}, + {"IsPlusBuild", Func, 16}, + {"NotExpr", Type, 16}, + {"NotExpr.X", Field, 16}, + {"OrExpr", Type, 16}, + {"OrExpr.X", Field, 16}, + {"OrExpr.Y", Field, 16}, + {"Parse", Func, 16}, + {"PlusBuildLines", Func, 16}, + {"SyntaxError", Type, 16}, + {"SyntaxError.Err", Field, 16}, + {"SyntaxError.Offset", Field, 16}, + {"TagExpr", Type, 16}, + {"TagExpr.Tag", Field, 16}, + }, + "go/constant": { + {"(Kind).String", Method, 18}, + {"BinaryOp", Func, 5}, + {"BitLen", Func, 5}, + {"Bool", Const, 5}, + {"BoolVal", Func, 5}, + {"Bytes", Func, 5}, + {"Compare", Func, 5}, + {"Complex", Const, 5}, + {"Denom", Func, 5}, + {"Float", Const, 5}, + {"Float32Val", Func, 5}, + {"Float64Val", Func, 5}, + {"Imag", Func, 5}, + {"Int", Const, 5}, + {"Int64Val", Func, 5}, + {"Kind", Type, 5}, + {"Make", Func, 13}, + {"MakeBool", Func, 5}, + {"MakeFloat64", Func, 5}, + {"MakeFromBytes", Func, 5}, + {"MakeFromLiteral", Func, 5}, + {"MakeImag", Func, 5}, + {"MakeInt64", Func, 5}, + {"MakeString", Func, 5}, + {"MakeUint64", Func, 5}, + {"MakeUnknown", Func, 5}, + {"Num", Func, 5}, + {"Real", Func, 5}, + {"Shift", Func, 5}, + {"Sign", Func, 5}, + {"String", Const, 5}, + {"StringVal", Func, 5}, + {"ToComplex", Func, 6}, + {"ToFloat", Func, 6}, + {"ToInt", Func, 6}, + {"Uint64Val", Func, 5}, + {"UnaryOp", Func, 5}, + {"Unknown", Const, 5}, + {"Val", Func, 13}, + {"Value", Type, 5}, + }, + "go/doc": { + {"(*Package).Filter", Method, 0}, + {"(*Package).HTML", Method, 19}, + {"(*Package).Markdown", Method, 19}, + {"(*Package).Parser", Method, 19}, + {"(*Package).Printer", Method, 19}, + {"(*Package).Synopsis", Method, 19}, + {"(*Package).Text", Method, 19}, + {"AllDecls", Const, 0}, + {"AllMethods", Const, 0}, + {"Example", Type, 0}, + {"Example.Code", Field, 0}, + {"Example.Comments", Field, 0}, + {"Example.Doc", Field, 0}, + {"Example.EmptyOutput", Field, 1}, + {"Example.Name", Field, 0}, + {"Example.Order", Field, 1}, + {"Example.Output", Field, 0}, + {"Example.Play", Field, 1}, + {"Example.Suffix", Field, 14}, + {"Example.Unordered", Field, 7}, + {"Examples", Func, 0}, + {"Filter", Type, 0}, + {"Func", Type, 0}, + {"Func.Decl", Field, 0}, + {"Func.Doc", Field, 0}, + {"Func.Examples", Field, 14}, + {"Func.Level", Field, 0}, + {"Func.Name", Field, 0}, + {"Func.Orig", Field, 0}, + {"Func.Recv", Field, 0}, + {"IllegalPrefixes", Var, 1}, + {"IsPredeclared", Func, 8}, + {"Mode", Type, 0}, + {"New", Func, 0}, + {"NewFromFiles", Func, 14}, + {"Note", Type, 1}, + {"Note.Body", Field, 1}, + {"Note.End", Field, 1}, + {"Note.Pos", Field, 1}, + {"Note.UID", Field, 1}, + {"Package", Type, 0}, + {"Package.Bugs", Field, 0}, + {"Package.Consts", Field, 0}, + {"Package.Doc", Field, 0}, + {"Package.Examples", Field, 14}, + {"Package.Filenames", Field, 0}, + {"Package.Funcs", Field, 0}, + {"Package.ImportPath", Field, 0}, + {"Package.Imports", Field, 0}, + {"Package.Name", Field, 0}, + {"Package.Notes", Field, 1}, + {"Package.Types", Field, 0}, + {"Package.Vars", Field, 0}, + {"PreserveAST", Const, 12}, + {"Synopsis", Func, 0}, + {"ToHTML", Func, 0}, + {"ToText", Func, 0}, + {"Type", Type, 0}, + {"Type.Consts", Field, 0}, + {"Type.Decl", Field, 0}, + {"Type.Doc", Field, 0}, + {"Type.Examples", Field, 14}, + {"Type.Funcs", Field, 0}, + {"Type.Methods", Field, 0}, + {"Type.Name", Field, 0}, + {"Type.Vars", Field, 0}, + {"Value", Type, 0}, + {"Value.Decl", Field, 0}, + {"Value.Doc", Field, 0}, + {"Value.Names", Field, 0}, + }, + "go/doc/comment": { + {"(*DocLink).DefaultURL", Method, 19}, + {"(*Heading).DefaultID", Method, 19}, + {"(*List).BlankBefore", Method, 19}, + {"(*List).BlankBetween", Method, 19}, + {"(*Parser).Parse", Method, 19}, + {"(*Printer).Comment", Method, 19}, + {"(*Printer).HTML", Method, 19}, + {"(*Printer).Markdown", Method, 19}, + {"(*Printer).Text", Method, 19}, + {"Block", Type, 19}, + {"Code", Type, 19}, + {"Code.Text", Field, 19}, + {"DefaultLookupPackage", Func, 19}, + {"Doc", Type, 19}, + {"Doc.Content", Field, 19}, + {"Doc.Links", Field, 19}, + {"DocLink", Type, 19}, + {"DocLink.ImportPath", Field, 19}, + {"DocLink.Name", Field, 19}, + {"DocLink.Recv", Field, 19}, + {"DocLink.Text", Field, 19}, + {"Heading", Type, 19}, + {"Heading.Text", Field, 19}, + {"Italic", Type, 19}, + {"Link", Type, 19}, + {"Link.Auto", Field, 19}, + {"Link.Text", Field, 19}, + {"Link.URL", Field, 19}, + {"LinkDef", Type, 19}, + {"LinkDef.Text", Field, 19}, + {"LinkDef.URL", Field, 19}, + {"LinkDef.Used", Field, 19}, + {"List", Type, 19}, + {"List.ForceBlankBefore", Field, 19}, + {"List.ForceBlankBetween", Field, 19}, + {"List.Items", Field, 19}, + {"ListItem", Type, 19}, + {"ListItem.Content", Field, 19}, + {"ListItem.Number", Field, 19}, + {"Paragraph", Type, 19}, + {"Paragraph.Text", Field, 19}, + {"Parser", Type, 19}, + {"Parser.LookupPackage", Field, 19}, + {"Parser.LookupSym", Field, 19}, + {"Parser.Words", Field, 19}, + {"Plain", Type, 19}, + {"Printer", Type, 19}, + {"Printer.DocLinkBaseURL", Field, 19}, + {"Printer.DocLinkURL", Field, 19}, + {"Printer.HeadingID", Field, 19}, + {"Printer.HeadingLevel", Field, 19}, + {"Printer.TextCodePrefix", Field, 19}, + {"Printer.TextPrefix", Field, 19}, + {"Printer.TextWidth", Field, 19}, + {"Text", Type, 19}, + }, + "go/format": { + {"Node", Func, 1}, + {"Source", Func, 1}, + }, + "go/importer": { + {"Default", Func, 5}, + {"For", Func, 5}, + {"ForCompiler", Func, 12}, + {"Lookup", Type, 5}, + }, + "go/parser": { + {"AllErrors", Const, 1}, + {"DeclarationErrors", Const, 0}, + {"ImportsOnly", Const, 0}, + {"Mode", Type, 0}, + {"PackageClauseOnly", Const, 0}, + {"ParseComments", Const, 0}, + {"ParseDir", Func, 0}, + {"ParseExpr", Func, 0}, + {"ParseExprFrom", Func, 5}, + {"ParseFile", Func, 0}, + {"SkipObjectResolution", Const, 17}, + {"SpuriousErrors", Const, 0}, + {"Trace", Const, 0}, + }, + "go/printer": { + {"(*Config).Fprint", Method, 0}, + {"CommentedNode", Type, 0}, + {"CommentedNode.Comments", Field, 0}, + {"CommentedNode.Node", Field, 0}, + {"Config", Type, 0}, + {"Config.Indent", Field, 1}, + {"Config.Mode", Field, 0}, + {"Config.Tabwidth", Field, 0}, + {"Fprint", Func, 0}, + {"Mode", Type, 0}, + {"RawFormat", Const, 0}, + {"SourcePos", Const, 0}, + {"TabIndent", Const, 0}, + {"UseSpaces", Const, 0}, + }, + "go/scanner": { + {"(*ErrorList).Add", Method, 0}, + {"(*ErrorList).RemoveMultiples", Method, 0}, + {"(*ErrorList).Reset", Method, 0}, + {"(*Scanner).Init", Method, 0}, + {"(*Scanner).Scan", Method, 0}, + {"(Error).Error", Method, 0}, + {"(ErrorList).Err", Method, 0}, + {"(ErrorList).Error", Method, 0}, + {"(ErrorList).Len", Method, 0}, + {"(ErrorList).Less", Method, 0}, + {"(ErrorList).Sort", Method, 0}, + {"(ErrorList).Swap", Method, 0}, + {"Error", Type, 0}, + {"Error.Msg", Field, 0}, + {"Error.Pos", Field, 0}, + {"ErrorHandler", Type, 0}, + {"ErrorList", Type, 0}, + {"Mode", Type, 0}, + {"PrintError", Func, 0}, + {"ScanComments", Const, 0}, + {"Scanner", Type, 0}, + {"Scanner.ErrorCount", Field, 0}, + }, + "go/token": { + {"(*File).AddLine", Method, 0}, + {"(*File).AddLineColumnInfo", Method, 11}, + {"(*File).AddLineInfo", Method, 0}, + {"(*File).Base", Method, 0}, + {"(*File).Line", Method, 0}, + {"(*File).LineCount", Method, 0}, + {"(*File).LineStart", Method, 12}, + {"(*File).Lines", Method, 21}, + {"(*File).MergeLine", Method, 2}, + {"(*File).Name", Method, 0}, + {"(*File).Offset", Method, 0}, + {"(*File).Pos", Method, 0}, + {"(*File).Position", Method, 0}, + {"(*File).PositionFor", Method, 4}, + {"(*File).SetLines", Method, 0}, + {"(*File).SetLinesForContent", Method, 0}, + {"(*File).Size", Method, 0}, + {"(*FileSet).AddFile", Method, 0}, + {"(*FileSet).Base", Method, 0}, + {"(*FileSet).File", Method, 0}, + {"(*FileSet).Iterate", Method, 0}, + {"(*FileSet).Position", Method, 0}, + {"(*FileSet).PositionFor", Method, 4}, + {"(*FileSet).Read", Method, 0}, + {"(*FileSet).RemoveFile", Method, 20}, + {"(*FileSet).Write", Method, 0}, + {"(*Position).IsValid", Method, 0}, + {"(Pos).IsValid", Method, 0}, + {"(Position).String", Method, 0}, + {"(Token).IsKeyword", Method, 0}, + {"(Token).IsLiteral", Method, 0}, + {"(Token).IsOperator", Method, 0}, + {"(Token).Precedence", Method, 0}, + {"(Token).String", Method, 0}, + {"ADD", Const, 0}, + {"ADD_ASSIGN", Const, 0}, + {"AND", Const, 0}, + {"AND_ASSIGN", Const, 0}, + {"AND_NOT", Const, 0}, + {"AND_NOT_ASSIGN", Const, 0}, + {"ARROW", Const, 0}, + {"ASSIGN", Const, 0}, + {"BREAK", Const, 0}, + {"CASE", Const, 0}, + {"CHAN", Const, 0}, + {"CHAR", Const, 0}, + {"COLON", Const, 0}, + {"COMMA", Const, 0}, + {"COMMENT", Const, 0}, + {"CONST", Const, 0}, + {"CONTINUE", Const, 0}, + {"DEC", Const, 0}, + {"DEFAULT", Const, 0}, + {"DEFER", Const, 0}, + {"DEFINE", Const, 0}, + {"ELLIPSIS", Const, 0}, + {"ELSE", Const, 0}, + {"EOF", Const, 0}, + {"EQL", Const, 0}, + {"FALLTHROUGH", Const, 0}, + {"FLOAT", Const, 0}, + {"FOR", Const, 0}, + {"FUNC", Const, 0}, + {"File", Type, 0}, + {"FileSet", Type, 0}, + {"GEQ", Const, 0}, + {"GO", Const, 0}, + {"GOTO", Const, 0}, + {"GTR", Const, 0}, + {"HighestPrec", Const, 0}, + {"IDENT", Const, 0}, + {"IF", Const, 0}, + {"ILLEGAL", Const, 0}, + {"IMAG", Const, 0}, + {"IMPORT", Const, 0}, + {"INC", Const, 0}, + {"INT", Const, 0}, + {"INTERFACE", Const, 0}, + {"IsExported", Func, 13}, + {"IsIdentifier", Func, 13}, + {"IsKeyword", Func, 13}, + {"LAND", Const, 0}, + {"LBRACE", Const, 0}, + {"LBRACK", Const, 0}, + {"LEQ", Const, 0}, + {"LOR", Const, 0}, + {"LPAREN", Const, 0}, + {"LSS", Const, 0}, + {"Lookup", Func, 0}, + {"LowestPrec", Const, 0}, + {"MAP", Const, 0}, + {"MUL", Const, 0}, + {"MUL_ASSIGN", Const, 0}, + {"NEQ", Const, 0}, + {"NOT", Const, 0}, + {"NewFileSet", Func, 0}, + {"NoPos", Const, 0}, + {"OR", Const, 0}, + {"OR_ASSIGN", Const, 0}, + {"PACKAGE", Const, 0}, + {"PERIOD", Const, 0}, + {"Pos", Type, 0}, + {"Position", Type, 0}, + {"Position.Column", Field, 0}, + {"Position.Filename", Field, 0}, + {"Position.Line", Field, 0}, + {"Position.Offset", Field, 0}, + {"QUO", Const, 0}, + {"QUO_ASSIGN", Const, 0}, + {"RANGE", Const, 0}, + {"RBRACE", Const, 0}, + {"RBRACK", Const, 0}, + {"REM", Const, 0}, + {"REM_ASSIGN", Const, 0}, + {"RETURN", Const, 0}, + {"RPAREN", Const, 0}, + {"SELECT", Const, 0}, + {"SEMICOLON", Const, 0}, + {"SHL", Const, 0}, + {"SHL_ASSIGN", Const, 0}, + {"SHR", Const, 0}, + {"SHR_ASSIGN", Const, 0}, + {"STRING", Const, 0}, + {"STRUCT", Const, 0}, + {"SUB", Const, 0}, + {"SUB_ASSIGN", Const, 0}, + {"SWITCH", Const, 0}, + {"TILDE", Const, 18}, + {"TYPE", Const, 0}, + {"Token", Type, 0}, + {"UnaryPrec", Const, 0}, + {"VAR", Const, 0}, + {"XOR", Const, 0}, + {"XOR_ASSIGN", Const, 0}, + }, + "go/types": { + {"(*Alias).Obj", Method, 22}, + {"(*Alias).Origin", Method, 23}, + {"(*Alias).Rhs", Method, 23}, + {"(*Alias).SetTypeParams", Method, 23}, + {"(*Alias).String", Method, 22}, + {"(*Alias).TypeArgs", Method, 23}, + {"(*Alias).TypeParams", Method, 23}, + {"(*Alias).Underlying", Method, 22}, + {"(*ArgumentError).Error", Method, 18}, + {"(*ArgumentError).Unwrap", Method, 18}, + {"(*Array).Elem", Method, 5}, + {"(*Array).Len", Method, 5}, + {"(*Array).String", Method, 5}, + {"(*Array).Underlying", Method, 5}, + {"(*Basic).Info", Method, 5}, + {"(*Basic).Kind", Method, 5}, + {"(*Basic).Name", Method, 5}, + {"(*Basic).String", Method, 5}, + {"(*Basic).Underlying", Method, 5}, + {"(*Builtin).Exported", Method, 5}, + {"(*Builtin).Id", Method, 5}, + {"(*Builtin).Name", Method, 5}, + {"(*Builtin).Parent", Method, 5}, + {"(*Builtin).Pkg", Method, 5}, + {"(*Builtin).Pos", Method, 5}, + {"(*Builtin).String", Method, 5}, + {"(*Builtin).Type", Method, 5}, + {"(*Chan).Dir", Method, 5}, + {"(*Chan).Elem", Method, 5}, + {"(*Chan).String", Method, 5}, + {"(*Chan).Underlying", Method, 5}, + {"(*Checker).Files", Method, 5}, + {"(*Config).Check", Method, 5}, + {"(*Const).Exported", Method, 5}, + {"(*Const).Id", Method, 5}, + {"(*Const).Name", Method, 5}, + {"(*Const).Parent", Method, 5}, + {"(*Const).Pkg", Method, 5}, + {"(*Const).Pos", Method, 5}, + {"(*Const).String", Method, 5}, + {"(*Const).Type", Method, 5}, + {"(*Const).Val", Method, 5}, + {"(*Func).Exported", Method, 5}, + {"(*Func).FullName", Method, 5}, + {"(*Func).Id", Method, 5}, + {"(*Func).Name", Method, 5}, + {"(*Func).Origin", Method, 19}, + {"(*Func).Parent", Method, 5}, + {"(*Func).Pkg", Method, 5}, + {"(*Func).Pos", Method, 5}, + {"(*Func).Scope", Method, 5}, + {"(*Func).Signature", Method, 23}, + {"(*Func).String", Method, 5}, + {"(*Func).Type", Method, 5}, + {"(*Info).ObjectOf", Method, 5}, + {"(*Info).PkgNameOf", Method, 22}, + {"(*Info).TypeOf", Method, 5}, + {"(*Initializer).String", Method, 5}, + {"(*Interface).Complete", Method, 5}, + {"(*Interface).Embedded", Method, 5}, + {"(*Interface).EmbeddedType", Method, 11}, + {"(*Interface).Empty", Method, 5}, + {"(*Interface).ExplicitMethod", Method, 5}, + {"(*Interface).IsComparable", Method, 18}, + {"(*Interface).IsImplicit", Method, 18}, + {"(*Interface).IsMethodSet", Method, 18}, + {"(*Interface).MarkImplicit", Method, 18}, + {"(*Interface).Method", Method, 5}, + {"(*Interface).NumEmbeddeds", Method, 5}, + {"(*Interface).NumExplicitMethods", Method, 5}, + {"(*Interface).NumMethods", Method, 5}, + {"(*Interface).String", Method, 5}, + {"(*Interface).Underlying", Method, 5}, + {"(*Label).Exported", Method, 5}, + {"(*Label).Id", Method, 5}, + {"(*Label).Name", Method, 5}, + {"(*Label).Parent", Method, 5}, + {"(*Label).Pkg", Method, 5}, + {"(*Label).Pos", Method, 5}, + {"(*Label).String", Method, 5}, + {"(*Label).Type", Method, 5}, + {"(*Map).Elem", Method, 5}, + {"(*Map).Key", Method, 5}, + {"(*Map).String", Method, 5}, + {"(*Map).Underlying", Method, 5}, + {"(*MethodSet).At", Method, 5}, + {"(*MethodSet).Len", Method, 5}, + {"(*MethodSet).Lookup", Method, 5}, + {"(*MethodSet).String", Method, 5}, + {"(*Named).AddMethod", Method, 5}, + {"(*Named).Method", Method, 5}, + {"(*Named).NumMethods", Method, 5}, + {"(*Named).Obj", Method, 5}, + {"(*Named).Origin", Method, 18}, + {"(*Named).SetTypeParams", Method, 18}, + {"(*Named).SetUnderlying", Method, 5}, + {"(*Named).String", Method, 5}, + {"(*Named).TypeArgs", Method, 18}, + {"(*Named).TypeParams", Method, 18}, + {"(*Named).Underlying", Method, 5}, + {"(*Nil).Exported", Method, 5}, + {"(*Nil).Id", Method, 5}, + {"(*Nil).Name", Method, 5}, + {"(*Nil).Parent", Method, 5}, + {"(*Nil).Pkg", Method, 5}, + {"(*Nil).Pos", Method, 5}, + {"(*Nil).String", Method, 5}, + {"(*Nil).Type", Method, 5}, + {"(*Package).Complete", Method, 5}, + {"(*Package).GoVersion", Method, 21}, + {"(*Package).Imports", Method, 5}, + {"(*Package).MarkComplete", Method, 5}, + {"(*Package).Name", Method, 5}, + {"(*Package).Path", Method, 5}, + {"(*Package).Scope", Method, 5}, + {"(*Package).SetImports", Method, 5}, + {"(*Package).SetName", Method, 6}, + {"(*Package).String", Method, 5}, + {"(*PkgName).Exported", Method, 5}, + {"(*PkgName).Id", Method, 5}, + {"(*PkgName).Imported", Method, 5}, + {"(*PkgName).Name", Method, 5}, + {"(*PkgName).Parent", Method, 5}, + {"(*PkgName).Pkg", Method, 5}, + {"(*PkgName).Pos", Method, 5}, + {"(*PkgName).String", Method, 5}, + {"(*PkgName).Type", Method, 5}, + {"(*Pointer).Elem", Method, 5}, + {"(*Pointer).String", Method, 5}, + {"(*Pointer).Underlying", Method, 5}, + {"(*Scope).Child", Method, 5}, + {"(*Scope).Contains", Method, 5}, + {"(*Scope).End", Method, 5}, + {"(*Scope).Innermost", Method, 5}, + {"(*Scope).Insert", Method, 5}, + {"(*Scope).Len", Method, 5}, + {"(*Scope).Lookup", Method, 5}, + {"(*Scope).LookupParent", Method, 5}, + {"(*Scope).Names", Method, 5}, + {"(*Scope).NumChildren", Method, 5}, + {"(*Scope).Parent", Method, 5}, + {"(*Scope).Pos", Method, 5}, + {"(*Scope).String", Method, 5}, + {"(*Scope).WriteTo", Method, 5}, + {"(*Selection).Index", Method, 5}, + {"(*Selection).Indirect", Method, 5}, + {"(*Selection).Kind", Method, 5}, + {"(*Selection).Obj", Method, 5}, + {"(*Selection).Recv", Method, 5}, + {"(*Selection).String", Method, 5}, + {"(*Selection).Type", Method, 5}, + {"(*Signature).Params", Method, 5}, + {"(*Signature).Recv", Method, 5}, + {"(*Signature).RecvTypeParams", Method, 18}, + {"(*Signature).Results", Method, 5}, + {"(*Signature).String", Method, 5}, + {"(*Signature).TypeParams", Method, 18}, + {"(*Signature).Underlying", Method, 5}, + {"(*Signature).Variadic", Method, 5}, + {"(*Slice).Elem", Method, 5}, + {"(*Slice).String", Method, 5}, + {"(*Slice).Underlying", Method, 5}, + {"(*StdSizes).Alignof", Method, 5}, + {"(*StdSizes).Offsetsof", Method, 5}, + {"(*StdSizes).Sizeof", Method, 5}, + {"(*Struct).Field", Method, 5}, + {"(*Struct).NumFields", Method, 5}, + {"(*Struct).String", Method, 5}, + {"(*Struct).Tag", Method, 5}, + {"(*Struct).Underlying", Method, 5}, + {"(*Term).String", Method, 18}, + {"(*Term).Tilde", Method, 18}, + {"(*Term).Type", Method, 18}, + {"(*Tuple).At", Method, 5}, + {"(*Tuple).Len", Method, 5}, + {"(*Tuple).String", Method, 5}, + {"(*Tuple).Underlying", Method, 5}, + {"(*TypeList).At", Method, 18}, + {"(*TypeList).Len", Method, 18}, + {"(*TypeName).Exported", Method, 5}, + {"(*TypeName).Id", Method, 5}, + {"(*TypeName).IsAlias", Method, 9}, + {"(*TypeName).Name", Method, 5}, + {"(*TypeName).Parent", Method, 5}, + {"(*TypeName).Pkg", Method, 5}, + {"(*TypeName).Pos", Method, 5}, + {"(*TypeName).String", Method, 5}, + {"(*TypeName).Type", Method, 5}, + {"(*TypeParam).Constraint", Method, 18}, + {"(*TypeParam).Index", Method, 18}, + {"(*TypeParam).Obj", Method, 18}, + {"(*TypeParam).SetConstraint", Method, 18}, + {"(*TypeParam).String", Method, 18}, + {"(*TypeParam).Underlying", Method, 18}, + {"(*TypeParamList).At", Method, 18}, + {"(*TypeParamList).Len", Method, 18}, + {"(*Union).Len", Method, 18}, + {"(*Union).String", Method, 18}, + {"(*Union).Term", Method, 18}, + {"(*Union).Underlying", Method, 18}, + {"(*Var).Anonymous", Method, 5}, + {"(*Var).Embedded", Method, 11}, + {"(*Var).Exported", Method, 5}, + {"(*Var).Id", Method, 5}, + {"(*Var).IsField", Method, 5}, + {"(*Var).Name", Method, 5}, + {"(*Var).Origin", Method, 19}, + {"(*Var).Parent", Method, 5}, + {"(*Var).Pkg", Method, 5}, + {"(*Var).Pos", Method, 5}, + {"(*Var).String", Method, 5}, + {"(*Var).Type", Method, 5}, + {"(Checker).ObjectOf", Method, 5}, + {"(Checker).PkgNameOf", Method, 22}, + {"(Checker).TypeOf", Method, 5}, + {"(Error).Error", Method, 5}, + {"(TypeAndValue).Addressable", Method, 5}, + {"(TypeAndValue).Assignable", Method, 5}, + {"(TypeAndValue).HasOk", Method, 5}, + {"(TypeAndValue).IsBuiltin", Method, 5}, + {"(TypeAndValue).IsNil", Method, 5}, + {"(TypeAndValue).IsType", Method, 5}, + {"(TypeAndValue).IsValue", Method, 5}, + {"(TypeAndValue).IsVoid", Method, 5}, + {"Alias", Type, 22}, + {"ArgumentError", Type, 18}, + {"ArgumentError.Err", Field, 18}, + {"ArgumentError.Index", Field, 18}, + {"Array", Type, 5}, + {"AssertableTo", Func, 5}, + {"AssignableTo", Func, 5}, + {"Basic", Type, 5}, + {"BasicInfo", Type, 5}, + {"BasicKind", Type, 5}, + {"Bool", Const, 5}, + {"Builtin", Type, 5}, + {"Byte", Const, 5}, + {"Chan", Type, 5}, + {"ChanDir", Type, 5}, + {"CheckExpr", Func, 13}, + {"Checker", Type, 5}, + {"Checker.Info", Field, 5}, + {"Comparable", Func, 5}, + {"Complex128", Const, 5}, + {"Complex64", Const, 5}, + {"Config", Type, 5}, + {"Config.Context", Field, 18}, + {"Config.DisableUnusedImportCheck", Field, 5}, + {"Config.Error", Field, 5}, + {"Config.FakeImportC", Field, 5}, + {"Config.GoVersion", Field, 18}, + {"Config.IgnoreFuncBodies", Field, 5}, + {"Config.Importer", Field, 5}, + {"Config.Sizes", Field, 5}, + {"Const", Type, 5}, + {"Context", Type, 18}, + {"ConvertibleTo", Func, 5}, + {"DefPredeclaredTestFuncs", Func, 5}, + {"Default", Func, 8}, + {"Error", Type, 5}, + {"Error.Fset", Field, 5}, + {"Error.Msg", Field, 5}, + {"Error.Pos", Field, 5}, + {"Error.Soft", Field, 5}, + {"Eval", Func, 5}, + {"ExprString", Func, 5}, + {"FieldVal", Const, 5}, + {"Float32", Const, 5}, + {"Float64", Const, 5}, + {"Func", Type, 5}, + {"Id", Func, 5}, + {"Identical", Func, 5}, + {"IdenticalIgnoreTags", Func, 8}, + {"Implements", Func, 5}, + {"ImportMode", Type, 6}, + {"Importer", Type, 5}, + {"ImporterFrom", Type, 6}, + {"Info", Type, 5}, + {"Info.Defs", Field, 5}, + {"Info.FileVersions", Field, 22}, + {"Info.Implicits", Field, 5}, + {"Info.InitOrder", Field, 5}, + {"Info.Instances", Field, 18}, + {"Info.Scopes", Field, 5}, + {"Info.Selections", Field, 5}, + {"Info.Types", Field, 5}, + {"Info.Uses", Field, 5}, + {"Initializer", Type, 5}, + {"Initializer.Lhs", Field, 5}, + {"Initializer.Rhs", Field, 5}, + {"Instance", Type, 18}, + {"Instance.Type", Field, 18}, + {"Instance.TypeArgs", Field, 18}, + {"Instantiate", Func, 18}, + {"Int", Const, 5}, + {"Int16", Const, 5}, + {"Int32", Const, 5}, + {"Int64", Const, 5}, + {"Int8", Const, 5}, + {"Interface", Type, 5}, + {"Invalid", Const, 5}, + {"IsBoolean", Const, 5}, + {"IsComplex", Const, 5}, + {"IsConstType", Const, 5}, + {"IsFloat", Const, 5}, + {"IsInteger", Const, 5}, + {"IsInterface", Func, 5}, + {"IsNumeric", Const, 5}, + {"IsOrdered", Const, 5}, + {"IsString", Const, 5}, + {"IsUnsigned", Const, 5}, + {"IsUntyped", Const, 5}, + {"Label", Type, 5}, + {"LookupFieldOrMethod", Func, 5}, + {"Map", Type, 5}, + {"MethodExpr", Const, 5}, + {"MethodSet", Type, 5}, + {"MethodVal", Const, 5}, + {"MissingMethod", Func, 5}, + {"Named", Type, 5}, + {"NewAlias", Func, 22}, + {"NewArray", Func, 5}, + {"NewChan", Func, 5}, + {"NewChecker", Func, 5}, + {"NewConst", Func, 5}, + {"NewContext", Func, 18}, + {"NewField", Func, 5}, + {"NewFunc", Func, 5}, + {"NewInterface", Func, 5}, + {"NewInterfaceType", Func, 11}, + {"NewLabel", Func, 5}, + {"NewMap", Func, 5}, + {"NewMethodSet", Func, 5}, + {"NewNamed", Func, 5}, + {"NewPackage", Func, 5}, + {"NewParam", Func, 5}, + {"NewPkgName", Func, 5}, + {"NewPointer", Func, 5}, + {"NewScope", Func, 5}, + {"NewSignature", Func, 5}, + {"NewSignatureType", Func, 18}, + {"NewSlice", Func, 5}, + {"NewStruct", Func, 5}, + {"NewTerm", Func, 18}, + {"NewTuple", Func, 5}, + {"NewTypeName", Func, 5}, + {"NewTypeParam", Func, 18}, + {"NewUnion", Func, 18}, + {"NewVar", Func, 5}, + {"Nil", Type, 5}, + {"Object", Type, 5}, + {"ObjectString", Func, 5}, + {"Package", Type, 5}, + {"PkgName", Type, 5}, + {"Pointer", Type, 5}, + {"Qualifier", Type, 5}, + {"RecvOnly", Const, 5}, + {"RelativeTo", Func, 5}, + {"Rune", Const, 5}, + {"Satisfies", Func, 20}, + {"Scope", Type, 5}, + {"Selection", Type, 5}, + {"SelectionKind", Type, 5}, + {"SelectionString", Func, 5}, + {"SendOnly", Const, 5}, + {"SendRecv", Const, 5}, + {"Signature", Type, 5}, + {"Sizes", Type, 5}, + {"SizesFor", Func, 9}, + {"Slice", Type, 5}, + {"StdSizes", Type, 5}, + {"StdSizes.MaxAlign", Field, 5}, + {"StdSizes.WordSize", Field, 5}, + {"String", Const, 5}, + {"Struct", Type, 5}, + {"Term", Type, 18}, + {"Tuple", Type, 5}, + {"Typ", Var, 5}, + {"Type", Type, 5}, + {"TypeAndValue", Type, 5}, + {"TypeAndValue.Type", Field, 5}, + {"TypeAndValue.Value", Field, 5}, + {"TypeList", Type, 18}, + {"TypeName", Type, 5}, + {"TypeParam", Type, 18}, + {"TypeParamList", Type, 18}, + {"TypeString", Func, 5}, + {"Uint", Const, 5}, + {"Uint16", Const, 5}, + {"Uint32", Const, 5}, + {"Uint64", Const, 5}, + {"Uint8", Const, 5}, + {"Uintptr", Const, 5}, + {"Unalias", Func, 22}, + {"Union", Type, 18}, + {"Universe", Var, 5}, + {"Unsafe", Var, 5}, + {"UnsafePointer", Const, 5}, + {"UntypedBool", Const, 5}, + {"UntypedComplex", Const, 5}, + {"UntypedFloat", Const, 5}, + {"UntypedInt", Const, 5}, + {"UntypedNil", Const, 5}, + {"UntypedRune", Const, 5}, + {"UntypedString", Const, 5}, + {"Var", Type, 5}, + {"WriteExpr", Func, 5}, + {"WriteSignature", Func, 5}, + {"WriteType", Func, 5}, + }, + "go/version": { + {"Compare", Func, 22}, + {"IsValid", Func, 22}, + {"Lang", Func, 22}, + }, + "hash": { + {"Hash", Type, 0}, + {"Hash32", Type, 0}, + {"Hash64", Type, 0}, + }, + "hash/adler32": { + {"Checksum", Func, 0}, + {"New", Func, 0}, + {"Size", Const, 0}, + }, + "hash/crc32": { + {"Castagnoli", Const, 0}, + {"Checksum", Func, 0}, + {"ChecksumIEEE", Func, 0}, + {"IEEE", Const, 0}, + {"IEEETable", Var, 0}, + {"Koopman", Const, 0}, + {"MakeTable", Func, 0}, + {"New", Func, 0}, + {"NewIEEE", Func, 0}, + {"Size", Const, 0}, + {"Table", Type, 0}, + {"Update", Func, 0}, + }, + "hash/crc64": { + {"Checksum", Func, 0}, + {"ECMA", Const, 0}, + {"ISO", Const, 0}, + {"MakeTable", Func, 0}, + {"New", Func, 0}, + {"Size", Const, 0}, + {"Table", Type, 0}, + {"Update", Func, 0}, + }, + "hash/fnv": { + {"New128", Func, 9}, + {"New128a", Func, 9}, + {"New32", Func, 0}, + {"New32a", Func, 0}, + {"New64", Func, 0}, + {"New64a", Func, 0}, + }, + "hash/maphash": { + {"(*Hash).BlockSize", Method, 14}, + {"(*Hash).Reset", Method, 14}, + {"(*Hash).Seed", Method, 14}, + {"(*Hash).SetSeed", Method, 14}, + {"(*Hash).Size", Method, 14}, + {"(*Hash).Sum", Method, 14}, + {"(*Hash).Sum64", Method, 14}, + {"(*Hash).Write", Method, 14}, + {"(*Hash).WriteByte", Method, 14}, + {"(*Hash).WriteString", Method, 14}, + {"Bytes", Func, 19}, + {"Hash", Type, 14}, + {"MakeSeed", Func, 14}, + {"Seed", Type, 14}, + {"String", Func, 19}, + }, + "html": { + {"EscapeString", Func, 0}, + {"UnescapeString", Func, 0}, + }, + "html/template": { + {"(*Error).Error", Method, 0}, + {"(*Template).AddParseTree", Method, 0}, + {"(*Template).Clone", Method, 0}, + {"(*Template).DefinedTemplates", Method, 6}, + {"(*Template).Delims", Method, 0}, + {"(*Template).Execute", Method, 0}, + {"(*Template).ExecuteTemplate", Method, 0}, + {"(*Template).Funcs", Method, 0}, + {"(*Template).Lookup", Method, 0}, + {"(*Template).Name", Method, 0}, + {"(*Template).New", Method, 0}, + {"(*Template).Option", Method, 5}, + {"(*Template).Parse", Method, 0}, + {"(*Template).ParseFS", Method, 16}, + {"(*Template).ParseFiles", Method, 0}, + {"(*Template).ParseGlob", Method, 0}, + {"(*Template).Templates", Method, 0}, + {"CSS", Type, 0}, + {"ErrAmbigContext", Const, 0}, + {"ErrBadHTML", Const, 0}, + {"ErrBranchEnd", Const, 0}, + {"ErrEndContext", Const, 0}, + {"ErrJSTemplate", Const, 21}, + {"ErrNoSuchTemplate", Const, 0}, + {"ErrOutputContext", Const, 0}, + {"ErrPartialCharset", Const, 0}, + {"ErrPartialEscape", Const, 0}, + {"ErrPredefinedEscaper", Const, 9}, + {"ErrRangeLoopReentry", Const, 0}, + {"ErrSlashAmbig", Const, 0}, + {"Error", Type, 0}, + {"Error.Description", Field, 0}, + {"Error.ErrorCode", Field, 0}, + {"Error.Line", Field, 0}, + {"Error.Name", Field, 0}, + {"Error.Node", Field, 4}, + {"ErrorCode", Type, 0}, + {"FuncMap", Type, 0}, + {"HTML", Type, 0}, + {"HTMLAttr", Type, 0}, + {"HTMLEscape", Func, 0}, + {"HTMLEscapeString", Func, 0}, + {"HTMLEscaper", Func, 0}, + {"IsTrue", Func, 6}, + {"JS", Type, 0}, + {"JSEscape", Func, 0}, + {"JSEscapeString", Func, 0}, + {"JSEscaper", Func, 0}, + {"JSStr", Type, 0}, + {"Must", Func, 0}, + {"New", Func, 0}, + {"OK", Const, 0}, + {"ParseFS", Func, 16}, + {"ParseFiles", Func, 0}, + {"ParseGlob", Func, 0}, + {"Srcset", Type, 10}, + {"Template", Type, 0}, + {"Template.Tree", Field, 2}, + {"URL", Type, 0}, + {"URLQueryEscaper", Func, 0}, + }, + "image": { + {"(*Alpha).AlphaAt", Method, 4}, + {"(*Alpha).At", Method, 0}, + {"(*Alpha).Bounds", Method, 0}, + {"(*Alpha).ColorModel", Method, 0}, + {"(*Alpha).Opaque", Method, 0}, + {"(*Alpha).PixOffset", Method, 0}, + {"(*Alpha).RGBA64At", Method, 17}, + {"(*Alpha).Set", Method, 0}, + {"(*Alpha).SetAlpha", Method, 0}, + {"(*Alpha).SetRGBA64", Method, 17}, + {"(*Alpha).SubImage", Method, 0}, + {"(*Alpha16).Alpha16At", Method, 4}, + {"(*Alpha16).At", Method, 0}, + {"(*Alpha16).Bounds", Method, 0}, + {"(*Alpha16).ColorModel", Method, 0}, + {"(*Alpha16).Opaque", Method, 0}, + {"(*Alpha16).PixOffset", Method, 0}, + {"(*Alpha16).RGBA64At", Method, 17}, + {"(*Alpha16).Set", Method, 0}, + {"(*Alpha16).SetAlpha16", Method, 0}, + {"(*Alpha16).SetRGBA64", Method, 17}, + {"(*Alpha16).SubImage", Method, 0}, + {"(*CMYK).At", Method, 5}, + {"(*CMYK).Bounds", Method, 5}, + {"(*CMYK).CMYKAt", Method, 5}, + {"(*CMYK).ColorModel", Method, 5}, + {"(*CMYK).Opaque", Method, 5}, + {"(*CMYK).PixOffset", Method, 5}, + {"(*CMYK).RGBA64At", Method, 17}, + {"(*CMYK).Set", Method, 5}, + {"(*CMYK).SetCMYK", Method, 5}, + {"(*CMYK).SetRGBA64", Method, 17}, + {"(*CMYK).SubImage", Method, 5}, + {"(*Gray).At", Method, 0}, + {"(*Gray).Bounds", Method, 0}, + {"(*Gray).ColorModel", Method, 0}, + {"(*Gray).GrayAt", Method, 4}, + {"(*Gray).Opaque", Method, 0}, + {"(*Gray).PixOffset", Method, 0}, + {"(*Gray).RGBA64At", Method, 17}, + {"(*Gray).Set", Method, 0}, + {"(*Gray).SetGray", Method, 0}, + {"(*Gray).SetRGBA64", Method, 17}, + {"(*Gray).SubImage", Method, 0}, + {"(*Gray16).At", Method, 0}, + {"(*Gray16).Bounds", Method, 0}, + {"(*Gray16).ColorModel", Method, 0}, + {"(*Gray16).Gray16At", Method, 4}, + {"(*Gray16).Opaque", Method, 0}, + {"(*Gray16).PixOffset", Method, 0}, + {"(*Gray16).RGBA64At", Method, 17}, + {"(*Gray16).Set", Method, 0}, + {"(*Gray16).SetGray16", Method, 0}, + {"(*Gray16).SetRGBA64", Method, 17}, + {"(*Gray16).SubImage", Method, 0}, + {"(*NRGBA).At", Method, 0}, + {"(*NRGBA).Bounds", Method, 0}, + {"(*NRGBA).ColorModel", Method, 0}, + {"(*NRGBA).NRGBAAt", Method, 4}, + {"(*NRGBA).Opaque", Method, 0}, + {"(*NRGBA).PixOffset", Method, 0}, + {"(*NRGBA).RGBA64At", Method, 17}, + {"(*NRGBA).Set", Method, 0}, + {"(*NRGBA).SetNRGBA", Method, 0}, + {"(*NRGBA).SetRGBA64", Method, 17}, + {"(*NRGBA).SubImage", Method, 0}, + {"(*NRGBA64).At", Method, 0}, + {"(*NRGBA64).Bounds", Method, 0}, + {"(*NRGBA64).ColorModel", Method, 0}, + {"(*NRGBA64).NRGBA64At", Method, 4}, + {"(*NRGBA64).Opaque", Method, 0}, + {"(*NRGBA64).PixOffset", Method, 0}, + {"(*NRGBA64).RGBA64At", Method, 17}, + {"(*NRGBA64).Set", Method, 0}, + {"(*NRGBA64).SetNRGBA64", Method, 0}, + {"(*NRGBA64).SetRGBA64", Method, 17}, + {"(*NRGBA64).SubImage", Method, 0}, + {"(*NYCbCrA).AOffset", Method, 6}, + {"(*NYCbCrA).At", Method, 6}, + {"(*NYCbCrA).Bounds", Method, 6}, + {"(*NYCbCrA).COffset", Method, 6}, + {"(*NYCbCrA).ColorModel", Method, 6}, + {"(*NYCbCrA).NYCbCrAAt", Method, 6}, + {"(*NYCbCrA).Opaque", Method, 6}, + {"(*NYCbCrA).RGBA64At", Method, 17}, + {"(*NYCbCrA).SubImage", Method, 6}, + {"(*NYCbCrA).YCbCrAt", Method, 6}, + {"(*NYCbCrA).YOffset", Method, 6}, + {"(*Paletted).At", Method, 0}, + {"(*Paletted).Bounds", Method, 0}, + {"(*Paletted).ColorIndexAt", Method, 0}, + {"(*Paletted).ColorModel", Method, 0}, + {"(*Paletted).Opaque", Method, 0}, + {"(*Paletted).PixOffset", Method, 0}, + {"(*Paletted).RGBA64At", Method, 17}, + {"(*Paletted).Set", Method, 0}, + {"(*Paletted).SetColorIndex", Method, 0}, + {"(*Paletted).SetRGBA64", Method, 17}, + {"(*Paletted).SubImage", Method, 0}, + {"(*RGBA).At", Method, 0}, + {"(*RGBA).Bounds", Method, 0}, + {"(*RGBA).ColorModel", Method, 0}, + {"(*RGBA).Opaque", Method, 0}, + {"(*RGBA).PixOffset", Method, 0}, + {"(*RGBA).RGBA64At", Method, 17}, + {"(*RGBA).RGBAAt", Method, 4}, + {"(*RGBA).Set", Method, 0}, + {"(*RGBA).SetRGBA", Method, 0}, + {"(*RGBA).SetRGBA64", Method, 17}, + {"(*RGBA).SubImage", Method, 0}, + {"(*RGBA64).At", Method, 0}, + {"(*RGBA64).Bounds", Method, 0}, + {"(*RGBA64).ColorModel", Method, 0}, + {"(*RGBA64).Opaque", Method, 0}, + {"(*RGBA64).PixOffset", Method, 0}, + {"(*RGBA64).RGBA64At", Method, 4}, + {"(*RGBA64).Set", Method, 0}, + {"(*RGBA64).SetRGBA64", Method, 0}, + {"(*RGBA64).SubImage", Method, 0}, + {"(*Uniform).At", Method, 0}, + {"(*Uniform).Bounds", Method, 0}, + {"(*Uniform).ColorModel", Method, 0}, + {"(*Uniform).Convert", Method, 0}, + {"(*Uniform).Opaque", Method, 0}, + {"(*Uniform).RGBA", Method, 0}, + {"(*Uniform).RGBA64At", Method, 17}, + {"(*YCbCr).At", Method, 0}, + {"(*YCbCr).Bounds", Method, 0}, + {"(*YCbCr).COffset", Method, 0}, + {"(*YCbCr).ColorModel", Method, 0}, + {"(*YCbCr).Opaque", Method, 0}, + {"(*YCbCr).RGBA64At", Method, 17}, + {"(*YCbCr).SubImage", Method, 0}, + {"(*YCbCr).YCbCrAt", Method, 4}, + {"(*YCbCr).YOffset", Method, 0}, + {"(Point).Add", Method, 0}, + {"(Point).Div", Method, 0}, + {"(Point).Eq", Method, 0}, + {"(Point).In", Method, 0}, + {"(Point).Mod", Method, 0}, + {"(Point).Mul", Method, 0}, + {"(Point).String", Method, 0}, + {"(Point).Sub", Method, 0}, + {"(Rectangle).Add", Method, 0}, + {"(Rectangle).At", Method, 5}, + {"(Rectangle).Bounds", Method, 5}, + {"(Rectangle).Canon", Method, 0}, + {"(Rectangle).ColorModel", Method, 5}, + {"(Rectangle).Dx", Method, 0}, + {"(Rectangle).Dy", Method, 0}, + {"(Rectangle).Empty", Method, 0}, + {"(Rectangle).Eq", Method, 0}, + {"(Rectangle).In", Method, 0}, + {"(Rectangle).Inset", Method, 0}, + {"(Rectangle).Intersect", Method, 0}, + {"(Rectangle).Overlaps", Method, 0}, + {"(Rectangle).RGBA64At", Method, 17}, + {"(Rectangle).Size", Method, 0}, + {"(Rectangle).String", Method, 0}, + {"(Rectangle).Sub", Method, 0}, + {"(Rectangle).Union", Method, 0}, + {"(YCbCrSubsampleRatio).String", Method, 0}, + {"Alpha", Type, 0}, + {"Alpha.Pix", Field, 0}, + {"Alpha.Rect", Field, 0}, + {"Alpha.Stride", Field, 0}, + {"Alpha16", Type, 0}, + {"Alpha16.Pix", Field, 0}, + {"Alpha16.Rect", Field, 0}, + {"Alpha16.Stride", Field, 0}, + {"Black", Var, 0}, + {"CMYK", Type, 5}, + {"CMYK.Pix", Field, 5}, + {"CMYK.Rect", Field, 5}, + {"CMYK.Stride", Field, 5}, + {"Config", Type, 0}, + {"Config.ColorModel", Field, 0}, + {"Config.Height", Field, 0}, + {"Config.Width", Field, 0}, + {"Decode", Func, 0}, + {"DecodeConfig", Func, 0}, + {"ErrFormat", Var, 0}, + {"Gray", Type, 0}, + {"Gray.Pix", Field, 0}, + {"Gray.Rect", Field, 0}, + {"Gray.Stride", Field, 0}, + {"Gray16", Type, 0}, + {"Gray16.Pix", Field, 0}, + {"Gray16.Rect", Field, 0}, + {"Gray16.Stride", Field, 0}, + {"Image", Type, 0}, + {"NRGBA", Type, 0}, + {"NRGBA.Pix", Field, 0}, + {"NRGBA.Rect", Field, 0}, + {"NRGBA.Stride", Field, 0}, + {"NRGBA64", Type, 0}, + {"NRGBA64.Pix", Field, 0}, + {"NRGBA64.Rect", Field, 0}, + {"NRGBA64.Stride", Field, 0}, + {"NYCbCrA", Type, 6}, + {"NYCbCrA.A", Field, 6}, + {"NYCbCrA.AStride", Field, 6}, + {"NYCbCrA.YCbCr", Field, 6}, + {"NewAlpha", Func, 0}, + {"NewAlpha16", Func, 0}, + {"NewCMYK", Func, 5}, + {"NewGray", Func, 0}, + {"NewGray16", Func, 0}, + {"NewNRGBA", Func, 0}, + {"NewNRGBA64", Func, 0}, + {"NewNYCbCrA", Func, 6}, + {"NewPaletted", Func, 0}, + {"NewRGBA", Func, 0}, + {"NewRGBA64", Func, 0}, + {"NewUniform", Func, 0}, + {"NewYCbCr", Func, 0}, + {"Opaque", Var, 0}, + {"Paletted", Type, 0}, + {"Paletted.Palette", Field, 0}, + {"Paletted.Pix", Field, 0}, + {"Paletted.Rect", Field, 0}, + {"Paletted.Stride", Field, 0}, + {"PalettedImage", Type, 0}, + {"Point", Type, 0}, + {"Point.X", Field, 0}, + {"Point.Y", Field, 0}, + {"Pt", Func, 0}, + {"RGBA", Type, 0}, + {"RGBA.Pix", Field, 0}, + {"RGBA.Rect", Field, 0}, + {"RGBA.Stride", Field, 0}, + {"RGBA64", Type, 0}, + {"RGBA64.Pix", Field, 0}, + {"RGBA64.Rect", Field, 0}, + {"RGBA64.Stride", Field, 0}, + {"RGBA64Image", Type, 17}, + {"Rect", Func, 0}, + {"Rectangle", Type, 0}, + {"Rectangle.Max", Field, 0}, + {"Rectangle.Min", Field, 0}, + {"RegisterFormat", Func, 0}, + {"Transparent", Var, 0}, + {"Uniform", Type, 0}, + {"Uniform.C", Field, 0}, + {"White", Var, 0}, + {"YCbCr", Type, 0}, + {"YCbCr.CStride", Field, 0}, + {"YCbCr.Cb", Field, 0}, + {"YCbCr.Cr", Field, 0}, + {"YCbCr.Rect", Field, 0}, + {"YCbCr.SubsampleRatio", Field, 0}, + {"YCbCr.Y", Field, 0}, + {"YCbCr.YStride", Field, 0}, + {"YCbCrSubsampleRatio", Type, 0}, + {"YCbCrSubsampleRatio410", Const, 5}, + {"YCbCrSubsampleRatio411", Const, 5}, + {"YCbCrSubsampleRatio420", Const, 0}, + {"YCbCrSubsampleRatio422", Const, 0}, + {"YCbCrSubsampleRatio440", Const, 1}, + {"YCbCrSubsampleRatio444", Const, 0}, + {"ZP", Var, 0}, + {"ZR", Var, 0}, + }, + "image/color": { + {"(Alpha).RGBA", Method, 0}, + {"(Alpha16).RGBA", Method, 0}, + {"(CMYK).RGBA", Method, 5}, + {"(Gray).RGBA", Method, 0}, + {"(Gray16).RGBA", Method, 0}, + {"(NRGBA).RGBA", Method, 0}, + {"(NRGBA64).RGBA", Method, 0}, + {"(NYCbCrA).RGBA", Method, 6}, + {"(Palette).Convert", Method, 0}, + {"(Palette).Index", Method, 0}, + {"(RGBA).RGBA", Method, 0}, + {"(RGBA64).RGBA", Method, 0}, + {"(YCbCr).RGBA", Method, 0}, + {"Alpha", Type, 0}, + {"Alpha.A", Field, 0}, + {"Alpha16", Type, 0}, + {"Alpha16.A", Field, 0}, + {"Alpha16Model", Var, 0}, + {"AlphaModel", Var, 0}, + {"Black", Var, 0}, + {"CMYK", Type, 5}, + {"CMYK.C", Field, 5}, + {"CMYK.K", Field, 5}, + {"CMYK.M", Field, 5}, + {"CMYK.Y", Field, 5}, + {"CMYKModel", Var, 5}, + {"CMYKToRGB", Func, 5}, + {"Color", Type, 0}, + {"Gray", Type, 0}, + {"Gray.Y", Field, 0}, + {"Gray16", Type, 0}, + {"Gray16.Y", Field, 0}, + {"Gray16Model", Var, 0}, + {"GrayModel", Var, 0}, + {"Model", Type, 0}, + {"ModelFunc", Func, 0}, + {"NRGBA", Type, 0}, + {"NRGBA.A", Field, 0}, + {"NRGBA.B", Field, 0}, + {"NRGBA.G", Field, 0}, + {"NRGBA.R", Field, 0}, + {"NRGBA64", Type, 0}, + {"NRGBA64.A", Field, 0}, + {"NRGBA64.B", Field, 0}, + {"NRGBA64.G", Field, 0}, + {"NRGBA64.R", Field, 0}, + {"NRGBA64Model", Var, 0}, + {"NRGBAModel", Var, 0}, + {"NYCbCrA", Type, 6}, + {"NYCbCrA.A", Field, 6}, + {"NYCbCrA.YCbCr", Field, 6}, + {"NYCbCrAModel", Var, 6}, + {"Opaque", Var, 0}, + {"Palette", Type, 0}, + {"RGBA", Type, 0}, + {"RGBA.A", Field, 0}, + {"RGBA.B", Field, 0}, + {"RGBA.G", Field, 0}, + {"RGBA.R", Field, 0}, + {"RGBA64", Type, 0}, + {"RGBA64.A", Field, 0}, + {"RGBA64.B", Field, 0}, + {"RGBA64.G", Field, 0}, + {"RGBA64.R", Field, 0}, + {"RGBA64Model", Var, 0}, + {"RGBAModel", Var, 0}, + {"RGBToCMYK", Func, 5}, + {"RGBToYCbCr", Func, 0}, + {"Transparent", Var, 0}, + {"White", Var, 0}, + {"YCbCr", Type, 0}, + {"YCbCr.Cb", Field, 0}, + {"YCbCr.Cr", Field, 0}, + {"YCbCr.Y", Field, 0}, + {"YCbCrModel", Var, 0}, + {"YCbCrToRGB", Func, 0}, + }, + "image/color/palette": { + {"Plan9", Var, 2}, + {"WebSafe", Var, 2}, + }, + "image/draw": { + {"(Op).Draw", Method, 2}, + {"Draw", Func, 0}, + {"DrawMask", Func, 0}, + {"Drawer", Type, 2}, + {"FloydSteinberg", Var, 2}, + {"Image", Type, 0}, + {"Op", Type, 0}, + {"Over", Const, 0}, + {"Quantizer", Type, 2}, + {"RGBA64Image", Type, 17}, + {"Src", Const, 0}, + }, + "image/gif": { + {"Decode", Func, 0}, + {"DecodeAll", Func, 0}, + {"DecodeConfig", Func, 0}, + {"DisposalBackground", Const, 5}, + {"DisposalNone", Const, 5}, + {"DisposalPrevious", Const, 5}, + {"Encode", Func, 2}, + {"EncodeAll", Func, 2}, + {"GIF", Type, 0}, + {"GIF.BackgroundIndex", Field, 5}, + {"GIF.Config", Field, 5}, + {"GIF.Delay", Field, 0}, + {"GIF.Disposal", Field, 5}, + {"GIF.Image", Field, 0}, + {"GIF.LoopCount", Field, 0}, + {"Options", Type, 2}, + {"Options.Drawer", Field, 2}, + {"Options.NumColors", Field, 2}, + {"Options.Quantizer", Field, 2}, + }, + "image/jpeg": { + {"(FormatError).Error", Method, 0}, + {"(UnsupportedError).Error", Method, 0}, + {"Decode", Func, 0}, + {"DecodeConfig", Func, 0}, + {"DefaultQuality", Const, 0}, + {"Encode", Func, 0}, + {"FormatError", Type, 0}, + {"Options", Type, 0}, + {"Options.Quality", Field, 0}, + {"Reader", Type, 0}, + {"UnsupportedError", Type, 0}, + }, + "image/png": { + {"(*Encoder).Encode", Method, 4}, + {"(FormatError).Error", Method, 0}, + {"(UnsupportedError).Error", Method, 0}, + {"BestCompression", Const, 4}, + {"BestSpeed", Const, 4}, + {"CompressionLevel", Type, 4}, + {"Decode", Func, 0}, + {"DecodeConfig", Func, 0}, + {"DefaultCompression", Const, 4}, + {"Encode", Func, 0}, + {"Encoder", Type, 4}, + {"Encoder.BufferPool", Field, 9}, + {"Encoder.CompressionLevel", Field, 4}, + {"EncoderBuffer", Type, 9}, + {"EncoderBufferPool", Type, 9}, + {"FormatError", Type, 0}, + {"NoCompression", Const, 4}, + {"UnsupportedError", Type, 0}, + }, + "index/suffixarray": { + {"(*Index).Bytes", Method, 0}, + {"(*Index).FindAllIndex", Method, 0}, + {"(*Index).Lookup", Method, 0}, + {"(*Index).Read", Method, 0}, + {"(*Index).Write", Method, 0}, + {"Index", Type, 0}, + {"New", Func, 0}, + }, + "io": { + {"(*LimitedReader).Read", Method, 0}, + {"(*OffsetWriter).Seek", Method, 20}, + {"(*OffsetWriter).Write", Method, 20}, + {"(*OffsetWriter).WriteAt", Method, 20}, + {"(*PipeReader).Close", Method, 0}, + {"(*PipeReader).CloseWithError", Method, 0}, + {"(*PipeReader).Read", Method, 0}, + {"(*PipeWriter).Close", Method, 0}, + {"(*PipeWriter).CloseWithError", Method, 0}, + {"(*PipeWriter).Write", Method, 0}, + {"(*SectionReader).Outer", Method, 22}, + {"(*SectionReader).Read", Method, 0}, + {"(*SectionReader).ReadAt", Method, 0}, + {"(*SectionReader).Seek", Method, 0}, + {"(*SectionReader).Size", Method, 0}, + {"ByteReader", Type, 0}, + {"ByteScanner", Type, 0}, + {"ByteWriter", Type, 1}, + {"Closer", Type, 0}, + {"Copy", Func, 0}, + {"CopyBuffer", Func, 5}, + {"CopyN", Func, 0}, + {"Discard", Var, 16}, + {"EOF", Var, 0}, + {"ErrClosedPipe", Var, 0}, + {"ErrNoProgress", Var, 1}, + {"ErrShortBuffer", Var, 0}, + {"ErrShortWrite", Var, 0}, + {"ErrUnexpectedEOF", Var, 0}, + {"LimitReader", Func, 0}, + {"LimitedReader", Type, 0}, + {"LimitedReader.N", Field, 0}, + {"LimitedReader.R", Field, 0}, + {"MultiReader", Func, 0}, + {"MultiWriter", Func, 0}, + {"NewOffsetWriter", Func, 20}, + {"NewSectionReader", Func, 0}, + {"NopCloser", Func, 16}, + {"OffsetWriter", Type, 20}, + {"Pipe", Func, 0}, + {"PipeReader", Type, 0}, + {"PipeWriter", Type, 0}, + {"ReadAll", Func, 16}, + {"ReadAtLeast", Func, 0}, + {"ReadCloser", Type, 0}, + {"ReadFull", Func, 0}, + {"ReadSeekCloser", Type, 16}, + {"ReadSeeker", Type, 0}, + {"ReadWriteCloser", Type, 0}, + {"ReadWriteSeeker", Type, 0}, + {"ReadWriter", Type, 0}, + {"Reader", Type, 0}, + {"ReaderAt", Type, 0}, + {"ReaderFrom", Type, 0}, + {"RuneReader", Type, 0}, + {"RuneScanner", Type, 0}, + {"SectionReader", Type, 0}, + {"SeekCurrent", Const, 7}, + {"SeekEnd", Const, 7}, + {"SeekStart", Const, 7}, + {"Seeker", Type, 0}, + {"StringWriter", Type, 12}, + {"TeeReader", Func, 0}, + {"WriteCloser", Type, 0}, + {"WriteSeeker", Type, 0}, + {"WriteString", Func, 0}, + {"Writer", Type, 0}, + {"WriterAt", Type, 0}, + {"WriterTo", Type, 0}, + }, + "io/fs": { + {"(*PathError).Error", Method, 16}, + {"(*PathError).Timeout", Method, 16}, + {"(*PathError).Unwrap", Method, 16}, + {"(FileMode).IsDir", Method, 16}, + {"(FileMode).IsRegular", Method, 16}, + {"(FileMode).Perm", Method, 16}, + {"(FileMode).String", Method, 16}, + {"(FileMode).Type", Method, 16}, + {"DirEntry", Type, 16}, + {"ErrClosed", Var, 16}, + {"ErrExist", Var, 16}, + {"ErrInvalid", Var, 16}, + {"ErrNotExist", Var, 16}, + {"ErrPermission", Var, 16}, + {"FS", Type, 16}, + {"File", Type, 16}, + {"FileInfo", Type, 16}, + {"FileInfoToDirEntry", Func, 17}, + {"FileMode", Type, 16}, + {"FormatDirEntry", Func, 21}, + {"FormatFileInfo", Func, 21}, + {"Glob", Func, 16}, + {"GlobFS", Type, 16}, + {"ModeAppend", Const, 16}, + {"ModeCharDevice", Const, 16}, + {"ModeDevice", Const, 16}, + {"ModeDir", Const, 16}, + {"ModeExclusive", Const, 16}, + {"ModeIrregular", Const, 16}, + {"ModeNamedPipe", Const, 16}, + {"ModePerm", Const, 16}, + {"ModeSetgid", Const, 16}, + {"ModeSetuid", Const, 16}, + {"ModeSocket", Const, 16}, + {"ModeSticky", Const, 16}, + {"ModeSymlink", Const, 16}, + {"ModeTemporary", Const, 16}, + {"ModeType", Const, 16}, + {"PathError", Type, 16}, + {"PathError.Err", Field, 16}, + {"PathError.Op", Field, 16}, + {"PathError.Path", Field, 16}, + {"ReadDir", Func, 16}, + {"ReadDirFS", Type, 16}, + {"ReadDirFile", Type, 16}, + {"ReadFile", Func, 16}, + {"ReadFileFS", Type, 16}, + {"SkipAll", Var, 20}, + {"SkipDir", Var, 16}, + {"Stat", Func, 16}, + {"StatFS", Type, 16}, + {"Sub", Func, 16}, + {"SubFS", Type, 16}, + {"ValidPath", Func, 16}, + {"WalkDir", Func, 16}, + {"WalkDirFunc", Type, 16}, + }, + "io/ioutil": { + {"Discard", Var, 0}, + {"NopCloser", Func, 0}, + {"ReadAll", Func, 0}, + {"ReadDir", Func, 0}, + {"ReadFile", Func, 0}, + {"TempDir", Func, 0}, + {"TempFile", Func, 0}, + {"WriteFile", Func, 0}, + }, + "iter": { + {"Pull", Func, 23}, + {"Pull2", Func, 23}, + {"Seq", Type, 23}, + {"Seq2", Type, 23}, + }, + "log": { + {"(*Logger).Fatal", Method, 0}, + {"(*Logger).Fatalf", Method, 0}, + {"(*Logger).Fatalln", Method, 0}, + {"(*Logger).Flags", Method, 0}, + {"(*Logger).Output", Method, 0}, + {"(*Logger).Panic", Method, 0}, + {"(*Logger).Panicf", Method, 0}, + {"(*Logger).Panicln", Method, 0}, + {"(*Logger).Prefix", Method, 0}, + {"(*Logger).Print", Method, 0}, + {"(*Logger).Printf", Method, 0}, + {"(*Logger).Println", Method, 0}, + {"(*Logger).SetFlags", Method, 0}, + {"(*Logger).SetOutput", Method, 5}, + {"(*Logger).SetPrefix", Method, 0}, + {"(*Logger).Writer", Method, 12}, + {"Default", Func, 16}, + {"Fatal", Func, 0}, + {"Fatalf", Func, 0}, + {"Fatalln", Func, 0}, + {"Flags", Func, 0}, + {"LUTC", Const, 5}, + {"Ldate", Const, 0}, + {"Llongfile", Const, 0}, + {"Lmicroseconds", Const, 0}, + {"Lmsgprefix", Const, 14}, + {"Logger", Type, 0}, + {"Lshortfile", Const, 0}, + {"LstdFlags", Const, 0}, + {"Ltime", Const, 0}, + {"New", Func, 0}, + {"Output", Func, 5}, + {"Panic", Func, 0}, + {"Panicf", Func, 0}, + {"Panicln", Func, 0}, + {"Prefix", Func, 0}, + {"Print", Func, 0}, + {"Printf", Func, 0}, + {"Println", Func, 0}, + {"SetFlags", Func, 0}, + {"SetOutput", Func, 0}, + {"SetPrefix", Func, 0}, + {"Writer", Func, 13}, + }, + "log/slog": { + {"(*JSONHandler).Enabled", Method, 21}, + {"(*JSONHandler).Handle", Method, 21}, + {"(*JSONHandler).WithAttrs", Method, 21}, + {"(*JSONHandler).WithGroup", Method, 21}, + {"(*Level).UnmarshalJSON", Method, 21}, + {"(*Level).UnmarshalText", Method, 21}, + {"(*LevelVar).Level", Method, 21}, + {"(*LevelVar).MarshalText", Method, 21}, + {"(*LevelVar).Set", Method, 21}, + {"(*LevelVar).String", Method, 21}, + {"(*LevelVar).UnmarshalText", Method, 21}, + {"(*Logger).Debug", Method, 21}, + {"(*Logger).DebugContext", Method, 21}, + {"(*Logger).Enabled", Method, 21}, + {"(*Logger).Error", Method, 21}, + {"(*Logger).ErrorContext", Method, 21}, + {"(*Logger).Handler", Method, 21}, + {"(*Logger).Info", Method, 21}, + {"(*Logger).InfoContext", Method, 21}, + {"(*Logger).Log", Method, 21}, + {"(*Logger).LogAttrs", Method, 21}, + {"(*Logger).Warn", Method, 21}, + {"(*Logger).WarnContext", Method, 21}, + {"(*Logger).With", Method, 21}, + {"(*Logger).WithGroup", Method, 21}, + {"(*Record).Add", Method, 21}, + {"(*Record).AddAttrs", Method, 21}, + {"(*TextHandler).Enabled", Method, 21}, + {"(*TextHandler).Handle", Method, 21}, + {"(*TextHandler).WithAttrs", Method, 21}, + {"(*TextHandler).WithGroup", Method, 21}, + {"(Attr).Equal", Method, 21}, + {"(Attr).String", Method, 21}, + {"(Kind).String", Method, 21}, + {"(Level).Level", Method, 21}, + {"(Level).MarshalJSON", Method, 21}, + {"(Level).MarshalText", Method, 21}, + {"(Level).String", Method, 21}, + {"(Record).Attrs", Method, 21}, + {"(Record).Clone", Method, 21}, + {"(Record).NumAttrs", Method, 21}, + {"(Value).Any", Method, 21}, + {"(Value).Bool", Method, 21}, + {"(Value).Duration", Method, 21}, + {"(Value).Equal", Method, 21}, + {"(Value).Float64", Method, 21}, + {"(Value).Group", Method, 21}, + {"(Value).Int64", Method, 21}, + {"(Value).Kind", Method, 21}, + {"(Value).LogValuer", Method, 21}, + {"(Value).Resolve", Method, 21}, + {"(Value).String", Method, 21}, + {"(Value).Time", Method, 21}, + {"(Value).Uint64", Method, 21}, + {"Any", Func, 21}, + {"AnyValue", Func, 21}, + {"Attr", Type, 21}, + {"Attr.Key", Field, 21}, + {"Attr.Value", Field, 21}, + {"Bool", Func, 21}, + {"BoolValue", Func, 21}, + {"Debug", Func, 21}, + {"DebugContext", Func, 21}, + {"Default", Func, 21}, + {"Duration", Func, 21}, + {"DurationValue", Func, 21}, + {"Error", Func, 21}, + {"ErrorContext", Func, 21}, + {"Float64", Func, 21}, + {"Float64Value", Func, 21}, + {"Group", Func, 21}, + {"GroupValue", Func, 21}, + {"Handler", Type, 21}, + {"HandlerOptions", Type, 21}, + {"HandlerOptions.AddSource", Field, 21}, + {"HandlerOptions.Level", Field, 21}, + {"HandlerOptions.ReplaceAttr", Field, 21}, + {"Info", Func, 21}, + {"InfoContext", Func, 21}, + {"Int", Func, 21}, + {"Int64", Func, 21}, + {"Int64Value", Func, 21}, + {"IntValue", Func, 21}, + {"JSONHandler", Type, 21}, + {"Kind", Type, 21}, + {"KindAny", Const, 21}, + {"KindBool", Const, 21}, + {"KindDuration", Const, 21}, + {"KindFloat64", Const, 21}, + {"KindGroup", Const, 21}, + {"KindInt64", Const, 21}, + {"KindLogValuer", Const, 21}, + {"KindString", Const, 21}, + {"KindTime", Const, 21}, + {"KindUint64", Const, 21}, + {"Level", Type, 21}, + {"LevelDebug", Const, 21}, + {"LevelError", Const, 21}, + {"LevelInfo", Const, 21}, + {"LevelKey", Const, 21}, + {"LevelVar", Type, 21}, + {"LevelWarn", Const, 21}, + {"Leveler", Type, 21}, + {"Log", Func, 21}, + {"LogAttrs", Func, 21}, + {"LogValuer", Type, 21}, + {"Logger", Type, 21}, + {"MessageKey", Const, 21}, + {"New", Func, 21}, + {"NewJSONHandler", Func, 21}, + {"NewLogLogger", Func, 21}, + {"NewRecord", Func, 21}, + {"NewTextHandler", Func, 21}, + {"Record", Type, 21}, + {"Record.Level", Field, 21}, + {"Record.Message", Field, 21}, + {"Record.PC", Field, 21}, + {"Record.Time", Field, 21}, + {"SetDefault", Func, 21}, + {"SetLogLoggerLevel", Func, 22}, + {"Source", Type, 21}, + {"Source.File", Field, 21}, + {"Source.Function", Field, 21}, + {"Source.Line", Field, 21}, + {"SourceKey", Const, 21}, + {"String", Func, 21}, + {"StringValue", Func, 21}, + {"TextHandler", Type, 21}, + {"Time", Func, 21}, + {"TimeKey", Const, 21}, + {"TimeValue", Func, 21}, + {"Uint64", Func, 21}, + {"Uint64Value", Func, 21}, + {"Value", Type, 21}, + {"Warn", Func, 21}, + {"WarnContext", Func, 21}, + {"With", Func, 21}, + }, + "log/syslog": { + {"(*Writer).Alert", Method, 0}, + {"(*Writer).Close", Method, 0}, + {"(*Writer).Crit", Method, 0}, + {"(*Writer).Debug", Method, 0}, + {"(*Writer).Emerg", Method, 0}, + {"(*Writer).Err", Method, 0}, + {"(*Writer).Info", Method, 0}, + {"(*Writer).Notice", Method, 0}, + {"(*Writer).Warning", Method, 0}, + {"(*Writer).Write", Method, 0}, + {"Dial", Func, 0}, + {"LOG_ALERT", Const, 0}, + {"LOG_AUTH", Const, 1}, + {"LOG_AUTHPRIV", Const, 1}, + {"LOG_CRIT", Const, 0}, + {"LOG_CRON", Const, 1}, + {"LOG_DAEMON", Const, 1}, + {"LOG_DEBUG", Const, 0}, + {"LOG_EMERG", Const, 0}, + {"LOG_ERR", Const, 0}, + {"LOG_FTP", Const, 1}, + {"LOG_INFO", Const, 0}, + {"LOG_KERN", Const, 1}, + {"LOG_LOCAL0", Const, 1}, + {"LOG_LOCAL1", Const, 1}, + {"LOG_LOCAL2", Const, 1}, + {"LOG_LOCAL3", Const, 1}, + {"LOG_LOCAL4", Const, 1}, + {"LOG_LOCAL5", Const, 1}, + {"LOG_LOCAL6", Const, 1}, + {"LOG_LOCAL7", Const, 1}, + {"LOG_LPR", Const, 1}, + {"LOG_MAIL", Const, 1}, + {"LOG_NEWS", Const, 1}, + {"LOG_NOTICE", Const, 0}, + {"LOG_SYSLOG", Const, 1}, + {"LOG_USER", Const, 1}, + {"LOG_UUCP", Const, 1}, + {"LOG_WARNING", Const, 0}, + {"New", Func, 0}, + {"NewLogger", Func, 0}, + {"Priority", Type, 0}, + {"Writer", Type, 0}, + }, + "maps": { + {"All", Func, 23}, + {"Clone", Func, 21}, + {"Collect", Func, 23}, + {"Copy", Func, 21}, + {"DeleteFunc", Func, 21}, + {"Equal", Func, 21}, + {"EqualFunc", Func, 21}, + {"Insert", Func, 23}, + {"Keys", Func, 23}, + {"Values", Func, 23}, + }, + "math": { + {"Abs", Func, 0}, + {"Acos", Func, 0}, + {"Acosh", Func, 0}, + {"Asin", Func, 0}, + {"Asinh", Func, 0}, + {"Atan", Func, 0}, + {"Atan2", Func, 0}, + {"Atanh", Func, 0}, + {"Cbrt", Func, 0}, + {"Ceil", Func, 0}, + {"Copysign", Func, 0}, + {"Cos", Func, 0}, + {"Cosh", Func, 0}, + {"Dim", Func, 0}, + {"E", Const, 0}, + {"Erf", Func, 0}, + {"Erfc", Func, 0}, + {"Erfcinv", Func, 10}, + {"Erfinv", Func, 10}, + {"Exp", Func, 0}, + {"Exp2", Func, 0}, + {"Expm1", Func, 0}, + {"FMA", Func, 14}, + {"Float32bits", Func, 0}, + {"Float32frombits", Func, 0}, + {"Float64bits", Func, 0}, + {"Float64frombits", Func, 0}, + {"Floor", Func, 0}, + {"Frexp", Func, 0}, + {"Gamma", Func, 0}, + {"Hypot", Func, 0}, + {"Ilogb", Func, 0}, + {"Inf", Func, 0}, + {"IsInf", Func, 0}, + {"IsNaN", Func, 0}, + {"J0", Func, 0}, + {"J1", Func, 0}, + {"Jn", Func, 0}, + {"Ldexp", Func, 0}, + {"Lgamma", Func, 0}, + {"Ln10", Const, 0}, + {"Ln2", Const, 0}, + {"Log", Func, 0}, + {"Log10", Func, 0}, + {"Log10E", Const, 0}, + {"Log1p", Func, 0}, + {"Log2", Func, 0}, + {"Log2E", Const, 0}, + {"Logb", Func, 0}, + {"Max", Func, 0}, + {"MaxFloat32", Const, 0}, + {"MaxFloat64", Const, 0}, + {"MaxInt", Const, 17}, + {"MaxInt16", Const, 0}, + {"MaxInt32", Const, 0}, + {"MaxInt64", Const, 0}, + {"MaxInt8", Const, 0}, + {"MaxUint", Const, 17}, + {"MaxUint16", Const, 0}, + {"MaxUint32", Const, 0}, + {"MaxUint64", Const, 0}, + {"MaxUint8", Const, 0}, + {"Min", Func, 0}, + {"MinInt", Const, 17}, + {"MinInt16", Const, 0}, + {"MinInt32", Const, 0}, + {"MinInt64", Const, 0}, + {"MinInt8", Const, 0}, + {"Mod", Func, 0}, + {"Modf", Func, 0}, + {"NaN", Func, 0}, + {"Nextafter", Func, 0}, + {"Nextafter32", Func, 4}, + {"Phi", Const, 0}, + {"Pi", Const, 0}, + {"Pow", Func, 0}, + {"Pow10", Func, 0}, + {"Remainder", Func, 0}, + {"Round", Func, 10}, + {"RoundToEven", Func, 10}, + {"Signbit", Func, 0}, + {"Sin", Func, 0}, + {"Sincos", Func, 0}, + {"Sinh", Func, 0}, + {"SmallestNonzeroFloat32", Const, 0}, + {"SmallestNonzeroFloat64", Const, 0}, + {"Sqrt", Func, 0}, + {"Sqrt2", Const, 0}, + {"SqrtE", Const, 0}, + {"SqrtPhi", Const, 0}, + {"SqrtPi", Const, 0}, + {"Tan", Func, 0}, + {"Tanh", Func, 0}, + {"Trunc", Func, 0}, + {"Y0", Func, 0}, + {"Y1", Func, 0}, + {"Yn", Func, 0}, + }, + "math/big": { + {"(*Float).Abs", Method, 5}, + {"(*Float).Acc", Method, 5}, + {"(*Float).Add", Method, 5}, + {"(*Float).Append", Method, 5}, + {"(*Float).Cmp", Method, 5}, + {"(*Float).Copy", Method, 5}, + {"(*Float).Float32", Method, 5}, + {"(*Float).Float64", Method, 5}, + {"(*Float).Format", Method, 5}, + {"(*Float).GobDecode", Method, 7}, + {"(*Float).GobEncode", Method, 7}, + {"(*Float).Int", Method, 5}, + {"(*Float).Int64", Method, 5}, + {"(*Float).IsInf", Method, 5}, + {"(*Float).IsInt", Method, 5}, + {"(*Float).MantExp", Method, 5}, + {"(*Float).MarshalText", Method, 6}, + {"(*Float).MinPrec", Method, 5}, + {"(*Float).Mode", Method, 5}, + {"(*Float).Mul", Method, 5}, + {"(*Float).Neg", Method, 5}, + {"(*Float).Parse", Method, 5}, + {"(*Float).Prec", Method, 5}, + {"(*Float).Quo", Method, 5}, + {"(*Float).Rat", Method, 5}, + {"(*Float).Scan", Method, 8}, + {"(*Float).Set", Method, 5}, + {"(*Float).SetFloat64", Method, 5}, + {"(*Float).SetInf", Method, 5}, + {"(*Float).SetInt", Method, 5}, + {"(*Float).SetInt64", Method, 5}, + {"(*Float).SetMantExp", Method, 5}, + {"(*Float).SetMode", Method, 5}, + {"(*Float).SetPrec", Method, 5}, + {"(*Float).SetRat", Method, 5}, + {"(*Float).SetString", Method, 5}, + {"(*Float).SetUint64", Method, 5}, + {"(*Float).Sign", Method, 5}, + {"(*Float).Signbit", Method, 5}, + {"(*Float).Sqrt", Method, 10}, + {"(*Float).String", Method, 5}, + {"(*Float).Sub", Method, 5}, + {"(*Float).Text", Method, 5}, + {"(*Float).Uint64", Method, 5}, + {"(*Float).UnmarshalText", Method, 6}, + {"(*Int).Abs", Method, 0}, + {"(*Int).Add", Method, 0}, + {"(*Int).And", Method, 0}, + {"(*Int).AndNot", Method, 0}, + {"(*Int).Append", Method, 6}, + {"(*Int).Binomial", Method, 0}, + {"(*Int).Bit", Method, 0}, + {"(*Int).BitLen", Method, 0}, + {"(*Int).Bits", Method, 0}, + {"(*Int).Bytes", Method, 0}, + {"(*Int).Cmp", Method, 0}, + {"(*Int).CmpAbs", Method, 10}, + {"(*Int).Div", Method, 0}, + {"(*Int).DivMod", Method, 0}, + {"(*Int).Exp", Method, 0}, + {"(*Int).FillBytes", Method, 15}, + {"(*Int).Float64", Method, 21}, + {"(*Int).Format", Method, 0}, + {"(*Int).GCD", Method, 0}, + {"(*Int).GobDecode", Method, 0}, + {"(*Int).GobEncode", Method, 0}, + {"(*Int).Int64", Method, 0}, + {"(*Int).IsInt64", Method, 9}, + {"(*Int).IsUint64", Method, 9}, + {"(*Int).Lsh", Method, 0}, + {"(*Int).MarshalJSON", Method, 1}, + {"(*Int).MarshalText", Method, 3}, + {"(*Int).Mod", Method, 0}, + {"(*Int).ModInverse", Method, 0}, + {"(*Int).ModSqrt", Method, 5}, + {"(*Int).Mul", Method, 0}, + {"(*Int).MulRange", Method, 0}, + {"(*Int).Neg", Method, 0}, + {"(*Int).Not", Method, 0}, + {"(*Int).Or", Method, 0}, + {"(*Int).ProbablyPrime", Method, 0}, + {"(*Int).Quo", Method, 0}, + {"(*Int).QuoRem", Method, 0}, + {"(*Int).Rand", Method, 0}, + {"(*Int).Rem", Method, 0}, + {"(*Int).Rsh", Method, 0}, + {"(*Int).Scan", Method, 0}, + {"(*Int).Set", Method, 0}, + {"(*Int).SetBit", Method, 0}, + {"(*Int).SetBits", Method, 0}, + {"(*Int).SetBytes", Method, 0}, + {"(*Int).SetInt64", Method, 0}, + {"(*Int).SetString", Method, 0}, + {"(*Int).SetUint64", Method, 1}, + {"(*Int).Sign", Method, 0}, + {"(*Int).Sqrt", Method, 8}, + {"(*Int).String", Method, 0}, + {"(*Int).Sub", Method, 0}, + {"(*Int).Text", Method, 6}, + {"(*Int).TrailingZeroBits", Method, 13}, + {"(*Int).Uint64", Method, 1}, + {"(*Int).UnmarshalJSON", Method, 1}, + {"(*Int).UnmarshalText", Method, 3}, + {"(*Int).Xor", Method, 0}, + {"(*Rat).Abs", Method, 0}, + {"(*Rat).Add", Method, 0}, + {"(*Rat).Cmp", Method, 0}, + {"(*Rat).Denom", Method, 0}, + {"(*Rat).Float32", Method, 4}, + {"(*Rat).Float64", Method, 1}, + {"(*Rat).FloatPrec", Method, 22}, + {"(*Rat).FloatString", Method, 0}, + {"(*Rat).GobDecode", Method, 0}, + {"(*Rat).GobEncode", Method, 0}, + {"(*Rat).Inv", Method, 0}, + {"(*Rat).IsInt", Method, 0}, + {"(*Rat).MarshalText", Method, 3}, + {"(*Rat).Mul", Method, 0}, + {"(*Rat).Neg", Method, 0}, + {"(*Rat).Num", Method, 0}, + {"(*Rat).Quo", Method, 0}, + {"(*Rat).RatString", Method, 0}, + {"(*Rat).Scan", Method, 0}, + {"(*Rat).Set", Method, 0}, + {"(*Rat).SetFloat64", Method, 1}, + {"(*Rat).SetFrac", Method, 0}, + {"(*Rat).SetFrac64", Method, 0}, + {"(*Rat).SetInt", Method, 0}, + {"(*Rat).SetInt64", Method, 0}, + {"(*Rat).SetString", Method, 0}, + {"(*Rat).SetUint64", Method, 13}, + {"(*Rat).Sign", Method, 0}, + {"(*Rat).String", Method, 0}, + {"(*Rat).Sub", Method, 0}, + {"(*Rat).UnmarshalText", Method, 3}, + {"(Accuracy).String", Method, 5}, + {"(ErrNaN).Error", Method, 5}, + {"(RoundingMode).String", Method, 5}, + {"Above", Const, 5}, + {"Accuracy", Type, 5}, + {"AwayFromZero", Const, 5}, + {"Below", Const, 5}, + {"ErrNaN", Type, 5}, + {"Exact", Const, 5}, + {"Float", Type, 5}, + {"Int", Type, 0}, + {"Jacobi", Func, 5}, + {"MaxBase", Const, 0}, + {"MaxExp", Const, 5}, + {"MaxPrec", Const, 5}, + {"MinExp", Const, 5}, + {"NewFloat", Func, 5}, + {"NewInt", Func, 0}, + {"NewRat", Func, 0}, + {"ParseFloat", Func, 5}, + {"Rat", Type, 0}, + {"RoundingMode", Type, 5}, + {"ToNearestAway", Const, 5}, + {"ToNearestEven", Const, 5}, + {"ToNegativeInf", Const, 5}, + {"ToPositiveInf", Const, 5}, + {"ToZero", Const, 5}, + {"Word", Type, 0}, + }, + "math/bits": { + {"Add", Func, 12}, + {"Add32", Func, 12}, + {"Add64", Func, 12}, + {"Div", Func, 12}, + {"Div32", Func, 12}, + {"Div64", Func, 12}, + {"LeadingZeros", Func, 9}, + {"LeadingZeros16", Func, 9}, + {"LeadingZeros32", Func, 9}, + {"LeadingZeros64", Func, 9}, + {"LeadingZeros8", Func, 9}, + {"Len", Func, 9}, + {"Len16", Func, 9}, + {"Len32", Func, 9}, + {"Len64", Func, 9}, + {"Len8", Func, 9}, + {"Mul", Func, 12}, + {"Mul32", Func, 12}, + {"Mul64", Func, 12}, + {"OnesCount", Func, 9}, + {"OnesCount16", Func, 9}, + {"OnesCount32", Func, 9}, + {"OnesCount64", Func, 9}, + {"OnesCount8", Func, 9}, + {"Rem", Func, 14}, + {"Rem32", Func, 14}, + {"Rem64", Func, 14}, + {"Reverse", Func, 9}, + {"Reverse16", Func, 9}, + {"Reverse32", Func, 9}, + {"Reverse64", Func, 9}, + {"Reverse8", Func, 9}, + {"ReverseBytes", Func, 9}, + {"ReverseBytes16", Func, 9}, + {"ReverseBytes32", Func, 9}, + {"ReverseBytes64", Func, 9}, + {"RotateLeft", Func, 9}, + {"RotateLeft16", Func, 9}, + {"RotateLeft32", Func, 9}, + {"RotateLeft64", Func, 9}, + {"RotateLeft8", Func, 9}, + {"Sub", Func, 12}, + {"Sub32", Func, 12}, + {"Sub64", Func, 12}, + {"TrailingZeros", Func, 9}, + {"TrailingZeros16", Func, 9}, + {"TrailingZeros32", Func, 9}, + {"TrailingZeros64", Func, 9}, + {"TrailingZeros8", Func, 9}, + {"UintSize", Const, 9}, + }, + "math/cmplx": { + {"Abs", Func, 0}, + {"Acos", Func, 0}, + {"Acosh", Func, 0}, + {"Asin", Func, 0}, + {"Asinh", Func, 0}, + {"Atan", Func, 0}, + {"Atanh", Func, 0}, + {"Conj", Func, 0}, + {"Cos", Func, 0}, + {"Cosh", Func, 0}, + {"Cot", Func, 0}, + {"Exp", Func, 0}, + {"Inf", Func, 0}, + {"IsInf", Func, 0}, + {"IsNaN", Func, 0}, + {"Log", Func, 0}, + {"Log10", Func, 0}, + {"NaN", Func, 0}, + {"Phase", Func, 0}, + {"Polar", Func, 0}, + {"Pow", Func, 0}, + {"Rect", Func, 0}, + {"Sin", Func, 0}, + {"Sinh", Func, 0}, + {"Sqrt", Func, 0}, + {"Tan", Func, 0}, + {"Tanh", Func, 0}, + }, + "math/rand": { + {"(*Rand).ExpFloat64", Method, 0}, + {"(*Rand).Float32", Method, 0}, + {"(*Rand).Float64", Method, 0}, + {"(*Rand).Int", Method, 0}, + {"(*Rand).Int31", Method, 0}, + {"(*Rand).Int31n", Method, 0}, + {"(*Rand).Int63", Method, 0}, + {"(*Rand).Int63n", Method, 0}, + {"(*Rand).Intn", Method, 0}, + {"(*Rand).NormFloat64", Method, 0}, + {"(*Rand).Perm", Method, 0}, + {"(*Rand).Read", Method, 6}, + {"(*Rand).Seed", Method, 0}, + {"(*Rand).Shuffle", Method, 10}, + {"(*Rand).Uint32", Method, 0}, + {"(*Rand).Uint64", Method, 8}, + {"(*Zipf).Uint64", Method, 0}, + {"ExpFloat64", Func, 0}, + {"Float32", Func, 0}, + {"Float64", Func, 0}, + {"Int", Func, 0}, + {"Int31", Func, 0}, + {"Int31n", Func, 0}, + {"Int63", Func, 0}, + {"Int63n", Func, 0}, + {"Intn", Func, 0}, + {"New", Func, 0}, + {"NewSource", Func, 0}, + {"NewZipf", Func, 0}, + {"NormFloat64", Func, 0}, + {"Perm", Func, 0}, + {"Rand", Type, 0}, + {"Read", Func, 6}, + {"Seed", Func, 0}, + {"Shuffle", Func, 10}, + {"Source", Type, 0}, + {"Source64", Type, 8}, + {"Uint32", Func, 0}, + {"Uint64", Func, 8}, + {"Zipf", Type, 0}, + }, + "math/rand/v2": { + {"(*ChaCha8).MarshalBinary", Method, 22}, + {"(*ChaCha8).Read", Method, 23}, + {"(*ChaCha8).Seed", Method, 22}, + {"(*ChaCha8).Uint64", Method, 22}, + {"(*ChaCha8).UnmarshalBinary", Method, 22}, + {"(*PCG).MarshalBinary", Method, 22}, + {"(*PCG).Seed", Method, 22}, + {"(*PCG).Uint64", Method, 22}, + {"(*PCG).UnmarshalBinary", Method, 22}, + {"(*Rand).ExpFloat64", Method, 22}, + {"(*Rand).Float32", Method, 22}, + {"(*Rand).Float64", Method, 22}, + {"(*Rand).Int", Method, 22}, + {"(*Rand).Int32", Method, 22}, + {"(*Rand).Int32N", Method, 22}, + {"(*Rand).Int64", Method, 22}, + {"(*Rand).Int64N", Method, 22}, + {"(*Rand).IntN", Method, 22}, + {"(*Rand).NormFloat64", Method, 22}, + {"(*Rand).Perm", Method, 22}, + {"(*Rand).Shuffle", Method, 22}, + {"(*Rand).Uint", Method, 23}, + {"(*Rand).Uint32", Method, 22}, + {"(*Rand).Uint32N", Method, 22}, + {"(*Rand).Uint64", Method, 22}, + {"(*Rand).Uint64N", Method, 22}, + {"(*Rand).UintN", Method, 22}, + {"(*Zipf).Uint64", Method, 22}, + {"ChaCha8", Type, 22}, + {"ExpFloat64", Func, 22}, + {"Float32", Func, 22}, + {"Float64", Func, 22}, + {"Int", Func, 22}, + {"Int32", Func, 22}, + {"Int32N", Func, 22}, + {"Int64", Func, 22}, + {"Int64N", Func, 22}, + {"IntN", Func, 22}, + {"N", Func, 22}, + {"New", Func, 22}, + {"NewChaCha8", Func, 22}, + {"NewPCG", Func, 22}, + {"NewZipf", Func, 22}, + {"NormFloat64", Func, 22}, + {"PCG", Type, 22}, + {"Perm", Func, 22}, + {"Rand", Type, 22}, + {"Shuffle", Func, 22}, + {"Source", Type, 22}, + {"Uint", Func, 23}, + {"Uint32", Func, 22}, + {"Uint32N", Func, 22}, + {"Uint64", Func, 22}, + {"Uint64N", Func, 22}, + {"UintN", Func, 22}, + {"Zipf", Type, 22}, + }, + "mime": { + {"(*WordDecoder).Decode", Method, 5}, + {"(*WordDecoder).DecodeHeader", Method, 5}, + {"(WordEncoder).Encode", Method, 5}, + {"AddExtensionType", Func, 0}, + {"BEncoding", Const, 5}, + {"ErrInvalidMediaParameter", Var, 9}, + {"ExtensionsByType", Func, 5}, + {"FormatMediaType", Func, 0}, + {"ParseMediaType", Func, 0}, + {"QEncoding", Const, 5}, + {"TypeByExtension", Func, 0}, + {"WordDecoder", Type, 5}, + {"WordDecoder.CharsetReader", Field, 5}, + {"WordEncoder", Type, 5}, + }, + "mime/multipart": { + {"(*FileHeader).Open", Method, 0}, + {"(*Form).RemoveAll", Method, 0}, + {"(*Part).Close", Method, 0}, + {"(*Part).FileName", Method, 0}, + {"(*Part).FormName", Method, 0}, + {"(*Part).Read", Method, 0}, + {"(*Reader).NextPart", Method, 0}, + {"(*Reader).NextRawPart", Method, 14}, + {"(*Reader).ReadForm", Method, 0}, + {"(*Writer).Boundary", Method, 0}, + {"(*Writer).Close", Method, 0}, + {"(*Writer).CreateFormField", Method, 0}, + {"(*Writer).CreateFormFile", Method, 0}, + {"(*Writer).CreatePart", Method, 0}, + {"(*Writer).FormDataContentType", Method, 0}, + {"(*Writer).SetBoundary", Method, 1}, + {"(*Writer).WriteField", Method, 0}, + {"ErrMessageTooLarge", Var, 9}, + {"File", Type, 0}, + {"FileHeader", Type, 0}, + {"FileHeader.Filename", Field, 0}, + {"FileHeader.Header", Field, 0}, + {"FileHeader.Size", Field, 9}, + {"Form", Type, 0}, + {"Form.File", Field, 0}, + {"Form.Value", Field, 0}, + {"NewReader", Func, 0}, + {"NewWriter", Func, 0}, + {"Part", Type, 0}, + {"Part.Header", Field, 0}, + {"Reader", Type, 0}, + {"Writer", Type, 0}, + }, + "mime/quotedprintable": { + {"(*Reader).Read", Method, 5}, + {"(*Writer).Close", Method, 5}, + {"(*Writer).Write", Method, 5}, + {"NewReader", Func, 5}, + {"NewWriter", Func, 5}, + {"Reader", Type, 5}, + {"Writer", Type, 5}, + {"Writer.Binary", Field, 5}, + }, + "net": { + {"(*AddrError).Error", Method, 0}, + {"(*AddrError).Temporary", Method, 0}, + {"(*AddrError).Timeout", Method, 0}, + {"(*Buffers).Read", Method, 8}, + {"(*Buffers).WriteTo", Method, 8}, + {"(*DNSConfigError).Error", Method, 0}, + {"(*DNSConfigError).Temporary", Method, 0}, + {"(*DNSConfigError).Timeout", Method, 0}, + {"(*DNSConfigError).Unwrap", Method, 13}, + {"(*DNSError).Error", Method, 0}, + {"(*DNSError).Temporary", Method, 0}, + {"(*DNSError).Timeout", Method, 0}, + {"(*DNSError).Unwrap", Method, 23}, + {"(*Dialer).Dial", Method, 1}, + {"(*Dialer).DialContext", Method, 7}, + {"(*Dialer).MultipathTCP", Method, 21}, + {"(*Dialer).SetMultipathTCP", Method, 21}, + {"(*IP).UnmarshalText", Method, 2}, + {"(*IPAddr).Network", Method, 0}, + {"(*IPAddr).String", Method, 0}, + {"(*IPConn).Close", Method, 0}, + {"(*IPConn).File", Method, 0}, + {"(*IPConn).LocalAddr", Method, 0}, + {"(*IPConn).Read", Method, 0}, + {"(*IPConn).ReadFrom", Method, 0}, + {"(*IPConn).ReadFromIP", Method, 0}, + {"(*IPConn).ReadMsgIP", Method, 1}, + {"(*IPConn).RemoteAddr", Method, 0}, + {"(*IPConn).SetDeadline", Method, 0}, + {"(*IPConn).SetReadBuffer", Method, 0}, + {"(*IPConn).SetReadDeadline", Method, 0}, + {"(*IPConn).SetWriteBuffer", Method, 0}, + {"(*IPConn).SetWriteDeadline", Method, 0}, + {"(*IPConn).SyscallConn", Method, 9}, + {"(*IPConn).Write", Method, 0}, + {"(*IPConn).WriteMsgIP", Method, 1}, + {"(*IPConn).WriteTo", Method, 0}, + {"(*IPConn).WriteToIP", Method, 0}, + {"(*IPNet).Contains", Method, 0}, + {"(*IPNet).Network", Method, 0}, + {"(*IPNet).String", Method, 0}, + {"(*Interface).Addrs", Method, 0}, + {"(*Interface).MulticastAddrs", Method, 0}, + {"(*ListenConfig).Listen", Method, 11}, + {"(*ListenConfig).ListenPacket", Method, 11}, + {"(*ListenConfig).MultipathTCP", Method, 21}, + {"(*ListenConfig).SetMultipathTCP", Method, 21}, + {"(*OpError).Error", Method, 0}, + {"(*OpError).Temporary", Method, 0}, + {"(*OpError).Timeout", Method, 0}, + {"(*OpError).Unwrap", Method, 13}, + {"(*ParseError).Error", Method, 0}, + {"(*ParseError).Temporary", Method, 17}, + {"(*ParseError).Timeout", Method, 17}, + {"(*Resolver).LookupAddr", Method, 8}, + {"(*Resolver).LookupCNAME", Method, 8}, + {"(*Resolver).LookupHost", Method, 8}, + {"(*Resolver).LookupIP", Method, 15}, + {"(*Resolver).LookupIPAddr", Method, 8}, + {"(*Resolver).LookupMX", Method, 8}, + {"(*Resolver).LookupNS", Method, 8}, + {"(*Resolver).LookupNetIP", Method, 18}, + {"(*Resolver).LookupPort", Method, 8}, + {"(*Resolver).LookupSRV", Method, 8}, + {"(*Resolver).LookupTXT", Method, 8}, + {"(*TCPAddr).AddrPort", Method, 18}, + {"(*TCPAddr).Network", Method, 0}, + {"(*TCPAddr).String", Method, 0}, + {"(*TCPConn).Close", Method, 0}, + {"(*TCPConn).CloseRead", Method, 0}, + {"(*TCPConn).CloseWrite", Method, 0}, + {"(*TCPConn).File", Method, 0}, + {"(*TCPConn).LocalAddr", Method, 0}, + {"(*TCPConn).MultipathTCP", Method, 21}, + {"(*TCPConn).Read", Method, 0}, + {"(*TCPConn).ReadFrom", Method, 0}, + {"(*TCPConn).RemoteAddr", Method, 0}, + {"(*TCPConn).SetDeadline", Method, 0}, + {"(*TCPConn).SetKeepAlive", Method, 0}, + {"(*TCPConn).SetKeepAliveConfig", Method, 23}, + {"(*TCPConn).SetKeepAlivePeriod", Method, 2}, + {"(*TCPConn).SetLinger", Method, 0}, + {"(*TCPConn).SetNoDelay", Method, 0}, + {"(*TCPConn).SetReadBuffer", Method, 0}, + {"(*TCPConn).SetReadDeadline", Method, 0}, + {"(*TCPConn).SetWriteBuffer", Method, 0}, + {"(*TCPConn).SetWriteDeadline", Method, 0}, + {"(*TCPConn).SyscallConn", Method, 9}, + {"(*TCPConn).Write", Method, 0}, + {"(*TCPConn).WriteTo", Method, 22}, + {"(*TCPListener).Accept", Method, 0}, + {"(*TCPListener).AcceptTCP", Method, 0}, + {"(*TCPListener).Addr", Method, 0}, + {"(*TCPListener).Close", Method, 0}, + {"(*TCPListener).File", Method, 0}, + {"(*TCPListener).SetDeadline", Method, 0}, + {"(*TCPListener).SyscallConn", Method, 10}, + {"(*UDPAddr).AddrPort", Method, 18}, + {"(*UDPAddr).Network", Method, 0}, + {"(*UDPAddr).String", Method, 0}, + {"(*UDPConn).Close", Method, 0}, + {"(*UDPConn).File", Method, 0}, + {"(*UDPConn).LocalAddr", Method, 0}, + {"(*UDPConn).Read", Method, 0}, + {"(*UDPConn).ReadFrom", Method, 0}, + {"(*UDPConn).ReadFromUDP", Method, 0}, + {"(*UDPConn).ReadFromUDPAddrPort", Method, 18}, + {"(*UDPConn).ReadMsgUDP", Method, 1}, + {"(*UDPConn).ReadMsgUDPAddrPort", Method, 18}, + {"(*UDPConn).RemoteAddr", Method, 0}, + {"(*UDPConn).SetDeadline", Method, 0}, + {"(*UDPConn).SetReadBuffer", Method, 0}, + {"(*UDPConn).SetReadDeadline", Method, 0}, + {"(*UDPConn).SetWriteBuffer", Method, 0}, + {"(*UDPConn).SetWriteDeadline", Method, 0}, + {"(*UDPConn).SyscallConn", Method, 9}, + {"(*UDPConn).Write", Method, 0}, + {"(*UDPConn).WriteMsgUDP", Method, 1}, + {"(*UDPConn).WriteMsgUDPAddrPort", Method, 18}, + {"(*UDPConn).WriteTo", Method, 0}, + {"(*UDPConn).WriteToUDP", Method, 0}, + {"(*UDPConn).WriteToUDPAddrPort", Method, 18}, + {"(*UnixAddr).Network", Method, 0}, + {"(*UnixAddr).String", Method, 0}, + {"(*UnixConn).Close", Method, 0}, + {"(*UnixConn).CloseRead", Method, 1}, + {"(*UnixConn).CloseWrite", Method, 1}, + {"(*UnixConn).File", Method, 0}, + {"(*UnixConn).LocalAddr", Method, 0}, + {"(*UnixConn).Read", Method, 0}, + {"(*UnixConn).ReadFrom", Method, 0}, + {"(*UnixConn).ReadFromUnix", Method, 0}, + {"(*UnixConn).ReadMsgUnix", Method, 0}, + {"(*UnixConn).RemoteAddr", Method, 0}, + {"(*UnixConn).SetDeadline", Method, 0}, + {"(*UnixConn).SetReadBuffer", Method, 0}, + {"(*UnixConn).SetReadDeadline", Method, 0}, + {"(*UnixConn).SetWriteBuffer", Method, 0}, + {"(*UnixConn).SetWriteDeadline", Method, 0}, + {"(*UnixConn).SyscallConn", Method, 9}, + {"(*UnixConn).Write", Method, 0}, + {"(*UnixConn).WriteMsgUnix", Method, 0}, + {"(*UnixConn).WriteTo", Method, 0}, + {"(*UnixConn).WriteToUnix", Method, 0}, + {"(*UnixListener).Accept", Method, 0}, + {"(*UnixListener).AcceptUnix", Method, 0}, + {"(*UnixListener).Addr", Method, 0}, + {"(*UnixListener).Close", Method, 0}, + {"(*UnixListener).File", Method, 0}, + {"(*UnixListener).SetDeadline", Method, 0}, + {"(*UnixListener).SetUnlinkOnClose", Method, 8}, + {"(*UnixListener).SyscallConn", Method, 10}, + {"(Flags).String", Method, 0}, + {"(HardwareAddr).String", Method, 0}, + {"(IP).DefaultMask", Method, 0}, + {"(IP).Equal", Method, 0}, + {"(IP).IsGlobalUnicast", Method, 0}, + {"(IP).IsInterfaceLocalMulticast", Method, 0}, + {"(IP).IsLinkLocalMulticast", Method, 0}, + {"(IP).IsLinkLocalUnicast", Method, 0}, + {"(IP).IsLoopback", Method, 0}, + {"(IP).IsMulticast", Method, 0}, + {"(IP).IsPrivate", Method, 17}, + {"(IP).IsUnspecified", Method, 0}, + {"(IP).MarshalText", Method, 2}, + {"(IP).Mask", Method, 0}, + {"(IP).String", Method, 0}, + {"(IP).To16", Method, 0}, + {"(IP).To4", Method, 0}, + {"(IPMask).Size", Method, 0}, + {"(IPMask).String", Method, 0}, + {"(InvalidAddrError).Error", Method, 0}, + {"(InvalidAddrError).Temporary", Method, 0}, + {"(InvalidAddrError).Timeout", Method, 0}, + {"(UnknownNetworkError).Error", Method, 0}, + {"(UnknownNetworkError).Temporary", Method, 0}, + {"(UnknownNetworkError).Timeout", Method, 0}, + {"Addr", Type, 0}, + {"AddrError", Type, 0}, + {"AddrError.Addr", Field, 0}, + {"AddrError.Err", Field, 0}, + {"Buffers", Type, 8}, + {"CIDRMask", Func, 0}, + {"Conn", Type, 0}, + {"DNSConfigError", Type, 0}, + {"DNSConfigError.Err", Field, 0}, + {"DNSError", Type, 0}, + {"DNSError.Err", Field, 0}, + {"DNSError.IsNotFound", Field, 13}, + {"DNSError.IsTemporary", Field, 6}, + {"DNSError.IsTimeout", Field, 0}, + {"DNSError.Name", Field, 0}, + {"DNSError.Server", Field, 0}, + {"DNSError.UnwrapErr", Field, 23}, + {"DefaultResolver", Var, 8}, + {"Dial", Func, 0}, + {"DialIP", Func, 0}, + {"DialTCP", Func, 0}, + {"DialTimeout", Func, 0}, + {"DialUDP", Func, 0}, + {"DialUnix", Func, 0}, + {"Dialer", Type, 1}, + {"Dialer.Cancel", Field, 6}, + {"Dialer.Control", Field, 11}, + {"Dialer.ControlContext", Field, 20}, + {"Dialer.Deadline", Field, 1}, + {"Dialer.DualStack", Field, 2}, + {"Dialer.FallbackDelay", Field, 5}, + {"Dialer.KeepAlive", Field, 3}, + {"Dialer.KeepAliveConfig", Field, 23}, + {"Dialer.LocalAddr", Field, 1}, + {"Dialer.Resolver", Field, 8}, + {"Dialer.Timeout", Field, 1}, + {"ErrClosed", Var, 16}, + {"ErrWriteToConnected", Var, 0}, + {"Error", Type, 0}, + {"FileConn", Func, 0}, + {"FileListener", Func, 0}, + {"FilePacketConn", Func, 0}, + {"FlagBroadcast", Const, 0}, + {"FlagLoopback", Const, 0}, + {"FlagMulticast", Const, 0}, + {"FlagPointToPoint", Const, 0}, + {"FlagRunning", Const, 20}, + {"FlagUp", Const, 0}, + {"Flags", Type, 0}, + {"HardwareAddr", Type, 0}, + {"IP", Type, 0}, + {"IPAddr", Type, 0}, + {"IPAddr.IP", Field, 0}, + {"IPAddr.Zone", Field, 1}, + {"IPConn", Type, 0}, + {"IPMask", Type, 0}, + {"IPNet", Type, 0}, + {"IPNet.IP", Field, 0}, + {"IPNet.Mask", Field, 0}, + {"IPv4", Func, 0}, + {"IPv4Mask", Func, 0}, + {"IPv4allrouter", Var, 0}, + {"IPv4allsys", Var, 0}, + {"IPv4bcast", Var, 0}, + {"IPv4len", Const, 0}, + {"IPv4zero", Var, 0}, + {"IPv6interfacelocalallnodes", Var, 0}, + {"IPv6len", Const, 0}, + {"IPv6linklocalallnodes", Var, 0}, + {"IPv6linklocalallrouters", Var, 0}, + {"IPv6loopback", Var, 0}, + {"IPv6unspecified", Var, 0}, + {"IPv6zero", Var, 0}, + {"Interface", Type, 0}, + {"Interface.Flags", Field, 0}, + {"Interface.HardwareAddr", Field, 0}, + {"Interface.Index", Field, 0}, + {"Interface.MTU", Field, 0}, + {"Interface.Name", Field, 0}, + {"InterfaceAddrs", Func, 0}, + {"InterfaceByIndex", Func, 0}, + {"InterfaceByName", Func, 0}, + {"Interfaces", Func, 0}, + {"InvalidAddrError", Type, 0}, + {"JoinHostPort", Func, 0}, + {"KeepAliveConfig", Type, 23}, + {"KeepAliveConfig.Count", Field, 23}, + {"KeepAliveConfig.Enable", Field, 23}, + {"KeepAliveConfig.Idle", Field, 23}, + {"KeepAliveConfig.Interval", Field, 23}, + {"Listen", Func, 0}, + {"ListenConfig", Type, 11}, + {"ListenConfig.Control", Field, 11}, + {"ListenConfig.KeepAlive", Field, 13}, + {"ListenConfig.KeepAliveConfig", Field, 23}, + {"ListenIP", Func, 0}, + {"ListenMulticastUDP", Func, 0}, + {"ListenPacket", Func, 0}, + {"ListenTCP", Func, 0}, + {"ListenUDP", Func, 0}, + {"ListenUnix", Func, 0}, + {"ListenUnixgram", Func, 0}, + {"Listener", Type, 0}, + {"LookupAddr", Func, 0}, + {"LookupCNAME", Func, 0}, + {"LookupHost", Func, 0}, + {"LookupIP", Func, 0}, + {"LookupMX", Func, 0}, + {"LookupNS", Func, 1}, + {"LookupPort", Func, 0}, + {"LookupSRV", Func, 0}, + {"LookupTXT", Func, 0}, + {"MX", Type, 0}, + {"MX.Host", Field, 0}, + {"MX.Pref", Field, 0}, + {"NS", Type, 1}, + {"NS.Host", Field, 1}, + {"OpError", Type, 0}, + {"OpError.Addr", Field, 0}, + {"OpError.Err", Field, 0}, + {"OpError.Net", Field, 0}, + {"OpError.Op", Field, 0}, + {"OpError.Source", Field, 5}, + {"PacketConn", Type, 0}, + {"ParseCIDR", Func, 0}, + {"ParseError", Type, 0}, + {"ParseError.Text", Field, 0}, + {"ParseError.Type", Field, 0}, + {"ParseIP", Func, 0}, + {"ParseMAC", Func, 0}, + {"Pipe", Func, 0}, + {"ResolveIPAddr", Func, 0}, + {"ResolveTCPAddr", Func, 0}, + {"ResolveUDPAddr", Func, 0}, + {"ResolveUnixAddr", Func, 0}, + {"Resolver", Type, 8}, + {"Resolver.Dial", Field, 9}, + {"Resolver.PreferGo", Field, 8}, + {"Resolver.StrictErrors", Field, 9}, + {"SRV", Type, 0}, + {"SRV.Port", Field, 0}, + {"SRV.Priority", Field, 0}, + {"SRV.Target", Field, 0}, + {"SRV.Weight", Field, 0}, + {"SplitHostPort", Func, 0}, + {"TCPAddr", Type, 0}, + {"TCPAddr.IP", Field, 0}, + {"TCPAddr.Port", Field, 0}, + {"TCPAddr.Zone", Field, 1}, + {"TCPAddrFromAddrPort", Func, 18}, + {"TCPConn", Type, 0}, + {"TCPListener", Type, 0}, + {"UDPAddr", Type, 0}, + {"UDPAddr.IP", Field, 0}, + {"UDPAddr.Port", Field, 0}, + {"UDPAddr.Zone", Field, 1}, + {"UDPAddrFromAddrPort", Func, 18}, + {"UDPConn", Type, 0}, + {"UnixAddr", Type, 0}, + {"UnixAddr.Name", Field, 0}, + {"UnixAddr.Net", Field, 0}, + {"UnixConn", Type, 0}, + {"UnixListener", Type, 0}, + {"UnknownNetworkError", Type, 0}, + }, + "net/http": { + {"(*Client).CloseIdleConnections", Method, 12}, + {"(*Client).Do", Method, 0}, + {"(*Client).Get", Method, 0}, + {"(*Client).Head", Method, 0}, + {"(*Client).Post", Method, 0}, + {"(*Client).PostForm", Method, 0}, + {"(*Cookie).String", Method, 0}, + {"(*Cookie).Valid", Method, 18}, + {"(*MaxBytesError).Error", Method, 19}, + {"(*ProtocolError).Error", Method, 0}, + {"(*ProtocolError).Is", Method, 21}, + {"(*Request).AddCookie", Method, 0}, + {"(*Request).BasicAuth", Method, 4}, + {"(*Request).Clone", Method, 13}, + {"(*Request).Context", Method, 7}, + {"(*Request).Cookie", Method, 0}, + {"(*Request).Cookies", Method, 0}, + {"(*Request).CookiesNamed", Method, 23}, + {"(*Request).FormFile", Method, 0}, + {"(*Request).FormValue", Method, 0}, + {"(*Request).MultipartReader", Method, 0}, + {"(*Request).ParseForm", Method, 0}, + {"(*Request).ParseMultipartForm", Method, 0}, + {"(*Request).PathValue", Method, 22}, + {"(*Request).PostFormValue", Method, 1}, + {"(*Request).ProtoAtLeast", Method, 0}, + {"(*Request).Referer", Method, 0}, + {"(*Request).SetBasicAuth", Method, 0}, + {"(*Request).SetPathValue", Method, 22}, + {"(*Request).UserAgent", Method, 0}, + {"(*Request).WithContext", Method, 7}, + {"(*Request).Write", Method, 0}, + {"(*Request).WriteProxy", Method, 0}, + {"(*Response).Cookies", Method, 0}, + {"(*Response).Location", Method, 0}, + {"(*Response).ProtoAtLeast", Method, 0}, + {"(*Response).Write", Method, 0}, + {"(*ResponseController).EnableFullDuplex", Method, 21}, + {"(*ResponseController).Flush", Method, 20}, + {"(*ResponseController).Hijack", Method, 20}, + {"(*ResponseController).SetReadDeadline", Method, 20}, + {"(*ResponseController).SetWriteDeadline", Method, 20}, + {"(*ServeMux).Handle", Method, 0}, + {"(*ServeMux).HandleFunc", Method, 0}, + {"(*ServeMux).Handler", Method, 1}, + {"(*ServeMux).ServeHTTP", Method, 0}, + {"(*Server).Close", Method, 8}, + {"(*Server).ListenAndServe", Method, 0}, + {"(*Server).ListenAndServeTLS", Method, 0}, + {"(*Server).RegisterOnShutdown", Method, 9}, + {"(*Server).Serve", Method, 0}, + {"(*Server).ServeTLS", Method, 9}, + {"(*Server).SetKeepAlivesEnabled", Method, 3}, + {"(*Server).Shutdown", Method, 8}, + {"(*Transport).CancelRequest", Method, 1}, + {"(*Transport).Clone", Method, 13}, + {"(*Transport).CloseIdleConnections", Method, 0}, + {"(*Transport).RegisterProtocol", Method, 0}, + {"(*Transport).RoundTrip", Method, 0}, + {"(ConnState).String", Method, 3}, + {"(Dir).Open", Method, 0}, + {"(HandlerFunc).ServeHTTP", Method, 0}, + {"(Header).Add", Method, 0}, + {"(Header).Clone", Method, 13}, + {"(Header).Del", Method, 0}, + {"(Header).Get", Method, 0}, + {"(Header).Set", Method, 0}, + {"(Header).Values", Method, 14}, + {"(Header).Write", Method, 0}, + {"(Header).WriteSubset", Method, 0}, + {"AllowQuerySemicolons", Func, 17}, + {"CanonicalHeaderKey", Func, 0}, + {"Client", Type, 0}, + {"Client.CheckRedirect", Field, 0}, + {"Client.Jar", Field, 0}, + {"Client.Timeout", Field, 3}, + {"Client.Transport", Field, 0}, + {"CloseNotifier", Type, 1}, + {"ConnState", Type, 3}, + {"Cookie", Type, 0}, + {"Cookie.Domain", Field, 0}, + {"Cookie.Expires", Field, 0}, + {"Cookie.HttpOnly", Field, 0}, + {"Cookie.MaxAge", Field, 0}, + {"Cookie.Name", Field, 0}, + {"Cookie.Partitioned", Field, 23}, + {"Cookie.Path", Field, 0}, + {"Cookie.Quoted", Field, 23}, + {"Cookie.Raw", Field, 0}, + {"Cookie.RawExpires", Field, 0}, + {"Cookie.SameSite", Field, 11}, + {"Cookie.Secure", Field, 0}, + {"Cookie.Unparsed", Field, 0}, + {"Cookie.Value", Field, 0}, + {"CookieJar", Type, 0}, + {"DefaultClient", Var, 0}, + {"DefaultMaxHeaderBytes", Const, 0}, + {"DefaultMaxIdleConnsPerHost", Const, 0}, + {"DefaultServeMux", Var, 0}, + {"DefaultTransport", Var, 0}, + {"DetectContentType", Func, 0}, + {"Dir", Type, 0}, + {"ErrAbortHandler", Var, 8}, + {"ErrBodyNotAllowed", Var, 0}, + {"ErrBodyReadAfterClose", Var, 0}, + {"ErrContentLength", Var, 0}, + {"ErrHandlerTimeout", Var, 0}, + {"ErrHeaderTooLong", Var, 0}, + {"ErrHijacked", Var, 0}, + {"ErrLineTooLong", Var, 0}, + {"ErrMissingBoundary", Var, 0}, + {"ErrMissingContentLength", Var, 0}, + {"ErrMissingFile", Var, 0}, + {"ErrNoCookie", Var, 0}, + {"ErrNoLocation", Var, 0}, + {"ErrNotMultipart", Var, 0}, + {"ErrNotSupported", Var, 0}, + {"ErrSchemeMismatch", Var, 21}, + {"ErrServerClosed", Var, 8}, + {"ErrShortBody", Var, 0}, + {"ErrSkipAltProtocol", Var, 6}, + {"ErrUnexpectedTrailer", Var, 0}, + {"ErrUseLastResponse", Var, 7}, + {"ErrWriteAfterFlush", Var, 0}, + {"Error", Func, 0}, + {"FS", Func, 16}, + {"File", Type, 0}, + {"FileServer", Func, 0}, + {"FileServerFS", Func, 22}, + {"FileSystem", Type, 0}, + {"Flusher", Type, 0}, + {"Get", Func, 0}, + {"Handle", Func, 0}, + {"HandleFunc", Func, 0}, + {"Handler", Type, 0}, + {"HandlerFunc", Type, 0}, + {"Head", Func, 0}, + {"Header", Type, 0}, + {"Hijacker", Type, 0}, + {"ListenAndServe", Func, 0}, + {"ListenAndServeTLS", Func, 0}, + {"LocalAddrContextKey", Var, 7}, + {"MaxBytesError", Type, 19}, + {"MaxBytesError.Limit", Field, 19}, + {"MaxBytesHandler", Func, 18}, + {"MaxBytesReader", Func, 0}, + {"MethodConnect", Const, 6}, + {"MethodDelete", Const, 6}, + {"MethodGet", Const, 6}, + {"MethodHead", Const, 6}, + {"MethodOptions", Const, 6}, + {"MethodPatch", Const, 6}, + {"MethodPost", Const, 6}, + {"MethodPut", Const, 6}, + {"MethodTrace", Const, 6}, + {"NewFileTransport", Func, 0}, + {"NewFileTransportFS", Func, 22}, + {"NewRequest", Func, 0}, + {"NewRequestWithContext", Func, 13}, + {"NewResponseController", Func, 20}, + {"NewServeMux", Func, 0}, + {"NoBody", Var, 8}, + {"NotFound", Func, 0}, + {"NotFoundHandler", Func, 0}, + {"ParseCookie", Func, 23}, + {"ParseHTTPVersion", Func, 0}, + {"ParseSetCookie", Func, 23}, + {"ParseTime", Func, 1}, + {"Post", Func, 0}, + {"PostForm", Func, 0}, + {"ProtocolError", Type, 0}, + {"ProtocolError.ErrorString", Field, 0}, + {"ProxyFromEnvironment", Func, 0}, + {"ProxyURL", Func, 0}, + {"PushOptions", Type, 8}, + {"PushOptions.Header", Field, 8}, + {"PushOptions.Method", Field, 8}, + {"Pusher", Type, 8}, + {"ReadRequest", Func, 0}, + {"ReadResponse", Func, 0}, + {"Redirect", Func, 0}, + {"RedirectHandler", Func, 0}, + {"Request", Type, 0}, + {"Request.Body", Field, 0}, + {"Request.Cancel", Field, 5}, + {"Request.Close", Field, 0}, + {"Request.ContentLength", Field, 0}, + {"Request.Form", Field, 0}, + {"Request.GetBody", Field, 8}, + {"Request.Header", Field, 0}, + {"Request.Host", Field, 0}, + {"Request.Method", Field, 0}, + {"Request.MultipartForm", Field, 0}, + {"Request.Pattern", Field, 23}, + {"Request.PostForm", Field, 1}, + {"Request.Proto", Field, 0}, + {"Request.ProtoMajor", Field, 0}, + {"Request.ProtoMinor", Field, 0}, + {"Request.RemoteAddr", Field, 0}, + {"Request.RequestURI", Field, 0}, + {"Request.Response", Field, 7}, + {"Request.TLS", Field, 0}, + {"Request.Trailer", Field, 0}, + {"Request.TransferEncoding", Field, 0}, + {"Request.URL", Field, 0}, + {"Response", Type, 0}, + {"Response.Body", Field, 0}, + {"Response.Close", Field, 0}, + {"Response.ContentLength", Field, 0}, + {"Response.Header", Field, 0}, + {"Response.Proto", Field, 0}, + {"Response.ProtoMajor", Field, 0}, + {"Response.ProtoMinor", Field, 0}, + {"Response.Request", Field, 0}, + {"Response.Status", Field, 0}, + {"Response.StatusCode", Field, 0}, + {"Response.TLS", Field, 3}, + {"Response.Trailer", Field, 0}, + {"Response.TransferEncoding", Field, 0}, + {"Response.Uncompressed", Field, 7}, + {"ResponseController", Type, 20}, + {"ResponseWriter", Type, 0}, + {"RoundTripper", Type, 0}, + {"SameSite", Type, 11}, + {"SameSiteDefaultMode", Const, 11}, + {"SameSiteLaxMode", Const, 11}, + {"SameSiteNoneMode", Const, 13}, + {"SameSiteStrictMode", Const, 11}, + {"Serve", Func, 0}, + {"ServeContent", Func, 0}, + {"ServeFile", Func, 0}, + {"ServeFileFS", Func, 22}, + {"ServeMux", Type, 0}, + {"ServeTLS", Func, 9}, + {"Server", Type, 0}, + {"Server.Addr", Field, 0}, + {"Server.BaseContext", Field, 13}, + {"Server.ConnContext", Field, 13}, + {"Server.ConnState", Field, 3}, + {"Server.DisableGeneralOptionsHandler", Field, 20}, + {"Server.ErrorLog", Field, 3}, + {"Server.Handler", Field, 0}, + {"Server.IdleTimeout", Field, 8}, + {"Server.MaxHeaderBytes", Field, 0}, + {"Server.ReadHeaderTimeout", Field, 8}, + {"Server.ReadTimeout", Field, 0}, + {"Server.TLSConfig", Field, 0}, + {"Server.TLSNextProto", Field, 1}, + {"Server.WriteTimeout", Field, 0}, + {"ServerContextKey", Var, 7}, + {"SetCookie", Func, 0}, + {"StateActive", Const, 3}, + {"StateClosed", Const, 3}, + {"StateHijacked", Const, 3}, + {"StateIdle", Const, 3}, + {"StateNew", Const, 3}, + {"StatusAccepted", Const, 0}, + {"StatusAlreadyReported", Const, 7}, + {"StatusBadGateway", Const, 0}, + {"StatusBadRequest", Const, 0}, + {"StatusConflict", Const, 0}, + {"StatusContinue", Const, 0}, + {"StatusCreated", Const, 0}, + {"StatusEarlyHints", Const, 13}, + {"StatusExpectationFailed", Const, 0}, + {"StatusFailedDependency", Const, 7}, + {"StatusForbidden", Const, 0}, + {"StatusFound", Const, 0}, + {"StatusGatewayTimeout", Const, 0}, + {"StatusGone", Const, 0}, + {"StatusHTTPVersionNotSupported", Const, 0}, + {"StatusIMUsed", Const, 7}, + {"StatusInsufficientStorage", Const, 7}, + {"StatusInternalServerError", Const, 0}, + {"StatusLengthRequired", Const, 0}, + {"StatusLocked", Const, 7}, + {"StatusLoopDetected", Const, 7}, + {"StatusMethodNotAllowed", Const, 0}, + {"StatusMisdirectedRequest", Const, 11}, + {"StatusMovedPermanently", Const, 0}, + {"StatusMultiStatus", Const, 7}, + {"StatusMultipleChoices", Const, 0}, + {"StatusNetworkAuthenticationRequired", Const, 6}, + {"StatusNoContent", Const, 0}, + {"StatusNonAuthoritativeInfo", Const, 0}, + {"StatusNotAcceptable", Const, 0}, + {"StatusNotExtended", Const, 7}, + {"StatusNotFound", Const, 0}, + {"StatusNotImplemented", Const, 0}, + {"StatusNotModified", Const, 0}, + {"StatusOK", Const, 0}, + {"StatusPartialContent", Const, 0}, + {"StatusPaymentRequired", Const, 0}, + {"StatusPermanentRedirect", Const, 7}, + {"StatusPreconditionFailed", Const, 0}, + {"StatusPreconditionRequired", Const, 6}, + {"StatusProcessing", Const, 7}, + {"StatusProxyAuthRequired", Const, 0}, + {"StatusRequestEntityTooLarge", Const, 0}, + {"StatusRequestHeaderFieldsTooLarge", Const, 6}, + {"StatusRequestTimeout", Const, 0}, + {"StatusRequestURITooLong", Const, 0}, + {"StatusRequestedRangeNotSatisfiable", Const, 0}, + {"StatusResetContent", Const, 0}, + {"StatusSeeOther", Const, 0}, + {"StatusServiceUnavailable", Const, 0}, + {"StatusSwitchingProtocols", Const, 0}, + {"StatusTeapot", Const, 0}, + {"StatusTemporaryRedirect", Const, 0}, + {"StatusText", Func, 0}, + {"StatusTooEarly", Const, 12}, + {"StatusTooManyRequests", Const, 6}, + {"StatusUnauthorized", Const, 0}, + {"StatusUnavailableForLegalReasons", Const, 6}, + {"StatusUnprocessableEntity", Const, 7}, + {"StatusUnsupportedMediaType", Const, 0}, + {"StatusUpgradeRequired", Const, 7}, + {"StatusUseProxy", Const, 0}, + {"StatusVariantAlsoNegotiates", Const, 7}, + {"StripPrefix", Func, 0}, + {"TimeFormat", Const, 0}, + {"TimeoutHandler", Func, 0}, + {"TrailerPrefix", Const, 8}, + {"Transport", Type, 0}, + {"Transport.Dial", Field, 0}, + {"Transport.DialContext", Field, 7}, + {"Transport.DialTLS", Field, 4}, + {"Transport.DialTLSContext", Field, 14}, + {"Transport.DisableCompression", Field, 0}, + {"Transport.DisableKeepAlives", Field, 0}, + {"Transport.ExpectContinueTimeout", Field, 6}, + {"Transport.ForceAttemptHTTP2", Field, 13}, + {"Transport.GetProxyConnectHeader", Field, 16}, + {"Transport.IdleConnTimeout", Field, 7}, + {"Transport.MaxConnsPerHost", Field, 11}, + {"Transport.MaxIdleConns", Field, 7}, + {"Transport.MaxIdleConnsPerHost", Field, 0}, + {"Transport.MaxResponseHeaderBytes", Field, 7}, + {"Transport.OnProxyConnectResponse", Field, 20}, + {"Transport.Proxy", Field, 0}, + {"Transport.ProxyConnectHeader", Field, 8}, + {"Transport.ReadBufferSize", Field, 13}, + {"Transport.ResponseHeaderTimeout", Field, 1}, + {"Transport.TLSClientConfig", Field, 0}, + {"Transport.TLSHandshakeTimeout", Field, 3}, + {"Transport.TLSNextProto", Field, 6}, + {"Transport.WriteBufferSize", Field, 13}, + }, + "net/http/cgi": { + {"(*Handler).ServeHTTP", Method, 0}, + {"Handler", Type, 0}, + {"Handler.Args", Field, 0}, + {"Handler.Dir", Field, 0}, + {"Handler.Env", Field, 0}, + {"Handler.InheritEnv", Field, 0}, + {"Handler.Logger", Field, 0}, + {"Handler.Path", Field, 0}, + {"Handler.PathLocationHandler", Field, 0}, + {"Handler.Root", Field, 0}, + {"Handler.Stderr", Field, 7}, + {"Request", Func, 0}, + {"RequestFromMap", Func, 0}, + {"Serve", Func, 0}, + }, + "net/http/cookiejar": { + {"(*Jar).Cookies", Method, 1}, + {"(*Jar).SetCookies", Method, 1}, + {"Jar", Type, 1}, + {"New", Func, 1}, + {"Options", Type, 1}, + {"Options.PublicSuffixList", Field, 1}, + {"PublicSuffixList", Type, 1}, + }, + "net/http/fcgi": { + {"ErrConnClosed", Var, 5}, + {"ErrRequestAborted", Var, 5}, + {"ProcessEnv", Func, 9}, + {"Serve", Func, 0}, + }, + "net/http/httptest": { + {"(*ResponseRecorder).Flush", Method, 0}, + {"(*ResponseRecorder).Header", Method, 0}, + {"(*ResponseRecorder).Result", Method, 7}, + {"(*ResponseRecorder).Write", Method, 0}, + {"(*ResponseRecorder).WriteHeader", Method, 0}, + {"(*ResponseRecorder).WriteString", Method, 6}, + {"(*Server).Certificate", Method, 9}, + {"(*Server).Client", Method, 9}, + {"(*Server).Close", Method, 0}, + {"(*Server).CloseClientConnections", Method, 0}, + {"(*Server).Start", Method, 0}, + {"(*Server).StartTLS", Method, 0}, + {"DefaultRemoteAddr", Const, 0}, + {"NewRecorder", Func, 0}, + {"NewRequest", Func, 7}, + {"NewRequestWithContext", Func, 23}, + {"NewServer", Func, 0}, + {"NewTLSServer", Func, 0}, + {"NewUnstartedServer", Func, 0}, + {"ResponseRecorder", Type, 0}, + {"ResponseRecorder.Body", Field, 0}, + {"ResponseRecorder.Code", Field, 0}, + {"ResponseRecorder.Flushed", Field, 0}, + {"ResponseRecorder.HeaderMap", Field, 0}, + {"Server", Type, 0}, + {"Server.Config", Field, 0}, + {"Server.EnableHTTP2", Field, 14}, + {"Server.Listener", Field, 0}, + {"Server.TLS", Field, 0}, + {"Server.URL", Field, 0}, + }, + "net/http/httptrace": { + {"ClientTrace", Type, 7}, + {"ClientTrace.ConnectDone", Field, 7}, + {"ClientTrace.ConnectStart", Field, 7}, + {"ClientTrace.DNSDone", Field, 7}, + {"ClientTrace.DNSStart", Field, 7}, + {"ClientTrace.GetConn", Field, 7}, + {"ClientTrace.Got100Continue", Field, 7}, + {"ClientTrace.Got1xxResponse", Field, 11}, + {"ClientTrace.GotConn", Field, 7}, + {"ClientTrace.GotFirstResponseByte", Field, 7}, + {"ClientTrace.PutIdleConn", Field, 7}, + {"ClientTrace.TLSHandshakeDone", Field, 8}, + {"ClientTrace.TLSHandshakeStart", Field, 8}, + {"ClientTrace.Wait100Continue", Field, 7}, + {"ClientTrace.WroteHeaderField", Field, 11}, + {"ClientTrace.WroteHeaders", Field, 7}, + {"ClientTrace.WroteRequest", Field, 7}, + {"ContextClientTrace", Func, 7}, + {"DNSDoneInfo", Type, 7}, + {"DNSDoneInfo.Addrs", Field, 7}, + {"DNSDoneInfo.Coalesced", Field, 7}, + {"DNSDoneInfo.Err", Field, 7}, + {"DNSStartInfo", Type, 7}, + {"DNSStartInfo.Host", Field, 7}, + {"GotConnInfo", Type, 7}, + {"GotConnInfo.Conn", Field, 7}, + {"GotConnInfo.IdleTime", Field, 7}, + {"GotConnInfo.Reused", Field, 7}, + {"GotConnInfo.WasIdle", Field, 7}, + {"WithClientTrace", Func, 7}, + {"WroteRequestInfo", Type, 7}, + {"WroteRequestInfo.Err", Field, 7}, + }, + "net/http/httputil": { + {"(*ClientConn).Close", Method, 0}, + {"(*ClientConn).Do", Method, 0}, + {"(*ClientConn).Hijack", Method, 0}, + {"(*ClientConn).Pending", Method, 0}, + {"(*ClientConn).Read", Method, 0}, + {"(*ClientConn).Write", Method, 0}, + {"(*ProxyRequest).SetURL", Method, 20}, + {"(*ProxyRequest).SetXForwarded", Method, 20}, + {"(*ReverseProxy).ServeHTTP", Method, 0}, + {"(*ServerConn).Close", Method, 0}, + {"(*ServerConn).Hijack", Method, 0}, + {"(*ServerConn).Pending", Method, 0}, + {"(*ServerConn).Read", Method, 0}, + {"(*ServerConn).Write", Method, 0}, + {"BufferPool", Type, 6}, + {"ClientConn", Type, 0}, + {"DumpRequest", Func, 0}, + {"DumpRequestOut", Func, 0}, + {"DumpResponse", Func, 0}, + {"ErrClosed", Var, 0}, + {"ErrLineTooLong", Var, 0}, + {"ErrPersistEOF", Var, 0}, + {"ErrPipeline", Var, 0}, + {"NewChunkedReader", Func, 0}, + {"NewChunkedWriter", Func, 0}, + {"NewClientConn", Func, 0}, + {"NewProxyClientConn", Func, 0}, + {"NewServerConn", Func, 0}, + {"NewSingleHostReverseProxy", Func, 0}, + {"ProxyRequest", Type, 20}, + {"ProxyRequest.In", Field, 20}, + {"ProxyRequest.Out", Field, 20}, + {"ReverseProxy", Type, 0}, + {"ReverseProxy.BufferPool", Field, 6}, + {"ReverseProxy.Director", Field, 0}, + {"ReverseProxy.ErrorHandler", Field, 11}, + {"ReverseProxy.ErrorLog", Field, 4}, + {"ReverseProxy.FlushInterval", Field, 0}, + {"ReverseProxy.ModifyResponse", Field, 8}, + {"ReverseProxy.Rewrite", Field, 20}, + {"ReverseProxy.Transport", Field, 0}, + {"ServerConn", Type, 0}, + }, + "net/http/pprof": { + {"Cmdline", Func, 0}, + {"Handler", Func, 0}, + {"Index", Func, 0}, + {"Profile", Func, 0}, + {"Symbol", Func, 0}, + {"Trace", Func, 5}, + }, + "net/mail": { + {"(*Address).String", Method, 0}, + {"(*AddressParser).Parse", Method, 5}, + {"(*AddressParser).ParseList", Method, 5}, + {"(Header).AddressList", Method, 0}, + {"(Header).Date", Method, 0}, + {"(Header).Get", Method, 0}, + {"Address", Type, 0}, + {"Address.Address", Field, 0}, + {"Address.Name", Field, 0}, + {"AddressParser", Type, 5}, + {"AddressParser.WordDecoder", Field, 5}, + {"ErrHeaderNotPresent", Var, 0}, + {"Header", Type, 0}, + {"Message", Type, 0}, + {"Message.Body", Field, 0}, + {"Message.Header", Field, 0}, + {"ParseAddress", Func, 1}, + {"ParseAddressList", Func, 1}, + {"ParseDate", Func, 8}, + {"ReadMessage", Func, 0}, + }, + "net/netip": { + {"(*Addr).UnmarshalBinary", Method, 18}, + {"(*Addr).UnmarshalText", Method, 18}, + {"(*AddrPort).UnmarshalBinary", Method, 18}, + {"(*AddrPort).UnmarshalText", Method, 18}, + {"(*Prefix).UnmarshalBinary", Method, 18}, + {"(*Prefix).UnmarshalText", Method, 18}, + {"(Addr).AppendTo", Method, 18}, + {"(Addr).As16", Method, 18}, + {"(Addr).As4", Method, 18}, + {"(Addr).AsSlice", Method, 18}, + {"(Addr).BitLen", Method, 18}, + {"(Addr).Compare", Method, 18}, + {"(Addr).Is4", Method, 18}, + {"(Addr).Is4In6", Method, 18}, + {"(Addr).Is6", Method, 18}, + {"(Addr).IsGlobalUnicast", Method, 18}, + {"(Addr).IsInterfaceLocalMulticast", Method, 18}, + {"(Addr).IsLinkLocalMulticast", Method, 18}, + {"(Addr).IsLinkLocalUnicast", Method, 18}, + {"(Addr).IsLoopback", Method, 18}, + {"(Addr).IsMulticast", Method, 18}, + {"(Addr).IsPrivate", Method, 18}, + {"(Addr).IsUnspecified", Method, 18}, + {"(Addr).IsValid", Method, 18}, + {"(Addr).Less", Method, 18}, + {"(Addr).MarshalBinary", Method, 18}, + {"(Addr).MarshalText", Method, 18}, + {"(Addr).Next", Method, 18}, + {"(Addr).Prefix", Method, 18}, + {"(Addr).Prev", Method, 18}, + {"(Addr).String", Method, 18}, + {"(Addr).StringExpanded", Method, 18}, + {"(Addr).Unmap", Method, 18}, + {"(Addr).WithZone", Method, 18}, + {"(Addr).Zone", Method, 18}, + {"(AddrPort).Addr", Method, 18}, + {"(AddrPort).AppendTo", Method, 18}, + {"(AddrPort).Compare", Method, 22}, + {"(AddrPort).IsValid", Method, 18}, + {"(AddrPort).MarshalBinary", Method, 18}, + {"(AddrPort).MarshalText", Method, 18}, + {"(AddrPort).Port", Method, 18}, + {"(AddrPort).String", Method, 18}, + {"(Prefix).Addr", Method, 18}, + {"(Prefix).AppendTo", Method, 18}, + {"(Prefix).Bits", Method, 18}, + {"(Prefix).Contains", Method, 18}, + {"(Prefix).IsSingleIP", Method, 18}, + {"(Prefix).IsValid", Method, 18}, + {"(Prefix).MarshalBinary", Method, 18}, + {"(Prefix).MarshalText", Method, 18}, + {"(Prefix).Masked", Method, 18}, + {"(Prefix).Overlaps", Method, 18}, + {"(Prefix).String", Method, 18}, + {"Addr", Type, 18}, + {"AddrFrom16", Func, 18}, + {"AddrFrom4", Func, 18}, + {"AddrFromSlice", Func, 18}, + {"AddrPort", Type, 18}, + {"AddrPortFrom", Func, 18}, + {"IPv4Unspecified", Func, 18}, + {"IPv6LinkLocalAllNodes", Func, 18}, + {"IPv6LinkLocalAllRouters", Func, 20}, + {"IPv6Loopback", Func, 20}, + {"IPv6Unspecified", Func, 18}, + {"MustParseAddr", Func, 18}, + {"MustParseAddrPort", Func, 18}, + {"MustParsePrefix", Func, 18}, + {"ParseAddr", Func, 18}, + {"ParseAddrPort", Func, 18}, + {"ParsePrefix", Func, 18}, + {"Prefix", Type, 18}, + {"PrefixFrom", Func, 18}, + }, + "net/rpc": { + {"(*Client).Call", Method, 0}, + {"(*Client).Close", Method, 0}, + {"(*Client).Go", Method, 0}, + {"(*Server).Accept", Method, 0}, + {"(*Server).HandleHTTP", Method, 0}, + {"(*Server).Register", Method, 0}, + {"(*Server).RegisterName", Method, 0}, + {"(*Server).ServeCodec", Method, 0}, + {"(*Server).ServeConn", Method, 0}, + {"(*Server).ServeHTTP", Method, 0}, + {"(*Server).ServeRequest", Method, 0}, + {"(ServerError).Error", Method, 0}, + {"Accept", Func, 0}, + {"Call", Type, 0}, + {"Call.Args", Field, 0}, + {"Call.Done", Field, 0}, + {"Call.Error", Field, 0}, + {"Call.Reply", Field, 0}, + {"Call.ServiceMethod", Field, 0}, + {"Client", Type, 0}, + {"ClientCodec", Type, 0}, + {"DefaultDebugPath", Const, 0}, + {"DefaultRPCPath", Const, 0}, + {"DefaultServer", Var, 0}, + {"Dial", Func, 0}, + {"DialHTTP", Func, 0}, + {"DialHTTPPath", Func, 0}, + {"ErrShutdown", Var, 0}, + {"HandleHTTP", Func, 0}, + {"NewClient", Func, 0}, + {"NewClientWithCodec", Func, 0}, + {"NewServer", Func, 0}, + {"Register", Func, 0}, + {"RegisterName", Func, 0}, + {"Request", Type, 0}, + {"Request.Seq", Field, 0}, + {"Request.ServiceMethod", Field, 0}, + {"Response", Type, 0}, + {"Response.Error", Field, 0}, + {"Response.Seq", Field, 0}, + {"Response.ServiceMethod", Field, 0}, + {"ServeCodec", Func, 0}, + {"ServeConn", Func, 0}, + {"ServeRequest", Func, 0}, + {"Server", Type, 0}, + {"ServerCodec", Type, 0}, + {"ServerError", Type, 0}, + }, + "net/rpc/jsonrpc": { + {"Dial", Func, 0}, + {"NewClient", Func, 0}, + {"NewClientCodec", Func, 0}, + {"NewServerCodec", Func, 0}, + {"ServeConn", Func, 0}, + }, + "net/smtp": { + {"(*Client).Auth", Method, 0}, + {"(*Client).Close", Method, 2}, + {"(*Client).Data", Method, 0}, + {"(*Client).Extension", Method, 0}, + {"(*Client).Hello", Method, 1}, + {"(*Client).Mail", Method, 0}, + {"(*Client).Noop", Method, 10}, + {"(*Client).Quit", Method, 0}, + {"(*Client).Rcpt", Method, 0}, + {"(*Client).Reset", Method, 0}, + {"(*Client).StartTLS", Method, 0}, + {"(*Client).TLSConnectionState", Method, 5}, + {"(*Client).Verify", Method, 0}, + {"Auth", Type, 0}, + {"CRAMMD5Auth", Func, 0}, + {"Client", Type, 0}, + {"Client.Text", Field, 0}, + {"Dial", Func, 0}, + {"NewClient", Func, 0}, + {"PlainAuth", Func, 0}, + {"SendMail", Func, 0}, + {"ServerInfo", Type, 0}, + {"ServerInfo.Auth", Field, 0}, + {"ServerInfo.Name", Field, 0}, + {"ServerInfo.TLS", Field, 0}, + }, + "net/textproto": { + {"(*Conn).Close", Method, 0}, + {"(*Conn).Cmd", Method, 0}, + {"(*Conn).DotReader", Method, 0}, + {"(*Conn).DotWriter", Method, 0}, + {"(*Conn).EndRequest", Method, 0}, + {"(*Conn).EndResponse", Method, 0}, + {"(*Conn).Next", Method, 0}, + {"(*Conn).PrintfLine", Method, 0}, + {"(*Conn).ReadCodeLine", Method, 0}, + {"(*Conn).ReadContinuedLine", Method, 0}, + {"(*Conn).ReadContinuedLineBytes", Method, 0}, + {"(*Conn).ReadDotBytes", Method, 0}, + {"(*Conn).ReadDotLines", Method, 0}, + {"(*Conn).ReadLine", Method, 0}, + {"(*Conn).ReadLineBytes", Method, 0}, + {"(*Conn).ReadMIMEHeader", Method, 0}, + {"(*Conn).ReadResponse", Method, 0}, + {"(*Conn).StartRequest", Method, 0}, + {"(*Conn).StartResponse", Method, 0}, + {"(*Error).Error", Method, 0}, + {"(*Pipeline).EndRequest", Method, 0}, + {"(*Pipeline).EndResponse", Method, 0}, + {"(*Pipeline).Next", Method, 0}, + {"(*Pipeline).StartRequest", Method, 0}, + {"(*Pipeline).StartResponse", Method, 0}, + {"(*Reader).DotReader", Method, 0}, + {"(*Reader).ReadCodeLine", Method, 0}, + {"(*Reader).ReadContinuedLine", Method, 0}, + {"(*Reader).ReadContinuedLineBytes", Method, 0}, + {"(*Reader).ReadDotBytes", Method, 0}, + {"(*Reader).ReadDotLines", Method, 0}, + {"(*Reader).ReadLine", Method, 0}, + {"(*Reader).ReadLineBytes", Method, 0}, + {"(*Reader).ReadMIMEHeader", Method, 0}, + {"(*Reader).ReadResponse", Method, 0}, + {"(*Writer).DotWriter", Method, 0}, + {"(*Writer).PrintfLine", Method, 0}, + {"(MIMEHeader).Add", Method, 0}, + {"(MIMEHeader).Del", Method, 0}, + {"(MIMEHeader).Get", Method, 0}, + {"(MIMEHeader).Set", Method, 0}, + {"(MIMEHeader).Values", Method, 14}, + {"(ProtocolError).Error", Method, 0}, + {"CanonicalMIMEHeaderKey", Func, 0}, + {"Conn", Type, 0}, + {"Conn.Pipeline", Field, 0}, + {"Conn.Reader", Field, 0}, + {"Conn.Writer", Field, 0}, + {"Dial", Func, 0}, + {"Error", Type, 0}, + {"Error.Code", Field, 0}, + {"Error.Msg", Field, 0}, + {"MIMEHeader", Type, 0}, + {"NewConn", Func, 0}, + {"NewReader", Func, 0}, + {"NewWriter", Func, 0}, + {"Pipeline", Type, 0}, + {"ProtocolError", Type, 0}, + {"Reader", Type, 0}, + {"Reader.R", Field, 0}, + {"TrimBytes", Func, 1}, + {"TrimString", Func, 1}, + {"Writer", Type, 0}, + {"Writer.W", Field, 0}, + }, + "net/url": { + {"(*Error).Error", Method, 0}, + {"(*Error).Temporary", Method, 6}, + {"(*Error).Timeout", Method, 6}, + {"(*Error).Unwrap", Method, 13}, + {"(*URL).EscapedFragment", Method, 15}, + {"(*URL).EscapedPath", Method, 5}, + {"(*URL).Hostname", Method, 8}, + {"(*URL).IsAbs", Method, 0}, + {"(*URL).JoinPath", Method, 19}, + {"(*URL).MarshalBinary", Method, 8}, + {"(*URL).Parse", Method, 0}, + {"(*URL).Port", Method, 8}, + {"(*URL).Query", Method, 0}, + {"(*URL).Redacted", Method, 15}, + {"(*URL).RequestURI", Method, 0}, + {"(*URL).ResolveReference", Method, 0}, + {"(*URL).String", Method, 0}, + {"(*URL).UnmarshalBinary", Method, 8}, + {"(*Userinfo).Password", Method, 0}, + {"(*Userinfo).String", Method, 0}, + {"(*Userinfo).Username", Method, 0}, + {"(EscapeError).Error", Method, 0}, + {"(InvalidHostError).Error", Method, 6}, + {"(Values).Add", Method, 0}, + {"(Values).Del", Method, 0}, + {"(Values).Encode", Method, 0}, + {"(Values).Get", Method, 0}, + {"(Values).Has", Method, 17}, + {"(Values).Set", Method, 0}, + {"Error", Type, 0}, + {"Error.Err", Field, 0}, + {"Error.Op", Field, 0}, + {"Error.URL", Field, 0}, + {"EscapeError", Type, 0}, + {"InvalidHostError", Type, 6}, + {"JoinPath", Func, 19}, + {"Parse", Func, 0}, + {"ParseQuery", Func, 0}, + {"ParseRequestURI", Func, 0}, + {"PathEscape", Func, 8}, + {"PathUnescape", Func, 8}, + {"QueryEscape", Func, 0}, + {"QueryUnescape", Func, 0}, + {"URL", Type, 0}, + {"URL.ForceQuery", Field, 7}, + {"URL.Fragment", Field, 0}, + {"URL.Host", Field, 0}, + {"URL.OmitHost", Field, 19}, + {"URL.Opaque", Field, 0}, + {"URL.Path", Field, 0}, + {"URL.RawFragment", Field, 15}, + {"URL.RawPath", Field, 5}, + {"URL.RawQuery", Field, 0}, + {"URL.Scheme", Field, 0}, + {"URL.User", Field, 0}, + {"User", Func, 0}, + {"UserPassword", Func, 0}, + {"Userinfo", Type, 0}, + {"Values", Type, 0}, + }, + "os": { + {"(*File).Chdir", Method, 0}, + {"(*File).Chmod", Method, 0}, + {"(*File).Chown", Method, 0}, + {"(*File).Close", Method, 0}, + {"(*File).Fd", Method, 0}, + {"(*File).Name", Method, 0}, + {"(*File).Read", Method, 0}, + {"(*File).ReadAt", Method, 0}, + {"(*File).ReadDir", Method, 16}, + {"(*File).ReadFrom", Method, 15}, + {"(*File).Readdir", Method, 0}, + {"(*File).Readdirnames", Method, 0}, + {"(*File).Seek", Method, 0}, + {"(*File).SetDeadline", Method, 10}, + {"(*File).SetReadDeadline", Method, 10}, + {"(*File).SetWriteDeadline", Method, 10}, + {"(*File).Stat", Method, 0}, + {"(*File).Sync", Method, 0}, + {"(*File).SyscallConn", Method, 12}, + {"(*File).Truncate", Method, 0}, + {"(*File).Write", Method, 0}, + {"(*File).WriteAt", Method, 0}, + {"(*File).WriteString", Method, 0}, + {"(*File).WriteTo", Method, 22}, + {"(*LinkError).Error", Method, 0}, + {"(*LinkError).Unwrap", Method, 13}, + {"(*PathError).Error", Method, 0}, + {"(*PathError).Timeout", Method, 10}, + {"(*PathError).Unwrap", Method, 13}, + {"(*Process).Kill", Method, 0}, + {"(*Process).Release", Method, 0}, + {"(*Process).Signal", Method, 0}, + {"(*Process).Wait", Method, 0}, + {"(*ProcessState).ExitCode", Method, 12}, + {"(*ProcessState).Exited", Method, 0}, + {"(*ProcessState).Pid", Method, 0}, + {"(*ProcessState).String", Method, 0}, + {"(*ProcessState).Success", Method, 0}, + {"(*ProcessState).Sys", Method, 0}, + {"(*ProcessState).SysUsage", Method, 0}, + {"(*ProcessState).SystemTime", Method, 0}, + {"(*ProcessState).UserTime", Method, 0}, + {"(*SyscallError).Error", Method, 0}, + {"(*SyscallError).Timeout", Method, 10}, + {"(*SyscallError).Unwrap", Method, 13}, + {"(FileMode).IsDir", Method, 0}, + {"(FileMode).IsRegular", Method, 1}, + {"(FileMode).Perm", Method, 0}, + {"(FileMode).String", Method, 0}, + {"Args", Var, 0}, + {"Chdir", Func, 0}, + {"Chmod", Func, 0}, + {"Chown", Func, 0}, + {"Chtimes", Func, 0}, + {"Clearenv", Func, 0}, + {"CopyFS", Func, 23}, + {"Create", Func, 0}, + {"CreateTemp", Func, 16}, + {"DevNull", Const, 0}, + {"DirEntry", Type, 16}, + {"DirFS", Func, 16}, + {"Environ", Func, 0}, + {"ErrClosed", Var, 8}, + {"ErrDeadlineExceeded", Var, 15}, + {"ErrExist", Var, 0}, + {"ErrInvalid", Var, 0}, + {"ErrNoDeadline", Var, 10}, + {"ErrNotExist", Var, 0}, + {"ErrPermission", Var, 0}, + {"ErrProcessDone", Var, 16}, + {"Executable", Func, 8}, + {"Exit", Func, 0}, + {"Expand", Func, 0}, + {"ExpandEnv", Func, 0}, + {"File", Type, 0}, + {"FileInfo", Type, 0}, + {"FileMode", Type, 0}, + {"FindProcess", Func, 0}, + {"Getegid", Func, 0}, + {"Getenv", Func, 0}, + {"Geteuid", Func, 0}, + {"Getgid", Func, 0}, + {"Getgroups", Func, 0}, + {"Getpagesize", Func, 0}, + {"Getpid", Func, 0}, + {"Getppid", Func, 0}, + {"Getuid", Func, 0}, + {"Getwd", Func, 0}, + {"Hostname", Func, 0}, + {"Interrupt", Var, 0}, + {"IsExist", Func, 0}, + {"IsNotExist", Func, 0}, + {"IsPathSeparator", Func, 0}, + {"IsPermission", Func, 0}, + {"IsTimeout", Func, 10}, + {"Kill", Var, 0}, + {"Lchown", Func, 0}, + {"Link", Func, 0}, + {"LinkError", Type, 0}, + {"LinkError.Err", Field, 0}, + {"LinkError.New", Field, 0}, + {"LinkError.Old", Field, 0}, + {"LinkError.Op", Field, 0}, + {"LookupEnv", Func, 5}, + {"Lstat", Func, 0}, + {"Mkdir", Func, 0}, + {"MkdirAll", Func, 0}, + {"MkdirTemp", Func, 16}, + {"ModeAppend", Const, 0}, + {"ModeCharDevice", Const, 0}, + {"ModeDevice", Const, 0}, + {"ModeDir", Const, 0}, + {"ModeExclusive", Const, 0}, + {"ModeIrregular", Const, 11}, + {"ModeNamedPipe", Const, 0}, + {"ModePerm", Const, 0}, + {"ModeSetgid", Const, 0}, + {"ModeSetuid", Const, 0}, + {"ModeSocket", Const, 0}, + {"ModeSticky", Const, 0}, + {"ModeSymlink", Const, 0}, + {"ModeTemporary", Const, 0}, + {"ModeType", Const, 0}, + {"NewFile", Func, 0}, + {"NewSyscallError", Func, 0}, + {"O_APPEND", Const, 0}, + {"O_CREATE", Const, 0}, + {"O_EXCL", Const, 0}, + {"O_RDONLY", Const, 0}, + {"O_RDWR", Const, 0}, + {"O_SYNC", Const, 0}, + {"O_TRUNC", Const, 0}, + {"O_WRONLY", Const, 0}, + {"Open", Func, 0}, + {"OpenFile", Func, 0}, + {"PathError", Type, 0}, + {"PathError.Err", Field, 0}, + {"PathError.Op", Field, 0}, + {"PathError.Path", Field, 0}, + {"PathListSeparator", Const, 0}, + {"PathSeparator", Const, 0}, + {"Pipe", Func, 0}, + {"ProcAttr", Type, 0}, + {"ProcAttr.Dir", Field, 0}, + {"ProcAttr.Env", Field, 0}, + {"ProcAttr.Files", Field, 0}, + {"ProcAttr.Sys", Field, 0}, + {"Process", Type, 0}, + {"Process.Pid", Field, 0}, + {"ProcessState", Type, 0}, + {"ReadDir", Func, 16}, + {"ReadFile", Func, 16}, + {"Readlink", Func, 0}, + {"Remove", Func, 0}, + {"RemoveAll", Func, 0}, + {"Rename", Func, 0}, + {"SEEK_CUR", Const, 0}, + {"SEEK_END", Const, 0}, + {"SEEK_SET", Const, 0}, + {"SameFile", Func, 0}, + {"Setenv", Func, 0}, + {"Signal", Type, 0}, + {"StartProcess", Func, 0}, + {"Stat", Func, 0}, + {"Stderr", Var, 0}, + {"Stdin", Var, 0}, + {"Stdout", Var, 0}, + {"Symlink", Func, 0}, + {"SyscallError", Type, 0}, + {"SyscallError.Err", Field, 0}, + {"SyscallError.Syscall", Field, 0}, + {"TempDir", Func, 0}, + {"Truncate", Func, 0}, + {"Unsetenv", Func, 4}, + {"UserCacheDir", Func, 11}, + {"UserConfigDir", Func, 13}, + {"UserHomeDir", Func, 12}, + {"WriteFile", Func, 16}, + }, + "os/exec": { + {"(*Cmd).CombinedOutput", Method, 0}, + {"(*Cmd).Environ", Method, 19}, + {"(*Cmd).Output", Method, 0}, + {"(*Cmd).Run", Method, 0}, + {"(*Cmd).Start", Method, 0}, + {"(*Cmd).StderrPipe", Method, 0}, + {"(*Cmd).StdinPipe", Method, 0}, + {"(*Cmd).StdoutPipe", Method, 0}, + {"(*Cmd).String", Method, 13}, + {"(*Cmd).Wait", Method, 0}, + {"(*Error).Error", Method, 0}, + {"(*Error).Unwrap", Method, 13}, + {"(*ExitError).Error", Method, 0}, + {"(ExitError).ExitCode", Method, 12}, + {"(ExitError).Exited", Method, 0}, + {"(ExitError).Pid", Method, 0}, + {"(ExitError).String", Method, 0}, + {"(ExitError).Success", Method, 0}, + {"(ExitError).Sys", Method, 0}, + {"(ExitError).SysUsage", Method, 0}, + {"(ExitError).SystemTime", Method, 0}, + {"(ExitError).UserTime", Method, 0}, + {"Cmd", Type, 0}, + {"Cmd.Args", Field, 0}, + {"Cmd.Cancel", Field, 20}, + {"Cmd.Dir", Field, 0}, + {"Cmd.Env", Field, 0}, + {"Cmd.Err", Field, 19}, + {"Cmd.ExtraFiles", Field, 0}, + {"Cmd.Path", Field, 0}, + {"Cmd.Process", Field, 0}, + {"Cmd.ProcessState", Field, 0}, + {"Cmd.Stderr", Field, 0}, + {"Cmd.Stdin", Field, 0}, + {"Cmd.Stdout", Field, 0}, + {"Cmd.SysProcAttr", Field, 0}, + {"Cmd.WaitDelay", Field, 20}, + {"Command", Func, 0}, + {"CommandContext", Func, 7}, + {"ErrDot", Var, 19}, + {"ErrNotFound", Var, 0}, + {"ErrWaitDelay", Var, 20}, + {"Error", Type, 0}, + {"Error.Err", Field, 0}, + {"Error.Name", Field, 0}, + {"ExitError", Type, 0}, + {"ExitError.ProcessState", Field, 0}, + {"ExitError.Stderr", Field, 6}, + {"LookPath", Func, 0}, + }, + "os/signal": { + {"Ignore", Func, 5}, + {"Ignored", Func, 11}, + {"Notify", Func, 0}, + {"NotifyContext", Func, 16}, + {"Reset", Func, 5}, + {"Stop", Func, 1}, + }, + "os/user": { + {"(*User).GroupIds", Method, 7}, + {"(UnknownGroupError).Error", Method, 7}, + {"(UnknownGroupIdError).Error", Method, 7}, + {"(UnknownUserError).Error", Method, 0}, + {"(UnknownUserIdError).Error", Method, 0}, + {"Current", Func, 0}, + {"Group", Type, 7}, + {"Group.Gid", Field, 7}, + {"Group.Name", Field, 7}, + {"Lookup", Func, 0}, + {"LookupGroup", Func, 7}, + {"LookupGroupId", Func, 7}, + {"LookupId", Func, 0}, + {"UnknownGroupError", Type, 7}, + {"UnknownGroupIdError", Type, 7}, + {"UnknownUserError", Type, 0}, + {"UnknownUserIdError", Type, 0}, + {"User", Type, 0}, + {"User.Gid", Field, 0}, + {"User.HomeDir", Field, 0}, + {"User.Name", Field, 0}, + {"User.Uid", Field, 0}, + {"User.Username", Field, 0}, + }, + "path": { + {"Base", Func, 0}, + {"Clean", Func, 0}, + {"Dir", Func, 0}, + {"ErrBadPattern", Var, 0}, + {"Ext", Func, 0}, + {"IsAbs", Func, 0}, + {"Join", Func, 0}, + {"Match", Func, 0}, + {"Split", Func, 0}, + }, + "path/filepath": { + {"Abs", Func, 0}, + {"Base", Func, 0}, + {"Clean", Func, 0}, + {"Dir", Func, 0}, + {"ErrBadPattern", Var, 0}, + {"EvalSymlinks", Func, 0}, + {"Ext", Func, 0}, + {"FromSlash", Func, 0}, + {"Glob", Func, 0}, + {"HasPrefix", Func, 0}, + {"IsAbs", Func, 0}, + {"IsLocal", Func, 20}, + {"Join", Func, 0}, + {"ListSeparator", Const, 0}, + {"Localize", Func, 23}, + {"Match", Func, 0}, + {"Rel", Func, 0}, + {"Separator", Const, 0}, + {"SkipAll", Var, 20}, + {"SkipDir", Var, 0}, + {"Split", Func, 0}, + {"SplitList", Func, 0}, + {"ToSlash", Func, 0}, + {"VolumeName", Func, 0}, + {"Walk", Func, 0}, + {"WalkDir", Func, 16}, + {"WalkFunc", Type, 0}, + }, + "plugin": { + {"(*Plugin).Lookup", Method, 8}, + {"Open", Func, 8}, + {"Plugin", Type, 8}, + {"Symbol", Type, 8}, + }, + "reflect": { + {"(*MapIter).Key", Method, 12}, + {"(*MapIter).Next", Method, 12}, + {"(*MapIter).Reset", Method, 18}, + {"(*MapIter).Value", Method, 12}, + {"(*ValueError).Error", Method, 0}, + {"(ChanDir).String", Method, 0}, + {"(Kind).String", Method, 0}, + {"(Method).IsExported", Method, 17}, + {"(StructField).IsExported", Method, 17}, + {"(StructTag).Get", Method, 0}, + {"(StructTag).Lookup", Method, 7}, + {"(Value).Addr", Method, 0}, + {"(Value).Bool", Method, 0}, + {"(Value).Bytes", Method, 0}, + {"(Value).Call", Method, 0}, + {"(Value).CallSlice", Method, 0}, + {"(Value).CanAddr", Method, 0}, + {"(Value).CanComplex", Method, 18}, + {"(Value).CanConvert", Method, 17}, + {"(Value).CanFloat", Method, 18}, + {"(Value).CanInt", Method, 18}, + {"(Value).CanInterface", Method, 0}, + {"(Value).CanSet", Method, 0}, + {"(Value).CanUint", Method, 18}, + {"(Value).Cap", Method, 0}, + {"(Value).Clear", Method, 21}, + {"(Value).Close", Method, 0}, + {"(Value).Comparable", Method, 20}, + {"(Value).Complex", Method, 0}, + {"(Value).Convert", Method, 1}, + {"(Value).Elem", Method, 0}, + {"(Value).Equal", Method, 20}, + {"(Value).Field", Method, 0}, + {"(Value).FieldByIndex", Method, 0}, + {"(Value).FieldByIndexErr", Method, 18}, + {"(Value).FieldByName", Method, 0}, + {"(Value).FieldByNameFunc", Method, 0}, + {"(Value).Float", Method, 0}, + {"(Value).Grow", Method, 20}, + {"(Value).Index", Method, 0}, + {"(Value).Int", Method, 0}, + {"(Value).Interface", Method, 0}, + {"(Value).InterfaceData", Method, 0}, + {"(Value).IsNil", Method, 0}, + {"(Value).IsValid", Method, 0}, + {"(Value).IsZero", Method, 13}, + {"(Value).Kind", Method, 0}, + {"(Value).Len", Method, 0}, + {"(Value).MapIndex", Method, 0}, + {"(Value).MapKeys", Method, 0}, + {"(Value).MapRange", Method, 12}, + {"(Value).Method", Method, 0}, + {"(Value).MethodByName", Method, 0}, + {"(Value).NumField", Method, 0}, + {"(Value).NumMethod", Method, 0}, + {"(Value).OverflowComplex", Method, 0}, + {"(Value).OverflowFloat", Method, 0}, + {"(Value).OverflowInt", Method, 0}, + {"(Value).OverflowUint", Method, 0}, + {"(Value).Pointer", Method, 0}, + {"(Value).Recv", Method, 0}, + {"(Value).Send", Method, 0}, + {"(Value).Seq", Method, 23}, + {"(Value).Seq2", Method, 23}, + {"(Value).Set", Method, 0}, + {"(Value).SetBool", Method, 0}, + {"(Value).SetBytes", Method, 0}, + {"(Value).SetCap", Method, 2}, + {"(Value).SetComplex", Method, 0}, + {"(Value).SetFloat", Method, 0}, + {"(Value).SetInt", Method, 0}, + {"(Value).SetIterKey", Method, 18}, + {"(Value).SetIterValue", Method, 18}, + {"(Value).SetLen", Method, 0}, + {"(Value).SetMapIndex", Method, 0}, + {"(Value).SetPointer", Method, 0}, + {"(Value).SetString", Method, 0}, + {"(Value).SetUint", Method, 0}, + {"(Value).SetZero", Method, 20}, + {"(Value).Slice", Method, 0}, + {"(Value).Slice3", Method, 2}, + {"(Value).String", Method, 0}, + {"(Value).TryRecv", Method, 0}, + {"(Value).TrySend", Method, 0}, + {"(Value).Type", Method, 0}, + {"(Value).Uint", Method, 0}, + {"(Value).UnsafeAddr", Method, 0}, + {"(Value).UnsafePointer", Method, 18}, + {"Append", Func, 0}, + {"AppendSlice", Func, 0}, + {"Array", Const, 0}, + {"ArrayOf", Func, 5}, + {"Bool", Const, 0}, + {"BothDir", Const, 0}, + {"Chan", Const, 0}, + {"ChanDir", Type, 0}, + {"ChanOf", Func, 1}, + {"Complex128", Const, 0}, + {"Complex64", Const, 0}, + {"Copy", Func, 0}, + {"DeepEqual", Func, 0}, + {"Float32", Const, 0}, + {"Float64", Const, 0}, + {"Func", Const, 0}, + {"FuncOf", Func, 5}, + {"Indirect", Func, 0}, + {"Int", Const, 0}, + {"Int16", Const, 0}, + {"Int32", Const, 0}, + {"Int64", Const, 0}, + {"Int8", Const, 0}, + {"Interface", Const, 0}, + {"Invalid", Const, 0}, + {"Kind", Type, 0}, + {"MakeChan", Func, 0}, + {"MakeFunc", Func, 1}, + {"MakeMap", Func, 0}, + {"MakeMapWithSize", Func, 9}, + {"MakeSlice", Func, 0}, + {"Map", Const, 0}, + {"MapIter", Type, 12}, + {"MapOf", Func, 1}, + {"Method", Type, 0}, + {"Method.Func", Field, 0}, + {"Method.Index", Field, 0}, + {"Method.Name", Field, 0}, + {"Method.PkgPath", Field, 0}, + {"Method.Type", Field, 0}, + {"New", Func, 0}, + {"NewAt", Func, 0}, + {"Pointer", Const, 18}, + {"PointerTo", Func, 18}, + {"Ptr", Const, 0}, + {"PtrTo", Func, 0}, + {"RecvDir", Const, 0}, + {"Select", Func, 1}, + {"SelectCase", Type, 1}, + {"SelectCase.Chan", Field, 1}, + {"SelectCase.Dir", Field, 1}, + {"SelectCase.Send", Field, 1}, + {"SelectDefault", Const, 1}, + {"SelectDir", Type, 1}, + {"SelectRecv", Const, 1}, + {"SelectSend", Const, 1}, + {"SendDir", Const, 0}, + {"Slice", Const, 0}, + {"SliceAt", Func, 23}, + {"SliceHeader", Type, 0}, + {"SliceHeader.Cap", Field, 0}, + {"SliceHeader.Data", Field, 0}, + {"SliceHeader.Len", Field, 0}, + {"SliceOf", Func, 1}, + {"String", Const, 0}, + {"StringHeader", Type, 0}, + {"StringHeader.Data", Field, 0}, + {"StringHeader.Len", Field, 0}, + {"Struct", Const, 0}, + {"StructField", Type, 0}, + {"StructField.Anonymous", Field, 0}, + {"StructField.Index", Field, 0}, + {"StructField.Name", Field, 0}, + {"StructField.Offset", Field, 0}, + {"StructField.PkgPath", Field, 0}, + {"StructField.Tag", Field, 0}, + {"StructField.Type", Field, 0}, + {"StructOf", Func, 7}, + {"StructTag", Type, 0}, + {"Swapper", Func, 8}, + {"Type", Type, 0}, + {"TypeFor", Func, 22}, + {"TypeOf", Func, 0}, + {"Uint", Const, 0}, + {"Uint16", Const, 0}, + {"Uint32", Const, 0}, + {"Uint64", Const, 0}, + {"Uint8", Const, 0}, + {"Uintptr", Const, 0}, + {"UnsafePointer", Const, 0}, + {"Value", Type, 0}, + {"ValueError", Type, 0}, + {"ValueError.Kind", Field, 0}, + {"ValueError.Method", Field, 0}, + {"ValueOf", Func, 0}, + {"VisibleFields", Func, 17}, + {"Zero", Func, 0}, + }, + "regexp": { + {"(*Regexp).Copy", Method, 6}, + {"(*Regexp).Expand", Method, 0}, + {"(*Regexp).ExpandString", Method, 0}, + {"(*Regexp).Find", Method, 0}, + {"(*Regexp).FindAll", Method, 0}, + {"(*Regexp).FindAllIndex", Method, 0}, + {"(*Regexp).FindAllString", Method, 0}, + {"(*Regexp).FindAllStringIndex", Method, 0}, + {"(*Regexp).FindAllStringSubmatch", Method, 0}, + {"(*Regexp).FindAllStringSubmatchIndex", Method, 0}, + {"(*Regexp).FindAllSubmatch", Method, 0}, + {"(*Regexp).FindAllSubmatchIndex", Method, 0}, + {"(*Regexp).FindIndex", Method, 0}, + {"(*Regexp).FindReaderIndex", Method, 0}, + {"(*Regexp).FindReaderSubmatchIndex", Method, 0}, + {"(*Regexp).FindString", Method, 0}, + {"(*Regexp).FindStringIndex", Method, 0}, + {"(*Regexp).FindStringSubmatch", Method, 0}, + {"(*Regexp).FindStringSubmatchIndex", Method, 0}, + {"(*Regexp).FindSubmatch", Method, 0}, + {"(*Regexp).FindSubmatchIndex", Method, 0}, + {"(*Regexp).LiteralPrefix", Method, 0}, + {"(*Regexp).Longest", Method, 1}, + {"(*Regexp).MarshalText", Method, 21}, + {"(*Regexp).Match", Method, 0}, + {"(*Regexp).MatchReader", Method, 0}, + {"(*Regexp).MatchString", Method, 0}, + {"(*Regexp).NumSubexp", Method, 0}, + {"(*Regexp).ReplaceAll", Method, 0}, + {"(*Regexp).ReplaceAllFunc", Method, 0}, + {"(*Regexp).ReplaceAllLiteral", Method, 0}, + {"(*Regexp).ReplaceAllLiteralString", Method, 0}, + {"(*Regexp).ReplaceAllString", Method, 0}, + {"(*Regexp).ReplaceAllStringFunc", Method, 0}, + {"(*Regexp).Split", Method, 1}, + {"(*Regexp).String", Method, 0}, + {"(*Regexp).SubexpIndex", Method, 15}, + {"(*Regexp).SubexpNames", Method, 0}, + {"(*Regexp).UnmarshalText", Method, 21}, + {"Compile", Func, 0}, + {"CompilePOSIX", Func, 0}, + {"Match", Func, 0}, + {"MatchReader", Func, 0}, + {"MatchString", Func, 0}, + {"MustCompile", Func, 0}, + {"MustCompilePOSIX", Func, 0}, + {"QuoteMeta", Func, 0}, + {"Regexp", Type, 0}, + }, + "regexp/syntax": { + {"(*Error).Error", Method, 0}, + {"(*Inst).MatchEmptyWidth", Method, 0}, + {"(*Inst).MatchRune", Method, 0}, + {"(*Inst).MatchRunePos", Method, 3}, + {"(*Inst).String", Method, 0}, + {"(*Prog).Prefix", Method, 0}, + {"(*Prog).StartCond", Method, 0}, + {"(*Prog).String", Method, 0}, + {"(*Regexp).CapNames", Method, 0}, + {"(*Regexp).Equal", Method, 0}, + {"(*Regexp).MaxCap", Method, 0}, + {"(*Regexp).Simplify", Method, 0}, + {"(*Regexp).String", Method, 0}, + {"(ErrorCode).String", Method, 0}, + {"(InstOp).String", Method, 3}, + {"(Op).String", Method, 11}, + {"ClassNL", Const, 0}, + {"Compile", Func, 0}, + {"DotNL", Const, 0}, + {"EmptyBeginLine", Const, 0}, + {"EmptyBeginText", Const, 0}, + {"EmptyEndLine", Const, 0}, + {"EmptyEndText", Const, 0}, + {"EmptyNoWordBoundary", Const, 0}, + {"EmptyOp", Type, 0}, + {"EmptyOpContext", Func, 0}, + {"EmptyWordBoundary", Const, 0}, + {"ErrInternalError", Const, 0}, + {"ErrInvalidCharClass", Const, 0}, + {"ErrInvalidCharRange", Const, 0}, + {"ErrInvalidEscape", Const, 0}, + {"ErrInvalidNamedCapture", Const, 0}, + {"ErrInvalidPerlOp", Const, 0}, + {"ErrInvalidRepeatOp", Const, 0}, + {"ErrInvalidRepeatSize", Const, 0}, + {"ErrInvalidUTF8", Const, 0}, + {"ErrLarge", Const, 20}, + {"ErrMissingBracket", Const, 0}, + {"ErrMissingParen", Const, 0}, + {"ErrMissingRepeatArgument", Const, 0}, + {"ErrNestingDepth", Const, 19}, + {"ErrTrailingBackslash", Const, 0}, + {"ErrUnexpectedParen", Const, 1}, + {"Error", Type, 0}, + {"Error.Code", Field, 0}, + {"Error.Expr", Field, 0}, + {"ErrorCode", Type, 0}, + {"Flags", Type, 0}, + {"FoldCase", Const, 0}, + {"Inst", Type, 0}, + {"Inst.Arg", Field, 0}, + {"Inst.Op", Field, 0}, + {"Inst.Out", Field, 0}, + {"Inst.Rune", Field, 0}, + {"InstAlt", Const, 0}, + {"InstAltMatch", Const, 0}, + {"InstCapture", Const, 0}, + {"InstEmptyWidth", Const, 0}, + {"InstFail", Const, 0}, + {"InstMatch", Const, 0}, + {"InstNop", Const, 0}, + {"InstOp", Type, 0}, + {"InstRune", Const, 0}, + {"InstRune1", Const, 0}, + {"InstRuneAny", Const, 0}, + {"InstRuneAnyNotNL", Const, 0}, + {"IsWordChar", Func, 0}, + {"Literal", Const, 0}, + {"MatchNL", Const, 0}, + {"NonGreedy", Const, 0}, + {"OneLine", Const, 0}, + {"Op", Type, 0}, + {"OpAlternate", Const, 0}, + {"OpAnyChar", Const, 0}, + {"OpAnyCharNotNL", Const, 0}, + {"OpBeginLine", Const, 0}, + {"OpBeginText", Const, 0}, + {"OpCapture", Const, 0}, + {"OpCharClass", Const, 0}, + {"OpConcat", Const, 0}, + {"OpEmptyMatch", Const, 0}, + {"OpEndLine", Const, 0}, + {"OpEndText", Const, 0}, + {"OpLiteral", Const, 0}, + {"OpNoMatch", Const, 0}, + {"OpNoWordBoundary", Const, 0}, + {"OpPlus", Const, 0}, + {"OpQuest", Const, 0}, + {"OpRepeat", Const, 0}, + {"OpStar", Const, 0}, + {"OpWordBoundary", Const, 0}, + {"POSIX", Const, 0}, + {"Parse", Func, 0}, + {"Perl", Const, 0}, + {"PerlX", Const, 0}, + {"Prog", Type, 0}, + {"Prog.Inst", Field, 0}, + {"Prog.NumCap", Field, 0}, + {"Prog.Start", Field, 0}, + {"Regexp", Type, 0}, + {"Regexp.Cap", Field, 0}, + {"Regexp.Flags", Field, 0}, + {"Regexp.Max", Field, 0}, + {"Regexp.Min", Field, 0}, + {"Regexp.Name", Field, 0}, + {"Regexp.Op", Field, 0}, + {"Regexp.Rune", Field, 0}, + {"Regexp.Rune0", Field, 0}, + {"Regexp.Sub", Field, 0}, + {"Regexp.Sub0", Field, 0}, + {"Simple", Const, 0}, + {"UnicodeGroups", Const, 0}, + {"WasDollar", Const, 0}, + }, + "runtime": { + {"(*BlockProfileRecord).Stack", Method, 1}, + {"(*Frames).Next", Method, 7}, + {"(*Func).Entry", Method, 0}, + {"(*Func).FileLine", Method, 0}, + {"(*Func).Name", Method, 0}, + {"(*MemProfileRecord).InUseBytes", Method, 0}, + {"(*MemProfileRecord).InUseObjects", Method, 0}, + {"(*MemProfileRecord).Stack", Method, 0}, + {"(*PanicNilError).Error", Method, 21}, + {"(*PanicNilError).RuntimeError", Method, 21}, + {"(*Pinner).Pin", Method, 21}, + {"(*Pinner).Unpin", Method, 21}, + {"(*StackRecord).Stack", Method, 0}, + {"(*TypeAssertionError).Error", Method, 0}, + {"(*TypeAssertionError).RuntimeError", Method, 0}, + {"BlockProfile", Func, 1}, + {"BlockProfileRecord", Type, 1}, + {"BlockProfileRecord.Count", Field, 1}, + {"BlockProfileRecord.Cycles", Field, 1}, + {"BlockProfileRecord.StackRecord", Field, 1}, + {"Breakpoint", Func, 0}, + {"CPUProfile", Func, 0}, + {"Caller", Func, 0}, + {"Callers", Func, 0}, + {"CallersFrames", Func, 7}, + {"Compiler", Const, 0}, + {"Error", Type, 0}, + {"Frame", Type, 7}, + {"Frame.Entry", Field, 7}, + {"Frame.File", Field, 7}, + {"Frame.Func", Field, 7}, + {"Frame.Function", Field, 7}, + {"Frame.Line", Field, 7}, + {"Frame.PC", Field, 7}, + {"Frames", Type, 7}, + {"Func", Type, 0}, + {"FuncForPC", Func, 0}, + {"GC", Func, 0}, + {"GOARCH", Const, 0}, + {"GOMAXPROCS", Func, 0}, + {"GOOS", Const, 0}, + {"GOROOT", Func, 0}, + {"Goexit", Func, 0}, + {"GoroutineProfile", Func, 0}, + {"Gosched", Func, 0}, + {"KeepAlive", Func, 7}, + {"LockOSThread", Func, 0}, + {"MemProfile", Func, 0}, + {"MemProfileRate", Var, 0}, + {"MemProfileRecord", Type, 0}, + {"MemProfileRecord.AllocBytes", Field, 0}, + {"MemProfileRecord.AllocObjects", Field, 0}, + {"MemProfileRecord.FreeBytes", Field, 0}, + {"MemProfileRecord.FreeObjects", Field, 0}, + {"MemProfileRecord.Stack0", Field, 0}, + {"MemStats", Type, 0}, + {"MemStats.Alloc", Field, 0}, + {"MemStats.BuckHashSys", Field, 0}, + {"MemStats.BySize", Field, 0}, + {"MemStats.DebugGC", Field, 0}, + {"MemStats.EnableGC", Field, 0}, + {"MemStats.Frees", Field, 0}, + {"MemStats.GCCPUFraction", Field, 5}, + {"MemStats.GCSys", Field, 2}, + {"MemStats.HeapAlloc", Field, 0}, + {"MemStats.HeapIdle", Field, 0}, + {"MemStats.HeapInuse", Field, 0}, + {"MemStats.HeapObjects", Field, 0}, + {"MemStats.HeapReleased", Field, 0}, + {"MemStats.HeapSys", Field, 0}, + {"MemStats.LastGC", Field, 0}, + {"MemStats.Lookups", Field, 0}, + {"MemStats.MCacheInuse", Field, 0}, + {"MemStats.MCacheSys", Field, 0}, + {"MemStats.MSpanInuse", Field, 0}, + {"MemStats.MSpanSys", Field, 0}, + {"MemStats.Mallocs", Field, 0}, + {"MemStats.NextGC", Field, 0}, + {"MemStats.NumForcedGC", Field, 8}, + {"MemStats.NumGC", Field, 0}, + {"MemStats.OtherSys", Field, 2}, + {"MemStats.PauseEnd", Field, 4}, + {"MemStats.PauseNs", Field, 0}, + {"MemStats.PauseTotalNs", Field, 0}, + {"MemStats.StackInuse", Field, 0}, + {"MemStats.StackSys", Field, 0}, + {"MemStats.Sys", Field, 0}, + {"MemStats.TotalAlloc", Field, 0}, + {"MutexProfile", Func, 8}, + {"NumCPU", Func, 0}, + {"NumCgoCall", Func, 0}, + {"NumGoroutine", Func, 0}, + {"PanicNilError", Type, 21}, + {"Pinner", Type, 21}, + {"ReadMemStats", Func, 0}, + {"ReadTrace", Func, 5}, + {"SetBlockProfileRate", Func, 1}, + {"SetCPUProfileRate", Func, 0}, + {"SetCgoTraceback", Func, 7}, + {"SetFinalizer", Func, 0}, + {"SetMutexProfileFraction", Func, 8}, + {"Stack", Func, 0}, + {"StackRecord", Type, 0}, + {"StackRecord.Stack0", Field, 0}, + {"StartTrace", Func, 5}, + {"StopTrace", Func, 5}, + {"ThreadCreateProfile", Func, 0}, + {"TypeAssertionError", Type, 0}, + {"UnlockOSThread", Func, 0}, + {"Version", Func, 0}, + }, + "runtime/cgo": { + {"(Handle).Delete", Method, 17}, + {"(Handle).Value", Method, 17}, + {"Handle", Type, 17}, + {"Incomplete", Type, 20}, + {"NewHandle", Func, 17}, + }, + "runtime/coverage": { + {"ClearCounters", Func, 20}, + {"WriteCounters", Func, 20}, + {"WriteCountersDir", Func, 20}, + {"WriteMeta", Func, 20}, + {"WriteMetaDir", Func, 20}, + }, + "runtime/debug": { + {"(*BuildInfo).String", Method, 18}, + {"BuildInfo", Type, 12}, + {"BuildInfo.Deps", Field, 12}, + {"BuildInfo.GoVersion", Field, 18}, + {"BuildInfo.Main", Field, 12}, + {"BuildInfo.Path", Field, 12}, + {"BuildInfo.Settings", Field, 18}, + {"BuildSetting", Type, 18}, + {"BuildSetting.Key", Field, 18}, + {"BuildSetting.Value", Field, 18}, + {"CrashOptions", Type, 23}, + {"FreeOSMemory", Func, 1}, + {"GCStats", Type, 1}, + {"GCStats.LastGC", Field, 1}, + {"GCStats.NumGC", Field, 1}, + {"GCStats.Pause", Field, 1}, + {"GCStats.PauseEnd", Field, 4}, + {"GCStats.PauseQuantiles", Field, 1}, + {"GCStats.PauseTotal", Field, 1}, + {"Module", Type, 12}, + {"Module.Path", Field, 12}, + {"Module.Replace", Field, 12}, + {"Module.Sum", Field, 12}, + {"Module.Version", Field, 12}, + {"ParseBuildInfo", Func, 18}, + {"PrintStack", Func, 0}, + {"ReadBuildInfo", Func, 12}, + {"ReadGCStats", Func, 1}, + {"SetCrashOutput", Func, 23}, + {"SetGCPercent", Func, 1}, + {"SetMaxStack", Func, 2}, + {"SetMaxThreads", Func, 2}, + {"SetMemoryLimit", Func, 19}, + {"SetPanicOnFault", Func, 3}, + {"SetTraceback", Func, 6}, + {"Stack", Func, 0}, + {"WriteHeapDump", Func, 3}, + }, + "runtime/metrics": { + {"(Value).Float64", Method, 16}, + {"(Value).Float64Histogram", Method, 16}, + {"(Value).Kind", Method, 16}, + {"(Value).Uint64", Method, 16}, + {"All", Func, 16}, + {"Description", Type, 16}, + {"Description.Cumulative", Field, 16}, + {"Description.Description", Field, 16}, + {"Description.Kind", Field, 16}, + {"Description.Name", Field, 16}, + {"Float64Histogram", Type, 16}, + {"Float64Histogram.Buckets", Field, 16}, + {"Float64Histogram.Counts", Field, 16}, + {"KindBad", Const, 16}, + {"KindFloat64", Const, 16}, + {"KindFloat64Histogram", Const, 16}, + {"KindUint64", Const, 16}, + {"Read", Func, 16}, + {"Sample", Type, 16}, + {"Sample.Name", Field, 16}, + {"Sample.Value", Field, 16}, + {"Value", Type, 16}, + {"ValueKind", Type, 16}, + }, + "runtime/pprof": { + {"(*Profile).Add", Method, 0}, + {"(*Profile).Count", Method, 0}, + {"(*Profile).Name", Method, 0}, + {"(*Profile).Remove", Method, 0}, + {"(*Profile).WriteTo", Method, 0}, + {"Do", Func, 9}, + {"ForLabels", Func, 9}, + {"Label", Func, 9}, + {"LabelSet", Type, 9}, + {"Labels", Func, 9}, + {"Lookup", Func, 0}, + {"NewProfile", Func, 0}, + {"Profile", Type, 0}, + {"Profiles", Func, 0}, + {"SetGoroutineLabels", Func, 9}, + {"StartCPUProfile", Func, 0}, + {"StopCPUProfile", Func, 0}, + {"WithLabels", Func, 9}, + {"WriteHeapProfile", Func, 0}, + }, + "runtime/trace": { + {"(*Region).End", Method, 11}, + {"(*Task).End", Method, 11}, + {"IsEnabled", Func, 11}, + {"Log", Func, 11}, + {"Logf", Func, 11}, + {"NewTask", Func, 11}, + {"Region", Type, 11}, + {"Start", Func, 5}, + {"StartRegion", Func, 11}, + {"Stop", Func, 5}, + {"Task", Type, 11}, + {"WithRegion", Func, 11}, + }, + "slices": { + {"All", Func, 23}, + {"AppendSeq", Func, 23}, + {"Backward", Func, 23}, + {"BinarySearch", Func, 21}, + {"BinarySearchFunc", Func, 21}, + {"Chunk", Func, 23}, + {"Clip", Func, 21}, + {"Clone", Func, 21}, + {"Collect", Func, 23}, + {"Compact", Func, 21}, + {"CompactFunc", Func, 21}, + {"Compare", Func, 21}, + {"CompareFunc", Func, 21}, + {"Concat", Func, 22}, + {"Contains", Func, 21}, + {"ContainsFunc", Func, 21}, + {"Delete", Func, 21}, + {"DeleteFunc", Func, 21}, + {"Equal", Func, 21}, + {"EqualFunc", Func, 21}, + {"Grow", Func, 21}, + {"Index", Func, 21}, + {"IndexFunc", Func, 21}, + {"Insert", Func, 21}, + {"IsSorted", Func, 21}, + {"IsSortedFunc", Func, 21}, + {"Max", Func, 21}, + {"MaxFunc", Func, 21}, + {"Min", Func, 21}, + {"MinFunc", Func, 21}, + {"Repeat", Func, 23}, + {"Replace", Func, 21}, + {"Reverse", Func, 21}, + {"Sort", Func, 21}, + {"SortFunc", Func, 21}, + {"SortStableFunc", Func, 21}, + {"Sorted", Func, 23}, + {"SortedFunc", Func, 23}, + {"SortedStableFunc", Func, 23}, + {"Values", Func, 23}, + }, + "sort": { + {"(Float64Slice).Len", Method, 0}, + {"(Float64Slice).Less", Method, 0}, + {"(Float64Slice).Search", Method, 0}, + {"(Float64Slice).Sort", Method, 0}, + {"(Float64Slice).Swap", Method, 0}, + {"(IntSlice).Len", Method, 0}, + {"(IntSlice).Less", Method, 0}, + {"(IntSlice).Search", Method, 0}, + {"(IntSlice).Sort", Method, 0}, + {"(IntSlice).Swap", Method, 0}, + {"(StringSlice).Len", Method, 0}, + {"(StringSlice).Less", Method, 0}, + {"(StringSlice).Search", Method, 0}, + {"(StringSlice).Sort", Method, 0}, + {"(StringSlice).Swap", Method, 0}, + {"Find", Func, 19}, + {"Float64Slice", Type, 0}, + {"Float64s", Func, 0}, + {"Float64sAreSorted", Func, 0}, + {"IntSlice", Type, 0}, + {"Interface", Type, 0}, + {"Ints", Func, 0}, + {"IntsAreSorted", Func, 0}, + {"IsSorted", Func, 0}, + {"Reverse", Func, 1}, + {"Search", Func, 0}, + {"SearchFloat64s", Func, 0}, + {"SearchInts", Func, 0}, + {"SearchStrings", Func, 0}, + {"Slice", Func, 8}, + {"SliceIsSorted", Func, 8}, + {"SliceStable", Func, 8}, + {"Sort", Func, 0}, + {"Stable", Func, 2}, + {"StringSlice", Type, 0}, + {"Strings", Func, 0}, + {"StringsAreSorted", Func, 0}, + }, + "strconv": { + {"(*NumError).Error", Method, 0}, + {"(*NumError).Unwrap", Method, 14}, + {"AppendBool", Func, 0}, + {"AppendFloat", Func, 0}, + {"AppendInt", Func, 0}, + {"AppendQuote", Func, 0}, + {"AppendQuoteRune", Func, 0}, + {"AppendQuoteRuneToASCII", Func, 0}, + {"AppendQuoteRuneToGraphic", Func, 6}, + {"AppendQuoteToASCII", Func, 0}, + {"AppendQuoteToGraphic", Func, 6}, + {"AppendUint", Func, 0}, + {"Atoi", Func, 0}, + {"CanBackquote", Func, 0}, + {"ErrRange", Var, 0}, + {"ErrSyntax", Var, 0}, + {"FormatBool", Func, 0}, + {"FormatComplex", Func, 15}, + {"FormatFloat", Func, 0}, + {"FormatInt", Func, 0}, + {"FormatUint", Func, 0}, + {"IntSize", Const, 0}, + {"IsGraphic", Func, 6}, + {"IsPrint", Func, 0}, + {"Itoa", Func, 0}, + {"NumError", Type, 0}, + {"NumError.Err", Field, 0}, + {"NumError.Func", Field, 0}, + {"NumError.Num", Field, 0}, + {"ParseBool", Func, 0}, + {"ParseComplex", Func, 15}, + {"ParseFloat", Func, 0}, + {"ParseInt", Func, 0}, + {"ParseUint", Func, 0}, + {"Quote", Func, 0}, + {"QuoteRune", Func, 0}, + {"QuoteRuneToASCII", Func, 0}, + {"QuoteRuneToGraphic", Func, 6}, + {"QuoteToASCII", Func, 0}, + {"QuoteToGraphic", Func, 6}, + {"QuotedPrefix", Func, 17}, + {"Unquote", Func, 0}, + {"UnquoteChar", Func, 0}, + }, + "strings": { + {"(*Builder).Cap", Method, 12}, + {"(*Builder).Grow", Method, 10}, + {"(*Builder).Len", Method, 10}, + {"(*Builder).Reset", Method, 10}, + {"(*Builder).String", Method, 10}, + {"(*Builder).Write", Method, 10}, + {"(*Builder).WriteByte", Method, 10}, + {"(*Builder).WriteRune", Method, 10}, + {"(*Builder).WriteString", Method, 10}, + {"(*Reader).Len", Method, 0}, + {"(*Reader).Read", Method, 0}, + {"(*Reader).ReadAt", Method, 0}, + {"(*Reader).ReadByte", Method, 0}, + {"(*Reader).ReadRune", Method, 0}, + {"(*Reader).Reset", Method, 7}, + {"(*Reader).Seek", Method, 0}, + {"(*Reader).Size", Method, 5}, + {"(*Reader).UnreadByte", Method, 0}, + {"(*Reader).UnreadRune", Method, 0}, + {"(*Reader).WriteTo", Method, 1}, + {"(*Replacer).Replace", Method, 0}, + {"(*Replacer).WriteString", Method, 0}, + {"Builder", Type, 10}, + {"Clone", Func, 18}, + {"Compare", Func, 5}, + {"Contains", Func, 0}, + {"ContainsAny", Func, 0}, + {"ContainsFunc", Func, 21}, + {"ContainsRune", Func, 0}, + {"Count", Func, 0}, + {"Cut", Func, 18}, + {"CutPrefix", Func, 20}, + {"CutSuffix", Func, 20}, + {"EqualFold", Func, 0}, + {"Fields", Func, 0}, + {"FieldsFunc", Func, 0}, + {"HasPrefix", Func, 0}, + {"HasSuffix", Func, 0}, + {"Index", Func, 0}, + {"IndexAny", Func, 0}, + {"IndexByte", Func, 2}, + {"IndexFunc", Func, 0}, + {"IndexRune", Func, 0}, + {"Join", Func, 0}, + {"LastIndex", Func, 0}, + {"LastIndexAny", Func, 0}, + {"LastIndexByte", Func, 5}, + {"LastIndexFunc", Func, 0}, + {"Map", Func, 0}, + {"NewReader", Func, 0}, + {"NewReplacer", Func, 0}, + {"Reader", Type, 0}, + {"Repeat", Func, 0}, + {"Replace", Func, 0}, + {"ReplaceAll", Func, 12}, + {"Replacer", Type, 0}, + {"Split", Func, 0}, + {"SplitAfter", Func, 0}, + {"SplitAfterN", Func, 0}, + {"SplitN", Func, 0}, + {"Title", Func, 0}, + {"ToLower", Func, 0}, + {"ToLowerSpecial", Func, 0}, + {"ToTitle", Func, 0}, + {"ToTitleSpecial", Func, 0}, + {"ToUpper", Func, 0}, + {"ToUpperSpecial", Func, 0}, + {"ToValidUTF8", Func, 13}, + {"Trim", Func, 0}, + {"TrimFunc", Func, 0}, + {"TrimLeft", Func, 0}, + {"TrimLeftFunc", Func, 0}, + {"TrimPrefix", Func, 1}, + {"TrimRight", Func, 0}, + {"TrimRightFunc", Func, 0}, + {"TrimSpace", Func, 0}, + {"TrimSuffix", Func, 1}, + }, + "structs": { + {"HostLayout", Type, 23}, + }, + "sync": { + {"(*Cond).Broadcast", Method, 0}, + {"(*Cond).Signal", Method, 0}, + {"(*Cond).Wait", Method, 0}, + {"(*Map).Clear", Method, 23}, + {"(*Map).CompareAndDelete", Method, 20}, + {"(*Map).CompareAndSwap", Method, 20}, + {"(*Map).Delete", Method, 9}, + {"(*Map).Load", Method, 9}, + {"(*Map).LoadAndDelete", Method, 15}, + {"(*Map).LoadOrStore", Method, 9}, + {"(*Map).Range", Method, 9}, + {"(*Map).Store", Method, 9}, + {"(*Map).Swap", Method, 20}, + {"(*Mutex).Lock", Method, 0}, + {"(*Mutex).TryLock", Method, 18}, + {"(*Mutex).Unlock", Method, 0}, + {"(*Once).Do", Method, 0}, + {"(*Pool).Get", Method, 3}, + {"(*Pool).Put", Method, 3}, + {"(*RWMutex).Lock", Method, 0}, + {"(*RWMutex).RLock", Method, 0}, + {"(*RWMutex).RLocker", Method, 0}, + {"(*RWMutex).RUnlock", Method, 0}, + {"(*RWMutex).TryLock", Method, 18}, + {"(*RWMutex).TryRLock", Method, 18}, + {"(*RWMutex).Unlock", Method, 0}, + {"(*WaitGroup).Add", Method, 0}, + {"(*WaitGroup).Done", Method, 0}, + {"(*WaitGroup).Wait", Method, 0}, + {"Cond", Type, 0}, + {"Cond.L", Field, 0}, + {"Locker", Type, 0}, + {"Map", Type, 9}, + {"Mutex", Type, 0}, + {"NewCond", Func, 0}, + {"Once", Type, 0}, + {"OnceFunc", Func, 21}, + {"OnceValue", Func, 21}, + {"OnceValues", Func, 21}, + {"Pool", Type, 3}, + {"Pool.New", Field, 3}, + {"RWMutex", Type, 0}, + {"WaitGroup", Type, 0}, + }, + "sync/atomic": { + {"(*Bool).CompareAndSwap", Method, 19}, + {"(*Bool).Load", Method, 19}, + {"(*Bool).Store", Method, 19}, + {"(*Bool).Swap", Method, 19}, + {"(*Int32).Add", Method, 19}, + {"(*Int32).And", Method, 23}, + {"(*Int32).CompareAndSwap", Method, 19}, + {"(*Int32).Load", Method, 19}, + {"(*Int32).Or", Method, 23}, + {"(*Int32).Store", Method, 19}, + {"(*Int32).Swap", Method, 19}, + {"(*Int64).Add", Method, 19}, + {"(*Int64).And", Method, 23}, + {"(*Int64).CompareAndSwap", Method, 19}, + {"(*Int64).Load", Method, 19}, + {"(*Int64).Or", Method, 23}, + {"(*Int64).Store", Method, 19}, + {"(*Int64).Swap", Method, 19}, + {"(*Pointer).CompareAndSwap", Method, 19}, + {"(*Pointer).Load", Method, 19}, + {"(*Pointer).Store", Method, 19}, + {"(*Pointer).Swap", Method, 19}, + {"(*Uint32).Add", Method, 19}, + {"(*Uint32).And", Method, 23}, + {"(*Uint32).CompareAndSwap", Method, 19}, + {"(*Uint32).Load", Method, 19}, + {"(*Uint32).Or", Method, 23}, + {"(*Uint32).Store", Method, 19}, + {"(*Uint32).Swap", Method, 19}, + {"(*Uint64).Add", Method, 19}, + {"(*Uint64).And", Method, 23}, + {"(*Uint64).CompareAndSwap", Method, 19}, + {"(*Uint64).Load", Method, 19}, + {"(*Uint64).Or", Method, 23}, + {"(*Uint64).Store", Method, 19}, + {"(*Uint64).Swap", Method, 19}, + {"(*Uintptr).Add", Method, 19}, + {"(*Uintptr).And", Method, 23}, + {"(*Uintptr).CompareAndSwap", Method, 19}, + {"(*Uintptr).Load", Method, 19}, + {"(*Uintptr).Or", Method, 23}, + {"(*Uintptr).Store", Method, 19}, + {"(*Uintptr).Swap", Method, 19}, + {"(*Value).CompareAndSwap", Method, 17}, + {"(*Value).Load", Method, 4}, + {"(*Value).Store", Method, 4}, + {"(*Value).Swap", Method, 17}, + {"AddInt32", Func, 0}, + {"AddInt64", Func, 0}, + {"AddUint32", Func, 0}, + {"AddUint64", Func, 0}, + {"AddUintptr", Func, 0}, + {"AndInt32", Func, 23}, + {"AndInt64", Func, 23}, + {"AndUint32", Func, 23}, + {"AndUint64", Func, 23}, + {"AndUintptr", Func, 23}, + {"Bool", Type, 19}, + {"CompareAndSwapInt32", Func, 0}, + {"CompareAndSwapInt64", Func, 0}, + {"CompareAndSwapPointer", Func, 0}, + {"CompareAndSwapUint32", Func, 0}, + {"CompareAndSwapUint64", Func, 0}, + {"CompareAndSwapUintptr", Func, 0}, + {"Int32", Type, 19}, + {"Int64", Type, 19}, + {"LoadInt32", Func, 0}, + {"LoadInt64", Func, 0}, + {"LoadPointer", Func, 0}, + {"LoadUint32", Func, 0}, + {"LoadUint64", Func, 0}, + {"LoadUintptr", Func, 0}, + {"OrInt32", Func, 23}, + {"OrInt64", Func, 23}, + {"OrUint32", Func, 23}, + {"OrUint64", Func, 23}, + {"OrUintptr", Func, 23}, + {"Pointer", Type, 19}, + {"StoreInt32", Func, 0}, + {"StoreInt64", Func, 0}, + {"StorePointer", Func, 0}, + {"StoreUint32", Func, 0}, + {"StoreUint64", Func, 0}, + {"StoreUintptr", Func, 0}, + {"SwapInt32", Func, 2}, + {"SwapInt64", Func, 2}, + {"SwapPointer", Func, 2}, + {"SwapUint32", Func, 2}, + {"SwapUint64", Func, 2}, + {"SwapUintptr", Func, 2}, + {"Uint32", Type, 19}, + {"Uint64", Type, 19}, + {"Uintptr", Type, 19}, + {"Value", Type, 4}, + }, + "syscall": { + {"(*Cmsghdr).SetLen", Method, 0}, + {"(*DLL).FindProc", Method, 0}, + {"(*DLL).MustFindProc", Method, 0}, + {"(*DLL).Release", Method, 0}, + {"(*DLLError).Error", Method, 0}, + {"(*DLLError).Unwrap", Method, 16}, + {"(*Filetime).Nanoseconds", Method, 0}, + {"(*Iovec).SetLen", Method, 0}, + {"(*LazyDLL).Handle", Method, 0}, + {"(*LazyDLL).Load", Method, 0}, + {"(*LazyDLL).NewProc", Method, 0}, + {"(*LazyProc).Addr", Method, 0}, + {"(*LazyProc).Call", Method, 0}, + {"(*LazyProc).Find", Method, 0}, + {"(*Msghdr).SetControllen", Method, 0}, + {"(*Proc).Addr", Method, 0}, + {"(*Proc).Call", Method, 0}, + {"(*PtraceRegs).PC", Method, 0}, + {"(*PtraceRegs).SetPC", Method, 0}, + {"(*RawSockaddrAny).Sockaddr", Method, 0}, + {"(*SID).Copy", Method, 0}, + {"(*SID).Len", Method, 0}, + {"(*SID).LookupAccount", Method, 0}, + {"(*SID).String", Method, 0}, + {"(*Timespec).Nano", Method, 0}, + {"(*Timespec).Unix", Method, 0}, + {"(*Timeval).Nano", Method, 0}, + {"(*Timeval).Nanoseconds", Method, 0}, + {"(*Timeval).Unix", Method, 0}, + {"(Errno).Error", Method, 0}, + {"(Errno).Is", Method, 13}, + {"(Errno).Temporary", Method, 0}, + {"(Errno).Timeout", Method, 0}, + {"(Signal).Signal", Method, 0}, + {"(Signal).String", Method, 0}, + {"(Token).Close", Method, 0}, + {"(Token).GetTokenPrimaryGroup", Method, 0}, + {"(Token).GetTokenUser", Method, 0}, + {"(Token).GetUserProfileDirectory", Method, 0}, + {"(WaitStatus).Continued", Method, 0}, + {"(WaitStatus).CoreDump", Method, 0}, + {"(WaitStatus).ExitStatus", Method, 0}, + {"(WaitStatus).Exited", Method, 0}, + {"(WaitStatus).Signal", Method, 0}, + {"(WaitStatus).Signaled", Method, 0}, + {"(WaitStatus).StopSignal", Method, 0}, + {"(WaitStatus).Stopped", Method, 0}, + {"(WaitStatus).TrapCause", Method, 0}, + {"AF_ALG", Const, 0}, + {"AF_APPLETALK", Const, 0}, + {"AF_ARP", Const, 0}, + {"AF_ASH", Const, 0}, + {"AF_ATM", Const, 0}, + {"AF_ATMPVC", Const, 0}, + {"AF_ATMSVC", Const, 0}, + {"AF_AX25", Const, 0}, + {"AF_BLUETOOTH", Const, 0}, + {"AF_BRIDGE", Const, 0}, + {"AF_CAIF", Const, 0}, + {"AF_CAN", Const, 0}, + {"AF_CCITT", Const, 0}, + {"AF_CHAOS", Const, 0}, + {"AF_CNT", Const, 0}, + {"AF_COIP", Const, 0}, + {"AF_DATAKIT", Const, 0}, + {"AF_DECnet", Const, 0}, + {"AF_DLI", Const, 0}, + {"AF_E164", Const, 0}, + {"AF_ECMA", Const, 0}, + {"AF_ECONET", Const, 0}, + {"AF_ENCAP", Const, 1}, + {"AF_FILE", Const, 0}, + {"AF_HYLINK", Const, 0}, + {"AF_IEEE80211", Const, 0}, + {"AF_IEEE802154", Const, 0}, + {"AF_IMPLINK", Const, 0}, + {"AF_INET", Const, 0}, + {"AF_INET6", Const, 0}, + {"AF_INET6_SDP", Const, 3}, + {"AF_INET_SDP", Const, 3}, + {"AF_IPX", Const, 0}, + {"AF_IRDA", Const, 0}, + {"AF_ISDN", Const, 0}, + {"AF_ISO", Const, 0}, + {"AF_IUCV", Const, 0}, + {"AF_KEY", Const, 0}, + {"AF_LAT", Const, 0}, + {"AF_LINK", Const, 0}, + {"AF_LLC", Const, 0}, + {"AF_LOCAL", Const, 0}, + {"AF_MAX", Const, 0}, + {"AF_MPLS", Const, 1}, + {"AF_NATM", Const, 0}, + {"AF_NDRV", Const, 0}, + {"AF_NETBEUI", Const, 0}, + {"AF_NETBIOS", Const, 0}, + {"AF_NETGRAPH", Const, 0}, + {"AF_NETLINK", Const, 0}, + {"AF_NETROM", Const, 0}, + {"AF_NS", Const, 0}, + {"AF_OROUTE", Const, 1}, + {"AF_OSI", Const, 0}, + {"AF_PACKET", Const, 0}, + {"AF_PHONET", Const, 0}, + {"AF_PPP", Const, 0}, + {"AF_PPPOX", Const, 0}, + {"AF_PUP", Const, 0}, + {"AF_RDS", Const, 0}, + {"AF_RESERVED_36", Const, 0}, + {"AF_ROSE", Const, 0}, + {"AF_ROUTE", Const, 0}, + {"AF_RXRPC", Const, 0}, + {"AF_SCLUSTER", Const, 0}, + {"AF_SECURITY", Const, 0}, + {"AF_SIP", Const, 0}, + {"AF_SLOW", Const, 0}, + {"AF_SNA", Const, 0}, + {"AF_SYSTEM", Const, 0}, + {"AF_TIPC", Const, 0}, + {"AF_UNIX", Const, 0}, + {"AF_UNSPEC", Const, 0}, + {"AF_UTUN", Const, 16}, + {"AF_VENDOR00", Const, 0}, + {"AF_VENDOR01", Const, 0}, + {"AF_VENDOR02", Const, 0}, + {"AF_VENDOR03", Const, 0}, + {"AF_VENDOR04", Const, 0}, + {"AF_VENDOR05", Const, 0}, + {"AF_VENDOR06", Const, 0}, + {"AF_VENDOR07", Const, 0}, + {"AF_VENDOR08", Const, 0}, + {"AF_VENDOR09", Const, 0}, + {"AF_VENDOR10", Const, 0}, + {"AF_VENDOR11", Const, 0}, + {"AF_VENDOR12", Const, 0}, + {"AF_VENDOR13", Const, 0}, + {"AF_VENDOR14", Const, 0}, + {"AF_VENDOR15", Const, 0}, + {"AF_VENDOR16", Const, 0}, + {"AF_VENDOR17", Const, 0}, + {"AF_VENDOR18", Const, 0}, + {"AF_VENDOR19", Const, 0}, + {"AF_VENDOR20", Const, 0}, + {"AF_VENDOR21", Const, 0}, + {"AF_VENDOR22", Const, 0}, + {"AF_VENDOR23", Const, 0}, + {"AF_VENDOR24", Const, 0}, + {"AF_VENDOR25", Const, 0}, + {"AF_VENDOR26", Const, 0}, + {"AF_VENDOR27", Const, 0}, + {"AF_VENDOR28", Const, 0}, + {"AF_VENDOR29", Const, 0}, + {"AF_VENDOR30", Const, 0}, + {"AF_VENDOR31", Const, 0}, + {"AF_VENDOR32", Const, 0}, + {"AF_VENDOR33", Const, 0}, + {"AF_VENDOR34", Const, 0}, + {"AF_VENDOR35", Const, 0}, + {"AF_VENDOR36", Const, 0}, + {"AF_VENDOR37", Const, 0}, + {"AF_VENDOR38", Const, 0}, + {"AF_VENDOR39", Const, 0}, + {"AF_VENDOR40", Const, 0}, + {"AF_VENDOR41", Const, 0}, + {"AF_VENDOR42", Const, 0}, + {"AF_VENDOR43", Const, 0}, + {"AF_VENDOR44", Const, 0}, + {"AF_VENDOR45", Const, 0}, + {"AF_VENDOR46", Const, 0}, + {"AF_VENDOR47", Const, 0}, + {"AF_WANPIPE", Const, 0}, + {"AF_X25", Const, 0}, + {"AI_CANONNAME", Const, 1}, + {"AI_NUMERICHOST", Const, 1}, + {"AI_PASSIVE", Const, 1}, + {"APPLICATION_ERROR", Const, 0}, + {"ARPHRD_ADAPT", Const, 0}, + {"ARPHRD_APPLETLK", Const, 0}, + {"ARPHRD_ARCNET", Const, 0}, + {"ARPHRD_ASH", Const, 0}, + {"ARPHRD_ATM", Const, 0}, + {"ARPHRD_AX25", Const, 0}, + {"ARPHRD_BIF", Const, 0}, + {"ARPHRD_CHAOS", Const, 0}, + {"ARPHRD_CISCO", Const, 0}, + {"ARPHRD_CSLIP", Const, 0}, + {"ARPHRD_CSLIP6", Const, 0}, + {"ARPHRD_DDCMP", Const, 0}, + {"ARPHRD_DLCI", Const, 0}, + {"ARPHRD_ECONET", Const, 0}, + {"ARPHRD_EETHER", Const, 0}, + {"ARPHRD_ETHER", Const, 0}, + {"ARPHRD_EUI64", Const, 0}, + {"ARPHRD_FCAL", Const, 0}, + {"ARPHRD_FCFABRIC", Const, 0}, + {"ARPHRD_FCPL", Const, 0}, + {"ARPHRD_FCPP", Const, 0}, + {"ARPHRD_FDDI", Const, 0}, + {"ARPHRD_FRAD", Const, 0}, + {"ARPHRD_FRELAY", Const, 1}, + {"ARPHRD_HDLC", Const, 0}, + {"ARPHRD_HIPPI", Const, 0}, + {"ARPHRD_HWX25", Const, 0}, + {"ARPHRD_IEEE1394", Const, 0}, + {"ARPHRD_IEEE802", Const, 0}, + {"ARPHRD_IEEE80211", Const, 0}, + {"ARPHRD_IEEE80211_PRISM", Const, 0}, + {"ARPHRD_IEEE80211_RADIOTAP", Const, 0}, + {"ARPHRD_IEEE802154", Const, 0}, + {"ARPHRD_IEEE802154_PHY", Const, 0}, + {"ARPHRD_IEEE802_TR", Const, 0}, + {"ARPHRD_INFINIBAND", Const, 0}, + {"ARPHRD_IPDDP", Const, 0}, + {"ARPHRD_IPGRE", Const, 0}, + {"ARPHRD_IRDA", Const, 0}, + {"ARPHRD_LAPB", Const, 0}, + {"ARPHRD_LOCALTLK", Const, 0}, + {"ARPHRD_LOOPBACK", Const, 0}, + {"ARPHRD_METRICOM", Const, 0}, + {"ARPHRD_NETROM", Const, 0}, + {"ARPHRD_NONE", Const, 0}, + {"ARPHRD_PIMREG", Const, 0}, + {"ARPHRD_PPP", Const, 0}, + {"ARPHRD_PRONET", Const, 0}, + {"ARPHRD_RAWHDLC", Const, 0}, + {"ARPHRD_ROSE", Const, 0}, + {"ARPHRD_RSRVD", Const, 0}, + {"ARPHRD_SIT", Const, 0}, + {"ARPHRD_SKIP", Const, 0}, + {"ARPHRD_SLIP", Const, 0}, + {"ARPHRD_SLIP6", Const, 0}, + {"ARPHRD_STRIP", Const, 1}, + {"ARPHRD_TUNNEL", Const, 0}, + {"ARPHRD_TUNNEL6", Const, 0}, + {"ARPHRD_VOID", Const, 0}, + {"ARPHRD_X25", Const, 0}, + {"AUTHTYPE_CLIENT", Const, 0}, + {"AUTHTYPE_SERVER", Const, 0}, + {"Accept", Func, 0}, + {"Accept4", Func, 1}, + {"AcceptEx", Func, 0}, + {"Access", Func, 0}, + {"Acct", Func, 0}, + {"AddrinfoW", Type, 1}, + {"AddrinfoW.Addr", Field, 1}, + {"AddrinfoW.Addrlen", Field, 1}, + {"AddrinfoW.Canonname", Field, 1}, + {"AddrinfoW.Family", Field, 1}, + {"AddrinfoW.Flags", Field, 1}, + {"AddrinfoW.Next", Field, 1}, + {"AddrinfoW.Protocol", Field, 1}, + {"AddrinfoW.Socktype", Field, 1}, + {"Adjtime", Func, 0}, + {"Adjtimex", Func, 0}, + {"AllThreadsSyscall", Func, 16}, + {"AllThreadsSyscall6", Func, 16}, + {"AttachLsf", Func, 0}, + {"B0", Const, 0}, + {"B1000000", Const, 0}, + {"B110", Const, 0}, + {"B115200", Const, 0}, + {"B1152000", Const, 0}, + {"B1200", Const, 0}, + {"B134", Const, 0}, + {"B14400", Const, 1}, + {"B150", Const, 0}, + {"B1500000", Const, 0}, + {"B1800", Const, 0}, + {"B19200", Const, 0}, + {"B200", Const, 0}, + {"B2000000", Const, 0}, + {"B230400", Const, 0}, + {"B2400", Const, 0}, + {"B2500000", Const, 0}, + {"B28800", Const, 1}, + {"B300", Const, 0}, + {"B3000000", Const, 0}, + {"B3500000", Const, 0}, + {"B38400", Const, 0}, + {"B4000000", Const, 0}, + {"B460800", Const, 0}, + {"B4800", Const, 0}, + {"B50", Const, 0}, + {"B500000", Const, 0}, + {"B57600", Const, 0}, + {"B576000", Const, 0}, + {"B600", Const, 0}, + {"B7200", Const, 1}, + {"B75", Const, 0}, + {"B76800", Const, 1}, + {"B921600", Const, 0}, + {"B9600", Const, 0}, + {"BASE_PROTOCOL", Const, 2}, + {"BIOCFEEDBACK", Const, 0}, + {"BIOCFLUSH", Const, 0}, + {"BIOCGBLEN", Const, 0}, + {"BIOCGDIRECTION", Const, 0}, + {"BIOCGDIRFILT", Const, 1}, + {"BIOCGDLT", Const, 0}, + {"BIOCGDLTLIST", Const, 0}, + {"BIOCGETBUFMODE", Const, 0}, + {"BIOCGETIF", Const, 0}, + {"BIOCGETZMAX", Const, 0}, + {"BIOCGFEEDBACK", Const, 1}, + {"BIOCGFILDROP", Const, 1}, + {"BIOCGHDRCMPLT", Const, 0}, + {"BIOCGRSIG", Const, 0}, + {"BIOCGRTIMEOUT", Const, 0}, + {"BIOCGSEESENT", Const, 0}, + {"BIOCGSTATS", Const, 0}, + {"BIOCGSTATSOLD", Const, 1}, + {"BIOCGTSTAMP", Const, 1}, + {"BIOCIMMEDIATE", Const, 0}, + {"BIOCLOCK", Const, 0}, + {"BIOCPROMISC", Const, 0}, + {"BIOCROTZBUF", Const, 0}, + {"BIOCSBLEN", Const, 0}, + {"BIOCSDIRECTION", Const, 0}, + {"BIOCSDIRFILT", Const, 1}, + {"BIOCSDLT", Const, 0}, + {"BIOCSETBUFMODE", Const, 0}, + {"BIOCSETF", Const, 0}, + {"BIOCSETFNR", Const, 0}, + {"BIOCSETIF", Const, 0}, + {"BIOCSETWF", Const, 0}, + {"BIOCSETZBUF", Const, 0}, + {"BIOCSFEEDBACK", Const, 1}, + {"BIOCSFILDROP", Const, 1}, + {"BIOCSHDRCMPLT", Const, 0}, + {"BIOCSRSIG", Const, 0}, + {"BIOCSRTIMEOUT", Const, 0}, + {"BIOCSSEESENT", Const, 0}, + {"BIOCSTCPF", Const, 1}, + {"BIOCSTSTAMP", Const, 1}, + {"BIOCSUDPF", Const, 1}, + {"BIOCVERSION", Const, 0}, + {"BPF_A", Const, 0}, + {"BPF_ABS", Const, 0}, + {"BPF_ADD", Const, 0}, + {"BPF_ALIGNMENT", Const, 0}, + {"BPF_ALIGNMENT32", Const, 1}, + {"BPF_ALU", Const, 0}, + {"BPF_AND", Const, 0}, + {"BPF_B", Const, 0}, + {"BPF_BUFMODE_BUFFER", Const, 0}, + {"BPF_BUFMODE_ZBUF", Const, 0}, + {"BPF_DFLTBUFSIZE", Const, 1}, + {"BPF_DIRECTION_IN", Const, 1}, + {"BPF_DIRECTION_OUT", Const, 1}, + {"BPF_DIV", Const, 0}, + {"BPF_H", Const, 0}, + {"BPF_IMM", Const, 0}, + {"BPF_IND", Const, 0}, + {"BPF_JA", Const, 0}, + {"BPF_JEQ", Const, 0}, + {"BPF_JGE", Const, 0}, + {"BPF_JGT", Const, 0}, + {"BPF_JMP", Const, 0}, + {"BPF_JSET", Const, 0}, + {"BPF_K", Const, 0}, + {"BPF_LD", Const, 0}, + {"BPF_LDX", Const, 0}, + {"BPF_LEN", Const, 0}, + {"BPF_LSH", Const, 0}, + {"BPF_MAJOR_VERSION", Const, 0}, + {"BPF_MAXBUFSIZE", Const, 0}, + {"BPF_MAXINSNS", Const, 0}, + {"BPF_MEM", Const, 0}, + {"BPF_MEMWORDS", Const, 0}, + {"BPF_MINBUFSIZE", Const, 0}, + {"BPF_MINOR_VERSION", Const, 0}, + {"BPF_MISC", Const, 0}, + {"BPF_MSH", Const, 0}, + {"BPF_MUL", Const, 0}, + {"BPF_NEG", Const, 0}, + {"BPF_OR", Const, 0}, + {"BPF_RELEASE", Const, 0}, + {"BPF_RET", Const, 0}, + {"BPF_RSH", Const, 0}, + {"BPF_ST", Const, 0}, + {"BPF_STX", Const, 0}, + {"BPF_SUB", Const, 0}, + {"BPF_TAX", Const, 0}, + {"BPF_TXA", Const, 0}, + {"BPF_T_BINTIME", Const, 1}, + {"BPF_T_BINTIME_FAST", Const, 1}, + {"BPF_T_BINTIME_MONOTONIC", Const, 1}, + {"BPF_T_BINTIME_MONOTONIC_FAST", Const, 1}, + {"BPF_T_FAST", Const, 1}, + {"BPF_T_FLAG_MASK", Const, 1}, + {"BPF_T_FORMAT_MASK", Const, 1}, + {"BPF_T_MICROTIME", Const, 1}, + {"BPF_T_MICROTIME_FAST", Const, 1}, + {"BPF_T_MICROTIME_MONOTONIC", Const, 1}, + {"BPF_T_MICROTIME_MONOTONIC_FAST", Const, 1}, + {"BPF_T_MONOTONIC", Const, 1}, + {"BPF_T_MONOTONIC_FAST", Const, 1}, + {"BPF_T_NANOTIME", Const, 1}, + {"BPF_T_NANOTIME_FAST", Const, 1}, + {"BPF_T_NANOTIME_MONOTONIC", Const, 1}, + {"BPF_T_NANOTIME_MONOTONIC_FAST", Const, 1}, + {"BPF_T_NONE", Const, 1}, + {"BPF_T_NORMAL", Const, 1}, + {"BPF_W", Const, 0}, + {"BPF_X", Const, 0}, + {"BRKINT", Const, 0}, + {"Bind", Func, 0}, + {"BindToDevice", Func, 0}, + {"BpfBuflen", Func, 0}, + {"BpfDatalink", Func, 0}, + {"BpfHdr", Type, 0}, + {"BpfHdr.Caplen", Field, 0}, + {"BpfHdr.Datalen", Field, 0}, + {"BpfHdr.Hdrlen", Field, 0}, + {"BpfHdr.Pad_cgo_0", Field, 0}, + {"BpfHdr.Tstamp", Field, 0}, + {"BpfHeadercmpl", Func, 0}, + {"BpfInsn", Type, 0}, + {"BpfInsn.Code", Field, 0}, + {"BpfInsn.Jf", Field, 0}, + {"BpfInsn.Jt", Field, 0}, + {"BpfInsn.K", Field, 0}, + {"BpfInterface", Func, 0}, + {"BpfJump", Func, 0}, + {"BpfProgram", Type, 0}, + {"BpfProgram.Insns", Field, 0}, + {"BpfProgram.Len", Field, 0}, + {"BpfProgram.Pad_cgo_0", Field, 0}, + {"BpfStat", Type, 0}, + {"BpfStat.Capt", Field, 2}, + {"BpfStat.Drop", Field, 0}, + {"BpfStat.Padding", Field, 2}, + {"BpfStat.Recv", Field, 0}, + {"BpfStats", Func, 0}, + {"BpfStmt", Func, 0}, + {"BpfTimeout", Func, 0}, + {"BpfTimeval", Type, 2}, + {"BpfTimeval.Sec", Field, 2}, + {"BpfTimeval.Usec", Field, 2}, + {"BpfVersion", Type, 0}, + {"BpfVersion.Major", Field, 0}, + {"BpfVersion.Minor", Field, 0}, + {"BpfZbuf", Type, 0}, + {"BpfZbuf.Bufa", Field, 0}, + {"BpfZbuf.Bufb", Field, 0}, + {"BpfZbuf.Buflen", Field, 0}, + {"BpfZbufHeader", Type, 0}, + {"BpfZbufHeader.Kernel_gen", Field, 0}, + {"BpfZbufHeader.Kernel_len", Field, 0}, + {"BpfZbufHeader.User_gen", Field, 0}, + {"BpfZbufHeader.X_bzh_pad", Field, 0}, + {"ByHandleFileInformation", Type, 0}, + {"ByHandleFileInformation.CreationTime", Field, 0}, + {"ByHandleFileInformation.FileAttributes", Field, 0}, + {"ByHandleFileInformation.FileIndexHigh", Field, 0}, + {"ByHandleFileInformation.FileIndexLow", Field, 0}, + {"ByHandleFileInformation.FileSizeHigh", Field, 0}, + {"ByHandleFileInformation.FileSizeLow", Field, 0}, + {"ByHandleFileInformation.LastAccessTime", Field, 0}, + {"ByHandleFileInformation.LastWriteTime", Field, 0}, + {"ByHandleFileInformation.NumberOfLinks", Field, 0}, + {"ByHandleFileInformation.VolumeSerialNumber", Field, 0}, + {"BytePtrFromString", Func, 1}, + {"ByteSliceFromString", Func, 1}, + {"CCR0_FLUSH", Const, 1}, + {"CERT_CHAIN_POLICY_AUTHENTICODE", Const, 0}, + {"CERT_CHAIN_POLICY_AUTHENTICODE_TS", Const, 0}, + {"CERT_CHAIN_POLICY_BASE", Const, 0}, + {"CERT_CHAIN_POLICY_BASIC_CONSTRAINTS", Const, 0}, + {"CERT_CHAIN_POLICY_EV", Const, 0}, + {"CERT_CHAIN_POLICY_MICROSOFT_ROOT", Const, 0}, + {"CERT_CHAIN_POLICY_NT_AUTH", Const, 0}, + {"CERT_CHAIN_POLICY_SSL", Const, 0}, + {"CERT_E_CN_NO_MATCH", Const, 0}, + {"CERT_E_EXPIRED", Const, 0}, + {"CERT_E_PURPOSE", Const, 0}, + {"CERT_E_ROLE", Const, 0}, + {"CERT_E_UNTRUSTEDROOT", Const, 0}, + {"CERT_STORE_ADD_ALWAYS", Const, 0}, + {"CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG", Const, 0}, + {"CERT_STORE_PROV_MEMORY", Const, 0}, + {"CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT", Const, 0}, + {"CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT", Const, 0}, + {"CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT", Const, 0}, + {"CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT", Const, 0}, + {"CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT", Const, 0}, + {"CERT_TRUST_INVALID_BASIC_CONSTRAINTS", Const, 0}, + {"CERT_TRUST_INVALID_EXTENSION", Const, 0}, + {"CERT_TRUST_INVALID_NAME_CONSTRAINTS", Const, 0}, + {"CERT_TRUST_INVALID_POLICY_CONSTRAINTS", Const, 0}, + {"CERT_TRUST_IS_CYCLIC", Const, 0}, + {"CERT_TRUST_IS_EXPLICIT_DISTRUST", Const, 0}, + {"CERT_TRUST_IS_NOT_SIGNATURE_VALID", Const, 0}, + {"CERT_TRUST_IS_NOT_TIME_VALID", Const, 0}, + {"CERT_TRUST_IS_NOT_VALID_FOR_USAGE", Const, 0}, + {"CERT_TRUST_IS_OFFLINE_REVOCATION", Const, 0}, + {"CERT_TRUST_IS_REVOKED", Const, 0}, + {"CERT_TRUST_IS_UNTRUSTED_ROOT", Const, 0}, + {"CERT_TRUST_NO_ERROR", Const, 0}, + {"CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY", Const, 0}, + {"CERT_TRUST_REVOCATION_STATUS_UNKNOWN", Const, 0}, + {"CFLUSH", Const, 1}, + {"CLOCAL", Const, 0}, + {"CLONE_CHILD_CLEARTID", Const, 2}, + {"CLONE_CHILD_SETTID", Const, 2}, + {"CLONE_CLEAR_SIGHAND", Const, 20}, + {"CLONE_CSIGNAL", Const, 3}, + {"CLONE_DETACHED", Const, 2}, + {"CLONE_FILES", Const, 2}, + {"CLONE_FS", Const, 2}, + {"CLONE_INTO_CGROUP", Const, 20}, + {"CLONE_IO", Const, 2}, + {"CLONE_NEWCGROUP", Const, 20}, + {"CLONE_NEWIPC", Const, 2}, + {"CLONE_NEWNET", Const, 2}, + {"CLONE_NEWNS", Const, 2}, + {"CLONE_NEWPID", Const, 2}, + {"CLONE_NEWTIME", Const, 20}, + {"CLONE_NEWUSER", Const, 2}, + {"CLONE_NEWUTS", Const, 2}, + {"CLONE_PARENT", Const, 2}, + {"CLONE_PARENT_SETTID", Const, 2}, + {"CLONE_PID", Const, 3}, + {"CLONE_PIDFD", Const, 20}, + {"CLONE_PTRACE", Const, 2}, + {"CLONE_SETTLS", Const, 2}, + {"CLONE_SIGHAND", Const, 2}, + {"CLONE_SYSVSEM", Const, 2}, + {"CLONE_THREAD", Const, 2}, + {"CLONE_UNTRACED", Const, 2}, + {"CLONE_VFORK", Const, 2}, + {"CLONE_VM", Const, 2}, + {"CPUID_CFLUSH", Const, 1}, + {"CREAD", Const, 0}, + {"CREATE_ALWAYS", Const, 0}, + {"CREATE_NEW", Const, 0}, + {"CREATE_NEW_PROCESS_GROUP", Const, 1}, + {"CREATE_UNICODE_ENVIRONMENT", Const, 0}, + {"CRYPT_DEFAULT_CONTAINER_OPTIONAL", Const, 0}, + {"CRYPT_DELETEKEYSET", Const, 0}, + {"CRYPT_MACHINE_KEYSET", Const, 0}, + {"CRYPT_NEWKEYSET", Const, 0}, + {"CRYPT_SILENT", Const, 0}, + {"CRYPT_VERIFYCONTEXT", Const, 0}, + {"CS5", Const, 0}, + {"CS6", Const, 0}, + {"CS7", Const, 0}, + {"CS8", Const, 0}, + {"CSIZE", Const, 0}, + {"CSTART", Const, 1}, + {"CSTATUS", Const, 1}, + {"CSTOP", Const, 1}, + {"CSTOPB", Const, 0}, + {"CSUSP", Const, 1}, + {"CTL_MAXNAME", Const, 0}, + {"CTL_NET", Const, 0}, + {"CTL_QUERY", Const, 1}, + {"CTRL_BREAK_EVENT", Const, 1}, + {"CTRL_CLOSE_EVENT", Const, 14}, + {"CTRL_C_EVENT", Const, 1}, + {"CTRL_LOGOFF_EVENT", Const, 14}, + {"CTRL_SHUTDOWN_EVENT", Const, 14}, + {"CancelIo", Func, 0}, + {"CancelIoEx", Func, 1}, + {"CertAddCertificateContextToStore", Func, 0}, + {"CertChainContext", Type, 0}, + {"CertChainContext.ChainCount", Field, 0}, + {"CertChainContext.Chains", Field, 0}, + {"CertChainContext.HasRevocationFreshnessTime", Field, 0}, + {"CertChainContext.LowerQualityChainCount", Field, 0}, + {"CertChainContext.LowerQualityChains", Field, 0}, + {"CertChainContext.RevocationFreshnessTime", Field, 0}, + {"CertChainContext.Size", Field, 0}, + {"CertChainContext.TrustStatus", Field, 0}, + {"CertChainElement", Type, 0}, + {"CertChainElement.ApplicationUsage", Field, 0}, + {"CertChainElement.CertContext", Field, 0}, + {"CertChainElement.ExtendedErrorInfo", Field, 0}, + {"CertChainElement.IssuanceUsage", Field, 0}, + {"CertChainElement.RevocationInfo", Field, 0}, + {"CertChainElement.Size", Field, 0}, + {"CertChainElement.TrustStatus", Field, 0}, + {"CertChainPara", Type, 0}, + {"CertChainPara.CacheResync", Field, 0}, + {"CertChainPara.CheckRevocationFreshnessTime", Field, 0}, + {"CertChainPara.RequestedUsage", Field, 0}, + {"CertChainPara.RequstedIssuancePolicy", Field, 0}, + {"CertChainPara.RevocationFreshnessTime", Field, 0}, + {"CertChainPara.Size", Field, 0}, + {"CertChainPara.URLRetrievalTimeout", Field, 0}, + {"CertChainPolicyPara", Type, 0}, + {"CertChainPolicyPara.ExtraPolicyPara", Field, 0}, + {"CertChainPolicyPara.Flags", Field, 0}, + {"CertChainPolicyPara.Size", Field, 0}, + {"CertChainPolicyStatus", Type, 0}, + {"CertChainPolicyStatus.ChainIndex", Field, 0}, + {"CertChainPolicyStatus.ElementIndex", Field, 0}, + {"CertChainPolicyStatus.Error", Field, 0}, + {"CertChainPolicyStatus.ExtraPolicyStatus", Field, 0}, + {"CertChainPolicyStatus.Size", Field, 0}, + {"CertCloseStore", Func, 0}, + {"CertContext", Type, 0}, + {"CertContext.CertInfo", Field, 0}, + {"CertContext.EncodedCert", Field, 0}, + {"CertContext.EncodingType", Field, 0}, + {"CertContext.Length", Field, 0}, + {"CertContext.Store", Field, 0}, + {"CertCreateCertificateContext", Func, 0}, + {"CertEnhKeyUsage", Type, 0}, + {"CertEnhKeyUsage.Length", Field, 0}, + {"CertEnhKeyUsage.UsageIdentifiers", Field, 0}, + {"CertEnumCertificatesInStore", Func, 0}, + {"CertFreeCertificateChain", Func, 0}, + {"CertFreeCertificateContext", Func, 0}, + {"CertGetCertificateChain", Func, 0}, + {"CertInfo", Type, 11}, + {"CertOpenStore", Func, 0}, + {"CertOpenSystemStore", Func, 0}, + {"CertRevocationCrlInfo", Type, 11}, + {"CertRevocationInfo", Type, 0}, + {"CertRevocationInfo.CrlInfo", Field, 0}, + {"CertRevocationInfo.FreshnessTime", Field, 0}, + {"CertRevocationInfo.HasFreshnessTime", Field, 0}, + {"CertRevocationInfo.OidSpecificInfo", Field, 0}, + {"CertRevocationInfo.RevocationOid", Field, 0}, + {"CertRevocationInfo.RevocationResult", Field, 0}, + {"CertRevocationInfo.Size", Field, 0}, + {"CertSimpleChain", Type, 0}, + {"CertSimpleChain.Elements", Field, 0}, + {"CertSimpleChain.HasRevocationFreshnessTime", Field, 0}, + {"CertSimpleChain.NumElements", Field, 0}, + {"CertSimpleChain.RevocationFreshnessTime", Field, 0}, + {"CertSimpleChain.Size", Field, 0}, + {"CertSimpleChain.TrustListInfo", Field, 0}, + {"CertSimpleChain.TrustStatus", Field, 0}, + {"CertTrustListInfo", Type, 11}, + {"CertTrustStatus", Type, 0}, + {"CertTrustStatus.ErrorStatus", Field, 0}, + {"CertTrustStatus.InfoStatus", Field, 0}, + {"CertUsageMatch", Type, 0}, + {"CertUsageMatch.Type", Field, 0}, + {"CertUsageMatch.Usage", Field, 0}, + {"CertVerifyCertificateChainPolicy", Func, 0}, + {"Chdir", Func, 0}, + {"CheckBpfVersion", Func, 0}, + {"Chflags", Func, 0}, + {"Chmod", Func, 0}, + {"Chown", Func, 0}, + {"Chroot", Func, 0}, + {"Clearenv", Func, 0}, + {"Close", Func, 0}, + {"CloseHandle", Func, 0}, + {"CloseOnExec", Func, 0}, + {"Closesocket", Func, 0}, + {"CmsgLen", Func, 0}, + {"CmsgSpace", Func, 0}, + {"Cmsghdr", Type, 0}, + {"Cmsghdr.Len", Field, 0}, + {"Cmsghdr.Level", Field, 0}, + {"Cmsghdr.Type", Field, 0}, + {"Cmsghdr.X__cmsg_data", Field, 0}, + {"CommandLineToArgv", Func, 0}, + {"ComputerName", Func, 0}, + {"Conn", Type, 9}, + {"Connect", Func, 0}, + {"ConnectEx", Func, 1}, + {"ConvertSidToStringSid", Func, 0}, + {"ConvertStringSidToSid", Func, 0}, + {"CopySid", Func, 0}, + {"Creat", Func, 0}, + {"CreateDirectory", Func, 0}, + {"CreateFile", Func, 0}, + {"CreateFileMapping", Func, 0}, + {"CreateHardLink", Func, 4}, + {"CreateIoCompletionPort", Func, 0}, + {"CreatePipe", Func, 0}, + {"CreateProcess", Func, 0}, + {"CreateProcessAsUser", Func, 10}, + {"CreateSymbolicLink", Func, 4}, + {"CreateToolhelp32Snapshot", Func, 4}, + {"Credential", Type, 0}, + {"Credential.Gid", Field, 0}, + {"Credential.Groups", Field, 0}, + {"Credential.NoSetGroups", Field, 9}, + {"Credential.Uid", Field, 0}, + {"CryptAcquireContext", Func, 0}, + {"CryptGenRandom", Func, 0}, + {"CryptReleaseContext", Func, 0}, + {"DIOCBSFLUSH", Const, 1}, + {"DIOCOSFPFLUSH", Const, 1}, + {"DLL", Type, 0}, + {"DLL.Handle", Field, 0}, + {"DLL.Name", Field, 0}, + {"DLLError", Type, 0}, + {"DLLError.Err", Field, 0}, + {"DLLError.Msg", Field, 0}, + {"DLLError.ObjName", Field, 0}, + {"DLT_A429", Const, 0}, + {"DLT_A653_ICM", Const, 0}, + {"DLT_AIRONET_HEADER", Const, 0}, + {"DLT_AOS", Const, 1}, + {"DLT_APPLE_IP_OVER_IEEE1394", Const, 0}, + {"DLT_ARCNET", Const, 0}, + {"DLT_ARCNET_LINUX", Const, 0}, + {"DLT_ATM_CLIP", Const, 0}, + {"DLT_ATM_RFC1483", Const, 0}, + {"DLT_AURORA", Const, 0}, + {"DLT_AX25", Const, 0}, + {"DLT_AX25_KISS", Const, 0}, + {"DLT_BACNET_MS_TP", Const, 0}, + {"DLT_BLUETOOTH_HCI_H4", Const, 0}, + {"DLT_BLUETOOTH_HCI_H4_WITH_PHDR", Const, 0}, + {"DLT_CAN20B", Const, 0}, + {"DLT_CAN_SOCKETCAN", Const, 1}, + {"DLT_CHAOS", Const, 0}, + {"DLT_CHDLC", Const, 0}, + {"DLT_CISCO_IOS", Const, 0}, + {"DLT_C_HDLC", Const, 0}, + {"DLT_C_HDLC_WITH_DIR", Const, 0}, + {"DLT_DBUS", Const, 1}, + {"DLT_DECT", Const, 1}, + {"DLT_DOCSIS", Const, 0}, + {"DLT_DVB_CI", Const, 1}, + {"DLT_ECONET", Const, 0}, + {"DLT_EN10MB", Const, 0}, + {"DLT_EN3MB", Const, 0}, + {"DLT_ENC", Const, 0}, + {"DLT_ERF", Const, 0}, + {"DLT_ERF_ETH", Const, 0}, + {"DLT_ERF_POS", Const, 0}, + {"DLT_FC_2", Const, 1}, + {"DLT_FC_2_WITH_FRAME_DELIMS", Const, 1}, + {"DLT_FDDI", Const, 0}, + {"DLT_FLEXRAY", Const, 0}, + {"DLT_FRELAY", Const, 0}, + {"DLT_FRELAY_WITH_DIR", Const, 0}, + {"DLT_GCOM_SERIAL", Const, 0}, + {"DLT_GCOM_T1E1", Const, 0}, + {"DLT_GPF_F", Const, 0}, + {"DLT_GPF_T", Const, 0}, + {"DLT_GPRS_LLC", Const, 0}, + {"DLT_GSMTAP_ABIS", Const, 1}, + {"DLT_GSMTAP_UM", Const, 1}, + {"DLT_HDLC", Const, 1}, + {"DLT_HHDLC", Const, 0}, + {"DLT_HIPPI", Const, 1}, + {"DLT_IBM_SN", Const, 0}, + {"DLT_IBM_SP", Const, 0}, + {"DLT_IEEE802", Const, 0}, + {"DLT_IEEE802_11", Const, 0}, + {"DLT_IEEE802_11_RADIO", Const, 0}, + {"DLT_IEEE802_11_RADIO_AVS", Const, 0}, + {"DLT_IEEE802_15_4", Const, 0}, + {"DLT_IEEE802_15_4_LINUX", Const, 0}, + {"DLT_IEEE802_15_4_NOFCS", Const, 1}, + {"DLT_IEEE802_15_4_NONASK_PHY", Const, 0}, + {"DLT_IEEE802_16_MAC_CPS", Const, 0}, + {"DLT_IEEE802_16_MAC_CPS_RADIO", Const, 0}, + {"DLT_IPFILTER", Const, 0}, + {"DLT_IPMB", Const, 0}, + {"DLT_IPMB_LINUX", Const, 0}, + {"DLT_IPNET", Const, 1}, + {"DLT_IPOIB", Const, 1}, + {"DLT_IPV4", Const, 1}, + {"DLT_IPV6", Const, 1}, + {"DLT_IP_OVER_FC", Const, 0}, + {"DLT_JUNIPER_ATM1", Const, 0}, + {"DLT_JUNIPER_ATM2", Const, 0}, + {"DLT_JUNIPER_ATM_CEMIC", Const, 1}, + {"DLT_JUNIPER_CHDLC", Const, 0}, + {"DLT_JUNIPER_ES", Const, 0}, + {"DLT_JUNIPER_ETHER", Const, 0}, + {"DLT_JUNIPER_FIBRECHANNEL", Const, 1}, + {"DLT_JUNIPER_FRELAY", Const, 0}, + {"DLT_JUNIPER_GGSN", Const, 0}, + {"DLT_JUNIPER_ISM", Const, 0}, + {"DLT_JUNIPER_MFR", Const, 0}, + {"DLT_JUNIPER_MLFR", Const, 0}, + {"DLT_JUNIPER_MLPPP", Const, 0}, + {"DLT_JUNIPER_MONITOR", Const, 0}, + {"DLT_JUNIPER_PIC_PEER", Const, 0}, + {"DLT_JUNIPER_PPP", Const, 0}, + {"DLT_JUNIPER_PPPOE", Const, 0}, + {"DLT_JUNIPER_PPPOE_ATM", Const, 0}, + {"DLT_JUNIPER_SERVICES", Const, 0}, + {"DLT_JUNIPER_SRX_E2E", Const, 1}, + {"DLT_JUNIPER_ST", Const, 0}, + {"DLT_JUNIPER_VP", Const, 0}, + {"DLT_JUNIPER_VS", Const, 1}, + {"DLT_LAPB_WITH_DIR", Const, 0}, + {"DLT_LAPD", Const, 0}, + {"DLT_LIN", Const, 0}, + {"DLT_LINUX_EVDEV", Const, 1}, + {"DLT_LINUX_IRDA", Const, 0}, + {"DLT_LINUX_LAPD", Const, 0}, + {"DLT_LINUX_PPP_WITHDIRECTION", Const, 0}, + {"DLT_LINUX_SLL", Const, 0}, + {"DLT_LOOP", Const, 0}, + {"DLT_LTALK", Const, 0}, + {"DLT_MATCHING_MAX", Const, 1}, + {"DLT_MATCHING_MIN", Const, 1}, + {"DLT_MFR", Const, 0}, + {"DLT_MOST", Const, 0}, + {"DLT_MPEG_2_TS", Const, 1}, + {"DLT_MPLS", Const, 1}, + {"DLT_MTP2", Const, 0}, + {"DLT_MTP2_WITH_PHDR", Const, 0}, + {"DLT_MTP3", Const, 0}, + {"DLT_MUX27010", Const, 1}, + {"DLT_NETANALYZER", Const, 1}, + {"DLT_NETANALYZER_TRANSPARENT", Const, 1}, + {"DLT_NFC_LLCP", Const, 1}, + {"DLT_NFLOG", Const, 1}, + {"DLT_NG40", Const, 1}, + {"DLT_NULL", Const, 0}, + {"DLT_PCI_EXP", Const, 0}, + {"DLT_PFLOG", Const, 0}, + {"DLT_PFSYNC", Const, 0}, + {"DLT_PPI", Const, 0}, + {"DLT_PPP", Const, 0}, + {"DLT_PPP_BSDOS", Const, 0}, + {"DLT_PPP_ETHER", Const, 0}, + {"DLT_PPP_PPPD", Const, 0}, + {"DLT_PPP_SERIAL", Const, 0}, + {"DLT_PPP_WITH_DIR", Const, 0}, + {"DLT_PPP_WITH_DIRECTION", Const, 0}, + {"DLT_PRISM_HEADER", Const, 0}, + {"DLT_PRONET", Const, 0}, + {"DLT_RAIF1", Const, 0}, + {"DLT_RAW", Const, 0}, + {"DLT_RAWAF_MASK", Const, 1}, + {"DLT_RIO", Const, 0}, + {"DLT_SCCP", Const, 0}, + {"DLT_SITA", Const, 0}, + {"DLT_SLIP", Const, 0}, + {"DLT_SLIP_BSDOS", Const, 0}, + {"DLT_STANAG_5066_D_PDU", Const, 1}, + {"DLT_SUNATM", Const, 0}, + {"DLT_SYMANTEC_FIREWALL", Const, 0}, + {"DLT_TZSP", Const, 0}, + {"DLT_USB", Const, 0}, + {"DLT_USB_LINUX", Const, 0}, + {"DLT_USB_LINUX_MMAPPED", Const, 1}, + {"DLT_USER0", Const, 0}, + {"DLT_USER1", Const, 0}, + {"DLT_USER10", Const, 0}, + {"DLT_USER11", Const, 0}, + {"DLT_USER12", Const, 0}, + {"DLT_USER13", Const, 0}, + {"DLT_USER14", Const, 0}, + {"DLT_USER15", Const, 0}, + {"DLT_USER2", Const, 0}, + {"DLT_USER3", Const, 0}, + {"DLT_USER4", Const, 0}, + {"DLT_USER5", Const, 0}, + {"DLT_USER6", Const, 0}, + {"DLT_USER7", Const, 0}, + {"DLT_USER8", Const, 0}, + {"DLT_USER9", Const, 0}, + {"DLT_WIHART", Const, 1}, + {"DLT_X2E_SERIAL", Const, 0}, + {"DLT_X2E_XORAYA", Const, 0}, + {"DNSMXData", Type, 0}, + {"DNSMXData.NameExchange", Field, 0}, + {"DNSMXData.Pad", Field, 0}, + {"DNSMXData.Preference", Field, 0}, + {"DNSPTRData", Type, 0}, + {"DNSPTRData.Host", Field, 0}, + {"DNSRecord", Type, 0}, + {"DNSRecord.Data", Field, 0}, + {"DNSRecord.Dw", Field, 0}, + {"DNSRecord.Length", Field, 0}, + {"DNSRecord.Name", Field, 0}, + {"DNSRecord.Next", Field, 0}, + {"DNSRecord.Reserved", Field, 0}, + {"DNSRecord.Ttl", Field, 0}, + {"DNSRecord.Type", Field, 0}, + {"DNSSRVData", Type, 0}, + {"DNSSRVData.Pad", Field, 0}, + {"DNSSRVData.Port", Field, 0}, + {"DNSSRVData.Priority", Field, 0}, + {"DNSSRVData.Target", Field, 0}, + {"DNSSRVData.Weight", Field, 0}, + {"DNSTXTData", Type, 0}, + {"DNSTXTData.StringArray", Field, 0}, + {"DNSTXTData.StringCount", Field, 0}, + {"DNS_INFO_NO_RECORDS", Const, 4}, + {"DNS_TYPE_A", Const, 0}, + {"DNS_TYPE_A6", Const, 0}, + {"DNS_TYPE_AAAA", Const, 0}, + {"DNS_TYPE_ADDRS", Const, 0}, + {"DNS_TYPE_AFSDB", Const, 0}, + {"DNS_TYPE_ALL", Const, 0}, + {"DNS_TYPE_ANY", Const, 0}, + {"DNS_TYPE_ATMA", Const, 0}, + {"DNS_TYPE_AXFR", Const, 0}, + {"DNS_TYPE_CERT", Const, 0}, + {"DNS_TYPE_CNAME", Const, 0}, + {"DNS_TYPE_DHCID", Const, 0}, + {"DNS_TYPE_DNAME", Const, 0}, + {"DNS_TYPE_DNSKEY", Const, 0}, + {"DNS_TYPE_DS", Const, 0}, + {"DNS_TYPE_EID", Const, 0}, + {"DNS_TYPE_GID", Const, 0}, + {"DNS_TYPE_GPOS", Const, 0}, + {"DNS_TYPE_HINFO", Const, 0}, + {"DNS_TYPE_ISDN", Const, 0}, + {"DNS_TYPE_IXFR", Const, 0}, + {"DNS_TYPE_KEY", Const, 0}, + {"DNS_TYPE_KX", Const, 0}, + {"DNS_TYPE_LOC", Const, 0}, + {"DNS_TYPE_MAILA", Const, 0}, + {"DNS_TYPE_MAILB", Const, 0}, + {"DNS_TYPE_MB", Const, 0}, + {"DNS_TYPE_MD", Const, 0}, + {"DNS_TYPE_MF", Const, 0}, + {"DNS_TYPE_MG", Const, 0}, + {"DNS_TYPE_MINFO", Const, 0}, + {"DNS_TYPE_MR", Const, 0}, + {"DNS_TYPE_MX", Const, 0}, + {"DNS_TYPE_NAPTR", Const, 0}, + {"DNS_TYPE_NBSTAT", Const, 0}, + {"DNS_TYPE_NIMLOC", Const, 0}, + {"DNS_TYPE_NS", Const, 0}, + {"DNS_TYPE_NSAP", Const, 0}, + {"DNS_TYPE_NSAPPTR", Const, 0}, + {"DNS_TYPE_NSEC", Const, 0}, + {"DNS_TYPE_NULL", Const, 0}, + {"DNS_TYPE_NXT", Const, 0}, + {"DNS_TYPE_OPT", Const, 0}, + {"DNS_TYPE_PTR", Const, 0}, + {"DNS_TYPE_PX", Const, 0}, + {"DNS_TYPE_RP", Const, 0}, + {"DNS_TYPE_RRSIG", Const, 0}, + {"DNS_TYPE_RT", Const, 0}, + {"DNS_TYPE_SIG", Const, 0}, + {"DNS_TYPE_SINK", Const, 0}, + {"DNS_TYPE_SOA", Const, 0}, + {"DNS_TYPE_SRV", Const, 0}, + {"DNS_TYPE_TEXT", Const, 0}, + {"DNS_TYPE_TKEY", Const, 0}, + {"DNS_TYPE_TSIG", Const, 0}, + {"DNS_TYPE_UID", Const, 0}, + {"DNS_TYPE_UINFO", Const, 0}, + {"DNS_TYPE_UNSPEC", Const, 0}, + {"DNS_TYPE_WINS", Const, 0}, + {"DNS_TYPE_WINSR", Const, 0}, + {"DNS_TYPE_WKS", Const, 0}, + {"DNS_TYPE_X25", Const, 0}, + {"DT_BLK", Const, 0}, + {"DT_CHR", Const, 0}, + {"DT_DIR", Const, 0}, + {"DT_FIFO", Const, 0}, + {"DT_LNK", Const, 0}, + {"DT_REG", Const, 0}, + {"DT_SOCK", Const, 0}, + {"DT_UNKNOWN", Const, 0}, + {"DT_WHT", Const, 0}, + {"DUPLICATE_CLOSE_SOURCE", Const, 0}, + {"DUPLICATE_SAME_ACCESS", Const, 0}, + {"DeleteFile", Func, 0}, + {"DetachLsf", Func, 0}, + {"DeviceIoControl", Func, 4}, + {"Dirent", Type, 0}, + {"Dirent.Fileno", Field, 0}, + {"Dirent.Ino", Field, 0}, + {"Dirent.Name", Field, 0}, + {"Dirent.Namlen", Field, 0}, + {"Dirent.Off", Field, 0}, + {"Dirent.Pad0", Field, 12}, + {"Dirent.Pad1", Field, 12}, + {"Dirent.Pad_cgo_0", Field, 0}, + {"Dirent.Reclen", Field, 0}, + {"Dirent.Seekoff", Field, 0}, + {"Dirent.Type", Field, 0}, + {"Dirent.X__d_padding", Field, 3}, + {"DnsNameCompare", Func, 4}, + {"DnsQuery", Func, 0}, + {"DnsRecordListFree", Func, 0}, + {"DnsSectionAdditional", Const, 4}, + {"DnsSectionAnswer", Const, 4}, + {"DnsSectionAuthority", Const, 4}, + {"DnsSectionQuestion", Const, 4}, + {"Dup", Func, 0}, + {"Dup2", Func, 0}, + {"Dup3", Func, 2}, + {"DuplicateHandle", Func, 0}, + {"E2BIG", Const, 0}, + {"EACCES", Const, 0}, + {"EADDRINUSE", Const, 0}, + {"EADDRNOTAVAIL", Const, 0}, + {"EADV", Const, 0}, + {"EAFNOSUPPORT", Const, 0}, + {"EAGAIN", Const, 0}, + {"EALREADY", Const, 0}, + {"EAUTH", Const, 0}, + {"EBADARCH", Const, 0}, + {"EBADE", Const, 0}, + {"EBADEXEC", Const, 0}, + {"EBADF", Const, 0}, + {"EBADFD", Const, 0}, + {"EBADMACHO", Const, 0}, + {"EBADMSG", Const, 0}, + {"EBADR", Const, 0}, + {"EBADRPC", Const, 0}, + {"EBADRQC", Const, 0}, + {"EBADSLT", Const, 0}, + {"EBFONT", Const, 0}, + {"EBUSY", Const, 0}, + {"ECANCELED", Const, 0}, + {"ECAPMODE", Const, 1}, + {"ECHILD", Const, 0}, + {"ECHO", Const, 0}, + {"ECHOCTL", Const, 0}, + {"ECHOE", Const, 0}, + {"ECHOK", Const, 0}, + {"ECHOKE", Const, 0}, + {"ECHONL", Const, 0}, + {"ECHOPRT", Const, 0}, + {"ECHRNG", Const, 0}, + {"ECOMM", Const, 0}, + {"ECONNABORTED", Const, 0}, + {"ECONNREFUSED", Const, 0}, + {"ECONNRESET", Const, 0}, + {"EDEADLK", Const, 0}, + {"EDEADLOCK", Const, 0}, + {"EDESTADDRREQ", Const, 0}, + {"EDEVERR", Const, 0}, + {"EDOM", Const, 0}, + {"EDOOFUS", Const, 0}, + {"EDOTDOT", Const, 0}, + {"EDQUOT", Const, 0}, + {"EEXIST", Const, 0}, + {"EFAULT", Const, 0}, + {"EFBIG", Const, 0}, + {"EFER_LMA", Const, 1}, + {"EFER_LME", Const, 1}, + {"EFER_NXE", Const, 1}, + {"EFER_SCE", Const, 1}, + {"EFTYPE", Const, 0}, + {"EHOSTDOWN", Const, 0}, + {"EHOSTUNREACH", Const, 0}, + {"EHWPOISON", Const, 0}, + {"EIDRM", Const, 0}, + {"EILSEQ", Const, 0}, + {"EINPROGRESS", Const, 0}, + {"EINTR", Const, 0}, + {"EINVAL", Const, 0}, + {"EIO", Const, 0}, + {"EIPSEC", Const, 1}, + {"EISCONN", Const, 0}, + {"EISDIR", Const, 0}, + {"EISNAM", Const, 0}, + {"EKEYEXPIRED", Const, 0}, + {"EKEYREJECTED", Const, 0}, + {"EKEYREVOKED", Const, 0}, + {"EL2HLT", Const, 0}, + {"EL2NSYNC", Const, 0}, + {"EL3HLT", Const, 0}, + {"EL3RST", Const, 0}, + {"ELAST", Const, 0}, + {"ELF_NGREG", Const, 0}, + {"ELF_PRARGSZ", Const, 0}, + {"ELIBACC", Const, 0}, + {"ELIBBAD", Const, 0}, + {"ELIBEXEC", Const, 0}, + {"ELIBMAX", Const, 0}, + {"ELIBSCN", Const, 0}, + {"ELNRNG", Const, 0}, + {"ELOOP", Const, 0}, + {"EMEDIUMTYPE", Const, 0}, + {"EMFILE", Const, 0}, + {"EMLINK", Const, 0}, + {"EMSGSIZE", Const, 0}, + {"EMT_TAGOVF", Const, 1}, + {"EMULTIHOP", Const, 0}, + {"EMUL_ENABLED", Const, 1}, + {"EMUL_LINUX", Const, 1}, + {"EMUL_LINUX32", Const, 1}, + {"EMUL_MAXID", Const, 1}, + {"EMUL_NATIVE", Const, 1}, + {"ENAMETOOLONG", Const, 0}, + {"ENAVAIL", Const, 0}, + {"ENDRUNDISC", Const, 1}, + {"ENEEDAUTH", Const, 0}, + {"ENETDOWN", Const, 0}, + {"ENETRESET", Const, 0}, + {"ENETUNREACH", Const, 0}, + {"ENFILE", Const, 0}, + {"ENOANO", Const, 0}, + {"ENOATTR", Const, 0}, + {"ENOBUFS", Const, 0}, + {"ENOCSI", Const, 0}, + {"ENODATA", Const, 0}, + {"ENODEV", Const, 0}, + {"ENOENT", Const, 0}, + {"ENOEXEC", Const, 0}, + {"ENOKEY", Const, 0}, + {"ENOLCK", Const, 0}, + {"ENOLINK", Const, 0}, + {"ENOMEDIUM", Const, 0}, + {"ENOMEM", Const, 0}, + {"ENOMSG", Const, 0}, + {"ENONET", Const, 0}, + {"ENOPKG", Const, 0}, + {"ENOPOLICY", Const, 0}, + {"ENOPROTOOPT", Const, 0}, + {"ENOSPC", Const, 0}, + {"ENOSR", Const, 0}, + {"ENOSTR", Const, 0}, + {"ENOSYS", Const, 0}, + {"ENOTBLK", Const, 0}, + {"ENOTCAPABLE", Const, 0}, + {"ENOTCONN", Const, 0}, + {"ENOTDIR", Const, 0}, + {"ENOTEMPTY", Const, 0}, + {"ENOTNAM", Const, 0}, + {"ENOTRECOVERABLE", Const, 0}, + {"ENOTSOCK", Const, 0}, + {"ENOTSUP", Const, 0}, + {"ENOTTY", Const, 0}, + {"ENOTUNIQ", Const, 0}, + {"ENXIO", Const, 0}, + {"EN_SW_CTL_INF", Const, 1}, + {"EN_SW_CTL_PREC", Const, 1}, + {"EN_SW_CTL_ROUND", Const, 1}, + {"EN_SW_DATACHAIN", Const, 1}, + {"EN_SW_DENORM", Const, 1}, + {"EN_SW_INVOP", Const, 1}, + {"EN_SW_OVERFLOW", Const, 1}, + {"EN_SW_PRECLOSS", Const, 1}, + {"EN_SW_UNDERFLOW", Const, 1}, + {"EN_SW_ZERODIV", Const, 1}, + {"EOPNOTSUPP", Const, 0}, + {"EOVERFLOW", Const, 0}, + {"EOWNERDEAD", Const, 0}, + {"EPERM", Const, 0}, + {"EPFNOSUPPORT", Const, 0}, + {"EPIPE", Const, 0}, + {"EPOLLERR", Const, 0}, + {"EPOLLET", Const, 0}, + {"EPOLLHUP", Const, 0}, + {"EPOLLIN", Const, 0}, + {"EPOLLMSG", Const, 0}, + {"EPOLLONESHOT", Const, 0}, + {"EPOLLOUT", Const, 0}, + {"EPOLLPRI", Const, 0}, + {"EPOLLRDBAND", Const, 0}, + {"EPOLLRDHUP", Const, 0}, + {"EPOLLRDNORM", Const, 0}, + {"EPOLLWRBAND", Const, 0}, + {"EPOLLWRNORM", Const, 0}, + {"EPOLL_CLOEXEC", Const, 0}, + {"EPOLL_CTL_ADD", Const, 0}, + {"EPOLL_CTL_DEL", Const, 0}, + {"EPOLL_CTL_MOD", Const, 0}, + {"EPOLL_NONBLOCK", Const, 0}, + {"EPROCLIM", Const, 0}, + {"EPROCUNAVAIL", Const, 0}, + {"EPROGMISMATCH", Const, 0}, + {"EPROGUNAVAIL", Const, 0}, + {"EPROTO", Const, 0}, + {"EPROTONOSUPPORT", Const, 0}, + {"EPROTOTYPE", Const, 0}, + {"EPWROFF", Const, 0}, + {"EQFULL", Const, 16}, + {"ERANGE", Const, 0}, + {"EREMCHG", Const, 0}, + {"EREMOTE", Const, 0}, + {"EREMOTEIO", Const, 0}, + {"ERESTART", Const, 0}, + {"ERFKILL", Const, 0}, + {"EROFS", Const, 0}, + {"ERPCMISMATCH", Const, 0}, + {"ERROR_ACCESS_DENIED", Const, 0}, + {"ERROR_ALREADY_EXISTS", Const, 0}, + {"ERROR_BROKEN_PIPE", Const, 0}, + {"ERROR_BUFFER_OVERFLOW", Const, 0}, + {"ERROR_DIR_NOT_EMPTY", Const, 8}, + {"ERROR_ENVVAR_NOT_FOUND", Const, 0}, + {"ERROR_FILE_EXISTS", Const, 0}, + {"ERROR_FILE_NOT_FOUND", Const, 0}, + {"ERROR_HANDLE_EOF", Const, 2}, + {"ERROR_INSUFFICIENT_BUFFER", Const, 0}, + {"ERROR_IO_PENDING", Const, 0}, + {"ERROR_MOD_NOT_FOUND", Const, 0}, + {"ERROR_MORE_DATA", Const, 3}, + {"ERROR_NETNAME_DELETED", Const, 3}, + {"ERROR_NOT_FOUND", Const, 1}, + {"ERROR_NO_MORE_FILES", Const, 0}, + {"ERROR_OPERATION_ABORTED", Const, 0}, + {"ERROR_PATH_NOT_FOUND", Const, 0}, + {"ERROR_PRIVILEGE_NOT_HELD", Const, 4}, + {"ERROR_PROC_NOT_FOUND", Const, 0}, + {"ESHLIBVERS", Const, 0}, + {"ESHUTDOWN", Const, 0}, + {"ESOCKTNOSUPPORT", Const, 0}, + {"ESPIPE", Const, 0}, + {"ESRCH", Const, 0}, + {"ESRMNT", Const, 0}, + {"ESTALE", Const, 0}, + {"ESTRPIPE", Const, 0}, + {"ETHERCAP_JUMBO_MTU", Const, 1}, + {"ETHERCAP_VLAN_HWTAGGING", Const, 1}, + {"ETHERCAP_VLAN_MTU", Const, 1}, + {"ETHERMIN", Const, 1}, + {"ETHERMTU", Const, 1}, + {"ETHERMTU_JUMBO", Const, 1}, + {"ETHERTYPE_8023", Const, 1}, + {"ETHERTYPE_AARP", Const, 1}, + {"ETHERTYPE_ACCTON", Const, 1}, + {"ETHERTYPE_AEONIC", Const, 1}, + {"ETHERTYPE_ALPHA", Const, 1}, + {"ETHERTYPE_AMBER", Const, 1}, + {"ETHERTYPE_AMOEBA", Const, 1}, + {"ETHERTYPE_AOE", Const, 1}, + {"ETHERTYPE_APOLLO", Const, 1}, + {"ETHERTYPE_APOLLODOMAIN", Const, 1}, + {"ETHERTYPE_APPLETALK", Const, 1}, + {"ETHERTYPE_APPLITEK", Const, 1}, + {"ETHERTYPE_ARGONAUT", Const, 1}, + {"ETHERTYPE_ARP", Const, 1}, + {"ETHERTYPE_AT", Const, 1}, + {"ETHERTYPE_ATALK", Const, 1}, + {"ETHERTYPE_ATOMIC", Const, 1}, + {"ETHERTYPE_ATT", Const, 1}, + {"ETHERTYPE_ATTSTANFORD", Const, 1}, + {"ETHERTYPE_AUTOPHON", Const, 1}, + {"ETHERTYPE_AXIS", Const, 1}, + {"ETHERTYPE_BCLOOP", Const, 1}, + {"ETHERTYPE_BOFL", Const, 1}, + {"ETHERTYPE_CABLETRON", Const, 1}, + {"ETHERTYPE_CHAOS", Const, 1}, + {"ETHERTYPE_COMDESIGN", Const, 1}, + {"ETHERTYPE_COMPUGRAPHIC", Const, 1}, + {"ETHERTYPE_COUNTERPOINT", Const, 1}, + {"ETHERTYPE_CRONUS", Const, 1}, + {"ETHERTYPE_CRONUSVLN", Const, 1}, + {"ETHERTYPE_DCA", Const, 1}, + {"ETHERTYPE_DDE", Const, 1}, + {"ETHERTYPE_DEBNI", Const, 1}, + {"ETHERTYPE_DECAM", Const, 1}, + {"ETHERTYPE_DECCUST", Const, 1}, + {"ETHERTYPE_DECDIAG", Const, 1}, + {"ETHERTYPE_DECDNS", Const, 1}, + {"ETHERTYPE_DECDTS", Const, 1}, + {"ETHERTYPE_DECEXPER", Const, 1}, + {"ETHERTYPE_DECLAST", Const, 1}, + {"ETHERTYPE_DECLTM", Const, 1}, + {"ETHERTYPE_DECMUMPS", Const, 1}, + {"ETHERTYPE_DECNETBIOS", Const, 1}, + {"ETHERTYPE_DELTACON", Const, 1}, + {"ETHERTYPE_DIDDLE", Const, 1}, + {"ETHERTYPE_DLOG1", Const, 1}, + {"ETHERTYPE_DLOG2", Const, 1}, + {"ETHERTYPE_DN", Const, 1}, + {"ETHERTYPE_DOGFIGHT", Const, 1}, + {"ETHERTYPE_DSMD", Const, 1}, + {"ETHERTYPE_ECMA", Const, 1}, + {"ETHERTYPE_ENCRYPT", Const, 1}, + {"ETHERTYPE_ES", Const, 1}, + {"ETHERTYPE_EXCELAN", Const, 1}, + {"ETHERTYPE_EXPERDATA", Const, 1}, + {"ETHERTYPE_FLIP", Const, 1}, + {"ETHERTYPE_FLOWCONTROL", Const, 1}, + {"ETHERTYPE_FRARP", Const, 1}, + {"ETHERTYPE_GENDYN", Const, 1}, + {"ETHERTYPE_HAYES", Const, 1}, + {"ETHERTYPE_HIPPI_FP", Const, 1}, + {"ETHERTYPE_HITACHI", Const, 1}, + {"ETHERTYPE_HP", Const, 1}, + {"ETHERTYPE_IEEEPUP", Const, 1}, + {"ETHERTYPE_IEEEPUPAT", Const, 1}, + {"ETHERTYPE_IMLBL", Const, 1}, + {"ETHERTYPE_IMLBLDIAG", Const, 1}, + {"ETHERTYPE_IP", Const, 1}, + {"ETHERTYPE_IPAS", Const, 1}, + {"ETHERTYPE_IPV6", Const, 1}, + {"ETHERTYPE_IPX", Const, 1}, + {"ETHERTYPE_IPXNEW", Const, 1}, + {"ETHERTYPE_KALPANA", Const, 1}, + {"ETHERTYPE_LANBRIDGE", Const, 1}, + {"ETHERTYPE_LANPROBE", Const, 1}, + {"ETHERTYPE_LAT", Const, 1}, + {"ETHERTYPE_LBACK", Const, 1}, + {"ETHERTYPE_LITTLE", Const, 1}, + {"ETHERTYPE_LLDP", Const, 1}, + {"ETHERTYPE_LOGICRAFT", Const, 1}, + {"ETHERTYPE_LOOPBACK", Const, 1}, + {"ETHERTYPE_MATRA", Const, 1}, + {"ETHERTYPE_MAX", Const, 1}, + {"ETHERTYPE_MERIT", Const, 1}, + {"ETHERTYPE_MICP", Const, 1}, + {"ETHERTYPE_MOPDL", Const, 1}, + {"ETHERTYPE_MOPRC", Const, 1}, + {"ETHERTYPE_MOTOROLA", Const, 1}, + {"ETHERTYPE_MPLS", Const, 1}, + {"ETHERTYPE_MPLS_MCAST", Const, 1}, + {"ETHERTYPE_MUMPS", Const, 1}, + {"ETHERTYPE_NBPCC", Const, 1}, + {"ETHERTYPE_NBPCLAIM", Const, 1}, + {"ETHERTYPE_NBPCLREQ", Const, 1}, + {"ETHERTYPE_NBPCLRSP", Const, 1}, + {"ETHERTYPE_NBPCREQ", Const, 1}, + {"ETHERTYPE_NBPCRSP", Const, 1}, + {"ETHERTYPE_NBPDG", Const, 1}, + {"ETHERTYPE_NBPDGB", Const, 1}, + {"ETHERTYPE_NBPDLTE", Const, 1}, + {"ETHERTYPE_NBPRAR", Const, 1}, + {"ETHERTYPE_NBPRAS", Const, 1}, + {"ETHERTYPE_NBPRST", Const, 1}, + {"ETHERTYPE_NBPSCD", Const, 1}, + {"ETHERTYPE_NBPVCD", Const, 1}, + {"ETHERTYPE_NBS", Const, 1}, + {"ETHERTYPE_NCD", Const, 1}, + {"ETHERTYPE_NESTAR", Const, 1}, + {"ETHERTYPE_NETBEUI", Const, 1}, + {"ETHERTYPE_NOVELL", Const, 1}, + {"ETHERTYPE_NS", Const, 1}, + {"ETHERTYPE_NSAT", Const, 1}, + {"ETHERTYPE_NSCOMPAT", Const, 1}, + {"ETHERTYPE_NTRAILER", Const, 1}, + {"ETHERTYPE_OS9", Const, 1}, + {"ETHERTYPE_OS9NET", Const, 1}, + {"ETHERTYPE_PACER", Const, 1}, + {"ETHERTYPE_PAE", Const, 1}, + {"ETHERTYPE_PCS", Const, 1}, + {"ETHERTYPE_PLANNING", Const, 1}, + {"ETHERTYPE_PPP", Const, 1}, + {"ETHERTYPE_PPPOE", Const, 1}, + {"ETHERTYPE_PPPOEDISC", Const, 1}, + {"ETHERTYPE_PRIMENTS", Const, 1}, + {"ETHERTYPE_PUP", Const, 1}, + {"ETHERTYPE_PUPAT", Const, 1}, + {"ETHERTYPE_QINQ", Const, 1}, + {"ETHERTYPE_RACAL", Const, 1}, + {"ETHERTYPE_RATIONAL", Const, 1}, + {"ETHERTYPE_RAWFR", Const, 1}, + {"ETHERTYPE_RCL", Const, 1}, + {"ETHERTYPE_RDP", Const, 1}, + {"ETHERTYPE_RETIX", Const, 1}, + {"ETHERTYPE_REVARP", Const, 1}, + {"ETHERTYPE_SCA", Const, 1}, + {"ETHERTYPE_SECTRA", Const, 1}, + {"ETHERTYPE_SECUREDATA", Const, 1}, + {"ETHERTYPE_SGITW", Const, 1}, + {"ETHERTYPE_SG_BOUNCE", Const, 1}, + {"ETHERTYPE_SG_DIAG", Const, 1}, + {"ETHERTYPE_SG_NETGAMES", Const, 1}, + {"ETHERTYPE_SG_RESV", Const, 1}, + {"ETHERTYPE_SIMNET", Const, 1}, + {"ETHERTYPE_SLOW", Const, 1}, + {"ETHERTYPE_SLOWPROTOCOLS", Const, 1}, + {"ETHERTYPE_SNA", Const, 1}, + {"ETHERTYPE_SNMP", Const, 1}, + {"ETHERTYPE_SONIX", Const, 1}, + {"ETHERTYPE_SPIDER", Const, 1}, + {"ETHERTYPE_SPRITE", Const, 1}, + {"ETHERTYPE_STP", Const, 1}, + {"ETHERTYPE_TALARIS", Const, 1}, + {"ETHERTYPE_TALARISMC", Const, 1}, + {"ETHERTYPE_TCPCOMP", Const, 1}, + {"ETHERTYPE_TCPSM", Const, 1}, + {"ETHERTYPE_TEC", Const, 1}, + {"ETHERTYPE_TIGAN", Const, 1}, + {"ETHERTYPE_TRAIL", Const, 1}, + {"ETHERTYPE_TRANSETHER", Const, 1}, + {"ETHERTYPE_TYMSHARE", Const, 1}, + {"ETHERTYPE_UBBST", Const, 1}, + {"ETHERTYPE_UBDEBUG", Const, 1}, + {"ETHERTYPE_UBDIAGLOOP", Const, 1}, + {"ETHERTYPE_UBDL", Const, 1}, + {"ETHERTYPE_UBNIU", Const, 1}, + {"ETHERTYPE_UBNMC", Const, 1}, + {"ETHERTYPE_VALID", Const, 1}, + {"ETHERTYPE_VARIAN", Const, 1}, + {"ETHERTYPE_VAXELN", Const, 1}, + {"ETHERTYPE_VEECO", Const, 1}, + {"ETHERTYPE_VEXP", Const, 1}, + {"ETHERTYPE_VGLAB", Const, 1}, + {"ETHERTYPE_VINES", Const, 1}, + {"ETHERTYPE_VINESECHO", Const, 1}, + {"ETHERTYPE_VINESLOOP", Const, 1}, + {"ETHERTYPE_VITAL", Const, 1}, + {"ETHERTYPE_VLAN", Const, 1}, + {"ETHERTYPE_VLTLMAN", Const, 1}, + {"ETHERTYPE_VPROD", Const, 1}, + {"ETHERTYPE_VURESERVED", Const, 1}, + {"ETHERTYPE_WATERLOO", Const, 1}, + {"ETHERTYPE_WELLFLEET", Const, 1}, + {"ETHERTYPE_X25", Const, 1}, + {"ETHERTYPE_X75", Const, 1}, + {"ETHERTYPE_XNSSM", Const, 1}, + {"ETHERTYPE_XTP", Const, 1}, + {"ETHER_ADDR_LEN", Const, 1}, + {"ETHER_ALIGN", Const, 1}, + {"ETHER_CRC_LEN", Const, 1}, + {"ETHER_CRC_POLY_BE", Const, 1}, + {"ETHER_CRC_POLY_LE", Const, 1}, + {"ETHER_HDR_LEN", Const, 1}, + {"ETHER_MAX_DIX_LEN", Const, 1}, + {"ETHER_MAX_LEN", Const, 1}, + {"ETHER_MAX_LEN_JUMBO", Const, 1}, + {"ETHER_MIN_LEN", Const, 1}, + {"ETHER_PPPOE_ENCAP_LEN", Const, 1}, + {"ETHER_TYPE_LEN", Const, 1}, + {"ETHER_VLAN_ENCAP_LEN", Const, 1}, + {"ETH_P_1588", Const, 0}, + {"ETH_P_8021Q", Const, 0}, + {"ETH_P_802_2", Const, 0}, + {"ETH_P_802_3", Const, 0}, + {"ETH_P_AARP", Const, 0}, + {"ETH_P_ALL", Const, 0}, + {"ETH_P_AOE", Const, 0}, + {"ETH_P_ARCNET", Const, 0}, + {"ETH_P_ARP", Const, 0}, + {"ETH_P_ATALK", Const, 0}, + {"ETH_P_ATMFATE", Const, 0}, + {"ETH_P_ATMMPOA", Const, 0}, + {"ETH_P_AX25", Const, 0}, + {"ETH_P_BPQ", Const, 0}, + {"ETH_P_CAIF", Const, 0}, + {"ETH_P_CAN", Const, 0}, + {"ETH_P_CONTROL", Const, 0}, + {"ETH_P_CUST", Const, 0}, + {"ETH_P_DDCMP", Const, 0}, + {"ETH_P_DEC", Const, 0}, + {"ETH_P_DIAG", Const, 0}, + {"ETH_P_DNA_DL", Const, 0}, + {"ETH_P_DNA_RC", Const, 0}, + {"ETH_P_DNA_RT", Const, 0}, + {"ETH_P_DSA", Const, 0}, + {"ETH_P_ECONET", Const, 0}, + {"ETH_P_EDSA", Const, 0}, + {"ETH_P_FCOE", Const, 0}, + {"ETH_P_FIP", Const, 0}, + {"ETH_P_HDLC", Const, 0}, + {"ETH_P_IEEE802154", Const, 0}, + {"ETH_P_IEEEPUP", Const, 0}, + {"ETH_P_IEEEPUPAT", Const, 0}, + {"ETH_P_IP", Const, 0}, + {"ETH_P_IPV6", Const, 0}, + {"ETH_P_IPX", Const, 0}, + {"ETH_P_IRDA", Const, 0}, + {"ETH_P_LAT", Const, 0}, + {"ETH_P_LINK_CTL", Const, 0}, + {"ETH_P_LOCALTALK", Const, 0}, + {"ETH_P_LOOP", Const, 0}, + {"ETH_P_MOBITEX", Const, 0}, + {"ETH_P_MPLS_MC", Const, 0}, + {"ETH_P_MPLS_UC", Const, 0}, + {"ETH_P_PAE", Const, 0}, + {"ETH_P_PAUSE", Const, 0}, + {"ETH_P_PHONET", Const, 0}, + {"ETH_P_PPPTALK", Const, 0}, + {"ETH_P_PPP_DISC", Const, 0}, + {"ETH_P_PPP_MP", Const, 0}, + {"ETH_P_PPP_SES", Const, 0}, + {"ETH_P_PUP", Const, 0}, + {"ETH_P_PUPAT", Const, 0}, + {"ETH_P_RARP", Const, 0}, + {"ETH_P_SCA", Const, 0}, + {"ETH_P_SLOW", Const, 0}, + {"ETH_P_SNAP", Const, 0}, + {"ETH_P_TEB", Const, 0}, + {"ETH_P_TIPC", Const, 0}, + {"ETH_P_TRAILER", Const, 0}, + {"ETH_P_TR_802_2", Const, 0}, + {"ETH_P_WAN_PPP", Const, 0}, + {"ETH_P_WCCP", Const, 0}, + {"ETH_P_X25", Const, 0}, + {"ETIME", Const, 0}, + {"ETIMEDOUT", Const, 0}, + {"ETOOMANYREFS", Const, 0}, + {"ETXTBSY", Const, 0}, + {"EUCLEAN", Const, 0}, + {"EUNATCH", Const, 0}, + {"EUSERS", Const, 0}, + {"EVFILT_AIO", Const, 0}, + {"EVFILT_FS", Const, 0}, + {"EVFILT_LIO", Const, 0}, + {"EVFILT_MACHPORT", Const, 0}, + {"EVFILT_PROC", Const, 0}, + {"EVFILT_READ", Const, 0}, + {"EVFILT_SIGNAL", Const, 0}, + {"EVFILT_SYSCOUNT", Const, 0}, + {"EVFILT_THREADMARKER", Const, 0}, + {"EVFILT_TIMER", Const, 0}, + {"EVFILT_USER", Const, 0}, + {"EVFILT_VM", Const, 0}, + {"EVFILT_VNODE", Const, 0}, + {"EVFILT_WRITE", Const, 0}, + {"EV_ADD", Const, 0}, + {"EV_CLEAR", Const, 0}, + {"EV_DELETE", Const, 0}, + {"EV_DISABLE", Const, 0}, + {"EV_DISPATCH", Const, 0}, + {"EV_DROP", Const, 3}, + {"EV_ENABLE", Const, 0}, + {"EV_EOF", Const, 0}, + {"EV_ERROR", Const, 0}, + {"EV_FLAG0", Const, 0}, + {"EV_FLAG1", Const, 0}, + {"EV_ONESHOT", Const, 0}, + {"EV_OOBAND", Const, 0}, + {"EV_POLL", Const, 0}, + {"EV_RECEIPT", Const, 0}, + {"EV_SYSFLAGS", Const, 0}, + {"EWINDOWS", Const, 0}, + {"EWOULDBLOCK", Const, 0}, + {"EXDEV", Const, 0}, + {"EXFULL", Const, 0}, + {"EXTA", Const, 0}, + {"EXTB", Const, 0}, + {"EXTPROC", Const, 0}, + {"Environ", Func, 0}, + {"EpollCreate", Func, 0}, + {"EpollCreate1", Func, 0}, + {"EpollCtl", Func, 0}, + {"EpollEvent", Type, 0}, + {"EpollEvent.Events", Field, 0}, + {"EpollEvent.Fd", Field, 0}, + {"EpollEvent.Pad", Field, 0}, + {"EpollEvent.PadFd", Field, 0}, + {"EpollWait", Func, 0}, + {"Errno", Type, 0}, + {"EscapeArg", Func, 0}, + {"Exchangedata", Func, 0}, + {"Exec", Func, 0}, + {"Exit", Func, 0}, + {"ExitProcess", Func, 0}, + {"FD_CLOEXEC", Const, 0}, + {"FD_SETSIZE", Const, 0}, + {"FILE_ACTION_ADDED", Const, 0}, + {"FILE_ACTION_MODIFIED", Const, 0}, + {"FILE_ACTION_REMOVED", Const, 0}, + {"FILE_ACTION_RENAMED_NEW_NAME", Const, 0}, + {"FILE_ACTION_RENAMED_OLD_NAME", Const, 0}, + {"FILE_APPEND_DATA", Const, 0}, + {"FILE_ATTRIBUTE_ARCHIVE", Const, 0}, + {"FILE_ATTRIBUTE_DIRECTORY", Const, 0}, + {"FILE_ATTRIBUTE_HIDDEN", Const, 0}, + {"FILE_ATTRIBUTE_NORMAL", Const, 0}, + {"FILE_ATTRIBUTE_READONLY", Const, 0}, + {"FILE_ATTRIBUTE_REPARSE_POINT", Const, 4}, + {"FILE_ATTRIBUTE_SYSTEM", Const, 0}, + {"FILE_BEGIN", Const, 0}, + {"FILE_CURRENT", Const, 0}, + {"FILE_END", Const, 0}, + {"FILE_FLAG_BACKUP_SEMANTICS", Const, 0}, + {"FILE_FLAG_OPEN_REPARSE_POINT", Const, 4}, + {"FILE_FLAG_OVERLAPPED", Const, 0}, + {"FILE_LIST_DIRECTORY", Const, 0}, + {"FILE_MAP_COPY", Const, 0}, + {"FILE_MAP_EXECUTE", Const, 0}, + {"FILE_MAP_READ", Const, 0}, + {"FILE_MAP_WRITE", Const, 0}, + {"FILE_NOTIFY_CHANGE_ATTRIBUTES", Const, 0}, + {"FILE_NOTIFY_CHANGE_CREATION", Const, 0}, + {"FILE_NOTIFY_CHANGE_DIR_NAME", Const, 0}, + {"FILE_NOTIFY_CHANGE_FILE_NAME", Const, 0}, + {"FILE_NOTIFY_CHANGE_LAST_ACCESS", Const, 0}, + {"FILE_NOTIFY_CHANGE_LAST_WRITE", Const, 0}, + {"FILE_NOTIFY_CHANGE_SIZE", Const, 0}, + {"FILE_SHARE_DELETE", Const, 0}, + {"FILE_SHARE_READ", Const, 0}, + {"FILE_SHARE_WRITE", Const, 0}, + {"FILE_SKIP_COMPLETION_PORT_ON_SUCCESS", Const, 2}, + {"FILE_SKIP_SET_EVENT_ON_HANDLE", Const, 2}, + {"FILE_TYPE_CHAR", Const, 0}, + {"FILE_TYPE_DISK", Const, 0}, + {"FILE_TYPE_PIPE", Const, 0}, + {"FILE_TYPE_REMOTE", Const, 0}, + {"FILE_TYPE_UNKNOWN", Const, 0}, + {"FILE_WRITE_ATTRIBUTES", Const, 0}, + {"FLUSHO", Const, 0}, + {"FORMAT_MESSAGE_ALLOCATE_BUFFER", Const, 0}, + {"FORMAT_MESSAGE_ARGUMENT_ARRAY", Const, 0}, + {"FORMAT_MESSAGE_FROM_HMODULE", Const, 0}, + {"FORMAT_MESSAGE_FROM_STRING", Const, 0}, + {"FORMAT_MESSAGE_FROM_SYSTEM", Const, 0}, + {"FORMAT_MESSAGE_IGNORE_INSERTS", Const, 0}, + {"FORMAT_MESSAGE_MAX_WIDTH_MASK", Const, 0}, + {"FSCTL_GET_REPARSE_POINT", Const, 4}, + {"F_ADDFILESIGS", Const, 0}, + {"F_ADDSIGS", Const, 0}, + {"F_ALLOCATEALL", Const, 0}, + {"F_ALLOCATECONTIG", Const, 0}, + {"F_CANCEL", Const, 0}, + {"F_CHKCLEAN", Const, 0}, + {"F_CLOSEM", Const, 1}, + {"F_DUP2FD", Const, 0}, + {"F_DUP2FD_CLOEXEC", Const, 1}, + {"F_DUPFD", Const, 0}, + {"F_DUPFD_CLOEXEC", Const, 0}, + {"F_EXLCK", Const, 0}, + {"F_FINDSIGS", Const, 16}, + {"F_FLUSH_DATA", Const, 0}, + {"F_FREEZE_FS", Const, 0}, + {"F_FSCTL", Const, 1}, + {"F_FSDIRMASK", Const, 1}, + {"F_FSIN", Const, 1}, + {"F_FSINOUT", Const, 1}, + {"F_FSOUT", Const, 1}, + {"F_FSPRIV", Const, 1}, + {"F_FSVOID", Const, 1}, + {"F_FULLFSYNC", Const, 0}, + {"F_GETCODEDIR", Const, 16}, + {"F_GETFD", Const, 0}, + {"F_GETFL", Const, 0}, + {"F_GETLEASE", Const, 0}, + {"F_GETLK", Const, 0}, + {"F_GETLK64", Const, 0}, + {"F_GETLKPID", Const, 0}, + {"F_GETNOSIGPIPE", Const, 0}, + {"F_GETOWN", Const, 0}, + {"F_GETOWN_EX", Const, 0}, + {"F_GETPATH", Const, 0}, + {"F_GETPATH_MTMINFO", Const, 0}, + {"F_GETPIPE_SZ", Const, 0}, + {"F_GETPROTECTIONCLASS", Const, 0}, + {"F_GETPROTECTIONLEVEL", Const, 16}, + {"F_GETSIG", Const, 0}, + {"F_GLOBAL_NOCACHE", Const, 0}, + {"F_LOCK", Const, 0}, + {"F_LOG2PHYS", Const, 0}, + {"F_LOG2PHYS_EXT", Const, 0}, + {"F_MARKDEPENDENCY", Const, 0}, + {"F_MAXFD", Const, 1}, + {"F_NOCACHE", Const, 0}, + {"F_NODIRECT", Const, 0}, + {"F_NOTIFY", Const, 0}, + {"F_OGETLK", Const, 0}, + {"F_OK", Const, 0}, + {"F_OSETLK", Const, 0}, + {"F_OSETLKW", Const, 0}, + {"F_PARAM_MASK", Const, 1}, + {"F_PARAM_MAX", Const, 1}, + {"F_PATHPKG_CHECK", Const, 0}, + {"F_PEOFPOSMODE", Const, 0}, + {"F_PREALLOCATE", Const, 0}, + {"F_RDADVISE", Const, 0}, + {"F_RDAHEAD", Const, 0}, + {"F_RDLCK", Const, 0}, + {"F_READAHEAD", Const, 0}, + {"F_READBOOTSTRAP", Const, 0}, + {"F_SETBACKINGSTORE", Const, 0}, + {"F_SETFD", Const, 0}, + {"F_SETFL", Const, 0}, + {"F_SETLEASE", Const, 0}, + {"F_SETLK", Const, 0}, + {"F_SETLK64", Const, 0}, + {"F_SETLKW", Const, 0}, + {"F_SETLKW64", Const, 0}, + {"F_SETLKWTIMEOUT", Const, 16}, + {"F_SETLK_REMOTE", Const, 0}, + {"F_SETNOSIGPIPE", Const, 0}, + {"F_SETOWN", Const, 0}, + {"F_SETOWN_EX", Const, 0}, + {"F_SETPIPE_SZ", Const, 0}, + {"F_SETPROTECTIONCLASS", Const, 0}, + {"F_SETSIG", Const, 0}, + {"F_SETSIZE", Const, 0}, + {"F_SHLCK", Const, 0}, + {"F_SINGLE_WRITER", Const, 16}, + {"F_TEST", Const, 0}, + {"F_THAW_FS", Const, 0}, + {"F_TLOCK", Const, 0}, + {"F_TRANSCODEKEY", Const, 16}, + {"F_ULOCK", Const, 0}, + {"F_UNLCK", Const, 0}, + {"F_UNLCKSYS", Const, 0}, + {"F_VOLPOSMODE", Const, 0}, + {"F_WRITEBOOTSTRAP", Const, 0}, + {"F_WRLCK", Const, 0}, + {"Faccessat", Func, 0}, + {"Fallocate", Func, 0}, + {"Fbootstraptransfer_t", Type, 0}, + {"Fbootstraptransfer_t.Buffer", Field, 0}, + {"Fbootstraptransfer_t.Length", Field, 0}, + {"Fbootstraptransfer_t.Offset", Field, 0}, + {"Fchdir", Func, 0}, + {"Fchflags", Func, 0}, + {"Fchmod", Func, 0}, + {"Fchmodat", Func, 0}, + {"Fchown", Func, 0}, + {"Fchownat", Func, 0}, + {"FcntlFlock", Func, 3}, + {"FdSet", Type, 0}, + {"FdSet.Bits", Field, 0}, + {"FdSet.X__fds_bits", Field, 0}, + {"Fdatasync", Func, 0}, + {"FileNotifyInformation", Type, 0}, + {"FileNotifyInformation.Action", Field, 0}, + {"FileNotifyInformation.FileName", Field, 0}, + {"FileNotifyInformation.FileNameLength", Field, 0}, + {"FileNotifyInformation.NextEntryOffset", Field, 0}, + {"Filetime", Type, 0}, + {"Filetime.HighDateTime", Field, 0}, + {"Filetime.LowDateTime", Field, 0}, + {"FindClose", Func, 0}, + {"FindFirstFile", Func, 0}, + {"FindNextFile", Func, 0}, + {"Flock", Func, 0}, + {"Flock_t", Type, 0}, + {"Flock_t.Len", Field, 0}, + {"Flock_t.Pad_cgo_0", Field, 0}, + {"Flock_t.Pad_cgo_1", Field, 3}, + {"Flock_t.Pid", Field, 0}, + {"Flock_t.Start", Field, 0}, + {"Flock_t.Sysid", Field, 0}, + {"Flock_t.Type", Field, 0}, + {"Flock_t.Whence", Field, 0}, + {"FlushBpf", Func, 0}, + {"FlushFileBuffers", Func, 0}, + {"FlushViewOfFile", Func, 0}, + {"ForkExec", Func, 0}, + {"ForkLock", Var, 0}, + {"FormatMessage", Func, 0}, + {"Fpathconf", Func, 0}, + {"FreeAddrInfoW", Func, 1}, + {"FreeEnvironmentStrings", Func, 0}, + {"FreeLibrary", Func, 0}, + {"Fsid", Type, 0}, + {"Fsid.Val", Field, 0}, + {"Fsid.X__fsid_val", Field, 2}, + {"Fsid.X__val", Field, 0}, + {"Fstat", Func, 0}, + {"Fstatat", Func, 12}, + {"Fstatfs", Func, 0}, + {"Fstore_t", Type, 0}, + {"Fstore_t.Bytesalloc", Field, 0}, + {"Fstore_t.Flags", Field, 0}, + {"Fstore_t.Length", Field, 0}, + {"Fstore_t.Offset", Field, 0}, + {"Fstore_t.Posmode", Field, 0}, + {"Fsync", Func, 0}, + {"Ftruncate", Func, 0}, + {"FullPath", Func, 4}, + {"Futimes", Func, 0}, + {"Futimesat", Func, 0}, + {"GENERIC_ALL", Const, 0}, + {"GENERIC_EXECUTE", Const, 0}, + {"GENERIC_READ", Const, 0}, + {"GENERIC_WRITE", Const, 0}, + {"GUID", Type, 1}, + {"GUID.Data1", Field, 1}, + {"GUID.Data2", Field, 1}, + {"GUID.Data3", Field, 1}, + {"GUID.Data4", Field, 1}, + {"GetAcceptExSockaddrs", Func, 0}, + {"GetAdaptersInfo", Func, 0}, + {"GetAddrInfoW", Func, 1}, + {"GetCommandLine", Func, 0}, + {"GetComputerName", Func, 0}, + {"GetConsoleMode", Func, 1}, + {"GetCurrentDirectory", Func, 0}, + {"GetCurrentProcess", Func, 0}, + {"GetEnvironmentStrings", Func, 0}, + {"GetEnvironmentVariable", Func, 0}, + {"GetExitCodeProcess", Func, 0}, + {"GetFileAttributes", Func, 0}, + {"GetFileAttributesEx", Func, 0}, + {"GetFileExInfoStandard", Const, 0}, + {"GetFileExMaxInfoLevel", Const, 0}, + {"GetFileInformationByHandle", Func, 0}, + {"GetFileType", Func, 0}, + {"GetFullPathName", Func, 0}, + {"GetHostByName", Func, 0}, + {"GetIfEntry", Func, 0}, + {"GetLastError", Func, 0}, + {"GetLengthSid", Func, 0}, + {"GetLongPathName", Func, 0}, + {"GetProcAddress", Func, 0}, + {"GetProcessTimes", Func, 0}, + {"GetProtoByName", Func, 0}, + {"GetQueuedCompletionStatus", Func, 0}, + {"GetServByName", Func, 0}, + {"GetShortPathName", Func, 0}, + {"GetStartupInfo", Func, 0}, + {"GetStdHandle", Func, 0}, + {"GetSystemTimeAsFileTime", Func, 0}, + {"GetTempPath", Func, 0}, + {"GetTimeZoneInformation", Func, 0}, + {"GetTokenInformation", Func, 0}, + {"GetUserNameEx", Func, 0}, + {"GetUserProfileDirectory", Func, 0}, + {"GetVersion", Func, 0}, + {"Getcwd", Func, 0}, + {"Getdents", Func, 0}, + {"Getdirentries", Func, 0}, + {"Getdtablesize", Func, 0}, + {"Getegid", Func, 0}, + {"Getenv", Func, 0}, + {"Geteuid", Func, 0}, + {"Getfsstat", Func, 0}, + {"Getgid", Func, 0}, + {"Getgroups", Func, 0}, + {"Getpagesize", Func, 0}, + {"Getpeername", Func, 0}, + {"Getpgid", Func, 0}, + {"Getpgrp", Func, 0}, + {"Getpid", Func, 0}, + {"Getppid", Func, 0}, + {"Getpriority", Func, 0}, + {"Getrlimit", Func, 0}, + {"Getrusage", Func, 0}, + {"Getsid", Func, 0}, + {"Getsockname", Func, 0}, + {"Getsockopt", Func, 1}, + {"GetsockoptByte", Func, 0}, + {"GetsockoptICMPv6Filter", Func, 2}, + {"GetsockoptIPMreq", Func, 0}, + {"GetsockoptIPMreqn", Func, 0}, + {"GetsockoptIPv6MTUInfo", Func, 2}, + {"GetsockoptIPv6Mreq", Func, 0}, + {"GetsockoptInet4Addr", Func, 0}, + {"GetsockoptInt", Func, 0}, + {"GetsockoptUcred", Func, 1}, + {"Gettid", Func, 0}, + {"Gettimeofday", Func, 0}, + {"Getuid", Func, 0}, + {"Getwd", Func, 0}, + {"Getxattr", Func, 1}, + {"HANDLE_FLAG_INHERIT", Const, 0}, + {"HKEY_CLASSES_ROOT", Const, 0}, + {"HKEY_CURRENT_CONFIG", Const, 0}, + {"HKEY_CURRENT_USER", Const, 0}, + {"HKEY_DYN_DATA", Const, 0}, + {"HKEY_LOCAL_MACHINE", Const, 0}, + {"HKEY_PERFORMANCE_DATA", Const, 0}, + {"HKEY_USERS", Const, 0}, + {"HUPCL", Const, 0}, + {"Handle", Type, 0}, + {"Hostent", Type, 0}, + {"Hostent.AddrList", Field, 0}, + {"Hostent.AddrType", Field, 0}, + {"Hostent.Aliases", Field, 0}, + {"Hostent.Length", Field, 0}, + {"Hostent.Name", Field, 0}, + {"ICANON", Const, 0}, + {"ICMP6_FILTER", Const, 2}, + {"ICMPV6_FILTER", Const, 2}, + {"ICMPv6Filter", Type, 2}, + {"ICMPv6Filter.Data", Field, 2}, + {"ICMPv6Filter.Filt", Field, 2}, + {"ICRNL", Const, 0}, + {"IEXTEN", Const, 0}, + {"IFAN_ARRIVAL", Const, 1}, + {"IFAN_DEPARTURE", Const, 1}, + {"IFA_ADDRESS", Const, 0}, + {"IFA_ANYCAST", Const, 0}, + {"IFA_BROADCAST", Const, 0}, + {"IFA_CACHEINFO", Const, 0}, + {"IFA_F_DADFAILED", Const, 0}, + {"IFA_F_DEPRECATED", Const, 0}, + {"IFA_F_HOMEADDRESS", Const, 0}, + {"IFA_F_NODAD", Const, 0}, + {"IFA_F_OPTIMISTIC", Const, 0}, + {"IFA_F_PERMANENT", Const, 0}, + {"IFA_F_SECONDARY", Const, 0}, + {"IFA_F_TEMPORARY", Const, 0}, + {"IFA_F_TENTATIVE", Const, 0}, + {"IFA_LABEL", Const, 0}, + {"IFA_LOCAL", Const, 0}, + {"IFA_MAX", Const, 0}, + {"IFA_MULTICAST", Const, 0}, + {"IFA_ROUTE", Const, 1}, + {"IFA_UNSPEC", Const, 0}, + {"IFF_ALLMULTI", Const, 0}, + {"IFF_ALTPHYS", Const, 0}, + {"IFF_AUTOMEDIA", Const, 0}, + {"IFF_BROADCAST", Const, 0}, + {"IFF_CANTCHANGE", Const, 0}, + {"IFF_CANTCONFIG", Const, 1}, + {"IFF_DEBUG", Const, 0}, + {"IFF_DRV_OACTIVE", Const, 0}, + {"IFF_DRV_RUNNING", Const, 0}, + {"IFF_DYING", Const, 0}, + {"IFF_DYNAMIC", Const, 0}, + {"IFF_LINK0", Const, 0}, + {"IFF_LINK1", Const, 0}, + {"IFF_LINK2", Const, 0}, + {"IFF_LOOPBACK", Const, 0}, + {"IFF_MASTER", Const, 0}, + {"IFF_MONITOR", Const, 0}, + {"IFF_MULTICAST", Const, 0}, + {"IFF_NOARP", Const, 0}, + {"IFF_NOTRAILERS", Const, 0}, + {"IFF_NO_PI", Const, 0}, + {"IFF_OACTIVE", Const, 0}, + {"IFF_ONE_QUEUE", Const, 0}, + {"IFF_POINTOPOINT", Const, 0}, + {"IFF_POINTTOPOINT", Const, 0}, + {"IFF_PORTSEL", Const, 0}, + {"IFF_PPROMISC", Const, 0}, + {"IFF_PROMISC", Const, 0}, + {"IFF_RENAMING", Const, 0}, + {"IFF_RUNNING", Const, 0}, + {"IFF_SIMPLEX", Const, 0}, + {"IFF_SLAVE", Const, 0}, + {"IFF_SMART", Const, 0}, + {"IFF_STATICARP", Const, 0}, + {"IFF_TAP", Const, 0}, + {"IFF_TUN", Const, 0}, + {"IFF_TUN_EXCL", Const, 0}, + {"IFF_UP", Const, 0}, + {"IFF_VNET_HDR", Const, 0}, + {"IFLA_ADDRESS", Const, 0}, + {"IFLA_BROADCAST", Const, 0}, + {"IFLA_COST", Const, 0}, + {"IFLA_IFALIAS", Const, 0}, + {"IFLA_IFNAME", Const, 0}, + {"IFLA_LINK", Const, 0}, + {"IFLA_LINKINFO", Const, 0}, + {"IFLA_LINKMODE", Const, 0}, + {"IFLA_MAP", Const, 0}, + {"IFLA_MASTER", Const, 0}, + {"IFLA_MAX", Const, 0}, + {"IFLA_MTU", Const, 0}, + {"IFLA_NET_NS_PID", Const, 0}, + {"IFLA_OPERSTATE", Const, 0}, + {"IFLA_PRIORITY", Const, 0}, + {"IFLA_PROTINFO", Const, 0}, + {"IFLA_QDISC", Const, 0}, + {"IFLA_STATS", Const, 0}, + {"IFLA_TXQLEN", Const, 0}, + {"IFLA_UNSPEC", Const, 0}, + {"IFLA_WEIGHT", Const, 0}, + {"IFLA_WIRELESS", Const, 0}, + {"IFNAMSIZ", Const, 0}, + {"IFT_1822", Const, 0}, + {"IFT_A12MPPSWITCH", Const, 0}, + {"IFT_AAL2", Const, 0}, + {"IFT_AAL5", Const, 0}, + {"IFT_ADSL", Const, 0}, + {"IFT_AFLANE8023", Const, 0}, + {"IFT_AFLANE8025", Const, 0}, + {"IFT_ARAP", Const, 0}, + {"IFT_ARCNET", Const, 0}, + {"IFT_ARCNETPLUS", Const, 0}, + {"IFT_ASYNC", Const, 0}, + {"IFT_ATM", Const, 0}, + {"IFT_ATMDXI", Const, 0}, + {"IFT_ATMFUNI", Const, 0}, + {"IFT_ATMIMA", Const, 0}, + {"IFT_ATMLOGICAL", Const, 0}, + {"IFT_ATMRADIO", Const, 0}, + {"IFT_ATMSUBINTERFACE", Const, 0}, + {"IFT_ATMVCIENDPT", Const, 0}, + {"IFT_ATMVIRTUAL", Const, 0}, + {"IFT_BGPPOLICYACCOUNTING", Const, 0}, + {"IFT_BLUETOOTH", Const, 1}, + {"IFT_BRIDGE", Const, 0}, + {"IFT_BSC", Const, 0}, + {"IFT_CARP", Const, 0}, + {"IFT_CCTEMUL", Const, 0}, + {"IFT_CELLULAR", Const, 0}, + {"IFT_CEPT", Const, 0}, + {"IFT_CES", Const, 0}, + {"IFT_CHANNEL", Const, 0}, + {"IFT_CNR", Const, 0}, + {"IFT_COFFEE", Const, 0}, + {"IFT_COMPOSITELINK", Const, 0}, + {"IFT_DCN", Const, 0}, + {"IFT_DIGITALPOWERLINE", Const, 0}, + {"IFT_DIGITALWRAPPEROVERHEADCHANNEL", Const, 0}, + {"IFT_DLSW", Const, 0}, + {"IFT_DOCSCABLEDOWNSTREAM", Const, 0}, + {"IFT_DOCSCABLEMACLAYER", Const, 0}, + {"IFT_DOCSCABLEUPSTREAM", Const, 0}, + {"IFT_DOCSCABLEUPSTREAMCHANNEL", Const, 1}, + {"IFT_DS0", Const, 0}, + {"IFT_DS0BUNDLE", Const, 0}, + {"IFT_DS1FDL", Const, 0}, + {"IFT_DS3", Const, 0}, + {"IFT_DTM", Const, 0}, + {"IFT_DUMMY", Const, 1}, + {"IFT_DVBASILN", Const, 0}, + {"IFT_DVBASIOUT", Const, 0}, + {"IFT_DVBRCCDOWNSTREAM", Const, 0}, + {"IFT_DVBRCCMACLAYER", Const, 0}, + {"IFT_DVBRCCUPSTREAM", Const, 0}, + {"IFT_ECONET", Const, 1}, + {"IFT_ENC", Const, 0}, + {"IFT_EON", Const, 0}, + {"IFT_EPLRS", Const, 0}, + {"IFT_ESCON", Const, 0}, + {"IFT_ETHER", Const, 0}, + {"IFT_FAITH", Const, 0}, + {"IFT_FAST", Const, 0}, + {"IFT_FASTETHER", Const, 0}, + {"IFT_FASTETHERFX", Const, 0}, + {"IFT_FDDI", Const, 0}, + {"IFT_FIBRECHANNEL", Const, 0}, + {"IFT_FRAMERELAYINTERCONNECT", Const, 0}, + {"IFT_FRAMERELAYMPI", Const, 0}, + {"IFT_FRDLCIENDPT", Const, 0}, + {"IFT_FRELAY", Const, 0}, + {"IFT_FRELAYDCE", Const, 0}, + {"IFT_FRF16MFRBUNDLE", Const, 0}, + {"IFT_FRFORWARD", Const, 0}, + {"IFT_G703AT2MB", Const, 0}, + {"IFT_G703AT64K", Const, 0}, + {"IFT_GIF", Const, 0}, + {"IFT_GIGABITETHERNET", Const, 0}, + {"IFT_GR303IDT", Const, 0}, + {"IFT_GR303RDT", Const, 0}, + {"IFT_H323GATEKEEPER", Const, 0}, + {"IFT_H323PROXY", Const, 0}, + {"IFT_HDH1822", Const, 0}, + {"IFT_HDLC", Const, 0}, + {"IFT_HDSL2", Const, 0}, + {"IFT_HIPERLAN2", Const, 0}, + {"IFT_HIPPI", Const, 0}, + {"IFT_HIPPIINTERFACE", Const, 0}, + {"IFT_HOSTPAD", Const, 0}, + {"IFT_HSSI", Const, 0}, + {"IFT_HY", Const, 0}, + {"IFT_IBM370PARCHAN", Const, 0}, + {"IFT_IDSL", Const, 0}, + {"IFT_IEEE1394", Const, 0}, + {"IFT_IEEE80211", Const, 0}, + {"IFT_IEEE80212", Const, 0}, + {"IFT_IEEE8023ADLAG", Const, 0}, + {"IFT_IFGSN", Const, 0}, + {"IFT_IMT", Const, 0}, + {"IFT_INFINIBAND", Const, 1}, + {"IFT_INTERLEAVE", Const, 0}, + {"IFT_IP", Const, 0}, + {"IFT_IPFORWARD", Const, 0}, + {"IFT_IPOVERATM", Const, 0}, + {"IFT_IPOVERCDLC", Const, 0}, + {"IFT_IPOVERCLAW", Const, 0}, + {"IFT_IPSWITCH", Const, 0}, + {"IFT_IPXIP", Const, 0}, + {"IFT_ISDN", Const, 0}, + {"IFT_ISDNBASIC", Const, 0}, + {"IFT_ISDNPRIMARY", Const, 0}, + {"IFT_ISDNS", Const, 0}, + {"IFT_ISDNU", Const, 0}, + {"IFT_ISO88022LLC", Const, 0}, + {"IFT_ISO88023", Const, 0}, + {"IFT_ISO88024", Const, 0}, + {"IFT_ISO88025", Const, 0}, + {"IFT_ISO88025CRFPINT", Const, 0}, + {"IFT_ISO88025DTR", Const, 0}, + {"IFT_ISO88025FIBER", Const, 0}, + {"IFT_ISO88026", Const, 0}, + {"IFT_ISUP", Const, 0}, + {"IFT_L2VLAN", Const, 0}, + {"IFT_L3IPVLAN", Const, 0}, + {"IFT_L3IPXVLAN", Const, 0}, + {"IFT_LAPB", Const, 0}, + {"IFT_LAPD", Const, 0}, + {"IFT_LAPF", Const, 0}, + {"IFT_LINEGROUP", Const, 1}, + {"IFT_LOCALTALK", Const, 0}, + {"IFT_LOOP", Const, 0}, + {"IFT_MEDIAMAILOVERIP", Const, 0}, + {"IFT_MFSIGLINK", Const, 0}, + {"IFT_MIOX25", Const, 0}, + {"IFT_MODEM", Const, 0}, + {"IFT_MPC", Const, 0}, + {"IFT_MPLS", Const, 0}, + {"IFT_MPLSTUNNEL", Const, 0}, + {"IFT_MSDSL", Const, 0}, + {"IFT_MVL", Const, 0}, + {"IFT_MYRINET", Const, 0}, + {"IFT_NFAS", Const, 0}, + {"IFT_NSIP", Const, 0}, + {"IFT_OPTICALCHANNEL", Const, 0}, + {"IFT_OPTICALTRANSPORT", Const, 0}, + {"IFT_OTHER", Const, 0}, + {"IFT_P10", Const, 0}, + {"IFT_P80", Const, 0}, + {"IFT_PARA", Const, 0}, + {"IFT_PDP", Const, 0}, + {"IFT_PFLOG", Const, 0}, + {"IFT_PFLOW", Const, 1}, + {"IFT_PFSYNC", Const, 0}, + {"IFT_PLC", Const, 0}, + {"IFT_PON155", Const, 1}, + {"IFT_PON622", Const, 1}, + {"IFT_POS", Const, 0}, + {"IFT_PPP", Const, 0}, + {"IFT_PPPMULTILINKBUNDLE", Const, 0}, + {"IFT_PROPATM", Const, 1}, + {"IFT_PROPBWAP2MP", Const, 0}, + {"IFT_PROPCNLS", Const, 0}, + {"IFT_PROPDOCSWIRELESSDOWNSTREAM", Const, 0}, + {"IFT_PROPDOCSWIRELESSMACLAYER", Const, 0}, + {"IFT_PROPDOCSWIRELESSUPSTREAM", Const, 0}, + {"IFT_PROPMUX", Const, 0}, + {"IFT_PROPVIRTUAL", Const, 0}, + {"IFT_PROPWIRELESSP2P", Const, 0}, + {"IFT_PTPSERIAL", Const, 0}, + {"IFT_PVC", Const, 0}, + {"IFT_Q2931", Const, 1}, + {"IFT_QLLC", Const, 0}, + {"IFT_RADIOMAC", Const, 0}, + {"IFT_RADSL", Const, 0}, + {"IFT_REACHDSL", Const, 0}, + {"IFT_RFC1483", Const, 0}, + {"IFT_RS232", Const, 0}, + {"IFT_RSRB", Const, 0}, + {"IFT_SDLC", Const, 0}, + {"IFT_SDSL", Const, 0}, + {"IFT_SHDSL", Const, 0}, + {"IFT_SIP", Const, 0}, + {"IFT_SIPSIG", Const, 1}, + {"IFT_SIPTG", Const, 1}, + {"IFT_SLIP", Const, 0}, + {"IFT_SMDSDXI", Const, 0}, + {"IFT_SMDSICIP", Const, 0}, + {"IFT_SONET", Const, 0}, + {"IFT_SONETOVERHEADCHANNEL", Const, 0}, + {"IFT_SONETPATH", Const, 0}, + {"IFT_SONETVT", Const, 0}, + {"IFT_SRP", Const, 0}, + {"IFT_SS7SIGLINK", Const, 0}, + {"IFT_STACKTOSTACK", Const, 0}, + {"IFT_STARLAN", Const, 0}, + {"IFT_STF", Const, 0}, + {"IFT_T1", Const, 0}, + {"IFT_TDLC", Const, 0}, + {"IFT_TELINK", Const, 1}, + {"IFT_TERMPAD", Const, 0}, + {"IFT_TR008", Const, 0}, + {"IFT_TRANSPHDLC", Const, 0}, + {"IFT_TUNNEL", Const, 0}, + {"IFT_ULTRA", Const, 0}, + {"IFT_USB", Const, 0}, + {"IFT_V11", Const, 0}, + {"IFT_V35", Const, 0}, + {"IFT_V36", Const, 0}, + {"IFT_V37", Const, 0}, + {"IFT_VDSL", Const, 0}, + {"IFT_VIRTUALIPADDRESS", Const, 0}, + {"IFT_VIRTUALTG", Const, 1}, + {"IFT_VOICEDID", Const, 1}, + {"IFT_VOICEEM", Const, 0}, + {"IFT_VOICEEMFGD", Const, 1}, + {"IFT_VOICEENCAP", Const, 0}, + {"IFT_VOICEFGDEANA", Const, 1}, + {"IFT_VOICEFXO", Const, 0}, + {"IFT_VOICEFXS", Const, 0}, + {"IFT_VOICEOVERATM", Const, 0}, + {"IFT_VOICEOVERCABLE", Const, 1}, + {"IFT_VOICEOVERFRAMERELAY", Const, 0}, + {"IFT_VOICEOVERIP", Const, 0}, + {"IFT_X213", Const, 0}, + {"IFT_X25", Const, 0}, + {"IFT_X25DDN", Const, 0}, + {"IFT_X25HUNTGROUP", Const, 0}, + {"IFT_X25MLP", Const, 0}, + {"IFT_X25PLE", Const, 0}, + {"IFT_XETHER", Const, 0}, + {"IGNBRK", Const, 0}, + {"IGNCR", Const, 0}, + {"IGNORE", Const, 0}, + {"IGNPAR", Const, 0}, + {"IMAXBEL", Const, 0}, + {"INFINITE", Const, 0}, + {"INLCR", Const, 0}, + {"INPCK", Const, 0}, + {"INVALID_FILE_ATTRIBUTES", Const, 0}, + {"IN_ACCESS", Const, 0}, + {"IN_ALL_EVENTS", Const, 0}, + {"IN_ATTRIB", Const, 0}, + {"IN_CLASSA_HOST", Const, 0}, + {"IN_CLASSA_MAX", Const, 0}, + {"IN_CLASSA_NET", Const, 0}, + {"IN_CLASSA_NSHIFT", Const, 0}, + {"IN_CLASSB_HOST", Const, 0}, + {"IN_CLASSB_MAX", Const, 0}, + {"IN_CLASSB_NET", Const, 0}, + {"IN_CLASSB_NSHIFT", Const, 0}, + {"IN_CLASSC_HOST", Const, 0}, + {"IN_CLASSC_NET", Const, 0}, + {"IN_CLASSC_NSHIFT", Const, 0}, + {"IN_CLASSD_HOST", Const, 0}, + {"IN_CLASSD_NET", Const, 0}, + {"IN_CLASSD_NSHIFT", Const, 0}, + {"IN_CLOEXEC", Const, 0}, + {"IN_CLOSE", Const, 0}, + {"IN_CLOSE_NOWRITE", Const, 0}, + {"IN_CLOSE_WRITE", Const, 0}, + {"IN_CREATE", Const, 0}, + {"IN_DELETE", Const, 0}, + {"IN_DELETE_SELF", Const, 0}, + {"IN_DONT_FOLLOW", Const, 0}, + {"IN_EXCL_UNLINK", Const, 0}, + {"IN_IGNORED", Const, 0}, + {"IN_ISDIR", Const, 0}, + {"IN_LINKLOCALNETNUM", Const, 0}, + {"IN_LOOPBACKNET", Const, 0}, + {"IN_MASK_ADD", Const, 0}, + {"IN_MODIFY", Const, 0}, + {"IN_MOVE", Const, 0}, + {"IN_MOVED_FROM", Const, 0}, + {"IN_MOVED_TO", Const, 0}, + {"IN_MOVE_SELF", Const, 0}, + {"IN_NONBLOCK", Const, 0}, + {"IN_ONESHOT", Const, 0}, + {"IN_ONLYDIR", Const, 0}, + {"IN_OPEN", Const, 0}, + {"IN_Q_OVERFLOW", Const, 0}, + {"IN_RFC3021_HOST", Const, 1}, + {"IN_RFC3021_MASK", Const, 1}, + {"IN_RFC3021_NET", Const, 1}, + {"IN_RFC3021_NSHIFT", Const, 1}, + {"IN_UNMOUNT", Const, 0}, + {"IOC_IN", Const, 1}, + {"IOC_INOUT", Const, 1}, + {"IOC_OUT", Const, 1}, + {"IOC_VENDOR", Const, 3}, + {"IOC_WS2", Const, 1}, + {"IO_REPARSE_TAG_SYMLINK", Const, 4}, + {"IPMreq", Type, 0}, + {"IPMreq.Interface", Field, 0}, + {"IPMreq.Multiaddr", Field, 0}, + {"IPMreqn", Type, 0}, + {"IPMreqn.Address", Field, 0}, + {"IPMreqn.Ifindex", Field, 0}, + {"IPMreqn.Multiaddr", Field, 0}, + {"IPPROTO_3PC", Const, 0}, + {"IPPROTO_ADFS", Const, 0}, + {"IPPROTO_AH", Const, 0}, + {"IPPROTO_AHIP", Const, 0}, + {"IPPROTO_APES", Const, 0}, + {"IPPROTO_ARGUS", Const, 0}, + {"IPPROTO_AX25", Const, 0}, + {"IPPROTO_BHA", Const, 0}, + {"IPPROTO_BLT", Const, 0}, + {"IPPROTO_BRSATMON", Const, 0}, + {"IPPROTO_CARP", Const, 0}, + {"IPPROTO_CFTP", Const, 0}, + {"IPPROTO_CHAOS", Const, 0}, + {"IPPROTO_CMTP", Const, 0}, + {"IPPROTO_COMP", Const, 0}, + {"IPPROTO_CPHB", Const, 0}, + {"IPPROTO_CPNX", Const, 0}, + {"IPPROTO_DCCP", Const, 0}, + {"IPPROTO_DDP", Const, 0}, + {"IPPROTO_DGP", Const, 0}, + {"IPPROTO_DIVERT", Const, 0}, + {"IPPROTO_DIVERT_INIT", Const, 3}, + {"IPPROTO_DIVERT_RESP", Const, 3}, + {"IPPROTO_DONE", Const, 0}, + {"IPPROTO_DSTOPTS", Const, 0}, + {"IPPROTO_EGP", Const, 0}, + {"IPPROTO_EMCON", Const, 0}, + {"IPPROTO_ENCAP", Const, 0}, + {"IPPROTO_EON", Const, 0}, + {"IPPROTO_ESP", Const, 0}, + {"IPPROTO_ETHERIP", Const, 0}, + {"IPPROTO_FRAGMENT", Const, 0}, + {"IPPROTO_GGP", Const, 0}, + {"IPPROTO_GMTP", Const, 0}, + {"IPPROTO_GRE", Const, 0}, + {"IPPROTO_HELLO", Const, 0}, + {"IPPROTO_HMP", Const, 0}, + {"IPPROTO_HOPOPTS", Const, 0}, + {"IPPROTO_ICMP", Const, 0}, + {"IPPROTO_ICMPV6", Const, 0}, + {"IPPROTO_IDP", Const, 0}, + {"IPPROTO_IDPR", Const, 0}, + {"IPPROTO_IDRP", Const, 0}, + {"IPPROTO_IGMP", Const, 0}, + {"IPPROTO_IGP", Const, 0}, + {"IPPROTO_IGRP", Const, 0}, + {"IPPROTO_IL", Const, 0}, + {"IPPROTO_INLSP", Const, 0}, + {"IPPROTO_INP", Const, 0}, + {"IPPROTO_IP", Const, 0}, + {"IPPROTO_IPCOMP", Const, 0}, + {"IPPROTO_IPCV", Const, 0}, + {"IPPROTO_IPEIP", Const, 0}, + {"IPPROTO_IPIP", Const, 0}, + {"IPPROTO_IPPC", Const, 0}, + {"IPPROTO_IPV4", Const, 0}, + {"IPPROTO_IPV6", Const, 0}, + {"IPPROTO_IPV6_ICMP", Const, 1}, + {"IPPROTO_IRTP", Const, 0}, + {"IPPROTO_KRYPTOLAN", Const, 0}, + {"IPPROTO_LARP", Const, 0}, + {"IPPROTO_LEAF1", Const, 0}, + {"IPPROTO_LEAF2", Const, 0}, + {"IPPROTO_MAX", Const, 0}, + {"IPPROTO_MAXID", Const, 0}, + {"IPPROTO_MEAS", Const, 0}, + {"IPPROTO_MH", Const, 1}, + {"IPPROTO_MHRP", Const, 0}, + {"IPPROTO_MICP", Const, 0}, + {"IPPROTO_MOBILE", Const, 0}, + {"IPPROTO_MPLS", Const, 1}, + {"IPPROTO_MTP", Const, 0}, + {"IPPROTO_MUX", Const, 0}, + {"IPPROTO_ND", Const, 0}, + {"IPPROTO_NHRP", Const, 0}, + {"IPPROTO_NONE", Const, 0}, + {"IPPROTO_NSP", Const, 0}, + {"IPPROTO_NVPII", Const, 0}, + {"IPPROTO_OLD_DIVERT", Const, 0}, + {"IPPROTO_OSPFIGP", Const, 0}, + {"IPPROTO_PFSYNC", Const, 0}, + {"IPPROTO_PGM", Const, 0}, + {"IPPROTO_PIGP", Const, 0}, + {"IPPROTO_PIM", Const, 0}, + {"IPPROTO_PRM", Const, 0}, + {"IPPROTO_PUP", Const, 0}, + {"IPPROTO_PVP", Const, 0}, + {"IPPROTO_RAW", Const, 0}, + {"IPPROTO_RCCMON", Const, 0}, + {"IPPROTO_RDP", Const, 0}, + {"IPPROTO_ROUTING", Const, 0}, + {"IPPROTO_RSVP", Const, 0}, + {"IPPROTO_RVD", Const, 0}, + {"IPPROTO_SATEXPAK", Const, 0}, + {"IPPROTO_SATMON", Const, 0}, + {"IPPROTO_SCCSP", Const, 0}, + {"IPPROTO_SCTP", Const, 0}, + {"IPPROTO_SDRP", Const, 0}, + {"IPPROTO_SEND", Const, 1}, + {"IPPROTO_SEP", Const, 0}, + {"IPPROTO_SKIP", Const, 0}, + {"IPPROTO_SPACER", Const, 0}, + {"IPPROTO_SRPC", Const, 0}, + {"IPPROTO_ST", Const, 0}, + {"IPPROTO_SVMTP", Const, 0}, + {"IPPROTO_SWIPE", Const, 0}, + {"IPPROTO_TCF", Const, 0}, + {"IPPROTO_TCP", Const, 0}, + {"IPPROTO_TLSP", Const, 0}, + {"IPPROTO_TP", Const, 0}, + {"IPPROTO_TPXX", Const, 0}, + {"IPPROTO_TRUNK1", Const, 0}, + {"IPPROTO_TRUNK2", Const, 0}, + {"IPPROTO_TTP", Const, 0}, + {"IPPROTO_UDP", Const, 0}, + {"IPPROTO_UDPLITE", Const, 0}, + {"IPPROTO_VINES", Const, 0}, + {"IPPROTO_VISA", Const, 0}, + {"IPPROTO_VMTP", Const, 0}, + {"IPPROTO_VRRP", Const, 1}, + {"IPPROTO_WBEXPAK", Const, 0}, + {"IPPROTO_WBMON", Const, 0}, + {"IPPROTO_WSN", Const, 0}, + {"IPPROTO_XNET", Const, 0}, + {"IPPROTO_XTP", Const, 0}, + {"IPV6_2292DSTOPTS", Const, 0}, + {"IPV6_2292HOPLIMIT", Const, 0}, + {"IPV6_2292HOPOPTS", Const, 0}, + {"IPV6_2292NEXTHOP", Const, 0}, + {"IPV6_2292PKTINFO", Const, 0}, + {"IPV6_2292PKTOPTIONS", Const, 0}, + {"IPV6_2292RTHDR", Const, 0}, + {"IPV6_ADDRFORM", Const, 0}, + {"IPV6_ADD_MEMBERSHIP", Const, 0}, + {"IPV6_AUTHHDR", Const, 0}, + {"IPV6_AUTH_LEVEL", Const, 1}, + {"IPV6_AUTOFLOWLABEL", Const, 0}, + {"IPV6_BINDANY", Const, 0}, + {"IPV6_BINDV6ONLY", Const, 0}, + {"IPV6_BOUND_IF", Const, 0}, + {"IPV6_CHECKSUM", Const, 0}, + {"IPV6_DEFAULT_MULTICAST_HOPS", Const, 0}, + {"IPV6_DEFAULT_MULTICAST_LOOP", Const, 0}, + {"IPV6_DEFHLIM", Const, 0}, + {"IPV6_DONTFRAG", Const, 0}, + {"IPV6_DROP_MEMBERSHIP", Const, 0}, + {"IPV6_DSTOPTS", Const, 0}, + {"IPV6_ESP_NETWORK_LEVEL", Const, 1}, + {"IPV6_ESP_TRANS_LEVEL", Const, 1}, + {"IPV6_FAITH", Const, 0}, + {"IPV6_FLOWINFO_MASK", Const, 0}, + {"IPV6_FLOWLABEL_MASK", Const, 0}, + {"IPV6_FRAGTTL", Const, 0}, + {"IPV6_FW_ADD", Const, 0}, + {"IPV6_FW_DEL", Const, 0}, + {"IPV6_FW_FLUSH", Const, 0}, + {"IPV6_FW_GET", Const, 0}, + {"IPV6_FW_ZERO", Const, 0}, + {"IPV6_HLIMDEC", Const, 0}, + {"IPV6_HOPLIMIT", Const, 0}, + {"IPV6_HOPOPTS", Const, 0}, + {"IPV6_IPCOMP_LEVEL", Const, 1}, + {"IPV6_IPSEC_POLICY", Const, 0}, + {"IPV6_JOIN_ANYCAST", Const, 0}, + {"IPV6_JOIN_GROUP", Const, 0}, + {"IPV6_LEAVE_ANYCAST", Const, 0}, + {"IPV6_LEAVE_GROUP", Const, 0}, + {"IPV6_MAXHLIM", Const, 0}, + {"IPV6_MAXOPTHDR", Const, 0}, + {"IPV6_MAXPACKET", Const, 0}, + {"IPV6_MAX_GROUP_SRC_FILTER", Const, 0}, + {"IPV6_MAX_MEMBERSHIPS", Const, 0}, + {"IPV6_MAX_SOCK_SRC_FILTER", Const, 0}, + {"IPV6_MIN_MEMBERSHIPS", Const, 0}, + {"IPV6_MMTU", Const, 0}, + {"IPV6_MSFILTER", Const, 0}, + {"IPV6_MTU", Const, 0}, + {"IPV6_MTU_DISCOVER", Const, 0}, + {"IPV6_MULTICAST_HOPS", Const, 0}, + {"IPV6_MULTICAST_IF", Const, 0}, + {"IPV6_MULTICAST_LOOP", Const, 0}, + {"IPV6_NEXTHOP", Const, 0}, + {"IPV6_OPTIONS", Const, 1}, + {"IPV6_PATHMTU", Const, 0}, + {"IPV6_PIPEX", Const, 1}, + {"IPV6_PKTINFO", Const, 0}, + {"IPV6_PMTUDISC_DO", Const, 0}, + {"IPV6_PMTUDISC_DONT", Const, 0}, + {"IPV6_PMTUDISC_PROBE", Const, 0}, + {"IPV6_PMTUDISC_WANT", Const, 0}, + {"IPV6_PORTRANGE", Const, 0}, + {"IPV6_PORTRANGE_DEFAULT", Const, 0}, + {"IPV6_PORTRANGE_HIGH", Const, 0}, + {"IPV6_PORTRANGE_LOW", Const, 0}, + {"IPV6_PREFER_TEMPADDR", Const, 0}, + {"IPV6_RECVDSTOPTS", Const, 0}, + {"IPV6_RECVDSTPORT", Const, 3}, + {"IPV6_RECVERR", Const, 0}, + {"IPV6_RECVHOPLIMIT", Const, 0}, + {"IPV6_RECVHOPOPTS", Const, 0}, + {"IPV6_RECVPATHMTU", Const, 0}, + {"IPV6_RECVPKTINFO", Const, 0}, + {"IPV6_RECVRTHDR", Const, 0}, + {"IPV6_RECVTCLASS", Const, 0}, + {"IPV6_ROUTER_ALERT", Const, 0}, + {"IPV6_RTABLE", Const, 1}, + {"IPV6_RTHDR", Const, 0}, + {"IPV6_RTHDRDSTOPTS", Const, 0}, + {"IPV6_RTHDR_LOOSE", Const, 0}, + {"IPV6_RTHDR_STRICT", Const, 0}, + {"IPV6_RTHDR_TYPE_0", Const, 0}, + {"IPV6_RXDSTOPTS", Const, 0}, + {"IPV6_RXHOPOPTS", Const, 0}, + {"IPV6_SOCKOPT_RESERVED1", Const, 0}, + {"IPV6_TCLASS", Const, 0}, + {"IPV6_UNICAST_HOPS", Const, 0}, + {"IPV6_USE_MIN_MTU", Const, 0}, + {"IPV6_V6ONLY", Const, 0}, + {"IPV6_VERSION", Const, 0}, + {"IPV6_VERSION_MASK", Const, 0}, + {"IPV6_XFRM_POLICY", Const, 0}, + {"IP_ADD_MEMBERSHIP", Const, 0}, + {"IP_ADD_SOURCE_MEMBERSHIP", Const, 0}, + {"IP_AUTH_LEVEL", Const, 1}, + {"IP_BINDANY", Const, 0}, + {"IP_BLOCK_SOURCE", Const, 0}, + {"IP_BOUND_IF", Const, 0}, + {"IP_DEFAULT_MULTICAST_LOOP", Const, 0}, + {"IP_DEFAULT_MULTICAST_TTL", Const, 0}, + {"IP_DF", Const, 0}, + {"IP_DIVERTFL", Const, 3}, + {"IP_DONTFRAG", Const, 0}, + {"IP_DROP_MEMBERSHIP", Const, 0}, + {"IP_DROP_SOURCE_MEMBERSHIP", Const, 0}, + {"IP_DUMMYNET3", Const, 0}, + {"IP_DUMMYNET_CONFIGURE", Const, 0}, + {"IP_DUMMYNET_DEL", Const, 0}, + {"IP_DUMMYNET_FLUSH", Const, 0}, + {"IP_DUMMYNET_GET", Const, 0}, + {"IP_EF", Const, 1}, + {"IP_ERRORMTU", Const, 1}, + {"IP_ESP_NETWORK_LEVEL", Const, 1}, + {"IP_ESP_TRANS_LEVEL", Const, 1}, + {"IP_FAITH", Const, 0}, + {"IP_FREEBIND", Const, 0}, + {"IP_FW3", Const, 0}, + {"IP_FW_ADD", Const, 0}, + {"IP_FW_DEL", Const, 0}, + {"IP_FW_FLUSH", Const, 0}, + {"IP_FW_GET", Const, 0}, + {"IP_FW_NAT_CFG", Const, 0}, + {"IP_FW_NAT_DEL", Const, 0}, + {"IP_FW_NAT_GET_CONFIG", Const, 0}, + {"IP_FW_NAT_GET_LOG", Const, 0}, + {"IP_FW_RESETLOG", Const, 0}, + {"IP_FW_TABLE_ADD", Const, 0}, + {"IP_FW_TABLE_DEL", Const, 0}, + {"IP_FW_TABLE_FLUSH", Const, 0}, + {"IP_FW_TABLE_GETSIZE", Const, 0}, + {"IP_FW_TABLE_LIST", Const, 0}, + {"IP_FW_ZERO", Const, 0}, + {"IP_HDRINCL", Const, 0}, + {"IP_IPCOMP_LEVEL", Const, 1}, + {"IP_IPSECFLOWINFO", Const, 1}, + {"IP_IPSEC_LOCAL_AUTH", Const, 1}, + {"IP_IPSEC_LOCAL_CRED", Const, 1}, + {"IP_IPSEC_LOCAL_ID", Const, 1}, + {"IP_IPSEC_POLICY", Const, 0}, + {"IP_IPSEC_REMOTE_AUTH", Const, 1}, + {"IP_IPSEC_REMOTE_CRED", Const, 1}, + {"IP_IPSEC_REMOTE_ID", Const, 1}, + {"IP_MAXPACKET", Const, 0}, + {"IP_MAX_GROUP_SRC_FILTER", Const, 0}, + {"IP_MAX_MEMBERSHIPS", Const, 0}, + {"IP_MAX_SOCK_MUTE_FILTER", Const, 0}, + {"IP_MAX_SOCK_SRC_FILTER", Const, 0}, + {"IP_MAX_SOURCE_FILTER", Const, 0}, + {"IP_MF", Const, 0}, + {"IP_MINFRAGSIZE", Const, 1}, + {"IP_MINTTL", Const, 0}, + {"IP_MIN_MEMBERSHIPS", Const, 0}, + {"IP_MSFILTER", Const, 0}, + {"IP_MSS", Const, 0}, + {"IP_MTU", Const, 0}, + {"IP_MTU_DISCOVER", Const, 0}, + {"IP_MULTICAST_IF", Const, 0}, + {"IP_MULTICAST_IFINDEX", Const, 0}, + {"IP_MULTICAST_LOOP", Const, 0}, + {"IP_MULTICAST_TTL", Const, 0}, + {"IP_MULTICAST_VIF", Const, 0}, + {"IP_NAT__XXX", Const, 0}, + {"IP_OFFMASK", Const, 0}, + {"IP_OLD_FW_ADD", Const, 0}, + {"IP_OLD_FW_DEL", Const, 0}, + {"IP_OLD_FW_FLUSH", Const, 0}, + {"IP_OLD_FW_GET", Const, 0}, + {"IP_OLD_FW_RESETLOG", Const, 0}, + {"IP_OLD_FW_ZERO", Const, 0}, + {"IP_ONESBCAST", Const, 0}, + {"IP_OPTIONS", Const, 0}, + {"IP_ORIGDSTADDR", Const, 0}, + {"IP_PASSSEC", Const, 0}, + {"IP_PIPEX", Const, 1}, + {"IP_PKTINFO", Const, 0}, + {"IP_PKTOPTIONS", Const, 0}, + {"IP_PMTUDISC", Const, 0}, + {"IP_PMTUDISC_DO", Const, 0}, + {"IP_PMTUDISC_DONT", Const, 0}, + {"IP_PMTUDISC_PROBE", Const, 0}, + {"IP_PMTUDISC_WANT", Const, 0}, + {"IP_PORTRANGE", Const, 0}, + {"IP_PORTRANGE_DEFAULT", Const, 0}, + {"IP_PORTRANGE_HIGH", Const, 0}, + {"IP_PORTRANGE_LOW", Const, 0}, + {"IP_RECVDSTADDR", Const, 0}, + {"IP_RECVDSTPORT", Const, 1}, + {"IP_RECVERR", Const, 0}, + {"IP_RECVIF", Const, 0}, + {"IP_RECVOPTS", Const, 0}, + {"IP_RECVORIGDSTADDR", Const, 0}, + {"IP_RECVPKTINFO", Const, 0}, + {"IP_RECVRETOPTS", Const, 0}, + {"IP_RECVRTABLE", Const, 1}, + {"IP_RECVTOS", Const, 0}, + {"IP_RECVTTL", Const, 0}, + {"IP_RETOPTS", Const, 0}, + {"IP_RF", Const, 0}, + {"IP_ROUTER_ALERT", Const, 0}, + {"IP_RSVP_OFF", Const, 0}, + {"IP_RSVP_ON", Const, 0}, + {"IP_RSVP_VIF_OFF", Const, 0}, + {"IP_RSVP_VIF_ON", Const, 0}, + {"IP_RTABLE", Const, 1}, + {"IP_SENDSRCADDR", Const, 0}, + {"IP_STRIPHDR", Const, 0}, + {"IP_TOS", Const, 0}, + {"IP_TRAFFIC_MGT_BACKGROUND", Const, 0}, + {"IP_TRANSPARENT", Const, 0}, + {"IP_TTL", Const, 0}, + {"IP_UNBLOCK_SOURCE", Const, 0}, + {"IP_XFRM_POLICY", Const, 0}, + {"IPv6MTUInfo", Type, 2}, + {"IPv6MTUInfo.Addr", Field, 2}, + {"IPv6MTUInfo.Mtu", Field, 2}, + {"IPv6Mreq", Type, 0}, + {"IPv6Mreq.Interface", Field, 0}, + {"IPv6Mreq.Multiaddr", Field, 0}, + {"ISIG", Const, 0}, + {"ISTRIP", Const, 0}, + {"IUCLC", Const, 0}, + {"IUTF8", Const, 0}, + {"IXANY", Const, 0}, + {"IXOFF", Const, 0}, + {"IXON", Const, 0}, + {"IfAddrmsg", Type, 0}, + {"IfAddrmsg.Family", Field, 0}, + {"IfAddrmsg.Flags", Field, 0}, + {"IfAddrmsg.Index", Field, 0}, + {"IfAddrmsg.Prefixlen", Field, 0}, + {"IfAddrmsg.Scope", Field, 0}, + {"IfAnnounceMsghdr", Type, 1}, + {"IfAnnounceMsghdr.Hdrlen", Field, 2}, + {"IfAnnounceMsghdr.Index", Field, 1}, + {"IfAnnounceMsghdr.Msglen", Field, 1}, + {"IfAnnounceMsghdr.Name", Field, 1}, + {"IfAnnounceMsghdr.Type", Field, 1}, + {"IfAnnounceMsghdr.Version", Field, 1}, + {"IfAnnounceMsghdr.What", Field, 1}, + {"IfData", Type, 0}, + {"IfData.Addrlen", Field, 0}, + {"IfData.Baudrate", Field, 0}, + {"IfData.Capabilities", Field, 2}, + {"IfData.Collisions", Field, 0}, + {"IfData.Datalen", Field, 0}, + {"IfData.Epoch", Field, 0}, + {"IfData.Hdrlen", Field, 0}, + {"IfData.Hwassist", Field, 0}, + {"IfData.Ibytes", Field, 0}, + {"IfData.Ierrors", Field, 0}, + {"IfData.Imcasts", Field, 0}, + {"IfData.Ipackets", Field, 0}, + {"IfData.Iqdrops", Field, 0}, + {"IfData.Lastchange", Field, 0}, + {"IfData.Link_state", Field, 0}, + {"IfData.Mclpool", Field, 2}, + {"IfData.Metric", Field, 0}, + {"IfData.Mtu", Field, 0}, + {"IfData.Noproto", Field, 0}, + {"IfData.Obytes", Field, 0}, + {"IfData.Oerrors", Field, 0}, + {"IfData.Omcasts", Field, 0}, + {"IfData.Opackets", Field, 0}, + {"IfData.Pad", Field, 2}, + {"IfData.Pad_cgo_0", Field, 2}, + {"IfData.Pad_cgo_1", Field, 2}, + {"IfData.Physical", Field, 0}, + {"IfData.Recvquota", Field, 0}, + {"IfData.Recvtiming", Field, 0}, + {"IfData.Reserved1", Field, 0}, + {"IfData.Reserved2", Field, 0}, + {"IfData.Spare_char1", Field, 0}, + {"IfData.Spare_char2", Field, 0}, + {"IfData.Type", Field, 0}, + {"IfData.Typelen", Field, 0}, + {"IfData.Unused1", Field, 0}, + {"IfData.Unused2", Field, 0}, + {"IfData.Xmitquota", Field, 0}, + {"IfData.Xmittiming", Field, 0}, + {"IfInfomsg", Type, 0}, + {"IfInfomsg.Change", Field, 0}, + {"IfInfomsg.Family", Field, 0}, + {"IfInfomsg.Flags", Field, 0}, + {"IfInfomsg.Index", Field, 0}, + {"IfInfomsg.Type", Field, 0}, + {"IfInfomsg.X__ifi_pad", Field, 0}, + {"IfMsghdr", Type, 0}, + {"IfMsghdr.Addrs", Field, 0}, + {"IfMsghdr.Data", Field, 0}, + {"IfMsghdr.Flags", Field, 0}, + {"IfMsghdr.Hdrlen", Field, 2}, + {"IfMsghdr.Index", Field, 0}, + {"IfMsghdr.Msglen", Field, 0}, + {"IfMsghdr.Pad1", Field, 2}, + {"IfMsghdr.Pad2", Field, 2}, + {"IfMsghdr.Pad_cgo_0", Field, 0}, + {"IfMsghdr.Pad_cgo_1", Field, 2}, + {"IfMsghdr.Tableid", Field, 2}, + {"IfMsghdr.Type", Field, 0}, + {"IfMsghdr.Version", Field, 0}, + {"IfMsghdr.Xflags", Field, 2}, + {"IfaMsghdr", Type, 0}, + {"IfaMsghdr.Addrs", Field, 0}, + {"IfaMsghdr.Flags", Field, 0}, + {"IfaMsghdr.Hdrlen", Field, 2}, + {"IfaMsghdr.Index", Field, 0}, + {"IfaMsghdr.Metric", Field, 0}, + {"IfaMsghdr.Msglen", Field, 0}, + {"IfaMsghdr.Pad1", Field, 2}, + {"IfaMsghdr.Pad2", Field, 2}, + {"IfaMsghdr.Pad_cgo_0", Field, 0}, + {"IfaMsghdr.Tableid", Field, 2}, + {"IfaMsghdr.Type", Field, 0}, + {"IfaMsghdr.Version", Field, 0}, + {"IfmaMsghdr", Type, 0}, + {"IfmaMsghdr.Addrs", Field, 0}, + {"IfmaMsghdr.Flags", Field, 0}, + {"IfmaMsghdr.Index", Field, 0}, + {"IfmaMsghdr.Msglen", Field, 0}, + {"IfmaMsghdr.Pad_cgo_0", Field, 0}, + {"IfmaMsghdr.Type", Field, 0}, + {"IfmaMsghdr.Version", Field, 0}, + {"IfmaMsghdr2", Type, 0}, + {"IfmaMsghdr2.Addrs", Field, 0}, + {"IfmaMsghdr2.Flags", Field, 0}, + {"IfmaMsghdr2.Index", Field, 0}, + {"IfmaMsghdr2.Msglen", Field, 0}, + {"IfmaMsghdr2.Pad_cgo_0", Field, 0}, + {"IfmaMsghdr2.Refcount", Field, 0}, + {"IfmaMsghdr2.Type", Field, 0}, + {"IfmaMsghdr2.Version", Field, 0}, + {"ImplementsGetwd", Const, 0}, + {"Inet4Pktinfo", Type, 0}, + {"Inet4Pktinfo.Addr", Field, 0}, + {"Inet4Pktinfo.Ifindex", Field, 0}, + {"Inet4Pktinfo.Spec_dst", Field, 0}, + {"Inet6Pktinfo", Type, 0}, + {"Inet6Pktinfo.Addr", Field, 0}, + {"Inet6Pktinfo.Ifindex", Field, 0}, + {"InotifyAddWatch", Func, 0}, + {"InotifyEvent", Type, 0}, + {"InotifyEvent.Cookie", Field, 0}, + {"InotifyEvent.Len", Field, 0}, + {"InotifyEvent.Mask", Field, 0}, + {"InotifyEvent.Name", Field, 0}, + {"InotifyEvent.Wd", Field, 0}, + {"InotifyInit", Func, 0}, + {"InotifyInit1", Func, 0}, + {"InotifyRmWatch", Func, 0}, + {"InterfaceAddrMessage", Type, 0}, + {"InterfaceAddrMessage.Data", Field, 0}, + {"InterfaceAddrMessage.Header", Field, 0}, + {"InterfaceAnnounceMessage", Type, 1}, + {"InterfaceAnnounceMessage.Header", Field, 1}, + {"InterfaceInfo", Type, 0}, + {"InterfaceInfo.Address", Field, 0}, + {"InterfaceInfo.BroadcastAddress", Field, 0}, + {"InterfaceInfo.Flags", Field, 0}, + {"InterfaceInfo.Netmask", Field, 0}, + {"InterfaceMessage", Type, 0}, + {"InterfaceMessage.Data", Field, 0}, + {"InterfaceMessage.Header", Field, 0}, + {"InterfaceMulticastAddrMessage", Type, 0}, + {"InterfaceMulticastAddrMessage.Data", Field, 0}, + {"InterfaceMulticastAddrMessage.Header", Field, 0}, + {"InvalidHandle", Const, 0}, + {"Ioperm", Func, 0}, + {"Iopl", Func, 0}, + {"Iovec", Type, 0}, + {"Iovec.Base", Field, 0}, + {"Iovec.Len", Field, 0}, + {"IpAdapterInfo", Type, 0}, + {"IpAdapterInfo.AdapterName", Field, 0}, + {"IpAdapterInfo.Address", Field, 0}, + {"IpAdapterInfo.AddressLength", Field, 0}, + {"IpAdapterInfo.ComboIndex", Field, 0}, + {"IpAdapterInfo.CurrentIpAddress", Field, 0}, + {"IpAdapterInfo.Description", Field, 0}, + {"IpAdapterInfo.DhcpEnabled", Field, 0}, + {"IpAdapterInfo.DhcpServer", Field, 0}, + {"IpAdapterInfo.GatewayList", Field, 0}, + {"IpAdapterInfo.HaveWins", Field, 0}, + {"IpAdapterInfo.Index", Field, 0}, + {"IpAdapterInfo.IpAddressList", Field, 0}, + {"IpAdapterInfo.LeaseExpires", Field, 0}, + {"IpAdapterInfo.LeaseObtained", Field, 0}, + {"IpAdapterInfo.Next", Field, 0}, + {"IpAdapterInfo.PrimaryWinsServer", Field, 0}, + {"IpAdapterInfo.SecondaryWinsServer", Field, 0}, + {"IpAdapterInfo.Type", Field, 0}, + {"IpAddrString", Type, 0}, + {"IpAddrString.Context", Field, 0}, + {"IpAddrString.IpAddress", Field, 0}, + {"IpAddrString.IpMask", Field, 0}, + {"IpAddrString.Next", Field, 0}, + {"IpAddressString", Type, 0}, + {"IpAddressString.String", Field, 0}, + {"IpMaskString", Type, 0}, + {"IpMaskString.String", Field, 2}, + {"Issetugid", Func, 0}, + {"KEY_ALL_ACCESS", Const, 0}, + {"KEY_CREATE_LINK", Const, 0}, + {"KEY_CREATE_SUB_KEY", Const, 0}, + {"KEY_ENUMERATE_SUB_KEYS", Const, 0}, + {"KEY_EXECUTE", Const, 0}, + {"KEY_NOTIFY", Const, 0}, + {"KEY_QUERY_VALUE", Const, 0}, + {"KEY_READ", Const, 0}, + {"KEY_SET_VALUE", Const, 0}, + {"KEY_WOW64_32KEY", Const, 0}, + {"KEY_WOW64_64KEY", Const, 0}, + {"KEY_WRITE", Const, 0}, + {"Kevent", Func, 0}, + {"Kevent_t", Type, 0}, + {"Kevent_t.Data", Field, 0}, + {"Kevent_t.Fflags", Field, 0}, + {"Kevent_t.Filter", Field, 0}, + {"Kevent_t.Flags", Field, 0}, + {"Kevent_t.Ident", Field, 0}, + {"Kevent_t.Pad_cgo_0", Field, 2}, + {"Kevent_t.Udata", Field, 0}, + {"Kill", Func, 0}, + {"Klogctl", Func, 0}, + {"Kqueue", Func, 0}, + {"LANG_ENGLISH", Const, 0}, + {"LAYERED_PROTOCOL", Const, 2}, + {"LCNT_OVERLOAD_FLUSH", Const, 1}, + {"LINUX_REBOOT_CMD_CAD_OFF", Const, 0}, + {"LINUX_REBOOT_CMD_CAD_ON", Const, 0}, + {"LINUX_REBOOT_CMD_HALT", Const, 0}, + {"LINUX_REBOOT_CMD_KEXEC", Const, 0}, + {"LINUX_REBOOT_CMD_POWER_OFF", Const, 0}, + {"LINUX_REBOOT_CMD_RESTART", Const, 0}, + {"LINUX_REBOOT_CMD_RESTART2", Const, 0}, + {"LINUX_REBOOT_CMD_SW_SUSPEND", Const, 0}, + {"LINUX_REBOOT_MAGIC1", Const, 0}, + {"LINUX_REBOOT_MAGIC2", Const, 0}, + {"LOCK_EX", Const, 0}, + {"LOCK_NB", Const, 0}, + {"LOCK_SH", Const, 0}, + {"LOCK_UN", Const, 0}, + {"LazyDLL", Type, 0}, + {"LazyDLL.Name", Field, 0}, + {"LazyProc", Type, 0}, + {"LazyProc.Name", Field, 0}, + {"Lchown", Func, 0}, + {"Linger", Type, 0}, + {"Linger.Linger", Field, 0}, + {"Linger.Onoff", Field, 0}, + {"Link", Func, 0}, + {"Listen", Func, 0}, + {"Listxattr", Func, 1}, + {"LoadCancelIoEx", Func, 1}, + {"LoadConnectEx", Func, 1}, + {"LoadCreateSymbolicLink", Func, 4}, + {"LoadDLL", Func, 0}, + {"LoadGetAddrInfo", Func, 1}, + {"LoadLibrary", Func, 0}, + {"LoadSetFileCompletionNotificationModes", Func, 2}, + {"LocalFree", Func, 0}, + {"Log2phys_t", Type, 0}, + {"Log2phys_t.Contigbytes", Field, 0}, + {"Log2phys_t.Devoffset", Field, 0}, + {"Log2phys_t.Flags", Field, 0}, + {"LookupAccountName", Func, 0}, + {"LookupAccountSid", Func, 0}, + {"LookupSID", Func, 0}, + {"LsfJump", Func, 0}, + {"LsfSocket", Func, 0}, + {"LsfStmt", Func, 0}, + {"Lstat", Func, 0}, + {"MADV_AUTOSYNC", Const, 1}, + {"MADV_CAN_REUSE", Const, 0}, + {"MADV_CORE", Const, 1}, + {"MADV_DOFORK", Const, 0}, + {"MADV_DONTFORK", Const, 0}, + {"MADV_DONTNEED", Const, 0}, + {"MADV_FREE", Const, 0}, + {"MADV_FREE_REUSABLE", Const, 0}, + {"MADV_FREE_REUSE", Const, 0}, + {"MADV_HUGEPAGE", Const, 0}, + {"MADV_HWPOISON", Const, 0}, + {"MADV_MERGEABLE", Const, 0}, + {"MADV_NOCORE", Const, 1}, + {"MADV_NOHUGEPAGE", Const, 0}, + {"MADV_NORMAL", Const, 0}, + {"MADV_NOSYNC", Const, 1}, + {"MADV_PROTECT", Const, 1}, + {"MADV_RANDOM", Const, 0}, + {"MADV_REMOVE", Const, 0}, + {"MADV_SEQUENTIAL", Const, 0}, + {"MADV_SPACEAVAIL", Const, 3}, + {"MADV_UNMERGEABLE", Const, 0}, + {"MADV_WILLNEED", Const, 0}, + {"MADV_ZERO_WIRED_PAGES", Const, 0}, + {"MAP_32BIT", Const, 0}, + {"MAP_ALIGNED_SUPER", Const, 3}, + {"MAP_ALIGNMENT_16MB", Const, 3}, + {"MAP_ALIGNMENT_1TB", Const, 3}, + {"MAP_ALIGNMENT_256TB", Const, 3}, + {"MAP_ALIGNMENT_4GB", Const, 3}, + {"MAP_ALIGNMENT_64KB", Const, 3}, + {"MAP_ALIGNMENT_64PB", Const, 3}, + {"MAP_ALIGNMENT_MASK", Const, 3}, + {"MAP_ALIGNMENT_SHIFT", Const, 3}, + {"MAP_ANON", Const, 0}, + {"MAP_ANONYMOUS", Const, 0}, + {"MAP_COPY", Const, 0}, + {"MAP_DENYWRITE", Const, 0}, + {"MAP_EXECUTABLE", Const, 0}, + {"MAP_FILE", Const, 0}, + {"MAP_FIXED", Const, 0}, + {"MAP_FLAGMASK", Const, 3}, + {"MAP_GROWSDOWN", Const, 0}, + {"MAP_HASSEMAPHORE", Const, 0}, + {"MAP_HUGETLB", Const, 0}, + {"MAP_INHERIT", Const, 3}, + {"MAP_INHERIT_COPY", Const, 3}, + {"MAP_INHERIT_DEFAULT", Const, 3}, + {"MAP_INHERIT_DONATE_COPY", Const, 3}, + {"MAP_INHERIT_NONE", Const, 3}, + {"MAP_INHERIT_SHARE", Const, 3}, + {"MAP_JIT", Const, 0}, + {"MAP_LOCKED", Const, 0}, + {"MAP_NOCACHE", Const, 0}, + {"MAP_NOCORE", Const, 1}, + {"MAP_NOEXTEND", Const, 0}, + {"MAP_NONBLOCK", Const, 0}, + {"MAP_NORESERVE", Const, 0}, + {"MAP_NOSYNC", Const, 1}, + {"MAP_POPULATE", Const, 0}, + {"MAP_PREFAULT_READ", Const, 1}, + {"MAP_PRIVATE", Const, 0}, + {"MAP_RENAME", Const, 0}, + {"MAP_RESERVED0080", Const, 0}, + {"MAP_RESERVED0100", Const, 1}, + {"MAP_SHARED", Const, 0}, + {"MAP_STACK", Const, 0}, + {"MAP_TRYFIXED", Const, 3}, + {"MAP_TYPE", Const, 0}, + {"MAP_WIRED", Const, 3}, + {"MAXIMUM_REPARSE_DATA_BUFFER_SIZE", Const, 4}, + {"MAXLEN_IFDESCR", Const, 0}, + {"MAXLEN_PHYSADDR", Const, 0}, + {"MAX_ADAPTER_ADDRESS_LENGTH", Const, 0}, + {"MAX_ADAPTER_DESCRIPTION_LENGTH", Const, 0}, + {"MAX_ADAPTER_NAME_LENGTH", Const, 0}, + {"MAX_COMPUTERNAME_LENGTH", Const, 0}, + {"MAX_INTERFACE_NAME_LEN", Const, 0}, + {"MAX_LONG_PATH", Const, 0}, + {"MAX_PATH", Const, 0}, + {"MAX_PROTOCOL_CHAIN", Const, 2}, + {"MCL_CURRENT", Const, 0}, + {"MCL_FUTURE", Const, 0}, + {"MNT_DETACH", Const, 0}, + {"MNT_EXPIRE", Const, 0}, + {"MNT_FORCE", Const, 0}, + {"MSG_BCAST", Const, 1}, + {"MSG_CMSG_CLOEXEC", Const, 0}, + {"MSG_COMPAT", Const, 0}, + {"MSG_CONFIRM", Const, 0}, + {"MSG_CONTROLMBUF", Const, 1}, + {"MSG_CTRUNC", Const, 0}, + {"MSG_DONTROUTE", Const, 0}, + {"MSG_DONTWAIT", Const, 0}, + {"MSG_EOF", Const, 0}, + {"MSG_EOR", Const, 0}, + {"MSG_ERRQUEUE", Const, 0}, + {"MSG_FASTOPEN", Const, 1}, + {"MSG_FIN", Const, 0}, + {"MSG_FLUSH", Const, 0}, + {"MSG_HAVEMORE", Const, 0}, + {"MSG_HOLD", Const, 0}, + {"MSG_IOVUSRSPACE", Const, 1}, + {"MSG_LENUSRSPACE", Const, 1}, + {"MSG_MCAST", Const, 1}, + {"MSG_MORE", Const, 0}, + {"MSG_NAMEMBUF", Const, 1}, + {"MSG_NBIO", Const, 0}, + {"MSG_NEEDSA", Const, 0}, + {"MSG_NOSIGNAL", Const, 0}, + {"MSG_NOTIFICATION", Const, 0}, + {"MSG_OOB", Const, 0}, + {"MSG_PEEK", Const, 0}, + {"MSG_PROXY", Const, 0}, + {"MSG_RCVMORE", Const, 0}, + {"MSG_RST", Const, 0}, + {"MSG_SEND", Const, 0}, + {"MSG_SYN", Const, 0}, + {"MSG_TRUNC", Const, 0}, + {"MSG_TRYHARD", Const, 0}, + {"MSG_USERFLAGS", Const, 1}, + {"MSG_WAITALL", Const, 0}, + {"MSG_WAITFORONE", Const, 0}, + {"MSG_WAITSTREAM", Const, 0}, + {"MS_ACTIVE", Const, 0}, + {"MS_ASYNC", Const, 0}, + {"MS_BIND", Const, 0}, + {"MS_DEACTIVATE", Const, 0}, + {"MS_DIRSYNC", Const, 0}, + {"MS_INVALIDATE", Const, 0}, + {"MS_I_VERSION", Const, 0}, + {"MS_KERNMOUNT", Const, 0}, + {"MS_KILLPAGES", Const, 0}, + {"MS_MANDLOCK", Const, 0}, + {"MS_MGC_MSK", Const, 0}, + {"MS_MGC_VAL", Const, 0}, + {"MS_MOVE", Const, 0}, + {"MS_NOATIME", Const, 0}, + {"MS_NODEV", Const, 0}, + {"MS_NODIRATIME", Const, 0}, + {"MS_NOEXEC", Const, 0}, + {"MS_NOSUID", Const, 0}, + {"MS_NOUSER", Const, 0}, + {"MS_POSIXACL", Const, 0}, + {"MS_PRIVATE", Const, 0}, + {"MS_RDONLY", Const, 0}, + {"MS_REC", Const, 0}, + {"MS_RELATIME", Const, 0}, + {"MS_REMOUNT", Const, 0}, + {"MS_RMT_MASK", Const, 0}, + {"MS_SHARED", Const, 0}, + {"MS_SILENT", Const, 0}, + {"MS_SLAVE", Const, 0}, + {"MS_STRICTATIME", Const, 0}, + {"MS_SYNC", Const, 0}, + {"MS_SYNCHRONOUS", Const, 0}, + {"MS_UNBINDABLE", Const, 0}, + {"Madvise", Func, 0}, + {"MapViewOfFile", Func, 0}, + {"MaxTokenInfoClass", Const, 0}, + {"Mclpool", Type, 2}, + {"Mclpool.Alive", Field, 2}, + {"Mclpool.Cwm", Field, 2}, + {"Mclpool.Grown", Field, 2}, + {"Mclpool.Hwm", Field, 2}, + {"Mclpool.Lwm", Field, 2}, + {"MibIfRow", Type, 0}, + {"MibIfRow.AdminStatus", Field, 0}, + {"MibIfRow.Descr", Field, 0}, + {"MibIfRow.DescrLen", Field, 0}, + {"MibIfRow.InDiscards", Field, 0}, + {"MibIfRow.InErrors", Field, 0}, + {"MibIfRow.InNUcastPkts", Field, 0}, + {"MibIfRow.InOctets", Field, 0}, + {"MibIfRow.InUcastPkts", Field, 0}, + {"MibIfRow.InUnknownProtos", Field, 0}, + {"MibIfRow.Index", Field, 0}, + {"MibIfRow.LastChange", Field, 0}, + {"MibIfRow.Mtu", Field, 0}, + {"MibIfRow.Name", Field, 0}, + {"MibIfRow.OperStatus", Field, 0}, + {"MibIfRow.OutDiscards", Field, 0}, + {"MibIfRow.OutErrors", Field, 0}, + {"MibIfRow.OutNUcastPkts", Field, 0}, + {"MibIfRow.OutOctets", Field, 0}, + {"MibIfRow.OutQLen", Field, 0}, + {"MibIfRow.OutUcastPkts", Field, 0}, + {"MibIfRow.PhysAddr", Field, 0}, + {"MibIfRow.PhysAddrLen", Field, 0}, + {"MibIfRow.Speed", Field, 0}, + {"MibIfRow.Type", Field, 0}, + {"Mkdir", Func, 0}, + {"Mkdirat", Func, 0}, + {"Mkfifo", Func, 0}, + {"Mknod", Func, 0}, + {"Mknodat", Func, 0}, + {"Mlock", Func, 0}, + {"Mlockall", Func, 0}, + {"Mmap", Func, 0}, + {"Mount", Func, 0}, + {"MoveFile", Func, 0}, + {"Mprotect", Func, 0}, + {"Msghdr", Type, 0}, + {"Msghdr.Control", Field, 0}, + {"Msghdr.Controllen", Field, 0}, + {"Msghdr.Flags", Field, 0}, + {"Msghdr.Iov", Field, 0}, + {"Msghdr.Iovlen", Field, 0}, + {"Msghdr.Name", Field, 0}, + {"Msghdr.Namelen", Field, 0}, + {"Msghdr.Pad_cgo_0", Field, 0}, + {"Msghdr.Pad_cgo_1", Field, 0}, + {"Munlock", Func, 0}, + {"Munlockall", Func, 0}, + {"Munmap", Func, 0}, + {"MustLoadDLL", Func, 0}, + {"NAME_MAX", Const, 0}, + {"NETLINK_ADD_MEMBERSHIP", Const, 0}, + {"NETLINK_AUDIT", Const, 0}, + {"NETLINK_BROADCAST_ERROR", Const, 0}, + {"NETLINK_CONNECTOR", Const, 0}, + {"NETLINK_DNRTMSG", Const, 0}, + {"NETLINK_DROP_MEMBERSHIP", Const, 0}, + {"NETLINK_ECRYPTFS", Const, 0}, + {"NETLINK_FIB_LOOKUP", Const, 0}, + {"NETLINK_FIREWALL", Const, 0}, + {"NETLINK_GENERIC", Const, 0}, + {"NETLINK_INET_DIAG", Const, 0}, + {"NETLINK_IP6_FW", Const, 0}, + {"NETLINK_ISCSI", Const, 0}, + {"NETLINK_KOBJECT_UEVENT", Const, 0}, + {"NETLINK_NETFILTER", Const, 0}, + {"NETLINK_NFLOG", Const, 0}, + {"NETLINK_NO_ENOBUFS", Const, 0}, + {"NETLINK_PKTINFO", Const, 0}, + {"NETLINK_RDMA", Const, 0}, + {"NETLINK_ROUTE", Const, 0}, + {"NETLINK_SCSITRANSPORT", Const, 0}, + {"NETLINK_SELINUX", Const, 0}, + {"NETLINK_UNUSED", Const, 0}, + {"NETLINK_USERSOCK", Const, 0}, + {"NETLINK_XFRM", Const, 0}, + {"NET_RT_DUMP", Const, 0}, + {"NET_RT_DUMP2", Const, 0}, + {"NET_RT_FLAGS", Const, 0}, + {"NET_RT_IFLIST", Const, 0}, + {"NET_RT_IFLIST2", Const, 0}, + {"NET_RT_IFLISTL", Const, 1}, + {"NET_RT_IFMALIST", Const, 0}, + {"NET_RT_MAXID", Const, 0}, + {"NET_RT_OIFLIST", Const, 1}, + {"NET_RT_OOIFLIST", Const, 1}, + {"NET_RT_STAT", Const, 0}, + {"NET_RT_STATS", Const, 1}, + {"NET_RT_TABLE", Const, 1}, + {"NET_RT_TRASH", Const, 0}, + {"NLA_ALIGNTO", Const, 0}, + {"NLA_F_NESTED", Const, 0}, + {"NLA_F_NET_BYTEORDER", Const, 0}, + {"NLA_HDRLEN", Const, 0}, + {"NLMSG_ALIGNTO", Const, 0}, + {"NLMSG_DONE", Const, 0}, + {"NLMSG_ERROR", Const, 0}, + {"NLMSG_HDRLEN", Const, 0}, + {"NLMSG_MIN_TYPE", Const, 0}, + {"NLMSG_NOOP", Const, 0}, + {"NLMSG_OVERRUN", Const, 0}, + {"NLM_F_ACK", Const, 0}, + {"NLM_F_APPEND", Const, 0}, + {"NLM_F_ATOMIC", Const, 0}, + {"NLM_F_CREATE", Const, 0}, + {"NLM_F_DUMP", Const, 0}, + {"NLM_F_ECHO", Const, 0}, + {"NLM_F_EXCL", Const, 0}, + {"NLM_F_MATCH", Const, 0}, + {"NLM_F_MULTI", Const, 0}, + {"NLM_F_REPLACE", Const, 0}, + {"NLM_F_REQUEST", Const, 0}, + {"NLM_F_ROOT", Const, 0}, + {"NOFLSH", Const, 0}, + {"NOTE_ABSOLUTE", Const, 0}, + {"NOTE_ATTRIB", Const, 0}, + {"NOTE_BACKGROUND", Const, 16}, + {"NOTE_CHILD", Const, 0}, + {"NOTE_CRITICAL", Const, 16}, + {"NOTE_DELETE", Const, 0}, + {"NOTE_EOF", Const, 1}, + {"NOTE_EXEC", Const, 0}, + {"NOTE_EXIT", Const, 0}, + {"NOTE_EXITSTATUS", Const, 0}, + {"NOTE_EXIT_CSERROR", Const, 16}, + {"NOTE_EXIT_DECRYPTFAIL", Const, 16}, + {"NOTE_EXIT_DETAIL", Const, 16}, + {"NOTE_EXIT_DETAIL_MASK", Const, 16}, + {"NOTE_EXIT_MEMORY", Const, 16}, + {"NOTE_EXIT_REPARENTED", Const, 16}, + {"NOTE_EXTEND", Const, 0}, + {"NOTE_FFAND", Const, 0}, + {"NOTE_FFCOPY", Const, 0}, + {"NOTE_FFCTRLMASK", Const, 0}, + {"NOTE_FFLAGSMASK", Const, 0}, + {"NOTE_FFNOP", Const, 0}, + {"NOTE_FFOR", Const, 0}, + {"NOTE_FORK", Const, 0}, + {"NOTE_LEEWAY", Const, 16}, + {"NOTE_LINK", Const, 0}, + {"NOTE_LOWAT", Const, 0}, + {"NOTE_NONE", Const, 0}, + {"NOTE_NSECONDS", Const, 0}, + {"NOTE_PCTRLMASK", Const, 0}, + {"NOTE_PDATAMASK", Const, 0}, + {"NOTE_REAP", Const, 0}, + {"NOTE_RENAME", Const, 0}, + {"NOTE_RESOURCEEND", Const, 0}, + {"NOTE_REVOKE", Const, 0}, + {"NOTE_SECONDS", Const, 0}, + {"NOTE_SIGNAL", Const, 0}, + {"NOTE_TRACK", Const, 0}, + {"NOTE_TRACKERR", Const, 0}, + {"NOTE_TRIGGER", Const, 0}, + {"NOTE_TRUNCATE", Const, 1}, + {"NOTE_USECONDS", Const, 0}, + {"NOTE_VM_ERROR", Const, 0}, + {"NOTE_VM_PRESSURE", Const, 0}, + {"NOTE_VM_PRESSURE_SUDDEN_TERMINATE", Const, 0}, + {"NOTE_VM_PRESSURE_TERMINATE", Const, 0}, + {"NOTE_WRITE", Const, 0}, + {"NameCanonical", Const, 0}, + {"NameCanonicalEx", Const, 0}, + {"NameDisplay", Const, 0}, + {"NameDnsDomain", Const, 0}, + {"NameFullyQualifiedDN", Const, 0}, + {"NameSamCompatible", Const, 0}, + {"NameServicePrincipal", Const, 0}, + {"NameUniqueId", Const, 0}, + {"NameUnknown", Const, 0}, + {"NameUserPrincipal", Const, 0}, + {"Nanosleep", Func, 0}, + {"NetApiBufferFree", Func, 0}, + {"NetGetJoinInformation", Func, 2}, + {"NetSetupDomainName", Const, 2}, + {"NetSetupUnjoined", Const, 2}, + {"NetSetupUnknownStatus", Const, 2}, + {"NetSetupWorkgroupName", Const, 2}, + {"NetUserGetInfo", Func, 0}, + {"NetlinkMessage", Type, 0}, + {"NetlinkMessage.Data", Field, 0}, + {"NetlinkMessage.Header", Field, 0}, + {"NetlinkRIB", Func, 0}, + {"NetlinkRouteAttr", Type, 0}, + {"NetlinkRouteAttr.Attr", Field, 0}, + {"NetlinkRouteAttr.Value", Field, 0}, + {"NetlinkRouteRequest", Type, 0}, + {"NetlinkRouteRequest.Data", Field, 0}, + {"NetlinkRouteRequest.Header", Field, 0}, + {"NewCallback", Func, 0}, + {"NewCallbackCDecl", Func, 3}, + {"NewLazyDLL", Func, 0}, + {"NlAttr", Type, 0}, + {"NlAttr.Len", Field, 0}, + {"NlAttr.Type", Field, 0}, + {"NlMsgerr", Type, 0}, + {"NlMsgerr.Error", Field, 0}, + {"NlMsgerr.Msg", Field, 0}, + {"NlMsghdr", Type, 0}, + {"NlMsghdr.Flags", Field, 0}, + {"NlMsghdr.Len", Field, 0}, + {"NlMsghdr.Pid", Field, 0}, + {"NlMsghdr.Seq", Field, 0}, + {"NlMsghdr.Type", Field, 0}, + {"NsecToFiletime", Func, 0}, + {"NsecToTimespec", Func, 0}, + {"NsecToTimeval", Func, 0}, + {"Ntohs", Func, 0}, + {"OCRNL", Const, 0}, + {"OFDEL", Const, 0}, + {"OFILL", Const, 0}, + {"OFIOGETBMAP", Const, 1}, + {"OID_PKIX_KP_SERVER_AUTH", Var, 0}, + {"OID_SERVER_GATED_CRYPTO", Var, 0}, + {"OID_SGC_NETSCAPE", Var, 0}, + {"OLCUC", Const, 0}, + {"ONLCR", Const, 0}, + {"ONLRET", Const, 0}, + {"ONOCR", Const, 0}, + {"ONOEOT", Const, 1}, + {"OPEN_ALWAYS", Const, 0}, + {"OPEN_EXISTING", Const, 0}, + {"OPOST", Const, 0}, + {"O_ACCMODE", Const, 0}, + {"O_ALERT", Const, 0}, + {"O_ALT_IO", Const, 1}, + {"O_APPEND", Const, 0}, + {"O_ASYNC", Const, 0}, + {"O_CLOEXEC", Const, 0}, + {"O_CREAT", Const, 0}, + {"O_DIRECT", Const, 0}, + {"O_DIRECTORY", Const, 0}, + {"O_DP_GETRAWENCRYPTED", Const, 16}, + {"O_DSYNC", Const, 0}, + {"O_EVTONLY", Const, 0}, + {"O_EXCL", Const, 0}, + {"O_EXEC", Const, 0}, + {"O_EXLOCK", Const, 0}, + {"O_FSYNC", Const, 0}, + {"O_LARGEFILE", Const, 0}, + {"O_NDELAY", Const, 0}, + {"O_NOATIME", Const, 0}, + {"O_NOCTTY", Const, 0}, + {"O_NOFOLLOW", Const, 0}, + {"O_NONBLOCK", Const, 0}, + {"O_NOSIGPIPE", Const, 1}, + {"O_POPUP", Const, 0}, + {"O_RDONLY", Const, 0}, + {"O_RDWR", Const, 0}, + {"O_RSYNC", Const, 0}, + {"O_SHLOCK", Const, 0}, + {"O_SYMLINK", Const, 0}, + {"O_SYNC", Const, 0}, + {"O_TRUNC", Const, 0}, + {"O_TTY_INIT", Const, 0}, + {"O_WRONLY", Const, 0}, + {"Open", Func, 0}, + {"OpenCurrentProcessToken", Func, 0}, + {"OpenProcess", Func, 0}, + {"OpenProcessToken", Func, 0}, + {"Openat", Func, 0}, + {"Overlapped", Type, 0}, + {"Overlapped.HEvent", Field, 0}, + {"Overlapped.Internal", Field, 0}, + {"Overlapped.InternalHigh", Field, 0}, + {"Overlapped.Offset", Field, 0}, + {"Overlapped.OffsetHigh", Field, 0}, + {"PACKET_ADD_MEMBERSHIP", Const, 0}, + {"PACKET_BROADCAST", Const, 0}, + {"PACKET_DROP_MEMBERSHIP", Const, 0}, + {"PACKET_FASTROUTE", Const, 0}, + {"PACKET_HOST", Const, 0}, + {"PACKET_LOOPBACK", Const, 0}, + {"PACKET_MR_ALLMULTI", Const, 0}, + {"PACKET_MR_MULTICAST", Const, 0}, + {"PACKET_MR_PROMISC", Const, 0}, + {"PACKET_MULTICAST", Const, 0}, + {"PACKET_OTHERHOST", Const, 0}, + {"PACKET_OUTGOING", Const, 0}, + {"PACKET_RECV_OUTPUT", Const, 0}, + {"PACKET_RX_RING", Const, 0}, + {"PACKET_STATISTICS", Const, 0}, + {"PAGE_EXECUTE_READ", Const, 0}, + {"PAGE_EXECUTE_READWRITE", Const, 0}, + {"PAGE_EXECUTE_WRITECOPY", Const, 0}, + {"PAGE_READONLY", Const, 0}, + {"PAGE_READWRITE", Const, 0}, + {"PAGE_WRITECOPY", Const, 0}, + {"PARENB", Const, 0}, + {"PARMRK", Const, 0}, + {"PARODD", Const, 0}, + {"PENDIN", Const, 0}, + {"PFL_HIDDEN", Const, 2}, + {"PFL_MATCHES_PROTOCOL_ZERO", Const, 2}, + {"PFL_MULTIPLE_PROTO_ENTRIES", Const, 2}, + {"PFL_NETWORKDIRECT_PROVIDER", Const, 2}, + {"PFL_RECOMMENDED_PROTO_ENTRY", Const, 2}, + {"PF_FLUSH", Const, 1}, + {"PKCS_7_ASN_ENCODING", Const, 0}, + {"PMC5_PIPELINE_FLUSH", Const, 1}, + {"PRIO_PGRP", Const, 2}, + {"PRIO_PROCESS", Const, 2}, + {"PRIO_USER", Const, 2}, + {"PRI_IOFLUSH", Const, 1}, + {"PROCESS_QUERY_INFORMATION", Const, 0}, + {"PROCESS_TERMINATE", Const, 2}, + {"PROT_EXEC", Const, 0}, + {"PROT_GROWSDOWN", Const, 0}, + {"PROT_GROWSUP", Const, 0}, + {"PROT_NONE", Const, 0}, + {"PROT_READ", Const, 0}, + {"PROT_WRITE", Const, 0}, + {"PROV_DH_SCHANNEL", Const, 0}, + {"PROV_DSS", Const, 0}, + {"PROV_DSS_DH", Const, 0}, + {"PROV_EC_ECDSA_FULL", Const, 0}, + {"PROV_EC_ECDSA_SIG", Const, 0}, + {"PROV_EC_ECNRA_FULL", Const, 0}, + {"PROV_EC_ECNRA_SIG", Const, 0}, + {"PROV_FORTEZZA", Const, 0}, + {"PROV_INTEL_SEC", Const, 0}, + {"PROV_MS_EXCHANGE", Const, 0}, + {"PROV_REPLACE_OWF", Const, 0}, + {"PROV_RNG", Const, 0}, + {"PROV_RSA_AES", Const, 0}, + {"PROV_RSA_FULL", Const, 0}, + {"PROV_RSA_SCHANNEL", Const, 0}, + {"PROV_RSA_SIG", Const, 0}, + {"PROV_SPYRUS_LYNKS", Const, 0}, + {"PROV_SSL", Const, 0}, + {"PR_CAPBSET_DROP", Const, 0}, + {"PR_CAPBSET_READ", Const, 0}, + {"PR_CLEAR_SECCOMP_FILTER", Const, 0}, + {"PR_ENDIAN_BIG", Const, 0}, + {"PR_ENDIAN_LITTLE", Const, 0}, + {"PR_ENDIAN_PPC_LITTLE", Const, 0}, + {"PR_FPEMU_NOPRINT", Const, 0}, + {"PR_FPEMU_SIGFPE", Const, 0}, + {"PR_FP_EXC_ASYNC", Const, 0}, + {"PR_FP_EXC_DISABLED", Const, 0}, + {"PR_FP_EXC_DIV", Const, 0}, + {"PR_FP_EXC_INV", Const, 0}, + {"PR_FP_EXC_NONRECOV", Const, 0}, + {"PR_FP_EXC_OVF", Const, 0}, + {"PR_FP_EXC_PRECISE", Const, 0}, + {"PR_FP_EXC_RES", Const, 0}, + {"PR_FP_EXC_SW_ENABLE", Const, 0}, + {"PR_FP_EXC_UND", Const, 0}, + {"PR_GET_DUMPABLE", Const, 0}, + {"PR_GET_ENDIAN", Const, 0}, + {"PR_GET_FPEMU", Const, 0}, + {"PR_GET_FPEXC", Const, 0}, + {"PR_GET_KEEPCAPS", Const, 0}, + {"PR_GET_NAME", Const, 0}, + {"PR_GET_PDEATHSIG", Const, 0}, + {"PR_GET_SECCOMP", Const, 0}, + {"PR_GET_SECCOMP_FILTER", Const, 0}, + {"PR_GET_SECUREBITS", Const, 0}, + {"PR_GET_TIMERSLACK", Const, 0}, + {"PR_GET_TIMING", Const, 0}, + {"PR_GET_TSC", Const, 0}, + {"PR_GET_UNALIGN", Const, 0}, + {"PR_MCE_KILL", Const, 0}, + {"PR_MCE_KILL_CLEAR", Const, 0}, + {"PR_MCE_KILL_DEFAULT", Const, 0}, + {"PR_MCE_KILL_EARLY", Const, 0}, + {"PR_MCE_KILL_GET", Const, 0}, + {"PR_MCE_KILL_LATE", Const, 0}, + {"PR_MCE_KILL_SET", Const, 0}, + {"PR_SECCOMP_FILTER_EVENT", Const, 0}, + {"PR_SECCOMP_FILTER_SYSCALL", Const, 0}, + {"PR_SET_DUMPABLE", Const, 0}, + {"PR_SET_ENDIAN", Const, 0}, + {"PR_SET_FPEMU", Const, 0}, + {"PR_SET_FPEXC", Const, 0}, + {"PR_SET_KEEPCAPS", Const, 0}, + {"PR_SET_NAME", Const, 0}, + {"PR_SET_PDEATHSIG", Const, 0}, + {"PR_SET_PTRACER", Const, 0}, + {"PR_SET_SECCOMP", Const, 0}, + {"PR_SET_SECCOMP_FILTER", Const, 0}, + {"PR_SET_SECUREBITS", Const, 0}, + {"PR_SET_TIMERSLACK", Const, 0}, + {"PR_SET_TIMING", Const, 0}, + {"PR_SET_TSC", Const, 0}, + {"PR_SET_UNALIGN", Const, 0}, + {"PR_TASK_PERF_EVENTS_DISABLE", Const, 0}, + {"PR_TASK_PERF_EVENTS_ENABLE", Const, 0}, + {"PR_TIMING_STATISTICAL", Const, 0}, + {"PR_TIMING_TIMESTAMP", Const, 0}, + {"PR_TSC_ENABLE", Const, 0}, + {"PR_TSC_SIGSEGV", Const, 0}, + {"PR_UNALIGN_NOPRINT", Const, 0}, + {"PR_UNALIGN_SIGBUS", Const, 0}, + {"PTRACE_ARCH_PRCTL", Const, 0}, + {"PTRACE_ATTACH", Const, 0}, + {"PTRACE_CONT", Const, 0}, + {"PTRACE_DETACH", Const, 0}, + {"PTRACE_EVENT_CLONE", Const, 0}, + {"PTRACE_EVENT_EXEC", Const, 0}, + {"PTRACE_EVENT_EXIT", Const, 0}, + {"PTRACE_EVENT_FORK", Const, 0}, + {"PTRACE_EVENT_VFORK", Const, 0}, + {"PTRACE_EVENT_VFORK_DONE", Const, 0}, + {"PTRACE_GETCRUNCHREGS", Const, 0}, + {"PTRACE_GETEVENTMSG", Const, 0}, + {"PTRACE_GETFPREGS", Const, 0}, + {"PTRACE_GETFPXREGS", Const, 0}, + {"PTRACE_GETHBPREGS", Const, 0}, + {"PTRACE_GETREGS", Const, 0}, + {"PTRACE_GETREGSET", Const, 0}, + {"PTRACE_GETSIGINFO", Const, 0}, + {"PTRACE_GETVFPREGS", Const, 0}, + {"PTRACE_GETWMMXREGS", Const, 0}, + {"PTRACE_GET_THREAD_AREA", Const, 0}, + {"PTRACE_KILL", Const, 0}, + {"PTRACE_OLDSETOPTIONS", Const, 0}, + {"PTRACE_O_MASK", Const, 0}, + {"PTRACE_O_TRACECLONE", Const, 0}, + {"PTRACE_O_TRACEEXEC", Const, 0}, + {"PTRACE_O_TRACEEXIT", Const, 0}, + {"PTRACE_O_TRACEFORK", Const, 0}, + {"PTRACE_O_TRACESYSGOOD", Const, 0}, + {"PTRACE_O_TRACEVFORK", Const, 0}, + {"PTRACE_O_TRACEVFORKDONE", Const, 0}, + {"PTRACE_PEEKDATA", Const, 0}, + {"PTRACE_PEEKTEXT", Const, 0}, + {"PTRACE_PEEKUSR", Const, 0}, + {"PTRACE_POKEDATA", Const, 0}, + {"PTRACE_POKETEXT", Const, 0}, + {"PTRACE_POKEUSR", Const, 0}, + {"PTRACE_SETCRUNCHREGS", Const, 0}, + {"PTRACE_SETFPREGS", Const, 0}, + {"PTRACE_SETFPXREGS", Const, 0}, + {"PTRACE_SETHBPREGS", Const, 0}, + {"PTRACE_SETOPTIONS", Const, 0}, + {"PTRACE_SETREGS", Const, 0}, + {"PTRACE_SETREGSET", Const, 0}, + {"PTRACE_SETSIGINFO", Const, 0}, + {"PTRACE_SETVFPREGS", Const, 0}, + {"PTRACE_SETWMMXREGS", Const, 0}, + {"PTRACE_SET_SYSCALL", Const, 0}, + {"PTRACE_SET_THREAD_AREA", Const, 0}, + {"PTRACE_SINGLEBLOCK", Const, 0}, + {"PTRACE_SINGLESTEP", Const, 0}, + {"PTRACE_SYSCALL", Const, 0}, + {"PTRACE_SYSEMU", Const, 0}, + {"PTRACE_SYSEMU_SINGLESTEP", Const, 0}, + {"PTRACE_TRACEME", Const, 0}, + {"PT_ATTACH", Const, 0}, + {"PT_ATTACHEXC", Const, 0}, + {"PT_CONTINUE", Const, 0}, + {"PT_DATA_ADDR", Const, 0}, + {"PT_DENY_ATTACH", Const, 0}, + {"PT_DETACH", Const, 0}, + {"PT_FIRSTMACH", Const, 0}, + {"PT_FORCEQUOTA", Const, 0}, + {"PT_KILL", Const, 0}, + {"PT_MASK", Const, 1}, + {"PT_READ_D", Const, 0}, + {"PT_READ_I", Const, 0}, + {"PT_READ_U", Const, 0}, + {"PT_SIGEXC", Const, 0}, + {"PT_STEP", Const, 0}, + {"PT_TEXT_ADDR", Const, 0}, + {"PT_TEXT_END_ADDR", Const, 0}, + {"PT_THUPDATE", Const, 0}, + {"PT_TRACE_ME", Const, 0}, + {"PT_WRITE_D", Const, 0}, + {"PT_WRITE_I", Const, 0}, + {"PT_WRITE_U", Const, 0}, + {"ParseDirent", Func, 0}, + {"ParseNetlinkMessage", Func, 0}, + {"ParseNetlinkRouteAttr", Func, 0}, + {"ParseRoutingMessage", Func, 0}, + {"ParseRoutingSockaddr", Func, 0}, + {"ParseSocketControlMessage", Func, 0}, + {"ParseUnixCredentials", Func, 0}, + {"ParseUnixRights", Func, 0}, + {"PathMax", Const, 0}, + {"Pathconf", Func, 0}, + {"Pause", Func, 0}, + {"Pipe", Func, 0}, + {"Pipe2", Func, 1}, + {"PivotRoot", Func, 0}, + {"Pointer", Type, 11}, + {"PostQueuedCompletionStatus", Func, 0}, + {"Pread", Func, 0}, + {"Proc", Type, 0}, + {"Proc.Dll", Field, 0}, + {"Proc.Name", Field, 0}, + {"ProcAttr", Type, 0}, + {"ProcAttr.Dir", Field, 0}, + {"ProcAttr.Env", Field, 0}, + {"ProcAttr.Files", Field, 0}, + {"ProcAttr.Sys", Field, 0}, + {"Process32First", Func, 4}, + {"Process32Next", Func, 4}, + {"ProcessEntry32", Type, 4}, + {"ProcessEntry32.DefaultHeapID", Field, 4}, + {"ProcessEntry32.ExeFile", Field, 4}, + {"ProcessEntry32.Flags", Field, 4}, + {"ProcessEntry32.ModuleID", Field, 4}, + {"ProcessEntry32.ParentProcessID", Field, 4}, + {"ProcessEntry32.PriClassBase", Field, 4}, + {"ProcessEntry32.ProcessID", Field, 4}, + {"ProcessEntry32.Size", Field, 4}, + {"ProcessEntry32.Threads", Field, 4}, + {"ProcessEntry32.Usage", Field, 4}, + {"ProcessInformation", Type, 0}, + {"ProcessInformation.Process", Field, 0}, + {"ProcessInformation.ProcessId", Field, 0}, + {"ProcessInformation.Thread", Field, 0}, + {"ProcessInformation.ThreadId", Field, 0}, + {"Protoent", Type, 0}, + {"Protoent.Aliases", Field, 0}, + {"Protoent.Name", Field, 0}, + {"Protoent.Proto", Field, 0}, + {"PtraceAttach", Func, 0}, + {"PtraceCont", Func, 0}, + {"PtraceDetach", Func, 0}, + {"PtraceGetEventMsg", Func, 0}, + {"PtraceGetRegs", Func, 0}, + {"PtracePeekData", Func, 0}, + {"PtracePeekText", Func, 0}, + {"PtracePokeData", Func, 0}, + {"PtracePokeText", Func, 0}, + {"PtraceRegs", Type, 0}, + {"PtraceRegs.Cs", Field, 0}, + {"PtraceRegs.Ds", Field, 0}, + {"PtraceRegs.Eax", Field, 0}, + {"PtraceRegs.Ebp", Field, 0}, + {"PtraceRegs.Ebx", Field, 0}, + {"PtraceRegs.Ecx", Field, 0}, + {"PtraceRegs.Edi", Field, 0}, + {"PtraceRegs.Edx", Field, 0}, + {"PtraceRegs.Eflags", Field, 0}, + {"PtraceRegs.Eip", Field, 0}, + {"PtraceRegs.Es", Field, 0}, + {"PtraceRegs.Esi", Field, 0}, + {"PtraceRegs.Esp", Field, 0}, + {"PtraceRegs.Fs", Field, 0}, + {"PtraceRegs.Fs_base", Field, 0}, + {"PtraceRegs.Gs", Field, 0}, + {"PtraceRegs.Gs_base", Field, 0}, + {"PtraceRegs.Orig_eax", Field, 0}, + {"PtraceRegs.Orig_rax", Field, 0}, + {"PtraceRegs.R10", Field, 0}, + {"PtraceRegs.R11", Field, 0}, + {"PtraceRegs.R12", Field, 0}, + {"PtraceRegs.R13", Field, 0}, + {"PtraceRegs.R14", Field, 0}, + {"PtraceRegs.R15", Field, 0}, + {"PtraceRegs.R8", Field, 0}, + {"PtraceRegs.R9", Field, 0}, + {"PtraceRegs.Rax", Field, 0}, + {"PtraceRegs.Rbp", Field, 0}, + {"PtraceRegs.Rbx", Field, 0}, + {"PtraceRegs.Rcx", Field, 0}, + {"PtraceRegs.Rdi", Field, 0}, + {"PtraceRegs.Rdx", Field, 0}, + {"PtraceRegs.Rip", Field, 0}, + {"PtraceRegs.Rsi", Field, 0}, + {"PtraceRegs.Rsp", Field, 0}, + {"PtraceRegs.Ss", Field, 0}, + {"PtraceRegs.Uregs", Field, 0}, + {"PtraceRegs.Xcs", Field, 0}, + {"PtraceRegs.Xds", Field, 0}, + {"PtraceRegs.Xes", Field, 0}, + {"PtraceRegs.Xfs", Field, 0}, + {"PtraceRegs.Xgs", Field, 0}, + {"PtraceRegs.Xss", Field, 0}, + {"PtraceSetOptions", Func, 0}, + {"PtraceSetRegs", Func, 0}, + {"PtraceSingleStep", Func, 0}, + {"PtraceSyscall", Func, 1}, + {"Pwrite", Func, 0}, + {"REG_BINARY", Const, 0}, + {"REG_DWORD", Const, 0}, + {"REG_DWORD_BIG_ENDIAN", Const, 0}, + {"REG_DWORD_LITTLE_ENDIAN", Const, 0}, + {"REG_EXPAND_SZ", Const, 0}, + {"REG_FULL_RESOURCE_DESCRIPTOR", Const, 0}, + {"REG_LINK", Const, 0}, + {"REG_MULTI_SZ", Const, 0}, + {"REG_NONE", Const, 0}, + {"REG_QWORD", Const, 0}, + {"REG_QWORD_LITTLE_ENDIAN", Const, 0}, + {"REG_RESOURCE_LIST", Const, 0}, + {"REG_RESOURCE_REQUIREMENTS_LIST", Const, 0}, + {"REG_SZ", Const, 0}, + {"RLIMIT_AS", Const, 0}, + {"RLIMIT_CORE", Const, 0}, + {"RLIMIT_CPU", Const, 0}, + {"RLIMIT_CPU_USAGE_MONITOR", Const, 16}, + {"RLIMIT_DATA", Const, 0}, + {"RLIMIT_FSIZE", Const, 0}, + {"RLIMIT_NOFILE", Const, 0}, + {"RLIMIT_STACK", Const, 0}, + {"RLIM_INFINITY", Const, 0}, + {"RTAX_ADVMSS", Const, 0}, + {"RTAX_AUTHOR", Const, 0}, + {"RTAX_BRD", Const, 0}, + {"RTAX_CWND", Const, 0}, + {"RTAX_DST", Const, 0}, + {"RTAX_FEATURES", Const, 0}, + {"RTAX_FEATURE_ALLFRAG", Const, 0}, + {"RTAX_FEATURE_ECN", Const, 0}, + {"RTAX_FEATURE_SACK", Const, 0}, + {"RTAX_FEATURE_TIMESTAMP", Const, 0}, + {"RTAX_GATEWAY", Const, 0}, + {"RTAX_GENMASK", Const, 0}, + {"RTAX_HOPLIMIT", Const, 0}, + {"RTAX_IFA", Const, 0}, + {"RTAX_IFP", Const, 0}, + {"RTAX_INITCWND", Const, 0}, + {"RTAX_INITRWND", Const, 0}, + {"RTAX_LABEL", Const, 1}, + {"RTAX_LOCK", Const, 0}, + {"RTAX_MAX", Const, 0}, + {"RTAX_MTU", Const, 0}, + {"RTAX_NETMASK", Const, 0}, + {"RTAX_REORDERING", Const, 0}, + {"RTAX_RTO_MIN", Const, 0}, + {"RTAX_RTT", Const, 0}, + {"RTAX_RTTVAR", Const, 0}, + {"RTAX_SRC", Const, 1}, + {"RTAX_SRCMASK", Const, 1}, + {"RTAX_SSTHRESH", Const, 0}, + {"RTAX_TAG", Const, 1}, + {"RTAX_UNSPEC", Const, 0}, + {"RTAX_WINDOW", Const, 0}, + {"RTA_ALIGNTO", Const, 0}, + {"RTA_AUTHOR", Const, 0}, + {"RTA_BRD", Const, 0}, + {"RTA_CACHEINFO", Const, 0}, + {"RTA_DST", Const, 0}, + {"RTA_FLOW", Const, 0}, + {"RTA_GATEWAY", Const, 0}, + {"RTA_GENMASK", Const, 0}, + {"RTA_IFA", Const, 0}, + {"RTA_IFP", Const, 0}, + {"RTA_IIF", Const, 0}, + {"RTA_LABEL", Const, 1}, + {"RTA_MAX", Const, 0}, + {"RTA_METRICS", Const, 0}, + {"RTA_MULTIPATH", Const, 0}, + {"RTA_NETMASK", Const, 0}, + {"RTA_OIF", Const, 0}, + {"RTA_PREFSRC", Const, 0}, + {"RTA_PRIORITY", Const, 0}, + {"RTA_SRC", Const, 0}, + {"RTA_SRCMASK", Const, 1}, + {"RTA_TABLE", Const, 0}, + {"RTA_TAG", Const, 1}, + {"RTA_UNSPEC", Const, 0}, + {"RTCF_DIRECTSRC", Const, 0}, + {"RTCF_DOREDIRECT", Const, 0}, + {"RTCF_LOG", Const, 0}, + {"RTCF_MASQ", Const, 0}, + {"RTCF_NAT", Const, 0}, + {"RTCF_VALVE", Const, 0}, + {"RTF_ADDRCLASSMASK", Const, 0}, + {"RTF_ADDRCONF", Const, 0}, + {"RTF_ALLONLINK", Const, 0}, + {"RTF_ANNOUNCE", Const, 1}, + {"RTF_BLACKHOLE", Const, 0}, + {"RTF_BROADCAST", Const, 0}, + {"RTF_CACHE", Const, 0}, + {"RTF_CLONED", Const, 1}, + {"RTF_CLONING", Const, 0}, + {"RTF_CONDEMNED", Const, 0}, + {"RTF_DEFAULT", Const, 0}, + {"RTF_DELCLONE", Const, 0}, + {"RTF_DONE", Const, 0}, + {"RTF_DYNAMIC", Const, 0}, + {"RTF_FLOW", Const, 0}, + {"RTF_FMASK", Const, 0}, + {"RTF_GATEWAY", Const, 0}, + {"RTF_GWFLAG_COMPAT", Const, 3}, + {"RTF_HOST", Const, 0}, + {"RTF_IFREF", Const, 0}, + {"RTF_IFSCOPE", Const, 0}, + {"RTF_INTERFACE", Const, 0}, + {"RTF_IRTT", Const, 0}, + {"RTF_LINKRT", Const, 0}, + {"RTF_LLDATA", Const, 0}, + {"RTF_LLINFO", Const, 0}, + {"RTF_LOCAL", Const, 0}, + {"RTF_MASK", Const, 1}, + {"RTF_MODIFIED", Const, 0}, + {"RTF_MPATH", Const, 1}, + {"RTF_MPLS", Const, 1}, + {"RTF_MSS", Const, 0}, + {"RTF_MTU", Const, 0}, + {"RTF_MULTICAST", Const, 0}, + {"RTF_NAT", Const, 0}, + {"RTF_NOFORWARD", Const, 0}, + {"RTF_NONEXTHOP", Const, 0}, + {"RTF_NOPMTUDISC", Const, 0}, + {"RTF_PERMANENT_ARP", Const, 1}, + {"RTF_PINNED", Const, 0}, + {"RTF_POLICY", Const, 0}, + {"RTF_PRCLONING", Const, 0}, + {"RTF_PROTO1", Const, 0}, + {"RTF_PROTO2", Const, 0}, + {"RTF_PROTO3", Const, 0}, + {"RTF_PROXY", Const, 16}, + {"RTF_REINSTATE", Const, 0}, + {"RTF_REJECT", Const, 0}, + {"RTF_RNH_LOCKED", Const, 0}, + {"RTF_ROUTER", Const, 16}, + {"RTF_SOURCE", Const, 1}, + {"RTF_SRC", Const, 1}, + {"RTF_STATIC", Const, 0}, + {"RTF_STICKY", Const, 0}, + {"RTF_THROW", Const, 0}, + {"RTF_TUNNEL", Const, 1}, + {"RTF_UP", Const, 0}, + {"RTF_USETRAILERS", Const, 1}, + {"RTF_WASCLONED", Const, 0}, + {"RTF_WINDOW", Const, 0}, + {"RTF_XRESOLVE", Const, 0}, + {"RTM_ADD", Const, 0}, + {"RTM_BASE", Const, 0}, + {"RTM_CHANGE", Const, 0}, + {"RTM_CHGADDR", Const, 1}, + {"RTM_DELACTION", Const, 0}, + {"RTM_DELADDR", Const, 0}, + {"RTM_DELADDRLABEL", Const, 0}, + {"RTM_DELETE", Const, 0}, + {"RTM_DELLINK", Const, 0}, + {"RTM_DELMADDR", Const, 0}, + {"RTM_DELNEIGH", Const, 0}, + {"RTM_DELQDISC", Const, 0}, + {"RTM_DELROUTE", Const, 0}, + {"RTM_DELRULE", Const, 0}, + {"RTM_DELTCLASS", Const, 0}, + {"RTM_DELTFILTER", Const, 0}, + {"RTM_DESYNC", Const, 1}, + {"RTM_F_CLONED", Const, 0}, + {"RTM_F_EQUALIZE", Const, 0}, + {"RTM_F_NOTIFY", Const, 0}, + {"RTM_F_PREFIX", Const, 0}, + {"RTM_GET", Const, 0}, + {"RTM_GET2", Const, 0}, + {"RTM_GETACTION", Const, 0}, + {"RTM_GETADDR", Const, 0}, + {"RTM_GETADDRLABEL", Const, 0}, + {"RTM_GETANYCAST", Const, 0}, + {"RTM_GETDCB", Const, 0}, + {"RTM_GETLINK", Const, 0}, + {"RTM_GETMULTICAST", Const, 0}, + {"RTM_GETNEIGH", Const, 0}, + {"RTM_GETNEIGHTBL", Const, 0}, + {"RTM_GETQDISC", Const, 0}, + {"RTM_GETROUTE", Const, 0}, + {"RTM_GETRULE", Const, 0}, + {"RTM_GETTCLASS", Const, 0}, + {"RTM_GETTFILTER", Const, 0}, + {"RTM_IEEE80211", Const, 0}, + {"RTM_IFANNOUNCE", Const, 0}, + {"RTM_IFINFO", Const, 0}, + {"RTM_IFINFO2", Const, 0}, + {"RTM_LLINFO_UPD", Const, 1}, + {"RTM_LOCK", Const, 0}, + {"RTM_LOSING", Const, 0}, + {"RTM_MAX", Const, 0}, + {"RTM_MAXSIZE", Const, 1}, + {"RTM_MISS", Const, 0}, + {"RTM_NEWACTION", Const, 0}, + {"RTM_NEWADDR", Const, 0}, + {"RTM_NEWADDRLABEL", Const, 0}, + {"RTM_NEWLINK", Const, 0}, + {"RTM_NEWMADDR", Const, 0}, + {"RTM_NEWMADDR2", Const, 0}, + {"RTM_NEWNDUSEROPT", Const, 0}, + {"RTM_NEWNEIGH", Const, 0}, + {"RTM_NEWNEIGHTBL", Const, 0}, + {"RTM_NEWPREFIX", Const, 0}, + {"RTM_NEWQDISC", Const, 0}, + {"RTM_NEWROUTE", Const, 0}, + {"RTM_NEWRULE", Const, 0}, + {"RTM_NEWTCLASS", Const, 0}, + {"RTM_NEWTFILTER", Const, 0}, + {"RTM_NR_FAMILIES", Const, 0}, + {"RTM_NR_MSGTYPES", Const, 0}, + {"RTM_OIFINFO", Const, 1}, + {"RTM_OLDADD", Const, 0}, + {"RTM_OLDDEL", Const, 0}, + {"RTM_OOIFINFO", Const, 1}, + {"RTM_REDIRECT", Const, 0}, + {"RTM_RESOLVE", Const, 0}, + {"RTM_RTTUNIT", Const, 0}, + {"RTM_SETDCB", Const, 0}, + {"RTM_SETGATE", Const, 1}, + {"RTM_SETLINK", Const, 0}, + {"RTM_SETNEIGHTBL", Const, 0}, + {"RTM_VERSION", Const, 0}, + {"RTNH_ALIGNTO", Const, 0}, + {"RTNH_F_DEAD", Const, 0}, + {"RTNH_F_ONLINK", Const, 0}, + {"RTNH_F_PERVASIVE", Const, 0}, + {"RTNLGRP_IPV4_IFADDR", Const, 1}, + {"RTNLGRP_IPV4_MROUTE", Const, 1}, + {"RTNLGRP_IPV4_ROUTE", Const, 1}, + {"RTNLGRP_IPV4_RULE", Const, 1}, + {"RTNLGRP_IPV6_IFADDR", Const, 1}, + {"RTNLGRP_IPV6_IFINFO", Const, 1}, + {"RTNLGRP_IPV6_MROUTE", Const, 1}, + {"RTNLGRP_IPV6_PREFIX", Const, 1}, + {"RTNLGRP_IPV6_ROUTE", Const, 1}, + {"RTNLGRP_IPV6_RULE", Const, 1}, + {"RTNLGRP_LINK", Const, 1}, + {"RTNLGRP_ND_USEROPT", Const, 1}, + {"RTNLGRP_NEIGH", Const, 1}, + {"RTNLGRP_NONE", Const, 1}, + {"RTNLGRP_NOTIFY", Const, 1}, + {"RTNLGRP_TC", Const, 1}, + {"RTN_ANYCAST", Const, 0}, + {"RTN_BLACKHOLE", Const, 0}, + {"RTN_BROADCAST", Const, 0}, + {"RTN_LOCAL", Const, 0}, + {"RTN_MAX", Const, 0}, + {"RTN_MULTICAST", Const, 0}, + {"RTN_NAT", Const, 0}, + {"RTN_PROHIBIT", Const, 0}, + {"RTN_THROW", Const, 0}, + {"RTN_UNICAST", Const, 0}, + {"RTN_UNREACHABLE", Const, 0}, + {"RTN_UNSPEC", Const, 0}, + {"RTN_XRESOLVE", Const, 0}, + {"RTPROT_BIRD", Const, 0}, + {"RTPROT_BOOT", Const, 0}, + {"RTPROT_DHCP", Const, 0}, + {"RTPROT_DNROUTED", Const, 0}, + {"RTPROT_GATED", Const, 0}, + {"RTPROT_KERNEL", Const, 0}, + {"RTPROT_MRT", Const, 0}, + {"RTPROT_NTK", Const, 0}, + {"RTPROT_RA", Const, 0}, + {"RTPROT_REDIRECT", Const, 0}, + {"RTPROT_STATIC", Const, 0}, + {"RTPROT_UNSPEC", Const, 0}, + {"RTPROT_XORP", Const, 0}, + {"RTPROT_ZEBRA", Const, 0}, + {"RTV_EXPIRE", Const, 0}, + {"RTV_HOPCOUNT", Const, 0}, + {"RTV_MTU", Const, 0}, + {"RTV_RPIPE", Const, 0}, + {"RTV_RTT", Const, 0}, + {"RTV_RTTVAR", Const, 0}, + {"RTV_SPIPE", Const, 0}, + {"RTV_SSTHRESH", Const, 0}, + {"RTV_WEIGHT", Const, 0}, + {"RT_CACHING_CONTEXT", Const, 1}, + {"RT_CLASS_DEFAULT", Const, 0}, + {"RT_CLASS_LOCAL", Const, 0}, + {"RT_CLASS_MAIN", Const, 0}, + {"RT_CLASS_MAX", Const, 0}, + {"RT_CLASS_UNSPEC", Const, 0}, + {"RT_DEFAULT_FIB", Const, 1}, + {"RT_NORTREF", Const, 1}, + {"RT_SCOPE_HOST", Const, 0}, + {"RT_SCOPE_LINK", Const, 0}, + {"RT_SCOPE_NOWHERE", Const, 0}, + {"RT_SCOPE_SITE", Const, 0}, + {"RT_SCOPE_UNIVERSE", Const, 0}, + {"RT_TABLEID_MAX", Const, 1}, + {"RT_TABLE_COMPAT", Const, 0}, + {"RT_TABLE_DEFAULT", Const, 0}, + {"RT_TABLE_LOCAL", Const, 0}, + {"RT_TABLE_MAIN", Const, 0}, + {"RT_TABLE_MAX", Const, 0}, + {"RT_TABLE_UNSPEC", Const, 0}, + {"RUSAGE_CHILDREN", Const, 0}, + {"RUSAGE_SELF", Const, 0}, + {"RUSAGE_THREAD", Const, 0}, + {"Radvisory_t", Type, 0}, + {"Radvisory_t.Count", Field, 0}, + {"Radvisory_t.Offset", Field, 0}, + {"Radvisory_t.Pad_cgo_0", Field, 0}, + {"RawConn", Type, 9}, + {"RawSockaddr", Type, 0}, + {"RawSockaddr.Data", Field, 0}, + {"RawSockaddr.Family", Field, 0}, + {"RawSockaddr.Len", Field, 0}, + {"RawSockaddrAny", Type, 0}, + {"RawSockaddrAny.Addr", Field, 0}, + {"RawSockaddrAny.Pad", Field, 0}, + {"RawSockaddrDatalink", Type, 0}, + {"RawSockaddrDatalink.Alen", Field, 0}, + {"RawSockaddrDatalink.Data", Field, 0}, + {"RawSockaddrDatalink.Family", Field, 0}, + {"RawSockaddrDatalink.Index", Field, 0}, + {"RawSockaddrDatalink.Len", Field, 0}, + {"RawSockaddrDatalink.Nlen", Field, 0}, + {"RawSockaddrDatalink.Pad_cgo_0", Field, 2}, + {"RawSockaddrDatalink.Slen", Field, 0}, + {"RawSockaddrDatalink.Type", Field, 0}, + {"RawSockaddrInet4", Type, 0}, + {"RawSockaddrInet4.Addr", Field, 0}, + {"RawSockaddrInet4.Family", Field, 0}, + {"RawSockaddrInet4.Len", Field, 0}, + {"RawSockaddrInet4.Port", Field, 0}, + {"RawSockaddrInet4.Zero", Field, 0}, + {"RawSockaddrInet6", Type, 0}, + {"RawSockaddrInet6.Addr", Field, 0}, + {"RawSockaddrInet6.Family", Field, 0}, + {"RawSockaddrInet6.Flowinfo", Field, 0}, + {"RawSockaddrInet6.Len", Field, 0}, + {"RawSockaddrInet6.Port", Field, 0}, + {"RawSockaddrInet6.Scope_id", Field, 0}, + {"RawSockaddrLinklayer", Type, 0}, + {"RawSockaddrLinklayer.Addr", Field, 0}, + {"RawSockaddrLinklayer.Family", Field, 0}, + {"RawSockaddrLinklayer.Halen", Field, 0}, + {"RawSockaddrLinklayer.Hatype", Field, 0}, + {"RawSockaddrLinklayer.Ifindex", Field, 0}, + {"RawSockaddrLinklayer.Pkttype", Field, 0}, + {"RawSockaddrLinklayer.Protocol", Field, 0}, + {"RawSockaddrNetlink", Type, 0}, + {"RawSockaddrNetlink.Family", Field, 0}, + {"RawSockaddrNetlink.Groups", Field, 0}, + {"RawSockaddrNetlink.Pad", Field, 0}, + {"RawSockaddrNetlink.Pid", Field, 0}, + {"RawSockaddrUnix", Type, 0}, + {"RawSockaddrUnix.Family", Field, 0}, + {"RawSockaddrUnix.Len", Field, 0}, + {"RawSockaddrUnix.Pad_cgo_0", Field, 2}, + {"RawSockaddrUnix.Path", Field, 0}, + {"RawSyscall", Func, 0}, + {"RawSyscall6", Func, 0}, + {"Read", Func, 0}, + {"ReadConsole", Func, 1}, + {"ReadDirectoryChanges", Func, 0}, + {"ReadDirent", Func, 0}, + {"ReadFile", Func, 0}, + {"Readlink", Func, 0}, + {"Reboot", Func, 0}, + {"Recvfrom", Func, 0}, + {"Recvmsg", Func, 0}, + {"RegCloseKey", Func, 0}, + {"RegEnumKeyEx", Func, 0}, + {"RegOpenKeyEx", Func, 0}, + {"RegQueryInfoKey", Func, 0}, + {"RegQueryValueEx", Func, 0}, + {"RemoveDirectory", Func, 0}, + {"Removexattr", Func, 1}, + {"Rename", Func, 0}, + {"Renameat", Func, 0}, + {"Revoke", Func, 0}, + {"Rlimit", Type, 0}, + {"Rlimit.Cur", Field, 0}, + {"Rlimit.Max", Field, 0}, + {"Rmdir", Func, 0}, + {"RouteMessage", Type, 0}, + {"RouteMessage.Data", Field, 0}, + {"RouteMessage.Header", Field, 0}, + {"RouteRIB", Func, 0}, + {"RoutingMessage", Type, 0}, + {"RtAttr", Type, 0}, + {"RtAttr.Len", Field, 0}, + {"RtAttr.Type", Field, 0}, + {"RtGenmsg", Type, 0}, + {"RtGenmsg.Family", Field, 0}, + {"RtMetrics", Type, 0}, + {"RtMetrics.Expire", Field, 0}, + {"RtMetrics.Filler", Field, 0}, + {"RtMetrics.Hopcount", Field, 0}, + {"RtMetrics.Locks", Field, 0}, + {"RtMetrics.Mtu", Field, 0}, + {"RtMetrics.Pad", Field, 3}, + {"RtMetrics.Pksent", Field, 0}, + {"RtMetrics.Recvpipe", Field, 0}, + {"RtMetrics.Refcnt", Field, 2}, + {"RtMetrics.Rtt", Field, 0}, + {"RtMetrics.Rttvar", Field, 0}, + {"RtMetrics.Sendpipe", Field, 0}, + {"RtMetrics.Ssthresh", Field, 0}, + {"RtMetrics.Weight", Field, 0}, + {"RtMsg", Type, 0}, + {"RtMsg.Dst_len", Field, 0}, + {"RtMsg.Family", Field, 0}, + {"RtMsg.Flags", Field, 0}, + {"RtMsg.Protocol", Field, 0}, + {"RtMsg.Scope", Field, 0}, + {"RtMsg.Src_len", Field, 0}, + {"RtMsg.Table", Field, 0}, + {"RtMsg.Tos", Field, 0}, + {"RtMsg.Type", Field, 0}, + {"RtMsghdr", Type, 0}, + {"RtMsghdr.Addrs", Field, 0}, + {"RtMsghdr.Errno", Field, 0}, + {"RtMsghdr.Flags", Field, 0}, + {"RtMsghdr.Fmask", Field, 0}, + {"RtMsghdr.Hdrlen", Field, 2}, + {"RtMsghdr.Index", Field, 0}, + {"RtMsghdr.Inits", Field, 0}, + {"RtMsghdr.Mpls", Field, 2}, + {"RtMsghdr.Msglen", Field, 0}, + {"RtMsghdr.Pad_cgo_0", Field, 0}, + {"RtMsghdr.Pad_cgo_1", Field, 2}, + {"RtMsghdr.Pid", Field, 0}, + {"RtMsghdr.Priority", Field, 2}, + {"RtMsghdr.Rmx", Field, 0}, + {"RtMsghdr.Seq", Field, 0}, + {"RtMsghdr.Tableid", Field, 2}, + {"RtMsghdr.Type", Field, 0}, + {"RtMsghdr.Use", Field, 0}, + {"RtMsghdr.Version", Field, 0}, + {"RtNexthop", Type, 0}, + {"RtNexthop.Flags", Field, 0}, + {"RtNexthop.Hops", Field, 0}, + {"RtNexthop.Ifindex", Field, 0}, + {"RtNexthop.Len", Field, 0}, + {"Rusage", Type, 0}, + {"Rusage.CreationTime", Field, 0}, + {"Rusage.ExitTime", Field, 0}, + {"Rusage.Idrss", Field, 0}, + {"Rusage.Inblock", Field, 0}, + {"Rusage.Isrss", Field, 0}, + {"Rusage.Ixrss", Field, 0}, + {"Rusage.KernelTime", Field, 0}, + {"Rusage.Majflt", Field, 0}, + {"Rusage.Maxrss", Field, 0}, + {"Rusage.Minflt", Field, 0}, + {"Rusage.Msgrcv", Field, 0}, + {"Rusage.Msgsnd", Field, 0}, + {"Rusage.Nivcsw", Field, 0}, + {"Rusage.Nsignals", Field, 0}, + {"Rusage.Nswap", Field, 0}, + {"Rusage.Nvcsw", Field, 0}, + {"Rusage.Oublock", Field, 0}, + {"Rusage.Stime", Field, 0}, + {"Rusage.UserTime", Field, 0}, + {"Rusage.Utime", Field, 0}, + {"SCM_BINTIME", Const, 0}, + {"SCM_CREDENTIALS", Const, 0}, + {"SCM_CREDS", Const, 0}, + {"SCM_RIGHTS", Const, 0}, + {"SCM_TIMESTAMP", Const, 0}, + {"SCM_TIMESTAMPING", Const, 0}, + {"SCM_TIMESTAMPNS", Const, 0}, + {"SCM_TIMESTAMP_MONOTONIC", Const, 0}, + {"SHUT_RD", Const, 0}, + {"SHUT_RDWR", Const, 0}, + {"SHUT_WR", Const, 0}, + {"SID", Type, 0}, + {"SIDAndAttributes", Type, 0}, + {"SIDAndAttributes.Attributes", Field, 0}, + {"SIDAndAttributes.Sid", Field, 0}, + {"SIGABRT", Const, 0}, + {"SIGALRM", Const, 0}, + {"SIGBUS", Const, 0}, + {"SIGCHLD", Const, 0}, + {"SIGCLD", Const, 0}, + {"SIGCONT", Const, 0}, + {"SIGEMT", Const, 0}, + {"SIGFPE", Const, 0}, + {"SIGHUP", Const, 0}, + {"SIGILL", Const, 0}, + {"SIGINFO", Const, 0}, + {"SIGINT", Const, 0}, + {"SIGIO", Const, 0}, + {"SIGIOT", Const, 0}, + {"SIGKILL", Const, 0}, + {"SIGLIBRT", Const, 1}, + {"SIGLWP", Const, 0}, + {"SIGPIPE", Const, 0}, + {"SIGPOLL", Const, 0}, + {"SIGPROF", Const, 0}, + {"SIGPWR", Const, 0}, + {"SIGQUIT", Const, 0}, + {"SIGSEGV", Const, 0}, + {"SIGSTKFLT", Const, 0}, + {"SIGSTOP", Const, 0}, + {"SIGSYS", Const, 0}, + {"SIGTERM", Const, 0}, + {"SIGTHR", Const, 0}, + {"SIGTRAP", Const, 0}, + {"SIGTSTP", Const, 0}, + {"SIGTTIN", Const, 0}, + {"SIGTTOU", Const, 0}, + {"SIGUNUSED", Const, 0}, + {"SIGURG", Const, 0}, + {"SIGUSR1", Const, 0}, + {"SIGUSR2", Const, 0}, + {"SIGVTALRM", Const, 0}, + {"SIGWINCH", Const, 0}, + {"SIGXCPU", Const, 0}, + {"SIGXFSZ", Const, 0}, + {"SIOCADDDLCI", Const, 0}, + {"SIOCADDMULTI", Const, 0}, + {"SIOCADDRT", Const, 0}, + {"SIOCAIFADDR", Const, 0}, + {"SIOCAIFGROUP", Const, 0}, + {"SIOCALIFADDR", Const, 0}, + {"SIOCARPIPLL", Const, 0}, + {"SIOCATMARK", Const, 0}, + {"SIOCAUTOADDR", Const, 0}, + {"SIOCAUTONETMASK", Const, 0}, + {"SIOCBRDGADD", Const, 1}, + {"SIOCBRDGADDS", Const, 1}, + {"SIOCBRDGARL", Const, 1}, + {"SIOCBRDGDADDR", Const, 1}, + {"SIOCBRDGDEL", Const, 1}, + {"SIOCBRDGDELS", Const, 1}, + {"SIOCBRDGFLUSH", Const, 1}, + {"SIOCBRDGFRL", Const, 1}, + {"SIOCBRDGGCACHE", Const, 1}, + {"SIOCBRDGGFD", Const, 1}, + {"SIOCBRDGGHT", Const, 1}, + {"SIOCBRDGGIFFLGS", Const, 1}, + {"SIOCBRDGGMA", Const, 1}, + {"SIOCBRDGGPARAM", Const, 1}, + {"SIOCBRDGGPRI", Const, 1}, + {"SIOCBRDGGRL", Const, 1}, + {"SIOCBRDGGSIFS", Const, 1}, + {"SIOCBRDGGTO", Const, 1}, + {"SIOCBRDGIFS", Const, 1}, + {"SIOCBRDGRTS", Const, 1}, + {"SIOCBRDGSADDR", Const, 1}, + {"SIOCBRDGSCACHE", Const, 1}, + {"SIOCBRDGSFD", Const, 1}, + {"SIOCBRDGSHT", Const, 1}, + {"SIOCBRDGSIFCOST", Const, 1}, + {"SIOCBRDGSIFFLGS", Const, 1}, + {"SIOCBRDGSIFPRIO", Const, 1}, + {"SIOCBRDGSMA", Const, 1}, + {"SIOCBRDGSPRI", Const, 1}, + {"SIOCBRDGSPROTO", Const, 1}, + {"SIOCBRDGSTO", Const, 1}, + {"SIOCBRDGSTXHC", Const, 1}, + {"SIOCDARP", Const, 0}, + {"SIOCDELDLCI", Const, 0}, + {"SIOCDELMULTI", Const, 0}, + {"SIOCDELRT", Const, 0}, + {"SIOCDEVPRIVATE", Const, 0}, + {"SIOCDIFADDR", Const, 0}, + {"SIOCDIFGROUP", Const, 0}, + {"SIOCDIFPHYADDR", Const, 0}, + {"SIOCDLIFADDR", Const, 0}, + {"SIOCDRARP", Const, 0}, + {"SIOCGARP", Const, 0}, + {"SIOCGDRVSPEC", Const, 0}, + {"SIOCGETKALIVE", Const, 1}, + {"SIOCGETLABEL", Const, 1}, + {"SIOCGETPFLOW", Const, 1}, + {"SIOCGETPFSYNC", Const, 1}, + {"SIOCGETSGCNT", Const, 0}, + {"SIOCGETVIFCNT", Const, 0}, + {"SIOCGETVLAN", Const, 0}, + {"SIOCGHIWAT", Const, 0}, + {"SIOCGIFADDR", Const, 0}, + {"SIOCGIFADDRPREF", Const, 1}, + {"SIOCGIFALIAS", Const, 1}, + {"SIOCGIFALTMTU", Const, 0}, + {"SIOCGIFASYNCMAP", Const, 0}, + {"SIOCGIFBOND", Const, 0}, + {"SIOCGIFBR", Const, 0}, + {"SIOCGIFBRDADDR", Const, 0}, + {"SIOCGIFCAP", Const, 0}, + {"SIOCGIFCONF", Const, 0}, + {"SIOCGIFCOUNT", Const, 0}, + {"SIOCGIFDATA", Const, 1}, + {"SIOCGIFDESCR", Const, 0}, + {"SIOCGIFDEVMTU", Const, 0}, + {"SIOCGIFDLT", Const, 1}, + {"SIOCGIFDSTADDR", Const, 0}, + {"SIOCGIFENCAP", Const, 0}, + {"SIOCGIFFIB", Const, 1}, + {"SIOCGIFFLAGS", Const, 0}, + {"SIOCGIFGATTR", Const, 1}, + {"SIOCGIFGENERIC", Const, 0}, + {"SIOCGIFGMEMB", Const, 0}, + {"SIOCGIFGROUP", Const, 0}, + {"SIOCGIFHARDMTU", Const, 3}, + {"SIOCGIFHWADDR", Const, 0}, + {"SIOCGIFINDEX", Const, 0}, + {"SIOCGIFKPI", Const, 0}, + {"SIOCGIFMAC", Const, 0}, + {"SIOCGIFMAP", Const, 0}, + {"SIOCGIFMEDIA", Const, 0}, + {"SIOCGIFMEM", Const, 0}, + {"SIOCGIFMETRIC", Const, 0}, + {"SIOCGIFMTU", Const, 0}, + {"SIOCGIFNAME", Const, 0}, + {"SIOCGIFNETMASK", Const, 0}, + {"SIOCGIFPDSTADDR", Const, 0}, + {"SIOCGIFPFLAGS", Const, 0}, + {"SIOCGIFPHYS", Const, 0}, + {"SIOCGIFPRIORITY", Const, 1}, + {"SIOCGIFPSRCADDR", Const, 0}, + {"SIOCGIFRDOMAIN", Const, 1}, + {"SIOCGIFRTLABEL", Const, 1}, + {"SIOCGIFSLAVE", Const, 0}, + {"SIOCGIFSTATUS", Const, 0}, + {"SIOCGIFTIMESLOT", Const, 1}, + {"SIOCGIFTXQLEN", Const, 0}, + {"SIOCGIFVLAN", Const, 0}, + {"SIOCGIFWAKEFLAGS", Const, 0}, + {"SIOCGIFXFLAGS", Const, 1}, + {"SIOCGLIFADDR", Const, 0}, + {"SIOCGLIFPHYADDR", Const, 0}, + {"SIOCGLIFPHYRTABLE", Const, 1}, + {"SIOCGLIFPHYTTL", Const, 3}, + {"SIOCGLINKSTR", Const, 1}, + {"SIOCGLOWAT", Const, 0}, + {"SIOCGPGRP", Const, 0}, + {"SIOCGPRIVATE_0", Const, 0}, + {"SIOCGPRIVATE_1", Const, 0}, + {"SIOCGRARP", Const, 0}, + {"SIOCGSPPPPARAMS", Const, 3}, + {"SIOCGSTAMP", Const, 0}, + {"SIOCGSTAMPNS", Const, 0}, + {"SIOCGVH", Const, 1}, + {"SIOCGVNETID", Const, 3}, + {"SIOCIFCREATE", Const, 0}, + {"SIOCIFCREATE2", Const, 0}, + {"SIOCIFDESTROY", Const, 0}, + {"SIOCIFGCLONERS", Const, 0}, + {"SIOCINITIFADDR", Const, 1}, + {"SIOCPROTOPRIVATE", Const, 0}, + {"SIOCRSLVMULTI", Const, 0}, + {"SIOCRTMSG", Const, 0}, + {"SIOCSARP", Const, 0}, + {"SIOCSDRVSPEC", Const, 0}, + {"SIOCSETKALIVE", Const, 1}, + {"SIOCSETLABEL", Const, 1}, + {"SIOCSETPFLOW", Const, 1}, + {"SIOCSETPFSYNC", Const, 1}, + {"SIOCSETVLAN", Const, 0}, + {"SIOCSHIWAT", Const, 0}, + {"SIOCSIFADDR", Const, 0}, + {"SIOCSIFADDRPREF", Const, 1}, + {"SIOCSIFALTMTU", Const, 0}, + {"SIOCSIFASYNCMAP", Const, 0}, + {"SIOCSIFBOND", Const, 0}, + {"SIOCSIFBR", Const, 0}, + {"SIOCSIFBRDADDR", Const, 0}, + {"SIOCSIFCAP", Const, 0}, + {"SIOCSIFDESCR", Const, 0}, + {"SIOCSIFDSTADDR", Const, 0}, + {"SIOCSIFENCAP", Const, 0}, + {"SIOCSIFFIB", Const, 1}, + {"SIOCSIFFLAGS", Const, 0}, + {"SIOCSIFGATTR", Const, 1}, + {"SIOCSIFGENERIC", Const, 0}, + {"SIOCSIFHWADDR", Const, 0}, + {"SIOCSIFHWBROADCAST", Const, 0}, + {"SIOCSIFKPI", Const, 0}, + {"SIOCSIFLINK", Const, 0}, + {"SIOCSIFLLADDR", Const, 0}, + {"SIOCSIFMAC", Const, 0}, + {"SIOCSIFMAP", Const, 0}, + {"SIOCSIFMEDIA", Const, 0}, + {"SIOCSIFMEM", Const, 0}, + {"SIOCSIFMETRIC", Const, 0}, + {"SIOCSIFMTU", Const, 0}, + {"SIOCSIFNAME", Const, 0}, + {"SIOCSIFNETMASK", Const, 0}, + {"SIOCSIFPFLAGS", Const, 0}, + {"SIOCSIFPHYADDR", Const, 0}, + {"SIOCSIFPHYS", Const, 0}, + {"SIOCSIFPRIORITY", Const, 1}, + {"SIOCSIFRDOMAIN", Const, 1}, + {"SIOCSIFRTLABEL", Const, 1}, + {"SIOCSIFRVNET", Const, 0}, + {"SIOCSIFSLAVE", Const, 0}, + {"SIOCSIFTIMESLOT", Const, 1}, + {"SIOCSIFTXQLEN", Const, 0}, + {"SIOCSIFVLAN", Const, 0}, + {"SIOCSIFVNET", Const, 0}, + {"SIOCSIFXFLAGS", Const, 1}, + {"SIOCSLIFPHYADDR", Const, 0}, + {"SIOCSLIFPHYRTABLE", Const, 1}, + {"SIOCSLIFPHYTTL", Const, 3}, + {"SIOCSLINKSTR", Const, 1}, + {"SIOCSLOWAT", Const, 0}, + {"SIOCSPGRP", Const, 0}, + {"SIOCSRARP", Const, 0}, + {"SIOCSSPPPPARAMS", Const, 3}, + {"SIOCSVH", Const, 1}, + {"SIOCSVNETID", Const, 3}, + {"SIOCZIFDATA", Const, 1}, + {"SIO_GET_EXTENSION_FUNCTION_POINTER", Const, 1}, + {"SIO_GET_INTERFACE_LIST", Const, 0}, + {"SIO_KEEPALIVE_VALS", Const, 3}, + {"SIO_UDP_CONNRESET", Const, 4}, + {"SOCK_CLOEXEC", Const, 0}, + {"SOCK_DCCP", Const, 0}, + {"SOCK_DGRAM", Const, 0}, + {"SOCK_FLAGS_MASK", Const, 1}, + {"SOCK_MAXADDRLEN", Const, 0}, + {"SOCK_NONBLOCK", Const, 0}, + {"SOCK_NOSIGPIPE", Const, 1}, + {"SOCK_PACKET", Const, 0}, + {"SOCK_RAW", Const, 0}, + {"SOCK_RDM", Const, 0}, + {"SOCK_SEQPACKET", Const, 0}, + {"SOCK_STREAM", Const, 0}, + {"SOL_AAL", Const, 0}, + {"SOL_ATM", Const, 0}, + {"SOL_DECNET", Const, 0}, + {"SOL_ICMPV6", Const, 0}, + {"SOL_IP", Const, 0}, + {"SOL_IPV6", Const, 0}, + {"SOL_IRDA", Const, 0}, + {"SOL_PACKET", Const, 0}, + {"SOL_RAW", Const, 0}, + {"SOL_SOCKET", Const, 0}, + {"SOL_TCP", Const, 0}, + {"SOL_X25", Const, 0}, + {"SOMAXCONN", Const, 0}, + {"SO_ACCEPTCONN", Const, 0}, + {"SO_ACCEPTFILTER", Const, 0}, + {"SO_ATTACH_FILTER", Const, 0}, + {"SO_BINDANY", Const, 1}, + {"SO_BINDTODEVICE", Const, 0}, + {"SO_BINTIME", Const, 0}, + {"SO_BROADCAST", Const, 0}, + {"SO_BSDCOMPAT", Const, 0}, + {"SO_DEBUG", Const, 0}, + {"SO_DETACH_FILTER", Const, 0}, + {"SO_DOMAIN", Const, 0}, + {"SO_DONTROUTE", Const, 0}, + {"SO_DONTTRUNC", Const, 0}, + {"SO_ERROR", Const, 0}, + {"SO_KEEPALIVE", Const, 0}, + {"SO_LABEL", Const, 0}, + {"SO_LINGER", Const, 0}, + {"SO_LINGER_SEC", Const, 0}, + {"SO_LISTENINCQLEN", Const, 0}, + {"SO_LISTENQLEN", Const, 0}, + {"SO_LISTENQLIMIT", Const, 0}, + {"SO_MARK", Const, 0}, + {"SO_NETPROC", Const, 1}, + {"SO_NKE", Const, 0}, + {"SO_NOADDRERR", Const, 0}, + {"SO_NOHEADER", Const, 1}, + {"SO_NOSIGPIPE", Const, 0}, + {"SO_NOTIFYCONFLICT", Const, 0}, + {"SO_NO_CHECK", Const, 0}, + {"SO_NO_DDP", Const, 0}, + {"SO_NO_OFFLOAD", Const, 0}, + {"SO_NP_EXTENSIONS", Const, 0}, + {"SO_NREAD", Const, 0}, + {"SO_NUMRCVPKT", Const, 16}, + {"SO_NWRITE", Const, 0}, + {"SO_OOBINLINE", Const, 0}, + {"SO_OVERFLOWED", Const, 1}, + {"SO_PASSCRED", Const, 0}, + {"SO_PASSSEC", Const, 0}, + {"SO_PEERCRED", Const, 0}, + {"SO_PEERLABEL", Const, 0}, + {"SO_PEERNAME", Const, 0}, + {"SO_PEERSEC", Const, 0}, + {"SO_PRIORITY", Const, 0}, + {"SO_PROTOCOL", Const, 0}, + {"SO_PROTOTYPE", Const, 1}, + {"SO_RANDOMPORT", Const, 0}, + {"SO_RCVBUF", Const, 0}, + {"SO_RCVBUFFORCE", Const, 0}, + {"SO_RCVLOWAT", Const, 0}, + {"SO_RCVTIMEO", Const, 0}, + {"SO_RESTRICTIONS", Const, 0}, + {"SO_RESTRICT_DENYIN", Const, 0}, + {"SO_RESTRICT_DENYOUT", Const, 0}, + {"SO_RESTRICT_DENYSET", Const, 0}, + {"SO_REUSEADDR", Const, 0}, + {"SO_REUSEPORT", Const, 0}, + {"SO_REUSESHAREUID", Const, 0}, + {"SO_RTABLE", Const, 1}, + {"SO_RXQ_OVFL", Const, 0}, + {"SO_SECURITY_AUTHENTICATION", Const, 0}, + {"SO_SECURITY_ENCRYPTION_NETWORK", Const, 0}, + {"SO_SECURITY_ENCRYPTION_TRANSPORT", Const, 0}, + {"SO_SETFIB", Const, 0}, + {"SO_SNDBUF", Const, 0}, + {"SO_SNDBUFFORCE", Const, 0}, + {"SO_SNDLOWAT", Const, 0}, + {"SO_SNDTIMEO", Const, 0}, + {"SO_SPLICE", Const, 1}, + {"SO_TIMESTAMP", Const, 0}, + {"SO_TIMESTAMPING", Const, 0}, + {"SO_TIMESTAMPNS", Const, 0}, + {"SO_TIMESTAMP_MONOTONIC", Const, 0}, + {"SO_TYPE", Const, 0}, + {"SO_UPCALLCLOSEWAIT", Const, 0}, + {"SO_UPDATE_ACCEPT_CONTEXT", Const, 0}, + {"SO_UPDATE_CONNECT_CONTEXT", Const, 1}, + {"SO_USELOOPBACK", Const, 0}, + {"SO_USER_COOKIE", Const, 1}, + {"SO_VENDOR", Const, 3}, + {"SO_WANTMORE", Const, 0}, + {"SO_WANTOOBFLAG", Const, 0}, + {"SSLExtraCertChainPolicyPara", Type, 0}, + {"SSLExtraCertChainPolicyPara.AuthType", Field, 0}, + {"SSLExtraCertChainPolicyPara.Checks", Field, 0}, + {"SSLExtraCertChainPolicyPara.ServerName", Field, 0}, + {"SSLExtraCertChainPolicyPara.Size", Field, 0}, + {"STANDARD_RIGHTS_ALL", Const, 0}, + {"STANDARD_RIGHTS_EXECUTE", Const, 0}, + {"STANDARD_RIGHTS_READ", Const, 0}, + {"STANDARD_RIGHTS_REQUIRED", Const, 0}, + {"STANDARD_RIGHTS_WRITE", Const, 0}, + {"STARTF_USESHOWWINDOW", Const, 0}, + {"STARTF_USESTDHANDLES", Const, 0}, + {"STD_ERROR_HANDLE", Const, 0}, + {"STD_INPUT_HANDLE", Const, 0}, + {"STD_OUTPUT_HANDLE", Const, 0}, + {"SUBLANG_ENGLISH_US", Const, 0}, + {"SW_FORCEMINIMIZE", Const, 0}, + {"SW_HIDE", Const, 0}, + {"SW_MAXIMIZE", Const, 0}, + {"SW_MINIMIZE", Const, 0}, + {"SW_NORMAL", Const, 0}, + {"SW_RESTORE", Const, 0}, + {"SW_SHOW", Const, 0}, + {"SW_SHOWDEFAULT", Const, 0}, + {"SW_SHOWMAXIMIZED", Const, 0}, + {"SW_SHOWMINIMIZED", Const, 0}, + {"SW_SHOWMINNOACTIVE", Const, 0}, + {"SW_SHOWNA", Const, 0}, + {"SW_SHOWNOACTIVATE", Const, 0}, + {"SW_SHOWNORMAL", Const, 0}, + {"SYMBOLIC_LINK_FLAG_DIRECTORY", Const, 4}, + {"SYNCHRONIZE", Const, 0}, + {"SYSCTL_VERSION", Const, 1}, + {"SYSCTL_VERS_0", Const, 1}, + {"SYSCTL_VERS_1", Const, 1}, + {"SYSCTL_VERS_MASK", Const, 1}, + {"SYS_ABORT2", Const, 0}, + {"SYS_ACCEPT", Const, 0}, + {"SYS_ACCEPT4", Const, 0}, + {"SYS_ACCEPT_NOCANCEL", Const, 0}, + {"SYS_ACCESS", Const, 0}, + {"SYS_ACCESS_EXTENDED", Const, 0}, + {"SYS_ACCT", Const, 0}, + {"SYS_ADD_KEY", Const, 0}, + {"SYS_ADD_PROFIL", Const, 0}, + {"SYS_ADJFREQ", Const, 1}, + {"SYS_ADJTIME", Const, 0}, + {"SYS_ADJTIMEX", Const, 0}, + {"SYS_AFS_SYSCALL", Const, 0}, + {"SYS_AIO_CANCEL", Const, 0}, + {"SYS_AIO_ERROR", Const, 0}, + {"SYS_AIO_FSYNC", Const, 0}, + {"SYS_AIO_MLOCK", Const, 14}, + {"SYS_AIO_READ", Const, 0}, + {"SYS_AIO_RETURN", Const, 0}, + {"SYS_AIO_SUSPEND", Const, 0}, + {"SYS_AIO_SUSPEND_NOCANCEL", Const, 0}, + {"SYS_AIO_WAITCOMPLETE", Const, 14}, + {"SYS_AIO_WRITE", Const, 0}, + {"SYS_ALARM", Const, 0}, + {"SYS_ARCH_PRCTL", Const, 0}, + {"SYS_ARM_FADVISE64_64", Const, 0}, + {"SYS_ARM_SYNC_FILE_RANGE", Const, 0}, + {"SYS_ATGETMSG", Const, 0}, + {"SYS_ATPGETREQ", Const, 0}, + {"SYS_ATPGETRSP", Const, 0}, + {"SYS_ATPSNDREQ", Const, 0}, + {"SYS_ATPSNDRSP", Const, 0}, + {"SYS_ATPUTMSG", Const, 0}, + {"SYS_ATSOCKET", Const, 0}, + {"SYS_AUDIT", Const, 0}, + {"SYS_AUDITCTL", Const, 0}, + {"SYS_AUDITON", Const, 0}, + {"SYS_AUDIT_SESSION_JOIN", Const, 0}, + {"SYS_AUDIT_SESSION_PORT", Const, 0}, + {"SYS_AUDIT_SESSION_SELF", Const, 0}, + {"SYS_BDFLUSH", Const, 0}, + {"SYS_BIND", Const, 0}, + {"SYS_BINDAT", Const, 3}, + {"SYS_BREAK", Const, 0}, + {"SYS_BRK", Const, 0}, + {"SYS_BSDTHREAD_CREATE", Const, 0}, + {"SYS_BSDTHREAD_REGISTER", Const, 0}, + {"SYS_BSDTHREAD_TERMINATE", Const, 0}, + {"SYS_CAPGET", Const, 0}, + {"SYS_CAPSET", Const, 0}, + {"SYS_CAP_ENTER", Const, 0}, + {"SYS_CAP_FCNTLS_GET", Const, 1}, + {"SYS_CAP_FCNTLS_LIMIT", Const, 1}, + {"SYS_CAP_GETMODE", Const, 0}, + {"SYS_CAP_GETRIGHTS", Const, 0}, + {"SYS_CAP_IOCTLS_GET", Const, 1}, + {"SYS_CAP_IOCTLS_LIMIT", Const, 1}, + {"SYS_CAP_NEW", Const, 0}, + {"SYS_CAP_RIGHTS_GET", Const, 1}, + {"SYS_CAP_RIGHTS_LIMIT", Const, 1}, + {"SYS_CHDIR", Const, 0}, + {"SYS_CHFLAGS", Const, 0}, + {"SYS_CHFLAGSAT", Const, 3}, + {"SYS_CHMOD", Const, 0}, + {"SYS_CHMOD_EXTENDED", Const, 0}, + {"SYS_CHOWN", Const, 0}, + {"SYS_CHOWN32", Const, 0}, + {"SYS_CHROOT", Const, 0}, + {"SYS_CHUD", Const, 0}, + {"SYS_CLOCK_ADJTIME", Const, 0}, + {"SYS_CLOCK_GETCPUCLOCKID2", Const, 1}, + {"SYS_CLOCK_GETRES", Const, 0}, + {"SYS_CLOCK_GETTIME", Const, 0}, + {"SYS_CLOCK_NANOSLEEP", Const, 0}, + {"SYS_CLOCK_SETTIME", Const, 0}, + {"SYS_CLONE", Const, 0}, + {"SYS_CLOSE", Const, 0}, + {"SYS_CLOSEFROM", Const, 0}, + {"SYS_CLOSE_NOCANCEL", Const, 0}, + {"SYS_CONNECT", Const, 0}, + {"SYS_CONNECTAT", Const, 3}, + {"SYS_CONNECT_NOCANCEL", Const, 0}, + {"SYS_COPYFILE", Const, 0}, + {"SYS_CPUSET", Const, 0}, + {"SYS_CPUSET_GETAFFINITY", Const, 0}, + {"SYS_CPUSET_GETID", Const, 0}, + {"SYS_CPUSET_SETAFFINITY", Const, 0}, + {"SYS_CPUSET_SETID", Const, 0}, + {"SYS_CREAT", Const, 0}, + {"SYS_CREATE_MODULE", Const, 0}, + {"SYS_CSOPS", Const, 0}, + {"SYS_CSOPS_AUDITTOKEN", Const, 16}, + {"SYS_DELETE", Const, 0}, + {"SYS_DELETE_MODULE", Const, 0}, + {"SYS_DUP", Const, 0}, + {"SYS_DUP2", Const, 0}, + {"SYS_DUP3", Const, 0}, + {"SYS_EACCESS", Const, 0}, + {"SYS_EPOLL_CREATE", Const, 0}, + {"SYS_EPOLL_CREATE1", Const, 0}, + {"SYS_EPOLL_CTL", Const, 0}, + {"SYS_EPOLL_CTL_OLD", Const, 0}, + {"SYS_EPOLL_PWAIT", Const, 0}, + {"SYS_EPOLL_WAIT", Const, 0}, + {"SYS_EPOLL_WAIT_OLD", Const, 0}, + {"SYS_EVENTFD", Const, 0}, + {"SYS_EVENTFD2", Const, 0}, + {"SYS_EXCHANGEDATA", Const, 0}, + {"SYS_EXECVE", Const, 0}, + {"SYS_EXIT", Const, 0}, + {"SYS_EXIT_GROUP", Const, 0}, + {"SYS_EXTATTRCTL", Const, 0}, + {"SYS_EXTATTR_DELETE_FD", Const, 0}, + {"SYS_EXTATTR_DELETE_FILE", Const, 0}, + {"SYS_EXTATTR_DELETE_LINK", Const, 0}, + {"SYS_EXTATTR_GET_FD", Const, 0}, + {"SYS_EXTATTR_GET_FILE", Const, 0}, + {"SYS_EXTATTR_GET_LINK", Const, 0}, + {"SYS_EXTATTR_LIST_FD", Const, 0}, + {"SYS_EXTATTR_LIST_FILE", Const, 0}, + {"SYS_EXTATTR_LIST_LINK", Const, 0}, + {"SYS_EXTATTR_SET_FD", Const, 0}, + {"SYS_EXTATTR_SET_FILE", Const, 0}, + {"SYS_EXTATTR_SET_LINK", Const, 0}, + {"SYS_FACCESSAT", Const, 0}, + {"SYS_FADVISE64", Const, 0}, + {"SYS_FADVISE64_64", Const, 0}, + {"SYS_FALLOCATE", Const, 0}, + {"SYS_FANOTIFY_INIT", Const, 0}, + {"SYS_FANOTIFY_MARK", Const, 0}, + {"SYS_FCHDIR", Const, 0}, + {"SYS_FCHFLAGS", Const, 0}, + {"SYS_FCHMOD", Const, 0}, + {"SYS_FCHMODAT", Const, 0}, + {"SYS_FCHMOD_EXTENDED", Const, 0}, + {"SYS_FCHOWN", Const, 0}, + {"SYS_FCHOWN32", Const, 0}, + {"SYS_FCHOWNAT", Const, 0}, + {"SYS_FCHROOT", Const, 1}, + {"SYS_FCNTL", Const, 0}, + {"SYS_FCNTL64", Const, 0}, + {"SYS_FCNTL_NOCANCEL", Const, 0}, + {"SYS_FDATASYNC", Const, 0}, + {"SYS_FEXECVE", Const, 0}, + {"SYS_FFCLOCK_GETCOUNTER", Const, 0}, + {"SYS_FFCLOCK_GETESTIMATE", Const, 0}, + {"SYS_FFCLOCK_SETESTIMATE", Const, 0}, + {"SYS_FFSCTL", Const, 0}, + {"SYS_FGETATTRLIST", Const, 0}, + {"SYS_FGETXATTR", Const, 0}, + {"SYS_FHOPEN", Const, 0}, + {"SYS_FHSTAT", Const, 0}, + {"SYS_FHSTATFS", Const, 0}, + {"SYS_FILEPORT_MAKEFD", Const, 0}, + {"SYS_FILEPORT_MAKEPORT", Const, 0}, + {"SYS_FKTRACE", Const, 1}, + {"SYS_FLISTXATTR", Const, 0}, + {"SYS_FLOCK", Const, 0}, + {"SYS_FORK", Const, 0}, + {"SYS_FPATHCONF", Const, 0}, + {"SYS_FREEBSD6_FTRUNCATE", Const, 0}, + {"SYS_FREEBSD6_LSEEK", Const, 0}, + {"SYS_FREEBSD6_MMAP", Const, 0}, + {"SYS_FREEBSD6_PREAD", Const, 0}, + {"SYS_FREEBSD6_PWRITE", Const, 0}, + {"SYS_FREEBSD6_TRUNCATE", Const, 0}, + {"SYS_FREMOVEXATTR", Const, 0}, + {"SYS_FSCTL", Const, 0}, + {"SYS_FSETATTRLIST", Const, 0}, + {"SYS_FSETXATTR", Const, 0}, + {"SYS_FSGETPATH", Const, 0}, + {"SYS_FSTAT", Const, 0}, + {"SYS_FSTAT64", Const, 0}, + {"SYS_FSTAT64_EXTENDED", Const, 0}, + {"SYS_FSTATAT", Const, 0}, + {"SYS_FSTATAT64", Const, 0}, + {"SYS_FSTATFS", Const, 0}, + {"SYS_FSTATFS64", Const, 0}, + {"SYS_FSTATV", Const, 0}, + {"SYS_FSTATVFS1", Const, 1}, + {"SYS_FSTAT_EXTENDED", Const, 0}, + {"SYS_FSYNC", Const, 0}, + {"SYS_FSYNC_NOCANCEL", Const, 0}, + {"SYS_FSYNC_RANGE", Const, 1}, + {"SYS_FTIME", Const, 0}, + {"SYS_FTRUNCATE", Const, 0}, + {"SYS_FTRUNCATE64", Const, 0}, + {"SYS_FUTEX", Const, 0}, + {"SYS_FUTIMENS", Const, 1}, + {"SYS_FUTIMES", Const, 0}, + {"SYS_FUTIMESAT", Const, 0}, + {"SYS_GETATTRLIST", Const, 0}, + {"SYS_GETAUDIT", Const, 0}, + {"SYS_GETAUDIT_ADDR", Const, 0}, + {"SYS_GETAUID", Const, 0}, + {"SYS_GETCONTEXT", Const, 0}, + {"SYS_GETCPU", Const, 0}, + {"SYS_GETCWD", Const, 0}, + {"SYS_GETDENTS", Const, 0}, + {"SYS_GETDENTS64", Const, 0}, + {"SYS_GETDIRENTRIES", Const, 0}, + {"SYS_GETDIRENTRIES64", Const, 0}, + {"SYS_GETDIRENTRIESATTR", Const, 0}, + {"SYS_GETDTABLECOUNT", Const, 1}, + {"SYS_GETDTABLESIZE", Const, 0}, + {"SYS_GETEGID", Const, 0}, + {"SYS_GETEGID32", Const, 0}, + {"SYS_GETEUID", Const, 0}, + {"SYS_GETEUID32", Const, 0}, + {"SYS_GETFH", Const, 0}, + {"SYS_GETFSSTAT", Const, 0}, + {"SYS_GETFSSTAT64", Const, 0}, + {"SYS_GETGID", Const, 0}, + {"SYS_GETGID32", Const, 0}, + {"SYS_GETGROUPS", Const, 0}, + {"SYS_GETGROUPS32", Const, 0}, + {"SYS_GETHOSTUUID", Const, 0}, + {"SYS_GETITIMER", Const, 0}, + {"SYS_GETLCID", Const, 0}, + {"SYS_GETLOGIN", Const, 0}, + {"SYS_GETLOGINCLASS", Const, 0}, + {"SYS_GETPEERNAME", Const, 0}, + {"SYS_GETPGID", Const, 0}, + {"SYS_GETPGRP", Const, 0}, + {"SYS_GETPID", Const, 0}, + {"SYS_GETPMSG", Const, 0}, + {"SYS_GETPPID", Const, 0}, + {"SYS_GETPRIORITY", Const, 0}, + {"SYS_GETRESGID", Const, 0}, + {"SYS_GETRESGID32", Const, 0}, + {"SYS_GETRESUID", Const, 0}, + {"SYS_GETRESUID32", Const, 0}, + {"SYS_GETRLIMIT", Const, 0}, + {"SYS_GETRTABLE", Const, 1}, + {"SYS_GETRUSAGE", Const, 0}, + {"SYS_GETSGROUPS", Const, 0}, + {"SYS_GETSID", Const, 0}, + {"SYS_GETSOCKNAME", Const, 0}, + {"SYS_GETSOCKOPT", Const, 0}, + {"SYS_GETTHRID", Const, 1}, + {"SYS_GETTID", Const, 0}, + {"SYS_GETTIMEOFDAY", Const, 0}, + {"SYS_GETUID", Const, 0}, + {"SYS_GETUID32", Const, 0}, + {"SYS_GETVFSSTAT", Const, 1}, + {"SYS_GETWGROUPS", Const, 0}, + {"SYS_GETXATTR", Const, 0}, + {"SYS_GET_KERNEL_SYMS", Const, 0}, + {"SYS_GET_MEMPOLICY", Const, 0}, + {"SYS_GET_ROBUST_LIST", Const, 0}, + {"SYS_GET_THREAD_AREA", Const, 0}, + {"SYS_GSSD_SYSCALL", Const, 14}, + {"SYS_GTTY", Const, 0}, + {"SYS_IDENTITYSVC", Const, 0}, + {"SYS_IDLE", Const, 0}, + {"SYS_INITGROUPS", Const, 0}, + {"SYS_INIT_MODULE", Const, 0}, + {"SYS_INOTIFY_ADD_WATCH", Const, 0}, + {"SYS_INOTIFY_INIT", Const, 0}, + {"SYS_INOTIFY_INIT1", Const, 0}, + {"SYS_INOTIFY_RM_WATCH", Const, 0}, + {"SYS_IOCTL", Const, 0}, + {"SYS_IOPERM", Const, 0}, + {"SYS_IOPL", Const, 0}, + {"SYS_IOPOLICYSYS", Const, 0}, + {"SYS_IOPRIO_GET", Const, 0}, + {"SYS_IOPRIO_SET", Const, 0}, + {"SYS_IO_CANCEL", Const, 0}, + {"SYS_IO_DESTROY", Const, 0}, + {"SYS_IO_GETEVENTS", Const, 0}, + {"SYS_IO_SETUP", Const, 0}, + {"SYS_IO_SUBMIT", Const, 0}, + {"SYS_IPC", Const, 0}, + {"SYS_ISSETUGID", Const, 0}, + {"SYS_JAIL", Const, 0}, + {"SYS_JAIL_ATTACH", Const, 0}, + {"SYS_JAIL_GET", Const, 0}, + {"SYS_JAIL_REMOVE", Const, 0}, + {"SYS_JAIL_SET", Const, 0}, + {"SYS_KAS_INFO", Const, 16}, + {"SYS_KDEBUG_TRACE", Const, 0}, + {"SYS_KENV", Const, 0}, + {"SYS_KEVENT", Const, 0}, + {"SYS_KEVENT64", Const, 0}, + {"SYS_KEXEC_LOAD", Const, 0}, + {"SYS_KEYCTL", Const, 0}, + {"SYS_KILL", Const, 0}, + {"SYS_KLDFIND", Const, 0}, + {"SYS_KLDFIRSTMOD", Const, 0}, + {"SYS_KLDLOAD", Const, 0}, + {"SYS_KLDNEXT", Const, 0}, + {"SYS_KLDSTAT", Const, 0}, + {"SYS_KLDSYM", Const, 0}, + {"SYS_KLDUNLOAD", Const, 0}, + {"SYS_KLDUNLOADF", Const, 0}, + {"SYS_KMQ_NOTIFY", Const, 14}, + {"SYS_KMQ_OPEN", Const, 14}, + {"SYS_KMQ_SETATTR", Const, 14}, + {"SYS_KMQ_TIMEDRECEIVE", Const, 14}, + {"SYS_KMQ_TIMEDSEND", Const, 14}, + {"SYS_KMQ_UNLINK", Const, 14}, + {"SYS_KQUEUE", Const, 0}, + {"SYS_KQUEUE1", Const, 1}, + {"SYS_KSEM_CLOSE", Const, 14}, + {"SYS_KSEM_DESTROY", Const, 14}, + {"SYS_KSEM_GETVALUE", Const, 14}, + {"SYS_KSEM_INIT", Const, 14}, + {"SYS_KSEM_OPEN", Const, 14}, + {"SYS_KSEM_POST", Const, 14}, + {"SYS_KSEM_TIMEDWAIT", Const, 14}, + {"SYS_KSEM_TRYWAIT", Const, 14}, + {"SYS_KSEM_UNLINK", Const, 14}, + {"SYS_KSEM_WAIT", Const, 14}, + {"SYS_KTIMER_CREATE", Const, 0}, + {"SYS_KTIMER_DELETE", Const, 0}, + {"SYS_KTIMER_GETOVERRUN", Const, 0}, + {"SYS_KTIMER_GETTIME", Const, 0}, + {"SYS_KTIMER_SETTIME", Const, 0}, + {"SYS_KTRACE", Const, 0}, + {"SYS_LCHFLAGS", Const, 0}, + {"SYS_LCHMOD", Const, 0}, + {"SYS_LCHOWN", Const, 0}, + {"SYS_LCHOWN32", Const, 0}, + {"SYS_LEDGER", Const, 16}, + {"SYS_LGETFH", Const, 0}, + {"SYS_LGETXATTR", Const, 0}, + {"SYS_LINK", Const, 0}, + {"SYS_LINKAT", Const, 0}, + {"SYS_LIO_LISTIO", Const, 0}, + {"SYS_LISTEN", Const, 0}, + {"SYS_LISTXATTR", Const, 0}, + {"SYS_LLISTXATTR", Const, 0}, + {"SYS_LOCK", Const, 0}, + {"SYS_LOOKUP_DCOOKIE", Const, 0}, + {"SYS_LPATHCONF", Const, 0}, + {"SYS_LREMOVEXATTR", Const, 0}, + {"SYS_LSEEK", Const, 0}, + {"SYS_LSETXATTR", Const, 0}, + {"SYS_LSTAT", Const, 0}, + {"SYS_LSTAT64", Const, 0}, + {"SYS_LSTAT64_EXTENDED", Const, 0}, + {"SYS_LSTATV", Const, 0}, + {"SYS_LSTAT_EXTENDED", Const, 0}, + {"SYS_LUTIMES", Const, 0}, + {"SYS_MAC_SYSCALL", Const, 0}, + {"SYS_MADVISE", Const, 0}, + {"SYS_MADVISE1", Const, 0}, + {"SYS_MAXSYSCALL", Const, 0}, + {"SYS_MBIND", Const, 0}, + {"SYS_MIGRATE_PAGES", Const, 0}, + {"SYS_MINCORE", Const, 0}, + {"SYS_MINHERIT", Const, 0}, + {"SYS_MKCOMPLEX", Const, 0}, + {"SYS_MKDIR", Const, 0}, + {"SYS_MKDIRAT", Const, 0}, + {"SYS_MKDIR_EXTENDED", Const, 0}, + {"SYS_MKFIFO", Const, 0}, + {"SYS_MKFIFOAT", Const, 0}, + {"SYS_MKFIFO_EXTENDED", Const, 0}, + {"SYS_MKNOD", Const, 0}, + {"SYS_MKNODAT", Const, 0}, + {"SYS_MLOCK", Const, 0}, + {"SYS_MLOCKALL", Const, 0}, + {"SYS_MMAP", Const, 0}, + {"SYS_MMAP2", Const, 0}, + {"SYS_MODCTL", Const, 1}, + {"SYS_MODFIND", Const, 0}, + {"SYS_MODFNEXT", Const, 0}, + {"SYS_MODIFY_LDT", Const, 0}, + {"SYS_MODNEXT", Const, 0}, + {"SYS_MODSTAT", Const, 0}, + {"SYS_MODWATCH", Const, 0}, + {"SYS_MOUNT", Const, 0}, + {"SYS_MOVE_PAGES", Const, 0}, + {"SYS_MPROTECT", Const, 0}, + {"SYS_MPX", Const, 0}, + {"SYS_MQUERY", Const, 1}, + {"SYS_MQ_GETSETATTR", Const, 0}, + {"SYS_MQ_NOTIFY", Const, 0}, + {"SYS_MQ_OPEN", Const, 0}, + {"SYS_MQ_TIMEDRECEIVE", Const, 0}, + {"SYS_MQ_TIMEDSEND", Const, 0}, + {"SYS_MQ_UNLINK", Const, 0}, + {"SYS_MREMAP", Const, 0}, + {"SYS_MSGCTL", Const, 0}, + {"SYS_MSGGET", Const, 0}, + {"SYS_MSGRCV", Const, 0}, + {"SYS_MSGRCV_NOCANCEL", Const, 0}, + {"SYS_MSGSND", Const, 0}, + {"SYS_MSGSND_NOCANCEL", Const, 0}, + {"SYS_MSGSYS", Const, 0}, + {"SYS_MSYNC", Const, 0}, + {"SYS_MSYNC_NOCANCEL", Const, 0}, + {"SYS_MUNLOCK", Const, 0}, + {"SYS_MUNLOCKALL", Const, 0}, + {"SYS_MUNMAP", Const, 0}, + {"SYS_NAME_TO_HANDLE_AT", Const, 0}, + {"SYS_NANOSLEEP", Const, 0}, + {"SYS_NEWFSTATAT", Const, 0}, + {"SYS_NFSCLNT", Const, 0}, + {"SYS_NFSSERVCTL", Const, 0}, + {"SYS_NFSSVC", Const, 0}, + {"SYS_NFSTAT", Const, 0}, + {"SYS_NICE", Const, 0}, + {"SYS_NLM_SYSCALL", Const, 14}, + {"SYS_NLSTAT", Const, 0}, + {"SYS_NMOUNT", Const, 0}, + {"SYS_NSTAT", Const, 0}, + {"SYS_NTP_ADJTIME", Const, 0}, + {"SYS_NTP_GETTIME", Const, 0}, + {"SYS_NUMA_GETAFFINITY", Const, 14}, + {"SYS_NUMA_SETAFFINITY", Const, 14}, + {"SYS_OABI_SYSCALL_BASE", Const, 0}, + {"SYS_OBREAK", Const, 0}, + {"SYS_OLDFSTAT", Const, 0}, + {"SYS_OLDLSTAT", Const, 0}, + {"SYS_OLDOLDUNAME", Const, 0}, + {"SYS_OLDSTAT", Const, 0}, + {"SYS_OLDUNAME", Const, 0}, + {"SYS_OPEN", Const, 0}, + {"SYS_OPENAT", Const, 0}, + {"SYS_OPENBSD_POLL", Const, 0}, + {"SYS_OPEN_BY_HANDLE_AT", Const, 0}, + {"SYS_OPEN_DPROTECTED_NP", Const, 16}, + {"SYS_OPEN_EXTENDED", Const, 0}, + {"SYS_OPEN_NOCANCEL", Const, 0}, + {"SYS_OVADVISE", Const, 0}, + {"SYS_PACCEPT", Const, 1}, + {"SYS_PATHCONF", Const, 0}, + {"SYS_PAUSE", Const, 0}, + {"SYS_PCICONFIG_IOBASE", Const, 0}, + {"SYS_PCICONFIG_READ", Const, 0}, + {"SYS_PCICONFIG_WRITE", Const, 0}, + {"SYS_PDFORK", Const, 0}, + {"SYS_PDGETPID", Const, 0}, + {"SYS_PDKILL", Const, 0}, + {"SYS_PERF_EVENT_OPEN", Const, 0}, + {"SYS_PERSONALITY", Const, 0}, + {"SYS_PID_HIBERNATE", Const, 0}, + {"SYS_PID_RESUME", Const, 0}, + {"SYS_PID_SHUTDOWN_SOCKETS", Const, 0}, + {"SYS_PID_SUSPEND", Const, 0}, + {"SYS_PIPE", Const, 0}, + {"SYS_PIPE2", Const, 0}, + {"SYS_PIVOT_ROOT", Const, 0}, + {"SYS_PMC_CONTROL", Const, 1}, + {"SYS_PMC_GET_INFO", Const, 1}, + {"SYS_POLL", Const, 0}, + {"SYS_POLLTS", Const, 1}, + {"SYS_POLL_NOCANCEL", Const, 0}, + {"SYS_POSIX_FADVISE", Const, 0}, + {"SYS_POSIX_FALLOCATE", Const, 0}, + {"SYS_POSIX_OPENPT", Const, 0}, + {"SYS_POSIX_SPAWN", Const, 0}, + {"SYS_PPOLL", Const, 0}, + {"SYS_PRCTL", Const, 0}, + {"SYS_PREAD", Const, 0}, + {"SYS_PREAD64", Const, 0}, + {"SYS_PREADV", Const, 0}, + {"SYS_PREAD_NOCANCEL", Const, 0}, + {"SYS_PRLIMIT64", Const, 0}, + {"SYS_PROCCTL", Const, 3}, + {"SYS_PROCESS_POLICY", Const, 0}, + {"SYS_PROCESS_VM_READV", Const, 0}, + {"SYS_PROCESS_VM_WRITEV", Const, 0}, + {"SYS_PROC_INFO", Const, 0}, + {"SYS_PROF", Const, 0}, + {"SYS_PROFIL", Const, 0}, + {"SYS_PSELECT", Const, 0}, + {"SYS_PSELECT6", Const, 0}, + {"SYS_PSET_ASSIGN", Const, 1}, + {"SYS_PSET_CREATE", Const, 1}, + {"SYS_PSET_DESTROY", Const, 1}, + {"SYS_PSYNCH_CVBROAD", Const, 0}, + {"SYS_PSYNCH_CVCLRPREPOST", Const, 0}, + {"SYS_PSYNCH_CVSIGNAL", Const, 0}, + {"SYS_PSYNCH_CVWAIT", Const, 0}, + {"SYS_PSYNCH_MUTEXDROP", Const, 0}, + {"SYS_PSYNCH_MUTEXWAIT", Const, 0}, + {"SYS_PSYNCH_RW_DOWNGRADE", Const, 0}, + {"SYS_PSYNCH_RW_LONGRDLOCK", Const, 0}, + {"SYS_PSYNCH_RW_RDLOCK", Const, 0}, + {"SYS_PSYNCH_RW_UNLOCK", Const, 0}, + {"SYS_PSYNCH_RW_UNLOCK2", Const, 0}, + {"SYS_PSYNCH_RW_UPGRADE", Const, 0}, + {"SYS_PSYNCH_RW_WRLOCK", Const, 0}, + {"SYS_PSYNCH_RW_YIELDWRLOCK", Const, 0}, + {"SYS_PTRACE", Const, 0}, + {"SYS_PUTPMSG", Const, 0}, + {"SYS_PWRITE", Const, 0}, + {"SYS_PWRITE64", Const, 0}, + {"SYS_PWRITEV", Const, 0}, + {"SYS_PWRITE_NOCANCEL", Const, 0}, + {"SYS_QUERY_MODULE", Const, 0}, + {"SYS_QUOTACTL", Const, 0}, + {"SYS_RASCTL", Const, 1}, + {"SYS_RCTL_ADD_RULE", Const, 0}, + {"SYS_RCTL_GET_LIMITS", Const, 0}, + {"SYS_RCTL_GET_RACCT", Const, 0}, + {"SYS_RCTL_GET_RULES", Const, 0}, + {"SYS_RCTL_REMOVE_RULE", Const, 0}, + {"SYS_READ", Const, 0}, + {"SYS_READAHEAD", Const, 0}, + {"SYS_READDIR", Const, 0}, + {"SYS_READLINK", Const, 0}, + {"SYS_READLINKAT", Const, 0}, + {"SYS_READV", Const, 0}, + {"SYS_READV_NOCANCEL", Const, 0}, + {"SYS_READ_NOCANCEL", Const, 0}, + {"SYS_REBOOT", Const, 0}, + {"SYS_RECV", Const, 0}, + {"SYS_RECVFROM", Const, 0}, + {"SYS_RECVFROM_NOCANCEL", Const, 0}, + {"SYS_RECVMMSG", Const, 0}, + {"SYS_RECVMSG", Const, 0}, + {"SYS_RECVMSG_NOCANCEL", Const, 0}, + {"SYS_REMAP_FILE_PAGES", Const, 0}, + {"SYS_REMOVEXATTR", Const, 0}, + {"SYS_RENAME", Const, 0}, + {"SYS_RENAMEAT", Const, 0}, + {"SYS_REQUEST_KEY", Const, 0}, + {"SYS_RESTART_SYSCALL", Const, 0}, + {"SYS_REVOKE", Const, 0}, + {"SYS_RFORK", Const, 0}, + {"SYS_RMDIR", Const, 0}, + {"SYS_RTPRIO", Const, 0}, + {"SYS_RTPRIO_THREAD", Const, 0}, + {"SYS_RT_SIGACTION", Const, 0}, + {"SYS_RT_SIGPENDING", Const, 0}, + {"SYS_RT_SIGPROCMASK", Const, 0}, + {"SYS_RT_SIGQUEUEINFO", Const, 0}, + {"SYS_RT_SIGRETURN", Const, 0}, + {"SYS_RT_SIGSUSPEND", Const, 0}, + {"SYS_RT_SIGTIMEDWAIT", Const, 0}, + {"SYS_RT_TGSIGQUEUEINFO", Const, 0}, + {"SYS_SBRK", Const, 0}, + {"SYS_SCHED_GETAFFINITY", Const, 0}, + {"SYS_SCHED_GETPARAM", Const, 0}, + {"SYS_SCHED_GETSCHEDULER", Const, 0}, + {"SYS_SCHED_GET_PRIORITY_MAX", Const, 0}, + {"SYS_SCHED_GET_PRIORITY_MIN", Const, 0}, + {"SYS_SCHED_RR_GET_INTERVAL", Const, 0}, + {"SYS_SCHED_SETAFFINITY", Const, 0}, + {"SYS_SCHED_SETPARAM", Const, 0}, + {"SYS_SCHED_SETSCHEDULER", Const, 0}, + {"SYS_SCHED_YIELD", Const, 0}, + {"SYS_SCTP_GENERIC_RECVMSG", Const, 0}, + {"SYS_SCTP_GENERIC_SENDMSG", Const, 0}, + {"SYS_SCTP_GENERIC_SENDMSG_IOV", Const, 0}, + {"SYS_SCTP_PEELOFF", Const, 0}, + {"SYS_SEARCHFS", Const, 0}, + {"SYS_SECURITY", Const, 0}, + {"SYS_SELECT", Const, 0}, + {"SYS_SELECT_NOCANCEL", Const, 0}, + {"SYS_SEMCONFIG", Const, 1}, + {"SYS_SEMCTL", Const, 0}, + {"SYS_SEMGET", Const, 0}, + {"SYS_SEMOP", Const, 0}, + {"SYS_SEMSYS", Const, 0}, + {"SYS_SEMTIMEDOP", Const, 0}, + {"SYS_SEM_CLOSE", Const, 0}, + {"SYS_SEM_DESTROY", Const, 0}, + {"SYS_SEM_GETVALUE", Const, 0}, + {"SYS_SEM_INIT", Const, 0}, + {"SYS_SEM_OPEN", Const, 0}, + {"SYS_SEM_POST", Const, 0}, + {"SYS_SEM_TRYWAIT", Const, 0}, + {"SYS_SEM_UNLINK", Const, 0}, + {"SYS_SEM_WAIT", Const, 0}, + {"SYS_SEM_WAIT_NOCANCEL", Const, 0}, + {"SYS_SEND", Const, 0}, + {"SYS_SENDFILE", Const, 0}, + {"SYS_SENDFILE64", Const, 0}, + {"SYS_SENDMMSG", Const, 0}, + {"SYS_SENDMSG", Const, 0}, + {"SYS_SENDMSG_NOCANCEL", Const, 0}, + {"SYS_SENDTO", Const, 0}, + {"SYS_SENDTO_NOCANCEL", Const, 0}, + {"SYS_SETATTRLIST", Const, 0}, + {"SYS_SETAUDIT", Const, 0}, + {"SYS_SETAUDIT_ADDR", Const, 0}, + {"SYS_SETAUID", Const, 0}, + {"SYS_SETCONTEXT", Const, 0}, + {"SYS_SETDOMAINNAME", Const, 0}, + {"SYS_SETEGID", Const, 0}, + {"SYS_SETEUID", Const, 0}, + {"SYS_SETFIB", Const, 0}, + {"SYS_SETFSGID", Const, 0}, + {"SYS_SETFSGID32", Const, 0}, + {"SYS_SETFSUID", Const, 0}, + {"SYS_SETFSUID32", Const, 0}, + {"SYS_SETGID", Const, 0}, + {"SYS_SETGID32", Const, 0}, + {"SYS_SETGROUPS", Const, 0}, + {"SYS_SETGROUPS32", Const, 0}, + {"SYS_SETHOSTNAME", Const, 0}, + {"SYS_SETITIMER", Const, 0}, + {"SYS_SETLCID", Const, 0}, + {"SYS_SETLOGIN", Const, 0}, + {"SYS_SETLOGINCLASS", Const, 0}, + {"SYS_SETNS", Const, 0}, + {"SYS_SETPGID", Const, 0}, + {"SYS_SETPRIORITY", Const, 0}, + {"SYS_SETPRIVEXEC", Const, 0}, + {"SYS_SETREGID", Const, 0}, + {"SYS_SETREGID32", Const, 0}, + {"SYS_SETRESGID", Const, 0}, + {"SYS_SETRESGID32", Const, 0}, + {"SYS_SETRESUID", Const, 0}, + {"SYS_SETRESUID32", Const, 0}, + {"SYS_SETREUID", Const, 0}, + {"SYS_SETREUID32", Const, 0}, + {"SYS_SETRLIMIT", Const, 0}, + {"SYS_SETRTABLE", Const, 1}, + {"SYS_SETSGROUPS", Const, 0}, + {"SYS_SETSID", Const, 0}, + {"SYS_SETSOCKOPT", Const, 0}, + {"SYS_SETTID", Const, 0}, + {"SYS_SETTID_WITH_PID", Const, 0}, + {"SYS_SETTIMEOFDAY", Const, 0}, + {"SYS_SETUID", Const, 0}, + {"SYS_SETUID32", Const, 0}, + {"SYS_SETWGROUPS", Const, 0}, + {"SYS_SETXATTR", Const, 0}, + {"SYS_SET_MEMPOLICY", Const, 0}, + {"SYS_SET_ROBUST_LIST", Const, 0}, + {"SYS_SET_THREAD_AREA", Const, 0}, + {"SYS_SET_TID_ADDRESS", Const, 0}, + {"SYS_SGETMASK", Const, 0}, + {"SYS_SHARED_REGION_CHECK_NP", Const, 0}, + {"SYS_SHARED_REGION_MAP_AND_SLIDE_NP", Const, 0}, + {"SYS_SHMAT", Const, 0}, + {"SYS_SHMCTL", Const, 0}, + {"SYS_SHMDT", Const, 0}, + {"SYS_SHMGET", Const, 0}, + {"SYS_SHMSYS", Const, 0}, + {"SYS_SHM_OPEN", Const, 0}, + {"SYS_SHM_UNLINK", Const, 0}, + {"SYS_SHUTDOWN", Const, 0}, + {"SYS_SIGACTION", Const, 0}, + {"SYS_SIGALTSTACK", Const, 0}, + {"SYS_SIGNAL", Const, 0}, + {"SYS_SIGNALFD", Const, 0}, + {"SYS_SIGNALFD4", Const, 0}, + {"SYS_SIGPENDING", Const, 0}, + {"SYS_SIGPROCMASK", Const, 0}, + {"SYS_SIGQUEUE", Const, 0}, + {"SYS_SIGQUEUEINFO", Const, 1}, + {"SYS_SIGRETURN", Const, 0}, + {"SYS_SIGSUSPEND", Const, 0}, + {"SYS_SIGSUSPEND_NOCANCEL", Const, 0}, + {"SYS_SIGTIMEDWAIT", Const, 0}, + {"SYS_SIGWAIT", Const, 0}, + {"SYS_SIGWAITINFO", Const, 0}, + {"SYS_SOCKET", Const, 0}, + {"SYS_SOCKETCALL", Const, 0}, + {"SYS_SOCKETPAIR", Const, 0}, + {"SYS_SPLICE", Const, 0}, + {"SYS_SSETMASK", Const, 0}, + {"SYS_SSTK", Const, 0}, + {"SYS_STACK_SNAPSHOT", Const, 0}, + {"SYS_STAT", Const, 0}, + {"SYS_STAT64", Const, 0}, + {"SYS_STAT64_EXTENDED", Const, 0}, + {"SYS_STATFS", Const, 0}, + {"SYS_STATFS64", Const, 0}, + {"SYS_STATV", Const, 0}, + {"SYS_STATVFS1", Const, 1}, + {"SYS_STAT_EXTENDED", Const, 0}, + {"SYS_STIME", Const, 0}, + {"SYS_STTY", Const, 0}, + {"SYS_SWAPCONTEXT", Const, 0}, + {"SYS_SWAPCTL", Const, 1}, + {"SYS_SWAPOFF", Const, 0}, + {"SYS_SWAPON", Const, 0}, + {"SYS_SYMLINK", Const, 0}, + {"SYS_SYMLINKAT", Const, 0}, + {"SYS_SYNC", Const, 0}, + {"SYS_SYNCFS", Const, 0}, + {"SYS_SYNC_FILE_RANGE", Const, 0}, + {"SYS_SYSARCH", Const, 0}, + {"SYS_SYSCALL", Const, 0}, + {"SYS_SYSCALL_BASE", Const, 0}, + {"SYS_SYSFS", Const, 0}, + {"SYS_SYSINFO", Const, 0}, + {"SYS_SYSLOG", Const, 0}, + {"SYS_TEE", Const, 0}, + {"SYS_TGKILL", Const, 0}, + {"SYS_THREAD_SELFID", Const, 0}, + {"SYS_THR_CREATE", Const, 0}, + {"SYS_THR_EXIT", Const, 0}, + {"SYS_THR_KILL", Const, 0}, + {"SYS_THR_KILL2", Const, 0}, + {"SYS_THR_NEW", Const, 0}, + {"SYS_THR_SELF", Const, 0}, + {"SYS_THR_SET_NAME", Const, 0}, + {"SYS_THR_SUSPEND", Const, 0}, + {"SYS_THR_WAKE", Const, 0}, + {"SYS_TIME", Const, 0}, + {"SYS_TIMERFD_CREATE", Const, 0}, + {"SYS_TIMERFD_GETTIME", Const, 0}, + {"SYS_TIMERFD_SETTIME", Const, 0}, + {"SYS_TIMER_CREATE", Const, 0}, + {"SYS_TIMER_DELETE", Const, 0}, + {"SYS_TIMER_GETOVERRUN", Const, 0}, + {"SYS_TIMER_GETTIME", Const, 0}, + {"SYS_TIMER_SETTIME", Const, 0}, + {"SYS_TIMES", Const, 0}, + {"SYS_TKILL", Const, 0}, + {"SYS_TRUNCATE", Const, 0}, + {"SYS_TRUNCATE64", Const, 0}, + {"SYS_TUXCALL", Const, 0}, + {"SYS_UGETRLIMIT", Const, 0}, + {"SYS_ULIMIT", Const, 0}, + {"SYS_UMASK", Const, 0}, + {"SYS_UMASK_EXTENDED", Const, 0}, + {"SYS_UMOUNT", Const, 0}, + {"SYS_UMOUNT2", Const, 0}, + {"SYS_UNAME", Const, 0}, + {"SYS_UNDELETE", Const, 0}, + {"SYS_UNLINK", Const, 0}, + {"SYS_UNLINKAT", Const, 0}, + {"SYS_UNMOUNT", Const, 0}, + {"SYS_UNSHARE", Const, 0}, + {"SYS_USELIB", Const, 0}, + {"SYS_USTAT", Const, 0}, + {"SYS_UTIME", Const, 0}, + {"SYS_UTIMENSAT", Const, 0}, + {"SYS_UTIMES", Const, 0}, + {"SYS_UTRACE", Const, 0}, + {"SYS_UUIDGEN", Const, 0}, + {"SYS_VADVISE", Const, 1}, + {"SYS_VFORK", Const, 0}, + {"SYS_VHANGUP", Const, 0}, + {"SYS_VM86", Const, 0}, + {"SYS_VM86OLD", Const, 0}, + {"SYS_VMSPLICE", Const, 0}, + {"SYS_VM_PRESSURE_MONITOR", Const, 0}, + {"SYS_VSERVER", Const, 0}, + {"SYS_WAIT4", Const, 0}, + {"SYS_WAIT4_NOCANCEL", Const, 0}, + {"SYS_WAIT6", Const, 1}, + {"SYS_WAITEVENT", Const, 0}, + {"SYS_WAITID", Const, 0}, + {"SYS_WAITID_NOCANCEL", Const, 0}, + {"SYS_WAITPID", Const, 0}, + {"SYS_WATCHEVENT", Const, 0}, + {"SYS_WORKQ_KERNRETURN", Const, 0}, + {"SYS_WORKQ_OPEN", Const, 0}, + {"SYS_WRITE", Const, 0}, + {"SYS_WRITEV", Const, 0}, + {"SYS_WRITEV_NOCANCEL", Const, 0}, + {"SYS_WRITE_NOCANCEL", Const, 0}, + {"SYS_YIELD", Const, 0}, + {"SYS__LLSEEK", Const, 0}, + {"SYS__LWP_CONTINUE", Const, 1}, + {"SYS__LWP_CREATE", Const, 1}, + {"SYS__LWP_CTL", Const, 1}, + {"SYS__LWP_DETACH", Const, 1}, + {"SYS__LWP_EXIT", Const, 1}, + {"SYS__LWP_GETNAME", Const, 1}, + {"SYS__LWP_GETPRIVATE", Const, 1}, + {"SYS__LWP_KILL", Const, 1}, + {"SYS__LWP_PARK", Const, 1}, + {"SYS__LWP_SELF", Const, 1}, + {"SYS__LWP_SETNAME", Const, 1}, + {"SYS__LWP_SETPRIVATE", Const, 1}, + {"SYS__LWP_SUSPEND", Const, 1}, + {"SYS__LWP_UNPARK", Const, 1}, + {"SYS__LWP_UNPARK_ALL", Const, 1}, + {"SYS__LWP_WAIT", Const, 1}, + {"SYS__LWP_WAKEUP", Const, 1}, + {"SYS__NEWSELECT", Const, 0}, + {"SYS__PSET_BIND", Const, 1}, + {"SYS__SCHED_GETAFFINITY", Const, 1}, + {"SYS__SCHED_GETPARAM", Const, 1}, + {"SYS__SCHED_SETAFFINITY", Const, 1}, + {"SYS__SCHED_SETPARAM", Const, 1}, + {"SYS__SYSCTL", Const, 0}, + {"SYS__UMTX_LOCK", Const, 0}, + {"SYS__UMTX_OP", Const, 0}, + {"SYS__UMTX_UNLOCK", Const, 0}, + {"SYS___ACL_ACLCHECK_FD", Const, 0}, + {"SYS___ACL_ACLCHECK_FILE", Const, 0}, + {"SYS___ACL_ACLCHECK_LINK", Const, 0}, + {"SYS___ACL_DELETE_FD", Const, 0}, + {"SYS___ACL_DELETE_FILE", Const, 0}, + {"SYS___ACL_DELETE_LINK", Const, 0}, + {"SYS___ACL_GET_FD", Const, 0}, + {"SYS___ACL_GET_FILE", Const, 0}, + {"SYS___ACL_GET_LINK", Const, 0}, + {"SYS___ACL_SET_FD", Const, 0}, + {"SYS___ACL_SET_FILE", Const, 0}, + {"SYS___ACL_SET_LINK", Const, 0}, + {"SYS___CAP_RIGHTS_GET", Const, 14}, + {"SYS___CLONE", Const, 1}, + {"SYS___DISABLE_THREADSIGNAL", Const, 0}, + {"SYS___GETCWD", Const, 0}, + {"SYS___GETLOGIN", Const, 1}, + {"SYS___GET_TCB", Const, 1}, + {"SYS___MAC_EXECVE", Const, 0}, + {"SYS___MAC_GETFSSTAT", Const, 0}, + {"SYS___MAC_GET_FD", Const, 0}, + {"SYS___MAC_GET_FILE", Const, 0}, + {"SYS___MAC_GET_LCID", Const, 0}, + {"SYS___MAC_GET_LCTX", Const, 0}, + {"SYS___MAC_GET_LINK", Const, 0}, + {"SYS___MAC_GET_MOUNT", Const, 0}, + {"SYS___MAC_GET_PID", Const, 0}, + {"SYS___MAC_GET_PROC", Const, 0}, + {"SYS___MAC_MOUNT", Const, 0}, + {"SYS___MAC_SET_FD", Const, 0}, + {"SYS___MAC_SET_FILE", Const, 0}, + {"SYS___MAC_SET_LCTX", Const, 0}, + {"SYS___MAC_SET_LINK", Const, 0}, + {"SYS___MAC_SET_PROC", Const, 0}, + {"SYS___MAC_SYSCALL", Const, 0}, + {"SYS___OLD_SEMWAIT_SIGNAL", Const, 0}, + {"SYS___OLD_SEMWAIT_SIGNAL_NOCANCEL", Const, 0}, + {"SYS___POSIX_CHOWN", Const, 1}, + {"SYS___POSIX_FCHOWN", Const, 1}, + {"SYS___POSIX_LCHOWN", Const, 1}, + {"SYS___POSIX_RENAME", Const, 1}, + {"SYS___PTHREAD_CANCELED", Const, 0}, + {"SYS___PTHREAD_CHDIR", Const, 0}, + {"SYS___PTHREAD_FCHDIR", Const, 0}, + {"SYS___PTHREAD_KILL", Const, 0}, + {"SYS___PTHREAD_MARKCANCEL", Const, 0}, + {"SYS___PTHREAD_SIGMASK", Const, 0}, + {"SYS___QUOTACTL", Const, 1}, + {"SYS___SEMCTL", Const, 1}, + {"SYS___SEMWAIT_SIGNAL", Const, 0}, + {"SYS___SEMWAIT_SIGNAL_NOCANCEL", Const, 0}, + {"SYS___SETLOGIN", Const, 1}, + {"SYS___SETUGID", Const, 0}, + {"SYS___SET_TCB", Const, 1}, + {"SYS___SIGACTION_SIGTRAMP", Const, 1}, + {"SYS___SIGTIMEDWAIT", Const, 1}, + {"SYS___SIGWAIT", Const, 0}, + {"SYS___SIGWAIT_NOCANCEL", Const, 0}, + {"SYS___SYSCTL", Const, 0}, + {"SYS___TFORK", Const, 1}, + {"SYS___THREXIT", Const, 1}, + {"SYS___THRSIGDIVERT", Const, 1}, + {"SYS___THRSLEEP", Const, 1}, + {"SYS___THRWAKEUP", Const, 1}, + {"S_ARCH1", Const, 1}, + {"S_ARCH2", Const, 1}, + {"S_BLKSIZE", Const, 0}, + {"S_IEXEC", Const, 0}, + {"S_IFBLK", Const, 0}, + {"S_IFCHR", Const, 0}, + {"S_IFDIR", Const, 0}, + {"S_IFIFO", Const, 0}, + {"S_IFLNK", Const, 0}, + {"S_IFMT", Const, 0}, + {"S_IFREG", Const, 0}, + {"S_IFSOCK", Const, 0}, + {"S_IFWHT", Const, 0}, + {"S_IREAD", Const, 0}, + {"S_IRGRP", Const, 0}, + {"S_IROTH", Const, 0}, + {"S_IRUSR", Const, 0}, + {"S_IRWXG", Const, 0}, + {"S_IRWXO", Const, 0}, + {"S_IRWXU", Const, 0}, + {"S_ISGID", Const, 0}, + {"S_ISTXT", Const, 0}, + {"S_ISUID", Const, 0}, + {"S_ISVTX", Const, 0}, + {"S_IWGRP", Const, 0}, + {"S_IWOTH", Const, 0}, + {"S_IWRITE", Const, 0}, + {"S_IWUSR", Const, 0}, + {"S_IXGRP", Const, 0}, + {"S_IXOTH", Const, 0}, + {"S_IXUSR", Const, 0}, + {"S_LOGIN_SET", Const, 1}, + {"SecurityAttributes", Type, 0}, + {"SecurityAttributes.InheritHandle", Field, 0}, + {"SecurityAttributes.Length", Field, 0}, + {"SecurityAttributes.SecurityDescriptor", Field, 0}, + {"Seek", Func, 0}, + {"Select", Func, 0}, + {"Sendfile", Func, 0}, + {"Sendmsg", Func, 0}, + {"SendmsgN", Func, 3}, + {"Sendto", Func, 0}, + {"Servent", Type, 0}, + {"Servent.Aliases", Field, 0}, + {"Servent.Name", Field, 0}, + {"Servent.Port", Field, 0}, + {"Servent.Proto", Field, 0}, + {"SetBpf", Func, 0}, + {"SetBpfBuflen", Func, 0}, + {"SetBpfDatalink", Func, 0}, + {"SetBpfHeadercmpl", Func, 0}, + {"SetBpfImmediate", Func, 0}, + {"SetBpfInterface", Func, 0}, + {"SetBpfPromisc", Func, 0}, + {"SetBpfTimeout", Func, 0}, + {"SetCurrentDirectory", Func, 0}, + {"SetEndOfFile", Func, 0}, + {"SetEnvironmentVariable", Func, 0}, + {"SetFileAttributes", Func, 0}, + {"SetFileCompletionNotificationModes", Func, 2}, + {"SetFilePointer", Func, 0}, + {"SetFileTime", Func, 0}, + {"SetHandleInformation", Func, 0}, + {"SetKevent", Func, 0}, + {"SetLsfPromisc", Func, 0}, + {"SetNonblock", Func, 0}, + {"Setdomainname", Func, 0}, + {"Setegid", Func, 0}, + {"Setenv", Func, 0}, + {"Seteuid", Func, 0}, + {"Setfsgid", Func, 0}, + {"Setfsuid", Func, 0}, + {"Setgid", Func, 0}, + {"Setgroups", Func, 0}, + {"Sethostname", Func, 0}, + {"Setlogin", Func, 0}, + {"Setpgid", Func, 0}, + {"Setpriority", Func, 0}, + {"Setprivexec", Func, 0}, + {"Setregid", Func, 0}, + {"Setresgid", Func, 0}, + {"Setresuid", Func, 0}, + {"Setreuid", Func, 0}, + {"Setrlimit", Func, 0}, + {"Setsid", Func, 0}, + {"Setsockopt", Func, 0}, + {"SetsockoptByte", Func, 0}, + {"SetsockoptICMPv6Filter", Func, 2}, + {"SetsockoptIPMreq", Func, 0}, + {"SetsockoptIPMreqn", Func, 0}, + {"SetsockoptIPv6Mreq", Func, 0}, + {"SetsockoptInet4Addr", Func, 0}, + {"SetsockoptInt", Func, 0}, + {"SetsockoptLinger", Func, 0}, + {"SetsockoptString", Func, 0}, + {"SetsockoptTimeval", Func, 0}, + {"Settimeofday", Func, 0}, + {"Setuid", Func, 0}, + {"Setxattr", Func, 1}, + {"Shutdown", Func, 0}, + {"SidTypeAlias", Const, 0}, + {"SidTypeComputer", Const, 0}, + {"SidTypeDeletedAccount", Const, 0}, + {"SidTypeDomain", Const, 0}, + {"SidTypeGroup", Const, 0}, + {"SidTypeInvalid", Const, 0}, + {"SidTypeLabel", Const, 0}, + {"SidTypeUnknown", Const, 0}, + {"SidTypeUser", Const, 0}, + {"SidTypeWellKnownGroup", Const, 0}, + {"Signal", Type, 0}, + {"SizeofBpfHdr", Const, 0}, + {"SizeofBpfInsn", Const, 0}, + {"SizeofBpfProgram", Const, 0}, + {"SizeofBpfStat", Const, 0}, + {"SizeofBpfVersion", Const, 0}, + {"SizeofBpfZbuf", Const, 0}, + {"SizeofBpfZbufHeader", Const, 0}, + {"SizeofCmsghdr", Const, 0}, + {"SizeofICMPv6Filter", Const, 2}, + {"SizeofIPMreq", Const, 0}, + {"SizeofIPMreqn", Const, 0}, + {"SizeofIPv6MTUInfo", Const, 2}, + {"SizeofIPv6Mreq", Const, 0}, + {"SizeofIfAddrmsg", Const, 0}, + {"SizeofIfAnnounceMsghdr", Const, 1}, + {"SizeofIfData", Const, 0}, + {"SizeofIfInfomsg", Const, 0}, + {"SizeofIfMsghdr", Const, 0}, + {"SizeofIfaMsghdr", Const, 0}, + {"SizeofIfmaMsghdr", Const, 0}, + {"SizeofIfmaMsghdr2", Const, 0}, + {"SizeofInet4Pktinfo", Const, 0}, + {"SizeofInet6Pktinfo", Const, 0}, + {"SizeofInotifyEvent", Const, 0}, + {"SizeofLinger", Const, 0}, + {"SizeofMsghdr", Const, 0}, + {"SizeofNlAttr", Const, 0}, + {"SizeofNlMsgerr", Const, 0}, + {"SizeofNlMsghdr", Const, 0}, + {"SizeofRtAttr", Const, 0}, + {"SizeofRtGenmsg", Const, 0}, + {"SizeofRtMetrics", Const, 0}, + {"SizeofRtMsg", Const, 0}, + {"SizeofRtMsghdr", Const, 0}, + {"SizeofRtNexthop", Const, 0}, + {"SizeofSockFilter", Const, 0}, + {"SizeofSockFprog", Const, 0}, + {"SizeofSockaddrAny", Const, 0}, + {"SizeofSockaddrDatalink", Const, 0}, + {"SizeofSockaddrInet4", Const, 0}, + {"SizeofSockaddrInet6", Const, 0}, + {"SizeofSockaddrLinklayer", Const, 0}, + {"SizeofSockaddrNetlink", Const, 0}, + {"SizeofSockaddrUnix", Const, 0}, + {"SizeofTCPInfo", Const, 1}, + {"SizeofUcred", Const, 0}, + {"SlicePtrFromStrings", Func, 1}, + {"SockFilter", Type, 0}, + {"SockFilter.Code", Field, 0}, + {"SockFilter.Jf", Field, 0}, + {"SockFilter.Jt", Field, 0}, + {"SockFilter.K", Field, 0}, + {"SockFprog", Type, 0}, + {"SockFprog.Filter", Field, 0}, + {"SockFprog.Len", Field, 0}, + {"SockFprog.Pad_cgo_0", Field, 0}, + {"Sockaddr", Type, 0}, + {"SockaddrDatalink", Type, 0}, + {"SockaddrDatalink.Alen", Field, 0}, + {"SockaddrDatalink.Data", Field, 0}, + {"SockaddrDatalink.Family", Field, 0}, + {"SockaddrDatalink.Index", Field, 0}, + {"SockaddrDatalink.Len", Field, 0}, + {"SockaddrDatalink.Nlen", Field, 0}, + {"SockaddrDatalink.Slen", Field, 0}, + {"SockaddrDatalink.Type", Field, 0}, + {"SockaddrGen", Type, 0}, + {"SockaddrInet4", Type, 0}, + {"SockaddrInet4.Addr", Field, 0}, + {"SockaddrInet4.Port", Field, 0}, + {"SockaddrInet6", Type, 0}, + {"SockaddrInet6.Addr", Field, 0}, + {"SockaddrInet6.Port", Field, 0}, + {"SockaddrInet6.ZoneId", Field, 0}, + {"SockaddrLinklayer", Type, 0}, + {"SockaddrLinklayer.Addr", Field, 0}, + {"SockaddrLinklayer.Halen", Field, 0}, + {"SockaddrLinklayer.Hatype", Field, 0}, + {"SockaddrLinklayer.Ifindex", Field, 0}, + {"SockaddrLinklayer.Pkttype", Field, 0}, + {"SockaddrLinklayer.Protocol", Field, 0}, + {"SockaddrNetlink", Type, 0}, + {"SockaddrNetlink.Family", Field, 0}, + {"SockaddrNetlink.Groups", Field, 0}, + {"SockaddrNetlink.Pad", Field, 0}, + {"SockaddrNetlink.Pid", Field, 0}, + {"SockaddrUnix", Type, 0}, + {"SockaddrUnix.Name", Field, 0}, + {"Socket", Func, 0}, + {"SocketControlMessage", Type, 0}, + {"SocketControlMessage.Data", Field, 0}, + {"SocketControlMessage.Header", Field, 0}, + {"SocketDisableIPv6", Var, 0}, + {"Socketpair", Func, 0}, + {"Splice", Func, 0}, + {"StartProcess", Func, 0}, + {"StartupInfo", Type, 0}, + {"StartupInfo.Cb", Field, 0}, + {"StartupInfo.Desktop", Field, 0}, + {"StartupInfo.FillAttribute", Field, 0}, + {"StartupInfo.Flags", Field, 0}, + {"StartupInfo.ShowWindow", Field, 0}, + {"StartupInfo.StdErr", Field, 0}, + {"StartupInfo.StdInput", Field, 0}, + {"StartupInfo.StdOutput", Field, 0}, + {"StartupInfo.Title", Field, 0}, + {"StartupInfo.X", Field, 0}, + {"StartupInfo.XCountChars", Field, 0}, + {"StartupInfo.XSize", Field, 0}, + {"StartupInfo.Y", Field, 0}, + {"StartupInfo.YCountChars", Field, 0}, + {"StartupInfo.YSize", Field, 0}, + {"Stat", Func, 0}, + {"Stat_t", Type, 0}, + {"Stat_t.Atim", Field, 0}, + {"Stat_t.Atim_ext", Field, 12}, + {"Stat_t.Atimespec", Field, 0}, + {"Stat_t.Birthtimespec", Field, 0}, + {"Stat_t.Blksize", Field, 0}, + {"Stat_t.Blocks", Field, 0}, + {"Stat_t.Btim_ext", Field, 12}, + {"Stat_t.Ctim", Field, 0}, + {"Stat_t.Ctim_ext", Field, 12}, + {"Stat_t.Ctimespec", Field, 0}, + {"Stat_t.Dev", Field, 0}, + {"Stat_t.Flags", Field, 0}, + {"Stat_t.Gen", Field, 0}, + {"Stat_t.Gid", Field, 0}, + {"Stat_t.Ino", Field, 0}, + {"Stat_t.Lspare", Field, 0}, + {"Stat_t.Lspare0", Field, 2}, + {"Stat_t.Lspare1", Field, 2}, + {"Stat_t.Mode", Field, 0}, + {"Stat_t.Mtim", Field, 0}, + {"Stat_t.Mtim_ext", Field, 12}, + {"Stat_t.Mtimespec", Field, 0}, + {"Stat_t.Nlink", Field, 0}, + {"Stat_t.Pad_cgo_0", Field, 0}, + {"Stat_t.Pad_cgo_1", Field, 0}, + {"Stat_t.Pad_cgo_2", Field, 0}, + {"Stat_t.Padding0", Field, 12}, + {"Stat_t.Padding1", Field, 12}, + {"Stat_t.Qspare", Field, 0}, + {"Stat_t.Rdev", Field, 0}, + {"Stat_t.Size", Field, 0}, + {"Stat_t.Spare", Field, 2}, + {"Stat_t.Uid", Field, 0}, + {"Stat_t.X__pad0", Field, 0}, + {"Stat_t.X__pad1", Field, 0}, + {"Stat_t.X__pad2", Field, 0}, + {"Stat_t.X__st_birthtim", Field, 2}, + {"Stat_t.X__st_ino", Field, 0}, + {"Stat_t.X__unused", Field, 0}, + {"Statfs", Func, 0}, + {"Statfs_t", Type, 0}, + {"Statfs_t.Asyncreads", Field, 0}, + {"Statfs_t.Asyncwrites", Field, 0}, + {"Statfs_t.Bavail", Field, 0}, + {"Statfs_t.Bfree", Field, 0}, + {"Statfs_t.Blocks", Field, 0}, + {"Statfs_t.Bsize", Field, 0}, + {"Statfs_t.Charspare", Field, 0}, + {"Statfs_t.F_asyncreads", Field, 2}, + {"Statfs_t.F_asyncwrites", Field, 2}, + {"Statfs_t.F_bavail", Field, 2}, + {"Statfs_t.F_bfree", Field, 2}, + {"Statfs_t.F_blocks", Field, 2}, + {"Statfs_t.F_bsize", Field, 2}, + {"Statfs_t.F_ctime", Field, 2}, + {"Statfs_t.F_favail", Field, 2}, + {"Statfs_t.F_ffree", Field, 2}, + {"Statfs_t.F_files", Field, 2}, + {"Statfs_t.F_flags", Field, 2}, + {"Statfs_t.F_fsid", Field, 2}, + {"Statfs_t.F_fstypename", Field, 2}, + {"Statfs_t.F_iosize", Field, 2}, + {"Statfs_t.F_mntfromname", Field, 2}, + {"Statfs_t.F_mntfromspec", Field, 3}, + {"Statfs_t.F_mntonname", Field, 2}, + {"Statfs_t.F_namemax", Field, 2}, + {"Statfs_t.F_owner", Field, 2}, + {"Statfs_t.F_spare", Field, 2}, + {"Statfs_t.F_syncreads", Field, 2}, + {"Statfs_t.F_syncwrites", Field, 2}, + {"Statfs_t.Ffree", Field, 0}, + {"Statfs_t.Files", Field, 0}, + {"Statfs_t.Flags", Field, 0}, + {"Statfs_t.Frsize", Field, 0}, + {"Statfs_t.Fsid", Field, 0}, + {"Statfs_t.Fssubtype", Field, 0}, + {"Statfs_t.Fstypename", Field, 0}, + {"Statfs_t.Iosize", Field, 0}, + {"Statfs_t.Mntfromname", Field, 0}, + {"Statfs_t.Mntonname", Field, 0}, + {"Statfs_t.Mount_info", Field, 2}, + {"Statfs_t.Namelen", Field, 0}, + {"Statfs_t.Namemax", Field, 0}, + {"Statfs_t.Owner", Field, 0}, + {"Statfs_t.Pad_cgo_0", Field, 0}, + {"Statfs_t.Pad_cgo_1", Field, 2}, + {"Statfs_t.Reserved", Field, 0}, + {"Statfs_t.Spare", Field, 0}, + {"Statfs_t.Syncreads", Field, 0}, + {"Statfs_t.Syncwrites", Field, 0}, + {"Statfs_t.Type", Field, 0}, + {"Statfs_t.Version", Field, 0}, + {"Stderr", Var, 0}, + {"Stdin", Var, 0}, + {"Stdout", Var, 0}, + {"StringBytePtr", Func, 0}, + {"StringByteSlice", Func, 0}, + {"StringSlicePtr", Func, 0}, + {"StringToSid", Func, 0}, + {"StringToUTF16", Func, 0}, + {"StringToUTF16Ptr", Func, 0}, + {"Symlink", Func, 0}, + {"Sync", Func, 0}, + {"SyncFileRange", Func, 0}, + {"SysProcAttr", Type, 0}, + {"SysProcAttr.AdditionalInheritedHandles", Field, 17}, + {"SysProcAttr.AmbientCaps", Field, 9}, + {"SysProcAttr.CgroupFD", Field, 20}, + {"SysProcAttr.Chroot", Field, 0}, + {"SysProcAttr.Cloneflags", Field, 2}, + {"SysProcAttr.CmdLine", Field, 0}, + {"SysProcAttr.CreationFlags", Field, 1}, + {"SysProcAttr.Credential", Field, 0}, + {"SysProcAttr.Ctty", Field, 1}, + {"SysProcAttr.Foreground", Field, 5}, + {"SysProcAttr.GidMappings", Field, 4}, + {"SysProcAttr.GidMappingsEnableSetgroups", Field, 5}, + {"SysProcAttr.HideWindow", Field, 0}, + {"SysProcAttr.Jail", Field, 21}, + {"SysProcAttr.NoInheritHandles", Field, 16}, + {"SysProcAttr.Noctty", Field, 0}, + {"SysProcAttr.ParentProcess", Field, 17}, + {"SysProcAttr.Pdeathsig", Field, 0}, + {"SysProcAttr.Pgid", Field, 5}, + {"SysProcAttr.PidFD", Field, 22}, + {"SysProcAttr.ProcessAttributes", Field, 13}, + {"SysProcAttr.Ptrace", Field, 0}, + {"SysProcAttr.Setctty", Field, 0}, + {"SysProcAttr.Setpgid", Field, 0}, + {"SysProcAttr.Setsid", Field, 0}, + {"SysProcAttr.ThreadAttributes", Field, 13}, + {"SysProcAttr.Token", Field, 10}, + {"SysProcAttr.UidMappings", Field, 4}, + {"SysProcAttr.Unshareflags", Field, 7}, + {"SysProcAttr.UseCgroupFD", Field, 20}, + {"SysProcIDMap", Type, 4}, + {"SysProcIDMap.ContainerID", Field, 4}, + {"SysProcIDMap.HostID", Field, 4}, + {"SysProcIDMap.Size", Field, 4}, + {"Syscall", Func, 0}, + {"Syscall12", Func, 0}, + {"Syscall15", Func, 0}, + {"Syscall18", Func, 12}, + {"Syscall6", Func, 0}, + {"Syscall9", Func, 0}, + {"SyscallN", Func, 18}, + {"Sysctl", Func, 0}, + {"SysctlUint32", Func, 0}, + {"Sysctlnode", Type, 2}, + {"Sysctlnode.Flags", Field, 2}, + {"Sysctlnode.Name", Field, 2}, + {"Sysctlnode.Num", Field, 2}, + {"Sysctlnode.Un", Field, 2}, + {"Sysctlnode.Ver", Field, 2}, + {"Sysctlnode.X__rsvd", Field, 2}, + {"Sysctlnode.X_sysctl_desc", Field, 2}, + {"Sysctlnode.X_sysctl_func", Field, 2}, + {"Sysctlnode.X_sysctl_parent", Field, 2}, + {"Sysctlnode.X_sysctl_size", Field, 2}, + {"Sysinfo", Func, 0}, + {"Sysinfo_t", Type, 0}, + {"Sysinfo_t.Bufferram", Field, 0}, + {"Sysinfo_t.Freehigh", Field, 0}, + {"Sysinfo_t.Freeram", Field, 0}, + {"Sysinfo_t.Freeswap", Field, 0}, + {"Sysinfo_t.Loads", Field, 0}, + {"Sysinfo_t.Pad", Field, 0}, + {"Sysinfo_t.Pad_cgo_0", Field, 0}, + {"Sysinfo_t.Pad_cgo_1", Field, 0}, + {"Sysinfo_t.Procs", Field, 0}, + {"Sysinfo_t.Sharedram", Field, 0}, + {"Sysinfo_t.Totalhigh", Field, 0}, + {"Sysinfo_t.Totalram", Field, 0}, + {"Sysinfo_t.Totalswap", Field, 0}, + {"Sysinfo_t.Unit", Field, 0}, + {"Sysinfo_t.Uptime", Field, 0}, + {"Sysinfo_t.X_f", Field, 0}, + {"Systemtime", Type, 0}, + {"Systemtime.Day", Field, 0}, + {"Systemtime.DayOfWeek", Field, 0}, + {"Systemtime.Hour", Field, 0}, + {"Systemtime.Milliseconds", Field, 0}, + {"Systemtime.Minute", Field, 0}, + {"Systemtime.Month", Field, 0}, + {"Systemtime.Second", Field, 0}, + {"Systemtime.Year", Field, 0}, + {"TCGETS", Const, 0}, + {"TCIFLUSH", Const, 1}, + {"TCIOFLUSH", Const, 1}, + {"TCOFLUSH", Const, 1}, + {"TCPInfo", Type, 1}, + {"TCPInfo.Advmss", Field, 1}, + {"TCPInfo.Ato", Field, 1}, + {"TCPInfo.Backoff", Field, 1}, + {"TCPInfo.Ca_state", Field, 1}, + {"TCPInfo.Fackets", Field, 1}, + {"TCPInfo.Last_ack_recv", Field, 1}, + {"TCPInfo.Last_ack_sent", Field, 1}, + {"TCPInfo.Last_data_recv", Field, 1}, + {"TCPInfo.Last_data_sent", Field, 1}, + {"TCPInfo.Lost", Field, 1}, + {"TCPInfo.Options", Field, 1}, + {"TCPInfo.Pad_cgo_0", Field, 1}, + {"TCPInfo.Pmtu", Field, 1}, + {"TCPInfo.Probes", Field, 1}, + {"TCPInfo.Rcv_mss", Field, 1}, + {"TCPInfo.Rcv_rtt", Field, 1}, + {"TCPInfo.Rcv_space", Field, 1}, + {"TCPInfo.Rcv_ssthresh", Field, 1}, + {"TCPInfo.Reordering", Field, 1}, + {"TCPInfo.Retrans", Field, 1}, + {"TCPInfo.Retransmits", Field, 1}, + {"TCPInfo.Rto", Field, 1}, + {"TCPInfo.Rtt", Field, 1}, + {"TCPInfo.Rttvar", Field, 1}, + {"TCPInfo.Sacked", Field, 1}, + {"TCPInfo.Snd_cwnd", Field, 1}, + {"TCPInfo.Snd_mss", Field, 1}, + {"TCPInfo.Snd_ssthresh", Field, 1}, + {"TCPInfo.State", Field, 1}, + {"TCPInfo.Total_retrans", Field, 1}, + {"TCPInfo.Unacked", Field, 1}, + {"TCPKeepalive", Type, 3}, + {"TCPKeepalive.Interval", Field, 3}, + {"TCPKeepalive.OnOff", Field, 3}, + {"TCPKeepalive.Time", Field, 3}, + {"TCP_CA_NAME_MAX", Const, 0}, + {"TCP_CONGCTL", Const, 1}, + {"TCP_CONGESTION", Const, 0}, + {"TCP_CONNECTIONTIMEOUT", Const, 0}, + {"TCP_CORK", Const, 0}, + {"TCP_DEFER_ACCEPT", Const, 0}, + {"TCP_ENABLE_ECN", Const, 16}, + {"TCP_INFO", Const, 0}, + {"TCP_KEEPALIVE", Const, 0}, + {"TCP_KEEPCNT", Const, 0}, + {"TCP_KEEPIDLE", Const, 0}, + {"TCP_KEEPINIT", Const, 1}, + {"TCP_KEEPINTVL", Const, 0}, + {"TCP_LINGER2", Const, 0}, + {"TCP_MAXBURST", Const, 0}, + {"TCP_MAXHLEN", Const, 0}, + {"TCP_MAXOLEN", Const, 0}, + {"TCP_MAXSEG", Const, 0}, + {"TCP_MAXWIN", Const, 0}, + {"TCP_MAX_SACK", Const, 0}, + {"TCP_MAX_WINSHIFT", Const, 0}, + {"TCP_MD5SIG", Const, 0}, + {"TCP_MD5SIG_MAXKEYLEN", Const, 0}, + {"TCP_MINMSS", Const, 0}, + {"TCP_MINMSSOVERLOAD", Const, 0}, + {"TCP_MSS", Const, 0}, + {"TCP_NODELAY", Const, 0}, + {"TCP_NOOPT", Const, 0}, + {"TCP_NOPUSH", Const, 0}, + {"TCP_NOTSENT_LOWAT", Const, 16}, + {"TCP_NSTATES", Const, 1}, + {"TCP_QUICKACK", Const, 0}, + {"TCP_RXT_CONNDROPTIME", Const, 0}, + {"TCP_RXT_FINDROP", Const, 0}, + {"TCP_SACK_ENABLE", Const, 1}, + {"TCP_SENDMOREACKS", Const, 16}, + {"TCP_SYNCNT", Const, 0}, + {"TCP_VENDOR", Const, 3}, + {"TCP_WINDOW_CLAMP", Const, 0}, + {"TCSAFLUSH", Const, 1}, + {"TCSETS", Const, 0}, + {"TF_DISCONNECT", Const, 0}, + {"TF_REUSE_SOCKET", Const, 0}, + {"TF_USE_DEFAULT_WORKER", Const, 0}, + {"TF_USE_KERNEL_APC", Const, 0}, + {"TF_USE_SYSTEM_THREAD", Const, 0}, + {"TF_WRITE_BEHIND", Const, 0}, + {"TH32CS_INHERIT", Const, 4}, + {"TH32CS_SNAPALL", Const, 4}, + {"TH32CS_SNAPHEAPLIST", Const, 4}, + {"TH32CS_SNAPMODULE", Const, 4}, + {"TH32CS_SNAPMODULE32", Const, 4}, + {"TH32CS_SNAPPROCESS", Const, 4}, + {"TH32CS_SNAPTHREAD", Const, 4}, + {"TIME_ZONE_ID_DAYLIGHT", Const, 0}, + {"TIME_ZONE_ID_STANDARD", Const, 0}, + {"TIME_ZONE_ID_UNKNOWN", Const, 0}, + {"TIOCCBRK", Const, 0}, + {"TIOCCDTR", Const, 0}, + {"TIOCCONS", Const, 0}, + {"TIOCDCDTIMESTAMP", Const, 0}, + {"TIOCDRAIN", Const, 0}, + {"TIOCDSIMICROCODE", Const, 0}, + {"TIOCEXCL", Const, 0}, + {"TIOCEXT", Const, 0}, + {"TIOCFLAG_CDTRCTS", Const, 1}, + {"TIOCFLAG_CLOCAL", Const, 1}, + {"TIOCFLAG_CRTSCTS", Const, 1}, + {"TIOCFLAG_MDMBUF", Const, 1}, + {"TIOCFLAG_PPS", Const, 1}, + {"TIOCFLAG_SOFTCAR", Const, 1}, + {"TIOCFLUSH", Const, 0}, + {"TIOCGDEV", Const, 0}, + {"TIOCGDRAINWAIT", Const, 0}, + {"TIOCGETA", Const, 0}, + {"TIOCGETD", Const, 0}, + {"TIOCGFLAGS", Const, 1}, + {"TIOCGICOUNT", Const, 0}, + {"TIOCGLCKTRMIOS", Const, 0}, + {"TIOCGLINED", Const, 1}, + {"TIOCGPGRP", Const, 0}, + {"TIOCGPTN", Const, 0}, + {"TIOCGQSIZE", Const, 1}, + {"TIOCGRANTPT", Const, 1}, + {"TIOCGRS485", Const, 0}, + {"TIOCGSERIAL", Const, 0}, + {"TIOCGSID", Const, 0}, + {"TIOCGSIZE", Const, 1}, + {"TIOCGSOFTCAR", Const, 0}, + {"TIOCGTSTAMP", Const, 1}, + {"TIOCGWINSZ", Const, 0}, + {"TIOCINQ", Const, 0}, + {"TIOCIXOFF", Const, 0}, + {"TIOCIXON", Const, 0}, + {"TIOCLINUX", Const, 0}, + {"TIOCMBIC", Const, 0}, + {"TIOCMBIS", Const, 0}, + {"TIOCMGDTRWAIT", Const, 0}, + {"TIOCMGET", Const, 0}, + {"TIOCMIWAIT", Const, 0}, + {"TIOCMODG", Const, 0}, + {"TIOCMODS", Const, 0}, + {"TIOCMSDTRWAIT", Const, 0}, + {"TIOCMSET", Const, 0}, + {"TIOCM_CAR", Const, 0}, + {"TIOCM_CD", Const, 0}, + {"TIOCM_CTS", Const, 0}, + {"TIOCM_DCD", Const, 0}, + {"TIOCM_DSR", Const, 0}, + {"TIOCM_DTR", Const, 0}, + {"TIOCM_LE", Const, 0}, + {"TIOCM_RI", Const, 0}, + {"TIOCM_RNG", Const, 0}, + {"TIOCM_RTS", Const, 0}, + {"TIOCM_SR", Const, 0}, + {"TIOCM_ST", Const, 0}, + {"TIOCNOTTY", Const, 0}, + {"TIOCNXCL", Const, 0}, + {"TIOCOUTQ", Const, 0}, + {"TIOCPKT", Const, 0}, + {"TIOCPKT_DATA", Const, 0}, + {"TIOCPKT_DOSTOP", Const, 0}, + {"TIOCPKT_FLUSHREAD", Const, 0}, + {"TIOCPKT_FLUSHWRITE", Const, 0}, + {"TIOCPKT_IOCTL", Const, 0}, + {"TIOCPKT_NOSTOP", Const, 0}, + {"TIOCPKT_START", Const, 0}, + {"TIOCPKT_STOP", Const, 0}, + {"TIOCPTMASTER", Const, 0}, + {"TIOCPTMGET", Const, 1}, + {"TIOCPTSNAME", Const, 1}, + {"TIOCPTYGNAME", Const, 0}, + {"TIOCPTYGRANT", Const, 0}, + {"TIOCPTYUNLK", Const, 0}, + {"TIOCRCVFRAME", Const, 1}, + {"TIOCREMOTE", Const, 0}, + {"TIOCSBRK", Const, 0}, + {"TIOCSCONS", Const, 0}, + {"TIOCSCTTY", Const, 0}, + {"TIOCSDRAINWAIT", Const, 0}, + {"TIOCSDTR", Const, 0}, + {"TIOCSERCONFIG", Const, 0}, + {"TIOCSERGETLSR", Const, 0}, + {"TIOCSERGETMULTI", Const, 0}, + {"TIOCSERGSTRUCT", Const, 0}, + {"TIOCSERGWILD", Const, 0}, + {"TIOCSERSETMULTI", Const, 0}, + {"TIOCSERSWILD", Const, 0}, + {"TIOCSER_TEMT", Const, 0}, + {"TIOCSETA", Const, 0}, + {"TIOCSETAF", Const, 0}, + {"TIOCSETAW", Const, 0}, + {"TIOCSETD", Const, 0}, + {"TIOCSFLAGS", Const, 1}, + {"TIOCSIG", Const, 0}, + {"TIOCSLCKTRMIOS", Const, 0}, + {"TIOCSLINED", Const, 1}, + {"TIOCSPGRP", Const, 0}, + {"TIOCSPTLCK", Const, 0}, + {"TIOCSQSIZE", Const, 1}, + {"TIOCSRS485", Const, 0}, + {"TIOCSSERIAL", Const, 0}, + {"TIOCSSIZE", Const, 1}, + {"TIOCSSOFTCAR", Const, 0}, + {"TIOCSTART", Const, 0}, + {"TIOCSTAT", Const, 0}, + {"TIOCSTI", Const, 0}, + {"TIOCSTOP", Const, 0}, + {"TIOCSTSTAMP", Const, 1}, + {"TIOCSWINSZ", Const, 0}, + {"TIOCTIMESTAMP", Const, 0}, + {"TIOCUCNTL", Const, 0}, + {"TIOCVHANGUP", Const, 0}, + {"TIOCXMTFRAME", Const, 1}, + {"TOKEN_ADJUST_DEFAULT", Const, 0}, + {"TOKEN_ADJUST_GROUPS", Const, 0}, + {"TOKEN_ADJUST_PRIVILEGES", Const, 0}, + {"TOKEN_ADJUST_SESSIONID", Const, 11}, + {"TOKEN_ALL_ACCESS", Const, 0}, + {"TOKEN_ASSIGN_PRIMARY", Const, 0}, + {"TOKEN_DUPLICATE", Const, 0}, + {"TOKEN_EXECUTE", Const, 0}, + {"TOKEN_IMPERSONATE", Const, 0}, + {"TOKEN_QUERY", Const, 0}, + {"TOKEN_QUERY_SOURCE", Const, 0}, + {"TOKEN_READ", Const, 0}, + {"TOKEN_WRITE", Const, 0}, + {"TOSTOP", Const, 0}, + {"TRUNCATE_EXISTING", Const, 0}, + {"TUNATTACHFILTER", Const, 0}, + {"TUNDETACHFILTER", Const, 0}, + {"TUNGETFEATURES", Const, 0}, + {"TUNGETIFF", Const, 0}, + {"TUNGETSNDBUF", Const, 0}, + {"TUNGETVNETHDRSZ", Const, 0}, + {"TUNSETDEBUG", Const, 0}, + {"TUNSETGROUP", Const, 0}, + {"TUNSETIFF", Const, 0}, + {"TUNSETLINK", Const, 0}, + {"TUNSETNOCSUM", Const, 0}, + {"TUNSETOFFLOAD", Const, 0}, + {"TUNSETOWNER", Const, 0}, + {"TUNSETPERSIST", Const, 0}, + {"TUNSETSNDBUF", Const, 0}, + {"TUNSETTXFILTER", Const, 0}, + {"TUNSETVNETHDRSZ", Const, 0}, + {"Tee", Func, 0}, + {"TerminateProcess", Func, 0}, + {"Termios", Type, 0}, + {"Termios.Cc", Field, 0}, + {"Termios.Cflag", Field, 0}, + {"Termios.Iflag", Field, 0}, + {"Termios.Ispeed", Field, 0}, + {"Termios.Lflag", Field, 0}, + {"Termios.Line", Field, 0}, + {"Termios.Oflag", Field, 0}, + {"Termios.Ospeed", Field, 0}, + {"Termios.Pad_cgo_0", Field, 0}, + {"Tgkill", Func, 0}, + {"Time", Func, 0}, + {"Time_t", Type, 0}, + {"Times", Func, 0}, + {"Timespec", Type, 0}, + {"Timespec.Nsec", Field, 0}, + {"Timespec.Pad_cgo_0", Field, 2}, + {"Timespec.Sec", Field, 0}, + {"TimespecToNsec", Func, 0}, + {"Timeval", Type, 0}, + {"Timeval.Pad_cgo_0", Field, 0}, + {"Timeval.Sec", Field, 0}, + {"Timeval.Usec", Field, 0}, + {"Timeval32", Type, 0}, + {"Timeval32.Sec", Field, 0}, + {"Timeval32.Usec", Field, 0}, + {"TimevalToNsec", Func, 0}, + {"Timex", Type, 0}, + {"Timex.Calcnt", Field, 0}, + {"Timex.Constant", Field, 0}, + {"Timex.Errcnt", Field, 0}, + {"Timex.Esterror", Field, 0}, + {"Timex.Freq", Field, 0}, + {"Timex.Jitcnt", Field, 0}, + {"Timex.Jitter", Field, 0}, + {"Timex.Maxerror", Field, 0}, + {"Timex.Modes", Field, 0}, + {"Timex.Offset", Field, 0}, + {"Timex.Pad_cgo_0", Field, 0}, + {"Timex.Pad_cgo_1", Field, 0}, + {"Timex.Pad_cgo_2", Field, 0}, + {"Timex.Pad_cgo_3", Field, 0}, + {"Timex.Ppsfreq", Field, 0}, + {"Timex.Precision", Field, 0}, + {"Timex.Shift", Field, 0}, + {"Timex.Stabil", Field, 0}, + {"Timex.Status", Field, 0}, + {"Timex.Stbcnt", Field, 0}, + {"Timex.Tai", Field, 0}, + {"Timex.Tick", Field, 0}, + {"Timex.Time", Field, 0}, + {"Timex.Tolerance", Field, 0}, + {"Timezoneinformation", Type, 0}, + {"Timezoneinformation.Bias", Field, 0}, + {"Timezoneinformation.DaylightBias", Field, 0}, + {"Timezoneinformation.DaylightDate", Field, 0}, + {"Timezoneinformation.DaylightName", Field, 0}, + {"Timezoneinformation.StandardBias", Field, 0}, + {"Timezoneinformation.StandardDate", Field, 0}, + {"Timezoneinformation.StandardName", Field, 0}, + {"Tms", Type, 0}, + {"Tms.Cstime", Field, 0}, + {"Tms.Cutime", Field, 0}, + {"Tms.Stime", Field, 0}, + {"Tms.Utime", Field, 0}, + {"Token", Type, 0}, + {"TokenAccessInformation", Const, 0}, + {"TokenAuditPolicy", Const, 0}, + {"TokenDefaultDacl", Const, 0}, + {"TokenElevation", Const, 0}, + {"TokenElevationType", Const, 0}, + {"TokenGroups", Const, 0}, + {"TokenGroupsAndPrivileges", Const, 0}, + {"TokenHasRestrictions", Const, 0}, + {"TokenImpersonationLevel", Const, 0}, + {"TokenIntegrityLevel", Const, 0}, + {"TokenLinkedToken", Const, 0}, + {"TokenLogonSid", Const, 0}, + {"TokenMandatoryPolicy", Const, 0}, + {"TokenOrigin", Const, 0}, + {"TokenOwner", Const, 0}, + {"TokenPrimaryGroup", Const, 0}, + {"TokenPrivileges", Const, 0}, + {"TokenRestrictedSids", Const, 0}, + {"TokenSandBoxInert", Const, 0}, + {"TokenSessionId", Const, 0}, + {"TokenSessionReference", Const, 0}, + {"TokenSource", Const, 0}, + {"TokenStatistics", Const, 0}, + {"TokenType", Const, 0}, + {"TokenUIAccess", Const, 0}, + {"TokenUser", Const, 0}, + {"TokenVirtualizationAllowed", Const, 0}, + {"TokenVirtualizationEnabled", Const, 0}, + {"Tokenprimarygroup", Type, 0}, + {"Tokenprimarygroup.PrimaryGroup", Field, 0}, + {"Tokenuser", Type, 0}, + {"Tokenuser.User", Field, 0}, + {"TranslateAccountName", Func, 0}, + {"TranslateName", Func, 0}, + {"TransmitFile", Func, 0}, + {"TransmitFileBuffers", Type, 0}, + {"TransmitFileBuffers.Head", Field, 0}, + {"TransmitFileBuffers.HeadLength", Field, 0}, + {"TransmitFileBuffers.Tail", Field, 0}, + {"TransmitFileBuffers.TailLength", Field, 0}, + {"Truncate", Func, 0}, + {"UNIX_PATH_MAX", Const, 12}, + {"USAGE_MATCH_TYPE_AND", Const, 0}, + {"USAGE_MATCH_TYPE_OR", Const, 0}, + {"UTF16FromString", Func, 1}, + {"UTF16PtrFromString", Func, 1}, + {"UTF16ToString", Func, 0}, + {"Ucred", Type, 0}, + {"Ucred.Gid", Field, 0}, + {"Ucred.Pid", Field, 0}, + {"Ucred.Uid", Field, 0}, + {"Umask", Func, 0}, + {"Uname", Func, 0}, + {"Undelete", Func, 0}, + {"UnixCredentials", Func, 0}, + {"UnixRights", Func, 0}, + {"Unlink", Func, 0}, + {"Unlinkat", Func, 0}, + {"UnmapViewOfFile", Func, 0}, + {"Unmount", Func, 0}, + {"Unsetenv", Func, 4}, + {"Unshare", Func, 0}, + {"UserInfo10", Type, 0}, + {"UserInfo10.Comment", Field, 0}, + {"UserInfo10.FullName", Field, 0}, + {"UserInfo10.Name", Field, 0}, + {"UserInfo10.UsrComment", Field, 0}, + {"Ustat", Func, 0}, + {"Ustat_t", Type, 0}, + {"Ustat_t.Fname", Field, 0}, + {"Ustat_t.Fpack", Field, 0}, + {"Ustat_t.Pad_cgo_0", Field, 0}, + {"Ustat_t.Pad_cgo_1", Field, 0}, + {"Ustat_t.Tfree", Field, 0}, + {"Ustat_t.Tinode", Field, 0}, + {"Utimbuf", Type, 0}, + {"Utimbuf.Actime", Field, 0}, + {"Utimbuf.Modtime", Field, 0}, + {"Utime", Func, 0}, + {"Utimes", Func, 0}, + {"UtimesNano", Func, 1}, + {"Utsname", Type, 0}, + {"Utsname.Domainname", Field, 0}, + {"Utsname.Machine", Field, 0}, + {"Utsname.Nodename", Field, 0}, + {"Utsname.Release", Field, 0}, + {"Utsname.Sysname", Field, 0}, + {"Utsname.Version", Field, 0}, + {"VDISCARD", Const, 0}, + {"VDSUSP", Const, 1}, + {"VEOF", Const, 0}, + {"VEOL", Const, 0}, + {"VEOL2", Const, 0}, + {"VERASE", Const, 0}, + {"VERASE2", Const, 1}, + {"VINTR", Const, 0}, + {"VKILL", Const, 0}, + {"VLNEXT", Const, 0}, + {"VMIN", Const, 0}, + {"VQUIT", Const, 0}, + {"VREPRINT", Const, 0}, + {"VSTART", Const, 0}, + {"VSTATUS", Const, 1}, + {"VSTOP", Const, 0}, + {"VSUSP", Const, 0}, + {"VSWTC", Const, 0}, + {"VT0", Const, 1}, + {"VT1", Const, 1}, + {"VTDLY", Const, 1}, + {"VTIME", Const, 0}, + {"VWERASE", Const, 0}, + {"VirtualLock", Func, 0}, + {"VirtualUnlock", Func, 0}, + {"WAIT_ABANDONED", Const, 0}, + {"WAIT_FAILED", Const, 0}, + {"WAIT_OBJECT_0", Const, 0}, + {"WAIT_TIMEOUT", Const, 0}, + {"WALL", Const, 0}, + {"WALLSIG", Const, 1}, + {"WALTSIG", Const, 1}, + {"WCLONE", Const, 0}, + {"WCONTINUED", Const, 0}, + {"WCOREFLAG", Const, 0}, + {"WEXITED", Const, 0}, + {"WLINUXCLONE", Const, 0}, + {"WNOHANG", Const, 0}, + {"WNOTHREAD", Const, 0}, + {"WNOWAIT", Const, 0}, + {"WNOZOMBIE", Const, 1}, + {"WOPTSCHECKED", Const, 1}, + {"WORDSIZE", Const, 0}, + {"WSABuf", Type, 0}, + {"WSABuf.Buf", Field, 0}, + {"WSABuf.Len", Field, 0}, + {"WSACleanup", Func, 0}, + {"WSADESCRIPTION_LEN", Const, 0}, + {"WSAData", Type, 0}, + {"WSAData.Description", Field, 0}, + {"WSAData.HighVersion", Field, 0}, + {"WSAData.MaxSockets", Field, 0}, + {"WSAData.MaxUdpDg", Field, 0}, + {"WSAData.SystemStatus", Field, 0}, + {"WSAData.VendorInfo", Field, 0}, + {"WSAData.Version", Field, 0}, + {"WSAEACCES", Const, 2}, + {"WSAECONNABORTED", Const, 9}, + {"WSAECONNRESET", Const, 3}, + {"WSAENOPROTOOPT", Const, 23}, + {"WSAEnumProtocols", Func, 2}, + {"WSAID_CONNECTEX", Var, 1}, + {"WSAIoctl", Func, 0}, + {"WSAPROTOCOL_LEN", Const, 2}, + {"WSAProtocolChain", Type, 2}, + {"WSAProtocolChain.ChainEntries", Field, 2}, + {"WSAProtocolChain.ChainLen", Field, 2}, + {"WSAProtocolInfo", Type, 2}, + {"WSAProtocolInfo.AddressFamily", Field, 2}, + {"WSAProtocolInfo.CatalogEntryId", Field, 2}, + {"WSAProtocolInfo.MaxSockAddr", Field, 2}, + {"WSAProtocolInfo.MessageSize", Field, 2}, + {"WSAProtocolInfo.MinSockAddr", Field, 2}, + {"WSAProtocolInfo.NetworkByteOrder", Field, 2}, + {"WSAProtocolInfo.Protocol", Field, 2}, + {"WSAProtocolInfo.ProtocolChain", Field, 2}, + {"WSAProtocolInfo.ProtocolMaxOffset", Field, 2}, + {"WSAProtocolInfo.ProtocolName", Field, 2}, + {"WSAProtocolInfo.ProviderFlags", Field, 2}, + {"WSAProtocolInfo.ProviderId", Field, 2}, + {"WSAProtocolInfo.ProviderReserved", Field, 2}, + {"WSAProtocolInfo.SecurityScheme", Field, 2}, + {"WSAProtocolInfo.ServiceFlags1", Field, 2}, + {"WSAProtocolInfo.ServiceFlags2", Field, 2}, + {"WSAProtocolInfo.ServiceFlags3", Field, 2}, + {"WSAProtocolInfo.ServiceFlags4", Field, 2}, + {"WSAProtocolInfo.SocketType", Field, 2}, + {"WSAProtocolInfo.Version", Field, 2}, + {"WSARecv", Func, 0}, + {"WSARecvFrom", Func, 0}, + {"WSASYS_STATUS_LEN", Const, 0}, + {"WSASend", Func, 0}, + {"WSASendTo", Func, 0}, + {"WSASendto", Func, 0}, + {"WSAStartup", Func, 0}, + {"WSTOPPED", Const, 0}, + {"WTRAPPED", Const, 1}, + {"WUNTRACED", Const, 0}, + {"Wait4", Func, 0}, + {"WaitForSingleObject", Func, 0}, + {"WaitStatus", Type, 0}, + {"WaitStatus.ExitCode", Field, 0}, + {"Win32FileAttributeData", Type, 0}, + {"Win32FileAttributeData.CreationTime", Field, 0}, + {"Win32FileAttributeData.FileAttributes", Field, 0}, + {"Win32FileAttributeData.FileSizeHigh", Field, 0}, + {"Win32FileAttributeData.FileSizeLow", Field, 0}, + {"Win32FileAttributeData.LastAccessTime", Field, 0}, + {"Win32FileAttributeData.LastWriteTime", Field, 0}, + {"Win32finddata", Type, 0}, + {"Win32finddata.AlternateFileName", Field, 0}, + {"Win32finddata.CreationTime", Field, 0}, + {"Win32finddata.FileAttributes", Field, 0}, + {"Win32finddata.FileName", Field, 0}, + {"Win32finddata.FileSizeHigh", Field, 0}, + {"Win32finddata.FileSizeLow", Field, 0}, + {"Win32finddata.LastAccessTime", Field, 0}, + {"Win32finddata.LastWriteTime", Field, 0}, + {"Win32finddata.Reserved0", Field, 0}, + {"Win32finddata.Reserved1", Field, 0}, + {"Write", Func, 0}, + {"WriteConsole", Func, 1}, + {"WriteFile", Func, 0}, + {"X509_ASN_ENCODING", Const, 0}, + {"XCASE", Const, 0}, + {"XP1_CONNECTIONLESS", Const, 2}, + {"XP1_CONNECT_DATA", Const, 2}, + {"XP1_DISCONNECT_DATA", Const, 2}, + {"XP1_EXPEDITED_DATA", Const, 2}, + {"XP1_GRACEFUL_CLOSE", Const, 2}, + {"XP1_GUARANTEED_DELIVERY", Const, 2}, + {"XP1_GUARANTEED_ORDER", Const, 2}, + {"XP1_IFS_HANDLES", Const, 2}, + {"XP1_MESSAGE_ORIENTED", Const, 2}, + {"XP1_MULTIPOINT_CONTROL_PLANE", Const, 2}, + {"XP1_MULTIPOINT_DATA_PLANE", Const, 2}, + {"XP1_PARTIAL_MESSAGE", Const, 2}, + {"XP1_PSEUDO_STREAM", Const, 2}, + {"XP1_QOS_SUPPORTED", Const, 2}, + {"XP1_SAN_SUPPORT_SDP", Const, 2}, + {"XP1_SUPPORT_BROADCAST", Const, 2}, + {"XP1_SUPPORT_MULTIPOINT", Const, 2}, + {"XP1_UNI_RECV", Const, 2}, + {"XP1_UNI_SEND", Const, 2}, + }, + "syscall/js": { + {"CopyBytesToGo", Func, 0}, + {"CopyBytesToJS", Func, 0}, + {"Error", Type, 0}, + {"Func", Type, 0}, + {"FuncOf", Func, 0}, + {"Global", Func, 0}, + {"Null", Func, 0}, + {"Type", Type, 0}, + {"TypeBoolean", Const, 0}, + {"TypeFunction", Const, 0}, + {"TypeNull", Const, 0}, + {"TypeNumber", Const, 0}, + {"TypeObject", Const, 0}, + {"TypeString", Const, 0}, + {"TypeSymbol", Const, 0}, + {"TypeUndefined", Const, 0}, + {"Undefined", Func, 0}, + {"Value", Type, 0}, + {"ValueError", Type, 0}, + {"ValueOf", Func, 0}, + }, + "testing": { + {"(*B).Cleanup", Method, 14}, + {"(*B).Elapsed", Method, 20}, + {"(*B).Error", Method, 0}, + {"(*B).Errorf", Method, 0}, + {"(*B).Fail", Method, 0}, + {"(*B).FailNow", Method, 0}, + {"(*B).Failed", Method, 0}, + {"(*B).Fatal", Method, 0}, + {"(*B).Fatalf", Method, 0}, + {"(*B).Helper", Method, 9}, + {"(*B).Log", Method, 0}, + {"(*B).Logf", Method, 0}, + {"(*B).Name", Method, 8}, + {"(*B).ReportAllocs", Method, 1}, + {"(*B).ReportMetric", Method, 13}, + {"(*B).ResetTimer", Method, 0}, + {"(*B).Run", Method, 7}, + {"(*B).RunParallel", Method, 3}, + {"(*B).SetBytes", Method, 0}, + {"(*B).SetParallelism", Method, 3}, + {"(*B).Setenv", Method, 17}, + {"(*B).Skip", Method, 1}, + {"(*B).SkipNow", Method, 1}, + {"(*B).Skipf", Method, 1}, + {"(*B).Skipped", Method, 1}, + {"(*B).StartTimer", Method, 0}, + {"(*B).StopTimer", Method, 0}, + {"(*B).TempDir", Method, 15}, + {"(*F).Add", Method, 18}, + {"(*F).Cleanup", Method, 18}, + {"(*F).Error", Method, 18}, + {"(*F).Errorf", Method, 18}, + {"(*F).Fail", Method, 18}, + {"(*F).FailNow", Method, 18}, + {"(*F).Failed", Method, 18}, + {"(*F).Fatal", Method, 18}, + {"(*F).Fatalf", Method, 18}, + {"(*F).Fuzz", Method, 18}, + {"(*F).Helper", Method, 18}, + {"(*F).Log", Method, 18}, + {"(*F).Logf", Method, 18}, + {"(*F).Name", Method, 18}, + {"(*F).Setenv", Method, 18}, + {"(*F).Skip", Method, 18}, + {"(*F).SkipNow", Method, 18}, + {"(*F).Skipf", Method, 18}, + {"(*F).Skipped", Method, 18}, + {"(*F).TempDir", Method, 18}, + {"(*M).Run", Method, 4}, + {"(*PB).Next", Method, 3}, + {"(*T).Cleanup", Method, 14}, + {"(*T).Deadline", Method, 15}, + {"(*T).Error", Method, 0}, + {"(*T).Errorf", Method, 0}, + {"(*T).Fail", Method, 0}, + {"(*T).FailNow", Method, 0}, + {"(*T).Failed", Method, 0}, + {"(*T).Fatal", Method, 0}, + {"(*T).Fatalf", Method, 0}, + {"(*T).Helper", Method, 9}, + {"(*T).Log", Method, 0}, + {"(*T).Logf", Method, 0}, + {"(*T).Name", Method, 8}, + {"(*T).Parallel", Method, 0}, + {"(*T).Run", Method, 7}, + {"(*T).Setenv", Method, 17}, + {"(*T).Skip", Method, 1}, + {"(*T).SkipNow", Method, 1}, + {"(*T).Skipf", Method, 1}, + {"(*T).Skipped", Method, 1}, + {"(*T).TempDir", Method, 15}, + {"(BenchmarkResult).AllocedBytesPerOp", Method, 1}, + {"(BenchmarkResult).AllocsPerOp", Method, 1}, + {"(BenchmarkResult).MemString", Method, 1}, + {"(BenchmarkResult).NsPerOp", Method, 0}, + {"(BenchmarkResult).String", Method, 0}, + {"AllocsPerRun", Func, 1}, + {"B", Type, 0}, + {"B.N", Field, 0}, + {"Benchmark", Func, 0}, + {"BenchmarkResult", Type, 0}, + {"BenchmarkResult.Bytes", Field, 0}, + {"BenchmarkResult.Extra", Field, 13}, + {"BenchmarkResult.MemAllocs", Field, 1}, + {"BenchmarkResult.MemBytes", Field, 1}, + {"BenchmarkResult.N", Field, 0}, + {"BenchmarkResult.T", Field, 0}, + {"Cover", Type, 2}, + {"Cover.Blocks", Field, 2}, + {"Cover.Counters", Field, 2}, + {"Cover.CoveredPackages", Field, 2}, + {"Cover.Mode", Field, 2}, + {"CoverBlock", Type, 2}, + {"CoverBlock.Col0", Field, 2}, + {"CoverBlock.Col1", Field, 2}, + {"CoverBlock.Line0", Field, 2}, + {"CoverBlock.Line1", Field, 2}, + {"CoverBlock.Stmts", Field, 2}, + {"CoverMode", Func, 8}, + {"Coverage", Func, 4}, + {"F", Type, 18}, + {"Init", Func, 13}, + {"InternalBenchmark", Type, 0}, + {"InternalBenchmark.F", Field, 0}, + {"InternalBenchmark.Name", Field, 0}, + {"InternalExample", Type, 0}, + {"InternalExample.F", Field, 0}, + {"InternalExample.Name", Field, 0}, + {"InternalExample.Output", Field, 0}, + {"InternalExample.Unordered", Field, 7}, + {"InternalFuzzTarget", Type, 18}, + {"InternalFuzzTarget.Fn", Field, 18}, + {"InternalFuzzTarget.Name", Field, 18}, + {"InternalTest", Type, 0}, + {"InternalTest.F", Field, 0}, + {"InternalTest.Name", Field, 0}, + {"M", Type, 4}, + {"Main", Func, 0}, + {"MainStart", Func, 4}, + {"PB", Type, 3}, + {"RegisterCover", Func, 2}, + {"RunBenchmarks", Func, 0}, + {"RunExamples", Func, 0}, + {"RunTests", Func, 0}, + {"Short", Func, 0}, + {"T", Type, 0}, + {"TB", Type, 2}, + {"Testing", Func, 21}, + {"Verbose", Func, 1}, + }, + "testing/fstest": { + {"(MapFS).Glob", Method, 16}, + {"(MapFS).Open", Method, 16}, + {"(MapFS).ReadDir", Method, 16}, + {"(MapFS).ReadFile", Method, 16}, + {"(MapFS).Stat", Method, 16}, + {"(MapFS).Sub", Method, 16}, + {"MapFS", Type, 16}, + {"MapFile", Type, 16}, + {"MapFile.Data", Field, 16}, + {"MapFile.ModTime", Field, 16}, + {"MapFile.Mode", Field, 16}, + {"MapFile.Sys", Field, 16}, + {"TestFS", Func, 16}, + }, + "testing/iotest": { + {"DataErrReader", Func, 0}, + {"ErrReader", Func, 16}, + {"ErrTimeout", Var, 0}, + {"HalfReader", Func, 0}, + {"NewReadLogger", Func, 0}, + {"NewWriteLogger", Func, 0}, + {"OneByteReader", Func, 0}, + {"TestReader", Func, 16}, + {"TimeoutReader", Func, 0}, + {"TruncateWriter", Func, 0}, + }, + "testing/quick": { + {"(*CheckEqualError).Error", Method, 0}, + {"(*CheckError).Error", Method, 0}, + {"(SetupError).Error", Method, 0}, + {"Check", Func, 0}, + {"CheckEqual", Func, 0}, + {"CheckEqualError", Type, 0}, + {"CheckEqualError.CheckError", Field, 0}, + {"CheckEqualError.Out1", Field, 0}, + {"CheckEqualError.Out2", Field, 0}, + {"CheckError", Type, 0}, + {"CheckError.Count", Field, 0}, + {"CheckError.In", Field, 0}, + {"Config", Type, 0}, + {"Config.MaxCount", Field, 0}, + {"Config.MaxCountScale", Field, 0}, + {"Config.Rand", Field, 0}, + {"Config.Values", Field, 0}, + {"Generator", Type, 0}, + {"SetupError", Type, 0}, + {"Value", Func, 0}, + }, + "testing/slogtest": { + {"Run", Func, 22}, + {"TestHandler", Func, 21}, + }, + "text/scanner": { + {"(*Position).IsValid", Method, 0}, + {"(*Scanner).Init", Method, 0}, + {"(*Scanner).IsValid", Method, 0}, + {"(*Scanner).Next", Method, 0}, + {"(*Scanner).Peek", Method, 0}, + {"(*Scanner).Pos", Method, 0}, + {"(*Scanner).Scan", Method, 0}, + {"(*Scanner).TokenText", Method, 0}, + {"(Position).String", Method, 0}, + {"(Scanner).String", Method, 0}, + {"Char", Const, 0}, + {"Comment", Const, 0}, + {"EOF", Const, 0}, + {"Float", Const, 0}, + {"GoTokens", Const, 0}, + {"GoWhitespace", Const, 0}, + {"Ident", Const, 0}, + {"Int", Const, 0}, + {"Position", Type, 0}, + {"Position.Column", Field, 0}, + {"Position.Filename", Field, 0}, + {"Position.Line", Field, 0}, + {"Position.Offset", Field, 0}, + {"RawString", Const, 0}, + {"ScanChars", Const, 0}, + {"ScanComments", Const, 0}, + {"ScanFloats", Const, 0}, + {"ScanIdents", Const, 0}, + {"ScanInts", Const, 0}, + {"ScanRawStrings", Const, 0}, + {"ScanStrings", Const, 0}, + {"Scanner", Type, 0}, + {"Scanner.Error", Field, 0}, + {"Scanner.ErrorCount", Field, 0}, + {"Scanner.IsIdentRune", Field, 4}, + {"Scanner.Mode", Field, 0}, + {"Scanner.Position", Field, 0}, + {"Scanner.Whitespace", Field, 0}, + {"SkipComments", Const, 0}, + {"String", Const, 0}, + {"TokenString", Func, 0}, + }, + "text/tabwriter": { + {"(*Writer).Flush", Method, 0}, + {"(*Writer).Init", Method, 0}, + {"(*Writer).Write", Method, 0}, + {"AlignRight", Const, 0}, + {"Debug", Const, 0}, + {"DiscardEmptyColumns", Const, 0}, + {"Escape", Const, 0}, + {"FilterHTML", Const, 0}, + {"NewWriter", Func, 0}, + {"StripEscape", Const, 0}, + {"TabIndent", Const, 0}, + {"Writer", Type, 0}, + }, + "text/template": { + {"(*Template).AddParseTree", Method, 0}, + {"(*Template).Clone", Method, 0}, + {"(*Template).DefinedTemplates", Method, 5}, + {"(*Template).Delims", Method, 0}, + {"(*Template).Execute", Method, 0}, + {"(*Template).ExecuteTemplate", Method, 0}, + {"(*Template).Funcs", Method, 0}, + {"(*Template).Lookup", Method, 0}, + {"(*Template).Name", Method, 0}, + {"(*Template).New", Method, 0}, + {"(*Template).Option", Method, 5}, + {"(*Template).Parse", Method, 0}, + {"(*Template).ParseFS", Method, 16}, + {"(*Template).ParseFiles", Method, 0}, + {"(*Template).ParseGlob", Method, 0}, + {"(*Template).Templates", Method, 0}, + {"(ExecError).Error", Method, 6}, + {"(ExecError).Unwrap", Method, 13}, + {"(Template).Copy", Method, 2}, + {"(Template).ErrorContext", Method, 1}, + {"ExecError", Type, 6}, + {"ExecError.Err", Field, 6}, + {"ExecError.Name", Field, 6}, + {"FuncMap", Type, 0}, + {"HTMLEscape", Func, 0}, + {"HTMLEscapeString", Func, 0}, + {"HTMLEscaper", Func, 0}, + {"IsTrue", Func, 6}, + {"JSEscape", Func, 0}, + {"JSEscapeString", Func, 0}, + {"JSEscaper", Func, 0}, + {"Must", Func, 0}, + {"New", Func, 0}, + {"ParseFS", Func, 16}, + {"ParseFiles", Func, 0}, + {"ParseGlob", Func, 0}, + {"Template", Type, 0}, + {"Template.Tree", Field, 0}, + {"URLQueryEscaper", Func, 0}, + }, + "text/template/parse": { + {"(*ActionNode).Copy", Method, 0}, + {"(*ActionNode).String", Method, 0}, + {"(*BoolNode).Copy", Method, 0}, + {"(*BoolNode).String", Method, 0}, + {"(*BranchNode).Copy", Method, 4}, + {"(*BranchNode).String", Method, 0}, + {"(*BreakNode).Copy", Method, 18}, + {"(*BreakNode).String", Method, 18}, + {"(*ChainNode).Add", Method, 1}, + {"(*ChainNode).Copy", Method, 1}, + {"(*ChainNode).String", Method, 1}, + {"(*CommandNode).Copy", Method, 0}, + {"(*CommandNode).String", Method, 0}, + {"(*CommentNode).Copy", Method, 16}, + {"(*CommentNode).String", Method, 16}, + {"(*ContinueNode).Copy", Method, 18}, + {"(*ContinueNode).String", Method, 18}, + {"(*DotNode).Copy", Method, 0}, + {"(*DotNode).String", Method, 0}, + {"(*DotNode).Type", Method, 0}, + {"(*FieldNode).Copy", Method, 0}, + {"(*FieldNode).String", Method, 0}, + {"(*IdentifierNode).Copy", Method, 0}, + {"(*IdentifierNode).SetPos", Method, 1}, + {"(*IdentifierNode).SetTree", Method, 4}, + {"(*IdentifierNode).String", Method, 0}, + {"(*IfNode).Copy", Method, 0}, + {"(*IfNode).String", Method, 0}, + {"(*ListNode).Copy", Method, 0}, + {"(*ListNode).CopyList", Method, 0}, + {"(*ListNode).String", Method, 0}, + {"(*NilNode).Copy", Method, 1}, + {"(*NilNode).String", Method, 1}, + {"(*NilNode).Type", Method, 1}, + {"(*NumberNode).Copy", Method, 0}, + {"(*NumberNode).String", Method, 0}, + {"(*PipeNode).Copy", Method, 0}, + {"(*PipeNode).CopyPipe", Method, 0}, + {"(*PipeNode).String", Method, 0}, + {"(*RangeNode).Copy", Method, 0}, + {"(*RangeNode).String", Method, 0}, + {"(*StringNode).Copy", Method, 0}, + {"(*StringNode).String", Method, 0}, + {"(*TemplateNode).Copy", Method, 0}, + {"(*TemplateNode).String", Method, 0}, + {"(*TextNode).Copy", Method, 0}, + {"(*TextNode).String", Method, 0}, + {"(*Tree).Copy", Method, 2}, + {"(*Tree).ErrorContext", Method, 1}, + {"(*Tree).Parse", Method, 0}, + {"(*VariableNode).Copy", Method, 0}, + {"(*VariableNode).String", Method, 0}, + {"(*WithNode).Copy", Method, 0}, + {"(*WithNode).String", Method, 0}, + {"(ActionNode).Position", Method, 1}, + {"(ActionNode).Type", Method, 0}, + {"(BoolNode).Position", Method, 1}, + {"(BoolNode).Type", Method, 0}, + {"(BranchNode).Position", Method, 1}, + {"(BranchNode).Type", Method, 0}, + {"(BreakNode).Position", Method, 18}, + {"(BreakNode).Type", Method, 18}, + {"(ChainNode).Position", Method, 1}, + {"(ChainNode).Type", Method, 1}, + {"(CommandNode).Position", Method, 1}, + {"(CommandNode).Type", Method, 0}, + {"(CommentNode).Position", Method, 16}, + {"(CommentNode).Type", Method, 16}, + {"(ContinueNode).Position", Method, 18}, + {"(ContinueNode).Type", Method, 18}, + {"(DotNode).Position", Method, 1}, + {"(FieldNode).Position", Method, 1}, + {"(FieldNode).Type", Method, 0}, + {"(IdentifierNode).Position", Method, 1}, + {"(IdentifierNode).Type", Method, 0}, + {"(IfNode).Position", Method, 1}, + {"(IfNode).Type", Method, 0}, + {"(ListNode).Position", Method, 1}, + {"(ListNode).Type", Method, 0}, + {"(NilNode).Position", Method, 1}, + {"(NodeType).Type", Method, 0}, + {"(NumberNode).Position", Method, 1}, + {"(NumberNode).Type", Method, 0}, + {"(PipeNode).Position", Method, 1}, + {"(PipeNode).Type", Method, 0}, + {"(Pos).Position", Method, 1}, + {"(RangeNode).Position", Method, 1}, + {"(RangeNode).Type", Method, 0}, + {"(StringNode).Position", Method, 1}, + {"(StringNode).Type", Method, 0}, + {"(TemplateNode).Position", Method, 1}, + {"(TemplateNode).Type", Method, 0}, + {"(TextNode).Position", Method, 1}, + {"(TextNode).Type", Method, 0}, + {"(VariableNode).Position", Method, 1}, + {"(VariableNode).Type", Method, 0}, + {"(WithNode).Position", Method, 1}, + {"(WithNode).Type", Method, 0}, + {"ActionNode", Type, 0}, + {"ActionNode.Line", Field, 0}, + {"ActionNode.NodeType", Field, 0}, + {"ActionNode.Pipe", Field, 0}, + {"ActionNode.Pos", Field, 1}, + {"BoolNode", Type, 0}, + {"BoolNode.NodeType", Field, 0}, + {"BoolNode.Pos", Field, 1}, + {"BoolNode.True", Field, 0}, + {"BranchNode", Type, 0}, + {"BranchNode.ElseList", Field, 0}, + {"BranchNode.Line", Field, 0}, + {"BranchNode.List", Field, 0}, + {"BranchNode.NodeType", Field, 0}, + {"BranchNode.Pipe", Field, 0}, + {"BranchNode.Pos", Field, 1}, + {"BreakNode", Type, 18}, + {"BreakNode.Line", Field, 18}, + {"BreakNode.NodeType", Field, 18}, + {"BreakNode.Pos", Field, 18}, + {"ChainNode", Type, 1}, + {"ChainNode.Field", Field, 1}, + {"ChainNode.Node", Field, 1}, + {"ChainNode.NodeType", Field, 1}, + {"ChainNode.Pos", Field, 1}, + {"CommandNode", Type, 0}, + {"CommandNode.Args", Field, 0}, + {"CommandNode.NodeType", Field, 0}, + {"CommandNode.Pos", Field, 1}, + {"CommentNode", Type, 16}, + {"CommentNode.NodeType", Field, 16}, + {"CommentNode.Pos", Field, 16}, + {"CommentNode.Text", Field, 16}, + {"ContinueNode", Type, 18}, + {"ContinueNode.Line", Field, 18}, + {"ContinueNode.NodeType", Field, 18}, + {"ContinueNode.Pos", Field, 18}, + {"DotNode", Type, 0}, + {"DotNode.NodeType", Field, 4}, + {"DotNode.Pos", Field, 1}, + {"FieldNode", Type, 0}, + {"FieldNode.Ident", Field, 0}, + {"FieldNode.NodeType", Field, 0}, + {"FieldNode.Pos", Field, 1}, + {"IdentifierNode", Type, 0}, + {"IdentifierNode.Ident", Field, 0}, + {"IdentifierNode.NodeType", Field, 0}, + {"IdentifierNode.Pos", Field, 1}, + {"IfNode", Type, 0}, + {"IfNode.BranchNode", Field, 0}, + {"IsEmptyTree", Func, 0}, + {"ListNode", Type, 0}, + {"ListNode.NodeType", Field, 0}, + {"ListNode.Nodes", Field, 0}, + {"ListNode.Pos", Field, 1}, + {"Mode", Type, 16}, + {"New", Func, 0}, + {"NewIdentifier", Func, 0}, + {"NilNode", Type, 1}, + {"NilNode.NodeType", Field, 4}, + {"NilNode.Pos", Field, 1}, + {"Node", Type, 0}, + {"NodeAction", Const, 0}, + {"NodeBool", Const, 0}, + {"NodeBreak", Const, 18}, + {"NodeChain", Const, 1}, + {"NodeCommand", Const, 0}, + {"NodeComment", Const, 16}, + {"NodeContinue", Const, 18}, + {"NodeDot", Const, 0}, + {"NodeField", Const, 0}, + {"NodeIdentifier", Const, 0}, + {"NodeIf", Const, 0}, + {"NodeList", Const, 0}, + {"NodeNil", Const, 1}, + {"NodeNumber", Const, 0}, + {"NodePipe", Const, 0}, + {"NodeRange", Const, 0}, + {"NodeString", Const, 0}, + {"NodeTemplate", Const, 0}, + {"NodeText", Const, 0}, + {"NodeType", Type, 0}, + {"NodeVariable", Const, 0}, + {"NodeWith", Const, 0}, + {"NumberNode", Type, 0}, + {"NumberNode.Complex128", Field, 0}, + {"NumberNode.Float64", Field, 0}, + {"NumberNode.Int64", Field, 0}, + {"NumberNode.IsComplex", Field, 0}, + {"NumberNode.IsFloat", Field, 0}, + {"NumberNode.IsInt", Field, 0}, + {"NumberNode.IsUint", Field, 0}, + {"NumberNode.NodeType", Field, 0}, + {"NumberNode.Pos", Field, 1}, + {"NumberNode.Text", Field, 0}, + {"NumberNode.Uint64", Field, 0}, + {"Parse", Func, 0}, + {"ParseComments", Const, 16}, + {"PipeNode", Type, 0}, + {"PipeNode.Cmds", Field, 0}, + {"PipeNode.Decl", Field, 0}, + {"PipeNode.IsAssign", Field, 11}, + {"PipeNode.Line", Field, 0}, + {"PipeNode.NodeType", Field, 0}, + {"PipeNode.Pos", Field, 1}, + {"Pos", Type, 1}, + {"RangeNode", Type, 0}, + {"RangeNode.BranchNode", Field, 0}, + {"SkipFuncCheck", Const, 17}, + {"StringNode", Type, 0}, + {"StringNode.NodeType", Field, 0}, + {"StringNode.Pos", Field, 1}, + {"StringNode.Quoted", Field, 0}, + {"StringNode.Text", Field, 0}, + {"TemplateNode", Type, 0}, + {"TemplateNode.Line", Field, 0}, + {"TemplateNode.Name", Field, 0}, + {"TemplateNode.NodeType", Field, 0}, + {"TemplateNode.Pipe", Field, 0}, + {"TemplateNode.Pos", Field, 1}, + {"TextNode", Type, 0}, + {"TextNode.NodeType", Field, 0}, + {"TextNode.Pos", Field, 1}, + {"TextNode.Text", Field, 0}, + {"Tree", Type, 0}, + {"Tree.Mode", Field, 16}, + {"Tree.Name", Field, 0}, + {"Tree.ParseName", Field, 1}, + {"Tree.Root", Field, 0}, + {"VariableNode", Type, 0}, + {"VariableNode.Ident", Field, 0}, + {"VariableNode.NodeType", Field, 0}, + {"VariableNode.Pos", Field, 1}, + {"WithNode", Type, 0}, + {"WithNode.BranchNode", Field, 0}, + }, + "time": { + {"(*Location).String", Method, 0}, + {"(*ParseError).Error", Method, 0}, + {"(*Ticker).Reset", Method, 15}, + {"(*Ticker).Stop", Method, 0}, + {"(*Time).GobDecode", Method, 0}, + {"(*Time).UnmarshalBinary", Method, 2}, + {"(*Time).UnmarshalJSON", Method, 0}, + {"(*Time).UnmarshalText", Method, 2}, + {"(*Timer).Reset", Method, 1}, + {"(*Timer).Stop", Method, 0}, + {"(Duration).Abs", Method, 19}, + {"(Duration).Hours", Method, 0}, + {"(Duration).Microseconds", Method, 13}, + {"(Duration).Milliseconds", Method, 13}, + {"(Duration).Minutes", Method, 0}, + {"(Duration).Nanoseconds", Method, 0}, + {"(Duration).Round", Method, 9}, + {"(Duration).Seconds", Method, 0}, + {"(Duration).String", Method, 0}, + {"(Duration).Truncate", Method, 9}, + {"(Month).String", Method, 0}, + {"(Time).Add", Method, 0}, + {"(Time).AddDate", Method, 0}, + {"(Time).After", Method, 0}, + {"(Time).AppendFormat", Method, 5}, + {"(Time).Before", Method, 0}, + {"(Time).Clock", Method, 0}, + {"(Time).Compare", Method, 20}, + {"(Time).Date", Method, 0}, + {"(Time).Day", Method, 0}, + {"(Time).Equal", Method, 0}, + {"(Time).Format", Method, 0}, + {"(Time).GoString", Method, 17}, + {"(Time).GobEncode", Method, 0}, + {"(Time).Hour", Method, 0}, + {"(Time).ISOWeek", Method, 0}, + {"(Time).In", Method, 0}, + {"(Time).IsDST", Method, 17}, + {"(Time).IsZero", Method, 0}, + {"(Time).Local", Method, 0}, + {"(Time).Location", Method, 0}, + {"(Time).MarshalBinary", Method, 2}, + {"(Time).MarshalJSON", Method, 0}, + {"(Time).MarshalText", Method, 2}, + {"(Time).Minute", Method, 0}, + {"(Time).Month", Method, 0}, + {"(Time).Nanosecond", Method, 0}, + {"(Time).Round", Method, 1}, + {"(Time).Second", Method, 0}, + {"(Time).String", Method, 0}, + {"(Time).Sub", Method, 0}, + {"(Time).Truncate", Method, 1}, + {"(Time).UTC", Method, 0}, + {"(Time).Unix", Method, 0}, + {"(Time).UnixMicro", Method, 17}, + {"(Time).UnixMilli", Method, 17}, + {"(Time).UnixNano", Method, 0}, + {"(Time).Weekday", Method, 0}, + {"(Time).Year", Method, 0}, + {"(Time).YearDay", Method, 1}, + {"(Time).Zone", Method, 0}, + {"(Time).ZoneBounds", Method, 19}, + {"(Weekday).String", Method, 0}, + {"ANSIC", Const, 0}, + {"After", Func, 0}, + {"AfterFunc", Func, 0}, + {"April", Const, 0}, + {"August", Const, 0}, + {"Date", Func, 0}, + {"DateOnly", Const, 20}, + {"DateTime", Const, 20}, + {"December", Const, 0}, + {"Duration", Type, 0}, + {"February", Const, 0}, + {"FixedZone", Func, 0}, + {"Friday", Const, 0}, + {"Hour", Const, 0}, + {"January", Const, 0}, + {"July", Const, 0}, + {"June", Const, 0}, + {"Kitchen", Const, 0}, + {"Layout", Const, 17}, + {"LoadLocation", Func, 0}, + {"LoadLocationFromTZData", Func, 10}, + {"Local", Var, 0}, + {"Location", Type, 0}, + {"March", Const, 0}, + {"May", Const, 0}, + {"Microsecond", Const, 0}, + {"Millisecond", Const, 0}, + {"Minute", Const, 0}, + {"Monday", Const, 0}, + {"Month", Type, 0}, + {"Nanosecond", Const, 0}, + {"NewTicker", Func, 0}, + {"NewTimer", Func, 0}, + {"November", Const, 0}, + {"Now", Func, 0}, + {"October", Const, 0}, + {"Parse", Func, 0}, + {"ParseDuration", Func, 0}, + {"ParseError", Type, 0}, + {"ParseError.Layout", Field, 0}, + {"ParseError.LayoutElem", Field, 0}, + {"ParseError.Message", Field, 0}, + {"ParseError.Value", Field, 0}, + {"ParseError.ValueElem", Field, 0}, + {"ParseInLocation", Func, 1}, + {"RFC1123", Const, 0}, + {"RFC1123Z", Const, 0}, + {"RFC3339", Const, 0}, + {"RFC3339Nano", Const, 0}, + {"RFC822", Const, 0}, + {"RFC822Z", Const, 0}, + {"RFC850", Const, 0}, + {"RubyDate", Const, 0}, + {"Saturday", Const, 0}, + {"Second", Const, 0}, + {"September", Const, 0}, + {"Since", Func, 0}, + {"Sleep", Func, 0}, + {"Stamp", Const, 0}, + {"StampMicro", Const, 0}, + {"StampMilli", Const, 0}, + {"StampNano", Const, 0}, + {"Sunday", Const, 0}, + {"Thursday", Const, 0}, + {"Tick", Func, 0}, + {"Ticker", Type, 0}, + {"Ticker.C", Field, 0}, + {"Time", Type, 0}, + {"TimeOnly", Const, 20}, + {"Timer", Type, 0}, + {"Timer.C", Field, 0}, + {"Tuesday", Const, 0}, + {"UTC", Var, 0}, + {"Unix", Func, 0}, + {"UnixDate", Const, 0}, + {"UnixMicro", Func, 17}, + {"UnixMilli", Func, 17}, + {"Until", Func, 8}, + {"Wednesday", Const, 0}, + {"Weekday", Type, 0}, + }, + "unicode": { + {"(SpecialCase).ToLower", Method, 0}, + {"(SpecialCase).ToTitle", Method, 0}, + {"(SpecialCase).ToUpper", Method, 0}, + {"ASCII_Hex_Digit", Var, 0}, + {"Adlam", Var, 7}, + {"Ahom", Var, 5}, + {"Anatolian_Hieroglyphs", Var, 5}, + {"Arabic", Var, 0}, + {"Armenian", Var, 0}, + {"Avestan", Var, 0}, + {"AzeriCase", Var, 0}, + {"Balinese", Var, 0}, + {"Bamum", Var, 0}, + {"Bassa_Vah", Var, 4}, + {"Batak", Var, 0}, + {"Bengali", Var, 0}, + {"Bhaiksuki", Var, 7}, + {"Bidi_Control", Var, 0}, + {"Bopomofo", Var, 0}, + {"Brahmi", Var, 0}, + {"Braille", Var, 0}, + {"Buginese", Var, 0}, + {"Buhid", Var, 0}, + {"C", Var, 0}, + {"Canadian_Aboriginal", Var, 0}, + {"Carian", Var, 0}, + {"CaseRange", Type, 0}, + {"CaseRange.Delta", Field, 0}, + {"CaseRange.Hi", Field, 0}, + {"CaseRange.Lo", Field, 0}, + {"CaseRanges", Var, 0}, + {"Categories", Var, 0}, + {"Caucasian_Albanian", Var, 4}, + {"Cc", Var, 0}, + {"Cf", Var, 0}, + {"Chakma", Var, 1}, + {"Cham", Var, 0}, + {"Cherokee", Var, 0}, + {"Chorasmian", Var, 16}, + {"Co", Var, 0}, + {"Common", Var, 0}, + {"Coptic", Var, 0}, + {"Cs", Var, 0}, + {"Cuneiform", Var, 0}, + {"Cypriot", Var, 0}, + {"Cypro_Minoan", Var, 21}, + {"Cyrillic", Var, 0}, + {"Dash", Var, 0}, + {"Deprecated", Var, 0}, + {"Deseret", Var, 0}, + {"Devanagari", Var, 0}, + {"Diacritic", Var, 0}, + {"Digit", Var, 0}, + {"Dives_Akuru", Var, 16}, + {"Dogra", Var, 13}, + {"Duployan", Var, 4}, + {"Egyptian_Hieroglyphs", Var, 0}, + {"Elbasan", Var, 4}, + {"Elymaic", Var, 14}, + {"Ethiopic", Var, 0}, + {"Extender", Var, 0}, + {"FoldCategory", Var, 0}, + {"FoldScript", Var, 0}, + {"Georgian", Var, 0}, + {"Glagolitic", Var, 0}, + {"Gothic", Var, 0}, + {"Grantha", Var, 4}, + {"GraphicRanges", Var, 0}, + {"Greek", Var, 0}, + {"Gujarati", Var, 0}, + {"Gunjala_Gondi", Var, 13}, + {"Gurmukhi", Var, 0}, + {"Han", Var, 0}, + {"Hangul", Var, 0}, + {"Hanifi_Rohingya", Var, 13}, + {"Hanunoo", Var, 0}, + {"Hatran", Var, 5}, + {"Hebrew", Var, 0}, + {"Hex_Digit", Var, 0}, + {"Hiragana", Var, 0}, + {"Hyphen", Var, 0}, + {"IDS_Binary_Operator", Var, 0}, + {"IDS_Trinary_Operator", Var, 0}, + {"Ideographic", Var, 0}, + {"Imperial_Aramaic", Var, 0}, + {"In", Func, 2}, + {"Inherited", Var, 0}, + {"Inscriptional_Pahlavi", Var, 0}, + {"Inscriptional_Parthian", Var, 0}, + {"Is", Func, 0}, + {"IsControl", Func, 0}, + {"IsDigit", Func, 0}, + {"IsGraphic", Func, 0}, + {"IsLetter", Func, 0}, + {"IsLower", Func, 0}, + {"IsMark", Func, 0}, + {"IsNumber", Func, 0}, + {"IsOneOf", Func, 0}, + {"IsPrint", Func, 0}, + {"IsPunct", Func, 0}, + {"IsSpace", Func, 0}, + {"IsSymbol", Func, 0}, + {"IsTitle", Func, 0}, + {"IsUpper", Func, 0}, + {"Javanese", Var, 0}, + {"Join_Control", Var, 0}, + {"Kaithi", Var, 0}, + {"Kannada", Var, 0}, + {"Katakana", Var, 0}, + {"Kawi", Var, 21}, + {"Kayah_Li", Var, 0}, + {"Kharoshthi", Var, 0}, + {"Khitan_Small_Script", Var, 16}, + {"Khmer", Var, 0}, + {"Khojki", Var, 4}, + {"Khudawadi", Var, 4}, + {"L", Var, 0}, + {"Lao", Var, 0}, + {"Latin", Var, 0}, + {"Lepcha", Var, 0}, + {"Letter", Var, 0}, + {"Limbu", Var, 0}, + {"Linear_A", Var, 4}, + {"Linear_B", Var, 0}, + {"Lisu", Var, 0}, + {"Ll", Var, 0}, + {"Lm", Var, 0}, + {"Lo", Var, 0}, + {"Logical_Order_Exception", Var, 0}, + {"Lower", Var, 0}, + {"LowerCase", Const, 0}, + {"Lt", Var, 0}, + {"Lu", Var, 0}, + {"Lycian", Var, 0}, + {"Lydian", Var, 0}, + {"M", Var, 0}, + {"Mahajani", Var, 4}, + {"Makasar", Var, 13}, + {"Malayalam", Var, 0}, + {"Mandaic", Var, 0}, + {"Manichaean", Var, 4}, + {"Marchen", Var, 7}, + {"Mark", Var, 0}, + {"Masaram_Gondi", Var, 10}, + {"MaxASCII", Const, 0}, + {"MaxCase", Const, 0}, + {"MaxLatin1", Const, 0}, + {"MaxRune", Const, 0}, + {"Mc", Var, 0}, + {"Me", Var, 0}, + {"Medefaidrin", Var, 13}, + {"Meetei_Mayek", Var, 0}, + {"Mende_Kikakui", Var, 4}, + {"Meroitic_Cursive", Var, 1}, + {"Meroitic_Hieroglyphs", Var, 1}, + {"Miao", Var, 1}, + {"Mn", Var, 0}, + {"Modi", Var, 4}, + {"Mongolian", Var, 0}, + {"Mro", Var, 4}, + {"Multani", Var, 5}, + {"Myanmar", Var, 0}, + {"N", Var, 0}, + {"Nabataean", Var, 4}, + {"Nag_Mundari", Var, 21}, + {"Nandinagari", Var, 14}, + {"Nd", Var, 0}, + {"New_Tai_Lue", Var, 0}, + {"Newa", Var, 7}, + {"Nko", Var, 0}, + {"Nl", Var, 0}, + {"No", Var, 0}, + {"Noncharacter_Code_Point", Var, 0}, + {"Number", Var, 0}, + {"Nushu", Var, 10}, + {"Nyiakeng_Puachue_Hmong", Var, 14}, + {"Ogham", Var, 0}, + {"Ol_Chiki", Var, 0}, + {"Old_Hungarian", Var, 5}, + {"Old_Italic", Var, 0}, + {"Old_North_Arabian", Var, 4}, + {"Old_Permic", Var, 4}, + {"Old_Persian", Var, 0}, + {"Old_Sogdian", Var, 13}, + {"Old_South_Arabian", Var, 0}, + {"Old_Turkic", Var, 0}, + {"Old_Uyghur", Var, 21}, + {"Oriya", Var, 0}, + {"Osage", Var, 7}, + {"Osmanya", Var, 0}, + {"Other", Var, 0}, + {"Other_Alphabetic", Var, 0}, + {"Other_Default_Ignorable_Code_Point", Var, 0}, + {"Other_Grapheme_Extend", Var, 0}, + {"Other_ID_Continue", Var, 0}, + {"Other_ID_Start", Var, 0}, + {"Other_Lowercase", Var, 0}, + {"Other_Math", Var, 0}, + {"Other_Uppercase", Var, 0}, + {"P", Var, 0}, + {"Pahawh_Hmong", Var, 4}, + {"Palmyrene", Var, 4}, + {"Pattern_Syntax", Var, 0}, + {"Pattern_White_Space", Var, 0}, + {"Pau_Cin_Hau", Var, 4}, + {"Pc", Var, 0}, + {"Pd", Var, 0}, + {"Pe", Var, 0}, + {"Pf", Var, 0}, + {"Phags_Pa", Var, 0}, + {"Phoenician", Var, 0}, + {"Pi", Var, 0}, + {"Po", Var, 0}, + {"Prepended_Concatenation_Mark", Var, 7}, + {"PrintRanges", Var, 0}, + {"Properties", Var, 0}, + {"Ps", Var, 0}, + {"Psalter_Pahlavi", Var, 4}, + {"Punct", Var, 0}, + {"Quotation_Mark", Var, 0}, + {"Radical", Var, 0}, + {"Range16", Type, 0}, + {"Range16.Hi", Field, 0}, + {"Range16.Lo", Field, 0}, + {"Range16.Stride", Field, 0}, + {"Range32", Type, 0}, + {"Range32.Hi", Field, 0}, + {"Range32.Lo", Field, 0}, + {"Range32.Stride", Field, 0}, + {"RangeTable", Type, 0}, + {"RangeTable.LatinOffset", Field, 1}, + {"RangeTable.R16", Field, 0}, + {"RangeTable.R32", Field, 0}, + {"Regional_Indicator", Var, 10}, + {"Rejang", Var, 0}, + {"ReplacementChar", Const, 0}, + {"Runic", Var, 0}, + {"S", Var, 0}, + {"STerm", Var, 0}, + {"Samaritan", Var, 0}, + {"Saurashtra", Var, 0}, + {"Sc", Var, 0}, + {"Scripts", Var, 0}, + {"Sentence_Terminal", Var, 7}, + {"Sharada", Var, 1}, + {"Shavian", Var, 0}, + {"Siddham", Var, 4}, + {"SignWriting", Var, 5}, + {"SimpleFold", Func, 0}, + {"Sinhala", Var, 0}, + {"Sk", Var, 0}, + {"Sm", Var, 0}, + {"So", Var, 0}, + {"Soft_Dotted", Var, 0}, + {"Sogdian", Var, 13}, + {"Sora_Sompeng", Var, 1}, + {"Soyombo", Var, 10}, + {"Space", Var, 0}, + {"SpecialCase", Type, 0}, + {"Sundanese", Var, 0}, + {"Syloti_Nagri", Var, 0}, + {"Symbol", Var, 0}, + {"Syriac", Var, 0}, + {"Tagalog", Var, 0}, + {"Tagbanwa", Var, 0}, + {"Tai_Le", Var, 0}, + {"Tai_Tham", Var, 0}, + {"Tai_Viet", Var, 0}, + {"Takri", Var, 1}, + {"Tamil", Var, 0}, + {"Tangsa", Var, 21}, + {"Tangut", Var, 7}, + {"Telugu", Var, 0}, + {"Terminal_Punctuation", Var, 0}, + {"Thaana", Var, 0}, + {"Thai", Var, 0}, + {"Tibetan", Var, 0}, + {"Tifinagh", Var, 0}, + {"Tirhuta", Var, 4}, + {"Title", Var, 0}, + {"TitleCase", Const, 0}, + {"To", Func, 0}, + {"ToLower", Func, 0}, + {"ToTitle", Func, 0}, + {"ToUpper", Func, 0}, + {"Toto", Var, 21}, + {"TurkishCase", Var, 0}, + {"Ugaritic", Var, 0}, + {"Unified_Ideograph", Var, 0}, + {"Upper", Var, 0}, + {"UpperCase", Const, 0}, + {"UpperLower", Const, 0}, + {"Vai", Var, 0}, + {"Variation_Selector", Var, 0}, + {"Version", Const, 0}, + {"Vithkuqi", Var, 21}, + {"Wancho", Var, 14}, + {"Warang_Citi", Var, 4}, + {"White_Space", Var, 0}, + {"Yezidi", Var, 16}, + {"Yi", Var, 0}, + {"Z", Var, 0}, + {"Zanabazar_Square", Var, 10}, + {"Zl", Var, 0}, + {"Zp", Var, 0}, + {"Zs", Var, 0}, + }, + "unicode/utf16": { + {"AppendRune", Func, 20}, + {"Decode", Func, 0}, + {"DecodeRune", Func, 0}, + {"Encode", Func, 0}, + {"EncodeRune", Func, 0}, + {"IsSurrogate", Func, 0}, + {"RuneLen", Func, 23}, + }, + "unicode/utf8": { + {"AppendRune", Func, 18}, + {"DecodeLastRune", Func, 0}, + {"DecodeLastRuneInString", Func, 0}, + {"DecodeRune", Func, 0}, + {"DecodeRuneInString", Func, 0}, + {"EncodeRune", Func, 0}, + {"FullRune", Func, 0}, + {"FullRuneInString", Func, 0}, + {"MaxRune", Const, 0}, + {"RuneCount", Func, 0}, + {"RuneCountInString", Func, 0}, + {"RuneError", Const, 0}, + {"RuneLen", Func, 0}, + {"RuneSelf", Const, 0}, + {"RuneStart", Func, 0}, + {"UTFMax", Const, 0}, + {"Valid", Func, 0}, + {"ValidRune", Func, 1}, + {"ValidString", Func, 0}, + }, + "unique": { + {"(Handle).Value", Method, 23}, + {"Handle", Type, 23}, + {"Make", Func, 23}, + }, + "unsafe": { + {"Add", Func, 0}, + {"Alignof", Func, 0}, + {"Offsetof", Func, 0}, + {"Pointer", Type, 0}, + {"Sizeof", Func, 0}, + {"Slice", Func, 0}, + {"SliceData", Func, 0}, + {"String", Func, 0}, + {"StringData", Func, 0}, + }, +} diff --git a/tools/vendor/golang.org/x/tools/internal/stdlib/stdlib.go b/tools/vendor/golang.org/x/tools/internal/stdlib/stdlib.go new file mode 100644 index 000000000..98904017f --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/stdlib/stdlib.go @@ -0,0 +1,97 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:generate go run generate.go + +// Package stdlib provides a table of all exported symbols in the +// standard library, along with the version at which they first +// appeared. +package stdlib + +import ( + "fmt" + "strings" +) + +type Symbol struct { + Name string + Kind Kind + Version Version // Go version that first included the symbol +} + +// A Kind indicates the kind of a symbol: +// function, variable, constant, type, and so on. +type Kind int8 + +const ( + Invalid Kind = iota // Example name: + Type // "Buffer" + Func // "Println" + Var // "EOF" + Const // "Pi" + Field // "Point.X" + Method // "(*Buffer).Grow" +) + +func (kind Kind) String() string { + return [...]string{ + Invalid: "invalid", + Type: "type", + Func: "func", + Var: "var", + Const: "const", + Field: "field", + Method: "method", + }[kind] +} + +// A Version represents a version of Go of the form "go1.%d". +type Version int8 + +// String returns a version string of the form "go1.23", without allocating. +func (v Version) String() string { return versions[v] } + +var versions [30]string // (increase constant as needed) + +func init() { + for i := range versions { + versions[i] = fmt.Sprintf("go1.%d", i) + } +} + +// HasPackage reports whether the specified package path is part of +// the standard library's public API. +func HasPackage(path string) bool { + _, ok := PackageSymbols[path] + return ok +} + +// SplitField splits the field symbol name into type and field +// components. It must be called only on Field symbols. +// +// Example: "File.Package" -> ("File", "Package") +func (sym *Symbol) SplitField() (typename, name string) { + if sym.Kind != Field { + panic("not a field") + } + typename, name, _ = strings.Cut(sym.Name, ".") + return +} + +// SplitMethod splits the method symbol name into pointer, receiver, +// and method components. It must be called only on Method symbols. +// +// Example: "(*Buffer).Grow" -> (true, "Buffer", "Grow") +func (sym *Symbol) SplitMethod() (ptr bool, recv, name string) { + if sym.Kind != Method { + panic("not a method") + } + recv, name, _ = strings.Cut(sym.Name, ".") + recv = recv[len("(") : len(recv)-len(")")] + ptr = recv[0] == '*' + if ptr { + recv = recv[len("*"):] + } + return +} diff --git a/tools/vendor/golang.org/x/tools/internal/tokeninternal/tokeninternal.go b/tools/vendor/golang.org/x/tools/internal/tokeninternal/tokeninternal.go index 7e638ec24..ff9437a36 100644 --- a/tools/vendor/golang.org/x/tools/internal/tokeninternal/tokeninternal.go +++ b/tools/vendor/golang.org/x/tools/internal/tokeninternal/tokeninternal.go @@ -34,30 +34,16 @@ func GetLines(file *token.File) []int { lines []int _ []struct{} } - type tokenFile118 struct { - _ *token.FileSet // deleted in go1.19 - tokenFile119 - } - - type uP = unsafe.Pointer - switch unsafe.Sizeof(*file) { - case unsafe.Sizeof(tokenFile118{}): - var ptr *tokenFile118 - *(*uP)(uP(&ptr)) = uP(file) - ptr.mu.Lock() - defer ptr.mu.Unlock() - return ptr.lines - case unsafe.Sizeof(tokenFile119{}): - var ptr *tokenFile119 - *(*uP)(uP(&ptr)) = uP(file) - ptr.mu.Lock() - defer ptr.mu.Unlock() - return ptr.lines - - default: + if unsafe.Sizeof(*file) != unsafe.Sizeof(tokenFile119{}) { panic("unexpected token.File size") } + var ptr *tokenFile119 + type uP = unsafe.Pointer + *(*uP)(uP(&ptr)) = uP(file) + ptr.mu.Lock() + defer ptr.mu.Unlock() + return ptr.lines } // AddExistingFiles adds the specified files to the FileSet if they diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/common.go b/tools/vendor/golang.org/x/tools/internal/typeparams/common.go index d0d0649fe..89bd256dc 100644 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/common.go +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/common.go @@ -2,20 +2,10 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package typeparams contains common utilities for writing tools that interact -// with generic Go code, as introduced with Go 1.18. -// -// Many of the types and functions in this package are proxies for the new APIs -// introduced in the standard library with Go 1.18. For example, the -// typeparams.Union type is an alias for go/types.Union, and the ForTypeSpec -// function returns the value of the go/ast.TypeSpec.TypeParams field. At Go -// versions older than 1.18 these helpers are implemented as stubs, allowing -// users of this package to write code that handles generic constructs inline, -// even if the Go version being used to compile does not support generics. -// -// Additionally, this package contains common utilities for working with the -// new generic constructs, to supplement the standard library APIs. Notably, -// the StructuralTerms API computes a minimal representation of the structural +// Package typeparams contains common utilities for writing tools that +// interact with generic Go code, as introduced with Go 1.18. It +// supplements the standard library APIs. Notably, the StructuralTerms +// API computes a minimal representation of the structural // restrictions on a type parameter. // // An external version of these APIs is available in the @@ -23,10 +13,11 @@ package typeparams import ( - "fmt" "go/ast" "go/token" "go/types" + + "golang.org/x/tools/internal/aliases" ) // UnpackIndexExpr extracts data from AST nodes that represent index @@ -42,7 +33,7 @@ func UnpackIndexExpr(n ast.Node) (x ast.Expr, lbrack token.Pos, indices []ast.Ex switch e := n.(type) { case *ast.IndexExpr: return e.X, e.Lbrack, []ast.Expr{e.Index}, e.Rbrack - case *IndexListExpr: + case *ast.IndexListExpr: return e.X, e.Lbrack, e.Indices, e.Rbrack } return nil, token.NoPos, nil, token.NoPos @@ -63,7 +54,7 @@ func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack toke Rbrack: rbrack, } default: - return &IndexListExpr{ + return &ast.IndexListExpr{ X: x, Lbrack: lbrack, Indices: indices, @@ -72,73 +63,17 @@ func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack toke } } -// IsTypeParam reports whether t is a type parameter. +// IsTypeParam reports whether t is a type parameter (or an alias of one). func IsTypeParam(t types.Type) bool { - _, ok := t.(*TypeParam) + _, ok := aliases.Unalias(t).(*types.TypeParam) return ok } -// OriginMethod returns the origin method associated with the method fn. -// For methods on a non-generic receiver base type, this is just -// fn. However, for methods with a generic receiver, OriginMethod returns the -// corresponding method in the method set of the origin type. -// -// As a special case, if fn is not a method (has no receiver), OriginMethod -// returns fn. -func OriginMethod(fn *types.Func) *types.Func { - recv := fn.Type().(*types.Signature).Recv() - if recv == nil { - return fn - } - base := recv.Type() - p, isPtr := base.(*types.Pointer) - if isPtr { - base = p.Elem() - } - named, isNamed := base.(*types.Named) - if !isNamed { - // Receiver is a *types.Interface. - return fn - } - if ForNamed(named).Len() == 0 { - // Receiver base has no type parameters, so we can avoid the lookup below. - return fn - } - orig := NamedTypeOrigin(named) - gfn, _, _ := types.LookupFieldOrMethod(orig, true, fn.Pkg(), fn.Name()) - - // This is a fix for a gopls crash (#60628) due to a go/types bug (#60634). In: - // package p - // type T *int - // func (*T) f() {} - // LookupFieldOrMethod(T, true, p, f)=nil, but NewMethodSet(*T)={(*T).f}. - // Here we make them consistent by force. - // (The go/types bug is general, but this workaround is reached only - // for generic T thanks to the early return above.) - if gfn == nil { - mset := types.NewMethodSet(types.NewPointer(orig)) - for i := 0; i < mset.Len(); i++ { - m := mset.At(i) - if m.Obj().Id() == fn.Id() { - gfn = m.Obj() - break - } - } - } - - // In golang/go#61196, we observe another crash, this time inexplicable. - if gfn == nil { - panic(fmt.Sprintf("missing origin method for %s.%s; named == origin: %t, named.NumMethods(): %d, origin.NumMethods(): %d", named, fn, named == orig, named.NumMethods(), orig.NumMethods())) - } - - return gfn.(*types.Func) -} - // GenericAssignableTo is a generalization of types.AssignableTo that // implements the following rule for uninstantiated generic types: // // If V and T are generic named types, then V is considered assignable to T if, -// for every possible instantation of V[A_1, ..., A_N], the instantiation +// for every possible instantiation of V[A_1, ..., A_N], the instantiation // T[A_1, ..., A_N] is valid and V[A_1, ..., A_N] implements T[A_1, ..., A_N]. // // If T has structural constraints, they must be satisfied by V. @@ -157,7 +92,10 @@ func OriginMethod(fn *types.Func) *types.Func { // // In this case, GenericAssignableTo reports that instantiations of Container // are assignable to the corresponding instantiation of Interface. -func GenericAssignableTo(ctxt *Context, V, T types.Type) bool { +func GenericAssignableTo(ctxt *types.Context, V, T types.Type) bool { + V = aliases.Unalias(V) + T = aliases.Unalias(T) + // If V and T are not both named, or do not have matching non-empty type // parameter lists, fall back on types.AssignableTo. @@ -167,9 +105,9 @@ func GenericAssignableTo(ctxt *Context, V, T types.Type) bool { return types.AssignableTo(V, T) } - vtparams := ForNamed(VN) - ttparams := ForNamed(TN) - if vtparams.Len() == 0 || vtparams.Len() != ttparams.Len() || NamedTypeArgs(VN).Len() != 0 || NamedTypeArgs(TN).Len() != 0 { + vtparams := VN.TypeParams() + ttparams := TN.TypeParams() + if vtparams.Len() == 0 || vtparams.Len() != ttparams.Len() || VN.TypeArgs().Len() != 0 || TN.TypeArgs().Len() != 0 { return types.AssignableTo(V, T) } @@ -182,7 +120,7 @@ func GenericAssignableTo(ctxt *Context, V, T types.Type) bool { // Minor optimization: ensure we share a context across the two // instantiations below. if ctxt == nil { - ctxt = NewContext() + ctxt = types.NewContext() } var targs []types.Type @@ -190,12 +128,12 @@ func GenericAssignableTo(ctxt *Context, V, T types.Type) bool { targs = append(targs, vtparams.At(i)) } - vinst, err := Instantiate(ctxt, V, targs, true) + vinst, err := types.Instantiate(ctxt, V, targs, true) if err != nil { panic("type parameters should satisfy their own constraints") } - tinst, err := Instantiate(ctxt, T, targs, true) + tinst, err := types.Instantiate(ctxt, T, targs, true) if err != nil { return false } diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/coretype.go b/tools/vendor/golang.org/x/tools/internal/typeparams/coretype.go index 71248209e..6e83c6fb1 100644 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/coretype.go +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/coretype.go @@ -5,6 +5,7 @@ package typeparams import ( + "fmt" "go/types" ) @@ -17,7 +18,7 @@ func CoreType(T types.Type) types.Type { return U // for non-interface types, } - terms, err := _NormalTerms(U) + terms, err := NormalTerms(U) if len(terms) == 0 || err != nil { // len(terms) -> empty type set of interface. // err != nil => U is invalid, exceeds complexity bounds, or has an empty type set. @@ -63,7 +64,7 @@ func CoreType(T types.Type) types.Type { return ch } -// _NormalTerms returns a slice of terms representing the normalized structural +// NormalTerms returns a slice of terms representing the normalized structural // type restrictions of a type, if any. // // For all types other than *types.TypeParam, *types.Interface, and @@ -93,30 +94,57 @@ func CoreType(T types.Type) types.Type { // expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, // which when intersected with C (~string|~int) yields ~string|int. // -// _NormalTerms computes these expansions and reductions, producing a +// NormalTerms computes these expansions and reductions, producing a // "normalized" form of the embeddings. A structural restriction is normalized // if it is a single union containing no interface terms, and is minimal in the // sense that removing any term changes the set of types satisfying the // constraint. It is left as a proof for the reader that, modulo sorting, there // is exactly one such normalized form. // -// Because the minimal representation always takes this form, _NormalTerms +// Because the minimal representation always takes this form, NormalTerms // returns a slice of tilde terms corresponding to the terms of the union in // the normalized structural restriction. An error is returned if the type is // invalid, exceeds complexity bounds, or has an empty type set. In the latter -// case, _NormalTerms returns ErrEmptyTypeSet. +// case, NormalTerms returns ErrEmptyTypeSet. // -// _NormalTerms makes no guarantees about the order of terms, except that it +// NormalTerms makes no guarantees about the order of terms, except that it // is deterministic. -func _NormalTerms(typ types.Type) ([]*Term, error) { - switch typ := typ.(type) { - case *TypeParam: +func NormalTerms(typ types.Type) ([]*types.Term, error) { + switch typ := typ.Underlying().(type) { + case *types.TypeParam: return StructuralTerms(typ) - case *Union: + case *types.Union: return UnionTermSet(typ) case *types.Interface: return InterfaceTermSet(typ) default: - return []*Term{NewTerm(false, typ)}, nil + return []*types.Term{types.NewTerm(false, typ)}, nil } } + +// Deref returns the type of the variable pointed to by t, +// if t's core type is a pointer; otherwise it returns t. +// +// Do not assume that Deref(T)==T implies T is not a pointer: +// consider "type T *T", for example. +// +// TODO(adonovan): ideally this would live in typesinternal, but that +// creates an import cycle. Move there when we melt this package down. +func Deref(t types.Type) types.Type { + if ptr, ok := CoreType(t).(*types.Pointer); ok { + return ptr.Elem() + } + return t +} + +// MustDeref returns the type of the variable pointed to by t. +// It panics if t's core type is not a pointer. +// +// TODO(adonovan): ideally this would live in typesinternal, but that +// creates an import cycle. Move there when we melt this package down. +func MustDeref(t types.Type) types.Type { + if ptr, ok := CoreType(t).(*types.Pointer); ok { + return ptr.Elem() + } + panic(fmt.Sprintf("%v is not a pointer", t)) +} diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go117.go b/tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go117.go deleted file mode 100644 index 18212390e..000000000 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go117.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.18 -// +build !go1.18 - -package typeparams - -// Enabled reports whether type parameters are enabled in the current build -// environment. -const Enabled = false diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go118.go b/tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go118.go deleted file mode 100644 index d67148823..000000000 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/enabled_go118.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.18 -// +build go1.18 - -package typeparams - -// Note: this constant is in a separate file as this is the only acceptable -// diff between the <1.18 API of this package and the 1.18 API. - -// Enabled reports whether type parameters are enabled in the current build -// environment. -const Enabled = true diff --git a/tools/vendor/golang.org/x/tools/go/ssa/parameterized.go b/tools/vendor/golang.org/x/tools/internal/typeparams/free.go similarity index 52% rename from tools/vendor/golang.org/x/tools/go/ssa/parameterized.go rename to tools/vendor/golang.org/x/tools/internal/typeparams/free.go index b90ee0e86..a1d138226 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/parameterized.go +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/free.go @@ -1,30 +1,33 @@ -// Copyright 2022 The Go Authors. All rights reserved. +// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package ssa +package typeparams import ( "go/types" - "golang.org/x/tools/internal/typeparams" + "golang.org/x/tools/internal/aliases" ) -// tpWalker walks over types looking for parameterized types. +// Free is a memoization of the set of free type parameters within a +// type. It makes a sequence of calls to [Free.Has] for overlapping +// types more efficient. The zero value is ready for use. // -// NOTE: Adapted from go/types/infer.go. If that is exported in a future release remove this copy. -type tpWalker struct { +// NOTE: Adapted from go/types/infer.go. If it is later exported, factor. +type Free struct { seen map[types.Type]bool } -// isParameterized returns true when typ reaches any type parameter. -func (w *tpWalker) isParameterized(typ types.Type) (res bool) { - // NOTE: Adapted from go/types/infer.go. Try to keep in sync. - +// Has reports whether the specified type has a free type parameter. +func (w *Free) Has(typ types.Type) (res bool) { // detect cycles if x, ok := w.seen[typ]; ok { return x } + if w.seen == nil { + w.seen = make(map[types.Type]bool) + } w.seen[typ] = false defer func() { w.seen[typ] = res @@ -34,26 +37,29 @@ func (w *tpWalker) isParameterized(typ types.Type) (res bool) { case nil, *types.Basic: // TODO(gri) should nil be handled here? break + case *aliases.Alias: + return w.Has(aliases.Unalias(t)) + case *types.Array: - return w.isParameterized(t.Elem()) + return w.Has(t.Elem()) case *types.Slice: - return w.isParameterized(t.Elem()) + return w.Has(t.Elem()) case *types.Struct: for i, n := 0, t.NumFields(); i < n; i++ { - if w.isParameterized(t.Field(i).Type()) { + if w.Has(t.Field(i).Type()) { return true } } case *types.Pointer: - return w.isParameterized(t.Elem()) + return w.Has(t.Elem()) case *types.Tuple: n := t.Len() for i := 0; i < n; i++ { - if w.isParameterized(t.At(i).Type()) { + if w.Has(t.At(i).Type()) { return true } } @@ -66,44 +72,44 @@ func (w *tpWalker) isParameterized(typ types.Type) (res bool) { // Similarly, the receiver of a method may declare (rather than // use) type parameters, we don't care about those either. // Thus, we only need to look at the input and result parameters. - return w.isParameterized(t.Params()) || w.isParameterized(t.Results()) + return w.Has(t.Params()) || w.Has(t.Results()) case *types.Interface: for i, n := 0, t.NumMethods(); i < n; i++ { - if w.isParameterized(t.Method(i).Type()) { + if w.Has(t.Method(i).Type()) { return true } } - terms, err := typeparams.InterfaceTermSet(t) + terms, err := InterfaceTermSet(t) if err != nil { - panic(err) + return false // ill typed } for _, term := range terms { - if w.isParameterized(term.Type()) { + if w.Has(term.Type()) { return true } } case *types.Map: - return w.isParameterized(t.Key()) || w.isParameterized(t.Elem()) + return w.Has(t.Key()) || w.Has(t.Elem()) case *types.Chan: - return w.isParameterized(t.Elem()) + return w.Has(t.Elem()) case *types.Named: - args := typeparams.NamedTypeArgs(t) + args := t.TypeArgs() // TODO(taking): this does not match go/types/infer.go. Check with rfindley. - if params := typeparams.ForNamed(t); params.Len() > args.Len() { + if params := t.TypeParams(); params.Len() > args.Len() { return true } for i, n := 0, args.Len(); i < n; i++ { - if w.isParameterized(args.At(i)) { + if w.Has(args.At(i)) { return true } } - return w.isParameterized(t.Underlying()) // recurse for types local to parameterized functions + return w.Has(t.Underlying()) // recurse for types local to parameterized functions - case *typeparams.TypeParam: + case *types.TypeParam: return true default: @@ -112,12 +118,3 @@ func (w *tpWalker) isParameterized(typ types.Type) (res bool) { return false } - -func (w *tpWalker) anyParameterized(ts []types.Type) bool { - for _, t := range ts { - if w.isParameterized(t) { - return true - } - } - return false -} diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/normalize.go b/tools/vendor/golang.org/x/tools/internal/typeparams/normalize.go index 9c631b651..93c80fdc9 100644 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/normalize.go +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/normalize.go @@ -60,7 +60,7 @@ var ErrEmptyTypeSet = errors.New("empty type set") // // StructuralTerms makes no guarantees about the order of terms, except that it // is deterministic. -func StructuralTerms(tparam *TypeParam) ([]*Term, error) { +func StructuralTerms(tparam *types.TypeParam) ([]*types.Term, error) { constraint := tparam.Constraint() if constraint == nil { return nil, fmt.Errorf("%s has nil constraint", tparam) @@ -78,7 +78,7 @@ func StructuralTerms(tparam *TypeParam) ([]*Term, error) { // // See the documentation of StructuralTerms for more information on // normalization. -func InterfaceTermSet(iface *types.Interface) ([]*Term, error) { +func InterfaceTermSet(iface *types.Interface) ([]*types.Term, error) { return computeTermSet(iface) } @@ -88,11 +88,11 @@ func InterfaceTermSet(iface *types.Interface) ([]*Term, error) { // // See the documentation of StructuralTerms for more information on // normalization. -func UnionTermSet(union *Union) ([]*Term, error) { +func UnionTermSet(union *types.Union) ([]*types.Term, error) { return computeTermSet(union) } -func computeTermSet(typ types.Type) ([]*Term, error) { +func computeTermSet(typ types.Type) ([]*types.Term, error) { tset, err := computeTermSetInternal(typ, make(map[types.Type]*termSet), 0) if err != nil { return nil, err @@ -103,9 +103,9 @@ func computeTermSet(typ types.Type) ([]*Term, error) { if tset.terms.isAll() { return nil, nil } - var terms []*Term + var terms []*types.Term for _, term := range tset.terms { - terms = append(terms, NewTerm(term.tilde, term.typ)) + terms = append(terms, types.NewTerm(term.tilde, term.typ)) } return terms, nil } @@ -162,7 +162,7 @@ func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth in tset.terms = allTermlist for i := 0; i < u.NumEmbeddeds(); i++ { embedded := u.EmbeddedType(i) - if _, ok := embedded.Underlying().(*TypeParam); ok { + if _, ok := embedded.Underlying().(*types.TypeParam); ok { return nil, fmt.Errorf("invalid embedded type %T", embedded) } tset2, err := computeTermSetInternal(embedded, seen, depth+1) @@ -171,7 +171,7 @@ func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth in } tset.terms = tset.terms.intersect(tset2.terms) } - case *Union: + case *types.Union: // The term set of a union is the union of term sets of its terms. tset.terms = nil for i := 0; i < u.Len(); i++ { @@ -184,7 +184,7 @@ func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth in return nil, err } terms = tset2.terms - case *TypeParam, *Union: + case *types.TypeParam, *types.Union: // A stand-alone type parameter or union is not permitted as union // term. return nil, fmt.Errorf("invalid union term %T", t) @@ -199,7 +199,7 @@ func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth in return nil, fmt.Errorf("exceeded max term count %d", maxTermCount) } } - case *TypeParam: + case *types.TypeParam: panic("unreachable") default: // For all other types, the term set is just a single non-tilde term diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go b/tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go deleted file mode 100644 index 7ed86e171..000000000 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go117.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.18 -// +build !go1.18 - -package typeparams - -import ( - "go/ast" - "go/token" - "go/types" -) - -func unsupported() { - panic("type parameters are unsupported at this go version") -} - -// IndexListExpr is a placeholder type, as type parameters are not supported at -// this Go version. Its methods panic on use. -type IndexListExpr struct { - ast.Expr - X ast.Expr // expression - Lbrack token.Pos // position of "[" - Indices []ast.Expr // index expressions - Rbrack token.Pos // position of "]" -} - -// ForTypeSpec returns an empty field list, as type parameters on not supported -// at this Go version. -func ForTypeSpec(*ast.TypeSpec) *ast.FieldList { - return nil -} - -// ForFuncType returns an empty field list, as type parameters are not -// supported at this Go version. -func ForFuncType(*ast.FuncType) *ast.FieldList { - return nil -} - -// TypeParam is a placeholder type, as type parameters are not supported at -// this Go version. Its methods panic on use. -type TypeParam struct{ types.Type } - -func (*TypeParam) Index() int { unsupported(); return 0 } -func (*TypeParam) Constraint() types.Type { unsupported(); return nil } -func (*TypeParam) Obj() *types.TypeName { unsupported(); return nil } - -// TypeParamList is a placeholder for an empty type parameter list. -type TypeParamList struct{} - -func (*TypeParamList) Len() int { return 0 } -func (*TypeParamList) At(int) *TypeParam { unsupported(); return nil } - -// TypeList is a placeholder for an empty type list. -type TypeList struct{} - -func (*TypeList) Len() int { return 0 } -func (*TypeList) At(int) types.Type { unsupported(); return nil } - -// NewTypeParam is unsupported at this Go version, and panics. -func NewTypeParam(name *types.TypeName, constraint types.Type) *TypeParam { - unsupported() - return nil -} - -// SetTypeParamConstraint is unsupported at this Go version, and panics. -func SetTypeParamConstraint(tparam *TypeParam, constraint types.Type) { - unsupported() -} - -// NewSignatureType calls types.NewSignature, panicking if recvTypeParams or -// typeParams is non-empty. -func NewSignatureType(recv *types.Var, recvTypeParams, typeParams []*TypeParam, params, results *types.Tuple, variadic bool) *types.Signature { - if len(recvTypeParams) != 0 || len(typeParams) != 0 { - panic("signatures cannot have type parameters at this Go version") - } - return types.NewSignature(recv, params, results, variadic) -} - -// ForSignature returns an empty slice. -func ForSignature(*types.Signature) *TypeParamList { - return nil -} - -// RecvTypeParams returns a nil slice. -func RecvTypeParams(sig *types.Signature) *TypeParamList { - return nil -} - -// IsComparable returns false, as no interfaces are type-restricted at this Go -// version. -func IsComparable(*types.Interface) bool { - return false -} - -// IsMethodSet returns true, as no interfaces are type-restricted at this Go -// version. -func IsMethodSet(*types.Interface) bool { - return true -} - -// IsImplicit returns false, as no interfaces are implicit at this Go version. -func IsImplicit(*types.Interface) bool { - return false -} - -// MarkImplicit does nothing, because this Go version does not have implicit -// interfaces. -func MarkImplicit(*types.Interface) {} - -// ForNamed returns an empty type parameter list, as type parameters are not -// supported at this Go version. -func ForNamed(*types.Named) *TypeParamList { - return nil -} - -// SetForNamed panics if tparams is non-empty. -func SetForNamed(_ *types.Named, tparams []*TypeParam) { - if len(tparams) > 0 { - unsupported() - } -} - -// NamedTypeArgs returns nil. -func NamedTypeArgs(*types.Named) *TypeList { - return nil -} - -// NamedTypeOrigin is the identity method at this Go version. -func NamedTypeOrigin(named *types.Named) *types.Named { - return named -} - -// Term holds information about a structural type restriction. -type Term struct { - tilde bool - typ types.Type -} - -func (m *Term) Tilde() bool { return m.tilde } -func (m *Term) Type() types.Type { return m.typ } -func (m *Term) String() string { - pre := "" - if m.tilde { - pre = "~" - } - return pre + m.typ.String() -} - -// NewTerm is unsupported at this Go version, and panics. -func NewTerm(tilde bool, typ types.Type) *Term { - return &Term{tilde, typ} -} - -// Union is a placeholder type, as type parameters are not supported at this Go -// version. Its methods panic on use. -type Union struct{ types.Type } - -func (*Union) Len() int { return 0 } -func (*Union) Term(i int) *Term { unsupported(); return nil } - -// NewUnion is unsupported at this Go version, and panics. -func NewUnion(terms []*Term) *Union { - unsupported() - return nil -} - -// InitInstanceInfo is a noop at this Go version. -func InitInstanceInfo(*types.Info) {} - -// Instance is a placeholder type, as type parameters are not supported at this -// Go version. -type Instance struct { - TypeArgs *TypeList - Type types.Type -} - -// GetInstances returns a nil map, as type parameters are not supported at this -// Go version. -func GetInstances(info *types.Info) map[*ast.Ident]Instance { return nil } - -// Context is a placeholder type, as type parameters are not supported at -// this Go version. -type Context struct{} - -// NewContext returns a placeholder Context instance. -func NewContext() *Context { - return &Context{} -} - -// Instantiate is unsupported on this Go version, and panics. -func Instantiate(ctxt *Context, typ types.Type, targs []types.Type, validate bool) (types.Type, error) { - unsupported() - return nil, nil -} diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go b/tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go deleted file mode 100644 index cf301af1d..000000000 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/typeparams_go118.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.18 -// +build go1.18 - -package typeparams - -import ( - "go/ast" - "go/types" -) - -// IndexListExpr is an alias for ast.IndexListExpr. -type IndexListExpr = ast.IndexListExpr - -// ForTypeSpec returns n.TypeParams. -func ForTypeSpec(n *ast.TypeSpec) *ast.FieldList { - if n == nil { - return nil - } - return n.TypeParams -} - -// ForFuncType returns n.TypeParams. -func ForFuncType(n *ast.FuncType) *ast.FieldList { - if n == nil { - return nil - } - return n.TypeParams -} - -// TypeParam is an alias for types.TypeParam -type TypeParam = types.TypeParam - -// TypeParamList is an alias for types.TypeParamList -type TypeParamList = types.TypeParamList - -// TypeList is an alias for types.TypeList -type TypeList = types.TypeList - -// NewTypeParam calls types.NewTypeParam. -func NewTypeParam(name *types.TypeName, constraint types.Type) *TypeParam { - return types.NewTypeParam(name, constraint) -} - -// SetTypeParamConstraint calls tparam.SetConstraint(constraint). -func SetTypeParamConstraint(tparam *TypeParam, constraint types.Type) { - tparam.SetConstraint(constraint) -} - -// NewSignatureType calls types.NewSignatureType. -func NewSignatureType(recv *types.Var, recvTypeParams, typeParams []*TypeParam, params, results *types.Tuple, variadic bool) *types.Signature { - return types.NewSignatureType(recv, recvTypeParams, typeParams, params, results, variadic) -} - -// ForSignature returns sig.TypeParams() -func ForSignature(sig *types.Signature) *TypeParamList { - return sig.TypeParams() -} - -// RecvTypeParams returns sig.RecvTypeParams(). -func RecvTypeParams(sig *types.Signature) *TypeParamList { - return sig.RecvTypeParams() -} - -// IsComparable calls iface.IsComparable(). -func IsComparable(iface *types.Interface) bool { - return iface.IsComparable() -} - -// IsMethodSet calls iface.IsMethodSet(). -func IsMethodSet(iface *types.Interface) bool { - return iface.IsMethodSet() -} - -// IsImplicit calls iface.IsImplicit(). -func IsImplicit(iface *types.Interface) bool { - return iface.IsImplicit() -} - -// MarkImplicit calls iface.MarkImplicit(). -func MarkImplicit(iface *types.Interface) { - iface.MarkImplicit() -} - -// ForNamed extracts the (possibly empty) type parameter object list from -// named. -func ForNamed(named *types.Named) *TypeParamList { - return named.TypeParams() -} - -// SetForNamed sets the type params tparams on n. Each tparam must be of -// dynamic type *types.TypeParam. -func SetForNamed(n *types.Named, tparams []*TypeParam) { - n.SetTypeParams(tparams) -} - -// NamedTypeArgs returns named.TypeArgs(). -func NamedTypeArgs(named *types.Named) *TypeList { - return named.TypeArgs() -} - -// NamedTypeOrigin returns named.Orig(). -func NamedTypeOrigin(named *types.Named) *types.Named { - return named.Origin() -} - -// Term is an alias for types.Term. -type Term = types.Term - -// NewTerm calls types.NewTerm. -func NewTerm(tilde bool, typ types.Type) *Term { - return types.NewTerm(tilde, typ) -} - -// Union is an alias for types.Union -type Union = types.Union - -// NewUnion calls types.NewUnion. -func NewUnion(terms []*Term) *Union { - return types.NewUnion(terms) -} - -// InitInstanceInfo initializes info to record information about type and -// function instances. -func InitInstanceInfo(info *types.Info) { - info.Instances = make(map[*ast.Ident]types.Instance) -} - -// Instance is an alias for types.Instance. -type Instance = types.Instance - -// GetInstances returns info.Instances. -func GetInstances(info *types.Info) map[*ast.Ident]Instance { - return info.Instances -} - -// Context is an alias for types.Context. -type Context = types.Context - -// NewContext calls types.NewContext. -func NewContext() *Context { - return types.NewContext() -} - -// Instantiate calls types.Instantiate. -func Instantiate(ctxt *Context, typ types.Type, targs []types.Type, validate bool) (types.Type, error) { - return types.Instantiate(ctxt, typ, targs, validate) -} diff --git a/tools/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go b/tools/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go index 07484073a..834e05381 100644 --- a/tools/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go +++ b/tools/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go @@ -167,7 +167,7 @@ const ( UntypedNilUse // WrongAssignCount occurs when the number of values on the right-hand side - // of an assignment or or initialization expression does not match the number + // of an assignment or initialization expression does not match the number // of variables on the left-hand side. // // Example: @@ -1449,10 +1449,10 @@ const ( NotAGenericType // WrongTypeArgCount occurs when a type or function is instantiated with an - // incorrent number of type arguments, including when a generic type or + // incorrect number of type arguments, including when a generic type or // function is used without instantiation. // - // Errors inolving failed type inference are assigned other error codes. + // Errors involving failed type inference are assigned other error codes. // // Example: // type T[p any] int diff --git a/tools/vendor/golang.org/x/tools/internal/typesinternal/objectpath.go b/tools/vendor/golang.org/x/tools/internal/typesinternal/objectpath.go deleted file mode 100644 index 5e96e8955..000000000 --- a/tools/vendor/golang.org/x/tools/internal/typesinternal/objectpath.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2023 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package typesinternal - -import "go/types" - -// This file contains back doors that allow gopls to avoid method sorting when -// using the objectpath package. -// -// This is performance-critical in certain repositories, but changing the -// behavior of the objectpath package is still being discussed in -// golang/go#61443. If we decide to remove the sorting in objectpath we can -// simply delete these back doors. Otherwise, we should add a new API to -// objectpath that allows controlling the sorting. - -// SkipEncoderMethodSorting marks enc (which must be an *objectpath.Encoder) as -// not requiring sorted methods. -var SkipEncoderMethodSorting func(enc interface{}) - -// ObjectpathObject is like objectpath.Object, but allows suppressing method -// sorting. -var ObjectpathObject func(pkg *types.Package, p string, skipMethodSorting bool) (types.Object, error) diff --git a/tools/vendor/golang.org/x/tools/internal/typesinternal/recv.go b/tools/vendor/golang.org/x/tools/internal/typesinternal/recv.go new file mode 100644 index 000000000..fea7c8b75 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/typesinternal/recv.go @@ -0,0 +1,43 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typesinternal + +import ( + "go/types" + + "golang.org/x/tools/internal/aliases" +) + +// ReceiverNamed returns the named type (if any) associated with the +// type of recv, which may be of the form N or *N, or aliases thereof. +// It also reports whether a Pointer was present. +func ReceiverNamed(recv *types.Var) (isPtr bool, named *types.Named) { + t := recv.Type() + if ptr, ok := aliases.Unalias(t).(*types.Pointer); ok { + isPtr = true + t = ptr.Elem() + } + named, _ = aliases.Unalias(t).(*types.Named) + return +} + +// Unpointer returns T given *T or an alias thereof. +// For all other types it is the identity function. +// It does not look at underlying types. +// The result may be an alias. +// +// Use this function to strip off the optional pointer on a receiver +// in a field or method selection, without losing the named type +// (which is needed to compute the method set). +// +// See also [typeparams.MustDeref], which removes one level of +// indirection from the type, regardless of named types (analogous to +// a LOAD instruction). +func Unpointer(t types.Type) types.Type { + if ptr, ok := aliases.Unalias(t).(*types.Pointer); ok { + return ptr.Elem() + } + return t +} diff --git a/tools/vendor/golang.org/x/tools/internal/typesinternal/toonew.go b/tools/vendor/golang.org/x/tools/internal/typesinternal/toonew.go new file mode 100644 index 000000000..cc86487ea --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/typesinternal/toonew.go @@ -0,0 +1,89 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typesinternal + +import ( + "go/types" + + "golang.org/x/tools/internal/stdlib" + "golang.org/x/tools/internal/versions" +) + +// TooNewStdSymbols computes the set of package-level symbols +// exported by pkg that are not available at the specified version. +// The result maps each symbol to its minimum version. +// +// The pkg is allowed to contain type errors. +func TooNewStdSymbols(pkg *types.Package, version string) map[types.Object]string { + disallowed := make(map[types.Object]string) + + // Pass 1: package-level symbols. + symbols := stdlib.PackageSymbols[pkg.Path()] + for _, sym := range symbols { + symver := sym.Version.String() + if versions.Before(version, symver) { + switch sym.Kind { + case stdlib.Func, stdlib.Var, stdlib.Const, stdlib.Type: + disallowed[pkg.Scope().Lookup(sym.Name)] = symver + } + } + } + + // Pass 2: fields and methods. + // + // We allow fields and methods if their associated type is + // disallowed, as otherwise we would report false positives + // for compatibility shims. Consider: + // + // //go:build go1.22 + // type T struct { F std.Real } // correct new API + // + // //go:build !go1.22 + // type T struct { F fake } // shim + // type fake struct { ... } + // func (fake) M () {} + // + // These alternative declarations of T use either the std.Real + // type, introduced in go1.22, or a fake type, for the field + // F. (The fakery could be arbitrarily deep, involving more + // nested fields and methods than are shown here.) Clients + // that use the compatibility shim T will compile with any + // version of go, whether older or newer than go1.22, but only + // the newer version will use the std.Real implementation. + // + // Now consider a reference to method M in new(T).F.M() in a + // module that requires a minimum of go1.21. The analysis may + // occur using a version of Go higher than 1.21, selecting the + // first version of T, so the method M is Real.M. This would + // spuriously cause the analyzer to report a reference to a + // too-new symbol even though this expression compiles just + // fine (with the fake implementation) using go1.21. + for _, sym := range symbols { + symVersion := sym.Version.String() + if !versions.Before(version, symVersion) { + continue // allowed + } + + var obj types.Object + switch sym.Kind { + case stdlib.Field: + typename, name := sym.SplitField() + if t := pkg.Scope().Lookup(typename); t != nil && disallowed[t] == "" { + obj, _, _ = types.LookupFieldOrMethod(t.Type(), false, pkg, name) + } + + case stdlib.Method: + ptr, recvname, name := sym.SplitMethod() + if t := pkg.Scope().Lookup(recvname); t != nil && disallowed[t] == "" { + obj, _, _ = types.LookupFieldOrMethod(t.Type(), ptr, pkg, name) + } + } + if obj != nil { + disallowed[obj] = symVersion + } + } + + return disallowed +} diff --git a/tools/vendor/golang.org/x/tools/internal/typesinternal/types.go b/tools/vendor/golang.org/x/tools/internal/typesinternal/types.go index ce7d4351b..839232861 100644 --- a/tools/vendor/golang.org/x/tools/internal/typesinternal/types.go +++ b/tools/vendor/golang.org/x/tools/internal/typesinternal/types.go @@ -49,4 +49,17 @@ func ReadGo116ErrorData(err types.Error) (code ErrorCode, start, end token.Pos, return ErrorCode(data[0]), token.Pos(data[1]), token.Pos(data[2]), true } -var SetGoVersion = func(conf *types.Config, version string) bool { return false } +// NameRelativeTo returns a types.Qualifier that qualifies members of +// all packages other than pkg, using only the package name. +// (By contrast, [types.RelativeTo] uses the complete package path, +// which is often excessive.) +// +// If pkg is nil, it is equivalent to [*types.Package.Name]. +func NameRelativeTo(pkg *types.Package) types.Qualifier { + return func(other *types.Package) string { + if pkg != nil && pkg == other { + return "" // same package; unqualified + } + return other.Name() + } +} diff --git a/tools/vendor/golang.org/x/tools/internal/typesinternal/types_118.go b/tools/vendor/golang.org/x/tools/internal/typesinternal/types_118.go deleted file mode 100644 index a42b072a6..000000000 --- a/tools/vendor/golang.org/x/tools/internal/typesinternal/types_118.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.18 -// +build go1.18 - -package typesinternal - -import ( - "go/types" -) - -func init() { - SetGoVersion = func(conf *types.Config, version string) bool { - conf.GoVersion = version - return true - } -} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/constraint.go b/tools/vendor/golang.org/x/tools/internal/versions/constraint.go new file mode 100644 index 000000000..179063d48 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/constraint.go @@ -0,0 +1,13 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package versions + +import "go/build/constraint" + +// ConstraintGoVersion is constraint.GoVersion (if built with go1.21+). +// Otherwise nil. +// +// Deprecate once x/tools is after go1.21. +var ConstraintGoVersion func(x constraint.Expr) string diff --git a/tools/vendor/golang.org/x/tools/internal/versions/constraint_go121.go b/tools/vendor/golang.org/x/tools/internal/versions/constraint_go121.go new file mode 100644 index 000000000..38011407d --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/constraint_go121.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.21 +// +build go1.21 + +package versions + +import "go/build/constraint" + +func init() { + ConstraintGoVersion = constraint.GoVersion +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/features.go b/tools/vendor/golang.org/x/tools/internal/versions/features.go new file mode 100644 index 000000000..b53f17861 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/features.go @@ -0,0 +1,43 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package versions + +// This file contains predicates for working with file versions to +// decide when a tool should consider a language feature enabled. + +// GoVersions that features in x/tools can be gated to. +const ( + Go1_18 = "go1.18" + Go1_19 = "go1.19" + Go1_20 = "go1.20" + Go1_21 = "go1.21" + Go1_22 = "go1.22" +) + +// Future is an invalid unknown Go version sometime in the future. +// Do not use directly with Compare. +const Future = "" + +// AtLeast reports whether the file version v comes after a Go release. +// +// Use this predicate to enable a behavior once a certain Go release +// has happened (and stays enabled in the future). +func AtLeast(v, release string) bool { + if v == Future { + return true // an unknown future version is always after y. + } + return Compare(Lang(v), Lang(release)) >= 0 +} + +// Before reports whether the file version v is strictly before a Go release. +// +// Use this predicate to disable a behavior once a certain Go release +// has happened (and stays enabled in the future). +func Before(v, release string) bool { + if v == Future { + return false // an unknown future version happens after y. + } + return Compare(Lang(v), Lang(release)) < 0 +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/gover.go b/tools/vendor/golang.org/x/tools/internal/versions/gover.go new file mode 100644 index 000000000..bbabcd22e --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/gover.go @@ -0,0 +1,172 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This is a fork of internal/gover for use by x/tools until +// go1.21 and earlier are no longer supported by x/tools. + +package versions + +import "strings" + +// A gover is a parsed Go gover: major[.Minor[.Patch]][kind[pre]] +// The numbers are the original decimal strings to avoid integer overflows +// and since there is very little actual math. (Probably overflow doesn't matter in practice, +// but at the time this code was written, there was an existing test that used +// go1.99999999999, which does not fit in an int on 32-bit platforms. +// The "big decimal" representation avoids the problem entirely.) +type gover struct { + major string // decimal + minor string // decimal or "" + patch string // decimal or "" + kind string // "", "alpha", "beta", "rc" + pre string // decimal or "" +} + +// compare returns -1, 0, or +1 depending on whether +// x < y, x == y, or x > y, interpreted as toolchain versions. +// The versions x and y must not begin with a "go" prefix: just "1.21" not "go1.21". +// Malformed versions compare less than well-formed versions and equal to each other. +// The language version "1.21" compares less than the release candidate and eventual releases "1.21rc1" and "1.21.0". +func compare(x, y string) int { + vx := parse(x) + vy := parse(y) + + if c := cmpInt(vx.major, vy.major); c != 0 { + return c + } + if c := cmpInt(vx.minor, vy.minor); c != 0 { + return c + } + if c := cmpInt(vx.patch, vy.patch); c != 0 { + return c + } + if c := strings.Compare(vx.kind, vy.kind); c != 0 { // "" < alpha < beta < rc + return c + } + if c := cmpInt(vx.pre, vy.pre); c != 0 { + return c + } + return 0 +} + +// lang returns the Go language version. For example, lang("1.2.3") == "1.2". +func lang(x string) string { + v := parse(x) + if v.minor == "" || v.major == "1" && v.minor == "0" { + return v.major + } + return v.major + "." + v.minor +} + +// isValid reports whether the version x is valid. +func isValid(x string) bool { + return parse(x) != gover{} +} + +// parse parses the Go version string x into a version. +// It returns the zero version if x is malformed. +func parse(x string) gover { + var v gover + + // Parse major version. + var ok bool + v.major, x, ok = cutInt(x) + if !ok { + return gover{} + } + if x == "" { + // Interpret "1" as "1.0.0". + v.minor = "0" + v.patch = "0" + return v + } + + // Parse . before minor version. + if x[0] != '.' { + return gover{} + } + + // Parse minor version. + v.minor, x, ok = cutInt(x[1:]) + if !ok { + return gover{} + } + if x == "" { + // Patch missing is same as "0" for older versions. + // Starting in Go 1.21, patch missing is different from explicit .0. + if cmpInt(v.minor, "21") < 0 { + v.patch = "0" + } + return v + } + + // Parse patch if present. + if x[0] == '.' { + v.patch, x, ok = cutInt(x[1:]) + if !ok || x != "" { + // Note that we are disallowing prereleases (alpha, beta, rc) for patch releases here (x != ""). + // Allowing them would be a bit confusing because we already have: + // 1.21 < 1.21rc1 + // But a prerelease of a patch would have the opposite effect: + // 1.21.3rc1 < 1.21.3 + // We've never needed them before, so let's not start now. + return gover{} + } + return v + } + + // Parse prerelease. + i := 0 + for i < len(x) && (x[i] < '0' || '9' < x[i]) { + if x[i] < 'a' || 'z' < x[i] { + return gover{} + } + i++ + } + if i == 0 { + return gover{} + } + v.kind, x = x[:i], x[i:] + if x == "" { + return v + } + v.pre, x, ok = cutInt(x) + if !ok || x != "" { + return gover{} + } + + return v +} + +// cutInt scans the leading decimal number at the start of x to an integer +// and returns that value and the rest of the string. +func cutInt(x string) (n, rest string, ok bool) { + i := 0 + for i < len(x) && '0' <= x[i] && x[i] <= '9' { + i++ + } + if i == 0 || x[0] == '0' && i != 1 { // no digits or unnecessary leading zero + return "", "", false + } + return x[:i], x[i:], true +} + +// cmpInt returns cmp.Compare(x, y) interpreting x and y as decimal numbers. +// (Copied from golang.org/x/mod/semver's compareInt.) +func cmpInt(x, y string) int { + if x == y { + return 0 + } + if len(x) < len(y) { + return -1 + } + if len(x) > len(y) { + return +1 + } + if x < y { + return -1 + } else { + return +1 + } +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/toolchain.go b/tools/vendor/golang.org/x/tools/internal/versions/toolchain.go new file mode 100644 index 000000000..377bf7a53 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/toolchain.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package versions + +// toolchain is maximum version (<1.22) that the go toolchain used +// to build the current tool is known to support. +// +// When a tool is built with >=1.22, the value of toolchain is unused. +// +// x/tools does not support building with go <1.18. So we take this +// as the minimum possible maximum. +var toolchain string = Go1_18 diff --git a/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go119.go b/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go119.go new file mode 100644 index 000000000..f65beed9d --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go119.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.19 +// +build go1.19 + +package versions + +func init() { + if Compare(toolchain, Go1_19) < 0 { + toolchain = Go1_19 + } +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go120.go b/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go120.go new file mode 100644 index 000000000..1a9efa126 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go120.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.20 +// +build go1.20 + +package versions + +func init() { + if Compare(toolchain, Go1_20) < 0 { + toolchain = Go1_20 + } +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go121.go b/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go121.go new file mode 100644 index 000000000..b7ef216df --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/toolchain_go121.go @@ -0,0 +1,14 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.21 +// +build go1.21 + +package versions + +func init() { + if Compare(toolchain, Go1_21) < 0 { + toolchain = Go1_21 + } +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/types.go b/tools/vendor/golang.org/x/tools/internal/versions/types.go new file mode 100644 index 000000000..562eef21f --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/types.go @@ -0,0 +1,19 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package versions + +import ( + "go/types" +) + +// GoVersion returns the Go version of the type package. +// It returns zero if no version can be determined. +func GoVersion(pkg *types.Package) string { + // TODO(taking): x/tools can call GoVersion() [from 1.21] after 1.25. + if pkg, ok := any(pkg).(interface{ GoVersion() string }); ok { + return pkg.GoVersion() + } + return "" +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/types_go121.go b/tools/vendor/golang.org/x/tools/internal/versions/types_go121.go new file mode 100644 index 000000000..b4345d334 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/types_go121.go @@ -0,0 +1,30 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build !go1.22 +// +build !go1.22 + +package versions + +import ( + "go/ast" + "go/types" +) + +// FileVersion returns a language version (<=1.21) derived from runtime.Version() +// or an unknown future version. +func FileVersion(info *types.Info, file *ast.File) string { + // In x/tools built with Go <= 1.21, we do not have Info.FileVersions + // available. We use a go version derived from the toolchain used to + // compile the tool by default. + // This will be <= go1.21. We take this as the maximum version that + // this tool can support. + // + // There are no features currently in x/tools that need to tell fine grained + // differences for versions <1.22. + return toolchain +} + +// InitFileVersions is a noop when compiled with this Go version. +func InitFileVersions(*types.Info) {} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/types_go122.go b/tools/vendor/golang.org/x/tools/internal/versions/types_go122.go new file mode 100644 index 000000000..aac5db62c --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/types_go122.go @@ -0,0 +1,41 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build go1.22 +// +build go1.22 + +package versions + +import ( + "go/ast" + "go/types" +) + +// FileVersion returns a file's Go version. +// The reported version is an unknown Future version if a +// version cannot be determined. +func FileVersion(info *types.Info, file *ast.File) string { + // In tools built with Go >= 1.22, the Go version of a file + // follow a cascades of sources: + // 1) types.Info.FileVersion, which follows the cascade: + // 1.a) file version (ast.File.GoVersion), + // 1.b) the package version (types.Config.GoVersion), or + // 2) is some unknown Future version. + // + // File versions require a valid package version to be provided to types + // in Config.GoVersion. Config.GoVersion is either from the package's module + // or the toolchain (go run). This value should be provided by go/packages + // or unitchecker.Config.GoVersion. + if v := info.FileVersions[file]; IsValid(v) { + return v + } + // Note: we could instead return runtime.Version() [if valid]. + // This would act as a max version on what a tool can support. + return Future +} + +// InitFileVersions initializes info to record Go versions for Go files. +func InitFileVersions(info *types.Info) { + info.FileVersions = make(map[*ast.File]string) +} diff --git a/tools/vendor/golang.org/x/tools/internal/versions/versions.go b/tools/vendor/golang.org/x/tools/internal/versions/versions.go new file mode 100644 index 000000000..8d1f7453d --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/versions/versions.go @@ -0,0 +1,57 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package versions + +import ( + "strings" +) + +// Note: If we use build tags to use go/versions when go >=1.22, +// we run into go.dev/issue/53737. Under some operations users would see an +// import of "go/versions" even if they would not compile the file. +// For example, during `go get -u ./...` (go.dev/issue/64490) we do not try to include +// For this reason, this library just a clone of go/versions for the moment. + +// Lang returns the Go language version for version x. +// If x is not a valid version, Lang returns the empty string. +// For example: +// +// Lang("go1.21rc2") = "go1.21" +// Lang("go1.21.2") = "go1.21" +// Lang("go1.21") = "go1.21" +// Lang("go1") = "go1" +// Lang("bad") = "" +// Lang("1.21") = "" +func Lang(x string) string { + v := lang(stripGo(x)) + if v == "" { + return "" + } + return x[:2+len(v)] // "go"+v without allocation +} + +// Compare returns -1, 0, or +1 depending on whether +// x < y, x == y, or x > y, interpreted as Go versions. +// The versions x and y must begin with a "go" prefix: "go1.21" not "1.21". +// Invalid versions, including the empty string, compare less than +// valid versions and equal to each other. +// The language version "go1.21" compares less than the +// release candidate and eventual releases "go1.21rc1" and "go1.21.0". +// Custom toolchain suffixes are ignored during comparison: +// "go1.21.0" and "go1.21.0-bigcorp" are equal. +func Compare(x, y string) int { return compare(stripGo(x), stripGo(y)) } + +// IsValid reports whether the version x is valid. +func IsValid(x string) bool { return isValid(stripGo(x)) } + +// stripGo converts from a "go1.21" version to a "1.21" version. +// If v does not start with "go", stripGo returns the empty string (a known invalid version). +func stripGo(v string) string { + v, _, _ = strings.Cut(v, "-") // strip -bigcorp suffix. + if len(v) < 2 || v[:2] != "go" { + return "" + } + return v[2:] +} diff --git a/tools/vendor/honnef.co/go/tools/analysis/callcheck/callcheck.go b/tools/vendor/honnef.co/go/tools/analysis/callcheck/callcheck.go new file mode 100644 index 000000000..11ec3fb91 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/analysis/callcheck/callcheck.go @@ -0,0 +1,161 @@ +// Package callcheck provides a framework for validating arguments in function calls. +package callcheck + +import ( + "fmt" + "go/ast" + "go/constant" + "go/types" + + "golang.org/x/tools/go/analysis" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" +) + +type Call struct { + Pass *analysis.Pass + Instr ir.CallInstruction + Args []*Argument + + Parent *ir.Function + + invalids []string +} + +func (c *Call) Invalid(msg string) { + c.invalids = append(c.invalids, msg) +} + +type Argument struct { + Value Value + invalids []string +} + +type Value struct { + Value ir.Value +} + +func (arg *Argument) Invalid(msg string) { + arg.invalids = append(arg.invalids, msg) +} + +type Check func(call *Call) + +func Analyzer(rules map[string]Check) func(pass *analysis.Pass) (interface{}, error) { + return func(pass *analysis.Pass) (interface{}, error) { + return checkCalls(pass, rules) + } +} + +func checkCalls(pass *analysis.Pass, rules map[string]Check) (interface{}, error) { + cb := func(caller *ir.Function, site ir.CallInstruction, callee *ir.Function) { + obj, ok := callee.Object().(*types.Func) + if !ok { + return + } + + r, ok := rules[typeutil.FuncName(obj)] + if !ok { + return + } + var args []*Argument + irargs := site.Common().Args + if callee.Signature.Recv() != nil { + irargs = irargs[1:] + } + for _, arg := range irargs { + if iarg, ok := arg.(*ir.MakeInterface); ok { + arg = iarg.X + } + args = append(args, &Argument{Value: Value{arg}}) + } + call := &Call{ + Pass: pass, + Instr: site, + Args: args, + Parent: site.Parent(), + } + r(call) + + var astcall *ast.CallExpr + switch source := site.Source().(type) { + case *ast.CallExpr: + astcall = source + case *ast.DeferStmt: + astcall = source.Call + case *ast.GoStmt: + astcall = source.Call + case nil: + // TODO(dh): I am not sure this can actually happen. If it + // can't, we should remove this case, and also stop + // checking for astcall == nil in the code that follows. + default: + panic(fmt.Sprintf("unhandled case %T", source)) + } + + for idx, arg := range call.Args { + for _, e := range arg.invalids { + if astcall != nil { + if idx < len(astcall.Args) { + report.Report(pass, astcall.Args[idx], e) + } else { + // this is an instance of fn1(fn2()) where fn2 + // returns multiple values. Report the error + // at the next-best position that we have, the + // first argument. An example of a check that + // triggers this is checkEncodingBinaryRules. + report.Report(pass, astcall.Args[0], e) + } + } else { + report.Report(pass, site, e) + } + } + } + for _, e := range call.invalids { + report.Report(pass, call.Instr, e) + } + } + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + eachCall(fn, cb) + } + return nil, nil +} + +func eachCall(fn *ir.Function, cb func(caller *ir.Function, site ir.CallInstruction, callee *ir.Function)) { + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + if site, ok := instr.(ir.CallInstruction); ok { + if g := site.Common().StaticCallee(); g != nil { + cb(fn, site, g) + } + } + } + } +} + +func ExtractConstExpectKind(v Value, kind constant.Kind) *ir.Const { + k := extractConst(v.Value) + if k == nil || k.Value == nil || k.Value.Kind() != kind { + return nil + } + return k +} + +func ExtractConst(v Value) *ir.Const { + return extractConst(v.Value) +} + +func extractConst(v ir.Value) *ir.Const { + v = irutil.Flatten(v) + switch v := v.(type) { + case *ir.Const: + return v + case *ir.MakeInterface: + return extractConst(v.X) + default: + return nil + } +} diff --git a/tools/vendor/honnef.co/go/tools/analysis/code/code.go b/tools/vendor/honnef.co/go/tools/analysis/code/code.go index f200363d9..7d20ea4c9 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/code/code.go +++ b/tools/vendor/honnef.co/go/tools/analysis/code/code.go @@ -2,12 +2,14 @@ package code import ( - "flag" "fmt" "go/ast" + "go/build/constraint" "go/constant" "go/token" "go/types" + "go/version" + "path/filepath" "strings" "honnef.co/go/tools/analysis/facts/generated" @@ -15,6 +17,7 @@ import ( "honnef.co/go/tools/analysis/facts/tokenfile" "honnef.co/go/tools/go/ast/astutil" "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/knowledge" "honnef.co/go/tools/pattern" "golang.org/x/tools/go/analysis" @@ -24,8 +27,30 @@ type Positioner interface { Pos() token.Pos } -func IsOfType(pass *analysis.Pass, expr ast.Expr, name string) bool { - return typeutil.IsType(pass.TypesInfo.TypeOf(expr), name) +func IsOfStringConvertibleByteSlice(pass *analysis.Pass, expr ast.Expr) bool { + typ, ok := pass.TypesInfo.TypeOf(expr).Underlying().(*types.Slice) + if !ok { + return false + } + elem := types.Unalias(typ.Elem()) + if version.Compare(LanguageVersion(pass, expr), "go1.18") >= 0 { + // Before Go 1.18, one could not directly convert from []T (where 'type T byte') + // to string. See also https://github.com/golang/go/issues/23536. + elem = elem.Underlying() + } + return types.Identical(elem, types.Typ[types.Byte]) +} + +func IsOfPointerToTypeWithName(pass *analysis.Pass, expr ast.Expr, name string) bool { + ptr, ok := types.Unalias(pass.TypesInfo.TypeOf(expr)).(*types.Pointer) + if !ok { + return false + } + return typeutil.IsTypeWithName(ptr.Elem(), name) +} + +func IsOfTypeWithName(pass *analysis.Pass, expr ast.Expr, name string) bool { + return typeutil.IsTypeWithName(pass.TypesInfo.TypeOf(expr), name) } func IsInTest(pass *analysis.Pass, node Positioner) bool { @@ -94,8 +119,9 @@ func BoolConst(pass *analysis.Pass, expr ast.Expr) bool { func IsBoolConst(pass *analysis.Pass, expr ast.Expr) bool { // We explicitly don't support typed bools because more often than - // not, custom bool types are used as binary enums and the - // explicit comparison is desired. + // not, custom bool types are used as binary enums and the explicit + // comparison is desired. We err on the side of false negatives and + // treat aliases like other custom types. ident, ok := expr.(*ast.Ident) if !ok { @@ -139,6 +165,9 @@ func ExprToString(pass *analysis.Pass, expr ast.Expr) (string, bool) { } func CallName(pass *analysis.Pass, call *ast.CallExpr) string { + // See the comment in typeutil.FuncName for why this doesn't require special handling + // of aliases. + fun := astutil.Unparen(call.Fun) // Instantiating a function cannot return another generic function, so doing this once is enough @@ -174,6 +203,9 @@ func CallName(pass *analysis.Pass, call *ast.CallExpr) string { } func IsCallTo(pass *analysis.Pass, node ast.Node, name string) bool { + // See the comment in typeutil.FuncName for why this doesn't require special handling + // of aliases. + call, ok := node.(*ast.CallExpr) if !ok { return false @@ -182,6 +214,9 @@ func IsCallTo(pass *analysis.Pass, node ast.Node, name string) bool { } func IsCallToAny(pass *analysis.Pass, node ast.Node, names ...string) bool { + // See the comment in typeutil.FuncName for why this doesn't require special handling + // of aliases. + call, ok := node.(*ast.CallExpr) if !ok { return false @@ -200,7 +235,91 @@ func File(pass *analysis.Pass, node Positioner) *ast.File { return m[pass.Fset.File(node.Pos())] } -// IsGenerated reports whether pos is in a generated file, It ignores +// BuildConstraints returns the build constraints for file f. It considers both //go:build lines as well as +// GOOS and GOARCH in file names. +func BuildConstraints(pass *analysis.Pass, f *ast.File) (constraint.Expr, bool) { + var expr constraint.Expr + for _, cmt := range f.Comments { + if len(cmt.List) == 0 { + continue + } + for _, el := range cmt.List { + if el.Pos() > f.Package { + break + } + if line := el.Text; strings.HasPrefix(line, "//go:build") { + var err error + expr, err = constraint.Parse(line) + if err != nil { + expr = nil + } + break + } + } + } + + name := pass.Fset.PositionFor(f.Pos(), false).Filename + oexpr := constraintsFromName(name) + if oexpr != nil { + if expr == nil { + expr = oexpr + } else { + expr = &constraint.AndExpr{X: expr, Y: oexpr} + } + } + + return expr, expr != nil +} + +func constraintsFromName(name string) constraint.Expr { + name = filepath.Base(name) + name = strings.TrimSuffix(name, ".go") + name = strings.TrimSuffix(name, "_test") + var goos, goarch string + switch strings.Count(name, "_") { + case 0: + // No GOOS or GOARCH in the file name. + case 1: + _, c, _ := strings.Cut(name, "_") + if _, ok := knowledge.KnownGOOS[c]; ok { + goos = c + } else if _, ok := knowledge.KnownGOARCH[c]; ok { + goarch = c + } + default: + n := strings.LastIndex(name, "_") + if _, ok := knowledge.KnownGOOS[name[n+1:]]; ok { + // The file name is *_stuff_GOOS.go + goos = name[n+1:] + } else if _, ok := knowledge.KnownGOARCH[name[n+1:]]; ok { + // The file name is *_GOOS_GOARCH.go or *_stuff_GOARCH.go + goarch = name[n+1:] + _, c, _ := strings.Cut(name[:n], "_") + if _, ok := knowledge.KnownGOOS[c]; ok { + // The file name is *_GOOS_GOARCH.go + goos = c + } + } else { + // The file name could also be something like foo_windows_nonsense.go — and because nonsense + // isn't a known GOARCH, "windows" won't be interpreted as a GOOS, either. + } + } + + var expr constraint.Expr + if goos != "" { + expr = &constraint.TagExpr{Tag: goos} + } + if goarch != "" { + if expr == nil { + expr = &constraint.TagExpr{Tag: goarch} + } else { + expr = &constraint.AndExpr{X: expr, Y: &constraint.TagExpr{Tag: goarch}} + } + } + return expr +} + +// IsGenerated reports whether pos is in a generated file. It ignores // //line directives. func IsGenerated(pass *analysis.Pass, pos token.Pos) bool { _, ok := Generator(pass, pos) @@ -315,13 +434,113 @@ func MayHaveSideEffects(pass *analysis.Pass, expr ast.Expr, purity purity.Result } } -func IsGoVersion(pass *analysis.Pass, minor int) bool { - f, ok := pass.Analyzer.Flags.Lookup("go").Value.(flag.Getter) - if !ok { - panic("requested Go version, but analyzer has no version flag") +// LanguageVersion returns the version of the Go language that node has access to. This +// might differ from the version of the Go standard library. +func LanguageVersion(pass *analysis.Pass, node Positioner) string { + // As of Go 1.21, two places can specify the minimum Go version: + // - 'go' directives in go.mod and go.work files + // - individual files by using '//go:build' + // + // Individual files can upgrade to a higher version than the module version. Individual files + // can also downgrade to a lower version, but only if the module version is at least Go 1.21. + // + // The restriction on downgrading doesn't matter to us. All language changes before Go 1.22 will + // not type-check on versions that are too old, and thus never reach our analyzes. In practice, + // such ineffective downgrading will always be useless, as the compiler will not restrict the + // language features used, and doesn't ever rely on minimum versions to restrict the use of the + // standard library. However, for us, both choices (respecting or ignoring ineffective + // downgrading) have equal complexity, but only respecting it has a non-zero chance of reducing + // noisy positives. + // + // The minimum Go versions are exposed via go/ast.File.GoVersion and go/types.Package.GoVersion. + // ast.File's version is populated by the parser, whereas types.Package's version is populated + // from the Go version specified in the types.Config, which is set by our package loader, based + // on the module information provided by go/packages, via 'go list -json'. + // + // As of Go 1.21, standard library packages do not present themselves as modules, and thus do + // not have a version set on their types.Package. In this case, we fall back to the version + // provided by our '-go' flag. In most cases, '-go' defaults to 'module', which falls back to + // the Go version that Staticcheck was built with when no module information exists. In the + // future, the standard library will hopefully be a proper module (see + // https://github.com/golang/go/issues/61174#issuecomment-1622471317). In that case, the version + // of standard library packages will match that of the used Go version. At that point, + // Staticcheck will refuse to work with Go versions that are too new, to avoid misinterpreting + // code due to language changes. + // + // We also lack module information when building in GOPATH mode. In this case, the implied + // language version is at most Go 1.21, as per https://github.com/golang/go/issues/60915. We + // don't handle this yet, and it will not matter until Go 1.22. + // + // It is not clear how per-file downgrading behaves in GOPATH mode. On the one hand, no module + // version at all is provided, which should preclude per-file downgrading. On the other hand, + // https://github.com/golang/go/issues/60915 suggests that the language version is at most 1.21 + // in GOPATH mode, which would allow per-file downgrading. Again it doesn't affect us, as all + // relevant language changes before Go 1.22 will lead to type-checking failures and never reach + // us. + // + // Per-file upgrading is permitted in GOPATH mode. + + // If the file has its own Go version, we will return that. Otherwise, we default to + // the type checker's GoVersion, which is populated from either the Go module, or from + // our '-go' flag. + return pass.TypesInfo.FileVersions[File(pass, node)] +} + +// StdlibVersion returns the version of the Go standard library that node can expect to +// have access to. This might differ from the language version for versions of Go older +// than 1.21. +func StdlibVersion(pass *analysis.Pass, node Positioner) string { + // The Go version as specified in go.mod or via the '-go' flag + n := pass.Pkg.GoVersion() + + f := File(pass, node) + if f == nil { + panic(fmt.Sprintf("no file found for node with position %s", pass.Fset.PositionFor(node.Pos(), false))) } - version := f.Get().(int) - return version >= minor + + if nf := f.GoVersion; nf != "" { + if version.Compare(n, "go1.21") == -1 { + // Before Go 1.21, the Go version set in go.mod specified the maximum language + // version available to the module. It wasn't uncommon to set the version to + // Go 1.20 but restrict usage of 1.20 functionality (both language and stdlib) + // to files tagged for 1.20, and supporting a lower version overall. As such, + // a file tagged lower than the module version couldn't expect to have access + // to the standard library of the version set in go.mod. + // + // At the same time, a file tagged higher than the module version, while not + // able to use newer language features, would still have been able to use a + // newer standard library. + // + // While Go 1.21's behavior has been backported to 1.19.11 and 1.20.6, users' + // expectations have not. + return nf + } else { + // Go 1.21 and newer refuse to build modules that depend on versions newer + // than the used version of the Go toolchain. This means that in a 1.22 module + // with a file tagged as 1.17, the file can expect to have access to 1.22's + // standard library (but not to 1.22 language features). A file tagged with a + // version higher than the minimum version has access to the newer standard + // library (and language features.) + // + // Do note that strictly speaking we're conflating the Go version and the + // module version in our check. Nothing is stopping a user from using Go 1.17 + // (which didn't implement the new rules for versions in go.mod) to build a Go + // 1.22 module, in which case a file tagged with go1.17 will not have acces to the 1.22 + // standard library. However, we believe that if a module requires 1.21 or + // newer, then the author clearly expects the new behavior, and doesn't care + // for the old one. Otherwise they would've specified an older version. + // + // In other words, the module version also specifies what it itself actually means, with + // >=1.21 being a minimum version for the toolchain, and <1.21 being a maximum version for + // the language. + + if version.Compare(nf, n) == 1 { + return nf + } + } + } + + return n } var integerLiteralQ = pattern.MustParse(`(IntegerLiteral tv)`) @@ -355,3 +574,20 @@ func IsMethod(pass *analysis.Pass, expr *ast.SelectorExpr, name string, meth *ty } return types.Identical(sel.Type(), meth) } + +func RefersTo(pass *analysis.Pass, expr ast.Expr, ident types.Object) bool { + found := false + fn := func(node ast.Node) bool { + ident2, ok := node.(*ast.Ident) + if !ok { + return true + } + if ident == pass.TypesInfo.ObjectOf(ident2) { + found = true + return false + } + return true + } + ast.Inspect(expr, fn) + return found +} diff --git a/tools/vendor/honnef.co/go/tools/analysis/facts/nilness/nilness.go b/tools/vendor/honnef.co/go/tools/analysis/facts/nilness/nilness.go index d296b5b0f..17d344fab 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/facts/nilness/nilness.go +++ b/tools/vendor/honnef.co/go/tools/analysis/facts/nilness/nilness.go @@ -221,6 +221,8 @@ func impl(pass *analysis.Pass, fn *ir.Function, seenFns map[*ir.Function]struct{ return nilly case *ir.ChangeType: return mightReturnNil(v.X) + case *ir.MultiConvert: + return mightReturnNil(v.X) case *ir.Load: if _, ok := v.X.(*ir.Global); ok { return onlyGlobal @@ -230,11 +232,6 @@ func impl(pass *analysis.Pass, fn *ir.Function, seenFns map[*ir.Function]struct{ return neverNil case *ir.TypeAssert, *ir.ChangeInterface, *ir.Field, *ir.Const, *ir.GenericConst, *ir.Index, *ir.MapLookup, *ir.Parameter, *ir.Recv, *ir.TypeSwitch: return nilly - case *ir.CompositeValue: - // We can get here via composite literals of type parameters, for which typeutil.IsPointerLike doesn't - // currently return false (see https://staticcheck.io/issues/1364). However, we only emit ir.CompositeValue - // for value types, so we know it can't be nil. - return neverNil default: panic(fmt.Sprintf("internal error: unhandled type %T", v)) } @@ -243,6 +240,8 @@ func impl(pass *analysis.Pass, fn *ir.Function, seenFns map[*ir.Function]struct{ out := make([]neverNilness, len(ret.Results)) export := false for i, v := range ret.Results { + // OPT(dh): couldn't we check the result type's pointer-likeness early, and skip + // processing the return value altogether? v := mightReturnNil(v) out[i] = v if v != nilly && typeutil.IsPointerLike(fn.Signature.Results().At(i).Type()) { diff --git a/tools/vendor/honnef.co/go/tools/analysis/lint/lint.go b/tools/vendor/honnef.co/go/tools/analysis/lint/lint.go index 7d116a23d..6f5861221 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/lint/lint.go +++ b/tools/vendor/honnef.co/go/tools/analysis/lint/lint.go @@ -3,16 +3,13 @@ package lint import ( - "flag" "fmt" "go/ast" - "go/build" "go/token" - "regexp" - "strconv" "strings" "golang.org/x/tools/go/analysis" + "honnef.co/go/tools/analysis/facts/tokenfile" ) // Analyzer wraps a go/analysis.Analyzer and provides structured documentation. @@ -20,33 +17,15 @@ type Analyzer struct { // The analyzer's documentation. Unlike go/analysis.Analyzer.Doc, // this field is structured, providing access to severity, options // etc. - Doc *Documentation + Doc *RawDocumentation Analyzer *analysis.Analyzer } -func (a *Analyzer) initialize() { - a.Analyzer.Doc = a.Doc.String() - if a.Analyzer.Flags.Usage == nil { - fs := flag.NewFlagSet("", flag.PanicOnError) - fs.Var(newVersionFlag(), "go", "Target Go version") - a.Analyzer.Flags = *fs - } -} - -// InitializeAnalyzers takes a map of documentation and a map of go/analysis.Analyzers and returns a slice of Analyzers. -// The map keys are the analyzer names. -func InitializeAnalyzers(docs map[string]*Documentation, analyzers map[string]*analysis.Analyzer) []*Analyzer { - out := make([]*Analyzer, 0, len(analyzers)) - for k, v := range analyzers { - v.Name = k - a := &Analyzer{ - Doc: docs[k], - Analyzer: v, - } - a.initialize() - out = append(out, a) - } - return out +func InitializeAnalyzer(a *Analyzer) *Analyzer { + a.Analyzer.Doc = a.Doc.Compile().String() + a.Analyzer.URL = "https://staticcheck.dev/docs/checks/#" + a.Analyzer.Name + a.Analyzer.Requires = append(a.Analyzer.Requires, tokenfile.Analyzer) + return a } // Severity describes the severity of diagnostics reported by an analyzer. @@ -97,26 +76,22 @@ type Documentation struct { MergeIf MergeStrategy } -func Markdownify(m map[string]*RawDocumentation) map[string]*Documentation { - out := make(map[string]*Documentation, len(m)) - for k, v := range m { - out[k] = &Documentation{ - Title: strings.TrimSpace(stripMarkdown(v.Title)), - Text: strings.TrimSpace(stripMarkdown(v.Text)), +func (doc RawDocumentation) Compile() *Documentation { + return &Documentation{ + Title: strings.TrimSpace(stripMarkdown(doc.Title)), + Text: strings.TrimSpace(stripMarkdown(doc.Text)), - TitleMarkdown: strings.TrimSpace(toMarkdown(v.Title)), - TextMarkdown: strings.TrimSpace(toMarkdown(v.Text)), + TitleMarkdown: strings.TrimSpace(toMarkdown(doc.Title)), + TextMarkdown: strings.TrimSpace(toMarkdown(doc.Text)), - Before: strings.TrimSpace(v.Before), - After: strings.TrimSpace(v.After), - Since: v.Since, - NonDefault: v.NonDefault, - Options: v.Options, - Severity: v.Severity, - MergeIf: v.MergeIf, - } + Before: strings.TrimSpace(doc.Before), + After: strings.TrimSpace(doc.After), + Since: doc.Since, + NonDefault: doc.NonDefault, + Options: doc.Options, + Severity: doc.Severity, + MergeIf: doc.MergeIf, } - return out } func toMarkdown(s string) string { @@ -191,51 +166,6 @@ func (doc *Documentation) String() string { return doc.Format(true) } -func newVersionFlag() flag.Getter { - tags := build.Default.ReleaseTags - v := tags[len(tags)-1][2:] - version := new(VersionFlag) - if err := version.Set(v); err != nil { - panic(fmt.Sprintf("internal error: %s", err)) - } - return version -} - -type VersionFlag int - -func (v *VersionFlag) String() string { - return fmt.Sprintf("1.%d", *v) -} - -var goVersionRE = regexp.MustCompile(`^(?:go)?1.(\d+).*$`) - -// ParseGoVersion parses Go versions of the form 1.M, 1.M.N, or 1.M.NrcR, with an optional "go" prefix. It assumes that -// versions have already been verified and are valid. -func ParseGoVersion(s string) (int, bool) { - m := goVersionRE.FindStringSubmatch(s) - if m == nil { - return 0, false - } - n, err := strconv.Atoi(m[1]) - if err != nil { - return 0, false - } - return n, true -} - -func (v *VersionFlag) Set(s string) error { - n, ok := ParseGoVersion(s) - if !ok { - return fmt.Errorf("invalid Go version: %q", s) - } - *v = VersionFlag(n) - return nil -} - -func (v *VersionFlag) Get() interface{} { - return int(*v) -} - // ExhaustiveTypeSwitch panics when called. It can be used to ensure // that type switches are exhaustive. func ExhaustiveTypeSwitch(v interface{}) { diff --git a/tools/vendor/honnef.co/go/tools/analysis/report/report.go b/tools/vendor/honnef.co/go/tools/analysis/report/report.go index d52945e72..fcc2317ce 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/report/report.go +++ b/tools/vendor/honnef.co/go/tools/analysis/report/report.go @@ -6,10 +6,12 @@ import ( "go/ast" "go/format" "go/token" + "go/version" "path/filepath" "strconv" "strings" + "honnef.co/go/tools/analysis/code" "honnef.co/go/tools/analysis/facts/generated" "honnef.co/go/tools/go/ast/astutil" @@ -17,10 +19,14 @@ import ( ) type Options struct { - ShortRange bool - FilterGenerated bool - Fixes []analysis.SuggestedFix - Related []analysis.RelatedInformation + ShortRange bool + FilterGenerated bool + Fixes []analysis.SuggestedFix + Related []analysis.RelatedInformation + MinimumLanguageVersion string + MaximumLanguageVersion string + MinimumStdlibVersion string + MaximumStdlibVersion string } type Option func(*Options) @@ -58,6 +64,19 @@ func Related(node Positioner, message string) Option { } } +func MinimumLanguageVersion(vers string) Option { + return func(opts *Options) { opts.MinimumLanguageVersion = vers } +} +func MaximumLanguageVersion(vers string) Option { + return func(opts *Options) { opts.MinimumLanguageVersion = vers } +} +func MinimumStdlibVersion(vers string) Option { + return func(opts *Options) { opts.MinimumStdlibVersion = vers } +} +func MaximumStdlibVersion(vers string) Option { + return func(opts *Options) { opts.MaximumStdlibVersion = vers } +} + type Positioner interface { Pos() token.Pos } @@ -170,6 +189,21 @@ func Report(pass *analysis.Pass, node Positioner, message string, opts ...Option opt(cfg) } + langVersion := code.LanguageVersion(pass, node) + stdlibVersion := code.StdlibVersion(pass, node) + if n := cfg.MaximumLanguageVersion; n != "" && version.Compare(n, langVersion) == -1 { + return + } + if n := cfg.MaximumStdlibVersion; n != "" && version.Compare(n, stdlibVersion) == -1 { + return + } + if n := cfg.MinimumLanguageVersion; n != "" && version.Compare(n, langVersion) == 1 { + return + } + if n := cfg.MinimumStdlibVersion; n != "" && version.Compare(n, stdlibVersion) == 1 { + return + } + file := DisplayPosition(pass.Fset, node.Pos()).Filename if cfg.FilterGenerated { m := pass.ResultOf[generated.Analyzer].(map[string]generated.Generator) diff --git a/tools/vendor/honnef.co/go/tools/config/example.conf b/tools/vendor/honnef.co/go/tools/config/example.conf index b25c3a815..dc102fbc0 100644 --- a/tools/vendor/honnef.co/go/tools/config/example.conf +++ b/tools/vendor/honnef.co/go/tools/config/example.conf @@ -1,4 +1,4 @@ -checks = ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022", "-ST1023"] +checks = ["all", "-SA9003", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022", "-ST1023"] initialisms = ["ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", diff --git a/tools/vendor/honnef.co/go/tools/go/ast/astutil/util.go b/tools/vendor/honnef.co/go/tools/go/ast/astutil/util.go index e04e1fb0c..342654409 100644 --- a/tools/vendor/honnef.co/go/tools/go/ast/astutil/util.go +++ b/tools/vendor/honnef.co/go/tools/go/ast/astutil/util.go @@ -6,6 +6,8 @@ import ( "go/token" "reflect" "strings" + + "golang.org/x/tools/go/ast/astutil" ) func IsIdent(expr ast.Expr, ident string) bool { @@ -360,3 +362,112 @@ func Equal(a, b ast.Node) bool { panic(fmt.Sprintf("unreachable: %T", a)) } } + +func NegateDeMorgan(expr ast.Expr, recursive bool) ast.Expr { + switch expr := expr.(type) { + case *ast.BinaryExpr: + var out ast.BinaryExpr + switch expr.Op { + case token.EQL: + out.X = expr.X + out.Op = token.NEQ + out.Y = expr.Y + case token.LSS: + out.X = expr.X + out.Op = token.GEQ + out.Y = expr.Y + case token.GTR: + out.X = expr.X + out.Op = token.LEQ + out.Y = expr.Y + case token.NEQ: + out.X = expr.X + out.Op = token.EQL + out.Y = expr.Y + case token.LEQ: + out.X = expr.X + out.Op = token.GTR + out.Y = expr.Y + case token.GEQ: + out.X = expr.X + out.Op = token.LSS + out.Y = expr.Y + + case token.LAND: + out.X = NegateDeMorgan(expr.X, recursive) + out.Op = token.LOR + out.Y = NegateDeMorgan(expr.Y, recursive) + case token.LOR: + out.X = NegateDeMorgan(expr.X, recursive) + out.Op = token.LAND + out.Y = NegateDeMorgan(expr.Y, recursive) + } + return &out + + case *ast.ParenExpr: + if recursive { + return &ast.ParenExpr{ + X: NegateDeMorgan(expr.X, recursive), + } + } else { + return &ast.UnaryExpr{ + Op: token.NOT, + X: expr, + } + } + + case *ast.UnaryExpr: + if expr.Op == token.NOT { + return expr.X + } else { + return &ast.UnaryExpr{ + Op: token.NOT, + X: expr, + } + } + + default: + return &ast.UnaryExpr{ + Op: token.NOT, + X: expr, + } + } +} + +func SimplifyParentheses(node ast.Expr) ast.Expr { + var changed bool + // XXX accept list of ops to operate on + // XXX copy AST node, don't modify in place + post := func(c *astutil.Cursor) bool { + out := c.Node() + if paren, ok := c.Node().(*ast.ParenExpr); ok { + out = paren.X + } + + if binop, ok := out.(*ast.BinaryExpr); ok { + if right, ok := binop.Y.(*ast.BinaryExpr); ok && binop.Op == right.Op { + // XXX also check that Op is associative + + root := binop + pivot := root.Y.(*ast.BinaryExpr) + root.Y = pivot.X + pivot.X = root + root = pivot + out = root + } + } + + if out != c.Node() { + changed = true + c.Replace(out) + } + return true + } + + for changed = true; changed; { + changed = false + node = astutil.Apply(node, nil, post).(ast.Expr) + } + + return node +} diff --git a/tools/vendor/honnef.co/go/tools/go/ir/UPSTREAM b/tools/vendor/honnef.co/go/tools/go/ir/UPSTREAM index 757ebfd59..bfcf02856 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/UPSTREAM +++ b/tools/vendor/honnef.co/go/tools/go/ir/UPSTREAM @@ -5,5 +5,5 @@ The changes are too many to list here, and it is best to consider this package i Upstream changes still get applied when they address bugs in portions of code we have inherited. The last upstream commit we've looked at was: -915f6209478fe61eb90dbe155a8a1c58655b931f +ac2946029ad3806349fa00546449da9f59320e89 diff --git a/tools/vendor/honnef.co/go/tools/go/ir/builder.go b/tools/vendor/honnef.co/go/tools/go/ir/builder.go index 1a77ed042..192eaaa50 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/builder.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/builder.go @@ -30,6 +30,7 @@ import ( "go/constant" "go/token" "go/types" + "go/version" "os" "honnef.co/go/tools/analysis/lint" @@ -49,8 +50,35 @@ var ( tString = types.Typ[types.String] tUntypedNil = types.Typ[types.UntypedNil] tEface = types.NewInterfaceType(nil, nil).Complete() + tDeferStack = types.NewPointer(typeutil.NewDeferStack()) + + vDeferStack = &Builtin{ + name: "ssa:deferstack", + sig: types.NewSignatureType(nil, nil, nil, nil, types.NewTuple(anonVar(tDeferStack)), false), + } ) +// range-over-func jump is READY +func jReady() *Const { + c := intConst(0, nil) + c.comment = "rangefunc.exit.ready" + return c +} + +// range-over-func jump is BUSY +func jBusy() *Const { + c := intConst(-1, nil) + c.comment = "rangefunc.exit.busy" + return c +} + +// range-over-func jump is DONE +func jDone() *Const { + c := intConst(-2, nil) + c.comment = "rangefunc.exit.done" + return c +} + // builder holds state associated with the package currently being built. // Its methods contain all the logic for AST-to-IR conversion. type builder struct { @@ -114,11 +142,11 @@ func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value { switch e.Op { case token.LAND: b.cond(fn, e.X, rhs, done) - short = emitConst(fn, NewConst(constant.MakeBool(false), t)) + short = emitConst(fn, NewConst(constant.MakeBool(false), t, e)) case token.LOR: b.cond(fn, e.X, done, rhs) - short = emitConst(fn, NewConst(constant.MakeBool(true), t)) + short = emitConst(fn, NewConst(constant.MakeBool(true), t, e)) } // Is rhs unreachable? @@ -149,6 +177,7 @@ func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value { phi := &Phi{Edges: edges} phi.typ = t + phi.comment = e.Op.String() return done.emit(phi, e) } @@ -222,9 +251,8 @@ func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ // treat make([]T, n, m) as new([m]T)[:n] cap := m.Int64() at := types.NewArray(styp.Underlying().(*types.Slice).Elem(), cap) - alloc := emitNew(fn, at, source) v := &Slice{ - X: alloc, + X: emitNew(fn, at, source, "makeslice"), High: n, } v.setType(typ) @@ -247,7 +275,7 @@ func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ return fn.emit(v, source) case *types.Chan: - var sz Value = emitConst(fn, intConst(0)) + var sz Value = emitConst(fn, intConst(0, source)) if len(args) == 2 { sz = b.expr(fn, args[1]) } @@ -260,8 +288,7 @@ func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ } case "new": - alloc := emitNew(fn, deref(typ), source) - return alloc + return emitNew(fn, deref(typ), source, "new") case "len", "cap": // Special case: len or cap of an array or *array is based on the type, not the value which may be nil. We must @@ -271,12 +298,12 @@ func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ // For example, for len(gen()), we need to evaluate gen() for its side-effects, but don't need the returned // value to determine the length of the array, which is constant. // - // This never applies to type parameters. Even if the constraint has a structural type, len/cap on a type - // parameter aren't constant. - t := deref(fn.Pkg.typeOf(args[0])).Underlying() + // Technically this shouldn't apply to type parameters because their length/capacity is never constant. We still + // choose to treat them as constant so that users of the IR get the practically constant length for free. + t := typeutil.CoreType(deref(fn.Pkg.typeOf(args[0]))) if at, ok := t.(*types.Array); ok { b.expr(fn, args[0]) // for effects only - return emitConst(fn, intConst(at.Len())) + return emitConst(fn, intConst(at.Len(), args[0])) } // Otherwise treat as normal. @@ -286,7 +313,7 @@ func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ }, source) addEdge(fn.currentBlock, fn.Exit) fn.currentBlock = fn.newBasicBlock("unreachable") - return emitConst(fn, NewConst(constant.MakeBool(true), tBool)) // any non-nil Value will do + return emitConst(fn, NewConst(constant.MakeBool(true), tBool, nil)) // any non-nil Value will do } return nil // treat all others as a regular function call } @@ -322,7 +349,7 @@ func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) (RET lvalue) { obj := fn.Pkg.objectOf(e) v := fn.Prog.packageLevelValue(obj) // var (address) if v == nil { - v = fn.lookup(obj, escaping) + v = fn.lookup(obj.(*types.Var), escaping) } return &address{addr: v, expr: e} @@ -330,9 +357,9 @@ func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) (RET lvalue) { t := deref(fn.Pkg.typeOf(e)) var v *Alloc if escaping { - v = emitNew(fn, t, e) + v = emitNew(fn, t, e, "complit") } else { - v = fn.addLocal(t, e) + v = emitLocal(fn, t, e, "complit") } var sb storebuf b.compLit(fn, v, e, true, &sb) @@ -353,11 +380,16 @@ func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) (RET lvalue) { } wantAddr := true v := b.receiver(fn, e.X, wantAddr, escaping, sel, e) - last := len(sel.Index()) - 1 - return &address{ - addr: emitFieldSelection(fn, v, sel.Index()[last], true, e.Sel), - expr: e.Sel, + index := sel.Index()[len(sel.Index())-1] + vut := typeutil.CoreType(deref(v.Type())).Underlying().(*types.Struct) + fld := vut.Field(index) + // Due to the two phases of resolving AssignStmt, a panic from x.f = p() + // when x is nil is required to come after the side-effects of + // evaluating x and p(). + emit := func(fn *Function) Value { + return emitFieldSelection(fn, v, index, true, e.Sel) } + return &lazyAddress{addr: emit, t: fld.Type(), expr: e.Sel} case *ast.IndexExpr: var x Value @@ -411,12 +443,19 @@ func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) (RET lvalue) { panic("unexpected container type in IndexExpr: " + t.String()) } - v := &IndexAddr{ - X: x, - Index: b.expr(fn, e.Index), + // Due to the two phases of resolving AssignStmt, a panic from x[i] = p() + // when x is nil or i is out-of-bounds is required to come after the + // side-effects of evaluating x, i and p(). + index := b.expr(fn, e.Index) + emit := func(fn *Function) Value { + v := &IndexAddr{ + X: x, + Index: index, + } + v.setType(et) + return fn.emit(v, e) } - v.setType(et) - return &address{addr: fn.emit(v, e), expr: e} + return &lazyAddress{addr: emit, t: deref(et), expr: e} case *ast.StarExpr: return &address{addr: b.expr(fn, e.X), expr: e} @@ -494,7 +533,7 @@ func (b *builder) assign(fn *Function, loc lvalue, e ast.Expr, isZero bool, sb * } if _, ok := loc.(*address); ok { - if isInterface(loc.typ()) && !typeparams.IsTypeParam(loc.typ()) { + if types.IsInterface(loc.typ()) && !typeparams.IsTypeParam(loc.typ()) { // e.g. var x interface{} = T{...} // Can't in-place initialize an interface value. // Fall back to copying. @@ -546,7 +585,7 @@ func (b *builder) expr(fn *Function, e ast.Expr) Value { // Is expression a constant? if tv.Value != nil { - return emitConst(fn, NewConst(tv.Value, tv.Type)) + return emitConst(fn, NewConst(tv.Value, tv.Type, e)) } var v Value @@ -577,11 +616,14 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { Pkg: fn.Pkg, Prog: fn.Prog, functionBody: new(functionBody), + goversion: fn.goversion, // share the parent's goversion } + fn2.uniq = fn.uniq // start from parent's unique values fn2.source = e fn.AnonFuncs = append(fn.AnonFuncs, fn2) fn2.initHTML(b.printFunc) b.buildFunction(fn2) + fn.uniq = fn2.uniq // resume after anon's unique values if fn2.FreeVars == nil { return fn2 } @@ -622,7 +664,7 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { case token.AND: // &X --- potentially escaping. addr := b.addr(fn, e.X, true) if _, ok := unparen(e.X).(*ast.StarExpr); ok { - // &*p must panic if p is nil (http://golang.org/s/go12nil). + // &*p must panic if p is nil (https://golang.org/s/go12nil). // For simplicity, we'll just (suboptimally) rely // on the side effects of a load. // TODO(adonovan): emit dedicated nilcheck. @@ -680,12 +722,12 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { } var low, high, max Value - if e.High != nil { - high = b.expr(fn, e.High) - } if e.Low != nil { low = b.expr(fn, e.Low) } + if e.High != nil { + high = b.expr(fn, e.High) + } if e.Slice3 { max = b.expr(fn, e.Max) } @@ -705,7 +747,7 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { case *types.Builtin: return &Builtin{name: obj.Name(), sig: tv.Type.(*types.Signature)} case *types.Nil: - return emitConst(fn, nilConst(tv.Type)) + return emitConst(fn, nilConst(tv.Type, e)) } // Package-level func or var? if v := fn.Prog.packageLevelValue(obj); v != nil { @@ -719,7 +761,7 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { return v // (func) } // Local var. - return emitLoad(fn, fn.lookup(obj, false), e) // var (address) + return emitLoad(fn, fn.lookup(obj.(*types.Var), false), e) // var (address) case *ast.SelectorExpr: sel, ok := fn.Pkg.info.Selections[e] @@ -745,7 +787,7 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { wantAddr := isPointer(rt) escaping := true v := b.receiver(fn, e.X, wantAddr, escaping, sel, e) - if isInterface(rt) { + if types.IsInterface(rt) { // If v has interface type I, // we must emit a check that v is non-nil. // We use: typeassert v.(I). @@ -887,7 +929,7 @@ func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) { wantAddr := isPointer(recv) escaping := true v := b.receiver(fn, selector.X, wantAddr, escaping, sel, selector) - if isInterface(recv) { + if types.IsInterface(recv) { // Invoke-mode call. // Methods in interfaces cannot have their own type parameters, so we needn't do anything for type @@ -987,16 +1029,16 @@ func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallEx st := sig.Params().At(np).Type().(*types.Slice) vt := st.Elem() if len(varargs) == 0 { - args = append(args, emitConst(fn, nilConst(st))) + args = append(args, emitConst(fn, nilConst(st, nil))) } else { // Replace a suffix of args with a slice containing it. at := types.NewArray(vt, int64(len(varargs))) - a := emitNew(fn, at, e) + a := emitNew(fn, at, e, "varargs") a.source = e for i, arg := range varargs { iaddr := &IndexAddr{ X: a, - Index: emitConst(fn, intConst(int64(i))), + Index: emitConst(fn, intConst(int64(i), nil)), } iaddr.setType(types.NewPointer(vt)) fn.emit(iaddr, e) @@ -1027,8 +1069,7 @@ func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) { // assignOp emits to fn code to perform loc = val. func (b *builder) assignOp(fn *Function, loc lvalue, val Value, op token.Token, source ast.Node) { - oldv := loc.load(fn, source) - loc.store(fn, emitArith(fn, op, oldv, emitConv(fn, val, oldv.Type(), source), loc.typ(), source), source) + loc.store(fn, emitArith(fn, op, loc.load(fn, source), val, loc.typ(), source), source) } // localValueSpec emits to fn code to define all of the vars in the @@ -1040,7 +1081,7 @@ func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { // 1:1 assignment for i, id := range spec.Names { if !isBlankIdent(id) { - fn.addLocalForIdent(id) + emitLocalVar(fn, identVar(fn, id), id) } lval := b.addr(fn, id, false) // non-escaping b.assign(fn, lval, spec.Values[i], true, nil, spec) @@ -1051,7 +1092,7 @@ func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { // Locals are implicitly zero-initialized. for _, id := range spec.Names { if !isBlankIdent(id) { - lhs := fn.addLocalForIdent(id) + lhs := emitLocalVar(fn, identVar(fn, id), id) if fn.debugInfo() { emitDebugRef(fn, id, lhs, true) } @@ -1063,7 +1104,7 @@ func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { tuple := b.exprN(fn, spec.Values[0]) for i, id := range spec.Names { if !isBlankIdent(id) { - fn.addLocalForIdent(id) + emitLocalVar(fn, identVar(fn, id), id) lhs := b.addr(fn, id, false) // non-escaping lhs.store(fn, emitExtract(fn, tuple, i, id), id) } @@ -1083,8 +1124,8 @@ func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool, so var lval lvalue = blank{} if !isBlankIdent(lhs) { if isDef { - if obj := fn.Pkg.info.Defs[lhs.(*ast.Ident)]; obj != nil { - fn.addNamedLocal(obj, lhs) + if obj, ok := fn.Pkg.info.Defs[lhs.(*ast.Ident)].(*types.Var); ok { + emitLocalVar(fn, obj, lhs) isZero[i] = true } } @@ -1165,7 +1206,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero Values: make([]Value, t.NumFields()), } for i := 0; i < t.NumFields(); i++ { - v.Values[i] = emitConst(fn, zeroConst(t.Field(i).Type())) + v.Values[i] = emitConst(fn, zeroConst(t.Field(i).Type(), e)) } v.setType(typ) @@ -1203,8 +1244,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero switch t := t.(type) { case *types.Slice: at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts)) - alloc := emitNew(fn, at, e) - array = alloc + array = emitNew(fn, at, e, "slicelit") case *types.Array: at = t array = addr @@ -1213,7 +1253,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero var final Value if len(e.Elts) == 0 { if !isZero { - zc := emitConst(fn, zeroConst(at)) + zc := emitConst(fn, zeroConst(at, e)) final = zc } } else { @@ -1222,7 +1262,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero v := &CompositeValue{ Values: make([]Value, at.Len()), } - zc := emitConst(fn, zeroConst(at.Elem())) + zc := emitConst(fn, zeroConst(at.Elem(), e)) for i := range v.Values { v.Values[i] = zc } @@ -1238,7 +1278,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero if idx != nil { idxval = idx.Int64() + 1 } - idx = emitConst(fn, intConst(idxval)).(*Const) + idx = emitConst(fn, intConst(idxval, e)).(*Const) } iaddr := &compositeElement{ @@ -1272,7 +1312,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero if idx != nil { idxval = idx.Int64() + 1 } - idx = emitConst(fn, intConst(idxval)).(*Const) + idx = emitConst(fn, intConst(idxval, e)).(*Const) } iaddr := &IndexAddr{ X: array, @@ -1301,7 +1341,7 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero } case *types.Map: - m := &MakeMap{Reserve: emitConst(fn, intConst(int64(len(e.Elts))))} + m := &MakeMap{Reserve: emitConst(fn, intConst(int64(len(e.Elts)), e))} m.setType(typ) fn.emit(m, e) for _, e := range e.Elts { @@ -1456,7 +1496,7 @@ func (b *builder) switchStmtDynamic(fn *Function, s *ast.SwitchStmt, label *lblo if s.Init != nil { b.stmt(fn, s.Init) } - kTrue := emitConst(fn, NewConst(constant.MakeBool(true), tBool)) + kTrue := emitConst(fn, NewConst(constant.MakeBool(true), tBool, nil)) var tagv Value = kTrue var tagSource ast.Node = s @@ -1467,7 +1507,8 @@ func (b *builder) switchStmtDynamic(fn *Function, s *ast.SwitchStmt, label *lblo // lifting only considers loads and stores, but we want different // sigma nodes for the different comparisons. use a temporary and // load it in every branch. - tag := fn.addLocal(tagv.Type(), tagSource) + tag := emitLocal(fn, tagv.Type(), tagSource, "switch.value") + tag.comment = "switch.tag" emitStore(fn, tag, tagv, tagSource) done := fn.newBasicBlock("switch.done") @@ -1569,7 +1610,7 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl default: panic("unreachable") } - tagPtr := fn.addLocal(tag.Type(), tag.Source()) + tagPtr := emitLocal(fn, tag.Type(), tag.Source(), "") emitStore(fn, tagPtr, tag, tag.Source()) // +1 in case there's no explicit default case @@ -1595,8 +1636,8 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl var default_ *ast.CaseClause for _, clause := range s.Body.List { cc := clause.(*ast.CaseClause) - if obj := fn.Pkg.info.Implicits[cc]; obj != nil { - fn.addNamedLocal(obj, cc) + if obj, ok := fn.Pkg.info.Implicits[cc].(*types.Var); ok { + emitLocalVar(fn, obj, cc) } if cc.List == nil { // default case @@ -1604,7 +1645,7 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl } else { for _, expr := range cc.List { tswtch.Conds = append(tswtch.Conds, fn.Pkg.typeOf(expr)) - cswtch.Conds = append(cswtch.Conds, emitConst(fn, intConst(int64(index)))) + cswtch.Conds = append(cswtch.Conds, emitConst(fn, intConst(int64(index), expr))) index++ } if len(cc.List) == 1 { @@ -1629,7 +1670,7 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl // default branch fn.currentBlock = entry fn.emit(tswtch, s) - cswtch.Conds = append(cswtch.Conds, emitConst(fn, intConst(int64(-1)))) + cswtch.Conds = append(cswtch.Conds, emitConst(fn, intConst(int64(-1), nil))) // in theory we should add a local and stores/loads for tswtch, to // generate sigma nodes in the branches. however, there isn't any // useful information we could possibly attach to it. @@ -1650,16 +1691,16 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl heads = append(heads, head) fn.currentBlock = head - if obj := fn.Pkg.info.Implicits[cc]; obj != nil { + if obj, ok := fn.Pkg.info.Implicits[cc].(*types.Var); ok { // In a switch y := x.(type), each case clause // implicitly declares a distinct object y. // In a single-type case, y has that type. // In multi-type cases, 'case nil' and default, // y has the same type as the interface operand. - l := fn.objects[obj] + l := fn.vars[obj] if rets[index] == tUntypedNil { - emitStore(fn, l, emitConst(fn, nilConst(tswtch.Tag.Type())), s.Assign) + emitStore(fn, l, emitConst(fn, nilConst(tswtch.Tag.Type(), nil)), s.Assign) } else { x := emitExtract(fn, tswtch, index+1, s.Assign) emitStore(fn, l, x, nil) @@ -1690,8 +1731,8 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl tail: fn.targets, _break: done, } - if obj := fn.Pkg.info.Implicits[default_]; obj != nil { - l := fn.objects[obj] + if obj, ok := fn.Pkg.info.Implicits[default_].(*types.Var); ok { + l := fn.vars[obj] x := emitExtract(fn, tswtch, index+1, s.Assign) emitStore(fn, l, x, s) } @@ -1840,10 +1881,10 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) (no b.stmtList(fn, clause.Body) emitJump(fn, done, s) fn.targets = fn.targets.tail - swtch.Conds = append(swtch.Conds, emitConst(fn, intConst(-1))) + swtch.Conds = append(swtch.Conds, emitConst(fn, intConst(-1, nil))) continue } - swtch.Conds = append(swtch.Conds, emitConst(fn, intConst(int64(state)))) + swtch.Conds = append(swtch.Conds, emitConst(fn, intConst(int64(state), nil))) body := fn.newBasicBlock("select.body") fn.currentBlock = body bodies = append(bodies, body) @@ -1861,7 +1902,8 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) (no case *ast.AssignStmt: // x := <-states[state].Chan if comm.Tok == token.DEFINE { - fn.addLocalForIdent(comm.Lhs[0].(*ast.Ident)) + id := comm.Lhs[0].(*ast.Ident) + emitLocalVar(fn, identVar(fn, id), id) } x := b.addr(fn, comm.Lhs[0], false) // non-escaping v := emitExtract(fn, sel, r, comm) @@ -1872,7 +1914,8 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) (no if len(comm.Lhs) == 2 { // x, ok := ... if comm.Tok == token.DEFINE { - fn.addLocalForIdent(comm.Lhs[1].(*ast.Ident)) + id := comm.Lhs[1].(*ast.Ident) + emitLocalVar(fn, identVar(fn, id), id) } ok := b.addr(fn, comm.Lhs[1], false) // non-escaping ok.store(fn, emitExtract(fn, sel, 1, comm), comm) @@ -1896,6 +1939,16 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) (no // forStmt emits to fn code for the for statement s, optionally // labelled by label. func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) { + // Use forStmtGo122 instead if it applies. + if s.Init != nil { + if assign, ok := s.Init.(*ast.AssignStmt); ok && assign.Tok == token.DEFINE { + if version.Compare(fn.goversion, "go1.22") >= 0 { + b.forStmtGo122(fn, s, label) + return + } + } + } + // ...init... // jump loop // loop: @@ -1947,6 +2000,169 @@ func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) { fn.currentBlock = done } +// forStmtGo122 emits to fn code for the for statement s, optionally +// labelled by label. s must define its variables. +// +// This allocates once per loop iteration. This is only correct in +// GoVersions >= go1.22. +func (b *builder) forStmtGo122(fn *Function, s *ast.ForStmt, label *lblock) { + // i_outer = alloc[T] + // *i_outer = ...init... // under objects[i] = i_outer + // jump loop + // loop: + // i = phi [head: i_outer, loop: i_next] + // ...cond... // under objects[i] = i + // if cond goto body else done + // body: + // ...body... // under objects[i] = i (same as loop) + // jump post + // post: + // tmp = *i + // i_next = alloc[T] + // *i_next = tmp + // ...post... // under objects[i] = i_next + // goto loop + // done: + + init := s.Init.(*ast.AssignStmt) + startingBlocks := len(fn.Blocks) + + pre := fn.currentBlock // current block before starting + loop := fn.newBasicBlock("for.loop") // target of back-edge + body := fn.newBasicBlock("for.body") + post := fn.newBasicBlock("for.post") // target of 'continue' + done := fn.newBasicBlock("for.done") // target of 'break' + + // For each of the n loop variables, we create five SSA values, + // outer, phi, next, load, and store in pre, loop, and post. + // There is no limit on n. + type loopVar struct { + obj *types.Var + outer *Alloc + phi *Phi + load *Load + next *Alloc + store *Store + } + vars := make([]loopVar, len(init.Lhs)) + for i, lhs := range init.Lhs { + v := identVar(fn, lhs.(*ast.Ident)) + + fn.currentBlock = pre + outer := emitLocal(fn, v.Type(), lhs, v.Name()) + + fn.currentBlock = loop + phi := &Phi{} + phi.comment = v.Name() + phi.typ = outer.Type() + fn.emit(phi, lhs) + + fn.currentBlock = post + // If next is is local, it reuses the address and zeroes the old value so + // load before allocating next. + load := emitLoad(fn, phi, init) + next := emitLocal(fn, v.Type(), lhs, v.Name()) + store := emitStore(fn, next, load, s) + + phi.Edges = []Value{outer, next} // pre edge is emitted before post edge. + vars[i] = loopVar{v, outer, phi, load, next, store} + } + + // ...init... under fn.objects[v] = i_outer + fn.currentBlock = pre + for _, v := range vars { + fn.vars[v.obj] = v.outer + } + const isDef = false // assign to already-allocated outers + b.assignStmt(fn, init.Lhs, init.Rhs, isDef, s) + if label != nil { + label._break = done + label._continue = post + } + emitJump(fn, loop, s) + + // ...cond... under fn.objects[v] = i + fn.currentBlock = loop + for _, v := range vars { + fn.vars[v.obj] = v.phi + } + if s.Cond != nil { + b.cond(fn, s.Cond, body, done) + } else { + emitJump(fn, body, s) + } + + // ...body... under fn.objects[v] = i + fn.currentBlock = body + fn.targets = &targets{ + tail: fn.targets, + _break: done, + _continue: post, + } + b.stmt(fn, s.Body) + fn.targets = fn.targets.tail + emitJump(fn, post, s) + + // ...post... under fn.objects[v] = i_next + for _, v := range vars { + fn.vars[v.obj] = v.next + } + fn.currentBlock = post + if s.Post != nil { + b.stmt(fn, s.Post) + } + emitJump(fn, loop, s) // back-edge + fn.currentBlock = done + + // For each loop variable that does not escape, + // (the common case), fuse its next cells into its + // (local) outer cell as they have disjoint live ranges. + // + // It is sufficient to test whether i_next escapes, + // because its Heap flag will be marked true if either + // the cond or post expression causes i to escape + // (because escape distributes over phi). + var nlocals int + for _, v := range vars { + if !v.next.Heap { + nlocals++ + } + } + if nlocals > 0 { + replace := make(map[Value]Value, 2*nlocals) + dead := make(map[Instruction]bool, 4*nlocals) + for _, v := range vars { + if !v.next.Heap { + replace[v.next] = v.outer + replace[v.phi] = v.outer + dead[v.phi], dead[v.next], dead[v.load], dead[v.store] = true, true, true, true + } + } + + // Replace all uses of i_next and phi with i_outer. + // Referrers have not been built for fn yet so only update Instruction operands. + // We need only look within the blocks added by the loop. + var operands []*Value // recycle storage + for _, b := range fn.Blocks[startingBlocks:] { + for _, instr := range b.Instrs { + operands = instr.Operands(operands[:0]) + for _, ptr := range operands { + k := *ptr + if v := replace[k]; v != nil { + *ptr = v + } + } + } + } + + // Remove instructions for phi, load, and store. + // lift() will remove the unused i_next *Alloc. + isDead := func(i Instruction) bool { return dead[i] } + loop.Instrs = removeInstrsIf(loop.Instrs, isDead) + post.Instrs = removeInstrsIf(post.Instrs, isDead) + } +} + // rangeIndexed emits to fn the header for an integer-indexed loop // over array, *array or slice value x. // The v result is defined only if tv is non-nil. @@ -1973,13 +2189,15 @@ func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, source ast. // // We store the length in an Alloc and load it on each iteration so that lifting produces the necessary σ nodes length := newVariable(fn, tInt, source) - if arr, ok := deref(x.Type()).Underlying().(*types.Array); ok && !typeparams.IsTypeParam(x.Type()) { + if arr, ok := typeutil.CoreType(deref(x.Type())).(*types.Array); ok { // For array or *array, the number of iterations is known statically thanks to the type. We avoid a data // dependence upon x, permitting later dead-code elimination if x is pure, static unrolling, etc. Ranging over a // nil *array may have >0 iterations. We still generate code for x, in case it has effects. // - // This intentionally misses type parameters with core types, because their length isn't technically constant. - length.store(emitConst(fn, intConst(arr.Len()))) + // We use the core type of x, even though the length of type parameters isn't constant as per the language + // specification. Just because len(x) isn't constant doesn't mean we can't emit IR that takes advantage of a + // known length. + length.store(emitConst(fn, intConst(arr.Len(), nil))) } else { // length = len(x). var c Call @@ -1989,8 +2207,8 @@ func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, source ast. length.store(fn.emit(&c, source)) } - index := fn.addLocal(tInt, source) - emitStore(fn, index, emitConst(fn, intConst(-1)), source) + index := emitLocal(fn, tInt, source, "rangeindex") + emitStore(fn, index, emitConst(fn, intConst(-1, nil)), source) loop = fn.newBasicBlock("rangeindex.loop") emitJump(fn, loop, source) @@ -1999,7 +2217,7 @@ func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, source ast. incr := &BinOp{ Op: token.ADD, X: emitLoad(fn, index, source), - Y: emitConst(fn, intConst(1)), + Y: emitConst(fn, intConst(1, nil)), } incr.setType(tInt) emitStore(fn, index, fn.emit(incr, source), source) @@ -2144,6 +2362,57 @@ func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, source ast.Nod return } +// rangeInt emits to fn the header for a range loop with an integer operand. +// tk is the key value's type, or nil if the k result is not wanted. +// pos is the position of the "for" token. +func (b *builder) rangeInt(fn *Function, x Value, tk types.Type, source ast.Node) (k Value, loop, done *BasicBlock) { + // + // iter = 0 + // if 0 < x goto body else done + // loop: (target of continue) + // iter++ + // if iter < x goto body else done + // body: + // k = x + // ...body... + // jump loop + // done: (target of break) + + if b, ok := x.Type().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 { + x = emitConv(fn, x, tInt, source) + } + + T := x.Type() + iter := emitLocal(fn, T, source, "rangeint.iter") + // x may be unsigned. Avoid initializing x to -1. + + body := fn.newBasicBlock("rangeint.body") + done = fn.newBasicBlock("rangeint.done") + emitIf(fn, emitCompare(fn, token.LSS, emitConst(fn, zeroConst(T, source)), x, source), body, done, source) + + loop = fn.newBasicBlock("rangeint.loop") + fn.currentBlock = loop + + incr := &BinOp{ + Op: token.ADD, + X: emitLoad(fn, iter, source), + Y: emitConv(fn, emitConst(fn, intConst(1, source)), T, source), + } + incr.setType(T) + emitStore(fn, iter, fn.emit(incr, source), source) + emitIf(fn, emitCompare(fn, token.LSS, incr, x, source), body, done, source) + fn.currentBlock = body + + if tk != nil { + // Integer types (int, uint8, etc.) are named and + // we know that k is assignable to x when tk != nil. + // This implies tk and T are identical so no conversion is needed. + k = emitLoad(fn, iter, source) + } + + return +} + type variable struct { alloc *Alloc fn *Function @@ -2181,21 +2450,29 @@ func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock, sourc tv = fn.Pkg.typeOf(s.Value) } - // If iteration variables are defined (:=), this - // occurs once outside the loop. - // - // Unlike a short variable declaration, a RangeStmt - // using := never redeclares an existing variable; it - // always creates a new one. - if s.Tok == token.DEFINE { + // create locals for s.Key and s.Value + createVars := func() { + // Unlike a short variable declaration, a RangeStmt + // using := never redeclares an existing variable; it + // always creates a new one. if tk != nil { - fn.addLocalForIdent(s.Key.(*ast.Ident)) + id := s.Key.(*ast.Ident) + emitLocalVar(fn, identVar(fn, id), id) } if tv != nil { - fn.addLocalForIdent(s.Value.(*ast.Ident)) + id := s.Value.(*ast.Ident) + emitLocalVar(fn, identVar(fn, id), id) } } + afterGo122 := version.Compare(fn.goversion, "go1.22") >= 0 + + if s.Tok == token.DEFINE && !afterGo122 { + // pre-go1.22: If iteration variables are defined (:=), this + // occurs once outside the loop. + createVars() + } + x := b.expr(fn, s.X) var k, v Value @@ -2207,13 +2484,38 @@ func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock, sourc case *types.Chan: k, loop, done = b.rangeChan(fn, x, tk, source) - case *types.Map, *types.Basic: // string + case *types.Map: k, v, loop, done = b.rangeIter(fn, x, tk, tv, source) + case *types.Basic: + switch { + case rt.Info()&types.IsString != 0: + k, v, loop, done = b.rangeIter(fn, x, tk, tv, source) + + case rt.Info()&types.IsInteger != 0: + k, loop, done = b.rangeInt(fn, x, tk, source) + + default: + panic("Cannot range over basic type: " + rt.String()) + } + + case *types.Signature: + // Special case rewrite (fn.goversion >= go1.23): + // for x := range f { ... } + // into + // f(func(x T) bool { ... }) + b.rangeFunc(fn, x, tk, tv, s, label) + return + default: panic("Cannot range over: " + rt.String()) } + if s.Tok == token.DEFINE && afterGo122 { + // go1.22: If iteration variables are defined (:=), this occurs inside the loop. + createVars() + } + // Evaluate both LHS expressions before we update either. var kl, vl lvalue if tk != nil { @@ -2245,6 +2547,283 @@ func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock, sourc fn.currentBlock = done } +// rangeFunc emits to fn code for the range-over-func rng.Body of the iterator +// function x, optionally labelled by label. It creates a new anonymous function +// yield for rng and builds the function. +func (b *builder) rangeFunc(fn *Function, x Value, tk, tv types.Type, rng *ast.RangeStmt, label *lblock) { + // Consider the SSA code for the outermost range-over-func in fn: + // + // func fn(...) (ret R) { + // ... + // for k, v = range x { + // ... + // } + // ... + // } + // + // The code emitted into fn will look something like this. + // + // loop: + // jump := READY + // y := make closure yield [ret, deferstack, jump, k, v] + // x(y) + // switch jump { + // [see resuming execution] + // } + // goto done + // done: + // ... + // + // where yield is a new synthetic yield function: + // + // func yield(_k tk, _v tv) bool + // free variables: [ret, stack, jump, k, v] + // { + // entry: + // if jump != READY then goto invalid else valid + // invalid: + // panic("iterator called when it is not in a ready state") + // valid: + // jump = BUSY + // k = _k + // v = _v + // ... + // cont: + // jump = READY + // return true + // } + // + // Yield state: + // + // Each range loop has an associated jump variable that records + // the state of the iterator. A yield function is initially + // in a READY (0) and callable state. If the yield function is called + // and is not in READY state, it panics. When it is called in a callable + // state, it becomes BUSY. When execution reaches the end of the body + // of the loop (or a continue statement targeting the loop is executed), + // the yield function returns true and resumes being in a READY state. + // After the iterator function x(y) returns, then if the yield function + // is in a READY state, the yield enters the DONE state. + // + // Each lowered control statement (break X, continue X, goto Z, or return) + // that exits the loop sets the variable to a unique positive EXIT value, + // before returning false from the yield function. + // + // If the yield function returns abruptly due to a panic or GoExit, + // it remains in a BUSY state. The generated code asserts that, after + // the iterator call x(y) returns normally, the jump variable state + // is DONE. + // + // Resuming execution: + // + // The code generated for the range statement checks the jump + // variable to determine how to resume execution. + // + // switch jump { + // case BUSY: panic("...") + // case DONE: goto done + // case READY: state = DONE; goto done + // case 123: ... // action for exit 123. + // case 456: ... // action for exit 456. + // ... + // } + // + // Forward goto statements within a yield are jumps to labels that + // have not yet been traversed in fn. They may be in the Body of the + // function. What we emit for these is: + // + // goto target + // target: + // ... + // + // We leave an unresolved exit in yield.exits to check at the end + // of building yield if it encountered target in the body. If it + // encountered target, no additional work is required. Otherwise, + // the yield emits a new early exit in the basic block for target. + // We expect that blockopt will fuse the early exit into the case + // block later. The unresolved exit is then added to yield.parent.exits. + + loop := fn.newBasicBlock("rangefunc.loop") + done := fn.newBasicBlock("rangefunc.done") + + // These are targets within y. + fn.targets = &targets{ + tail: fn.targets, + _break: done, + // _continue is within y. + } + if label != nil { + label._break = done + // _continue is within y + } + + emitJump(fn, loop, nil) + fn.currentBlock = loop + + // loop: + // jump := READY + + anonIdx := len(fn.AnonFuncs) + + jump := newVar(fmt.Sprintf("jump$%d", anonIdx+1), tInt) + emitLocalVar(fn, jump, nil) // zero value is READY + + xsig := typeutil.CoreType(x.Type()).(*types.Signature) + ysig := typeutil.CoreType(xsig.Params().At(0).Type()).(*types.Signature) + + /* synthetic yield function for body of range-over-func loop */ + y := &Function{ + name: fmt.Sprintf("%s$%d", fn.Name(), anonIdx+1), + Signature: ysig, + Synthetic: SyntheticRangeOverFuncYield, + parent: fn, + Pkg: fn.Pkg, + Prog: fn.Prog, + functionBody: new(functionBody), + } + y.source = rng + y.goversion = fn.goversion + y.jump = jump + y.deferstack = fn.deferstack + y.returnVars = fn.returnVars // use the parent's return variables + y.uniq = fn.uniq // start from parent's unique values + + // If the RangeStmt has a label, this is how it is passed to buildYieldFunc. + if label != nil { + y.lblocks = map[*types.Label]*lblock{label.label: nil} + } + fn.AnonFuncs = append(fn.AnonFuncs, y) + + // Build y immediately. It may: + // * cause fn's locals to escape, and + // * create new exit nodes in exits. + // (y is not marked 'built' until the end of the enclosing FuncDecl.) + unresolved := len(fn.exits) + b.buildYieldFunc(y) + fn.uniq = y.uniq // resume after y's unique values + + // Emit the call of y. + // c := MakeClosure y + // x(c) + c := &MakeClosure{Fn: y} + c.setType(ysig) + c.comment = "yield" + for _, fv := range y.FreeVars { + c.Bindings = append(c.Bindings, fv.outer) + fv.outer = nil + } + fn.emit(c, nil) + call := Call{ + Call: CallCommon{ + Value: x, + Args: []Value{c}, + }, + } + call.setType(xsig.Results()) + fn.emit(&call, nil) + + exits := fn.exits[unresolved:] + b.buildYieldResume(fn, jump, exits, done) + + fn.currentBlock = done +} + +// buildYieldResume emits to fn code for how to resume execution once a call to +// the iterator function over the yield function returns x(y). It does this by building +// a switch over the value of jump for when it is READY, BUSY, or EXIT(id). +func (b *builder) buildYieldResume(fn *Function, jump *types.Var, exits []*exit, done *BasicBlock) { + // v := *jump + // switch v { + // case BUSY: panic("...") + // case READY: jump = DONE; goto done + // case EXIT(a): ... + // case EXIT(b): ... + // ... + // } + v := emitLoad(fn, fn.lookup(jump, false), nil) + + entry := fn.currentBlock + bodies := make([]*BasicBlock, 2, 2+len(exits)) + bodies[0] = fn.newBasicBlock("rangefunc.resume.busy") + bodies[1] = fn.newBasicBlock("rangefunc.resume.ready") + + conds := make([]Value, 2, 2+len(exits)) + conds[0] = emitConst(fn, jBusy()) + conds[1] = emitConst(fn, jReady()) + + fn.currentBlock = bodies[0] + fn.emit( + &Panic{ + X: emitConv(fn, emitConst(fn, stringConst("iterator call did not preserve panic", nil)), tEface, nil), + }, + nil, + ) + addEdge(fn.currentBlock, fn.Exit) + + fn.currentBlock = bodies[1] + storeVar(fn, jump, emitConst(fn, jDone()), nil) + emitJump(fn, done, nil) + + for _, e := range exits { + body := fn.newBasicBlock(fmt.Sprintf("rangefunc.resume.exit.%d", e.id)) + bodies = append(bodies, body) + id_ := intConst(e.id, nil) + id_.comment = fmt.Sprintf("rangefunc.exit.%d", e.id) + id := emitConst(fn, id_) + conds = append(conds, id) + + fn.currentBlock = body + switch { + case e.label != nil: // forward goto? + // case EXIT(id): goto lb // label + lb := fn.lblockOf(e.label) + // Do not mark lb as resolved. + // If fn does not contain label, lb remains unresolved and + // fn must itself be a range-over-func function. lb will be: + // lb: + // fn.jump = id + // return false + emitJump(fn, lb._goto, e.source) + + case e.to != fn: // e jumps to an ancestor of fn? + // case EXIT(id): { fn.jump = id; return false } + // fn is a range-over-func function. + + storeVar(fn, fn.jump, id, e.source) + vFalse := emitConst(fn, NewConst(constant.MakeBool(false), tBool, e.source)) + emitReturn(fn, []Value{vFalse}, e.source) + + case e.block == nil && e.label == nil: // return from fn? + // case EXIT(id): { return ... } + + // The results have already been stored to variables in fn.results, so + // emitReturn doesn't have to do it again. + emitReturn(fn, nil, e.source) + + case e.block != nil: + // case EXIT(id): goto block + emitJump(fn, e.block, e.source) + + default: + panic("unreachable") + } + + } + + fn.currentBlock = entry + // Note that this switch does not have an implicit default case. This wouldn't be + // valid for a user-provided switch statement, but for range-over-func we know all + // possible values and we can avoid the impossible branch. + swtch := &ConstantSwitch{ + Tag: v, + Conds: conds, + } + fn.emit(swtch, nil) + for _, body := range bodies { + addEdge(entry, body) + } +} + // stmt lowers statement s to IR form, emitting code to fn. func (b *builder) stmt(fn *Function, _s ast.Stmt) { // The label of the current statement. If non-nil, its _goto @@ -2268,7 +2847,14 @@ start: } case *ast.LabeledStmt: - label = fn.labelledBlock(s.Label) + if s.Label.Name == "_" { + // Blank labels can't be the target of a goto, break, + // or continue statement, so we don't need a new block. + _s = s.Stmt + goto start + } + label = fn.lblockOf(fn.label(s.Label)) + label.resolved = true emitJump(fn, label._goto, s) fn.currentBlock = label._goto _s = s.Stmt @@ -2291,7 +2877,7 @@ start: op = token.SUB } loc := b.addr(fn, s.X, false) - b.assignOp(fn, loc, emitConst(fn, NewConst(constant.MakeInt64(1), loc.typ())), op, s) + b.assignOp(fn, loc, emitConst(fn, NewConst(constant.MakeInt64(1), loc.typ(), s)), op, s) case *ast.AssignStmt: switch s.Tok { @@ -2313,73 +2899,17 @@ start: case *ast.DeferStmt: // The "intrinsics" new/make/len/cap are forbidden here. // panic is treated like an ordinary function call. - v := Defer{} + deferstack := emitLoad(fn, fn.lookup(fn.deferstack, false), s) + v := Defer{_DeferStack: deferstack} b.setCall(fn, s.Call, &v.Call) fn.hasDefer = true fn.emit(&v, s) case *ast.ReturnStmt: - // TODO(dh): we could emit tighter position information by - // using the ith returned expression - - var results []Value - if len(s.Results) == 1 && fn.Signature.Results().Len() > 1 { - // Return of one expression in a multi-valued function. - tuple := b.exprN(fn, s.Results[0]) - ttuple := tuple.Type().(*types.Tuple) - for i, n := 0, ttuple.Len(); i < n; i++ { - results = append(results, - emitConv(fn, emitExtract(fn, tuple, i, s), - fn.Signature.Results().At(i).Type(), s)) - } - } else { - // 1:1 return, or no-arg return in non-void function. - for i, r := range s.Results { - v := emitConv(fn, b.expr(fn, r), fn.Signature.Results().At(i).Type(), s) - results = append(results, v) - } - } - - ret := fn.results() - for i, r := range results { - emitStore(fn, ret[i], r, s) - } - - emitJump(fn, fn.Exit, s) - fn.currentBlock = fn.newBasicBlock("unreachable") + b.returnStmt(fn, s) case *ast.BranchStmt: - var block *BasicBlock - switch s.Tok { - case token.BREAK: - if s.Label != nil { - block = fn.labelledBlock(s.Label)._break - } else { - for t := fn.targets; t != nil && block == nil; t = t.tail { - block = t._break - } - } - - case token.CONTINUE: - if s.Label != nil { - block = fn.labelledBlock(s.Label)._continue - } else { - for t := fn.targets; t != nil && block == nil; t = t.tail { - block = t._continue - } - } - - case token.FALLTHROUGH: - for t := fn.targets; t != nil && block == nil; t = t.tail { - block = t._fallthrough - } - - case token.GOTO: - block = fn.labelledBlock(s.Label)._goto - } - j := emitJump(fn, block, s) - j.comment = s.Tok.String() - fn.currentBlock = fn.newBasicBlock("unreachable") + b.branchStmt(fn, s) case *ast.BlockStmt: b.stmtList(fn, s.List) @@ -2431,6 +2961,106 @@ start: } } +func (b *builder) branchStmt(fn *Function, s *ast.BranchStmt) { + var block *BasicBlock + if s.Label == nil { + block = targetedBlock(fn, s.Tok) + } else { + target := fn.label(s.Label) + block = labelledBlock(fn, target, s.Tok) + if block == nil { // forward goto + lb := fn.lblockOf(target) + block = lb._goto // jump to lb._goto + if fn.jump != nil { + // fn is a range-over-func and the goto may exit fn. + // Create an exit and resolve it at the end of + // builder.buildYieldFunc. + labelExit(fn, target, s) + } + } + } + to := block.parent + + if to == fn { + emitJump(fn, block, s) + } else { // break outside of fn. + // fn must be a range-over-func + e := blockExit(fn, block, s) + id_ := intConst(e.id, s) + id_.comment = fmt.Sprintf("rangefunc.exit.%d", e.id) + id := emitConst(fn, id_) + storeVar(fn, fn.jump, id, s) + vFalse := emitConst(fn, NewConst(constant.MakeBool(false), tBool, s)) + emitReturn(fn, []Value{vFalse}, s) + } + fn.currentBlock = fn.newBasicBlock("unreachable") +} + +func (b *builder) returnStmt(fn *Function, s *ast.ReturnStmt) { + // TODO(dh): we could emit tighter position information by + // using the ith returned expression + + var results []Value + + sig := fn.sourceFn.Signature // signature of the enclosing source function + + // Convert return operands to result type. + if len(s.Results) == 1 && sig.Results().Len() > 1 { + // Return of one expression in a multi-valued function. + tuple := b.exprN(fn, s.Results[0]) + ttuple := tuple.Type().(*types.Tuple) + for i, n := 0, ttuple.Len(); i < n; i++ { + results = append(results, + emitConv(fn, emitExtract(fn, tuple, i, s), + sig.Results().At(i).Type(), s)) + } + } else { + // 1:1 return, or no-arg return in non-void function. + for i, r := range s.Results { + v := emitConv(fn, b.expr(fn, r), sig.Results().At(i).Type(), s) + results = append(results, v) + } + } + + // Store the results. + for i, r := range results { + var result Value // fn.sourceFn.result[i] conceptually + if fn == fn.sourceFn { + result = fn.results[i] + } else { // lookup needed? + result = fn.lookup(fn.returnVars[i], false) + } + emitStore(fn, result, r, s) + } + + if fn.jump != nil { + // Return from body of a range-over-func. + // The return statement is syntactically within the loop, + // but the generated code is in the 'switch jump {...}' after it. + e := returnExit(fn, s) + id_ := intConst(e.id, e.source) + id_.comment = fmt.Sprintf("rangefunc.exit.%d", e.id) + id := emitConst(fn, id_) + storeVar(fn, fn.jump, id, e.source) + vFalse := emitConst(fn, NewConst(constant.MakeBool(false), tBool, e.source)) + emitReturn(fn, []Value{vFalse}, e.source) + return + } + + // The results have already been stored to variables in fn.results, so + // emitReturn doesn't have to do it again. + emitReturn(fn, nil, s) +} + +func emitReturn(fn *Function, results []Value, source ast.Node) { + for i, r := range results { + emitStore(fn, fn.results[i], r, source) + } + + emitJump(fn, fn.Exit, source) + fn.currentBlock = fn.newBasicBlock("unreachable") +} + // buildFunction builds IR code for the body of function fn. Idempotent. func (b *builder) buildFunction(fn *Function) { if fn.Blocks != nil { @@ -2476,12 +3106,12 @@ func (b *builder) buildFunction(fn *Function) { // code to reference them. This simplifies clients. if recv := fn.Signature.Recv(); recv != nil { // XXX synthesize an ast.Node - fn.addParamObj(recv, nil) + fn.addParamVar(recv, nil) } params := fn.Signature.Params() for i, n := 0, params.Len(); i < n; i++ { // XXX synthesize an ast.Node - fn.addParamObj(params.At(i), nil) + fn.addParamVar(params.At(i), nil) } } return @@ -2491,8 +3121,10 @@ func (b *builder) buildFunction(fn *Function) { } fn.blocksets = b.blocksets fn.Blocks = make([]*BasicBlock, 0, avgBlocks) + fn.sourceFn = fn fn.startBody() fn.createSyntacticParams(recvField, functype) + fn.createDeferStack() fn.exitBlock() b.stmt(fn, body) if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb.Preds != nil) { @@ -2516,13 +3148,161 @@ func (b *builder) buildFunction(fn *Function) { fn.functionBody = nil } +// buildYieldFunc builds the body of the yield function created +// from a range-over-func *ast.RangeStmt. +func (b *builder) buildYieldFunc(fn *Function) { + // See builder.rangeFunc for detailed documentation on how fn is set up. + // + // In psuedo-Go this roughly builds: + // func yield(_k tk, _v tv) bool { + // if jump != READY { panic("yield function called after range loop exit") } + // jump = BUSY + // k, v = _k, _v // assign the iterator variable (if needed) + // ... // rng.Body + // continue: + // jump = READY + // return true + // } + s := fn.source.(*ast.RangeStmt) + fn.sourceFn = fn.parent.sourceFn + fn.startBody() + params := fn.Signature.Params() + for i := 0; i < params.Len(); i++ { + fn.addParamVar(params.At(i), nil) + } + fn.addResultVar(fn.Signature.Results().At(0), nil) + fn.exitBlock() + + // Initial targets + ycont := fn.newBasicBlock("yield-continue") + // lblocks is either {} or is {label: nil} where label is the label of syntax. + for label := range fn.lblocks { + fn.lblocks[label] = &lblock{ + label: label, + resolved: true, + _goto: ycont, + _continue: ycont, + // `break label` statement targets fn.parent.targets._break + } + } + fn.targets = &targets{ + _continue: ycont, + // `break` statement targets fn.parent.targets._break. + } + + // continue: + // jump = READY + // return true + saved := fn.currentBlock + fn.currentBlock = ycont + storeVar(fn, fn.jump, emitConst(fn, jReady()), s.Body) + vTrue := emitConst(fn, NewConst(constant.MakeBool(true), tBool, nil)) + emitReturn(fn, []Value{vTrue}, nil) + + // Emit header: + // + // if jump != READY { panic("yield iterator accessed after exit") } + // jump = BUSY + // k, v = _k, _v + fn.currentBlock = saved + yloop := fn.newBasicBlock("yield-loop") + invalid := fn.newBasicBlock("yield-invalid") + + jumpVal := emitLoad(fn, fn.lookup(fn.jump, true), nil) + emitIf(fn, emitCompare(fn, token.EQL, jumpVal, emitConst(fn, jReady()), nil), yloop, invalid, nil) + fn.currentBlock = invalid + fn.emit( + &Panic{ + X: emitConv(fn, emitConst(fn, stringConst("yield function called after range loop exit", nil)), tEface, nil), + }, + nil, + ) + addEdge(fn.currentBlock, fn.Exit) + + fn.currentBlock = yloop + storeVar(fn, fn.jump, emitConst(fn, jBusy()), s.Body) + + // Initialize k and v from params. + var tk, tv types.Type + if s.Key != nil && !isBlankIdent(s.Key) { + tk = fn.Pkg.typeOf(s.Key) // fn.parent.typeOf is identical + } + if s.Value != nil && !isBlankIdent(s.Value) { + tv = fn.Pkg.typeOf(s.Value) + } + if s.Tok == token.DEFINE { + if tk != nil { + emitLocalVar(fn, identVar(fn, s.Key.(*ast.Ident)), s.Key) + } + if tv != nil { + emitLocalVar(fn, identVar(fn, s.Value.(*ast.Ident)), s.Value) + } + } + var k, v Value + if len(fn.Params) > 0 { + k = fn.Params[0] + } + if len(fn.Params) > 1 { + v = fn.Params[1] + } + var kl, vl lvalue + if tk != nil { + kl = b.addr(fn, s.Key, false) // non-escaping + } + if tv != nil { + vl = b.addr(fn, s.Value, false) // non-escaping + } + if tk != nil { + kl.store(fn, k, s.Key) + } + if tv != nil { + vl.store(fn, v, s.Value) + } + + // Build the body of the range loop. + b.stmt(fn, s.Body) + if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb.Preds != nil) { + // Control fell off the end of the function's body block. + // Block optimizations eliminate the current block, if + // unreachable. + emitJump(fn, ycont, nil) + } + + // Clean up exits and promote any unresolved exits to fn.parent. + for _, e := range fn.exits { + if e.label != nil { + lb := fn.lblocks[e.label] + if lb.resolved { + // label was resolved. Do not turn lb into an exit. + // e does not need to be handled by the parent. + continue + } + + // _goto becomes an exit. + // _goto: + // jump = id + // return false + fn.currentBlock = lb._goto + id_ := intConst(e.id, e.source) + id_.comment = fmt.Sprintf("rangefunc.exit.%d", e.id) + id := emitConst(fn, id_) + storeVar(fn, fn.jump, id, e.source) + vFalse := emitConst(fn, NewConst(constant.MakeBool(false), tBool, e.source)) + emitReturn(fn, []Value{vFalse}, e.source) + } + + if e.to != fn { // e needs to be handled by the parent too. + fn.parent.exits = append(fn.parent.exits, e) + } + } + + fn.finishBody() +} + // buildFuncDecl builds IR code for the function or method declared // by decl in package pkg. func (b *builder) buildFuncDecl(pkg *Package, decl *ast.FuncDecl) { id := decl.Name - if isBlankIdent(id) { - return // discard - } fn := pkg.values[pkg.info.Defs[id]].(*Function) if decl.Recv == nil && id.Name == "init" { var v Call @@ -2583,7 +3363,7 @@ func (p *Package) build() { done = init.Exit emitIf(init, emitLoad(init, initguard, nil), done, doinit, nil) init.currentBlock = doinit - emitStore(init, initguard, emitConst(init, NewConst(constant.MakeBool(true), tBool)), nil) + emitStore(init, initguard, emitConst(init, NewConst(constant.MakeBool(true), tBool, nil)), nil) // Call the init() function of each package we import. for _, pkg := range p.Pkg.Imports() { @@ -2607,6 +3387,12 @@ func (p *Package) build() { fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n", varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos())) } + // Initializers for global vars are evaluated in dependency + // order, but may come from arbitrary files of the package + // with different versions, so we transiently update + // init.goversion for each one. (Since init is a synthetic + // function it has no syntax of its own that needs a version.) + init.goversion = p.initVersion[varinit.Rhs] if len(varinit.Lhs) == 1 { // 1:1 initialization: var x, y = a(), b() var lval lvalue @@ -2628,6 +3414,7 @@ func (p *Package) build() { } } } + init.goversion = "" // The rest of the init function is synthetic. No syntax => no goversion. // Build all package-level functions, init functions // and methods, including unreachable/blank ones. @@ -2644,7 +3431,9 @@ func (p *Package) build() { emitJump(init, done, nil) init.finishBody() - p.info = nil // We no longer need ASTs or go/types deductions. + // We no longer need ASTs or go/types deductions. + p.info = nil + p.initVersion = nil if p.Prog.mode&SanityCheckFunctions != 0 { sanityCheckPackage(p) diff --git a/tools/vendor/honnef.co/go/tools/go/ir/const.go b/tools/vendor/honnef.co/go/tools/go/ir/const.go index 0faf3852a..7d27ec577 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/const.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/const.go @@ -8,6 +8,7 @@ package ir import ( "fmt" + "go/ast" "go/constant" "go/types" "strconv" @@ -19,37 +20,39 @@ import ( // NewConst returns a new constant of the specified value and type. // val must be valid according to the specification of Const.Value. -func NewConst(val constant.Value, typ types.Type) *Const { - return &Const{ +func NewConst(val constant.Value, typ types.Type, source ast.Node) *Const { + c := &Const{ register: register{ typ: typ, }, Value: val, } + c.setSource(source) + return c } // intConst returns an 'int' constant that evaluates to i. // (i is an int64 in case the host is narrower than the target.) -func intConst(i int64) *Const { - return NewConst(constant.MakeInt64(i), tInt) +func intConst(i int64, source ast.Node) *Const { + return NewConst(constant.MakeInt64(i), tInt, source) } // nilConst returns a nil constant of the specified type, which may // be any reference type, including interfaces. -func nilConst(typ types.Type) *Const { - return NewConst(nil, typ) +func nilConst(typ types.Type, source ast.Node) *Const { + return NewConst(nil, typ, source) } // stringConst returns a 'string' constant that evaluates to s. -func stringConst(s string) *Const { - return NewConst(constant.MakeString(s), tString) +func stringConst(s string, source ast.Node) *Const { + return NewConst(constant.MakeString(s), tString, source) } // zeroConst returns a new "zero" constant of the specified type. -func zeroConst(t types.Type) Constant { +func zeroConst(t types.Type, source ast.Node) Constant { if _, ok := t.Underlying().(*types.Interface); ok && !typeparams.IsTypeParam(t) { // Handle non-generic interface early to simplify following code. - return nilConst(t) + return nilConst(t, source) } tset := typeutil.NewTypeSet(t) @@ -58,21 +61,25 @@ func zeroConst(t types.Type) Constant { case *types.Struct: values := make([]Value, typ.NumFields()) for i := 0; i < typ.NumFields(); i++ { - values[i] = zeroConst(typ.Field(i).Type()) + values[i] = zeroConst(typ.Field(i).Type(), source) } - return &AggregateConst{ + ac := &AggregateConst{ register: register{typ: t}, Values: values, } + ac.setSource(source) + return ac case *types.Tuple: values := make([]Value, typ.Len()) for i := 0; i < typ.Len(); i++ { - values[i] = zeroConst(typ.At(i).Type()) + values[i] = zeroConst(typ.At(i).Type(), source) } - return &AggregateConst{ + ac := &AggregateConst{ register: register{typ: t}, Values: values, } + ac.setSource(source) + return ac } isNillable := func(term *types.Term) bool { @@ -108,20 +115,22 @@ func zeroConst(t types.Type) Constant { switch { case tset.All(isInfo(types.IsNumeric)): - return NewConst(constant.MakeInt64(0), t) + return NewConst(constant.MakeInt64(0), t, source) case tset.All(isInfo(types.IsString)): - return NewConst(constant.MakeString(""), t) + return NewConst(constant.MakeString(""), t, source) case tset.All(isInfo(types.IsBoolean)): - return NewConst(constant.MakeBool(false), t) + return NewConst(constant.MakeBool(false), t, source) case tset.All(isNillable): - return nilConst(t) + return nilConst(t, source) case tset.All(isArray): var k ArrayConst k.setType(t) + k.setSource(source) return &k default: var k GenericConst k.setType(t) + k.setSource(source) return &k } } @@ -246,7 +255,7 @@ func (c *Const) equal(o Constant) bool { if !ok { return false } - return c.typ == oc.typ && c.Value == oc.Value + return c.typ == oc.typ && c.Value == oc.Value && c.source == oc.source } func (c *AggregateConst) equal(o Constant) bool { @@ -258,6 +267,9 @@ func (c *AggregateConst) equal(o Constant) bool { if c.typ != oc.typ { return false } + if c.source != oc.source { + return false + } for i, v := range c.Values { if !v.(Constant).equal(oc.Values[i].(Constant)) { return false @@ -272,7 +284,7 @@ func (c *ArrayConst) equal(o Constant) bool { return false } // TODO(dh): don't use == for types, this will miss identical pointer types, among others - return c.typ == oc.typ + return c.typ == oc.typ && c.source == oc.source } func (c *GenericConst) equal(o Constant) bool { @@ -281,5 +293,5 @@ func (c *GenericConst) equal(o Constant) bool { return false } // TODO(dh): don't use == for types, this will miss identical pointer types, among others - return c.typ == oc.typ + return c.typ == oc.typ && c.source == oc.source } diff --git a/tools/vendor/honnef.co/go/tools/go/ir/create.go b/tools/vendor/honnef.co/go/tools/go/ir/create.go index 28e7da7e9..9aef3a5df 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/create.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/create.go @@ -12,6 +12,7 @@ import ( "go/ast" "go/token" "go/types" + "go/version" "os" "sync" @@ -32,8 +33,6 @@ func NewProgram(fset *token.FileSet, mode BuilderMode) *Program { Fset: fset, imported: make(map[string]*Package), packages: make(map[*types.Package]*Package), - thunks: make(map[selectionKey]*Function), - bounds: make(map[*types.Func]*Function), mode: mode, } @@ -47,10 +46,10 @@ func NewProgram(fset *token.FileSet, mode BuilderMode) *Program { // memberFromObject populates package pkg with a member for the // typechecker object obj. // -// For objects from Go source code, syntax is the associated syntax -// tree (for funcs and vars only); it will be used during the build -// phase. -func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { +// For objects from Go source code, syntax is the associated syntax tree +// (for funcs and vars only) and goversion defines the appropriate +// interpretation; they will be used during the build phase. +func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node, goversion string) { name := obj.Name() switch obj := obj.(type) { case *types.Builtin: @@ -59,19 +58,23 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { } case *types.TypeName: - pkg.Members[name] = &Type{ - object: obj, - pkg: pkg, + if name != "_" { + pkg.Members[name] = &Type{ + object: obj, + pkg: pkg, + } } case *types.Const: c := &NamedConst{ object: obj, - Value: NewConst(obj.Val(), obj.Type()), + Value: NewConst(obj.Val(), obj.Type(), syntax), pkg: pkg, } pkg.values[obj] = c.Value - pkg.Members[name] = c + if name != "_" { + pkg.Members[name] = c + } case *types.Var: g := &Global{ @@ -81,7 +84,9 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { typ: types.NewPointer(obj.Type()), // address } pkg.values[obj] = g - pkg.Members[name] = g + if name != "_" { + pkg.Members[name] = g + } case *types.Func: sig := obj.Type().(*types.Signature) @@ -95,6 +100,7 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { Signature: sig, Pkg: pkg, Prog: pkg.Prog, + goversion: goversion, } fn.source = syntax @@ -114,7 +120,7 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { pkg.values[obj] = fn pkg.Functions = append(pkg.Functions, fn) - if sig.Recv() == nil { + if name != "_" && sig.Recv() == nil { pkg.Members[name] = fn // package-level function } @@ -126,42 +132,46 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { // membersFromDecl populates package pkg with members for each // typechecker object (var, func, const or type) associated with the // specified decl. -func membersFromDecl(pkg *Package, decl ast.Decl) { +func membersFromDecl(pkg *Package, decl ast.Decl, goversion string) { switch decl := decl.(type) { case *ast.GenDecl: // import, const, type or var switch decl.Tok { case token.CONST: for _, spec := range decl.Specs { for _, id := range spec.(*ast.ValueSpec).Names { - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], nil) - } + memberFromObject(pkg, pkg.info.Defs[id], nil, "") } } case token.VAR: for _, spec := range decl.Specs { + for _, rhs := range spec.(*ast.ValueSpec).Values { + pkg.initVersion[rhs] = goversion + } for _, id := range spec.(*ast.ValueSpec).Names { - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], spec) - } + memberFromObject(pkg, pkg.info.Defs[id], spec, goversion) } } case token.TYPE: for _, spec := range decl.Specs { id := spec.(*ast.TypeSpec).Name - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], nil) - } + memberFromObject(pkg, pkg.info.Defs[id], nil, "") } } case *ast.FuncDecl: id := decl.Name - if !isBlankIdent(id) { - memberFromObject(pkg, pkg.info.Defs[id], decl) + obj, ok := pkg.info.Defs[id] + if !ok { + panic(fmt.Sprintf("couldn't find object for id %q at %s", + id.Name, pkg.Prog.Fset.PositionFor(id.Pos(), false))) + } + if obj == nil { + panic(fmt.Sprintf("found nil object for id %q at %s", + id.Name, pkg.Prog.Fset.PositionFor(id.Pos(), false))) } + memberFromObject(pkg, obj, decl, goversion) } } @@ -176,13 +186,15 @@ func membersFromDecl(pkg *Package, decl ast.Decl) { // until a subsequent call to Package.Build(). func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info *types.Info, importable bool) *Package { p := &Package{ - Prog: prog, - Members: make(map[string]Member), - values: make(map[types.Object]Value), - Pkg: pkg, - info: info, // transient (CREATE and BUILD phases) - files: files, // transient (CREATE and BUILD phases) - printFunc: prog.PrintFunc, + Prog: prog, + Members: make(map[string]Member), + values: make(map[types.Object]Value), + Pkg: pkg, + // transient values (CREATE and BUILD phases) + info: info, + files: files, + printFunc: prog.PrintFunc, + initVersion: make(map[ast.Expr]string), } // Add init() function. @@ -193,6 +205,7 @@ func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info * Pkg: p, Prog: prog, functionBody: new(functionBody), + goversion: "", // See Package.build for details. } p.init.initHTML(prog.PrintFunc) p.Members[p.init.name] = p.init @@ -203,8 +216,9 @@ func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info * if len(files) > 0 { // Go source package. for _, file := range files { + goversion := version.Lang(p.info.FileVersions[file]) for _, decl := range file.Decls { - membersFromDecl(p, decl) + membersFromDecl(p, decl, goversion) } } } else { @@ -214,11 +228,11 @@ func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info * scope := p.Pkg.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) - memberFromObject(p, obj, nil) + memberFromObject(p, obj, nil, "") if obj, ok := obj.(*types.TypeName); ok { if named, ok := obj.Type().(*types.Named); ok { for i, n := 0, named.NumMethods(); i < n; i++ { - memberFromObject(p, named.Method(i), nil) + memberFromObject(p, named.Method(i), nil, "") } } } diff --git a/tools/vendor/honnef.co/go/tools/go/ir/doc.go b/tools/vendor/honnef.co/go/tools/go/ir/doc.go index 5ee6637db..e15ef60f4 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/doc.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/doc.go @@ -10,9 +10,9 @@ // THIS INTERFACE IS EXPERIMENTAL AND IS LIKELY TO CHANGE. // // For an introduction to SSA form, upon which SSI builds, see -// http://en.wikipedia.org/wiki/Static_single_assignment_form. +// https://en.wikipedia.org/wiki/Static_single_assignment_form. // This page provides a broader reading list: -// http://www.dcs.gla.ac.uk/~jsinger/ssa.html. +// https://www.dcs.gla.ac.uk/~jsinger/ssa.html. // // For an introduction to SSI form, see The static single information // form by C. Scott Ananian. @@ -79,6 +79,7 @@ // *MakeSlice ✔ ✔ // *MapLookup ✔ ✔ // *MapUpdate ✔ ✔ +// *MultiConvert ✔ ✔ // *NamedConst ✔ (const) // *Next ✔ ✔ // *Panic ✔ diff --git a/tools/vendor/honnef.co/go/tools/go/ir/dom.go b/tools/vendor/honnef.co/go/tools/go/ir/dom.go index 4febd284b..3f44c7c2a 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/dom.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/dom.go @@ -10,11 +10,11 @@ package ir // // We use the algorithm described in Lengauer & Tarjan. 1979. A fast // algorithm for finding dominators in a flowgraph. -// http://doi.acm.org/10.1145/357062.357071 +// https://doi.acm.org/10.1145/357062.357071 // // We also apply the optimizations to SLT described in Georgiadis et // al, Finding Dominators in Practice, JGAA 2006, -// http://jgaa.info/accepted/2006/GeorgiadisTarjanWerneck2006.10.1.pdf +// https://jgaa.info/accepted/2006/GeorgiadisTarjanWerneck2006.10.1.pdf // to avoid the need for buckets of size > 1. import ( diff --git a/tools/vendor/honnef.co/go/tools/go/ir/emit.go b/tools/vendor/honnef.co/go/tools/go/ir/emit.go index f6a1ef373..e4304d10a 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/emit.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/emit.go @@ -18,15 +18,52 @@ import ( "golang.org/x/exp/typeparams" ) -// emitNew emits to f a new (heap Alloc) instruction allocating an -// object of type typ. pos is the optional source location. -func emitNew(f *Function, typ types.Type, source ast.Node) *Alloc { - v := &Alloc{Heap: true} +// emitAlloc emits to f a new Alloc instruction allocating a variable +// of type typ. +// +// The caller must set Alloc.Heap=true (for a heap-allocated variable) +// or add the Alloc to f.Locals (for a frame-allocated variable). +// +// During building, a variable in f.Locals may have its Heap flag +// set when it is discovered that its address is taken. +// These Allocs are removed from f.Locals at the end. +// +// The builder should generally call one of the emit{New,Local,LocalVar} wrappers instead. +func emitAlloc(f *Function, typ types.Type, source ast.Node, comment string) *Alloc { + v := &Alloc{} + v.comment = comment v.setType(types.NewPointer(typ)) f.emit(v, source) return v } +// emitNew emits to f a new Alloc instruction heap-allocating a +// variable of type typ. +func emitNew(f *Function, typ types.Type, source ast.Node, comment string) *Alloc { + alloc := emitAlloc(f, typ, source, comment) + alloc.Heap = true + return alloc +} + +// emitLocal creates a local var for (t, source, comment) and +// emits an Alloc instruction for it. +// +// (Use this function or emitNew for synthetic variables; +// for source-level variables, use emitLocalVar.) +func emitLocal(f *Function, t types.Type, source ast.Node, comment string) *Alloc { + local := emitAlloc(f, t, source, comment) + f.Locals = append(f.Locals, local) + return local +} + +// emitLocalVar creates a local var for v and emits an Alloc instruction for it. +// Subsequent calls to f.lookup(v) return it. +func emitLocalVar(f *Function, v *types.Var, source ast.Node) *Alloc { + alloc := emitLocal(f, v.Type(), source, v.Name()) + f.vars[v] = alloc + return alloc +} + // emitLoad emits to f an instruction to load the address addr into a // new temporary, and returns the value so defined. func emitLoad(f *Function, addr Value, source ast.Node) *Load { @@ -199,24 +236,17 @@ func emitConv(f *Function, val Value, t_dst types.Type, source ast.Node) Value { ut_dst := t_dst.Underlying() ut_src := t_src.Underlying() - tset_dst := typeutil.NewTypeSet(ut_dst) - tset_src := typeutil.NewTypeSet(ut_src) - - // Just a change of type, but not value or representation? - if tset_src.All(func(termSrc *types.Term) bool { - return tset_dst.All(func(termDst *types.Term) bool { - return isValuePreserving(termSrc.Type().Underlying(), termDst.Type().Underlying()) - }) - }) { - c := &ChangeType{X: val} - c.setType(t_dst) - return f.emit(c, source) - } - // Conversion to, or construction of a value of, an interface type? - if _, ok := ut_dst.(*types.Interface); ok && !typeparams.IsTypeParam(t_dst) { + if isNonTypeParamInterface(t_dst) { + // Interface name change? + if isValuePreserving(ut_src, ut_dst) { + c := &ChangeType{X: val} + c.setType(t_dst) + return f.emit(c, source) + } + // Assignment from one interface type to another? - if _, ok := ut_src.(*types.Interface); ok && !typeparams.IsTypeParam(t_src) { + if isNonTypeParamInterface(t_src) { c := &ChangeInterface{X: val} c.setType(t_dst) return f.emit(c, source) @@ -224,7 +254,7 @@ func emitConv(f *Function, val Value, t_dst types.Type, source ast.Node) Value { // Untyped nil constant? Return interface-typed nil constant. if ut_src == tUntypedNil { - return emitConst(f, nilConst(t_dst)) + return emitConst(f, zeroConst(t_dst, source)) } // Convert (non-nil) "untyped" literals to their default type. @@ -238,71 +268,130 @@ func emitConv(f *Function, val Value, t_dst types.Type, source ast.Node) Value { return f.emit(mi, source) } - // Conversion of a compile-time constant value? Note that converting a constant to a type parameter never results in - // a constant value. + // In the common case, the typesets of src and dst are singletons + // and we emit an appropriate conversion. But if either contains + // a type parameter, the conversion may represent a cross product, + // in which case which we emit a MultiConvert. + tset_dst := typeutil.NewTypeSet(ut_dst) + tset_src := typeutil.NewTypeSet(ut_src) + + // conversionCase describes an instruction pattern that may be emitted to + // model d <- s for d in dst_terms and s in src_terms. + // Multiple conversions can match the same pattern. + type conversionCase uint8 + const ( + changeType conversionCase = 1 << iota + sliceToArray + sliceToArrayPtr + sliceTo0Array + sliceTo0ArrayPtr + convert + ) + + classify := func(s, d types.Type) conversionCase { + // Just a change of type, but not value or representation? + if isValuePreserving(s, d) { + return changeType + } + + // Conversion from slice to array or slice to array pointer? + if slice, ok := s.(*types.Slice); ok { + var arr *types.Array + var ptr bool + // Conversion from slice to array pointer? + switch d := d.(type) { + case *types.Array: + arr = d + case *types.Pointer: + arr, _ = d.Elem().Underlying().(*types.Array) + ptr = true + } + if arr != nil && types.Identical(slice.Elem(), arr.Elem()) { + if arr.Len() == 0 { + if ptr { + return sliceTo0ArrayPtr + } else { + return sliceTo0Array + } + } + if ptr { + return sliceToArrayPtr + } else { + return sliceToArray + } + } + } + + // The only remaining case in well-typed code is a representation- + // changing conversion of basic types (possibly with []byte/[]rune). + if !isBasic(s) && !isBasic(d) { + panic(fmt.Sprintf("in %s: cannot convert term %s (%s [within %s]) to type %s [within %s]", f, val, val.Type(), s, t_dst, d)) + } + return convert + } + + var classifications conversionCase + for _, s := range tset_src.Terms { + us := s.Type().Underlying() + for _, d := range tset_dst.Terms { + ud := d.Type().Underlying() + classifications |= classify(us, ud) + } + } + if classifications == 0 { + panic(fmt.Sprintf("in %s: cannot convert %s (%s) to %s", f, val, val.Type(), t_dst)) + } + + // Conversion of a compile-time constant value? if c, ok := val.(*Const); ok { - if _, ok := ut_dst.(*types.Basic); ok || c.IsNil() { + // Conversion to a basic type? + if isBasic(ut_dst) { // Conversion of a compile-time constant to // another constant type results in a new // constant of the destination type and // (initially) the same abstract value. // We don't truncate the value yet. - return emitConst(f, NewConst(c.Value, t_dst)) + return emitConst(f, NewConst(c.Value, t_dst, source)) + } + // Can we always convert from zero value without panicking? + const mayPanic = sliceToArray | sliceToArrayPtr + if c.Value == nil && classifications&mayPanic == 0 { + return emitConst(f, NewConst(nil, t_dst, source)) } // We're converting from constant to non-constant type, // e.g. string -> []byte/[]rune. } - // Conversion from slice to array pointer? - if tset_src.All(func(termSrc *types.Term) bool { - return tset_dst.All(func(termDst *types.Term) bool { - if slice, ok := termSrc.Type().Underlying().(*types.Slice); ok { - if ptr, ok := termDst.Type().Underlying().(*types.Pointer); ok { - if arr, ok := ptr.Elem().Underlying().(*types.Array); ok && types.Identical(slice.Elem(), arr.Elem()) { - return true - } - } - } - return false - }) - }) { - c := &SliceToArrayPointer{X: val} + switch classifications { + case changeType: // representation-preserving change + c := &ChangeType{X: val} c.setType(t_dst) return f.emit(c, source) - } - // Conversion from slice to array. This is almost the same as converting from slice to array pointer, then - // dereferencing the pointer. Except that a nil slice can be converted to [0]T, whereas converting a nil slice to - // (*[0]T) results in a nil pointer, dereferencing which would panic. To hide the extra branching we use a dedicated - // instruction, SliceToArray. - if tset_src.All(func(termSrc *types.Term) bool { - return tset_dst.All(func(termDst *types.Term) bool { - if slice, ok := termSrc.Type().Underlying().(*types.Slice); ok { - if arr, ok := termDst.Type().Underlying().(*types.Array); ok && types.Identical(slice.Elem(), arr.Elem()) { - return true - } - } - return false - }) - }) { - c := &SliceToArray{X: val} + case sliceToArrayPtr, sliceTo0ArrayPtr: // slice to array pointer + c := &SliceToArrayPointer{X: val} c.setType(t_dst) return f.emit(c, source) - } - // A representation-changing conversion? - // At least one of {ut_src,ut_dst} must be *Basic. - // (The other may be []byte or []rune.) - ok1 := tset_src.Any(func(term *types.Term) bool { _, ok := term.Type().Underlying().(*types.Basic); return ok }) - ok2 := tset_dst.Any(func(term *types.Term) bool { _, ok := term.Type().Underlying().(*types.Basic); return ok }) - if ok1 || ok2 { + case sliceToArray: // slice to arrays (not zero-length) + p := &SliceToArray{X: val} + p.setType(t_dst) + return f.emit(p, source) + + case sliceTo0Array: // slice to zero-length arrays (constant) + return emitConst(f, zeroConst(t_dst, source)) + + case convert: // representation-changing conversion c := &Convert{X: val} c.setType(t_dst) return f.emit(c, source) - } - panic(fmt.Sprintf("in %s: cannot convert %s (%s) to %s", f, val, val.Type(), t_dst)) + default: // multiple conversion + c := &MultiConvert{X: val, from: tset_src, to: tset_dst} + c.setType(t_dst) + return f.emit(c, source) + } } // emitStore emits to f an instruction to store value val at location @@ -486,12 +575,13 @@ func emitFieldSelection(f *Function, v Value, index int, wantAddr bool, id *ast. // zeroValue emits to f code to produce a zero value of type t, // and returns it. func zeroValue(f *Function, t types.Type, source ast.Node) Value { - return emitConst(f, zeroConst(t)) + return emitConst(f, zeroConst(t, source)) } type constKey struct { - typ types.Type - value constant.Value + typ types.Type + value constant.Value + source ast.Node } func emitConst(f *Function, c Constant) Constant { @@ -529,8 +619,9 @@ func emitConst(f *Function, c Constant) Constant { panic(fmt.Sprintf("unexpected type %T", c)) } k := constKey{ - typ: typ, - value: val, + typ: typ, + value: val, + source: c.Source(), } dup, ok := f.consts[k] if ok { diff --git a/tools/vendor/honnef.co/go/tools/go/ir/func.go b/tools/vendor/honnef.co/go/tools/go/ir/func.go index 4449b405d..923b04966 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/func.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/func.go @@ -176,77 +176,131 @@ type targets struct { // Destinations associated with a labelled block. // We populate these as labels are encountered in forward gotos or // labelled statements. +// Forward gotos are resolved once it is known which statement they +// are associated with inside the Function. type lblock struct { + label *types.Label // Label targeted by the blocks. + resolved bool // _goto block encountered (back jump or resolved fwd jump) _goto *BasicBlock _break *BasicBlock _continue *BasicBlock } -// labelledBlock returns the branch target associated with the -// specified label, creating it if needed. -func (f *Function) labelledBlock(label *ast.Ident) *lblock { - obj := f.Pkg.info.ObjectOf(label) - if obj == nil { - // Blank label, as in '_:' - don't store to f.lblocks, this label can never be referred to; just return a fresh - // lbock. - return &lblock{_goto: f.newBasicBlock(label.Name)} - } +// label returns the symbol denoted by a label identifier. +// +// label should be a non-blank identifier (label.Name != "_"). +func (f *Function) label(label *ast.Ident) *types.Label { + return f.Pkg.objectOf(label).(*types.Label) +} - lb := f.lblocks[obj] +// lblockOf returns the branch target associated with the +// specified label, creating it if needed. +func (f *Function) lblockOf(label *types.Label) *lblock { + lb := f.lblocks[label] if lb == nil { - lb = &lblock{_goto: f.newBasicBlock(label.Name)} + lb = &lblock{ + label: label, + _goto: f.newBasicBlock(label.Name()), + } if f.lblocks == nil { - f.lblocks = make(map[types.Object]*lblock) + f.lblocks = make(map[*types.Label]*lblock) } - f.lblocks[obj] = lb + f.lblocks[label] = lb } return lb } -// addParam adds a (non-escaping) parameter to f.Params of the -// specified name, type and source position. -func (f *Function) addParam(name string, typ types.Type, source ast.Node) *Parameter { - var b *BasicBlock - if len(f.Blocks) > 0 { - b = f.Blocks[0] +// labelledBlock searches f for the block of the specified label. +// +// If f is a yield function, it additionally searches ancestor Functions +// corresponding to enclosing range-over-func statements within the +// same source function, so the returned block may belong to a different Function. +func labelledBlock(f *Function, label *types.Label, tok token.Token) *BasicBlock { + if lb := f.lblocks[label]; lb != nil { + var block *BasicBlock + switch tok { + case token.BREAK: + block = lb._break + case token.CONTINUE: + block = lb._continue + case token.GOTO: + block = lb._goto + } + if block != nil { + return block + } } - v := &Parameter{ - name: name, + // Search ancestors if this is a yield function. + if f.jump != nil { + return labelledBlock(f.parent, label, tok) } - v.setBlock(b) - v.setType(typ) - v.setSource(source) - f.Params = append(f.Params, v) - if b != nil { - // There may be no blocks if this function has no body. We - // still create params, but aren't interested in the - // instruction. - f.Blocks[0].Instrs = append(f.Blocks[0].Instrs, v) + return nil +} + +// targetedBlock looks for the nearest block in f.targets +// (and f's ancestors) that matches tok's type, and returns +// the block and function it was found in. +func targetedBlock(f *Function, tok token.Token) *BasicBlock { + if f == nil { + return nil } - return v + for t := f.targets; t != nil; t = t.tail { + var block *BasicBlock + switch tok { + case token.BREAK: + block = t._break + case token.CONTINUE: + block = t._continue + case token.FALLTHROUGH: + block = t._fallthrough + } + if block != nil { + return block + } + } + // Search f's ancestors (in case f is a yield function). + return targetedBlock(f.parent, tok) +} + +// addResultVar adds a result for a variable v to f.results and v to f.returnVars. +func (f *Function) addResultVar(v *types.Var, source ast.Node) { + name := v.Name() + if name == "" { + name = fmt.Sprintf("res.%d", len(f.results)) + } + result := emitLocalVar(f, v, source) + result.comment = name + f.results = append(f.results, result) + f.returnVars = append(f.returnVars, v) } -func (f *Function) addParamObj(obj types.Object, source ast.Node) *Parameter { - name := obj.Name() +func (f *Function) addParamVar(v *types.Var, source ast.Node) *Parameter { + name := v.Name() if name == "" { name = fmt.Sprintf("arg%d", len(f.Params)) } - param := f.addParam(name, obj.Type(), source) - param.object = obj + var b *BasicBlock + if len(f.Blocks) > 0 { + b = f.Blocks[0] + } + param := &Parameter{name: name} + param.setBlock(b) + param.setType(v.Type()) + param.setSource(source) + param.object = v + f.Params = append(f.Params, param) + if b != nil { + f.Blocks[0].Instrs = append(f.Blocks[0].Instrs, param) + } return param } // addSpilledParam declares a parameter that is pre-spilled to the // stack; the function body will load/store the spilled location. // Subsequent lifting will eliminate spills where possible. -func (f *Function) addSpilledParam(obj types.Object, source ast.Node) { - param := f.addParamObj(obj, source) - spill := &Alloc{} - spill.setType(types.NewPointer(obj.Type())) - spill.source = source - f.objects[obj] = spill - f.Locals = append(f.Locals, spill) - f.emit(spill, source) +func (f *Function) addSpilledParam(obj *types.Var, source ast.Node) { + param := f.addParamVar(obj, source) + spill := emitLocalVar(f, obj, source) emitStore(f, spill, param, source) // f.emit(&Store{Addr: spill, Val: param}) } @@ -256,7 +310,7 @@ func (f *Function) addSpilledParam(obj types.Object, source ast.Node) { func (f *Function) startBody() { entry := f.newBasicBlock("entry") f.currentBlock = entry - f.objects = make(map[types.Object]Value) // needed for some synthetics, e.g. init + f.vars = make(map[*types.Var]Value) // needed for some synthetics, e.g. init } func (f *Function) blockset(i int) *BlockSet { @@ -280,12 +334,11 @@ func (f *Function) exitBlock() { f.Exit = f.newBasicBlock("exit") f.currentBlock = f.Exit - ret := f.results() - results := make([]Value, len(ret)) + results := make([]Value, len(f.results)) // Run function calls deferred in this // function when explicitly returning from it. f.emit(new(RunDefers), nil) - for i, r := range ret { + for i, r := range f.results { results[i] = emitLoad(f, r, nil) } @@ -306,11 +359,11 @@ func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.Func if recv != nil { for _, field := range recv.List { for _, n := range field.Names { - f.addSpilledParam(f.Pkg.info.Defs[n], n) + f.addSpilledParam(identVar(f, n), n) } // Anonymous receiver? No need to spill. if field.Names == nil { - f.addParamObj(f.Signature.Recv(), field) + f.addParamVar(f.Signature.Recv(), field) } } } @@ -320,35 +373,45 @@ func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.Func n := len(f.Params) // 1 if has recv, 0 otherwise for _, field := range functype.Params.List { for _, n := range field.Names { - f.addSpilledParam(f.Pkg.info.Defs[n], n) + f.addSpilledParam(identVar(f, n), n) } // Anonymous parameter? No need to spill. if field.Names == nil { - f.addParamObj(f.Signature.Params().At(len(f.Params)-n), field) + f.addParamVar(f.Signature.Params().At(len(f.Params)-n), field) } } } - // Named results. + // Results. if functype.Results != nil { for _, field := range functype.Results.List { // Implicit "var" decl of locals for named results. for _, n := range field.Names { - f.namedResults = append(f.namedResults, f.addLocalForIdent(n)) + v := identVar(f, n) + f.addResultVar(v, n) } - } - - if len(f.namedResults) == 0 { - sig := f.Signature.Results() - for i := 0; i < sig.Len(); i++ { - // XXX position information - v := f.addLocal(sig.At(i).Type(), nil) - f.implicitResults = append(f.implicitResults, v) + // Implicit "var" decl of local for an unnamed result. + if field.Names == nil { + v := f.Signature.Results().At(len(f.results)) + f.addResultVar(v, field.Type) } } } } +// createDeferStack initializes fn.deferstack to a local variable +// initialized to a ssa:deferstack() call. +func (fn *Function) createDeferStack() { + // Each syntactic function makes a call to ssa:deferstack, + // which is spilled to a local. Unused ones are later removed. + fn.deferstack = newVar("defer$stack", tDeferStack) + call := &Call{Call: CallCommon{Value: vDeferStack}} + call.setType(tDeferStack) + deferstack := fn.emit(call, nil) + spill := emitLocalVar(fn, fn.deferstack, nil) + emitStore(fn, spill, deferstack, nil) +} + func numberNodes(f *Function) { var base ID for _, b := range f.Blocks { @@ -508,7 +571,6 @@ buildLoop: // finishBody() finalizes the function after IR code generation of its body. func (f *Function) finishBody() { - f.objects = nil f.currentBlock = nil f.lblocks = nil @@ -549,8 +611,11 @@ func (f *Function) finishBody() { splitOnNewInformation(f.Blocks[0], &StackMap{}) } - f.namedResults = nil // (used by lifting) - f.implicitResults = nil + // clear remaining builder state + f.results = nil // (used by lifting) + f.deferstack = nil // (used by lifting) + f.vars = nil // (used by lifting) + f.goversion = "" numberNodes(f) @@ -627,37 +692,25 @@ func (f *Function) debugInfo() bool { return f.Pkg != nil && f.Pkg.debug } -// addNamedLocal creates a local variable, adds it to function f and -// returns it. Its name and type are taken from obj. Subsequent -// calls to f.lookup(obj) will return the same local. -func (f *Function) addNamedLocal(obj types.Object, source ast.Node) *Alloc { - l := f.addLocal(obj.Type(), source) - f.objects[obj] = l - return l -} - -func (f *Function) addLocalForIdent(id *ast.Ident) *Alloc { - return f.addNamedLocal(f.Pkg.info.Defs[id], id) -} - -// addLocal creates an anonymous local variable of type typ, adds it -// to function f and returns it. pos is the optional source location. -func (f *Function) addLocal(typ types.Type, source ast.Node) *Alloc { - v := &Alloc{} - v.setType(types.NewPointer(typ)) - f.Locals = append(f.Locals, v) - f.emit(v, source) - return v -} - // lookup returns the address of the named variable identified by obj // that is local to function f or one of its enclosing functions. // If escaping, the reference comes from a potentially escaping pointer // expression and the referent must be heap-allocated. -func (f *Function) lookup(obj types.Object, escaping bool) Value { - if v, ok := f.objects[obj]; ok { - if alloc, ok := v.(*Alloc); ok && escaping { - alloc.Heap = true +// We assume the referent is a *Alloc or *Phi. +// (The only Phis at this stage are those created directly by go1.22 "for" loops.) +func (f *Function) lookup(obj *types.Var, escaping bool) Value { + if v, ok := f.vars[obj]; ok { + if escaping { + switch v := v.(type) { + case *Alloc: + v.Heap = true + case *Phi: + for _, edge := range v.Edges { + if alloc, ok := edge.(*Alloc); ok { + alloc.Heap = true + } + } + } } return v // function-local var (address) } @@ -674,7 +727,7 @@ func (f *Function) lookup(obj types.Object, escaping bool) Value { outer: outer, parent: f, } - f.objects[obj] = v + f.vars[obj] = v f.FreeVars = append(f.FreeVars, v) return v } @@ -752,15 +805,15 @@ func (f *Function) relMethod(from *types.Package, recv types.Type) string { } // writeSignature writes to buf the signature sig in declaration syntax. -func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature, params []*Parameter) { +func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature) { buf.WriteString("func ") if recv := sig.Recv(); recv != nil { buf.WriteString("(") - if n := params[0].Name(); n != "" { - buf.WriteString(n) + if name := recv.Name(); name != "" { + buf.WriteString(name) buf.WriteString(" ") } - types.WriteType(buf, params[0].Type(), types.RelativeTo(from)) + types.WriteType(buf, recv.Type(), types.RelativeTo(from)) buf.WriteString(") ") } buf.WriteString(name) @@ -815,7 +868,7 @@ func WriteFunction(buf *bytes.Buffer, f *Function) { fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(deref(l.Type()), from)) } } - writeSignature(buf, from, f.Name(), f.Signature, f.Params) + writeSignature(buf, from, f.Name(), f.Signature) buf.WriteString(":\n") if f.Blocks == nil { @@ -955,3 +1008,83 @@ func killInstruction(instr Instruction) { } } } + +// identVar returns the variable defined by id. +func identVar(fn *Function, id *ast.Ident) *types.Var { + return fn.Pkg.info.Defs[id].(*types.Var) +} + +// unique returns a unique positive int within the source tree of f. +// The source tree of f includes all of f's ancestors by parent and all +// of the AnonFuncs contained within these. +func unique(f *Function) int64 { + f.uniq++ + return f.uniq +} + +// exit is a change of control flow going from a range-over-func +// yield function to an ancestor function caused by a break, continue, +// goto, or return statement. +// +// There are 3 types of exits: +// * return from the source function (from ReturnStmt), +// * jump to a block (from break and continue statements [labelled/unlabelled]), +// * go to a label (from goto statements). +// +// As the builder does one pass over the ast, it is unclear whether +// a forward goto statement will leave a range-over-func body. +// The function being exited to is unresolved until the end +// of building the range-over-func body. +type exit struct { + id int64 // unique value for exit within from and to + from *Function // the function the exit starts from + to *Function // the function being exited to (nil if unresolved) + source ast.Node + + block *BasicBlock // basic block within to being jumped to. + label *types.Label // forward label being jumped to via goto. + // block == nil && label == nil => return +} + +// storeVar emits to function f code to store a value v to a *types.Var x. +func storeVar(f *Function, x *types.Var, v Value, source ast.Node) { + emitStore(f, f.lookup(x, true), v, source) +} + +// labelExit creates a new exit to a yield fn to exit the function using a label. +func labelExit(fn *Function, label *types.Label, source ast.Node) *exit { + e := &exit{ + id: unique(fn), + from: fn, + to: nil, + source: source, + label: label, + } + fn.exits = append(fn.exits, e) + return e +} + +// blockExit creates a new exit to a yield fn that jumps to a basic block. +func blockExit(fn *Function, block *BasicBlock, source ast.Node) *exit { + e := &exit{ + id: unique(fn), + from: fn, + to: block.parent, + source: source, + block: block, + } + fn.exits = append(fn.exits, e) + return e +} + +// returnExit creates a new exit to a yield fn that returns to the source function. +func returnExit(fn *Function, source ast.Node) *exit { + e := &exit{ + id: unique(fn), + from: fn, + to: fn.sourceFn, + source: source, + } + fn.exits = append(fn.exits, e) + return e +} diff --git a/tools/vendor/honnef.co/go/tools/go/ir/html.go b/tools/vendor/honnef.co/go/tools/go/ir/html.go index 35b421a70..ae502db4e 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/html.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/html.go @@ -881,6 +881,9 @@ func valueLongHTML(v Node) string { for _, a := range v.Operands(nil) { s += fmt.Sprintf(" %s", valueHTML(*a)) } + if v, ok := v.(Instruction); ok { + s += fmt.Sprintf(" (%s)", v.Comment()) + } // OPT(dh): we're calling namedValues many times on the same function. allNames := namedValues(v.Parent()) diff --git a/tools/vendor/honnef.co/go/tools/go/ir/irutil/load.go b/tools/vendor/honnef.co/go/tools/go/ir/irutil/load.go index 883447b7a..bbf0e2719 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/irutil/load.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/irutil/load.go @@ -146,12 +146,14 @@ func BuildPackage(tc *types.Config, fset *token.FileSet, pkg *types.Package, fil } info := &types.Info{ - Types: make(map[ast.Expr]types.TypeAndValue), - Defs: make(map[*ast.Ident]types.Object), - Uses: make(map[*ast.Ident]types.Object), - Implicits: make(map[ast.Node]types.Object), - Scopes: make(map[ast.Node]*types.Scope), - Selections: make(map[*ast.SelectorExpr]*types.Selection), + Types: make(map[ast.Expr]types.TypeAndValue), + Defs: make(map[*ast.Ident]types.Object), + Uses: make(map[*ast.Ident]types.Object), + Implicits: make(map[ast.Node]types.Object), + Scopes: make(map[ast.Node]*types.Scope), + Selections: make(map[*ast.SelectorExpr]*types.Selection), + Instances: make(map[*ast.Ident]types.Instance), + FileVersions: make(map[*ast.File]string), } if err := types.NewChecker(tc, fset, pkg, info).Files(files); err != nil { return nil, nil, err diff --git a/tools/vendor/honnef.co/go/tools/go/ir/lift.go b/tools/vendor/honnef.co/go/tools/go/ir/lift.go index 8ac8330dc..08be0d371 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/lift.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/lift.go @@ -12,14 +12,14 @@ package ir // Cited papers and resources: // // Ron Cytron et al. 1991. Efficiently computing SSA form... -// http://doi.acm.org/10.1145/115372.115320 +// https://doi.acm.org/10.1145/115372.115320 // // Cooper, Harvey, Kennedy. 2001. A Simple, Fast Dominance Algorithm. // Software Practice and Experience 2001, 4:1-10. -// http://www.hipersoft.rice.edu/grads/publications/dom14.pdf +// https://www.hipersoft.rice.edu/grads/publications/dom14.pdf // // Daniel Berlin, llvmdev mailing list, 2012. -// http://lists.cs.uiuc.edu/pipermail/llvmdev/2012-January/046638.html +// https://lists.cs.uiuc.edu/pipermail/llvmdev/2012-January/046638.html // (Be sure to expand the whole thread.) // // C. Scott Ananian. 1997. The static single information form. @@ -46,6 +46,7 @@ import ( "encoding/binary" "fmt" "os" + "slices" ) // If true, show diagnostic information at each step of lifting. @@ -135,18 +136,11 @@ func buildPostDomFrontier(fn *Function) postDomFrontier { } func removeInstr(refs []Instruction, instr Instruction) []Instruction { - i := 0 - for _, ref := range refs { - if ref == instr { - continue - } - refs[i] = ref - i++ - } - for j := i; j != len(refs); j++ { - refs[j] = nil // aid GC - } - return refs[:i] + return removeInstrsIf(refs, func(i Instruction) bool { return i == instr }) +} + +func removeInstrsIf(refs []Instruction, p func(Instruction) bool) []Instruction { + return slices.DeleteFunc(refs, p) } func clearInstrs(instrs []Instruction) { @@ -208,9 +202,12 @@ func lift(fn *Function) bool { // for the block, reusing the original array if space permits. // While we're here, we also eliminate 'rundefers' - // instructions in functions that contain no 'defer' - // instructions. + // instructions and ssa:deferstack() in functions that contain no + // 'defer' instructions. Eliminate ssa:deferstack() if it does not + // escape. usesDefer := false + deferstackAlloc, deferstackCall := deferstackPreamble(fn) + eliminateDeferStack := deferstackAlloc != nil && !deferstackAlloc.Heap // Determine which allocs we can lift and number them densely. // The renaming phase uses this numbering for compact maps. @@ -262,6 +259,15 @@ func lift(fn *Function) bool { numAllocs++ case *Defer: usesDefer = true + if eliminateDeferStack { + // Clear _DeferStack and remove references to loads + if instr._DeferStack != nil { + if refs := instr._DeferStack.Referrers(); refs != nil { + *refs = removeInstr(*refs, instr) + } + instr._DeferStack = nil + } + } case *RunDefers: b.rundefers++ } @@ -316,6 +322,18 @@ func lift(fn *Function) bool { // Eliminate dead φ- and σ-nodes. markLiveNodes(fn.Blocks, newPhis, newSigmas) + + // Eliminate ssa:deferstack() call. + if eliminateDeferStack { + b := deferstackCall.block + for i, instr := range b.Instrs { + if instr == deferstackCall { + b.Instrs[i] = nil + b.gaps++ + break + } + } + } } // Prepend remaining live φ-nodes to each block and possibly kill rundefers. @@ -880,10 +898,10 @@ type liftInstructions struct { func liftable(alloc *Alloc, instructions BlockMap[liftInstructions]) bool { fn := alloc.block.parent - // Don't lift named return values in functions that defer + // Don't lift result values in functions that defer // calls that may recover from panic. if fn.hasDefer { - for _, nr := range fn.namedResults { + for _, nr := range fn.results { if nr == alloc { return false } @@ -970,7 +988,24 @@ func liftable(alloc *Alloc, instructions BlockMap[liftInstructions]) bool { for i := range blocks { // Update firstUnliftable to be one after lastLiftable. We do this to include the unliftable's preceding // DebugRefs in the renaming. - blocks[i].firstUnliftable = blocks[i].lastLiftable + 1 + if blocks[i].lastLiftable == -1 && !blocks[i].storeInPreds { + // There are no liftable instructions (for this alloc) in this block. Set firstUnliftable to the + // first non-head instruction to avoid inserting the store before phi instructions, which would + // fail validation. + first := -1 + instrLoop: + for i, instr := range fn.Blocks[i].Instrs { + switch instr.(type) { + case *Phi, *Sigma: + default: + first = i + break instrLoop + } + } + blocks[i].firstUnliftable = first + } else { + blocks[i].firstUnliftable = blocks[i].lastLiftable + 1 + } } // If a block is reachable by a (partially) unliftable block, then the entirety of the block is unliftable. In that @@ -1208,10 +1243,26 @@ func liftAlloc(closure *closure, df domFrontier, rdf postDomFrontier, alloc *All // Create φ-node. // It will be prepended to v.Instrs later, if needed. + if len(y.Preds) == 0 { + // The exit block may be unreachable if the function doesn't + // return, e.g. due to an infinite loop. In that case we + // should not replace loads in the exit block with ϕ node that + // have no edges. Such loads exist when the function has named + // return parameters, as the exit block loads them to turn + // them into a Return instruction. By not replacing the loads + // with ϕ nodes, they will later be replaced by zero + // constants. This is arguably more correct, and more + // importantly, it doesn't break code that assumes that phis + // have at least one edge. + // + // For one instance of breakage see + // https://staticcheck.dev/issues/1533 + continue + } phi := &Phi{ Edges: make([]Value, len(y.Preds)), } - + phi.comment = alloc.comment phi.source = alloc.source phi.setType(deref(alloc.Type())) phi.block = y @@ -1254,6 +1305,7 @@ func liftAlloc(closure *closure, df domFrontier, rdf postDomFrontier, alloc *All From: y, X: alloc, } + sigma.comment = alloc.comment sigma.source = alloc.source sigma.setType(deref(alloc.Type())) sigma.block = succ @@ -1342,7 +1394,7 @@ func replace(instr Instruction, x, y Value) { func renamed(fn *Function, renaming []Value, alloc *Alloc) Value { v := renaming[alloc.index] if v == nil { - v = emitConst(fn, zeroConst(deref(alloc.Type()))) + v = emitConst(fn, zeroConst(deref(alloc.Type()), alloc.source)) renaming[alloc.index] = v } return v @@ -1751,3 +1803,17 @@ func updateOperandReferrers(instr Instruction) { } } } + +// deferstackPreamble returns the *Alloc and ssa:deferstack() call for fn.deferstack. +func deferstackPreamble(fn *Function) (*Alloc, *Call) { + if alloc, _ := fn.vars[fn.deferstack].(*Alloc); alloc != nil { + for _, ref := range *alloc.Referrers() { + if ref, _ := ref.(*Store); ref != nil && ref.Addr == alloc { + if call, _ := ref.Val.(*Call); call != nil { + return alloc, call + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/go/ir/lvalue.go b/tools/vendor/honnef.co/go/tools/go/ir/lvalue.go index 119eed6c3..86eb4a5d1 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/lvalue.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/lvalue.go @@ -114,6 +114,40 @@ func (e *element) typ() types.Type { return e.t } +// A lazyAddress is an lvalue whose address is the result of an instruction. +// These work like an *address except a new address.address() Value +// is created on each load, store and address call. +// A lazyAddress can be used to control when a side effect (nil pointer +// dereference, index out of bounds) of using a location happens. +type lazyAddress struct { + addr func(fn *Function) Value // emit to fn the computation of the address + t types.Type // type of the location + expr ast.Expr // source syntax of the value (not address) [debug mode] +} + +func (l *lazyAddress) load(fn *Function, source ast.Node) Value { + load := emitLoad(fn, l.addr(fn), source) + return load +} + +func (l *lazyAddress) store(fn *Function, v Value, source ast.Node) { + store := emitStore(fn, l.addr(fn), v, source) + if l.expr != nil { + // store.Val is v, converted for assignability. + emitDebugRef(fn, l.expr, store.Val, false) + } +} + +func (l *lazyAddress) address(fn *Function) Value { + addr := l.addr(fn) + if l.expr != nil { + emitDebugRef(fn, l.expr, addr, true) + } + return addr +} + +func (l *lazyAddress) typ() types.Type { return l.t } + // A blank is a dummy variable whose name is "_". // It is not reified: loads are illegal and stores are ignored. type blank struct{} diff --git a/tools/vendor/honnef.co/go/tools/go/ir/methods.go b/tools/vendor/honnef.co/go/tools/go/ir/methods.go index b7903c847..f8607b03d 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/methods.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/methods.go @@ -27,7 +27,7 @@ func (prog *Program) MethodValue(sel *types.Selection) *Function { panic(fmt.Sprintf("MethodValue(%s) kind != MethodVal", sel)) } T := sel.Recv() - if isInterface(T) { + if types.IsInterface(T) { return nil // abstract method } if prog.mode&LogSource != 0 { @@ -165,7 +165,7 @@ func (prog *Program) needMethods(T types.Type, skip bool) { tmset := prog.MethodSets.MethodSet(T) - if !skip && !isInterface(T) && tmset.Len() > 0 { + if !skip && !types.IsInterface(T) && tmset.Len() > 0 { // Create methods of T. mset := prog.createMethodSet(T) if !mset.complete { @@ -235,6 +235,9 @@ func (prog *Program) needMethods(T types.Type, skip bool) { prog.needMethods(t.At(i).Type(), false) } + case *types.Alias: + prog.needMethods(types.Unalias(t), false) + default: lint.ExhaustiveTypeSwitch(T) } diff --git a/tools/vendor/honnef.co/go/tools/go/ir/print.go b/tools/vendor/honnef.co/go/tools/go/ir/print.go index ad23d16dc..b30753dff 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/print.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/print.go @@ -14,6 +14,7 @@ import ( "io" "reflect" "sort" + "strings" "honnef.co/go/tools/go/types/typeutil" ) @@ -42,6 +43,14 @@ func relType(t types.Type, from *types.Package) string { return types.TypeString(t, types.RelativeTo(from)) } +func relTerm(term *types.Term, from *types.Package) string { + s := relType(term.Type(), from) + if term.Tilde() { + return "~" + s + } + return s +} + func relString(m Member, from *types.Package) string { // NB: not all globals have an Object (e.g. init$guard), // so use Package().Object not Object.Package(). @@ -398,7 +407,12 @@ func (recv *Recv) String() string { } func (s *Defer) String() string { - return printCall(&s.Call, "Defer", s) + prefix := "Defer " + if s._DeferStack != nil { + prefix += "[" + relName(s._DeferStack, s) + "] " + } + c := printCall(&s.Call, prefix, s) + return c } func (s *Select) String() string { @@ -505,3 +519,21 @@ func WritePackage(buf *bytes.Buffer, p *Package) { fmt.Fprintf(buf, "\n") } + +func (v *MultiConvert) String() string { + from := v.Parent().Pkg.Pkg + + var b strings.Builder + b.WriteString(printConv("MultiConvert", v, v.X)) + b.WriteString(" [") + for i, s := range v.from.Terms { + for j, d := range v.to.Terms { + if i != 0 || j != 0 { + b.WriteString(" | ") + } + fmt.Fprintf(&b, "%s -> %s", relTerm(s, from), relTerm(d, from)) + } + } + b.WriteString("]") + return b.String() +} diff --git a/tools/vendor/honnef.co/go/tools/go/ir/sanity.go b/tools/vendor/honnef.co/go/tools/go/ir/sanity.go index b6c59c95f..4bbd711fa 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/sanity.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/sanity.go @@ -8,7 +8,9 @@ package ir // Currently it checks CFG invariants but little at the instruction level. import ( + "bytes" "fmt" + "go/ast" "go/types" "io" "os" @@ -118,7 +120,7 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { } else { for i, e := range instr.Edges { if e == nil { - s.errorf("phi node '%v' has no value for edge #%d from %s", instr, i, s.block.Preds[i]) + s.errorf("phi node '%s' has no value for edge #%d from %s", instr.Comment(), i, s.block.Preds[i]) } } } @@ -152,6 +154,7 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { s.errorf("convert %s -> %s: at least one type set must contain basic type", instr.X.Type(), instr.Type()) } + case *MultiConvert: case *Defer: case *Extract: case *Field: @@ -371,7 +374,7 @@ func (s *sanity) checkBlock(b *BasicBlock, index int) { // Check that "untyped" types only appear on constant operands. if _, ok := (*op).(*Const); !ok { - if basic, ok := (*op).Type().(*types.Basic); ok { + if basic, ok := types.Unalias((*op).Type()).(*types.Basic); ok { if basic.Info()&types.IsUntyped != 0 { s.errorf("operand #%d of %s is untyped: %s", i, instr, basic) } @@ -442,8 +445,10 @@ func (s *sanity) checkFunction(fn *Function) bool { s.errorf("nil Prog") } + var buf bytes.Buffer _ = fn.String() // must not crash _ = fn.RelString(fn.pkg()) // must not crash + WriteFunction(&buf, fn) // must not crash // All functions have a package, except delegates (which are // shared across packages, or duplicated as weak symbols in a @@ -457,8 +462,11 @@ func (s *sanity) checkFunction(fn *Function) bool { } } } - if src, syn := fn.Synthetic == 0, fn.source != nil; src != syn { - s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn) + if syn, src := fn.Synthetic == 0, fn.source != nil; src != syn { + if _, ok := fn.source.(*ast.RangeStmt); !ok || fn.Synthetic != SyntheticRangeOverFuncYield { + // Only range-over-func yield functions are synthetic and have syntax + s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn) + } } for i, l := range fn.Locals { if l.Parent() != fn { diff --git a/tools/vendor/honnef.co/go/tools/go/ir/source.go b/tools/vendor/honnef.co/go/tools/go/ir/source.go index 155c5f733..5e3ac28b8 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/source.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/source.go @@ -181,13 +181,13 @@ func (prog *Program) ConstValue(obj *types.Const) *Const { // Universal constant? {true,false,nil} if obj.Parent() == types.Universe { - return NewConst(obj.Val(), obj.Type()) + return NewConst(obj.Val(), obj.Type(), nil) } // Package-level named constant? if v := prog.packageLevelValue(obj); v != nil { return v.(*Const) } - return NewConst(obj.Val(), obj.Type()) + return NewConst(obj.Val(), obj.Type(), nil) } // VarValue returns the IR Value that corresponds to a specific diff --git a/tools/vendor/honnef.co/go/tools/go/ir/ssa.go b/tools/vendor/honnef.co/go/tools/go/ir/ssa.go index 1ef87f9e8..6061b6085 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/ssa.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/ssa.go @@ -36,12 +36,10 @@ type Program struct { mode BuilderMode // set of mode bits for IR construction MethodSets typeutil.MethodSetCache // cache of type-checker's method-sets - methodsMu sync.Mutex // guards the following maps: - methodSets typeutil.Map[*methodSet] // maps type to its concrete methodSet - runtimeTypes typeutil.Map[bool] // types for which rtypes are needed - canon typeutil.Map[types.Type] // type canonicalization map - bounds map[*types.Func]*Function // bounds for curried x.Method closures - thunks map[selectionKey]*Function // thunks for T.Method expressions + methodsMu sync.Mutex // guards the following maps: + methodSets typeutil.Map[*methodSet] // maps type to its concrete methodSet + runtimeTypes typeutil.Map[bool] // types for which rtypes are needed + canon typeutil.Map[types.Type] // type canonicalization map } // A Package is a single analyzed Go package containing Members for @@ -64,10 +62,11 @@ type Package struct { // The following fields are set transiently, then cleared // after building. - buildOnce sync.Once // ensures package building occurs once - ninit int32 // number of init functions - info *types.Info // package type information - files []*ast.File // package ASTs + buildOnce sync.Once // ensures package building occurs once + ninit int32 // number of init functions + info *types.Info // package type information + files []*ast.File // package ASTs + initVersion map[ast.Expr]string // goversion to use for each global var init expr } // A Member is a member of a Go package, implemented by *NamedConst, @@ -292,6 +291,7 @@ const ( SyntheticWrapper SyntheticBound SyntheticGeneric + SyntheticRangeOverFuncYield ) func (syn Synthetic) String() string { @@ -308,6 +308,8 @@ func (syn Synthetic) String() string { return "bound" case SyntheticGeneric: return "generic" + case SyntheticRangeOverFuncYield: + return "range-over-func yield" default: return fmt.Sprintf("Synthetic(%d)", syn) } @@ -317,8 +319,8 @@ func (syn Synthetic) String() string { // or method. // // If Blocks is nil, this indicates an external function for which no -// Go source code is available. In this case, FreeVars and Locals -// are nil too. Clients performing whole-program analysis must +// Go source code is available. In this case, FreeVars, Locals, and +// Params are nil too. Clients performing whole-program analysis must // handle external functions specially. // // Blocks contains the function's control-flow graph (CFG). @@ -346,29 +348,51 @@ func (syn Synthetic) String() string { // the same position as the function they wrap. // Syntax.Pos() always returns the position of the declaring "func" token. // +// When the operand of a range statement is an iterator function, +// the loop body is transformed into a synthetic anonymous function +// that is passed as the yield argument in a call to the iterator. +// In that case, Function.Source() is the ast.RangeStmt. +// +// Synthetic functions, for which Synthetic != "", are functions +// that do not appear in the source AST. These include: +// - method wrappers, +// - thunks, +// - bound functions, +// - empty functions built from loaded type information, +// - yield functions created from range-over-func loops, and +// - package init functions. +// // Type() returns the function's Signature. type Function struct { node name string - object types.Object // a declared *types.Func or one of its wrappers + object *types.Func // symbol for declared function (nil for FuncLit or synthetic init) method *types.Selection // info about provenance of synthetic methods Signature *types.Signature generics instanceWrapperMap - Synthetic Synthetic - parent *Function // enclosing function if anon; nil if global - Pkg *Package // enclosing package; nil for shared funcs (wrappers and error.Error) - Prog *Program // enclosing program + Synthetic Synthetic // provenance of synthetic function; 0 for true source functions + parent *Function // enclosing function if anon; nil if global + Pkg *Package // enclosing package; nil for shared funcs (wrappers and error.Error) + Prog *Program // enclosing program + + // These fields are populated only when the function body is built: + Params []*Parameter // function parameters; for methods, includes receiver FreeVars []*FreeVar // free variables whose values must be supplied by closure - Locals []*Alloc // local variables of this function + Locals []*Alloc // frame-allocated variables of this function Blocks []*BasicBlock // basic blocks of the function; nil => external Exit *BasicBlock // The function's exit block - AnonFuncs []*Function // anonymous functions directly beneath this one + AnonFuncs []*Function // anonymous functions (from FuncLit, RangeStmt) directly beneath this one referrers []Instruction // referring instructions (iff Parent() != nil) NoReturn NoReturn // Calling this function will always terminate control flow. + goversion string // Go version of syntax (NB: init is special) + + // uniq is not stored in functionBody because we need it after function building finishes + uniq int64 // source of unique ints within the source tree while building + *functionBody } @@ -466,12 +490,16 @@ type constValue struct { type functionBody struct { // The following fields are set transiently during building, // then cleared. - currentBlock *BasicBlock // where to emit code - objects map[types.Object]Value // addresses of local variables - namedResults []*Alloc // tuple of named results - implicitResults []*Alloc // tuple of results - targets *targets // linked stack of branch targets - lblocks map[types.Object]*lblock // labelled blocks + currentBlock *BasicBlock // where to emit code + vars map[*types.Var]Value // addresses of local variables + results []*Alloc // result allocations of the current function + returnVars []*types.Var // variables for a return statement. Either results or for range-over-func a parent's results + targets *targets // linked stack of branch targets + lblocks map[*types.Label]*lblock // labelled blocks + jump *types.Var // synthetic variable for the yield state (non-nil => range-over-func) + deferstack *types.Var // synthetic variable holding enclosing ssa:deferstack() + sourceFn *Function // nearest enclosing source function + exits []*exit // exits of the function that need to be resolved consts map[constKey]constValue aggregateConsts typeutil.Map[[]*AggregateConst] @@ -486,13 +514,6 @@ type functionBody struct { scratchInstructions []Instruction } -func (fn *Function) results() []*Alloc { - if len(fn.namedResults) > 0 { - return fn.namedResults - } - return fn.implicitResults -} - // BasicBlock represents an IR basic block. // // The final element of Instrs is always an explicit transfer of @@ -560,7 +581,7 @@ type Parameter struct { register name string - object types.Object // a *types.Var; nil for non-source locals + object *types.Var // non-nil } // A Const represents the value of a constant expression. @@ -683,15 +704,12 @@ type Builtin struct { // type of the allocated variable is actually // Type().Underlying().(*types.Pointer).Elem(). // -// If Heap is false, Alloc allocates space in the function's -// activation record (frame); we refer to an Alloc(Heap=false) as a -// "stack" alloc. Each stack Alloc returns the same address each time -// it is executed within the same activation; the space is -// re-initialized to zero. +// If Heap is false, Alloc zero-initializes the same local variable in +// the call frame and returns its address; in this case the Alloc must +// be present in Function.Locals. We call this a "local" alloc. // -// If Heap is true, Alloc allocates space in the heap; we -// refer to an Alloc(Heap=true) as a "heap" alloc. Each heap Alloc -// returns a different address each time it is executed. +// If Heap is true, Alloc allocates a new zero-initialized variable +// each time the instruction is executed. We call this a "new" alloc. // // When Alloc is applied to a channel, map or slice type, it returns // the address of an uninitialized (nil) reference of that kind; store @@ -892,6 +910,26 @@ type Convert struct { X Value } +// The MultiConvert instruction yields the conversion of value X to type +// Type(). Either X.Type() or Type() must be a type parameter. Each +// type in the type set of X.Type() can be converted to each type in the +// type set of Type(). +// +// See the documentation for Convert, ChangeType, SliceToArray, and SliceToArrayPointer +// for the conversions that are permitted. +// +// This operation can fail dynamically (see SliceToArrayPointer). +// +// Example printed form: +// +// t1 = multiconvert D <- S (t0) [*[2]rune <- []rune | string <- []rune] +type MultiConvert struct { + register + X Value + from typeutil.TypeSet + to typeutil.TypeSet +} + // ChangeInterface constructs a value of one interface type from a // value of another interface type known to be assignable to it. // This operation cannot fail. @@ -1463,6 +1501,12 @@ type Go struct { // The Defer instruction pushes the specified call onto a stack of // functions to be called by a RunDefers instruction or by a panic. // +// If _DeferStack != nil, it indicates the defer list that the defer is +// added to. Defer list values come from the Builtin function +// ssa:deferstack. Calls to ssa:deferstack() produces the defer stack +// of the current function frame. _DeferStack allows for deferring into an +// alternative function stack than the current function. +// // See CallCommon for generic function call documentation. // // Pos() returns the ast.DeferStmt.Defer. @@ -1474,7 +1518,10 @@ type Go struct { // DeferInvoke t4.Bar t2 type Defer struct { anInstruction - Call CallCommon + Call CallCommon + _DeferStack Value // stack (from ssa:deferstack() intrinsic) onto which this function is pushed + + // TODO: Exporting _DeferStack and possibly making _DeferStack != nil awaits proposal https://github.com/golang/go/issues/66601. } // The Send instruction sends X on channel Chan. @@ -1790,13 +1837,18 @@ func (v *Global) String() string { return v.RelString(nil) func (v *Global) Package() *Package { return v.Pkg } func (v *Global) RelString(from *types.Package) string { return relString(v, from) } -func (v *Function) Name() string { return v.name } -func (v *Function) Type() types.Type { return v.Signature } -func (v *Function) Token() token.Token { return token.FUNC } -func (v *Function) Object() types.Object { return v.object } -func (v *Function) String() string { return v.RelString(nil) } -func (v *Function) Package() *Package { return v.Pkg } -func (v *Function) Parent() *Function { return v.parent } +func (v *Function) Name() string { return v.name } +func (v *Function) Type() types.Type { return v.Signature } +func (v *Function) Token() token.Token { return token.FUNC } +func (v *Function) Object() types.Object { + if v.object != nil { + return types.Object(v.object) + } + return nil +} +func (v *Function) String() string { return v.RelString(nil) } +func (v *Function) Package() *Package { return v.Pkg } +func (v *Function) Parent() *Function { return v.parent } func (v *Function) Referrers() *[]Instruction { if v.parent != nil { return &v.referrers @@ -1894,7 +1946,7 @@ func (s *Call) Operands(rands []*Value) []*Value { } func (s *Defer) Operands(rands []*Value) []*Value { - return s.Call.Operands(rands) + return append(s.Call.Operands(rands), &s._DeferStack) } func (v *ChangeInterface) Operands(rands []*Value) []*Value { @@ -1909,6 +1961,10 @@ func (v *Convert) Operands(rands []*Value) []*Value { return append(rands, &v.X) } +func (v *MultiConvert) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + func (v *SliceToArrayPointer) Operands(rands []*Value) []*Value { return append(rands, &v.X) } diff --git a/tools/vendor/honnef.co/go/tools/go/ir/util.go b/tools/vendor/honnef.co/go/tools/go/ir/util.go index 0a733b654..3a0e3ad92 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/util.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/util.go @@ -16,6 +16,8 @@ import ( "honnef.co/go/tools/go/ast/astutil" "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/exp/typeparams" ) //// AST utilities @@ -42,14 +44,15 @@ func isPointer(typ types.Type) bool { return ok } -func isInterface(T types.Type) bool { return types.IsInterface(T) } - // deref returns a pointer's element type; otherwise it returns typ. func deref(typ types.Type) types.Type { orig := typ + typ = types.Unalias(typ) if t, ok := typ.(*types.TypeParam); ok { if ctyp := typeutil.CoreType(t); ctyp != nil { + // This can happen, for example, with len(T) where T is a + // type parameter whose core type is a pointer to array. typ = ctyp } } @@ -146,3 +149,14 @@ func assert(x bool) { // BlockMap is a mapping from basic blocks (identified by their indices) to values. type BlockMap[T any] []T + +// isBasic reports whether t is a basic type. +func isBasic(t types.Type) bool { + _, ok := t.(*types.Basic) + return ok +} + +// isNonTypeParamInterface reports whether t is an interface type but not a type parameter. +func isNonTypeParamInterface(t types.Type) bool { + return !typeparams.IsTypeParam(t) && types.IsInterface(t) +} diff --git a/tools/vendor/honnef.co/go/tools/go/ir/wrappers.go b/tools/vendor/honnef.co/go/tools/go/ir/wrappers.go index 69537fb77..d5afb2cda 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/wrappers.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/wrappers.go @@ -93,8 +93,8 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { } c.Call.Args = []Value{ v, - emitConst(fn, stringConst(deref(sel.Recv()).String())), - emitConst(fn, stringConst(sel.Obj().Name())), + emitConst(fn, stringConst(deref(sel.Recv()).String(), nil)), + emitConst(fn, stringConst(sel.Obj().Name(), nil)), } c.setType(v.Type()) v = fn.emit(&c, nil) @@ -116,7 +116,7 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { // address of implicit C field. var c Call - if r := recvType(obj); !isInterface(r) { // concrete method + if r := recvType(obj); !types.IsInterface(r) { // concrete method if !isPointer(r) { v = emitLoad(fn, v, nil) } @@ -140,7 +140,7 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { func createParams(fn *Function, start int) { tparams := fn.Signature.Params() for i, n := start, tparams.Len(); i < n; i++ { - fn.addParamObj(tparams.At(i), nil) + fn.addParamVar(tparams.At(i), nil) } } @@ -173,42 +173,37 @@ func createParams(fn *Function, start int) { func makeBound(prog *Program, obj *types.Func) *Function { prog.methodsMu.Lock() defer prog.methodsMu.Unlock() - fn, ok := prog.bounds[obj] - if !ok { - if prog.mode&LogSource != 0 { - defer logStack("%s", SyntheticBound)() - } - fn = &Function{ - name: obj.Name() + "$bound", - object: obj, - Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver - Synthetic: SyntheticBound, - Prog: prog, - functionBody: new(functionBody), - } - fn.initHTML(prog.PrintFunc) - - fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn} - fn.FreeVars = []*FreeVar{fv} - fn.startBody() - createParams(fn, 0) - var c Call + if prog.mode&LogSource != 0 { + defer logStack("%s", SyntheticBound)() + } + fn := &Function{ + name: obj.Name() + "$bound", + object: obj, + Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver + Synthetic: SyntheticBound, + Prog: prog, + functionBody: new(functionBody), + } + fn.initHTML(prog.PrintFunc) - if !isInterface(recvType(obj)) { // concrete - c.Call.Value = prog.declaredFunc(obj) - c.Call.Args = []Value{fv} - } else { - c.Call.Value = fv - c.Call.Method = obj - } - for _, arg := range fn.Params { - c.Call.Args = append(c.Call.Args, arg) - } - emitTailCall(fn, &c, nil) - fn.finishBody() + fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn} + fn.FreeVars = []*FreeVar{fv} + fn.startBody() + createParams(fn, 0) + var c Call - prog.bounds[obj] = fn + if !types.IsInterface(recvType(obj)) { // concrete + c.Call.Value = prog.declaredFunc(obj) + c.Call.Args = []Value{fv} + } else { + c.Call.Value = fv + c.Call.Method = obj + } + for _, arg := range fn.Params { + c.Call.Args = append(c.Call.Args, arg) } + emitTailCall(fn, &c, nil) + fn.finishBody() return fn } @@ -231,42 +226,18 @@ func makeBound(prog *Program, obj *types.Func) *Function { // // f := func(t T) { return t.meth() } // -// TODO(adonovan): opt: currently the stub is created even when used -// directly in a function call: C.f(i, 0). This is less efficient -// than inlining the stub. -// // EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu) func makeThunk(prog *Program, sel *types.Selection) *Function { if sel.Kind() != types.MethodExpr { panic(sel) } - key := selectionKey{ - kind: sel.Kind(), - recv: sel.Recv(), - obj: sel.Obj(), - index: fmt.Sprint(sel.Index()), - indirect: sel.Indirect(), - } - prog.methodsMu.Lock() defer prog.methodsMu.Unlock() - // Canonicalize key.recv to avoid constructing duplicate thunks. - canonRecv, ok := prog.canon.At(key.recv) - if !ok { - canonRecv = key.recv - prog.canon.Set(key.recv, canonRecv) - } - key.recv = canonRecv - - fn, ok := prog.thunks[key] - if !ok { - fn = makeWrapper(prog, sel) - if fn.Signature.Recv() != nil { - panic(fn) // unexpected receiver - } - prog.thunks[key] = fn + fn := makeWrapper(prog, sel) + if fn.Signature.Recv() != nil { + panic(fn) // unexpected receiver } return fn } @@ -275,15 +246,6 @@ func changeRecv(s *types.Signature, recv *types.Var) *types.Signature { return types.NewSignatureType(recv, nil, nil, s.Params(), s.Results(), s.Variadic()) } -// selectionKey is like types.Selection but a usable map key. -type selectionKey struct { - kind types.SelectionKind - recv types.Type // canonicalized via Program.canon - obj types.Object - index string - indirect bool -} - // makeInstance creates a wrapper function with signature sig that calls the generic function fn. // If targs is not nil, fn is a function and targs describes the concrete type arguments. // If targs is nil, fn is a method and the type arguments are derived from the receiver. @@ -291,7 +253,7 @@ func makeInstance(prog *Program, fn *Function, sig *types.Signature, targs *type if sig.Recv() != nil { assert(targs == nil) // Methods don't have their own type parameters, but the receiver does - targs = deref(sig.Recv().Type()).(*types.Named).TypeArgs() + targs = types.Unalias(deref(sig.Recv().Type())).(*types.Named).TypeArgs() } else { assert(targs != nil) } @@ -318,7 +280,7 @@ func makeInstance(prog *Program, fn *Function, sig *types.Signature, targs *type w.initHTML(prog.PrintFunc) w.startBody() if sig.Recv() != nil { - w.addParamObj(sig.Recv(), nil) + w.addParamVar(sig.Recv(), nil) } createParams(w, 0) var c Call diff --git a/tools/vendor/honnef.co/go/tools/go/types/typeutil/ext.go b/tools/vendor/honnef.co/go/tools/go/types/typeutil/ext.go index bc553ec01..19b4ae5a7 100644 --- a/tools/vendor/honnef.co/go/tools/go/types/typeutil/ext.go +++ b/tools/vendor/honnef.co/go/tools/go/types/typeutil/ext.go @@ -16,3 +16,12 @@ func (t *Iterator) Elem() types.Type { return t.elem } func NewIterator(elem types.Type) *Iterator { return &Iterator{elem: elem} } + +type DeferStack struct{} + +func (t *DeferStack) Underlying() types.Type { return t } +func (t *DeferStack) String() string { return "deferStack" } + +func NewDeferStack() *DeferStack { + return &DeferStack{} +} diff --git a/tools/vendor/honnef.co/go/tools/go/types/typeutil/util.go b/tools/vendor/honnef.co/go/tools/go/types/typeutil/util.go index 3a2ad973b..ef11564c7 100644 --- a/tools/vendor/honnef.co/go/tools/go/types/typeutil/util.go +++ b/tools/vendor/honnef.co/go/tools/go/types/typeutil/util.go @@ -3,7 +3,10 @@ package typeutil import ( "bytes" "go/types" + "strings" "sync" + + "golang.org/x/exp/typeparams" ) var bufferPool = &sync.Pool{ @@ -15,6 +18,11 @@ var bufferPool = &sync.Pool{ } func FuncName(f *types.Func) string { + // We don't care about aliases in this function because we use FuncName to check calls + // to known methods, and method receivers are determined by the method declaration, + // not the call. Thus, even if a user does 'type Alias = *sync.Mutex' and calls + // Alias.Lock, we'll still see it as (*sync.Mutex).Lock. + buf := bufferPool.Get().(*bytes.Buffer) buf.Reset() if f.Type() != nil { @@ -80,12 +88,82 @@ func IsObject(obj types.Object, name string) bool { return path+obj.Name() == name } -// OPT(dh): IsType is kind of expensive; should we really use it? -func IsType(T types.Type, name string) bool { return types.TypeString(T, nil) == name } +// IsTypeName reports whether obj represents the qualified name. If obj is a type alias, +// IsTypeName checks both the alias and the aliased type, if the aliased type has a type +// name. +func IsTypeName(obj *types.TypeName, name string) bool { + var qf string + if idx := strings.LastIndex(name, "."); idx != -1 { + qf = name[:idx] + name = name[idx+1:] + } + if obj.Name() == name && + ((qf == "" && obj.Pkg() == nil) || (obj.Pkg() != nil && obj.Pkg().Path() == qf)) { + return true + } + + if !obj.IsAlias() { + return false + } + + // FIXME(dh): we should peel away one layer of alias at a time; this is blocked on + // github.com/golang/go/issues/66559 + if typ, ok := types.Unalias(obj.Type()).(interface{ Obj() *types.TypeName }); ok { + return IsTypeName(typ.Obj(), name) + } + + return false +} + +func IsPointerToTypeWithName(typ types.Type, name string) bool { + ptr, ok := types.Unalias(typ).(*types.Pointer) + if !ok { + return false + } + return IsTypeWithName(ptr.Elem(), name) +} + +// IsTypeWithName reports whether typ represents a type with the qualified name, If typ is +// a type alias, IsTypeWithName checks both the alias and the aliased type. The following +// types can have names: Basic, Named, Alias. +func IsTypeWithName(typ types.Type, name string) bool { + switch typ := typ.(type) { + case *types.Basic: + return typ.Name() == name + case *types.Named: + return IsTypeName(typ.Obj(), name) + case *types.Alias: + // FIXME(dh): we should peel away one layer of alias at a time; this is blocked on + // github.com/golang/go/issues/66559 + + // IsTypeName already handles aliases to other aliases or named types; our + // fallback is required for aliases to basic types. + return IsTypeName(typ.Obj(), name) || IsTypeWithName(types.Unalias(typ), name) + default: + return false + } +} +// IsPointerLike returns true if type T is like a pointer. This returns true for all nillable types, +// unsafe.Pointer, and type sets where at least one term is pointer-like. func IsPointerLike(T types.Type) bool { switch T := T.Underlying().(type) { - case *types.Interface, *types.Chan, *types.Map, *types.Signature, *types.Pointer, *types.Slice: + case *types.Interface: + if T.IsMethodSet() { + return true + } else { + terms, err := typeparams.NormalTerms(T) + if err != nil { + return false + } + for _, term := range terms { + if IsPointerLike(term.Type()) { + return true + } + } + return false + } + case *types.Chan, *types.Map, *types.Signature, *types.Pointer, *types.Slice: return true case *types.Basic: return T.Kind() == types.UnsafePointer diff --git a/tools/vendor/honnef.co/go/tools/internal/passes/buildir/buildir.go b/tools/vendor/honnef.co/go/tools/internal/passes/buildir/buildir.go index 51dfaef53..dc26a6721 100644 --- a/tools/vendor/honnef.co/go/tools/internal/passes/buildir/buildir.go +++ b/tools/vendor/honnef.co/go/tools/internal/passes/buildir/buildir.go @@ -35,7 +35,7 @@ var Analyzer = &analysis.Analyzer{ } // IR provides intermediate representation for all the -// non-blank source functions in the current package. +// source functions in the current package. type IR struct { Pkg *ir.Package SrcFuncs []*ir.Function diff --git a/tools/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go b/tools/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go index 6e4cdff26..b78899ab5 100644 --- a/tools/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go +++ b/tools/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go @@ -44,7 +44,7 @@ func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { if !ok { return true } - TdstElem, ok := Tdst.Elem().(*types.Basic) + TdstElem, ok := types.Unalias(Tdst.Elem()).(*types.Basic) if !ok || TdstElem.Kind() != types.Int32 { return true } @@ -154,7 +154,7 @@ func RedundantTypeInDeclarationChecker(verb string, flagHelpfulTypes bool) *anal if err != nil { panic(err) } - if b, ok := tv.Type.(*types.Basic); ok && (b.Info()&types.IsUntyped) != 0 { + if b, ok := types.Unalias(tv.Type).(*types.Basic); ok && (b.Info()&types.IsUntyped) != 0 { if Tlhs != types.Default(b) { // The rhs is untyped and its default type differs from the explicit type on the lhs continue specLoop diff --git a/tools/vendor/honnef.co/go/tools/knowledge/arg.go b/tools/vendor/honnef.co/go/tools/knowledge/arg.go index 1fe61c1d5..4fab2eba1 100644 --- a/tools/vendor/honnef.co/go/tools/knowledge/arg.go +++ b/tools/vendor/honnef.co/go/tools/knowledge/arg.go @@ -1,58 +1,66 @@ package knowledge var Args = map[string]int{ - "(*encoding/json.Decoder).Decode.v": 0, - "(*encoding/json.Encoder).Encode.v": 0, - "(*encoding/xml.Decoder).Decode.v": 0, - "(*encoding/xml.Encoder).Encode.v": 0, - "(*sync.Pool).Put.x": 0, - "(*text/template.Template).Parse.text": 0, - "(io.Seeker).Seek.offset": 0, - "(time.Time).Sub.u": 0, - "append.elems": 1, - "append.slice": 0, - "bytes.Equal.a": 0, - "bytes.Equal.b": 1, - "encoding/binary.Write.data": 2, - "errors.New.text": 0, - "fmt.Fprintf.format": 1, - "fmt.Printf.format": 0, - "fmt.Sprintf.a[0]": 1, - "fmt.Sprintf.format": 0, - "json.Marshal.v": 0, - "json.Unmarshal.v": 1, - "len.v": 0, - "make.size[0]": 1, - "make.size[1]": 2, - "make.t": 0, - "net/url.Parse.rawurl": 0, - "os.OpenFile.flag": 1, - "os/exec.Command.name": 0, - "os/signal.Notify.c": 0, - "regexp.Compile.expr": 0, - "runtime.SetFinalizer.finalizer": 1, - "runtime.SetFinalizer.obj": 0, - "sort.Sort.data": 0, - "strconv.AppendFloat.bitSize": 4, - "strconv.AppendFloat.fmt": 2, - "strconv.AppendInt.base": 2, - "strconv.AppendUint.base": 2, - "strconv.FormatComplex.bitSize": 3, - "strconv.FormatComplex.fmt": 1, - "strconv.FormatFloat.bitSize": 3, - "strconv.FormatFloat.fmt": 1, - "strconv.FormatInt.base": 1, - "strconv.FormatUint.base": 1, - "strconv.ParseComplex.bitSize": 1, - "strconv.ParseFloat.bitSize": 1, - "strconv.ParseInt.base": 1, - "strconv.ParseInt.bitSize": 2, - "strconv.ParseUint.base": 1, - "strconv.ParseUint.bitSize": 2, - "time.Parse.layout": 0, - "time.Sleep.d": 0, - "xml.Marshal.v": 0, - "xml.Unmarshal.v": 1, + "(*sync.Pool).Put.x": 0, + "(*text/template.Template).Parse.text": 0, + "(io.Seeker).Seek.offset": 0, + "(time.Time).Sub.u": 0, + "append.elems": 1, + "append.slice": 0, + "bytes.Equal.a": 0, + "bytes.Equal.b": 1, + "encoding/ascii85.Encode.dst": 0, + "encoding/ascii85.Encode.src": 1, + "(*encoding/base32.Encoding).Encode.dst": 0, + "(*encoding/base32.Encoding).Encode.src": 1, + "(*encoding/base64.Encoding).Encode.dst": 0, + "(*encoding/base64.Encoding).Encode.src": 1, + "encoding/binary.Write.data": 2, + "encoding/hex.Encode.dst": 0, + "encoding/hex.Encode.src": 1, + "(*encoding/json.Decoder).Decode.v": 0, + "(*encoding/json.Encoder).Encode.v": 0, + "(*encoding/xml.Decoder).Decode.v": 0, + "(*encoding/xml.Encoder).Encode.v": 0, + "errors.New.text": 0, + "fmt.Fprintf.format": 1, + "fmt.Printf.format": 0, + "fmt.Sprintf.a[0]": 1, + "fmt.Sprintf.format": 0, + "json.Marshal.v": 0, + "json.Unmarshal.v": 1, + "len.v": 0, + "make.size[0]": 1, + "make.size[1]": 2, + "make.t": 0, + "net/url.Parse.rawurl": 0, + "os.OpenFile.flag": 1, + "os/exec.Command.name": 0, + "os/signal.Notify.c": 0, + "regexp.Compile.expr": 0, + "runtime.SetFinalizer.finalizer": 1, + "runtime.SetFinalizer.obj": 0, + "sort.Sort.data": 0, + "strconv.AppendFloat.bitSize": 4, + "strconv.AppendFloat.fmt": 2, + "strconv.AppendInt.base": 2, + "strconv.AppendUint.base": 2, + "strconv.FormatComplex.bitSize": 3, + "strconv.FormatComplex.fmt": 1, + "strconv.FormatFloat.bitSize": 3, + "strconv.FormatFloat.fmt": 1, + "strconv.FormatInt.base": 1, + "strconv.FormatUint.base": 1, + "strconv.ParseComplex.bitSize": 1, + "strconv.ParseFloat.bitSize": 1, + "strconv.ParseInt.base": 1, + "strconv.ParseInt.bitSize": 2, + "strconv.ParseUint.base": 1, + "strconv.ParseUint.bitSize": 2, + "time.Parse.layout": 0, + "time.Sleep.d": 0, + "xml.Marshal.v": 0, + "xml.Unmarshal.v": 1, } // Arg turns the name of an argument into an argument index. diff --git a/tools/vendor/honnef.co/go/tools/knowledge/deprecated.go b/tools/vendor/honnef.co/go/tools/knowledge/deprecated.go index caeb49975..854e5bd1f 100644 --- a/tools/vendor/honnef.co/go/tools/knowledge/deprecated.go +++ b/tools/vendor/honnef.co/go/tools/knowledge/deprecated.go @@ -2,18 +2,18 @@ package knowledge const ( // DeprecatedNeverUse indicates that an API should never be used, regardless of Go version. - DeprecatedNeverUse = -1 + DeprecatedNeverUse = "never" // DeprecatedUseNoLonger indicates that an API has no use anymore. - DeprecatedUseNoLonger = -2 + DeprecatedUseNoLonger = "no longer" ) // Deprecation describes when a Go API has been deprecated. type Deprecation struct { // The minor Go version since which this API has been deprecated. - DeprecatedSince int + DeprecatedSince string // The minor Go version since which an alternative API has been available. // May also be one of DeprecatedNeverUse or DeprecatedUseNoLonger. - AlternativeAvailableSince int + AlternativeAvailableSince string } // go/importer.ForCompiler contains "Deprecated:", but it refers to a single argument, not the whole function. @@ -27,246 +27,188 @@ type Deprecation struct { var StdlibDeprecations = map[string]Deprecation{ // FIXME(dh): AllowBinary isn't being detected as deprecated // because the comment has a newline right after "Deprecated:" - "go/build.AllowBinary": {7, 7}, - "(archive/zip.FileHeader).CompressedSize": {1, 1}, - "(archive/zip.FileHeader).UncompressedSize": {1, 1}, - "(archive/zip.FileHeader).ModifiedTime": {10, 10}, - "(archive/zip.FileHeader).ModifiedDate": {10, 10}, - "(*archive/zip.FileHeader).ModTime": {10, 10}, - "(*archive/zip.FileHeader).SetModTime": {10, 10}, - "(go/doc.Package).Bugs": {1, 1}, - "os.SEEK_SET": {7, 7}, - "os.SEEK_CUR": {7, 7}, - "os.SEEK_END": {7, 7}, - "(net.Dialer).Cancel": {7, 7}, - "runtime.CPUProfile": {9, 0}, - "compress/flate.ReadError": {6, DeprecatedUseNoLonger}, - "compress/flate.WriteError": {6, DeprecatedUseNoLonger}, - "path/filepath.HasPrefix": {0, DeprecatedNeverUse}, - "(net/http.Transport).Dial": {7, 7}, - "(net/http.Transport).DialTLS": {14, 14}, - "(*net/http.Transport).CancelRequest": {6, 5}, - "net/http.ErrWriteAfterFlush": {7, DeprecatedUseNoLonger}, - "net/http.ErrHeaderTooLong": {8, DeprecatedUseNoLonger}, - "net/http.ErrShortBody": {8, DeprecatedUseNoLonger}, - "net/http.ErrMissingContentLength": {8, DeprecatedUseNoLonger}, - "net/http/httputil.ErrPersistEOF": {0, DeprecatedUseNoLonger}, - "net/http/httputil.ErrClosed": {0, DeprecatedUseNoLonger}, - "net/http/httputil.ErrPipeline": {0, DeprecatedUseNoLonger}, - "net/http/httputil.ServerConn": {0, 0}, - "net/http/httputil.NewServerConn": {0, 0}, - "net/http/httputil.ClientConn": {0, 0}, - "net/http/httputil.NewClientConn": {0, 0}, - "net/http/httputil.NewProxyClientConn": {0, 0}, - "(net/http.Request).Cancel": {7, 7}, - "(text/template/parse.PipeNode).Line": {1, DeprecatedUseNoLonger}, - "(text/template/parse.ActionNode).Line": {1, DeprecatedUseNoLonger}, - "(text/template/parse.BranchNode).Line": {1, DeprecatedUseNoLonger}, - "(text/template/parse.TemplateNode).Line": {1, DeprecatedUseNoLonger}, - "database/sql/driver.ColumnConverter": {9, 9}, - "database/sql/driver.Execer": {8, 8}, - "database/sql/driver.Queryer": {8, 8}, - "(database/sql/driver.Conn).Begin": {8, 8}, - "(database/sql/driver.Stmt).Exec": {8, 8}, - "(database/sql/driver.Stmt).Query": {8, 8}, - "syscall.StringByteSlice": {1, 1}, - "syscall.StringBytePtr": {1, 1}, - "syscall.StringSlicePtr": {1, 1}, - "syscall.StringToUTF16": {1, 1}, - "syscall.StringToUTF16Ptr": {1, 1}, - "(*regexp.Regexp).Copy": {12, DeprecatedUseNoLonger}, - "(archive/tar.Header).Xattrs": {10, 10}, - "archive/tar.TypeRegA": {11, 1}, - "go/types.NewInterface": {11, 11}, - "(*go/types.Interface).Embedded": {11, 11}, - "go/importer.For": {12, 12}, - "encoding/json.InvalidUTF8Error": {2, DeprecatedUseNoLonger}, - "encoding/json.UnmarshalFieldError": {2, DeprecatedUseNoLonger}, - "encoding/csv.ErrTrailingComma": {2, DeprecatedUseNoLonger}, - "(encoding/csv.Reader).TrailingComma": {2, DeprecatedUseNoLonger}, - "(net.Dialer).DualStack": {12, 12}, - "net/http.ErrUnexpectedTrailer": {12, DeprecatedUseNoLonger}, - "net/http.CloseNotifier": {11, 7}, + "go/build.AllowBinary": {"go1.7", "go1.7"}, + "(archive/zip.FileHeader).CompressedSize": {"go1.1", "go1.1"}, + "(archive/zip.FileHeader).UncompressedSize": {"go1.1", "go1.1"}, + "(archive/zip.FileHeader).ModifiedTime": {"go1.10", "go1.10"}, + "(archive/zip.FileHeader).ModifiedDate": {"go1.10", "go1.10"}, + "(*archive/zip.FileHeader).ModTime": {"go1.10", "go1.10"}, + "(*archive/zip.FileHeader).SetModTime": {"go1.10", "go1.10"}, + "(go/doc.Package).Bugs": {"go1.1", "go1.1"}, + "os.SEEK_SET": {"go1.7", "go1.7"}, + "os.SEEK_CUR": {"go1.7", "go1.7"}, + "os.SEEK_END": {"go1.7", "go1.7"}, + "(net.Dialer).Cancel": {"go1.7", "go1.7"}, + "runtime.CPUProfile": {"go1.9", "go1.0"}, + "compress/flate.ReadError": {"go1.6", DeprecatedUseNoLonger}, + "compress/flate.WriteError": {"go1.6", DeprecatedUseNoLonger}, + "path/filepath.HasPrefix": {"go1.0", DeprecatedNeverUse}, + "(net/http.Transport).Dial": {"go1.7", "go1.7"}, + "(net/http.Transport).DialTLS": {"go1.14", "go1.14"}, + "(*net/http.Transport).CancelRequest": {"go1.6", "go1.5"}, + "net/http.ErrWriteAfterFlush": {"go1.7", DeprecatedUseNoLonger}, + "net/http.ErrHeaderTooLong": {"go1.8", DeprecatedUseNoLonger}, + "net/http.ErrShortBody": {"go1.8", DeprecatedUseNoLonger}, + "net/http.ErrMissingContentLength": {"go1.8", DeprecatedUseNoLonger}, + "net/http/httputil.ErrPersistEOF": {"go1.0", DeprecatedUseNoLonger}, + "net/http/httputil.ErrClosed": {"go1.0", DeprecatedUseNoLonger}, + "net/http/httputil.ErrPipeline": {"go1.0", DeprecatedUseNoLonger}, + "net/http/httputil.ServerConn": {"go1.0", "go1.0"}, + "net/http/httputil.NewServerConn": {"go1.0", "go1.0"}, + "net/http/httputil.ClientConn": {"go1.0", "go1.0"}, + "net/http/httputil.NewClientConn": {"go1.0", "go1.0"}, + "net/http/httputil.NewProxyClientConn": {"go1.0", "go1.0"}, + "(net/http.Request).Cancel": {"go1.7", "go1.7"}, + "(text/template/parse.PipeNode).Line": {"go1.1", DeprecatedUseNoLonger}, + "(text/template/parse.ActionNode).Line": {"go1.1", DeprecatedUseNoLonger}, + "(text/template/parse.BranchNode).Line": {"go1.1", DeprecatedUseNoLonger}, + "(text/template/parse.TemplateNode).Line": {"go1.1", DeprecatedUseNoLonger}, + "database/sql/driver.ColumnConverter": {"go1.9", "go1.9"}, + "database/sql/driver.Execer": {"go1.8", "go1.8"}, + "database/sql/driver.Queryer": {"go1.8", "go1.8"}, + "(database/sql/driver.Conn).Begin": {"go1.8", "go1.8"}, + "(database/sql/driver.Stmt).Exec": {"go1.8", "go1.8"}, + "(database/sql/driver.Stmt).Query": {"go1.8", "go1.8"}, + "syscall.StringByteSlice": {"go1.1", "go1.1"}, + "syscall.StringBytePtr": {"go1.1", "go1.1"}, + "syscall.StringSlicePtr": {"go1.1", "go1.1"}, + "syscall.StringToUTF16": {"go1.1", "go1.1"}, + "syscall.StringToUTF16Ptr": {"go1.1", "go1.1"}, + "(*regexp.Regexp).Copy": {"go1.12", DeprecatedUseNoLonger}, + "(archive/tar.Header).Xattrs": {"go1.10", "go1.10"}, + "archive/tar.TypeRegA": {"go1.11", "go1.1"}, + "go/types.NewInterface": {"go1.11", "go1.11"}, + "(*go/types.Interface).Embedded": {"go1.11", "go1.11"}, + "go/importer.For": {"go1.12", "go1.12"}, + "encoding/json.InvalidUTF8Error": {"go1.2", DeprecatedUseNoLonger}, + "encoding/json.UnmarshalFieldError": {"go1.2", DeprecatedUseNoLonger}, + "encoding/csv.ErrTrailingComma": {"go1.2", DeprecatedUseNoLonger}, + "(encoding/csv.Reader).TrailingComma": {"go1.2", DeprecatedUseNoLonger}, + "(net.Dialer).DualStack": {"go1.12", "go1.12"}, + "net/http.ErrUnexpectedTrailer": {"go1.12", DeprecatedUseNoLonger}, + "net/http.CloseNotifier": {"go1.11", "go1.7"}, // This is hairy. The notice says "Not all errors in the http package related to protocol errors are of type ProtocolError", but doesn't that imply that some errors do? - "net/http.ProtocolError": {8, DeprecatedUseNoLonger}, - "(crypto/x509.CertificateRequest).Attributes": {5, 3}, - "(*crypto/x509.Certificate).CheckCRLSignature": {19, 19}, - "crypto/x509.ParseCRL": {19, 19}, - "crypto/x509.ParseDERCRL": {19, 19}, - "(*crypto/x509.Certificate).CreateCRL": {19, 19}, - "crypto/x509/pkix.TBSCertificateList": {19, 19}, - "crypto/x509/pkix.RevokedCertificate": {19, 19}, - "go/doc.ToHTML": {20, 20}, - "go/doc.ToText": {20, 20}, - "go/doc.Synopsis": {20, 20}, - "math/rand.Seed": {20, 0}, - "math/rand.Read": {20, DeprecatedNeverUse}, + "net/http.ProtocolError": {"go1.8", DeprecatedUseNoLonger}, + "(crypto/x509.CertificateRequest).Attributes": {"go1.5", "go1.3"}, + "(*crypto/x509.Certificate).CheckCRLSignature": {"go1.19", "go1.19"}, + "crypto/x509.ParseCRL": {"go1.19", "go1.19"}, + "crypto/x509.ParseDERCRL": {"go1.19", "go1.19"}, + "(*crypto/x509.Certificate).CreateCRL": {"go1.19", "go1.19"}, + "crypto/x509/pkix.TBSCertificateList": {"go1.19", "go1.19"}, + "crypto/x509/pkix.RevokedCertificate": {"go1.19", "go1.19"}, + "go/doc.ToHTML": {"go1.20", "go1.20"}, + "go/doc.ToText": {"go1.20", "go1.20"}, + "go/doc.Synopsis": {"go1.20", "go1.20"}, + "math/rand.Seed": {"go1.20", "go1.0"}, + "math/rand.Read": {"go1.20", DeprecatedNeverUse}, // These functions have no direct alternative, but they are insecure and should no longer be used. - "crypto/x509.IsEncryptedPEMBlock": {16, DeprecatedNeverUse}, - "crypto/x509.DecryptPEMBlock": {16, DeprecatedNeverUse}, - "crypto/x509.EncryptPEMBlock": {16, DeprecatedNeverUse}, - "crypto/dsa": {16, DeprecatedNeverUse}, + "crypto/x509.IsEncryptedPEMBlock": {"go1.16", DeprecatedNeverUse}, + "crypto/x509.DecryptPEMBlock": {"go1.16", DeprecatedNeverUse}, + "crypto/x509.EncryptPEMBlock": {"go1.16", DeprecatedNeverUse}, + "crypto/dsa": {"go1.16", DeprecatedNeverUse}, // This function has no alternative, but also no purpose. - "(*crypto/rc4.Cipher).Reset": {12, DeprecatedNeverUse}, - "(net/http/httptest.ResponseRecorder).HeaderMap": {11, 7}, - "image.ZP": {13, 0}, - "image.ZR": {13, 0}, - "(*debug/gosym.LineTable).LineToPC": {2, 2}, - "(*debug/gosym.LineTable).PCToLine": {2, 2}, - "crypto/tls.VersionSSL30": {13, DeprecatedNeverUse}, - "(crypto/tls.Config).NameToCertificate": {14, DeprecatedUseNoLonger}, - "(*crypto/tls.Config).BuildNameToCertificate": {14, DeprecatedUseNoLonger}, - "(crypto/tls.Config).SessionTicketKey": {16, 5}, + "(*crypto/rc4.Cipher).Reset": {"go1.12", DeprecatedNeverUse}, + "(net/http/httptest.ResponseRecorder).HeaderMap": {"go1.11", "go1.7"}, + "image.ZP": {"go1.13", "go1.0"}, + "image.ZR": {"go1.13", "go1.0"}, + "(*debug/gosym.LineTable).LineToPC": {"go1.2", "go1.2"}, + "(*debug/gosym.LineTable).PCToLine": {"go1.2", "go1.2"}, + "crypto/tls.VersionSSL30": {"go1.13", DeprecatedNeverUse}, + "(crypto/tls.Config).NameToCertificate": {"go1.14", DeprecatedUseNoLonger}, + "(*crypto/tls.Config).BuildNameToCertificate": {"go1.14", DeprecatedUseNoLonger}, + "(crypto/tls.Config).SessionTicketKey": {"go1.16", "go1.5"}, // No alternative, no use - "(crypto/tls.ConnectionState).NegotiatedProtocolIsMutual": {16, DeprecatedNeverUse}, + "(crypto/tls.ConnectionState).NegotiatedProtocolIsMutual": {"go1.16", DeprecatedNeverUse}, // No alternative, but insecure - "(crypto/tls.ConnectionState).TLSUnique": {16, DeprecatedNeverUse}, - "image/jpeg.Reader": {4, DeprecatedNeverUse}, + "(crypto/tls.ConnectionState).TLSUnique": {"go1.16", DeprecatedNeverUse}, + "image/jpeg.Reader": {"go1.4", DeprecatedNeverUse}, // All of these have been deprecated in favour of external libraries - "syscall.AttachLsf": {7, 0}, - "syscall.DetachLsf": {7, 0}, - "syscall.LsfSocket": {7, 0}, - "syscall.SetLsfPromisc": {7, 0}, - "syscall.LsfJump": {7, 0}, - "syscall.LsfStmt": {7, 0}, - "syscall.BpfStmt": {7, 0}, - "syscall.BpfJump": {7, 0}, - "syscall.BpfBuflen": {7, 0}, - "syscall.SetBpfBuflen": {7, 0}, - "syscall.BpfDatalink": {7, 0}, - "syscall.SetBpfDatalink": {7, 0}, - "syscall.SetBpfPromisc": {7, 0}, - "syscall.FlushBpf": {7, 0}, - "syscall.BpfInterface": {7, 0}, - "syscall.SetBpfInterface": {7, 0}, - "syscall.BpfTimeout": {7, 0}, - "syscall.SetBpfTimeout": {7, 0}, - "syscall.BpfStats": {7, 0}, - "syscall.SetBpfImmediate": {7, 0}, - "syscall.SetBpf": {7, 0}, - "syscall.CheckBpfVersion": {7, 0}, - "syscall.BpfHeadercmpl": {7, 0}, - "syscall.SetBpfHeadercmpl": {7, 0}, - "syscall.RouteRIB": {8, 0}, - "syscall.RoutingMessage": {8, 0}, - "syscall.RouteMessage": {8, 0}, - "syscall.InterfaceMessage": {8, 0}, - "syscall.InterfaceAddrMessage": {8, 0}, - "syscall.ParseRoutingMessage": {8, 0}, - "syscall.ParseRoutingSockaddr": {8, 0}, - "syscall.InterfaceAnnounceMessage": {7, 0}, - "syscall.InterfaceMulticastAddrMessage": {7, 0}, - "syscall.FormatMessage": {5, 0}, - "syscall.PostQueuedCompletionStatus": {17, 0}, - "syscall.GetQueuedCompletionStatus": {17, 0}, - "syscall.CreateIoCompletionPort": {17, 0}, + "syscall.AttachLsf": {"go1.7", "go1.0"}, + "syscall.DetachLsf": {"go1.7", "go1.0"}, + "syscall.LsfSocket": {"go1.7", "go1.0"}, + "syscall.SetLsfPromisc": {"go1.7", "go1.0"}, + "syscall.LsfJump": {"go1.7", "go1.0"}, + "syscall.LsfStmt": {"go1.7", "go1.0"}, + "syscall.BpfStmt": {"go1.7", "go1.0"}, + "syscall.BpfJump": {"go1.7", "go1.0"}, + "syscall.BpfBuflen": {"go1.7", "go1.0"}, + "syscall.SetBpfBuflen": {"go1.7", "go1.0"}, + "syscall.BpfDatalink": {"go1.7", "go1.0"}, + "syscall.SetBpfDatalink": {"go1.7", "go1.0"}, + "syscall.SetBpfPromisc": {"go1.7", "go1.0"}, + "syscall.FlushBpf": {"go1.7", "go1.0"}, + "syscall.BpfInterface": {"go1.7", "go1.0"}, + "syscall.SetBpfInterface": {"go1.7", "go1.0"}, + "syscall.BpfTimeout": {"go1.7", "go1.0"}, + "syscall.SetBpfTimeout": {"go1.7", "go1.0"}, + "syscall.BpfStats": {"go1.7", "go1.0"}, + "syscall.SetBpfImmediate": {"go1.7", "go1.0"}, + "syscall.SetBpf": {"go1.7", "go1.0"}, + "syscall.CheckBpfVersion": {"go1.7", "go1.0"}, + "syscall.BpfHeadercmpl": {"go1.7", "go1.0"}, + "syscall.SetBpfHeadercmpl": {"go1.7", "go1.0"}, + "syscall.RouteRIB": {"go1.8", "go1.0"}, + "syscall.RoutingMessage": {"go1.8", "go1.0"}, + "syscall.RouteMessage": {"go1.8", "go1.0"}, + "syscall.InterfaceMessage": {"go1.8", "go1.0"}, + "syscall.InterfaceAddrMessage": {"go1.8", "go1.0"}, + "syscall.ParseRoutingMessage": {"go1.8", "go1.0"}, + "syscall.ParseRoutingSockaddr": {"go1.8", "go1.0"}, + "syscall.InterfaceAnnounceMessage": {"go1.7", "go1.0"}, + "syscall.InterfaceMulticastAddrMessage": {"go1.7", "go1.0"}, + "syscall.FormatMessage": {"go1.5", "go1.0"}, + "syscall.PostQueuedCompletionStatus": {"go1.17", "go1.0"}, + "syscall.GetQueuedCompletionStatus": {"go1.17", "go1.0"}, + "syscall.CreateIoCompletionPort": {"go1.17", "go1.0"}, // We choose to only track the package itself, even though all functions are derecated individually, too. Anyone // using ioutil directly will have to import it, and this keeps the noise down. - "io/ioutil": {19, 19}, + "io/ioutil": {"go1.19", "go1.19"}, - "bytes.Title": {18, 0}, - "strings.Title": {18, 0}, - "(crypto/tls.Config).PreferServerCipherSuites": {18, DeprecatedUseNoLonger}, + "bytes.Title": {"go1.18", "go1.0"}, + "strings.Title": {"go1.18", "go1.0"}, + "(crypto/tls.Config).PreferServerCipherSuites": {"go1.18", DeprecatedUseNoLonger}, // It's not clear if Subjects was okay to use in the past, so we err on the less noisy side of assuming that it was. - "(*crypto/x509.CertPool).Subjects": {18, DeprecatedUseNoLonger}, - "go/types.NewSignature": {18, 18}, - "(net.Error).Temporary": {18, DeprecatedNeverUse}, + "(*crypto/x509.CertPool).Subjects": {"go1.18", DeprecatedUseNoLonger}, + "go/types.NewSignature": {"go1.18", "go1.18"}, + "(net.Error).Temporary": {"go1.18", DeprecatedNeverUse}, // InterfaceData is another tricky case. It was deprecated in Go 1.18, but has been useless since Go 1.4, and an // "alternative" (using your own unsafe hacks) has existed forever. We don't want to get into hairsplitting with // users who somehow successfully used this between 1.4 and 1.18, so we'll just tag it as deprecated since 1.18. - "(reflect.Value).InterfaceData": {18, 18}, + "(reflect.Value).InterfaceData": {"go1.18", "go1.18"}, // The following objects are only deprecated on Windows. - "syscall.Syscall": {18, 18}, - "syscall.Syscall12": {18, 18}, - "syscall.Syscall15": {18, 18}, - "syscall.Syscall18": {18, 18}, - "syscall.Syscall6": {18, 18}, - "syscall.Syscall9": {18, 18}, + "syscall.Syscall": {"go1.18", "go1.18"}, + "syscall.Syscall12": {"go1.18", "go1.18"}, + "syscall.Syscall15": {"go1.18", "go1.18"}, + "syscall.Syscall18": {"go1.18", "go1.18"}, + "syscall.Syscall6": {"go1.18", "go1.18"}, + "syscall.Syscall9": {"go1.18", "go1.18"}, - "reflect.SliceHeader": {21, 17}, - "reflect.StringHeader": {21, 20}, - "crypto/elliptic.GenerateKey": {21, 21}, - "crypto/elliptic.Marshal": {21, 21}, - "crypto/elliptic.Unmarshal": {21, 21}, - "(*crypto/elliptic.CurveParams).Add": {21, 21}, - "(*crypto/elliptic.CurveParams).Double": {21, 21}, - "(*crypto/elliptic.CurveParams).IsOnCurve": {21, 21}, - "(*crypto/elliptic.CurveParams).ScalarBaseMult": {21, 21}, - "(*crypto/elliptic.CurveParams).ScalarMult": {21, 21}, - "crypto/rsa.GenerateMultiPrimeKey": {21, DeprecatedNeverUse}, - "(crypto/rsa.PrecomputedValues).CRTValues": {21, DeprecatedNeverUse}, - "(crypto/x509.RevocationList).RevokedCertificates": {21, 21}, + "reflect.SliceHeader": {"go1.21", "go1.17"}, + "reflect.StringHeader": {"go1.21", "go1.20"}, + "crypto/elliptic.GenerateKey": {"go1.21", "go1.21"}, + "crypto/elliptic.Marshal": {"go1.21", "go1.21"}, + "crypto/elliptic.Unmarshal": {"go1.21", "go1.21"}, + "(*crypto/elliptic.CurveParams).Add": {"go1.21", "go1.21"}, + "(*crypto/elliptic.CurveParams).Double": {"go1.21", "go1.21"}, + "(*crypto/elliptic.CurveParams).IsOnCurve": {"go1.21", "go1.21"}, + "(*crypto/elliptic.CurveParams).ScalarBaseMult": {"go1.21", "go1.21"}, + "(*crypto/elliptic.CurveParams).ScalarMult": {"go1.21", "go1.21"}, + "crypto/rsa.GenerateMultiPrimeKey": {"go1.21", DeprecatedNeverUse}, + "(crypto/rsa.PrecomputedValues).CRTValues": {"go1.21", DeprecatedNeverUse}, + "(crypto/x509.RevocationList).RevokedCertificates": {"go1.21", "go1.21"}, + + "go/ast.NewPackage": {"go1.22", "go1.0"}, + "go/ast.Importer": {"go1.22", "go1.0"}, + "go/ast.Object": {"go1.22", "go1.0"}, + "go/ast.Package": {"go1.22", "go1.0"}, + "go/ast.Scope": {"go1.22", "go1.0"}, + "html/template.ErrJSTemplate": {"go1.22", DeprecatedUseNoLonger}, + "reflect.PtrTo": {"go1.22", "go1.18"}, } -// Last imported from Go at c19c4c566c63818dfd059b352e52c4710eecf14d with the following numbers of deprecations: -// -// archive/tar/common.go:2 -// archive/zip/struct.go:6 -// bytes/bytes.go:1 -// compress/flate/inflate.go:2 -// crypto/dsa/dsa.go:1 -// crypto/elliptic/elliptic.go:8 -// crypto/elliptic/params.go:5 -// crypto/rc4/rc4.go:1 -// crypto/rsa/rsa.go:2 -// crypto/tls/common.go:6 -// crypto/x509/cert_pool.go:1 -// crypto/x509/pem_decrypt.go:3 -// crypto/x509/pkix/pkix.go:2 -// crypto/x509/x509.go:6 -// database/sql/driver/driver.go:6 -// debug/gosym/pclntab.go:2 -// encoding/csv/reader.go:2 -// encoding/json/decode.go:1 -// encoding/json/encode.go:1 -// go/build/build.go:1 -// go/doc/comment.go:2 -// go/doc/doc.go:1 -// go/doc/synopsis.go:1 -// go/importer/importer.go:2 -// go/types/interface.go:2 -// go/types/signature.go:1 -// image/geom.go:2 -// image/jpeg/reader.go:1 -// internal/types/errors/codes.go:1 -// io/ioutil/ioutil.go:7 -// io/ioutil/tempfile.go:2 -// math/rand/rand.go:2 -// net/dial.go:2 -// net/http/h2_bundle.go:1 -// net/http/httptest/recorder.go:1 -// net/http/httputil/persist.go:8 -// net/http/request.go:6 -// net/http/server.go:2 -// net/http/socks_bundle.go:1 -// net/http/transport.go:3 -// net/net.go:1 -// os/file.go:1 -// path/filepath/path_plan9.go:1 -// path/filepath/path_unix.go:1 -// path/filepath/path_windows.go:1 -// reflect/value.go:3 -// regexp/regexp.go:1 -// runtime/cpuprof.go:1 -// strings/strings.go:1 -// syscall/bpf_bsd.go:18 -// syscall/bpf_darwin.go:18 -// syscall/dll_windows.go:6 -// syscall/exec_plan9.go:1 -// syscall/exec_unix.go:1 -// syscall/lsf_linux.go:6 -// syscall/route_bsd.go:7 -// syscall/route_darwin.go:1 -// syscall/route_dragonfly.go:2 -// syscall/route_freebsd.go:2 -// syscall/route_netbsd.go:1 -// syscall/route_openbsd.go:1 -// syscall/syscall.go:3 -// syscall/syscall_windows.go:6 -// text/template/parse/node.go:5 -// vendor/golang.org/x/text/transform/transform.go:1 +// Last imported from Go at e8ee1dc4f9e2632ba1018610d1a1187743ae397f diff --git a/tools/vendor/honnef.co/go/tools/knowledge/targets.go b/tools/vendor/honnef.co/go/tools/knowledge/targets.go new file mode 100644 index 000000000..d9c44f83f --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/knowledge/targets.go @@ -0,0 +1,38 @@ +package knowledge + +var KnownGOOS = map[string]struct{}{ + "aix": {}, + "android": {}, + "darwin": {}, + "dragonfly": {}, + "freebsd": {}, + "hurd": {}, + "illumos": {}, + "ios": {}, + "js": {}, + "linux": {}, + "netbsd": {}, + "openbsd": {}, + "plan9": {}, + "solaris": {}, + "wasip1": {}, + "windows": {}, +} + +var KnownGOARCH = map[string]struct{}{ + "386": {}, + "amd64": {}, + "arm": {}, + "arm64": {}, + "loong64": {}, + "mips": {}, + "mipsle": {}, + "mips64": {}, + "mips64le": {}, + "ppc64": {}, + "ppc64le": {}, + "riscv64": {}, + "s390x": {}, + "sparc64": {}, + "wasm": {}, +} diff --git a/tools/vendor/honnef.co/go/tools/pattern/match.go b/tools/vendor/honnef.co/go/tools/pattern/match.go index 3eae3bd63..4fb4f8ec6 100644 --- a/tools/vendor/honnef.co/go/tools/pattern/match.go +++ b/tools/vendor/honnef.co/go/tools/pattern/match.go @@ -586,13 +586,28 @@ func (fn Symbol) Match(m *Matcher, node interface{}) (interface{}, bool) { case *types.Builtin: name = obj.Name() case *types.TypeName: - if obj.Pkg() == nil { - return nil, false - } - if obj.Parent() != obj.Pkg().Scope() { - return nil, false + origObj := obj + for { + if obj.Parent() != obj.Pkg().Scope() { + return nil, false + } + name = types.TypeString(obj.Type(), nil) + _, ok = match(m, fn.Name, name) + if ok || !obj.IsAlias() { + return origObj, ok + } else { + // FIXME(dh): we should peel away one layer of alias at a time; this is blocked on + // github.com/golang/go/issues/66559 + switch typ := types.Unalias(obj.Type()).(type) { + case interface{ Obj() *types.TypeName }: + obj = typ.Obj() + case *types.Basic: + return match(m, fn.Name, typ.Name()) + default: + return nil, false + } + } } - name = types.TypeString(obj.Type(), nil) case *types.Const, *types.Var: if obj.Pkg() == nil { return nil, false diff --git a/tools/vendor/honnef.co/go/tools/simple/analysis.go b/tools/vendor/honnef.co/go/tools/simple/analysis.go index 04ac2f5e0..9512d2aa3 100644 --- a/tools/vendor/honnef.co/go/tools/simple/analysis.go +++ b/tools/vendor/honnef.co/go/tools/simple/analysis.go @@ -1,153 +1,80 @@ +// Code generated by generate.go. DO NOT EDIT. + package simple import ( - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" - "honnef.co/go/tools/analysis/facts/generated" - "honnef.co/go/tools/analysis/facts/purity" "honnef.co/go/tools/analysis/lint" - "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/simple/s1000" + "honnef.co/go/tools/simple/s1001" + "honnef.co/go/tools/simple/s1002" + "honnef.co/go/tools/simple/s1003" + "honnef.co/go/tools/simple/s1004" + "honnef.co/go/tools/simple/s1005" + "honnef.co/go/tools/simple/s1006" + "honnef.co/go/tools/simple/s1007" + "honnef.co/go/tools/simple/s1008" + "honnef.co/go/tools/simple/s1009" + "honnef.co/go/tools/simple/s1010" + "honnef.co/go/tools/simple/s1011" + "honnef.co/go/tools/simple/s1012" + "honnef.co/go/tools/simple/s1016" + "honnef.co/go/tools/simple/s1017" + "honnef.co/go/tools/simple/s1018" + "honnef.co/go/tools/simple/s1019" + "honnef.co/go/tools/simple/s1020" + "honnef.co/go/tools/simple/s1021" + "honnef.co/go/tools/simple/s1023" + "honnef.co/go/tools/simple/s1024" + "honnef.co/go/tools/simple/s1025" + "honnef.co/go/tools/simple/s1028" + "honnef.co/go/tools/simple/s1029" + "honnef.co/go/tools/simple/s1030" + "honnef.co/go/tools/simple/s1031" + "honnef.co/go/tools/simple/s1032" + "honnef.co/go/tools/simple/s1033" + "honnef.co/go/tools/simple/s1034" + "honnef.co/go/tools/simple/s1035" + "honnef.co/go/tools/simple/s1036" + "honnef.co/go/tools/simple/s1037" + "honnef.co/go/tools/simple/s1038" + "honnef.co/go/tools/simple/s1039" + "honnef.co/go/tools/simple/s1040" ) -var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ - "S1000": { - Run: CheckSingleCaseSelect, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1001": { - Run: CheckLoopCopy, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1002": { - Run: CheckIfBoolCmp, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1003": { - Run: CheckStringsContains, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1004": { - Run: CheckBytesCompare, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1005": { - Run: CheckUnnecessaryBlank, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1006": { - Run: CheckForTrue, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1007": { - Run: CheckRegexpRaw, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1008": { - Run: CheckIfReturn, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1009": { - Run: CheckRedundantNilCheckWithLen, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1010": { - Run: CheckSlicing, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1011": { - Run: CheckLoopAppend, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, purity.Analyzer}, - }, - "S1012": { - Run: CheckTimeSince, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1016": { - Run: CheckSimplerStructConversion, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1017": { - Run: CheckTrim, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1018": { - Run: CheckLoopSlide, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1019": { - Run: CheckMakeLenCap, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1020": { - Run: CheckAssertNotNil, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1021": { - Run: CheckDeclareAssign, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1023": { - Run: CheckRedundantBreak, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1024": { - Run: CheckTimeUntil, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1025": { - Run: CheckRedundantSprintf, - Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer, generated.Analyzer}, - }, - "S1028": { - Run: CheckErrorsNewSprintf, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1029": { - Run: CheckRangeStringRunes, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "S1030": { - Run: CheckBytesBufferConversions, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1031": { - Run: CheckNilCheckAroundRange, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1032": { - Run: CheckSortHelpers, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1033": { - Run: CheckGuardedDelete, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1034": { - Run: CheckSimplifyTypeSwitch, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1035": { - Run: CheckRedundantCanonicalHeaderKey, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1036": { - Run: CheckUnnecessaryGuard, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "S1037": { - Run: CheckElaborateSleep, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1038": { - Run: CheckPrintSprintf, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1039": { - Run: CheckSprintLiteral, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, - "S1040": { - Run: CheckSameTypeTypeAssertion, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, - }, -}) +var Analyzers = []*lint.Analyzer{ + s1000.SCAnalyzer, + s1001.SCAnalyzer, + s1002.SCAnalyzer, + s1003.SCAnalyzer, + s1004.SCAnalyzer, + s1005.SCAnalyzer, + s1006.SCAnalyzer, + s1007.SCAnalyzer, + s1008.SCAnalyzer, + s1009.SCAnalyzer, + s1010.SCAnalyzer, + s1011.SCAnalyzer, + s1012.SCAnalyzer, + s1016.SCAnalyzer, + s1017.SCAnalyzer, + s1018.SCAnalyzer, + s1019.SCAnalyzer, + s1020.SCAnalyzer, + s1021.SCAnalyzer, + s1023.SCAnalyzer, + s1024.SCAnalyzer, + s1025.SCAnalyzer, + s1028.SCAnalyzer, + s1029.SCAnalyzer, + s1030.SCAnalyzer, + s1031.SCAnalyzer, + s1032.SCAnalyzer, + s1033.SCAnalyzer, + s1034.SCAnalyzer, + s1035.SCAnalyzer, + s1036.SCAnalyzer, + s1037.SCAnalyzer, + s1038.SCAnalyzer, + s1039.SCAnalyzer, + s1040.SCAnalyzer, +} diff --git a/tools/vendor/honnef.co/go/tools/simple/doc.go b/tools/vendor/honnef.co/go/tools/simple/doc.go index 421f85134..c04bc24c7 100644 --- a/tools/vendor/honnef.co/go/tools/simple/doc.go +++ b/tools/vendor/honnef.co/go/tools/simple/doc.go @@ -1,469 +1,6 @@ +//go:generate go run ../generate.go + // Package simple contains analyzes that simplify code. // All suggestions made by these analyzes are intended to result in objectively simpler code, // and following their advice is recommended. package simple - -import "honnef.co/go/tools/analysis/lint" - -var Docs = lint.Markdownify(map[string]*lint.RawDocumentation{ - "S1000": { - Title: `Use plain channel send or receive instead of single-case select`, - Text: `Select statements with a single case can be replaced with a simple -send or receive.`, - Before: ` -select { -case x := <-ch: - fmt.Println(x) -}`, - After: ` -x := <-ch -fmt.Println(x) -`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1001": { - Title: `Replace for loop with call to copy`, - Text: ` -Use \'copy()\' for copying elements from one slice to another. For -arrays of identical size, you can use simple assignment.`, - Before: ` -for i, x := range src { - dst[i] = x -}`, - After: `copy(dst, src)`, - Since: "2017.1", - // MergeIfAll because the types of src and dst might be different under different build tags. - // You shouldn't write code like that… - MergeIf: lint.MergeIfAll, - }, - - "S1002": { - Title: `Omit comparison with boolean constant`, - Before: `if x == true {}`, - After: `if x {}`, - Since: "2017.1", - // MergeIfAll because 'true' might not be the builtin constant under all build tags. - // You shouldn't write code like that… - MergeIf: lint.MergeIfAll, - }, - - "S1003": { - Title: `Replace call to \'strings.Index\' with \'strings.Contains\'`, - Before: `if strings.Index(x, y) != -1 {}`, - After: `if strings.Contains(x, y) {}`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1004": { - Title: `Replace call to \'bytes.Compare\' with \'bytes.Equal\'`, - Before: `if bytes.Compare(x, y) == 0 {}`, - After: `if bytes.Equal(x, y) {}`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1005": { - Title: `Drop unnecessary use of the blank identifier`, - Text: `In many cases, assigning to the blank identifier is unnecessary.`, - Before: ` -for _ = range s {} -x, _ = someMap[key] -_ = <-ch`, - After: ` -for range s{} -x = someMap[key] -<-ch`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1006": { - Title: `Use \"for { ... }\" for infinite loops`, - Text: `For infinite loops, using \'for { ... }\' is the most idiomatic choice.`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1007": { - Title: `Simplify regular expression by using raw string literal`, - Text: `Raw string literals use backticks instead of quotation marks and do not support -any escape sequences. This means that the backslash can be used -freely, without the need of escaping. - -Since regular expressions have their own escape sequences, raw strings -can improve their readability.`, - Before: `regexp.Compile("\\A(\\w+) profile: total \\d+\\n\\z")`, - After: "regexp.Compile(`\\A(\\w+) profile: total \\d+\\n\\z`)", - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1008": { - Title: `Simplify returning boolean expression`, - Before: ` -if { - return true -} -return false`, - After: `return `, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1009": { - Title: `Omit redundant nil check on slices`, - Text: `The \'len\' function is defined for all slices, even nil ones, which have -a length of zero. It is not necessary to check if a slice is not nil -before checking that its length is not zero.`, - Before: `if x != nil && len(x) != 0 {}`, - After: `if len(x) != 0 {}`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1010": { - Title: `Omit default slice index`, - Text: `When slicing, the second index defaults to the length of the value, -making \'s[n:len(s)]\' and \'s[n:]\' equivalent.`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1011": { - Title: `Use a single \'append\' to concatenate two slices`, - Before: ` -for _, e := range y { - x = append(x, e) -} - -for i := range y { - x = append(x, y[i]) -} - -for i := range y { - v := y[i] - x = append(x, v) -}`, - - After: ` -x = append(x, y...) -x = append(x, y...) -x = append(x, y...)`, - Since: "2017.1", - // MergeIfAll because y might not be a slice under all build tags. - MergeIf: lint.MergeIfAll, - }, - - "S1012": { - Title: `Replace \'time.Now().Sub(x)\' with \'time.Since(x)\'`, - Text: `The \'time.Since\' helper has the same effect as using \'time.Now().Sub(x)\' -but is easier to read.`, - Before: `time.Now().Sub(x)`, - After: `time.Since(x)`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1016": { - Title: `Use a type conversion instead of manually copying struct fields`, - Text: `Two struct types with identical fields can be converted between each -other. In older versions of Go, the fields had to have identical -struct tags. Since Go 1.8, however, struct tags are ignored during -conversions. It is thus not necessary to manually copy every field -individually.`, - Before: ` -var x T1 -y := T2{ - Field1: x.Field1, - Field2: x.Field2, -}`, - After: ` -var x T1 -y := T2(x)`, - Since: "2017.1", - MergeIf: lint.MergeIfAll, - }, - - "S1017": { - Title: `Replace manual trimming with \'strings.TrimPrefix\'`, - Text: `Instead of using \'strings.HasPrefix\' and manual slicing, use the -\'strings.TrimPrefix\' function. If the string doesn't start with the -prefix, the original string will be returned. Using \'strings.TrimPrefix\' -reduces complexity, and avoids common bugs, such as off-by-one -mistakes.`, - Before: ` -if strings.HasPrefix(str, prefix) { - str = str[len(prefix):] -}`, - After: `str = strings.TrimPrefix(str, prefix)`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1018": { - Title: `Use \"copy\" for sliding elements`, - Text: `\'copy()\' permits using the same source and destination slice, even with -overlapping ranges. This makes it ideal for sliding elements in a -slice.`, - - Before: ` -for i := 0; i < n; i++ { - bs[i] = bs[offset+i] -}`, - After: `copy(bs[:n], bs[offset:])`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1019": { - Title: `Simplify \"make\" call by omitting redundant arguments`, - Text: `The \"make\" function has default values for the length and capacity -arguments. For channels, the length defaults to zero, and for slices, -the capacity defaults to the length.`, - Since: "2017.1", - // MergeIfAll because the type might be different under different build tags. - // You shouldn't write code like that… - MergeIf: lint.MergeIfAll, - }, - - "S1020": { - Title: `Omit redundant nil check in type assertion`, - Before: `if _, ok := i.(T); ok && i != nil {}`, - After: `if _, ok := i.(T); ok {}`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1021": { - Title: `Merge variable declaration and assignment`, - Before: ` -var x uint -x = 1`, - After: `var x uint = 1`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1023": { - Title: `Omit redundant control flow`, - Text: `Functions that have no return value do not need a return statement as -the final statement of the function. - -Switches in Go do not have automatic fallthrough, unlike languages -like C. It is not necessary to have a break statement as the final -statement in a case block.`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1024": { - Title: `Replace \'x.Sub(time.Now())\' with \'time.Until(x)\'`, - Text: `The \'time.Until\' helper has the same effect as using \'x.Sub(time.Now())\' -but is easier to read.`, - Before: `x.Sub(time.Now())`, - After: `time.Until(x)`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1025": { - Title: `Don't use \'fmt.Sprintf("%s", x)\' unnecessarily`, - Text: `In many instances, there are easier and more efficient ways of getting -a value's string representation. Whenever a value's underlying type is -a string already, or the type has a String method, they should be used -directly. - -Given the following shared definitions - - type T1 string - type T2 int - - func (T2) String() string { return "Hello, world" } - - var x string - var y T1 - var z T2 - -we can simplify - - fmt.Sprintf("%s", x) - fmt.Sprintf("%s", y) - fmt.Sprintf("%s", z) - -to - - x - string(y) - z.String() -`, - Since: "2017.1", - MergeIf: lint.MergeIfAll, - }, - - "S1028": { - Title: `Simplify error construction with \'fmt.Errorf\'`, - Before: `errors.New(fmt.Sprintf(...))`, - After: `fmt.Errorf(...)`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1029": { - Title: `Range over the string directly`, - Text: `Ranging over a string will yield byte offsets and runes. If the offset -isn't used, this is functionally equivalent to converting the string -to a slice of runes and ranging over that. Ranging directly over the -string will be more performant, however, as it avoids allocating a new -slice, the size of which depends on the length of the string.`, - Before: `for _, r := range []rune(s) {}`, - After: `for _, r := range s {}`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1030": { - Title: `Use \'bytes.Buffer.String\' or \'bytes.Buffer.Bytes\'`, - Text: `\'bytes.Buffer\' has both a \'String\' and a \'Bytes\' method. It is almost never -necessary to use \'string(buf.Bytes())\' or \'[]byte(buf.String())\' – simply -use the other method. - -The only exception to this are map lookups. Due to a compiler optimization, -\'m[string(buf.Bytes())]\' is more efficient than \'m[buf.String()]\'. -`, - Since: "2017.1", - MergeIf: lint.MergeIfAny, - }, - - "S1031": { - Title: `Omit redundant nil check around loop`, - Text: `You can use range on nil slices and maps, the loop will simply never -execute. This makes an additional nil check around the loop -unnecessary.`, - Before: ` -if s != nil { - for _, x := range s { - ... - } -}`, - After: ` -for _, x := range s { - ... -}`, - Since: "2017.1", - // MergeIfAll because x might be a channel under some build tags. - // you shouldn't write code like that… - MergeIf: lint.MergeIfAll, - }, - - "S1032": { - Title: `Use \'sort.Ints(x)\', \'sort.Float64s(x)\', and \'sort.Strings(x)\'`, - Text: `The \'sort.Ints\', \'sort.Float64s\' and \'sort.Strings\' functions are easier to -read than \'sort.Sort(sort.IntSlice(x))\', \'sort.Sort(sort.Float64Slice(x))\' -and \'sort.Sort(sort.StringSlice(x))\'.`, - Before: `sort.Sort(sort.StringSlice(x))`, - After: `sort.Strings(x)`, - Since: "2019.1", - MergeIf: lint.MergeIfAny, - }, - - "S1033": { - Title: `Unnecessary guard around call to \"delete\"`, - Text: `Calling \'delete\' on a nil map is a no-op.`, - Since: "2019.2", - MergeIf: lint.MergeIfAny, - }, - - "S1034": { - Title: `Use result of type assertion to simplify cases`, - Since: "2019.2", - MergeIf: lint.MergeIfAny, - }, - - "S1035": { - Title: `Redundant call to \'net/http.CanonicalHeaderKey\' in method call on \'net/http.Header\'`, - Text: ` -The methods on \'net/http.Header\', namely \'Add\', \'Del\', \'Get\' -and \'Set\', already canonicalize the given header name.`, - Since: "2020.1", - MergeIf: lint.MergeIfAny, - }, - - "S1036": { - Title: `Unnecessary guard around map access`, - - Text: ` -When accessing a map key that doesn't exist yet, one receives a zero -value. Often, the zero value is a suitable value, for example when -using append or doing integer math. - -The following - - if _, ok := m["foo"]; ok { - m["foo"] = append(m["foo"], "bar") - } else { - m["foo"] = []string{"bar"} - } - -can be simplified to - - m["foo"] = append(m["foo"], "bar") - -and - - if _, ok := m2["k"]; ok { - m2["k"] += 4 - } else { - m2["k"] = 4 - } - -can be simplified to - - m["k"] += 4 -`, - Since: "2020.1", - MergeIf: lint.MergeIfAny, - }, - - "S1037": { - Title: `Elaborate way of sleeping`, - Text: `Using a select statement with a single case receiving -from the result of \'time.After\' is a very elaborate way of sleeping that -can much simpler be expressed with a simple call to time.Sleep.`, - Since: "2020.1", - MergeIf: lint.MergeIfAny, - }, - - "S1038": { - Title: "Unnecessarily complex way of printing formatted string", - Text: `Instead of using \'fmt.Print(fmt.Sprintf(...))\', one can use \'fmt.Printf(...)\'.`, - Since: "2020.1", - MergeIf: lint.MergeIfAny, - }, - - "S1039": { - Title: `Unnecessary use of \'fmt.Sprint\'`, - Text: ` -Calling \'fmt.Sprint\' with a single string argument is unnecessary -and identical to using the string directly.`, - Since: "2020.1", - // MergeIfAll because s might not be a string under all build tags. - // you shouldn't write code like that… - MergeIf: lint.MergeIfAll, - }, - "S1040": { - Title: "Type assertion to current type", - Text: `The type assertion \'x.(SomeInterface)\', when \'x\' already has type -\'SomeInterface\', can only fail if \'x\' is nil. Usually, this is -left-over code from when \'x\' had a different type and you can safely -delete the type assertion. If you want to check that \'x\' is not nil, -consider being explicit and using an actual \'if x == nil\' comparison -instead of relying on the type assertion panicking.`, - Since: "2021.1", - // MergeIfAll because x might have different types under different build tags. - // You shouldn't write code like that… - MergeIf: lint.MergeIfAll, - }, -}) diff --git a/tools/vendor/honnef.co/go/tools/simple/lint.go b/tools/vendor/honnef.co/go/tools/simple/lint.go deleted file mode 100644 index 8458f7be6..000000000 --- a/tools/vendor/honnef.co/go/tools/simple/lint.go +++ /dev/null @@ -1,2192 +0,0 @@ -package simple - -import ( - "fmt" - "go/ast" - "go/constant" - "go/token" - "go/types" - "path/filepath" - "reflect" - "sort" - "strings" - - "honnef.co/go/tools/analysis/code" - "honnef.co/go/tools/analysis/edit" - "honnef.co/go/tools/analysis/facts/purity" - "honnef.co/go/tools/analysis/lint" - "honnef.co/go/tools/analysis/report" - "honnef.co/go/tools/go/ast/astutil" - "honnef.co/go/tools/go/types/typeutil" - "honnef.co/go/tools/internal/passes/buildir" - "honnef.co/go/tools/internal/sharedcheck" - "honnef.co/go/tools/knowledge" - "honnef.co/go/tools/pattern" - - "golang.org/x/exp/typeparams" - "golang.org/x/tools/go/analysis" -) - -var ( - checkSingleCaseSelectQ1 = pattern.MustParse(` - (ForStmt - nil nil nil - select@(SelectStmt - (CommClause - (Or - (UnaryExpr "<-" _) - (AssignStmt _ _ (UnaryExpr "<-" _))) - _)))`) - checkSingleCaseSelectQ2 = pattern.MustParse(`(SelectStmt (CommClause _ _))`) -) - -func CheckSingleCaseSelect(pass *analysis.Pass) (interface{}, error) { - seen := map[ast.Node]struct{}{} - fn := func(node ast.Node) { - if m, ok := code.Match(pass, checkSingleCaseSelectQ1, node); ok { - seen[m.State["select"].(ast.Node)] = struct{}{} - report.Report(pass, node, "should use for range instead of for { select {} }", report.FilterGenerated()) - } else if _, ok := code.Match(pass, checkSingleCaseSelectQ2, node); ok { - if _, ok := seen[node]; !ok { - report.Report(pass, node, "should use a simple channel send/receive instead of select with a single case", - report.ShortRange(), - report.FilterGenerated()) - } - } - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.SelectStmt)(nil)) - return nil, nil -} - -var ( - checkLoopCopyQ = pattern.MustParse(` - (Or - (RangeStmt - key@(Ident _) value@(Ident _) ":=" src - [(AssignStmt (IndexExpr dst key) "=" value)]) - (RangeStmt - key@(Ident _) nil ":=" src - [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))]) - (ForStmt - (AssignStmt key@(Ident _) ":=" (IntegerLiteral "0")) - (BinaryExpr key "<" (CallExpr (Symbol "len") [src])) - (IncDecStmt key "++") - [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))]))`) -) - -func CheckLoopCopy(pass *analysis.Pass) (interface{}, error) { - // TODO revisit once range doesn't require a structural type - - isInvariant := func(k, v types.Object, node ast.Expr) bool { - if code.MayHaveSideEffects(pass, node, nil) { - return false - } - invariant := true - ast.Inspect(node, func(node ast.Node) bool { - if node, ok := node.(*ast.Ident); ok { - obj := pass.TypesInfo.ObjectOf(node) - if obj == k || obj == v { - // don't allow loop bodies like 'a[i][i] = v' - invariant = false - return false - } - } - return true - }) - return invariant - } - - var elType func(T types.Type) (el types.Type, isArray bool, isArrayPointer bool, ok bool) - elType = func(T types.Type) (el types.Type, isArray bool, isArrayPointer bool, ok bool) { - switch typ := T.Underlying().(type) { - case *types.Slice: - return typ.Elem(), false, false, true - case *types.Array: - return typ.Elem(), true, false, true - case *types.Pointer: - el, isArray, _, ok = elType(typ.Elem()) - return el, isArray, true, ok - default: - return nil, false, false, false - } - } - - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkLoopCopyQ, node) - if !ok { - return - } - - src := m.State["src"].(ast.Expr) - dst := m.State["dst"].(ast.Expr) - - k := pass.TypesInfo.ObjectOf(m.State["key"].(*ast.Ident)) - var v types.Object - if value, ok := m.State["value"]; ok { - v = pass.TypesInfo.ObjectOf(value.(*ast.Ident)) - } - if !isInvariant(k, v, dst) { - return - } - if !isInvariant(k, v, src) { - // For example: 'for i := range foo()' - return - } - - Tsrc := pass.TypesInfo.TypeOf(src) - Tdst := pass.TypesInfo.TypeOf(dst) - TsrcElem, TsrcArray, TsrcPointer, ok := elType(Tsrc) - if !ok { - return - } - if TsrcPointer { - Tsrc = Tsrc.Underlying().(*types.Pointer).Elem() - } - TdstElem, TdstArray, TdstPointer, ok := elType(Tdst) - if !ok { - return - } - if TdstPointer { - Tdst = Tdst.Underlying().(*types.Pointer).Elem() - } - - if !types.Identical(TsrcElem, TdstElem) { - return - } - - if TsrcArray && TdstArray && types.Identical(Tsrc, Tdst) { - if TsrcPointer { - src = &ast.StarExpr{ - X: src, - } - } - if TdstPointer { - dst = &ast.StarExpr{ - X: dst, - } - } - r := &ast.AssignStmt{ - Lhs: []ast.Expr{dst}, - Rhs: []ast.Expr{src}, - Tok: token.ASSIGN, - } - - report.Report(pass, node, "should copy arrays using assignment instead of using a loop", - report.FilterGenerated(), - report.ShortRange(), - report.Fixes(edit.Fix("replace loop with assignment", edit.ReplaceWithNode(pass.Fset, node, r)))) - } else { - tv, err := types.Eval(pass.Fset, pass.Pkg, node.Pos(), "copy") - if err == nil && tv.IsBuiltin() { - to := "to" - from := "from" - src := m.State["src"].(ast.Expr) - if TsrcArray { - from = "from[:]" - src = &ast.SliceExpr{ - X: src, - } - } - dst := m.State["dst"].(ast.Expr) - if TdstArray { - to = "to[:]" - dst = &ast.SliceExpr{ - X: dst, - } - } - - r := &ast.CallExpr{ - Fun: &ast.Ident{Name: "copy"}, - Args: []ast.Expr{dst, src}, - } - opts := []report.Option{ - report.ShortRange(), - report.FilterGenerated(), - report.Fixes(edit.Fix("replace loop with call to copy()", edit.ReplaceWithNode(pass.Fset, node, r))), - } - report.Report(pass, node, fmt.Sprintf("should use copy(%s, %s) instead of a loop", to, from), opts...) - } - } - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.RangeStmt)(nil)) - return nil, nil -} - -func CheckIfBoolCmp(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if code.IsInTest(pass, node) { - return - } - - expr := node.(*ast.BinaryExpr) - if expr.Op != token.EQL && expr.Op != token.NEQ { - return - } - x := code.IsBoolConst(pass, expr.X) - y := code.IsBoolConst(pass, expr.Y) - if !x && !y { - return - } - var other ast.Expr - var val bool - if x { - val = code.BoolConst(pass, expr.X) - other = expr.Y - } else { - val = code.BoolConst(pass, expr.Y) - other = expr.X - } - - ok := typeutil.All(pass.TypesInfo.TypeOf(other), func(term *types.Term) bool { - basic, ok := term.Type().Underlying().(*types.Basic) - return ok && basic.Kind() == types.Bool - }) - if !ok { - return - } - op := "" - if (expr.Op == token.EQL && !val) || (expr.Op == token.NEQ && val) { - op = "!" - } - r := op + report.Render(pass, other) - l1 := len(r) - r = strings.TrimLeft(r, "!") - if (l1-len(r))%2 == 1 { - r = "!" + r - } - report.Report(pass, expr, fmt.Sprintf("should omit comparison to bool constant, can be simplified to %s", r), - report.FilterGenerated(), - report.Fixes(edit.Fix("simplify bool comparison", edit.ReplaceWithString(expr, r)))) - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -var ( - checkBytesBufferConversionsQ = pattern.MustParse(`(CallExpr _ [(CallExpr sel@(SelectorExpr recv _) [])])`) - checkBytesBufferConversionsRs = pattern.MustParse(`(CallExpr (SelectorExpr recv (Ident "String")) [])`) - checkBytesBufferConversionsRb = pattern.MustParse(`(CallExpr (SelectorExpr recv (Ident "Bytes")) [])`) -) - -func CheckBytesBufferConversions(pass *analysis.Pass) (interface{}, error) { - if pass.Pkg.Path() == "bytes" || pass.Pkg.Path() == "bytes_test" { - // The bytes package can use itself however it wants - return nil, nil - } - fn := func(node ast.Node, stack []ast.Node) { - m, ok := code.Match(pass, checkBytesBufferConversionsQ, node) - if !ok { - return - } - call := node.(*ast.CallExpr) - sel := m.State["sel"].(*ast.SelectorExpr) - - typ := pass.TypesInfo.TypeOf(call.Fun) - if typ == types.Universe.Lookup("string").Type() && code.IsCallTo(pass, call.Args[0], "(*bytes.Buffer).Bytes") { - if _, ok := stack[len(stack)-2].(*ast.IndexExpr); ok { - // Don't flag m[string(buf.Bytes())] – thanks to a - // compiler optimization, this is actually faster than - // m[buf.String()] - return - } - - report.Report(pass, call, fmt.Sprintf("should use %v.String() instead of %v", report.Render(pass, sel.X), report.Render(pass, call)), - report.FilterGenerated(), - report.Fixes(edit.Fix("simplify conversion", edit.ReplaceWithPattern(pass.Fset, node, checkBytesBufferConversionsRs, m.State)))) - } else if typ, ok := typ.(*types.Slice); ok && typ.Elem() == types.Universe.Lookup("byte").Type() && code.IsCallTo(pass, call.Args[0], "(*bytes.Buffer).String") { - report.Report(pass, call, fmt.Sprintf("should use %v.Bytes() instead of %v", report.Render(pass, sel.X), report.Render(pass, call)), - report.FilterGenerated(), - report.Fixes(edit.Fix("simplify conversion", edit.ReplaceWithPattern(pass.Fset, node, checkBytesBufferConversionsRb, m.State)))) - } - - } - code.PreorderStack(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckStringsContains(pass *analysis.Pass) (interface{}, error) { - // map of value to token to bool value - allowed := map[int64]map[token.Token]bool{ - -1: {token.GTR: true, token.NEQ: true, token.EQL: false}, - 0: {token.GEQ: true, token.LSS: false}, - } - fn := func(node ast.Node) { - expr := node.(*ast.BinaryExpr) - switch expr.Op { - case token.GEQ, token.GTR, token.NEQ, token.LSS, token.EQL: - default: - return - } - - value, ok := code.ExprToInt(pass, expr.Y) - if !ok { - return - } - - allowedOps, ok := allowed[value] - if !ok { - return - } - b, ok := allowedOps[expr.Op] - if !ok { - return - } - - call, ok := expr.X.(*ast.CallExpr) - if !ok { - return - } - sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok { - return - } - pkgIdent, ok := sel.X.(*ast.Ident) - if !ok { - return - } - funIdent := sel.Sel - if pkgIdent.Name != "strings" && pkgIdent.Name != "bytes" { - return - } - - var r ast.Expr - switch funIdent.Name { - case "IndexRune": - r = &ast.SelectorExpr{ - X: pkgIdent, - Sel: &ast.Ident{Name: "ContainsRune"}, - } - case "IndexAny": - r = &ast.SelectorExpr{ - X: pkgIdent, - Sel: &ast.Ident{Name: "ContainsAny"}, - } - case "Index": - r = &ast.SelectorExpr{ - X: pkgIdent, - Sel: &ast.Ident{Name: "Contains"}, - } - default: - return - } - - r = &ast.CallExpr{ - Fun: r, - Args: call.Args, - } - if !b { - r = &ast.UnaryExpr{ - Op: token.NOT, - X: r, - } - } - - report.Report(pass, node, fmt.Sprintf("should use %s instead", report.Render(pass, r)), - report.FilterGenerated(), - report.Fixes(edit.Fix(fmt.Sprintf("simplify use of %s", report.Render(pass, call.Fun)), edit.ReplaceWithNode(pass.Fset, node, r)))) - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -var ( - checkBytesCompareQ = pattern.MustParse(`(BinaryExpr (CallExpr (Symbol "bytes.Compare") args) op@(Or "==" "!=") (IntegerLiteral "0"))`) - checkBytesCompareRe = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "bytes") (Ident "Equal")) args)`) - checkBytesCompareRn = pattern.MustParse(`(UnaryExpr "!" (CallExpr (SelectorExpr (Ident "bytes") (Ident "Equal")) args))`) -) - -func CheckBytesCompare(pass *analysis.Pass) (interface{}, error) { - if pass.Pkg.Path() == "bytes" || pass.Pkg.Path() == "bytes_test" { - // the bytes package is free to use bytes.Compare as it sees fit - return nil, nil - } - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkBytesCompareQ, node) - if !ok { - return - } - - args := report.RenderArgs(pass, m.State["args"].([]ast.Expr)) - prefix := "" - if m.State["op"].(token.Token) == token.NEQ { - prefix = "!" - } - - var fix analysis.SuggestedFix - switch tok := m.State["op"].(token.Token); tok { - case token.EQL: - fix = edit.Fix("simplify use of bytes.Compare", edit.ReplaceWithPattern(pass.Fset, node, checkBytesCompareRe, m.State)) - case token.NEQ: - fix = edit.Fix("simplify use of bytes.Compare", edit.ReplaceWithPattern(pass.Fset, node, checkBytesCompareRn, m.State)) - default: - panic(fmt.Sprintf("unexpected token %v", tok)) - } - report.Report(pass, node, fmt.Sprintf("should use %sbytes.Equal(%s) instead", prefix, args), report.FilterGenerated(), report.Fixes(fix)) - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -func CheckForTrue(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - loop := node.(*ast.ForStmt) - if loop.Init != nil || loop.Post != nil { - return - } - if !code.IsBoolConst(pass, loop.Cond) || !code.BoolConst(pass, loop.Cond) { - return - } - report.Report(pass, loop, "should use for {} instead of for true {}", - report.ShortRange(), - report.FilterGenerated()) - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil)) - return nil, nil -} - -func CheckRegexpRaw(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - if !code.IsCallToAny(pass, call, "regexp.MustCompile", "regexp.Compile") { - return - } - sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok { - return - } - lit, ok := call.Args[knowledge.Arg("regexp.Compile.expr")].(*ast.BasicLit) - if !ok { - // TODO(dominikh): support string concat, maybe support constants - return - } - if lit.Kind != token.STRING { - // invalid function call - return - } - if lit.Value[0] != '"' { - // already a raw string - return - } - val := lit.Value - if !strings.Contains(val, `\\`) { - return - } - if strings.Contains(val, "`") { - return - } - - bs := false - for _, c := range val { - if !bs && c == '\\' { - bs = true - continue - } - if bs && c == '\\' { - bs = false - continue - } - if bs { - // backslash followed by non-backslash -> escape sequence - return - } - } - - report.Report(pass, call, fmt.Sprintf("should use raw string (`...`) with regexp.%s to avoid having to escape twice", sel.Sel.Name), report.FilterGenerated()) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var ( - checkIfReturnQIf = pattern.MustParse(`(IfStmt nil cond [(ReturnStmt [ret@(Builtin (Or "true" "false"))])] nil)`) - checkIfReturnQRet = pattern.MustParse(`(ReturnStmt [ret@(Builtin (Or "true" "false"))])`) -) - -func CheckIfReturn(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - block := node.(*ast.BlockStmt) - l := len(block.List) - if l < 2 { - return - } - n1, n2 := block.List[l-2], block.List[l-1] - - if len(block.List) >= 3 { - if _, ok := block.List[l-3].(*ast.IfStmt); ok { - // Do not flag a series of if statements - return - } - } - m1, ok := code.Match(pass, checkIfReturnQIf, n1) - if !ok { - return - } - m2, ok := code.Match(pass, checkIfReturnQRet, n2) - if !ok { - return - } - - if op, ok := m1.State["cond"].(*ast.BinaryExpr); ok { - switch op.Op { - case token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ: - default: - return - } - } - - ret1 := m1.State["ret"].(*ast.Ident) - ret2 := m2.State["ret"].(*ast.Ident) - - if ret1.Name == ret2.Name { - // we want the function to return true and false, not the - // same value both times. - return - } - - cond := m1.State["cond"].(ast.Expr) - origCond := cond - if ret1.Name == "false" { - cond = negate(cond) - } - report.Report(pass, n1, - fmt.Sprintf("should use 'return %s' instead of 'if %s { return %s }; return %s'", - report.Render(pass, cond), - report.Render(pass, origCond), report.Render(pass, ret1), report.Render(pass, ret2)), - report.FilterGenerated()) - } - code.Preorder(pass, fn, (*ast.BlockStmt)(nil)) - return nil, nil -} - -func negate(expr ast.Expr) ast.Expr { - switch expr := expr.(type) { - case *ast.BinaryExpr: - out := *expr - switch expr.Op { - case token.EQL: - out.Op = token.NEQ - case token.LSS: - out.Op = token.GEQ - case token.GTR: - out.Op = token.LEQ - case token.NEQ: - out.Op = token.EQL - case token.LEQ: - out.Op = token.GTR - case token.GEQ: - out.Op = token.LSS - } - return &out - case *ast.Ident, *ast.CallExpr, *ast.IndexExpr, *ast.StarExpr: - return &ast.UnaryExpr{ - Op: token.NOT, - X: expr, - } - case *ast.UnaryExpr: - if expr.Op == token.NOT { - return expr.X - } - return &ast.UnaryExpr{ - Op: token.NOT, - X: expr, - } - default: - return &ast.UnaryExpr{ - Op: token.NOT, - X: &ast.ParenExpr{ - X: expr, - }, - } - } -} - -// CheckRedundantNilCheckWithLen checks for the following redundant nil-checks: -// -// if x == nil || len(x) == 0 {} -// if x != nil && len(x) != 0 {} -// if x != nil && len(x) == N {} (where N != 0) -// if x != nil && len(x) > N {} -// if x != nil && len(x) >= N {} (where N != 0) -func CheckRedundantNilCheckWithLen(pass *analysis.Pass) (interface{}, error) { - isConstZero := func(expr ast.Expr) (isConst bool, isZero bool) { - _, ok := expr.(*ast.BasicLit) - if ok { - return true, code.IsIntegerLiteral(pass, expr, constant.MakeInt64(0)) - } - id, ok := expr.(*ast.Ident) - if !ok { - return false, false - } - c, ok := pass.TypesInfo.ObjectOf(id).(*types.Const) - if !ok { - return false, false - } - return true, c.Val().Kind() == constant.Int && c.Val().String() == "0" - } - - fn := func(node ast.Node) { - // check that expr is "x || y" or "x && y" - expr := node.(*ast.BinaryExpr) - if expr.Op != token.LOR && expr.Op != token.LAND { - return - } - eqNil := expr.Op == token.LOR - - // check that x is "xx == nil" or "xx != nil" - x, ok := expr.X.(*ast.BinaryExpr) - if !ok { - return - } - if eqNil && x.Op != token.EQL { - return - } - if !eqNil && x.Op != token.NEQ { - return - } - xx, ok := x.X.(*ast.Ident) - if !ok { - return - } - if !code.IsNil(pass, x.Y) { - return - } - - // check that y is "len(xx) == 0" or "len(xx) ... " - y, ok := expr.Y.(*ast.BinaryExpr) - if !ok { - return - } - if eqNil && y.Op != token.EQL { // must be len(xx) *==* 0 - return - } - yx, ok := y.X.(*ast.CallExpr) - if !ok { - return - } - if !code.IsCallTo(pass, yx, "len") { - return - } - yxArg, ok := yx.Args[knowledge.Arg("len.v")].(*ast.Ident) - if !ok { - return - } - if yxArg.Name != xx.Name { - return - } - - if eqNil && !code.IsIntegerLiteral(pass, y.Y, constant.MakeInt64(0)) { // must be len(x) == *0* - return - } - - if !eqNil { - isConst, isZero := isConstZero(y.Y) - if !isConst { - return - } - switch y.Op { - case token.EQL: - // avoid false positive for "xx != nil && len(xx) == 0" - if isZero { - return - } - case token.GEQ: - // avoid false positive for "xx != nil && len(xx) >= 0" - if isZero { - return - } - case token.NEQ: - // avoid false positive for "xx != nil && len(xx) != " - if !isZero { - return - } - case token.GTR: - // ok - default: - return - } - } - - // finally check that xx type is one of array, slice, map or chan - // this is to prevent false positive in case if xx is a pointer to an array - typ := pass.TypesInfo.TypeOf(xx) - ok = typeutil.All(typ, func(term *types.Term) bool { - switch term.Type().Underlying().(type) { - case *types.Slice: - return true - case *types.Map: - return true - case *types.Chan: - return true - case *types.Pointer: - return false - case *types.TypeParam: - return false - default: - lint.ExhaustiveTypeSwitch(term.Type().Underlying()) - return false - } - }) - if !ok { - return - } - - report.Report(pass, expr, fmt.Sprintf("should omit nil check; len() for %s is defined as zero", typ), report.FilterGenerated()) - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -var checkSlicingQ = pattern.MustParse(`(SliceExpr x@(Object _) low (CallExpr (Builtin "len") [x]) nil)`) - -func CheckSlicing(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if _, ok := code.Match(pass, checkSlicingQ, node); ok { - expr := node.(*ast.SliceExpr) - report.Report(pass, expr.High, - "should omit second index in slice, s[a:len(s)] is identical to s[a:]", - report.FilterGenerated(), - report.Fixes(edit.Fix("simplify slice expression", edit.Delete(expr.High)))) - } - } - code.Preorder(pass, fn, (*ast.SliceExpr)(nil)) - return nil, nil -} - -func refersTo(pass *analysis.Pass, expr ast.Expr, ident types.Object) bool { - found := false - fn := func(node ast.Node) bool { - ident2, ok := node.(*ast.Ident) - if !ok { - return true - } - if ident == pass.TypesInfo.ObjectOf(ident2) { - found = true - return false - } - return true - } - ast.Inspect(expr, fn) - return found -} - -var checkLoopAppendQ = pattern.MustParse(` -(Or - (RangeStmt - (Ident "_") - val@(Object _) - _ - x - [(AssignStmt [lhs] "=" [(CallExpr (Builtin "append") [lhs val])])]) - (RangeStmt - idx@(Object _) - nil - _ - x - [(AssignStmt [lhs] "=" [(CallExpr (Builtin "append") [lhs (IndexExpr x idx)])])]) - (RangeStmt - idx@(Object _) - nil - _ - x - [(AssignStmt val@(Object _) ":=" (IndexExpr x idx)) - (AssignStmt [lhs] "=" [(CallExpr (Builtin "append") [lhs val])])]))`) - -func CheckLoopAppend(pass *analysis.Pass) (interface{}, error) { - pure := pass.ResultOf[purity.Analyzer].(purity.Result) - - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkLoopAppendQ, node) - if !ok { - return - } - - if val, ok := m.State["val"].(types.Object); ok && refersTo(pass, m.State["lhs"].(ast.Expr), val) { - return - } - - if m.State["idx"] != nil && code.MayHaveSideEffects(pass, m.State["x"].(ast.Expr), pure) { - // When using an index-based loop, x gets evaluated repeatedly and thus should be pure. - // This doesn't matter for value-based loops, because x only gets evaluated once. - return - } - - if idx, ok := m.State["idx"].(types.Object); ok && refersTo(pass, m.State["lhs"].(ast.Expr), idx) { - // The lhs mustn't refer to the index loop variable. - return - } - - if code.MayHaveSideEffects(pass, m.State["lhs"].(ast.Expr), pure) { - // The lhs may be dynamic and return different values on each iteration. For example: - // - // func bar() map[int][]int { /* return one of several maps */ } - // - // func foo(x []int, y [][]int) { - // for i := range x { - // bar()[0] = append(bar()[0], x[i]) - // } - // } - // - // The dynamic nature of the lhs might also affect the value of the index. - return - } - - src := pass.TypesInfo.TypeOf(m.State["x"].(ast.Expr)) - dst := pass.TypesInfo.TypeOf(m.State["lhs"].(ast.Expr)) - if !types.Identical(src, dst) { - return - } - - r := &ast.AssignStmt{ - Lhs: []ast.Expr{m.State["lhs"].(ast.Expr)}, - Tok: token.ASSIGN, - Rhs: []ast.Expr{ - &ast.CallExpr{ - Fun: &ast.Ident{Name: "append"}, - Args: []ast.Expr{ - m.State["lhs"].(ast.Expr), - m.State["x"].(ast.Expr), - }, - Ellipsis: 1, - }, - }, - } - - report.Report(pass, node, fmt.Sprintf("should replace loop with %s", report.Render(pass, r)), - report.ShortRange(), - report.FilterGenerated(), - report.Fixes(edit.Fix("replace loop with call to append", edit.ReplaceWithNode(pass.Fset, node, r)))) - } - code.Preorder(pass, fn, (*ast.RangeStmt)(nil)) - return nil, nil -} - -var ( - checkTimeSinceQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (Symbol "time.Now") []) (Symbol "(time.Time).Sub")) [arg])`) - checkTimeSinceR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Since")) [arg])`) -) - -func CheckTimeSince(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if _, edits, ok := code.MatchAndEdit(pass, checkTimeSinceQ, checkTimeSinceR, node); ok { - report.Report(pass, node, "should use time.Since instead of time.Now().Sub", - report.FilterGenerated(), - report.Fixes(edit.Fix("replace with call to time.Since", edits...))) - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var ( - checkTimeUntilQ = pattern.MustParse(`(CallExpr (Symbol "(time.Time).Sub") [(CallExpr (Symbol "time.Now") [])])`) - checkTimeUntilR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Until")) [arg])`) -) - -func CheckTimeUntil(pass *analysis.Pass) (interface{}, error) { - if !code.IsGoVersion(pass, 8) { - return nil, nil - } - fn := func(node ast.Node) { - if _, ok := code.Match(pass, checkTimeUntilQ, node); ok { - if sel, ok := node.(*ast.CallExpr).Fun.(*ast.SelectorExpr); ok { - r := pattern.NodeToAST(checkTimeUntilR.Root, map[string]interface{}{"arg": sel.X}).(ast.Node) - report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())", - report.FilterGenerated(), - report.Fixes(edit.Fix("replace with call to time.Until", edit.ReplaceWithNode(pass.Fset, node, r)))) - } else { - report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())", report.FilterGenerated()) - } - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var ( - checkUnnecessaryBlankQ1 = pattern.MustParse(` - (AssignStmt - [_ (Ident "_")] - _ - (Or - (IndexExpr _ _) - (UnaryExpr "<-" _))) `) - checkUnnecessaryBlankQ2 = pattern.MustParse(` - (AssignStmt - (Ident "_") _ recv@(UnaryExpr "<-" _))`) -) - -func CheckUnnecessaryBlank(pass *analysis.Pass) (interface{}, error) { - fn1 := func(node ast.Node) { - if _, ok := code.Match(pass, checkUnnecessaryBlankQ1, node); ok { - r := *node.(*ast.AssignStmt) - r.Lhs = r.Lhs[0:1] - report.Report(pass, node, "unnecessary assignment to the blank identifier", - report.FilterGenerated(), - report.Fixes(edit.Fix("remove assignment to blank identifier", edit.ReplaceWithNode(pass.Fset, node, &r)))) - } else if m, ok := code.Match(pass, checkUnnecessaryBlankQ2, node); ok { - report.Report(pass, node, "unnecessary assignment to the blank identifier", - report.FilterGenerated(), - report.Fixes(edit.Fix("simplify channel receive operation", edit.ReplaceWithNode(pass.Fset, node, m.State["recv"].(ast.Node))))) - } - } - - fn3 := func(node ast.Node) { - rs := node.(*ast.RangeStmt) - - // for _ - if rs.Value == nil && astutil.IsBlank(rs.Key) { - report.Report(pass, rs.Key, "unnecessary assignment to the blank identifier", - report.FilterGenerated(), - report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.Pos(), rs.TokPos + 1})))) - } - - // for _, _ - if astutil.IsBlank(rs.Key) && astutil.IsBlank(rs.Value) { - // FIXME we should mark both key and value - report.Report(pass, rs.Key, "unnecessary assignment to the blank identifier", - report.FilterGenerated(), - report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.Pos(), rs.TokPos + 1})))) - } - - // for x, _ - if !astutil.IsBlank(rs.Key) && astutil.IsBlank(rs.Value) { - report.Report(pass, rs.Value, "unnecessary assignment to the blank identifier", - report.FilterGenerated(), - report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.End(), rs.Value.End()})))) - } - } - - code.Preorder(pass, fn1, (*ast.AssignStmt)(nil)) - if code.IsGoVersion(pass, 4) { - code.Preorder(pass, fn3, (*ast.RangeStmt)(nil)) - } - return nil, nil -} - -func CheckSimplerStructConversion(pass *analysis.Pass) (interface{}, error) { - // TODO(dh): support conversions between type parameters - fn := func(node ast.Node, stack []ast.Node) { - if unary, ok := stack[len(stack)-2].(*ast.UnaryExpr); ok && unary.Op == token.AND { - // Do not suggest type conversion between pointers - return - } - - lit := node.(*ast.CompositeLit) - typ1, _ := pass.TypesInfo.TypeOf(lit.Type).(*types.Named) - if typ1 == nil { - return - } - s1, ok := typ1.Underlying().(*types.Struct) - if !ok { - return - } - - var typ2 *types.Named - var ident *ast.Ident - getSelType := func(expr ast.Expr) (types.Type, *ast.Ident, bool) { - sel, ok := expr.(*ast.SelectorExpr) - if !ok { - return nil, nil, false - } - ident, ok := sel.X.(*ast.Ident) - if !ok { - return nil, nil, false - } - typ := pass.TypesInfo.TypeOf(sel.X) - return typ, ident, typ != nil - } - if len(lit.Elts) == 0 { - return - } - if s1.NumFields() != len(lit.Elts) { - return - } - for i, elt := range lit.Elts { - var t types.Type - var id *ast.Ident - var ok bool - switch elt := elt.(type) { - case *ast.SelectorExpr: - t, id, ok = getSelType(elt) - if !ok { - return - } - if i >= s1.NumFields() || s1.Field(i).Name() != elt.Sel.Name { - return - } - case *ast.KeyValueExpr: - var sel *ast.SelectorExpr - sel, ok = elt.Value.(*ast.SelectorExpr) - if !ok { - return - } - - if elt.Key.(*ast.Ident).Name != sel.Sel.Name { - return - } - t, id, ok = getSelType(elt.Value) - } - if !ok { - return - } - // All fields must be initialized from the same object - if ident != nil && pass.TypesInfo.ObjectOf(ident) != pass.TypesInfo.ObjectOf(id) { - return - } - typ2, _ = t.(*types.Named) - if typ2 == nil { - return - } - ident = id - } - - if typ2 == nil { - return - } - - if typ1.Obj().Pkg() != typ2.Obj().Pkg() { - // Do not suggest type conversions between different - // packages. Types in different packages might only match - // by coincidence. Furthermore, if the dependency ever - // adds more fields to its type, it could break the code - // that relies on the type conversion to work. - return - } - - s2, ok := typ2.Underlying().(*types.Struct) - if !ok { - return - } - if typ1 == typ2 { - return - } - if code.IsGoVersion(pass, 8) { - if !types.IdenticalIgnoreTags(s1, s2) { - return - } - } else { - if !types.Identical(s1, s2) { - return - } - } - - r := &ast.CallExpr{ - Fun: lit.Type, - Args: []ast.Expr{ident}, - } - report.Report(pass, node, - fmt.Sprintf("should convert %s (type %s) to %s instead of using struct literal", ident.Name, types.TypeString(typ2, types.RelativeTo(pass.Pkg)), types.TypeString(typ1, types.RelativeTo(pass.Pkg))), - report.FilterGenerated(), - report.Fixes(edit.Fix("use type conversion", edit.ReplaceWithNode(pass.Fset, node, r)))) - } - code.PreorderStack(pass, fn, (*ast.CompositeLit)(nil)) - return nil, nil -} - -func CheckTrim(pass *analysis.Pass) (interface{}, error) { - sameNonDynamic := func(node1, node2 ast.Node) bool { - if reflect.TypeOf(node1) != reflect.TypeOf(node2) { - return false - } - - switch node1 := node1.(type) { - case *ast.Ident: - return pass.TypesInfo.ObjectOf(node1) == pass.TypesInfo.ObjectOf(node2.(*ast.Ident)) - case *ast.SelectorExpr, *ast.IndexExpr: - return astutil.Equal(node1, node2) - case *ast.BasicLit: - return astutil.Equal(node1, node2) - } - return false - } - - isLenOnIdent := func(fn ast.Expr, ident ast.Expr) bool { - call, ok := fn.(*ast.CallExpr) - if !ok { - return false - } - if !code.IsCallTo(pass, call, "len") { - return false - } - if len(call.Args) != 1 { - return false - } - return sameNonDynamic(call.Args[knowledge.Arg("len.v")], ident) - } - - fn := func(node ast.Node) { - var pkg string - var fun string - - ifstmt := node.(*ast.IfStmt) - if ifstmt.Init != nil { - return - } - if ifstmt.Else != nil { - return - } - if len(ifstmt.Body.List) != 1 { - return - } - condCall, ok := ifstmt.Cond.(*ast.CallExpr) - if !ok { - return - } - - condCallName := code.CallName(pass, condCall) - switch condCallName { - case "strings.HasPrefix": - pkg = "strings" - fun = "HasPrefix" - case "strings.HasSuffix": - pkg = "strings" - fun = "HasSuffix" - case "strings.Contains": - pkg = "strings" - fun = "Contains" - case "bytes.HasPrefix": - pkg = "bytes" - fun = "HasPrefix" - case "bytes.HasSuffix": - pkg = "bytes" - fun = "HasSuffix" - case "bytes.Contains": - pkg = "bytes" - fun = "Contains" - default: - return - } - - assign, ok := ifstmt.Body.List[0].(*ast.AssignStmt) - if !ok { - return - } - if assign.Tok != token.ASSIGN { - return - } - if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { - return - } - if !sameNonDynamic(condCall.Args[0], assign.Lhs[0]) { - return - } - - switch rhs := assign.Rhs[0].(type) { - case *ast.CallExpr: - if len(rhs.Args) < 2 || !sameNonDynamic(condCall.Args[0], rhs.Args[0]) || !sameNonDynamic(condCall.Args[1], rhs.Args[1]) { - return - } - - rhsName := code.CallName(pass, rhs) - if condCallName == "strings.HasPrefix" && rhsName == "strings.TrimPrefix" || - condCallName == "strings.HasSuffix" && rhsName == "strings.TrimSuffix" || - condCallName == "strings.Contains" && rhsName == "strings.Replace" || - condCallName == "bytes.HasPrefix" && rhsName == "bytes.TrimPrefix" || - condCallName == "bytes.HasSuffix" && rhsName == "bytes.TrimSuffix" || - condCallName == "bytes.Contains" && rhsName == "bytes.Replace" { - report.Report(pass, ifstmt, fmt.Sprintf("should replace this if statement with an unconditional %s", rhsName), report.FilterGenerated()) - } - case *ast.SliceExpr: - slice := rhs - if !ok { - return - } - if slice.Slice3 { - return - } - if !sameNonDynamic(slice.X, condCall.Args[0]) { - return - } - - validateOffset := func(off ast.Expr) bool { - switch off := off.(type) { - case *ast.CallExpr: - return isLenOnIdent(off, condCall.Args[1]) - case *ast.BasicLit: - if pkg != "strings" { - return false - } - if _, ok := condCall.Args[1].(*ast.BasicLit); !ok { - // Only allow manual slicing with an integer - // literal if the second argument to HasPrefix - // was a string literal. - return false - } - s, ok1 := code.ExprToString(pass, condCall.Args[1]) - n, ok2 := code.ExprToInt(pass, off) - if !ok1 || !ok2 || n != int64(len(s)) { - return false - } - return true - default: - return false - } - } - - switch fun { - case "HasPrefix": - // TODO(dh) We could detect a High that is len(s), but another - // rule will already flag that, anyway. - if slice.High != nil { - return - } - if !validateOffset(slice.Low) { - return - } - case "HasSuffix": - if slice.Low != nil { - n, ok := code.ExprToInt(pass, slice.Low) - if !ok || n != 0 { - return - } - } - switch index := slice.High.(type) { - case *ast.BinaryExpr: - if index.Op != token.SUB { - return - } - if !isLenOnIdent(index.X, condCall.Args[0]) { - return - } - if !validateOffset(index.Y) { - return - } - default: - return - } - default: - return - } - - var replacement string - switch fun { - case "HasPrefix": - replacement = "TrimPrefix" - case "HasSuffix": - replacement = "TrimSuffix" - } - report.Report(pass, ifstmt, fmt.Sprintf("should replace this if statement with an unconditional %s.%s", pkg, replacement), - report.ShortRange(), - report.FilterGenerated()) - } - } - code.Preorder(pass, fn, (*ast.IfStmt)(nil)) - return nil, nil -} - -var ( - checkLoopSlideQ = pattern.MustParse(` - (ForStmt - (AssignStmt initvar@(Ident _) _ (IntegerLiteral "0")) - (BinaryExpr initvar "<" limit@(Ident _)) - (IncDecStmt initvar "++") - [(AssignStmt - (IndexExpr slice@(Ident _) initvar) - "=" - (IndexExpr slice (BinaryExpr offset@(Ident _) "+" initvar)))])`) - checkLoopSlideR = pattern.MustParse(` - (CallExpr - (Ident "copy") - [(SliceExpr slice nil limit nil) - (SliceExpr slice offset nil nil)])`) -) - -func CheckLoopSlide(pass *analysis.Pass) (interface{}, error) { - // TODO(dh): detect bs[i+offset] in addition to bs[offset+i] - // TODO(dh): consider merging this function with LintLoopCopy - // TODO(dh): detect length that is an expression, not a variable name - // TODO(dh): support sliding to a different offset than the beginning of the slice - - fn := func(node ast.Node) { - loop := node.(*ast.ForStmt) - m, edits, ok := code.MatchAndEdit(pass, checkLoopSlideQ, checkLoopSlideR, loop) - if !ok { - return - } - typ := pass.TypesInfo.TypeOf(m.State["slice"].(*ast.Ident)) - // The pattern probably needs a core type, but All is fine, too. Either way we only accept slices. - if !typeutil.All(typ, typeutil.IsSlice) { - return - } - - report.Report(pass, loop, "should use copy() instead of loop for sliding slice elements", - report.ShortRange(), - report.FilterGenerated(), - report.Fixes(edit.Fix("use copy() instead of loop", edits...))) - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil)) - return nil, nil -} - -var ( - checkMakeLenCapQ1 = pattern.MustParse(`(CallExpr (Builtin "make") [typ size@(IntegerLiteral "0")])`) - checkMakeLenCapQ2 = pattern.MustParse(`(CallExpr (Builtin "make") [typ size size])`) -) - -func CheckMakeLenCap(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if pass.Pkg.Path() == "runtime_test" && filepath.Base(pass.Fset.Position(node.Pos()).Filename) == "map_test.go" { - // special case of runtime tests testing map creation - return - } - if m, ok := code.Match(pass, checkMakeLenCapQ1, node); ok { - T := m.State["typ"].(ast.Expr) - size := m.State["size"].(ast.Node) - - if _, ok := typeutil.CoreType(pass.TypesInfo.TypeOf(T)).Underlying().(*types.Chan); ok { - report.Report(pass, size, fmt.Sprintf("should use make(%s) instead", report.Render(pass, T)), report.FilterGenerated()) - } - - } else if m, ok := code.Match(pass, checkMakeLenCapQ2, node); ok { - // TODO(dh): don't consider sizes identical if they're - // dynamic. for example: make(T, <-ch, <-ch). - T := m.State["typ"].(ast.Expr) - size := m.State["size"].(ast.Node) - report.Report(pass, size, - fmt.Sprintf("should use make(%s, %s) instead", report.Render(pass, T), report.Render(pass, size)), - report.FilterGenerated()) - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var ( - checkAssertNotNilFn1Q = pattern.MustParse(` - (IfStmt - (AssignStmt [(Ident "_") ok@(Object _)] _ [(TypeAssertExpr assert@(Object _) _)]) - (Or - (BinaryExpr ok "&&" (BinaryExpr assert "!=" (Builtin "nil"))) - (BinaryExpr (BinaryExpr assert "!=" (Builtin "nil")) "&&" ok)) - _ - _)`) - checkAssertNotNilFn2Q = pattern.MustParse(` - (IfStmt - nil - (BinaryExpr lhs@(Object _) "!=" (Builtin "nil")) - [ - ifstmt@(IfStmt - (AssignStmt [(Ident "_") ok@(Object _)] _ [(TypeAssertExpr lhs _)]) - ok - _ - nil) - ] - nil)`) -) - -func CheckAssertNotNil(pass *analysis.Pass) (interface{}, error) { - fn1 := func(node ast.Node) { - m, ok := code.Match(pass, checkAssertNotNilFn1Q, node) - if !ok { - return - } - assert := m.State["assert"].(types.Object) - assign := m.State["ok"].(types.Object) - report.Report(pass, node, fmt.Sprintf("when %s is true, %s can't be nil", assign.Name(), assert.Name()), - report.ShortRange(), - report.FilterGenerated()) - } - fn2 := func(node ast.Node) { - m, ok := code.Match(pass, checkAssertNotNilFn2Q, node) - if !ok { - return - } - ifstmt := m.State["ifstmt"].(*ast.IfStmt) - lhs := m.State["lhs"].(types.Object) - assignIdent := m.State["ok"].(types.Object) - report.Report(pass, ifstmt, fmt.Sprintf("when %s is true, %s can't be nil", assignIdent.Name(), lhs.Name()), - report.ShortRange(), - report.FilterGenerated()) - } - // OPT(dh): merge fn1 and fn2 - code.Preorder(pass, fn1, (*ast.IfStmt)(nil)) - code.Preorder(pass, fn2, (*ast.IfStmt)(nil)) - return nil, nil -} - -func CheckDeclareAssign(pass *analysis.Pass) (interface{}, error) { - hasMultipleAssignments := func(root ast.Node, ident *ast.Ident) bool { - num := 0 - ast.Inspect(root, func(node ast.Node) bool { - if num >= 2 { - return false - } - assign, ok := node.(*ast.AssignStmt) - if !ok { - return true - } - for _, lhs := range assign.Lhs { - if oident, ok := lhs.(*ast.Ident); ok { - if pass.TypesInfo.ObjectOf(oident) == pass.TypesInfo.ObjectOf(ident) { - num++ - } - } - } - - return true - }) - return num >= 2 - } - fn := func(node ast.Node) { - block := node.(*ast.BlockStmt) - if len(block.List) < 2 { - return - } - for i, stmt := range block.List[:len(block.List)-1] { - _ = i - decl, ok := stmt.(*ast.DeclStmt) - if !ok { - continue - } - gdecl, ok := decl.Decl.(*ast.GenDecl) - if !ok || gdecl.Tok != token.VAR || len(gdecl.Specs) != 1 { - continue - } - vspec, ok := gdecl.Specs[0].(*ast.ValueSpec) - if !ok || len(vspec.Names) != 1 || len(vspec.Values) != 0 { - continue - } - - assign, ok := block.List[i+1].(*ast.AssignStmt) - if !ok || assign.Tok != token.ASSIGN { - continue - } - if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { - continue - } - ident, ok := assign.Lhs[0].(*ast.Ident) - if !ok { - continue - } - if pass.TypesInfo.ObjectOf(vspec.Names[0]) != pass.TypesInfo.ObjectOf(ident) { - continue - } - - if refersTo(pass, assign.Rhs[0], pass.TypesInfo.ObjectOf(ident)) { - continue - } - if hasMultipleAssignments(block, ident) { - continue - } - - r := &ast.GenDecl{ - Specs: []ast.Spec{ - &ast.ValueSpec{ - Names: vspec.Names, - Values: []ast.Expr{assign.Rhs[0]}, - Type: vspec.Type, - }, - }, - Tok: gdecl.Tok, - } - report.Report(pass, decl, "should merge variable declaration with assignment on next line", - report.FilterGenerated(), - report.Fixes(edit.Fix("merge declaration with assignment", edit.ReplaceWithNode(pass.Fset, edit.Range{decl.Pos(), assign.End()}, r)))) - } - } - code.Preorder(pass, fn, (*ast.BlockStmt)(nil)) - return nil, nil -} - -func CheckRedundantBreak(pass *analysis.Pass) (interface{}, error) { - fn1 := func(node ast.Node) { - clause := node.(*ast.CaseClause) - if len(clause.Body) < 2 { - return - } - branch, ok := clause.Body[len(clause.Body)-1].(*ast.BranchStmt) - if !ok || branch.Tok != token.BREAK || branch.Label != nil { - return - } - report.Report(pass, branch, "redundant break statement", report.FilterGenerated()) - } - fn2 := func(node ast.Node) { - var ret *ast.FieldList - var body *ast.BlockStmt - switch x := node.(type) { - case *ast.FuncDecl: - ret = x.Type.Results - body = x.Body - case *ast.FuncLit: - ret = x.Type.Results - body = x.Body - default: - lint.ExhaustiveTypeSwitch(node) - } - // if the func has results, a return can't be redundant. - // similarly, if there are no statements, there can be - // no return. - if ret != nil || body == nil || len(body.List) < 1 { - return - } - rst, ok := body.List[len(body.List)-1].(*ast.ReturnStmt) - if !ok { - return - } - // we don't need to check rst.Results as we already - // checked x.Type.Results to be nil. - report.Report(pass, rst, "redundant return statement", report.FilterGenerated()) - } - code.Preorder(pass, fn1, (*ast.CaseClause)(nil)) - code.Preorder(pass, fn2, (*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) - return nil, nil -} - -func isFormatter(T types.Type, msCache *typeutil.MethodSetCache) bool { - // TODO(dh): this function also exists in staticcheck/lint.go – deduplicate. - - ms := msCache.MethodSet(T) - sel := ms.Lookup(nil, "Format") - if sel == nil { - return false - } - fn, ok := sel.Obj().(*types.Func) - if !ok { - // should be unreachable - return false - } - sig := fn.Type().(*types.Signature) - if sig.Params().Len() != 2 { - return false - } - // TODO(dh): check the types of the arguments for more - // precision - if sig.Results().Len() != 0 { - return false - } - return true -} - -var checkRedundantSprintfQ = pattern.MustParse(`(CallExpr (Symbol "fmt.Sprintf") [format arg])`) - -func CheckRedundantSprintf(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkRedundantSprintfQ, node) - if !ok { - return - } - - format := m.State["format"].(ast.Expr) - arg := m.State["arg"].(ast.Expr) - // TODO(dh): should we really support named constants here? - // shouldn't we only look for string literals? to avoid false - // positives via build tags? - if s, ok := code.ExprToString(pass, format); !ok || s != "%s" { - return - } - typ := pass.TypesInfo.TypeOf(arg) - if typeparams.IsTypeParam(typ) { - return - } - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg - - if types.TypeString(typ, nil) == "reflect.Value" { - // printing with %s produces output different from using - // the String method - return - } - - if isFormatter(typ, &irpkg.Prog.MethodSets) { - // the type may choose to handle %s in arbitrary ways - return - } - - if types.Implements(typ, knowledge.Interfaces["fmt.Stringer"]) { - replacement := &ast.CallExpr{ - Fun: &ast.SelectorExpr{ - X: arg, - Sel: &ast.Ident{Name: "String"}, - }, - } - report.Report(pass, node, "should use String() instead of fmt.Sprintf", - report.Fixes(edit.Fix("replace with call to String method", edit.ReplaceWithNode(pass.Fset, node, replacement)))) - } else if typ == types.Universe.Lookup("string").Type() { - report.Report(pass, node, "the argument is already a string, there's no need to use fmt.Sprintf", - report.FilterGenerated(), - report.Fixes(edit.Fix("remove unnecessary call to fmt.Sprintf", edit.ReplaceWithNode(pass.Fset, node, arg)))) - } else if typ.Underlying() == types.Universe.Lookup("string").Type() { - replacement := &ast.CallExpr{ - Fun: &ast.Ident{Name: "string"}, - Args: []ast.Expr{arg}, - } - report.Report(pass, node, "the argument's underlying type is a string, should use a simple conversion instead of fmt.Sprintf", - report.FilterGenerated(), - report.Fixes(edit.Fix("replace with conversion to string", edit.ReplaceWithNode(pass.Fset, node, replacement)))) - } else if slice, ok := typ.Underlying().(*types.Slice); ok && slice.Elem() == types.Universe.Lookup("byte").Type() { - // Note that we check slice.Elem(), not slice.Elem().Underlying, because of https://github.com/golang/go/issues/23536 - replacement := &ast.CallExpr{ - Fun: &ast.Ident{Name: "string"}, - Args: []ast.Expr{arg}, - } - report.Report(pass, node, "the argument's underlying type is a slice of bytes, should use a simple conversion instead of fmt.Sprintf", - report.FilterGenerated(), - report.Fixes(edit.Fix("replace with conversion to string", edit.ReplaceWithNode(pass.Fset, node, replacement)))) - } - - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var ( - checkErrorsNewSprintfQ = pattern.MustParse(`(CallExpr (Symbol "errors.New") [(CallExpr (Symbol "fmt.Sprintf") args)])`) - checkErrorsNewSprintfR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "fmt") (Ident "Errorf")) args)`) -) - -func CheckErrorsNewSprintf(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if _, edits, ok := code.MatchAndEdit(pass, checkErrorsNewSprintfQ, checkErrorsNewSprintfR, node); ok { - // TODO(dh): the suggested fix may leave an unused import behind - report.Report(pass, node, "should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...))", - report.FilterGenerated(), - report.Fixes(edit.Fix("use fmt.Errorf", edits...))) - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { - return sharedcheck.CheckRangeStringRunes(pass) -} - -var checkNilCheckAroundRangeQ = pattern.MustParse(` - (IfStmt - nil - (BinaryExpr x@(Object _) "!=" (Builtin "nil")) - [(RangeStmt _ _ _ x _)] - nil)`) - -func CheckNilCheckAroundRange(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkNilCheckAroundRangeQ, node) - if !ok { - return - } - ok = typeutil.All(m.State["x"].(types.Object).Type(), func(term *types.Term) bool { - switch term.Type().Underlying().(type) { - case *types.Slice, *types.Map: - return true - case *types.TypeParam, *types.Chan, *types.Pointer: - return false - default: - lint.ExhaustiveTypeSwitch(term.Type().Underlying()) - return false - } - }) - if !ok { - return - } - report.Report(pass, node, "unnecessary nil check around range", report.ShortRange(), report.FilterGenerated()) - } - code.Preorder(pass, fn, (*ast.IfStmt)(nil)) - return nil, nil -} - -func isPermissibleSort(pass *analysis.Pass, node ast.Node) bool { - call := node.(*ast.CallExpr) - typeconv, ok := call.Args[0].(*ast.CallExpr) - if !ok { - return true - } - - sel, ok := typeconv.Fun.(*ast.SelectorExpr) - if !ok { - return true - } - name := code.SelectorName(pass, sel) - switch name { - case "sort.IntSlice", "sort.Float64Slice", "sort.StringSlice": - default: - return true - } - - return false -} - -func CheckSortHelpers(pass *analysis.Pass) (interface{}, error) { - type Error struct { - node ast.Node - msg string - } - var allErrors []Error - fn := func(node ast.Node) { - var body *ast.BlockStmt - switch node := node.(type) { - case *ast.FuncLit: - body = node.Body - case *ast.FuncDecl: - body = node.Body - default: - lint.ExhaustiveTypeSwitch(node) - } - if body == nil { - return - } - - var errors []Error - permissible := false - fnSorts := func(node ast.Node) bool { - if permissible { - return false - } - if !code.IsCallTo(pass, node, "sort.Sort") { - return true - } - if isPermissibleSort(pass, node) { - permissible = true - return false - } - call := node.(*ast.CallExpr) - // isPermissibleSort guarantees that this type assertion will succeed - typeconv := call.Args[knowledge.Arg("sort.Sort.data")].(*ast.CallExpr) - sel := typeconv.Fun.(*ast.SelectorExpr) - name := code.SelectorName(pass, sel) - - switch name { - case "sort.IntSlice": - errors = append(errors, Error{node, "should use sort.Ints(...) instead of sort.Sort(sort.IntSlice(...))"}) - case "sort.Float64Slice": - errors = append(errors, Error{node, "should use sort.Float64s(...) instead of sort.Sort(sort.Float64Slice(...))"}) - case "sort.StringSlice": - errors = append(errors, Error{node, "should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...))"}) - } - return true - } - ast.Inspect(body, fnSorts) - - if permissible { - return - } - allErrors = append(allErrors, errors...) - } - code.Preorder(pass, fn, (*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)) - sort.Slice(allErrors, func(i, j int) bool { - return allErrors[i].node.Pos() < allErrors[j].node.Pos() - }) - var prev token.Pos - for _, err := range allErrors { - if err.node.Pos() == prev { - continue - } - prev = err.node.Pos() - report.Report(pass, err.node, err.msg, report.FilterGenerated()) - } - return nil, nil -} - -var checkGuardedDeleteQ = pattern.MustParse(` - (IfStmt - (AssignStmt - [(Ident "_") ok@(Ident _)] - ":=" - (IndexExpr m key)) - ok - [call@(CallExpr (Builtin "delete") [m key])] - nil)`) - -func CheckGuardedDelete(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if m, ok := code.Match(pass, checkGuardedDeleteQ, node); ok { - report.Report(pass, node, "unnecessary guard around call to delete", - report.ShortRange(), - report.FilterGenerated(), - report.Fixes(edit.Fix("remove guard", edit.ReplaceWithNode(pass.Fset, node, m.State["call"].(ast.Node))))) - } - } - - code.Preorder(pass, fn, (*ast.IfStmt)(nil)) - return nil, nil -} - -var ( - checkSimplifyTypeSwitchQ = pattern.MustParse(` - (TypeSwitchStmt - nil - expr@(TypeAssertExpr ident@(Ident _) _) - body)`) - checkSimplifyTypeSwitchR = pattern.MustParse(`(AssignStmt ident ":=" expr)`) -) - -func CheckSimplifyTypeSwitch(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkSimplifyTypeSwitchQ, node) - if !ok { - return - } - stmt := node.(*ast.TypeSwitchStmt) - expr := m.State["expr"].(ast.Node) - ident := m.State["ident"].(*ast.Ident) - - x := pass.TypesInfo.ObjectOf(ident) - var allOffenders []*ast.TypeAssertExpr - canSuggestFix := true - for _, clause := range stmt.Body.List { - clause := clause.(*ast.CaseClause) - if len(clause.List) != 1 { - continue - } - hasUnrelatedAssertion := false - var offenders []*ast.TypeAssertExpr - ast.Inspect(clause, func(node ast.Node) bool { - assert2, ok := node.(*ast.TypeAssertExpr) - if !ok { - return true - } - ident, ok := assert2.X.(*ast.Ident) - if !ok { - hasUnrelatedAssertion = true - return false - } - if pass.TypesInfo.ObjectOf(ident) != x { - hasUnrelatedAssertion = true - return false - } - - if !types.Identical(pass.TypesInfo.TypeOf(clause.List[0]), pass.TypesInfo.TypeOf(assert2.Type)) { - hasUnrelatedAssertion = true - return false - } - offenders = append(offenders, assert2) - return true - }) - if !hasUnrelatedAssertion { - // don't flag cases that have other type assertions - // unrelated to the one in the case clause. often - // times, this is done for symmetry, when two - // different values have to be asserted to the same - // type. - allOffenders = append(allOffenders, offenders...) - } - canSuggestFix = canSuggestFix && !hasUnrelatedAssertion - } - if len(allOffenders) != 0 { - var opts []report.Option - for _, offender := range allOffenders { - opts = append(opts, report.Related(offender, "could eliminate this type assertion")) - } - opts = append(opts, report.FilterGenerated()) - - msg := fmt.Sprintf("assigning the result of this type assertion to a variable (switch %s := %s.(type)) could eliminate type assertions in switch cases", - report.Render(pass, ident), report.Render(pass, ident)) - if canSuggestFix { - var edits []analysis.TextEdit - edits = append(edits, edit.ReplaceWithPattern(pass.Fset, expr, checkSimplifyTypeSwitchR, m.State)) - for _, offender := range allOffenders { - edits = append(edits, edit.ReplaceWithNode(pass.Fset, offender, offender.X)) - } - opts = append(opts, report.Fixes(edit.Fix("simplify type switch", edits...))) - report.Report(pass, expr, msg, opts...) - } else { - report.Report(pass, expr, msg, opts...) - } - } - } - code.Preorder(pass, fn, (*ast.TypeSwitchStmt)(nil)) - return nil, nil -} - -func CheckRedundantCanonicalHeaderKey(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - callName := code.CallName(pass, call) - switch callName { - case "(net/http.Header).Add", "(net/http.Header).Del", "(net/http.Header).Get", "(net/http.Header).Set": - default: - return - } - - if !code.IsCallTo(pass, call.Args[0], "net/http.CanonicalHeaderKey") { - return - } - - report.Report(pass, call, - fmt.Sprintf("calling net/http.CanonicalHeaderKey on the 'key' argument of %s is redundant", callName), - report.FilterGenerated(), - report.Fixes(edit.Fix("remove call to CanonicalHeaderKey", edit.ReplaceWithNode(pass.Fset, call.Args[0], call.Args[0].(*ast.CallExpr).Args[0])))) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var checkUnnecessaryGuardQ = pattern.MustParse(` - (Or - (IfStmt - (AssignStmt [(Ident "_") ok@(Ident _)] ":=" indexexpr@(IndexExpr _ _)) - ok - set@(AssignStmt indexexpr "=" (CallExpr (Builtin "append") indexexpr:values)) - (AssignStmt indexexpr "=" (CompositeLit _ values))) - (IfStmt - (AssignStmt [(Ident "_") ok] ":=" indexexpr@(IndexExpr _ _)) - ok - set@(AssignStmt indexexpr "+=" value) - (AssignStmt indexexpr "=" value)) - (IfStmt - (AssignStmt [(Ident "_") ok] ":=" indexexpr@(IndexExpr _ _)) - ok - set@(IncDecStmt indexexpr "++") - (AssignStmt indexexpr "=" (IntegerLiteral "1"))))`) - -func CheckUnnecessaryGuard(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if m, ok := code.Match(pass, checkUnnecessaryGuardQ, node); ok { - if code.MayHaveSideEffects(pass, m.State["indexexpr"].(ast.Expr), nil) { - return - } - report.Report(pass, node, "unnecessary guard around map access", - report.ShortRange(), - report.Fixes(edit.Fix("simplify map access", edit.ReplaceWithNode(pass.Fset, node, m.State["set"].(ast.Node))))) - } - } - code.Preorder(pass, fn, (*ast.IfStmt)(nil)) - return nil, nil -} - -var ( - checkElaborateSleepQ = pattern.MustParse(`(SelectStmt (CommClause (UnaryExpr "<-" (CallExpr (Symbol "time.After") [arg])) body))`) - checkElaborateSleepR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Sleep")) [arg])`) -) - -func CheckElaborateSleep(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if m, ok := code.Match(pass, checkElaborateSleepQ, node); ok { - if body, ok := m.State["body"].([]ast.Stmt); ok && len(body) == 0 { - report.Report(pass, node, "should use time.Sleep instead of elaborate way of sleeping", - report.ShortRange(), - report.FilterGenerated(), - report.Fixes(edit.Fix("Use time.Sleep", edit.ReplaceWithPattern(pass.Fset, node, checkElaborateSleepR, m.State)))) - } else { - // TODO(dh): we could make a suggested fix if the body - // doesn't declare or shadow any identifiers - report.Report(pass, node, "should use time.Sleep instead of elaborate way of sleeping", - report.ShortRange(), - report.FilterGenerated()) - } - } - } - code.Preorder(pass, fn, (*ast.SelectStmt)(nil)) - return nil, nil -} - -var ( - checkPrintSprintQ = pattern.MustParse(` - (Or - (CallExpr - fn@(Or - (Symbol "fmt.Print") - (Symbol "fmt.Sprint") - (Symbol "fmt.Println") - (Symbol "fmt.Sprintln")) - [(CallExpr (Symbol "fmt.Sprintf") f:_)]) - (CallExpr - fn@(Or - (Symbol "fmt.Fprint") - (Symbol "fmt.Fprintln")) - [_ (CallExpr (Symbol "fmt.Sprintf") f:_)]))`) - - checkTestingErrorSprintfQ = pattern.MustParse(` - (CallExpr - sel@(SelectorExpr - recv - (Ident - name@(Or - "Error" - "Fatal" - "Fatalln" - "Log" - "Panic" - "Panicln" - "Print" - "Println" - "Skip"))) - [(CallExpr (Symbol "fmt.Sprintf") args)])`) - - checkLogSprintfQ = pattern.MustParse(` - (CallExpr - (Symbol - (Or - "log.Fatal" - "log.Fatalln" - "log.Panic" - "log.Panicln" - "log.Print" - "log.Println")) - [(CallExpr (Symbol "fmt.Sprintf") args)])`) - - checkSprintfMapping = map[string]struct { - recv string - alternative string - }{ - "(*testing.common).Error": {"(*testing.common)", "Errorf"}, - "(testing.TB).Error": {"(testing.TB)", "Errorf"}, - "(*testing.common).Fatal": {"(*testing.common)", "Fatalf"}, - "(testing.TB).Fatal": {"(testing.TB)", "Fatalf"}, - "(*testing.common).Log": {"(*testing.common)", "Logf"}, - "(testing.TB).Log": {"(testing.TB)", "Logf"}, - "(*testing.common).Skip": {"(*testing.common)", "Skipf"}, - "(testing.TB).Skip": {"(testing.TB)", "Skipf"}, - "(*log.Logger).Fatal": {"(*log.Logger)", "Fatalf"}, - "(*log.Logger).Fatalln": {"(*log.Logger)", "Fatalf"}, - "(*log.Logger).Panic": {"(*log.Logger)", "Panicf"}, - "(*log.Logger).Panicln": {"(*log.Logger)", "Panicf"}, - "(*log.Logger).Print": {"(*log.Logger)", "Printf"}, - "(*log.Logger).Println": {"(*log.Logger)", "Printf"}, - "log.Fatal": {"", "log.Fatalf"}, - "log.Fatalln": {"", "log.Fatalf"}, - "log.Panic": {"", "log.Panicf"}, - "log.Panicln": {"", "log.Panicf"}, - "log.Print": {"", "log.Printf"}, - "log.Println": {"", "log.Printf"}, - } -) - -func CheckPrintSprintf(pass *analysis.Pass) (interface{}, error) { - fmtPrintf := func(node ast.Node) { - m, ok := code.Match(pass, checkPrintSprintQ, node) - if !ok { - return - } - - name := m.State["fn"].(*types.Func).Name() - var msg string - switch name { - case "Print", "Fprint", "Sprint": - newname := name + "f" - msg = fmt.Sprintf("should use fmt.%s instead of fmt.%s(fmt.Sprintf(...))", newname, name) - case "Println", "Fprintln", "Sprintln": - if _, ok := m.State["f"].(*ast.BasicLit); !ok { - // This may be an instance of - // fmt.Println(fmt.Sprintf(arg, ...)) where arg is an - // externally provided format string and the caller - // cannot guarantee that the format string ends with a - // newline. - return - } - newname := name[:len(name)-2] + "f" - msg = fmt.Sprintf("should use fmt.%s instead of fmt.%s(fmt.Sprintf(...)) (but don't forget the newline)", newname, name) - } - report.Report(pass, node, msg, - report.FilterGenerated()) - } - - methSprintf := func(node ast.Node) { - m, ok := code.Match(pass, checkTestingErrorSprintfQ, node) - if !ok { - return - } - mapped, ok := checkSprintfMapping[code.CallName(pass, node.(*ast.CallExpr))] - if !ok { - return - } - - // Ensure that Errorf/Fatalf refer to the right method - recvTV, ok := pass.TypesInfo.Types[m.State["recv"].(ast.Expr)] - if !ok { - return - } - obj, _, _ := types.LookupFieldOrMethod(recvTV.Type, recvTV.Addressable(), nil, mapped.alternative) - f, ok := obj.(*types.Func) - if !ok { - return - } - if typeutil.FuncName(f) != mapped.recv+"."+mapped.alternative { - return - } - - alt := &ast.SelectorExpr{ - X: m.State["recv"].(ast.Expr), - Sel: &ast.Ident{Name: mapped.alternative}, - } - report.Report(pass, node, fmt.Sprintf("should use %s(...) instead of %s(fmt.Sprintf(...))", report.Render(pass, alt), report.Render(pass, m.State["sel"].(*ast.SelectorExpr)))) - } - - pkgSprintf := func(node ast.Node) { - _, ok := code.Match(pass, checkLogSprintfQ, node) - if !ok { - return - } - callName := code.CallName(pass, node.(*ast.CallExpr)) - mapped, ok := checkSprintfMapping[callName] - if !ok { - return - } - report.Report(pass, node, fmt.Sprintf("should use %s(...) instead of %s(fmt.Sprintf(...))", mapped.alternative, callName)) - } - - fn := func(node ast.Node) { - fmtPrintf(node) - // TODO(dh): add suggested fixes - methSprintf(node) - pkgSprintf(node) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var checkSprintLiteralQ = pattern.MustParse(` - (CallExpr - fn@(Or - (Symbol "fmt.Sprint") - (Symbol "fmt.Sprintf")) - [lit@(BasicLit "STRING" _)])`) - -func CheckSprintLiteral(pass *analysis.Pass) (interface{}, error) { - // We only flag calls with string literals, not expressions of - // type string, because some people use fmt.Sprint(s) as a pattern - // for copying strings, which may be useful when extracting a small - // substring from a large string. - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkSprintLiteralQ, node) - if !ok { - return - } - callee := m.State["fn"].(*types.Func) - lit := m.State["lit"].(*ast.BasicLit) - if callee.Name() == "Sprintf" { - if strings.ContainsRune(lit.Value, '%') { - // This might be a format string - return - } - } - report.Report(pass, node, fmt.Sprintf("unnecessary use of fmt.%s", callee.Name()), - report.FilterGenerated(), - report.Fixes(edit.Fix("Replace with string literal", edit.ReplaceWithNode(pass.Fset, node, lit)))) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckSameTypeTypeAssertion(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - expr := node.(*ast.TypeAssertExpr) - if expr.Type == nil { - // skip type switches - // - // TODO(dh): we could flag type switches, too, when a case - // statement has the same type as expr.X – however, - // depending on the location of that case, it might behave - // identically to a default branch. we need to think - // carefully about the instances we want to flag. We also - // have to take nil interface values into consideration. - // - // It might make more sense to extend SA4020 to handle - // this. - return - } - t1 := pass.TypesInfo.TypeOf(expr.Type) - t2 := pass.TypesInfo.TypeOf(expr.X) - if types.IsInterface(t1) && types.Identical(t1, t2) { - report.Report(pass, expr, - fmt.Sprintf("type assertion to the same type: %s already has type %s", report.Render(pass, expr.X), report.Render(pass, expr.Type)), - report.FilterGenerated()) - } - } - - // TODO(dh): add suggested fixes. we need different fixes depending on the context: - // - assignment with 1 or 2 lhs - // - assignment to blank identifiers (as the first, second or both lhs) - // - initializers in if statements, with the same variations as above - - code.Preorder(pass, fn, (*ast.TypeAssertExpr)(nil)) - return nil, nil -} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1000/s1000.go b/tools/vendor/honnef.co/go/tools/simple/s1000/s1000.go new file mode 100644 index 000000000..c5b9a1408 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1000/s1000.go @@ -0,0 +1,71 @@ +package s1000 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1000", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use plain channel send or receive instead of single-case select`, + Text: `Select statements with a single case can be replaced with a simple +send or receive.`, + Before: ` +select { +case x := <-ch: + fmt.Println(x) +}`, + After: ` +x := <-ch +fmt.Println(x) +`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkSingleCaseSelectQ1 = pattern.MustParse(` + (ForStmt + nil nil nil + select@(SelectStmt + (CommClause + (Or + (UnaryExpr "<-" _) + (AssignStmt _ _ (UnaryExpr "<-" _))) + _)))`) + checkSingleCaseSelectQ2 = pattern.MustParse(`(SelectStmt (CommClause _ _))`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + seen := map[ast.Node]struct{}{} + fn := func(node ast.Node) { + if m, ok := code.Match(pass, checkSingleCaseSelectQ1, node); ok { + seen[m.State["select"].(ast.Node)] = struct{}{} + report.Report(pass, node, "should use for range instead of for { select {} }", report.FilterGenerated()) + } else if _, ok := code.Match(pass, checkSingleCaseSelectQ2, node); ok { + if _, ok := seen[node]; !ok { + report.Report(pass, node, "should use a simple channel send/receive instead of select with a single case", + report.ShortRange(), + report.FilterGenerated()) + } + } + } + code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.SelectStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1001/s1001.go b/tools/vendor/honnef.co/go/tools/simple/s1001/s1001.go new file mode 100644 index 000000000..889227cd8 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1001/s1001.go @@ -0,0 +1,197 @@ +package s1001 + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1001", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Replace for loop with call to copy`, + Text: ` +Use \'copy()\' for copying elements from one slice to another. For +arrays of identical size, you can use simple assignment.`, + Before: ` +for i, x := range src { + dst[i] = x +}`, + After: `copy(dst, src)`, + Since: "2017.1", + // MergeIfAll because the types of src and dst might be different under different build tags. + // You shouldn't write code like that… + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkLoopCopyQ = pattern.MustParse(` + (Or + (RangeStmt + key@(Ident _) value@(Ident _) ":=" src + [(AssignStmt (IndexExpr dst key) "=" value)]) + (RangeStmt + key@(Ident _) nil ":=" src + [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))]) + (ForStmt + (AssignStmt key@(Ident _) ":=" (IntegerLiteral "0")) + (BinaryExpr key "<" (CallExpr (Symbol "len") [src])) + (IncDecStmt key "++") + [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))]))`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + // TODO revisit once range doesn't require a structural type + + isInvariant := func(k, v types.Object, node ast.Expr) bool { + if code.MayHaveSideEffects(pass, node, nil) { + return false + } + invariant := true + ast.Inspect(node, func(node ast.Node) bool { + if node, ok := node.(*ast.Ident); ok { + obj := pass.TypesInfo.ObjectOf(node) + if obj == k || obj == v { + // don't allow loop bodies like 'a[i][i] = v' + invariant = false + return false + } + } + return true + }) + return invariant + } + + var elType func(T types.Type) (el types.Type, isArray bool, isArrayPointer bool, ok bool) + elType = func(T types.Type) (el types.Type, isArray bool, isArrayPointer bool, ok bool) { + switch typ := T.Underlying().(type) { + case *types.Slice: + return typ.Elem(), false, false, true + case *types.Array: + return typ.Elem(), true, false, true + case *types.Pointer: + el, isArray, _, ok = elType(typ.Elem()) + return el, isArray, true, ok + default: + return nil, false, false, false + } + } + + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkLoopCopyQ, node) + if !ok { + return + } + + src := m.State["src"].(ast.Expr) + dst := m.State["dst"].(ast.Expr) + + k := pass.TypesInfo.ObjectOf(m.State["key"].(*ast.Ident)) + var v types.Object + if value, ok := m.State["value"]; ok { + v = pass.TypesInfo.ObjectOf(value.(*ast.Ident)) + } + if !isInvariant(k, v, dst) { + return + } + if !isInvariant(k, v, src) { + // For example: 'for i := range foo()' + return + } + + Tsrc := pass.TypesInfo.TypeOf(src) + Tdst := pass.TypesInfo.TypeOf(dst) + TsrcElem, TsrcArray, TsrcPointer, ok := elType(Tsrc) + if !ok { + return + } + if TsrcPointer { + Tsrc = Tsrc.Underlying().(*types.Pointer).Elem() + } + TdstElem, TdstArray, TdstPointer, ok := elType(Tdst) + if !ok { + return + } + if TdstPointer { + Tdst = Tdst.Underlying().(*types.Pointer).Elem() + } + + if !types.Identical(TsrcElem, TdstElem) { + return + } + + if TsrcArray && TdstArray && types.Identical(Tsrc, Tdst) { + if TsrcPointer { + src = &ast.StarExpr{ + X: src, + } + } + if TdstPointer { + dst = &ast.StarExpr{ + X: dst, + } + } + r := &ast.AssignStmt{ + Lhs: []ast.Expr{dst}, + Rhs: []ast.Expr{src}, + Tok: token.ASSIGN, + } + + report.Report(pass, node, "should copy arrays using assignment instead of using a loop", + report.FilterGenerated(), + report.ShortRange(), + report.Fixes(edit.Fix("replace loop with assignment", edit.ReplaceWithNode(pass.Fset, node, r)))) + } else { + tv, err := types.Eval(pass.Fset, pass.Pkg, node.Pos(), "copy") + if err == nil && tv.IsBuiltin() { + to := "to" + from := "from" + src := m.State["src"].(ast.Expr) + if TsrcArray { + from = "from[:]" + src = &ast.SliceExpr{ + X: src, + } + } + dst := m.State["dst"].(ast.Expr) + if TdstArray { + to = "to[:]" + dst = &ast.SliceExpr{ + X: dst, + } + } + + r := &ast.CallExpr{ + Fun: &ast.Ident{Name: "copy"}, + Args: []ast.Expr{dst, src}, + } + opts := []report.Option{ + report.ShortRange(), + report.FilterGenerated(), + report.Fixes(edit.Fix("replace loop with call to copy()", edit.ReplaceWithNode(pass.Fset, node, r))), + } + report.Report(pass, node, fmt.Sprintf("should use copy(%s, %s) instead of a loop", to, from), opts...) + } + } + } + code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.RangeStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1002/s1002.go b/tools/vendor/honnef.co/go/tools/simple/s1002/s1002.go new file mode 100644 index 000000000..8cc37fd2a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1002/s1002.go @@ -0,0 +1,88 @@ +package s1002 + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1002", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Omit comparison with boolean constant`, + Before: `if x == true {}`, + After: `if x {}`, + Since: "2017.1", + // MergeIfAll because 'true' might not be the builtin constant under all build tags. + // You shouldn't write code like that… + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if code.IsInTest(pass, node) { + return + } + + expr := node.(*ast.BinaryExpr) + if expr.Op != token.EQL && expr.Op != token.NEQ { + return + } + x := code.IsBoolConst(pass, expr.X) + y := code.IsBoolConst(pass, expr.Y) + if !x && !y { + return + } + var other ast.Expr + var val bool + if x { + val = code.BoolConst(pass, expr.X) + other = expr.Y + } else { + val = code.BoolConst(pass, expr.Y) + other = expr.X + } + + ok := typeutil.All(pass.TypesInfo.TypeOf(other), func(term *types.Term) bool { + basic, ok := term.Type().Underlying().(*types.Basic) + return ok && basic.Kind() == types.Bool + }) + if !ok { + return + } + op := "" + if (expr.Op == token.EQL && !val) || (expr.Op == token.NEQ && val) { + op = "!" + } + r := op + report.Render(pass, other) + l1 := len(r) + r = strings.TrimLeft(r, "!") + if (l1-len(r))%2 == 1 { + r = "!" + r + } + report.Report(pass, expr, fmt.Sprintf("should omit comparison to bool constant, can be simplified to %s", r), + report.FilterGenerated(), + report.Fixes(edit.Fix("simplify bool comparison", edit.ReplaceWithString(expr, r)))) + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1003/s1003.go b/tools/vendor/honnef.co/go/tools/simple/s1003/s1003.go new file mode 100644 index 000000000..aa649c5d5 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1003/s1003.go @@ -0,0 +1,118 @@ +package s1003 + +import ( + "fmt" + "go/ast" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1003", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Replace call to \'strings.Index\' with \'strings.Contains\'`, + Before: `if strings.Index(x, y) != -1 {}`, + After: `if strings.Contains(x, y) {}`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // map of value to token to bool value + allowed := map[int64]map[token.Token]bool{ + -1: {token.GTR: true, token.NEQ: true, token.EQL: false}, + 0: {token.GEQ: true, token.LSS: false}, + } + fn := func(node ast.Node) { + expr := node.(*ast.BinaryExpr) + switch expr.Op { + case token.GEQ, token.GTR, token.NEQ, token.LSS, token.EQL: + default: + return + } + + value, ok := code.ExprToInt(pass, expr.Y) + if !ok { + return + } + + allowedOps, ok := allowed[value] + if !ok { + return + } + b, ok := allowedOps[expr.Op] + if !ok { + return + } + + call, ok := expr.X.(*ast.CallExpr) + if !ok { + return + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return + } + pkgIdent, ok := sel.X.(*ast.Ident) + if !ok { + return + } + funIdent := sel.Sel + if pkgIdent.Name != "strings" && pkgIdent.Name != "bytes" { + return + } + + var r ast.Expr + switch funIdent.Name { + case "IndexRune": + r = &ast.SelectorExpr{ + X: pkgIdent, + Sel: &ast.Ident{Name: "ContainsRune"}, + } + case "IndexAny": + r = &ast.SelectorExpr{ + X: pkgIdent, + Sel: &ast.Ident{Name: "ContainsAny"}, + } + case "Index": + r = &ast.SelectorExpr{ + X: pkgIdent, + Sel: &ast.Ident{Name: "Contains"}, + } + default: + return + } + + r = &ast.CallExpr{ + Fun: r, + Args: call.Args, + } + if !b { + r = &ast.UnaryExpr{ + Op: token.NOT, + X: r, + } + } + + report.Report(pass, node, fmt.Sprintf("should use %s instead", report.Render(pass, r)), + report.FilterGenerated(), + report.Fixes(edit.Fix(fmt.Sprintf("simplify use of %s", report.Render(pass, call.Fun)), edit.ReplaceWithNode(pass.Fset, node, r)))) + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1004/s1004.go b/tools/vendor/honnef.co/go/tools/simple/s1004/s1004.go new file mode 100644 index 000000000..d2b7f58d0 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1004/s1004.go @@ -0,0 +1,72 @@ +package s1004 + +import ( + "fmt" + "go/ast" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1004", + Run: CheckBytesCompare, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Replace call to \'bytes.Compare\' with \'bytes.Equal\'`, + Before: `if bytes.Compare(x, y) == 0 {}`, + After: `if bytes.Equal(x, y) {}`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkBytesCompareQ = pattern.MustParse(`(BinaryExpr (CallExpr (Symbol "bytes.Compare") args) op@(Or "==" "!=") (IntegerLiteral "0"))`) + checkBytesCompareRe = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "bytes") (Ident "Equal")) args)`) + checkBytesCompareRn = pattern.MustParse(`(UnaryExpr "!" (CallExpr (SelectorExpr (Ident "bytes") (Ident "Equal")) args))`) +) + +func CheckBytesCompare(pass *analysis.Pass) (interface{}, error) { + if pass.Pkg.Path() == "bytes" || pass.Pkg.Path() == "bytes_test" { + // the bytes package is free to use bytes.Compare as it sees fit + return nil, nil + } + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkBytesCompareQ, node) + if !ok { + return + } + + args := report.RenderArgs(pass, m.State["args"].([]ast.Expr)) + prefix := "" + if m.State["op"].(token.Token) == token.NEQ { + prefix = "!" + } + + var fix analysis.SuggestedFix + switch tok := m.State["op"].(token.Token); tok { + case token.EQL: + fix = edit.Fix("simplify use of bytes.Compare", edit.ReplaceWithPattern(pass.Fset, node, checkBytesCompareRe, m.State)) + case token.NEQ: + fix = edit.Fix("simplify use of bytes.Compare", edit.ReplaceWithPattern(pass.Fset, node, checkBytesCompareRn, m.State)) + default: + panic(fmt.Sprintf("unexpected token %v", tok)) + } + report.Report(pass, node, fmt.Sprintf("should use %sbytes.Equal(%s) instead", prefix, args), report.FilterGenerated(), report.Fixes(fix)) + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1005/s1005.go b/tools/vendor/honnef.co/go/tools/simple/s1005/s1005.go new file mode 100644 index 000000000..e84ede29a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1005/s1005.go @@ -0,0 +1,108 @@ +package s1005 + +import ( + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ast/astutil" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1005", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Drop unnecessary use of the blank identifier`, + Text: `In many cases, assigning to the blank identifier is unnecessary.`, + Before: ` +for _ = range s {} +x, _ = someMap[key] +_ = <-ch`, + After: ` +for range s{} +x = someMap[key] +<-ch`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkUnnecessaryBlankQ1 = pattern.MustParse(` + (AssignStmt + [_ (Ident "_")] + _ + (Or + (IndexExpr _ _) + (UnaryExpr "<-" _))) `) + checkUnnecessaryBlankQ2 = pattern.MustParse(` + (AssignStmt + (Ident "_") _ recv@(UnaryExpr "<-" _))`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn1 := func(node ast.Node) { + if _, ok := code.Match(pass, checkUnnecessaryBlankQ1, node); ok { + r := *node.(*ast.AssignStmt) + r.Lhs = r.Lhs[0:1] + report.Report(pass, node, "unnecessary assignment to the blank identifier", + report.FilterGenerated(), + report.Fixes(edit.Fix("remove assignment to blank identifier", edit.ReplaceWithNode(pass.Fset, node, &r)))) + } else if m, ok := code.Match(pass, checkUnnecessaryBlankQ2, node); ok { + report.Report(pass, node, "unnecessary assignment to the blank identifier", + report.FilterGenerated(), + report.Fixes(edit.Fix("simplify channel receive operation", edit.ReplaceWithNode(pass.Fset, node, m.State["recv"].(ast.Node))))) + } + } + + fn3 := func(node ast.Node) { + rs := node.(*ast.RangeStmt) + + if _, ok := pass.TypesInfo.TypeOf(rs.X).Underlying().(*types.Signature); ok { + // iteration variables are not optional with rangefunc + return + } + + // for _ + if rs.Value == nil && astutil.IsBlank(rs.Key) { + report.Report(pass, rs.Key, "unnecessary assignment to the blank identifier", + report.FilterGenerated(), + report.MinimumLanguageVersion("go1.4"), + report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.Pos(), rs.TokPos + 1})))) + } + + // for _, _ + if astutil.IsBlank(rs.Key) && astutil.IsBlank(rs.Value) { + // FIXME we should mark both key and value + report.Report(pass, rs.Key, "unnecessary assignment to the blank identifier", + report.FilterGenerated(), + report.MinimumLanguageVersion("go1.4"), + report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.Pos(), rs.TokPos + 1})))) + } + + // for x, _ + if !astutil.IsBlank(rs.Key) && astutil.IsBlank(rs.Value) { + report.Report(pass, rs.Value, "unnecessary assignment to the blank identifier", + report.FilterGenerated(), + report.MinimumLanguageVersion("go1.4"), + report.Fixes(edit.Fix("remove assignment to blank identifier", edit.Delete(edit.Range{rs.Key.End(), rs.Value.End()})))) + } + } + + code.Preorder(pass, fn1, (*ast.AssignStmt)(nil)) + code.Preorder(pass, fn3, (*ast.RangeStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1006/s1006.go b/tools/vendor/honnef.co/go/tools/simple/s1006/s1006.go new file mode 100644 index 000000000..fa177531e --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1006/s1006.go @@ -0,0 +1,46 @@ +package s1006 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1006", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use \"for { ... }\" for infinite loops`, + Text: `For infinite loops, using \'for { ... }\' is the most idiomatic choice.`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + loop := node.(*ast.ForStmt) + if loop.Init != nil || loop.Post != nil { + return + } + if !code.IsBoolConst(pass, loop.Cond) || !code.BoolConst(pass, loop.Cond) { + return + } + report.Report(pass, loop, "should use for {} instead of for true {}", + report.ShortRange(), + report.FilterGenerated()) + } + code.Preorder(pass, fn, (*ast.ForStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1007/s1007.go b/tools/vendor/honnef.co/go/tools/simple/s1007/s1007.go new file mode 100644 index 000000000..ac42c8d18 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1007/s1007.go @@ -0,0 +1,93 @@ +package s1007 + +import ( + "fmt" + "go/ast" + "go/token" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1007", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Simplify regular expression by using raw string literal`, + Text: `Raw string literals use backticks instead of quotation marks and do not support +any escape sequences. This means that the backslash can be used +freely, without the need of escaping. + +Since regular expressions have their own escape sequences, raw strings +can improve their readability.`, + Before: `regexp.Compile("\\A(\\w+) profile: total \\d+\\n\\z")`, + After: "regexp.Compile(`\\A(\\w+) profile: total \\d+\\n\\z`)", + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + if !code.IsCallToAny(pass, call, "regexp.MustCompile", "regexp.Compile") { + return + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return + } + lit, ok := call.Args[knowledge.Arg("regexp.Compile.expr")].(*ast.BasicLit) + if !ok { + // TODO(dominikh): support string concat, maybe support constants + return + } + if lit.Kind != token.STRING { + // invalid function call + return + } + if lit.Value[0] != '"' { + // already a raw string + return + } + val := lit.Value + if !strings.Contains(val, `\\`) { + return + } + if strings.Contains(val, "`") { + return + } + + bs := false + for _, c := range val { + if !bs && c == '\\' { + bs = true + continue + } + if bs && c == '\\' { + bs = false + continue + } + if bs { + // backslash followed by non-backslash -> escape sequence + return + } + } + + report.Report(pass, call, fmt.Sprintf("should use raw string (`...`) with regexp.%s to avoid having to escape twice", sel.Sel.Name), report.FilterGenerated()) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1008/s1008.go b/tools/vendor/honnef.co/go/tools/simple/s1008/s1008.go new file mode 100644 index 000000000..98cd00dac --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1008/s1008.go @@ -0,0 +1,148 @@ +package s1008 + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1008", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Simplify returning boolean expression`, + Before: ` +if { + return true +} +return false`, + After: `return `, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkIfReturnQIf = pattern.MustParse(`(IfStmt nil cond [(ReturnStmt [ret@(Builtin (Or "true" "false"))])] nil)`) + checkIfReturnQRet = pattern.MustParse(`(ReturnStmt [ret@(Builtin (Or "true" "false"))])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + block := node.(*ast.BlockStmt) + l := len(block.List) + if l < 2 { + return + } + n1, n2 := block.List[l-2], block.List[l-1] + + if len(block.List) >= 3 { + if _, ok := block.List[l-3].(*ast.IfStmt); ok { + // Do not flag a series of if statements + return + } + } + m1, ok := code.Match(pass, checkIfReturnQIf, n1) + if !ok { + return + } + m2, ok := code.Match(pass, checkIfReturnQRet, n2) + if !ok { + return + } + + if op, ok := m1.State["cond"].(*ast.BinaryExpr); ok { + switch op.Op { + case token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ: + default: + return + } + } + + ret1 := m1.State["ret"].(*ast.Ident) + ret2 := m2.State["ret"].(*ast.Ident) + + if ret1.Name == ret2.Name { + // we want the function to return true and false, not the + // same value both times. + return + } + + cond := m1.State["cond"].(ast.Expr) + origCond := cond + if ret1.Name == "false" { + cond = negate(pass, cond) + } + report.Report(pass, n1, + fmt.Sprintf("should use 'return %s' instead of 'if %s { return %s }; return %s'", + report.Render(pass, cond), + report.Render(pass, origCond), report.Render(pass, ret1), report.Render(pass, ret2)), + report.FilterGenerated()) + } + code.Preorder(pass, fn, (*ast.BlockStmt)(nil)) + return nil, nil +} + +func negate(pass *analysis.Pass, expr ast.Expr) ast.Expr { + switch expr := expr.(type) { + case *ast.BinaryExpr: + out := *expr + switch expr.Op { + case token.EQL: + out.Op = token.NEQ + case token.LSS: + out.Op = token.GEQ + case token.GTR: + // Some builtins never return negative ints; "len(x) <= 0" should be "len(x) == 0". + if call, ok := expr.X.(*ast.CallExpr); ok && + code.IsCallToAny(pass, call, "len", "cap", "copy") && + code.IsIntegerLiteral(pass, expr.Y, constant.MakeInt64(0)) { + out.Op = token.EQL + } else { + out.Op = token.LEQ + } + case token.NEQ: + out.Op = token.EQL + case token.LEQ: + out.Op = token.GTR + case token.GEQ: + out.Op = token.LSS + } + return &out + case *ast.Ident, *ast.CallExpr, *ast.IndexExpr, *ast.StarExpr: + return &ast.UnaryExpr{ + Op: token.NOT, + X: expr, + } + case *ast.UnaryExpr: + if expr.Op == token.NOT { + return expr.X + } + return &ast.UnaryExpr{ + Op: token.NOT, + X: expr, + } + default: + return &ast.UnaryExpr{ + Op: token.NOT, + X: &ast.ParenExpr{ + X: expr, + }, + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1009/s1009.go b/tools/vendor/honnef.co/go/tools/simple/s1009/s1009.go new file mode 100644 index 000000000..afe5c3c14 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1009/s1009.go @@ -0,0 +1,185 @@ +package s1009 + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1009", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Omit redundant nil check on slices, maps, and channels`, + Text: `The \'len\' function is defined for all slices, maps, and +channels, even nil ones, which have a length of zero. It is not necessary to +check for nil before checking that their length is not zero.`, + Before: `if x != nil && len(x) != 0 {}`, + After: `if len(x) != 0 {}`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +// run checks for the following redundant nil-checks: +// +// if x == nil || len(x) == 0 {} +// if x != nil && len(x) != 0 {} +// if x != nil && len(x) == N {} (where N != 0) +// if x != nil && len(x) > N {} +// if x != nil && len(x) >= N {} (where N != 0) +func run(pass *analysis.Pass) (interface{}, error) { + isConstZero := func(expr ast.Expr) (isConst bool, isZero bool) { + _, ok := expr.(*ast.BasicLit) + if ok { + return true, code.IsIntegerLiteral(pass, expr, constant.MakeInt64(0)) + } + id, ok := expr.(*ast.Ident) + if !ok { + return false, false + } + c, ok := pass.TypesInfo.ObjectOf(id).(*types.Const) + if !ok { + return false, false + } + return true, c.Val().Kind() == constant.Int && c.Val().String() == "0" + } + + fn := func(node ast.Node) { + // check that expr is "x || y" or "x && y" + expr := node.(*ast.BinaryExpr) + if expr.Op != token.LOR && expr.Op != token.LAND { + return + } + eqNil := expr.Op == token.LOR + + // check that x is "xx == nil" or "xx != nil" + x, ok := expr.X.(*ast.BinaryExpr) + if !ok { + return + } + if eqNil && x.Op != token.EQL { + return + } + if !eqNil && x.Op != token.NEQ { + return + } + var xx *ast.Ident + switch s := x.X.(type) { + case *ast.Ident: + xx = s + case *ast.SelectorExpr: + xx = s.Sel + default: + return + } + if !code.IsNil(pass, x.Y) { + return + } + + // check that y is "len(xx) == 0" or "len(xx) ... " + y, ok := expr.Y.(*ast.BinaryExpr) + if !ok { + return + } + if eqNil && y.Op != token.EQL { // must be len(xx) *==* 0 + return + } + yx, ok := y.X.(*ast.CallExpr) + if !ok { + return + } + if !code.IsCallTo(pass, yx, "len") { + return + } + var yxArg *ast.Ident + switch s := yx.Args[knowledge.Arg("len.v")].(type) { + case *ast.Ident: + yxArg = s + case *ast.SelectorExpr: + yxArg = s.Sel + default: + return + } + if yxArg.Name != xx.Name { + return + } + + if eqNil && !code.IsIntegerLiteral(pass, y.Y, constant.MakeInt64(0)) { // must be len(x) == *0* + return + } + + if !eqNil { + isConst, isZero := isConstZero(y.Y) + if !isConst { + return + } + switch y.Op { + case token.EQL: + // avoid false positive for "xx != nil && len(xx) == 0" + if isZero { + return + } + case token.GEQ: + // avoid false positive for "xx != nil && len(xx) >= 0" + if isZero { + return + } + case token.NEQ: + // avoid false positive for "xx != nil && len(xx) != " + if !isZero { + return + } + case token.GTR: + // ok + default: + return + } + } + + // finally check that xx type is one of array, slice, map or chan + // this is to prevent false positive in case if xx is a pointer to an array + typ := pass.TypesInfo.TypeOf(xx) + ok = typeutil.All(typ, func(term *types.Term) bool { + switch term.Type().Underlying().(type) { + case *types.Slice: + return true + case *types.Map: + return true + case *types.Chan: + return true + case *types.Pointer: + return false + case *types.TypeParam: + return false + default: + lint.ExhaustiveTypeSwitch(term.Type().Underlying()) + return false + } + }) + if !ok { + return + } + + report.Report(pass, expr, fmt.Sprintf("should omit nil check; len() for %s is defined as zero", typ), report.FilterGenerated()) + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1010/s1010.go b/tools/vendor/honnef.co/go/tools/simple/s1010/s1010.go new file mode 100644 index 000000000..0545718a4 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1010/s1010.go @@ -0,0 +1,48 @@ +package s1010 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1010", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Omit default slice index`, + Text: `When slicing, the second index defaults to the length of the value, +making \'s[n:len(s)]\' and \'s[n:]\' equivalent.`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkSlicingQ = pattern.MustParse(`(SliceExpr x@(Object _) low (CallExpr (Builtin "len") [x]) nil)`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if _, ok := code.Match(pass, checkSlicingQ, node); ok { + expr := node.(*ast.SliceExpr) + report.Report(pass, expr.High, + "should omit second index in slice, s[a:len(s)] is identical to s[a:]", + report.FilterGenerated(), + report.Fixes(edit.Fix("simplify slice expression", edit.Delete(expr.High)))) + } + } + code.Preorder(pass, fn, (*ast.SliceExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1011/s1011.go b/tools/vendor/honnef.co/go/tools/simple/s1011/s1011.go new file mode 100644 index 000000000..73169266d --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1011/s1011.go @@ -0,0 +1,144 @@ +package s1011 + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/facts/purity" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1011", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, purity.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use a single \'append\' to concatenate two slices`, + Before: ` +for _, e := range y { + x = append(x, e) +} + +for i := range y { + x = append(x, y[i]) +} + +for i := range y { + v := y[i] + x = append(x, v) +}`, + + After: ` +x = append(x, y...) +x = append(x, y...) +x = append(x, y...)`, + Since: "2017.1", + // MergeIfAll because y might not be a slice under all build tags. + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkLoopAppendQ = pattern.MustParse(` +(Or + (RangeStmt + (Ident "_") + val@(Object _) + _ + x + [(AssignStmt [lhs] "=" [(CallExpr (Builtin "append") [lhs val])])]) + (RangeStmt + idx@(Object _) + nil + _ + x + [(AssignStmt [lhs] "=" [(CallExpr (Builtin "append") [lhs (IndexExpr x idx)])])]) + (RangeStmt + idx@(Object _) + nil + _ + x + [(AssignStmt val@(Object _) ":=" (IndexExpr x idx)) + (AssignStmt [lhs] "=" [(CallExpr (Builtin "append") [lhs val])])]))`) + +func run(pass *analysis.Pass) (interface{}, error) { + pure := pass.ResultOf[purity.Analyzer].(purity.Result) + + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkLoopAppendQ, node) + if !ok { + return + } + + if val, ok := m.State["val"].(types.Object); ok && code.RefersTo(pass, m.State["lhs"].(ast.Expr), val) { + return + } + + if m.State["idx"] != nil && code.MayHaveSideEffects(pass, m.State["x"].(ast.Expr), pure) { + // When using an index-based loop, x gets evaluated repeatedly and thus should be pure. + // This doesn't matter for value-based loops, because x only gets evaluated once. + return + } + + if idx, ok := m.State["idx"].(types.Object); ok && code.RefersTo(pass, m.State["lhs"].(ast.Expr), idx) { + // The lhs mustn't refer to the index loop variable. + return + } + + if code.MayHaveSideEffects(pass, m.State["lhs"].(ast.Expr), pure) { + // The lhs may be dynamic and return different values on each iteration. For example: + // + // func bar() map[int][]int { /* return one of several maps */ } + // + // func foo(x []int, y [][]int) { + // for i := range x { + // bar()[0] = append(bar()[0], x[i]) + // } + // } + // + // The dynamic nature of the lhs might also affect the value of the index. + return + } + + src := pass.TypesInfo.TypeOf(m.State["x"].(ast.Expr)) + dst := pass.TypesInfo.TypeOf(m.State["lhs"].(ast.Expr)) + if !types.Identical(src, dst) { + return + } + + r := &ast.AssignStmt{ + Lhs: []ast.Expr{m.State["lhs"].(ast.Expr)}, + Tok: token.ASSIGN, + Rhs: []ast.Expr{ + &ast.CallExpr{ + Fun: &ast.Ident{Name: "append"}, + Args: []ast.Expr{ + m.State["lhs"].(ast.Expr), + m.State["x"].(ast.Expr), + }, + Ellipsis: 1, + }, + }, + } + + report.Report(pass, node, fmt.Sprintf("should replace loop with %s", report.Render(pass, r)), + report.ShortRange(), + report.FilterGenerated(), + report.Fixes(edit.Fix("replace loop with call to append", edit.ReplaceWithNode(pass.Fset, node, r)))) + } + code.Preorder(pass, fn, (*ast.RangeStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1012/s1012.go b/tools/vendor/honnef.co/go/tools/simple/s1012/s1012.go new file mode 100644 index 000000000..ceabd2cff --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1012/s1012.go @@ -0,0 +1,51 @@ +package s1012 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1012", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Replace \'time.Now().Sub(x)\' with \'time.Since(x)\'`, + Text: `The \'time.Since\' helper has the same effect as using \'time.Now().Sub(x)\' +but is easier to read.`, + Before: `time.Now().Sub(x)`, + After: `time.Since(x)`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkTimeSinceQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (Symbol "time.Now") []) (Symbol "(time.Time).Sub")) [arg])`) + checkTimeSinceR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Since")) [arg])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if _, edits, ok := code.MatchAndEdit(pass, checkTimeSinceQ, checkTimeSinceR, node); ok { + report.Report(pass, node, "should use time.Since instead of time.Now().Sub", + report.FilterGenerated(), + report.Fixes(edit.Fix("replace with call to time.Since", edits...))) + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1016/s1016.go b/tools/vendor/honnef.co/go/tools/simple/s1016/s1016.go new file mode 100644 index 000000000..01c844aa7 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1016/s1016.go @@ -0,0 +1,189 @@ +package s1016 + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "go/version" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1016", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use a type conversion instead of manually copying struct fields`, + Text: `Two struct types with identical fields can be converted between each +other. In older versions of Go, the fields had to have identical +struct tags. Since Go 1.8, however, struct tags are ignored during +conversions. It is thus not necessary to manually copy every field +individually.`, + Before: ` +var x T1 +y := T2{ + Field1: x.Field1, + Field2: x.Field2, +}`, + After: ` +var x T1 +y := T2(x)`, + Since: "2017.1", + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // TODO(dh): support conversions between type parameters + fn := func(node ast.Node, stack []ast.Node) { + if unary, ok := stack[len(stack)-2].(*ast.UnaryExpr); ok && unary.Op == token.AND { + // Do not suggest type conversion between pointers + return + } + + lit := node.(*ast.CompositeLit) + var typ1 types.Type + var named1 *types.Named + switch typ := pass.TypesInfo.TypeOf(lit.Type).(type) { + case *types.Named: + typ1 = typ + named1 = typ + case *types.Alias: + ua := types.Unalias(typ) + if n, ok := ua.(*types.Named); ok { + typ1 = typ + named1 = n + } + } + if typ1 == nil { + return + } + s1, ok := typ1.Underlying().(*types.Struct) + if !ok { + return + } + + var typ2 types.Type + var named2 *types.Named + var ident *ast.Ident + getSelType := func(expr ast.Expr) (types.Type, *ast.Ident, bool) { + sel, ok := expr.(*ast.SelectorExpr) + if !ok { + return nil, nil, false + } + ident, ok := sel.X.(*ast.Ident) + if !ok { + return nil, nil, false + } + typ := pass.TypesInfo.TypeOf(sel.X) + return typ, ident, typ != nil + } + if len(lit.Elts) == 0 { + return + } + if s1.NumFields() != len(lit.Elts) { + return + } + for i, elt := range lit.Elts { + var t types.Type + var id *ast.Ident + var ok bool + switch elt := elt.(type) { + case *ast.SelectorExpr: + t, id, ok = getSelType(elt) + if !ok { + return + } + if i >= s1.NumFields() || s1.Field(i).Name() != elt.Sel.Name { + return + } + case *ast.KeyValueExpr: + var sel *ast.SelectorExpr + sel, ok = elt.Value.(*ast.SelectorExpr) + if !ok { + return + } + + if elt.Key.(*ast.Ident).Name != sel.Sel.Name { + return + } + t, id, ok = getSelType(elt.Value) + } + if !ok { + return + } + // All fields must be initialized from the same object + if ident != nil && pass.TypesInfo.ObjectOf(ident) != pass.TypesInfo.ObjectOf(id) { + return + } + switch t := t.(type) { + case *types.Named: + typ2 = t + named2 = t + case *types.Alias: + if n, ok := types.Unalias(t).(*types.Named); ok { + typ2 = t + named2 = n + } + } + if typ2 == nil { + return + } + ident = id + } + + if typ2 == nil { + return + } + + if named1.Obj().Pkg() != named2.Obj().Pkg() { + // Do not suggest type conversions between different + // packages. Types in different packages might only match + // by coincidence. Furthermore, if the dependency ever + // adds more fields to its type, it could break the code + // that relies on the type conversion to work. + return + } + + s2, ok := typ2.Underlying().(*types.Struct) + if !ok { + return + } + if typ1 == typ2 { + return + } + if version.Compare(code.LanguageVersion(pass, node), "go1.8") >= 0 { + if !types.IdenticalIgnoreTags(s1, s2) { + return + } + } else { + if !types.Identical(s1, s2) { + return + } + } + + r := &ast.CallExpr{ + Fun: lit.Type, + Args: []ast.Expr{ident}, + } + report.Report(pass, node, + fmt.Sprintf("should convert %s (type %s) to %s instead of using struct literal", ident.Name, types.TypeString(typ2, types.RelativeTo(pass.Pkg)), types.TypeString(typ1, types.RelativeTo(pass.Pkg))), + report.FilterGenerated(), + report.Fixes(edit.Fix("use type conversion", edit.ReplaceWithNode(pass.Fset, node, r)))) + } + code.PreorderStack(pass, fn, (*ast.CompositeLit)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1017/s1017.go b/tools/vendor/honnef.co/go/tools/simple/s1017/s1017.go new file mode 100644 index 000000000..aa99b7c2a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1017/s1017.go @@ -0,0 +1,239 @@ +package s1017 + +import ( + "fmt" + "go/ast" + "go/token" + "reflect" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ast/astutil" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1017", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Replace manual trimming with \'strings.TrimPrefix\'`, + Text: `Instead of using \'strings.HasPrefix\' and manual slicing, use the +\'strings.TrimPrefix\' function. If the string doesn't start with the +prefix, the original string will be returned. Using \'strings.TrimPrefix\' +reduces complexity, and avoids common bugs, such as off-by-one +mistakes.`, + Before: ` +if strings.HasPrefix(str, prefix) { + str = str[len(prefix):] +}`, + After: `str = strings.TrimPrefix(str, prefix)`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + sameNonDynamic := func(node1, node2 ast.Node) bool { + if reflect.TypeOf(node1) != reflect.TypeOf(node2) { + return false + } + + switch node1 := node1.(type) { + case *ast.Ident: + return pass.TypesInfo.ObjectOf(node1) == pass.TypesInfo.ObjectOf(node2.(*ast.Ident)) + case *ast.SelectorExpr, *ast.IndexExpr: + return astutil.Equal(node1, node2) + case *ast.BasicLit: + return astutil.Equal(node1, node2) + } + return false + } + + isLenOnIdent := func(fn ast.Expr, ident ast.Expr) bool { + call, ok := fn.(*ast.CallExpr) + if !ok { + return false + } + if !code.IsCallTo(pass, call, "len") { + return false + } + if len(call.Args) != 1 { + return false + } + return sameNonDynamic(call.Args[knowledge.Arg("len.v")], ident) + } + + seen := make(map[ast.Node]struct{}) + fn := func(node ast.Node) { + var pkg string + var fun string + + ifstmt := node.(*ast.IfStmt) + if ifstmt.Init != nil { + return + } + if ifstmt.Else != nil { + seen[ifstmt.Else] = struct{}{} + return + } + if _, ok := seen[ifstmt]; ok { + return + } + if len(ifstmt.Body.List) != 1 { + return + } + condCall, ok := ifstmt.Cond.(*ast.CallExpr) + if !ok { + return + } + + condCallName := code.CallName(pass, condCall) + switch condCallName { + case "strings.HasPrefix": + pkg = "strings" + fun = "HasPrefix" + case "strings.HasSuffix": + pkg = "strings" + fun = "HasSuffix" + case "strings.Contains": + pkg = "strings" + fun = "Contains" + case "bytes.HasPrefix": + pkg = "bytes" + fun = "HasPrefix" + case "bytes.HasSuffix": + pkg = "bytes" + fun = "HasSuffix" + case "bytes.Contains": + pkg = "bytes" + fun = "Contains" + default: + return + } + + assign, ok := ifstmt.Body.List[0].(*ast.AssignStmt) + if !ok { + return + } + if assign.Tok != token.ASSIGN { + return + } + if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { + return + } + if !sameNonDynamic(condCall.Args[0], assign.Lhs[0]) { + return + } + + switch rhs := assign.Rhs[0].(type) { + case *ast.CallExpr: + if len(rhs.Args) < 2 || !sameNonDynamic(condCall.Args[0], rhs.Args[0]) || !sameNonDynamic(condCall.Args[1], rhs.Args[1]) { + return + } + + rhsName := code.CallName(pass, rhs) + if condCallName == "strings.HasPrefix" && rhsName == "strings.TrimPrefix" || + condCallName == "strings.HasSuffix" && rhsName == "strings.TrimSuffix" || + condCallName == "strings.Contains" && rhsName == "strings.Replace" || + condCallName == "bytes.HasPrefix" && rhsName == "bytes.TrimPrefix" || + condCallName == "bytes.HasSuffix" && rhsName == "bytes.TrimSuffix" || + condCallName == "bytes.Contains" && rhsName == "bytes.Replace" { + report.Report(pass, ifstmt, fmt.Sprintf("should replace this if statement with an unconditional %s", rhsName), report.FilterGenerated()) + } + case *ast.SliceExpr: + slice := rhs + if !ok { + return + } + if slice.Slice3 { + return + } + if !sameNonDynamic(slice.X, condCall.Args[0]) { + return + } + + validateOffset := func(off ast.Expr) bool { + switch off := off.(type) { + case *ast.CallExpr: + return isLenOnIdent(off, condCall.Args[1]) + case *ast.BasicLit: + if pkg != "strings" { + return false + } + if _, ok := condCall.Args[1].(*ast.BasicLit); !ok { + // Only allow manual slicing with an integer + // literal if the second argument to HasPrefix + // was a string literal. + return false + } + s, ok1 := code.ExprToString(pass, condCall.Args[1]) + n, ok2 := code.ExprToInt(pass, off) + if !ok1 || !ok2 || n != int64(len(s)) { + return false + } + return true + default: + return false + } + } + + switch fun { + case "HasPrefix": + // TODO(dh) We could detect a High that is len(s), but another + // rule will already flag that, anyway. + if slice.High != nil { + return + } + if !validateOffset(slice.Low) { + return + } + case "HasSuffix": + if slice.Low != nil { + n, ok := code.ExprToInt(pass, slice.Low) + if !ok || n != 0 { + return + } + } + switch index := slice.High.(type) { + case *ast.BinaryExpr: + if index.Op != token.SUB { + return + } + if !isLenOnIdent(index.X, condCall.Args[0]) { + return + } + if !validateOffset(index.Y) { + return + } + default: + return + } + default: + return + } + + var replacement string + switch fun { + case "HasPrefix": + replacement = "TrimPrefix" + case "HasSuffix": + replacement = "TrimSuffix" + } + report.Report(pass, ifstmt, fmt.Sprintf("should replace this if statement with an unconditional %s.%s", pkg, replacement), + report.ShortRange(), + report.FilterGenerated()) + } + } + code.Preorder(pass, fn, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1018/s1018.go b/tools/vendor/honnef.co/go/tools/simple/s1018/s1018.go new file mode 100644 index 000000000..ef3ee897c --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1018/s1018.go @@ -0,0 +1,84 @@ +package s1018 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1018", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use \"copy\" for sliding elements`, + Text: `\'copy()\' permits using the same source and destination slice, even with +overlapping ranges. This makes it ideal for sliding elements in a +slice.`, + + Before: ` +for i := 0; i < n; i++ { + bs[i] = bs[offset+i] +}`, + After: `copy(bs[:n], bs[offset:])`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkLoopSlideQ = pattern.MustParse(` + (ForStmt + (AssignStmt initvar@(Ident _) _ (IntegerLiteral "0")) + (BinaryExpr initvar "<" limit@(Ident _)) + (IncDecStmt initvar "++") + [(AssignStmt + (IndexExpr slice@(Ident _) initvar) + "=" + (IndexExpr slice (BinaryExpr offset@(Ident _) "+" initvar)))])`) + checkLoopSlideR = pattern.MustParse(` + (CallExpr + (Ident "copy") + [(SliceExpr slice nil limit nil) + (SliceExpr slice offset nil nil)])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + // TODO(dh): detect bs[i+offset] in addition to bs[offset+i] + // TODO(dh): consider merging this function with LintLoopCopy + // TODO(dh): detect length that is an expression, not a variable name + // TODO(dh): support sliding to a different offset than the beginning of the slice + + fn := func(node ast.Node) { + loop := node.(*ast.ForStmt) + m, edits, ok := code.MatchAndEdit(pass, checkLoopSlideQ, checkLoopSlideR, loop) + if !ok { + return + } + typ := pass.TypesInfo.TypeOf(m.State["slice"].(*ast.Ident)) + // The pattern probably needs a core type, but All is fine, too. Either way we only accept slices. + if !typeutil.All(typ, typeutil.IsSlice) { + return + } + + report.Report(pass, loop, "should use copy() instead of loop for sliding slice elements", + report.ShortRange(), + report.FilterGenerated(), + report.Fixes(edit.Fix("use copy() instead of loop", edits...))) + } + code.Preorder(pass, fn, (*ast.ForStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1019/s1019.go b/tools/vendor/honnef.co/go/tools/simple/s1019/s1019.go new file mode 100644 index 000000000..4f3288edb --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1019/s1019.go @@ -0,0 +1,71 @@ +package s1019 + +import ( + "fmt" + "go/ast" + "go/types" + "path/filepath" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1019", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Simplify \"make\" call by omitting redundant arguments`, + Text: `The \"make\" function has default values for the length and capacity +arguments. For channels, the length defaults to zero, and for slices, +the capacity defaults to the length.`, + Since: "2017.1", + // MergeIfAll because the type might be different under different build tags. + // You shouldn't write code like that… + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkMakeLenCapQ1 = pattern.MustParse(`(CallExpr (Builtin "make") [typ size@(IntegerLiteral "0")])`) + checkMakeLenCapQ2 = pattern.MustParse(`(CallExpr (Builtin "make") [typ size size])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if pass.Pkg.Path() == "runtime_test" && filepath.Base(pass.Fset.Position(node.Pos()).Filename) == "map_test.go" { + // special case of runtime tests testing map creation + return + } + if m, ok := code.Match(pass, checkMakeLenCapQ1, node); ok { + T := m.State["typ"].(ast.Expr) + size := m.State["size"].(ast.Node) + + if _, ok := typeutil.CoreType(pass.TypesInfo.TypeOf(T)).Underlying().(*types.Chan); ok { + report.Report(pass, size, fmt.Sprintf("should use make(%s) instead", report.Render(pass, T)), report.FilterGenerated()) + } + + } else if m, ok := code.Match(pass, checkMakeLenCapQ2, node); ok { + // TODO(dh): don't consider sizes identical if they're + // dynamic. for example: make(T, <-ch, <-ch). + T := m.State["typ"].(ast.Expr) + size := m.State["size"].(ast.Node) + report.Report(pass, size, + fmt.Sprintf("should use make(%s, %s) instead", report.Render(pass, T), report.Render(pass, size)), + report.FilterGenerated()) + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1020/s1020.go b/tools/vendor/honnef.co/go/tools/simple/s1020/s1020.go new file mode 100644 index 000000000..8795847ef --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1020/s1020.go @@ -0,0 +1,86 @@ +package s1020 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1020", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Omit redundant nil check in type assertion`, + Before: `if _, ok := i.(T); ok && i != nil {}`, + After: `if _, ok := i.(T); ok {}`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkAssertNotNilFn1Q = pattern.MustParse(` + (IfStmt + (AssignStmt [(Ident "_") ok@(Object _)] _ [(TypeAssertExpr assert@(Object _) _)]) + (Or + (BinaryExpr ok "&&" (BinaryExpr assert "!=" (Builtin "nil"))) + (BinaryExpr (BinaryExpr assert "!=" (Builtin "nil")) "&&" ok)) + _ + _)`) + checkAssertNotNilFn2Q = pattern.MustParse(` + (IfStmt + nil + (BinaryExpr lhs@(Object _) "!=" (Builtin "nil")) + [ + ifstmt@(IfStmt + (AssignStmt [(Ident "_") ok@(Object _)] _ [(TypeAssertExpr lhs _)]) + ok + _ + nil) + ] + nil)`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn1 := func(node ast.Node) { + m, ok := code.Match(pass, checkAssertNotNilFn1Q, node) + if !ok { + return + } + assert := m.State["assert"].(types.Object) + assign := m.State["ok"].(types.Object) + report.Report(pass, node, fmt.Sprintf("when %s is true, %s can't be nil", assign.Name(), assert.Name()), + report.ShortRange(), + report.FilterGenerated()) + } + fn2 := func(node ast.Node) { + m, ok := code.Match(pass, checkAssertNotNilFn2Q, node) + if !ok { + return + } + ifstmt := m.State["ifstmt"].(*ast.IfStmt) + lhs := m.State["lhs"].(types.Object) + assignIdent := m.State["ok"].(types.Object) + report.Report(pass, ifstmt, fmt.Sprintf("when %s is true, %s can't be nil", assignIdent.Name(), lhs.Name()), + report.ShortRange(), + report.FilterGenerated()) + } + // OPT(dh): merge fn1 and fn2 + code.Preorder(pass, fn1, (*ast.IfStmt)(nil)) + code.Preorder(pass, fn2, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1021/s1021.go b/tools/vendor/honnef.co/go/tools/simple/s1021/s1021.go new file mode 100644 index 000000000..6ea8e4f60 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1021/s1021.go @@ -0,0 +1,118 @@ +package s1021 + +import ( + "go/ast" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1021", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Merge variable declaration and assignment`, + Before: ` +var x uint +x = 1`, + After: `var x uint = 1`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + hasMultipleAssignments := func(root ast.Node, ident *ast.Ident) bool { + num := 0 + ast.Inspect(root, func(node ast.Node) bool { + if num >= 2 { + return false + } + assign, ok := node.(*ast.AssignStmt) + if !ok { + return true + } + for _, lhs := range assign.Lhs { + if oident, ok := lhs.(*ast.Ident); ok { + if pass.TypesInfo.ObjectOf(oident) == pass.TypesInfo.ObjectOf(ident) { + num++ + } + } + } + + return true + }) + return num >= 2 + } + fn := func(node ast.Node) { + block := node.(*ast.BlockStmt) + if len(block.List) < 2 { + return + } + for i, stmt := range block.List[:len(block.List)-1] { + _ = i + decl, ok := stmt.(*ast.DeclStmt) + if !ok { + continue + } + gdecl, ok := decl.Decl.(*ast.GenDecl) + if !ok || gdecl.Tok != token.VAR || len(gdecl.Specs) != 1 { + continue + } + vspec, ok := gdecl.Specs[0].(*ast.ValueSpec) + if !ok || len(vspec.Names) != 1 || len(vspec.Values) != 0 { + continue + } + + assign, ok := block.List[i+1].(*ast.AssignStmt) + if !ok || assign.Tok != token.ASSIGN { + continue + } + if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { + continue + } + ident, ok := assign.Lhs[0].(*ast.Ident) + if !ok { + continue + } + if pass.TypesInfo.ObjectOf(vspec.Names[0]) != pass.TypesInfo.ObjectOf(ident) { + continue + } + + if code.RefersTo(pass, assign.Rhs[0], pass.TypesInfo.ObjectOf(ident)) { + continue + } + if hasMultipleAssignments(block, ident) { + continue + } + + r := &ast.GenDecl{ + Specs: []ast.Spec{ + &ast.ValueSpec{ + Names: vspec.Names, + Values: []ast.Expr{assign.Rhs[0]}, + Type: vspec.Type, + }, + }, + Tok: gdecl.Tok, + } + report.Report(pass, decl, "should merge variable declaration with assignment on next line", + report.FilterGenerated(), + report.Fixes(edit.Fix("merge declaration with assignment", edit.ReplaceWithNode(pass.Fset, edit.Range{decl.Pos(), assign.End()}, r)))) + } + } + code.Preorder(pass, fn, (*ast.BlockStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1023/s1023.go b/tools/vendor/honnef.co/go/tools/simple/s1023/s1023.go new file mode 100644 index 000000000..a2e8fcd2b --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1023/s1023.go @@ -0,0 +1,79 @@ +package s1023 + +import ( + "go/ast" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1023", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Omit redundant control flow`, + Text: `Functions that have no return value do not need a return statement as +the final statement of the function. + +Switches in Go do not have automatic fallthrough, unlike languages +like C. It is not necessary to have a break statement as the final +statement in a case block.`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn1 := func(node ast.Node) { + clause := node.(*ast.CaseClause) + if len(clause.Body) < 2 { + return + } + branch, ok := clause.Body[len(clause.Body)-1].(*ast.BranchStmt) + if !ok || branch.Tok != token.BREAK || branch.Label != nil { + return + } + report.Report(pass, branch, "redundant break statement", report.FilterGenerated()) + } + fn2 := func(node ast.Node) { + var ret *ast.FieldList + var body *ast.BlockStmt + switch x := node.(type) { + case *ast.FuncDecl: + ret = x.Type.Results + body = x.Body + case *ast.FuncLit: + ret = x.Type.Results + body = x.Body + default: + lint.ExhaustiveTypeSwitch(node) + } + // if the func has results, a return can't be redundant. + // similarly, if there are no statements, there can be + // no return. + if ret != nil || body == nil || len(body.List) < 1 { + return + } + rst, ok := body.List[len(body.List)-1].(*ast.ReturnStmt) + if !ok { + return + } + // we don't need to check rst.Results as we already + // checked x.Type.Results to be nil. + report.Report(pass, rst, "redundant return statement", report.FilterGenerated()) + } + code.Preorder(pass, fn1, (*ast.CaseClause)(nil)) + code.Preorder(pass, fn2, (*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1024/s1024.go b/tools/vendor/honnef.co/go/tools/simple/s1024/s1024.go new file mode 100644 index 000000000..dbf8940b3 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1024/s1024.go @@ -0,0 +1,59 @@ +package s1024 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1024", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Replace \'x.Sub(time.Now())\' with \'time.Until(x)\'`, + Text: `The \'time.Until\' helper has the same effect as using \'x.Sub(time.Now())\' +but is easier to read.`, + Before: `x.Sub(time.Now())`, + After: `time.Until(x)`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkTimeUntilQ = pattern.MustParse(`(CallExpr (Symbol "(time.Time).Sub") [(CallExpr (Symbol "time.Now") [])])`) + checkTimeUntilR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Until")) [arg])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if _, ok := code.Match(pass, checkTimeUntilQ, node); ok { + if sel, ok := node.(*ast.CallExpr).Fun.(*ast.SelectorExpr); ok { + r := pattern.NodeToAST(checkTimeUntilR.Root, map[string]interface{}{"arg": sel.X}).(ast.Node) + report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())", + report.FilterGenerated(), + report.MinimumStdlibVersion("go1.8"), + report.Fixes(edit.Fix("replace with call to time.Until", edit.ReplaceWithNode(pass.Fset, node, r)))) + } else { + report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())", + report.MinimumStdlibVersion("go1.8"), + report.FilterGenerated()) + } + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1025/s1025.go b/tools/vendor/honnef.co/go/tools/simple/s1025/s1025.go new file mode 100644 index 000000000..3ea2996d1 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1025/s1025.go @@ -0,0 +1,158 @@ +package s1025 + +import ( + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + "honnef.co/go/tools/pattern" + + "golang.org/x/exp/typeparams" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1025", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Don't use \'fmt.Sprintf("%s", x)\' unnecessarily`, + Text: `In many instances, there are easier and more efficient ways of getting +a value's string representation. Whenever a value's underlying type is +a string already, or the type has a String method, they should be used +directly. + +Given the following shared definitions + + type T1 string + type T2 int + + func (T2) String() string { return "Hello, world" } + + var x string + var y T1 + var z T2 + +we can simplify + + fmt.Sprintf("%s", x) + fmt.Sprintf("%s", y) + fmt.Sprintf("%s", z) + +to + + x + string(y) + z.String() +`, + Since: "2017.1", + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkRedundantSprintfQ = pattern.MustParse(`(CallExpr (Symbol "fmt.Sprintf") [format arg])`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkRedundantSprintfQ, node) + if !ok { + return + } + + format := m.State["format"].(ast.Expr) + arg := m.State["arg"].(ast.Expr) + // TODO(dh): should we really support named constants here? + // shouldn't we only look for string literals? to avoid false + // positives via build tags? + if s, ok := code.ExprToString(pass, format); !ok || s != "%s" { + return + } + typ := pass.TypesInfo.TypeOf(arg) + if typeparams.IsTypeParam(typ) { + return + } + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg + + if typeutil.IsTypeWithName(typ, "reflect.Value") { + // printing with %s produces output different from using + // the String method + return + } + + if isFormatter(typ, &irpkg.Prog.MethodSets) { + // the type may choose to handle %s in arbitrary ways + return + } + + if types.Implements(typ, knowledge.Interfaces["fmt.Stringer"]) { + replacement := &ast.CallExpr{ + Fun: &ast.SelectorExpr{ + X: arg, + Sel: &ast.Ident{Name: "String"}, + }, + } + report.Report(pass, node, "should use String() instead of fmt.Sprintf", + report.Fixes(edit.Fix("replace with call to String method", edit.ReplaceWithNode(pass.Fset, node, replacement)))) + } else if types.Unalias(typ) == types.Universe.Lookup("string").Type() { + report.Report(pass, node, "the argument is already a string, there's no need to use fmt.Sprintf", + report.FilterGenerated(), + report.Fixes(edit.Fix("remove unnecessary call to fmt.Sprintf", edit.ReplaceWithNode(pass.Fset, node, arg)))) + } else if typ.Underlying() == types.Universe.Lookup("string").Type() { + replacement := &ast.CallExpr{ + Fun: &ast.Ident{Name: "string"}, + Args: []ast.Expr{arg}, + } + report.Report(pass, node, "the argument's underlying type is a string, should use a simple conversion instead of fmt.Sprintf", + report.FilterGenerated(), + report.Fixes(edit.Fix("replace with conversion to string", edit.ReplaceWithNode(pass.Fset, node, replacement)))) + } else if code.IsOfStringConvertibleByteSlice(pass, arg) { + replacement := &ast.CallExpr{ + Fun: &ast.Ident{Name: "string"}, + Args: []ast.Expr{arg}, + } + report.Report(pass, node, "the argument's underlying type is a slice of bytes, should use a simple conversion instead of fmt.Sprintf", + report.FilterGenerated(), + report.Fixes(edit.Fix("replace with conversion to string", edit.ReplaceWithNode(pass.Fset, node, replacement)))) + } + + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} + +func isFormatter(T types.Type, msCache *typeutil.MethodSetCache) bool { + // TODO(dh): this function also exists in staticcheck/lint.go – deduplicate. + + ms := msCache.MethodSet(T) + sel := ms.Lookup(nil, "Format") + if sel == nil { + return false + } + fn, ok := sel.Obj().(*types.Func) + if !ok { + // should be unreachable + return false + } + sig := fn.Type().(*types.Signature) + if sig.Params().Len() != 2 { + return false + } + // TODO(dh): check the types of the arguments for more + // precision + if sig.Results().Len() != 0 { + return false + } + return true +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1028/s1028.go b/tools/vendor/honnef.co/go/tools/simple/s1028/s1028.go new file mode 100644 index 000000000..2d2588e23 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1028/s1028.go @@ -0,0 +1,50 @@ +package s1028 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1028", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Simplify error construction with \'fmt.Errorf\'`, + Before: `errors.New(fmt.Sprintf(...))`, + After: `fmt.Errorf(...)`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkErrorsNewSprintfQ = pattern.MustParse(`(CallExpr (Symbol "errors.New") [(CallExpr (Symbol "fmt.Sprintf") args)])`) + checkErrorsNewSprintfR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "fmt") (Ident "Errorf")) args)`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if _, edits, ok := code.MatchAndEdit(pass, checkErrorsNewSprintfQ, checkErrorsNewSprintfR, node); ok { + // TODO(dh): the suggested fix may leave an unused import behind + report.Report(pass, node, "should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...))", + report.FilterGenerated(), + report.Fixes(edit.Fix("use fmt.Errorf", edits...))) + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1029/s1029.go b/tools/vendor/honnef.co/go/tools/simple/s1029/s1029.go new file mode 100644 index 000000000..1bf3f0097 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1029/s1029.go @@ -0,0 +1,31 @@ +package s1029 + +import ( + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/internal/sharedcheck" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1029", + Run: sharedcheck.CheckRangeStringRunes, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Range over the string directly`, + Text: `Ranging over a string will yield byte offsets and runes. If the offset +isn't used, this is functionally equivalent to converting the string +to a slice of runes and ranging over that. Ranging directly over the +string will be more performant, however, as it avoids allocating a new +slice, the size of which depends on the length of the string.`, + Before: `for _, r := range []rune(s) {}`, + After: `for _, r := range s {}`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer diff --git a/tools/vendor/honnef.co/go/tools/simple/s1030/s1030.go b/tools/vendor/honnef.co/go/tools/simple/s1030/s1030.go new file mode 100644 index 000000000..4adf8d8b5 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1030/s1030.go @@ -0,0 +1,83 @@ +package s1030 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1030", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use \'bytes.Buffer.String\' or \'bytes.Buffer.Bytes\'`, + Text: `\'bytes.Buffer\' has both a \'String\' and a \'Bytes\' method. It is almost never +necessary to use \'string(buf.Bytes())\' or \'[]byte(buf.String())\' – simply +use the other method. + +The only exception to this are map lookups. Due to a compiler optimization, +\'m[string(buf.Bytes())]\' is more efficient than \'m[buf.String()]\'. +`, + Since: "2017.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkBytesBufferConversionsQ = pattern.MustParse(`(CallExpr _ [(CallExpr sel@(SelectorExpr recv _) [])])`) + checkBytesBufferConversionsRs = pattern.MustParse(`(CallExpr (SelectorExpr recv (Ident "String")) [])`) + checkBytesBufferConversionsRb = pattern.MustParse(`(CallExpr (SelectorExpr recv (Ident "Bytes")) [])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + if pass.Pkg.Path() == "bytes" || pass.Pkg.Path() == "bytes_test" { + // The bytes package can use itself however it wants + return nil, nil + } + fn := func(node ast.Node, stack []ast.Node) { + m, ok := code.Match(pass, checkBytesBufferConversionsQ, node) + if !ok { + return + } + call := node.(*ast.CallExpr) + sel := m.State["sel"].(*ast.SelectorExpr) + + typ := pass.TypesInfo.TypeOf(call.Fun) + if types.Unalias(typ) == types.Universe.Lookup("string").Type() && code.IsCallTo(pass, call.Args[0], "(*bytes.Buffer).Bytes") { + if _, ok := stack[len(stack)-2].(*ast.IndexExpr); ok { + // Don't flag m[string(buf.Bytes())] – thanks to a + // compiler optimization, this is actually faster than + // m[buf.String()] + return + } + + report.Report(pass, call, fmt.Sprintf("should use %v.String() instead of %v", report.Render(pass, sel.X), report.Render(pass, call)), + report.FilterGenerated(), + report.Fixes(edit.Fix("simplify conversion", edit.ReplaceWithPattern(pass.Fset, node, checkBytesBufferConversionsRs, m.State)))) + } else if typ, ok := types.Unalias(typ).(*types.Slice); ok && + types.Unalias(typ.Elem()) == types.Universe.Lookup("byte").Type() && + code.IsCallTo(pass, call.Args[0], "(*bytes.Buffer).String") { + report.Report(pass, call, fmt.Sprintf("should use %v.Bytes() instead of %v", report.Render(pass, sel.X), report.Render(pass, call)), + report.FilterGenerated(), + report.Fixes(edit.Fix("simplify conversion", edit.ReplaceWithPattern(pass.Fset, node, checkBytesBufferConversionsRb, m.State)))) + } + + } + code.PreorderStack(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1031/s1031.go b/tools/vendor/honnef.co/go/tools/simple/s1031/s1031.go new file mode 100644 index 000000000..e1ce6aa04 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1031/s1031.go @@ -0,0 +1,79 @@ +package s1031 + +import ( + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1031", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Omit redundant nil check around loop`, + Text: `You can use range on nil slices and maps, the loop will simply never +execute. This makes an additional nil check around the loop +unnecessary.`, + Before: ` +if s != nil { + for _, x := range s { + ... + } +}`, + After: ` +for _, x := range s { + ... +}`, + Since: "2017.1", + // MergeIfAll because x might be a channel under some build tags. + // you shouldn't write code like that… + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkNilCheckAroundRangeQ = pattern.MustParse(` + (IfStmt + nil + (BinaryExpr x@(Object _) "!=" (Builtin "nil")) + [(RangeStmt _ _ _ x _)] + nil)`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkNilCheckAroundRangeQ, node) + if !ok { + return + } + ok = typeutil.All(m.State["x"].(types.Object).Type(), func(term *types.Term) bool { + switch term.Type().Underlying().(type) { + case *types.Slice, *types.Map: + return true + case *types.TypeParam, *types.Chan, *types.Pointer, *types.Signature: + return false + default: + lint.ExhaustiveTypeSwitch(term.Type().Underlying()) + return false + } + }) + if !ok { + return + } + report.Report(pass, node, "unnecessary nil check around range", report.ShortRange(), report.FilterGenerated()) + } + code.Preorder(pass, fn, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1032/s1032.go b/tools/vendor/honnef.co/go/tools/simple/s1032/s1032.go new file mode 100644 index 000000000..7a0873cca --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1032/s1032.go @@ -0,0 +1,128 @@ +package s1032 + +import ( + "go/ast" + "go/token" + "sort" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1032", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use \'sort.Ints(x)\', \'sort.Float64s(x)\', and \'sort.Strings(x)\'`, + Text: `The \'sort.Ints\', \'sort.Float64s\' and \'sort.Strings\' functions are easier to +read than \'sort.Sort(sort.IntSlice(x))\', \'sort.Sort(sort.Float64Slice(x))\' +and \'sort.Sort(sort.StringSlice(x))\'.`, + Before: `sort.Sort(sort.StringSlice(x))`, + After: `sort.Strings(x)`, + Since: "2019.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func isPermissibleSort(pass *analysis.Pass, node ast.Node) bool { + call := node.(*ast.CallExpr) + typeconv, ok := call.Args[0].(*ast.CallExpr) + if !ok { + return true + } + + sel, ok := typeconv.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + name := code.SelectorName(pass, sel) + switch name { + case "sort.IntSlice", "sort.Float64Slice", "sort.StringSlice": + default: + return true + } + + return false +} + +func run(pass *analysis.Pass) (interface{}, error) { + type Error struct { + node ast.Node + msg string + } + var allErrors []Error + fn := func(node ast.Node) { + var body *ast.BlockStmt + switch node := node.(type) { + case *ast.FuncLit: + body = node.Body + case *ast.FuncDecl: + body = node.Body + default: + lint.ExhaustiveTypeSwitch(node) + } + if body == nil { + return + } + + var errors []Error + permissible := false + fnSorts := func(node ast.Node) bool { + if permissible { + return false + } + if !code.IsCallTo(pass, node, "sort.Sort") { + return true + } + if isPermissibleSort(pass, node) { + permissible = true + return false + } + call := node.(*ast.CallExpr) + // isPermissibleSort guarantees that this type assertion will succeed + typeconv := call.Args[knowledge.Arg("sort.Sort.data")].(*ast.CallExpr) + sel := typeconv.Fun.(*ast.SelectorExpr) + name := code.SelectorName(pass, sel) + + switch name { + case "sort.IntSlice": + errors = append(errors, Error{node, "should use sort.Ints(...) instead of sort.Sort(sort.IntSlice(...))"}) + case "sort.Float64Slice": + errors = append(errors, Error{node, "should use sort.Float64s(...) instead of sort.Sort(sort.Float64Slice(...))"}) + case "sort.StringSlice": + errors = append(errors, Error{node, "should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...))"}) + } + return true + } + ast.Inspect(body, fnSorts) + + if permissible { + return + } + allErrors = append(allErrors, errors...) + } + code.Preorder(pass, fn, (*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)) + sort.Slice(allErrors, func(i, j int) bool { + return allErrors[i].node.Pos() < allErrors[j].node.Pos() + }) + var prev token.Pos + for _, err := range allErrors { + if err.node.Pos() == prev { + continue + } + prev = err.node.Pos() + report.Report(pass, err.node, err.msg, report.FilterGenerated()) + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1033/s1033.go b/tools/vendor/honnef.co/go/tools/simple/s1033/s1033.go new file mode 100644 index 000000000..bf2895298 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1033/s1033.go @@ -0,0 +1,55 @@ +package s1033 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1033", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Unnecessary guard around call to \"delete\"`, + Text: `Calling \'delete\' on a nil map is a no-op.`, + Since: "2019.2", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkGuardedDeleteQ = pattern.MustParse(` + (IfStmt + (AssignStmt + [(Ident "_") ok@(Ident _)] + ":=" + (IndexExpr m key)) + ok + [call@(CallExpr (Builtin "delete") [m key])] + nil)`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if m, ok := code.Match(pass, checkGuardedDeleteQ, node); ok { + report.Report(pass, node, "unnecessary guard around call to delete", + report.ShortRange(), + report.FilterGenerated(), + report.Fixes(edit.Fix("remove guard", edit.ReplaceWithNode(pass.Fset, node, m.State["call"].(ast.Node))))) + } + } + + code.Preorder(pass, fn, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1034/s1034.go b/tools/vendor/honnef.co/go/tools/simple/s1034/s1034.go new file mode 100644 index 000000000..e561dfe4f --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1034/s1034.go @@ -0,0 +1,119 @@ +package s1034 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1034", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use result of type assertion to simplify cases`, + Since: "2019.2", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkSimplifyTypeSwitchQ = pattern.MustParse(` + (TypeSwitchStmt + nil + expr@(TypeAssertExpr ident@(Ident _) _) + body)`) + checkSimplifyTypeSwitchR = pattern.MustParse(`(AssignStmt ident ":=" expr)`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkSimplifyTypeSwitchQ, node) + if !ok { + return + } + stmt := node.(*ast.TypeSwitchStmt) + expr := m.State["expr"].(ast.Node) + ident := m.State["ident"].(*ast.Ident) + + x := pass.TypesInfo.ObjectOf(ident) + var allOffenders []*ast.TypeAssertExpr + canSuggestFix := true + for _, clause := range stmt.Body.List { + clause := clause.(*ast.CaseClause) + if len(clause.List) != 1 { + continue + } + hasUnrelatedAssertion := false + var offenders []*ast.TypeAssertExpr + ast.Inspect(clause, func(node ast.Node) bool { + assert2, ok := node.(*ast.TypeAssertExpr) + if !ok { + return true + } + ident, ok := assert2.X.(*ast.Ident) + if !ok { + hasUnrelatedAssertion = true + return false + } + if pass.TypesInfo.ObjectOf(ident) != x { + hasUnrelatedAssertion = true + return false + } + + if !types.Identical(pass.TypesInfo.TypeOf(clause.List[0]), pass.TypesInfo.TypeOf(assert2.Type)) { + hasUnrelatedAssertion = true + return false + } + offenders = append(offenders, assert2) + return true + }) + if !hasUnrelatedAssertion { + // don't flag cases that have other type assertions + // unrelated to the one in the case clause. often + // times, this is done for symmetry, when two + // different values have to be asserted to the same + // type. + allOffenders = append(allOffenders, offenders...) + } + canSuggestFix = canSuggestFix && !hasUnrelatedAssertion + } + if len(allOffenders) != 0 { + var opts []report.Option + for _, offender := range allOffenders { + opts = append(opts, report.Related(offender, "could eliminate this type assertion")) + } + opts = append(opts, report.FilterGenerated()) + + msg := fmt.Sprintf("assigning the result of this type assertion to a variable (switch %s := %s.(type)) could eliminate type assertions in switch cases", + report.Render(pass, ident), report.Render(pass, ident)) + if canSuggestFix { + var edits []analysis.TextEdit + edits = append(edits, edit.ReplaceWithPattern(pass.Fset, expr, checkSimplifyTypeSwitchR, m.State)) + for _, offender := range allOffenders { + edits = append(edits, edit.ReplaceWithNode(pass.Fset, offender, offender.X)) + } + opts = append(opts, report.Fixes(edit.Fix("simplify type switch", edits...))) + report.Report(pass, expr, msg, opts...) + } else { + report.Report(pass, expr, msg, opts...) + } + } + } + code.Preorder(pass, fn, (*ast.TypeSwitchStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1035/s1035.go b/tools/vendor/honnef.co/go/tools/simple/s1035/s1035.go new file mode 100644 index 000000000..ed5faf757 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1035/s1035.go @@ -0,0 +1,56 @@ +package s1035 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1035", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Redundant call to \'net/http.CanonicalHeaderKey\' in method call on \'net/http.Header\'`, + Text: ` +The methods on \'net/http.Header\', namely \'Add\', \'Del\', \'Get\' +and \'Set\', already canonicalize the given header name.`, + Since: "2020.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + callName := code.CallName(pass, call) + switch callName { + case "(net/http.Header).Add", "(net/http.Header).Del", "(net/http.Header).Get", "(net/http.Header).Set": + default: + return + } + + if !code.IsCallTo(pass, call.Args[0], "net/http.CanonicalHeaderKey") { + return + } + + report.Report(pass, call, + fmt.Sprintf("calling net/http.CanonicalHeaderKey on the 'key' argument of %s is redundant", callName), + report.FilterGenerated(), + report.Fixes(edit.Fix("remove call to CanonicalHeaderKey", edit.ReplaceWithNode(pass.Fset, call.Args[0], call.Args[0].(*ast.CallExpr).Args[0])))) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1036/s1036.go b/tools/vendor/honnef.co/go/tools/simple/s1036/s1036.go new file mode 100644 index 000000000..ea675b13c --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1036/s1036.go @@ -0,0 +1,92 @@ +package s1036 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1036", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Unnecessary guard around map access`, + + Text: ` +When accessing a map key that doesn't exist yet, one receives a zero +value. Often, the zero value is a suitable value, for example when +using append or doing integer math. + +The following + + if _, ok := m["foo"]; ok { + m["foo"] = append(m["foo"], "bar") + } else { + m["foo"] = []string{"bar"} + } + +can be simplified to + + m["foo"] = append(m["foo"], "bar") + +and + + if _, ok := m2["k"]; ok { + m2["k"] += 4 + } else { + m2["k"] = 4 + } + +can be simplified to + + m["k"] += 4 +`, + Since: "2020.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkUnnecessaryGuardQ = pattern.MustParse(` + (Or + (IfStmt + (AssignStmt [(Ident "_") ok@(Ident _)] ":=" indexexpr@(IndexExpr _ _)) + ok + set@(AssignStmt indexexpr "=" (CallExpr (Builtin "append") indexexpr:values)) + (AssignStmt indexexpr "=" (CompositeLit _ values))) + (IfStmt + (AssignStmt [(Ident "_") ok] ":=" indexexpr@(IndexExpr _ _)) + ok + set@(AssignStmt indexexpr "+=" value) + (AssignStmt indexexpr "=" value)) + (IfStmt + (AssignStmt [(Ident "_") ok] ":=" indexexpr@(IndexExpr _ _)) + ok + set@(IncDecStmt indexexpr "++") + (AssignStmt indexexpr "=" (IntegerLiteral "1"))))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if m, ok := code.Match(pass, checkUnnecessaryGuardQ, node); ok { + if code.MayHaveSideEffects(pass, m.State["indexexpr"].(ast.Expr), nil) { + return + } + report.Report(pass, node, "unnecessary guard around map access", + report.ShortRange(), + report.Fixes(edit.Fix("simplify map access", edit.ReplaceWithNode(pass.Fset, node, m.State["set"].(ast.Node))))) + } + } + code.Preorder(pass, fn, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1037/s1037.go b/tools/vendor/honnef.co/go/tools/simple/s1037/s1037.go new file mode 100644 index 000000000..a72d42ccc --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1037/s1037.go @@ -0,0 +1,59 @@ +package s1037 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1037", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Elaborate way of sleeping`, + Text: `Using a select statement with a single case receiving +from the result of \'time.After\' is a very elaborate way of sleeping that +can much simpler be expressed with a simple call to time.Sleep.`, + Since: "2020.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkElaborateSleepQ = pattern.MustParse(`(SelectStmt (CommClause (UnaryExpr "<-" (CallExpr (Symbol "time.After") [arg])) body))`) + checkElaborateSleepR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Sleep")) [arg])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if m, ok := code.Match(pass, checkElaborateSleepQ, node); ok { + if body, ok := m.State["body"].([]ast.Stmt); ok && len(body) == 0 { + report.Report(pass, node, "should use time.Sleep instead of elaborate way of sleeping", + report.ShortRange(), + report.FilterGenerated(), + report.Fixes(edit.Fix("Use time.Sleep", edit.ReplaceWithPattern(pass.Fset, node, checkElaborateSleepR, m.State)))) + } else { + // TODO(dh): we could make a suggested fix if the body + // doesn't declare or shadow any identifiers + report.Report(pass, node, "should use time.Sleep instead of elaborate way of sleeping", + report.ShortRange(), + report.FilterGenerated()) + } + } + } + code.Preorder(pass, fn, (*ast.SelectStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1038/s1038.go b/tools/vendor/honnef.co/go/tools/simple/s1038/s1038.go new file mode 100644 index 000000000..301b90164 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1038/s1038.go @@ -0,0 +1,188 @@ +package s1038 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1038", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Unnecessarily complex way of printing formatted string", + Text: `Instead of using \'fmt.Print(fmt.Sprintf(...))\', one can use \'fmt.Printf(...)\'.`, + Since: "2020.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkPrintSprintQ = pattern.MustParse(` + (Or + (CallExpr + fn@(Or + (Symbol "fmt.Print") + (Symbol "fmt.Sprint") + (Symbol "fmt.Println") + (Symbol "fmt.Sprintln")) + [(CallExpr (Symbol "fmt.Sprintf") f:_)]) + (CallExpr + fn@(Or + (Symbol "fmt.Fprint") + (Symbol "fmt.Fprintln")) + [_ (CallExpr (Symbol "fmt.Sprintf") f:_)]))`) + + checkTestingErrorSprintfQ = pattern.MustParse(` + (CallExpr + sel@(SelectorExpr + recv + (Ident + name@(Or + "Error" + "Fatal" + "Fatalln" + "Log" + "Panic" + "Panicln" + "Print" + "Println" + "Skip"))) + [(CallExpr (Symbol "fmt.Sprintf") args)])`) + + checkLogSprintfQ = pattern.MustParse(` + (CallExpr + (Symbol + (Or + "log.Fatal" + "log.Fatalln" + "log.Panic" + "log.Panicln" + "log.Print" + "log.Println")) + [(CallExpr (Symbol "fmt.Sprintf") args)])`) + + checkSprintfMapping = map[string]struct { + recv string + alternative string + }{ + "(*testing.common).Error": {"(*testing.common)", "Errorf"}, + "(testing.TB).Error": {"(testing.TB)", "Errorf"}, + "(*testing.common).Fatal": {"(*testing.common)", "Fatalf"}, + "(testing.TB).Fatal": {"(testing.TB)", "Fatalf"}, + "(*testing.common).Log": {"(*testing.common)", "Logf"}, + "(testing.TB).Log": {"(testing.TB)", "Logf"}, + "(*testing.common).Skip": {"(*testing.common)", "Skipf"}, + "(testing.TB).Skip": {"(testing.TB)", "Skipf"}, + "(*log.Logger).Fatal": {"(*log.Logger)", "Fatalf"}, + "(*log.Logger).Fatalln": {"(*log.Logger)", "Fatalf"}, + "(*log.Logger).Panic": {"(*log.Logger)", "Panicf"}, + "(*log.Logger).Panicln": {"(*log.Logger)", "Panicf"}, + "(*log.Logger).Print": {"(*log.Logger)", "Printf"}, + "(*log.Logger).Println": {"(*log.Logger)", "Printf"}, + "log.Fatal": {"", "log.Fatalf"}, + "log.Fatalln": {"", "log.Fatalf"}, + "log.Panic": {"", "log.Panicf"}, + "log.Panicln": {"", "log.Panicf"}, + "log.Print": {"", "log.Printf"}, + "log.Println": {"", "log.Printf"}, + } +) + +func run(pass *analysis.Pass) (interface{}, error) { + fmtPrintf := func(node ast.Node) { + m, ok := code.Match(pass, checkPrintSprintQ, node) + if !ok { + return + } + + name := m.State["fn"].(*types.Func).Name() + var msg string + switch name { + case "Print", "Fprint", "Sprint": + newname := name + "f" + msg = fmt.Sprintf("should use fmt.%s instead of fmt.%s(fmt.Sprintf(...))", newname, name) + case "Println", "Fprintln", "Sprintln": + if _, ok := m.State["f"].(*ast.BasicLit); !ok { + // This may be an instance of + // fmt.Println(fmt.Sprintf(arg, ...)) where arg is an + // externally provided format string and the caller + // cannot guarantee that the format string ends with a + // newline. + return + } + newname := name[:len(name)-2] + "f" + msg = fmt.Sprintf("should use fmt.%s instead of fmt.%s(fmt.Sprintf(...)) (but don't forget the newline)", newname, name) + } + report.Report(pass, node, msg, + report.FilterGenerated()) + } + + methSprintf := func(node ast.Node) { + m, ok := code.Match(pass, checkTestingErrorSprintfQ, node) + if !ok { + return + } + mapped, ok := checkSprintfMapping[code.CallName(pass, node.(*ast.CallExpr))] + if !ok { + return + } + + // Ensure that Errorf/Fatalf refer to the right method + recvTV, ok := pass.TypesInfo.Types[m.State["recv"].(ast.Expr)] + if !ok { + return + } + obj, _, _ := types.LookupFieldOrMethod(recvTV.Type, recvTV.Addressable(), nil, mapped.alternative) + f, ok := obj.(*types.Func) + if !ok { + return + } + if typeutil.FuncName(f) != mapped.recv+"."+mapped.alternative { + return + } + + alt := &ast.SelectorExpr{ + X: m.State["recv"].(ast.Expr), + Sel: &ast.Ident{Name: mapped.alternative}, + } + report.Report(pass, node, fmt.Sprintf("should use %s(...) instead of %s(fmt.Sprintf(...))", report.Render(pass, alt), report.Render(pass, m.State["sel"].(*ast.SelectorExpr)))) + } + + pkgSprintf := func(node ast.Node) { + _, ok := code.Match(pass, checkLogSprintfQ, node) + if !ok { + return + } + callName := code.CallName(pass, node.(*ast.CallExpr)) + mapped, ok := checkSprintfMapping[callName] + if !ok { + return + } + report.Report(pass, node, fmt.Sprintf("should use %s(...) instead of %s(fmt.Sprintf(...))", mapped.alternative, callName)) + } + + fn := func(node ast.Node) { + fmtPrintf(node) + // TODO(dh): add suggested fixes + methSprintf(node) + pkgSprintf(node) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1039/s1039.go b/tools/vendor/honnef.co/go/tools/simple/s1039/s1039.go new file mode 100644 index 000000000..24eef6a11 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1039/s1039.go @@ -0,0 +1,71 @@ +package s1039 + +import ( + "fmt" + "go/ast" + "go/types" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1039", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Unnecessary use of \'fmt.Sprint\'`, + Text: ` +Calling \'fmt.Sprint\' with a single string argument is unnecessary +and identical to using the string directly.`, + Since: "2020.1", + // MergeIfAll because s might not be a string under all build tags. + // you shouldn't write code like that… + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkSprintLiteralQ = pattern.MustParse(` + (CallExpr + fn@(Or + (Symbol "fmt.Sprint") + (Symbol "fmt.Sprintf")) + [lit@(BasicLit "STRING" _)])`) + +func run(pass *analysis.Pass) (interface{}, error) { + // We only flag calls with string literals, not expressions of + // type string, because some people use fmt.Sprint(s) as a pattern + // for copying strings, which may be useful when extracting a small + // substring from a large string. + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkSprintLiteralQ, node) + if !ok { + return + } + callee := m.State["fn"].(*types.Func) + lit := m.State["lit"].(*ast.BasicLit) + if callee.Name() == "Sprintf" { + if strings.ContainsRune(lit.Value, '%') { + // This might be a format string + return + } + } + report.Report(pass, node, fmt.Sprintf("unnecessary use of fmt.%s", callee.Name()), + report.FilterGenerated(), + report.Fixes(edit.Fix("Replace with string literal", edit.ReplaceWithNode(pass.Fset, node, lit)))) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/simple/s1040/s1040.go b/tools/vendor/honnef.co/go/tools/simple/s1040/s1040.go new file mode 100644 index 000000000..d13dae4d4 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/simple/s1040/s1040.go @@ -0,0 +1,73 @@ +package s1040 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "S1040", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Type assertion to current type", + Text: `The type assertion \'x.(SomeInterface)\', when \'x\' already has type +\'SomeInterface\', can only fail if \'x\' is nil. Usually, this is +left-over code from when \'x\' had a different type and you can safely +delete the type assertion. If you want to check that \'x\' is not nil, +consider being explicit and using an actual \'if x == nil\' comparison +instead of relying on the type assertion panicking.`, + Since: "2021.1", + // MergeIfAll because x might have different types under different build tags. + // You shouldn't write code like that… + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + expr := node.(*ast.TypeAssertExpr) + if expr.Type == nil { + // skip type switches + // + // TODO(dh): we could flag type switches, too, when a case + // statement has the same type as expr.X – however, + // depending on the location of that case, it might behave + // identically to a default branch. we need to think + // carefully about the instances we want to flag. We also + // have to take nil interface values into consideration. + // + // It might make more sense to extend SA4020 to handle + // this. + return + } + t1 := pass.TypesInfo.TypeOf(expr.Type) + t2 := pass.TypesInfo.TypeOf(expr.X) + if types.IsInterface(t1) && types.Identical(t1, t2) { + report.Report(pass, expr, + fmt.Sprintf("type assertion to the same type: %s already has type %s", report.Render(pass, expr.X), report.Render(pass, expr.Type)), + report.FilterGenerated()) + } + } + + // TODO(dh): add suggested fixes. we need different fixes depending on the context: + // - assignment with 1 or 2 lhs + // - assignment to blank identifiers (as the first, second or both lhs) + // - initializers in if statements, with the same variations as above + + code.Preorder(pass, fn, (*ast.TypeAssertExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go b/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go index 210c348c9..fe8642aba 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go @@ -1,330 +1,200 @@ +// Code generated by generate.go. DO NOT EDIT. + package staticcheck import ( - "honnef.co/go/tools/analysis/facts/deprecated" - "honnef.co/go/tools/analysis/facts/generated" - "honnef.co/go/tools/analysis/facts/nilness" - "honnef.co/go/tools/analysis/facts/purity" - "honnef.co/go/tools/analysis/facts/tokenfile" - "honnef.co/go/tools/analysis/facts/typedness" "honnef.co/go/tools/analysis/lint" - "honnef.co/go/tools/internal/passes/buildir" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" + "honnef.co/go/tools/staticcheck/sa1000" + "honnef.co/go/tools/staticcheck/sa1001" + "honnef.co/go/tools/staticcheck/sa1002" + "honnef.co/go/tools/staticcheck/sa1003" + "honnef.co/go/tools/staticcheck/sa1004" + "honnef.co/go/tools/staticcheck/sa1005" + "honnef.co/go/tools/staticcheck/sa1006" + "honnef.co/go/tools/staticcheck/sa1007" + "honnef.co/go/tools/staticcheck/sa1008" + "honnef.co/go/tools/staticcheck/sa1010" + "honnef.co/go/tools/staticcheck/sa1011" + "honnef.co/go/tools/staticcheck/sa1012" + "honnef.co/go/tools/staticcheck/sa1013" + "honnef.co/go/tools/staticcheck/sa1014" + "honnef.co/go/tools/staticcheck/sa1015" + "honnef.co/go/tools/staticcheck/sa1016" + "honnef.co/go/tools/staticcheck/sa1017" + "honnef.co/go/tools/staticcheck/sa1018" + "honnef.co/go/tools/staticcheck/sa1019" + "honnef.co/go/tools/staticcheck/sa1020" + "honnef.co/go/tools/staticcheck/sa1021" + "honnef.co/go/tools/staticcheck/sa1023" + "honnef.co/go/tools/staticcheck/sa1024" + "honnef.co/go/tools/staticcheck/sa1025" + "honnef.co/go/tools/staticcheck/sa1026" + "honnef.co/go/tools/staticcheck/sa1027" + "honnef.co/go/tools/staticcheck/sa1028" + "honnef.co/go/tools/staticcheck/sa1029" + "honnef.co/go/tools/staticcheck/sa1030" + "honnef.co/go/tools/staticcheck/sa1031" + "honnef.co/go/tools/staticcheck/sa1032" + "honnef.co/go/tools/staticcheck/sa2000" + "honnef.co/go/tools/staticcheck/sa2001" + "honnef.co/go/tools/staticcheck/sa2002" + "honnef.co/go/tools/staticcheck/sa2003" + "honnef.co/go/tools/staticcheck/sa3000" + "honnef.co/go/tools/staticcheck/sa3001" + "honnef.co/go/tools/staticcheck/sa4000" + "honnef.co/go/tools/staticcheck/sa4001" + "honnef.co/go/tools/staticcheck/sa4003" + "honnef.co/go/tools/staticcheck/sa4004" + "honnef.co/go/tools/staticcheck/sa4005" + "honnef.co/go/tools/staticcheck/sa4006" + "honnef.co/go/tools/staticcheck/sa4008" + "honnef.co/go/tools/staticcheck/sa4009" + "honnef.co/go/tools/staticcheck/sa4010" + "honnef.co/go/tools/staticcheck/sa4011" + "honnef.co/go/tools/staticcheck/sa4012" + "honnef.co/go/tools/staticcheck/sa4013" + "honnef.co/go/tools/staticcheck/sa4014" + "honnef.co/go/tools/staticcheck/sa4015" + "honnef.co/go/tools/staticcheck/sa4016" + "honnef.co/go/tools/staticcheck/sa4017" + "honnef.co/go/tools/staticcheck/sa4018" + "honnef.co/go/tools/staticcheck/sa4019" + "honnef.co/go/tools/staticcheck/sa4020" + "honnef.co/go/tools/staticcheck/sa4021" + "honnef.co/go/tools/staticcheck/sa4022" + "honnef.co/go/tools/staticcheck/sa4023" + "honnef.co/go/tools/staticcheck/sa4024" + "honnef.co/go/tools/staticcheck/sa4025" + "honnef.co/go/tools/staticcheck/sa4026" + "honnef.co/go/tools/staticcheck/sa4027" + "honnef.co/go/tools/staticcheck/sa4028" + "honnef.co/go/tools/staticcheck/sa4029" + "honnef.co/go/tools/staticcheck/sa4030" + "honnef.co/go/tools/staticcheck/sa4031" + "honnef.co/go/tools/staticcheck/sa4032" + "honnef.co/go/tools/staticcheck/sa5000" + "honnef.co/go/tools/staticcheck/sa5001" + "honnef.co/go/tools/staticcheck/sa5002" + "honnef.co/go/tools/staticcheck/sa5003" + "honnef.co/go/tools/staticcheck/sa5004" + "honnef.co/go/tools/staticcheck/sa5005" + "honnef.co/go/tools/staticcheck/sa5007" + "honnef.co/go/tools/staticcheck/sa5008" + "honnef.co/go/tools/staticcheck/sa5009" + "honnef.co/go/tools/staticcheck/sa5010" + "honnef.co/go/tools/staticcheck/sa5011" + "honnef.co/go/tools/staticcheck/sa5012" + "honnef.co/go/tools/staticcheck/sa6000" + "honnef.co/go/tools/staticcheck/sa6001" + "honnef.co/go/tools/staticcheck/sa6002" + "honnef.co/go/tools/staticcheck/sa6003" + "honnef.co/go/tools/staticcheck/sa6005" + "honnef.co/go/tools/staticcheck/sa6006" + "honnef.co/go/tools/staticcheck/sa9001" + "honnef.co/go/tools/staticcheck/sa9002" + "honnef.co/go/tools/staticcheck/sa9003" + "honnef.co/go/tools/staticcheck/sa9004" + "honnef.co/go/tools/staticcheck/sa9005" + "honnef.co/go/tools/staticcheck/sa9006" + "honnef.co/go/tools/staticcheck/sa9007" + "honnef.co/go/tools/staticcheck/sa9008" + "honnef.co/go/tools/staticcheck/sa9009" ) -func makeCallCheckerAnalyzer(rules map[string]CallCheck, extraReqs ...*analysis.Analyzer) *analysis.Analyzer { - reqs := []*analysis.Analyzer{buildir.Analyzer, tokenfile.Analyzer} - reqs = append(reqs, extraReqs...) - return &analysis.Analyzer{ - Run: callChecker(rules), - Requires: reqs, - } +var Analyzers = []*lint.Analyzer{ + sa1000.SCAnalyzer, + sa1001.SCAnalyzer, + sa1002.SCAnalyzer, + sa1003.SCAnalyzer, + sa1004.SCAnalyzer, + sa1005.SCAnalyzer, + sa1006.SCAnalyzer, + sa1007.SCAnalyzer, + sa1008.SCAnalyzer, + sa1010.SCAnalyzer, + sa1011.SCAnalyzer, + sa1012.SCAnalyzer, + sa1013.SCAnalyzer, + sa1014.SCAnalyzer, + sa1015.SCAnalyzer, + sa1016.SCAnalyzer, + sa1017.SCAnalyzer, + sa1018.SCAnalyzer, + sa1019.SCAnalyzer, + sa1020.SCAnalyzer, + sa1021.SCAnalyzer, + sa1023.SCAnalyzer, + sa1024.SCAnalyzer, + sa1025.SCAnalyzer, + sa1026.SCAnalyzer, + sa1027.SCAnalyzer, + sa1028.SCAnalyzer, + sa1029.SCAnalyzer, + sa1030.SCAnalyzer, + sa1031.SCAnalyzer, + sa1032.SCAnalyzer, + sa2000.SCAnalyzer, + sa2001.SCAnalyzer, + sa2002.SCAnalyzer, + sa2003.SCAnalyzer, + sa3000.SCAnalyzer, + sa3001.SCAnalyzer, + sa4000.SCAnalyzer, + sa4001.SCAnalyzer, + sa4003.SCAnalyzer, + sa4004.SCAnalyzer, + sa4005.SCAnalyzer, + sa4006.SCAnalyzer, + sa4008.SCAnalyzer, + sa4009.SCAnalyzer, + sa4010.SCAnalyzer, + sa4011.SCAnalyzer, + sa4012.SCAnalyzer, + sa4013.SCAnalyzer, + sa4014.SCAnalyzer, + sa4015.SCAnalyzer, + sa4016.SCAnalyzer, + sa4017.SCAnalyzer, + sa4018.SCAnalyzer, + sa4019.SCAnalyzer, + sa4020.SCAnalyzer, + sa4021.SCAnalyzer, + sa4022.SCAnalyzer, + sa4023.SCAnalyzer, + sa4024.SCAnalyzer, + sa4025.SCAnalyzer, + sa4026.SCAnalyzer, + sa4027.SCAnalyzer, + sa4028.SCAnalyzer, + sa4029.SCAnalyzer, + sa4030.SCAnalyzer, + sa4031.SCAnalyzer, + sa4032.SCAnalyzer, + sa5000.SCAnalyzer, + sa5001.SCAnalyzer, + sa5002.SCAnalyzer, + sa5003.SCAnalyzer, + sa5004.SCAnalyzer, + sa5005.SCAnalyzer, + sa5007.SCAnalyzer, + sa5008.SCAnalyzer, + sa5009.SCAnalyzer, + sa5010.SCAnalyzer, + sa5011.SCAnalyzer, + sa5012.SCAnalyzer, + sa6000.SCAnalyzer, + sa6001.SCAnalyzer, + sa6002.SCAnalyzer, + sa6003.SCAnalyzer, + sa6005.SCAnalyzer, + sa6006.SCAnalyzer, + sa9001.SCAnalyzer, + sa9002.SCAnalyzer, + sa9003.SCAnalyzer, + sa9004.SCAnalyzer, + sa9005.SCAnalyzer, + sa9006.SCAnalyzer, + sa9007.SCAnalyzer, + sa9008.SCAnalyzer, + sa9009.SCAnalyzer, } - -var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ - "SA1000": makeCallCheckerAnalyzer(checkRegexpRules), - "SA1001": { - Run: CheckTemplate, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1002": makeCallCheckerAnalyzer(checkTimeParseRules), - "SA1003": makeCallCheckerAnalyzer(checkEncodingBinaryRules), - "SA1004": { - Run: CheckTimeSleepConstant, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1005": { - Run: CheckExec, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1006": { - Run: CheckUnsafePrintf, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1007": makeCallCheckerAnalyzer(checkURLsRules), - "SA1008": { - Run: CheckCanonicalHeaderKey, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1010": makeCallCheckerAnalyzer(checkRegexpFindAllRules), - "SA1011": makeCallCheckerAnalyzer(checkUTF8CutsetRules), - "SA1012": { - Run: CheckNilContext, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1013": { - Run: CheckSeeker, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1014": makeCallCheckerAnalyzer(checkUnmarshalPointerRules), - "SA1015": { - Run: CheckLeakyTimeTick, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA1016": { - Run: CheckUntrappableSignal, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA1017": makeCallCheckerAnalyzer(checkUnbufferedSignalChanRules), - "SA1018": makeCallCheckerAnalyzer(checkStringsReplaceZeroRules), - "SA1019": { - Run: CheckDeprecated, - Requires: []*analysis.Analyzer{inspect.Analyzer, deprecated.Analyzer, generated.Analyzer}, - }, - "SA1020": makeCallCheckerAnalyzer(checkListenAddressRules), - "SA1021": makeCallCheckerAnalyzer(checkBytesEqualIPRules), - "SA1023": { - Run: CheckWriterBufferModified, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA1024": makeCallCheckerAnalyzer(checkUniqueCutsetRules), - "SA1025": { - Run: CheckTimerResetReturnValue, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA1026": makeCallCheckerAnalyzer(checkUnsupportedMarshal), - "SA1027": makeCallCheckerAnalyzer(checkAtomicAlignment), - "SA1028": makeCallCheckerAnalyzer(checkSortSliceRules), - "SA1029": makeCallCheckerAnalyzer(checkWithValueKeyRules), - "SA1030": makeCallCheckerAnalyzer(checkStrconvRules), - - "SA2000": { - Run: CheckWaitgroupAdd, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA2001": { - Run: CheckEmptyCriticalSection, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA2002": { - Run: CheckConcurrentTesting, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA2003": { - Run: CheckDeferLock, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - - "SA3000": { - Run: CheckTestMainExit, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA3001": { - Run: CheckBenchmarkN, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - - "SA4000": { - Run: CheckLhsRhsIdentical, - Requires: []*analysis.Analyzer{inspect.Analyzer, tokenfile.Analyzer, generated.Analyzer}, - }, - "SA4001": { - Run: CheckIneffectiveCopy, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4003": { - Run: CheckExtremeComparison, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4004": { - Run: CheckIneffectiveLoop, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4005": { - Run: CheckIneffectiveFieldAssignments, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA4006": { - Run: CheckUnreadVariableValues, - Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, - }, - "SA4008": { - Run: CheckLoopCondition, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA4009": { - Run: CheckArgOverwritten, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA4010": { - Run: CheckIneffectiveAppend, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA4011": { - Run: CheckScopedBreak, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4012": { - Run: CheckNaNComparison, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA4013": { - Run: CheckDoubleNegation, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4014": { - Run: CheckRepeatedIfElse, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4015": makeCallCheckerAnalyzer(checkMathIntRules), - "SA4016": { - Run: CheckSillyBitwiseOps, - Requires: []*analysis.Analyzer{inspect.Analyzer, tokenfile.Analyzer}, - }, - "SA4017": { - Run: CheckSideEffectFreeCalls, - Requires: []*analysis.Analyzer{buildir.Analyzer, purity.Analyzer}, - }, - "SA4018": { - Run: CheckSelfAssignment, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer, purity.Analyzer}, - }, - "SA4019": { - Run: CheckDuplicateBuildConstraints, - Requires: []*analysis.Analyzer{generated.Analyzer}, - }, - "SA4020": { - Run: CheckUnreachableTypeCases, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4021": { - Run: CheckSingleArgAppend, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer}, - }, - "SA4022": { - Run: CheckAddressIsNil, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4023": { - Run: CheckTypedNilInterface, - Requires: []*analysis.Analyzer{buildir.Analyzer, typedness.Analysis, nilness.Analysis}, - }, - "SA4024": { - Run: CheckBuiltinZeroComparison, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4025": { - Run: CheckIntegerDivisionEqualsZero, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4026": { - Run: CheckNegativeZeroFloat, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4027": { - Run: CheckIneffectiveURLQueryModification, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4028": { - Run: CheckModuloOne, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4029": { - Run: CheckIneffectiveSort, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4030": { - Run: CheckIneffectiveRandInt, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA4031": { - Run: CheckAllocationNilCheck, - Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer, tokenfile.Analyzer}, - }, - - "SA5000": { - Run: CheckNilMaps, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA5001": { - Run: CheckEarlyDefer, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA5002": { - Run: CheckInfiniteEmptyLoop, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA5003": { - Run: CheckDeferInInfiniteLoop, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA5004": { - Run: CheckLoopEmptyDefault, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA5005": { - Run: CheckCyclicFinalizer, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA5007": { - Run: CheckInfiniteRecursion, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA5008": { - Run: CheckStructTags, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA5009": makeCallCheckerAnalyzer(checkPrintfRules), - "SA5010": { - Run: CheckImpossibleTypeAssertion, - Requires: []*analysis.Analyzer{buildir.Analyzer, tokenfile.Analyzer}, - }, - "SA5011": { - Run: CheckMaybeNil, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA5012": { - Run: CheckEvenSliceLength, - FactTypes: []analysis.Fact{new(evenElements)}, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - - "SA6000": makeCallCheckerAnalyzer(checkRegexpMatchLoopRules), - "SA6001": { - Run: CheckMapBytesKey, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA6002": makeCallCheckerAnalyzer(checkSyncPoolValueRules), - "SA6003": { - Run: CheckRangeStringRunes, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "SA6005": { - Run: CheckToLowerToUpperComparison, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - - "SA9001": { - Run: CheckDubiousDeferInChannelRangeLoop, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA9002": { - Run: CheckNonOctalFileMode, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA9003": { - Run: CheckEmptyBranch, - Requires: []*analysis.Analyzer{buildir.Analyzer, tokenfile.Analyzer, generated.Analyzer}, - }, - "SA9004": { - Run: CheckMissingEnumTypesInDeclaration, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - // Filtering generated code because it may include empty structs generated from data models. - "SA9005": makeCallCheckerAnalyzer(checkNoopMarshal, generated.Analyzer), - "SA9006": { - Run: CheckStaticBitShift, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "SA9007": { - Run: CheckBadRemoveAll, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - - "SA9008": { - Run: CheckTypeAssertionShadowingElse, - Requires: []*analysis.Analyzer{inspect.Analyzer, buildir.Analyzer, tokenfile.Analyzer}, - }, -}) diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/buildtag.go b/tools/vendor/honnef.co/go/tools/staticcheck/buildtag.go deleted file mode 100644 index 97ccf77b4..000000000 --- a/tools/vendor/honnef.co/go/tools/staticcheck/buildtag.go +++ /dev/null @@ -1,21 +0,0 @@ -package staticcheck - -import ( - "go/ast" - "strings" - - "honnef.co/go/tools/go/ast/astutil" -) - -func buildTags(f *ast.File) [][]string { - var out [][]string - for _, line := range strings.Split(astutil.Preamble(f), "\n") { - if !strings.HasPrefix(line, "+build ") { - continue - } - line = strings.TrimSpace(strings.TrimPrefix(line, "+build ")) - fields := strings.Fields(line) - out = append(out, fields) - } - return out -} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/doc.go b/tools/vendor/honnef.co/go/tools/staticcheck/doc.go index c28fdbf04..462acee3d 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/doc.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/doc.go @@ -1,1302 +1,5 @@ +//go:generate go run ../generate.go + // Package staticcheck contains analyzes that find bugs and performance issues. // Barring the rare false positive, any code flagged by these analyzes needs to be fixed. package staticcheck - -import "honnef.co/go/tools/analysis/lint" - -var Docs = lint.Markdownify(map[string]*lint.RawDocumentation{ - "SA1000": { - Title: `Invalid regular expression`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1001": { - Title: `Invalid template`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1002": { - Title: `Invalid format in \'time.Parse\'`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1003": { - Title: `Unsupported argument to functions in \'encoding/binary\'`, - Text: `The \'encoding/binary\' package can only serialize types with known sizes. -This precludes the use of the \'int\' and \'uint\' types, as their sizes -differ on different architectures. Furthermore, it doesn't support -serializing maps, channels, strings, or functions. - -Before Go 1.8, \'bool\' wasn't supported, either.`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1004": { - Title: `Suspiciously small untyped constant in \'time.Sleep\'`, - Text: `The \'time\'.Sleep function takes a \'time.Duration\' as its only argument. -Durations are expressed in nanoseconds. Thus, calling \'time.Sleep(1)\' -will sleep for 1 nanosecond. This is a common source of bugs, as sleep -functions in other languages often accept seconds or milliseconds. - -The \'time\' package provides constants such as \'time.Second\' to express -large durations. These can be combined with arithmetic to express -arbitrary durations, for example \'5 * time.Second\' for 5 seconds. - -If you truly meant to sleep for a tiny amount of time, use -\'n * time.Nanosecond\' to signal to Staticcheck that you did mean to sleep -for some amount of nanoseconds.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1005": { - Title: `Invalid first argument to \'exec.Command\'`, - Text: `\'os/exec\' runs programs directly (using variants of the fork and exec -system calls on Unix systems). This shouldn't be confused with running -a command in a shell. The shell will allow for features such as input -redirection, pipes, and general scripting. The shell is also -responsible for splitting the user's input into a program name and its -arguments. For example, the equivalent to - - ls / /tmp - -would be - - exec.Command("ls", "/", "/tmp") - -If you want to run a command in a shell, consider using something like -the following – but be aware that not all systems, particularly -Windows, will have a \'/bin/sh\' program: - - exec.Command("/bin/sh", "-c", "ls | grep Awesome")`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1006": { - Title: `\'Printf\' with dynamic first argument and no further arguments`, - Text: `Using \'fmt.Printf\' with a dynamic first argument can lead to unexpected -output. The first argument is a format string, where certain character -combinations have special meaning. If, for example, a user were to -enter a string such as - - Interest rate: 5% - -and you printed it with - - fmt.Printf(s) - -it would lead to the following output: - - Interest rate: 5%!(NOVERB). - -Similarly, forming the first parameter via string concatenation with -user input should be avoided for the same reason. When printing user -input, either use a variant of \'fmt.Print\', or use the \'%s\' Printf verb -and pass the string as an argument.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1007": { - Title: `Invalid URL in \'net/url.Parse\'`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1008": { - Title: `Non-canonical key in \'http.Header\' map`, - Text: `Keys in \'http.Header\' maps are canonical, meaning they follow a specific -combination of uppercase and lowercase letters. Methods such as -\'http.Header.Add\' and \'http.Header.Del\' convert inputs into this canonical -form before manipulating the map. - -When manipulating \'http.Header\' maps directly, as opposed to using the -provided methods, care should be taken to stick to canonical form in -order to avoid inconsistencies. The following piece of code -demonstrates one such inconsistency: - - h := http.Header{} - h["etag"] = []string{"1234"} - h.Add("etag", "5678") - fmt.Println(h) - - // Output: - // map[Etag:[5678] etag:[1234]] - -The easiest way of obtaining the canonical form of a key is to use -\'http.CanonicalHeaderKey\'.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1010": { - Title: `\'(*regexp.Regexp).FindAll\' called with \'n == 0\', which will always return zero results`, - Text: `If \'n >= 0\', the function returns at most \'n\' matches/submatches. To -return all results, specify a negative number.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants - }, - - "SA1011": { - Title: `Various methods in the \"strings\" package expect valid UTF-8, but invalid input is provided`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1012": { - Title: `A nil \'context.Context\' is being passed to a function, consider using \'context.TODO\' instead`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1013": { - Title: `\'io.Seeker.Seek\' is being called with the whence constant as the first argument, but it should be the second`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1014": { - Title: `Non-pointer value passed to \'Unmarshal\' or \'Decode\'`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1015": { - Title: `Using \'time.Tick\' in a way that will leak. Consider using \'time.NewTicker\', and only use \'time.Tick\' in tests, commands and endless functions`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1016": { - Title: `Trapping a signal that cannot be trapped`, - Text: `Not all signals can be intercepted by a process. Specifically, on -UNIX-like systems, the \'syscall.SIGKILL\' and \'syscall.SIGSTOP\' signals are -never passed to the process, but instead handled directly by the -kernel. It is therefore pointless to try and handle these signals.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1017": { - Title: `Channels used with \'os/signal.Notify\' should be buffered`, - Text: `The \'os/signal\' package uses non-blocking channel sends when delivering -signals. If the receiving end of the channel isn't ready and the -channel is either unbuffered or full, the signal will be dropped. To -avoid missing signals, the channel should be buffered and of the -appropriate size. For a channel used for notification of just one -signal value, a buffer of size 1 is sufficient.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1018": { - Title: `\'strings.Replace\' called with \'n == 0\', which does nothing`, - Text: `With \'n == 0\', zero instances will be replaced. To replace all -instances, use a negative number, or use \'strings.ReplaceAll\'.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants - }, - - "SA1019": { - Title: `Using a deprecated function, variable, constant or field`, - Since: "2017.1", - Severity: lint.SeverityDeprecated, - MergeIf: lint.MergeIfAny, - }, - - "SA1020": { - Title: `Using an invalid host:port pair with a \'net.Listen\'-related function`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1021": { - Title: `Using \'bytes.Equal\' to compare two \'net.IP\'`, - Text: `A \'net.IP\' stores an IPv4 or IPv6 address as a slice of bytes. The -length of the slice for an IPv4 address, however, can be either 4 or -16 bytes long, using different ways of representing IPv4 addresses. In -order to correctly compare two \'net.IP\'s, the \'net.IP.Equal\' method should -be used, as it takes both representations into account.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1023": { - Title: `Modifying the buffer in an \'io.Writer\' implementation`, - Text: `\'Write\' must not modify the slice data, even temporarily.`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1024": { - Title: `A string cutset contains duplicate characters`, - Text: `The \'strings.TrimLeft\' and \'strings.TrimRight\' functions take cutsets, not -prefixes. A cutset is treated as a set of characters to remove from a -string. For example, - - strings.TrimLeft("42133word", "1234") - -will result in the string \'"word"\' – any characters that are 1, 2, 3 or -4 are cut from the left of the string. - -In order to remove one string from another, use \'strings.TrimPrefix\' instead.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1025": { - Title: `It is not possible to use \'(*time.Timer).Reset\''s return value correctly`, - Since: "2019.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1026": { - Title: `Cannot marshal channels or functions`, - Since: "2019.2", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1027": { - Title: `Atomic access to 64-bit variable must be 64-bit aligned`, - Text: `On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility to -arrange for 64-bit alignment of 64-bit words accessed atomically. The -first word in a variable or in an allocated struct, array, or slice -can be relied upon to be 64-bit aligned. - -You can use the structlayout tool to inspect the alignment of fields -in a struct.`, - Since: "2019.2", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1028": { - Title: `\'sort.Slice\' can only be used on slices`, - Text: `The first argument of \'sort.Slice\' must be a slice.`, - Since: "2020.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA1029": { - Title: `Inappropriate key in call to \'context.WithValue\'`, - Text: `The provided key must be comparable and should not be -of type \'string\' or any other built-in type to avoid collisions between -packages using context. Users of \'WithValue\' should define their own -types for keys. - -To avoid allocating when assigning to an \'interface{}\', -context keys often have concrete type \'struct{}\'. Alternatively, -exported context key variables' static type should be a pointer or -interface.`, - Since: "2020.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA1030": { - Title: `Invalid argument in call to a \'strconv\' function`, - Text: `This check validates the format, number base and bit size arguments of -the various parsing and formatting functions in \'strconv\'.`, - Since: "2021.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA2000": { - Title: `\'sync.WaitGroup.Add\' called inside the goroutine, leading to a race condition`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA2001": { - Title: `Empty critical section, did you mean to defer the unlock?`, - Text: `Empty critical sections of the kind - - mu.Lock() - mu.Unlock() - -are very often a typo, and the following was intended instead: - - mu.Lock() - defer mu.Unlock() - -Do note that sometimes empty critical sections can be useful, as a -form of signaling to wait on another goroutine. Many times, there are -simpler ways of achieving the same effect. When that isn't the case, -the code should be amply commented to avoid confusion. Combining such -comments with a \'//lint:ignore\' directive can be used to suppress this -rare false positive.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA2002": { - Title: `Called \'testing.T.FailNow\' or \'SkipNow\' in a goroutine, which isn't allowed`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA2003": { - Title: `Deferred \'Lock\' right after locking, likely meant to defer \'Unlock\' instead`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA3000": { - Title: `\'TestMain\' doesn't call \'os.Exit\', hiding test failures`, - Text: `Test executables (and in turn \"go test\") exit with a non-zero status -code if any tests failed. When specifying your own \'TestMain\' function, -it is your responsibility to arrange for this, by calling \'os.Exit\' with -the correct code. The correct code is returned by \'(*testing.M).Run\', so -the usual way of implementing \'TestMain\' is to end it with -\'os.Exit(m.Run())\'.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA3001": { - Title: `Assigning to \'b.N\' in benchmarks distorts the results`, - Text: `The testing package dynamically sets \'b.N\' to improve the reliability of -benchmarks and uses it in computations to determine the duration of a -single operation. Benchmark code must not alter \'b.N\' as this would -falsify results.`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA4000": { - Title: `Binary operator has identical expressions on both sides`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4001": { - Title: `\'&*x\' gets simplified to \'x\', it does not copy \'x\'`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4003": { - Title: `Comparing unsigned values against negative values is pointless`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4004": { - Title: `The loop exits unconditionally after one iteration`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4005": { - Title: `Field assignment that will never be observed. Did you mean to use a pointer receiver?`, - Since: "2021.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4006": { - Title: `A value assigned to a variable is never read before being overwritten. Forgotten error check or dead code?`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4008": { - Title: `The variable in the loop condition never changes, are you incrementing the wrong variable?`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4009": { - Title: `A function argument is overwritten before its first use`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4010": { - Title: `The result of \'append\' will never be observed anywhere`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4011": { - Title: `Break statement with no effect. Did you mean to break out of an outer loop?`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4012": { - Title: `Comparing a value against NaN even though no value is equal to NaN`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4013": { - Title: `Negating a boolean twice (\'!!b\') is the same as writing \'b\'. This is either redundant, or a typo.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4014": { - Title: `An if/else if chain has repeated conditions and no side-effects; if the condition didn't match the first time, it won't match the second time, either`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4015": { - Title: `Calling functions like \'math.Ceil\' on floats converted from integers doesn't do anything useful`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4016": { - Title: `Certain bitwise operations, such as \'x ^ 0\', do not do anything useful`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants - }, - - "SA4017": { - Title: `Discarding the return values of a function without side effects, making the call pointless`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4018": { - Title: `Self-assignment of variables`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4019": { - Title: `Multiple, identical build constraints in the same file`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4020": { - Title: `Unreachable case clause in a type switch`, - Text: `In a type switch like the following - - type T struct{} - func (T) Read(b []byte) (int, error) { return 0, nil } - - var v interface{} = T{} - - switch v.(type) { - case io.Reader: - // ... - case T: - // unreachable - } - -the second case clause can never be reached because \'T\' implements -\'io.Reader\' and case clauses are evaluated in source order. - -Another example: - - type T struct{} - func (T) Read(b []byte) (int, error) { return 0, nil } - func (T) Close() error { return nil } - - var v interface{} = T{} - - switch v.(type) { - case io.Reader: - // ... - case io.ReadCloser: - // unreachable - } - -Even though \'T\' has a \'Close\' method and thus implements \'io.ReadCloser\', -\'io.Reader\' will always match first. The method set of \'io.Reader\' is a -subset of \'io.ReadCloser\'. Thus it is impossible to match the second -case without matching the first case. - - -Structurally equivalent interfaces - -A special case of the previous example are structurally identical -interfaces. Given these declarations - - type T error - type V error - - func doSomething() error { - err, ok := doAnotherThing() - if ok { - return T(err) - } - - return U(err) - } - -the following type switch will have an unreachable case clause: - - switch doSomething().(type) { - case T: - // ... - case V: - // unreachable - } - -\'T\' will always match before V because they are structurally equivalent -and therefore \'doSomething()\''s return value implements both.`, - Since: "2019.2", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA4021": { - Title: `\"x = append(y)\" is equivalent to \"x = y\"`, - Since: "2019.2", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4022": { - Title: `Comparing the address of a variable against nil`, - Text: `Code such as \"if &x == nil\" is meaningless, because taking the address of a variable always yields a non-nil pointer.`, - Since: "2020.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4023": { - Title: `Impossible comparison of interface value with untyped nil`, - Text: `Under the covers, interfaces are implemented as two elements, a -type T and a value V. V is a concrete value such as an int, -struct or pointer, never an interface itself, and has type T. For -instance, if we store the int value 3 in an interface, the -resulting interface value has, schematically, (T=int, V=3). The -value V is also known as the interface's dynamic value, since a -given interface variable might hold different values V (and -corresponding types T) during the execution of the program. - -An interface value is nil only if the V and T are both -unset, (T=nil, V is not set), In particular, a nil interface will -always hold a nil type. If we store a nil pointer of type *int -inside an interface value, the inner type will be *int regardless -of the value of the pointer: (T=*int, V=nil). Such an interface -value will therefore be non-nil even when the pointer value V -inside is nil. - -This situation can be confusing, and arises when a nil value is -stored inside an interface value such as an error return: - - func returnsError() error { - var p *MyError = nil - if bad() { - p = ErrBad - } - return p // Will always return a non-nil error. - } - -If all goes well, the function returns a nil p, so the return -value is an error interface value holding (T=*MyError, V=nil). -This means that if the caller compares the returned error to nil, -it will always look as if there was an error even if nothing bad -happened. To return a proper nil error to the caller, the -function must return an explicit nil: - - func returnsError() error { - if bad() { - return ErrBad - } - return nil - } - -It's a good idea for functions that return errors always to use -the error type in their signature (as we did above) rather than a -concrete type such as \'*MyError\', to help guarantee the error is -created correctly. As an example, \'os.Open\' returns an error even -though, if not nil, it's always of concrete type *os.PathError. - -Similar situations to those described here can arise whenever -interfaces are used. Just keep in mind that if any concrete value -has been stored in the interface, the interface will not be nil. -For more information, see The Laws of -Reflection (https://golang.org/doc/articles/laws_of_reflection.html). - -This text has been copied from -https://golang.org/doc/faq#nil_error, licensed under the Creative -Commons Attribution 3.0 License.`, - Since: "2020.2", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, // TODO should this be MergeIfAll? - }, - - "SA4024": { - Title: `Checking for impossible return value from a builtin function`, - Text: `Return values of the \'len\' and \'cap\' builtins cannot be negative. - -See https://golang.org/pkg/builtin/#len and https://golang.org/pkg/builtin/#cap. - -Example: - - if len(slice) < 0 { - fmt.Println("unreachable code") - }`, - Since: "2021.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4025": { - Title: "Integer division of literals that results in zero", - Text: `When dividing two integer constants, the result will -also be an integer. Thus, a division such as \'2 / 3\' results in \'0\'. -This is true for all of the following examples: - - _ = 2 / 3 - const _ = 2 / 3 - const _ float64 = 2 / 3 - _ = float64(2 / 3) - -Staticcheck will flag such divisions if both sides of the division are -integer literals, as it is highly unlikely that the division was -intended to truncate to zero. Staticcheck will not flag integer -division involving named constants, to avoid noisy positives. -`, - Since: "2021.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4026": { - Title: "Go constants cannot express negative zero", - Text: `In IEEE 754 floating point math, zero has a sign and can be positive -or negative. This can be useful in certain numerical code. - -Go constants, however, cannot express negative zero. This means that -the literals \'-0.0\' and \'0.0\' have the same ideal value (zero) and -will both represent positive zero at runtime. - -To explicitly and reliably create a negative zero, you can use the -\'math.Copysign\' function: \'math.Copysign(0, -1)\'.`, - Since: "2021.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4027": { - Title: `\'(*net/url.URL).Query\' returns a copy, modifying it doesn't change the URL`, - Text: `\'(*net/url.URL).Query\' parses the current value of \'net/url.URL.RawQuery\' -and returns it as a map of type \'net/url.Values\'. Subsequent changes to -this map will not affect the URL unless the map gets encoded and -assigned to the URL's \'RawQuery\'. - -As a consequence, the following code pattern is an expensive no-op: -\'u.Query().Add(key, value)\'.`, - Since: "2021.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4028": { - Title: `\'x % 1\' is always zero`, - Since: "2022.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants - }, - - "SA4029": { - Title: "Ineffective attempt at sorting slice", - Text: ` -\'sort.Float64Slice\', \'sort.IntSlice\', and \'sort.StringSlice\' are -types, not functions. Doing \'x = sort.StringSlice(x)\' does nothing, -especially not sort any values. The correct usage is -\'sort.Sort(sort.StringSlice(x))\' or \'sort.StringSlice(x).Sort()\', -but there are more convenient helpers, namely \'sort.Float64s\', -\'sort.Ints\', and \'sort.Strings\'. -`, - Since: "2022.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4030": { - Title: "Ineffective attempt at generating random number", - Text: ` -Functions in the \'math/rand\' package that accept upper limits, such -as \'Intn\', generate random numbers in the half-open interval [0,n). In -other words, the generated numbers will be \'>= 0\' and \'< n\' – they -don't include \'n\'. \'rand.Intn(1)\' therefore doesn't generate \'0\' -or \'1\', it always generates \'0\'.`, - Since: "2022.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA4031": { - Title: `Checking never-nil value against nil`, - Since: "2022.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5000": { - Title: `Assignment to nil map`, - Since: "2017.1", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA5001": { - Title: `Deferring \'Close\' before checking for a possible error`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5002": { - Title: `The empty for loop (\"for {}\") spins and can block the scheduler`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5003": { - Title: `Defers in infinite loops will never execute`, - Text: `Defers are scoped to the surrounding function, not the surrounding -block. In a function that never returns, i.e. one containing an -infinite loop, defers will never execute.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5004": { - Title: `\"for { select { ...\" with an empty default branch spins`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5005": { - Title: `The finalizer references the finalized object, preventing garbage collection`, - Text: `A finalizer is a function associated with an object that runs when the -garbage collector is ready to collect said object, that is when the -object is no longer referenced by anything. - -If the finalizer references the object, however, it will always remain -as the final reference to that object, preventing the garbage -collector from collecting the object. The finalizer will never run, -and the object will never be collected, leading to a memory leak. That -is why the finalizer should instead use its first argument to operate -on the object. That way, the number of references can temporarily go -to zero before the object is being passed to the finalizer.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5007": { - Title: `Infinite recursive call`, - Text: `A function that calls itself recursively needs to have an exit -condition. Otherwise it will recurse forever, until the system runs -out of memory. - -This issue can be caused by simple bugs such as forgetting to add an -exit condition. It can also happen "on purpose". Some languages have -tail call optimization which makes certain infinite recursive calls -safe to use. Go, however, does not implement TCO, and as such a loop -should be used instead.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5008": { - Title: `Invalid struct tag`, - Since: "2019.2", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5009": { - Title: `Invalid Printf call`, - Since: "2019.2", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA5010": { - Title: `Impossible type assertion`, - - Text: `Some type assertions can be statically proven to be -impossible. This is the case when the method sets of both -arguments of the type assertion conflict with each other, for -example by containing the same method with different -signatures. - -The Go compiler already applies this check when asserting from an -interface value to a concrete type. If the concrete type misses -methods from the interface, or if function signatures don't match, -then the type assertion can never succeed. - -This check applies the same logic when asserting from one interface to -another. If both interface types contain the same method but with -different signatures, then the type assertion can never succeed, -either.`, - - Since: "2020.1", - Severity: lint.SeverityWarning, - // Technically this should be MergeIfAll, but the Go compiler - // already flags some impossible type assertions, so - // MergeIfAny is consistent with the compiler. - MergeIf: lint.MergeIfAny, - }, - - "SA5011": { - Title: `Possible nil pointer dereference`, - - Text: `A pointer is being dereferenced unconditionally, while -also being checked against nil in another place. This suggests that -the pointer may be nil and dereferencing it may panic. This is -commonly a result of improperly ordered code or missing return -statements. Consider the following examples: - - func fn(x *int) { - fmt.Println(*x) - - // This nil check is equally important for the previous dereference - if x != nil { - foo(*x) - } - } - - func TestFoo(t *testing.T) { - x := compute() - if x == nil { - t.Errorf("nil pointer received") - } - - // t.Errorf does not abort the test, so if x is nil, the next line will panic. - foo(*x) - } - -Staticcheck tries to deduce which functions abort control flow. -For example, it is aware that a function will not continue -execution after a call to \'panic\' or \'log.Fatal\'. However, sometimes -this detection fails, in particular in the presence of -conditionals. Consider the following example: - - func Log(msg string, level int) { - fmt.Println(msg) - if level == levelFatal { - os.Exit(1) - } - } - - func Fatal(msg string) { - Log(msg, levelFatal) - } - - func fn(x *int) { - if x == nil { - Fatal("unexpected nil pointer") - } - fmt.Println(*x) - } - -Staticcheck will flag the dereference of \'x\', even though it is perfectly -safe. Staticcheck is not able to deduce that a call to -Fatal will exit the program. For the time being, the easiest -workaround is to modify the definition of Fatal like so: - - func Fatal(msg string) { - Log(msg, levelFatal) - panic("unreachable") - } - -We also hard-code functions from common logging packages such as -logrus. Please file an issue if we're missing support for a -popular package.`, - Since: "2020.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA5012": { - Title: "Passing odd-sized slice to function expecting even size", - Text: `Some functions that take slices as parameters expect the slices to have an even number of elements. -Often, these functions treat elements in a slice as pairs. -For example, \'strings.NewReplacer\' takes pairs of old and new strings, -and calling it with an odd number of elements would be an error.`, - Since: "2020.2", - Severity: lint.SeverityError, - MergeIf: lint.MergeIfAny, - }, - - "SA6000": { - Title: `Using \'regexp.Match\' or related in a loop, should use \'regexp.Compile\'`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA6001": { - Title: `Missing an optimization opportunity when indexing maps by byte slices`, - - Text: `Map keys must be comparable, which precludes the use of byte slices. -This usually leads to using string keys and converting byte slices to -strings. - -Normally, a conversion of a byte slice to a string needs to copy the data and -causes allocations. The compiler, however, recognizes \'m[string(b)]\' and -uses the data of \'b\' directly, without copying it, because it knows that -the data can't change during the map lookup. This leads to the -counter-intuitive situation that - - k := string(b) - println(m[k]) - println(m[k]) - -will be less efficient than - - println(m[string(b)]) - println(m[string(b)]) - -because the first version needs to copy and allocate, while the second -one does not. - -For some history on this optimization, check out commit -f5f5a8b6209f84961687d993b93ea0d397f5d5bf in the Go repository.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA6002": { - Title: `Storing non-pointer values in \'sync.Pool\' allocates memory`, - Text: `A \'sync.Pool\' is used to avoid unnecessary allocations and reduce the -amount of work the garbage collector has to do. - -When passing a value that is not a pointer to a function that accepts -an interface, the value needs to be placed on the heap, which means an -additional allocation. Slices are a common thing to put in sync.Pools, -and they're structs with 3 fields (length, capacity, and a pointer to -an array). In order to avoid the extra allocation, one should store a -pointer to the slice instead. - -See the comments on https://go-review.googlesource.com/c/go/+/24371 -that discuss this problem.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA6003": { - Title: `Converting a string to a slice of runes before ranging over it`, - Text: `You may want to loop over the runes in a string. Instead of converting -the string to a slice of runes and looping over that, you can loop -over the string itself. That is, - - for _, r := range s {} - -and - - for _, r := range []rune(s) {} - -will yield the same values. The first version, however, will be faster -and avoid unnecessary memory allocations. - -Do note that if you are interested in the indices, ranging over a -string and over a slice of runes will yield different indices. The -first one yields byte offsets, while the second one yields indices in -the slice of runes.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA6005": { - Title: `Inefficient string comparison with \'strings.ToLower\' or \'strings.ToUpper\'`, - Text: `Converting two strings to the same case and comparing them like so - - if strings.ToLower(s1) == strings.ToLower(s2) { - ... - } - -is significantly more expensive than comparing them with -\'strings.EqualFold(s1, s2)\'. This is due to memory usage as well as -computational complexity. - -\'strings.ToLower\' will have to allocate memory for the new strings, as -well as convert both strings fully, even if they differ on the very -first byte. strings.EqualFold, on the other hand, compares the strings -one character at a time. It doesn't need to create two intermediate -strings and can return as soon as the first non-matching character has -been found. - -For a more in-depth explanation of this issue, see -https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/`, - Since: "2019.2", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA9001": { - Title: `Defers in range loops may not run when you expect them to`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA9002": { - Title: `Using a non-octal \'os.FileMode\' that looks like it was meant to be in octal.`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA9003": { - Title: `Empty body in an if or else branch`, - Since: "2017.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA9004": { - Title: `Only the first constant has an explicit type`, - - Text: `In a constant declaration such as the following: - - const ( - First byte = 1 - Second = 2 - ) - -the constant Second does not have the same type as the constant First. -This construct shouldn't be confused with - - const ( - First byte = iota - Second - ) - -where \'First\' and \'Second\' do indeed have the same type. The type is only -passed on when no explicit value is assigned to the constant. - -When declaring enumerations with explicit values it is therefore -important not to write - - const ( - EnumFirst EnumType = 1 - EnumSecond = 2 - EnumThird = 3 - ) - -This discrepancy in types can cause various confusing behaviors and -bugs. - - -Wrong type in variable declarations - -The most obvious issue with such incorrect enumerations expresses -itself as a compile error: - - package pkg - - const ( - EnumFirst uint8 = 1 - EnumSecond = 2 - ) - - func fn(useFirst bool) { - x := EnumSecond - if useFirst { - x = EnumFirst - } - } - -fails to compile with - - ./const.go:11:5: cannot use EnumFirst (type uint8) as type int in assignment - - -Losing method sets - -A more subtle issue occurs with types that have methods and optional -interfaces. Consider the following: - - package main - - import "fmt" - - type Enum int - - func (e Enum) String() string { - return "an enum" - } - - const ( - EnumFirst Enum = 1 - EnumSecond = 2 - ) - - func main() { - fmt.Println(EnumFirst) - fmt.Println(EnumSecond) - } - -This code will output - - an enum - 2 - -as \'EnumSecond\' has no explicit type, and thus defaults to \'int\'.`, - Since: "2019.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA9005": { - Title: `Trying to marshal a struct with no public fields nor custom marshaling`, - Text: ` -The \'encoding/json\' and \'encoding/xml\' packages only operate on exported -fields in structs, not unexported ones. It is usually an error to try -to (un)marshal structs that only consist of unexported fields. - -This check will not flag calls involving types that define custom -marshaling behavior, e.g. via \'MarshalJSON\' methods. It will also not -flag empty structs.`, - Since: "2019.2", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAll, - }, - - "SA9006": { - Title: `Dubious bit shifting of a fixed size integer value`, - Text: `Bit shifting a value past its size will always clear the value. - -For instance: - - v := int8(42) - v >>= 8 - -will always result in 0. - -This check flags bit shifting operations on fixed size integer values only. -That is, int, uint and uintptr are never flagged to avoid potential false -positives in somewhat exotic but valid bit twiddling tricks: - - // Clear any value above 32 bits if integers are more than 32 bits. - func f(i int) int { - v := i >> 32 - v = v << 32 - return i-v - }`, - Since: "2020.2", - Severity: lint.SeverityWarning, - // Technically this should be MergeIfAll, because the type of - // v might be different for different build tags. Practically, - // don't write code that depends on that. - MergeIf: lint.MergeIfAny, - }, - - "SA9007": { - Title: "Deleting a directory that shouldn't be deleted", - Text: ` -It is virtually never correct to delete system directories such as -/tmp or the user's home directory. However, it can be fairly easy to -do by mistake, for example by mistakingly using \'os.TempDir\' instead -of \'ioutil.TempDir\', or by forgetting to add a suffix to the result -of \'os.UserHomeDir\'. - -Writing - - d := os.TempDir() - defer os.RemoveAll(d) - -in your unit tests will have a devastating effect on the stability of your system. - -This check flags attempts at deleting the following directories: - -- os.TempDir -- os.UserCacheDir -- os.UserConfigDir -- os.UserHomeDir -`, - Since: "2022.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, - - "SA9008": { - Title: `\'else\' branch of a type assertion is probably not reading the right value`, - Text: ` -When declaring variables as part of an \'if\' statement (like in \"if -foo := ...; foo {\"), the same variables will also be in the scope of -the \'else\' branch. This means that in the following example - - if x, ok := x.(int); ok { - // ... - } else { - fmt.Printf("unexpected type %T", x) - } - -\'x\' in the \'else\' branch will refer to the \'x\' from \'x, ok -:=\'; it will not refer to the \'x\' that is being type-asserted. The -result of a failed type assertion is the zero value of the type that -is being asserted to, so \'x\' in the else branch will always have the -value \'0\' and the type \'int\'. -`, - Since: "2022.1", - Severity: lint.SeverityWarning, - MergeIf: lint.MergeIfAny, - }, -}) diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/fakereflect/fakereflect.go b/tools/vendor/honnef.co/go/tools/staticcheck/fakereflect/fakereflect.go index 7f8fd4799..5fdf15b25 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/fakereflect/fakereflect.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/fakereflect/fakereflect.go @@ -84,7 +84,7 @@ func (t TypeAndCanAddr) IsStruct() bool { } func (t TypeAndCanAddr) Name() string { - named, ok := t.Type.(*types.Named) + named, ok := types.Unalias(t.Type).(*types.Named) if !ok { return "" } diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/marshal.go b/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/marshal.go index 64fce5f5b..6a30d7907 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/marshal.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/marshal.go @@ -56,17 +56,17 @@ func implementsMarshaler(v fakereflect.TypeAndCanAddr) bool { if params.Len() != 2 { return false } - if !typeutil.IsType(params.At(0).Type(), "*encoding/xml.Encoder") { + if !typeutil.IsPointerToTypeWithName(params.At(0).Type(), "encoding/xml.Encoder") { return false } - if !typeutil.IsType(params.At(1).Type(), "encoding/xml.StartElement") { + if !typeutil.IsTypeWithName(params.At(1).Type(), "encoding/xml.StartElement") { return false } rets := fn.Type().(*types.Signature).Results() if rets.Len() != 1 { return false } - if !typeutil.IsType(rets.At(0).Type(), "error") { + if !typeutil.IsTypeWithName(rets.At(0).Type(), "error") { return false } return true @@ -86,17 +86,17 @@ func implementsMarshalerAttr(v fakereflect.TypeAndCanAddr) bool { if params.Len() != 1 { return false } - if !typeutil.IsType(params.At(0).Type(), "encoding/xml.Name") { + if !typeutil.IsTypeWithName(params.At(0).Type(), "encoding/xml.Name") { return false } rets := fn.Type().(*types.Signature).Results() if rets.Len() != 2 { return false } - if !typeutil.IsType(rets.At(0).Type(), "encoding/xml.Attr") { + if !typeutil.IsTypeWithName(rets.At(0).Type(), "encoding/xml.Attr") { return false } - if !typeutil.IsType(rets.At(1).Type(), "error") { + if !typeutil.IsTypeWithName(rets.At(1).Type(), "error") { return false } return true @@ -279,7 +279,7 @@ func (e *Encoder) marshalAttr(start *StartElement, name Name, val fakereflect.Ty return nil } - if typeutil.IsType(val.Type, "encoding/xml.Attr") { + if typeutil.IsTypeWithName(val.Type, "encoding/xml.Attr") { return nil } @@ -350,7 +350,7 @@ func (e *Encoder) marshalStruct(tinfo *typeInfo, val fakereflect.TypeAndCanAddr, case fInnerXML: vf = indirect(vf) - if typeutil.IsType(vf.Type, "[]byte") || typeutil.IsType(vf.Type, "string") { + if t, ok := vf.Type.(*types.Slice); (ok && types.Identical(t.Elem(), types.Typ[types.Byte])) || types.Identical(vf.Type, types.Typ[types.String]) { continue } diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/typeinfo.go b/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/typeinfo.go index 07e5abe79..cbde81bd9 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/typeinfo.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/typeinfo.go @@ -6,11 +6,11 @@ package fakexml import ( "fmt" - "go/types" "strconv" "strings" "sync" + "honnef.co/go/tools/go/types/typeutil" "honnef.co/go/tools/staticcheck/fakereflect" ) @@ -80,8 +80,7 @@ func getTypeInfo(typ fakereflect.TypeAndCanAddr) (*typeInfo, error) { } tinfo := &typeInfo{} - named, ok := typ.Type.(*types.Named) - if typ.IsStruct() && !(ok && named.Obj().Pkg().Path() == "encoding/xml" && named.Obj().Name() == "Name") { + if typ.IsStruct() && !typeutil.IsTypeWithName(typ.Type, "encoding/xml.Name") { n := typ.NumField() for i := 0; i < n; i++ { f := typ.Field(i) diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/lint.go b/tools/vendor/honnef.co/go/tools/staticcheck/lint.go deleted file mode 100644 index b7c0f9137..000000000 --- a/tools/vendor/honnef.co/go/tools/staticcheck/lint.go +++ /dev/null @@ -1,5237 +0,0 @@ -package staticcheck - -import ( - "fmt" - "go/ast" - "go/constant" - "go/token" - "go/types" - htmltemplate "html/template" - "net/http" - "os" - "reflect" - "regexp" - "regexp/syntax" - "sort" - "strconv" - "strings" - texttemplate "text/template" - "unicode" - - "honnef.co/go/tools/analysis/code" - "honnef.co/go/tools/analysis/edit" - "honnef.co/go/tools/analysis/facts/deprecated" - "honnef.co/go/tools/analysis/facts/generated" - "honnef.co/go/tools/analysis/facts/nilness" - "honnef.co/go/tools/analysis/facts/purity" - "honnef.co/go/tools/analysis/facts/typedness" - "honnef.co/go/tools/analysis/lint" - "honnef.co/go/tools/analysis/report" - "honnef.co/go/tools/go/ast/astutil" - "honnef.co/go/tools/go/ir" - "honnef.co/go/tools/go/ir/irutil" - "honnef.co/go/tools/go/types/typeutil" - "honnef.co/go/tools/internal/passes/buildir" - "honnef.co/go/tools/internal/sharedcheck" - "honnef.co/go/tools/knowledge" - "honnef.co/go/tools/pattern" - "honnef.co/go/tools/printf" - "honnef.co/go/tools/staticcheck/fakejson" - "honnef.co/go/tools/staticcheck/fakereflect" - "honnef.co/go/tools/staticcheck/fakexml" - - "golang.org/x/exp/typeparams" - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" - "golang.org/x/tools/go/ast/inspector" -) - -func checkSortSlice(call *Call) { - c := call.Instr.Common().StaticCallee() - arg := call.Args[0] - - T := arg.Value.Value.Type().Underlying() - switch T.(type) { - case *types.Interface: - // we don't know. - // TODO(dh): if the value is a phi node we can look at its edges - if k, ok := arg.Value.Value.(*ir.Const); ok && k.Value == nil { - // literal nil, e.g. sort.Sort(nil, ...) - arg.Invalid(fmt.Sprintf("cannot call %s on nil literal", c)) - } - case *types.Slice: - // this is fine - default: - // this is not fine - arg.Invalid(fmt.Sprintf("%s must only be called on slices, was called on %s", c, T)) - } -} - -func validRegexp(call *Call) { - arg := call.Args[0] - err := ValidateRegexp(arg.Value) - if err != nil { - arg.Invalid(err.Error()) - } -} - -type runeSlice []rune - -func (rs runeSlice) Len() int { return len(rs) } -func (rs runeSlice) Less(i int, j int) bool { return rs[i] < rs[j] } -func (rs runeSlice) Swap(i int, j int) { rs[i], rs[j] = rs[j], rs[i] } - -func utf8Cutset(call *Call) { - arg := call.Args[1] - if InvalidUTF8(arg.Value) { - arg.Invalid(MsgInvalidUTF8) - } -} - -func uniqueCutset(call *Call) { - arg := call.Args[1] - if !UniqueStringCutset(arg.Value) { - arg.Invalid(MsgNonUniqueCutset) - } -} - -func unmarshalPointer(name string, arg int) CallCheck { - return func(call *Call) { - if !Pointer(call.Args[arg].Value) { - call.Args[arg].Invalid(fmt.Sprintf("%s expects to unmarshal into a pointer, but the provided value is not a pointer", name)) - } - } -} - -func pointlessIntMath(call *Call) { - if ConvertedFromInt(call.Args[0].Value) { - call.Invalid(fmt.Sprintf("calling %s on a converted integer is pointless", irutil.CallName(call.Instr.Common()))) - } -} - -func checkValidHostPort(arg int) CallCheck { - return func(call *Call) { - if !ValidHostPort(call.Args[arg].Value) { - call.Args[arg].Invalid(MsgInvalidHostPort) - } - } -} - -var ( - checkRegexpRules = map[string]CallCheck{ - "regexp.MustCompile": validRegexp, - "regexp.Compile": validRegexp, - "regexp.Match": validRegexp, - "regexp.MatchReader": validRegexp, - "regexp.MatchString": validRegexp, - } - - checkTimeParseRules = map[string]CallCheck{ - "time.Parse": func(call *Call) { - arg := call.Args[knowledge.Arg("time.Parse.layout")] - err := ValidateTimeLayout(arg.Value) - if err != nil { - arg.Invalid(err.Error()) - } - }, - } - - checkEncodingBinaryRules = map[string]CallCheck{ - "encoding/binary.Write": func(call *Call) { - arg := call.Args[knowledge.Arg("encoding/binary.Write.data")] - if !CanBinaryMarshal(call.Pass, arg.Value) { - arg.Invalid(fmt.Sprintf("value of type %s cannot be used with binary.Write", arg.Value.Value.Type())) - } - }, - } - - checkURLsRules = map[string]CallCheck{ - "net/url.Parse": func(call *Call) { - arg := call.Args[knowledge.Arg("net/url.Parse.rawurl")] - err := ValidateURL(arg.Value) - if err != nil { - arg.Invalid(err.Error()) - } - }, - } - - checkSyncPoolValueRules = map[string]CallCheck{ - "(*sync.Pool).Put": func(call *Call) { - arg := call.Args[knowledge.Arg("(*sync.Pool).Put.x")] - typ := arg.Value.Value.Type() - _, isSlice := typ.Underlying().(*types.Slice) - if !typeutil.IsPointerLike(typ) || isSlice { - arg.Invalid("argument should be pointer-like to avoid allocations") - } - }, - } - - checkRegexpFindAllRules = map[string]CallCheck{ - "(*regexp.Regexp).FindAll": RepeatZeroTimes("a FindAll method", 1), - "(*regexp.Regexp).FindAllIndex": RepeatZeroTimes("a FindAll method", 1), - "(*regexp.Regexp).FindAllString": RepeatZeroTimes("a FindAll method", 1), - "(*regexp.Regexp).FindAllStringIndex": RepeatZeroTimes("a FindAll method", 1), - "(*regexp.Regexp).FindAllStringSubmatch": RepeatZeroTimes("a FindAll method", 1), - "(*regexp.Regexp).FindAllStringSubmatchIndex": RepeatZeroTimes("a FindAll method", 1), - "(*regexp.Regexp).FindAllSubmatch": RepeatZeroTimes("a FindAll method", 1), - "(*regexp.Regexp).FindAllSubmatchIndex": RepeatZeroTimes("a FindAll method", 1), - } - - checkUTF8CutsetRules = map[string]CallCheck{ - "strings.IndexAny": utf8Cutset, - "strings.LastIndexAny": utf8Cutset, - "strings.ContainsAny": utf8Cutset, - "strings.Trim": utf8Cutset, - "strings.TrimLeft": utf8Cutset, - "strings.TrimRight": utf8Cutset, - } - - checkUniqueCutsetRules = map[string]CallCheck{ - "strings.Trim": uniqueCutset, - "strings.TrimLeft": uniqueCutset, - "strings.TrimRight": uniqueCutset, - } - - checkUnmarshalPointerRules = map[string]CallCheck{ - "encoding/xml.Unmarshal": unmarshalPointer("xml.Unmarshal", 1), - "(*encoding/xml.Decoder).Decode": unmarshalPointer("Decode", 0), - "(*encoding/xml.Decoder).DecodeElement": unmarshalPointer("DecodeElement", 0), - "encoding/json.Unmarshal": unmarshalPointer("json.Unmarshal", 1), - "(*encoding/json.Decoder).Decode": unmarshalPointer("Decode", 0), - } - - checkUnbufferedSignalChanRules = map[string]CallCheck{ - "os/signal.Notify": func(call *Call) { - arg := call.Args[knowledge.Arg("os/signal.Notify.c")] - if UnbufferedChannel(arg.Value) { - arg.Invalid("the channel used with signal.Notify should be buffered") - } - }, - } - - checkMathIntRules = map[string]CallCheck{ - "math.Ceil": pointlessIntMath, - "math.Floor": pointlessIntMath, - "math.IsNaN": pointlessIntMath, - "math.Trunc": pointlessIntMath, - "math.IsInf": pointlessIntMath, - } - - checkStringsReplaceZeroRules = map[string]CallCheck{ - "strings.Replace": RepeatZeroTimes("strings.Replace", 3), - "bytes.Replace": RepeatZeroTimes("bytes.Replace", 3), - } - - checkListenAddressRules = map[string]CallCheck{ - "net/http.ListenAndServe": checkValidHostPort(0), - "net/http.ListenAndServeTLS": checkValidHostPort(0), - } - - checkBytesEqualIPRules = map[string]CallCheck{ - "bytes.Equal": func(call *Call) { - if ConvertedFrom(call.Args[knowledge.Arg("bytes.Equal.a")].Value, "net.IP") && - ConvertedFrom(call.Args[knowledge.Arg("bytes.Equal.b")].Value, "net.IP") { - call.Invalid("use net.IP.Equal to compare net.IPs, not bytes.Equal") - } - }, - } - - checkRegexpMatchLoopRules = map[string]CallCheck{ - "regexp.Match": loopedRegexp("regexp.Match"), - "regexp.MatchReader": loopedRegexp("regexp.MatchReader"), - "regexp.MatchString": loopedRegexp("regexp.MatchString"), - } - - checkNoopMarshal = map[string]CallCheck{ - // TODO(dh): should we really flag XML? Even an empty struct - // produces a non-zero amount of data, namely its type name. - // Let's see if we encounter any false positives. - // - // Also, should we flag gob? - "encoding/json.Marshal": checkNoopMarshalImpl(knowledge.Arg("json.Marshal.v"), "MarshalJSON", "MarshalText"), - "encoding/xml.Marshal": checkNoopMarshalImpl(knowledge.Arg("xml.Marshal.v"), "MarshalXML", "MarshalText"), - "(*encoding/json.Encoder).Encode": checkNoopMarshalImpl(knowledge.Arg("(*encoding/json.Encoder).Encode.v"), "MarshalJSON", "MarshalText"), - "(*encoding/xml.Encoder).Encode": checkNoopMarshalImpl(knowledge.Arg("(*encoding/xml.Encoder).Encode.v"), "MarshalXML", "MarshalText"), - - "encoding/json.Unmarshal": checkNoopMarshalImpl(knowledge.Arg("json.Unmarshal.v"), "UnmarshalJSON", "UnmarshalText"), - "encoding/xml.Unmarshal": checkNoopMarshalImpl(knowledge.Arg("xml.Unmarshal.v"), "UnmarshalXML", "UnmarshalText"), - "(*encoding/json.Decoder).Decode": checkNoopMarshalImpl(knowledge.Arg("(*encoding/json.Decoder).Decode.v"), "UnmarshalJSON", "UnmarshalText"), - "(*encoding/xml.Decoder).Decode": checkNoopMarshalImpl(knowledge.Arg("(*encoding/xml.Decoder).Decode.v"), "UnmarshalXML", "UnmarshalText"), - } - - checkUnsupportedMarshal = map[string]CallCheck{ - "encoding/json.Marshal": checkUnsupportedMarshalJSON, - "encoding/xml.Marshal": checkUnsupportedMarshalXML, - "(*encoding/json.Encoder).Encode": checkUnsupportedMarshalJSON, - "(*encoding/xml.Encoder).Encode": checkUnsupportedMarshalXML, - } - - checkAtomicAlignment = map[string]CallCheck{ - "sync/atomic.AddInt64": checkAtomicAlignmentImpl, - "sync/atomic.AddUint64": checkAtomicAlignmentImpl, - "sync/atomic.CompareAndSwapInt64": checkAtomicAlignmentImpl, - "sync/atomic.CompareAndSwapUint64": checkAtomicAlignmentImpl, - "sync/atomic.LoadInt64": checkAtomicAlignmentImpl, - "sync/atomic.LoadUint64": checkAtomicAlignmentImpl, - "sync/atomic.StoreInt64": checkAtomicAlignmentImpl, - "sync/atomic.StoreUint64": checkAtomicAlignmentImpl, - "sync/atomic.SwapInt64": checkAtomicAlignmentImpl, - "sync/atomic.SwapUint64": checkAtomicAlignmentImpl, - } - - // TODO(dh): detect printf wrappers - checkPrintfRules = map[string]CallCheck{ - "fmt.Errorf": func(call *Call) { checkPrintfCall(call, 0, 1) }, - "fmt.Printf": func(call *Call) { checkPrintfCall(call, 0, 1) }, - "fmt.Sprintf": func(call *Call) { checkPrintfCall(call, 0, 1) }, - "fmt.Fprintf": func(call *Call) { checkPrintfCall(call, 1, 2) }, - "golang.org/x/xerrors.Errorf": func(call *Call) { checkPrintfCall(call, 0, 1) }, - } - - checkSortSliceRules = map[string]CallCheck{ - "sort.Slice": checkSortSlice, - "sort.SliceIsSorted": checkSortSlice, - "sort.SliceStable": checkSortSlice, - } - - checkWithValueKeyRules = map[string]CallCheck{ - "context.WithValue": checkWithValueKey, - } - - checkStrconvRules = map[string]CallCheck{ - "strconv.ParseComplex": func(call *Call) { - validateComplexBitSize(call.Args[knowledge.Arg("strconv.ParseComplex.bitSize")]) - }, - "strconv.ParseFloat": func(call *Call) { - validateFloatBitSize(call.Args[knowledge.Arg("strconv.ParseFloat.bitSize")]) - }, - "strconv.ParseInt": func(call *Call) { - validateContinuousBitSize(call.Args[knowledge.Arg("strconv.ParseInt.bitSize")], 0, 64) - validateIntBaseAllowZero(call.Args[knowledge.Arg("strconv.ParseInt.base")]) - }, - "strconv.ParseUint": func(call *Call) { - validateContinuousBitSize(call.Args[knowledge.Arg("strconv.ParseUint.bitSize")], 0, 64) - validateIntBaseAllowZero(call.Args[knowledge.Arg("strconv.ParseUint.base")]) - }, - - "strconv.FormatComplex": func(call *Call) { - validateComplexFormat(call.Args[knowledge.Arg("strconv.FormatComplex.fmt")]) - validateComplexBitSize(call.Args[knowledge.Arg("strconv.FormatComplex.bitSize")]) - }, - "strconv.FormatFloat": func(call *Call) { - validateFloatFormat(call.Args[knowledge.Arg("strconv.FormatFloat.fmt")]) - validateFloatBitSize(call.Args[knowledge.Arg("strconv.FormatFloat.bitSize")]) - }, - "strconv.FormatInt": func(call *Call) { - validateIntBase(call.Args[knowledge.Arg("strconv.FormatInt.base")]) - }, - "strconv.FormatUint": func(call *Call) { - validateIntBase(call.Args[knowledge.Arg("strconv.FormatUint.base")]) - }, - - "strconv.AppendFloat": func(call *Call) { - validateFloatFormat(call.Args[knowledge.Arg("strconv.AppendFloat.fmt")]) - validateFloatBitSize(call.Args[knowledge.Arg("strconv.AppendFloat.bitSize")]) - }, - "strconv.AppendInt": func(call *Call) { - validateIntBase(call.Args[knowledge.Arg("strconv.AppendInt.base")]) - }, - "strconv.AppendUint": func(call *Call) { - validateIntBase(call.Args[knowledge.Arg("strconv.AppendUint.base")]) - }, - } -) - -func validateIntBase(arg *Argument) { - if c := extractConstExpectKind(arg.Value.Value, constant.Int); c != nil { - val, _ := constant.Int64Val(c.Value) - if val < 2 { - arg.Invalid("'base' must not be smaller than 2") - } - if val > 36 { - arg.Invalid("'base' must not be larger than 36") - } - } -} - -func validateIntBaseAllowZero(arg *Argument) { - if c := extractConstExpectKind(arg.Value.Value, constant.Int); c != nil { - val, _ := constant.Int64Val(c.Value) - if val < 2 && val != 0 { - arg.Invalid("'base' must not be smaller than 2, unless it is 0") - } - if val > 36 { - arg.Invalid("'base' must not be larger than 36") - } - } -} - -func validateComplexFormat(arg *Argument) { - validateFloatFormat(arg) -} - -func validateFloatFormat(arg *Argument) { - if c := extractConstExpectKind(arg.Value.Value, constant.Int); c != nil { - val, _ := constant.Int64Val(c.Value) - switch val { - case 'b', 'e', 'E', 'f', 'g', 'G', 'x', 'X': - default: - arg.Invalid(fmt.Sprintf("'fmt' argument is invalid: unknown format %q", val)) - } - } -} - -func validateComplexBitSize(arg *Argument) { validateDiscreetBitSize(arg, 64, 128) } -func validateFloatBitSize(arg *Argument) { validateDiscreetBitSize(arg, 32, 64) } - -func validateDiscreetBitSize(arg *Argument, size1 int, size2 int) { - if c := extractConstExpectKind(arg.Value.Value, constant.Int); c != nil { - val, _ := constant.Int64Val(c.Value) - if val != int64(size1) && val != int64(size2) { - arg.Invalid(fmt.Sprintf("'bitSize' argument is invalid, must be either %d or %d", size1, size2)) - } - } -} - -func validateContinuousBitSize(arg *Argument, min int, max int) { - if c := extractConstExpectKind(arg.Value.Value, constant.Int); c != nil { - val, _ := constant.Int64Val(c.Value) - if val < int64(min) || val > int64(max) { - arg.Invalid(fmt.Sprintf("'bitSize' argument is invalid, must be within %d and %d", min, max)) - } - } -} - -func checkPrintfCall(call *Call, fIdx, vIdx int) { - f := call.Args[fIdx] - var args []ir.Value - switch v := call.Args[vIdx].Value.Value.(type) { - case *ir.Slice: - var ok bool - args, ok = irutil.Vararg(v) - if !ok { - // We don't know what the actual arguments to the function are - return - } - case *ir.Const: - // nil, i.e. no arguments - default: - // We don't know what the actual arguments to the function are - return - } - checkPrintfCallImpl(f, f.Value.Value, args) -} - -type verbFlag int - -const ( - isInt verbFlag = 1 << iota - isBool - isFP - isString - isPointer - // Verbs that accept "pseudo pointers" will sometimes dereference - // non-nil pointers. For example, %x on a non-nil *struct will print the - // individual fields, but on a nil pointer it will print the address. - isPseudoPointer - isSlice - isAny - noRecurse -) - -var verbs = [...]verbFlag{ - 'b': isPseudoPointer | isInt | isFP, - 'c': isInt, - 'd': isPseudoPointer | isInt, - 'e': isFP, - 'E': isFP, - 'f': isFP, - 'F': isFP, - 'g': isFP, - 'G': isFP, - 'o': isPseudoPointer | isInt, - 'O': isPseudoPointer | isInt, - 'p': isSlice | isPointer | noRecurse, - 'q': isInt | isString, - 's': isString, - 't': isBool, - 'T': isAny, - 'U': isInt, - 'v': isAny, - 'X': isPseudoPointer | isInt | isFP | isString, - 'x': isPseudoPointer | isInt | isFP | isString, -} - -func checkPrintfCallImpl(carg *Argument, f ir.Value, args []ir.Value) { - var msCache *typeutil.MethodSetCache - if f.Parent() != nil { - msCache = &f.Parent().Prog.MethodSets - } - - elem := func(T types.Type, verb rune) ([]types.Type, bool) { - if verbs[verb]&noRecurse != 0 { - return []types.Type{T}, false - } - switch T := T.(type) { - case *types.Slice: - if verbs[verb]&isSlice != 0 { - return []types.Type{T}, false - } - if verbs[verb]&isString != 0 && typeutil.IsType(T.Elem().Underlying(), "byte") { - return []types.Type{T}, false - } - return []types.Type{T.Elem()}, true - case *types.Map: - key := T.Key() - val := T.Elem() - return []types.Type{key, val}, true - case *types.Struct: - out := make([]types.Type, 0, T.NumFields()) - for i := 0; i < T.NumFields(); i++ { - out = append(out, T.Field(i).Type()) - } - return out, true - case *types.Array: - return []types.Type{T.Elem()}, true - default: - return []types.Type{T}, false - } - } - isInfo := func(T types.Type, info types.BasicInfo) bool { - basic, ok := T.Underlying().(*types.Basic) - return ok && basic.Info()&info != 0 - } - - isFormatter := func(T types.Type, ms *types.MethodSet) bool { - sel := ms.Lookup(nil, "Format") - if sel == nil { - return false - } - fn, ok := sel.Obj().(*types.Func) - if !ok { - // should be unreachable - return false - } - sig := fn.Type().(*types.Signature) - if sig.Params().Len() != 2 { - return false - } - // TODO(dh): check the types of the arguments for more - // precision - if sig.Results().Len() != 0 { - return false - } - return true - } - - var seen typeutil.Map[struct{}] - var checkType func(verb rune, T types.Type, top bool) bool - checkType = func(verb rune, T types.Type, top bool) bool { - if top { - seen = typeutil.Map[struct{}]{} - } - if _, ok := seen.At(T); ok { - return true - } - seen.Set(T, struct{}{}) - if int(verb) >= len(verbs) { - // Unknown verb - return true - } - - flags := verbs[verb] - if flags == 0 { - // Unknown verb - return true - } - - ms := msCache.MethodSet(T) - if isFormatter(T, ms) { - // the value is responsible for formatting itself - return true - } - - if flags&isString != 0 && (types.Implements(T, knowledge.Interfaces["fmt.Stringer"]) || types.Implements(T, knowledge.Interfaces["error"])) { - // Check for stringer early because we're about to dereference - return true - } - - T = T.Underlying() - if flags&(isPointer|isPseudoPointer) == 0 && top { - T = typeutil.Dereference(T) - } - if flags&isPseudoPointer != 0 && top { - t := typeutil.Dereference(T) - if _, ok := t.Underlying().(*types.Struct); ok { - T = t - } - } - - if _, ok := T.(*types.Interface); ok { - // We don't know what's in the interface - return true - } - - var info types.BasicInfo - if flags&isInt != 0 { - info |= types.IsInteger - } - if flags&isBool != 0 { - info |= types.IsBoolean - } - if flags&isFP != 0 { - info |= types.IsFloat | types.IsComplex - } - if flags&isString != 0 { - info |= types.IsString - } - - if info != 0 && isInfo(T, info) { - return true - } - - if flags&isString != 0 { - isStringyElem := func(typ types.Type) bool { - if typ, ok := typ.Underlying().(*types.Basic); ok { - return typ.Kind() == types.Byte - } - return false - } - switch T := T.(type) { - case *types.Slice: - if isStringyElem(T.Elem()) { - return true - } - case *types.Array: - if isStringyElem(T.Elem()) { - return true - } - } - if types.Implements(T, knowledge.Interfaces["fmt.Stringer"]) || types.Implements(T, knowledge.Interfaces["error"]) { - return true - } - } - - if flags&isPointer != 0 && typeutil.IsPointerLike(T) { - return true - } - if flags&isPseudoPointer != 0 { - switch U := T.Underlying().(type) { - case *types.Pointer: - if !top { - return true - } - - if _, ok := U.Elem().Underlying().(*types.Struct); !ok { - // TODO(dh): can this condition ever be false? For - // *T, if T is a struct, we'll already have - // dereferenced it, meaning the *types.Pointer - // branch couldn't have been taken. For T that - // aren't structs, this condition will always - // evaluate to true. - return true - } - case *types.Chan, *types.Signature: - // Channels and functions are always treated as - // pointers and never recursed into. - return true - case *types.Basic: - if U.Kind() == types.UnsafePointer { - return true - } - case *types.Interface: - // we will already have bailed if the type is an - // interface. - panic("unreachable") - default: - // other pointer-like types, such as maps or slices, - // will be printed element-wise. - } - } - - if flags&isSlice != 0 { - if _, ok := T.(*types.Slice); ok { - return true - } - } - - if flags&isAny != 0 { - return true - } - - elems, ok := elem(T.Underlying(), verb) - if !ok { - return false - } - for _, elem := range elems { - if !checkType(verb, elem, false) { - return false - } - } - - return true - } - - k, ok := irutil.Flatten(f).(*ir.Const) - if !ok { - return - } - actions, err := printf.Parse(constant.StringVal(k.Value)) - if err != nil { - carg.Invalid("couldn't parse format string") - return - } - - ptr := 1 - hasExplicit := false - - checkStar := func(verb printf.Verb, star printf.Argument) bool { - if star, ok := star.(printf.Star); ok { - idx := 0 - if star.Index == -1 { - idx = ptr - ptr++ - } else { - hasExplicit = true - idx = star.Index - ptr = star.Index + 1 - } - if idx == 0 { - carg.Invalid(fmt.Sprintf("Printf format %s reads invalid arg 0; indices are 1-based", verb.Raw)) - return false - } - if idx > len(args) { - carg.Invalid( - fmt.Sprintf("Printf format %s reads arg #%d, but call has only %d args", - verb.Raw, idx, len(args))) - return false - } - if arg, ok := args[idx-1].(*ir.MakeInterface); ok { - if !isInfo(arg.X.Type(), types.IsInteger) { - carg.Invalid(fmt.Sprintf("Printf format %s reads non-int arg #%d as argument of *", verb.Raw, idx)) - } - } - } - return true - } - - // We only report one problem per format string. Making a - // mistake with an index tends to invalidate all future - // implicit indices. - for _, action := range actions { - verb, ok := action.(printf.Verb) - if !ok { - continue - } - - if !checkStar(verb, verb.Width) || !checkStar(verb, verb.Precision) { - return - } - - off := ptr - if verb.Value != -1 { - hasExplicit = true - off = verb.Value - } - if off > len(args) { - carg.Invalid( - fmt.Sprintf("Printf format %s reads arg #%d, but call has only %d args", - verb.Raw, off, len(args))) - return - } else if verb.Value == 0 && verb.Letter != '%' { - carg.Invalid(fmt.Sprintf("Printf format %s reads invalid arg 0; indices are 1-based", verb.Raw)) - return - } else if off != 0 { - arg, ok := args[off-1].(*ir.MakeInterface) - if ok { - if !checkType(verb.Letter, arg.X.Type(), true) { - carg.Invalid(fmt.Sprintf("Printf format %s has arg #%d of wrong type %s", - verb.Raw, ptr, args[ptr-1].(*ir.MakeInterface).X.Type())) - return - } - } - } - - switch verb.Value { - case -1: - // Consume next argument - ptr++ - case 0: - // Don't consume any arguments - default: - ptr = verb.Value + 1 - } - } - - if !hasExplicit && ptr <= len(args) { - carg.Invalid(fmt.Sprintf("Printf call needs %d args but has %d args", ptr-1, len(args))) - } -} - -func checkAtomicAlignmentImpl(call *Call) { - sizes := call.Pass.TypesSizes - if sizes.Sizeof(types.Typ[types.Uintptr]) != 4 { - // Not running on a 32-bit platform - return - } - v, ok := irutil.Flatten(call.Args[0].Value.Value).(*ir.FieldAddr) - if !ok { - // TODO(dh): also check indexing into arrays and slices - return - } - T := v.X.Type().Underlying().(*types.Pointer).Elem().Underlying().(*types.Struct) - fields := make([]*types.Var, 0, T.NumFields()) - for i := 0; i < T.NumFields() && i <= v.Field; i++ { - fields = append(fields, T.Field(i)) - } - - off := sizes.Offsetsof(fields)[v.Field] - if off%8 != 0 { - msg := fmt.Sprintf("address of non 64-bit aligned field %s passed to %s", - T.Field(v.Field).Name(), - irutil.CallName(call.Instr.Common())) - call.Invalid(msg) - } -} - -func checkNoopMarshalImpl(argN int, meths ...string) CallCheck { - return func(call *Call) { - if code.IsGenerated(call.Pass, call.Instr.Pos()) { - return - } - arg := call.Args[argN] - T := arg.Value.Value.Type() - Ts, ok := typeutil.Dereference(T).Underlying().(*types.Struct) - if !ok { - return - } - if Ts.NumFields() == 0 { - return - } - fields := typeutil.FlattenFields(Ts) - for _, field := range fields { - if field.Var.Exported() { - return - } - } - // OPT(dh): we could use a method set cache here - ms := call.Instr.Parent().Prog.MethodSets.MethodSet(T) - // TODO(dh): we're not checking the signature, which can cause false negatives. - // This isn't a huge problem, however, since vet complains about incorrect signatures. - for _, meth := range meths { - if ms.Lookup(nil, meth) != nil { - return - } - } - arg.Invalid(fmt.Sprintf("struct type '%s' doesn't have any exported fields, nor custom marshaling", typeutil.Dereference(T))) - } -} - -func checkUnsupportedMarshalJSON(call *Call) { - arg := call.Args[0] - T := arg.Value.Value.Type() - if err := fakejson.Marshal(T); err != nil { - typ := types.TypeString(err.Type, types.RelativeTo(arg.Value.Value.Parent().Pkg.Pkg)) - if err.Path == "x" { - arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s", typ)) - } else { - arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s, via %s", typ, err.Path)) - } - } -} - -func checkUnsupportedMarshalXML(call *Call) { - arg := call.Args[0] - T := arg.Value.Value.Type() - if err := fakexml.Marshal(T); err != nil { - switch err := err.(type) { - case *fakexml.UnsupportedTypeError: - typ := types.TypeString(err.Type, types.RelativeTo(arg.Value.Value.Parent().Pkg.Pkg)) - if err.Path == "x" { - arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s", typ)) - } else { - arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s, via %s", typ, err.Path)) - } - case *fakexml.CyclicTypeError: - typ := types.TypeString(err.Type, types.RelativeTo(arg.Value.Value.Parent().Pkg.Pkg)) - if err.Path == "x" { - arg.Invalid(fmt.Sprintf("trying to marshal cyclic type %s", typ)) - } else { - arg.Invalid(fmt.Sprintf("trying to marshal cyclic type %s, via %s", typ, err.Path)) - } - case *fakexml.TagPathError: - // Vet does a better job at reporting this error, because it can flag the actual struct tags, not just the call to Marshal - default: - // These errors get reported by SA5008 instead, which can flag the actual fields, independently of calls to xml.Marshal - } - } -} - -func isInLoop(b *ir.BasicBlock) bool { - sets := irutil.FindLoops(b.Parent()) - for _, set := range sets { - if set.Has(b) { - return true - } - } - return false -} - -func CheckUntrappableSignal(pass *analysis.Pass) (interface{}, error) { - isSignal := func(pass *analysis.Pass, expr ast.Expr, name string) bool { - if expr, ok := expr.(*ast.SelectorExpr); ok { - return code.SelectorName(pass, expr) == name - } else { - return false - } - } - - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - if !code.IsCallToAny(pass, call, - "os/signal.Ignore", "os/signal.Notify", "os/signal.Reset") { - return - } - - hasSigterm := false - for _, arg := range call.Args { - if conv, ok := arg.(*ast.CallExpr); ok && isSignal(pass, conv.Fun, "os.Signal") { - arg = conv.Args[0] - } - - if isSignal(pass, arg, "syscall.SIGTERM") { - hasSigterm = true - break - } - - } - for i, arg := range call.Args { - if conv, ok := arg.(*ast.CallExpr); ok && isSignal(pass, conv.Fun, "os.Signal") { - arg = conv.Args[0] - } - - if isSignal(pass, arg, "os.Kill") || isSignal(pass, arg, "syscall.SIGKILL") { - var fixes []analysis.SuggestedFix - if !hasSigterm { - nargs := make([]ast.Expr, len(call.Args)) - for j, a := range call.Args { - if i == j { - nargs[j] = edit.Selector("syscall", "SIGTERM") - } else { - nargs[j] = a - } - } - ncall := *call - ncall.Args = nargs - fixes = append(fixes, edit.Fix(fmt.Sprintf("use syscall.SIGTERM instead of %s", report.Render(pass, arg)), edit.ReplaceWithNode(pass.Fset, call, &ncall))) - } - nargs := make([]ast.Expr, 0, len(call.Args)) - for j, a := range call.Args { - if i == j { - continue - } - nargs = append(nargs, a) - } - ncall := *call - ncall.Args = nargs - fixes = append(fixes, edit.Fix(fmt.Sprintf("remove %s from list of arguments", report.Render(pass, arg)), edit.ReplaceWithNode(pass.Fset, call, &ncall))) - report.Report(pass, arg, fmt.Sprintf("%s cannot be trapped (did you mean syscall.SIGTERM?)", report.Render(pass, arg)), report.Fixes(fixes...)) - } - if isSignal(pass, arg, "syscall.SIGSTOP") { - nargs := make([]ast.Expr, 0, len(call.Args)-1) - for j, a := range call.Args { - if i == j { - continue - } - nargs = append(nargs, a) - } - ncall := *call - ncall.Args = nargs - report.Report(pass, arg, "syscall.SIGSTOP cannot be trapped", report.Fixes(edit.Fix("remove syscall.SIGSTOP from list of arguments", edit.ReplaceWithNode(pass.Fset, call, &ncall)))) - } - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckTemplate(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - // OPT(dh): use integer for kind - var kind string - switch code.CallName(pass, call) { - case "(*text/template.Template).Parse": - kind = "text" - case "(*html/template.Template).Parse": - kind = "html" - default: - return - } - sel := call.Fun.(*ast.SelectorExpr) - if !code.IsCallToAny(pass, sel.X, "text/template.New", "html/template.New") { - // TODO(dh): this is a cheap workaround for templates with - // different delims. A better solution with less false - // negatives would use data flow analysis to see where the - // template comes from and where it has been - return - } - s, ok := code.ExprToString(pass, call.Args[knowledge.Arg("(*text/template.Template).Parse.text")]) - if !ok { - return - } - var err error - switch kind { - case "text": - _, err = texttemplate.New("").Parse(s) - case "html": - _, err = htmltemplate.New("").Parse(s) - } - if err != nil { - // TODO(dominikh): whitelist other parse errors, if any - if strings.Contains(err.Error(), "unexpected") || - strings.Contains(err.Error(), "bad character") { - report.Report(pass, call.Args[knowledge.Arg("(*text/template.Template).Parse.text")], err.Error()) - } - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var ( - checkTimeSleepConstantPatternQ = pattern.MustParse(`(CallExpr (Symbol "time.Sleep") lit@(IntegerLiteral value))`) - checkTimeSleepConstantPatternRns = pattern.MustParse(`(BinaryExpr duration "*" (SelectorExpr (Ident "time") (Ident "Nanosecond")))`) - checkTimeSleepConstantPatternRs = pattern.MustParse(`(BinaryExpr duration "*" (SelectorExpr (Ident "time") (Ident "Second")))`) -) - -func CheckTimeSleepConstant(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkTimeSleepConstantPatternQ, node) - if !ok { - return - } - n, ok := constant.Int64Val(m.State["value"].(types.TypeAndValue).Value) - if !ok { - return - } - if n == 0 || n > 120 { - // time.Sleep(0) is a seldom used pattern in concurrency - // tests. >120 might be intentional. 120 was chosen - // because the user could've meant 2 minutes. - return - } - - lit := m.State["lit"].(ast.Node) - report.Report(pass, lit, - fmt.Sprintf("sleeping for %d nanoseconds is probably a bug; be explicit if it isn't", n), report.Fixes( - edit.Fix("explicitly use nanoseconds", edit.ReplaceWithPattern(pass.Fset, lit, checkTimeSleepConstantPatternRns, pattern.State{"duration": lit})), - edit.Fix("use seconds", edit.ReplaceWithPattern(pass.Fset, lit, checkTimeSleepConstantPatternRs, pattern.State{"duration": lit})))) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var checkWaitgroupAddQ = pattern.MustParse(` - (GoStmt - (CallExpr - (FuncLit - _ - call@(CallExpr (Symbol "(*sync.WaitGroup).Add") _):_) _))`) - -func CheckWaitgroupAdd(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if m, ok := code.Match(pass, checkWaitgroupAddQ, node); ok { - call := m.State["call"].(ast.Node) - report.Report(pass, call, fmt.Sprintf("should call %s before starting the goroutine to avoid a race", report.Render(pass, call))) - } - } - code.Preorder(pass, fn, (*ast.GoStmt)(nil)) - return nil, nil -} - -func CheckInfiniteEmptyLoop(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - loop := node.(*ast.ForStmt) - if len(loop.Body.List) != 0 || loop.Post != nil { - return - } - - if loop.Init != nil { - // TODO(dh): this isn't strictly necessary, it just makes - // the check easier. - return - } - // An empty loop is bad news in two cases: 1) The loop has no - // condition. In that case, it's just a loop that spins - // forever and as fast as it can, keeping a core busy. 2) The - // loop condition only consists of variable or field reads and - // operators on those. The only way those could change their - // value is with unsynchronised access, which constitutes a - // data race. - // - // If the condition contains any function calls, its behaviour - // is dynamic and the loop might terminate. Similarly for - // channel receives. - - if loop.Cond != nil { - if code.MayHaveSideEffects(pass, loop.Cond, nil) { - return - } - if ident, ok := loop.Cond.(*ast.Ident); ok { - if k, ok := pass.TypesInfo.ObjectOf(ident).(*types.Const); ok { - if !constant.BoolVal(k.Val()) { - // don't flag `for false {}` loops. They're a debug aid. - return - } - } - } - report.Report(pass, loop, "loop condition never changes or has a race condition") - } - report.Report(pass, loop, "this loop will spin, using 100% CPU", report.ShortRange()) - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil)) - return nil, nil -} - -func CheckDeferInInfiniteLoop(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - mightExit := false - var defers []ast.Stmt - loop := node.(*ast.ForStmt) - if loop.Cond != nil { - return - } - fn2 := func(node ast.Node) bool { - switch stmt := node.(type) { - case *ast.ReturnStmt: - mightExit = true - return false - case *ast.BranchStmt: - // TODO(dominikh): if this sees a break in a switch or - // select, it doesn't check if it breaks the loop or - // just the select/switch. This causes some false - // negatives. - if stmt.Tok == token.BREAK { - mightExit = true - return false - } - case *ast.DeferStmt: - defers = append(defers, stmt) - case *ast.FuncLit: - // Don't look into function bodies - return false - } - return true - } - ast.Inspect(loop.Body, fn2) - if mightExit { - return - } - for _, stmt := range defers { - report.Report(pass, stmt, "defers in this infinite loop will never run") - } - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil)) - return nil, nil -} - -func CheckDubiousDeferInChannelRangeLoop(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - loop := node.(*ast.RangeStmt) - typ := pass.TypesInfo.TypeOf(loop.X) - _, ok := typeutil.CoreType(typ).(*types.Chan) - if !ok { - return - } - - stmts := []*ast.DeferStmt{} - exits := false - fn2 := func(node ast.Node) bool { - switch stmt := node.(type) { - case *ast.DeferStmt: - stmts = append(stmts, stmt) - case *ast.FuncLit: - // Don't look into function bodies - return false - case *ast.ReturnStmt: - exits = true - case *ast.BranchStmt: - exits = node.(*ast.BranchStmt).Tok == token.BREAK - } - return true - } - ast.Inspect(loop.Body, fn2) - - if exits { - return - } - for _, stmt := range stmts { - report.Report(pass, stmt, "defers in this range loop won't run unless the channel gets closed") - } - } - code.Preorder(pass, fn, (*ast.RangeStmt)(nil)) - return nil, nil -} - -func CheckTestMainExit(pass *analysis.Pass) (interface{}, error) { - if code.IsGoVersion(pass, 15) { - // Beginning with Go 1.15, the test framework will call - // os.Exit for us. - return nil, nil - } - - var ( - fnmain ast.Node - callsExit bool - callsRun bool - arg types.Object - ) - fn := func(node ast.Node, push bool) bool { - if !push { - if fnmain != nil && node == fnmain { - if !callsExit && callsRun { - report.Report(pass, fnmain, "TestMain should call os.Exit to set exit code") - } - fnmain = nil - callsExit = false - callsRun = false - arg = nil - } - return true - } - - switch node := node.(type) { - case *ast.FuncDecl: - if fnmain != nil { - return true - } - if !isTestMain(pass, node) { - return false - } - fnmain = node - arg = pass.TypesInfo.ObjectOf(node.Type.Params.List[0].Names[0]) - return true - case *ast.CallExpr: - if code.IsCallTo(pass, node, "os.Exit") { - callsExit = true - return false - } - sel, ok := node.Fun.(*ast.SelectorExpr) - if !ok { - return true - } - ident, ok := sel.X.(*ast.Ident) - if !ok { - return true - } - if arg != pass.TypesInfo.ObjectOf(ident) { - return true - } - if sel.Sel.Name == "Run" { - callsRun = true - return false - } - return true - default: - lint.ExhaustiveTypeSwitch(node) - return true - } - } - pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.FuncDecl)(nil), (*ast.CallExpr)(nil)}, fn) - return nil, nil -} - -func isTestMain(pass *analysis.Pass, decl *ast.FuncDecl) bool { - if decl.Name.Name != "TestMain" { - return false - } - if len(decl.Type.Params.List) != 1 { - return false - } - arg := decl.Type.Params.List[0] - if len(arg.Names) != 1 { - return false - } - return code.IsOfType(pass, arg.Type, "*testing.M") -} - -func CheckExec(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - if !code.IsCallTo(pass, call, "os/exec.Command") { - return - } - val, ok := code.ExprToString(pass, call.Args[knowledge.Arg("os/exec.Command.name")]) - if !ok { - return - } - if !strings.Contains(val, " ") || strings.Contains(val, `\`) || strings.Contains(val, "/") { - return - } - report.Report(pass, call.Args[knowledge.Arg("os/exec.Command.name")], - "first argument to exec.Command looks like a shell command, but a program name or path are expected") - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckLoopEmptyDefault(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - loop := node.(*ast.ForStmt) - if len(loop.Body.List) != 1 || loop.Cond != nil || loop.Init != nil { - return - } - sel, ok := loop.Body.List[0].(*ast.SelectStmt) - if !ok { - return - } - for _, c := range sel.Body.List { - // FIXME this leaves behind an empty line, and possibly - // comments in the default branch. We can't easily fix - // either. - if comm, ok := c.(*ast.CommClause); ok && comm.Comm == nil && len(comm.Body) == 0 { - report.Report(pass, comm, "should not have an empty default case in a for+select loop; the loop will spin", - report.Fixes(edit.Fix("remove empty default branch", edit.Delete(comm)))) - // there can only be one default case - break - } - } - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil)) - return nil, nil -} - -func CheckLhsRhsIdentical(pass *analysis.Pass) (interface{}, error) { - var isFloat func(T types.Type) bool - isFloat = func(T types.Type) bool { - tset := typeutil.NewTypeSet(T) - if len(tset.Terms) == 0 { - // no terms, so floats are a possibility - return true - } - return tset.Any(func(term *types.Term) bool { - switch typ := term.Type().Underlying().(type) { - case *types.Basic: - kind := typ.Kind() - return kind == types.Float32 || kind == types.Float64 - case *types.Array: - return isFloat(typ.Elem()) - case *types.Struct: - for i := 0; i < typ.NumFields(); i++ { - if !isFloat(typ.Field(i).Type()) { - return false - } - } - return true - default: - return false - } - }) - } - - // TODO(dh): this check ignores the existence of side-effects and - // happily flags fn() == fn() – so far, we've had nobody complain - // about a false positive, and it's caught several bugs in real - // code. - // - // We special case functions from the math/rand package. Someone ran - // into the following false positive: "rand.Intn(2) - rand.Intn(2), which I wrote to generate values {-1, 0, 1} with {0.25, 0.5, 0.25} probability." - fn := func(node ast.Node) { - op := node.(*ast.BinaryExpr) - switch op.Op { - case token.EQL, token.NEQ: - case token.SUB, token.QUO, token.AND, token.REM, token.OR, token.XOR, token.AND_NOT, - token.LAND, token.LOR, token.LSS, token.GTR, token.LEQ, token.GEQ: - default: - // For some ops, such as + and *, it can make sense to - // have identical operands - return - } - - if isFloat(pass.TypesInfo.TypeOf(op.X)) { - // 'float float' makes sense for several operators. - // We've tried keeping an exact list of operators to allow, but floats keep surprising us. Let's just give up instead. - return - } - - if reflect.TypeOf(op.X) != reflect.TypeOf(op.Y) { - return - } - if report.Render(pass, op.X) != report.Render(pass, op.Y) { - return - } - l1, ok1 := op.X.(*ast.BasicLit) - l2, ok2 := op.Y.(*ast.BasicLit) - if ok1 && ok2 && l1.Kind == token.INT && l2.Kind == l1.Kind && l1.Value == "0" && l2.Value == l1.Value && code.IsGenerated(pass, l1.Pos()) { - // cgo generates the following function call: - // _cgoCheckPointer(_cgoBase0, 0 == 0) – it uses 0 == 0 - // instead of true in case the user shadowed the - // identifier. Ideally we'd restrict this exception to - // calls of _cgoCheckPointer, but it's not worth the - // hassle of keeping track of the stack. - // are very rare to begin with, and we're mostly checking - // for them to catch typos such as 1 == 1 where the user - // meant to type i == 1. The odds of a false negative for - // 0 == 0 are slim. - return - } - - if expr, ok := op.X.(*ast.CallExpr); ok { - call := code.CallName(pass, expr) - switch call { - case "math/rand.Int", - "math/rand.Int31", - "math/rand.Int31n", - "math/rand.Int63", - "math/rand.Int63n", - "math/rand.Intn", - "math/rand.Uint32", - "math/rand.Uint64", - "math/rand.ExpFloat64", - "math/rand.Float32", - "math/rand.Float64", - "math/rand.NormFloat64", - "(*math/rand.Rand).Int", - "(*math/rand.Rand).Int31", - "(*math/rand.Rand).Int31n", - "(*math/rand.Rand).Int63", - "(*math/rand.Rand).Int63n", - "(*math/rand.Rand).Intn", - "(*math/rand.Rand).Uint32", - "(*math/rand.Rand).Uint64", - "(*math/rand.Rand).ExpFloat64", - "(*math/rand.Rand).Float32", - "(*math/rand.Rand).Float64", - "(*math/rand.Rand).NormFloat64": - return - } - } - - report.Report(pass, op, fmt.Sprintf("identical expressions on the left and right side of the '%s' operator", op.Op)) - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -func CheckScopedBreak(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - var body *ast.BlockStmt - switch node := node.(type) { - case *ast.ForStmt: - body = node.Body - case *ast.RangeStmt: - body = node.Body - default: - lint.ExhaustiveTypeSwitch(node) - } - for _, stmt := range body.List { - var blocks [][]ast.Stmt - switch stmt := stmt.(type) { - case *ast.SwitchStmt: - for _, c := range stmt.Body.List { - blocks = append(blocks, c.(*ast.CaseClause).Body) - } - case *ast.SelectStmt: - for _, c := range stmt.Body.List { - blocks = append(blocks, c.(*ast.CommClause).Body) - } - default: - continue - } - - for _, body := range blocks { - if len(body) == 0 { - continue - } - lasts := []ast.Stmt{body[len(body)-1]} - // TODO(dh): unfold all levels of nested block - // statements, not just a single level if statement - if ifs, ok := lasts[0].(*ast.IfStmt); ok { - if len(ifs.Body.List) == 0 { - continue - } - lasts[0] = ifs.Body.List[len(ifs.Body.List)-1] - - if block, ok := ifs.Else.(*ast.BlockStmt); ok { - if len(block.List) != 0 { - lasts = append(lasts, block.List[len(block.List)-1]) - } - } - } - for _, last := range lasts { - branch, ok := last.(*ast.BranchStmt) - if !ok || branch.Tok != token.BREAK || branch.Label != nil { - continue - } - report.Report(pass, branch, "ineffective break statement. Did you mean to break out of the outer loop?") - } - } - } - } - code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.RangeStmt)(nil)) - return nil, nil -} - -func CheckUnsafePrintf(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - name := code.CallName(pass, call) - var arg int - - switch name { - case "fmt.Printf", "fmt.Sprintf", "log.Printf": - arg = knowledge.Arg("fmt.Printf.format") - case "fmt.Fprintf": - arg = knowledge.Arg("fmt.Fprintf.format") - default: - return - } - if len(call.Args) != arg+1 { - return - } - switch call.Args[arg].(type) { - case *ast.CallExpr, *ast.Ident: - default: - return - } - - if _, ok := pass.TypesInfo.TypeOf(call.Args[arg]).(*types.Tuple); ok { - // the called function returns multiple values and got - // splatted into the call. for all we know, it is - // returning good arguments. - return - } - - alt := name[:len(name)-1] - report.Report(pass, call, - "printf-style function with dynamic format string and no further arguments should use print-style function instead", - report.Fixes(edit.Fix(fmt.Sprintf("use %s instead of %s", alt, name), edit.ReplaceWithString(call.Fun, alt)))) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckEarlyDefer(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - block := node.(*ast.BlockStmt) - if len(block.List) < 2 { - return - } - for i, stmt := range block.List { - if i == len(block.List)-1 { - break - } - assign, ok := stmt.(*ast.AssignStmt) - if !ok { - continue - } - if len(assign.Rhs) != 1 { - continue - } - if len(assign.Lhs) < 2 { - continue - } - if lhs, ok := assign.Lhs[len(assign.Lhs)-1].(*ast.Ident); ok && lhs.Name == "_" { - continue - } - call, ok := assign.Rhs[0].(*ast.CallExpr) - if !ok { - continue - } - sig, ok := pass.TypesInfo.TypeOf(call.Fun).(*types.Signature) - if !ok { - continue - } - if sig.Results().Len() < 2 { - continue - } - last := sig.Results().At(sig.Results().Len() - 1) - // FIXME(dh): check that it's error from universe, not - // another type of the same name - if last.Type().String() != "error" { - continue - } - lhs, ok := assign.Lhs[0].(*ast.Ident) - if !ok { - continue - } - def, ok := block.List[i+1].(*ast.DeferStmt) - if !ok { - continue - } - sel, ok := def.Call.Fun.(*ast.SelectorExpr) - if !ok { - continue - } - ident, ok := selectorX(sel).(*ast.Ident) - if !ok { - continue - } - if pass.TypesInfo.ObjectOf(ident) != pass.TypesInfo.ObjectOf(lhs) { - continue - } - if sel.Sel.Name != "Close" { - continue - } - report.Report(pass, def, fmt.Sprintf("should check returned error before deferring %s", report.Render(pass, def.Call))) - } - } - code.Preorder(pass, fn, (*ast.BlockStmt)(nil)) - return nil, nil -} - -func selectorX(sel *ast.SelectorExpr) ast.Node { - switch x := sel.X.(type) { - case *ast.SelectorExpr: - return selectorX(x) - default: - return x - } -} - -func CheckEmptyCriticalSection(pass *analysis.Pass) (interface{}, error) { - if pass.Pkg.Path() == "sync_test" { - // exception for the sync package's tests - return nil, nil - } - - // Initially it might seem like this check would be easier to - // implement using IR. After all, we're only checking for two - // consecutive method calls. In reality, however, there may be any - // number of other instructions between the lock and unlock, while - // still constituting an empty critical section. For example, - // given `m.x().Lock(); m.x().Unlock()`, there will be a call to - // x(). In the AST-based approach, this has a tiny potential for a - // false positive (the second call to x might be doing work that - // is protected by the mutex). In an IR-based approach, however, - // it would miss a lot of real bugs. - - mutexParams := func(s ast.Stmt) (x ast.Expr, funcName string, ok bool) { - expr, ok := s.(*ast.ExprStmt) - if !ok { - return nil, "", false - } - call, ok := astutil.Unparen(expr.X).(*ast.CallExpr) - if !ok { - return nil, "", false - } - sel, ok := call.Fun.(*ast.SelectorExpr) - if !ok { - return nil, "", false - } - - fn, ok := pass.TypesInfo.ObjectOf(sel.Sel).(*types.Func) - if !ok { - return nil, "", false - } - sig := fn.Type().(*types.Signature) - if sig.Params().Len() != 0 || sig.Results().Len() != 0 { - return nil, "", false - } - - return sel.X, fn.Name(), true - } - - fn := func(node ast.Node) { - block := node.(*ast.BlockStmt) - if len(block.List) < 2 { - return - } - for i := range block.List[:len(block.List)-1] { - sel1, method1, ok1 := mutexParams(block.List[i]) - sel2, method2, ok2 := mutexParams(block.List[i+1]) - - if !ok1 || !ok2 || report.Render(pass, sel1) != report.Render(pass, sel2) { - continue - } - if (method1 == "Lock" && method2 == "Unlock") || - (method1 == "RLock" && method2 == "RUnlock") { - report.Report(pass, block.List[i+1], "empty critical section") - } - } - } - code.Preorder(pass, fn, (*ast.BlockStmt)(nil)) - return nil, nil -} - -var ( - // cgo produces code like fn(&*_Cvar_kSomeCallbacks) which we don't - // want to flag. - cgoIdent = regexp.MustCompile(`^_C(func|var)_.+$`) - checkIneffectiveCopyQ1 = pattern.MustParse(`(UnaryExpr "&" (StarExpr obj))`) - checkIneffectiveCopyQ2 = pattern.MustParse(`(StarExpr (UnaryExpr "&" _))`) -) - -func CheckIneffectiveCopy(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if m, ok := code.Match(pass, checkIneffectiveCopyQ1, node); ok { - if ident, ok := m.State["obj"].(*ast.Ident); !ok || !cgoIdent.MatchString(ident.Name) { - report.Report(pass, node, "&*x will be simplified to x. It will not copy x.") - } - } else if _, ok := code.Match(pass, checkIneffectiveCopyQ2, node); ok { - report.Report(pass, node, "*&x will be simplified to x. It will not copy x.") - } - } - code.Preorder(pass, fn, (*ast.UnaryExpr)(nil), (*ast.StarExpr)(nil)) - return nil, nil -} - -func CheckCanonicalHeaderKey(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node, push bool) bool { - if !push { - return false - } - if assign, ok := node.(*ast.AssignStmt); ok { - // TODO(dh): This risks missing some Header reads, for - // example in `h1["foo"] = h2["foo"]` – these edge - // cases are probably rare enough to ignore for now. - for _, expr := range assign.Lhs { - op, ok := expr.(*ast.IndexExpr) - if !ok { - continue - } - if code.IsOfType(pass, op.X, "net/http.Header") { - return false - } - } - return true - } - op, ok := node.(*ast.IndexExpr) - if !ok { - return true - } - if !code.IsOfType(pass, op.X, "net/http.Header") { - return true - } - s, ok := code.ExprToString(pass, op.Index) - if !ok { - return true - } - canonical := http.CanonicalHeaderKey(s) - if s == canonical { - return true - } - var fix analysis.SuggestedFix - switch op.Index.(type) { - case *ast.BasicLit: - fix = edit.Fix("canonicalize header key", edit.ReplaceWithString(op.Index, strconv.Quote(canonical))) - case *ast.Ident: - call := &ast.CallExpr{ - Fun: edit.Selector("http", "CanonicalHeaderKey"), - Args: []ast.Expr{op.Index}, - } - fix = edit.Fix("wrap in http.CanonicalHeaderKey", edit.ReplaceWithNode(pass.Fset, op.Index, call)) - } - msg := fmt.Sprintf("keys in http.Header are canonicalized, %q is not canonical; fix the constant or use http.CanonicalHeaderKey", s) - if fix.Message != "" { - report.Report(pass, op, msg, report.Fixes(fix)) - } else { - report.Report(pass, op, msg) - } - return true - } - pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.AssignStmt)(nil), (*ast.IndexExpr)(nil)}, fn) - return nil, nil -} - -func CheckBenchmarkN(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - assign := node.(*ast.AssignStmt) - if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { - return - } - sel, ok := assign.Lhs[0].(*ast.SelectorExpr) - if !ok { - return - } - if sel.Sel.Name != "N" { - return - } - if !code.IsOfType(pass, sel.X, "*testing.B") { - return - } - report.Report(pass, assign, fmt.Sprintf("should not assign to %s", report.Render(pass, sel))) - } - code.Preorder(pass, fn, (*ast.AssignStmt)(nil)) - return nil, nil -} - -func CheckUnreadVariableValues(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - if irutil.IsExample(fn) { - continue - } - node := fn.Source() - if node == nil { - continue - } - if gen, ok := code.Generator(pass, node.Pos()); ok && gen == generated.Goyacc { - // Don't flag unused values in code generated by goyacc. - // There may be hundreds of those due to the way the state - // machine is constructed. - continue - } - - switchTags := map[ir.Value]struct{}{} - ast.Inspect(node, func(node ast.Node) bool { - s, ok := node.(*ast.SwitchStmt) - if !ok { - return true - } - v, _ := fn.ValueForExpr(s.Tag) - switchTags[v] = struct{}{} - return true - }) - - // OPT(dh): don't use a map, possibly use a bitset - var hasUse func(v ir.Value, seen map[ir.Value]struct{}) bool - hasUse = func(v ir.Value, seen map[ir.Value]struct{}) bool { - if _, ok := seen[v]; ok { - return false - } - if _, ok := switchTags[v]; ok { - return true - } - refs := v.Referrers() - if refs == nil { - // TODO investigate why refs can be nil - return true - } - for _, ref := range *refs { - switch ref := ref.(type) { - case *ir.DebugRef: - case *ir.Sigma: - if seen == nil { - seen = map[ir.Value]struct{}{} - } - seen[v] = struct{}{} - if hasUse(ref, seen) { - return true - } - case *ir.Phi: - if seen == nil { - seen = map[ir.Value]struct{}{} - } - seen[v] = struct{}{} - if hasUse(ref, seen) { - return true - } - default: - return true - } - } - return false - } - - ast.Inspect(node, func(node ast.Node) bool { - assign, ok := node.(*ast.AssignStmt) - if !ok { - return true - } - if len(assign.Lhs) > 1 && len(assign.Rhs) == 1 { - // Either a function call with multiple return values, - // or a comma-ok assignment - - val, _ := fn.ValueForExpr(assign.Rhs[0]) - if val == nil { - return true - } - refs := val.Referrers() - if refs == nil { - return true - } - for _, ref := range *refs { - ex, ok := ref.(*ir.Extract) - if !ok { - continue - } - if !hasUse(ex, nil) { - lhs := assign.Lhs[ex.Index] - if ident, ok := lhs.(*ast.Ident); !ok || ok && ident.Name == "_" { - continue - } - report.Report(pass, assign, fmt.Sprintf("this value of %s is never used", lhs)) - } - } - return true - } - for i, lhs := range assign.Lhs { - rhs := assign.Rhs[i] - if ident, ok := lhs.(*ast.Ident); !ok || ok && ident.Name == "_" { - continue - } - val, _ := fn.ValueForExpr(rhs) - if val == nil { - continue - } - - if _, ok := val.(*ir.Const); ok { - // a zero-valued constant, for example in 'foo := []string(nil)' - continue - } - if !hasUse(val, nil) { - report.Report(pass, assign, fmt.Sprintf("this value of %s is never used", lhs)) - } - } - return true - }) - } - return nil, nil -} - -func CheckPredeterminedBooleanExprs(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - binop, ok := ins.(*ir.BinOp) - if !ok { - continue - } - switch binop.Op { - case token.GTR, token.LSS, token.EQL, token.NEQ, token.LEQ, token.GEQ: - default: - continue - } - - xs, ok1 := consts(binop.X, nil, nil) - ys, ok2 := consts(binop.Y, nil, nil) - if !ok1 || !ok2 || len(xs) == 0 || len(ys) == 0 { - continue - } - - trues := 0 - for _, x := range xs { - for _, y := range ys { - if x.Value == nil { - if y.Value == nil { - trues++ - } - continue - } - if constant.Compare(x.Value, binop.Op, y.Value) { - trues++ - } - } - } - b := trues != 0 - if trues == 0 || trues == len(xs)*len(ys) { - report.Report(pass, binop, fmt.Sprintf("binary expression is always %t for all possible values (%s %s %s)", b, xs, binop.Op, ys)) - } - } - } - } - return nil, nil -} - -func CheckNilMaps(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - mu, ok := ins.(*ir.MapUpdate) - if !ok { - continue - } - c, ok := irutil.Flatten(mu.Map).(*ir.Const) - if !ok { - continue - } - if c.Value != nil { - continue - } - report.Report(pass, mu, "assignment to nil map") - } - } - } - return nil, nil -} - -func CheckExtremeComparison(pass *analysis.Pass) (interface{}, error) { - isobj := func(expr ast.Expr, name string) bool { - sel, ok := expr.(*ast.SelectorExpr) - if !ok { - return false - } - return typeutil.IsObject(pass.TypesInfo.ObjectOf(sel.Sel), name) - } - - fn := func(node ast.Node) { - expr := node.(*ast.BinaryExpr) - tx := pass.TypesInfo.TypeOf(expr.X) - basic, ok := tx.Underlying().(*types.Basic) - if !ok { - return - } - - var max string - var min string - - switch basic.Kind() { - case types.Uint8: - max = "math.MaxUint8" - case types.Uint16: - max = "math.MaxUint16" - case types.Uint32: - max = "math.MaxUint32" - case types.Uint64: - max = "math.MaxUint64" - case types.Uint: - max = "math.MaxUint64" - - case types.Int8: - min = "math.MinInt8" - max = "math.MaxInt8" - case types.Int16: - min = "math.MinInt16" - max = "math.MaxInt16" - case types.Int32: - min = "math.MinInt32" - max = "math.MaxInt32" - case types.Int64: - min = "math.MinInt64" - max = "math.MaxInt64" - case types.Int: - min = "math.MinInt64" - max = "math.MaxInt64" - } - - if (expr.Op == token.GTR || expr.Op == token.GEQ) && isobj(expr.Y, max) || - (expr.Op == token.LSS || expr.Op == token.LEQ) && isobj(expr.X, max) { - report.Report(pass, expr, fmt.Sprintf("no value of type %s is greater than %s", basic, max)) - } - if expr.Op == token.LEQ && isobj(expr.Y, max) || - expr.Op == token.GEQ && isobj(expr.X, max) { - report.Report(pass, expr, fmt.Sprintf("every value of type %s is <= %s", basic, max)) - } - - isZeroLiteral := func(expr ast.Expr) bool { - return code.IsIntegerLiteral(pass, expr, constant.MakeInt64(0)) - } - if (basic.Info() & types.IsUnsigned) != 0 { - if (expr.Op == token.LSS && isZeroLiteral(expr.Y)) || - (expr.Op == token.GTR && isZeroLiteral(expr.X)) { - report.Report(pass, expr, fmt.Sprintf("no value of type %s is less than 0", basic)) - } - if expr.Op == token.GEQ && isZeroLiteral(expr.Y) || - expr.Op == token.LEQ && isZeroLiteral(expr.X) { - report.Report(pass, expr, fmt.Sprintf("every value of type %s is >= 0", basic)) - } - } else { - if (expr.Op == token.LSS || expr.Op == token.LEQ) && isobj(expr.Y, min) || - (expr.Op == token.GTR || expr.Op == token.GEQ) && isobj(expr.X, min) { - report.Report(pass, expr, fmt.Sprintf("no value of type %s is less than %s", basic, min)) - } - if expr.Op == token.GEQ && isobj(expr.Y, min) || - expr.Op == token.LEQ && isobj(expr.X, min) { - report.Report(pass, expr, fmt.Sprintf("every value of type %s is >= %s", basic, min)) - } - } - - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -func consts(val ir.Value, out []*ir.Const, visitedPhis map[string]bool) ([]*ir.Const, bool) { - if visitedPhis == nil { - visitedPhis = map[string]bool{} - } - var ok bool - switch val := val.(type) { - case *ir.Phi: - if visitedPhis[val.Name()] { - break - } - visitedPhis[val.Name()] = true - vals := val.Operands(nil) - for _, phival := range vals { - out, ok = consts(*phival, out, visitedPhis) - if !ok { - return nil, false - } - } - case *ir.Const: - out = append(out, val) - case *ir.Convert: - out, ok = consts(val.X, out, visitedPhis) - if !ok { - return nil, false - } - default: - return nil, false - } - if len(out) < 2 { - return out, true - } - uniq := []*ir.Const{out[0]} - for _, val := range out[1:] { - if val.Value == uniq[len(uniq)-1].Value { - continue - } - uniq = append(uniq, val) - } - return uniq, true -} - -func CheckLoopCondition(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - cb := func(node ast.Node) bool { - loop, ok := node.(*ast.ForStmt) - if !ok { - return true - } - if loop.Init == nil || loop.Cond == nil || loop.Post == nil { - return true - } - init, ok := loop.Init.(*ast.AssignStmt) - if !ok || len(init.Lhs) != 1 || len(init.Rhs) != 1 { - return true - } - cond, ok := loop.Cond.(*ast.BinaryExpr) - if !ok { - return true - } - x, ok := cond.X.(*ast.Ident) - if !ok { - return true - } - lhs, ok := init.Lhs[0].(*ast.Ident) - if !ok { - return true - } - if pass.TypesInfo.ObjectOf(x) != pass.TypesInfo.ObjectOf(lhs) { - return true - } - if _, ok := loop.Post.(*ast.IncDecStmt); !ok { - return true - } - - v, isAddr := fn.ValueForExpr(cond.X) - if v == nil || isAddr { - return true - } - switch v := v.(type) { - case *ir.Phi: - ops := v.Operands(nil) - if len(ops) != 2 { - return true - } - _, ok := (*ops[0]).(*ir.Const) - if !ok { - return true - } - sigma, ok := (*ops[1]).(*ir.Sigma) - if !ok { - return true - } - if sigma.X != v { - return true - } - case *ir.Load: - return true - } - report.Report(pass, cond, "variable in loop condition never changes") - - return true - } - if source := fn.Source(); source != nil { - ast.Inspect(source, cb) - } - } - return nil, nil -} - -func CheckArgOverwritten(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - cb := func(node ast.Node) bool { - var typ *ast.FuncType - var body *ast.BlockStmt - switch fn := node.(type) { - case *ast.FuncDecl: - typ = fn.Type - body = fn.Body - case *ast.FuncLit: - typ = fn.Type - body = fn.Body - } - if body == nil { - return true - } - if len(typ.Params.List) == 0 { - return true - } - for _, field := range typ.Params.List { - for _, arg := range field.Names { - obj := pass.TypesInfo.ObjectOf(arg) - var irobj *ir.Parameter - for _, param := range fn.Params { - if param.Object() == obj { - irobj = param - break - } - } - if irobj == nil { - continue - } - refs := irobj.Referrers() - if refs == nil { - continue - } - if len(irutil.FilterDebug(*refs)) != 0 { - continue - } - - var assignment ast.Node - ast.Inspect(body, func(node ast.Node) bool { - if assignment != nil { - return false - } - assign, ok := node.(*ast.AssignStmt) - if !ok { - return true - } - for _, lhs := range assign.Lhs { - ident, ok := lhs.(*ast.Ident) - if !ok { - continue - } - if pass.TypesInfo.ObjectOf(ident) == obj { - assignment = assign - return false - } - } - return true - }) - if assignment != nil { - report.Report(pass, arg, fmt.Sprintf("argument %s is overwritten before first use", arg), - report.Related(assignment, fmt.Sprintf("assignment to %s", arg))) - } - } - } - return true - } - if source := fn.Source(); source != nil { - ast.Inspect(source, cb) - } - } - return nil, nil -} - -func CheckIneffectiveLoop(pass *analysis.Pass) (interface{}, error) { - // This check detects some, but not all unconditional loop exits. - // We give up in the following cases: - // - // - a goto anywhere in the loop. The goto might skip over our - // return, and we don't check that it doesn't. - // - // - any nested, unlabelled continue, even if it is in another - // loop or closure. - fn := func(node ast.Node) { - var body *ast.BlockStmt - switch fn := node.(type) { - case *ast.FuncDecl: - body = fn.Body - case *ast.FuncLit: - body = fn.Body - default: - lint.ExhaustiveTypeSwitch(node) - } - if body == nil { - return - } - labels := map[types.Object]ast.Stmt{} - ast.Inspect(body, func(node ast.Node) bool { - label, ok := node.(*ast.LabeledStmt) - if !ok { - return true - } - labels[pass.TypesInfo.ObjectOf(label.Label)] = label.Stmt - return true - }) - - ast.Inspect(body, func(node ast.Node) bool { - var loop ast.Node - var body *ast.BlockStmt - switch node := node.(type) { - case *ast.ForStmt: - body = node.Body - loop = node - case *ast.RangeStmt: - ok := typeutil.All(pass.TypesInfo.TypeOf(node.X), func(term *types.Term) bool { - switch term.Type().Underlying().(type) { - case *types.Slice, *types.Chan, *types.Basic, *types.Pointer, *types.Array: - return true - case *types.Map: - // looping once over a map is a valid pattern for - // getting an arbitrary element. - return false - default: - lint.ExhaustiveTypeSwitch(term.Type().Underlying()) - return false - } - }) - if !ok { - return true - } - body = node.Body - loop = node - default: - return true - } - if len(body.List) < 2 { - // TODO(dh): is this check needed? when body.List < 2, - // then we can't find both an unconditional exit and a - // branching statement (if, ...). and we don't flag - // unconditional exits if there has been no branching - // in the loop body. - - // avoid flagging the somewhat common pattern of using - // a range loop to get the first element in a slice, - // or the first rune in a string. - return true - } - var unconditionalExit ast.Node - hasBranching := false - for _, stmt := range body.List { - switch stmt := stmt.(type) { - case *ast.BranchStmt: - switch stmt.Tok { - case token.BREAK: - if stmt.Label == nil || labels[pass.TypesInfo.ObjectOf(stmt.Label)] == loop { - unconditionalExit = stmt - } - case token.CONTINUE: - if stmt.Label == nil || labels[pass.TypesInfo.ObjectOf(stmt.Label)] == loop { - unconditionalExit = nil - return false - } - } - case *ast.ReturnStmt: - unconditionalExit = stmt - case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt: - hasBranching = true - } - } - if unconditionalExit == nil || !hasBranching { - return false - } - ast.Inspect(body, func(node ast.Node) bool { - if branch, ok := node.(*ast.BranchStmt); ok { - - switch branch.Tok { - case token.GOTO: - unconditionalExit = nil - return false - case token.CONTINUE: - if branch.Label != nil && labels[pass.TypesInfo.ObjectOf(branch.Label)] != loop { - return true - } - unconditionalExit = nil - return false - } - } - return true - }) - if unconditionalExit != nil { - report.Report(pass, unconditionalExit, "the surrounding loop is unconditionally terminated") - } - return true - }) - } - code.Preorder(pass, fn, (*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) - return nil, nil -} - -var checkNilContextQ = pattern.MustParse(`(CallExpr fun@(Symbol _) (Builtin "nil"):_)`) - -func CheckNilContext(pass *analysis.Pass) (interface{}, error) { - todo := &ast.CallExpr{ - Fun: edit.Selector("context", "TODO"), - } - bg := &ast.CallExpr{ - Fun: edit.Selector("context", "Background"), - } - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkNilContextQ, node) - if !ok { - return - } - - call := node.(*ast.CallExpr) - fun, ok := m.State["fun"].(*types.Func) - if !ok { - // it might also be a builtin - return - } - sig := fun.Type().(*types.Signature) - if sig.Params().Len() == 0 { - // Our CallExpr might've matched a method expression, like - // (*T).Foo(nil) – here, nil isn't the first argument of - // the Foo method, but the method receiver. - return - } - if !typeutil.IsType(sig.Params().At(0).Type(), "context.Context") { - return - } - report.Report(pass, call.Args[0], - "do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use", report.Fixes( - edit.Fix("use context.TODO", edit.ReplaceWithNode(pass.Fset, call.Args[0], todo)), - edit.Fix("use context.Background", edit.ReplaceWithNode(pass.Fset, call.Args[0], bg)))) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var ( - checkSeekerQ = pattern.MustParse(`(CallExpr fun@(SelectorExpr _ (Ident "Seek")) [arg1@(SelectorExpr _ (Symbol (Or "io.SeekStart" "io.SeekCurrent" "io.SeekEnd"))) arg2])`) - checkSeekerR = pattern.MustParse(`(CallExpr fun [arg2 arg1])`) -) - -func CheckSeeker(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if m, edits, ok := code.MatchAndEdit(pass, checkSeekerQ, checkSeekerR, node); ok { - if !code.IsMethod(pass, m.State["fun"].(*ast.SelectorExpr), "Seek", knowledge.Signatures["(io.Seeker).Seek"]) { - return - } - report.Report(pass, node, "the first argument of io.Seeker is the offset, but an io.Seek* constant is being used instead", - report.Fixes(edit.Fix("swap arguments", edits...))) - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckIneffectiveAppend(pass *analysis.Pass) (interface{}, error) { - isAppend := func(ins ir.Value) bool { - call, ok := ins.(*ir.Call) - if !ok { - return false - } - if call.Call.IsInvoke() { - return false - } - if builtin, ok := call.Call.Value.(*ir.Builtin); !ok || builtin.Name() != "append" { - return false - } - return true - } - - // We have to be careful about aliasing. - // Multiple slices may refer to the same backing array, - // making appends observable even when we don't see the result of append be used anywhere. - // - // We will have to restrict ourselves to slices that have been allocated within the function, - // haven't been sliced, - // and haven't been passed anywhere that could retain them (such as function calls or memory stores). - // - // We check whether an append should be flagged in two steps. - // - // In the first step, we look at the data flow graph, starting in reverse from the argument to append, till we reach the root. - // This graph must only consist of the following instructions: - // - // - phi - // - sigma - // - slice - // - const nil - // - MakeSlice - // - Alloc - // - calls to append - // - // If this step succeeds, we look at all referrers of the values found in the first step, recursively. - // These referrers must either be in the set of values found in the first step, - // be DebugRefs, - // or fulfill the same type requirements as step 1, with the exception of appends, which are forbidden. - // - // If both steps succeed then we know that the backing array hasn't been aliased in an observable manner. - // - // We could relax these restrictions by making use of additional information: - // - if we passed the slice to a function that doesn't retain the slice then we can still flag it - // - if a slice has been sliced but is dead afterwards, we can flag appends to the new slice - - // OPT(dh): We could cache the results of both validate functions. - // However, we only use these functions on values that we otherwise want to flag, which are very few. - // Not caching values hasn't increased the runtimes for the standard library nor k8s. - var validateArgument func(v ir.Value, seen map[ir.Value]struct{}) bool - validateArgument = func(v ir.Value, seen map[ir.Value]struct{}) bool { - if _, ok := seen[v]; ok { - // break cycle - return true - } - seen[v] = struct{}{} - switch v := v.(type) { - case *ir.Phi: - for _, edge := range v.Edges { - if !validateArgument(edge, seen) { - return false - } - } - return true - case *ir.Sigma: - return validateArgument(v.X, seen) - case *ir.Slice: - return validateArgument(v.X, seen) - case *ir.Const: - return true - case *ir.MakeSlice: - return true - case *ir.Alloc: - return true - case *ir.Call: - if isAppend(v) { - return validateArgument(v.Call.Args[0], seen) - } - return false - default: - return false - } - } - - var validateReferrers func(v ir.Value, seen map[ir.Instruction]struct{}) bool - validateReferrers = func(v ir.Value, seen map[ir.Instruction]struct{}) bool { - for _, ref := range *v.Referrers() { - if _, ok := seen[ref]; ok { - continue - } - - seen[ref] = struct{}{} - switch ref.(type) { - case *ir.Phi: - case *ir.Sigma: - case *ir.Slice: - case *ir.Const: - case *ir.MakeSlice: - case *ir.Alloc: - case *ir.DebugRef: - default: - return false - } - - if ref, ok := ref.(ir.Value); ok { - if !validateReferrers(ref, seen) { - return false - } - } - } - return true - } - - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - val, ok := ins.(ir.Value) - if !ok || !isAppend(val) { - continue - } - - isUsed := false - visited := map[ir.Instruction]bool{} - var walkRefs func(refs []ir.Instruction) - walkRefs = func(refs []ir.Instruction) { - loop: - for _, ref := range refs { - if visited[ref] { - continue - } - visited[ref] = true - if _, ok := ref.(*ir.DebugRef); ok { - continue - } - switch ref := ref.(type) { - case *ir.Phi: - walkRefs(*ref.Referrers()) - case *ir.Sigma: - walkRefs(*ref.Referrers()) - case ir.Value: - if !isAppend(ref) { - isUsed = true - } else { - walkRefs(*ref.Referrers()) - } - case ir.Instruction: - isUsed = true - break loop - } - } - } - - refs := val.Referrers() - if refs == nil { - continue - } - walkRefs(*refs) - - if isUsed { - continue - } - - seen := map[ir.Value]struct{}{} - if !validateArgument(ins.(*ir.Call).Call.Args[0], seen) { - continue - } - - seen2 := map[ir.Instruction]struct{}{} - for k := range seen { - // the only values we allow are also instructions, so this type assertion cannot fail - seen2[k.(ir.Instruction)] = struct{}{} - } - seen2[ins] = struct{}{} - failed := false - for v := range seen { - if !validateReferrers(v, seen2) { - failed = true - break - } - } - if !failed { - report.Report(pass, ins, "this result of append is never used, except maybe in other appends") - } - } - } - } - return nil, nil -} - -func CheckConcurrentTesting(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - gostmt, ok := ins.(*ir.Go) - if !ok { - continue - } - var fn *ir.Function - switch val := gostmt.Call.Value.(type) { - case *ir.Function: - fn = val - case *ir.MakeClosure: - fn = val.Fn.(*ir.Function) - default: - continue - } - if fn.Blocks == nil { - continue - } - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - call, ok := ins.(*ir.Call) - if !ok { - continue - } - if call.Call.IsInvoke() { - continue - } - callee := call.Call.StaticCallee() - if callee == nil { - continue - } - recv := callee.Signature.Recv() - if recv == nil { - continue - } - if !typeutil.IsType(recv.Type(), "*testing.common") { - continue - } - fn, ok := call.Call.StaticCallee().Object().(*types.Func) - if !ok { - continue - } - name := fn.Name() - switch name { - case "FailNow", "Fatal", "Fatalf", "SkipNow", "Skip", "Skipf": - default: - continue - } - // TODO(dh): don't report multiple diagnostics - // for multiple calls to T.Fatal, but do - // collect all of them as related information - report.Report(pass, gostmt, fmt.Sprintf("the goroutine calls T.%s, which must be called in the same goroutine as the test", name), - report.Related(call, fmt.Sprintf("call to T.%s", name))) - } - } - } - } - } - return nil, nil -} - -func eachCall(fn *ir.Function, cb func(caller *ir.Function, site ir.CallInstruction, callee *ir.Function)) { - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - if site, ok := instr.(ir.CallInstruction); ok { - if g := site.Common().StaticCallee(); g != nil { - cb(fn, site, g) - } - } - } - } -} - -func CheckCyclicFinalizer(pass *analysis.Pass) (interface{}, error) { - cb := func(caller *ir.Function, site ir.CallInstruction, callee *ir.Function) { - if callee.RelString(nil) != "runtime.SetFinalizer" { - return - } - arg0 := site.Common().Args[knowledge.Arg("runtime.SetFinalizer.obj")] - if iface, ok := arg0.(*ir.MakeInterface); ok { - arg0 = iface.X - } - load, ok := arg0.(*ir.Load) - if !ok { - return - } - v, ok := load.X.(*ir.Alloc) - if !ok { - return - } - arg1 := site.Common().Args[knowledge.Arg("runtime.SetFinalizer.finalizer")] - if iface, ok := arg1.(*ir.MakeInterface); ok { - arg1 = iface.X - } - mc, ok := arg1.(*ir.MakeClosure) - if !ok { - return - } - for _, b := range mc.Bindings { - if b == v { - pos := report.DisplayPosition(pass.Fset, mc.Fn.Pos()) - report.Report(pass, site, fmt.Sprintf("the finalizer closes over the object, preventing the finalizer from ever running (at %s)", pos)) - } - } - } - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - eachCall(fn, cb) - } - return nil, nil -} - -/* -func CheckSliceOutOfBounds(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - ia, ok := ins.(*ir.IndexAddr) - if !ok { - continue - } - if _, ok := ia.X.Type().Underlying().(*types.Slice); !ok { - continue - } - sr, ok1 := c.funcDescs.Get(fn).Ranges[ia.X].(vrp.SliceInterval) - idxr, ok2 := c.funcDescs.Get(fn).Ranges[ia.Index].(vrp.IntInterval) - if !ok1 || !ok2 || !sr.IsKnown() || !idxr.IsKnown() || sr.Length.Empty() || idxr.Empty() { - continue - } - if idxr.Lower.Cmp(sr.Length.Upper) >= 0 { - report.Nodef(pass, ia, "index out of bounds") - } - } - } - } - return nil, nil -} -*/ - -func CheckDeferLock(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - instrs := irutil.FilterDebug(block.Instrs) - if len(instrs) < 2 { - continue - } - for i, ins := range instrs[:len(instrs)-1] { - call, ok := ins.(*ir.Call) - if !ok { - continue - } - if !irutil.IsCallToAny(call.Common(), "(*sync.Mutex).Lock", "(*sync.RWMutex).RLock") { - continue - } - nins, ok := instrs[i+1].(*ir.Defer) - if !ok { - continue - } - if !irutil.IsCallToAny(&nins.Call, "(*sync.Mutex).Lock", "(*sync.RWMutex).RLock") { - continue - } - if call.Common().Args[0] != nins.Call.Args[0] { - continue - } - name := shortCallName(call.Common()) - alt := "" - switch name { - case "Lock": - alt = "Unlock" - case "RLock": - alt = "RUnlock" - } - report.Report(pass, nins, fmt.Sprintf("deferring %s right after having locked already; did you mean to defer %s?", name, alt)) - } - } - } - return nil, nil -} - -func CheckNaNComparison(pass *analysis.Pass) (interface{}, error) { - isNaN := func(v ir.Value) bool { - call, ok := v.(*ir.Call) - if !ok { - return false - } - return irutil.IsCallTo(call.Common(), "math.NaN") - } - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - ins, ok := ins.(*ir.BinOp) - if !ok { - continue - } - if isNaN(irutil.Flatten(ins.X)) || isNaN(irutil.Flatten(ins.Y)) { - report.Report(pass, ins, "no value is equal to NaN, not even NaN itself") - } - } - } - } - return nil, nil -} - -func CheckInfiniteRecursion(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - eachCall(fn, func(caller *ir.Function, site ir.CallInstruction, callee *ir.Function) { - if callee != fn { - return - } - if _, ok := site.(*ir.Go); ok { - // Recursively spawning goroutines doesn't consume - // stack space infinitely, so don't flag it. - return - } - - block := site.Block() - for _, b := range fn.Blocks { - if block.Dominates(b) { - continue - } - if len(b.Instrs) == 0 { - continue - } - if _, ok := b.Control().(*ir.Return); ok { - return - } - } - report.Report(pass, site, "infinite recursive call") - }) - } - return nil, nil -} - -func CheckLeakyTimeTick(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - if code.IsMainLike(pass) || code.IsInTest(pass, fn) { - continue - } - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - call, ok := ins.(*ir.Call) - if !ok || !irutil.IsCallTo(call.Common(), "time.Tick") { - continue - } - if !irutil.Terminates(call.Parent()) { - continue - } - report.Report(pass, call, "using time.Tick leaks the underlying ticker, consider using it only in endless functions, tests and the main package, and use time.NewTicker here") - } - } - } - return nil, nil -} - -var checkDoubleNegationQ = pattern.MustParse(`(UnaryExpr "!" single@(UnaryExpr "!" x))`) - -func CheckDoubleNegation(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if m, ok := code.Match(pass, checkDoubleNegationQ, node); ok { - report.Report(pass, node, "negating a boolean twice has no effect; is this a typo?", report.Fixes( - edit.Fix("turn into single negation", edit.ReplaceWithNode(pass.Fset, node, m.State["single"].(ast.Node))), - edit.Fix("remove double negation", edit.ReplaceWithNode(pass.Fset, node, m.State["x"].(ast.Node))))) - } - } - code.Preorder(pass, fn, (*ast.UnaryExpr)(nil)) - return nil, nil -} - -func CheckRepeatedIfElse(pass *analysis.Pass) (interface{}, error) { - seen := map[ast.Node]bool{} - - var collectConds func(ifstmt *ast.IfStmt, conds []ast.Expr) ([]ast.Expr, bool) - collectConds = func(ifstmt *ast.IfStmt, conds []ast.Expr) ([]ast.Expr, bool) { - seen[ifstmt] = true - // Bail if any if-statement has an Init statement or side effects in its condition - if ifstmt.Init != nil { - return nil, false - } - if code.MayHaveSideEffects(pass, ifstmt.Cond, nil) { - return nil, false - } - - conds = append(conds, ifstmt.Cond) - if elsestmt, ok := ifstmt.Else.(*ast.IfStmt); ok { - return collectConds(elsestmt, conds) - } - return conds, true - } - fn := func(node ast.Node) { - ifstmt := node.(*ast.IfStmt) - if seen[ifstmt] { - // this if-statement is part of an if/else-if chain that we've already processed - return - } - if ifstmt.Else == nil { - // there can be at most one condition - return - } - conds, ok := collectConds(ifstmt, nil) - if !ok { - return - } - if len(conds) < 2 { - return - } - counts := map[string]int{} - for _, cond := range conds { - s := report.Render(pass, cond) - counts[s]++ - if counts[s] == 2 { - report.Report(pass, cond, "this condition occurs multiple times in this if/else if chain") - } - } - } - code.Preorder(pass, fn, (*ast.IfStmt)(nil)) - return nil, nil -} - -func CheckSillyBitwiseOps(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - binop := node.(*ast.BinaryExpr) - if !typeutil.All(pass.TypesInfo.TypeOf(binop), func(term *types.Term) bool { - b, ok := term.Type().Underlying().(*types.Basic) - if !ok { - return false - } - return (b.Info() & types.IsInteger) != 0 - }) { - return - } - switch binop.Op { - case token.AND, token.OR, token.XOR: - default: - // we do not flag shifts because too often, x<<0 is part - // of a pattern, x<<0, x<<8, x<<16, ... - return - } - if y, ok := binop.Y.(*ast.Ident); ok { - obj, ok := pass.TypesInfo.ObjectOf(y).(*types.Const) - if !ok { - return - } - if obj.Pkg() != pass.Pkg { - // identifier was dot-imported - return - } - if v, _ := constant.Int64Val(obj.Val()); v != 0 { - return - } - path, _ := astutil.PathEnclosingInterval(code.File(pass, obj), obj.Pos(), obj.Pos()) - if len(path) < 2 { - return - } - spec, ok := path[1].(*ast.ValueSpec) - if !ok { - return - } - if len(spec.Names) != 1 || len(spec.Values) != 1 { - // TODO(dh): we could support this - return - } - ident, ok := spec.Values[0].(*ast.Ident) - if !ok { - return - } - if !isIota(pass.TypesInfo.ObjectOf(ident)) { - return - } - switch binop.Op { - case token.AND: - report.Report(pass, node, - fmt.Sprintf("%s always equals 0; %s is defined as iota and has value 0, maybe %s is meant to be 1 << iota?", report.Render(pass, binop), report.Render(pass, binop.Y), report.Render(pass, binop.Y))) - case token.OR, token.XOR: - report.Report(pass, node, - fmt.Sprintf("%s always equals %s; %s is defined as iota and has value 0, maybe %s is meant to be 1 << iota?", report.Render(pass, binop), report.Render(pass, binop.X), report.Render(pass, binop.Y), report.Render(pass, binop.Y))) - } - } else if code.IsIntegerLiteral(pass, binop.Y, constant.MakeInt64(0)) { - switch binop.Op { - case token.AND: - report.Report(pass, node, fmt.Sprintf("%s always equals 0", report.Render(pass, binop))) - case token.OR, token.XOR: - report.Report(pass, node, fmt.Sprintf("%s always equals %s", report.Render(pass, binop), report.Render(pass, binop.X))) - } - } - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -func isIota(obj types.Object) bool { - if obj.Name() != "iota" { - return false - } - c, ok := obj.(*types.Const) - if !ok { - return false - } - return c.Pkg() == nil -} - -func CheckNonOctalFileMode(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - for _, arg := range call.Args { - lit, ok := arg.(*ast.BasicLit) - if !ok { - continue - } - if !typeutil.IsType(pass.TypesInfo.TypeOf(lit), "os.FileMode") && - !typeutil.IsType(pass.TypesInfo.TypeOf(lit), "io/fs.FileMode") { - continue - } - if len(lit.Value) == 3 && - lit.Value[0] != '0' && - lit.Value[0] >= '0' && lit.Value[0] <= '7' && - lit.Value[1] >= '0' && lit.Value[1] <= '7' && - lit.Value[2] >= '0' && lit.Value[2] <= '7' { - - v, err := strconv.ParseInt(lit.Value, 10, 64) - if err != nil { - continue - } - report.Report(pass, arg, fmt.Sprintf("file mode '%s' evaluates to %#o; did you mean '0%s'?", lit.Value, v, lit.Value), - report.Fixes(edit.Fix("fix octal literal", edit.ReplaceWithString(arg, "0"+lit.Value)))) - } - } - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckSideEffectFreeCalls(pass *analysis.Pass) (interface{}, error) { - pure := pass.ResultOf[purity.Analyzer].(purity.Result) - -fnLoop: - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - if code.IsInTest(pass, fn) { - params := fn.Signature.Params() - for i := 0; i < params.Len(); i++ { - param := params.At(i) - if typeutil.IsType(param.Type(), "*testing.B") { - // Ignore discarded pure functions in code related - // to benchmarks. Instead of matching BenchmarkFoo - // functions, we match any function accepting a - // *testing.B. Benchmarks sometimes call generic - // functions for doing the actual work, and - // checking for the parameter is a lot easier and - // faster than analyzing call trees. - continue fnLoop - } - } - } - - for _, b := range fn.Blocks { - for _, ins := range b.Instrs { - ins, ok := ins.(*ir.Call) - if !ok { - continue - } - refs := ins.Referrers() - if refs == nil || len(irutil.FilterDebug(*refs)) > 0 { - continue - } - - callee := ins.Common().StaticCallee() - if callee == nil { - continue - } - if callee.Object() == nil { - // TODO(dh): support anonymous functions - continue - } - if _, ok := pure[callee.Object().(*types.Func)]; ok { - if pass.Pkg.Path() == "fmt_test" && callee.Object().(*types.Func).FullName() == "fmt.Sprintf" { - // special case for benchmarks in the fmt package - continue - } - report.Report(pass, ins, fmt.Sprintf("%s doesn't have side effects and its return value is ignored", callee.Object().Name())) - } - } - } - } - return nil, nil -} - -func CheckDeprecated(pass *analysis.Pass) (interface{}, error) { - deprs := pass.ResultOf[deprecated.Analyzer].(deprecated.Result) - - // Selectors can appear outside of function literals, e.g. when - // declaring package level variables. - - isStdlibPath := func(path string) bool { - // Modules with no dot in the first path element are reserved for the standard library and tooling. - // This is the best we can currently do. - // Nobody tells us which import paths are part of the standard library. - // - // We check the entire path instead of just the first path element, because the standard library doesn't contain paths with any dots, anyway. - - return !strings.Contains(path, ".") - } - - handleDeprecation := func(depr *deprecated.IsDeprecated, node ast.Node, deprecatedObjName string, pkgPath string, tfn types.Object) { - // Note: gopls doesn't correctly run analyzers on - // dependencies, so we'll never be able to find deprecated - // objects in imported code. We've experimented with - // lifting the stdlib handling out of the general check, - // to at least work for deprecated objects in the stdlib, - // but we gave up on that, because we wouldn't have access - // to the deprecation message. - std, ok := knowledge.StdlibDeprecations[deprecatedObjName] - if !ok && isStdlibPath(pkgPath) { - // Deprecated object in the standard library, but we don't know the details of the deprecation. - // Don't flag it at all, to avoid flagging an object that was deprecated in 1.N when targeting 1.N-1. - // See https://staticcheck.io/issues/1108 for the background on this. - return - } - if ok { - // In the past, we made use of the AlternativeAvailableSince field. If a function was deprecated in Go - // 1.6 and an alternative had been available in Go 1.0, then we'd recommend using the alternative even - // if targeting Go 1.2. The idea was to suggest writing future-proof code by using already-existing - // alternatives. This had a major flaw, however: the user would need to use at least Go 1.6 for - // Staticcheck to know that the function had been deprecated. Thus, targeting Go 1.2 and using Go 1.2 - // would behave differently from targeting Go 1.2 and using Go 1.6. This is especially a problem if the - // user tries to ignore the warning. Depending on the Go version in use, the ignore directive may or may - // not match, causing a warning of its own. - // - // To avoid this issue, we no longer try to be smart. We now only compare the targeted version against - // the version that deprecated an object. - // - // Unfortunately, this issue also applies to AlternativeAvailableSince == DeprecatedNeverUse. Even though it - // is only applied to seriously flawed API, such as broken cryptography, users may wish to ignore those - // warnings. - // - // See also https://staticcheck.io/issues/1318. - if !code.IsGoVersion(pass, std.DeprecatedSince) { - return - } - } - - if tfn != nil { - if _, ok := deprs.Objects[tfn]; ok { - // functions that are deprecated may use deprecated - // symbols - return - } - } - - if ok { - switch std.AlternativeAvailableSince { - case knowledge.DeprecatedNeverUse: - report.Report(pass, node, - fmt.Sprintf("%s has been deprecated since Go 1.%d because it shouldn't be used: %s", - report.Render(pass, node), std.DeprecatedSince, depr.Msg)) - case std.DeprecatedSince, knowledge.DeprecatedUseNoLonger: - report.Report(pass, node, - fmt.Sprintf("%s has been deprecated since Go 1.%d: %s", - report.Render(pass, node), std.DeprecatedSince, depr.Msg)) - default: - report.Report(pass, node, - fmt.Sprintf("%s has been deprecated since Go 1.%d and an alternative has been available since Go 1.%d: %s", - report.Render(pass, node), std.DeprecatedSince, std.AlternativeAvailableSince, depr.Msg)) - } - } else { - report.Report(pass, node, fmt.Sprintf("%s is deprecated: %s", report.Render(pass, node), depr.Msg)) - } - } - - var tfn types.Object - stack := 0 - fn := func(node ast.Node, push bool) bool { - if !push { - stack-- - return false - } - stack++ - if stack == 1 { - tfn = nil - } - if fn, ok := node.(*ast.FuncDecl); ok { - tfn = pass.TypesInfo.ObjectOf(fn.Name) - } - - // FIXME(dh): this misses dot-imported objects - sel, ok := node.(*ast.SelectorExpr) - if !ok { - return true - } - - obj := pass.TypesInfo.ObjectOf(sel.Sel) - if obj_, ok := obj.(*types.Func); ok { - obj = obj_.Origin() - } - if obj.Pkg() == nil { - return true - } - - if obj.Pkg() == pass.Pkg { - // A package is allowed to use its own deprecated objects - return true - } - - // A package "foo" has two related packages "foo_test" and "foo.test", for external tests and the package main - // generated by 'go test' respectively. "foo_test" can import and use "foo", "foo.test" imports and uses "foo" - // and "foo_test". - - if strings.TrimSuffix(pass.Pkg.Path(), "_test") == obj.Pkg().Path() { - // foo_test (the external tests of foo) can use objects from foo. - return true - } - if strings.TrimSuffix(pass.Pkg.Path(), ".test") == obj.Pkg().Path() { - // foo.test (the main package of foo's tests) can use objects from foo. - return true - } - if strings.TrimSuffix(pass.Pkg.Path(), ".test") == strings.TrimSuffix(obj.Pkg().Path(), "_test") { - // foo.test (the main package of foo's tests) can use objects from foo's external tests. - return true - } - - if depr, ok := deprs.Objects[obj]; ok { - handleDeprecation(depr, sel, code.SelectorName(pass, sel), obj.Pkg().Path(), tfn) - } - return true - } - - fn2 := func(node ast.Node) { - spec := node.(*ast.ImportSpec) - var imp *types.Package - if spec.Name != nil { - imp = pass.TypesInfo.ObjectOf(spec.Name).(*types.PkgName).Imported() - } else { - imp = pass.TypesInfo.Implicits[spec].(*types.PkgName).Imported() - } - - p := spec.Path.Value - path := p[1 : len(p)-1] - if depr, ok := deprs.Packages[imp]; ok { - if path == "github.com/golang/protobuf/proto" { - gen, ok := code.Generator(pass, spec.Path.Pos()) - if ok && gen == generated.ProtocGenGo { - return - } - } - - if strings.TrimSuffix(pass.Pkg.Path(), "_test") == path { - // foo_test can import foo - return - } - if strings.TrimSuffix(pass.Pkg.Path(), ".test") == path { - // foo.test can import foo - return - } - if strings.TrimSuffix(pass.Pkg.Path(), ".test") == strings.TrimSuffix(path, "_test") { - // foo.test can import foo_test - return - } - - handleDeprecation(depr, spec.Path, path, path, nil) - } - } - pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes(nil, fn) - code.Preorder(pass, fn2, (*ast.ImportSpec)(nil)) - return nil, nil -} - -func callChecker(rules map[string]CallCheck) func(pass *analysis.Pass) (interface{}, error) { - return func(pass *analysis.Pass) (interface{}, error) { - return checkCalls(pass, rules) - } -} - -func checkCalls(pass *analysis.Pass, rules map[string]CallCheck) (interface{}, error) { - cb := func(caller *ir.Function, site ir.CallInstruction, callee *ir.Function) { - obj, ok := callee.Object().(*types.Func) - if !ok { - return - } - - r, ok := rules[typeutil.FuncName(obj)] - if !ok { - return - } - var args []*Argument - irargs := site.Common().Args - if callee.Signature.Recv() != nil { - irargs = irargs[1:] - } - for _, arg := range irargs { - if iarg, ok := arg.(*ir.MakeInterface); ok { - arg = iarg.X - } - args = append(args, &Argument{Value: Value{arg}}) - } - call := &Call{ - Pass: pass, - Instr: site, - Args: args, - Parent: site.Parent(), - } - r(call) - - var astcall *ast.CallExpr - switch source := site.Source().(type) { - case *ast.CallExpr: - astcall = source - case *ast.DeferStmt: - astcall = source.Call - case *ast.GoStmt: - astcall = source.Call - case nil: - // TODO(dh): I am not sure this can actually happen. If it - // can't, we should remove this case, and also stop - // checking for astcall == nil in the code that follows. - default: - panic(fmt.Sprintf("unhandled case %T", source)) - } - - for idx, arg := range call.Args { - for _, e := range arg.invalids { - if astcall != nil { - if idx < len(astcall.Args) { - report.Report(pass, astcall.Args[idx], e) - } else { - // this is an instance of fn1(fn2()) where fn2 - // returns multiple values. Report the error - // at the next-best position that we have, the - // first argument. An example of a check that - // triggers this is checkEncodingBinaryRules. - report.Report(pass, astcall.Args[0], e) - } - } else { - report.Report(pass, site, e) - } - } - } - for _, e := range call.invalids { - report.Report(pass, call.Instr, e) - } - } - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - eachCall(fn, cb) - } - return nil, nil -} - -func shortCallName(call *ir.CallCommon) string { - if call.IsInvoke() { - return "" - } - switch v := call.Value.(type) { - case *ir.Function: - fn, ok := v.Object().(*types.Func) - if !ok { - return "" - } - return fn.Name() - case *ir.Builtin: - return v.Name() - } - return "" -} - -func CheckWriterBufferModified(pass *analysis.Pass) (interface{}, error) { - // TODO(dh): this might be a good candidate for taint analysis. - // Taint the argument as MUST_NOT_MODIFY, then propagate that - // through functions like bytes.Split - - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - sig := fn.Signature - if fn.Name() != "Write" || sig.Recv() == nil || sig.Params().Len() != 1 || sig.Results().Len() != 2 { - continue - } - tArg, ok := sig.Params().At(0).Type().(*types.Slice) - if !ok { - continue - } - if basic, ok := tArg.Elem().(*types.Basic); !ok || basic.Kind() != types.Byte { - continue - } - if basic, ok := sig.Results().At(0).Type().(*types.Basic); !ok || basic.Kind() != types.Int { - continue - } - if named, ok := sig.Results().At(1).Type().(*types.Named); !ok || !typeutil.IsType(named, "error") { - continue - } - - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - switch ins := ins.(type) { - case *ir.Store: - addr, ok := ins.Addr.(*ir.IndexAddr) - if !ok { - continue - } - if addr.X != fn.Params[1] { - continue - } - report.Report(pass, ins, "io.Writer.Write must not modify the provided buffer, not even temporarily") - case *ir.Call: - if !irutil.IsCallTo(ins.Common(), "append") { - continue - } - if ins.Common().Args[0] != fn.Params[1] { - continue - } - report.Report(pass, ins, "io.Writer.Write must not modify the provided buffer, not even temporarily") - } - } - } - } - return nil, nil -} - -func loopedRegexp(name string) CallCheck { - return func(call *Call) { - if extractConst(call.Args[0].Value.Value) == nil { - return - } - if !isInLoop(call.Instr.Block()) { - return - } - call.Invalid(fmt.Sprintf("calling %s in a loop has poor performance, consider using regexp.Compile", name)) - } -} - -func CheckEmptyBranch(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - if fn.Source() == nil { - continue - } - if irutil.IsExample(fn) { - continue - } - cb := func(node ast.Node) bool { - ifstmt, ok := node.(*ast.IfStmt) - if !ok { - return true - } - if ifstmt.Else != nil { - b, ok := ifstmt.Else.(*ast.BlockStmt) - if !ok || len(b.List) != 0 { - return true - } - report.Report(pass, ifstmt.Else, "empty branch", report.FilterGenerated(), report.ShortRange()) - } - if len(ifstmt.Body.List) != 0 { - return true - } - report.Report(pass, ifstmt, "empty branch", report.FilterGenerated(), report.ShortRange()) - return true - } - if source := fn.Source(); source != nil { - ast.Inspect(source, cb) - } - } - return nil, nil -} - -func CheckMapBytesKey(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, b := range fn.Blocks { - insLoop: - for _, ins := range b.Instrs { - // find []byte -> string conversions - conv, ok := ins.(*ir.Convert) - if !ok || conv.Type() != types.Universe.Lookup("string").Type() { - continue - } - tset := typeutil.NewTypeSet(conv.X.Type()) - // If at least one of the types is []byte, then it's more efficient to inline the conversion - if !tset.Any(func(term *types.Term) bool { - s, ok := term.Type().Underlying().(*types.Slice) - return ok && s.Elem().Underlying() == types.Universe.Lookup("byte").Type() - }) { - continue - } - refs := conv.Referrers() - // need at least two (DebugRef) references: the - // conversion and the *ast.Ident - if refs == nil || len(*refs) < 2 { - continue - } - ident := false - // skip first reference, that's the conversion itself - for _, ref := range (*refs)[1:] { - switch ref := ref.(type) { - case *ir.DebugRef: - if _, ok := ref.Expr.(*ast.Ident); !ok { - // the string seems to be used somewhere - // unexpected; the default branch should - // catch this already, but be safe - continue insLoop - } else { - ident = true - } - case *ir.MapLookup: - default: - // the string is used somewhere else than a - // map lookup - continue insLoop - } - } - - // the result of the conversion wasn't assigned to an - // identifier - if !ident { - continue - } - report.Report(pass, conv, "m[string(key)] would be more efficient than k := string(key); m[k]") - } - } - } - return nil, nil -} - -func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { - return sharedcheck.CheckRangeStringRunes(pass) -} - -func CheckSelfAssignment(pass *analysis.Pass) (interface{}, error) { - pure := pass.ResultOf[purity.Analyzer].(purity.Result) - - fn := func(node ast.Node) { - assign := node.(*ast.AssignStmt) - if assign.Tok != token.ASSIGN || len(assign.Lhs) != len(assign.Rhs) { - return - } - for i, lhs := range assign.Lhs { - rhs := assign.Rhs[i] - if reflect.TypeOf(lhs) != reflect.TypeOf(rhs) { - continue - } - if code.MayHaveSideEffects(pass, lhs, pure) || code.MayHaveSideEffects(pass, rhs, pure) { - continue - } - - rlh := report.Render(pass, lhs) - rrh := report.Render(pass, rhs) - if rlh == rrh { - report.Report(pass, assign, fmt.Sprintf("self-assignment of %s to %s", rrh, rlh), report.FilterGenerated()) - } - } - } - code.Preorder(pass, fn, (*ast.AssignStmt)(nil)) - return nil, nil -} - -func buildTagsIdentical(s1, s2 []string) bool { - if len(s1) != len(s2) { - return false - } - s1s := make([]string, len(s1)) - copy(s1s, s1) - sort.Strings(s1s) - s2s := make([]string, len(s2)) - copy(s2s, s2) - sort.Strings(s2s) - for i, s := range s1s { - if s != s2s[i] { - return false - } - } - return true -} - -func CheckDuplicateBuildConstraints(pass *analysis.Pass) (interface{}, error) { - for _, f := range pass.Files { - constraints := buildTags(f) - for i, constraint1 := range constraints { - for j, constraint2 := range constraints { - if i >= j { - continue - } - if buildTagsIdentical(constraint1, constraint2) { - msg := fmt.Sprintf("identical build constraints %q and %q", - strings.Join(constraint1, " "), - strings.Join(constraint2, " ")) - report.Report(pass, f, msg, report.FilterGenerated(), report.ShortRange()) - } - } - } - } - return nil, nil -} - -func CheckSillyRegexp(pass *analysis.Pass) (interface{}, error) { - // We could use the rule checking engine for this, but the - // arguments aren't really invalid. - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, b := range fn.Blocks { - for _, ins := range b.Instrs { - call, ok := ins.(*ir.Call) - if !ok { - continue - } - if !irutil.IsCallToAny(call.Common(), "regexp.MustCompile", "regexp.Compile", "regexp.Match", "regexp.MatchReader", "regexp.MatchString") { - continue - } - c, ok := call.Common().Args[0].(*ir.Const) - if !ok { - continue - } - s := constant.StringVal(c.Value) - re, err := syntax.Parse(s, 0) - if err != nil { - continue - } - if re.Op != syntax.OpLiteral && re.Op != syntax.OpEmptyMatch { - continue - } - report.Report(pass, call, "regular expression does not contain any meta characters") - } - } - } - return nil, nil -} - -func CheckMissingEnumTypesInDeclaration(pass *analysis.Pass) (interface{}, error) { - convertibleTo := func(V, T types.Type) bool { - if types.ConvertibleTo(V, T) { - return true - } - // Go <1.16 returns false for untyped string to string conversion - if V, ok := V.(*types.Basic); ok && V.Kind() == types.UntypedString { - if T, ok := T.Underlying().(*types.Basic); ok && T.Kind() == types.String { - return true - } - } - return false - } - fn := func(node ast.Node) { - decl := node.(*ast.GenDecl) - if !decl.Lparen.IsValid() { - return - } - if decl.Tok != token.CONST { - return - } - - groups := astutil.GroupSpecs(pass.Fset, decl.Specs) - groupLoop: - for _, group := range groups { - if len(group) < 2 { - continue - } - if group[0].(*ast.ValueSpec).Type == nil { - // first constant doesn't have a type - continue groupLoop - } - - firstType := pass.TypesInfo.TypeOf(group[0].(*ast.ValueSpec).Values[0]) - for i, spec := range group { - spec := spec.(*ast.ValueSpec) - if i > 0 && spec.Type != nil { - continue groupLoop - } - if len(spec.Names) != 1 || len(spec.Values) != 1 { - continue groupLoop - } - - if !convertibleTo(pass.TypesInfo.TypeOf(spec.Values[0]), firstType) { - continue groupLoop - } - - switch v := spec.Values[0].(type) { - case *ast.BasicLit: - case *ast.UnaryExpr: - if _, ok := v.X.(*ast.BasicLit); !ok { - continue groupLoop - } - default: - // if it's not a literal it might be typed, such as - // time.Microsecond = 1000 * Nanosecond - continue groupLoop - } - } - var edits []analysis.TextEdit - typ := group[0].(*ast.ValueSpec).Type - for _, spec := range group[1:] { - nspec := *spec.(*ast.ValueSpec) - nspec.Type = typ - // The position of `spec` node excludes comments (if any). - // However, on generating the source back from the node, the comments are included. Setting `Comment` to nil ensures deduplication of comments. - nspec.Comment = nil - edits = append(edits, edit.ReplaceWithNode(pass.Fset, spec, &nspec)) - } - report.Report(pass, group[0], "only the first constant in this group has an explicit type", report.Fixes(edit.Fix("add type to all constants in group", edits...))) - } - } - code.Preorder(pass, fn, (*ast.GenDecl)(nil)) - return nil, nil -} - -func CheckTimerResetReturnValue(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, block := range fn.Blocks { - for _, ins := range block.Instrs { - call, ok := ins.(*ir.Call) - if !ok { - continue - } - if !irutil.IsCallTo(call.Common(), "(*time.Timer).Reset") { - continue - } - refs := call.Referrers() - if refs == nil { - continue - } - for _, ref := range irutil.FilterDebug(*refs) { - ifstmt, ok := ref.(*ir.If) - if !ok { - continue - } - - found := false - for _, succ := range ifstmt.Block().Succs { - if len(succ.Preds) != 1 { - // Merge point, not a branch in the - // syntactical sense. - - // FIXME(dh): this is broken for if - // statements a la "if x || y" - continue - } - irutil.Walk(succ, func(b *ir.BasicBlock) bool { - if !succ.Dominates(b) { - // We've reached the end of the branch - return false - } - for _, ins := range b.Instrs { - // TODO(dh): we should check that - // we're receiving from the channel of - // a time.Timer to further reduce - // false positives. Not a key - // priority, considering the rarity of - // Reset and the tiny likeliness of a - // false positive - if ins, ok := ins.(*ir.Recv); ok && typeutil.IsType(ins.Chan.Type(), "<-chan time.Time") { - found = true - return false - } - } - return true - }) - } - - if found { - report.Report(pass, call, "it is not possible to use Reset's return value correctly, as there is a race condition between draining the channel and the new timer expiring") - } - } - } - } - } - return nil, nil -} - -var ( - checkToLowerToUpperComparisonQ = pattern.MustParse(` - (BinaryExpr - (CallExpr fun@(Symbol (Or "strings.ToLower" "strings.ToUpper")) [a]) - tok@(Or "==" "!=") - (CallExpr fun [b]))`) - checkToLowerToUpperComparisonR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "strings") (Ident "EqualFold")) [a b])`) -) - -func CheckToLowerToUpperComparison(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkToLowerToUpperComparisonQ, node) - if !ok { - return - } - rn := pattern.NodeToAST(checkToLowerToUpperComparisonR.Root, m.State).(ast.Expr) - if m.State["tok"].(token.Token) == token.NEQ { - rn = &ast.UnaryExpr{ - Op: token.NOT, - X: rn, - } - } - - report.Report(pass, node, "should use strings.EqualFold instead", report.Fixes(edit.Fix("replace with strings.EqualFold", edit.ReplaceWithNode(pass.Fset, node, rn)))) - } - - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -func CheckUnreachableTypeCases(pass *analysis.Pass) (interface{}, error) { - // Check if T subsumes V in a type switch. T subsumes V if T is an interface and T's method set is a subset of V's method set. - subsumes := func(T, V types.Type) bool { - if typeparams.IsTypeParam(T) { - return false - } - tIface, ok := T.Underlying().(*types.Interface) - if !ok { - return false - } - - return types.Implements(V, tIface) - } - - subsumesAny := func(Ts, Vs []types.Type) (types.Type, types.Type, bool) { - for _, T := range Ts { - for _, V := range Vs { - if subsumes(T, V) { - return T, V, true - } - } - } - - return nil, nil, false - } - - fn := func(node ast.Node) { - tsStmt := node.(*ast.TypeSwitchStmt) - - type ccAndTypes struct { - cc *ast.CaseClause - types []types.Type - } - - // All asserted types in the order of case clauses. - ccs := make([]ccAndTypes, 0, len(tsStmt.Body.List)) - for _, stmt := range tsStmt.Body.List { - cc, _ := stmt.(*ast.CaseClause) - - // Exclude the 'default' case. - if len(cc.List) == 0 { - continue - } - - Ts := make([]types.Type, 0, len(cc.List)) - for _, expr := range cc.List { - // Exclude the 'nil' value from any 'case' statement (it is always reachable). - if typ := pass.TypesInfo.TypeOf(expr); typ != types.Typ[types.UntypedNil] { - Ts = append(Ts, typ) - } - } - - ccs = append(ccs, ccAndTypes{cc: cc, types: Ts}) - } - - if len(ccs) <= 1 { - // Zero or one case clauses, nothing to check. - return - } - - // Check if case clauses following cc have types that are subsumed by cc. - for i, cc := range ccs[:len(ccs)-1] { - for _, next := range ccs[i+1:] { - if T, V, yes := subsumesAny(cc.types, next.types); yes { - report.Report(pass, next.cc, fmt.Sprintf("unreachable case clause: %s will always match before %s", T.String(), V.String()), - report.ShortRange()) - } - } - } - } - - code.Preorder(pass, fn, (*ast.TypeSwitchStmt)(nil)) - return nil, nil -} - -var checkSingleArgAppendQ = pattern.MustParse(`(CallExpr (Builtin "append") [_])`) - -func CheckSingleArgAppend(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - _, ok := code.Match(pass, checkSingleArgAppendQ, node) - if !ok { - return - } - report.Report(pass, node, "x = append(y) is equivalent to x = y", report.FilterGenerated()) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckStructTags(pass *analysis.Pass) (interface{}, error) { - importsGoFlags := false - - // we use the AST instead of (*types.Package).Imports to work - // around vendored packages in GOPATH mode. A vendored package's - // path will include the vendoring subtree as a prefix. - for _, f := range pass.Files { - for _, imp := range f.Imports { - v := imp.Path.Value - if v[1:len(v)-1] == "github.com/jessevdk/go-flags" { - importsGoFlags = true - break - } - } - } - - fn := func(node ast.Node) { - structNode := node.(*ast.StructType) - T := pass.TypesInfo.Types[structNode].Type.(*types.Struct) - rt := fakereflect.TypeAndCanAddr{ - Type: T, - } - for i, field := range structNode.Fields.List { - if field.Tag == nil { - continue - } - tags, err := parseStructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]) - if err != nil { - report.Report(pass, field.Tag, fmt.Sprintf("unparseable struct tag: %s", err)) - continue - } - for k, v := range tags { - if len(v) > 1 { - isGoFlagsTag := importsGoFlags && - (k == "choice" || k == "optional-value" || k == "default") - if !isGoFlagsTag { - report.Report(pass, field.Tag, fmt.Sprintf("duplicate struct tag %q", k)) - } - } - - switch k { - case "json": - checkJSONTag(pass, field, v[0]) - case "xml": - if _, err := fakexml.StructFieldInfo(rt.Field(i)); err != nil { - report.Report(pass, field.Tag, fmt.Sprintf("invalid XML tag: %s", err)) - } - checkXMLTag(pass, field, v[0]) - } - } - } - } - code.Preorder(pass, fn, (*ast.StructType)(nil)) - return nil, nil -} - -func checkJSONTag(pass *analysis.Pass, field *ast.Field, tag string) { - if pass.Pkg.Path() == "encoding/json" || pass.Pkg.Path() == "encoding/json_test" { - // don't flag malformed JSON tags in the encoding/json - // package; it knows what it is doing, and it is testing - // itself. - return - } - //lint:ignore SA9003 TODO(dh): should we flag empty tags? - if len(tag) == 0 { - } - if i := strings.Index(tag, ",format:"); i >= 0 { - tag = tag[:i] - } - fields := strings.Split(tag, ",") - for _, r := range fields[0] { - if !unicode.IsLetter(r) && !unicode.IsDigit(r) && !strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", r) { - report.Report(pass, field.Tag, fmt.Sprintf("invalid JSON field name %q", fields[0])) - } - } - options := make(map[string]int) - for _, s := range fields[1:] { - switch s { - case "": - // allow stuff like "-," - case "string": - // only for string, floating point, integer and bool - options[s]++ - tset := typeutil.NewTypeSet(pass.TypesInfo.TypeOf(field.Type)) - if len(tset.Terms) == 0 { - // TODO(dh): improve message, call out the use of type parameters - report.Report(pass, field.Tag, "the JSON string option only applies to fields of type string, floating point, integer or bool, or pointers to those") - continue - } - for _, term := range tset.Terms { - T := typeutil.Dereference(term.Type().Underlying()) - for _, term2 := range typeutil.NewTypeSet(T).Terms { - basic, ok := term2.Type().Underlying().(*types.Basic) - if !ok || (basic.Info()&(types.IsBoolean|types.IsInteger|types.IsFloat|types.IsString)) == 0 { - // TODO(dh): improve message, show how we arrived at the type - report.Report(pass, field.Tag, "the JSON string option only applies to fields of type string, floating point, integer or bool, or pointers to those") - } - } - } - case "omitzero", "omitempty", "nocase", "inline", "unknown": - options[s]++ - default: - report.Report(pass, field.Tag, fmt.Sprintf("unknown JSON option %q", s)) - } - } - var duplicates []string - for option, n := range options { - if n > 1 { - duplicates = append(duplicates, option) - } - } - if len(duplicates) > 0 { - sort.Strings(duplicates) - for _, option := range duplicates { - report.Report(pass, field.Tag, fmt.Sprintf("duplicate JSON option %q", option)) - } - } -} - -func checkXMLTag(pass *analysis.Pass, field *ast.Field, tag string) { - //lint:ignore SA9003 TODO(dh): should we flag empty tags? - if len(tag) == 0 { - } - fields := strings.Split(tag, ",") - counts := map[string]int{} - for _, s := range fields[1:] { - switch s { - case "attr", "chardata", "cdata", "innerxml", "comment": - counts[s]++ - case "omitempty", "any": - counts[s]++ - case "": - default: - report.Report(pass, field.Tag, fmt.Sprintf("invalid XML tag: unknown option %q", s)) - } - } - for k, v := range counts { - if v > 1 { - report.Report(pass, field.Tag, fmt.Sprintf("invalid XML tag: duplicate option %q", k)) - } - } -} - -func CheckImpossibleTypeAssertion(pass *analysis.Pass) (interface{}, error) { - type entry struct { - l, r *types.Func - } - - msc := &pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg.Prog.MethodSets - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - assert, ok := instr.(*ir.TypeAssert) - if !ok { - continue - } - var wrong []entry - left := assert.X.Type() - right := assert.AssertedType - righti, ok := right.Underlying().(*types.Interface) - - if !ok { - // We only care about interface->interface - // assertions. The Go compiler already catches - // impossible interface->concrete assertions. - continue - } - - ms := msc.MethodSet(left) - for i := 0; i < righti.NumMethods(); i++ { - mr := righti.Method(i).Origin() - sel := ms.Lookup(mr.Pkg(), mr.Name()) - if sel == nil { - continue - } - ml := sel.Obj().(*types.Func).Origin() - if types.AssignableTo(ml.Type(), mr.Type()) { - continue - } - - wrong = append(wrong, entry{ml, mr}) - } - - if len(wrong) != 0 { - s := fmt.Sprintf("impossible type assertion; %s and %s contradict each other:", - types.TypeString(left, types.RelativeTo(pass.Pkg)), - types.TypeString(right, types.RelativeTo(pass.Pkg))) - for _, e := range wrong { - s += fmt.Sprintf("\n\twrong type for %s method", e.l.Name()) - s += fmt.Sprintf("\n\t\thave %s", e.l.Type()) - s += fmt.Sprintf("\n\t\twant %s", e.r.Type()) - } - report.Report(pass, assert, s) - } - } - } - } - return nil, nil -} - -func checkWithValueKey(call *Call) { - arg := call.Args[1] - T := arg.Value.Value.Type() - if T, ok := T.(*types.Basic); ok { - arg.Invalid( - fmt.Sprintf("should not use built-in type %s as key for value; define your own type to avoid collisions", T)) - } - if !types.Comparable(T) { - arg.Invalid(fmt.Sprintf("keys used with context.WithValue must be comparable, but type %s is not comparable", T)) - } -} - -func CheckMaybeNil(pass *analysis.Pass) (interface{}, error) { - // This is an extremely trivial check that doesn't try to reason - // about control flow. That is, phis and sigmas do not propagate - // any information. As such, we can flag this: - // - // _ = *x - // if x == nil { return } - // - // but we cannot flag this: - // - // if x == nil { println(x) } - // _ = *x - // - // but we can flag this, because the if's body doesn't use x: - // - // if x == nil { println("this is bad") } - // _ = *x - // - // nor many other variations of conditional uses of or assignments to x. - // - // However, even this trivial implementation finds plenty of - // real-world bugs, such as dereference before nil pointer check, - // or using t.Error instead of t.Fatal when encountering nil - // pointers. - // - // On the flip side, our naive implementation avoids false positives in branches, such as - // - // if x != nil { _ = *x } - // - // due to the same lack of propagating information through sigma - // nodes. x inside the branch will be independent of the x in the - // nil pointer check. - // - // - // We could implement a more powerful check, but then we'd be - // getting false positives instead of false negatives because - // we're incapable of deducing relationships between variables. - // For example, a function might return a pointer and an error, - // and the error being nil guarantees that the pointer is not nil. - // Depending on the surrounding code, the pointer may still end up - // being checked against nil in one place, and guarded by a check - // on the error in another, which would lead to us marking some - // loads as unsafe. - // - // Unfortunately, simply hard-coding the relationship between - // return values wouldn't eliminate all false positives, either. - // Many other more subtle relationships exist. An abridged example - // from real code: - // - // if a == nil && b == nil { return } - // c := fn(a) - // if c != "" { _ = *a } - // - // where `fn` is guaranteed to return a non-empty string if a - // isn't nil. - // - // We choose to err on the side of false negatives. - - isNilConst := func(v ir.Value) bool { - if typeutil.IsPointerLike(v.Type()) { - if k, ok := v.(*ir.Const); ok { - return k.IsNil() - } - } - return false - } - - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - maybeNil := map[ir.Value]ir.Instruction{} - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - // Originally we looked at all ir.BinOp, but that would lead to calls like 'assert(x != nil)' causing false positives. - // Restrict ourselves to actual if statements, as these are more likely to affect control flow in a way we can observe. - if instr, ok := instr.(*ir.If); ok { - if cond, ok := instr.Cond.(*ir.BinOp); ok { - var ptr ir.Value - if isNilConst(cond.X) { - ptr = cond.Y - } else if isNilConst(cond.Y) { - ptr = cond.X - } - maybeNil[ptr] = cond - } - } - } - } - - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - var ptr ir.Value - switch instr := instr.(type) { - case *ir.Load: - ptr = instr.X - case *ir.Store: - ptr = instr.Addr - case *ir.IndexAddr: - ptr = instr.X - if typeutil.All(ptr.Type(), func(term *types.Term) bool { - if _, ok := term.Type().Underlying().(*types.Slice); ok { - return true - } - return false - }) { - // indexing a nil slice does not cause a nil pointer panic - // - // Note: This also works around the bad lowering of range loops over slices - // (https://github.com/dominikh/go-tools/issues/1053) - continue - } - case *ir.FieldAddr: - ptr = instr.X - } - if ptr != nil { - switch ptr.(type) { - case *ir.Alloc, *ir.FieldAddr, *ir.IndexAddr: - // these cannot be nil - continue - } - if r, ok := maybeNil[ptr]; ok { - report.Report(pass, instr, "possible nil pointer dereference", - report.Related(r, "this check suggests that the pointer can be nil")) - } - } - } - } - } - - return nil, nil -} - -var checkAddressIsNilQ = pattern.MustParse( - `(BinaryExpr - (UnaryExpr "&" _) - (Or "==" "!=") - (Builtin "nil"))`) - -func CheckAddressIsNil(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - _, ok := code.Match(pass, checkAddressIsNilQ, node) - if !ok { - return - } - report.Report(pass, node, "the address of a variable cannot be nil") - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -var ( - checkFixedLengthTypeShiftQ = pattern.MustParse(` - (Or - (AssignStmt _ (Or ">>=" "<<=") _) - (BinaryExpr _ (Or ">>" "<<") _)) - `) -) - -func CheckStaticBitShift(pass *analysis.Pass) (interface{}, error) { - isDubiousShift := func(x, y ast.Expr) (int64, int64, bool) { - typ, ok := pass.TypesInfo.TypeOf(x).Underlying().(*types.Basic) - if !ok { - return 0, 0, false - } - switch typ.Kind() { - case types.Int8, types.Int16, types.Int32, types.Int64, - types.Uint8, types.Uint16, types.Uint32, types.Uint64: - // We're only interested in fixed–size types. - default: - return 0, 0, false - } - - const bitsInByte = 8 - typeBits := pass.TypesSizes.Sizeof(typ) * bitsInByte - - shiftLength, ok := code.ExprToInt(pass, y) - if !ok { - return 0, 0, false - } - - return typeBits, shiftLength, shiftLength >= typeBits - } - - fn := func(node ast.Node) { - if _, ok := code.Match(pass, checkFixedLengthTypeShiftQ, node); !ok { - return - } - - switch e := node.(type) { - case *ast.AssignStmt: - if size, shift, yes := isDubiousShift(e.Lhs[0], e.Rhs[0]); yes { - report.Report(pass, e, fmt.Sprintf("shifting %d-bit value by %d bits will always clear it", size, shift)) - } - case *ast.BinaryExpr: - if size, shift, yes := isDubiousShift(e.X, e.Y); yes { - report.Report(pass, e, fmt.Sprintf("shifting %d-bit value by %d bits will always clear it", size, shift)) - } - } - } - code.Preorder(pass, fn, (*ast.AssignStmt)(nil), (*ast.BinaryExpr)(nil)) - - return nil, nil -} - -func findSliceLenChecks(pass *analysis.Pass) { - // mark all function parameters that have to be of even length - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, b := range fn.Blocks { - // all paths go through this block - if !b.Dominates(fn.Exit) { - continue - } - - // if foo % 2 != 0 - ifi, ok := b.Control().(*ir.If) - if !ok { - continue - } - cmp, ok := ifi.Cond.(*ir.BinOp) - if !ok { - continue - } - var needle uint64 - switch cmp.Op { - case token.NEQ: - // look for != 0 - needle = 0 - case token.EQL: - // look for == 1 - needle = 1 - default: - continue - } - - rem, ok1 := cmp.X.(*ir.BinOp) - k, ok2 := cmp.Y.(*ir.Const) - if ok1 != ok2 { - continue - } - if !ok1 { - rem, ok1 = cmp.Y.(*ir.BinOp) - k, ok2 = cmp.X.(*ir.Const) - } - if !ok1 || !ok2 || rem.Op != token.REM || k.Value.Kind() != constant.Int || k.Uint64() != needle { - continue - } - k, ok = rem.Y.(*ir.Const) - if !ok || k.Value.Kind() != constant.Int || k.Uint64() != 2 { - continue - } - - // if len(foo) % 2 != 0 - call, ok := rem.X.(*ir.Call) - if !ok || !irutil.IsCallTo(call.Common(), "len") { - continue - } - - // we're checking the length of a parameter that is a slice - // TODO(dh): support parameters that have flown through sigmas and phis - param, ok := call.Call.Args[0].(*ir.Parameter) - if !ok { - continue - } - if !typeutil.All(param.Type(), typeutil.IsSlice) { - continue - } - - // if len(foo) % 2 != 0 then panic - if _, ok := b.Succs[0].Control().(*ir.Panic); !ok { - continue - } - - pass.ExportObjectFact(param.Object(), new(evenElements)) - } - } -} - -func findIndirectSliceLenChecks(pass *analysis.Pass) { - seen := map[*ir.Function]struct{}{} - - var doFunction func(fn *ir.Function) - doFunction = func(fn *ir.Function) { - if _, ok := seen[fn]; ok { - return - } - seen[fn] = struct{}{} - - for _, b := range fn.Blocks { - // all paths go through this block - if !b.Dominates(fn.Exit) { - continue - } - - for _, instr := range b.Instrs { - call, ok := instr.(*ir.Call) - if !ok { - continue - } - callee := call.Call.StaticCallee() - if callee == nil { - continue - } - - if callee.Pkg == fn.Pkg || callee.Pkg == nil { - doFunction(callee) - } - - for argi, arg := range call.Call.Args { - if callee.Signature.Recv() != nil { - if argi == 0 { - continue - } - argi-- - } - - // TODO(dh): support parameters that have flown through length-preserving instructions - param, ok := arg.(*ir.Parameter) - if !ok { - continue - } - if !typeutil.All(param.Type(), typeutil.IsSlice) { - continue - } - - // We can't use callee.Params to look up the - // parameter, because Params is not populated for - // external functions. In our modular analysis. - // any function in any package that isn't the - // current package is considered "external", as it - // has been loaded from export data only. - sigParams := callee.Signature.Params() - - if !pass.ImportObjectFact(sigParams.At(argi), new(evenElements)) { - continue - } - pass.ExportObjectFact(param.Object(), new(evenElements)) - } - } - } - } - - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - doFunction(fn) - } -} - -func findSliceLength(v ir.Value) int { - // TODO(dh): VRP would help here - - v = irutil.Flatten(v) - val := func(v ir.Value) int { - if v, ok := v.(*ir.Const); ok { - return int(v.Int64()) - } - return -1 - } - switch v := v.(type) { - case *ir.Slice: - low := 0 - high := -1 - if v.Low != nil { - low = val(v.Low) - } - if v.High != nil { - high = val(v.High) - } else { - switch vv := v.X.(type) { - case *ir.Alloc: - high = int(typeutil.Dereference(vv.Type()).Underlying().(*types.Array).Len()) - case *ir.Slice: - high = findSliceLength(vv) - } - } - if low == -1 || high == -1 { - return -1 - } - return high - low - default: - return -1 - } -} - -type evenElements struct{} - -func (evenElements) AFact() {} - -func (evenElements) String() string { return "needs even elements" } - -func flagSliceLens(pass *analysis.Pass) { - var tag evenElements - - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - call, ok := instr.(ir.CallInstruction) - if !ok { - continue - } - callee := call.Common().StaticCallee() - if callee == nil { - continue - } - for argi, arg := range call.Common().Args { - if callee.Signature.Recv() != nil { - if argi == 0 { - continue - } - argi-- - } - - _, ok := arg.Type().Underlying().(*types.Slice) - if !ok { - continue - } - param := callee.Signature.Params().At(argi) - if !pass.ImportObjectFact(param, &tag) { - continue - } - - // TODO handle stubs - - // we know the argument has to have even length. - // now let's try to find its length - if n := findSliceLength(arg); n > -1 && n%2 != 0 { - src := call.Source().(*ast.CallExpr).Args[argi] - sig := call.Common().Signature() - var label string - if argi == sig.Params().Len()-1 && sig.Variadic() { - label = "variadic argument" - } else { - label = "argument" - } - // Note that param.Name() is guaranteed to not - // be empty, otherwise the function couldn't - // have enforced its length. - report.Report(pass, src, fmt.Sprintf("%s %q is expected to have even number of elements, but has %d elements", label, param.Name(), n)) - } - } - } - } - } -} - -func CheckEvenSliceLength(pass *analysis.Pass) (interface{}, error) { - findSliceLenChecks(pass) - findIndirectSliceLenChecks(pass) - flagSliceLens(pass) - - return nil, nil -} - -func CheckTypedNilInterface(pass *analysis.Pass) (interface{}, error) { - // The comparison 'fn() == nil' can never be true if fn() returns - // an interface value and only returns typed nils. This is usually - // a mistake in the function itself, but all we can say for - // certain is that the comparison is pointless. - // - // Flag results if no untyped nils are being returned, but either - // known typed nils, or typed unknown nilness are being returned. - - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR) - typedness := pass.ResultOf[typedness.Analysis].(*typedness.Result) - nilness := pass.ResultOf[nilness.Analysis].(*nilness.Result) - for _, fn := range irpkg.SrcFuncs { - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - binop, ok := instr.(*ir.BinOp) - if !ok || !(binop.Op == token.EQL || binop.Op == token.NEQ) { - continue - } - if _, ok := binop.X.Type().Underlying().(*types.Interface); !ok || typeparams.IsTypeParam(binop.X.Type()) { - // TODO support swapped X and Y - continue - } - - k, ok := binop.Y.(*ir.Const) - if !ok || !k.IsNil() { - // if binop.X is an interface, then binop.Y can - // only be a Const if its untyped. A typed nil - // constant would first be passed to - // MakeInterface. - continue - } - - var idx int - var obj *types.Func - switch x := irutil.Flatten(binop.X).(type) { - case *ir.Call: - callee := x.Call.StaticCallee() - if callee == nil { - continue - } - obj, _ = callee.Object().(*types.Func) - idx = 0 - case *ir.Extract: - call, ok := irutil.Flatten(x.Tuple).(*ir.Call) - if !ok { - continue - } - callee := call.Call.StaticCallee() - if callee == nil { - continue - } - obj, _ = callee.Object().(*types.Func) - idx = x.Index - case *ir.MakeInterface: - var qualifier string - switch binop.Op { - case token.EQL: - qualifier = "never" - case token.NEQ: - qualifier = "always" - default: - panic("unreachable") - } - - terms, err := typeparams.NormalTerms(x.X.Type()) - if len(terms) == 0 || err != nil { - // Type is a type parameter with no type terms (or we couldn't determine the terms). Such a type - // _can_ be nil when put in an interface value. - continue - } - - if report.HasRange(x.X) { - report.Report(pass, binop, fmt.Sprintf("this comparison is %s true", qualifier), - report.Related(x.X, "the lhs of the comparison gets its value from here and has a concrete type")) - } else { - // we can't generate related information for this, so make the diagnostic itself slightly more useful - report.Report(pass, binop, fmt.Sprintf("this comparison is %s true; the lhs of the comparison has been assigned a concretely typed value", qualifier)) - } - continue - } - if obj == nil { - continue - } - - isNil, onlyGlobal := nilness.MayReturnNil(obj, idx) - if typedness.MustReturnTyped(obj, idx) && isNil && !onlyGlobal && !code.IsInTest(pass, binop) { - // Don't flag these comparisons in tests. Tests - // may be explicitly enforcing the invariant that - // a value isn't nil. - - var qualifier string - switch binop.Op { - case token.EQL: - qualifier = "never" - case token.NEQ: - qualifier = "always" - default: - panic("unreachable") - } - report.Report(pass, binop, fmt.Sprintf("this comparison is %s true", qualifier), - // TODO support swapped X and Y - report.Related(binop.X, fmt.Sprintf("the lhs of the comparison is the %s return value of this function call", report.Ordinal(idx+1))), - report.Related(obj, fmt.Sprintf("%s never returns a nil interface value", typeutil.FuncName(obj)))) - } - } - } - } - - return nil, nil -} - -var builtinLessThanZeroQ = pattern.MustParse(` - (Or - (BinaryExpr - (IntegerLiteral "0") - ">" - (CallExpr builtin@(Builtin (Or "len" "cap")) _)) - (BinaryExpr - (CallExpr builtin@(Builtin (Or "len" "cap")) _) - "<" - (IntegerLiteral "0"))) -`) - -func CheckBuiltinZeroComparison(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - matcher, ok := code.Match(pass, builtinLessThanZeroQ, node) - if !ok { - return - } - - builtin := matcher.State["builtin"].(*ast.Ident) - report.Report(pass, node, fmt.Sprintf("builtin function %s does not return negative values", builtin.Name)) - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - - return nil, nil -} - -var integerDivisionQ = pattern.MustParse(`(BinaryExpr (IntegerLiteral _) "/" (IntegerLiteral _))`) - -func CheckIntegerDivisionEqualsZero(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - _, ok := code.Match(pass, integerDivisionQ, node) - if !ok { - return - } - - val := constant.ToInt(pass.TypesInfo.Types[node.(ast.Expr)].Value) - if v, ok := constant.Uint64Val(val); ok && v == 0 { - report.Report(pass, node, fmt.Sprintf("the integer division '%s' results in zero", report.Render(pass, node))) - } - - // TODO: we could offer a suggested fix here, but I am not - // sure what it should be. There are many options to choose - // from. - - // Note: we experimented with flagging divisions that truncate - // (e.g. 4 / 3), but it ran into false positives in Go's - // 'time' package, which does this, deliberately: - // - // unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay - // - // The check also found a real bug in other code, but I don't - // think we can outright ban this kind of division. - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - - return nil, nil -} - -func CheckIneffectiveFieldAssignments(pass *analysis.Pass) (interface{}, error) { - // The analysis only considers the receiver and its first level - // fields. It doesn't look at other parameters, nor at nested - // fields. - // - // The analysis does not detect all kinds of dead stores, only - // those of fields that are never read after the write. That is, - // we do not flag 'a.x = 1; a.x = 2; _ = a.x'. We might explore - // this again if we add support for SROA to go/ir and implement - // https://github.com/dominikh/go-tools/issues/191. - - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR) -fnLoop: - for _, fn := range irpkg.SrcFuncs { - if recv := fn.Signature.Recv(); recv == nil { - continue - } else if _, ok := recv.Type().Underlying().(*types.Struct); !ok { - continue - } - - recv := fn.Params[0] - refs := irutil.FilterDebug(*recv.Referrers()) - if len(refs) != 1 { - continue - } - store, ok := refs[0].(*ir.Store) - if !ok { - continue - } - alloc, ok := store.Addr.(*ir.Alloc) - if !ok || alloc.Heap { - continue - } - - reads := map[int][]ir.Instruction{} - writes := map[int][]ir.Instruction{} - for _, ref := range *alloc.Referrers() { - switch ref := ref.(type) { - case *ir.FieldAddr: - for _, refref := range *ref.Referrers() { - switch refref.(type) { - case *ir.Store: - writes[ref.Field] = append(writes[ref.Field], refref) - case *ir.Load: - reads[ref.Field] = append(reads[ref.Field], refref) - case *ir.DebugRef: - continue - default: - // this should be safe… if the field address - // escapes, then alloc.Heap will be true. - // there should be no instructions left that, - // given this FieldAddr, without escaping, can - // effect a load or store. - continue - } - } - case *ir.Store: - // we could treat this as a store to every field, but - // we don't want to decide the semantics of partial - // struct initializers. should `v = t{x: 1}` also mark - // v.y as being written to? - if ref != store { - continue fnLoop - } - case *ir.Load: - // a load of the entire struct loads every field - for i := 0; i < recv.Type().Underlying().(*types.Struct).NumFields(); i++ { - reads[i] = append(reads[i], ref) - } - case *ir.DebugRef: - continue - default: - continue fnLoop - } - } - - offset := func(instr ir.Instruction) int { - for i, other := range instr.Block().Instrs { - if instr == other { - return i - } - } - panic("couldn't find instruction in its block") - } - - for field, ws := range writes { - rs := reads[field] - wLoop: - for _, w := range ws { - for _, r := range rs { - if w.Block() == r.Block() { - if offset(r) > offset(w) { - // found a reachable read of our write - continue wLoop - } - } else if irutil.Reachable(w.Block(), r.Block()) { - // found a reachable read of our write - continue wLoop - } - } - fieldName := recv.Type().Underlying().(*types.Struct).Field(field).Name() - report.Report(pass, w, fmt.Sprintf("ineffective assignment to field %s.%s", recv.Type().(*types.Named).Obj().Name(), fieldName)) - } - } - } - return nil, nil -} - -var negativeZeroFloatQ = pattern.MustParse(` - (Or - (UnaryExpr - "-" - (BasicLit "FLOAT" "0.0")) - - (UnaryExpr - "-" - (CallExpr conv@(Object (Or "float32" "float64")) lit@(Or (BasicLit "INT" "0") (BasicLit "FLOAT" "0.0")))) - - (CallExpr - conv@(Object (Or "float32" "float64")) - (UnaryExpr "-" lit@(BasicLit "INT" "0"))))`) - -func CheckNegativeZeroFloat(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, negativeZeroFloatQ, node) - if !ok { - return - } - - if conv, ok := m.State["conv"].(*types.TypeName); ok { - var replacement string - // TODO(dh): how does this handle type aliases? - if conv.Name() == "float32" { - replacement = `float32(math.Copysign(0, -1))` - } else { - replacement = `math.Copysign(0, -1)` - } - report.Report(pass, node, - fmt.Sprintf("in Go, the floating-point expression '%s' is the same as '%s(%s)', it does not produce a negative zero", - report.Render(pass, node), - conv.Name(), - report.Render(pass, m.State["lit"])), - report.Fixes(edit.Fix("use math.Copysign to create negative zero", edit.ReplaceWithString(node, replacement)))) - } else { - const replacement = `math.Copysign(0, -1)` - report.Report(pass, node, - "in Go, the floating-point literal '-0.0' is the same as '0.0', it does not produce a negative zero", - report.Fixes(edit.Fix("use math.Copysign to create negative zero", edit.ReplaceWithString(node, replacement)))) - } - } - code.Preorder(pass, fn, (*ast.UnaryExpr)(nil), (*ast.CallExpr)(nil)) - return nil, nil -} - -var ineffectiveURLQueryAddQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (SelectorExpr recv (Ident "Query")) []) (Ident meth)) _)`) - -func CheckIneffectiveURLQueryModification(pass *analysis.Pass) (interface{}, error) { - // TODO(dh): We could make this check more complex and detect - // pointless modifications of net/url.Values in general, but that - // requires us to get the state machine correct, else we'll cause - // false positives. - - fn := func(node ast.Node) { - m, ok := code.Match(pass, ineffectiveURLQueryAddQ, node) - if !ok { - return - } - if !code.IsOfType(pass, m.State["recv"].(ast.Expr), "*net/url.URL") { - return - } - switch m.State["meth"].(string) { - case "Add", "Del", "Set": - default: - return - } - report.Report(pass, node, "(*net/url.URL).Query returns a copy, modifying it doesn't change the URL") - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckBadRemoveAll(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - for _, b := range fn.Blocks { - for _, instr := range b.Instrs { - call, ok := instr.(ir.CallInstruction) - if !ok { - continue - } - if !irutil.IsCallTo(call.Common(), "os.RemoveAll") { - continue - } - - kind := "" - ex := "" - callName := "" - arg := irutil.Flatten(call.Common().Args[0]) - switch arg := arg.(type) { - case *ir.Call: - callName = irutil.CallName(&arg.Call) - if callName != "os.TempDir" { - continue - } - kind = "temporary" - ex = os.TempDir() - case *ir.Extract: - if arg.Index != 0 { - continue - } - first, ok := arg.Tuple.(*ir.Call) - if !ok { - continue - } - callName = irutil.CallName(&first.Call) - switch callName { - case "os.UserCacheDir": - kind = "cache" - ex, _ = os.UserCacheDir() - case "os.UserConfigDir": - kind = "config" - ex, _ = os.UserConfigDir() - case "os.UserHomeDir": - kind = "home" - ex, _ = os.UserHomeDir() - default: - continue - } - default: - continue - } - - if ex == "" { - report.Report(pass, call, fmt.Sprintf("this call to os.RemoveAll deletes the user's entire %s directory, not a subdirectory therein", kind), - report.Related(arg, fmt.Sprintf("this call to %s returns the user's %s directory", callName, kind))) - } else { - report.Report(pass, call, fmt.Sprintf("this call to os.RemoveAll deletes the user's entire %s directory, not a subdirectory therein", kind), - report.Related(arg, fmt.Sprintf("this call to %s returns the user's %s directory, for example %s", callName, kind, ex))) - } - } - } - } - return nil, nil -} - -var moduloOneQ = pattern.MustParse(`(BinaryExpr _ "%" (IntegerLiteral "1"))`) - -func CheckModuloOne(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - _, ok := code.Match(pass, moduloOneQ, node) - if !ok { - return - } - report.Report(pass, node, "x % 1 is always zero") - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -var typeAssertionShadowingElseQ = pattern.MustParse(`(IfStmt (AssignStmt [obj@(Ident _) ok@(Ident _)] ":=" assert@(TypeAssertExpr obj _)) ok _ elseBranch)`) - -func CheckTypeAssertionShadowingElse(pass *analysis.Pass) (interface{}, error) { - // TODO(dh): without the IR-based verification, this check is able - // to find more bugs, but also more prone to false positives. It - // would be a good candidate for the 'codereview' category of - // checks. - - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg - fn := func(node ast.Node) { - m, ok := code.Match(pass, typeAssertionShadowingElseQ, node) - if !ok { - return - } - shadow := pass.TypesInfo.ObjectOf(m.State["obj"].(*ast.Ident)) - shadowed := m.State["assert"].(*ast.TypeAssertExpr).X - - path, exact := astutil.PathEnclosingInterval(code.File(pass, shadow), shadow.Pos(), shadow.Pos()) - if !exact { - // TODO(dh): when can this happen? - return - } - irfn := ir.EnclosingFunction(irpkg, path) - if irfn == nil { - // For example for functions named "_", because we don't generate IR for them. - return - } - - shadoweeIR, isAddr := irfn.ValueForExpr(m.State["obj"].(*ast.Ident)) - if shadoweeIR == nil || isAddr { - // TODO(dh): is this possible? - return - } - - var branch ast.Node - switch br := m.State["elseBranch"].(type) { - case ast.Node: - branch = br - case []ast.Stmt: - branch = &ast.BlockStmt{List: br} - case nil: - return - default: - panic(fmt.Sprintf("unexpected type %T", br)) - } - - ast.Inspect(branch, func(node ast.Node) bool { - ident, ok := node.(*ast.Ident) - if !ok { - return true - } - if pass.TypesInfo.ObjectOf(ident) != shadow { - return true - } - - v, isAddr := irfn.ValueForExpr(ident) - if v == nil || isAddr { - return true - } - if irutil.Flatten(v) != shadoweeIR { - // Same types.Object, but different IR value. This - // either means that the variable has been - // assigned to since the type assertion, or that - // the variable has escaped to the heap. Either - // way, we shouldn't flag reads of it. - return true - } - - report.Report(pass, ident, - fmt.Sprintf("%s refers to the result of a failed type assertion and is a zero value, not the value that was being type-asserted", report.Render(pass, ident)), - report.Related(shadow, "this is the variable being read"), - report.Related(shadowed, "this is the variable being shadowed")) - return true - }) - } - code.Preorder(pass, fn, (*ast.IfStmt)(nil)) - return nil, nil -} - -var ineffectiveSortQ = pattern.MustParse(`(AssignStmt target@(Ident _) "=" (CallExpr typ@(Symbol (Or "sort.Float64Slice" "sort.IntSlice" "sort.StringSlice")) [target]))`) - -func CheckIneffectiveSort(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, ineffectiveSortQ, node) - if !ok { - return - } - - _, ok = pass.TypesInfo.TypeOf(m.State["target"].(ast.Expr)).(*types.Slice) - if !ok { - // Avoid flagging 'x = sort.StringSlice(x)' where TypeOf(x) == sort.StringSlice - return - } - - var alternative string - typeName := types.TypeString(m.State["typ"].(*types.TypeName).Type(), nil) - switch typeName { - case "sort.Float64Slice": - alternative = "Float64s" - case "sort.IntSlice": - alternative = "Ints" - case "sort.StringSlice": - alternative = "Strings" - default: - panic(fmt.Sprintf("unreachable: %q", typeName)) - } - - r := &ast.CallExpr{ - Fun: &ast.SelectorExpr{ - X: &ast.Ident{Name: "sort"}, - Sel: &ast.Ident{Name: alternative}, - }, - Args: []ast.Expr{m.State["target"].(ast.Expr)}, - } - - report.Report(pass, node, - fmt.Sprintf("%s is a type, not a function, and %s doesn't sort your values; consider using sort.%s instead", - typeName, - report.Render(pass, node.(*ast.AssignStmt).Rhs[0]), - alternative), - report.Fixes(edit.Fix(fmt.Sprintf("replace with call to sort.%s", alternative), edit.ReplaceWithNode(pass.Fset, node, r)))) - } - code.Preorder(pass, fn, (*ast.AssignStmt)(nil)) - return nil, nil -} - -var ineffectiveRandIntQ = pattern.MustParse(` - (CallExpr - (Symbol - name@(Or - "math/rand.Int31n" - "math/rand.Int63n" - "math/rand.Intn" - "(*math/rand.Rand).Int31n" - "(*math/rand.Rand).Int63n" - "(*math/rand.Rand).Intn")) - [(IntegerLiteral "1")])`) - -func CheckIneffectiveRandInt(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - m, ok := code.Match(pass, ineffectiveRandIntQ, node) - if !ok { - return - } - - report.Report(pass, node, - fmt.Sprintf("%s(n) generates a random value 0 <= x < n; that is, the generated values don't include n; %s therefore always returns 0", - m.State["name"], report.Render(pass, node))) - } - - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -var allocationNilCheckQ = pattern.MustParse(`(IfStmt _ cond@(BinaryExpr lhs op@(Or "==" "!=") (Builtin "nil")) _ _)`) - -func CheckAllocationNilCheck(pass *analysis.Pass) (interface{}, error) { - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg - - var path []ast.Node - fn := func(node ast.Node, stack []ast.Node) { - m, ok := code.Match(pass, allocationNilCheckQ, node) - if !ok { - return - } - cond := m.State["cond"].(ast.Node) - if _, ok := code.Match(pass, checkAddressIsNilQ, cond); ok { - // Don't duplicate diagnostics reported by SA4022 - return - } - lhs := m.State["lhs"].(ast.Expr) - path = path[:0] - for i := len(stack) - 1; i >= 0; i-- { - path = append(path, stack[i]) - } - irfn := ir.EnclosingFunction(irpkg, path) - if irfn == nil { - // For example for functions named "_", because we don't generate IR for them. - return - } - v, isAddr := irfn.ValueForExpr(lhs) - if isAddr { - return - } - - seen := map[ir.Value]struct{}{} - var values []ir.Value - var neverNil func(v ir.Value, track bool) bool - neverNil = func(v ir.Value, track bool) bool { - if _, ok := seen[v]; ok { - return true - } - seen[v] = struct{}{} - switch v := v.(type) { - case *ir.MakeClosure, *ir.Function: - if track { - values = append(values, v) - } - return true - case *ir.MakeChan, *ir.MakeMap, *ir.MakeSlice, *ir.Alloc: - if track { - values = append(values, v) - } - return true - case *ir.Slice: - if track { - values = append(values, v) - } - return neverNil(v.X, false) - case *ir.FieldAddr: - if track { - values = append(values, v) - } - return neverNil(v.X, false) - case *ir.Sigma: - return neverNil(v.X, true) - case *ir.Phi: - for _, e := range v.Edges { - if !neverNil(e, true) { - return false - } - } - return true - default: - return false - } - } - - if !neverNil(v, true) { - return - } - - var qualifier string - if op := m.State["op"].(token.Token); op == token.EQL { - qualifier = "never" - } else { - qualifier = "always" - } - fallback := fmt.Sprintf("this nil check is %s true", qualifier) - - sort.Slice(values, func(i, j int) bool { return values[i].Pos() < values[j].Pos() }) - - if ident, ok := m.State["lhs"].(*ast.Ident); ok { - if _, ok := pass.TypesInfo.ObjectOf(ident).(*types.Var); ok { - var opts []report.Option - if v.Parent() == irfn { - if len(values) == 1 { - opts = append(opts, report.Related(values[0], fmt.Sprintf("this is the value of %s", ident.Name))) - } else { - for _, vv := range values { - opts = append(opts, report.Related(vv, fmt.Sprintf("this is one of the value of %s", ident.Name))) - } - } - } - - switch v.(type) { - case *ir.MakeClosure, *ir.Function: - report.Report(pass, cond, "the checked variable contains a function and is never nil; did you mean to call it?", opts...) - default: - report.Report(pass, cond, fallback, opts...) - } - } else { - if _, ok := v.(*ir.Function); ok { - report.Report(pass, cond, "functions are never nil; did you mean to call it?") - } else { - report.Report(pass, cond, fallback) - } - } - } else { - if _, ok := v.(*ir.Function); ok { - report.Report(pass, cond, "functions are never nil; did you mean to call it?") - } else { - report.Report(pass, cond, fallback) - } - } - } - code.PreorderStack(pass, fn, (*ast.IfStmt)(nil)) - return nil, nil -} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/rules.go b/tools/vendor/honnef.co/go/tools/staticcheck/rules.go deleted file mode 100644 index debdf5d23..000000000 --- a/tools/vendor/honnef.co/go/tools/staticcheck/rules.go +++ /dev/null @@ -1,294 +0,0 @@ -package staticcheck - -import ( - "fmt" - "go/constant" - "go/types" - "net" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - "time" - "unicode/utf8" - - "honnef.co/go/tools/analysis/code" - "honnef.co/go/tools/go/ir" - "honnef.co/go/tools/go/ir/irutil" - "honnef.co/go/tools/go/types/typeutil" - - "golang.org/x/tools/go/analysis" -) - -const ( - MsgInvalidHostPort = "invalid port or service name in host:port pair" - MsgInvalidUTF8 = "argument is not a valid UTF-8 encoded string" - MsgNonUniqueCutset = "cutset contains duplicate characters" -) - -type Call struct { - Pass *analysis.Pass - Instr ir.CallInstruction - Args []*Argument - - Parent *ir.Function - - invalids []string -} - -func (c *Call) Invalid(msg string) { - c.invalids = append(c.invalids, msg) -} - -type Argument struct { - Value Value - invalids []string -} - -type Value struct { - Value ir.Value -} - -func (arg *Argument) Invalid(msg string) { - arg.invalids = append(arg.invalids, msg) -} - -type CallCheck func(call *Call) - -func extractConstExpectKind(v ir.Value, kind constant.Kind) *ir.Const { - k := extractConst(v) - if k == nil || k.Value == nil || k.Value.Kind() != kind { - return nil - } - return k -} - -func extractConst(v ir.Value) *ir.Const { - v = irutil.Flatten(v) - switch v := v.(type) { - case *ir.Const: - return v - case *ir.MakeInterface: - return extractConst(v.X) - default: - return nil - } -} - -func ValidateRegexp(v Value) error { - if c := extractConstExpectKind(v.Value, constant.String); c != nil { - s := constant.StringVal(c.Value) - if _, err := regexp.Compile(s); err != nil { - return err - } - } - return nil -} - -func ValidateTimeLayout(v Value) error { - if c := extractConstExpectKind(v.Value, constant.String); c != nil { - s := constant.StringVal(c.Value) - s = strings.Replace(s, "_", " ", -1) - s = strings.Replace(s, "Z", "-", -1) - _, err := time.Parse(s, s) - if err != nil { - return err - } - } - return nil -} - -func ValidateURL(v Value) error { - if c := extractConstExpectKind(v.Value, constant.String); c != nil { - s := constant.StringVal(c.Value) - _, err := url.Parse(s) - if err != nil { - return fmt.Errorf("%q is not a valid URL: %s", s, err) - } - } - return nil -} - -func InvalidUTF8(v Value) bool { - if c := extractConstExpectKind(v.Value, constant.String); c != nil { - s := constant.StringVal(c.Value) - if !utf8.ValidString(s) { - return true - } - } - return false -} - -func UnbufferedChannel(v Value) bool { - // TODO(dh): this check of course misses many cases of unbuffered - // channels, such as any in phi or sigma nodes. We'll eventually - // replace this function. - val := v.Value - if ct, ok := val.(*ir.ChangeType); ok { - val = ct.X - } - mk, ok := val.(*ir.MakeChan) - if !ok { - return false - } - if k, ok := mk.Size.(*ir.Const); ok && k.Value.Kind() == constant.Int { - if v, ok := constant.Int64Val(k.Value); ok && v == 0 { - return true - } - } - return false -} - -func Pointer(v Value) bool { - switch v.Value.Type().Underlying().(type) { - case *types.Pointer, *types.Interface: - return true - } - return false -} - -func ConvertedFromInt(v Value) bool { - conv, ok := v.Value.(*ir.Convert) - if !ok { - return false - } - b, ok := conv.X.Type().Underlying().(*types.Basic) - if !ok { - return false - } - if (b.Info() & types.IsInteger) == 0 { - return false - } - return true -} - -func validEncodingBinaryType(pass *analysis.Pass, typ types.Type) bool { - typ = typ.Underlying() - switch typ := typ.(type) { - case *types.Basic: - switch typ.Kind() { - case types.Uint8, types.Uint16, types.Uint32, types.Uint64, - types.Int8, types.Int16, types.Int32, types.Int64, - types.Float32, types.Float64, types.Complex64, types.Complex128, types.Invalid: - return true - case types.Bool: - return code.IsGoVersion(pass, 8) - } - return false - case *types.Struct: - n := typ.NumFields() - for i := 0; i < n; i++ { - if !validEncodingBinaryType(pass, typ.Field(i).Type()) { - return false - } - } - return true - case *types.Array: - return validEncodingBinaryType(pass, typ.Elem()) - case *types.Interface: - // we can't determine if it's a valid type or not - return true - } - return false -} - -func CanBinaryMarshal(pass *analysis.Pass, v Value) bool { - typ := v.Value.Type().Underlying() - if ttyp, ok := typ.(*types.Pointer); ok { - typ = ttyp.Elem().Underlying() - } - if ttyp, ok := typ.(interface { - Elem() types.Type - }); ok { - if _, ok := ttyp.(*types.Pointer); !ok { - typ = ttyp.Elem() - } - } - - return validEncodingBinaryType(pass, typ) -} - -func RepeatZeroTimes(name string, arg int) CallCheck { - return func(call *Call) { - arg := call.Args[arg] - if k, ok := arg.Value.Value.(*ir.Const); ok && k.Value.Kind() == constant.Int { - if v, ok := constant.Int64Val(k.Value); ok && v == 0 { - arg.Invalid(fmt.Sprintf("calling %s with n == 0 will return no results, did you mean -1?", name)) - } - } - } -} - -func validateServiceName(s string) bool { - if len(s) < 1 || len(s) > 15 { - return false - } - if s[0] == '-' || s[len(s)-1] == '-' { - return false - } - if strings.Contains(s, "--") { - return false - } - hasLetter := false - for _, r := range s { - if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') { - hasLetter = true - continue - } - if r >= '0' && r <= '9' { - continue - } - return false - } - return hasLetter -} - -func validatePort(s string) bool { - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return validateServiceName(s) - } - return n >= 0 && n <= 65535 -} - -func ValidHostPort(v Value) bool { - if k := extractConstExpectKind(v.Value, constant.String); k != nil { - s := constant.StringVal(k.Value) - if s == "" { - return true - } - _, port, err := net.SplitHostPort(s) - if err != nil { - return false - } - // TODO(dh): check hostname - if !validatePort(port) { - return false - } - } - return true -} - -// ConvertedFrom reports whether value v was converted from type typ. -func ConvertedFrom(v Value, typ string) bool { - change, ok := v.Value.(*ir.ChangeType) - return ok && typeutil.IsType(change.X.Type(), typ) -} - -func UniqueStringCutset(v Value) bool { - if c := extractConstExpectKind(v.Value, constant.String); c != nil { - s := constant.StringVal(c.Value) - rs := runeSlice(s) - if len(rs) < 2 { - return true - } - sort.Sort(rs) - for i, r := range rs[1:] { - if rs[i] == r { - return false - } - } - } - return true -} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1000/sa1000.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1000/sa1000.go new file mode 100644 index 000000000..3a1356ae3 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1000/sa1000.go @@ -0,0 +1,46 @@ +package sa1000 + +import ( + "go/constant" + "regexp" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1000", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Invalid regular expression`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "regexp.MustCompile": check, + "regexp.Compile": check, + "regexp.Match": check, + "regexp.MatchReader": check, + "regexp.MatchString": check, +} + +func check(call *callcheck.Call) { + arg := call.Args[0] + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.String); c != nil { + s := constant.StringVal(c.Value) + if _, err := regexp.Compile(s); err != nil { + arg.Invalid(err.Error()) + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1001/sa1001.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1001/sa1001.go new file mode 100644 index 000000000..659a9a63b --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1001/sa1001.go @@ -0,0 +1,76 @@ +package sa1001 + +import ( + "go/ast" + htmltemplate "html/template" + "strings" + texttemplate "text/template" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1001", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Invalid template`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + // OPT(dh): use integer for kind + var kind string + switch code.CallName(pass, call) { + case "(*text/template.Template).Parse": + kind = "text" + case "(*html/template.Template).Parse": + kind = "html" + default: + return + } + sel := call.Fun.(*ast.SelectorExpr) + if !code.IsCallToAny(pass, sel.X, "text/template.New", "html/template.New") { + // TODO(dh): this is a cheap workaround for templates with + // different delims. A better solution with less false + // negatives would use data flow analysis to see where the + // template comes from and where it has been + return + } + s, ok := code.ExprToString(pass, call.Args[knowledge.Arg("(*text/template.Template).Parse.text")]) + if !ok { + return + } + var err error + switch kind { + case "text": + _, err = texttemplate.New("").Parse(s) + case "html": + _, err = htmltemplate.New("").Parse(s) + } + if err != nil { + // TODO(dominikh): whitelist other parse errors, if any + if strings.Contains(err.Error(), "unexpected") || + strings.Contains(err.Error(), "bad character") { + report.Report(pass, call.Args[knowledge.Arg("(*text/template.Template).Parse.text")], err.Error()) + } + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1002/sa1002.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1002/sa1002.go new file mode 100644 index 000000000..ddc207675 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1002/sa1002.go @@ -0,0 +1,45 @@ +package sa1002 + +import ( + "go/constant" + "strings" + "time" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1002", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Invalid format in \'time.Parse\'`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "time.Parse": func(call *callcheck.Call) { + arg := call.Args[knowledge.Arg("time.Parse.layout")] + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.String); c != nil { + s := constant.StringVal(c.Value) + s = strings.Replace(s, "_", " ", -1) + s = strings.Replace(s, "Z", "-", -1) + _, err := time.Parse(s, s) + if err != nil { + arg.Invalid(err.Error()) + } + } + }, +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1003/sa1003.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1003/sa1003.go new file mode 100644 index 000000000..4513ed244 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1003/sa1003.go @@ -0,0 +1,92 @@ +package sa1003 + +import ( + "fmt" + "go/types" + "go/version" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1003", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkEncodingBinaryRules), + }, + Doc: &lint.RawDocumentation{ + Title: `Unsupported argument to functions in \'encoding/binary\'`, + Text: `The \'encoding/binary\' package can only serialize types with known sizes. +This precludes the use of the \'int\' and \'uint\' types, as their sizes +differ on different architectures. Furthermore, it doesn't support +serializing maps, channels, strings, or functions. + +Before Go 1.8, \'bool\' wasn't supported, either.`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkEncodingBinaryRules = map[string]callcheck.Check{ + "encoding/binary.Write": func(call *callcheck.Call) { + arg := call.Args[knowledge.Arg("encoding/binary.Write.data")] + if !CanBinaryMarshal(call.Pass, call.Parent, arg.Value) { + arg.Invalid(fmt.Sprintf("value of type %s cannot be used with binary.Write", arg.Value.Value.Type())) + } + }, +} + +func CanBinaryMarshal(pass *analysis.Pass, node code.Positioner, v callcheck.Value) bool { + typ := v.Value.Type().Underlying() + if ttyp, ok := typ.(*types.Pointer); ok { + typ = ttyp.Elem().Underlying() + } + if ttyp, ok := types.Unalias(typ).(interface { + Elem() types.Type + }); ok { + if _, ok := ttyp.(*types.Pointer); !ok { + typ = ttyp.Elem() + } + } + + return validEncodingBinaryType(pass, node, typ) +} + +func validEncodingBinaryType(pass *analysis.Pass, node code.Positioner, typ types.Type) bool { + typ = typ.Underlying() + switch typ := typ.(type) { + case *types.Basic: + switch typ.Kind() { + case types.Uint8, types.Uint16, types.Uint32, types.Uint64, + types.Int8, types.Int16, types.Int32, types.Int64, + types.Float32, types.Float64, types.Complex64, types.Complex128, types.Invalid: + return true + case types.Bool: + return version.Compare(code.StdlibVersion(pass, node), "go1.8") >= 0 + } + return false + case *types.Struct: + n := typ.NumFields() + for i := 0; i < n; i++ { + if !validEncodingBinaryType(pass, node, typ.Field(i).Type()) { + return false + } + } + return true + case *types.Array: + return validEncodingBinaryType(pass, node, typ.Elem()) + case *types.Interface: + // we can't determine if it's a valid type or not + return true + } + return false +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1004/sa1004.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1004/sa1004.go new file mode 100644 index 000000000..c65de9271 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1004/sa1004.go @@ -0,0 +1,78 @@ +package sa1004 + +import ( + "fmt" + "go/ast" + "go/constant" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1004", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Suspiciously small untyped constant in \'time.Sleep\'`, + Text: `The \'time\'.Sleep function takes a \'time.Duration\' as its only argument. +Durations are expressed in nanoseconds. Thus, calling \'time.Sleep(1)\' +will sleep for 1 nanosecond. This is a common source of bugs, as sleep +functions in other languages often accept seconds or milliseconds. + +The \'time\' package provides constants such as \'time.Second\' to express +large durations. These can be combined with arithmetic to express +arbitrary durations, for example \'5 * time.Second\' for 5 seconds. + +If you truly meant to sleep for a tiny amount of time, use +\'n * time.Nanosecond\' to signal to Staticcheck that you did mean to sleep +for some amount of nanoseconds.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkTimeSleepConstantPatternQ = pattern.MustParse(`(CallExpr (Symbol "time.Sleep") lit@(IntegerLiteral value))`) + checkTimeSleepConstantPatternRns = pattern.MustParse(`(BinaryExpr duration "*" (SelectorExpr (Ident "time") (Ident "Nanosecond")))`) + checkTimeSleepConstantPatternRs = pattern.MustParse(`(BinaryExpr duration "*" (SelectorExpr (Ident "time") (Ident "Second")))`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkTimeSleepConstantPatternQ, node) + if !ok { + return + } + n, ok := constant.Int64Val(m.State["value"].(types.TypeAndValue).Value) + if !ok { + return + } + if n == 0 || n > 120 { + // time.Sleep(0) is a seldom used pattern in concurrency + // tests. >120 might be intentional. 120 was chosen + // because the user could've meant 2 minutes. + return + } + + lit := m.State["lit"].(ast.Node) + report.Report(pass, lit, + fmt.Sprintf("sleeping for %d nanoseconds is probably a bug; be explicit if it isn't", n), report.Fixes( + edit.Fix("explicitly use nanoseconds", edit.ReplaceWithPattern(pass.Fset, lit, checkTimeSleepConstantPatternRns, pattern.State{"duration": lit})), + edit.Fix("use seconds", edit.ReplaceWithPattern(pass.Fset, lit, checkTimeSleepConstantPatternRs, pattern.State{"duration": lit})))) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1005/sa1005.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1005/sa1005.go new file mode 100644 index 000000000..454dc01c6 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1005/sa1005.go @@ -0,0 +1,68 @@ +package sa1005 + +import ( + "go/ast" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1005", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Invalid first argument to \'exec.Command\'`, + Text: `\'os/exec\' runs programs directly (using variants of the fork and exec +system calls on Unix systems). This shouldn't be confused with running +a command in a shell. The shell will allow for features such as input +redirection, pipes, and general scripting. The shell is also +responsible for splitting the user's input into a program name and its +arguments. For example, the equivalent to + + ls / /tmp + +would be + + exec.Command("ls", "/", "/tmp") + +If you want to run a command in a shell, consider using something like +the following – but be aware that not all systems, particularly +Windows, will have a \'/bin/sh\' program: + + exec.Command("/bin/sh", "-c", "ls | grep Awesome")`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + if !code.IsCallTo(pass, call, "os/exec.Command") { + return + } + val, ok := code.ExprToString(pass, call.Args[knowledge.Arg("os/exec.Command.name")]) + if !ok { + return + } + if !strings.Contains(val, " ") || strings.Contains(val, `\`) || strings.Contains(val, "/") { + return + } + report.Report(pass, call.Args[knowledge.Arg("os/exec.Command.name")], + "first argument to exec.Command looks like a shell command, but a program name or path are expected") + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1006/sa1006.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1006/sa1006.go new file mode 100644 index 000000000..06b77436d --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1006/sa1006.go @@ -0,0 +1,107 @@ +package sa1006 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1006", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'Printf\' with dynamic first argument and no further arguments`, + Text: `Using \'fmt.Printf\' with a dynamic first argument can lead to unexpected +output. The first argument is a format string, where certain character +combinations have special meaning. If, for example, a user were to +enter a string such as + + Interest rate: 5% + +and you printed it with + + fmt.Printf(s) + +it would lead to the following output: + + Interest rate: 5%!(NOVERB). + +Similarly, forming the first parameter via string concatenation with +user input should be avoided for the same reason. When printing user +input, either use a variant of \'fmt.Print\', or use the \'%s\' Printf verb +and pass the string as an argument.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + name := code.CallName(pass, call) + var arg int + + switch name { + case "fmt.Errorf", "fmt.Printf", "fmt.Sprintf", + "log.Fatalf", "log.Panicf", "log.Printf", "(*log.Logger).Printf", + "(*testing.common).Logf", "(*testing.common).Errorf", + "(*testing.common).Fatalf", "(*testing.common).Skipf", + "(testing.TB).Logf", "(testing.TB).Errorf", + "(testing.TB).Fatalf", "(testing.TB).Skipf": + arg = knowledge.Arg("fmt.Printf.format") + case "fmt.Fprintf": + arg = knowledge.Arg("fmt.Fprintf.format") + default: + return + } + if len(call.Args) != arg+1 { + // This filters out calls of method expressions like (*log.Logger).Printf(nil, s) + return + } + switch call.Args[arg].(type) { + case *ast.CallExpr, *ast.Ident: + default: + return + } + + if _, ok := pass.TypesInfo.TypeOf(call.Args[arg]).(*types.Tuple); ok { + // the called function returns multiple values and got + // splatted into the call. for all we know, it is + // returning good arguments. + return + } + + var alt string + if name == "fmt.Errorf" { + // The alternative to fmt.Errorf isn't fmt.Error but errors.New + alt = "errors.New" + } else { + // This can be either a function call like log.Printf or a method call with an + // arbitrarily complex selector, such as foo.bar[0].Printf. In either case, + // all we have to do is remove the final 'f' from the existing call.Fun + // expression. + alt = report.Render(pass, call.Fun) + alt = alt[:len(alt)-1] + } + report.Report(pass, call, + "printf-style function with dynamic format string and no further arguments should use print-style function instead", + report.Fixes(edit.Fix(fmt.Sprintf("use %s instead of %s", alt, name), edit.ReplaceWithString(call.Fun, alt)))) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1007/sa1007.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1007/sa1007.go new file mode 100644 index 000000000..8aa6958ea --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1007/sa1007.go @@ -0,0 +1,43 @@ +package sa1007 + +import ( + "fmt" + "go/constant" + "net/url" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1007", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Invalid URL in \'net/url.Parse\'`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "net/url.Parse": func(call *callcheck.Call) { + arg := call.Args[knowledge.Arg("net/url.Parse.rawurl")] + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.String); c != nil { + s := constant.StringVal(c.Value) + _, err := url.Parse(s) + if err != nil { + arg.Invalid(fmt.Sprintf("%q is not a valid URL: %s", s, err)) + } + } + }, +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1008/sa1008.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1008/sa1008.go new file mode 100644 index 000000000..60e78d5be --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1008/sa1008.go @@ -0,0 +1,111 @@ +package sa1008 + +import ( + "fmt" + "go/ast" + "net/http" + "strconv" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1008", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Non-canonical key in \'http.Header\' map`, + Text: `Keys in \'http.Header\' maps are canonical, meaning they follow a specific +combination of uppercase and lowercase letters. Methods such as +\'http.Header.Add\' and \'http.Header.Del\' convert inputs into this canonical +form before manipulating the map. + +When manipulating \'http.Header\' maps directly, as opposed to using the +provided methods, care should be taken to stick to canonical form in +order to avoid inconsistencies. The following piece of code +demonstrates one such inconsistency: + + h := http.Header{} + h["etag"] = []string{"1234"} + h.Add("etag", "5678") + fmt.Println(h) + + // Output: + // map[Etag:[5678] etag:[1234]] + +The easiest way of obtaining the canonical form of a key is to use +\'http.CanonicalHeaderKey\'.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node, push bool) bool { + if !push { + return false + } + if assign, ok := node.(*ast.AssignStmt); ok { + // TODO(dh): This risks missing some Header reads, for + // example in `h1["foo"] = h2["foo"]` – these edge + // cases are probably rare enough to ignore for now. + for _, expr := range assign.Lhs { + op, ok := expr.(*ast.IndexExpr) + if !ok { + continue + } + if code.IsOfTypeWithName(pass, op.X, "net/http.Header") { + return false + } + } + return true + } + op, ok := node.(*ast.IndexExpr) + if !ok { + return true + } + if !code.IsOfTypeWithName(pass, op.X, "net/http.Header") { + return true + } + s, ok := code.ExprToString(pass, op.Index) + if !ok { + return true + } + canonical := http.CanonicalHeaderKey(s) + if s == canonical { + return true + } + var fix analysis.SuggestedFix + switch op.Index.(type) { + case *ast.BasicLit: + fix = edit.Fix("canonicalize header key", edit.ReplaceWithString(op.Index, strconv.Quote(canonical))) + case *ast.Ident: + call := &ast.CallExpr{ + Fun: edit.Selector("http", "CanonicalHeaderKey"), + Args: []ast.Expr{op.Index}, + } + fix = edit.Fix("wrap in http.CanonicalHeaderKey", edit.ReplaceWithNode(pass.Fset, op.Index, call)) + } + msg := fmt.Sprintf("keys in http.Header are canonicalized, %q is not canonical; fix the constant or use http.CanonicalHeaderKey", s) + if fix.Message != "" { + report.Report(pass, op, msg, report.Fixes(fix)) + } else { + report.Report(pass, op, msg) + } + return true + } + pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.AssignStmt)(nil), (*ast.IndexExpr)(nil)}, fn) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1010/sa1010.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1010/sa1010.go new file mode 100644 index 000000000..2ad6b1fe4 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1010/sa1010.go @@ -0,0 +1,53 @@ +package sa1010 + +import ( + "fmt" + "go/constant" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1010", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkRegexpFindAllRules), + }, + Doc: &lint.RawDocumentation{ + Title: `\'(*regexp.Regexp).FindAll\' called with \'n == 0\', which will always return zero results`, + Text: `If \'n >= 0\', the function returns at most \'n\' matches/submatches. To +return all results, specify a negative number.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkRegexpFindAllRules = map[string]callcheck.Check{ + "(*regexp.Regexp).FindAll": RepeatZeroTimes("a FindAll method", 1), + "(*regexp.Regexp).FindAllIndex": RepeatZeroTimes("a FindAll method", 1), + "(*regexp.Regexp).FindAllString": RepeatZeroTimes("a FindAll method", 1), + "(*regexp.Regexp).FindAllStringIndex": RepeatZeroTimes("a FindAll method", 1), + "(*regexp.Regexp).FindAllStringSubmatch": RepeatZeroTimes("a FindAll method", 1), + "(*regexp.Regexp).FindAllStringSubmatchIndex": RepeatZeroTimes("a FindAll method", 1), + "(*regexp.Regexp).FindAllSubmatch": RepeatZeroTimes("a FindAll method", 1), + "(*regexp.Regexp).FindAllSubmatchIndex": RepeatZeroTimes("a FindAll method", 1), +} + +func RepeatZeroTimes(name string, arg int) callcheck.Check { + return func(call *callcheck.Call) { + arg := call.Args[arg] + if k, ok := arg.Value.Value.(*ir.Const); ok && k.Value.Kind() == constant.Int { + if v, ok := constant.Int64Val(k.Value); ok && v == 0 { + arg.Invalid(fmt.Sprintf("calling %s with n == 0 will return no results, did you mean -1?", name)) + } + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1011/sa1011.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1011/sa1011.go new file mode 100644 index 000000000..5b86c6ded --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1011/sa1011.go @@ -0,0 +1,47 @@ +package sa1011 + +import ( + "go/constant" + "unicode/utf8" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1011", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkUTF8CutsetRules), + }, + Doc: &lint.RawDocumentation{ + Title: `Various methods in the \"strings\" package expect valid UTF-8, but invalid input is provided`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkUTF8CutsetRules = map[string]callcheck.Check{ + "strings.IndexAny": check, + "strings.LastIndexAny": check, + "strings.ContainsAny": check, + "strings.Trim": check, + "strings.TrimLeft": check, + "strings.TrimRight": check, +} + +func check(call *callcheck.Call) { + arg := call.Args[1] + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.String); c != nil { + s := constant.StringVal(c.Value) + if !utf8.ValidString(s) { + arg.Invalid("argument is not a valid UTF-8 encoded string") + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1012/sa1012.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1012/sa1012.go new file mode 100644 index 000000000..1bf771210 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1012/sa1012.go @@ -0,0 +1,72 @@ +package sa1012 + +import ( + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1012", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `A nil \'context.Context\' is being passed to a function, consider using \'context.TODO\' instead`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkNilContextQ = pattern.MustParse(`(CallExpr fun@(Symbol _) (Builtin "nil"):_)`) + +func run(pass *analysis.Pass) (interface{}, error) { + todo := &ast.CallExpr{ + Fun: edit.Selector("context", "TODO"), + } + bg := &ast.CallExpr{ + Fun: edit.Selector("context", "Background"), + } + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkNilContextQ, node) + if !ok { + return + } + + call := node.(*ast.CallExpr) + fun, ok := m.State["fun"].(*types.Func) + if !ok { + // it might also be a builtin + return + } + sig := fun.Type().(*types.Signature) + if sig.Params().Len() == 0 { + // Our CallExpr might've matched a method expression, like + // (*T).Foo(nil) – here, nil isn't the first argument of + // the Foo method, but the method receiver. + return + } + if !typeutil.IsTypeWithName(sig.Params().At(0).Type(), "context.Context") { + return + } + report.Report(pass, call.Args[0], + "do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use", report.Fixes( + edit.Fix("use context.TODO", edit.ReplaceWithNode(pass.Fset, call.Args[0], todo)), + edit.Fix("use context.Background", edit.ReplaceWithNode(pass.Fset, call.Args[0], bg)))) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1013/sa1013.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1013/sa1013.go new file mode 100644 index 000000000..722baaa6f --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1013/sa1013.go @@ -0,0 +1,50 @@ +package sa1013 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1013", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'io.Seeker.Seek\' is being called with the whence constant as the first argument, but it should be the second`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkSeekerQ = pattern.MustParse(`(CallExpr fun@(SelectorExpr _ (Ident "Seek")) [arg1@(SelectorExpr _ (Symbol (Or "io.SeekStart" "io.SeekCurrent" "io.SeekEnd"))) arg2])`) + checkSeekerR = pattern.MustParse(`(CallExpr fun [arg2 arg1])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if m, edits, ok := code.MatchAndEdit(pass, checkSeekerQ, checkSeekerR, node); ok { + if !code.IsMethod(pass, m.State["fun"].(*ast.SelectorExpr), "Seek", knowledge.Signatures["(io.Seeker).Seek"]) { + return + } + report.Report(pass, node, "the first argument of io.Seeker is the offset, but an io.Seek* constant is being used instead", + report.Fixes(edit.Fix("swap arguments", edits...))) + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1014/sa1014.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1014/sa1014.go new file mode 100644 index 000000000..90d676af2 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1014/sa1014.go @@ -0,0 +1,52 @@ +package sa1014 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1014", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkUnmarshalPointerRules), + }, + Doc: &lint.RawDocumentation{ + Title: `Non-pointer value passed to \'Unmarshal\' or \'Decode\'`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkUnmarshalPointerRules = map[string]callcheck.Check{ + "encoding/xml.Unmarshal": unmarshalPointer("xml.Unmarshal", 1), + "(*encoding/xml.Decoder).Decode": unmarshalPointer("Decode", 0), + "(*encoding/xml.Decoder).DecodeElement": unmarshalPointer("DecodeElement", 0), + "encoding/json.Unmarshal": unmarshalPointer("json.Unmarshal", 1), + "(*encoding/json.Decoder).Decode": unmarshalPointer("Decode", 0), +} + +func unmarshalPointer(name string, arg int) callcheck.Check { + return func(call *callcheck.Call) { + if !Pointer(call.Args[arg].Value) { + call.Args[arg].Invalid(fmt.Sprintf("%s expects to unmarshal into a pointer, but the provided value is not a pointer", name)) + } + } +} + +func Pointer(v callcheck.Value) bool { + switch v.Value.Type().Underlying().(type) { + case *types.Pointer, *types.Interface: + return true + } + return false +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1015/sa1015.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1015/sa1015.go new file mode 100644 index 000000000..386c1a255 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1015/sa1015.go @@ -0,0 +1,69 @@ +package sa1015 + +import ( + "go/token" + "go/version" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1015", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Using \'time.Tick\' in a way that will leak. Consider using \'time.NewTicker\', and only use \'time.Tick\' in tests, commands and endless functions`, + + Text: `Before Go 1.23, \'time.Ticker\'s had to be closed to be able to be garbage +collected. Since \'time.Tick\' doesn't make it possible to close the underlying +ticker, using it repeatedly would leak memory. + +Go 1.23 fixes this by allowing tickers to be collected even if they weren't closed.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + if fn.Pos() == token.NoPos || version.Compare(code.StdlibVersion(pass, fn), "go1.23") >= 0 { + // Beginning with Go 1.23, the GC is able to collect unreferenced, unclosed + // tickers, which makes time.Tick safe(r) to use. + // + // When we don't have a valid position, we err on the side of false negatives. + // This shouldn't actually lead to any false negatives, as no functions + // without valid positions (such as the synthesized init function) should be + // able to use time.Tick. + continue + } + + if code.IsMainLike(pass) || code.IsInTest(pass, fn) { + continue + } + for _, block := range fn.Blocks { + for _, ins := range block.Instrs { + call, ok := ins.(*ir.Call) + if !ok || !irutil.IsCallTo(call.Common(), "time.Tick") { + continue + } + if !irutil.Terminates(call.Parent()) { + continue + } + report.Report(pass, call, "using time.Tick leaks the underlying ticker, consider using it only in endless functions, tests and the main package, and use time.NewTicker here") + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1016/sa1016.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1016/sa1016.go new file mode 100644 index 000000000..fa9c62024 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1016/sa1016.go @@ -0,0 +1,112 @@ +package sa1016 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1016", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Trapping a signal that cannot be trapped`, + Text: `Not all signals can be intercepted by a process. Specifically, on +UNIX-like systems, the \'syscall.SIGKILL\' and \'syscall.SIGSTOP\' signals are +never passed to the process, but instead handled directly by the +kernel. It is therefore pointless to try and handle these signals.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + isSignal := func(pass *analysis.Pass, expr ast.Expr, name string) bool { + if expr, ok := expr.(*ast.SelectorExpr); ok { + return code.SelectorName(pass, expr) == name + } else { + return false + } + } + + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + if !code.IsCallToAny(pass, call, + "os/signal.Ignore", "os/signal.Notify", "os/signal.Reset") { + return + } + + hasSigterm := false + for _, arg := range call.Args { + if conv, ok := arg.(*ast.CallExpr); ok && isSignal(pass, conv.Fun, "os.Signal") { + arg = conv.Args[0] + } + + if isSignal(pass, arg, "syscall.SIGTERM") { + hasSigterm = true + break + } + + } + for i, arg := range call.Args { + if conv, ok := arg.(*ast.CallExpr); ok && isSignal(pass, conv.Fun, "os.Signal") { + arg = conv.Args[0] + } + + if isSignal(pass, arg, "os.Kill") || isSignal(pass, arg, "syscall.SIGKILL") { + var fixes []analysis.SuggestedFix + if !hasSigterm { + nargs := make([]ast.Expr, len(call.Args)) + for j, a := range call.Args { + if i == j { + nargs[j] = edit.Selector("syscall", "SIGTERM") + } else { + nargs[j] = a + } + } + ncall := *call + ncall.Args = nargs + fixes = append(fixes, edit.Fix(fmt.Sprintf("use syscall.SIGTERM instead of %s", report.Render(pass, arg)), edit.ReplaceWithNode(pass.Fset, call, &ncall))) + } + nargs := make([]ast.Expr, 0, len(call.Args)) + for j, a := range call.Args { + if i == j { + continue + } + nargs = append(nargs, a) + } + ncall := *call + ncall.Args = nargs + fixes = append(fixes, edit.Fix(fmt.Sprintf("remove %s from list of arguments", report.Render(pass, arg)), edit.ReplaceWithNode(pass.Fset, call, &ncall))) + report.Report(pass, arg, fmt.Sprintf("%s cannot be trapped (did you mean syscall.SIGTERM?)", report.Render(pass, arg)), report.Fixes(fixes...)) + } + if isSignal(pass, arg, "syscall.SIGSTOP") { + nargs := make([]ast.Expr, 0, len(call.Args)-1) + for j, a := range call.Args { + if i == j { + continue + } + nargs = append(nargs, a) + } + ncall := *call + ncall.Args = nargs + report.Report(pass, arg, "syscall.SIGSTOP cannot be trapped", report.Fixes(edit.Fix("remove syscall.SIGSTOP from list of arguments", edit.ReplaceWithNode(pass.Fset, call, &ncall)))) + } + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1017/sa1017.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1017/sa1017.go new file mode 100644 index 000000000..f200d997a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1017/sa1017.go @@ -0,0 +1,64 @@ +package sa1017 + +import ( + "go/constant" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1017", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Channels used with \'os/signal.Notify\' should be buffered`, + Text: `The \'os/signal\' package uses non-blocking channel sends when delivering +signals. If the receiving end of the channel isn't ready and the +channel is either unbuffered or full, the signal will be dropped. To +avoid missing signals, the channel should be buffered and of the +appropriate size. For a channel used for notification of just one +signal value, a buffer of size 1 is sufficient.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "os/signal.Notify": func(call *callcheck.Call) { + arg := call.Args[knowledge.Arg("os/signal.Notify.c")] + if isUnbufferedChannel(arg.Value) { + arg.Invalid("the channel used with signal.Notify should be buffered") + } + }, +} + +func isUnbufferedChannel(v callcheck.Value) bool { + // TODO(dh): this check of course misses many cases of unbuffered + // channels, such as any in phi or sigma nodes. We'll eventually + // replace this function. + val := v.Value + if ct, ok := val.(*ir.ChangeType); ok { + val = ct.X + } + mk, ok := val.(*ir.MakeChan) + if !ok { + return false + } + if k, ok := mk.Size.(*ir.Const); ok && k.Value.Kind() == constant.Int { + if v, ok := constant.Int64Val(k.Value); ok && v == 0 { + return true + } + } + return false +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1018/sa1018.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1018/sa1018.go new file mode 100644 index 000000000..9981910ea --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1018/sa1018.go @@ -0,0 +1,47 @@ +package sa1018 + +import ( + "fmt" + "go/constant" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1018", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `\'strings.Replace\' called with \'n == 0\', which does nothing`, + Text: `With \'n == 0\', zero instances will be replaced. To replace all +instances, use a negative number, or use \'strings.ReplaceAll\'.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "strings.Replace": check("strings.Replace", 3), + "bytes.Replace": check("bytes.Replace", 3), +} + +func check(name string, arg int) callcheck.Check { + return func(call *callcheck.Call) { + arg := call.Args[arg] + if k, ok := arg.Value.Value.(*ir.Const); ok && k.Value.Kind() == constant.Int { + if v, ok := constant.Int64Val(k.Value); ok && v == 0 { + arg.Invalid(fmt.Sprintf("calling %s with n == 0 will return no results, did you mean -1?", name)) + } + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1019/sa1019.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1019/sa1019.go new file mode 100644 index 000000000..50a400669 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1019/sa1019.go @@ -0,0 +1,212 @@ +package sa1019 + +import ( + "fmt" + "go/ast" + "go/types" + "go/version" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/deprecated" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1019", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, deprecated.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Using a deprecated function, variable, constant or field`, + Since: "2017.1", + Severity: lint.SeverityDeprecated, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func formatGoVersion(s string) string { + return "Go " + strings.TrimPrefix(s, "go") +} + +func run(pass *analysis.Pass) (interface{}, error) { + deprs := pass.ResultOf[deprecated.Analyzer].(deprecated.Result) + + // Selectors can appear outside of function literals, e.g. when + // declaring package level variables. + + isStdlibPath := func(path string) bool { + // Modules with no dot in the first path element are reserved for the standard library and tooling. + // This is the best we can currently do. + // Nobody tells us which import paths are part of the standard library. + // + // We check the entire path instead of just the first path element, because the standard library doesn't contain paths with any dots, anyway. + + return !strings.Contains(path, ".") + } + + handleDeprecation := func(depr *deprecated.IsDeprecated, node ast.Node, deprecatedObjName string, pkgPath string, tfn types.Object) { + std, ok := knowledge.StdlibDeprecations[deprecatedObjName] + if !ok && isStdlibPath(pkgPath) { + // Deprecated object in the standard library, but we don't know the details of the deprecation. + // Don't flag it at all, to avoid flagging an object that was deprecated in 1.N when targeting 1.N-1. + // See https://staticcheck.dev/issues/1108 for the background on this. + return + } + if ok { + // In the past, we made use of the AlternativeAvailableSince field. If a function was deprecated in Go + // 1.6 and an alternative had been available in Go 1.0, then we'd recommend using the alternative even + // if targeting Go 1.2. The idea was to suggest writing future-proof code by using already-existing + // alternatives. This had a major flaw, however: the user would need to use at least Go 1.6 for + // Staticcheck to know that the function had been deprecated. Thus, targeting Go 1.2 and using Go 1.2 + // would behave differently from targeting Go 1.2 and using Go 1.6. This is especially a problem if the + // user tries to ignore the warning. Depending on the Go version in use, the ignore directive may or may + // not match, causing a warning of its own. + // + // To avoid this issue, we no longer try to be smart. We now only compare the targeted version against + // the version that deprecated an object. + // + // Unfortunately, this issue also applies to AlternativeAvailableSince == DeprecatedNeverUse. Even though it + // is only applied to seriously flawed API, such as broken cryptography, users may wish to ignore those + // warnings. + // + // See also https://staticcheck.dev/issues/1318. + if version.Compare(code.StdlibVersion(pass, node), std.DeprecatedSince) == -1 { + return + } + } + + if tfn != nil { + if _, ok := deprs.Objects[tfn]; ok { + // functions that are deprecated may use deprecated + // symbols + return + } + } + + if ok { + switch std.AlternativeAvailableSince { + case knowledge.DeprecatedNeverUse: + report.Report(pass, node, + fmt.Sprintf("%s has been deprecated since %s because it shouldn't be used: %s", + report.Render(pass, node), formatGoVersion(std.DeprecatedSince), depr.Msg)) + case std.DeprecatedSince, knowledge.DeprecatedUseNoLonger: + report.Report(pass, node, + fmt.Sprintf("%s has been deprecated since %s: %s", + report.Render(pass, node), formatGoVersion(std.DeprecatedSince), depr.Msg)) + default: + report.Report(pass, node, + fmt.Sprintf("%s has been deprecated since %s and an alternative has been available since %s: %s", + report.Render(pass, node), formatGoVersion(std.DeprecatedSince), formatGoVersion(std.AlternativeAvailableSince), depr.Msg)) + } + } else { + report.Report(pass, node, fmt.Sprintf("%s is deprecated: %s", report.Render(pass, node), depr.Msg)) + } + } + + var tfn types.Object + stack := 0 + fn := func(node ast.Node, push bool) bool { + if !push { + stack-- + return false + } + stack++ + if stack == 1 { + tfn = nil + } + if fn, ok := node.(*ast.FuncDecl); ok { + tfn = pass.TypesInfo.ObjectOf(fn.Name) + } + + // FIXME(dh): this misses dot-imported objects + sel, ok := node.(*ast.SelectorExpr) + if !ok { + return true + } + + obj := pass.TypesInfo.ObjectOf(sel.Sel) + if obj_, ok := obj.(*types.Func); ok { + obj = obj_.Origin() + } + if obj.Pkg() == nil { + return true + } + + if obj.Pkg() == pass.Pkg { + // A package is allowed to use its own deprecated objects + return true + } + + // A package "foo" has two related packages "foo_test" and "foo.test", for external tests and the package main + // generated by 'go test' respectively. "foo_test" can import and use "foo", "foo.test" imports and uses "foo" + // and "foo_test". + + if strings.TrimSuffix(pass.Pkg.Path(), "_test") == obj.Pkg().Path() { + // foo_test (the external tests of foo) can use objects from foo. + return true + } + if strings.TrimSuffix(pass.Pkg.Path(), ".test") == obj.Pkg().Path() { + // foo.test (the main package of foo's tests) can use objects from foo. + return true + } + if strings.TrimSuffix(pass.Pkg.Path(), ".test") == strings.TrimSuffix(obj.Pkg().Path(), "_test") { + // foo.test (the main package of foo's tests) can use objects from foo's external tests. + return true + } + + if depr, ok := deprs.Objects[obj]; ok { + handleDeprecation(depr, sel, code.SelectorName(pass, sel), obj.Pkg().Path(), tfn) + } + return true + } + + fn2 := func(node ast.Node) { + spec := node.(*ast.ImportSpec) + var imp *types.Package + if spec.Name != nil { + imp = pass.TypesInfo.ObjectOf(spec.Name).(*types.PkgName).Imported() + } else { + imp = pass.TypesInfo.Implicits[spec].(*types.PkgName).Imported() + } + + p := spec.Path.Value + path := p[1 : len(p)-1] + if depr, ok := deprs.Packages[imp]; ok { + if path == "github.com/golang/protobuf/proto" { + gen, ok := code.Generator(pass, spec.Path.Pos()) + if ok && gen == generated.ProtocGenGo { + return + } + } + + if strings.TrimSuffix(pass.Pkg.Path(), "_test") == path { + // foo_test can import foo + return + } + if strings.TrimSuffix(pass.Pkg.Path(), ".test") == path { + // foo.test can import foo + return + } + if strings.TrimSuffix(pass.Pkg.Path(), ".test") == strings.TrimSuffix(path, "_test") { + // foo.test can import foo_test + return + } + + handleDeprecation(depr, spec.Path, path, path, nil) + } + } + pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes(nil, fn) + code.Preorder(pass, fn2, (*ast.ImportSpec)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1020/sa1020.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1020/sa1020.go new file mode 100644 index 000000000..aa1aeae65 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1020/sa1020.go @@ -0,0 +1,94 @@ +package sa1020 + +import ( + "go/constant" + "net" + "strconv" + "strings" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1020", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkListenAddressRules), + }, + Doc: &lint.RawDocumentation{ + Title: `Using an invalid host:port pair with a \'net.Listen\'-related function`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkListenAddressRules = map[string]callcheck.Check{ + "net/http.ListenAndServe": checkValidHostPort(0), + "net/http.ListenAndServeTLS": checkValidHostPort(0), +} + +func checkValidHostPort(arg int) callcheck.Check { + return func(call *callcheck.Call) { + if !ValidHostPort(call.Args[arg].Value) { + const MsgInvalidHostPort = "invalid port or service name in host:port pair" + call.Args[arg].Invalid(MsgInvalidHostPort) + } + } +} + +func ValidHostPort(v callcheck.Value) bool { + if k := callcheck.ExtractConstExpectKind(v, constant.String); k != nil { + s := constant.StringVal(k.Value) + if s == "" { + return true + } + _, port, err := net.SplitHostPort(s) + if err != nil { + return false + } + // TODO(dh): check hostname + if !validatePort(port) { + return false + } + } + return true +} + +func validateServiceName(s string) bool { + if len(s) < 1 || len(s) > 15 { + return false + } + if s[0] == '-' || s[len(s)-1] == '-' { + return false + } + if strings.Contains(s, "--") { + return false + } + hasLetter := false + for _, r := range s { + if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') { + hasLetter = true + continue + } + if r >= '0' && r <= '9' { + continue + } + return false + } + return hasLetter +} + +func validatePort(s string) bool { + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return validateServiceName(s) + } + return n >= 0 && n <= 65535 +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1021/sa1021.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1021/sa1021.go new file mode 100644 index 000000000..95fc96021 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1021/sa1021.go @@ -0,0 +1,49 @@ +package sa1021 + +import ( + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1021", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Using \'bytes.Equal\' to compare two \'net.IP\'`, + Text: `A \'net.IP\' stores an IPv4 or IPv6 address as a slice of bytes. The +length of the slice for an IPv4 address, however, can be either 4 or +16 bytes long, using different ways of representing IPv4 addresses. In +order to correctly compare two \'net.IP\'s, the \'net.IP.Equal\' method should +be used, as it takes both representations into account.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "bytes.Equal": func(call *callcheck.Call) { + if isConvertedFrom(call.Args[knowledge.Arg("bytes.Equal.a")].Value, "net.IP") && + isConvertedFrom(call.Args[knowledge.Arg("bytes.Equal.b")].Value, "net.IP") { + call.Invalid("use net.IP.Equal to compare net.IPs, not bytes.Equal") + } + }, +} + +// ConvertedFrom reports whether value v was converted from type typ. +func isConvertedFrom(v callcheck.Value, typ string) bool { + change, ok := v.Value.(*ir.ChangeType) + return ok && types.TypeString(types.Unalias(change.X.Type()), nil) == typ +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1023/sa1023.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1023/sa1023.go new file mode 100644 index 000000000..1ebfe7e93 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1023/sa1023.go @@ -0,0 +1,72 @@ +package sa1023 + +import ( + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1023", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Modifying the buffer in an \'io.Writer\' implementation`, + Text: `\'Write\' must not modify the slice data, even temporarily.`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // TODO(dh): this might be a good candidate for taint analysis. + // Taint the argument as MUST_NOT_MODIFY, then propagate that + // through functions like bytes.Split + + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + sig := fn.Signature + if fn.Name() != "Write" || sig.Recv() == nil { + continue + } + if !types.Identical(sig, knowledge.Signatures["(io.Writer).Write"]) { + continue + } + + for _, block := range fn.Blocks { + for _, ins := range block.Instrs { + switch ins := ins.(type) { + case *ir.Store: + addr, ok := ins.Addr.(*ir.IndexAddr) + if !ok { + continue + } + if addr.X != fn.Params[1] { + continue + } + report.Report(pass, ins, "io.Writer.Write must not modify the provided buffer, not even temporarily") + case *ir.Call: + if !irutil.IsCallTo(ins.Common(), "append") { + continue + } + if ins.Common().Args[0] != fn.Params[1] { + continue + } + report.Report(pass, ins, "io.Writer.Write must not modify the provided buffer, not even temporarily") + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1024/sa1024.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1024/sa1024.go new file mode 100644 index 000000000..2ff489684 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1024/sa1024.go @@ -0,0 +1,75 @@ +package sa1024 + +import ( + "go/constant" + "sort" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1024", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `A string cutset contains duplicate characters`, + Text: `The \'strings.TrimLeft\' and \'strings.TrimRight\' functions take cutsets, not +prefixes. A cutset is treated as a set of characters to remove from a +string. For example, + + strings.TrimLeft("42133word", "1234") + +will result in the string \'"word"\' – any characters that are 1, 2, 3 or +4 are cut from the left of the string. + +In order to remove one string from another, use \'strings.TrimPrefix\' instead.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "strings.Trim": check, + "strings.TrimLeft": check, + "strings.TrimRight": check, +} + +func check(call *callcheck.Call) { + arg := call.Args[1] + if !isUniqueStringCutset(arg.Value) { + const MsgNonUniqueCutset = "cutset contains duplicate characters" + arg.Invalid(MsgNonUniqueCutset) + } +} + +func isUniqueStringCutset(v callcheck.Value) bool { + if c := callcheck.ExtractConstExpectKind(v, constant.String); c != nil { + s := constant.StringVal(c.Value) + rs := runeSlice(s) + if len(rs) < 2 { + return true + } + sort.Sort(rs) + for i, r := range rs[1:] { + if rs[i] == r { + return false + } + } + } + return true +} + +type runeSlice []rune + +func (rs runeSlice) Len() int { return len(rs) } +func (rs runeSlice) Less(i int, j int) bool { return rs[i] < rs[j] } +func (rs runeSlice) Swap(i int, j int) { rs[i], rs[j] = rs[j], rs[i] } diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1025/sa1025.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1025/sa1025.go new file mode 100644 index 000000000..9445c7d6e --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1025/sa1025.go @@ -0,0 +1,92 @@ +package sa1025 + +import ( + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1025", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `It is not possible to use \'(*time.Timer).Reset\''s return value correctly`, + Since: "2019.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, block := range fn.Blocks { + for _, ins := range block.Instrs { + call, ok := ins.(*ir.Call) + if !ok { + continue + } + if !irutil.IsCallTo(call.Common(), "(*time.Timer).Reset") { + continue + } + refs := call.Referrers() + if refs == nil { + continue + } + for _, ref := range irutil.FilterDebug(*refs) { + ifstmt, ok := ref.(*ir.If) + if !ok { + continue + } + + found := false + for _, succ := range ifstmt.Block().Succs { + if len(succ.Preds) != 1 { + // Merge point, not a branch in the + // syntactical sense. + + // FIXME(dh): this is broken for if + // statements a la "if x || y" + continue + } + irutil.Walk(succ, func(b *ir.BasicBlock) bool { + if !succ.Dominates(b) { + // We've reached the end of the branch + return false + } + for _, ins := range b.Instrs { + // TODO(dh): we should check that we're receiving from the + // channel of a time.Timer to further reduce false + // positives. Not a key priority, considering the rarity + // of Reset and the tiny likeliness of a false positive + // + // We intentionally don't handle aliases here, because + // we're only interested in time.Timer.C. + if ins, ok := ins.(*ir.Recv); ok && types.TypeString(ins.Chan.Type(), nil) == "<-chan time.Time" { + found = true + return false + } + } + return true + }) + } + + if found { + report.Report(pass, call, "it is not possible to use Reset's return value correctly, as there is a race condition between draining the channel and the new timer expiring") + } + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1026/sa1026.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1026/sa1026.go new file mode 100644 index 000000000..51ea62e5d --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1026/sa1026.go @@ -0,0 +1,77 @@ +package sa1026 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/staticcheck/fakejson" + "honnef.co/go/tools/staticcheck/fakexml" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1026", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Cannot marshal channels or functions`, + Since: "2019.2", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "encoding/json.Marshal": checkJSON, + "encoding/xml.Marshal": checkXML, + "(*encoding/json.Encoder).Encode": checkJSON, + "(*encoding/xml.Encoder).Encode": checkXML, +} + +func checkJSON(call *callcheck.Call) { + arg := call.Args[0] + T := arg.Value.Value.Type() + if err := fakejson.Marshal(T); err != nil { + typ := types.TypeString(err.Type, types.RelativeTo(arg.Value.Value.Parent().Pkg.Pkg)) + if err.Path == "x" { + arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s", typ)) + } else { + arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s, via %s", typ, err.Path)) + } + } +} + +func checkXML(call *callcheck.Call) { + arg := call.Args[0] + T := arg.Value.Value.Type() + if err := fakexml.Marshal(T); err != nil { + switch err := err.(type) { + case *fakexml.UnsupportedTypeError: + typ := types.TypeString(err.Type, types.RelativeTo(arg.Value.Value.Parent().Pkg.Pkg)) + if err.Path == "x" { + arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s", typ)) + } else { + arg.Invalid(fmt.Sprintf("trying to marshal unsupported type %s, via %s", typ, err.Path)) + } + case *fakexml.CyclicTypeError: + typ := types.TypeString(err.Type, types.RelativeTo(arg.Value.Value.Parent().Pkg.Pkg)) + if err.Path == "x" { + arg.Invalid(fmt.Sprintf("trying to marshal cyclic type %s", typ)) + } else { + arg.Invalid(fmt.Sprintf("trying to marshal cyclic type %s, via %s", typ, err.Path)) + } + case *fakexml.TagPathError: + // Vet does a better job at reporting this error, because it can flag the actual struct tags, not just the call to Marshal + default: + // These errors get reported by SA5008 instead, which can flag the actual fields, independently of calls to xml.Marshal + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1027/sa1027.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1027/sa1027.go new file mode 100644 index 000000000..95633c479 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1027/sa1027.go @@ -0,0 +1,76 @@ +package sa1027 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1027", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkAtomicAlignment), + }, + Doc: &lint.RawDocumentation{ + Title: `Atomic access to 64-bit variable must be 64-bit aligned`, + Text: `On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility to +arrange for 64-bit alignment of 64-bit words accessed atomically. The +first word in a variable or in an allocated struct, array, or slice +can be relied upon to be 64-bit aligned. + +You can use the structlayout tool to inspect the alignment of fields +in a struct.`, + Since: "2019.2", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkAtomicAlignment = map[string]callcheck.Check{ + "sync/atomic.AddInt64": checkAtomicAlignmentImpl, + "sync/atomic.AddUint64": checkAtomicAlignmentImpl, + "sync/atomic.CompareAndSwapInt64": checkAtomicAlignmentImpl, + "sync/atomic.CompareAndSwapUint64": checkAtomicAlignmentImpl, + "sync/atomic.LoadInt64": checkAtomicAlignmentImpl, + "sync/atomic.LoadUint64": checkAtomicAlignmentImpl, + "sync/atomic.StoreInt64": checkAtomicAlignmentImpl, + "sync/atomic.StoreUint64": checkAtomicAlignmentImpl, + "sync/atomic.SwapInt64": checkAtomicAlignmentImpl, + "sync/atomic.SwapUint64": checkAtomicAlignmentImpl, +} + +func checkAtomicAlignmentImpl(call *callcheck.Call) { + sizes := call.Pass.TypesSizes + if sizes.Sizeof(types.Typ[types.Uintptr]) != 4 { + // Not running on a 32-bit platform + return + } + v, ok := irutil.Flatten(call.Args[0].Value.Value).(*ir.FieldAddr) + if !ok { + // TODO(dh): also check indexing into arrays and slices + return + } + T := v.X.Type().Underlying().(*types.Pointer).Elem().Underlying().(*types.Struct) + fields := make([]*types.Var, 0, T.NumFields()) + for i := 0; i < T.NumFields() && i <= v.Field; i++ { + fields = append(fields, T.Field(i)) + } + + off := sizes.Offsetsof(fields)[v.Field] + if off%8 != 0 { + msg := fmt.Sprintf("address of non 64-bit aligned field %s passed to %s", + T.Field(v.Field).Name(), + irutil.CallName(call.Instr.Common())) + call.Invalid(msg) + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1028/sa1028.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1028/sa1028.go new file mode 100644 index 000000000..5ac1216d9 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1028/sa1028.go @@ -0,0 +1,57 @@ +package sa1028 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1028", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `\'sort.Slice\' can only be used on slices`, + Text: `The first argument of \'sort.Slice\' must be a slice.`, + Since: "2020.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "sort.Slice": check, + "sort.SliceIsSorted": check, + "sort.SliceStable": check, +} + +func check(call *callcheck.Call) { + c := call.Instr.Common().StaticCallee() + arg := call.Args[0] + + T := arg.Value.Value.Type().Underlying() + switch T.(type) { + case *types.Interface: + // we don't know. + // TODO(dh): if the value is a phi node we can look at its edges + if k, ok := arg.Value.Value.(*ir.Const); ok && k.Value == nil { + // literal nil, e.g. sort.Sort(nil, ...) + arg.Invalid(fmt.Sprintf("cannot call %s on nil literal", c)) + } + case *types.Slice: + // this is fine + default: + // this is not fine + arg.Invalid(fmt.Sprintf("%s must only be called on slices, was called on %s", c, T)) + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1029/sa1029.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1029/sa1029.go new file mode 100644 index 000000000..c981baa2a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1029/sa1029.go @@ -0,0 +1,61 @@ +package sa1029 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1029", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkWithValueKeyRules), + }, + Doc: &lint.RawDocumentation{ + Title: `Inappropriate key in call to \'context.WithValue\'`, + Text: `The provided key must be comparable and should not be +of type \'string\' or any other built-in type to avoid collisions between +packages using context. Users of \'WithValue\' should define their own +types for keys. + +To avoid allocating when assigning to an \'interface{}\', +context keys often have concrete type \'struct{}\'. Alternatively, +exported context key variables' static type should be a pointer or +interface.`, + Since: "2020.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkWithValueKeyRules = map[string]callcheck.Check{ + "context.WithValue": checkWithValueKey, +} + +func checkWithValueKey(call *callcheck.Call) { + arg := call.Args[1] + T := arg.Value.Value.Type() + if typ, ok := types.Unalias(T).(*types.Basic); ok { + if _, ok := T.(*types.Alias); ok { + arg.Invalid( + fmt.Sprintf("should not use built-in type %s (via alias %s) as key for value; define your own type to avoid collisions", typ, types.TypeString(T, types.RelativeTo(call.Pass.Pkg)))) + } else { + arg.Invalid( + fmt.Sprintf("should not use built-in type %s as key for value; define your own type to avoid collisions", typ)) + } + } + // TODO(dh): we should probably flag all anonymous structs, as they all risk collisions + if s, ok := T.(*types.Struct); ok && s.NumFields() == 0 { + arg.Invalid("should not use empty anonymous struct as key for value; define your own type to avoid collisions") + } else if !types.Comparable(T) { + arg.Invalid(fmt.Sprintf("keys used with context.WithValue must be comparable, but type %s is not comparable", T)) + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1030/sa1030.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1030/sa1030.go new file mode 100644 index 000000000..1a274ce1a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1030/sa1030.go @@ -0,0 +1,134 @@ +package sa1030 + +import ( + "fmt" + "go/constant" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1030", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Invalid argument in call to a \'strconv\' function`, + Text: `This check validates the format, number base and bit size arguments of +the various parsing and formatting functions in \'strconv\'.`, + Since: "2021.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "strconv.ParseComplex": func(call *callcheck.Call) { + validateComplexBitSize(call.Args[knowledge.Arg("strconv.ParseComplex.bitSize")]) + }, + "strconv.ParseFloat": func(call *callcheck.Call) { + validateFloatBitSize(call.Args[knowledge.Arg("strconv.ParseFloat.bitSize")]) + }, + "strconv.ParseInt": func(call *callcheck.Call) { + validateContinuousBitSize(call.Args[knowledge.Arg("strconv.ParseInt.bitSize")], 0, 64) + validateIntBaseAllowZero(call.Args[knowledge.Arg("strconv.ParseInt.base")]) + }, + "strconv.ParseUint": func(call *callcheck.Call) { + validateContinuousBitSize(call.Args[knowledge.Arg("strconv.ParseUint.bitSize")], 0, 64) + validateIntBaseAllowZero(call.Args[knowledge.Arg("strconv.ParseUint.base")]) + }, + + "strconv.FormatComplex": func(call *callcheck.Call) { + validateComplexFormat(call.Args[knowledge.Arg("strconv.FormatComplex.fmt")]) + validateComplexBitSize(call.Args[knowledge.Arg("strconv.FormatComplex.bitSize")]) + }, + "strconv.FormatFloat": func(call *callcheck.Call) { + validateFloatFormat(call.Args[knowledge.Arg("strconv.FormatFloat.fmt")]) + validateFloatBitSize(call.Args[knowledge.Arg("strconv.FormatFloat.bitSize")]) + }, + "strconv.FormatInt": func(call *callcheck.Call) { + validateIntBase(call.Args[knowledge.Arg("strconv.FormatInt.base")]) + }, + "strconv.FormatUint": func(call *callcheck.Call) { + validateIntBase(call.Args[knowledge.Arg("strconv.FormatUint.base")]) + }, + + "strconv.AppendFloat": func(call *callcheck.Call) { + validateFloatFormat(call.Args[knowledge.Arg("strconv.AppendFloat.fmt")]) + validateFloatBitSize(call.Args[knowledge.Arg("strconv.AppendFloat.bitSize")]) + }, + "strconv.AppendInt": func(call *callcheck.Call) { + validateIntBase(call.Args[knowledge.Arg("strconv.AppendInt.base")]) + }, + "strconv.AppendUint": func(call *callcheck.Call) { + validateIntBase(call.Args[knowledge.Arg("strconv.AppendUint.base")]) + }, +} + +func validateDiscreetBitSize(arg *callcheck.Argument, size1 int, size2 int) { + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.Int); c != nil { + val, _ := constant.Int64Val(c.Value) + if val != int64(size1) && val != int64(size2) { + arg.Invalid(fmt.Sprintf("'bitSize' argument is invalid, must be either %d or %d", size1, size2)) + } + } +} + +func validateComplexBitSize(arg *callcheck.Argument) { validateDiscreetBitSize(arg, 64, 128) } +func validateFloatBitSize(arg *callcheck.Argument) { validateDiscreetBitSize(arg, 32, 64) } + +func validateContinuousBitSize(arg *callcheck.Argument, min int, max int) { + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.Int); c != nil { + val, _ := constant.Int64Val(c.Value) + if val < int64(min) || val > int64(max) { + arg.Invalid(fmt.Sprintf("'bitSize' argument is invalid, must be within %d and %d", min, max)) + } + } +} + +func validateIntBase(arg *callcheck.Argument) { + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.Int); c != nil { + val, _ := constant.Int64Val(c.Value) + if val < 2 { + arg.Invalid("'base' must not be smaller than 2") + } + if val > 36 { + arg.Invalid("'base' must not be larger than 36") + } + } +} + +func validateIntBaseAllowZero(arg *callcheck.Argument) { + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.Int); c != nil { + val, _ := constant.Int64Val(c.Value) + if val < 2 && val != 0 { + arg.Invalid("'base' must not be smaller than 2, unless it is 0") + } + if val > 36 { + arg.Invalid("'base' must not be larger than 36") + } + } +} + +func validateComplexFormat(arg *callcheck.Argument) { + validateFloatFormat(arg) +} + +func validateFloatFormat(arg *callcheck.Argument) { + if c := callcheck.ExtractConstExpectKind(arg.Value, constant.Int); c != nil { + val, _ := constant.Int64Val(c.Value) + switch val { + case 'b', 'e', 'E', 'f', 'g', 'G', 'x', 'X': + default: + arg.Invalid(fmt.Sprintf("'fmt' argument is invalid: unknown format %q", val)) + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1031/sa1031.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1031/sa1031.go new file mode 100644 index 000000000..52ba4dcda --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1031/sa1031.go @@ -0,0 +1,81 @@ +package sa1031 + +import ( + "go/constant" + "go/token" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1031", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkEncodeRules), + }, + Doc: &lint.RawDocumentation{ + Title: `Overlapping byte slices passed to an encoder`, + Text: `In an encoding function of the form \'Encode(dst, src)\', \'dst\' and +\'src\' were found to reference the same memory. This can result in +\'src\' bytes being overwritten before they are read, when the encoder +writes more than one byte per \'src\' byte.`, + Since: "2024.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkEncodeRules = map[string]callcheck.Check{ + "encoding/ascii85.Encode": checkNonOverlappingDstSrc(knowledge.Arg("encoding/ascii85.Encode.dst"), knowledge.Arg("encoding/ascii85.Encode.src")), + "(*encoding/base32.Encoding).Encode": checkNonOverlappingDstSrc(knowledge.Arg("(*encoding/base32.Encoding).Encode.dst"), knowledge.Arg("(*encoding/base32.Encoding).Encode.src")), + "(*encoding/base64.Encoding).Encode": checkNonOverlappingDstSrc(knowledge.Arg("(*encoding/base64.Encoding).Encode.dst"), knowledge.Arg("(*encoding/base64.Encoding).Encode.src")), + "encoding/hex.Encode": checkNonOverlappingDstSrc(knowledge.Arg("encoding/hex.Encode.dst"), knowledge.Arg("encoding/hex.Encode.src")), +} + +func checkNonOverlappingDstSrc(dstArg, srcArg int) callcheck.Check { + return func(call *callcheck.Call) { + dst := call.Args[dstArg] + src := call.Args[srcArg] + _, dstConst := irutil.Flatten(dst.Value.Value).(*ir.Const) + _, srcConst := irutil.Flatten(src.Value.Value).(*ir.Const) + if dstConst || srcConst { + // one of the arguments is nil, therefore overlap is not possible + return + } + if dst.Value == src.Value { + // simple case of f(b, b) + dst.Invalid("overlapping dst and src") + return + } + dstSlice, ok := irutil.Flatten(dst.Value.Value).(*ir.Slice) + if !ok { + return + } + srcSlice, ok := irutil.Flatten(src.Value.Value).(*ir.Slice) + if !ok { + return + } + if irutil.Flatten(dstSlice.X) != irutil.Flatten(srcSlice.X) { + // differing underlying arrays, all is well + return + } + l1 := irutil.Flatten(dstSlice.Low) + l2 := irutil.Flatten(srcSlice.Low) + c1, ok1 := l1.(*ir.Const) + c2, ok2 := l2.(*ir.Const) + if l1 == l2 || (ok1 && ok2 && constant.Compare(c1.Value, token.EQL, c2.Value)) { + // dst and src are the same slice, and have the same lower bound + dst.Invalid("overlapping dst and src") + return + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa1032/sa1032.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa1032/sa1032.go new file mode 100644 index 000000000..2ea603861 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa1032/sa1032.go @@ -0,0 +1,79 @@ +package sa1032 + +import ( + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA1032", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Wrong order of arguments to \'errors.Is\'`, + Text: ` +The first argument of the function \'errors.Is\' is the error +that we have and the second argument is the error we're trying to match against. +For example: + + if errors.Is(err, io.EOF) { ... } + +This check detects some cases where the two arguments have been swapped. It +flags any calls where the first argument is referring to a package-level error +variable, such as + + if errors.Is(io.EOF, err) { /* this is wrong */ }`, + Since: "2024.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "errors.Is": validateIs, +} + +func validateIs(call *callcheck.Call) { + if len(call.Args) != 2 { + return + } + + global := func(arg *callcheck.Argument) *ir.Global { + v, ok := arg.Value.Value.(*ir.Load) + if !ok { + return nil + } + g, _ := v.X.(*ir.Global) + return g + } + + x, y := call.Args[0], call.Args[1] + gx := global(x) + if gx == nil { + return + } + + if pkgx := gx.Package().Pkg; pkgx != nil && pkgx.Path() != call.Pass.Pkg.Path() { + // x is a global that's not in this package + + if gy := global(y); gy != nil { + if pkgy := gy.Package().Pkg; pkgy != nil && pkgy.Path() != call.Pass.Pkg.Path() { + // Both arguments refer to globals that aren't in this package. This can + // genuinely happen for external tests that check that one error "is" + // another one. net/http's external tests, for example, do + // `errors.Is(http.ErrNotSupported, errors.ErrUnsupported)`. + return + } + } + + call.Invalid("arguments have the wrong order") + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa2000/sa2000.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa2000/sa2000.go new file mode 100644 index 000000000..2de4f5626 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa2000/sa2000.go @@ -0,0 +1,48 @@ +package sa2000 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA2000", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'sync.WaitGroup.Add\' called inside the goroutine, leading to a race condition`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkWaitgroupAddQ = pattern.MustParse(` + (GoStmt + (CallExpr + (FuncLit + _ + call@(CallExpr (Symbol "(*sync.WaitGroup).Add") _):_) _))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if m, ok := code.Match(pass, checkWaitgroupAddQ, node); ok { + call := m.State["call"].(ast.Node) + report.Report(pass, call, fmt.Sprintf("should call %s before starting the goroutine to avoid a race", report.Render(pass, call))) + } + } + code.Preorder(pass, fn, (*ast.GoStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa2001/sa2001.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa2001/sa2001.go new file mode 100644 index 000000000..21ca99c61 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa2001/sa2001.go @@ -0,0 +1,111 @@ +package sa2001 + +import ( + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ast/astutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA2001", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Empty critical section, did you mean to defer the unlock?`, + Text: `Empty critical sections of the kind + + mu.Lock() + mu.Unlock() + +are very often a typo, and the following was intended instead: + + mu.Lock() + defer mu.Unlock() + +Do note that sometimes empty critical sections can be useful, as a +form of signaling to wait on another goroutine. Many times, there are +simpler ways of achieving the same effect. When that isn't the case, +the code should be amply commented to avoid confusion. Combining such +comments with a \'//lint:ignore\' directive can be used to suppress this +rare false positive.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + if pass.Pkg.Path() == "sync_test" { + // exception for the sync package's tests + return nil, nil + } + + // Initially it might seem like this check would be easier to + // implement using IR. After all, we're only checking for two + // consecutive method calls. In reality, however, there may be any + // number of other instructions between the lock and unlock, while + // still constituting an empty critical section. For example, + // given `m.x().Lock(); m.x().Unlock()`, there will be a call to + // x(). In the AST-based approach, this has a tiny potential for a + // false positive (the second call to x might be doing work that + // is protected by the mutex). In an IR-based approach, however, + // it would miss a lot of real bugs. + + mutexParams := func(s ast.Stmt) (x ast.Expr, funcName string, ok bool) { + expr, ok := s.(*ast.ExprStmt) + if !ok { + return nil, "", false + } + call, ok := astutil.Unparen(expr.X).(*ast.CallExpr) + if !ok { + return nil, "", false + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return nil, "", false + } + + fn, ok := pass.TypesInfo.ObjectOf(sel.Sel).(*types.Func) + if !ok { + return nil, "", false + } + sig := fn.Type().(*types.Signature) + if sig.Params().Len() != 0 || sig.Results().Len() != 0 { + return nil, "", false + } + + return sel.X, fn.Name(), true + } + + fn := func(node ast.Node) { + block := node.(*ast.BlockStmt) + if len(block.List) < 2 { + return + } + for i := range block.List[:len(block.List)-1] { + sel1, method1, ok1 := mutexParams(block.List[i]) + sel2, method2, ok2 := mutexParams(block.List[i+1]) + + if !ok1 || !ok2 || report.Render(pass, sel1) != report.Render(pass, sel2) { + continue + } + if (method1 == "Lock" && method2 == "Unlock") || + (method1 == "RLock" && method2 == "RUnlock") { + report.Report(pass, block.List[i+1], "empty critical section") + } + } + } + code.Preorder(pass, fn, (*ast.BlockStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa2002/sa2002.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa2002/sa2002.go new file mode 100644 index 000000000..1f3eefadd --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa2002/sa2002.go @@ -0,0 +1,93 @@ +package sa2002 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA2002", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Called \'testing.T.FailNow\' or \'SkipNow\' in a goroutine, which isn't allowed`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, block := range fn.Blocks { + for _, ins := range block.Instrs { + gostmt, ok := ins.(*ir.Go) + if !ok { + continue + } + var fn *ir.Function + switch val := gostmt.Call.Value.(type) { + case *ir.Function: + fn = val + case *ir.MakeClosure: + fn = val.Fn.(*ir.Function) + default: + continue + } + if fn.Blocks == nil { + continue + } + for _, block := range fn.Blocks { + for _, ins := range block.Instrs { + call, ok := ins.(*ir.Call) + if !ok { + continue + } + if call.Call.IsInvoke() { + continue + } + callee := call.Call.StaticCallee() + if callee == nil { + continue + } + recv := callee.Signature.Recv() + if recv == nil { + continue + } + if !typeutil.IsPointerToTypeWithName(recv.Type(), "testing.common") { + continue + } + fn, ok := call.Call.StaticCallee().Object().(*types.Func) + if !ok { + continue + } + name := fn.Name() + switch name { + case "FailNow", "Fatal", "Fatalf", "SkipNow", "Skip", "Skipf": + default: + continue + } + // TODO(dh): don't report multiple diagnostics + // for multiple calls to T.Fatal, but do + // collect all of them as related information + report.Report(pass, gostmt, fmt.Sprintf("the goroutine calls T.%s, which must be called in the same goroutine as the test", name), + report.Related(call, fmt.Sprintf("call to T.%s", name))) + } + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa2003/sa2003.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa2003/sa2003.go new file mode 100644 index 000000000..9085d3052 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa2003/sa2003.go @@ -0,0 +1,87 @@ +package sa2003 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA2003", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Deferred \'Lock\' right after locking, likely meant to defer \'Unlock\' instead`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, block := range fn.Blocks { + instrs := irutil.FilterDebug(block.Instrs) + if len(instrs) < 2 { + continue + } + for i, ins := range instrs[:len(instrs)-1] { + call, ok := ins.(*ir.Call) + if !ok { + continue + } + if !irutil.IsCallToAny(call.Common(), "(*sync.Mutex).Lock", "(*sync.RWMutex).RLock") { + continue + } + nins, ok := instrs[i+1].(*ir.Defer) + if !ok { + continue + } + if !irutil.IsCallToAny(&nins.Call, "(*sync.Mutex).Lock", "(*sync.RWMutex).RLock") { + continue + } + if call.Common().Args[0] != nins.Call.Args[0] { + continue + } + name := shortCallName(call.Common()) + alt := "" + switch name { + case "Lock": + alt = "Unlock" + case "RLock": + alt = "RUnlock" + } + report.Report(pass, nins, fmt.Sprintf("deferring %s right after having locked already; did you mean to defer %s?", name, alt)) + } + } + } + return nil, nil +} + +func shortCallName(call *ir.CallCommon) string { + if call.IsInvoke() { + return "" + } + switch v := call.Value.(type) { + case *ir.Function: + fn, ok := v.Object().(*types.Func) + if !ok { + return "" + } + return fn.Name() + case *ir.Builtin: + return v.Name() + } + return "" +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa3000/sa3000.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa3000/sa3000.go new file mode 100644 index 000000000..2f1106065 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa3000/sa3000.go @@ -0,0 +1,118 @@ +package sa3000 + +import ( + "go/ast" + "go/types" + "go/version" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA3000", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'TestMain\' doesn't call \'os.Exit\', hiding test failures`, + Text: `Test executables (and in turn \"go test\") exit with a non-zero status +code if any tests failed. When specifying your own \'TestMain\' function, +it is your responsibility to arrange for this, by calling \'os.Exit\' with +the correct code. The correct code is returned by \'(*testing.M).Run\', so +the usual way of implementing \'TestMain\' is to end it with +\'os.Exit(m.Run())\'.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + var ( + fnmain ast.Node + callsExit bool + callsRun bool + arg types.Object + ) + fn := func(node ast.Node, push bool) bool { + if !push { + if fnmain != nil && node == fnmain { + if !callsExit && callsRun { + report.Report(pass, fnmain, "TestMain should call os.Exit to set exit code") + } + fnmain = nil + callsExit = false + callsRun = false + arg = nil + } + return true + } + + switch node := node.(type) { + case *ast.FuncDecl: + if fnmain != nil { + return true + } + if !isTestMain(pass, node) { + return false + } + if version.Compare(code.StdlibVersion(pass, node), "go1.15") >= 0 { + // Beginning with Go 1.15, the test framework will call + // os.Exit for us. + return false + } + fnmain = node + arg = pass.TypesInfo.ObjectOf(node.Type.Params.List[0].Names[0]) + return true + case *ast.CallExpr: + if code.IsCallTo(pass, node, "os.Exit") { + callsExit = true + return false + } + sel, ok := node.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + ident, ok := sel.X.(*ast.Ident) + if !ok { + return true + } + if arg != pass.TypesInfo.ObjectOf(ident) { + return true + } + if sel.Sel.Name == "Run" { + callsRun = true + return false + } + return true + default: + lint.ExhaustiveTypeSwitch(node) + return true + } + } + pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.FuncDecl)(nil), (*ast.CallExpr)(nil)}, fn) + return nil, nil +} + +func isTestMain(pass *analysis.Pass, decl *ast.FuncDecl) bool { + if decl.Name.Name != "TestMain" { + return false + } + if len(decl.Type.Params.List) != 1 { + return false + } + arg := decl.Type.Params.List[0] + if len(arg.Names) != 1 { + return false + } + return code.IsOfPointerToTypeWithName(pass, arg.Type, "testing.M") +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa3001/sa3001.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa3001/sa3001.go new file mode 100644 index 000000000..c51f179e3 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa3001/sa3001.go @@ -0,0 +1,55 @@ +package sa3001 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA3001", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Assigning to \'b.N\' in benchmarks distorts the results`, + Text: `The testing package dynamically sets \'b.N\' to improve the reliability of +benchmarks and uses it in computations to determine the duration of a +single operation. Benchmark code must not alter \'b.N\' as this would +falsify results.`, + Since: "2017.1", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + assign := node.(*ast.AssignStmt) + if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { + return + } + sel, ok := assign.Lhs[0].(*ast.SelectorExpr) + if !ok { + return + } + if sel.Sel.Name != "N" { + return + } + if !code.IsOfPointerToTypeWithName(pass, sel.X, "testing.B") { + return + } + report.Report(pass, assign, fmt.Sprintf("should not assign to %s", report.Render(pass, sel))) + } + code.Preorder(pass, fn, (*ast.AssignStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4000/sa4000.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4000/sa4000.go new file mode 100644 index 000000000..577bc3938 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4000/sa4000.go @@ -0,0 +1,146 @@ +package sa4000 + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "reflect" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4000", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Binary operator has identical expressions on both sides`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + var isFloat func(T types.Type) bool + isFloat = func(T types.Type) bool { + tset := typeutil.NewTypeSet(T) + if len(tset.Terms) == 0 { + // no terms, so floats are a possibility + return true + } + return tset.Any(func(term *types.Term) bool { + switch typ := term.Type().Underlying().(type) { + case *types.Basic: + kind := typ.Kind() + return kind == types.Float32 || kind == types.Float64 + case *types.Array: + return isFloat(typ.Elem()) + case *types.Struct: + for i := 0; i < typ.NumFields(); i++ { + if !isFloat(typ.Field(i).Type()) { + return false + } + } + return true + default: + return false + } + }) + } + + // TODO(dh): this check ignores the existence of side-effects and + // happily flags fn() == fn() – so far, we've had nobody complain + // about a false positive, and it's caught several bugs in real + // code. + // + // We special case functions from the math/rand package. Someone ran + // into the following false positive: "rand.Intn(2) - rand.Intn(2), which I wrote to generate values {-1, 0, 1} with {0.25, 0.5, 0.25} probability." + fn := func(node ast.Node) { + op := node.(*ast.BinaryExpr) + switch op.Op { + case token.EQL, token.NEQ: + case token.SUB, token.QUO, token.AND, token.REM, token.OR, token.XOR, token.AND_NOT, + token.LAND, token.LOR, token.LSS, token.GTR, token.LEQ, token.GEQ: + default: + // For some ops, such as + and *, it can make sense to + // have identical operands + return + } + + if isFloat(pass.TypesInfo.TypeOf(op.X)) { + // 'float float' makes sense for several operators. + // We've tried keeping an exact list of operators to allow, but floats keep surprising us. Let's just give up instead. + return + } + + if reflect.TypeOf(op.X) != reflect.TypeOf(op.Y) { + return + } + if report.Render(pass, op.X) != report.Render(pass, op.Y) { + return + } + l1, ok1 := op.X.(*ast.BasicLit) + l2, ok2 := op.Y.(*ast.BasicLit) + if ok1 && ok2 && l1.Kind == token.INT && l2.Kind == l1.Kind && l1.Value == "0" && l2.Value == l1.Value && code.IsGenerated(pass, l1.Pos()) { + // cgo generates the following function call: + // _cgoCheckPointer(_cgoBase0, 0 == 0) – it uses 0 == 0 + // instead of true in case the user shadowed the + // identifier. Ideally we'd restrict this exception to + // calls of _cgoCheckPointer, but it's not worth the + // hassle of keeping track of the stack. + // are very rare to begin with, and we're mostly checking + // for them to catch typos such as 1 == 1 where the user + // meant to type i == 1. The odds of a false negative for + // 0 == 0 are slim. + return + } + + if expr, ok := op.X.(*ast.CallExpr); ok { + call := code.CallName(pass, expr) + switch call { + case "math/rand.Int", + "math/rand.Int31", + "math/rand.Int31n", + "math/rand.Int63", + "math/rand.Int63n", + "math/rand.Intn", + "math/rand.Uint32", + "math/rand.Uint64", + "math/rand.ExpFloat64", + "math/rand.Float32", + "math/rand.Float64", + "math/rand.NormFloat64", + "(*math/rand.Rand).Int", + "(*math/rand.Rand).Int31", + "(*math/rand.Rand).Int31n", + "(*math/rand.Rand).Int63", + "(*math/rand.Rand).Int63n", + "(*math/rand.Rand).Intn", + "(*math/rand.Rand).Uint32", + "(*math/rand.Rand).Uint64", + "(*math/rand.Rand).ExpFloat64", + "(*math/rand.Rand).Float32", + "(*math/rand.Rand).Float64", + "(*math/rand.Rand).NormFloat64": + return + } + } + + report.Report(pass, op, fmt.Sprintf("identical expressions on the left and right side of the '%s' operator", op.Op)) + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4001/sa4001.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4001/sa4001.go new file mode 100644 index 000000000..63e527f6a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4001/sa4001.go @@ -0,0 +1,52 @@ +package sa4001 + +import ( + "go/ast" + "regexp" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4001", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'&*x\' gets simplified to \'x\', it does not copy \'x\'`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + // cgo produces code like fn(&*_Cvar_kSomeCallbacks) which we don't + // want to flag. + cgoIdent = regexp.MustCompile(`^_C(func|var)_.+$`) + checkIneffectiveCopyQ1 = pattern.MustParse(`(UnaryExpr "&" (StarExpr obj))`) + checkIneffectiveCopyQ2 = pattern.MustParse(`(StarExpr (UnaryExpr "&" _))`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if m, ok := code.Match(pass, checkIneffectiveCopyQ1, node); ok { + if ident, ok := m.State["obj"].(*ast.Ident); !ok || !cgoIdent.MatchString(ident.Name) { + report.Report(pass, node, "&*x will be simplified to x. It will not copy x.") + } + } else if _, ok := code.Match(pass, checkIneffectiveCopyQ2, node); ok { + report.Report(pass, node, "*&x will be simplified to x. It will not copy x.") + } + } + code.Preorder(pass, fn, (*ast.UnaryExpr)(nil), (*ast.StarExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4003/sa4003.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4003/sa4003.go new file mode 100644 index 000000000..033ee3a6c --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4003/sa4003.go @@ -0,0 +1,159 @@ +package sa4003 + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + "math" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4003", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Comparing unsigned values against negative values is pointless`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + isobj := func(expr ast.Expr, name string) bool { + if name == "" { + return false + } + sel, ok := expr.(*ast.SelectorExpr) + if !ok { + return false + } + return typeutil.IsObject(pass.TypesInfo.ObjectOf(sel.Sel), name) + } + + fn := func(node ast.Node) { + expr := node.(*ast.BinaryExpr) + tx := pass.TypesInfo.TypeOf(expr.X) + basic, ok := tx.Underlying().(*types.Basic) + if !ok { + return + } + + // We only check for the math constants and integer literals, not for all constant expressions. This is to avoid + // false positives when constant values differ under different build tags. + var ( + maxMathConst string + minMathConst string + maxLiteral constant.Value + minLiteral constant.Value + ) + + switch basic.Kind() { + case types.Uint8: + maxMathConst = "math.MaxUint8" + minLiteral = constant.MakeUint64(0) + maxLiteral = constant.MakeUint64(math.MaxUint8) + case types.Uint16: + maxMathConst = "math.MaxUint16" + minLiteral = constant.MakeUint64(0) + maxLiteral = constant.MakeUint64(math.MaxUint16) + case types.Uint32: + maxMathConst = "math.MaxUint32" + minLiteral = constant.MakeUint64(0) + maxLiteral = constant.MakeUint64(math.MaxUint32) + case types.Uint64: + maxMathConst = "math.MaxUint64" + minLiteral = constant.MakeUint64(0) + maxLiteral = constant.MakeUint64(math.MaxUint64) + case types.Uint: + // TODO(dh): we could chose 32 bit vs 64 bit depending on the file's build tags + maxMathConst = "math.MaxUint64" + minLiteral = constant.MakeUint64(0) + maxLiteral = constant.MakeUint64(math.MaxUint64) + + case types.Int8: + minMathConst = "math.MinInt8" + maxMathConst = "math.MaxInt8" + minLiteral = constant.MakeInt64(math.MinInt8) + maxLiteral = constant.MakeInt64(math.MaxInt8) + case types.Int16: + minMathConst = "math.MinInt16" + maxMathConst = "math.MaxInt16" + minLiteral = constant.MakeInt64(math.MinInt16) + maxLiteral = constant.MakeInt64(math.MaxInt16) + case types.Int32: + minMathConst = "math.MinInt32" + maxMathConst = "math.MaxInt32" + minLiteral = constant.MakeInt64(math.MinInt32) + maxLiteral = constant.MakeInt64(math.MaxInt32) + case types.Int64: + minMathConst = "math.MinInt64" + maxMathConst = "math.MaxInt64" + minLiteral = constant.MakeInt64(math.MinInt64) + maxLiteral = constant.MakeInt64(math.MaxInt64) + case types.Int: + // TODO(dh): we could chose 32 bit vs 64 bit depending on the file's build tags + minMathConst = "math.MinInt64" + maxMathConst = "math.MaxInt64" + minLiteral = constant.MakeInt64(math.MinInt64) + maxLiteral = constant.MakeInt64(math.MaxInt64) + } + + isLiteral := func(expr ast.Expr, c constant.Value) bool { + if c == nil { + return false + } + return code.IsIntegerLiteral(pass, expr, c) + } + isZeroLiteral := func(expr ast.Expr) bool { + return code.IsIntegerLiteral(pass, expr, constant.MakeInt64(0)) + } + + if (expr.Op == token.GTR || expr.Op == token.GEQ) && (isobj(expr.Y, maxMathConst) || isLiteral(expr.Y, maxLiteral)) || + (expr.Op == token.LSS || expr.Op == token.LEQ) && (isobj(expr.X, maxMathConst) || isLiteral(expr.X, maxLiteral)) { + report.Report(pass, expr, fmt.Sprintf("no value of type %s is greater than %s", basic, maxMathConst)) + } + + if expr.Op == token.LEQ && (isobj(expr.Y, maxMathConst) || isLiteral(expr.Y, maxLiteral)) || + expr.Op == token.GEQ && (isobj(expr.X, maxMathConst) || isLiteral(expr.X, maxLiteral)) { + report.Report(pass, expr, fmt.Sprintf("every value of type %s is <= %s", basic, maxMathConst)) + } + + if (basic.Info() & types.IsUnsigned) != 0 { + if (expr.Op == token.LSS && isZeroLiteral(expr.Y)) || + (expr.Op == token.GTR && isZeroLiteral(expr.X)) { + report.Report(pass, expr, fmt.Sprintf("no value of type %s is less than 0", basic)) + } + if expr.Op == token.GEQ && isZeroLiteral(expr.Y) || + expr.Op == token.LEQ && isZeroLiteral(expr.X) { + report.Report(pass, expr, fmt.Sprintf("every value of type %s is >= 0", basic)) + } + } else { + if (expr.Op == token.LSS || expr.Op == token.LEQ) && (isobj(expr.Y, minMathConst) || isLiteral(expr.Y, minLiteral)) || + (expr.Op == token.GTR || expr.Op == token.GEQ) && (isobj(expr.X, minMathConst) || isLiteral(expr.X, minLiteral)) { + report.Report(pass, expr, fmt.Sprintf("no value of type %s is less than %s", basic, minMathConst)) + } + if expr.Op == token.GEQ && (isobj(expr.Y, minMathConst) || isLiteral(expr.Y, minLiteral)) || + expr.Op == token.LEQ && (isobj(expr.X, minMathConst) || isLiteral(expr.X, minLiteral)) { + report.Report(pass, expr, fmt.Sprintf("every value of type %s is >= %s", basic, minMathConst)) + } + } + + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4004/sa4004.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4004/sa4004.go new file mode 100644 index 000000000..e38f9f3ee --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4004/sa4004.go @@ -0,0 +1,159 @@ +package sa4004 + +import ( + "go/ast" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4004", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `The loop exits unconditionally after one iteration`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // This check detects some, but not all unconditional loop exits. + // We give up in the following cases: + // + // - a goto anywhere in the loop. The goto might skip over our + // return, and we don't check that it doesn't. + // + // - any nested, unlabelled continue, even if it is in another + // loop or closure. + fn := func(node ast.Node) { + var body *ast.BlockStmt + switch fn := node.(type) { + case *ast.FuncDecl: + body = fn.Body + case *ast.FuncLit: + body = fn.Body + default: + lint.ExhaustiveTypeSwitch(node) + } + if body == nil { + return + } + labels := map[types.Object]ast.Stmt{} + ast.Inspect(body, func(node ast.Node) bool { + label, ok := node.(*ast.LabeledStmt) + if !ok { + return true + } + labels[pass.TypesInfo.ObjectOf(label.Label)] = label.Stmt + return true + }) + + ast.Inspect(body, func(node ast.Node) bool { + var loop ast.Node + var body *ast.BlockStmt + switch node := node.(type) { + case *ast.ForStmt: + body = node.Body + loop = node + case *ast.RangeStmt: + ok := typeutil.All(pass.TypesInfo.TypeOf(node.X), func(term *types.Term) bool { + switch term.Type().Underlying().(type) { + case *types.Slice, *types.Chan, *types.Basic, *types.Pointer, *types.Array: + return true + case *types.Map: + // looping once over a map is a valid pattern for + // getting an arbitrary element. + return false + case *types.Signature: + // we have no idea what semantics the function implements + return false + default: + lint.ExhaustiveTypeSwitch(term.Type().Underlying()) + return false + } + }) + if !ok { + return true + } + body = node.Body + loop = node + default: + return true + } + if len(body.List) < 2 { + // TODO(dh): is this check needed? when body.List < 2, + // then we can't find both an unconditional exit and a + // branching statement (if, ...). and we don't flag + // unconditional exits if there has been no branching + // in the loop body. + + // avoid flagging the somewhat common pattern of using + // a range loop to get the first element in a slice, + // or the first rune in a string. + return true + } + var unconditionalExit ast.Node + hasBranching := false + for _, stmt := range body.List { + switch stmt := stmt.(type) { + case *ast.BranchStmt: + switch stmt.Tok { + case token.BREAK: + if stmt.Label == nil || labels[pass.TypesInfo.ObjectOf(stmt.Label)] == loop { + unconditionalExit = stmt + } + case token.CONTINUE: + if stmt.Label == nil || labels[pass.TypesInfo.ObjectOf(stmt.Label)] == loop { + unconditionalExit = nil + return false + } + } + case *ast.ReturnStmt: + unconditionalExit = stmt + case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt: + hasBranching = true + } + } + if unconditionalExit == nil || !hasBranching { + return false + } + ast.Inspect(body, func(node ast.Node) bool { + if branch, ok := node.(*ast.BranchStmt); ok { + + switch branch.Tok { + case token.GOTO: + unconditionalExit = nil + return false + case token.CONTINUE: + if branch.Label != nil && labels[pass.TypesInfo.ObjectOf(branch.Label)] != loop { + return true + } + unconditionalExit = nil + return false + } + } + return true + }) + if unconditionalExit != nil { + report.Report(pass, unconditionalExit, "the surrounding loop is unconditionally terminated") + } + return true + }) + } + code.Preorder(pass, fn, (*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4005/sa4005.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4005/sa4005.go new file mode 100644 index 000000000..fc1d78c8c --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4005/sa4005.go @@ -0,0 +1,138 @@ +package sa4005 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4005", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Field assignment that will never be observed. Did you mean to use a pointer receiver?`, + Since: "2021.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // The analysis only considers the receiver and its first level + // fields. It doesn't look at other parameters, nor at nested + // fields. + // + // The analysis does not detect all kinds of dead stores, only + // those of fields that are never read after the write. That is, + // we do not flag 'a.x = 1; a.x = 2; _ = a.x'. We might explore + // this again if we add support for SROA to go/ir and implement + // https://github.com/dominikh/go-tools/issues/191. + + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR) +fnLoop: + for _, fn := range irpkg.SrcFuncs { + if recv := fn.Signature.Recv(); recv == nil { + continue + } else if _, ok := recv.Type().Underlying().(*types.Struct); !ok { + continue + } + + recv := fn.Params[0] + refs := irutil.FilterDebug(*recv.Referrers()) + if len(refs) != 1 { + continue + } + store, ok := refs[0].(*ir.Store) + if !ok { + continue + } + alloc, ok := store.Addr.(*ir.Alloc) + if !ok || alloc.Heap { + continue + } + + reads := map[int][]ir.Instruction{} + writes := map[int][]ir.Instruction{} + for _, ref := range *alloc.Referrers() { + switch ref := ref.(type) { + case *ir.FieldAddr: + for _, refref := range *ref.Referrers() { + switch refref.(type) { + case *ir.Store: + writes[ref.Field] = append(writes[ref.Field], refref) + case *ir.Load: + reads[ref.Field] = append(reads[ref.Field], refref) + case *ir.DebugRef: + continue + default: + // this should be safe… if the field address + // escapes, then alloc.Heap will be true. + // there should be no instructions left that, + // given this FieldAddr, without escaping, can + // effect a load or store. + continue + } + } + case *ir.Store: + // we could treat this as a store to every field, but + // we don't want to decide the semantics of partial + // struct initializers. should `v = t{x: 1}` also mark + // v.y as being written to? + if ref != store { + continue fnLoop + } + case *ir.Load: + // a load of the entire struct loads every field + for i := 0; i < recv.Type().Underlying().(*types.Struct).NumFields(); i++ { + reads[i] = append(reads[i], ref) + } + case *ir.DebugRef: + continue + default: + continue fnLoop + } + } + + offset := func(instr ir.Instruction) int { + for i, other := range instr.Block().Instrs { + if instr == other { + return i + } + } + panic("couldn't find instruction in its block") + } + + for field, ws := range writes { + rs := reads[field] + wLoop: + for _, w := range ws { + for _, r := range rs { + if w.Block() == r.Block() { + if offset(r) > offset(w) { + // found a reachable read of our write + continue wLoop + } + } else if irutil.Reachable(w.Block(), r.Block()) { + // found a reachable read of our write + continue wLoop + } + } + fieldName := recv.Type().Underlying().(*types.Struct).Field(field).Name() + report.Report(pass, w, fmt.Sprintf("ineffective assignment to field %s.%s", recv.Type().(interface{ Obj() *types.TypeName }).Obj().Name(), fieldName)) + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4006/sa4006.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4006/sa4006.go new file mode 100644 index 000000000..e980434a4 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4006/sa4006.go @@ -0,0 +1,155 @@ +package sa4006 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4006", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `A value assigned to a variable is never read before being overwritten. Forgotten error check or dead code?`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + if irutil.IsExample(fn) { + continue + } + node := fn.Source() + if node == nil { + continue + } + if gen, ok := code.Generator(pass, node.Pos()); ok && gen == generated.Goyacc { + // Don't flag unused values in code generated by goyacc. + // There may be hundreds of those due to the way the state + // machine is constructed. + continue + } + + switchTags := map[ir.Value]struct{}{} + ast.Inspect(node, func(node ast.Node) bool { + s, ok := node.(*ast.SwitchStmt) + if !ok { + return true + } + v, _ := fn.ValueForExpr(s.Tag) + switchTags[v] = struct{}{} + return true + }) + + // OPT(dh): don't use a map, possibly use a bitset + var hasUse func(v ir.Value, seen map[ir.Value]struct{}) bool + hasUse = func(v ir.Value, seen map[ir.Value]struct{}) bool { + if _, ok := seen[v]; ok { + return false + } + if _, ok := switchTags[v]; ok { + return true + } + refs := v.Referrers() + if refs == nil { + // TODO investigate why refs can be nil + return true + } + for _, ref := range *refs { + switch ref := ref.(type) { + case *ir.DebugRef: + case *ir.Sigma: + if seen == nil { + seen = map[ir.Value]struct{}{} + } + seen[v] = struct{}{} + if hasUse(ref, seen) { + return true + } + case *ir.Phi: + if seen == nil { + seen = map[ir.Value]struct{}{} + } + seen[v] = struct{}{} + if hasUse(ref, seen) { + return true + } + default: + return true + } + } + return false + } + + ast.Inspect(node, func(node ast.Node) bool { + assign, ok := node.(*ast.AssignStmt) + if !ok { + return true + } + if len(assign.Lhs) > 1 && len(assign.Rhs) == 1 { + // Either a function call with multiple return values, + // or a comma-ok assignment + + val, _ := fn.ValueForExpr(assign.Rhs[0]) + if val == nil { + return true + } + refs := val.Referrers() + if refs == nil { + return true + } + for _, ref := range *refs { + ex, ok := ref.(*ir.Extract) + if !ok { + continue + } + if !hasUse(ex, nil) { + lhs := assign.Lhs[ex.Index] + if ident, ok := lhs.(*ast.Ident); !ok || ok && ident.Name == "_" { + continue + } + report.Report(pass, assign, fmt.Sprintf("this value of %s is never used", lhs)) + } + } + return true + } + for i, lhs := range assign.Lhs { + rhs := assign.Rhs[i] + if ident, ok := lhs.(*ast.Ident); !ok || ok && ident.Name == "_" { + continue + } + val, _ := fn.ValueForExpr(rhs) + if val == nil { + continue + } + + if _, ok := val.(*ir.Const); ok { + // a zero-valued constant, for example in 'foo := []string(nil)' + continue + } + if !hasUse(val, nil) { + report.Report(pass, assign, fmt.Sprintf("this value of %s is never used", lhs)) + } + } + return true + }) + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4008/sa4008.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4008/sa4008.go new file mode 100644 index 000000000..704273723 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4008/sa4008.go @@ -0,0 +1,114 @@ +package sa4008 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4008", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `The variable in the loop condition never changes, are you incrementing the wrong variable?`, + Text: `For example: + + for i := 0; i < 10; j++ { ... } + +This may also occur when a loop can only execute once because of unconditional +control flow that terminates the loop. For example, when a loop body contains an +unconditional break, return, or panic: + + func f() { + panic("oops") + } + func g() { + for i := 0; i < 10; i++ { + // f unconditionally calls panic, which means "i" is + // never incremented. + f() + } + }`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + cb := func(node ast.Node) bool { + loop, ok := node.(*ast.ForStmt) + if !ok { + return true + } + if loop.Init == nil || loop.Cond == nil || loop.Post == nil { + return true + } + init, ok := loop.Init.(*ast.AssignStmt) + if !ok || len(init.Lhs) != 1 || len(init.Rhs) != 1 { + return true + } + cond, ok := loop.Cond.(*ast.BinaryExpr) + if !ok { + return true + } + x, ok := cond.X.(*ast.Ident) + if !ok { + return true + } + lhs, ok := init.Lhs[0].(*ast.Ident) + if !ok { + return true + } + if pass.TypesInfo.ObjectOf(x) != pass.TypesInfo.ObjectOf(lhs) { + return true + } + if _, ok := loop.Post.(*ast.IncDecStmt); !ok { + return true + } + + v, isAddr := fn.ValueForExpr(cond.X) + if v == nil || isAddr { + return true + } + switch v := v.(type) { + case *ir.Phi: + ops := v.Operands(nil) + if len(ops) != 2 { + return true + } + _, ok := (*ops[0]).(*ir.Const) + if !ok { + return true + } + sigma, ok := (*ops[1]).(*ir.Sigma) + if !ok { + return true + } + if sigma.X != v { + return true + } + case *ir.Load: + return true + } + report.Report(pass, cond, "variable in loop condition never changes") + + return true + } + if source := fn.Source(); source != nil { + ast.Inspect(source, cb) + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4009/sa4009.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4009/sa4009.go new file mode 100644 index 000000000..c1aa50bd4 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4009/sa4009.go @@ -0,0 +1,106 @@ +package sa4009 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4009", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `A function argument is overwritten before its first use`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + cb := func(node ast.Node) bool { + var typ *ast.FuncType + var body *ast.BlockStmt + switch fn := node.(type) { + case *ast.FuncDecl: + typ = fn.Type + body = fn.Body + case *ast.FuncLit: + typ = fn.Type + body = fn.Body + } + if body == nil { + return true + } + if len(typ.Params.List) == 0 { + return true + } + for _, field := range typ.Params.List { + for _, arg := range field.Names { + obj := pass.TypesInfo.ObjectOf(arg) + var irobj *ir.Parameter + for _, param := range fn.Params { + if param.Object() == obj { + irobj = param + break + } + } + if irobj == nil { + continue + } + refs := irobj.Referrers() + if refs == nil { + continue + } + if len(irutil.FilterDebug(*refs)) != 0 { + continue + } + + var assignment ast.Node + ast.Inspect(body, func(node ast.Node) bool { + if assignment != nil { + return false + } + assign, ok := node.(*ast.AssignStmt) + if !ok { + return true + } + for _, lhs := range assign.Lhs { + ident, ok := lhs.(*ast.Ident) + if !ok { + continue + } + if pass.TypesInfo.ObjectOf(ident) == obj { + assignment = assign + return false + } + } + return true + }) + if assignment != nil { + report.Report(pass, arg, fmt.Sprintf("argument %s is overwritten before first use", arg), + report.Related(assignment, fmt.Sprintf("assignment to %s", arg))) + } + } + } + return true + } + if source := fn.Source(); source != nil { + ast.Inspect(source, cb) + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4010/sa4010.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4010/sa4010.go new file mode 100644 index 000000000..771ebbd1a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4010/sa4010.go @@ -0,0 +1,216 @@ +package sa4010 + +import ( + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4010", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `The result of \'append\' will never be observed anywhere`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + isAppend := func(ins ir.Value) bool { + call, ok := ins.(*ir.Call) + if !ok { + return false + } + if call.Call.IsInvoke() { + return false + } + if builtin, ok := call.Call.Value.(*ir.Builtin); !ok || builtin.Name() != "append" { + return false + } + return true + } + + // We have to be careful about aliasing. + // Multiple slices may refer to the same backing array, + // making appends observable even when we don't see the result of append be used anywhere. + // + // We will have to restrict ourselves to slices that have been allocated within the function, + // haven't been sliced, + // and haven't been passed anywhere that could retain them (such as function calls or memory stores). + // + // We check whether an append should be flagged in two steps. + // + // In the first step, we look at the data flow graph, starting in reverse from the argument to append, till we reach the root. + // This graph must only consist of the following instructions: + // + // - phi + // - sigma + // - slice + // - const nil + // - MakeSlice + // - Alloc + // - calls to append + // + // If this step succeeds, we look at all referrers of the values found in the first step, recursively. + // These referrers must either be in the set of values found in the first step, + // be DebugRefs, + // or fulfill the same type requirements as step 1, with the exception of appends, which are forbidden. + // + // If both steps succeed then we know that the backing array hasn't been aliased in an observable manner. + // + // We could relax these restrictions by making use of additional information: + // - if we passed the slice to a function that doesn't retain the slice then we can still flag it + // - if a slice has been sliced but is dead afterwards, we can flag appends to the new slice + + // OPT(dh): We could cache the results of both validate functions. + // However, we only use these functions on values that we otherwise want to flag, which are very few. + // Not caching values hasn't increased the runtimes for the standard library nor k8s. + var validateArgument func(v ir.Value, seen map[ir.Value]struct{}) bool + validateArgument = func(v ir.Value, seen map[ir.Value]struct{}) bool { + if _, ok := seen[v]; ok { + // break cycle + return true + } + seen[v] = struct{}{} + switch v := v.(type) { + case *ir.Phi: + for _, edge := range v.Edges { + if !validateArgument(edge, seen) { + return false + } + } + return true + case *ir.Sigma: + return validateArgument(v.X, seen) + case *ir.Slice: + return validateArgument(v.X, seen) + case *ir.Const: + return true + case *ir.MakeSlice: + return true + case *ir.Alloc: + return true + case *ir.Call: + if isAppend(v) { + return validateArgument(v.Call.Args[0], seen) + } + return false + default: + return false + } + } + + var validateReferrers func(v ir.Value, seen map[ir.Instruction]struct{}) bool + validateReferrers = func(v ir.Value, seen map[ir.Instruction]struct{}) bool { + for _, ref := range *v.Referrers() { + if _, ok := seen[ref]; ok { + continue + } + + seen[ref] = struct{}{} + switch ref.(type) { + case *ir.Phi: + case *ir.Sigma: + case *ir.Slice: + case *ir.Const: + case *ir.MakeSlice: + case *ir.Alloc: + case *ir.DebugRef: + default: + return false + } + + if ref, ok := ref.(ir.Value); ok { + if !validateReferrers(ref, seen) { + return false + } + } + } + return true + } + + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, block := range fn.Blocks { + for _, ins := range block.Instrs { + val, ok := ins.(ir.Value) + if !ok || !isAppend(val) { + continue + } + + isUsed := false + visited := map[ir.Instruction]bool{} + var walkRefs func(refs []ir.Instruction) + walkRefs = func(refs []ir.Instruction) { + loop: + for _, ref := range refs { + if visited[ref] { + continue + } + visited[ref] = true + if _, ok := ref.(*ir.DebugRef); ok { + continue + } + switch ref := ref.(type) { + case *ir.Phi: + walkRefs(*ref.Referrers()) + case *ir.Sigma: + walkRefs(*ref.Referrers()) + case ir.Value: + if !isAppend(ref) { + isUsed = true + } else { + walkRefs(*ref.Referrers()) + } + case ir.Instruction: + isUsed = true + break loop + } + } + } + + refs := val.Referrers() + if refs == nil { + continue + } + walkRefs(*refs) + + if isUsed { + continue + } + + seen := map[ir.Value]struct{}{} + if !validateArgument(ins.(*ir.Call).Call.Args[0], seen) { + continue + } + + seen2 := map[ir.Instruction]struct{}{} + for k := range seen { + // the only values we allow are also instructions, so this type assertion cannot fail + seen2[k.(ir.Instruction)] = struct{}{} + } + seen2[ins] = struct{}{} + failed := false + for v := range seen { + if !validateReferrers(v, seen2) { + failed = true + break + } + } + if !failed { + report.Report(pass, ins, "this result of append is never used, except maybe in other appends") + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4011/sa4011.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4011/sa4011.go new file mode 100644 index 000000000..f9197bddf --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4011/sa4011.go @@ -0,0 +1,88 @@ +package sa4011 + +import ( + "go/ast" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4011", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Break statement with no effect. Did you mean to break out of an outer loop?`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + var body *ast.BlockStmt + switch node := node.(type) { + case *ast.ForStmt: + body = node.Body + case *ast.RangeStmt: + body = node.Body + default: + lint.ExhaustiveTypeSwitch(node) + } + for _, stmt := range body.List { + var blocks [][]ast.Stmt + switch stmt := stmt.(type) { + case *ast.SwitchStmt: + for _, c := range stmt.Body.List { + blocks = append(blocks, c.(*ast.CaseClause).Body) + } + case *ast.SelectStmt: + for _, c := range stmt.Body.List { + blocks = append(blocks, c.(*ast.CommClause).Body) + } + default: + continue + } + + for _, body := range blocks { + if len(body) == 0 { + continue + } + lasts := []ast.Stmt{body[len(body)-1]} + // TODO(dh): unfold all levels of nested block + // statements, not just a single level if statement + if ifs, ok := lasts[0].(*ast.IfStmt); ok { + if len(ifs.Body.List) == 0 { + continue + } + lasts[0] = ifs.Body.List[len(ifs.Body.List)-1] + + if block, ok := ifs.Else.(*ast.BlockStmt); ok { + if len(block.List) != 0 { + lasts = append(lasts, block.List[len(block.List)-1]) + } + } + } + for _, last := range lasts { + branch, ok := last.(*ast.BranchStmt) + if !ok || branch.Tok != token.BREAK || branch.Label != nil { + continue + } + report.Report(pass, branch, "ineffective break statement. Did you mean to break out of the outer loop?") + } + } + } + } + code.Preorder(pass, fn, (*ast.ForStmt)(nil), (*ast.RangeStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4012/sa4012.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4012/sa4012.go new file mode 100644 index 000000000..d2e42a3e9 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4012/sa4012.go @@ -0,0 +1,51 @@ +package sa4012 + +import ( + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4012", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Comparing a value against NaN even though no value is equal to NaN`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + isNaN := func(v ir.Value) bool { + call, ok := v.(*ir.Call) + if !ok { + return false + } + return irutil.IsCallTo(call.Common(), "math.NaN") + } + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, block := range fn.Blocks { + for _, ins := range block.Instrs { + ins, ok := ins.(*ir.BinOp) + if !ok { + continue + } + if isNaN(irutil.Flatten(ins.X)) || isNaN(irutil.Flatten(ins.Y)) { + report.Report(pass, ins, "no value is equal to NaN, not even NaN itself") + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4013/sa4013.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4013/sa4013.go new file mode 100644 index 000000000..ca451c622 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4013/sa4013.go @@ -0,0 +1,44 @@ +package sa4013 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4013", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Negating a boolean twice (\'!!b\') is the same as writing \'b\'. This is either redundant, or a typo.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkDoubleNegationQ = pattern.MustParse(`(UnaryExpr "!" single@(UnaryExpr "!" x))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if m, ok := code.Match(pass, checkDoubleNegationQ, node); ok { + report.Report(pass, node, "negating a boolean twice has no effect; is this a typo?", report.Fixes( + edit.Fix("turn into single negation", edit.ReplaceWithNode(pass.Fset, node, m.State["single"].(ast.Node))), + edit.Fix("remove double negation", edit.ReplaceWithNode(pass.Fset, node, m.State["x"].(ast.Node))))) + } + } + code.Preorder(pass, fn, (*ast.UnaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4014/sa4014.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4014/sa4014.go new file mode 100644 index 000000000..642c80ca6 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4014/sa4014.go @@ -0,0 +1,78 @@ +package sa4014 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4014", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `An if/else if chain has repeated conditions and no side-effects; if the condition didn't match the first time, it won't match the second time, either`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + seen := map[ast.Node]bool{} + + var collectConds func(ifstmt *ast.IfStmt, conds []ast.Expr) ([]ast.Expr, bool) + collectConds = func(ifstmt *ast.IfStmt, conds []ast.Expr) ([]ast.Expr, bool) { + seen[ifstmt] = true + // Bail if any if-statement has an Init statement or side effects in its condition + if ifstmt.Init != nil { + return nil, false + } + if code.MayHaveSideEffects(pass, ifstmt.Cond, nil) { + return nil, false + } + + conds = append(conds, ifstmt.Cond) + if elsestmt, ok := ifstmt.Else.(*ast.IfStmt); ok { + return collectConds(elsestmt, conds) + } + return conds, true + } + fn := func(node ast.Node) { + ifstmt := node.(*ast.IfStmt) + if seen[ifstmt] { + // this if-statement is part of an if/else-if chain that we've already processed + return + } + if ifstmt.Else == nil { + // there can be at most one condition + return + } + conds, ok := collectConds(ifstmt, nil) + if !ok { + return + } + if len(conds) < 2 { + return + } + counts := map[string]int{} + for _, cond := range conds { + s := report.Render(pass, cond) + counts[s]++ + if counts[s] == 2 { + report.Report(pass, cond, "this condition occurs multiple times in this if/else if chain") + } + } + } + code.Preorder(pass, fn, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4015/sa4015.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4015/sa4015.go new file mode 100644 index 000000000..d94a89df6 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4015/sa4015.go @@ -0,0 +1,56 @@ +package sa4015 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4015", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(checkMathIntRules), + }, + Doc: &lint.RawDocumentation{ + Title: `Calling functions like \'math.Ceil\' on floats converted from integers doesn't do anything useful`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkMathIntRules = map[string]callcheck.Check{ + "math.Ceil": pointlessIntMath, + "math.Floor": pointlessIntMath, + "math.IsNaN": pointlessIntMath, + "math.Trunc": pointlessIntMath, + "math.IsInf": pointlessIntMath, +} + +func pointlessIntMath(call *callcheck.Call) { + if ConvertedFromInt(call.Args[0].Value) { + call.Invalid(fmt.Sprintf("calling %s on a converted integer is pointless", irutil.CallName(call.Instr.Common()))) + } +} + +func ConvertedFromInt(v callcheck.Value) bool { + conv, ok := v.Value.(*ir.Convert) + if !ok { + return false + } + return typeutil.NewTypeSet(conv.X.Type()).All(func(t *types.Term) bool { + b, ok := t.Type().Underlying().(*types.Basic) + return ok && b.Info()&types.IsInteger != 0 + }) +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4016/sa4016.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4016/sa4016.go new file mode 100644 index 000000000..cc644370c --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4016/sa4016.go @@ -0,0 +1,116 @@ +package sa4016 + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ast/astutil" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4016", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Certain bitwise operations, such as \'x ^ 0\', do not do anything useful`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + binop := node.(*ast.BinaryExpr) + if !typeutil.All(pass.TypesInfo.TypeOf(binop), func(term *types.Term) bool { + b, ok := term.Type().Underlying().(*types.Basic) + if !ok { + return false + } + return (b.Info() & types.IsInteger) != 0 + }) { + return + } + switch binop.Op { + case token.AND, token.OR, token.XOR: + default: + // we do not flag shifts because too often, x<<0 is part + // of a pattern, x<<0, x<<8, x<<16, ... + return + } + if y, ok := binop.Y.(*ast.Ident); ok { + obj, ok := pass.TypesInfo.ObjectOf(y).(*types.Const) + if !ok { + return + } + if obj.Pkg() != pass.Pkg { + // identifier was dot-imported + return + } + if v, _ := constant.Int64Val(obj.Val()); v != 0 { + return + } + path, _ := astutil.PathEnclosingInterval(code.File(pass, obj), obj.Pos(), obj.Pos()) + if len(path) < 2 { + return + } + spec, ok := path[1].(*ast.ValueSpec) + if !ok { + return + } + if len(spec.Names) != 1 || len(spec.Values) != 1 { + // TODO(dh): we could support this + return + } + ident, ok := spec.Values[0].(*ast.Ident) + if !ok { + return + } + if !isIota(pass.TypesInfo.ObjectOf(ident)) { + return + } + switch binop.Op { + case token.AND: + report.Report(pass, node, + fmt.Sprintf("%s always equals 0; %s is defined as iota and has value 0, maybe %s is meant to be 1 << iota?", report.Render(pass, binop), report.Render(pass, binop.Y), report.Render(pass, binop.Y))) + case token.OR, token.XOR: + report.Report(pass, node, + fmt.Sprintf("%s always equals %s; %s is defined as iota and has value 0, maybe %s is meant to be 1 << iota?", report.Render(pass, binop), report.Render(pass, binop.X), report.Render(pass, binop.Y), report.Render(pass, binop.Y))) + } + } else if code.IsIntegerLiteral(pass, binop.Y, constant.MakeInt64(0)) { + switch binop.Op { + case token.AND: + report.Report(pass, node, fmt.Sprintf("%s always equals 0", report.Render(pass, binop))) + case token.OR, token.XOR: + report.Report(pass, node, fmt.Sprintf("%s always equals %s", report.Render(pass, binop), report.Render(pass, binop.X))) + } + } + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} + +func isIota(obj types.Object) bool { + if obj.Name() != "iota" { + return false + } + c, ok := obj.(*types.Const) + if !ok { + return false + } + return c.Pkg() == nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4017/sa4017.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4017/sa4017.go new file mode 100644 index 000000000..f0d10a4b9 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4017/sa4017.go @@ -0,0 +1,87 @@ +package sa4017 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/purity" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4017", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, purity.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Discarding the return values of a function without side effects, making the call pointless`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + pure := pass.ResultOf[purity.Analyzer].(purity.Result) + +fnLoop: + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + if code.IsInTest(pass, fn) { + params := fn.Signature.Params() + for i := 0; i < params.Len(); i++ { + param := params.At(i) + if typeutil.IsPointerToTypeWithName(param.Type(), "testing.B") { + // Ignore discarded pure functions in code related + // to benchmarks. Instead of matching BenchmarkFoo + // functions, we match any function accepting a + // *testing.B. Benchmarks sometimes call generic + // functions for doing the actual work, and + // checking for the parameter is a lot easier and + // faster than analyzing call trees. + continue fnLoop + } + } + } + + for _, b := range fn.Blocks { + for _, ins := range b.Instrs { + ins, ok := ins.(*ir.Call) + if !ok { + continue + } + refs := ins.Referrers() + if refs == nil || len(irutil.FilterDebug(*refs)) > 0 { + continue + } + + callee := ins.Common().StaticCallee() + if callee == nil { + continue + } + if callee.Object() == nil { + // TODO(dh): support anonymous functions + continue + } + if _, ok := pure[callee.Object().(*types.Func)]; ok { + if pass.Pkg.Path() == "fmt_test" && callee.Object().(*types.Func).FullName() == "fmt.Sprintf" { + // special case for benchmarks in the fmt package + continue + } + report.Report(pass, ins, fmt.Sprintf("%s doesn't have side effects and its return value is ignored", callee.Object().Name())) + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4018/sa4018.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4018/sa4018.go new file mode 100644 index 000000000..f04ed33ef --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4018/sa4018.go @@ -0,0 +1,61 @@ +package sa4018 + +import ( + "fmt" + "go/ast" + "go/token" + "reflect" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/facts/purity" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4018", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, purity.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Self-assignment of variables`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + pure := pass.ResultOf[purity.Analyzer].(purity.Result) + + fn := func(node ast.Node) { + assign := node.(*ast.AssignStmt) + if assign.Tok != token.ASSIGN || len(assign.Lhs) != len(assign.Rhs) { + return + } + for i, lhs := range assign.Lhs { + rhs := assign.Rhs[i] + if reflect.TypeOf(lhs) != reflect.TypeOf(rhs) { + continue + } + if code.MayHaveSideEffects(pass, lhs, pure) || code.MayHaveSideEffects(pass, rhs, pure) { + continue + } + + rlh := report.Render(pass, lhs) + rrh := report.Render(pass, rhs) + if rlh == rrh { + report.Report(pass, assign, fmt.Sprintf("self-assignment of %s to %s", rrh, rlh), report.FilterGenerated()) + } + } + } + code.Preorder(pass, fn, (*ast.AssignStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4019/sa4019.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4019/sa4019.go new file mode 100644 index 000000000..dca7d23f1 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4019/sa4019.go @@ -0,0 +1,82 @@ +package sa4019 + +import ( + "fmt" + "go/ast" + "sort" + "strings" + + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ast/astutil" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4019", + Run: run, + Requires: []*analysis.Analyzer{generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Multiple, identical build constraints in the same file`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func buildTagsIdentical(s1, s2 []string) bool { + if len(s1) != len(s2) { + return false + } + s1s := make([]string, len(s1)) + copy(s1s, s1) + sort.Strings(s1s) + s2s := make([]string, len(s2)) + copy(s2s, s2) + sort.Strings(s2s) + for i, s := range s1s { + if s != s2s[i] { + return false + } + } + return true +} + +func run(pass *analysis.Pass) (interface{}, error) { + for _, f := range pass.Files { + constraints := buildTags(f) + for i, constraint1 := range constraints { + for j, constraint2 := range constraints { + if i >= j { + continue + } + if buildTagsIdentical(constraint1, constraint2) { + msg := fmt.Sprintf("identical build constraints %q and %q", + strings.Join(constraint1, " "), + strings.Join(constraint2, " ")) + report.Report(pass, f, msg, report.FilterGenerated(), report.ShortRange()) + } + } + } + } + return nil, nil +} + +func buildTags(f *ast.File) [][]string { + var out [][]string + for _, line := range strings.Split(astutil.Preamble(f), "\n") { + if !strings.HasPrefix(line, "+build ") { + continue + } + line = strings.TrimSpace(strings.TrimPrefix(line, "+build ")) + fields := strings.Fields(line) + out = append(out, fields) + } + return out +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4020/sa4020.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4020/sa4020.go new file mode 100644 index 000000000..8994cc5d7 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4020/sa4020.go @@ -0,0 +1,172 @@ +package sa4020 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/exp/typeparams" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4020", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Unreachable case clause in a type switch`, + Text: `In a type switch like the following + + type T struct{} + func (T) Read(b []byte) (int, error) { return 0, nil } + + var v interface{} = T{} + + switch v.(type) { + case io.Reader: + // ... + case T: + // unreachable + } + +the second case clause can never be reached because \'T\' implements +\'io.Reader\' and case clauses are evaluated in source order. + +Another example: + + type T struct{} + func (T) Read(b []byte) (int, error) { return 0, nil } + func (T) Close() error { return nil } + + var v interface{} = T{} + + switch v.(type) { + case io.Reader: + // ... + case io.ReadCloser: + // unreachable + } + +Even though \'T\' has a \'Close\' method and thus implements \'io.ReadCloser\', +\'io.Reader\' will always match first. The method set of \'io.Reader\' is a +subset of \'io.ReadCloser\'. Thus it is impossible to match the second +case without matching the first case. + + +Structurally equivalent interfaces + +A special case of the previous example are structurally identical +interfaces. Given these declarations + + type T error + type V error + + func doSomething() error { + err, ok := doAnotherThing() + if ok { + return T(err) + } + + return U(err) + } + +the following type switch will have an unreachable case clause: + + switch doSomething().(type) { + case T: + // ... + case V: + // unreachable + } + +\'T\' will always match before V because they are structurally equivalent +and therefore \'doSomething()\''s return value implements both.`, + Since: "2019.2", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // Check if T subsumes V in a type switch. T subsumes V if T is an interface and T's method set is a subset of V's method set. + subsumes := func(T, V types.Type) bool { + if typeparams.IsTypeParam(T) { + return false + } + tIface, ok := T.Underlying().(*types.Interface) + if !ok { + return false + } + + return types.Implements(V, tIface) + } + + subsumesAny := func(Ts, Vs []types.Type) (types.Type, types.Type, bool) { + for _, T := range Ts { + for _, V := range Vs { + if subsumes(T, V) { + return T, V, true + } + } + } + + return nil, nil, false + } + + fn := func(node ast.Node) { + tsStmt := node.(*ast.TypeSwitchStmt) + + type ccAndTypes struct { + cc *ast.CaseClause + types []types.Type + } + + // All asserted types in the order of case clauses. + ccs := make([]ccAndTypes, 0, len(tsStmt.Body.List)) + for _, stmt := range tsStmt.Body.List { + cc, _ := stmt.(*ast.CaseClause) + + // Exclude the 'default' case. + if len(cc.List) == 0 { + continue + } + + Ts := make([]types.Type, 0, len(cc.List)) + for _, expr := range cc.List { + // Exclude the 'nil' value from any 'case' statement (it is always reachable). + if typ := pass.TypesInfo.TypeOf(expr); typ != types.Typ[types.UntypedNil] { + Ts = append(Ts, typ) + } + } + + ccs = append(ccs, ccAndTypes{cc: cc, types: Ts}) + } + + if len(ccs) <= 1 { + // Zero or one case clauses, nothing to check. + return + } + + // Check if case clauses following cc have types that are subsumed by cc. + for i, cc := range ccs[:len(ccs)-1] { + for _, next := range ccs[i+1:] { + if T, V, yes := subsumesAny(cc.types, next.types); yes { + report.Report(pass, next.cc, fmt.Sprintf("unreachable case clause: %s will always match before %s", T.String(), V.String()), + report.ShortRange()) + } + } + } + } + + code.Preorder(pass, fn, (*ast.TypeSwitchStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4021/sa4021.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4021/sa4021.go new file mode 100644 index 000000000..76d923524 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4021/sa4021.go @@ -0,0 +1,44 @@ +package sa4021 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4021", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\"x = append(y)\" is equivalent to \"x = y\"`, + Since: "2019.2", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var checkSingleArgAppendQ = pattern.MustParse(`(CallExpr (Builtin "append") [_])`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + _, ok := code.Match(pass, checkSingleArgAppendQ, node) + if !ok { + return + } + report.Report(pass, node, "x = append(y) is equivalent to x = y", report.FilterGenerated()) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4022/sa4022.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4022/sa4022.go new file mode 100644 index 000000000..c6575442c --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4022/sa4022.go @@ -0,0 +1,48 @@ +package sa4022 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4022", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Comparing the address of a variable against nil`, + Text: `Code such as \"if &x == nil\" is meaningless, because taking the address of a variable always yields a non-nil pointer.`, + Since: "2020.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var CheckAddressIsNilQ = pattern.MustParse( + `(BinaryExpr + (UnaryExpr "&" _) + (Or "==" "!=") + (Builtin "nil"))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + _, ok := code.Match(pass, CheckAddressIsNilQ, node) + if !ok { + return + } + report.Report(pass, node, "the address of a variable cannot be nil") + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4023/sa4023.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4023/sa4023.go new file mode 100644 index 000000000..991d4f819 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4023/sa4023.go @@ -0,0 +1,205 @@ +package sa4023 + +import ( + "fmt" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/nilness" + "honnef.co/go/tools/analysis/facts/typedness" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/exp/typeparams" + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4023", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, typedness.Analysis, nilness.Analysis}, + }, + Doc: &lint.RawDocumentation{ + Title: `Impossible comparison of interface value with untyped nil`, + Text: `Under the covers, interfaces are implemented as two elements, a +type T and a value V. V is a concrete value such as an int, +struct or pointer, never an interface itself, and has type T. For +instance, if we store the int value 3 in an interface, the +resulting interface value has, schematically, (T=int, V=3). The +value V is also known as the interface's dynamic value, since a +given interface variable might hold different values V (and +corresponding types T) during the execution of the program. + +An interface value is nil only if the V and T are both +unset, (T=nil, V is not set), In particular, a nil interface will +always hold a nil type. If we store a nil pointer of type *int +inside an interface value, the inner type will be *int regardless +of the value of the pointer: (T=*int, V=nil). Such an interface +value will therefore be non-nil even when the pointer value V +inside is nil. + +This situation can be confusing, and arises when a nil value is +stored inside an interface value such as an error return: + + func returnsError() error { + var p *MyError = nil + if bad() { + p = ErrBad + } + return p // Will always return a non-nil error. + } + +If all goes well, the function returns a nil p, so the return +value is an error interface value holding (T=*MyError, V=nil). +This means that if the caller compares the returned error to nil, +it will always look as if there was an error even if nothing bad +happened. To return a proper nil error to the caller, the +function must return an explicit nil: + + func returnsError() error { + if bad() { + return ErrBad + } + return nil + } + +It's a good idea for functions that return errors always to use +the error type in their signature (as we did above) rather than a +concrete type such as \'*MyError\', to help guarantee the error is +created correctly. As an example, \'os.Open\' returns an error even +though, if not nil, it's always of concrete type *os.PathError. + +Similar situations to those described here can arise whenever +interfaces are used. Just keep in mind that if any concrete value +has been stored in the interface, the interface will not be nil. +For more information, see The Laws of +Reflection (https://golang.org/doc/articles/laws_of_reflection.html). + +This text has been copied from +https://golang.org/doc/faq#nil_error, licensed under the Creative +Commons Attribution 3.0 License.`, + Since: "2020.2", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, // TODO should this be MergeIfAll? + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // The comparison 'fn() == nil' can never be true if fn() returns + // an interface value and only returns typed nils. This is usually + // a mistake in the function itself, but all we can say for + // certain is that the comparison is pointless. + // + // Flag results if no untyped nils are being returned, but either + // known typed nils, or typed unknown nilness are being returned. + + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR) + typedness := pass.ResultOf[typedness.Analysis].(*typedness.Result) + nilness := pass.ResultOf[nilness.Analysis].(*nilness.Result) + for _, fn := range irpkg.SrcFuncs { + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + binop, ok := instr.(*ir.BinOp) + if !ok || !(binop.Op == token.EQL || binop.Op == token.NEQ) { + continue + } + if _, ok := binop.X.Type().Underlying().(*types.Interface); !ok || typeparams.IsTypeParam(binop.X.Type()) { + // TODO support swapped X and Y + continue + } + + k, ok := binop.Y.(*ir.Const) + if !ok || !k.IsNil() { + // if binop.X is an interface, then binop.Y can + // only be a Const if its untyped. A typed nil + // constant would first be passed to + // MakeInterface. + continue + } + + var idx int + var obj *types.Func + switch x := irutil.Flatten(binop.X).(type) { + case *ir.Call: + callee := x.Call.StaticCallee() + if callee == nil { + continue + } + obj, _ = callee.Object().(*types.Func) + idx = 0 + case *ir.Extract: + call, ok := irutil.Flatten(x.Tuple).(*ir.Call) + if !ok { + continue + } + callee := call.Call.StaticCallee() + if callee == nil { + continue + } + obj, _ = callee.Object().(*types.Func) + idx = x.Index + case *ir.MakeInterface: + var qualifier string + switch binop.Op { + case token.EQL: + qualifier = "never" + case token.NEQ: + qualifier = "always" + default: + panic("unreachable") + } + + terms, err := typeparams.NormalTerms(x.X.Type()) + if len(terms) == 0 || err != nil { + // Type is a type parameter with no type terms (or we couldn't determine the terms). Such a type + // _can_ be nil when put in an interface value. + continue + } + + if report.HasRange(x.X) { + report.Report(pass, binop, fmt.Sprintf("this comparison is %s true", qualifier), + report.Related(x.X, "the lhs of the comparison gets its value from here and has a concrete type")) + } else { + // we can't generate related information for this, so make the diagnostic itself slightly more useful + report.Report(pass, binop, fmt.Sprintf("this comparison is %s true; the lhs of the comparison has been assigned a concretely typed value", qualifier)) + } + continue + } + if obj == nil { + continue + } + + isNil, onlyGlobal := nilness.MayReturnNil(obj, idx) + if typedness.MustReturnTyped(obj, idx) && isNil && !onlyGlobal && !code.IsInTest(pass, binop) { + // Don't flag these comparisons in tests. Tests + // may be explicitly enforcing the invariant that + // a value isn't nil. + + var qualifier string + switch binop.Op { + case token.EQL: + qualifier = "never" + case token.NEQ: + qualifier = "always" + default: + panic("unreachable") + } + report.Report(pass, binop, fmt.Sprintf("this comparison is %s true", qualifier), + // TODO support swapped X and Y + report.Related(binop.X, fmt.Sprintf("the lhs of the comparison is the %s return value of this function call", report.Ordinal(idx+1))), + report.Related(obj, fmt.Sprintf("%s never returns a nil interface value", typeutil.FuncName(obj)))) + } + } + } + } + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4024/sa4024.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4024/sa4024.go new file mode 100644 index 000000000..fad0742bd --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4024/sa4024.go @@ -0,0 +1,66 @@ +package sa4024 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4024", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Checking for impossible return value from a builtin function`, + Text: `Return values of the \'len\' and \'cap\' builtins cannot be negative. + +See https://golang.org/pkg/builtin/#len and https://golang.org/pkg/builtin/#cap. + +Example: + + if len(slice) < 0 { + fmt.Println("unreachable code") + }`, + Since: "2021.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var builtinLessThanZeroQ = pattern.MustParse(` + (Or + (BinaryExpr + (IntegerLiteral "0") + ">" + (CallExpr builtin@(Builtin (Or "len" "cap")) _)) + (BinaryExpr + (CallExpr builtin@(Builtin (Or "len" "cap")) _) + "<" + (IntegerLiteral "0"))) +`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + matcher, ok := code.Match(pass, builtinLessThanZeroQ, node) + if !ok { + return + } + + builtin := matcher.State["builtin"].(*ast.Ident) + report.Report(pass, node, fmt.Sprintf("builtin function %s does not return negative values", builtin.Name)) + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4025/sa4025.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4025/sa4025.go new file mode 100644 index 000000000..2a2262b2c --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4025/sa4025.go @@ -0,0 +1,77 @@ +package sa4025 + +import ( + "fmt" + "go/ast" + "go/constant" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4025", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Integer division of literals that results in zero", + Text: `When dividing two integer constants, the result will +also be an integer. Thus, a division such as \'2 / 3\' results in \'0\'. +This is true for all of the following examples: + + _ = 2 / 3 + const _ = 2 / 3 + const _ float64 = 2 / 3 + _ = float64(2 / 3) + +Staticcheck will flag such divisions if both sides of the division are +integer literals, as it is highly unlikely that the division was +intended to truncate to zero. Staticcheck will not flag integer +division involving named constants, to avoid noisy positives. +`, + Since: "2021.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var integerDivisionQ = pattern.MustParse(`(BinaryExpr (IntegerLiteral _) "/" (IntegerLiteral _))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + _, ok := code.Match(pass, integerDivisionQ, node) + if !ok { + return + } + + val := constant.ToInt(pass.TypesInfo.Types[node.(ast.Expr)].Value) + if v, ok := constant.Uint64Val(val); ok && v == 0 { + report.Report(pass, node, fmt.Sprintf("the integer division '%s' results in zero", report.Render(pass, node))) + } + + // TODO: we could offer a suggested fix here, but I am not + // sure what it should be. There are many options to choose + // from. + + // Note: we experimented with flagging divisions that truncate + // (e.g. 4 / 3), but it ran into false positives in Go's + // 'time' package, which does this, deliberately: + // + // unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay + // + // The check also found a real bug in other code, but I don't + // think we can outright ban this kind of division. + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4026/sa4026.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4026/sa4026.go new file mode 100644 index 000000000..9fde1329b --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4026/sa4026.go @@ -0,0 +1,87 @@ +package sa4026 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4026", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Go constants cannot express negative zero", + Text: `In IEEE 754 floating point math, zero has a sign and can be positive +or negative. This can be useful in certain numerical code. + +Go constants, however, cannot express negative zero. This means that +the literals \'-0.0\' and \'0.0\' have the same ideal value (zero) and +will both represent positive zero at runtime. + +To explicitly and reliably create a negative zero, you can use the +\'math.Copysign\' function: \'math.Copysign(0, -1)\'.`, + Since: "2021.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var negativeZeroFloatQ = pattern.MustParse(` + (Or + (UnaryExpr + "-" + (BasicLit "FLOAT" "0.0")) + + (UnaryExpr + "-" + (CallExpr conv@(Object (Or "float32" "float64")) lit@(Or (BasicLit "INT" "0") (BasicLit "FLOAT" "0.0")))) + + (CallExpr + conv@(Object (Or "float32" "float64")) + (UnaryExpr "-" lit@(BasicLit "INT" "0"))))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, negativeZeroFloatQ, node) + if !ok { + return + } + + if conv, ok := m.State["conv"].(*types.TypeName); ok { + var replacement string + // TODO(dh): how does this handle type aliases? + if conv.Name() == "float32" { + replacement = `float32(math.Copysign(0, -1))` + } else { + replacement = `math.Copysign(0, -1)` + } + report.Report(pass, node, + fmt.Sprintf("in Go, the floating-point expression '%s' is the same as '%s(%s)', it does not produce a negative zero", + report.Render(pass, node), + conv.Name(), + report.Render(pass, m.State["lit"])), + report.Fixes(edit.Fix("use math.Copysign to create negative zero", edit.ReplaceWithString(node, replacement)))) + } else { + const replacement = `math.Copysign(0, -1)` + report.Report(pass, node, + "in Go, the floating-point literal '-0.0' is the same as '0.0', it does not produce a negative zero", + report.Fixes(edit.Fix("use math.Copysign to create negative zero", edit.ReplaceWithString(node, replacement)))) + } + } + code.Preorder(pass, fn, (*ast.UnaryExpr)(nil), (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4027/sa4027.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4027/sa4027.go new file mode 100644 index 000000000..99092fb36 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4027/sa4027.go @@ -0,0 +1,64 @@ +package sa4027 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4027", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'(*net/url.URL).Query\' returns a copy, modifying it doesn't change the URL`, + Text: `\'(*net/url.URL).Query\' parses the current value of \'net/url.URL.RawQuery\' +and returns it as a map of type \'net/url.Values\'. Subsequent changes to +this map will not affect the URL unless the map gets encoded and +assigned to the URL's \'RawQuery\'. + +As a consequence, the following code pattern is an expensive no-op: +\'u.Query().Add(key, value)\'.`, + Since: "2021.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ineffectiveURLQueryAddQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (SelectorExpr recv (Ident "Query")) []) (Ident meth)) _)`) + +func run(pass *analysis.Pass) (interface{}, error) { + // TODO(dh): We could make this check more complex and detect + // pointless modifications of net/url.Values in general, but that + // requires us to get the state machine correct, else we'll cause + // false positives. + + fn := func(node ast.Node) { + m, ok := code.Match(pass, ineffectiveURLQueryAddQ, node) + if !ok { + return + } + if !code.IsOfPointerToTypeWithName(pass, m.State["recv"].(ast.Expr), "net/url.URL") { + return + } + switch m.State["meth"].(string) { + case "Add", "Del", "Set": + default: + return + } + report.Report(pass, node, "(*net/url.URL).Query returns a copy, modifying it doesn't change the URL") + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4028/sa4028.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4028/sa4028.go new file mode 100644 index 000000000..afcdcdda5 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4028/sa4028.go @@ -0,0 +1,43 @@ +package sa4028 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4028", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'x % 1\' is always zero`, + Since: "2022.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, // MergeIfAny if we only flag literals, not named constants + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var moduloOneQ = pattern.MustParse(`(BinaryExpr _ "%" (IntegerLiteral "1"))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + _, ok := code.Match(pass, moduloOneQ, node) + if !ok { + return + } + report.Report(pass, node, "x % 1 is always zero") + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4029/sa4029.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4029/sa4029.go new file mode 100644 index 000000000..a2d830ee7 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4029/sa4029.go @@ -0,0 +1,87 @@ +package sa4029 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4029", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Ineffective attempt at sorting slice", + Text: ` +\'sort.Float64Slice\', \'sort.IntSlice\', and \'sort.StringSlice\' are +types, not functions. Doing \'x = sort.StringSlice(x)\' does nothing, +especially not sort any values. The correct usage is +\'sort.Sort(sort.StringSlice(x))\' or \'sort.StringSlice(x).Sort()\', +but there are more convenient helpers, namely \'sort.Float64s\', +\'sort.Ints\', and \'sort.Strings\'. +`, + Since: "2022.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ineffectiveSortQ = pattern.MustParse(`(AssignStmt target@(Ident _) "=" (CallExpr typ@(Symbol (Or "sort.Float64Slice" "sort.IntSlice" "sort.StringSlice")) [target]))`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, ineffectiveSortQ, node) + if !ok { + return + } + + _, ok = types.Unalias(pass.TypesInfo.TypeOf(m.State["target"].(ast.Expr))).(*types.Slice) + if !ok { + // Avoid flagging 'x = sort.StringSlice(x)' where TypeOf(x) == sort.StringSlice + return + } + + var alternative string + typeName := types.TypeString(types.Unalias(m.State["typ"].(*types.TypeName).Type()), nil) + switch typeName { + case "sort.Float64Slice": + alternative = "Float64s" + case "sort.IntSlice": + alternative = "Ints" + case "sort.StringSlice": + alternative = "Strings" + default: + panic(fmt.Sprintf("unreachable: %q", typeName)) + } + + r := &ast.CallExpr{ + Fun: &ast.SelectorExpr{ + X: &ast.Ident{Name: "sort"}, + Sel: &ast.Ident{Name: alternative}, + }, + Args: []ast.Expr{m.State["target"].(ast.Expr)}, + } + + report.Report(pass, node, + fmt.Sprintf("%s is a type, not a function, and %s doesn't sort your values; consider using sort.%s instead", + typeName, + report.Render(pass, node.(*ast.AssignStmt).Rhs[0]), + alternative), + report.Fixes(edit.Fix(fmt.Sprintf("replace with call to sort.%s", alternative), edit.ReplaceWithNode(pass.Fset, node, r)))) + } + code.Preorder(pass, fn, (*ast.AssignStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4030/sa4030.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4030/sa4030.go new file mode 100644 index 000000000..e54edc263 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4030/sa4030.go @@ -0,0 +1,64 @@ +package sa4030 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4030", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Ineffective attempt at generating random number", + Text: ` +Functions in the \'math/rand\' package that accept upper limits, such +as \'Intn\', generate random numbers in the half-open interval [0,n). In +other words, the generated numbers will be \'>= 0\' and \'< n\' – they +don't include \'n\'. \'rand.Intn(1)\' therefore doesn't generate \'0\' +or \'1\', it always generates \'0\'.`, + Since: "2022.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ineffectiveRandIntQ = pattern.MustParse(` + (CallExpr + (Symbol + name@(Or + "math/rand.Int31n" + "math/rand.Int63n" + "math/rand.Intn" + "(*math/rand.Rand).Int31n" + "(*math/rand.Rand).Int63n" + "(*math/rand.Rand).Intn")) + [(IntegerLiteral "1")])`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, ineffectiveRandIntQ, node) + if !ok { + return + } + + report.Report(pass, node, + fmt.Sprintf("%s(n) generates a random value 0 <= x < n; that is, the generated values don't include n; %s therefore always returns 0", + m.State["name"], report.Render(pass, node))) + } + + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4031/sa4031.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4031/sa4031.go new file mode 100644 index 000000000..c7740b4a6 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4031/sa4031.go @@ -0,0 +1,162 @@ +package sa4031 + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "sort" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/pattern" + "honnef.co/go/tools/staticcheck/sa4022" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4031", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Checking never-nil value against nil`, + Since: "2022.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var allocationNilCheckQ = pattern.MustParse(`(IfStmt _ cond@(BinaryExpr lhs op@(Or "==" "!=") (Builtin "nil")) _ _)`) + +func run(pass *analysis.Pass) (interface{}, error) { + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg + + var path []ast.Node + fn := func(node ast.Node, stack []ast.Node) { + m, ok := code.Match(pass, allocationNilCheckQ, node) + if !ok { + return + } + cond := m.State["cond"].(ast.Node) + if _, ok := code.Match(pass, sa4022.CheckAddressIsNilQ, cond); ok { + // Don't duplicate diagnostics reported by SA4022 + return + } + lhs := m.State["lhs"].(ast.Expr) + path = path[:0] + for i := len(stack) - 1; i >= 0; i-- { + path = append(path, stack[i]) + } + irfn := ir.EnclosingFunction(irpkg, path) + if irfn == nil { + // For example for functions named "_", because we don't generate IR for them. + return + } + v, isAddr := irfn.ValueForExpr(lhs) + if isAddr { + return + } + + seen := map[ir.Value]struct{}{} + var values []ir.Value + var neverNil func(v ir.Value, track bool) bool + neverNil = func(v ir.Value, track bool) bool { + if _, ok := seen[v]; ok { + return true + } + seen[v] = struct{}{} + switch v := v.(type) { + case *ir.MakeClosure, *ir.Function: + if track { + values = append(values, v) + } + return true + case *ir.MakeChan, *ir.MakeMap, *ir.MakeSlice, *ir.Alloc: + if track { + values = append(values, v) + } + return true + case *ir.Slice: + if track { + values = append(values, v) + } + return neverNil(v.X, false) + case *ir.FieldAddr: + if track { + values = append(values, v) + } + return neverNil(v.X, false) + case *ir.Sigma: + return neverNil(v.X, true) + case *ir.Phi: + for _, e := range v.Edges { + if !neverNil(e, true) { + return false + } + } + return true + default: + return false + } + } + + if !neverNil(v, true) { + return + } + + var qualifier string + if op := m.State["op"].(token.Token); op == token.EQL { + qualifier = "never" + } else { + qualifier = "always" + } + fallback := fmt.Sprintf("this nil check is %s true", qualifier) + + sort.Slice(values, func(i, j int) bool { return values[i].Pos() < values[j].Pos() }) + + if ident, ok := m.State["lhs"].(*ast.Ident); ok { + if _, ok := pass.TypesInfo.ObjectOf(ident).(*types.Var); ok { + var opts []report.Option + if v.Parent() == irfn { + if len(values) == 1 { + opts = append(opts, report.Related(values[0], fmt.Sprintf("this is the value of %s", ident.Name))) + } else { + for _, vv := range values { + opts = append(opts, report.Related(vv, fmt.Sprintf("this is one of the value of %s", ident.Name))) + } + } + } + + switch v.(type) { + case *ir.MakeClosure, *ir.Function: + report.Report(pass, cond, "the checked variable contains a function and is never nil; did you mean to call it?", opts...) + default: + report.Report(pass, cond, fallback, opts...) + } + } else { + if _, ok := v.(*ir.Function); ok { + report.Report(pass, cond, "functions are never nil; did you mean to call it?") + } else { + report.Report(pass, cond, fallback) + } + } + } else { + if _, ok := v.(*ir.Function); ok { + report.Report(pass, cond, "functions are never nil; did you mean to call it?") + } else { + report.Report(pass, cond, fallback) + } + } + } + code.PreorderStack(pass, fn, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa4032/sa4032.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa4032/sa4032.go new file mode 100644 index 000000000..28dae9a05 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa4032/sa4032.go @@ -0,0 +1,218 @@ +package sa4032 + +import ( + "fmt" + "go/ast" + "go/build/constraint" + "go/constant" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/knowledge" + "honnef.co/go/tools/pattern" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA4032", + Run: CheckImpossibleGOOSGOARCH, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Comparing \'runtime.GOOS\' or \'runtime.GOARCH\' against impossible value`, + Since: "2024.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + goosComparisonQ = pattern.MustParse(`(BinaryExpr (Symbol "runtime.GOOS") op@(Or "==" "!=") lit@(BasicLit "STRING" _))`) + goarchComparisonQ = pattern.MustParse(`(BinaryExpr (Symbol "runtime.GOARCH") op@(Or "==" "!=") lit@(BasicLit "STRING" _))`) +) + +func CheckImpossibleGOOSGOARCH(pass *analysis.Pass) (any, error) { + // TODO(dh): validate GOOS and GOARCH together. that is, + // given '(linux && amd64) || (windows && mips)', + // flag 'if runtime.GOOS == "linux" && runtime.GOARCH == "mips"' + // + // We can't use our IR for the control flow graph, because go/types constant folds constant comparisons, so + // 'runtime.GOOS == "windows"' will just become 'false'. We can't use the AST-based CFG builder from x/tools, + // because it doesn't model branch conditions. + + for _, f := range pass.Files { + expr, ok := code.BuildConstraints(pass, f) + if !ok { + continue + } + + ast.Inspect(f, func(node ast.Node) bool { + if m, ok := code.Match(pass, goosComparisonQ, node); ok { + tv := pass.TypesInfo.Types[m.State["lit"].(ast.Expr)] + goos := constant.StringVal(tv.Value) + + if _, ok := knowledge.KnownGOOS[goos]; !ok { + // Don't try to reason about GOOS values we don't know about. Maybe the user is using a newer + // version of Go that supports a new target, or maybe they run a fork of Go. + return true + } + sat, ok := validateGOOSComparison(expr, goos) + if !ok { + return true + } + if !sat { + // Note that we do not have to worry about constraints that can never be satisfied, such as 'linux + // && windows'. Packages with such files will not be passed to Staticcheck in the first place, + // precisely because the constraints aren't satisfiable. + report.Report(pass, node, + fmt.Sprintf("due to the file's build constraints, runtime.GOOS will never equal %q", goos)) + } + } else if m, ok := code.Match(pass, goarchComparisonQ, node); ok { + tv := pass.TypesInfo.Types[m.State["lit"].(ast.Expr)] + goarch := constant.StringVal(tv.Value) + + if _, ok := knowledge.KnownGOARCH[goarch]; !ok { + // Don't try to reason about GOARCH values we don't know about. Maybe the user is using a newer + // version of Go that supports a new target, or maybe they run a fork of Go. + return true + } + sat, ok := validateGOARCHComparison(expr, goarch) + if !ok { + return true + } + if !sat { + // Note that we do not have to worry about constraints that can never be satisfied, such as 'amd64 + // && mips'. Packages with such files will not be passed to Staticcheck in the first place, + // precisely because the constraints aren't satisfiable. + report.Report(pass, node, + fmt.Sprintf("due to the file's build constraints, runtime.GOARCH will never equal %q", goarch)) + } + } + return true + }) + } + + return nil, nil +} +func validateGOOSComparison(expr constraint.Expr, goos string) (sat bool, didCheck bool) { + matchGoosTag := func(tag string, goos string) (ok bool, goosTag bool) { + switch tag { + case "aix", + "android", + "dragonfly", + "freebsd", + "hurd", + "illumos", + "ios", + "js", + "netbsd", + "openbsd", + "plan9", + "wasip1", + "windows": + return goos == tag, true + case "darwin": + return (goos == "darwin" || goos == "ios"), true + case "linux": + return (goos == "linux" || goos == "android"), true + case "solaris": + return (goos == "solaris" || goos == "illumos"), true + case "unix": + return (goos == "aix" || + goos == "android" || + goos == "darwin" || + goos == "dragonfly" || + goos == "freebsd" || + goos == "hurd" || + goos == "illumos" || + goos == "ios" || + goos == "linux" || + goos == "netbsd" || + goos == "openbsd" || + goos == "solaris"), true + default: + return false, false + } + } + + return validateTagComparison(expr, func(tag string) (matched bool, special bool) { + return matchGoosTag(tag, goos) + }) +} + +func validateGOARCHComparison(expr constraint.Expr, goarch string) (sat bool, didCheck bool) { + matchGoarchTag := func(tag string, goarch string) (ok bool, goosTag bool) { + switch tag { + case "386", + "amd64", + "arm", + "arm64", + "loong64", + "mips", + "mipsle", + "mips64", + "mips64le", + "ppc64", + "ppc64le", + "riscv64", + "s390x", + "sparc64", + "wasm": + return goarch == tag, true + default: + return false, false + } + } + + return validateTagComparison(expr, func(tag string) (matched bool, special bool) { + return matchGoarchTag(tag, goarch) + }) +} + +func validateTagComparison(expr constraint.Expr, matchSpecialTag func(tag string) (matched bool, special bool)) (sat bool, didCheck bool) { + otherTags := map[string]int{} + // Collect all tags that aren't known architecture-based tags + b := expr.Eval(func(tag string) bool { + ok, special := matchSpecialTag(tag) + if !special { + // Assign an ID to this tag, but only if we haven't seen it before. For the expression 'foo && foo', this + // callback will be called twice for the 'foo' tag. + if _, ok := otherTags[tag]; !ok { + otherTags[tag] = len(otherTags) + } + } + return ok + }) + + if b || len(otherTags) == 0 { + // We're done. Either the formula can be satisfied regardless of the values of non-special tags, if any, + // or there aren't any non-special tags and the formula cannot be satisfied. + return b, true + } + + if len(otherTags) > 10 { + // We have to try 2**len(otherTags) combinations of tags. 2**10 is about the worst we're willing to try. + return false, false + } + + // Try all permutations of otherTags. If any evaluates to true, then the expression is satisfiable. + for bits := 0; bits < 1< 1 { + isGoFlagsTag := importsGoFlags && + (k == "choice" || k == "optional-value" || k == "default") + if !isGoFlagsTag { + report.Report(pass, field.Tag, fmt.Sprintf("duplicate struct tag %q", k)) + } + } + + switch k { + case "json": + checkJSONTag(pass, field, v[0]) + case "xml": + if _, err := fakexml.StructFieldInfo(rt.Field(i)); err != nil { + report.Report(pass, field.Tag, fmt.Sprintf("invalid XML tag: %s", err)) + } + checkXMLTag(pass, field, v[0]) + } + } + } + } + code.Preorder(pass, fn, (*ast.StructType)(nil)) + return nil, nil +} + +func checkJSONTag(pass *analysis.Pass, field *ast.Field, tag string) { + if pass.Pkg.Path() == "encoding/json" || pass.Pkg.Path() == "encoding/json_test" { + // don't flag malformed JSON tags in the encoding/json + // package; it knows what it is doing, and it is testing + // itself. + return + } + //lint:ignore SA9003 TODO(dh): should we flag empty tags? + if len(tag) == 0 { + } + if i := strings.Index(tag, ",format:"); i >= 0 { + tag = tag[:i] + } + fields := strings.Split(tag, ",") + for _, r := range fields[0] { + if !unicode.IsLetter(r) && !unicode.IsDigit(r) && !strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", r) { + report.Report(pass, field.Tag, fmt.Sprintf("invalid JSON field name %q", fields[0])) + } + } + options := make(map[string]int) + for _, s := range fields[1:] { + switch s { + case "": + // allow stuff like "-," + case "string": + // only for string, floating point, integer and bool + options[s]++ + tset := typeutil.NewTypeSet(pass.TypesInfo.TypeOf(field.Type)) + if len(tset.Terms) == 0 { + // TODO(dh): improve message, call out the use of type parameters + report.Report(pass, field.Tag, "the JSON string option only applies to fields of type string, floating point, integer or bool, or pointers to those") + continue + } + for _, term := range tset.Terms { + T := typeutil.Dereference(term.Type().Underlying()) + for _, term2 := range typeutil.NewTypeSet(T).Terms { + basic, ok := term2.Type().Underlying().(*types.Basic) + if !ok || (basic.Info()&(types.IsBoolean|types.IsInteger|types.IsFloat|types.IsString)) == 0 { + // TODO(dh): improve message, show how we arrived at the type + report.Report(pass, field.Tag, "the JSON string option only applies to fields of type string, floating point, integer or bool, or pointers to those") + } + } + } + case "omitzero", "omitempty", "nocase", "inline", "unknown": + options[s]++ + default: + report.Report(pass, field.Tag, fmt.Sprintf("unknown JSON option %q", s)) + } + } + var duplicates []string + for option, n := range options { + if n > 1 { + duplicates = append(duplicates, option) + } + } + if len(duplicates) > 0 { + sort.Strings(duplicates) + for _, option := range duplicates { + report.Report(pass, field.Tag, fmt.Sprintf("duplicate JSON option %q", option)) + } + } +} + +func checkXMLTag(pass *analysis.Pass, field *ast.Field, tag string) { + //lint:ignore SA9003 TODO(dh): should we flag empty tags? + if len(tag) == 0 { + } + fields := strings.Split(tag, ",") + counts := map[string]int{} + for _, s := range fields[1:] { + switch s { + case "attr", "chardata", "cdata", "innerxml", "comment": + counts[s]++ + case "omitempty", "any": + counts[s]++ + case "": + default: + report.Report(pass, field.Tag, fmt.Sprintf("invalid XML tag: unknown option %q", s)) + } + } + for k, v := range counts { + if v > 1 { + report.Report(pass, field.Tag, fmt.Sprintf("invalid XML tag: duplicate option %q", k)) + } + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/structtag.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa5008/structtag.go similarity index 98% rename from tools/vendor/honnef.co/go/tools/staticcheck/structtag.go rename to tools/vendor/honnef.co/go/tools/staticcheck/sa5008/structtag.go index 38830a22c..e8121e508 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/structtag.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa5008/structtag.go @@ -1,7 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. // Copyright 2019 Dominik Honnef. All rights reserved. -package staticcheck +package sa5008 import "strconv" diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa5009/sa5009.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa5009/sa5009.go new file mode 100644 index 000000000..4375c7fdc --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa5009/sa5009.go @@ -0,0 +1,409 @@ +package sa5009 + +import ( + "fmt" + "go/constant" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + "honnef.co/go/tools/printf" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA5009", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Invalid Printf call`, + Since: "2019.2", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +// TODO(dh): detect printf wrappers +var rules = map[string]callcheck.Check{ + "fmt.Errorf": func(call *callcheck.Call) { check(call, 0, 1) }, + "fmt.Printf": func(call *callcheck.Call) { check(call, 0, 1) }, + "fmt.Sprintf": func(call *callcheck.Call) { check(call, 0, 1) }, + "fmt.Fprintf": func(call *callcheck.Call) { check(call, 1, 2) }, + "golang.org/x/xerrors.Errorf": func(call *callcheck.Call) { check(call, 0, 1) }, +} + +type verbFlag int + +const ( + isInt verbFlag = 1 << iota + isBool + isFP + isString + isPointer + // Verbs that accept "pseudo pointers" will sometimes dereference + // non-nil pointers. For example, %x on a non-nil *struct will print the + // individual fields, but on a nil pointer it will print the address. + isPseudoPointer + isSlice + isAny + noRecurse +) + +var verbs = [...]verbFlag{ + 'b': isPseudoPointer | isInt | isFP, + 'c': isInt, + 'd': isPseudoPointer | isInt, + 'e': isFP, + 'E': isFP, + 'f': isFP, + 'F': isFP, + 'g': isFP, + 'G': isFP, + 'o': isPseudoPointer | isInt, + 'O': isPseudoPointer | isInt, + 'p': isSlice | isPointer | noRecurse, + 'q': isInt | isString, + 's': isString, + 't': isBool, + 'T': isAny, + 'U': isInt, + 'v': isAny, + 'X': isPseudoPointer | isInt | isFP | isString, + 'x': isPseudoPointer | isInt | isFP | isString, +} + +func check(call *callcheck.Call, fIdx, vIdx int) { + f := call.Args[fIdx] + var args []ir.Value + switch v := call.Args[vIdx].Value.Value.(type) { + case *ir.Slice: + var ok bool + args, ok = irutil.Vararg(v) + if !ok { + // We don't know what the actual arguments to the function are + return + } + case *ir.Const: + // nil, i.e. no arguments + default: + // We don't know what the actual arguments to the function are + return + } + checkImpl(f, f.Value.Value, args) +} + +func checkImpl(carg *callcheck.Argument, f ir.Value, args []ir.Value) { + var msCache *typeutil.MethodSetCache + if f.Parent() != nil { + msCache = &f.Parent().Prog.MethodSets + } + + elem := func(T types.Type, verb rune) ([]types.Type, bool) { + if verbs[verb]&noRecurse != 0 { + return []types.Type{T}, false + } + switch T := T.(type) { + case *types.Slice: + if verbs[verb]&isSlice != 0 { + return []types.Type{T}, false + } + if verbs[verb]&isString != 0 && types.Identical(T.Elem().Underlying(), types.Typ[types.Byte]) { + return []types.Type{T}, false + } + return []types.Type{T.Elem()}, true + case *types.Map: + key := T.Key() + val := T.Elem() + return []types.Type{key, val}, true + case *types.Struct: + out := make([]types.Type, 0, T.NumFields()) + for i := 0; i < T.NumFields(); i++ { + out = append(out, T.Field(i).Type()) + } + return out, true + case *types.Array: + return []types.Type{T.Elem()}, true + default: + return []types.Type{T}, false + } + } + isInfo := func(T types.Type, info types.BasicInfo) bool { + basic, ok := T.Underlying().(*types.Basic) + return ok && basic.Info()&info != 0 + } + + isFormatter := func(T types.Type, ms *types.MethodSet) bool { + sel := ms.Lookup(nil, "Format") + if sel == nil { + return false + } + fn, ok := sel.Obj().(*types.Func) + if !ok { + // should be unreachable + return false + } + sig := fn.Type().(*types.Signature) + if sig.Params().Len() != 2 { + return false + } + // TODO(dh): check the types of the arguments for more + // precision + if sig.Results().Len() != 0 { + return false + } + return true + } + + var seen typeutil.Map[struct{}] + var checkType func(verb rune, T types.Type, top bool) bool + checkType = func(verb rune, T types.Type, top bool) bool { + if top { + seen = typeutil.Map[struct{}]{} + } + if _, ok := seen.At(T); ok { + return true + } + seen.Set(T, struct{}{}) + if int(verb) >= len(verbs) { + // Unknown verb + return true + } + + flags := verbs[verb] + if flags == 0 { + // Unknown verb + return true + } + + ms := msCache.MethodSet(T) + if isFormatter(T, ms) { + // the value is responsible for formatting itself + return true + } + + if flags&isString != 0 && (types.Implements(T, knowledge.Interfaces["fmt.Stringer"]) || types.Implements(T, knowledge.Interfaces["error"])) { + // Check for stringer early because we're about to dereference + return true + } + + T = T.Underlying() + if flags&(isPointer|isPseudoPointer) == 0 && top { + T = typeutil.Dereference(T) + } + if flags&isPseudoPointer != 0 && top { + t := typeutil.Dereference(T) + if _, ok := t.Underlying().(*types.Struct); ok { + T = t + } + } + + if _, ok := T.(*types.Interface); ok { + // We don't know what's in the interface + return true + } + + var info types.BasicInfo + if flags&isInt != 0 { + info |= types.IsInteger + } + if flags&isBool != 0 { + info |= types.IsBoolean + } + if flags&isFP != 0 { + info |= types.IsFloat | types.IsComplex + } + if flags&isString != 0 { + info |= types.IsString + } + + if info != 0 && isInfo(T, info) { + return true + } + + if flags&isString != 0 { + isStringyElem := func(typ types.Type) bool { + if typ, ok := typ.Underlying().(*types.Basic); ok { + return typ.Kind() == types.Byte + } + return false + } + switch T := T.(type) { + case *types.Slice: + if isStringyElem(T.Elem()) { + return true + } + case *types.Array: + if isStringyElem(T.Elem()) { + return true + } + } + if types.Implements(T, knowledge.Interfaces["fmt.Stringer"]) || types.Implements(T, knowledge.Interfaces["error"]) { + return true + } + } + + if flags&isPointer != 0 && typeutil.IsPointerLike(T) { + return true + } + if flags&isPseudoPointer != 0 { + switch U := T.Underlying().(type) { + case *types.Pointer: + if !top { + return true + } + + if _, ok := U.Elem().Underlying().(*types.Struct); !ok { + // TODO(dh): can this condition ever be false? For + // *T, if T is a struct, we'll already have + // dereferenced it, meaning the *types.Pointer + // branch couldn't have been taken. For T that + // aren't structs, this condition will always + // evaluate to true. + return true + } + case *types.Chan, *types.Signature: + // Channels and functions are always treated as + // pointers and never recursed into. + return true + case *types.Basic: + if U.Kind() == types.UnsafePointer { + return true + } + case *types.Interface: + // we will already have bailed if the type is an + // interface. + panic("unreachable") + default: + // other pointer-like types, such as maps or slices, + // will be printed element-wise. + } + } + + if flags&isSlice != 0 { + if _, ok := T.(*types.Slice); ok { + return true + } + } + + if flags&isAny != 0 { + return true + } + + elems, ok := elem(T.Underlying(), verb) + if !ok { + return false + } + for _, elem := range elems { + if !checkType(verb, elem, false) { + return false + } + } + + return true + } + + k, ok := irutil.Flatten(f).(*ir.Const) + if !ok { + return + } + actions, err := printf.Parse(constant.StringVal(k.Value)) + if err != nil { + carg.Invalid("couldn't parse format string") + return + } + + ptr := 1 + hasExplicit := false + + checkStar := func(verb printf.Verb, star printf.Argument) bool { + if star, ok := star.(printf.Star); ok { + idx := 0 + if star.Index == -1 { + idx = ptr + ptr++ + } else { + hasExplicit = true + idx = star.Index + ptr = star.Index + 1 + } + if idx == 0 { + carg.Invalid(fmt.Sprintf("Printf format %s reads invalid arg 0; indices are 1-based", verb.Raw)) + return false + } + if idx > len(args) { + carg.Invalid( + fmt.Sprintf("Printf format %s reads arg #%d, but call has only %d args", + verb.Raw, idx, len(args))) + return false + } + if arg, ok := args[idx-1].(*ir.MakeInterface); ok { + if !isInfo(arg.X.Type(), types.IsInteger) { + carg.Invalid(fmt.Sprintf("Printf format %s reads non-int arg #%d as argument of *", verb.Raw, idx)) + } + } + } + return true + } + + // We only report one problem per format string. Making a + // mistake with an index tends to invalidate all future + // implicit indices. + for _, action := range actions { + verb, ok := action.(printf.Verb) + if !ok { + continue + } + + if !checkStar(verb, verb.Width) || !checkStar(verb, verb.Precision) { + return + } + + off := ptr + if verb.Value != -1 { + hasExplicit = true + off = verb.Value + } + if off > len(args) { + carg.Invalid( + fmt.Sprintf("Printf format %s reads arg #%d, but call has only %d args", + verb.Raw, off, len(args))) + return + } else if verb.Value == 0 && verb.Letter != '%' { + carg.Invalid(fmt.Sprintf("Printf format %s reads invalid arg 0; indices are 1-based", verb.Raw)) + return + } else if off != 0 { + arg, ok := args[off-1].(*ir.MakeInterface) + if ok { + if !checkType(verb.Letter, arg.X.Type(), true) { + carg.Invalid(fmt.Sprintf("Printf format %s has arg #%d of wrong type %s", + verb.Raw, ptr, args[ptr-1].(*ir.MakeInterface).X.Type())) + return + } + } + } + + switch verb.Value { + case -1: + // Consume next argument + ptr++ + case 0: + // Don't consume any arguments + default: + ptr = verb.Value + 1 + } + } + + if !hasExplicit && ptr <= len(args) { + carg.Invalid(fmt.Sprintf("Printf call needs %d args but has %d args", ptr-1, len(args))) + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa5010/sa5010.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa5010/sa5010.go new file mode 100644 index 000000000..49c8ec287 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa5010/sa5010.go @@ -0,0 +1,106 @@ +package sa5010 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA5010", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Impossible type assertion`, + + Text: `Some type assertions can be statically proven to be +impossible. This is the case when the method sets of both +arguments of the type assertion conflict with each other, for +example by containing the same method with different +signatures. + +The Go compiler already applies this check when asserting from an +interface value to a concrete type. If the concrete type misses +methods from the interface, or if function signatures don't match, +then the type assertion can never succeed. + +This check applies the same logic when asserting from one interface to +another. If both interface types contain the same method but with +different signatures, then the type assertion can never succeed, +either.`, + + Since: "2020.1", + Severity: lint.SeverityWarning, + // Technically this should be MergeIfAll, but the Go compiler + // already flags some impossible type assertions, so + // MergeIfAny is consistent with the compiler. + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + type entry struct { + l, r *types.Func + } + + msc := &pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg.Prog.MethodSets + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + assert, ok := instr.(*ir.TypeAssert) + if !ok { + continue + } + var wrong []entry + left := assert.X.Type() + right := assert.AssertedType + righti, ok := right.Underlying().(*types.Interface) + + if !ok { + // We only care about interface->interface + // assertions. The Go compiler already catches + // impossible interface->concrete assertions. + continue + } + + ms := msc.MethodSet(left) + for i := 0; i < righti.NumMethods(); i++ { + mr := righti.Method(i).Origin() + sel := ms.Lookup(mr.Pkg(), mr.Name()) + if sel == nil { + continue + } + ml := sel.Obj().(*types.Func).Origin() + if types.AssignableTo(ml.Type(), mr.Type()) { + continue + } + + wrong = append(wrong, entry{ml, mr}) + } + + if len(wrong) != 0 { + s := fmt.Sprintf("impossible type assertion; %s and %s contradict each other:", + types.TypeString(left, types.RelativeTo(pass.Pkg)), + types.TypeString(right, types.RelativeTo(pass.Pkg))) + for _, e := range wrong { + s += fmt.Sprintf("\n\twrong type for %s method", e.l.Name()) + s += fmt.Sprintf("\n\t\thave %s", e.l.Type()) + s += fmt.Sprintf("\n\t\twant %s", e.r.Type()) + } + report.Report(pass, assert, s) + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa5011/sa5011.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa5011/sa5011.go new file mode 100644 index 000000000..9f2f75799 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa5011/sa5011.go @@ -0,0 +1,221 @@ +package sa5011 + +import ( + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA5011", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Possible nil pointer dereference`, + + Text: `A pointer is being dereferenced unconditionally, while +also being checked against nil in another place. This suggests that +the pointer may be nil and dereferencing it may panic. This is +commonly a result of improperly ordered code or missing return +statements. Consider the following examples: + + func fn(x *int) { + fmt.Println(*x) + + // This nil check is equally important for the previous dereference + if x != nil { + foo(*x) + } + } + + func TestFoo(t *testing.T) { + x := compute() + if x == nil { + t.Errorf("nil pointer received") + } + + // t.Errorf does not abort the test, so if x is nil, the next line will panic. + foo(*x) + } + +Staticcheck tries to deduce which functions abort control flow. +For example, it is aware that a function will not continue +execution after a call to \'panic\' or \'log.Fatal\'. However, sometimes +this detection fails, in particular in the presence of +conditionals. Consider the following example: + + func Log(msg string, level int) { + fmt.Println(msg) + if level == levelFatal { + os.Exit(1) + } + } + + func Fatal(msg string) { + Log(msg, levelFatal) + } + + func fn(x *int) { + if x == nil { + Fatal("unexpected nil pointer") + } + fmt.Println(*x) + } + +Staticcheck will flag the dereference of \'x\', even though it is perfectly +safe. Staticcheck is not able to deduce that a call to +Fatal will exit the program. For the time being, the easiest +workaround is to modify the definition of Fatal like so: + + func Fatal(msg string) { + Log(msg, levelFatal) + panic("unreachable") + } + +We also hard-code functions from common logging packages such as +logrus. Please file an issue if we're missing support for a +popular package.`, + Since: "2020.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // This is an extremely trivial check that doesn't try to reason + // about control flow. That is, phis and sigmas do not propagate + // any information. As such, we can flag this: + // + // _ = *x + // if x == nil { return } + // + // but we cannot flag this: + // + // if x == nil { println(x) } + // _ = *x + // + // but we can flag this, because the if's body doesn't use x: + // + // if x == nil { println("this is bad") } + // _ = *x + // + // nor many other variations of conditional uses of or assignments to x. + // + // However, even this trivial implementation finds plenty of + // real-world bugs, such as dereference before nil pointer check, + // or using t.Error instead of t.Fatal when encountering nil + // pointers. + // + // On the flip side, our naive implementation avoids false positives in branches, such as + // + // if x != nil { _ = *x } + // + // due to the same lack of propagating information through sigma + // nodes. x inside the branch will be independent of the x in the + // nil pointer check. + // + // + // We could implement a more powerful check, but then we'd be + // getting false positives instead of false negatives because + // we're incapable of deducing relationships between variables. + // For example, a function might return a pointer and an error, + // and the error being nil guarantees that the pointer is not nil. + // Depending on the surrounding code, the pointer may still end up + // being checked against nil in one place, and guarded by a check + // on the error in another, which would lead to us marking some + // loads as unsafe. + // + // Unfortunately, simply hard-coding the relationship between + // return values wouldn't eliminate all false positives, either. + // Many other more subtle relationships exist. An abridged example + // from real code: + // + // if a == nil && b == nil { return } + // c := fn(a) + // if c != "" { _ = *a } + // + // where `fn` is guaranteed to return a non-empty string if a + // isn't nil. + // + // We choose to err on the side of false negatives. + + isNilConst := func(v ir.Value) bool { + if typeutil.IsPointerLike(v.Type()) { + if k, ok := v.(*ir.Const); ok { + return k.IsNil() + } + } + return false + } + + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + maybeNil := map[ir.Value]ir.Instruction{} + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + // Originally we looked at all ir.BinOp, but that would lead to calls like 'assert(x != nil)' causing false positives. + // Restrict ourselves to actual if statements, as these are more likely to affect control flow in a way we can observe. + if instr, ok := instr.(*ir.If); ok { + if cond, ok := instr.Cond.(*ir.BinOp); ok { + if isNilConst(cond.X) { + maybeNil[cond.Y] = cond + } + if isNilConst(cond.Y) { + maybeNil[cond.X] = cond + } + } + } + } + } + + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + var ptr ir.Value + switch instr := instr.(type) { + case *ir.Load: + ptr = instr.X + case *ir.Store: + ptr = instr.Addr + case *ir.IndexAddr: + ptr = instr.X + if typeutil.All(ptr.Type(), func(term *types.Term) bool { + if _, ok := term.Type().Underlying().(*types.Slice); ok { + return true + } + return false + }) { + // indexing a nil slice does not cause a nil pointer panic + // + // Note: This also works around the bad lowering of range loops over slices + // (https://github.com/dominikh/go-tools/issues/1053) + continue + } + case *ir.FieldAddr: + ptr = instr.X + } + if ptr != nil { + switch ptr.(type) { + case *ir.Alloc, *ir.FieldAddr, *ir.IndexAddr: + // these cannot be nil + continue + } + if r, ok := maybeNil[ptr]; ok { + report.Report(pass, instr, "possible nil pointer dereference", + report.Related(r, "this check suggests that the pointer can be nil")) + } + } + } + } + } + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa5012/sa5012.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa5012/sa5012.go new file mode 100644 index 000000000..350cf43d9 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa5012/sa5012.go @@ -0,0 +1,286 @@ +package sa5012 + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA5012", + Run: run, + FactTypes: []analysis.Fact{new(evenElements)}, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Passing odd-sized slice to function expecting even size", + Text: `Some functions that take slices as parameters expect the slices to have an even number of elements. +Often, these functions treat elements in a slice as pairs. +For example, \'strings.NewReplacer\' takes pairs of old and new strings, +and calling it with an odd number of elements would be an error.`, + Since: "2020.2", + Severity: lint.SeverityError, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +type evenElements struct{} + +func (evenElements) AFact() {} + +func (evenElements) String() string { return "needs even elements" } + +func findSliceLength(v ir.Value) int { + // TODO(dh): VRP would help here + + v = irutil.Flatten(v) + val := func(v ir.Value) int { + if v, ok := v.(*ir.Const); ok { + return int(v.Int64()) + } + return -1 + } + switch v := v.(type) { + case *ir.Slice: + low := 0 + high := -1 + if v.Low != nil { + low = val(v.Low) + } + if v.High != nil { + high = val(v.High) + } else { + switch vv := v.X.(type) { + case *ir.Alloc: + high = int(typeutil.Dereference(vv.Type()).Underlying().(*types.Array).Len()) + case *ir.Slice: + high = findSliceLength(vv) + } + } + if low == -1 || high == -1 { + return -1 + } + return high - low + default: + return -1 + } +} + +func flagSliceLens(pass *analysis.Pass) { + var tag evenElements + + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + call, ok := instr.(ir.CallInstruction) + if !ok { + continue + } + callee := call.Common().StaticCallee() + if callee == nil { + continue + } + for argi, arg := range call.Common().Args { + if callee.Signature.Recv() != nil { + if argi == 0 { + continue + } + argi-- + } + + _, ok := arg.Type().Underlying().(*types.Slice) + if !ok { + continue + } + param := callee.Signature.Params().At(argi) + if !pass.ImportObjectFact(param, &tag) { + continue + } + + // TODO handle stubs + + // we know the argument has to have even length. + // now let's try to find its length + if n := findSliceLength(arg); n > -1 && n%2 != 0 { + src := call.Source().(*ast.CallExpr).Args[argi] + sig := call.Common().Signature() + var label string + if argi == sig.Params().Len()-1 && sig.Variadic() { + label = "variadic argument" + } else { + label = "argument" + } + // Note that param.Name() is guaranteed to not + // be empty, otherwise the function couldn't + // have enforced its length. + report.Report(pass, src, fmt.Sprintf("%s %q is expected to have even number of elements, but has %d elements", label, param.Name(), n)) + } + } + } + } + } +} + +func findSliceLenChecks(pass *analysis.Pass) { + // mark all function parameters that have to be of even length + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, b := range fn.Blocks { + // all paths go through this block + if !b.Dominates(fn.Exit) { + continue + } + + // if foo % 2 != 0 + ifi, ok := b.Control().(*ir.If) + if !ok { + continue + } + cmp, ok := ifi.Cond.(*ir.BinOp) + if !ok { + continue + } + var needle uint64 + switch cmp.Op { + case token.NEQ: + // look for != 0 + needle = 0 + case token.EQL: + // look for == 1 + needle = 1 + default: + continue + } + + rem, ok1 := cmp.X.(*ir.BinOp) + k, ok2 := cmp.Y.(*ir.Const) + if ok1 != ok2 { + continue + } + if !ok1 { + rem, ok1 = cmp.Y.(*ir.BinOp) + k, ok2 = cmp.X.(*ir.Const) + } + if !ok1 || !ok2 || rem.Op != token.REM || k.Value.Kind() != constant.Int || k.Uint64() != needle { + continue + } + k, ok = rem.Y.(*ir.Const) + if !ok || k.Value.Kind() != constant.Int || k.Uint64() != 2 { + continue + } + + // if len(foo) % 2 != 0 + call, ok := rem.X.(*ir.Call) + if !ok || !irutil.IsCallTo(call.Common(), "len") { + continue + } + + // we're checking the length of a parameter that is a slice + // TODO(dh): support parameters that have flown through sigmas and phis + param, ok := call.Call.Args[0].(*ir.Parameter) + if !ok { + continue + } + if !typeutil.All(param.Type(), typeutil.IsSlice) { + continue + } + + // if len(foo) % 2 != 0 then panic + if _, ok := b.Succs[0].Control().(*ir.Panic); !ok { + continue + } + + pass.ExportObjectFact(param.Object(), new(evenElements)) + } + } +} + +func findIndirectSliceLenChecks(pass *analysis.Pass) { + seen := map[*ir.Function]struct{}{} + + var doFunction func(fn *ir.Function) + doFunction = func(fn *ir.Function) { + if _, ok := seen[fn]; ok { + return + } + seen[fn] = struct{}{} + + for _, b := range fn.Blocks { + // all paths go through this block + if !b.Dominates(fn.Exit) { + continue + } + + for _, instr := range b.Instrs { + call, ok := instr.(*ir.Call) + if !ok { + continue + } + callee := call.Call.StaticCallee() + if callee == nil { + continue + } + + if callee.Pkg == fn.Pkg || callee.Pkg == nil { + doFunction(callee) + } + + for argi, arg := range call.Call.Args { + if callee.Signature.Recv() != nil { + if argi == 0 { + continue + } + argi-- + } + + // TODO(dh): support parameters that have flown through length-preserving instructions + param, ok := arg.(*ir.Parameter) + if !ok { + continue + } + if !typeutil.All(param.Type(), typeutil.IsSlice) { + continue + } + + // We can't use callee.Params to look up the + // parameter, because Params is not populated for + // external functions. In our modular analysis. + // any function in any package that isn't the + // current package is considered "external", as it + // has been loaded from export data only. + sigParams := callee.Signature.Params() + + if !pass.ImportObjectFact(sigParams.At(argi), new(evenElements)) { + continue + } + pass.ExportObjectFact(param.Object(), new(evenElements)) + } + } + } + } + + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + doFunction(fn) + } +} + +func run(pass *analysis.Pass) (interface{}, error) { + findSliceLenChecks(pass) + findIndirectSliceLenChecks(pass) + flagSliceLens(pass) + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa6000/sa6000.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa6000/sa6000.go new file mode 100644 index 000000000..958cc8ff5 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa6000/sa6000.go @@ -0,0 +1,57 @@ +package sa6000 + +import ( + "fmt" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA6000", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Using \'regexp.Match\' or related in a loop, should use \'regexp.Compile\'`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "regexp.Match": check("regexp.Match"), + "regexp.MatchReader": check("regexp.MatchReader"), + "regexp.MatchString": check("regexp.MatchString"), +} + +func check(name string) callcheck.Check { + return func(call *callcheck.Call) { + if callcheck.ExtractConst(call.Args[0].Value) == nil { + return + } + if !isInLoop(call.Instr.Block()) { + return + } + call.Invalid(fmt.Sprintf("calling %s in a loop has poor performance, consider using regexp.Compile", name)) + } +} + +func isInLoop(b *ir.BasicBlock) bool { + sets := irutil.FindLoops(b.Parent()) + for _, set := range sets { + if set.Has(b) { + return true + } + } + return false +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa6001/sa6001.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa6001/sa6001.go new file mode 100644 index 000000000..ae19f0297 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa6001/sa6001.go @@ -0,0 +1,124 @@ +package sa6001 + +import ( + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA6001", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Missing an optimization opportunity when indexing maps by byte slices`, + + Text: `Map keys must be comparable, which precludes the use of byte slices. +This usually leads to using string keys and converting byte slices to +strings. + +Normally, a conversion of a byte slice to a string needs to copy the data and +causes allocations. The compiler, however, recognizes \'m[string(b)]\' and +uses the data of \'b\' directly, without copying it, because it knows that +the data can't change during the map lookup. This leads to the +counter-intuitive situation that + + k := string(b) + println(m[k]) + println(m[k]) + +will be less efficient than + + println(m[string(b)]) + println(m[string(b)]) + +because the first version needs to copy and allocate, while the second +one does not. + +For some history on this optimization, check out commit +f5f5a8b6209f84961687d993b93ea0d397f5d5bf in the Go repository.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, b := range fn.Blocks { + insLoop: + for _, ins := range b.Instrs { + var fromType types.Type + var toType types.Type + + // find []byte -> string conversions + switch ins := ins.(type) { + case *ir.Convert: + fromType = ins.X.Type() + toType = ins.Type() + case *ir.MultiConvert: + fromType = ins.X.Type() + toType = ins.Type() + default: + continue + } + if toType != types.Universe.Lookup("string").Type() { + continue + } + tset := typeutil.NewTypeSet(fromType) + // If at least one of the types is []byte, then it's more efficient to inline the conversion + if !tset.Any(func(term *types.Term) bool { + s, ok := term.Type().Underlying().(*types.Slice) + return ok && s.Elem().Underlying() == types.Universe.Lookup("byte").Type() + }) { + continue + } + refs := ins.Referrers() + // need at least two (DebugRef) references: the + // conversion and the *ast.Ident + if refs == nil || len(*refs) < 2 { + continue + } + ident := false + // skip first reference, that's the conversion itself + for _, ref := range (*refs)[1:] { + switch ref := ref.(type) { + case *ir.DebugRef: + if _, ok := ref.Expr.(*ast.Ident); !ok { + // the string seems to be used somewhere + // unexpected; the default branch should + // catch this already, but be safe + continue insLoop + } else { + ident = true + } + case *ir.MapLookup: + default: + // the string is used somewhere else than a + // map lookup + continue insLoop + } + } + + // the result of the conversion wasn't assigned to an + // identifier + if !ident { + continue + } + report.Report(pass, ins, "m[string(key)] would be more efficient than k := string(key); m[k]") + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa6002/sa6002.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa6002/sa6002.go new file mode 100644 index 000000000..91ec73030 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa6002/sa6002.go @@ -0,0 +1,52 @@ +package sa6002 + +import ( + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA6002", + Requires: []*analysis.Analyzer{buildir.Analyzer}, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Storing non-pointer values in \'sync.Pool\' allocates memory`, + Text: `A \'sync.Pool\' is used to avoid unnecessary allocations and reduce the +amount of work the garbage collector has to do. + +When passing a value that is not a pointer to a function that accepts +an interface, the value needs to be placed on the heap, which means an +additional allocation. Slices are a common thing to put in sync.Pools, +and they're structs with 3 fields (length, capacity, and a pointer to +an array). In order to avoid the extra allocation, one should store a +pointer to the slice instead. + +See the comments on https://go-review.googlesource.com/c/go/+/24371 +that discuss this problem.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + "(*sync.Pool).Put": func(call *callcheck.Call) { + arg := call.Args[knowledge.Arg("(*sync.Pool).Put.x")] + typ := arg.Value.Value.Type() + _, isSlice := typ.Underlying().(*types.Slice) + if !typeutil.IsPointerLike(typ) || isSlice { + arg.Invalid("argument should be pointer-like to avoid allocations") + } + }, +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa6003/sa6003.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa6003/sa6003.go new file mode 100644 index 000000000..271ee9f0a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa6003/sa6003.go @@ -0,0 +1,42 @@ +package sa6003 + +import ( + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/internal/sharedcheck" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA6003", + Run: sharedcheck.CheckRangeStringRunes, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Converting a string to a slice of runes before ranging over it`, + Text: `You may want to loop over the runes in a string. Instead of converting +the string to a slice of runes and looping over that, you can loop +over the string itself. That is, + + for _, r := range s {} + +and + + for _, r := range []rune(s) {} + +will yield the same values. The first version, however, will be faster +and avoid unnecessary memory allocations. + +Do note that if you are interested in the indices, ranging over a +string and over a slice of runes will yield different indices. The +first one yields byte offsets, while the second one yields indices in +the slice of runes.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa6005/sa6005.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa6005/sa6005.go new file mode 100644 index 000000000..f7c151198 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa6005/sa6005.go @@ -0,0 +1,80 @@ +package sa6005 + +import ( + "go/ast" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA6005", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Inefficient string comparison with \'strings.ToLower\' or \'strings.ToUpper\'`, + Text: `Converting two strings to the same case and comparing them like so + + if strings.ToLower(s1) == strings.ToLower(s2) { + ... + } + +is significantly more expensive than comparing them with +\'strings.EqualFold(s1, s2)\'. This is due to memory usage as well as +computational complexity. + +\'strings.ToLower\' will have to allocate memory for the new strings, as +well as convert both strings fully, even if they differ on the very +first byte. strings.EqualFold, on the other hand, compares the strings +one character at a time. It doesn't need to create two intermediate +strings and can return as soon as the first non-matching character has +been found. + +For a more in-depth explanation of this issue, see +https://blog.digitalocean.com/how-to-efficiently-compare-strings-in-go/`, + Since: "2019.2", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkToLowerToUpperComparisonQ = pattern.MustParse(` + (BinaryExpr + (CallExpr fun@(Symbol (Or "strings.ToLower" "strings.ToUpper")) [a]) + tok@(Or "==" "!=") + (CallExpr fun [b]))`) + checkToLowerToUpperComparisonR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "strings") (Ident "EqualFold")) [a b])`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, checkToLowerToUpperComparisonQ, node) + if !ok { + return + } + rn := pattern.NodeToAST(checkToLowerToUpperComparisonR.Root, m.State).(ast.Expr) + if m.State["tok"].(token.Token) == token.NEQ { + rn = &ast.UnaryExpr{ + Op: token.NOT, + X: rn, + } + } + + report.Report(pass, node, "should use strings.EqualFold instead", report.Fixes(edit.Fix("replace with strings.EqualFold", edit.ReplaceWithNode(pass.Fset, node, rn)))) + } + + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa6006/sa6006.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa6006/sa6006.go new file mode 100644 index 000000000..768905ab4 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa6006/sa6006.go @@ -0,0 +1,53 @@ +package sa6006 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA6006", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Using io.WriteString to write \'[]byte\'`, + Text: `Using io.WriteString to write a slice of bytes, as in + + io.WriteString(w, string(b)) + +is both unnecessary and inefficient. Converting from \'[]byte\' to \'string\' +has to allocate and copy the data, and we could simply use \'w.Write(b)\' +instead.`, + + Since: "2024.1", + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ioWriteStringConversion = pattern.MustParse(`(CallExpr (Symbol "io.WriteString") [_ (CallExpr (Builtin "string") [arg])])`) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + m, ok := code.Match(pass, ioWriteStringConversion, node) + if !ok { + return + } + if !code.IsOfStringConvertibleByteSlice(pass, m.State["arg"].(ast.Expr)) { + return + } + report.Report(pass, node, "use io.Writer.Write instead of converting from []byte to string to use io.WriteString") + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9001/sa9001.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9001/sa9001.go new file mode 100644 index 000000000..1c97ccd55 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9001/sa9001.go @@ -0,0 +1,69 @@ +package sa9001 + +import ( + "go/ast" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9001", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Defers in range loops may not run when you expect them to`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + loop := node.(*ast.RangeStmt) + typ := pass.TypesInfo.TypeOf(loop.X) + _, ok := typeutil.CoreType(typ).(*types.Chan) + if !ok { + return + } + + stmts := []*ast.DeferStmt{} + exits := false + fn2 := func(node ast.Node) bool { + switch stmt := node.(type) { + case *ast.DeferStmt: + stmts = append(stmts, stmt) + case *ast.FuncLit: + // Don't look into function bodies + return false + case *ast.ReturnStmt: + exits = true + case *ast.BranchStmt: + exits = node.(*ast.BranchStmt).Tok == token.BREAK + } + return true + } + ast.Inspect(loop.Body, fn2) + + if exits { + return + } + for _, stmt := range stmts { + report.Report(pass, stmt, "defers in this range loop won't run unless the channel gets closed") + } + } + code.Preorder(pass, fn, (*ast.RangeStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9002/sa9002.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9002/sa9002.go new file mode 100644 index 000000000..054aa284a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9002/sa9002.go @@ -0,0 +1,63 @@ +package sa9002 + +import ( + "fmt" + "go/ast" + "strconv" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9002", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Using a non-octal \'os.FileMode\' that looks like it was meant to be in octal.`, + Since: "2017.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + for _, arg := range call.Args { + lit, ok := arg.(*ast.BasicLit) + if !ok { + continue + } + if !typeutil.IsTypeWithName(pass.TypesInfo.TypeOf(lit), "os.FileMode") && + !typeutil.IsTypeWithName(pass.TypesInfo.TypeOf(lit), "io/fs.FileMode") { + continue + } + if len(lit.Value) == 3 && + lit.Value[0] != '0' && + lit.Value[0] >= '0' && lit.Value[0] <= '7' && + lit.Value[1] >= '0' && lit.Value[1] <= '7' && + lit.Value[2] >= '0' && lit.Value[2] <= '7' { + + v, err := strconv.ParseInt(lit.Value, 10, 64) + if err != nil { + continue + } + report.Report(pass, arg, fmt.Sprintf("file mode '%s' evaluates to %#o; did you mean '0%s'?", lit.Value, v, lit.Value), + report.Fixes(edit.Fix("fix octal literal", edit.ReplaceWithString(arg, "0"+lit.Value)))) + } + } + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9003/sa9003.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9003/sa9003.go new file mode 100644 index 000000000..9ee66475f --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9003/sa9003.go @@ -0,0 +1,62 @@ +package sa9003 + +import ( + "go/ast" + + "golang.org/x/tools/go/analysis" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9003", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Empty body in an if or else branch`, + Since: "2017.1", + NonDefault: true, + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + if fn.Source() == nil { + continue + } + if irutil.IsExample(fn) { + continue + } + cb := func(node ast.Node) bool { + ifstmt, ok := node.(*ast.IfStmt) + if !ok { + return true + } + if ifstmt.Else != nil { + b, ok := ifstmt.Else.(*ast.BlockStmt) + if !ok || len(b.List) != 0 { + return true + } + report.Report(pass, ifstmt.Else, "empty branch", report.FilterGenerated(), report.ShortRange()) + } + if len(ifstmt.Body.List) != 0 { + return true + } + report.Report(pass, ifstmt, "empty branch", report.FilterGenerated(), report.ShortRange()) + return true + } + if source := fn.Source(); source != nil { + ast.Inspect(source, cb) + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9004/sa9004.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9004/sa9004.go new file mode 100644 index 000000000..2e8838ee0 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9004/sa9004.go @@ -0,0 +1,183 @@ +package sa9004 + +import ( + "go/ast" + "go/token" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ast/astutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9004", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Only the first constant has an explicit type`, + + Text: `In a constant declaration such as the following: + + const ( + First byte = 1 + Second = 2 + ) + +the constant Second does not have the same type as the constant First. +This construct shouldn't be confused with + + const ( + First byte = iota + Second + ) + +where \'First\' and \'Second\' do indeed have the same type. The type is only +passed on when no explicit value is assigned to the constant. + +When declaring enumerations with explicit values it is therefore +important not to write + + const ( + EnumFirst EnumType = 1 + EnumSecond = 2 + EnumThird = 3 + ) + +This discrepancy in types can cause various confusing behaviors and +bugs. + + +Wrong type in variable declarations + +The most obvious issue with such incorrect enumerations expresses +itself as a compile error: + + package pkg + + const ( + EnumFirst uint8 = 1 + EnumSecond = 2 + ) + + func fn(useFirst bool) { + x := EnumSecond + if useFirst { + x = EnumFirst + } + } + +fails to compile with + + ./const.go:11:5: cannot use EnumFirst (type uint8) as type int in assignment + + +Losing method sets + +A more subtle issue occurs with types that have methods and optional +interfaces. Consider the following: + + package main + + import "fmt" + + type Enum int + + func (e Enum) String() string { + return "an enum" + } + + const ( + EnumFirst Enum = 1 + EnumSecond = 2 + ) + + func main() { + fmt.Println(EnumFirst) + fmt.Println(EnumSecond) + } + +This code will output + + an enum + 2 + +as \'EnumSecond\' has no explicit type, and thus defaults to \'int\'.`, + Since: "2019.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + decl := node.(*ast.GenDecl) + if !decl.Lparen.IsValid() { + return + } + if decl.Tok != token.CONST { + return + } + + groups := astutil.GroupSpecs(pass.Fset, decl.Specs) + groupLoop: + for _, group := range groups { + if len(group) < 2 { + continue + } + if group[0].(*ast.ValueSpec).Type == nil { + // first constant doesn't have a type + continue groupLoop + } + + firstType := pass.TypesInfo.TypeOf(group[0].(*ast.ValueSpec).Values[0]) + for i, spec := range group { + spec := spec.(*ast.ValueSpec) + if i > 0 && spec.Type != nil { + continue groupLoop + } + if len(spec.Names) != 1 || len(spec.Values) != 1 { + continue groupLoop + } + + if !types.ConvertibleTo(pass.TypesInfo.TypeOf(spec.Values[0]), firstType) { + continue groupLoop + } + + switch v := spec.Values[0].(type) { + case *ast.BasicLit: + case *ast.UnaryExpr: + if _, ok := v.X.(*ast.BasicLit); !ok { + continue groupLoop + } + default: + // if it's not a literal it might be typed, such as + // time.Microsecond = 1000 * Nanosecond + continue groupLoop + } + } + var edits []analysis.TextEdit + typ := group[0].(*ast.ValueSpec).Type + for _, spec := range group[1:] { + nspec := *spec.(*ast.ValueSpec) + nspec.Type = typ + // The position of `spec` node excludes comments (if any). + // However, on generating the source back from the node, the comments are included. Setting `Comment` to nil ensures deduplication of comments. + nspec.Comment = nil + edits = append(edits, edit.ReplaceWithNode(pass.Fset, spec, &nspec)) + } + report.Report(pass, group[0], "only the first constant in this group has an explicit type", report.Fixes(edit.Fix("add type to all constants in group", edits...))) + } + } + code.Preorder(pass, fn, (*ast.GenDecl)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9005/sa9005.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9005/sa9005.go new file mode 100644 index 000000000..94c1f5dc9 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9005/sa9005.go @@ -0,0 +1,94 @@ +package sa9005 + +import ( + "fmt" + "go/types" + + "honnef.co/go/tools/analysis/callcheck" + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/knowledge" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9005", + Requires: []*analysis.Analyzer{ + buildir.Analyzer, + // Filtering generated code because it may include empty structs generated from data models. + generated.Analyzer, + }, + Run: callcheck.Analyzer(rules), + }, + Doc: &lint.RawDocumentation{ + Title: `Trying to marshal a struct with no public fields nor custom marshaling`, + Text: ` +The \'encoding/json\' and \'encoding/xml\' packages only operate on exported +fields in structs, not unexported ones. It is usually an error to try +to (un)marshal structs that only consist of unexported fields. + +This check will not flag calls involving types that define custom +marshaling behavior, e.g. via \'MarshalJSON\' methods. It will also not +flag empty structs.`, + Since: "2019.2", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var rules = map[string]callcheck.Check{ + // TODO(dh): should we really flag XML? Even an empty struct + // produces a non-zero amount of data, namely its type name. + // Let's see if we encounter any false positives. + // + // Also, should we flag gob? + "encoding/json.Marshal": check(knowledge.Arg("json.Marshal.v"), "MarshalJSON", "MarshalText"), + "encoding/xml.Marshal": check(knowledge.Arg("xml.Marshal.v"), "MarshalXML", "MarshalText"), + "(*encoding/json.Encoder).Encode": check(knowledge.Arg("(*encoding/json.Encoder).Encode.v"), "MarshalJSON", "MarshalText"), + "(*encoding/xml.Encoder).Encode": check(knowledge.Arg("(*encoding/xml.Encoder).Encode.v"), "MarshalXML", "MarshalText"), + + "encoding/json.Unmarshal": check(knowledge.Arg("json.Unmarshal.v"), "UnmarshalJSON", "UnmarshalText"), + "encoding/xml.Unmarshal": check(knowledge.Arg("xml.Unmarshal.v"), "UnmarshalXML", "UnmarshalText"), + "(*encoding/json.Decoder).Decode": check(knowledge.Arg("(*encoding/json.Decoder).Decode.v"), "UnmarshalJSON", "UnmarshalText"), + "(*encoding/xml.Decoder).Decode": check(knowledge.Arg("(*encoding/xml.Decoder).Decode.v"), "UnmarshalXML", "UnmarshalText"), +} + +func check(argN int, meths ...string) callcheck.Check { + return func(call *callcheck.Call) { + if code.IsGenerated(call.Pass, call.Instr.Pos()) { + return + } + arg := call.Args[argN] + T := arg.Value.Value.Type() + Ts, ok := typeutil.Dereference(T).Underlying().(*types.Struct) + if !ok { + return + } + if Ts.NumFields() == 0 { + return + } + fields := typeutil.FlattenFields(Ts) + for _, field := range fields { + if field.Var.Exported() { + return + } + } + // OPT(dh): we could use a method set cache here + ms := call.Instr.Parent().Prog.MethodSets.MethodSet(T) + // TODO(dh): we're not checking the signature, which can cause false negatives. + // This isn't a huge problem, however, since vet complains about incorrect signatures. + for _, meth := range meths { + if ms.Lookup(nil, meth) != nil { + return + } + } + arg.Invalid(fmt.Sprintf("struct type '%s' doesn't have any exported fields, nor custom marshaling", typeutil.Dereference(T))) + } +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9006/sa9006.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9006/sa9006.go new file mode 100644 index 000000000..44f992399 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9006/sa9006.go @@ -0,0 +1,106 @@ +package sa9006 + +import ( + "fmt" + "go/ast" + "go/types" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9006", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Dubious bit shifting of a fixed size integer value`, + Text: `Bit shifting a value past its size will always clear the value. + +For instance: + + v := int8(42) + v >>= 8 + +will always result in 0. + +This check flags bit shifting operations on fixed size integer values only. +That is, int, uint and uintptr are never flagged to avoid potential false +positives in somewhat exotic but valid bit twiddling tricks: + + // Clear any value above 32 bits if integers are more than 32 bits. + func f(i int) int { + v := i >> 32 + v = v << 32 + return i-v + }`, + Since: "2020.2", + Severity: lint.SeverityWarning, + // Technically this should be MergeIfAll, because the type of + // v might be different for different build tags. Practically, + // don't write code that depends on that. + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer +var ( + checkFixedLengthTypeShiftQ = pattern.MustParse(` + (Or + (AssignStmt _ (Or ">>=" "<<=") _) + (BinaryExpr _ (Or ">>" "<<") _)) + `) +) + +func run(pass *analysis.Pass) (interface{}, error) { + isDubiousShift := func(x, y ast.Expr) (int64, int64, bool) { + typ, ok := pass.TypesInfo.TypeOf(x).Underlying().(*types.Basic) + if !ok { + return 0, 0, false + } + switch typ.Kind() { + case types.Int8, types.Int16, types.Int32, types.Int64, + types.Uint8, types.Uint16, types.Uint32, types.Uint64: + // We're only interested in fixed–size types. + default: + return 0, 0, false + } + + const bitsInByte = 8 + typeBits := pass.TypesSizes.Sizeof(typ) * bitsInByte + + shiftLength, ok := code.ExprToInt(pass, y) + if !ok { + return 0, 0, false + } + + return typeBits, shiftLength, shiftLength >= typeBits + } + + fn := func(node ast.Node) { + if _, ok := code.Match(pass, checkFixedLengthTypeShiftQ, node); !ok { + return + } + + switch e := node.(type) { + case *ast.AssignStmt: + if size, shift, yes := isDubiousShift(e.Lhs[0], e.Rhs[0]); yes { + report.Report(pass, e, fmt.Sprintf("shifting %d-bit value by %d bits will always clear it", size, shift)) + } + case *ast.BinaryExpr: + if size, shift, yes := isDubiousShift(e.X, e.Y); yes { + report.Report(pass, e, fmt.Sprintf("shifting %d-bit value by %d bits will always clear it", size, shift)) + } + } + } + code.Preorder(pass, fn, (*ast.AssignStmt)(nil), (*ast.BinaryExpr)(nil)) + + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9007/sa9007.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9007/sa9007.go new file mode 100644 index 000000000..d10e5e7e8 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9007/sa9007.go @@ -0,0 +1,114 @@ +package sa9007 + +import ( + "fmt" + "os" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9007", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "Deleting a directory that shouldn't be deleted", + Text: ` +It is virtually never correct to delete system directories such as +/tmp or the user's home directory. However, it can be fairly easy to +do by mistake, for example by mistakingly using \'os.TempDir\' instead +of \'ioutil.TempDir\', or by forgetting to add a suffix to the result +of \'os.UserHomeDir\'. + +Writing + + d := os.TempDir() + defer os.RemoveAll(d) + +in your unit tests will have a devastating effect on the stability of your system. + +This check flags attempts at deleting the following directories: + +- os.TempDir +- os.UserCacheDir +- os.UserConfigDir +- os.UserHomeDir +`, + Since: "2022.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + call, ok := instr.(ir.CallInstruction) + if !ok { + continue + } + if !irutil.IsCallTo(call.Common(), "os.RemoveAll") { + continue + } + + kind := "" + ex := "" + callName := "" + arg := irutil.Flatten(call.Common().Args[0]) + switch arg := arg.(type) { + case *ir.Call: + callName = irutil.CallName(&arg.Call) + if callName != "os.TempDir" { + continue + } + kind = "temporary" + ex = os.TempDir() + case *ir.Extract: + if arg.Index != 0 { + continue + } + first, ok := arg.Tuple.(*ir.Call) + if !ok { + continue + } + callName = irutil.CallName(&first.Call) + switch callName { + case "os.UserCacheDir": + kind = "cache" + ex, _ = os.UserCacheDir() + case "os.UserConfigDir": + kind = "config" + ex, _ = os.UserConfigDir() + case "os.UserHomeDir": + kind = "home" + ex, _ = os.UserHomeDir() + default: + continue + } + default: + continue + } + + if ex == "" { + report.Report(pass, call, fmt.Sprintf("this call to os.RemoveAll deletes the user's entire %s directory, not a subdirectory therein", kind), + report.Related(arg, fmt.Sprintf("this call to %s returns the user's %s directory", callName, kind))) + } else { + report.Report(pass, call, fmt.Sprintf("this call to os.RemoveAll deletes the user's entire %s directory, not a subdirectory therein", kind), + report.Related(arg, fmt.Sprintf("this call to %s returns the user's %s directory, for example %s", callName, kind, ex))) + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9008/sa9008.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9008/sa9008.go new file mode 100644 index 000000000..355b11e42 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9008/sa9008.go @@ -0,0 +1,130 @@ +package sa9008 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ast/astutil" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9008", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `\'else\' branch of a type assertion is probably not reading the right value`, + Text: ` +When declaring variables as part of an \'if\' statement (like in \"if +foo := ...; foo {\"), the same variables will also be in the scope of +the \'else\' branch. This means that in the following example + + if x, ok := x.(int); ok { + // ... + } else { + fmt.Printf("unexpected type %T", x) + } + +\'x\' in the \'else\' branch will refer to the \'x\' from \'x, ok +:=\'; it will not refer to the \'x\' that is being type-asserted. The +result of a failed type assertion is the zero value of the type that +is being asserted to, so \'x\' in the else branch will always have the +value \'0\' and the type \'int\'. +`, + Since: "2022.1", + Severity: lint.SeverityWarning, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var typeAssertionShadowingElseQ = pattern.MustParse(`(IfStmt (AssignStmt [obj@(Ident _) ok@(Ident _)] ":=" assert@(TypeAssertExpr obj _)) ok _ elseBranch)`) + +func run(pass *analysis.Pass) (interface{}, error) { + // TODO(dh): without the IR-based verification, this check is able + // to find more bugs, but also more prone to false positives. It + // would be a good candidate for the 'codereview' category of + // checks. + + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg + fn := func(node ast.Node) { + m, ok := code.Match(pass, typeAssertionShadowingElseQ, node) + if !ok { + return + } + shadow := pass.TypesInfo.ObjectOf(m.State["obj"].(*ast.Ident)) + shadowed := m.State["assert"].(*ast.TypeAssertExpr).X + + path, exact := astutil.PathEnclosingInterval(code.File(pass, shadow), shadow.Pos(), shadow.Pos()) + if !exact { + // TODO(dh): when can this happen? + return + } + irfn := ir.EnclosingFunction(irpkg, path) + if irfn == nil { + // For example for functions named "_", because we don't generate IR for them. + return + } + + shadoweeIR, isAddr := irfn.ValueForExpr(m.State["obj"].(*ast.Ident)) + if shadoweeIR == nil || isAddr { + // TODO(dh): is this possible? + return + } + + var branch ast.Node + switch br := m.State["elseBranch"].(type) { + case ast.Node: + branch = br + case []ast.Stmt: + branch = &ast.BlockStmt{List: br} + case nil: + return + default: + panic(fmt.Sprintf("unexpected type %T", br)) + } + + ast.Inspect(branch, func(node ast.Node) bool { + ident, ok := node.(*ast.Ident) + if !ok { + return true + } + if pass.TypesInfo.ObjectOf(ident) != shadow { + return true + } + + v, isAddr := irfn.ValueForExpr(ident) + if v == nil || isAddr { + return true + } + if irutil.Flatten(v) != shadoweeIR { + // Same types.Object, but different IR value. This + // either means that the variable has been + // assigned to since the type assertion, or that + // the variable has escaped to the heap. Either + // way, we shouldn't flag reads of it. + return true + } + + report.Report(pass, ident, + fmt.Sprintf("%s refers to the result of a failed type assertion and is a zero value, not the value that was being type-asserted", report.Render(pass, ident)), + report.Related(shadow, "this is the variable being read"), + report.Related(shadowed, "this is the variable being shadowed")) + return true + }) + } + code.Preorder(pass, fn, (*ast.IfStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/sa9009/sa9009.go b/tools/vendor/honnef.co/go/tools/staticcheck/sa9009/sa9009.go new file mode 100644 index 000000000..f98db5aee --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/staticcheck/sa9009/sa9009.go @@ -0,0 +1,68 @@ +package sa9009 + +import ( + "fmt" + "strings" + + "golang.org/x/tools/go/analysis" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "SA9009", + Run: run, + Requires: []*analysis.Analyzer{}, + }, + Doc: &lint.RawDocumentation{ + Title: "Ineffectual Go compiler directive", + Text: ` +A potential Go compiler directive was found, but is ineffectual as it begins +with whitespace.`, + Since: "2024.1", + Severity: lint.SeverityWarning, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (any, error) { + for _, f := range pass.Files { + for _, cg := range f.Comments { + for _, c := range cg.List { + // Compiler directives have to be // comments + if !strings.HasPrefix(c.Text, "//") { + continue + } + if pass.Fset.PositionFor(c.Pos(), false).Column != 1 { + // Compiler directives have to be top-level. This also + // avoids a false positive for + // 'import _ "unsafe" // go:linkname' + continue + } + text := strings.TrimLeft(c.Text[2:], " \t") + if len(text) == len(c.Text[2:]) { + // There was no leading whitespace + continue + } + if !strings.HasPrefix(text, "go:") { + // Not an attempted compiler directive + continue + } + text = text[3:] + if len(text) == 0 || text[0] < 'a' || text[0] > 'z' { + // A letter other than a-z after "go:", so unlikely to be an + // attempted compiler directive + continue + } + report.Report(pass, c, + fmt.Sprintf( + "ineffectual compiler directive due to extraneous space: %q", + c.Text)) + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/analysis.go b/tools/vendor/honnef.co/go/tools/stylecheck/analysis.go index d560d972e..7171befe2 100644 --- a/tools/vendor/honnef.co/go/tools/stylecheck/analysis.go +++ b/tools/vendor/honnef.co/go/tools/stylecheck/analysis.go @@ -1,84 +1,46 @@ +// Code generated by generate.go. DO NOT EDIT. + package stylecheck import ( - "honnef.co/go/tools/analysis/facts/generated" - "honnef.co/go/tools/analysis/facts/tokenfile" "honnef.co/go/tools/analysis/lint" - "honnef.co/go/tools/config" - "honnef.co/go/tools/internal/passes/buildir" - "honnef.co/go/tools/internal/sharedcheck" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" + "honnef.co/go/tools/stylecheck/st1000" + "honnef.co/go/tools/stylecheck/st1001" + "honnef.co/go/tools/stylecheck/st1003" + "honnef.co/go/tools/stylecheck/st1005" + "honnef.co/go/tools/stylecheck/st1006" + "honnef.co/go/tools/stylecheck/st1008" + "honnef.co/go/tools/stylecheck/st1011" + "honnef.co/go/tools/stylecheck/st1012" + "honnef.co/go/tools/stylecheck/st1013" + "honnef.co/go/tools/stylecheck/st1015" + "honnef.co/go/tools/stylecheck/st1016" + "honnef.co/go/tools/stylecheck/st1017" + "honnef.co/go/tools/stylecheck/st1018" + "honnef.co/go/tools/stylecheck/st1019" + "honnef.co/go/tools/stylecheck/st1020" + "honnef.co/go/tools/stylecheck/st1021" + "honnef.co/go/tools/stylecheck/st1022" + "honnef.co/go/tools/stylecheck/st1023" ) -var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ - "ST1000": { - Run: CheckPackageComment, - }, - "ST1001": { - Run: CheckDotImports, - Requires: []*analysis.Analyzer{generated.Analyzer, config.Analyzer}, - }, - "ST1003": { - Run: CheckNames, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, config.Analyzer}, - }, - "ST1005": { - Run: CheckErrorStrings, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "ST1006": { - Run: CheckReceiverNames, - Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, - }, - "ST1008": { - Run: CheckErrorReturn, - Requires: []*analysis.Analyzer{buildir.Analyzer}, - }, - "ST1011": { - Run: CheckTimeNames, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "ST1012": { - Run: CheckErrorVarNames, - }, - "ST1013": { - Run: CheckHTTPStatusCodes, - // TODO(dh): why does this depend on tokenfile.TokenFile? - Requires: []*analysis.Analyzer{generated.Analyzer, tokenfile.Analyzer, config.Analyzer, inspect.Analyzer}, - }, - "ST1015": { - Run: CheckDefaultCaseOrder, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer}, - }, - "ST1016": { - Run: CheckReceiverNamesIdentical, - Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, - }, - "ST1017": { - Run: CheckYodaConditions, - Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer}, - }, - "ST1018": { - Run: CheckInvisibleCharacters, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - }, - "ST1019": { - Run: CheckDuplicatedImports, - Requires: []*analysis.Analyzer{generated.Analyzer}, - }, - "ST1020": { - Run: CheckExportedFunctionDocs, - Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, - }, - "ST1021": { - Run: CheckExportedTypeDocs, - Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, - }, - "ST1022": { - Run: CheckExportedVarDocs, - Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, - }, - "ST1023": sharedcheck.RedundantTypeInDeclarationChecker("should", false), -}) +var Analyzers = []*lint.Analyzer{ + st1000.SCAnalyzer, + st1001.SCAnalyzer, + st1003.SCAnalyzer, + st1005.SCAnalyzer, + st1006.SCAnalyzer, + st1008.SCAnalyzer, + st1011.SCAnalyzer, + st1012.SCAnalyzer, + st1013.SCAnalyzer, + st1015.SCAnalyzer, + st1016.SCAnalyzer, + st1017.SCAnalyzer, + st1018.SCAnalyzer, + st1019.SCAnalyzer, + st1020.SCAnalyzer, + st1021.SCAnalyzer, + st1022.SCAnalyzer, + st1023.SCAnalyzer, +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/doc.go b/tools/vendor/honnef.co/go/tools/stylecheck/doc.go index 7ac707ee2..29649906a 100644 --- a/tools/vendor/honnef.co/go/tools/stylecheck/doc.go +++ b/tools/vendor/honnef.co/go/tools/stylecheck/doc.go @@ -1,3 +1,5 @@ +//go:generate go run ../generate.go + // Package stylecheck contains analyzes that enforce style rules. // Most of the recommendations made are universally agreed upon by the wider Go community. // Some analyzes, however, implement stricter rules that not everyone will agree with. @@ -6,257 +8,3 @@ // For the most part it is recommended to follow the advice given by the analyzers that are enabled by default, // but you may want to disable additional analyzes on a case by case basis. package stylecheck - -import "honnef.co/go/tools/analysis/lint" - -var Docs = lint.Markdownify(map[string]*lint.RawDocumentation{ - "ST1000": { - Title: `Incorrect or missing package comment`, - Text: `Packages must have a package comment that is formatted according to -the guidelines laid out in -https://github.com/golang/go/wiki/CodeReviewComments#package-comments.`, - Since: "2019.1", - NonDefault: true, - MergeIf: lint.MergeIfAny, - }, - - "ST1001": { - Title: `Dot imports are discouraged`, - Text: `Dot imports that aren't in external test packages are discouraged. - -The \'dot_import_whitelist\' option can be used to whitelist certain -imports. - -Quoting Go Code Review Comments: - -> The \'import .\' form can be useful in tests that, due to circular -> dependencies, cannot be made part of the package being tested: -> -> package foo_test -> -> import ( -> "bar/testutil" // also imports "foo" -> . "foo" -> ) -> -> In this case, the test file cannot be in package foo because it -> uses \'bar/testutil\', which imports \'foo\'. So we use the \'import .\' -> form to let the file pretend to be part of package foo even though -> it is not. Except for this one case, do not use \'import .\' in your -> programs. It makes the programs much harder to read because it is -> unclear whether a name like \'Quux\' is a top-level identifier in the -> current package or in an imported package.`, - Since: "2019.1", - Options: []string{"dot_import_whitelist"}, - MergeIf: lint.MergeIfAny, - }, - - "ST1003": { - Title: `Poorly chosen identifier`, - Text: `Identifiers, such as variable and package names, follow certain rules. - -See the following links for details: - -- https://golang.org/doc/effective_go.html#package-names -- https://golang.org/doc/effective_go.html#mixed-caps -- https://github.com/golang/go/wiki/CodeReviewComments#initialisms -- https://github.com/golang/go/wiki/CodeReviewComments#variable-names`, - Since: "2019.1", - NonDefault: true, - Options: []string{"initialisms"}, - MergeIf: lint.MergeIfAny, - }, - - "ST1005": { - Title: `Incorrectly formatted error string`, - Text: `Error strings follow a set of guidelines to ensure uniformity and good -composability. - -Quoting Go Code Review Comments: - -> Error strings should not be capitalized (unless beginning with -> proper nouns or acronyms) or end with punctuation, since they are -> usually printed following other context. That is, use -> \'fmt.Errorf("something bad")\' not \'fmt.Errorf("Something bad")\', so -> that \'log.Printf("Reading %s: %v", filename, err)\' formats without a -> spurious capital letter mid-message.`, - Since: "2019.1", - MergeIf: lint.MergeIfAny, - }, - - "ST1006": { - Title: `Poorly chosen receiver name`, - Text: `Quoting Go Code Review Comments: - -> The name of a method's receiver should be a reflection of its -> identity; often a one or two letter abbreviation of its type -> suffices (such as "c" or "cl" for "Client"). Don't use generic -> names such as "me", "this" or "self", identifiers typical of -> object-oriented languages that place more emphasis on methods as -> opposed to functions. The name need not be as descriptive as that -> of a method argument, as its role is obvious and serves no -> documentary purpose. It can be very short as it will appear on -> almost every line of every method of the type; familiarity admits -> brevity. Be consistent, too: if you call the receiver "c" in one -> method, don't call it "cl" in another.`, - Since: "2019.1", - MergeIf: lint.MergeIfAny, - }, - - "ST1008": { - Title: `A function's error value should be its last return value`, - Text: `A function's error value should be its last return value.`, - Since: `2019.1`, - MergeIf: lint.MergeIfAny, - }, - - "ST1011": { - Title: `Poorly chosen name for variable of type \'time.Duration\'`, - Text: `\'time.Duration\' values represent an amount of time, which is represented -as a count of nanoseconds. An expression like \'5 * time.Microsecond\' -yields the value \'5000\'. It is therefore not appropriate to suffix a -variable of type \'time.Duration\' with any time unit, such as \'Msec\' or -\'Milli\'.`, - Since: `2019.1`, - MergeIf: lint.MergeIfAny, - }, - - "ST1012": { - Title: `Poorly chosen name for error variable`, - Text: `Error variables that are part of an API should be called \'errFoo\' or -\'ErrFoo\'.`, - Since: "2019.1", - MergeIf: lint.MergeIfAny, - }, - - "ST1013": { - Title: `Should use constants for HTTP error codes, not magic numbers`, - Text: `HTTP has a tremendous number of status codes. While some of those are -well known (200, 400, 404, 500), most of them are not. The \'net/http\' -package provides constants for all status codes that are part of the -various specifications. It is recommended to use these constants -instead of hard-coding magic numbers, to vastly improve the -readability of your code.`, - Since: "2019.1", - Options: []string{"http_status_code_whitelist"}, - MergeIf: lint.MergeIfAny, - }, - - "ST1015": { - Title: `A switch's default case should be the first or last case`, - Since: "2019.1", - MergeIf: lint.MergeIfAny, - }, - - "ST1016": { - Title: `Use consistent method receiver names`, - Since: "2019.1", - NonDefault: true, - MergeIf: lint.MergeIfAny, - }, - - "ST1017": { - Title: `Don't use Yoda conditions`, - Text: `Yoda conditions are conditions of the kind \"if 42 == x\", where the -literal is on the left side of the comparison. These are a common -idiom in languages in which assignment is an expression, to avoid bugs -of the kind \"if (x = 42)\". In Go, which doesn't allow for this kind of -bug, we prefer the more idiomatic \"if x == 42\".`, - Since: "2019.2", - MergeIf: lint.MergeIfAny, - }, - - "ST1018": { - Title: `Avoid zero-width and control characters in string literals`, - Since: "2019.2", - MergeIf: lint.MergeIfAny, - }, - - "ST1019": { - Title: `Importing the same package multiple times`, - Text: `Go allows importing the same package multiple times, as long as -different import aliases are being used. That is, the following -bit of code is valid: - - import ( - "fmt" - fumpt "fmt" - format "fmt" - _ "fmt" - ) - -However, this is very rarely done on purpose. Usually, it is a -sign of code that got refactored, accidentally adding duplicate -import statements. It is also a rarely known feature, which may -contribute to confusion. - -Do note that sometimes, this feature may be used -intentionally (see for example -https://github.com/golang/go/commit/3409ce39bfd7584523b7a8c150a310cea92d879d) -– if you want to allow this pattern in your code base, you're -advised to disable this check.`, - Since: "2020.1", - MergeIf: lint.MergeIfAny, - }, - - "ST1020": { - Title: "The documentation of an exported function should start with the function's name", - Text: `Doc comments work best as complete sentences, which -allow a wide variety of automated presentations. The first sentence -should be a one-sentence summary that starts with the name being -declared. - -If every doc comment begins with the name of the item it describes, -you can use the \'doc\' subcommand of the \'go\' tool and run the output -through grep. - -See https://golang.org/doc/effective_go.html#commentary for more -information on how to write good documentation.`, - Since: "2020.1", - NonDefault: true, - MergeIf: lint.MergeIfAny, - }, - - "ST1021": { - Title: "The documentation of an exported type should start with type's name", - Text: `Doc comments work best as complete sentences, which -allow a wide variety of automated presentations. The first sentence -should be a one-sentence summary that starts with the name being -declared. - -If every doc comment begins with the name of the item it describes, -you can use the \'doc\' subcommand of the \'go\' tool and run the output -through grep. - -See https://golang.org/doc/effective_go.html#commentary for more -information on how to write good documentation.`, - Since: "2020.1", - NonDefault: true, - MergeIf: lint.MergeIfAny, - }, - - "ST1022": { - Title: "The documentation of an exported variable or constant should start with variable's name", - Text: `Doc comments work best as complete sentences, which -allow a wide variety of automated presentations. The first sentence -should be a one-sentence summary that starts with the name being -declared. - -If every doc comment begins with the name of the item it describes, -you can use the \'doc\' subcommand of the \'go\' tool and run the output -through grep. - -See https://golang.org/doc/effective_go.html#commentary for more -information on how to write good documentation.`, - Since: "2020.1", - NonDefault: true, - MergeIf: lint.MergeIfAny, - }, - - "ST1023": { - Title: "Redundant type in variable declaration", - Since: "2021.1", - NonDefault: true, - MergeIf: lint.MergeIfAll, - }, -}) diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/lint.go b/tools/vendor/honnef.co/go/tools/stylecheck/lint.go deleted file mode 100644 index a15e6d97a..000000000 --- a/tools/vendor/honnef.co/go/tools/stylecheck/lint.go +++ /dev/null @@ -1,990 +0,0 @@ -package stylecheck - -import ( - "fmt" - "go/ast" - "go/constant" - "go/token" - "go/types" - "sort" - "strconv" - "strings" - "unicode" - "unicode/utf8" - - "honnef.co/go/tools/analysis/code" - "honnef.co/go/tools/analysis/edit" - "honnef.co/go/tools/analysis/lint" - "honnef.co/go/tools/analysis/report" - "honnef.co/go/tools/config" - "honnef.co/go/tools/go/ast/astutil" - "honnef.co/go/tools/go/ir" - "honnef.co/go/tools/go/ir/irutil" - "honnef.co/go/tools/go/types/typeutil" - "honnef.co/go/tools/internal/passes/buildir" - "honnef.co/go/tools/pattern" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" - "golang.org/x/tools/go/ast/inspector" -) - -func docText(doc *ast.CommentGroup) (string, bool) { - if doc == nil { - return "", false - } - // We trim spaces primarily because of /**/ style comments, which often have leading space. - text := strings.TrimSpace(doc.Text()) - return text, text != "" -} - -func CheckPackageComment(pass *analysis.Pass) (interface{}, error) { - // - At least one file in a non-main package should have a package comment - // - // - The comment should be of the form - // "Package x ...". This has a slight potential for false - // positives, as multiple files can have package comments, in - // which case they get appended. But that doesn't happen a lot in - // the real world. - - if pass.Pkg.Name() == "main" { - return nil, nil - } - hasDocs := false - for _, f := range pass.Files { - if code.IsInTest(pass, f) { - continue - } - text, ok := docText(f.Doc) - if ok { - hasDocs = true - prefix := "Package " + f.Name.Name + " " - if !strings.HasPrefix(text, prefix) { - report.Report(pass, f.Doc, fmt.Sprintf(`package comment should be of the form "%s..."`, prefix)) - } - } - } - - if !hasDocs { - for _, f := range pass.Files { - if code.IsInTest(pass, f) { - continue - } - report.Report(pass, f, "at least one file in a package should have a package comment", report.ShortRange()) - } - } - return nil, nil -} - -func CheckDotImports(pass *analysis.Pass) (interface{}, error) { - for _, f := range pass.Files { - imports: - for _, imp := range f.Imports { - path := imp.Path.Value - path = path[1 : len(path)-1] - for _, w := range config.For(pass).DotImportWhitelist { - if w == path { - continue imports - } - } - - if imp.Name != nil && imp.Name.Name == "." && !code.IsInTest(pass, f) { - report.Report(pass, imp, "should not use dot imports", report.FilterGenerated()) - } - } - } - return nil, nil -} - -func CheckDuplicatedImports(pass *analysis.Pass) (interface{}, error) { - for _, f := range pass.Files { - // Collect all imports by their import path - imports := make(map[string][]*ast.ImportSpec, len(f.Imports)) - for _, imp := range f.Imports { - imports[imp.Path.Value] = append(imports[imp.Path.Value], imp) - } - - for path, value := range imports { - if path[1:len(path)-1] == "unsafe" { - // Don't flag unsafe. Cgo generated code imports - // unsafe using the blank identifier, and most - // user-written cgo code also imports unsafe - // explicitly. - continue - } - // If there's more than one import per path, we flag that - if len(value) > 1 { - s := fmt.Sprintf("package %s is being imported more than once", path) - opts := []report.Option{report.FilterGenerated()} - for _, imp := range value[1:] { - opts = append(opts, report.Related(imp, fmt.Sprintf("other import of %s", path))) - } - report.Report(pass, value[0], s, opts...) - } - } - } - return nil, nil -} - -func CheckBlankImports(pass *analysis.Pass) (interface{}, error) { - fset := pass.Fset - for _, f := range pass.Files { - if code.IsMainLike(pass) || code.IsInTest(pass, f) { - continue - } - - // Collect imports of the form `import _ "foo"`, i.e. with no - // parentheses, as their comment will be associated with the - // (paren-free) GenDecl, not the import spec itself. - // - // We don't directly process the GenDecl so that we can - // correctly handle the following: - // - // import _ "foo" - // import _ "bar" - // - // where only the first import should get flagged. - skip := map[ast.Spec]bool{} - ast.Inspect(f, func(node ast.Node) bool { - switch node := node.(type) { - case *ast.File: - return true - case *ast.GenDecl: - if node.Tok != token.IMPORT { - return false - } - if node.Lparen == token.NoPos && node.Doc != nil { - skip[node.Specs[0]] = true - } - return false - } - return false - }) - for i, imp := range f.Imports { - pos := fset.Position(imp.Pos()) - - if !astutil.IsBlank(imp.Name) { - continue - } - // Only flag the first blank import in a group of imports, - // or don't flag any of them, if the first one is - // commented - if i > 0 { - prev := f.Imports[i-1] - prevPos := fset.Position(prev.Pos()) - if pos.Line-1 == prevPos.Line && astutil.IsBlank(prev.Name) { - continue - } - } - - if imp.Doc == nil && imp.Comment == nil && !skip[imp] { - report.Report(pass, imp, "a blank import should be only in a main or test package, or have a comment justifying it") - } - } - } - return nil, nil -} - -var checkIncDecQ = pattern.MustParse(`(AssignStmt x tok@(Or "+=" "-=") (BasicLit "INT" "1"))`) - -func CheckIncDec(pass *analysis.Pass) (interface{}, error) { - // TODO(dh): this can be noisy for function bodies that look like this: - // x += 3 - // ... - // x += 2 - // ... - // x += 1 - fn := func(node ast.Node) { - m, ok := code.Match(pass, checkIncDecQ, node) - if !ok { - return - } - suffix := "" - switch m.State["tok"].(token.Token) { - case token.ADD_ASSIGN: - suffix = "++" - case token.SUB_ASSIGN: - suffix = "--" - } - - report.Report(pass, node, fmt.Sprintf("should replace %s with %s%s", report.Render(pass, node), report.Render(pass, m.State["x"].(ast.Node)), suffix)) - } - code.Preorder(pass, fn, (*ast.AssignStmt)(nil)) - return nil, nil -} - -func CheckErrorReturn(pass *analysis.Pass) (interface{}, error) { -fnLoop: - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - sig := fn.Type().(*types.Signature) - rets := sig.Results() - if rets == nil || rets.Len() < 2 { - continue - } - - if rets.At(rets.Len()-1).Type() == types.Universe.Lookup("error").Type() { - // Last return type is error. If the function also returns - // errors in other positions, that's fine. - continue - } - - if rets.Len() >= 2 && rets.At(rets.Len()-1).Type() == types.Universe.Lookup("bool").Type() && rets.At(rets.Len()-2).Type() == types.Universe.Lookup("error").Type() { - // Accept (..., error, bool) and assume it's a comma-ok function. It's not clear whether the bool should come last or not for these kinds of functions. - continue - } - for i := rets.Len() - 2; i >= 0; i-- { - if rets.At(i).Type() == types.Universe.Lookup("error").Type() { - report.Report(pass, rets.At(i), "error should be returned as the last argument", report.ShortRange()) - continue fnLoop - } - } - } - return nil, nil -} - -// CheckUnexportedReturn checks that exported functions on exported -// types do not return unexported types. -func CheckUnexportedReturn(pass *analysis.Pass) (interface{}, error) { - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - if fn.Synthetic != 0 || fn.Parent() != nil { - continue - } - if !ast.IsExported(fn.Name()) || code.IsMain(pass) || code.IsInTest(pass, fn) { - continue - } - sig := fn.Type().(*types.Signature) - if sig.Recv() != nil && !ast.IsExported(typeutil.Dereference(sig.Recv().Type()).(*types.Named).Obj().Name()) { - continue - } - res := sig.Results() - for i := 0; i < res.Len(); i++ { - if named, ok := typeutil.DereferenceR(res.At(i).Type()).(*types.Named); ok && - !ast.IsExported(named.Obj().Name()) && - named != types.Universe.Lookup("error").Type() { - report.Report(pass, fn, "should not return unexported type") - } - } - } - return nil, nil -} - -func CheckReceiverNames(pass *analysis.Pass) (interface{}, error) { - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg - for _, m := range irpkg.Members { - if T, ok := m.Object().(*types.TypeName); ok && !T.IsAlias() { - ms := typeutil.IntuitiveMethodSet(T.Type(), nil) - for _, sel := range ms { - fn := sel.Obj().(*types.Func) - recv := fn.Type().(*types.Signature).Recv() - if typeutil.Dereference(recv.Type()) != T.Type() { - // skip embedded methods - continue - } - if recv.Name() == "self" || recv.Name() == "this" { - report.Report(pass, recv, `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`, report.FilterGenerated()) - } - if recv.Name() == "_" { - report.Report(pass, recv, "receiver name should not be an underscore, omit the name if it is unused", report.FilterGenerated()) - } - } - } - } - return nil, nil -} - -func CheckReceiverNamesIdentical(pass *analysis.Pass) (interface{}, error) { - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg - for _, m := range irpkg.Members { - names := map[string]int{} - - var firstFn *types.Func - if T, ok := m.Object().(*types.TypeName); ok && !T.IsAlias() { - ms := typeutil.IntuitiveMethodSet(T.Type(), nil) - for _, sel := range ms { - fn := sel.Obj().(*types.Func) - recv := fn.Type().(*types.Signature).Recv() - if code.IsGenerated(pass, recv.Pos()) { - // Don't concern ourselves with methods in generated code - continue - } - if typeutil.Dereference(recv.Type()) != T.Type() { - // skip embedded methods - continue - } - if firstFn == nil { - firstFn = fn - } - if recv.Name() != "" && recv.Name() != "_" { - names[recv.Name()]++ - } - } - } - - if len(names) > 1 { - var seen []string - for name, count := range names { - seen = append(seen, fmt.Sprintf("%dx %q", count, name)) - } - sort.Strings(seen) - - report.Report(pass, firstFn, fmt.Sprintf("methods on the same type should have the same receiver name (seen %s)", strings.Join(seen, ", "))) - } - } - return nil, nil -} - -func CheckContextFirstArg(pass *analysis.Pass) (interface{}, error) { - // TODO(dh): this check doesn't apply to test helpers. Example from the stdlib: - // func helperCommandContext(t *testing.T, ctx context.Context, s ...string) (cmd *exec.Cmd) { -fnLoop: - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - if fn.Synthetic != 0 || fn.Parent() != nil { - continue - } - params := fn.Signature.Params() - if params.Len() < 2 { - continue - } - if types.TypeString(params.At(0).Type(), nil) == "context.Context" { - continue - } - for i := 1; i < params.Len(); i++ { - param := params.At(i) - if types.TypeString(param.Type(), nil) == "context.Context" { - report.Report(pass, param, "context.Context should be the first argument of a function", report.ShortRange()) - continue fnLoop - } - } - } - return nil, nil -} - -func CheckErrorStrings(pass *analysis.Pass) (interface{}, error) { - objNames := map[*ir.Package]map[string]bool{} - irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg - objNames[irpkg] = map[string]bool{} - for _, m := range irpkg.Members { - if typ, ok := m.(*ir.Type); ok { - objNames[irpkg][typ.Name()] = true - } - } - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - objNames[fn.Package()][fn.Name()] = true - } - - for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { - if code.IsInTest(pass, fn) { - // We don't care about malformed error messages in tests; - // they're usually for direct human consumption, not part - // of an API - continue - } - for _, block := range fn.Blocks { - instrLoop: - for _, ins := range block.Instrs { - call, ok := ins.(*ir.Call) - if !ok { - continue - } - if !irutil.IsCallToAny(call.Common(), "errors.New", "fmt.Errorf") { - continue - } - - k, ok := call.Common().Args[0].(*ir.Const) - if !ok { - continue - } - - s := constant.StringVal(k.Value) - if len(s) == 0 { - continue - } - switch s[len(s)-1] { - case '.', ':', '!', '\n': - report.Report(pass, call, "error strings should not end with punctuation or newlines") - } - idx := strings.IndexByte(s, ' ') - if idx == -1 { - // single word error message, probably not a real - // error but something used in tests or during - // debugging - continue - } - word := s[:idx] - first, n := utf8.DecodeRuneInString(word) - if !unicode.IsUpper(first) { - continue - } - for _, c := range word[n:] { - if unicode.IsUpper(c) || unicode.IsDigit(c) { - // Word is probably an initialism or multi-word function name. Digits cover elliptic curves like - // P384. - continue instrLoop - } - } - - if strings.ContainsRune(word, '(') { - // Might be a function call - continue instrLoop - } - word = strings.TrimRightFunc(word, func(r rune) bool { return unicode.IsPunct(r) }) - if objNames[fn.Package()][word] { - // Word is probably the name of a function or type in this package - continue - } - // First word in error starts with a capital - // letter, and the word doesn't contain any other - // capitals, making it unlikely to be an - // initialism or multi-word function name. - // - // It could still be a proper noun, though. - - report.Report(pass, call, "error strings should not be capitalized") - } - } - } - return nil, nil -} - -func CheckTimeNames(pass *analysis.Pass) (interface{}, error) { - suffixes := []string{ - "Sec", "Secs", "Seconds", - "Msec", "Msecs", - "Milli", "Millis", "Milliseconds", - "Usec", "Usecs", "Microseconds", - "MS", "Ms", - } - fn := func(names []*ast.Ident) { - for _, name := range names { - if _, ok := pass.TypesInfo.Defs[name]; !ok { - continue - } - T := pass.TypesInfo.TypeOf(name) - if !typeutil.IsType(T, "time.Duration") && !typeutil.IsType(T, "*time.Duration") { - continue - } - for _, suffix := range suffixes { - if strings.HasSuffix(name.Name, suffix) { - report.Report(pass, name, fmt.Sprintf("var %s is of type %v; don't use unit-specific suffix %q", name.Name, T, suffix)) - break - } - } - } - } - - fn2 := func(node ast.Node) { - switch node := node.(type) { - case *ast.ValueSpec: - fn(node.Names) - case *ast.FieldList: - for _, field := range node.List { - fn(field.Names) - } - case *ast.AssignStmt: - if node.Tok != token.DEFINE { - break - } - var names []*ast.Ident - for _, lhs := range node.Lhs { - if lhs, ok := lhs.(*ast.Ident); ok { - names = append(names, lhs) - } - } - fn(names) - } - } - - code.Preorder(pass, fn2, (*ast.ValueSpec)(nil), (*ast.FieldList)(nil), (*ast.AssignStmt)(nil)) - return nil, nil -} - -func CheckErrorVarNames(pass *analysis.Pass) (interface{}, error) { - for _, f := range pass.Files { - for _, decl := range f.Decls { - gen, ok := decl.(*ast.GenDecl) - if !ok || gen.Tok != token.VAR { - continue - } - for _, spec := range gen.Specs { - spec := spec.(*ast.ValueSpec) - if len(spec.Names) != len(spec.Values) { - continue - } - - for i, name := range spec.Names { - val := spec.Values[i] - if !code.IsCallToAny(pass, val, "errors.New", "fmt.Errorf") { - continue - } - - if pass.Pkg.Path() == "net/http" && strings.HasPrefix(name.Name, "http2err") { - // special case for internal variable names of - // bundled HTTP 2 code in net/http - continue - } - prefix := "err" - if name.IsExported() { - prefix = "Err" - } - if !strings.HasPrefix(name.Name, prefix) { - report.Report(pass, name, fmt.Sprintf("error var %s should have name of the form %sFoo", name.Name, prefix)) - } - } - } - } - } - return nil, nil -} - -var httpStatusCodes = map[int64]string{ - 100: "StatusContinue", - 101: "StatusSwitchingProtocols", - 102: "StatusProcessing", - 200: "StatusOK", - 201: "StatusCreated", - 202: "StatusAccepted", - 203: "StatusNonAuthoritativeInfo", - 204: "StatusNoContent", - 205: "StatusResetContent", - 206: "StatusPartialContent", - 207: "StatusMultiStatus", - 208: "StatusAlreadyReported", - 226: "StatusIMUsed", - 300: "StatusMultipleChoices", - 301: "StatusMovedPermanently", - 302: "StatusFound", - 303: "StatusSeeOther", - 304: "StatusNotModified", - 305: "StatusUseProxy", - 307: "StatusTemporaryRedirect", - 308: "StatusPermanentRedirect", - 400: "StatusBadRequest", - 401: "StatusUnauthorized", - 402: "StatusPaymentRequired", - 403: "StatusForbidden", - 404: "StatusNotFound", - 405: "StatusMethodNotAllowed", - 406: "StatusNotAcceptable", - 407: "StatusProxyAuthRequired", - 408: "StatusRequestTimeout", - 409: "StatusConflict", - 410: "StatusGone", - 411: "StatusLengthRequired", - 412: "StatusPreconditionFailed", - 413: "StatusRequestEntityTooLarge", - 414: "StatusRequestURITooLong", - 415: "StatusUnsupportedMediaType", - 416: "StatusRequestedRangeNotSatisfiable", - 417: "StatusExpectationFailed", - 418: "StatusTeapot", - 422: "StatusUnprocessableEntity", - 423: "StatusLocked", - 424: "StatusFailedDependency", - 426: "StatusUpgradeRequired", - 428: "StatusPreconditionRequired", - 429: "StatusTooManyRequests", - 431: "StatusRequestHeaderFieldsTooLarge", - 451: "StatusUnavailableForLegalReasons", - 500: "StatusInternalServerError", - 501: "StatusNotImplemented", - 502: "StatusBadGateway", - 503: "StatusServiceUnavailable", - 504: "StatusGatewayTimeout", - 505: "StatusHTTPVersionNotSupported", - 506: "StatusVariantAlsoNegotiates", - 507: "StatusInsufficientStorage", - 508: "StatusLoopDetected", - 510: "StatusNotExtended", - 511: "StatusNetworkAuthenticationRequired", -} - -func CheckHTTPStatusCodes(pass *analysis.Pass) (interface{}, error) { - whitelist := map[string]bool{} - for _, code := range config.For(pass).HTTPStatusCodeWhitelist { - whitelist[code] = true - } - fn := func(node ast.Node) { - call := node.(*ast.CallExpr) - - var arg int - switch code.CallName(pass, call) { - case "net/http.Error": - arg = 2 - case "net/http.Redirect": - arg = 3 - case "net/http.StatusText": - arg = 0 - case "net/http.RedirectHandler": - arg = 1 - default: - return - } - if arg >= len(call.Args) { - return - } - tv, ok := code.IntegerLiteral(pass, call.Args[arg]) - if !ok { - return - } - n, ok := constant.Int64Val(tv.Value) - if !ok { - return - } - if whitelist[strconv.FormatInt(n, 10)] { - return - } - - s, ok := httpStatusCodes[n] - if !ok { - return - } - lit := call.Args[arg] - report.Report(pass, lit, fmt.Sprintf("should use constant http.%s instead of numeric literal %d", s, n), - report.FilterGenerated(), - report.Fixes(edit.Fix(fmt.Sprintf("use http.%s instead of %d", s, n), edit.ReplaceWithString(lit, "http."+s)))) - } - code.Preorder(pass, fn, (*ast.CallExpr)(nil)) - return nil, nil -} - -func CheckDefaultCaseOrder(pass *analysis.Pass) (interface{}, error) { - hasFallthrough := func(clause ast.Stmt) bool { - // A valid fallthrough statement may be used only as the final non-empty statement in a case clause. Thus we can - // easily avoid falsely matching fallthroughs in nested switches by not descending into blocks. - - body := clause.(*ast.CaseClause).Body - for i := len(body) - 1; i >= 0; i-- { - last := body[i] - switch stmt := last.(type) { - case *ast.EmptyStmt: - // Fallthrough may be followed by empty statements - case *ast.BranchStmt: - return stmt.Tok == token.FALLTHROUGH - default: - return false - } - } - - return false - } - - fn := func(node ast.Node) { - stmt := node.(*ast.SwitchStmt) - list := stmt.Body.List - defaultIdx := -1 - for i, c := range list { - if c.(*ast.CaseClause).List == nil { - defaultIdx = i - break - } - } - - if defaultIdx == -1 || defaultIdx == 0 || defaultIdx == len(list)-1 { - // No default case, or it's the first or last case - return - } - - if hasFallthrough(list[defaultIdx-1]) || hasFallthrough(list[defaultIdx]) { - // We either fall into or out of this case; don't mess with the order - return - } - - report.Report(pass, list[defaultIdx], "default case should be first or last in switch statement", report.FilterGenerated()) - } - code.Preorder(pass, fn, (*ast.SwitchStmt)(nil)) - return nil, nil -} - -var ( - checkYodaConditionsQ = pattern.MustParse(`(BinaryExpr left@(TrulyConstantExpression _) tok@(Or "==" "!=") right@(Not (TrulyConstantExpression _)))`) - checkYodaConditionsR = pattern.MustParse(`(BinaryExpr right tok left)`) -) - -func CheckYodaConditions(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if _, edits, ok := code.MatchAndEdit(pass, checkYodaConditionsQ, checkYodaConditionsR, node); ok { - report.Report(pass, node, "don't use Yoda conditions", - report.FilterGenerated(), - report.Fixes(edit.Fix("un-Yoda-fy", edits...))) - } - } - code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) - return nil, nil -} - -func CheckInvisibleCharacters(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - lit := node.(*ast.BasicLit) - if lit.Kind != token.STRING { - return - } - - type invalid struct { - r rune - off int - } - var invalids []invalid - hasFormat := false - hasControl := false - prev := rune(-1) - const zwj = '\u200d' - for off, r := range lit.Value { - if unicode.Is(unicode.Cf, r) { - // Don't flag joined emojis. These are multiple emojis joined with ZWJ, which some platform render as single composite emojis. - // For the purpose of this check, we consider all symbols, including all symbol modifiers, emoji. - if r != zwj || (r == zwj && !unicode.Is(unicode.S, prev)) { - invalids = append(invalids, invalid{r, off}) - hasFormat = true - } - } else if unicode.Is(unicode.Cc, r) && r != '\n' && r != '\t' && r != '\r' { - invalids = append(invalids, invalid{r, off}) - hasControl = true - } - prev = r - } - - switch len(invalids) { - case 0: - return - case 1: - var kind string - if hasFormat { - kind = "format" - } else if hasControl { - kind = "control" - } else { - panic("unreachable") - } - - r := invalids[0] - msg := fmt.Sprintf("string literal contains the Unicode %s character %U, consider using the %q escape sequence instead", kind, r.r, r.r) - - replacement := strconv.QuoteRune(r.r) - replacement = replacement[1 : len(replacement)-1] - edit := analysis.SuggestedFix{ - Message: fmt.Sprintf("replace %s character %U with %q", kind, r.r, r.r), - TextEdits: []analysis.TextEdit{{ - Pos: lit.Pos() + token.Pos(r.off), - End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), - NewText: []byte(replacement), - }}, - } - delete := analysis.SuggestedFix{ - Message: fmt.Sprintf("delete %s character %U", kind, r.r), - TextEdits: []analysis.TextEdit{{ - Pos: lit.Pos() + token.Pos(r.off), - End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), - }}, - } - report.Report(pass, lit, msg, report.Fixes(edit, delete)) - default: - var kind string - if hasFormat && hasControl { - kind = "format and control" - } else if hasFormat { - kind = "format" - } else if hasControl { - kind = "control" - } else { - panic("unreachable") - } - - msg := fmt.Sprintf("string literal contains Unicode %s characters, consider using escape sequences instead", kind) - var edits []analysis.TextEdit - var deletions []analysis.TextEdit - for _, r := range invalids { - replacement := strconv.QuoteRune(r.r) - replacement = replacement[1 : len(replacement)-1] - edits = append(edits, analysis.TextEdit{ - Pos: lit.Pos() + token.Pos(r.off), - End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), - NewText: []byte(replacement), - }) - deletions = append(deletions, analysis.TextEdit{ - Pos: lit.Pos() + token.Pos(r.off), - End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), - }) - } - edit := analysis.SuggestedFix{ - Message: fmt.Sprintf("replace all %s characters with escape sequences", kind), - TextEdits: edits, - } - delete := analysis.SuggestedFix{ - Message: fmt.Sprintf("delete all %s characters", kind), - TextEdits: deletions, - } - report.Report(pass, lit, msg, report.Fixes(edit, delete)) - } - } - code.Preorder(pass, fn, (*ast.BasicLit)(nil)) - return nil, nil -} - -func CheckExportedFunctionDocs(pass *analysis.Pass) (interface{}, error) { - fn := func(node ast.Node) { - if code.IsInTest(pass, node) { - return - } - - decl := node.(*ast.FuncDecl) - text, ok := docText(decl.Doc) - if !ok { - return - } - if !ast.IsExported(decl.Name.Name) { - return - } - kind := "function" - if decl.Recv != nil { - kind = "method" - var ident *ast.Ident - T := decl.Recv.List[0].Type - if T_, ok := T.(*ast.StarExpr); ok { - T = T_.X - } - switch T := T.(type) { - case *ast.IndexExpr: - ident = T.X.(*ast.Ident) - case *ast.IndexListExpr: - ident = T.X.(*ast.Ident) - case *ast.Ident: - ident = T - default: - lint.ExhaustiveTypeSwitch(T) - } - if !ast.IsExported(ident.Name) { - return - } - } - prefix := decl.Name.Name + " " - if !strings.HasPrefix(text, prefix) { - report.Report(pass, decl.Doc, fmt.Sprintf(`comment on exported %s %s should be of the form "%s..."`, kind, decl.Name.Name, prefix), report.FilterGenerated()) - } - } - - code.Preorder(pass, fn, (*ast.FuncDecl)(nil)) - return nil, nil -} - -func CheckExportedTypeDocs(pass *analysis.Pass) (interface{}, error) { - var genDecl *ast.GenDecl - fn := func(node ast.Node, push bool) bool { - if !push { - genDecl = nil - return false - } - if code.IsInTest(pass, node) { - return false - } - - switch node := node.(type) { - case *ast.GenDecl: - if node.Tok == token.IMPORT { - return false - } - genDecl = node - return true - case *ast.TypeSpec: - if !ast.IsExported(node.Name.Name) { - return false - } - - doc := node.Doc - text, ok := docText(doc) - if !ok { - if len(genDecl.Specs) != 1 { - // more than one spec in the GenDecl, don't validate the - // docstring - return false - } - if genDecl.Lparen.IsValid() { - // 'type ( T )' is weird, don't guess the user's intention - return false - } - doc = genDecl.Doc - text, ok = docText(doc) - if !ok { - return false - } - } - - // Check comment before we strip articles in case the type's name is an article. - if strings.HasPrefix(text, node.Name.Name+" ") { - return false - } - - s := text - articles := [...]string{"A", "An", "The"} - for _, a := range articles { - if strings.HasPrefix(s, a+" ") { - s = s[len(a)+1:] - break - } - } - if !strings.HasPrefix(s, node.Name.Name+" ") { - report.Report(pass, doc, fmt.Sprintf(`comment on exported type %s should be of the form "%s ..." (with optional leading article)`, node.Name.Name, node.Name.Name), report.FilterGenerated()) - } - return false - case *ast.FuncLit, *ast.FuncDecl: - return false - default: - lint.ExhaustiveTypeSwitch(node) - return false - } - } - - pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.GenDecl)(nil), (*ast.TypeSpec)(nil), (*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)}, fn) - return nil, nil -} - -func CheckExportedVarDocs(pass *analysis.Pass) (interface{}, error) { - var genDecl *ast.GenDecl - fn := func(node ast.Node, push bool) bool { - if !push { - genDecl = nil - return false - } - if code.IsInTest(pass, node) { - return false - } - - switch node := node.(type) { - case *ast.GenDecl: - if node.Tok == token.IMPORT { - return false - } - genDecl = node - return true - case *ast.ValueSpec: - if genDecl.Lparen.IsValid() || len(node.Names) > 1 { - // Don't try to guess the user's intention - return false - } - name := node.Names[0].Name - if !ast.IsExported(name) { - return false - } - text, ok := docText(genDecl.Doc) - if !ok { - return false - } - prefix := name + " " - if !strings.HasPrefix(text, prefix) { - kind := "var" - if genDecl.Tok == token.CONST { - kind = "const" - } - report.Report(pass, genDecl.Doc, fmt.Sprintf(`comment on exported %s %s should be of the form "%s..."`, kind, name, prefix), report.FilterGenerated()) - } - return false - case *ast.FuncLit, *ast.FuncDecl: - return false - default: - lint.ExhaustiveTypeSwitch(node) - return false - } - } - - pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.GenDecl)(nil), (*ast.ValueSpec)(nil), (*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)}, fn) - return nil, nil -} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1000/st1000.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1000/st1000.go new file mode 100644 index 000000000..246dbc247 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1000/st1000.go @@ -0,0 +1,83 @@ +package st1000 + +import ( + "fmt" + "go/ast" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1000", + Run: run, + }, + Doc: &lint.RawDocumentation{ + Title: `Incorrect or missing package comment`, + Text: `Packages must have a package comment that is formatted according to +the guidelines laid out in +https://go.dev/wiki/CodeReviewComments#package-comments.`, + Since: "2019.1", + NonDefault: true, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + // - At least one file in a non-main package should have a package comment + // + // - The comment should be of the form + // "Package x ...". This has a slight potential for false + // positives, as multiple files can have package comments, in + // which case they get appended. But that doesn't happen a lot in + // the real world. + + if pass.Pkg.Name() == "main" { + return nil, nil + } + hasDocs := false + for _, f := range pass.Files { + if code.IsInTest(pass, f) { + continue + } + text, ok := docText(f.Doc) + if ok { + hasDocs = true + prefix := "Package " + f.Name.Name + isNonAlpha := func(b byte) bool { + // This check only considers ASCII, which can lead to false negatives for some malformed package + // comments. + return !((b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')) + } + if !strings.HasPrefix(text, prefix) || (len(text) > len(prefix) && !isNonAlpha(text[len(prefix)])) { + report.Report(pass, f.Doc, fmt.Sprintf(`package comment should be of the form "%s..."`, prefix)) + } + } + } + + if !hasDocs { + for _, f := range pass.Files { + if code.IsInTest(pass, f) { + continue + } + report.Report(pass, f, "at least one file in a package should have a package comment", report.ShortRange()) + } + } + return nil, nil +} + +func docText(doc *ast.CommentGroup) (string, bool) { + if doc == nil { + return "", false + } + // We trim spaces primarily because of /**/ style comments, which often have leading space. + text := strings.TrimSpace(doc.Text()) + return text, text != "" +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1001/st1001.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1001/st1001.go new file mode 100644 index 000000000..3b2fd2ad2 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1001/st1001.go @@ -0,0 +1,71 @@ +package st1001 + +import ( + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/config" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1001", + Run: run, + Requires: []*analysis.Analyzer{generated.Analyzer, config.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Dot imports are discouraged`, + Text: `Dot imports that aren't in external test packages are discouraged. + +The \'dot_import_whitelist\' option can be used to whitelist certain +imports. + +Quoting Go Code Review Comments: + +> The \'import .\' form can be useful in tests that, due to circular +> dependencies, cannot be made part of the package being tested: +> +> package foo_test +> +> import ( +> "bar/testutil" // also imports "foo" +> . "foo" +> ) +> +> In this case, the test file cannot be in package foo because it +> uses \'bar/testutil\', which imports \'foo\'. So we use the \'import .\' +> form to let the file pretend to be part of package foo even though +> it is not. Except for this one case, do not use \'import .\' in your +> programs. It makes the programs much harder to read because it is +> unclear whether a name like \'Quux\' is a top-level identifier in the +> current package or in an imported package.`, + Since: "2019.1", + Options: []string{"dot_import_whitelist"}, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, f := range pass.Files { + imports: + for _, imp := range f.Imports { + path := imp.Path.Value + path = path[1 : len(path)-1] + for _, w := range config.For(pass).DotImportWhitelist { + if w == path { + continue imports + } + } + + if imp.Name != nil && imp.Name.Name == "." && !code.IsInTest(pass, f) { + report.Report(pass, imp, "should not use dot imports", report.FilterGenerated()) + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/names.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1003/st1003.go similarity index 88% rename from tools/vendor/honnef.co/go/tools/stylecheck/names.go rename to tools/vendor/honnef.co/go/tools/stylecheck/st1003/st1003.go index d37bf6baf..d2ff5a9e5 100644 --- a/tools/vendor/honnef.co/go/tools/stylecheck/names.go +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1003/st1003.go @@ -1,7 +1,4 @@ -// Copyright (c) 2013 The Go Authors. All rights reserved. -// Copyright (c) 2018 Dominik Honnef. All rights reserved. - -package stylecheck +package st1003 import ( "fmt" @@ -11,12 +8,40 @@ import ( "unicode" "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" "honnef.co/go/tools/analysis/report" "honnef.co/go/tools/config" "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" ) +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1003", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, config.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Poorly chosen identifier`, + Text: `Identifiers, such as variable and package names, follow certain rules. + +See the following links for details: + +- https://go.dev/doc/effective_go#package-names +- https://go.dev/doc/effective_go#mixed-caps +- https://go.dev/wiki/CodeReviewComments#initialisms +- https://go.dev/wiki/CodeReviewComments#variable-names`, + Since: "2019.1", + NonDefault: true, + Options: []string{"initialisms"}, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + // knownNameExceptions is a set of names that are known to be exempt from naming checks. // This is usually because they are constrained by having to match names in the // standard library. @@ -25,7 +50,7 @@ var knownNameExceptions = map[string]bool{ "kWh": true, } -func CheckNames(pass *analysis.Pass) (interface{}, error) { +func run(pass *analysis.Pass) (interface{}, error) { // A large part of this function is copied from // github.com/golang/lint, Copyright (c) 2013 The Go Authors, // licensed under the BSD 3-clause license. diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1005/st1005.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1005/st1005.go new file mode 100644 index 000000000..a2909c377 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1005/st1005.go @@ -0,0 +1,130 @@ +package st1005 + +import ( + "go/constant" + "strings" + "unicode" + "unicode/utf8" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/ir" + "honnef.co/go/tools/go/ir/irutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1005", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Incorrectly formatted error string`, + Text: `Error strings follow a set of guidelines to ensure uniformity and good +composability. + +Quoting Go Code Review Comments: + +> Error strings should not be capitalized (unless beginning with +> proper nouns or acronyms) or end with punctuation, since they are +> usually printed following other context. That is, use +> \'fmt.Errorf("something bad")\' not \'fmt.Errorf("Something bad")\', so +> that \'log.Printf("Reading %s: %v", filename, err)\' formats without a +> spurious capital letter mid-message.`, + Since: "2019.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + objNames := map[*ir.Package]map[string]bool{} + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg + objNames[irpkg] = map[string]bool{} + for _, m := range irpkg.Members { + if typ, ok := m.(*ir.Type); ok { + objNames[irpkg][typ.Name()] = true + } + } + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + objNames[fn.Package()][fn.Name()] = true + } + + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + if code.IsInTest(pass, fn) { + // We don't care about malformed error messages in tests; + // they're usually for direct human consumption, not part + // of an API + continue + } + for _, block := range fn.Blocks { + instrLoop: + for _, ins := range block.Instrs { + call, ok := ins.(*ir.Call) + if !ok { + continue + } + if !irutil.IsCallToAny(call.Common(), "errors.New", "fmt.Errorf") { + continue + } + + k, ok := call.Common().Args[0].(*ir.Const) + if !ok { + continue + } + + s := constant.StringVal(k.Value) + if len(s) == 0 { + continue + } + switch s[len(s)-1] { + case '.', ':', '!', '\n': + report.Report(pass, call, "error strings should not end with punctuation or newlines") + } + idx := strings.IndexByte(s, ' ') + if idx == -1 { + // single word error message, probably not a real + // error but something used in tests or during + // debugging + continue + } + word := s[:idx] + first, n := utf8.DecodeRuneInString(word) + if !unicode.IsUpper(first) { + continue + } + for _, c := range word[n:] { + if unicode.IsUpper(c) || unicode.IsDigit(c) { + // Word is probably an initialism or multi-word function name. Digits cover elliptic curves like + // P384. + continue instrLoop + } + } + + if strings.ContainsRune(word, '(') { + // Might be a function call + continue instrLoop + } + word = strings.TrimRightFunc(word, func(r rune) bool { return unicode.IsPunct(r) }) + if objNames[fn.Package()][word] { + // Word is probably the name of a function or type in this package + continue + } + // First word in error starts with a capital + // letter, and the word doesn't contain any other + // capitals, making it unlikely to be an + // initialism or multi-word function name. + // + // It could still be a proper noun, though. + + report.Report(pass, call, "error strings should not be capitalized") + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1006/st1006.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1006/st1006.go new file mode 100644 index 000000000..42aad45cd --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1006/st1006.go @@ -0,0 +1,65 @@ +package st1006 + +import ( + "go/types" + + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1006", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Poorly chosen receiver name`, + Text: `Quoting Go Code Review Comments: + +> The name of a method's receiver should be a reflection of its +> identity; often a one or two letter abbreviation of its type +> suffices (such as "c" or "cl" for "Client"). Don't use generic +> names such as "me", "this" or "self", identifiers typical of +> object-oriented languages that place more emphasis on methods as +> opposed to functions. The name need not be as descriptive as that +> of a method argument, as its role is obvious and serves no +> documentary purpose. It can be very short as it will appear on +> almost every line of every method of the type; familiarity admits +> brevity. Be consistent, too: if you call the receiver "c" in one +> method, don't call it "cl" in another.`, + Since: "2019.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg + for _, m := range irpkg.Members { + if T, ok := m.Object().(*types.TypeName); ok && !T.IsAlias() { + ms := typeutil.IntuitiveMethodSet(T.Type(), nil) + for _, sel := range ms { + fn := sel.Obj().(*types.Func) + recv := fn.Type().(*types.Signature).Recv() + if typeutil.Dereference(recv.Type()) != T.Type() { + // skip embedded methods + continue + } + if recv.Name() == "self" || recv.Name() == "this" { + report.Report(pass, recv, `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`, report.FilterGenerated()) + } + if recv.Name() == "_" { + report.Report(pass, recv, "receiver name should not be an underscore, omit the name if it is unused", report.FilterGenerated()) + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1008/st1008.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1008/st1008.go new file mode 100644 index 000000000..23c557ea9 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1008/st1008.go @@ -0,0 +1,58 @@ +package st1008 + +import ( + "go/types" + + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1008", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `A function's error value should be its last return value`, + Text: `A function's error value should be its last return value.`, + Since: `2019.1`, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { +fnLoop: + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + sig := fn.Type().(*types.Signature) + rets := sig.Results() + if rets == nil || rets.Len() < 2 { + continue + } + + if types.Unalias(rets.At(rets.Len()-1).Type()) == types.Universe.Lookup("error").Type() { + // Last return type is error. If the function also returns + // errors in other positions, that's fine. + continue + } + + if rets.Len() >= 2 && + types.Unalias(rets.At(rets.Len()-1).Type()) == types.Universe.Lookup("bool").Type() && + types.Unalias(rets.At(rets.Len()-2).Type()) == types.Universe.Lookup("error").Type() { + // Accept (..., error, bool) and assume it's a comma-ok function. It's not clear whether the bool should come last or not for these kinds of functions. + continue + } + for i := rets.Len() - 2; i >= 0; i-- { + if types.Unalias(rets.At(i).Type()) == types.Universe.Lookup("error").Type() { + report.Report(pass, rets.At(i), "error should be returned as the last argument", report.ShortRange()) + continue fnLoop + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1011/st1011.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1011/st1011.go new file mode 100644 index 000000000..3bf7ecdf1 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1011/st1011.go @@ -0,0 +1,88 @@ +package st1011 + +import ( + "fmt" + "go/ast" + "go/token" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1011", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Poorly chosen name for variable of type \'time.Duration\'`, + Text: `\'time.Duration\' values represent an amount of time, which is represented +as a count of nanoseconds. An expression like \'5 * time.Microsecond\' +yields the value \'5000\'. It is therefore not appropriate to suffix a +variable of type \'time.Duration\' with any time unit, such as \'Msec\' or +\'Milli\'.`, + Since: `2019.1`, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + suffixes := []string{ + "Sec", "Secs", "Seconds", + "Msec", "Msecs", + "Milli", "Millis", "Milliseconds", + "Usec", "Usecs", "Microseconds", + "MS", "Ms", + } + fn := func(names []*ast.Ident) { + for _, name := range names { + if _, ok := pass.TypesInfo.Defs[name]; !ok { + continue + } + T := pass.TypesInfo.TypeOf(name) + if !typeutil.IsTypeWithName(T, "time.Duration") && !typeutil.IsPointerToTypeWithName(T, "time.Duration") { + continue + } + for _, suffix := range suffixes { + if strings.HasSuffix(name.Name, suffix) { + report.Report(pass, name, fmt.Sprintf("var %s is of type %v; don't use unit-specific suffix %q", name.Name, T, suffix)) + break + } + } + } + } + + fn2 := func(node ast.Node) { + switch node := node.(type) { + case *ast.ValueSpec: + fn(node.Names) + case *ast.FieldList: + for _, field := range node.List { + fn(field.Names) + } + case *ast.AssignStmt: + if node.Tok != token.DEFINE { + break + } + var names []*ast.Ident + for _, lhs := range node.Lhs { + if lhs, ok := lhs.(*ast.Ident); ok { + names = append(names, lhs) + } + } + fn(names) + } + } + + code.Preorder(pass, fn2, (*ast.ValueSpec)(nil), (*ast.FieldList)(nil), (*ast.AssignStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1012/st1012.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1012/st1012.go new file mode 100644 index 000000000..fdeaee76d --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1012/st1012.go @@ -0,0 +1,68 @@ +package st1012 + +import ( + "fmt" + "go/ast" + "go/token" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1012", + Run: run, + }, + Doc: &lint.RawDocumentation{ + Title: `Poorly chosen name for error variable`, + Text: `Error variables that are part of an API should be called \'errFoo\' or +\'ErrFoo\'.`, + Since: "2019.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, f := range pass.Files { + for _, decl := range f.Decls { + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.VAR { + continue + } + for _, spec := range gen.Specs { + spec := spec.(*ast.ValueSpec) + if len(spec.Names) != len(spec.Values) { + continue + } + + for i, name := range spec.Names { + val := spec.Values[i] + if !code.IsCallToAny(pass, val, "errors.New", "fmt.Errorf") { + continue + } + + if pass.Pkg.Path() == "net/http" && strings.HasPrefix(name.Name, "http2err") { + // special case for internal variable names of + // bundled HTTP 2 code in net/http + continue + } + prefix := "err" + if name.IsExported() { + prefix = "Err" + } + if !strings.HasPrefix(name.Name, prefix) { + report.Report(pass, name, fmt.Sprintf("error var %s should have name of the form %sFoo", name.Name, prefix)) + } + } + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1013/st1013.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1013/st1013.go new file mode 100644 index 000000000..d28daa35e --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1013/st1013.go @@ -0,0 +1,151 @@ +package st1013 + +import ( + "fmt" + "go/ast" + "go/constant" + "strconv" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/config" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1013", + Run: run, + Requires: []*analysis.Analyzer{generated.Analyzer, config.Analyzer, inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Should use constants for HTTP error codes, not magic numbers`, + Text: `HTTP has a tremendous number of status codes. While some of those are +well known (200, 400, 404, 500), most of them are not. The \'net/http\' +package provides constants for all status codes that are part of the +various specifications. It is recommended to use these constants +instead of hard-coding magic numbers, to vastly improve the +readability of your code.`, + Since: "2019.1", + Options: []string{"http_status_code_whitelist"}, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + whitelist := map[string]bool{} + for _, code := range config.For(pass).HTTPStatusCodeWhitelist { + whitelist[code] = true + } + fn := func(node ast.Node) { + call := node.(*ast.CallExpr) + + var arg int + switch code.CallName(pass, call) { + case "net/http.Error": + arg = 2 + case "net/http.Redirect": + arg = 3 + case "net/http.StatusText": + arg = 0 + case "net/http.RedirectHandler": + arg = 1 + default: + return + } + if arg >= len(call.Args) { + return + } + tv, ok := code.IntegerLiteral(pass, call.Args[arg]) + if !ok { + return + } + n, ok := constant.Int64Val(tv.Value) + if !ok { + return + } + if whitelist[strconv.FormatInt(n, 10)] { + return + } + + s, ok := httpStatusCodes[n] + if !ok { + return + } + lit := call.Args[arg] + report.Report(pass, lit, fmt.Sprintf("should use constant http.%s instead of numeric literal %d", s, n), + report.FilterGenerated(), + report.Fixes(edit.Fix(fmt.Sprintf("use http.%s instead of %d", s, n), edit.ReplaceWithString(lit, "http."+s)))) + } + code.Preorder(pass, fn, (*ast.CallExpr)(nil)) + return nil, nil +} + +var httpStatusCodes = map[int64]string{ + 100: "StatusContinue", + 101: "StatusSwitchingProtocols", + 102: "StatusProcessing", + 200: "StatusOK", + 201: "StatusCreated", + 202: "StatusAccepted", + 203: "StatusNonAuthoritativeInfo", + 204: "StatusNoContent", + 205: "StatusResetContent", + 206: "StatusPartialContent", + 207: "StatusMultiStatus", + 208: "StatusAlreadyReported", + 226: "StatusIMUsed", + 300: "StatusMultipleChoices", + 301: "StatusMovedPermanently", + 302: "StatusFound", + 303: "StatusSeeOther", + 304: "StatusNotModified", + 305: "StatusUseProxy", + 307: "StatusTemporaryRedirect", + 308: "StatusPermanentRedirect", + 400: "StatusBadRequest", + 401: "StatusUnauthorized", + 402: "StatusPaymentRequired", + 403: "StatusForbidden", + 404: "StatusNotFound", + 405: "StatusMethodNotAllowed", + 406: "StatusNotAcceptable", + 407: "StatusProxyAuthRequired", + 408: "StatusRequestTimeout", + 409: "StatusConflict", + 410: "StatusGone", + 411: "StatusLengthRequired", + 412: "StatusPreconditionFailed", + 413: "StatusRequestEntityTooLarge", + 414: "StatusRequestURITooLong", + 415: "StatusUnsupportedMediaType", + 416: "StatusRequestedRangeNotSatisfiable", + 417: "StatusExpectationFailed", + 418: "StatusTeapot", + 422: "StatusUnprocessableEntity", + 423: "StatusLocked", + 424: "StatusFailedDependency", + 426: "StatusUpgradeRequired", + 428: "StatusPreconditionRequired", + 429: "StatusTooManyRequests", + 431: "StatusRequestHeaderFieldsTooLarge", + 451: "StatusUnavailableForLegalReasons", + 500: "StatusInternalServerError", + 501: "StatusNotImplemented", + 502: "StatusBadGateway", + 503: "StatusServiceUnavailable", + 504: "StatusGatewayTimeout", + 505: "StatusHTTPVersionNotSupported", + 506: "StatusVariantAlsoNegotiates", + 507: "StatusInsufficientStorage", + 508: "StatusLoopDetected", + 510: "StatusNotExtended", + 511: "StatusNetworkAuthenticationRequired", +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1015/st1015.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1015/st1015.go new file mode 100644 index 000000000..a03be7471 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1015/st1015.go @@ -0,0 +1,77 @@ +package st1015 + +import ( + "go/ast" + "go/token" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1015", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `A switch's default case should be the first or last case`, + Since: "2019.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + hasFallthrough := func(clause ast.Stmt) bool { + // A valid fallthrough statement may be used only as the final non-empty statement in a case clause. Thus we can + // easily avoid falsely matching fallthroughs in nested switches by not descending into blocks. + + body := clause.(*ast.CaseClause).Body + for i := len(body) - 1; i >= 0; i-- { + last := body[i] + switch stmt := last.(type) { + case *ast.EmptyStmt: + // Fallthrough may be followed by empty statements + case *ast.BranchStmt: + return stmt.Tok == token.FALLTHROUGH + default: + return false + } + } + + return false + } + + fn := func(node ast.Node) { + stmt := node.(*ast.SwitchStmt) + list := stmt.Body.List + defaultIdx := -1 + for i, c := range list { + if c.(*ast.CaseClause).List == nil { + defaultIdx = i + break + } + } + + if defaultIdx == -1 || defaultIdx == 0 || defaultIdx == len(list)-1 { + // No default case, or it's the first or last case + return + } + + if hasFallthrough(list[defaultIdx-1]) || hasFallthrough(list[defaultIdx]) { + // We either fall into or out of this case; don't mess with the order + return + } + + report.Report(pass, list[defaultIdx], "default case should be first or last in switch statement", report.FilterGenerated()) + } + code.Preorder(pass, fn, (*ast.SwitchStmt)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1016/st1016.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1016/st1016.go new file mode 100644 index 000000000..d175a749a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1016/st1016.go @@ -0,0 +1,74 @@ +package st1016 + +import ( + "fmt" + "go/types" + "sort" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/internal/passes/buildir" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1016", + Run: run, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Use consistent method receiver names`, + Since: "2019.1", + NonDefault: true, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg + for _, m := range irpkg.Members { + names := map[string]int{} + + var firstFn *types.Func + if T, ok := m.Object().(*types.TypeName); ok && !T.IsAlias() { + ms := typeutil.IntuitiveMethodSet(T.Type(), nil) + for _, sel := range ms { + fn := sel.Obj().(*types.Func) + recv := fn.Type().(*types.Signature).Recv() + if code.IsGenerated(pass, recv.Pos()) { + // Don't concern ourselves with methods in generated code + continue + } + if typeutil.Dereference(recv.Type()) != T.Type() { + // skip embedded methods + continue + } + if firstFn == nil { + firstFn = fn + } + if recv.Name() != "" && recv.Name() != "_" { + names[recv.Name()]++ + } + } + } + + if len(names) > 1 { + var seen []string + for name, count := range names { + seen = append(seen, fmt.Sprintf("%dx %q", count, name)) + } + sort.Strings(seen) + + report.Report(pass, firstFn, fmt.Sprintf("methods on the same type should have the same receiver name (seen %s)", strings.Join(seen, ", "))) + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1017/st1017.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1017/st1017.go new file mode 100644 index 000000000..6e8ccca64 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1017/st1017.go @@ -0,0 +1,52 @@ +package st1017 + +import ( + "go/ast" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/edit" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + "honnef.co/go/tools/pattern" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1017", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Don't use Yoda conditions`, + Text: `Yoda conditions are conditions of the kind \"if 42 == x\", where the +literal is on the left side of the comparison. These are a common +idiom in languages in which assignment is an expression, to avoid bugs +of the kind \"if (x = 42)\". In Go, which doesn't allow for this kind of +bug, we prefer the more idiomatic \"if x == 42\".`, + Since: "2019.2", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +var ( + checkYodaConditionsQ = pattern.MustParse(`(BinaryExpr left@(TrulyConstantExpression _) tok@(Or "==" "!=") right@(Not (TrulyConstantExpression _)))`) + checkYodaConditionsR = pattern.MustParse(`(BinaryExpr right tok left)`) +) + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if _, edits, ok := code.MatchAndEdit(pass, checkYodaConditionsQ, checkYodaConditionsR, node); ok { + report.Report(pass, node, "don't use Yoda conditions", + report.FilterGenerated(), + report.Fixes(edit.Fix("un-Yoda-fy", edits...))) + } + } + code.Preorder(pass, fn, (*ast.BinaryExpr)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1018/st1018.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1018/st1018.go new file mode 100644 index 000000000..85d961c61 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1018/st1018.go @@ -0,0 +1,157 @@ +package st1018 + +import ( + "fmt" + "go/ast" + "go/token" + "strconv" + "unicode" + "unicode/utf8" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1018", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Avoid zero-width and control characters in string literals`, + Since: "2019.2", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + lit := node.(*ast.BasicLit) + if lit.Kind != token.STRING { + return + } + + type invalid struct { + r rune + off int + } + var invalids []invalid + hasFormat := false + hasControl := false + prev := rune(-1) + const zwj = '\u200d' + for off, r := range lit.Value { + if unicode.Is(unicode.Cf, r) { + if r >= '\U000e0020' && r <= '\U000e007f' { + // These are used for spelling out country codes for flag emoji + } else if unicode.Is(unicode.Variation_Selector, r) { + // Always allow variation selectors + } else if r == zwj && (unicode.Is(unicode.S, prev) || unicode.Is(unicode.Variation_Selector, prev)) { + // Allow zero-width joiner in emoji, including those that use variation selectors. + + // Technically some foreign scripts make valid use of zero-width joiners, too, but for now we'll err + // on the side of flagging all non-emoji uses of ZWJ. + } else { + switch r { + case '\u0600', '\u0601', '\u0602', '\u0603', '\u0604', '\u0605', '\u0890', '\u0891', '\u08e2': + // Arabic characters that are not actually invisible. If anyone knows why these are in the + // Other, Format category please let me know. + case '\u061c', '\u202A', '\u202B', '\u202D', '\u202E', '\u2066', '\u2067', '\u2068', '\u202C', '\u2069': + // Bidirectional formatting characters. At best they will render confusingly, at worst they're used + // to cause confusion. + fallthrough + default: + invalids = append(invalids, invalid{r, off}) + hasFormat = true + } + } + } else if unicode.Is(unicode.Cc, r) && r != '\n' && r != '\t' && r != '\r' { + invalids = append(invalids, invalid{r, off}) + hasControl = true + } + prev = r + } + + switch len(invalids) { + case 0: + return + case 1: + var kind string + if hasFormat { + kind = "format" + } else if hasControl { + kind = "control" + } else { + panic("unreachable") + } + + r := invalids[0] + msg := fmt.Sprintf("string literal contains the Unicode %s character %U, consider using the %q escape sequence instead", kind, r.r, r.r) + + replacement := strconv.QuoteRune(r.r) + replacement = replacement[1 : len(replacement)-1] + edit := analysis.SuggestedFix{ + Message: fmt.Sprintf("replace %s character %U with %q", kind, r.r, r.r), + TextEdits: []analysis.TextEdit{{ + Pos: lit.Pos() + token.Pos(r.off), + End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), + NewText: []byte(replacement), + }}, + } + delete := analysis.SuggestedFix{ + Message: fmt.Sprintf("delete %s character %U", kind, r.r), + TextEdits: []analysis.TextEdit{{ + Pos: lit.Pos() + token.Pos(r.off), + End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), + }}, + } + report.Report(pass, lit, msg, report.Fixes(edit, delete)) + default: + var kind string + if hasFormat && hasControl { + kind = "format and control" + } else if hasFormat { + kind = "format" + } else if hasControl { + kind = "control" + } else { + panic("unreachable") + } + + msg := fmt.Sprintf("string literal contains Unicode %s characters, consider using escape sequences instead", kind) + var edits []analysis.TextEdit + var deletions []analysis.TextEdit + for _, r := range invalids { + replacement := strconv.QuoteRune(r.r) + replacement = replacement[1 : len(replacement)-1] + edits = append(edits, analysis.TextEdit{ + Pos: lit.Pos() + token.Pos(r.off), + End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), + NewText: []byte(replacement), + }) + deletions = append(deletions, analysis.TextEdit{ + Pos: lit.Pos() + token.Pos(r.off), + End: lit.Pos() + token.Pos(r.off) + token.Pos(utf8.RuneLen(r.r)), + }) + } + edit := analysis.SuggestedFix{ + Message: fmt.Sprintf("replace all %s characters with escape sequences", kind), + TextEdits: edits, + } + delete := analysis.SuggestedFix{ + Message: fmt.Sprintf("delete all %s characters", kind), + TextEdits: deletions, + } + report.Report(pass, lit, msg, report.Fixes(edit, delete)) + } + } + code.Preorder(pass, fn, (*ast.BasicLit)(nil)) + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1019/st1019.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1019/st1019.go new file mode 100644 index 000000000..f08781ec3 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1019/st1019.go @@ -0,0 +1,78 @@ +package st1019 + +import ( + "fmt" + "go/ast" + + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1019", + Run: run, + Requires: []*analysis.Analyzer{generated.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: `Importing the same package multiple times`, + Text: `Go allows importing the same package multiple times, as long as +different import aliases are being used. That is, the following +bit of code is valid: + + import ( + "fmt" + fumpt "fmt" + format "fmt" + _ "fmt" + ) + +However, this is very rarely done on purpose. Usually, it is a +sign of code that got refactored, accidentally adding duplicate +import statements. It is also a rarely known feature, which may +contribute to confusion. + +Do note that sometimes, this feature may be used +intentionally (see for example +https://github.com/golang/go/commit/3409ce39bfd7584523b7a8c150a310cea92d879d) +– if you want to allow this pattern in your code base, you're +advised to disable this check.`, + Since: "2020.1", + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + for _, f := range pass.Files { + // Collect all imports by their import path + imports := make(map[string][]*ast.ImportSpec, len(f.Imports)) + for _, imp := range f.Imports { + imports[imp.Path.Value] = append(imports[imp.Path.Value], imp) + } + + for path, value := range imports { + if path[1:len(path)-1] == "unsafe" { + // Don't flag unsafe. Cgo generated code imports + // unsafe using the blank identifier, and most + // user-written cgo code also imports unsafe + // explicitly. + continue + } + // If there's more than one import per path, we flag that + if len(value) > 1 { + s := fmt.Sprintf("package %s is being imported more than once", path) + opts := []report.Option{report.FilterGenerated()} + for _, imp := range value[1:] { + opts = append(opts, report.Related(imp, fmt.Sprintf("other import of %s", path))) + } + report.Report(pass, value[0], s, opts...) + } + } + } + return nil, nil +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1020/st1020.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1020/st1020.go new file mode 100644 index 000000000..aed4290b6 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1020/st1020.go @@ -0,0 +1,101 @@ +package st1020 + +import ( + "fmt" + "go/ast" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1020", + Run: run, + Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "The documentation of an exported function should start with the function's name", + Text: `Doc comments work best as complete sentences, which +allow a wide variety of automated presentations. The first sentence +should be a one-sentence summary that starts with the name being +declared. + +If every doc comment begins with the name of the item it describes, +you can use the \'doc\' subcommand of the \'go\' tool and run the output +through grep. + +See https://go.dev/doc/effective_go#commentary for more +information on how to write good documentation.`, + Since: "2020.1", + NonDefault: true, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + fn := func(node ast.Node) { + if code.IsInTest(pass, node) { + return + } + + decl := node.(*ast.FuncDecl) + text, ok := docText(decl.Doc) + if !ok { + return + } + if !ast.IsExported(decl.Name.Name) { + return + } + if strings.HasPrefix(text, "Deprecated: ") { + return + } + + kind := "function" + if decl.Recv != nil { + kind = "method" + var ident *ast.Ident + T := decl.Recv.List[0].Type + if T_, ok := T.(*ast.StarExpr); ok { + T = T_.X + } + switch T := T.(type) { + case *ast.IndexExpr: + ident = T.X.(*ast.Ident) + case *ast.IndexListExpr: + ident = T.X.(*ast.Ident) + case *ast.Ident: + ident = T + default: + lint.ExhaustiveTypeSwitch(T) + } + if !ast.IsExported(ident.Name) { + return + } + } + prefix := decl.Name.Name + " " + if !strings.HasPrefix(text, prefix) { + report.Report(pass, decl.Doc, fmt.Sprintf(`comment on exported %s %s should be of the form "%s..."`, kind, decl.Name.Name, prefix), report.FilterGenerated()) + } + } + + code.Preorder(pass, fn, (*ast.FuncDecl)(nil)) + return nil, nil +} + +func docText(doc *ast.CommentGroup) (string, bool) { + if doc == nil { + return "", false + } + // We trim spaces primarily because of /**/ style comments, which often have leading space. + text := strings.TrimSpace(doc.Text()) + return text, text != "" +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1021/st1021.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1021/st1021.go new file mode 100644 index 000000000..8ba6a5b23 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1021/st1021.go @@ -0,0 +1,124 @@ +package st1021 + +import ( + "fmt" + "go/ast" + "go/token" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1021", + Run: run, + Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "The documentation of an exported type should start with type's name", + Text: `Doc comments work best as complete sentences, which +allow a wide variety of automated presentations. The first sentence +should be a one-sentence summary that starts with the name being +declared. + +If every doc comment begins with the name of the item it describes, +you can use the \'doc\' subcommand of the \'go\' tool and run the output +through grep. + +See https://go.dev/doc/effective_go#commentary for more +information on how to write good documentation.`, + Since: "2020.1", + NonDefault: true, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + var genDecl *ast.GenDecl + fn := func(node ast.Node, push bool) bool { + if !push { + genDecl = nil + return false + } + if code.IsInTest(pass, node) { + return false + } + + switch node := node.(type) { + case *ast.GenDecl: + if node.Tok == token.IMPORT { + return false + } + genDecl = node + return true + case *ast.TypeSpec: + if !ast.IsExported(node.Name.Name) { + return false + } + + doc := node.Doc + text, ok := docText(doc) + if !ok { + if len(genDecl.Specs) != 1 { + // more than one spec in the GenDecl, don't validate the + // docstring + return false + } + if genDecl.Lparen.IsValid() { + // 'type ( T )' is weird, don't guess the user's intention + return false + } + doc = genDecl.Doc + text, ok = docText(doc) + if !ok { + return false + } + } + + // Check comment before we strip articles in case the type's name is an article. + if strings.HasPrefix(text, node.Name.Name+" ") { + return false + } + + s := text + articles := [...]string{"A", "An", "The"} + for _, a := range articles { + if strings.HasPrefix(s, a+" ") { + s = s[len(a)+1:] + break + } + } + if !strings.HasPrefix(s, node.Name.Name+" ") { + report.Report(pass, doc, fmt.Sprintf(`comment on exported type %s should be of the form "%s ..." (with optional leading article)`, node.Name.Name, node.Name.Name), report.FilterGenerated()) + } + return false + case *ast.FuncLit, *ast.FuncDecl: + return false + default: + lint.ExhaustiveTypeSwitch(node) + return false + } + } + + pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.GenDecl)(nil), (*ast.TypeSpec)(nil), (*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)}, fn) + return nil, nil +} + +func docText(doc *ast.CommentGroup) (string, bool) { + if doc == nil { + return "", false + } + // We trim spaces primarily because of /**/ style comments, which often have leading space. + text := strings.TrimSpace(doc.Text()) + return text, text != "" +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1022/st1022.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1022/st1022.go new file mode 100644 index 000000000..d37711988 --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1022/st1022.go @@ -0,0 +1,105 @@ +package st1022 + +import ( + "fmt" + "go/ast" + "go/token" + "strings" + + "honnef.co/go/tools/analysis/code" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/analysis/report" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: &analysis.Analyzer{ + Name: "ST1022", + Run: run, + Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, + }, + Doc: &lint.RawDocumentation{ + Title: "The documentation of an exported variable or constant should start with variable's name", + Text: `Doc comments work best as complete sentences, which +allow a wide variety of automated presentations. The first sentence +should be a one-sentence summary that starts with the name being +declared. + +If every doc comment begins with the name of the item it describes, +you can use the \'doc\' subcommand of the \'go\' tool and run the output +through grep. + +See https://go.dev/doc/effective_go#commentary for more +information on how to write good documentation.`, + Since: "2020.1", + NonDefault: true, + MergeIf: lint.MergeIfAny, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer + +func run(pass *analysis.Pass) (interface{}, error) { + var genDecl *ast.GenDecl + fn := func(node ast.Node, push bool) bool { + if !push { + genDecl = nil + return false + } + if code.IsInTest(pass, node) { + return false + } + + switch node := node.(type) { + case *ast.GenDecl: + if node.Tok == token.IMPORT { + return false + } + genDecl = node + return true + case *ast.ValueSpec: + if genDecl.Lparen.IsValid() || len(node.Names) > 1 { + // Don't try to guess the user's intention + return false + } + name := node.Names[0].Name + if !ast.IsExported(name) { + return false + } + text, ok := docText(genDecl.Doc) + if !ok { + return false + } + prefix := name + " " + if !strings.HasPrefix(text, prefix) { + kind := "var" + if genDecl.Tok == token.CONST { + kind = "const" + } + report.Report(pass, genDecl.Doc, fmt.Sprintf(`comment on exported %s %s should be of the form "%s..."`, kind, name, prefix), report.FilterGenerated()) + } + return false + case *ast.FuncLit, *ast.FuncDecl: + return false + default: + lint.ExhaustiveTypeSwitch(node) + return false + } + } + + pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes([]ast.Node{(*ast.GenDecl)(nil), (*ast.ValueSpec)(nil), (*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)}, fn) + return nil, nil +} + +func docText(doc *ast.CommentGroup) (string, bool) { + if doc == nil { + return "", false + } + // We trim spaces primarily because of /**/ style comments, which often have leading space. + text := strings.TrimSpace(doc.Text()) + return text, text != "" +} diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/st1023/st1023.go b/tools/vendor/honnef.co/go/tools/stylecheck/st1023/st1023.go new file mode 100644 index 000000000..c1ab2c07f --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/stylecheck/st1023/st1023.go @@ -0,0 +1,22 @@ +package st1023 + +import ( + "honnef.co/go/tools/analysis/lint" + "honnef.co/go/tools/internal/sharedcheck" +) + +func init() { + SCAnalyzer.Analyzer.Name = "ST1023" +} + +var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ + Analyzer: sharedcheck.RedundantTypeInDeclarationChecker("should", false), + Doc: &lint.RawDocumentation{ + Title: "Redundant type in variable declaration", + Since: "2021.1", + NonDefault: true, + MergeIf: lint.MergeIfAll, + }, +}) + +var Analyzer = SCAnalyzer.Analyzer diff --git a/tools/vendor/honnef.co/go/tools/unused/implements.go b/tools/vendor/honnef.co/go/tools/unused/implements.go index 2a202c6d7..05f87bbbc 100644 --- a/tools/vendor/honnef.co/go/tools/unused/implements.go +++ b/tools/vendor/honnef.co/go/tools/unused/implements.go @@ -1,6 +1,8 @@ package unused -import "go/types" +import ( + "go/types" +) // lookupMethod returns the index of and method with matching package and name, or (-1, nil). func lookupMethod(T *types.Interface, pkg *types.Package, name string) (int, *types.Func) { @@ -60,6 +62,7 @@ func implements(V types.Type, T *types.Interface, msV *types.MethodSet) ([]*type // A concrete type implements T if it implements all methods of T. var sels []*types.Selection + var c methodsChecker for i := 0; i < T.NumMethods(); i++ { m := T.Method(i) sel := msV.Lookup(m.Pkg(), m.Name()) @@ -72,7 +75,7 @@ func implements(V types.Type, T *types.Interface, msV *types.MethodSet) ([]*type return nil, false } - if !types.Identical(f.Type(), m.Type()) { + if !c.methodIsCompatible(f, m) { return nil, false } @@ -80,3 +83,69 @@ func implements(V types.Type, T *types.Interface, msV *types.MethodSet) ([]*type } return sels, true } + +type methodsChecker struct { + typeParams map[*types.TypeParam]types.Type +} + +// Currently, this doesn't support methods like `foo(x []T)`. +func (c *methodsChecker) methodIsCompatible(implFunc *types.Func, interfaceFunc *types.Func) bool { + if types.Identical(implFunc.Type(), interfaceFunc.Type()) { + return true + } + implSig, implOk := implFunc.Type().(*types.Signature) + interfaceSig, interfaceOk := interfaceFunc.Type().(*types.Signature) + if !implOk || !interfaceOk { + // probably not reachable. handle conservatively. + return false + } + + if !c.typesAreCompatible(implSig.Params(), interfaceSig.Params()) { + return false + } + + if !c.typesAreCompatible(implSig.Results(), interfaceSig.Results()) { + return false + } + + return true +} + +func (c *methodsChecker) typesAreCompatible(implTypes, interfaceTypes *types.Tuple) bool { + if implTypes.Len() != interfaceTypes.Len() { + return false + } + for i := 0; i < implTypes.Len(); i++ { + if !c.typeIsCompatible(implTypes.At(i).Type(), interfaceTypes.At(i).Type()) { + return false + } + } + return true +} + +func (c *methodsChecker) typeIsCompatible(implType, interfaceType types.Type) bool { + if types.Identical(implType, interfaceType) { + return true + } + // We only support trivial use of type parameters. This isn't fully compatible with compiler type checking yet. + tp, ok := interfaceType.(*types.TypeParam) + if !ok { + return false + } + if c.typeParams == nil { + c.typeParams = make(map[*types.TypeParam]types.Type) + } + if c.typeParams[tp] == nil { + if !satisfiesConstraint(implType, tp) { + return false + } + c.typeParams[tp] = implType + return true + } + return types.Identical(c.typeParams[tp], implType) +} + +func satisfiesConstraint(t types.Type, tp *types.TypeParam) bool { + bound := tp.Constraint().Underlying().(*types.Interface) + return types.Satisfies(t, bound) +} diff --git a/tools/vendor/honnef.co/go/tools/unused/unused.go b/tools/vendor/honnef.co/go/tools/unused/unused.go index edd263075..46c147e1a 100644 --- a/tools/vendor/honnef.co/go/tools/unused/unused.go +++ b/tools/vendor/honnef.co/go/tools/unused/unused.go @@ -168,7 +168,7 @@ type Result struct { } var Analyzer = &lint.Analyzer{ - Doc: &lint.Documentation{ + Doc: &lint.RawDocumentation{ Title: "Unused code", }, Analyzer: &analysis.Analyzer{ @@ -344,7 +344,7 @@ func (g *graph) objectToObject(obj types.Object) Object { } name := obj.Name() if sig, ok := obj.Type().(*types.Signature); ok && sig.Recv() != nil { - switch sig.Recv().Type().(type) { + switch types.Unalias(sig.Recv().Type()).(type) { case *types.Named, *types.Pointer: typ := types.TypeString(sig.Recv().Type(), func(*types.Package) string { return "" }) if len(typ) > 0 && typ[0] == '*' { @@ -534,6 +534,19 @@ func (g *graph) entry() { } } + // We use a normal map instead of a typeutil.Map because we deduplicate + // these on a best effort basis, as an optimization. + allInterfaces := make(map[*types.Interface]struct{}) + for _, typ := range g.interfaceTypes { + allInterfaces[typ] = struct{}{} + } + for _, ins := range g.info.Instances { + if typ, ok := ins.Type.(*types.Named); ok && typ.Obj().Pkg() == g.pkg { + if iface, ok := typ.Underlying().(*types.Interface); ok { + allInterfaces[iface] = struct{}{} + } + } + } processMethodSet := func(named *types.TypeName, ms *types.MethodSet) { if g.opts.ExportedIsUsed { for i := 0; i < ms.Len(); i++ { @@ -552,7 +565,7 @@ func (g *graph) entry() { // (8.0) handle interfaces // // We don't care about interfaces implementing interfaces; all their methods are already used, anyway - for _, iface := range g.interfaceTypes { + for iface := range allInterfaces { if sels, ok := implements(named.Type(), iface, ms); ok { for _, sel := range sels { // (8.2) any concrete type implements all known interfaces @@ -628,7 +641,7 @@ func (g *graph) entry() { // use methods and fields of ignored types if obj, ok := obj.(*types.TypeName); ok { if obj.IsAlias() { - if typ, ok := obj.Type().(*types.Named); ok && (g.opts.ExportedIsUsed && typ.Obj().Pkg() != obj.Pkg() || typ.Obj().Pkg() == nil) { + if typ, ok := types.Unalias(obj.Type()).(*types.Named); ok && (g.opts.ExportedIsUsed && typ.Obj().Pkg() != obj.Pkg() || typ.Obj().Pkg() == nil) { // This is an alias of a named type in another package. // Don't walk its fields or methods; we don't have to. // @@ -637,7 +650,7 @@ func (g *graph) entry() { continue } } - if typ, ok := obj.Type().(*types.Named); ok { + if typ, ok := types.Unalias(obj.Type()).(*types.Named); ok { for i := 0; i < typ.NumMethods(); i++ { g.use(typ.Method(i), nil) } @@ -960,7 +973,7 @@ func (g *graph) write(node ast.Node, by types.Object) { case *ast.SelectorExpr: if g.opts.FieldWritesAreUses { - // Writing to a field constitutes a use. See https://staticcheck.io/issues/288 for some discussion on that. + // Writing to a field constitutes a use. See https://staticcheck.dev/issues/288 for some discussion on that. // // This code can also get triggered by qualified package variables, in which case it doesn't matter what we do, // because the object is in another package. @@ -1457,7 +1470,7 @@ func isNoCopyType(typ types.Type) bool { return false } - named, ok := typ.(*types.Named) + named, ok := types.Unalias(typ).(*types.Named) if !ok { return false } diff --git a/tools/vendor/modules.txt b/tools/vendor/modules.txt index 63b57129f..086febcf2 100644 --- a/tools/vendor/modules.txt +++ b/tools/vendor/modules.txt @@ -4,49 +4,54 @@ # 4d63.com/gochecknoglobals v0.2.1 ## explicit; go 1.15 4d63.com/gochecknoglobals/checknoglobals -# github.com/4meepo/tagalign v1.3.3 +# github.com/4meepo/tagalign v1.3.4 ## explicit; go 1.19 github.com/4meepo/tagalign -# github.com/Abirdcfly/dupword v0.0.13 +# github.com/Abirdcfly/dupword v0.0.14 ## explicit; go 1.20 github.com/Abirdcfly/dupword -# github.com/Antonboom/errname v0.1.12 +# github.com/Antonboom/errname v0.1.13 ## explicit; go 1.20 github.com/Antonboom/errname/pkg/analyzer -# github.com/Antonboom/nilnil v0.1.7 +# github.com/Antonboom/nilnil v0.1.9 ## explicit; go 1.20 github.com/Antonboom/nilnil/pkg/analyzer -# github.com/Antonboom/testifylint v0.2.3 +# github.com/Antonboom/testifylint v1.4.3 ## explicit; go 1.20 github.com/Antonboom/testifylint/analyzer github.com/Antonboom/testifylint/internal/analysisutil github.com/Antonboom/testifylint/internal/checkers +github.com/Antonboom/testifylint/internal/checkers/printf github.com/Antonboom/testifylint/internal/config github.com/Antonboom/testifylint/internal/testify -# github.com/BurntSushi/toml v1.3.2 -## explicit; go 1.16 +# github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c +## explicit; go 1.18 github.com/BurntSushi/toml github.com/BurntSushi/toml/internal +# github.com/Crocmagnon/fatcontext v0.4.0 +## explicit; go 1.21 +github.com/Crocmagnon/fatcontext/pkg/analyzer # github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 ## explicit; go 1.13 github.com/Djarvur/go-err113 -# github.com/GaijinEntertainment/go-exhaustruct/v3 v3.1.0 -## explicit; go 1.20 +# github.com/GaijinEntertainment/go-exhaustruct/v3 v3.3.0 +## explicit; go 1.21 github.com/GaijinEntertainment/go-exhaustruct/v3/analyzer -github.com/GaijinEntertainment/go-exhaustruct/v3/internal/fields +github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment github.com/GaijinEntertainment/go-exhaustruct/v3/internal/pattern -# github.com/Masterminds/semver v1.5.0 -## explicit -github.com/Masterminds/semver -# github.com/OpenPeeDeeP/depguard/v2 v2.1.0 +github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure +# github.com/Masterminds/semver/v3 v3.2.1 +## explicit; go 1.18 +github.com/Masterminds/semver/v3 +# github.com/OpenPeeDeeP/depguard/v2 v2.2.0 ## explicit; go 1.20 github.com/OpenPeeDeeP/depguard/v2 github.com/OpenPeeDeeP/depguard/v2/internal/utils -# github.com/alecthomas/go-check-sumtype v0.1.3 +# github.com/alecthomas/go-check-sumtype v0.1.4 ## explicit; go 1.18 github.com/alecthomas/go-check-sumtype -# github.com/alexkohler/nakedret/v2 v2.0.2 -## explicit; go 1.18 +# github.com/alexkohler/nakedret/v2 v2.0.4 +## explicit; go 1.21 github.com/alexkohler/nakedret/v2 # github.com/alexkohler/prealloc v1.0.0 ## explicit; go 1.15 @@ -69,28 +74,28 @@ github.com/bkielbasa/cyclop/pkg/analyzer # github.com/blizzy78/varnamelen v0.8.0 ## explicit; go 1.16 github.com/blizzy78/varnamelen -# github.com/bombsimon/wsl/v3 v3.4.0 -## explicit; go 1.19 -github.com/bombsimon/wsl/v3 +# github.com/bombsimon/wsl/v4 v4.4.1 +## explicit; go 1.21 +github.com/bombsimon/wsl/v4 # github.com/breml/bidichk v0.2.7 ## explicit; go 1.20 github.com/breml/bidichk/pkg/bidichk # github.com/breml/errchkjson v0.3.6 ## explicit; go 1.20 github.com/breml/errchkjson -# github.com/butuzov/ireturn v0.2.2 +# github.com/butuzov/ireturn v0.3.0 ## explicit; go 1.18 github.com/butuzov/ireturn/analyzer github.com/butuzov/ireturn/analyzer/internal/config github.com/butuzov/ireturn/analyzer/internal/types -# github.com/butuzov/mirror v1.1.0 +# github.com/butuzov/mirror v1.2.0 ## explicit; go 1.19 github.com/butuzov/mirror github.com/butuzov/mirror/internal/checker -# github.com/catenacyber/perfsprint v0.2.0 +# github.com/catenacyber/perfsprint v0.7.1 ## explicit; go 1.20 github.com/catenacyber/perfsprint/analyzer -# github.com/ccojocar/zxcvbn-go v1.0.1 +# github.com/ccojocar/zxcvbn-go v1.0.2 ## explicit; go 1.20 github.com/ccojocar/zxcvbn-go github.com/ccojocar/zxcvbn-go/adjacency @@ -110,12 +115,15 @@ github.com/charithe/durationcheck # github.com/chavacava/garif v0.1.0 ## explicit; go 1.16 github.com/chavacava/garif +# github.com/ckaznocha/intrange v0.1.2 +## explicit; go 1.21 +github.com/ckaznocha/intrange # github.com/curioswitch/go-reassign v0.2.0 ## explicit; go 1.18 github.com/curioswitch/go-reassign github.com/curioswitch/go-reassign/internal/analyzer -# github.com/daixiang0/gci v0.11.2 -## explicit; go 1.18 +# github.com/daixiang0/gci v0.13.4 +## explicit; go 1.21 github.com/daixiang0/gci/pkg/config github.com/daixiang0/gci/pkg/format github.com/daixiang0/gci/pkg/gci @@ -128,22 +136,19 @@ github.com/daixiang0/gci/pkg/utils # github.com/davecgh/go-spew v1.1.1 ## explicit github.com/davecgh/go-spew/spew -# github.com/denis-tingaikin/go-header v0.4.3 -## explicit; go 1.17 +# github.com/denis-tingaikin/go-header v0.5.0 +## explicit; go 1.21 github.com/denis-tingaikin/go-header -# github.com/esimonov/ifshort v1.0.4 -## explicit; go 1.17 -github.com/esimonov/ifshort/pkg/analyzer -# github.com/ettle/strcase v0.1.1 +# github.com/ettle/strcase v0.2.0 ## explicit; go 1.12 github.com/ettle/strcase -# github.com/fatih/color v1.15.0 +# github.com/fatih/color v1.17.0 ## explicit; go 1.17 github.com/fatih/color # github.com/fatih/structtag v1.2.0 ## explicit; go 1.12 github.com/fatih/structtag -# github.com/firefart/nonamedreturns v1.0.4 +# github.com/firefart/nonamedreturns v1.0.5 ## explicit; go 1.18 github.com/firefart/nonamedreturns/analyzer # github.com/fsnotify/fsnotify v1.5.4 @@ -152,10 +157,10 @@ github.com/fsnotify/fsnotify # github.com/fzipp/gocyclo v0.6.0 ## explicit; go 1.18 github.com/fzipp/gocyclo -# github.com/ghostiam/protogetter v0.2.3 +# github.com/ghostiam/protogetter v0.3.6 ## explicit; go 1.19 github.com/ghostiam/protogetter -# github.com/go-critic/go-critic v0.9.0 +# github.com/go-critic/go-critic v0.11.4 ## explicit; go 1.18 github.com/go-critic/go-critic/checkers github.com/go-critic/go-critic/checkers/internal/astwalk @@ -168,8 +173,8 @@ github.com/go-toolsmith/astcast # github.com/go-toolsmith/astcopy v1.1.0 ## explicit; go 1.16 github.com/go-toolsmith/astcopy -# github.com/go-toolsmith/astequal v1.1.0 -## explicit; go 1.16 +# github.com/go-toolsmith/astequal v1.2.0 +## explicit; go 1.18 github.com/go-toolsmith/astequal # github.com/go-toolsmith/astfmt v1.1.0 ## explicit; go 1.16 @@ -183,6 +188,10 @@ github.com/go-toolsmith/strparse # github.com/go-toolsmith/typep v1.1.0 ## explicit; go 1.16 github.com/go-toolsmith/typep +# github.com/go-viper/mapstructure/v2 v2.0.0 +## explicit; go 1.18 +github.com/go-viper/mapstructure/v2 +github.com/go-viper/mapstructure/v2/internal/errors # github.com/go-xmlfmt/xmlfmt v1.1.2 ## explicit github.com/go-xmlfmt/xmlfmt @@ -196,20 +205,16 @@ github.com/gobwas/glob/syntax/ast github.com/gobwas/glob/syntax/lexer github.com/gobwas/glob/util/runes github.com/gobwas/glob/util/strings -# github.com/gofrs/flock v0.8.1 -## explicit +# github.com/gofrs/flock v0.12.1 +## explicit; go 1.21.0 github.com/gofrs/flock -# github.com/golang/protobuf v1.5.2 +# github.com/golang/protobuf v1.5.3 ## explicit; go 1.9 github.com/golang/protobuf/proto github.com/golang/protobuf/ptypes github.com/golang/protobuf/ptypes/any github.com/golang/protobuf/ptypes/duration github.com/golang/protobuf/ptypes/timestamp -# github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 -## explicit -github.com/golangci/check/cmd/structcheck -github.com/golangci/check/cmd/varcheck # github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a ## explicit github.com/golangci/dupl @@ -218,16 +223,13 @@ github.com/golangci/dupl/printer github.com/golangci/dupl/suffixtree github.com/golangci/dupl/syntax github.com/golangci/dupl/syntax/golang -# github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe -## explicit; go 1.17 -github.com/golangci/go-misc/deadcode # github.com/golangci/gofmt v0.0.0-20231018234816-f50ced29576e ## explicit; go 1.20 github.com/golangci/gofmt/gofmt github.com/golangci/gofmt/gofmt/internal/diff github.com/golangci/gofmt/goimports -# github.com/golangci/golangci-lint v1.55.2 -## explicit; go 1.20 +# github.com/golangci/golangci-lint v1.60.1 +## explicit; go 1.22.1 github.com/golangci/golangci-lint/cmd/golangci-lint github.com/golangci/golangci-lint/internal/cache github.com/golangci/golangci-lint/internal/errorutil @@ -235,38 +237,147 @@ github.com/golangci/golangci-lint/internal/pkgcache github.com/golangci/golangci-lint/internal/renameio github.com/golangci/golangci-lint/internal/robustio github.com/golangci/golangci-lint/pkg/commands +github.com/golangci/golangci-lint/pkg/commands/internal github.com/golangci/golangci-lint/pkg/config github.com/golangci/golangci-lint/pkg/exitcodes github.com/golangci/golangci-lint/pkg/fsutils +github.com/golangci/golangci-lint/pkg/goanalysis +github.com/golangci/golangci-lint/pkg/goanalysis/load +github.com/golangci/golangci-lint/pkg/goanalysis/pkgerrors github.com/golangci/golangci-lint/pkg/golinters -github.com/golangci/golangci-lint/pkg/golinters/goanalysis -github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load +github.com/golangci/golangci-lint/pkg/golinters/asasalint +github.com/golangci/golangci-lint/pkg/golinters/asciicheck +github.com/golangci/golangci-lint/pkg/golinters/bidichk +github.com/golangci/golangci-lint/pkg/golinters/bodyclose +github.com/golangci/golangci-lint/pkg/golinters/canonicalheader +github.com/golangci/golangci-lint/pkg/golinters/containedctx +github.com/golangci/golangci-lint/pkg/golinters/contextcheck +github.com/golangci/golangci-lint/pkg/golinters/copyloopvar +github.com/golangci/golangci-lint/pkg/golinters/cyclop +github.com/golangci/golangci-lint/pkg/golinters/decorder +github.com/golangci/golangci-lint/pkg/golinters/depguard +github.com/golangci/golangci-lint/pkg/golinters/dogsled +github.com/golangci/golangci-lint/pkg/golinters/dupl +github.com/golangci/golangci-lint/pkg/golinters/dupword +github.com/golangci/golangci-lint/pkg/golinters/durationcheck +github.com/golangci/golangci-lint/pkg/golinters/err113 +github.com/golangci/golangci-lint/pkg/golinters/errcheck +github.com/golangci/golangci-lint/pkg/golinters/errchkjson +github.com/golangci/golangci-lint/pkg/golinters/errname +github.com/golangci/golangci-lint/pkg/golinters/errorlint +github.com/golangci/golangci-lint/pkg/golinters/execinquery +github.com/golangci/golangci-lint/pkg/golinters/exhaustive +github.com/golangci/golangci-lint/pkg/golinters/exhaustruct +github.com/golangci/golangci-lint/pkg/golinters/exportloopref +github.com/golangci/golangci-lint/pkg/golinters/fatcontext +github.com/golangci/golangci-lint/pkg/golinters/forbidigo +github.com/golangci/golangci-lint/pkg/golinters/forcetypeassert +github.com/golangci/golangci-lint/pkg/golinters/funlen +github.com/golangci/golangci-lint/pkg/golinters/gci +github.com/golangci/golangci-lint/pkg/golinters/ginkgolinter +github.com/golangci/golangci-lint/pkg/golinters/gocheckcompilerdirectives +github.com/golangci/golangci-lint/pkg/golinters/gochecknoglobals +github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits +github.com/golangci/golangci-lint/pkg/golinters/gochecksumtype +github.com/golangci/golangci-lint/pkg/golinters/gocognit +github.com/golangci/golangci-lint/pkg/golinters/goconst +github.com/golangci/golangci-lint/pkg/golinters/gocritic +github.com/golangci/golangci-lint/pkg/golinters/gocyclo +github.com/golangci/golangci-lint/pkg/golinters/godot +github.com/golangci/golangci-lint/pkg/golinters/godox +github.com/golangci/golangci-lint/pkg/golinters/gofmt +github.com/golangci/golangci-lint/pkg/golinters/gofumpt +github.com/golangci/golangci-lint/pkg/golinters/goheader +github.com/golangci/golangci-lint/pkg/golinters/goimports +github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives +github.com/golangci/golangci-lint/pkg/golinters/gomodguard +github.com/golangci/golangci-lint/pkg/golinters/goprintffuncname +github.com/golangci/golangci-lint/pkg/golinters/gosec +github.com/golangci/golangci-lint/pkg/golinters/gosimple +github.com/golangci/golangci-lint/pkg/golinters/gosmopolitan +github.com/golangci/golangci-lint/pkg/golinters/govet +github.com/golangci/golangci-lint/pkg/golinters/grouper +github.com/golangci/golangci-lint/pkg/golinters/importas +github.com/golangci/golangci-lint/pkg/golinters/inamedparam +github.com/golangci/golangci-lint/pkg/golinters/ineffassign +github.com/golangci/golangci-lint/pkg/golinters/interfacebloat +github.com/golangci/golangci-lint/pkg/golinters/internal +github.com/golangci/golangci-lint/pkg/golinters/intrange +github.com/golangci/golangci-lint/pkg/golinters/ireturn +github.com/golangci/golangci-lint/pkg/golinters/lll +github.com/golangci/golangci-lint/pkg/golinters/loggercheck +github.com/golangci/golangci-lint/pkg/golinters/maintidx +github.com/golangci/golangci-lint/pkg/golinters/makezero +github.com/golangci/golangci-lint/pkg/golinters/mirror +github.com/golangci/golangci-lint/pkg/golinters/misspell +github.com/golangci/golangci-lint/pkg/golinters/mnd +github.com/golangci/golangci-lint/pkg/golinters/musttag +github.com/golangci/golangci-lint/pkg/golinters/nakedret +github.com/golangci/golangci-lint/pkg/golinters/nestif +github.com/golangci/golangci-lint/pkg/golinters/nilerr +github.com/golangci/golangci-lint/pkg/golinters/nilnil +github.com/golangci/golangci-lint/pkg/golinters/nlreturn +github.com/golangci/golangci-lint/pkg/golinters/noctx github.com/golangci/golangci-lint/pkg/golinters/nolintlint +github.com/golangci/golangci-lint/pkg/golinters/nolintlint/internal +github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns +github.com/golangci/golangci-lint/pkg/golinters/nosprintfhostport +github.com/golangci/golangci-lint/pkg/golinters/paralleltest +github.com/golangci/golangci-lint/pkg/golinters/perfsprint +github.com/golangci/golangci-lint/pkg/golinters/prealloc +github.com/golangci/golangci-lint/pkg/golinters/predeclared +github.com/golangci/golangci-lint/pkg/golinters/promlinter +github.com/golangci/golangci-lint/pkg/golinters/protogetter +github.com/golangci/golangci-lint/pkg/golinters/reassign +github.com/golangci/golangci-lint/pkg/golinters/revive +github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck +github.com/golangci/golangci-lint/pkg/golinters/sloglint +github.com/golangci/golangci-lint/pkg/golinters/spancheck +github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck +github.com/golangci/golangci-lint/pkg/golinters/staticcheck +github.com/golangci/golangci-lint/pkg/golinters/stylecheck +github.com/golangci/golangci-lint/pkg/golinters/tagalign +github.com/golangci/golangci-lint/pkg/golinters/tagliatelle +github.com/golangci/golangci-lint/pkg/golinters/tenv +github.com/golangci/golangci-lint/pkg/golinters/testableexamples +github.com/golangci/golangci-lint/pkg/golinters/testifylint +github.com/golangci/golangci-lint/pkg/golinters/testpackage +github.com/golangci/golangci-lint/pkg/golinters/thelper +github.com/golangci/golangci-lint/pkg/golinters/tparallel +github.com/golangci/golangci-lint/pkg/golinters/unconvert +github.com/golangci/golangci-lint/pkg/golinters/unparam +github.com/golangci/golangci-lint/pkg/golinters/unused +github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars +github.com/golangci/golangci-lint/pkg/golinters/varnamelen +github.com/golangci/golangci-lint/pkg/golinters/wastedassign +github.com/golangci/golangci-lint/pkg/golinters/whitespace +github.com/golangci/golangci-lint/pkg/golinters/wrapcheck +github.com/golangci/golangci-lint/pkg/golinters/wsl +github.com/golangci/golangci-lint/pkg/golinters/zerologlint github.com/golangci/golangci-lint/pkg/goutil github.com/golangci/golangci-lint/pkg/lint github.com/golangci/golangci-lint/pkg/lint/linter github.com/golangci/golangci-lint/pkg/lint/lintersdb github.com/golangci/golangci-lint/pkg/logutils -github.com/golangci/golangci-lint/pkg/packages github.com/golangci/golangci-lint/pkg/printers github.com/golangci/golangci-lint/pkg/report github.com/golangci/golangci-lint/pkg/result github.com/golangci/golangci-lint/pkg/result/processors github.com/golangci/golangci-lint/pkg/timeutils -# github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 -## explicit -github.com/golangci/lint-1 -# github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca -## explicit -github.com/golangci/maligned -# github.com/golangci/misspell v0.4.1 -## explicit; go 1.19 +# github.com/golangci/misspell v0.6.0 +## explicit; go 1.21 github.com/golangci/misspell -# github.com/golangci/revgrep v0.5.2 -## explicit; go 1.19 +# github.com/golangci/modinfo v0.3.4 +## explicit; go 1.21 +github.com/golangci/modinfo +# github.com/golangci/plugin-module-register v0.1.1 +## explicit; go 1.21 +github.com/golangci/plugin-module-register/register +# github.com/golangci/revgrep v0.5.3 +## explicit; go 1.21 github.com/golangci/revgrep -# github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 -## explicit +# github.com/golangci/unconvert v0.0.0-20240309020433-c5143eacb3ed +## explicit; go 1.20 github.com/golangci/unconvert # github.com/google/go-cmp v0.6.0 ## explicit; go 1.13 @@ -275,7 +386,7 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/gordonklaus/ineffassign v0.0.0-20230610083614-0e73809eb601 +# github.com/gordonklaus/ineffassign v0.1.0 ## explicit; go 1.14 github.com/gordonklaus/ineffassign/pkg/ineffassign # github.com/gostaticanalysis/analysisutil v0.7.1 @@ -291,13 +402,7 @@ github.com/gostaticanalysis/forcetypeassert # github.com/gostaticanalysis/nilerr v0.1.1 ## explicit; go 1.15 github.com/gostaticanalysis/nilerr -# github.com/hashicorp/errwrap v1.0.0 -## explicit -github.com/hashicorp/errwrap -# github.com/hashicorp/go-multierror v1.1.1 -## explicit; go 1.13 -github.com/hashicorp/go-multierror -# github.com/hashicorp/go-version v1.6.0 +# github.com/hashicorp/go-version v1.7.0 ## explicit github.com/hashicorp/go-version # github.com/hashicorp/hcl v1.0.0 @@ -320,7 +425,7 @@ github.com/hexops/gotextdiff/span # github.com/inconshreveable/mousetrap v1.1.0 ## explicit; go 1.18 github.com/inconshreveable/mousetrap -# github.com/jgautheron/goconst v1.6.0 +# github.com/jgautheron/goconst v1.7.1 ## explicit; go 1.13 github.com/jgautheron/goconst # github.com/jingyugao/rowserrcheck v1.1.1 @@ -329,36 +434,41 @@ github.com/jingyugao/rowserrcheck/passes/rowserr # github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af ## explicit; go 1.13 github.com/jirfag/go-printf-func-name/pkg/analyzer +# github.com/jjti/go-spancheck v0.6.2 +## explicit; go 1.20 +github.com/jjti/go-spancheck # github.com/julz/importas v0.1.0 ## explicit; go 1.15 github.com/julz/importas -# github.com/kisielk/errcheck v1.6.3 -## explicit; go 1.14 +# github.com/karamaru-alpha/copyloopvar v1.1.0 +## explicit; go 1.21 +github.com/karamaru-alpha/copyloopvar +# github.com/kisielk/errcheck v1.7.0 +## explicit; go 1.18 github.com/kisielk/errcheck/errcheck -# github.com/kisielk/gotool v1.0.0 -## explicit -github.com/kisielk/gotool -github.com/kisielk/gotool/internal/load -# github.com/kkHAIKE/contextcheck v1.1.4 +# github.com/kkHAIKE/contextcheck v1.1.5 ## explicit; go 1.20 github.com/kkHAIKE/contextcheck # github.com/kulti/thelper v0.6.3 ## explicit; go 1.18 github.com/kulti/thelper/pkg/analyzer -# github.com/kunwardeep/paralleltest v1.0.8 +# github.com/kunwardeep/paralleltest v1.0.10 ## explicit; go 1.17 github.com/kunwardeep/paralleltest/pkg/paralleltest # github.com/kyoh86/exportloopref v0.1.11 ## explicit; go 1.18 github.com/kyoh86/exportloopref -# github.com/ldez/gomoddirectives v0.2.3 -## explicit; go 1.16 +# github.com/lasiar/canonicalheader v1.1.1 +## explicit; go 1.21 +github.com/lasiar/canonicalheader +# github.com/ldez/gomoddirectives v0.2.4 +## explicit; go 1.21 github.com/ldez/gomoddirectives # github.com/ldez/tagliatelle v0.5.0 ## explicit; go 1.19 github.com/ldez/tagliatelle -# github.com/leonklingele/grouper v1.1.1 -## explicit; go 1.17 +# github.com/leonklingele/grouper v1.1.2 +## explicit; go 1.18 github.com/leonklingele/grouper/pkg/analyzer github.com/leonklingele/grouper/pkg/analyzer/consts github.com/leonklingele/grouper/pkg/analyzer/globals @@ -368,8 +478,8 @@ github.com/leonklingele/grouper/pkg/analyzer/vars # github.com/lufeee/execinquery v1.2.1 ## explicit; go 1.17 github.com/lufeee/execinquery -# github.com/macabu/inamedparam v0.1.2 -## explicit; go 1.19 +# github.com/macabu/inamedparam v0.1.3 +## explicit; go 1.20 github.com/macabu/inamedparam # github.com/magiconair/properties v1.8.6 ## explicit; go 1.13 @@ -386,7 +496,7 @@ github.com/matoous/godox # github.com/mattn/go-colorable v0.1.13 ## explicit; go 1.15 github.com/mattn/go-colorable -# github.com/mattn/go-isatty v0.0.17 +# github.com/mattn/go-isatty v0.0.20 ## explicit; go 1.15 github.com/mattn/go-isatty # github.com/mattn/go-runewidth v0.0.9 @@ -395,11 +505,8 @@ github.com/mattn/go-runewidth # github.com/matttproud/golang_protobuf_extensions v1.0.1 ## explicit github.com/matttproud/golang_protobuf_extensions/pbutil -# github.com/mbilski/exhaustivestruct v1.2.0 -## explicit; go 1.15 -github.com/mbilski/exhaustivestruct/pkg/analyzer -# github.com/mgechev/revive v1.3.4 -## explicit; go 1.20 +# github.com/mgechev/revive v1.3.9 +## explicit; go 1.21 github.com/mgechev/revive/config github.com/mgechev/revive/formatter github.com/mgechev/revive/internal/ifelse @@ -412,7 +519,7 @@ github.com/mitchellh/go-homedir # github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 github.com/mitchellh/mapstructure -# github.com/moricho/tparallel v0.3.1 +# github.com/moricho/tparallel v0.3.2 ## explicit; go 1.20 github.com/moricho/tparallel github.com/moricho/tparallel/pkg/ssafunc @@ -420,18 +527,22 @@ github.com/moricho/tparallel/pkg/ssainstr # github.com/nakabonne/nestif v0.3.1 ## explicit; go 1.15 github.com/nakabonne/nestif -# github.com/nishanths/exhaustive v0.11.0 +# github.com/nishanths/exhaustive v0.12.0 ## explicit; go 1.18 github.com/nishanths/exhaustive # github.com/nishanths/predeclared v0.2.2 ## explicit; go 1.14 github.com/nishanths/predeclared/passes/predeclared -# github.com/nunnatsa/ginkgolinter v0.14.1 -## explicit; go 1.20 +# github.com/nunnatsa/ginkgolinter v0.16.2 +## explicit; go 1.21 github.com/nunnatsa/ginkgolinter -github.com/nunnatsa/ginkgolinter/ginkgohandler -github.com/nunnatsa/ginkgolinter/gomegahandler -github.com/nunnatsa/ginkgolinter/reverseassertion +github.com/nunnatsa/ginkgolinter/internal/ginkgohandler +github.com/nunnatsa/ginkgolinter/internal/gomegahandler +github.com/nunnatsa/ginkgolinter/internal/interfaces +github.com/nunnatsa/ginkgolinter/internal/intervals +github.com/nunnatsa/ginkgolinter/internal/reports +github.com/nunnatsa/ginkgolinter/internal/reverseassertion +github.com/nunnatsa/ginkgolinter/linter github.com/nunnatsa/ginkgolinter/types github.com/nunnatsa/ginkgolinter/version # github.com/olekukonko/tablewriter v0.0.5 @@ -440,16 +551,17 @@ github.com/olekukonko/tablewriter # github.com/pelletier/go-toml v1.9.5 ## explicit; go 1.12 github.com/pelletier/go-toml -# github.com/pelletier/go-toml/v2 v2.0.5 +# github.com/pelletier/go-toml/v2 v2.2.2 ## explicit; go 1.16 github.com/pelletier/go-toml/v2 -github.com/pelletier/go-toml/v2/internal/ast +github.com/pelletier/go-toml/v2/internal/characters github.com/pelletier/go-toml/v2/internal/danger github.com/pelletier/go-toml/v2/internal/tracker +github.com/pelletier/go-toml/v2/unstable # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib -# github.com/polyfloyd/go-errorlint v1.4.5 +# github.com/polyfloyd/go-errorlint v1.6.0 ## explicit; go 1.20 github.com/polyfloyd/go-errorlint/errorlint # github.com/prometheus/client_golang v1.12.1 @@ -470,7 +582,7 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/quasilyte/go-ruleguard v0.4.0 +# github.com/quasilyte/go-ruleguard v0.4.2 ## explicit; go 1.19 github.com/quasilyte/go-ruleguard/internal/goenv github.com/quasilyte/go-ruleguard/internal/golist @@ -487,6 +599,10 @@ github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrconv github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrings github.com/quasilyte/go-ruleguard/ruleguard/textmatch github.com/quasilyte/go-ruleguard/ruleguard/typematch +# github.com/quasilyte/go-ruleguard/dsl v0.3.22 +## explicit; go 1.15 +github.com/quasilyte/go-ruleguard/dsl +github.com/quasilyte/go-ruleguard/dsl/types # github.com/quasilyte/gogrep v0.5.0 ## explicit; go 1.16 github.com/quasilyte/gogrep @@ -501,8 +617,8 @@ github.com/quasilyte/stdinfo # github.com/randall77/makefat v0.0.0-20210315173500-7ddd0e42c844 ## explicit; go 1.13 github.com/randall77/makefat -# github.com/ryancurrah/gomodguard v1.3.0 -## explicit; go 1.19 +# github.com/ryancurrah/gomodguard v1.3.3 +## explicit; go 1.21 github.com/ryancurrah/gomodguard # github.com/ryanrolds/sqlclosecheck v0.5.1 ## explicit; go 1.20 @@ -510,14 +626,18 @@ github.com/ryanrolds/sqlclosecheck/pkg/analyzer # github.com/sanposhiho/wastedassign/v2 v2.0.7 ## explicit; go 1.14 github.com/sanposhiho/wastedassign/v2 +# github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 +## explicit; go 1.19 +github.com/santhosh-tekuri/jsonschema/v5 +github.com/santhosh-tekuri/jsonschema/v5/httploader # github.com/sashamelentyev/interfacebloat v1.1.0 ## explicit; go 1.18 github.com/sashamelentyev/interfacebloat/pkg/analyzer -# github.com/sashamelentyev/usestdlibvars v1.24.0 +# github.com/sashamelentyev/usestdlibvars v1.27.0 ## explicit; go 1.20 github.com/sashamelentyev/usestdlibvars/pkg/analyzer github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping -# github.com/securego/gosec/v2 v2.18.2 +# github.com/securego/gosec/v2 v2.20.1-0.20240525090044-5f0084eb01a9 ## explicit; go 1.20 github.com/securego/gosec/v2 github.com/securego/gosec/v2/analyzers @@ -533,11 +653,8 @@ github.com/sirupsen/logrus # github.com/sivchari/containedctx v1.0.3 ## explicit; go 1.17 github.com/sivchari/containedctx -# github.com/sivchari/nosnakecase v1.7.0 -## explicit; go 1.18 -github.com/sivchari/nosnakecase -# github.com/sivchari/tenv v1.7.1 -## explicit; go 1.18 +# github.com/sivchari/tenv v1.10.0 +## explicit; go 1.21.0 github.com/sivchari/tenv # github.com/sonatard/noctx v0.0.2 ## explicit; go 1.20 @@ -547,14 +664,15 @@ github.com/sonatard/noctx/reqwithoutctx # github.com/sourcegraph/go-diff v0.7.0 ## explicit; go 1.14 github.com/sourcegraph/go-diff/diff -# github.com/spf13/afero v1.8.2 -## explicit; go 1.13 +# github.com/spf13/afero v1.11.0 +## explicit; go 1.19 github.com/spf13/afero +github.com/spf13/afero/internal/common github.com/spf13/afero/mem # github.com/spf13/cast v1.5.0 ## explicit; go 1.18 github.com/spf13/cast -# github.com/spf13/cobra v1.7.0 +# github.com/spf13/cobra v1.8.1 ## explicit; go 1.15 github.com/spf13/cobra # github.com/spf13/jwalterweatherman v1.1.0 @@ -580,23 +698,20 @@ github.com/ssgreg/nlreturn/v2/pkg/nlreturn # github.com/stbenjam/no-sprintf-host-port v0.1.1 ## explicit; go 1.16 github.com/stbenjam/no-sprintf-host-port/pkg/analyzer -# github.com/stretchr/objx v0.5.0 -## explicit; go 1.12 -github.com/stretchr/objx -# github.com/stretchr/testify v1.8.4 +# github.com/stretchr/objx v0.5.2 ## explicit; go 1.20 +github.com/stretchr/objx +# github.com/stretchr/testify v1.9.0 +## explicit; go 1.17 github.com/stretchr/testify/assert github.com/stretchr/testify/mock # github.com/subosito/gotenv v1.4.1 ## explicit; go 1.18 github.com/subosito/gotenv -# github.com/t-yuki/gocover-cobertura v0.0.0-20180217150009-aaee18c8195c -## explicit -github.com/t-yuki/gocover-cobertura # github.com/tdakkota/asciicheck v0.2.0 ## explicit; go 1.18 github.com/tdakkota/asciicheck -# github.com/tetafro/godot v1.4.15 +# github.com/tetafro/godot v1.4.16 ## explicit; go 1.20 github.com/tetafro/godot # github.com/timakin/bodyclose v0.0.0-20230421092635-574207250966 @@ -611,8 +726,8 @@ github.com/timonwong/loggercheck/internal/checkers/printf github.com/timonwong/loggercheck/internal/rules github.com/timonwong/loggercheck/internal/sets github.com/timonwong/loggercheck/internal/stringutil -# github.com/tomarrell/wrapcheck/v2 v2.8.1 -## explicit; go 1.18 +# github.com/tomarrell/wrapcheck/v2 v2.8.3 +## explicit; go 1.21 github.com/tomarrell/wrapcheck/v2/wrapcheck # github.com/tommy-muehle/go-mnd/v2 v2.5.1 ## explicit; go 1.12 @@ -622,11 +737,11 @@ github.com/tommy-muehle/go-mnd/v2/config # github.com/ultraware/funlen v0.1.0 ## explicit; go 1.20 github.com/ultraware/funlen -# github.com/ultraware/whitespace v0.0.5 -## explicit +# github.com/ultraware/whitespace v0.1.1 +## explicit; go 1.20 github.com/ultraware/whitespace -# github.com/uudashr/gocognit v1.1.2 -## explicit; go 1.16 +# github.com/uudashr/gocognit v1.1.3 +## explicit; go 1.18 github.com/uudashr/gocognit # github.com/xen0n/gosmopolitan v1.2.2 ## explicit; go 1.19 @@ -636,24 +751,29 @@ github.com/xen0n/gosmopolitan github.com/yagipy/maintidx github.com/yagipy/maintidx/pkg/cyc github.com/yagipy/maintidx/pkg/halstvol -# github.com/yeya24/promlinter v0.2.0 -## explicit; go 1.16 +# github.com/yeya24/promlinter v0.3.0 +## explicit; go 1.20 github.com/yeya24/promlinter -# github.com/ykadowak/zerologlint v0.1.3 +# github.com/ykadowak/zerologlint v0.1.5 ## explicit; go 1.19 github.com/ykadowak/zerologlint -# gitlab.com/bosi/decorder v0.4.1 +# gitlab.com/bosi/decorder v0.4.2 ## explicit; go 1.20 gitlab.com/bosi/decorder -# go-simpler.org/sloglint v0.1.2 +# go-simpler.org/musttag v0.12.2 ## explicit; go 1.20 +go-simpler.org/musttag +# go-simpler.org/sloglint v0.7.2 +## explicit; go 1.21 go-simpler.org/sloglint -# go.tmz.dev/musttag v0.7.2 -## explicit; go 1.19 -go.tmz.dev/musttag # go.uber.org/atomic v1.7.0 ## explicit; go 1.13 go.uber.org/atomic +# go.uber.org/automaxprocs v1.5.3 +## explicit; go 1.18 +go.uber.org/automaxprocs/internal/cgroups +go.uber.org/automaxprocs/internal/runtime +go.uber.org/automaxprocs/maxprocs # go.uber.org/multierr v1.6.0 ## explicit; go 1.12 go.uber.org/multierr @@ -666,36 +786,36 @@ go.uber.org/zap/internal/bufferpool go.uber.org/zap/internal/color go.uber.org/zap/internal/exit go.uber.org/zap/zapcore -# golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea +# golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc ## explicit; go 1.20 golang.org/x/exp/constraints +golang.org/x/exp/maps golang.org/x/exp/slices -# golang.org/x/exp/typeparams v0.0.0-20230307190834-24139beb5833 +# golang.org/x/exp/typeparams v0.0.0-20240314144324-c7f7c6466f7f ## explicit; go 1.18 golang.org/x/exp/typeparams -# golang.org/x/mod v0.13.0 +# golang.org/x/mod v0.20.0 ## explicit; go 1.18 golang.org/x/mod/internal/lazyregexp golang.org/x/mod/modfile golang.org/x/mod/module golang.org/x/mod/semver -# golang.org/x/sync v0.4.0 -## explicit; go 1.17 +# golang.org/x/sync v0.8.0 +## explicit; go 1.18 golang.org/x/sync/errgroup golang.org/x/sync/semaphore -# golang.org/x/sys v0.13.0 -## explicit; go 1.17 -golang.org/x/sys/execabs +# golang.org/x/sys v0.23.0 +## explicit; go 1.18 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/text v0.13.0 -## explicit; go 1.17 +# golang.org/x/text v0.15.0 +## explicit; go 1.18 golang.org/x/text/runes golang.org/x/text/transform golang.org/x/text/unicode/norm golang.org/x/text/width -# golang.org/x/tools v0.14.0 -## explicit; go 1.18 +# golang.org/x/tools v0.24.0 +## explicit; go 1.19 golang.org/x/tools/go/analysis golang.org/x/tools/go/analysis/passes/appends golang.org/x/tools/go/analysis/passes/asmdecl @@ -749,7 +869,6 @@ golang.org/x/tools/go/buildutil golang.org/x/tools/go/cfg golang.org/x/tools/go/gcexportdata golang.org/x/tools/go/internal/cgo -golang.org/x/tools/go/internal/packagesdriver golang.org/x/tools/go/loader golang.org/x/tools/go/packages golang.org/x/tools/go/ssa @@ -757,21 +876,23 @@ golang.org/x/tools/go/ssa/ssautil golang.org/x/tools/go/types/objectpath golang.org/x/tools/go/types/typeutil golang.org/x/tools/imports +golang.org/x/tools/internal/aliases +golang.org/x/tools/internal/analysisinternal golang.org/x/tools/internal/event golang.org/x/tools/internal/event/core golang.org/x/tools/internal/event/keys golang.org/x/tools/internal/event/label -golang.org/x/tools/internal/event/tag -golang.org/x/tools/internal/fastwalk golang.org/x/tools/internal/gcimporter golang.org/x/tools/internal/gocommand golang.org/x/tools/internal/gopathwalk golang.org/x/tools/internal/imports golang.org/x/tools/internal/packagesinternal golang.org/x/tools/internal/pkgbits +golang.org/x/tools/internal/stdlib golang.org/x/tools/internal/tokeninternal golang.org/x/tools/internal/typeparams golang.org/x/tools/internal/typesinternal +golang.org/x/tools/internal/versions # google.golang.org/protobuf v1.33.0 ## explicit; go 1.17 google.golang.org/protobuf/encoding/prototext @@ -815,8 +936,9 @@ gopkg.in/yaml.v2 # gopkg.in/yaml.v3 v3.0.1 ## explicit gopkg.in/yaml.v3 -# honnef.co/go/tools v0.4.6 -## explicit; go 1.19 +# honnef.co/go/tools v0.5.0 +## explicit; go 1.22.1 +honnef.co/go/tools/analysis/callcheck honnef.co/go/tools/analysis/code honnef.co/go/tools/analysis/edit honnef.co/go/tools/analysis/facts/deprecated @@ -839,25 +961,167 @@ honnef.co/go/tools/knowledge honnef.co/go/tools/pattern honnef.co/go/tools/printf honnef.co/go/tools/simple +honnef.co/go/tools/simple/s1000 +honnef.co/go/tools/simple/s1001 +honnef.co/go/tools/simple/s1002 +honnef.co/go/tools/simple/s1003 +honnef.co/go/tools/simple/s1004 +honnef.co/go/tools/simple/s1005 +honnef.co/go/tools/simple/s1006 +honnef.co/go/tools/simple/s1007 +honnef.co/go/tools/simple/s1008 +honnef.co/go/tools/simple/s1009 +honnef.co/go/tools/simple/s1010 +honnef.co/go/tools/simple/s1011 +honnef.co/go/tools/simple/s1012 +honnef.co/go/tools/simple/s1016 +honnef.co/go/tools/simple/s1017 +honnef.co/go/tools/simple/s1018 +honnef.co/go/tools/simple/s1019 +honnef.co/go/tools/simple/s1020 +honnef.co/go/tools/simple/s1021 +honnef.co/go/tools/simple/s1023 +honnef.co/go/tools/simple/s1024 +honnef.co/go/tools/simple/s1025 +honnef.co/go/tools/simple/s1028 +honnef.co/go/tools/simple/s1029 +honnef.co/go/tools/simple/s1030 +honnef.co/go/tools/simple/s1031 +honnef.co/go/tools/simple/s1032 +honnef.co/go/tools/simple/s1033 +honnef.co/go/tools/simple/s1034 +honnef.co/go/tools/simple/s1035 +honnef.co/go/tools/simple/s1036 +honnef.co/go/tools/simple/s1037 +honnef.co/go/tools/simple/s1038 +honnef.co/go/tools/simple/s1039 +honnef.co/go/tools/simple/s1040 honnef.co/go/tools/staticcheck honnef.co/go/tools/staticcheck/fakejson honnef.co/go/tools/staticcheck/fakereflect honnef.co/go/tools/staticcheck/fakexml +honnef.co/go/tools/staticcheck/sa1000 +honnef.co/go/tools/staticcheck/sa1001 +honnef.co/go/tools/staticcheck/sa1002 +honnef.co/go/tools/staticcheck/sa1003 +honnef.co/go/tools/staticcheck/sa1004 +honnef.co/go/tools/staticcheck/sa1005 +honnef.co/go/tools/staticcheck/sa1006 +honnef.co/go/tools/staticcheck/sa1007 +honnef.co/go/tools/staticcheck/sa1008 +honnef.co/go/tools/staticcheck/sa1010 +honnef.co/go/tools/staticcheck/sa1011 +honnef.co/go/tools/staticcheck/sa1012 +honnef.co/go/tools/staticcheck/sa1013 +honnef.co/go/tools/staticcheck/sa1014 +honnef.co/go/tools/staticcheck/sa1015 +honnef.co/go/tools/staticcheck/sa1016 +honnef.co/go/tools/staticcheck/sa1017 +honnef.co/go/tools/staticcheck/sa1018 +honnef.co/go/tools/staticcheck/sa1019 +honnef.co/go/tools/staticcheck/sa1020 +honnef.co/go/tools/staticcheck/sa1021 +honnef.co/go/tools/staticcheck/sa1023 +honnef.co/go/tools/staticcheck/sa1024 +honnef.co/go/tools/staticcheck/sa1025 +honnef.co/go/tools/staticcheck/sa1026 +honnef.co/go/tools/staticcheck/sa1027 +honnef.co/go/tools/staticcheck/sa1028 +honnef.co/go/tools/staticcheck/sa1029 +honnef.co/go/tools/staticcheck/sa1030 +honnef.co/go/tools/staticcheck/sa1031 +honnef.co/go/tools/staticcheck/sa1032 +honnef.co/go/tools/staticcheck/sa2000 +honnef.co/go/tools/staticcheck/sa2001 +honnef.co/go/tools/staticcheck/sa2002 +honnef.co/go/tools/staticcheck/sa2003 +honnef.co/go/tools/staticcheck/sa3000 +honnef.co/go/tools/staticcheck/sa3001 +honnef.co/go/tools/staticcheck/sa4000 +honnef.co/go/tools/staticcheck/sa4001 +honnef.co/go/tools/staticcheck/sa4003 +honnef.co/go/tools/staticcheck/sa4004 +honnef.co/go/tools/staticcheck/sa4005 +honnef.co/go/tools/staticcheck/sa4006 +honnef.co/go/tools/staticcheck/sa4008 +honnef.co/go/tools/staticcheck/sa4009 +honnef.co/go/tools/staticcheck/sa4010 +honnef.co/go/tools/staticcheck/sa4011 +honnef.co/go/tools/staticcheck/sa4012 +honnef.co/go/tools/staticcheck/sa4013 +honnef.co/go/tools/staticcheck/sa4014 +honnef.co/go/tools/staticcheck/sa4015 +honnef.co/go/tools/staticcheck/sa4016 +honnef.co/go/tools/staticcheck/sa4017 +honnef.co/go/tools/staticcheck/sa4018 +honnef.co/go/tools/staticcheck/sa4019 +honnef.co/go/tools/staticcheck/sa4020 +honnef.co/go/tools/staticcheck/sa4021 +honnef.co/go/tools/staticcheck/sa4022 +honnef.co/go/tools/staticcheck/sa4023 +honnef.co/go/tools/staticcheck/sa4024 +honnef.co/go/tools/staticcheck/sa4025 +honnef.co/go/tools/staticcheck/sa4026 +honnef.co/go/tools/staticcheck/sa4027 +honnef.co/go/tools/staticcheck/sa4028 +honnef.co/go/tools/staticcheck/sa4029 +honnef.co/go/tools/staticcheck/sa4030 +honnef.co/go/tools/staticcheck/sa4031 +honnef.co/go/tools/staticcheck/sa4032 +honnef.co/go/tools/staticcheck/sa5000 +honnef.co/go/tools/staticcheck/sa5001 +honnef.co/go/tools/staticcheck/sa5002 +honnef.co/go/tools/staticcheck/sa5003 +honnef.co/go/tools/staticcheck/sa5004 +honnef.co/go/tools/staticcheck/sa5005 +honnef.co/go/tools/staticcheck/sa5007 +honnef.co/go/tools/staticcheck/sa5008 +honnef.co/go/tools/staticcheck/sa5009 +honnef.co/go/tools/staticcheck/sa5010 +honnef.co/go/tools/staticcheck/sa5011 +honnef.co/go/tools/staticcheck/sa5012 +honnef.co/go/tools/staticcheck/sa6000 +honnef.co/go/tools/staticcheck/sa6001 +honnef.co/go/tools/staticcheck/sa6002 +honnef.co/go/tools/staticcheck/sa6003 +honnef.co/go/tools/staticcheck/sa6005 +honnef.co/go/tools/staticcheck/sa6006 +honnef.co/go/tools/staticcheck/sa9001 +honnef.co/go/tools/staticcheck/sa9002 +honnef.co/go/tools/staticcheck/sa9003 +honnef.co/go/tools/staticcheck/sa9004 +honnef.co/go/tools/staticcheck/sa9005 +honnef.co/go/tools/staticcheck/sa9006 +honnef.co/go/tools/staticcheck/sa9007 +honnef.co/go/tools/staticcheck/sa9008 +honnef.co/go/tools/staticcheck/sa9009 honnef.co/go/tools/stylecheck +honnef.co/go/tools/stylecheck/st1000 +honnef.co/go/tools/stylecheck/st1001 +honnef.co/go/tools/stylecheck/st1003 +honnef.co/go/tools/stylecheck/st1005 +honnef.co/go/tools/stylecheck/st1006 +honnef.co/go/tools/stylecheck/st1008 +honnef.co/go/tools/stylecheck/st1011 +honnef.co/go/tools/stylecheck/st1012 +honnef.co/go/tools/stylecheck/st1013 +honnef.co/go/tools/stylecheck/st1015 +honnef.co/go/tools/stylecheck/st1016 +honnef.co/go/tools/stylecheck/st1017 +honnef.co/go/tools/stylecheck/st1018 +honnef.co/go/tools/stylecheck/st1019 +honnef.co/go/tools/stylecheck/st1020 +honnef.co/go/tools/stylecheck/st1021 +honnef.co/go/tools/stylecheck/st1022 +honnef.co/go/tools/stylecheck/st1023 honnef.co/go/tools/unused -# mvdan.cc/gofumpt v0.5.0 -## explicit; go 1.19 +# mvdan.cc/gofumpt v0.6.0 +## explicit; go 1.20 mvdan.cc/gofumpt/format mvdan.cc/gofumpt/internal/govendor/go/doc/comment mvdan.cc/gofumpt/internal/govendor/go/format mvdan.cc/gofumpt/internal/govendor/go/printer mvdan.cc/gofumpt/internal/version -# mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed -## explicit -mvdan.cc/interfacer/check -# mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b -## explicit -mvdan.cc/lint -# mvdan.cc/unparam v0.0.0-20221223090309-7455f1af531d -## explicit; go 1.18 +# mvdan.cc/unparam v0.0.0-20240528143540-8a5130ca722f +## explicit; go 1.21 mvdan.cc/unparam/check diff --git a/tools/vendor/mvdan.cc/gofumpt/format/format.go b/tools/vendor/mvdan.cc/gofumpt/format/format.go index 787561781..7316eb78b 100644 --- a/tools/vendor/mvdan.cc/gofumpt/format/format.go +++ b/tools/vendor/mvdan.cc/gofumpt/format/format.go @@ -31,17 +31,20 @@ import ( // Options is the set of formatting options which affect gofumpt. type Options struct { - // LangVersion corresponds to the Go language version a piece of code is - // written in. The version is used to decide whether to apply formatting - // rules which require new language features. When inside a Go module, - // LangVersion should be: - // - // go mod edit -json | jq -r '.Go' + // TODO: link to the go/version docs once Go 1.22 is out. + // The old semver docs said: // // LangVersion is treated as a semantic version, which may start with a "v" // prefix. Like Go versions, it may also be incomplete; "1.14" is equivalent // to "1.14.0". When empty, it is equivalent to "v1", to not use language // features which could break programs. + + // LangVersion is the Go version a piece of code is written in. + // The version is used to decide whether to apply formatting + // rules which require new language features. + // When inside a Go module, LangVersion should typically be: + // + // go mod edit -json | jq -r '.Go' LangVersion string // ModulePath corresponds to the Go module path which contains the source @@ -82,22 +85,28 @@ func Source(src []byte, opts Options) ([]byte, error) { return buf.Bytes(), nil } +var rxGoVersionMajorMinor = regexp.MustCompile(`^(v|go)?([1-9]+)\.([0-9]+)`) + // File modifies a file and fset in place to follow gofumpt's format. The // changes might include manipulating adding or removing newlines in fset, // modifying the position of nodes, or modifying literal values. func File(fset *token.FileSet, file *ast.File, opts Options) { simplify(file) + // TODO: replace this hacky mess with go/version once we can rely on Go 1.22, + // as well as replacing our uses of the semver package. + // In particular, we likely want to allow any of 1.21, 1.21.2, or go1.21rc3, + // but we can rely on go/version.Lang to validate and normalize. if opts.LangVersion == "" { - opts.LangVersion = "v1" - } else if opts.LangVersion[0] != 'v' { - opts.LangVersion = "v" + opts.LangVersion + opts.LangVersion = "v1.0" } - if !semver.IsValid(opts.LangVersion) { - panic(fmt.Sprintf("invalid semver string: %q", opts.LangVersion)) + m := rxGoVersionMajorMinor.FindStringSubmatch(opts.LangVersion) + if m == nil { + panic(fmt.Sprintf("invalid Go version: %q", opts.LangVersion)) } + opts.LangVersion = "v" + m[2] + "." + m[3] f := &fumpter{ - File: fset.File(file.Pos()), + file: fset.File(file.Pos()), fset: fset, astFile: file, Options: opts, @@ -170,7 +179,7 @@ var rxOctalInteger = regexp.MustCompile(`\A0[0-7_]+\z`) type fumpter struct { Options - *token.File + file *token.File fset *token.FileSet astFile *ast.File @@ -217,7 +226,8 @@ func (f *fumpter) inlineComment(pos token.Pos) *ast.Comment { func (f *fumpter) addNewline(at token.Pos) { offset := f.Offset(at) - field := reflect.ValueOf(f.File).Elem().FieldByName("lines") + // TODO: replace with the new Lines method once we require Go 1.21 or later + field := reflect.ValueOf(f.file).Elem().FieldByName("lines") n := field.Len() lines := make([]int, 0, n+1) for i := 0; i < n; i++ { @@ -236,7 +246,7 @@ func (f *fumpter) addNewline(at token.Pos) { if offset >= 0 { lines = append(lines, offset) } - if !f.SetLines(lines) { + if !f.file.SetLines(lines) { panic(fmt.Sprintf("could not set lines to %v", lines)) } } @@ -245,7 +255,7 @@ func (f *fumpter) addNewline(at token.Pos) { // up on the same line. func (f *fumpter) removeLines(fromLine, toLine int) { for fromLine < toLine { - f.MergeLine(fromLine) + f.file.MergeLine(fromLine) toLine-- } } @@ -256,6 +266,18 @@ func (f *fumpter) removeLinesBetween(from, to token.Pos) { f.removeLines(f.Line(from)+1, f.Line(to)) } +func (f *fumpter) Position(p token.Pos) token.Position { + return f.file.PositionFor(p, false) +} + +func (f *fumpter) Line(p token.Pos) int { + return f.Position(p).Line +} + +func (f *fumpter) Offset(p token.Pos) int { + return f.file.Offset(p) +} + type byteCounter int func (b *byteCounter) Write(p []byte) (n int, err error) { @@ -285,14 +307,14 @@ func (f *fumpter) lineEnd(line int) token.Pos { if line < 1 { panic("illegal line number") } - total := f.LineCount() + total := f.file.LineCount() if line > total { panic("illegal line number") } if line == total { return f.astFile.End() } - return f.LineStart(line+1) - 1 + return f.file.LineStart(line+1) - 1 } // rxCommentDirective covers all common Go comment directives: @@ -305,10 +327,11 @@ func (f *fumpter) lineEnd(line int) token.Pos { // //sys(nb)? | syscall function wrapper prototypes // //nolint | nolint directive for golangci // //noinspection | noinspection directive for GoLand and friends +// //NOSONAR | NOSONAR directive for SonarQube // // Note that the "some-words:" matching expects a letter afterward, such as // "go:generate", to prevent matching false positives like "https://site". -var rxCommentDirective = regexp.MustCompile(`^([a-z-]+:[a-z]+|line\b|export\b|extern\b|sys(nb)?\b|no(lint|inspection)\b)`) +var rxCommentDirective = regexp.MustCompile(`^([a-z-]+:[a-z]+|line\b|export\b|extern\b|sys(nb)?\b|no(lint|inspection)\b)|NOSONAR\b`) func (f *fumpter) applyPre(c *astutil.Cursor) { f.splitLongLine(c) @@ -865,9 +888,9 @@ func (f *fumpter) stmts(list []ast.Stmt) { continue // not an if following another statement } as, ok := list[i-1].(*ast.AssignStmt) - if !ok || as.Tok != token.DEFINE || + if !ok || (as.Tok != token.DEFINE && as.Tok != token.ASSIGN) || !identEqual(as.Lhs[len(as.Lhs)-1], "err") { - continue // not "..., err := ..." + continue // not ", err :=" nor ", err =" } be, ok := ifs.Cond.(*ast.BinaryExpr) if !ok || ifs.Init != nil || ifs.Else != nil { diff --git a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/print.go b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/print.go index 4e9da3d1e..e1c070d5a 100644 --- a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/print.go +++ b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/print.go @@ -148,8 +148,6 @@ func (h *Heading) DefaultID() string { type commentPrinter struct { *Printer - headingPrefix string - needDoc map[string]bool } // Comment returns the standard Go formatting of the Doc, diff --git a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/std.go b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/std.go index 6786e4d7a..d128eda8c 100644 --- a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/std.go +++ b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/doc/comment/std.go @@ -10,6 +10,7 @@ package comment var stdPkgs = []string{ "bufio", "bytes", + "cmp", "context", "crypto", "embed", @@ -23,6 +24,7 @@ var stdPkgs = []string{ "image", "io", "log", + "maps", "math", "mime", "net", @@ -32,6 +34,7 @@ var stdPkgs = []string{ "reflect", "regexp", "runtime", + "slices", "sort", "strconv", "strings", diff --git a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/comment.go b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/comment.go index 5b9775dc8..1f0e7df9d 100644 --- a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/comment.go +++ b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/comment.go @@ -37,15 +37,16 @@ func formatDocComment(list []*ast.Comment) []*ast.Comment { kind = "//" var b strings.Builder for _, c := range list { - if !strings.HasPrefix(c.Text, "//") { + after, found := strings.CutPrefix(c.Text, "//") + if !found { return list } // Accumulate //go:build etc lines separately. - if isDirective(c.Text[2:]) { + if isDirective(after) { directives = append(directives, c) continue } - b.WriteString(strings.TrimPrefix(c.Text[2:], " ")) + b.WriteString(strings.TrimPrefix(after, " ")) b.WriteString("\n") } text = b.String() diff --git a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/printer.go b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/printer.go index 576f9690d..2ab0278b0 100644 --- a/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/printer.go +++ b/tools/vendor/mvdan.cc/gofumpt/internal/govendor/go/printer/printer.go @@ -75,10 +75,11 @@ type printer struct { // white space). If there's a difference and SourcePos is set in // ConfigMode, //line directives are used in the output to restore // original source positions for a reader. - pos token.Position // current position in AST (source) space - out token.Position // current position in output space - last token.Position // value of pos after calling writeString - linePtr *int // if set, record out.Line for the next token in *linePtr + pos token.Position // current position in AST (source) space + out token.Position // current position in output space + last token.Position // value of pos after calling writeString + linePtr *int // if set, record out.Line for the next token in *linePtr + sourcePosErr error // if non-nil, the first error emitting a //line directive // The list of all source comments, in order of appearance. comments []*ast.CommentGroup // may be nil @@ -196,6 +197,13 @@ func (p *printer) lineFor(pos token.Pos) int { // writeLineDirective writes a //line directive if necessary. func (p *printer) writeLineDirective(pos token.Position) { if pos.IsValid() && (p.out.Line != pos.Line || p.out.Filename != pos.Filename) { + if strings.ContainsAny(pos.Filename, "\r\n") { + if p.sourcePosErr == nil { + p.sourcePosErr = fmt.Errorf("mvdan.cc/gofumpt/internal/govendor/go/printer: source filename contains unexpected newline character: %q", pos.Filename) + } + return + } + p.output = append(p.output, tabwriter.Escape) // protect '\n' in //line from tabwriter interpretation p.output = append(p.output, fmt.Sprintf("//line %s:%d\n", pos.Filename, pos.Line)...) p.output = append(p.output, tabwriter.Escape) @@ -804,7 +812,7 @@ func (p *printer) intersperseComments(next token.Position, tok token.Token) (wro return } -// whiteWhitespace writes the first n whitespace entries. +// writeWhitespace writes the first n whitespace entries. func (p *printer) writeWhitespace(n int) { // write entries for i := 0; i < n; i++ { @@ -1168,7 +1176,7 @@ func (p *printer) printNode(node any) error { goto unsupported } - return nil + return p.sourcePosErr unsupported: return fmt.Errorf("mvdan.cc/gofumpt/internal/govendor/go/printer: unsupported node type %T", node) diff --git a/tools/vendor/mvdan.cc/interfacer/LICENSE b/tools/vendor/mvdan.cc/interfacer/LICENSE deleted file mode 100644 index 7d71d51a5..000000000 --- a/tools/vendor/mvdan.cc/interfacer/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2015, Daniel Martí. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of 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 -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/vendor/mvdan.cc/interfacer/check/cache.go b/tools/vendor/mvdan.cc/interfacer/check/cache.go deleted file mode 100644 index 757eca55e..000000000 --- a/tools/vendor/mvdan.cc/interfacer/check/cache.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2015, Daniel Martí -// See LICENSE for licensing information - -package check - -import ( - "go/ast" - "go/types" -) - -type pkgTypes struct { - ifaces map[string]string - funcSigns map[string]bool -} - -func (p *pkgTypes) getTypes(pkg *types.Package) { - p.ifaces = make(map[string]string) - p.funcSigns = make(map[string]bool) - done := make(map[*types.Package]bool) - addTypes := func(pkg *types.Package, top bool) { - if done[pkg] { - return - } - done[pkg] = true - ifs, funs := fromScope(pkg.Scope()) - fullName := func(name string) string { - if !top { - return pkg.Path() + "." + name - } - return name - } - for iftype, name := range ifs { - // only suggest exported interfaces - if ast.IsExported(name) { - p.ifaces[iftype] = fullName(name) - } - } - for ftype := range funs { - // ignore non-exported func signatures too - p.funcSigns[ftype] = true - } - } - for _, imp := range pkg.Imports() { - addTypes(imp, false) - for _, imp2 := range imp.Imports() { - addTypes(imp2, false) - } - } - addTypes(pkg, true) -} diff --git a/tools/vendor/mvdan.cc/interfacer/check/check.go b/tools/vendor/mvdan.cc/interfacer/check/check.go deleted file mode 100644 index f4d3b4037..000000000 --- a/tools/vendor/mvdan.cc/interfacer/check/check.go +++ /dev/null @@ -1,462 +0,0 @@ -// Copyright (c) 2015, Daniel Martí -// See LICENSE for licensing information - -package check // import "mvdan.cc/interfacer/check" - -import ( - "fmt" - "go/ast" - "go/token" - "go/types" - "os" - "strings" - - "golang.org/x/tools/go/loader" - "golang.org/x/tools/go/ssa" - "golang.org/x/tools/go/ssa/ssautil" - - "github.com/kisielk/gotool" - "mvdan.cc/lint" -) - -func toDiscard(usage *varUsage) bool { - if usage.discard { - return true - } - for to := range usage.assigned { - if toDiscard(to) { - return true - } - } - return false -} - -func allCalls(usage *varUsage, all, ftypes map[string]string) { - for fname := range usage.calls { - all[fname] = ftypes[fname] - } - for to := range usage.assigned { - allCalls(to, all, ftypes) - } -} - -func (c *Checker) interfaceMatching(param *types.Var, usage *varUsage) (string, string) { - if toDiscard(usage) { - return "", "" - } - ftypes := typeFuncMap(param.Type()) - called := make(map[string]string, len(usage.calls)) - allCalls(usage, called, ftypes) - s := funcMapString(called) - return c.ifaces[s], s -} - -type varUsage struct { - calls map[string]struct{} - discard bool - - assigned map[*varUsage]struct{} -} - -type funcDecl struct { - astDecl *ast.FuncDecl - ssaFn *ssa.Function -} - -// CheckArgs checks the packages specified by their import paths in -// args. -func CheckArgs(args []string) ([]string, error) { - paths := gotool.ImportPaths(args) - conf := loader.Config{} - conf.AllowErrors = true - rest, err := conf.FromArgs(paths, false) - if err != nil { - return nil, err - } - if len(rest) > 0 { - return nil, fmt.Errorf("unwanted extra args: %v", rest) - } - lprog, err := conf.Load() - if err != nil { - return nil, err - } - prog := ssautil.CreateProgram(lprog, 0) - prog.Build() - c := new(Checker) - c.Program(lprog) - c.ProgramSSA(prog) - issues, err := c.Check() - if err != nil { - return nil, err - } - wd, err := os.Getwd() - if err != nil { - return nil, err - } - lines := make([]string, len(issues)) - for i, issue := range issues { - fpos := prog.Fset.Position(issue.Pos()).String() - if strings.HasPrefix(fpos, wd) { - fpos = fpos[len(wd)+1:] - } - lines[i] = fmt.Sprintf("%s: %s", fpos, issue.Message()) - } - return lines, nil -} - -type Checker struct { - lprog *loader.Program - prog *ssa.Program - - pkgTypes - *loader.PackageInfo - - funcs []*funcDecl - - ssaByPos map[token.Pos]*ssa.Function - - discardFuncs map[*types.Signature]struct{} - - vars map[*types.Var]*varUsage -} - -var ( - _ lint.Checker = (*Checker)(nil) - _ lint.WithSSA = (*Checker)(nil) -) - -func (c *Checker) Program(lprog *loader.Program) { - c.lprog = lprog -} - -func (c *Checker) ProgramSSA(prog *ssa.Program) { - c.prog = prog -} - -func (c *Checker) Check() ([]lint.Issue, error) { - var total []lint.Issue - c.ssaByPos = make(map[token.Pos]*ssa.Function) - wantPkg := make(map[*types.Package]bool) - for _, pinfo := range c.lprog.InitialPackages() { - wantPkg[pinfo.Pkg] = true - } - for fn := range ssautil.AllFunctions(c.prog) { - if fn.Pkg == nil { // builtin? - continue - } - if len(fn.Blocks) == 0 { // stub - continue - } - if !wantPkg[fn.Pkg.Pkg] { // not part of given pkgs - continue - } - c.ssaByPos[fn.Pos()] = fn - } - for _, pinfo := range c.lprog.InitialPackages() { - pkg := pinfo.Pkg - c.getTypes(pkg) - c.PackageInfo = c.lprog.AllPackages[pkg] - total = append(total, c.checkPkg()...) - } - return total, nil -} - -func (c *Checker) checkPkg() []lint.Issue { - c.discardFuncs = make(map[*types.Signature]struct{}) - c.vars = make(map[*types.Var]*varUsage) - c.funcs = c.funcs[:0] - findFuncs := func(node ast.Node) bool { - decl, ok := node.(*ast.FuncDecl) - if !ok { - return true - } - ssaFn := c.ssaByPos[decl.Name.Pos()] - if ssaFn == nil { - return true - } - fd := &funcDecl{ - astDecl: decl, - ssaFn: ssaFn, - } - if c.funcSigns[signString(fd.ssaFn.Signature)] { - // implements interface - return true - } - c.funcs = append(c.funcs, fd) - ast.Walk(c, decl.Body) - return true - } - for _, f := range c.Files { - ast.Inspect(f, findFuncs) - } - return c.packageIssues() -} - -func paramVarAndType(sign *types.Signature, i int) (*types.Var, types.Type) { - params := sign.Params() - extra := sign.Variadic() && i >= params.Len()-1 - if !extra { - if i >= params.Len() { - // builtins with multiple signatures - return nil, nil - } - vr := params.At(i) - return vr, vr.Type() - } - last := params.At(params.Len() - 1) - switch x := last.Type().(type) { - case *types.Slice: - return nil, x.Elem() - default: - return nil, x - } -} - -func (c *Checker) varUsage(e ast.Expr) *varUsage { - id, ok := e.(*ast.Ident) - if !ok { - return nil - } - param, ok := c.ObjectOf(id).(*types.Var) - if !ok { - // not a variable - return nil - } - if usage, e := c.vars[param]; e { - return usage - } - if !interesting(param.Type()) { - return nil - } - usage := &varUsage{ - calls: make(map[string]struct{}), - assigned: make(map[*varUsage]struct{}), - } - c.vars[param] = usage - return usage -} - -func (c *Checker) addUsed(e ast.Expr, as types.Type) { - if as == nil { - return - } - if usage := c.varUsage(e); usage != nil { - // using variable - iface, ok := as.Underlying().(*types.Interface) - if !ok { - usage.discard = true - return - } - for i := 0; i < iface.NumMethods(); i++ { - m := iface.Method(i) - usage.calls[m.Name()] = struct{}{} - } - } else if t, ok := c.TypeOf(e).(*types.Signature); ok { - // using func - c.discardFuncs[t] = struct{}{} - } -} - -func (c *Checker) addAssign(to, from ast.Expr) { - pto := c.varUsage(to) - pfrom := c.varUsage(from) - if pto == nil || pfrom == nil { - // either isn't interesting - return - } - pfrom.assigned[pto] = struct{}{} -} - -func (c *Checker) discard(e ast.Expr) { - if usage := c.varUsage(e); usage != nil { - usage.discard = true - } -} - -func (c *Checker) comparedWith(e, with ast.Expr) { - if _, ok := with.(*ast.BasicLit); ok { - c.discard(e) - } -} - -func (c *Checker) Visit(node ast.Node) ast.Visitor { - switch x := node.(type) { - case *ast.SelectorExpr: - if _, ok := c.TypeOf(x.Sel).(*types.Signature); !ok { - c.discard(x.X) - } - case *ast.StarExpr: - c.discard(x.X) - case *ast.UnaryExpr: - c.discard(x.X) - case *ast.IndexExpr: - c.discard(x.X) - case *ast.IncDecStmt: - c.discard(x.X) - case *ast.BinaryExpr: - switch x.Op { - case token.EQL, token.NEQ: - c.comparedWith(x.X, x.Y) - c.comparedWith(x.Y, x.X) - default: - c.discard(x.X) - c.discard(x.Y) - } - case *ast.ValueSpec: - for _, val := range x.Values { - c.addUsed(val, c.TypeOf(x.Type)) - } - case *ast.AssignStmt: - for i, val := range x.Rhs { - left := x.Lhs[i] - if x.Tok == token.ASSIGN { - c.addUsed(val, c.TypeOf(left)) - } - c.addAssign(left, val) - } - case *ast.CompositeLit: - for i, e := range x.Elts { - switch y := e.(type) { - case *ast.KeyValueExpr: - c.addUsed(y.Key, c.TypeOf(y.Value)) - c.addUsed(y.Value, c.TypeOf(y.Key)) - case *ast.Ident: - c.addUsed(y, compositeIdentType(c.TypeOf(x), i)) - } - } - case *ast.CallExpr: - switch y := c.TypeOf(x.Fun).Underlying().(type) { - case *types.Signature: - c.onMethodCall(x, y) - default: - // type conversion - if len(x.Args) == 1 { - c.addUsed(x.Args[0], y) - } - } - } - return c -} - -func compositeIdentType(t types.Type, i int) types.Type { - switch x := t.(type) { - case *types.Named: - return compositeIdentType(x.Underlying(), i) - case *types.Struct: - return x.Field(i).Type() - case *types.Array: - return x.Elem() - case *types.Slice: - return x.Elem() - } - return nil -} - -func (c *Checker) onMethodCall(ce *ast.CallExpr, sign *types.Signature) { - for i, e := range ce.Args { - paramObj, t := paramVarAndType(sign, i) - // Don't if this is a parameter being re-used as itself - // in a recursive call - if id, ok := e.(*ast.Ident); ok { - if paramObj == c.ObjectOf(id) { - continue - } - } - c.addUsed(e, t) - } - sel, ok := ce.Fun.(*ast.SelectorExpr) - if !ok { - return - } - // receiver func call on the left side - if usage := c.varUsage(sel.X); usage != nil { - usage.calls[sel.Sel.Name] = struct{}{} - } -} - -func (fd *funcDecl) paramGroups() [][]*types.Var { - astList := fd.astDecl.Type.Params.List - groups := make([][]*types.Var, len(astList)) - signIndex := 0 - for i, field := range astList { - group := make([]*types.Var, len(field.Names)) - for j := range field.Names { - group[j] = fd.ssaFn.Signature.Params().At(signIndex) - signIndex++ - } - groups[i] = group - } - return groups -} - -func (c *Checker) packageIssues() []lint.Issue { - var issues []lint.Issue - for _, fd := range c.funcs { - if _, e := c.discardFuncs[fd.ssaFn.Signature]; e { - continue - } - for _, group := range fd.paramGroups() { - issues = append(issues, c.groupIssues(fd, group)...) - } - } - return issues -} - -type Issue struct { - pos token.Pos - msg string -} - -func (i Issue) Pos() token.Pos { return i.pos } -func (i Issue) Message() string { return i.msg } - -func (c *Checker) groupIssues(fd *funcDecl, group []*types.Var) []lint.Issue { - var issues []lint.Issue - for _, param := range group { - usage := c.vars[param] - if usage == nil { - return nil - } - newType := c.paramNewType(fd.astDecl.Name.Name, param, usage) - if newType == "" { - return nil - } - issues = append(issues, Issue{ - pos: param.Pos(), - msg: fmt.Sprintf("%s can be %s", param.Name(), newType), - }) - } - return issues -} - -func willAddAllocation(t types.Type) bool { - switch t.Underlying().(type) { - case *types.Pointer, *types.Interface: - return false - } - return true -} - -func (c *Checker) paramNewType(funcName string, param *types.Var, usage *varUsage) string { - t := param.Type() - if !ast.IsExported(funcName) && willAddAllocation(t) { - return "" - } - if named := typeNamed(t); named != nil { - tname := named.Obj().Name() - vname := param.Name() - if mentionsName(funcName, tname) || mentionsName(funcName, vname) { - return "" - } - } - ifname, iftype := c.interfaceMatching(param, usage) - if ifname == "" { - return "" - } - if types.IsInterface(t.Underlying()) { - if have := funcMapString(typeFuncMap(t)); have == iftype { - return "" - } - } - return ifname -} diff --git a/tools/vendor/mvdan.cc/interfacer/check/types.go b/tools/vendor/mvdan.cc/interfacer/check/types.go deleted file mode 100644 index 393bb0b9f..000000000 --- a/tools/vendor/mvdan.cc/interfacer/check/types.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) 2015, Daniel Martí -// See LICENSE for licensing information - -package check - -import ( - "bytes" - "fmt" - "go/types" - "sort" - "strings" -) - -type methoder interface { - NumMethods() int - Method(int) *types.Func -} - -func methoderFuncMap(m methoder, skip bool) map[string]string { - ifuncs := make(map[string]string, m.NumMethods()) - for i := 0; i < m.NumMethods(); i++ { - f := m.Method(i) - if !f.Exported() { - if skip { - continue - } - return nil - } - sign := f.Type().(*types.Signature) - ifuncs[f.Name()] = signString(sign) - } - return ifuncs -} - -func typeFuncMap(t types.Type) map[string]string { - switch x := t.(type) { - case *types.Pointer: - return typeFuncMap(x.Elem()) - case *types.Named: - u := x.Underlying() - if types.IsInterface(u) { - return typeFuncMap(u) - } - return methoderFuncMap(x, true) - case *types.Interface: - return methoderFuncMap(x, false) - default: - return nil - } -} - -func funcMapString(iface map[string]string) string { - fnames := make([]string, 0, len(iface)) - for fname := range iface { - fnames = append(fnames, fname) - } - sort.Strings(fnames) - var b bytes.Buffer - for i, fname := range fnames { - if i > 0 { - fmt.Fprint(&b, "; ") - } - fmt.Fprint(&b, fname, iface[fname]) - } - return b.String() -} - -func tupleJoin(buf *bytes.Buffer, t *types.Tuple) { - buf.WriteByte('(') - for i := 0; i < t.Len(); i++ { - if i > 0 { - buf.WriteString(", ") - } - buf.WriteString(t.At(i).Type().String()) - } - buf.WriteByte(')') -} - -// signString is similar to Signature.String(), but it ignores -// param/result names. -func signString(sign *types.Signature) string { - var buf bytes.Buffer - tupleJoin(&buf, sign.Params()) - tupleJoin(&buf, sign.Results()) - return buf.String() -} - -func interesting(t types.Type) bool { - switch x := t.(type) { - case *types.Interface: - return x.NumMethods() > 1 - case *types.Named: - if u := x.Underlying(); types.IsInterface(u) { - return interesting(u) - } - return x.NumMethods() >= 1 - case *types.Pointer: - return interesting(x.Elem()) - default: - return false - } -} - -func anyInteresting(params *types.Tuple) bool { - for i := 0; i < params.Len(); i++ { - t := params.At(i).Type() - if interesting(t) { - return true - } - } - return false -} - -func fromScope(scope *types.Scope) (ifaces map[string]string, funcs map[string]bool) { - ifaces = make(map[string]string) - funcs = make(map[string]bool) - for _, name := range scope.Names() { - tn, ok := scope.Lookup(name).(*types.TypeName) - if !ok { - continue - } - switch x := tn.Type().Underlying().(type) { - case *types.Interface: - iface := methoderFuncMap(x, false) - if len(iface) == 0 { - continue - } - for i := 0; i < x.NumMethods(); i++ { - f := x.Method(i) - sign := f.Type().(*types.Signature) - if !anyInteresting(sign.Params()) { - continue - } - funcs[signString(sign)] = true - } - s := funcMapString(iface) - if _, e := ifaces[s]; !e { - ifaces[s] = tn.Name() - } - case *types.Signature: - if !anyInteresting(x.Params()) { - continue - } - funcs[signString(x)] = true - } - } - return ifaces, funcs -} - -func mentionsName(fname, name string) bool { - if len(name) < 2 { - return false - } - capit := strings.ToUpper(name[:1]) + name[1:] - lower := strings.ToLower(name) - return strings.Contains(fname, capit) || strings.HasPrefix(fname, lower) -} - -func typeNamed(t types.Type) *types.Named { - for { - switch x := t.(type) { - case *types.Named: - return x - case *types.Pointer: - t = x.Elem() - default: - return nil - } - } -} diff --git a/tools/vendor/mvdan.cc/lint/.travis.yml b/tools/vendor/mvdan.cc/lint/.travis.yml deleted file mode 100644 index 2ccdeab9a..000000000 --- a/tools/vendor/mvdan.cc/lint/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go - -go: - - 1.8.x - - 1.9.x - -go_import_path: mvdan.cc/lint diff --git a/tools/vendor/mvdan.cc/lint/LICENSE b/tools/vendor/mvdan.cc/lint/LICENSE deleted file mode 100644 index a06c5ebfc..000000000 --- a/tools/vendor/mvdan.cc/lint/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2017, Daniel Martí. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of 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 -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/vendor/mvdan.cc/lint/README.md b/tools/vendor/mvdan.cc/lint/README.md deleted file mode 100644 index 8a9c8b51c..000000000 --- a/tools/vendor/mvdan.cc/lint/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# lint - -[![GoDoc](https://godoc.org/mvdan.cc/lint?status.svg)](https://godoc.org/mvdan.cc/lint) -[![Build Status](https://travis-ci.org/mvdan/lint.svg?branch=master)](https://travis-ci.org/mvdan/lint) - -Work in progress. Its API might change before the 1.0 release. - -This package intends to define simple interfaces that Go code checkers -can implement. This would simplify calling them from Go code, as well as -running multiple linters while sharing initial loading work. - -### metalint - - go get -u mvdan.cc/lint/cmd/metalint - -The start of a linter that runs many linters leveraging the common -interface. Not stable yet. - -Linters included: - -* [unparam](https://mvdan.cc/unparam) -* [interfacer](https://github.com/mvdan/interfacer) - -### Related projects - -* [golinters](https://github.com/thomasheller/golinters) - Report on - linter support diff --git a/tools/vendor/mvdan.cc/lint/lint.go b/tools/vendor/mvdan.cc/lint/lint.go deleted file mode 100644 index a16789fad..000000000 --- a/tools/vendor/mvdan.cc/lint/lint.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2017, Daniel Martí -// See LICENSE for licensing information - -// Package lint defines common interfaces for Go code checkers. -package lint // import "mvdan.cc/lint" - -import ( - "go/token" - - "golang.org/x/tools/go/loader" - "golang.org/x/tools/go/ssa" -) - -// A Checker points out issues in a program. -type Checker interface { - Program(*loader.Program) - Check() ([]Issue, error) -} - -type WithSSA interface { - ProgramSSA(*ssa.Program) -} - -// Issue represents an issue somewhere in a source code file. -type Issue interface { - Pos() token.Pos - Message() string -} diff --git a/tools/vendor/mvdan.cc/unparam/check/check.go b/tools/vendor/mvdan.cc/unparam/check/check.go index 8f9a3cb0a..2bda01305 100644 --- a/tools/vendor/mvdan.cc/unparam/check/check.go +++ b/tools/vendor/mvdan.cc/unparam/check/check.go @@ -908,15 +908,22 @@ func recvPrefix(recv *ast.FieldList) string { } expr = star.X } + + return identName(expr) +} + +func identName(expr ast.Expr) string { switch expr := expr.(type) { case *ast.Ident: return expr.Name + "." case *ast.IndexExpr: - return expr.X.(*ast.Ident).Name + "." + return identName(expr.X) + case *ast.ParenExpr: + return identName(expr.X) case *ast.IndexListExpr: - return expr.X.(*ast.Ident).Name + "." + return identName(expr.X) default: - panic(fmt.Sprintf("unexepected receiver AST node: %T", expr)) + panic(fmt.Sprintf("unexpected receiver AST node: %T", expr)) } }