diff --git a/tools/go.mod b/tools/go.mod index 9794ce01..2db9792f 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -4,12 +4,12 @@ go 1.18 require ( github.com/axw/gocov v1.1.0 - github.com/golangci/golangci-lint v1.46.2 + github.com/golangci/golangci-lint v1.49.0 github.com/goreleaser/goreleaser v1.11.2 github.com/matm/gocov-html v0.0.0-20200509184451-71874e2e203b github.com/mattn/goveralls v0.0.11 github.com/obalunenko/coverbadger v1.2.0 - golang.org/x/tools v0.1.11-0.20220316014157-77aa08bb151a + golang.org/x/tools v0.1.12 gotest.tools/gotestsum v1.8.1 ) @@ -22,7 +22,7 @@ require ( cloud.google.com/go/storage v1.22.1 // indirect code.gitea.io/sdk/gitea v0.15.1 // indirect github.com/AlekSi/pointer v1.2.0 // indirect - github.com/Antonboom/errname v0.1.6 // indirect + github.com/Antonboom/errname v0.1.7 // indirect github.com/Antonboom/nilnil v0.1.1 // indirect github.com/Azure/azure-pipeline-go v0.2.3 // indirect github.com/Azure/azure-sdk-for-go v60.2.0+incompatible // indirect @@ -37,9 +37,9 @@ require ( github.com/Azure/go-autorest/autorest/validation v0.3.1 // indirect github.com/Azure/go-autorest/logger v0.2.1 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect - github.com/BurntSushi/toml v1.1.0 // indirect + github.com/BurntSushi/toml v1.2.0 // indirect github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 // indirect - github.com/GaijinEntertainment/go-exhaustruct/v2 v2.1.0 // indirect + github.com/GaijinEntertainment/go-exhaustruct/v2 v2.3.0 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/semver/v3 v3.1.1 // indirect @@ -49,6 +49,7 @@ require ( github.com/ProtonMail/go-crypto v0.0.0-20211112122917-428f8eabeeb3 // indirect github.com/acomagu/bufpipe v1.0.3 // indirect github.com/alexkohler/prealloc v1.0.0 // indirect + github.com/alingse/asasalint v0.0.11 // indirect github.com/ashanbrown/forbidigo v1.3.0 // indirect github.com/ashanbrown/makezero v1.1.1 // indirect github.com/atc0005/go-teams-notify/v2 v2.6.1 // indirect @@ -90,9 +91,10 @@ require ( github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/charithe/durationcheck v0.0.9 // indirect github.com/charmbracelet/lipgloss v0.5.1-0.20220615005615-2e17a8a06096 // indirect - github.com/chavacava/garif v0.0.0-20220316182200-5cad0b5181d4 // indirect + github.com/chavacava/garif v0.0.0-20220630083739-93517212f375 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect - github.com/daixiang0/gci v0.3.3 // indirect + github.com/curioswitch/go-reassign v0.1.2 // indirect + github.com/daixiang0/gci v0.6.3 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/denis-tingaikin/go-header v0.4.3 // indirect github.com/dghubble/go-twitter v0.0.0-20211115160449-93a8679adecb // indirect @@ -108,17 +110,17 @@ require ( github.com/ettle/strcase v0.1.1 // indirect github.com/fatih/color v1.13.0 // indirect github.com/fatih/structtag v1.2.0 // indirect - github.com/firefart/nonamedreturns v1.0.1 // indirect + github.com/firefart/nonamedreturns v1.0.4 // indirect github.com/fsnotify/fsnotify v1.5.4 // indirect - github.com/fzipp/gocyclo v0.5.1 // indirect - github.com/go-critic/go-critic v0.6.3 // indirect + github.com/fzipp/gocyclo v0.6.0 // indirect + github.com/go-critic/go-critic v0.6.4 // indirect github.com/go-git/gcfg v1.5.0 // indirect github.com/go-git/go-billy/v5 v5.3.1 // indirect github.com/go-git/go-git/v5 v5.4.2 // indirect github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible // indirect github.com/go-toolsmith/astcast v1.0.0 // indirect - github.com/go-toolsmith/astcopy v1.0.0 // indirect - github.com/go-toolsmith/astequal v1.0.1 // indirect + github.com/go-toolsmith/astcopy v1.0.1 // indirect + github.com/go-toolsmith/astequal v1.0.2 // indirect github.com/go-toolsmith/astfmt v1.0.0 // indirect github.com/go-toolsmith/astp v1.0.0 // indirect github.com/go-toolsmith/strparse v1.0.0 // indirect @@ -136,7 +138,7 @@ require ( 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.3.5 // indirect - github.com/golangci/revgrep v0.0.0-20210930125155-c22e5001d4f2 // indirect + github.com/golangci/revgrep v0.0.0-20220804021717-745bb2f7c2e6 // indirect github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 // indirect github.com/google/go-cmp v0.5.8 // indirect github.com/google/go-github/v47 v47.0.0 // indirect @@ -161,7 +163,7 @@ require ( github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-retryablehttp v0.7.1 // indirect - github.com/hashicorp/go-version v1.4.0 // indirect + github.com/hashicorp/go-version v1.6.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/huandu/xstrings v1.3.2 // indirect @@ -177,12 +179,12 @@ require ( github.com/jonboulle/clockwork v0.2.2 // indirect github.com/julz/importas v0.1.0 // indirect github.com/kevinburke/ssh_config v1.1.0 // indirect - github.com/kisielk/errcheck v1.6.0 // indirect + github.com/kisielk/errcheck v1.6.2 // indirect github.com/kisielk/gotool v1.0.0 // indirect github.com/klauspost/compress v1.15.1 // indirect github.com/klauspost/pgzip v1.2.5 // indirect - github.com/kulti/thelper v0.6.2 // indirect - github.com/kunwardeep/paralleltest v1.0.3 // indirect + github.com/kulti/thelper v0.6.3 // indirect + github.com/kunwardeep/paralleltest v1.0.6 // indirect github.com/kyoh86/exportloopref v0.1.8 // indirect github.com/ldez/gomoddirectives v0.2.3 // indirect github.com/ldez/tagliatelle v0.3.1 // indirect @@ -190,15 +192,15 @@ require ( github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/lufeee/execinquery v1.2.1 // indirect github.com/magiconair/properties v1.8.6 // indirect - github.com/maratori/testpackage v1.0.1 // indirect + github.com/maratori/testpackage v1.1.0 // indirect github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 // indirect - github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-ieproxy v0.0.1 // indirect - github.com/mattn/go-isatty v0.0.14 // indirect + github.com/mattn/go-isatty v0.0.16 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect github.com/mbilski/exhaustivestruct v1.2.0 // indirect - github.com/mgechev/revive v1.2.1 // indirect + github.com/mgechev/revive v1.2.3 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect @@ -212,36 +214,39 @@ require ( github.com/muesli/termenv v0.12.1-0.20220615005108-4e9068de9898 // indirect github.com/nakabonne/nestif v0.3.1 // indirect github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 // indirect - github.com/nishanths/exhaustive v0.7.11 // indirect + github.com/nishanths/exhaustive v0.8.1 // indirect github.com/nishanths/predeclared v0.2.2 // indirect github.com/obalunenko/version v1.1.0 // 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.1 // indirect + github.com/pelletier/go-toml/v2 v2.0.2 // indirect github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/polyfloyd/go-errorlint v1.0.0 // indirect + github.com/polyfloyd/go-errorlint v1.0.2 // 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.3.16-0.20220213074421-6aa060fab41a // indirect + github.com/quasilyte/go-ruleguard v0.3.17 // indirect github.com/quasilyte/gogrep v0.0.0-20220120141003-628d8b3623b5 // indirect github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95 // indirect github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/ryancurrah/gomodguard v1.2.3 // indirect + github.com/ryancurrah/gomodguard v1.2.4 // indirect github.com/ryanrolds/sqlclosecheck v0.3.0 // indirect github.com/sanposhiho/wastedassign/v2 v2.0.6 // indirect github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b // indirect - github.com/securego/gosec/v2 v2.11.0 // indirect + github.com/sashamelentyev/interfacebloat v1.1.0 // indirect + github.com/sashamelentyev/usestdlibvars v1.13.0 // indirect + github.com/securego/gosec/v2 v2.13.1 // indirect github.com/sergi/go-diff v1.2.0 // indirect github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c // indirect - github.com/sirupsen/logrus v1.8.1 // indirect + github.com/sirupsen/logrus v1.9.0 // indirect github.com/sivchari/containedctx v1.0.2 // indirect - github.com/sivchari/tenv v1.5.0 // indirect + github.com/sivchari/nosnakecase v1.7.0 // indirect + github.com/sivchari/tenv v1.7.0 // indirect github.com/slack-go/slack v0.11.2 // indirect github.com/sonatard/noctx v0.0.1 // indirect github.com/sourcegraph/go-diff v0.6.1 // indirect @@ -255,34 +260,39 @@ require ( github.com/stbenjam/no-sprintf-host-port v0.1.1 // indirect github.com/stretchr/objx v0.4.0 // indirect github.com/stretchr/testify v1.8.0 // indirect - github.com/subosito/gotenv v1.3.0 // indirect - github.com/sylvia7788/contextcheck v1.0.4 // indirect + github.com/subosito/gotenv v1.4.0 // indirect + github.com/sylvia7788/contextcheck v1.0.6 // indirect github.com/tdakkota/asciicheck v0.1.1 // indirect github.com/technoweenie/multipartstreamer v1.0.1 // indirect github.com/tetafro/godot v1.4.11 // indirect github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 // indirect - github.com/tomarrell/wrapcheck/v2 v2.6.1 // indirect + github.com/timonwong/logrlint v0.1.0 // indirect + github.com/tomarrell/wrapcheck/v2 v2.6.2 // indirect github.com/tommy-muehle/go-mnd/v2 v2.5.0 // indirect github.com/ulikunitz/xz v0.5.10 // indirect github.com/ultraware/funlen v0.0.3 // indirect github.com/ultraware/whitespace v0.0.5 // indirect - github.com/uudashr/gocognit v1.0.5 // indirect + github.com/uudashr/gocognit v1.0.6 // indirect github.com/withfig/autocomplete-tools/integrations/cobra v1.2.1 // indirect github.com/xanzy/go-gitlab v0.73.1 // indirect github.com/xanzy/ssh-agent v0.3.1 // indirect github.com/yagipy/maintidx v1.0.0 // indirect github.com/yeya24/promlinter v0.2.0 // indirect - gitlab.com/bosi/decorder v0.2.1 // indirect + gitlab.com/bosi/decorder v0.2.3 // indirect gitlab.com/digitalxero/go-conventional-commit v1.0.7 // indirect go.opencensus.io v0.23.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.8.0 // indirect + go.uber.org/zap v1.21.0 // indirect gocloud.dev v0.26.0 // indirect - golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect - golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e // indirect - golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect + golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa // indirect + golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect + golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d // indirect + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48 // indirect golang.org/x/oauth2 v0.0.0-20220722155238-128564f6959c // indirect - golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect - golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 // indirect + golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect + golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 // indirect @@ -293,14 +303,14 @@ require ( google.golang.org/grpc v1.47.0 // indirect google.golang.org/protobuf v1.28.1 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect - gopkg.in/ini.v1 v1.66.4 // indirect + gopkg.in/ini.v1 v1.66.6 // indirect gopkg.in/mail.v2 v2.3.1 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - honnef.co/go/tools v0.3.1 // indirect + honnef.co/go/tools v0.3.3 // indirect mvdan.cc/gofumpt v0.3.1 // 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-20211214103731-d0ef000c54e5 // indirect + mvdan.cc/unparam v0.0.0-20220706161116-678bad134442 // indirect ) diff --git a/tools/go.sum b/tools/go.sum index 7ded7a8b..b4108c0c 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -1,6 +1,5 @@ 4d63.com/gochecknoglobals v0.1.0 h1:zeZSRqj5yCg28tCkIV/z/lWbwvNm5qnKVS15PI8nhD0= 4d63.com/gochecknoglobals v0.1.0/go.mod h1:wfdC5ZjKSPr7CybKEcgJhUOgeAQW1+7WcyK8OvUilfo= -bitbucket.org/creachadair/shell v0.0.6/go.mod h1:8Qqi/cYk7vPnsOePHroKXDJYmb5x7ENhtiFtfZq8K+M= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= @@ -15,7 +14,6 @@ cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6 cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.60.0/go.mod h1:yw2G51M9IfRboUH61Us8GqCeF1PzPblB823Mn2q2eAU= 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= @@ -67,10 +65,8 @@ cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2k cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/pubsub v1.5.0/go.mod h1:ZEwJccE3z93Z2HWvstpri00jOg7oO4UZDtKhwDwqF0w= cloud.google.com/go/pubsub v1.19.0/go.mod h1:/O9kmSe9bb9KRnIAWkzmqhPjHo6LtzGOBYd/kr06XSs= cloud.google.com/go/secretmanager v1.3.0/go.mod h1:+oLTkouyiYiabAQNugCeTS3PAArGiMJuBqvJnJsyH+U= -cloud.google.com/go/spanner v1.7.0/go.mod h1:sd3K2gZ9Fd0vMPLXzeCrF6fq4i63Q7aTLW/lBIfBkIk= cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= @@ -86,14 +82,13 @@ code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFj code.gitea.io/sdk/gitea v0.15.1 h1:WJreC7YYuxbn0UDaPuWIe/mtiNKTvLN8MLkaw71yx/M= code.gitea.io/sdk/gitea v0.15.1/go.mod h1:klY2LVI3s3NChzIk/MzMn7G1FHrfU7qd63iSMVoHRBA= contrib.go.opencensus.io/exporter/aws v0.0.0-20200617204711-c478e41e60e9/go.mod h1:uu1P0UCM/6RbsMrgPa98ll8ZcHM858i/AD06a9aLRCA= -contrib.go.opencensus.io/exporter/stackdriver v0.13.4/go.mod h1:aXENhDJ1Y4lIg4EUaVTwzvYETVNZk10Pu26tevFKLUc= contrib.go.opencensus.io/exporter/stackdriver v0.13.10/go.mod h1:I5htMbyta491eUxufwwZPQdcKvvgzMB4O9ni41YnIM8= contrib.go.opencensus.io/integrations/ocsql v0.1.7/go.mod h1:8DsSdjz3F+APR+0z0WkU1aRorQCFfRxvqjUUPMbF3fE= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/AlekSi/pointer v1.2.0 h1:glcy/gc4h8HnG2Z3ZECSzZ1IX1x2JxRVuDzaJwQE0+w= github.com/AlekSi/pointer v1.2.0/go.mod h1:gZGfd3dpW4vEc/UlyfKKi1roIqcCgwOIvb0tSNSBle0= -github.com/Antonboom/errname v0.1.6 h1:LzIJZlyLOCSu51o3/t2n9Ck7PcoP9wdbrdaW6J8fX24= -github.com/Antonboom/errname v0.1.6/go.mod h1:7lz79JAnuoMNDAWE9MeeIr1/c/VpSUWatBv2FH9NYpI= +github.com/Antonboom/errname v0.1.7 h1:mBBDKvEYwPl4WFFNwec1CZO096G6vzK9vvDQzAwkako= +github.com/Antonboom/errname v0.1.7/go.mod h1:g0ONh16msHIPgJSGsecu1G/dcF2hlYR/0SddnIAGavU= github.com/Antonboom/nilnil v0.1.1 h1:PHhrh5ANKFWRBh7TdYmyyq2gyT2lotnvFvvFbylF81Q= github.com/Antonboom/nilnil v0.1.1/go.mod h1:L1jBqoWM7AOeTD+tSquifKSesRHs4ZdaxvZR+xdJEaI= github.com/Azure/azure-amqp-common-go/v3 v3.2.1/go.mod h1:O6X1iYHP7s2x7NjUKsXVhkwWrQhxrd+d8/3rRadj4CI= @@ -144,25 +139,21 @@ github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZ github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= -github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= +github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= 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/v2 v2.1.0 h1:LAPPhJ4KR5Z8aKVZF5S48csJkxL5RMKmE/98fMs1u5M= -github.com/GaijinEntertainment/go-exhaustruct/v2 v2.1.0/go.mod h1:LGOGuvEgCfCQsy3JF2tRmpGDpzA53iZfyGEWSPwQ6/4= +github.com/GaijinEntertainment/go-exhaustruct/v2 v2.3.0 h1:+r1rSv4gvYn0wmRjC8X7IAzX8QezqtFV9m0MUHFJgts= +github.com/GaijinEntertainment/go-exhaustruct/v2 v2.3.0/go.mod h1:b3g59n2Y+T5xmcxJL+UEG2f8cQploZm1mR/v6BW0mU0= github.com/GoogleCloudPlatform/cloudsql-proxy v1.29.0/go.mod h1:spvB9eLJH9dutlbPSRmHvSXXHOwGRyeXh1jVdquA2G8= -github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= -github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc= github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= -github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= @@ -187,17 +178,11 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= 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= +github.com/alingse/asasalint v0.0.11/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA= github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= -github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-metrics v0.3.10/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/ashanbrown/forbidigo v1.3.0 h1:VkYIwb/xxdireGAdJNZoo24O4lmnEWkactplBlWTShc= @@ -207,9 +192,6 @@ github.com/ashanbrown/makezero v1.1.1/go.mod h1:i1bJLCRSCHOcOa9Y6MyF2FTfMZMFdHvx github.com/atc0005/go-teams-notify/v2 v2.6.1 h1:t22ybzQuaQs4UJe4ceF5VYGsPhs6ir3nZOId/FBy6Go= github.com/atc0005/go-teams-notify/v2 v2.6.1/go.mod h1:xo6GejLDHn3tWBA181F8LrllIL0xC1uRsRxq7YNXaaY= github.com/aws/aws-sdk-go v1.15.27/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= -github.com/aws/aws-sdk-go v1.23.20/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go v1.25.37/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go v1.36.30/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= github.com/aws/aws-sdk-go v1.37.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= github.com/aws/aws-sdk-go v1.43.31 h1:yJZIr8nMV1hXjAvvOLUFqZRJcHV7udPQBfhJqawDzI0= github.com/aws/aws-sdk-go v1.43.31/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= @@ -258,12 +240,12 @@ github.com/axw/gocov v1.1.0 h1:y5U1krExoJDlb/kNtzxyZQmNRprFOFCutWbNjcQvmVM= github.com/axw/gocov v1.1.0/go.mod h1:H9G4tivgdN3pYSSVrTFBr6kGDCmAkgbJhtxFzAvgcdw= github.com/aymanbagabas/go-osc52 v1.0.3 h1:DTwqENW7X9arYimJrPeGZcV0ln14sGMt3pHZspWD+Mg= github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4= +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= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bkielbasa/cyclop v1.2.0 h1:7Jmnh0yL2DjKfw28p86YTd/B4lRGcNuu12sKE35sM7A= github.com/bkielbasa/cyclop v1.2.0/go.mod h1:qOI0yy6A7dYC4Zgsa72Ppm9kONl0RoIlPbzot9mhmeI= github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb h1:m935MPodAbYS46DG4pJSv7WO+VECIWUQ7OJYSoTrMh4= @@ -307,13 +289,11 @@ github.com/charithe/durationcheck v0.0.9/go.mod h1:SSbRIBVfMjCi/kEB6K65XEA83D6pr github.com/charmbracelet/keygen v0.3.0 h1:mXpsQcH7DDlST5TddmXNXjS0L7ECk4/kLQYyBcsan2Y= github.com/charmbracelet/lipgloss v0.5.1-0.20220615005615-2e17a8a06096 h1:ai19sA3Zyg3DARevWCbdLOWt+MfWiE3e8voBqzFOgP8= github.com/charmbracelet/lipgloss v0.5.1-0.20220615005615-2e17a8a06096/go.mod h1:D7uPgcyfB9T1Ug2mfJOnES17o47nz5oqIzSSVrpcviU= -github.com/chavacava/garif v0.0.0-20220316182200-5cad0b5181d4 h1:tFXjAxje9thrTF4h57Ckik+scJjTWdwAtZqZPtOT48M= -github.com/chavacava/garif v0.0.0-20220316182200-5cad0b5181d4/go.mod h1:W8EnPSQ8Nv4fUjc/v1/8tHFqhuOJXnRub0dTfuAQktU= +github.com/chavacava/garif v0.0.0-20220630083739-93517212f375 h1:E7LT642ysztPWE0dfz43cWOvMiF42DyTRC+eZIaO4yI= +github.com/chavacava/garif v0.0.0-20220630083739-93517212f375/go.mod h1:4m1Rv7xfuwWPNKXlThldNuJvutYM6J95wNuuVmn55To= 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/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= -github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= 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= @@ -325,28 +305,18 @@ github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= -github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= -github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= -github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20190620071333-e64a0ec8b42a/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/daixiang0/gci v0.3.3 h1:55xJKH7Gl9Vk6oQ1cMkwrDWjAkT1D+D1G9kNmRcAIY4= -github.com/daixiang0/gci v0.3.3/go.mod h1:1Xr2bxnQbDxCqqulUOv8qpGqkgRw9RSCGGjEC2LjF8o= -github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/cristalhq/acmd v0.7.0/go.mod h1:LG5oa43pE/BbxtfMoImHCQN++0Su7dzipdgBjMCBVDQ= +github.com/curioswitch/go-reassign v0.1.2 h1:ekM07+z+VFT560Exz4mTv0/s1yU9gem6CJc/tlYpkmI= +github.com/curioswitch/go-reassign v0.1.2/go.mod h1:bFJIHgtTM3hRm2sKXSPkbwNjSFyGURQXyn4IXD2qwfQ= +github.com/daixiang0/gci v0.6.3 h1:wUAqXChk8HbwXn8AfxD9DYSCp9Bpz1L3e6Q4Roe+q9E= +github.com/daixiang0/gci v0.6.3/go.mod h1:EpVfrztufwVgQRXjnX4zuNinEpLj5OmMjtu/+MB0V0c= 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= @@ -360,7 +330,6 @@ github.com/dghubble/oauth1 v0.7.1 h1:JjbOVSVVkms9A4h/sTQy5Jb2nFuAAVb2qVYgenJPyrE github.com/dghubble/oauth1 v0.7.1/go.mod h1:0eEzON0UY/OLACQrmnjgJjmvCGXzjBCsZqL1kWDXtF0= github.com/dghubble/sling v1.4.0 h1:/n8MRosVTthvMbwlNZgLx579OGVjUOy3GNEv5BIqAWY= github.com/dghubble/sling v1.4.0/go.mod h1:0r40aNsU9EdDUVBNhfCstAtFgutjgJGYbO1oNzkMoM8= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi/U= github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= @@ -373,8 +342,6 @@ github.com/disgoorg/snowflake/v2 v2.0.0/go.mod h1:SPU9c2CNn5DSyb86QcKtdZgix9osEt github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/dnephin/pflag v1.0.7 h1:oxONGlWxhmUct0YzKTgrpQv9AUA1wtPBn7zuSjJqptk= github.com/dnephin/pflag v1.0.7/go.mod h1:uxE91IoWURlOiTUIA8Mq5ZZkAv3dPUfZNaT80Zm7OQE= -github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg= github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -386,41 +353,36 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= -github.com/envoyproxy/protoc-gen-validate v0.0.14/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= 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.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= 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.1 h1:fSvcq6ZpK/uBAgJEGMvzErlzyM4NELLqqdTofVjVNag= -github.com/firefart/nonamedreturns v1.0.1/go.mod h1:D3dpIBojGGNh5UfElmwPu73SwDCm+VKhHYqwlNOk2uQ= +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/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= -github.com/fullstorydev/grpcurl v1.6.0/go.mod h1:ZQ+ayqbKMJNhzLmbpCiurTVlaK2M/3nqZCxaQ2Ze/sM= -github.com/fzipp/gocyclo v0.5.1 h1:L66amyuYogbxl0j2U+vGqJXusPF2IkduvXLnYD5TFgw= -github.com/fzipp/gocyclo v0.5.1/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= +github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo= +github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= github.com/gin-gonic/gin v1.7.3/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= -github.com/go-critic/go-critic v0.6.3 h1:abibh5XYBTASawfTQ0rA7dVtQT+6KzpGqb/J+DxRDaw= -github.com/go-critic/go-critic v0.6.3/go.mod h1:c6b3ZP1MQ7o6lPR7Rv3lEf7pYQUmAcx8ABHgdZCQt/k= +github.com/go-critic/go-critic v0.6.4 h1:tucuG1pvOyYgpBIrVxw0R6gwO42lNa92Aq3VaDoIs+E= +github.com/go-critic/go-critic v0.6.4/go.mod h1:qL5SOlk7NtY6sJPoVCTKDIgzNOxHkkkOCVDyi9wJe1U= github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= github.com/go-git/go-billy/v5 v5.2.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= @@ -445,23 +407,22 @@ github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTM github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= -github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible h1:2cauKuaELYAEARXRkq2LrJ0yDDv1rW7+wrTEdVL3uaU= github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible/go.mod h1:qf9acutJ8cwBUhm1bqgz6Bei9/C/c93FPDljKWwsOgM= github.com/go-test/deep v1.0.4 h1:u2CU3YKy9I2pmu9pX0eq50wCgjfGIt539SqR7FbHiho= github.com/go-test/deep v1.0.4/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= github.com/go-toolsmith/astcast v1.0.0 h1:JojxlmI6STnFVG9yOImLeGREv8W2ocNUM+iOhR6jE7g= github.com/go-toolsmith/astcast v1.0.0/go.mod h1:mt2OdQTeAQcY4DQgPSArJjHCcOwlX+Wl/kwN+LbLGQ4= -github.com/go-toolsmith/astcopy v1.0.0 h1:OMgl1b1MEpjFQ1m5ztEO06rz5CUd3oBv9RF7+DyvdG8= github.com/go-toolsmith/astcopy v1.0.0/go.mod h1:vrgyG+5Bxrnz4MZWPF+pI4R8h3qKRjjyvV/DSez4WVQ= +github.com/go-toolsmith/astcopy v1.0.1 h1:l09oBhAPyV74kLJ3ZO31iBU8htZGTwr9LTjuMCyL8go= +github.com/go-toolsmith/astcopy v1.0.1/go.mod h1:4TcEdbElGc9twQEYpVo/aieIXfHhiuLh4aLAck6dO7Y= github.com/go-toolsmith/astequal v1.0.0/go.mod h1:H+xSiq0+LtiDC11+h1G32h7Of5O3CYFJ99GVbS5lDKY= -github.com/go-toolsmith/astequal v1.0.1 h1:JbSszi42Jiqu36Gnf363HWS9MTEAz67vTQLponh3Moc= github.com/go-toolsmith/astequal v1.0.1/go.mod h1:4oGA3EZXTVItV/ipGiOx7NWkY5veFfcsOJVS2YxltLw= +github.com/go-toolsmith/astequal v1.0.2 h1:+XvaV8zNxua+9+Oa4AHmgmpo4RYAbwr/qjNppLfX2yM= +github.com/go-toolsmith/astequal v1.0.2/go.mod h1:9Ai4UglvtR+4up+bAD4+hCj7iTo4m/OXVTSLnCyTAx4= github.com/go-toolsmith/astfmt v1.0.0 h1:A0vDDXt+vsvLEdbMFJAUBI/uTbRw1ffOPnxsILnFL6k= github.com/go-toolsmith/astfmt v1.0.0/go.mod h1:cnWmsOAuq4jJY6Ct5YWlVLmcmLMn1JUPuQIHCY7CJDw= github.com/go-toolsmith/astp v1.0.0 h1:alXE75TXgcmupDsMK1fRAy0YUzLzqPVvBKoyWV+KPXg= @@ -484,17 +445,12 @@ github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= -github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.4.1 h1:pC5DB52sCeK48Wlb9oPcdhnjkz1TKt1D/P7WKJ0kUcQ= github.com/golang-jwt/jwt/v4 v4.4.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -509,7 +465,6 @@ github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= -github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -537,22 +492,20 @@ github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe h1:6RGUuS7EGotKx6 github.com/golangci/go-misc v0.0.0-20220329215616-d24fe342adfe/go.mod h1:gjqyPShc/m8pEMpk0a3SeagVb0kaqvhscv+i9jI5ZhQ= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a h1:iR3fYXUjHCR97qWS8ch1y9zPNsgXThGwjKPrYfqMPks= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= -github.com/golangci/golangci-lint v1.46.2 h1:o90t/Xa6dhJbvy8Bz2RpzUXqrkigp19DLStMolTZbyo= -github.com/golangci/golangci-lint v1.46.2/go.mod h1:3DkdHnxn9eoTTrpT2gB0TEv8KSziuoqe9FitgQLHvAY= +github.com/golangci/golangci-lint v1.49.0 h1:I8WHOavragDttlLHtSraHn/h39C+R60bEQ5NoGcHQr8= +github.com/golangci/golangci-lint v1.49.0/go.mod h1:+V/7lLv449R6w9mQ3WdV0EKh7Je/jTylMeSwBZcLeWE= 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.3.5 h1:pLzmVdl3VxTOncgzHcvLOKirdvcx/TydsClUQXTehjo= github.com/golangci/misspell v0.3.5/go.mod h1:dEbvlSfYbMQDtrpRMQU675gSDLDNa8sCPPChZ7PhiVA= -github.com/golangci/revgrep v0.0.0-20210930125155-c22e5001d4f2 h1:SgM7GDZTxtTTQPU84heOxy34iG5Du7F2jcoZnvp+fXI= -github.com/golangci/revgrep v0.0.0-20210930125155-c22e5001d4f2/go.mod h1:LK+zW4MpyytAWQRz0M4xnzEk50lSvqDQKfx304apFkY= +github.com/golangci/revgrep v0.0.0-20220804021717-745bb2f7c2e6 h1:DIPQnGy2Gv2FSA4B/hh8Q7xx3B7AIDk3DAMeHclH1vQ= +github.com/golangci/revgrep v0.0.0-20220804021717-745bb2f7c2e6/go.mod h1:0AKcRCkMoKvUvlf89F6O7H2LYdhr1zBh736mBItOdRs= 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/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/certificate-transparency-go v1.0.21/go.mod h1:QeJfpSbVSfYc7RgB3gJFj9cbuQMMchQxrWXz8Ruopmg= -github.com/google/certificate-transparency-go v1.1.1/go.mod h1:FDKqPvSXawb2ecErVRrD+nfy23RCzyl7eqVCEmlT1Zs= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -591,14 +544,12 @@ github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= 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-20200507031123-427632fa3b1c/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-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210506205249-923b5ab0fc1a/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= @@ -609,10 +560,6 @@ github.com/google/rpmpack v0.0.0-20220314092521-38642b5e571e/go.mod h1:83rLnx5vh github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= -github.com/google/trillian v1.3.11/go.mod h1:0tPraVHrSDkA3BO6vKX67zgLXs6SsOAbHEivX+9mPgw= -github.com/google/uuid v0.0.0-20161128191214-064e2069ce9c/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= @@ -632,9 +579,7 @@ github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK github.com/googleapis/go-type-adapters v1.0.0 h1:9XdMn+d/G57qq1s8dNc5IesGCXHf6V2HZ2JwRxfA2tA= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= -github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= -github.com/gordonklaus/ineffassign v0.0.0-20200309095847-7953dde2c7bf/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU= github.com/gordonklaus/ineffassign v0.0.0-20210914165742-4cc7213b9bc8 h1:PVRE9d4AQKmbelZ7emNig1+NT27DUmKZn5qXxfio54U= github.com/gordonklaus/ineffassign v0.0.0-20210914165742-4cc7213b9bc8/go.mod h1:Qcp2HIAYhR7mNUVSIxZww3Guk4it82ghYcEXIAk+QT0= github.com/goreleaser/chglog v0.2.2 h1:V7nf07baXtGAgGevvqgW2MM4kZ6gOr12vKNSAU3VIZ0= @@ -645,9 +590,6 @@ github.com/goreleaser/goreleaser v1.11.2 h1:LqKj+63p60dRF3PA15+y+DN9jP6IMrxvyOpZ github.com/goreleaser/goreleaser v1.11.2/go.mod h1:JrU2vIev2RCFSwSQpnb/8QxC7juX3F8VzY/05y5KEvo= github.com/goreleaser/nfpm/v2 v2.18.1 h1:TuZQvnOLCXVv/wdDwS1luoQKRQo0vtjwP09YWcXMhR8= github.com/goreleaser/nfpm/v2 v2.18.1/go.mod h1:CCNOctcFfuzGLbaA8D4trDCa4xfSMtp9uoempUcG8gE= -github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75/go.mod h1:g2644b03hfBX9Ov0ZBDgXXens4rxSxmqFBbhvKv2yVA= -github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= @@ -667,60 +609,29 @@ 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/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/grpc-ecosystem/grpc-gateway v1.12.1/go.mod h1:8XEsbTttt/W+VvjtQhLACqCisSPWTxCZ7sBRjU6iH9c= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hanwen/go-fuse v1.0.0/go.mod h1:unqXarDXqzAk0rt98O2tVndEPIpUgLD9+rwFisZH3Ok= github.com/hanwen/go-fuse/v2 v2.1.0/go.mod h1:oRyA5eK+pvJyv5otpO/DgccS8y/RvYMaO00GgRLGryc= -github.com/hashicorp/consul/api v1.12.0/go.mod h1:6pVBMo0ebnYdt2S3H87XhekM/HHrUoTD2XXb/VrZVy0= -github.com/hashicorp/consul/sdk v0.8.0/go.mod h1:GBvyrGALthsZObzUGsfgHZQDXjg4lOjagTIwIR1vPms= 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-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= -github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-hclog v1.2.0 h1:La19f8d7WIlm4ogzNHB0JGqs5AUDAZ2UfCY4sJXcJdM= -github.com/hashicorp/go-hclog v1.2.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= 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/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-retryablehttp v0.7.1 h1:sUiuQAnLlbvmExtFQs72iFW/HXeUn8Z1aJLQ4LJJbTQ= github.com/hashicorp/go-retryablehttp v0.7.1/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= -github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.4.0 h1:aAQzgqIrRKRa7w75CKpbBxYsmUoPjzVm1W59ca1L0J4= -github.com/hashicorp/go-version v1.4.0/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/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/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc= -github.com/hashicorp/memberlist v0.3.0/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= -github.com/hashicorp/serf v0.9.6/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= -github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= 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/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= -github.com/huandu/xstrings v1.2.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/iancoleman/orderedmap v0.0.0-20190318233801-ac98e3ecb4b0/go.mod h1:N0Wam8K1arqPXNWjMo21EXnBPOPp36vB07FNRdD2geA= @@ -728,8 +639,6 @@ github.com/iancoleman/orderedmap v0.2.0 h1:sq1N/TFpYH++aViPcaKjys3bDClUEU7s5B+z6 github.com/iancoleman/orderedmap v0.2.0/go.mod h1:N0Wam8K1arqPXNWjMo21EXnBPOPp36vB07FNRdD2geA= 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/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= @@ -781,26 +690,21 @@ github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/jgautheron/goconst v1.5.1 h1:HxVbL1MhydKs8R8n/HE5NPvzfaYmQJA3o879lE4+WcM= github.com/jgautheron/goconst v1.5.1/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= -github.com/jhump/protoreflect v1.6.1/go.mod h1:RZQ/lnuN+zqeRVpQigTwO6o0AJUkxbnSnpuG7toUTG4= 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/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/jonboulle/clockwork v0.2.0/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= 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.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -808,20 +712,15 @@ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHm github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= -github.com/juju/ratelimit v1.0.1/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 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/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/kevinburke/ssh_config v1.1.0 h1:pH/t1WS9NzT8go394IqZeJTMHVm6Cr6ZJ6AQ+mdNo/o= github.com/kevinburke/ssh_config v1.1.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= -github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/errcheck v1.6.0 h1:YTDO4pNy7AUN/021p+JGHycQyYNIyMoenM1YDVK6RlY= -github.com/kisielk/errcheck v1.6.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/errcheck v1.6.2 h1:uGQ9xI8/pgc9iOoCe7kWQgRE6SBTrCGmTSf0LrEtY7c= +github.com/kisielk/errcheck v1.6.2/go.mod h1:nXw/i/MfnvRHqXa7XXmQMUB0oNFGuBrNI8d8NLy0LPw= github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= @@ -836,7 +735,6 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxv 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.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -844,12 +742,11 @@ github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= 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.2 h1:K4xulKkwOCnT1CDms6Ex3uG1dvSMUUQe9zxgYQgbRXs= -github.com/kulti/thelper v0.6.2/go.mod h1:DsqKShOvP40epevkFrvIwkCMNYxMeTNjdWL4dqWHZ6I= -github.com/kunwardeep/paralleltest v1.0.3 h1:UdKIkImEAXjR1chUWLn+PNXqWUGs//7tzMeWuP7NhmI= -github.com/kunwardeep/paralleltest v1.0.3/go.mod h1:vLydzomDFpk7yu5UX02RmP0H8QfRPOV/oFhWN85Mjb4= +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.6 h1:FCKYMF1OF2+RveWlABsdnmsvJrei5aoyZoaGS+Ugg8g= +github.com/kunwardeep/paralleltest v1.0.6/go.mod h1:Y0Y0XISdZM5IKm3TREQMZ6iteqn1YuwCsJO/0kL9Zes= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/kyoh86/exportloopref v0.1.8 h1:5Ry/at+eFdkX9Vsdw3qU4YkvGtzuVfzT4X7S77LoN/M= github.com/kyoh86/exportloopref v0.1.8/go.mod h1:1tUcJeiioIs7VWe5gcOObrux3lb66+sBqGZrRkMwPgg= github.com/ldez/gomoddirectives v0.2.3 h1:y7MBaisZVDYmKvt9/l1mjNCiSA1BVn34U0ObUcJwlhA= @@ -859,23 +756,19 @@ github.com/ldez/tagliatelle v0.3.1/go.mod h1:8s6WJQwEYHbKZDsp/LjArytKOG8qaMrKQQ3 github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/leonklingele/grouper v1.1.0 h1:tC2y/ygPbMFSBOs3DcyaEMKnnwH7eYKzohOtRrf0SAg= github.com/leonklingele/grouper v1.1.0/go.mod h1:uk3I3uDfi9B6PeUjsCKi6ndcf63Uy7snXgR4yDYQVDY= -github.com/letsencrypt/pkcs11key/v4 v4.0.0/go.mod h1:EFUvBDay26dErnNb70Nd0/VW3tJiIbETBPTl9ATXQag= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lib/pq v1.9.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 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/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= -github.com/maratori/testpackage v1.0.1 h1:QtJ5ZjqapShm0w5DosRjg0PRlSdAdlx+W6cCKoALdbQ= -github.com/maratori/testpackage v1.0.1/go.mod h1:ddKdw+XG0Phzhx8BFDTKgpWP4i7MpApTE5fXSKAqwDU= +github.com/maratori/testpackage v1.1.0 h1:GJY4wlzQhuBusMF1oahQCBtUV/AQ/k69IZ68vxaac2Q= +github.com/maratori/testpackage v1.1.0/go.mod h1:PeAhzU8qkCwdGEMTEupsHJNlQu2gZopMC6RjbhmHeDc= github.com/matm/gocov-html v0.0.0-20200509184451-71874e2e203b h1:5Wc/N1FIBnExmX0/SEdKe0A0COvdJc3rCGHQ7s1oBPQ= github.com/matm/gocov-html v0.0.0-20200509184451-71874e2e203b/go.mod h1:zha4ZSIA/qviBBKx3j6tJG/Lx6aIdjOXPWuKAcJchQM= github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 h1:pWxk9e//NbPwfxat7RXkts09K+dEBJWakUWwICVqYbA= @@ -883,29 +776,20 @@ github.com/matoous/godox v0.0.0-20210227103229-6504466cf951/go.mod h1:1BELzlh859 github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA= github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE= github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= -github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +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-ieproxy v0.0.1 h1:qiyop7gCflfhwCzGyeT0gro3sF9AIg9HU98JORTkqfI= github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= -github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= @@ -917,29 +801,16 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0j 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/dots v0.0.0-20210922191527-e955255bf517/go.mod h1:KQ7+USdGKfpPjXk4Ga+5XxQM4Lm4e3gAogrreFAYpOg= -github.com/mgechev/revive v1.2.1 h1:GjFml7ZsoR0IrQ2E2YIvWFNS5GPDV7xNwvA5GM1HZC4= -github.com/mgechev/revive v1.2.1/go.mod h1:+Ro3wqY4vakcYNtkBWdZC7dBg1xSB6sp054wWwmeFm0= -github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= -github.com/miekg/dns v1.1.35/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM= -github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= -github.com/miekg/pkcs11 v1.0.2/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= -github.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= -github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= -github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mgechev/revive v1.2.3 h1:NzIEEa9+WimQ6q2Ov7OcNeySS/IOcwtkQ8RAh0R5UJ4= +github.com/mgechev/revive v1.2.3/go.mod h1:iAWlQishqCuj4yhV24FTnKSXGpbAA+0SckXB8GQMX/Q= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= 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/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -948,11 +819,8 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN 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/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= -github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/moricho/tparallel v0.2.1 h1:95FytivzT6rYzdJLdtfn6m1bfFJylOJK41+lgv/EHf4= github.com/moricho/tparallel v0.2.1/go.mod h1:fXEIZxG2vdfl0ZF8b42f5a78EhjjD5mX8qUplsoSU4k= -github.com/mozilla/scribe v0.0.0-20180711195314-fb71baf557c1/go.mod h1:FIczTrinKo8VaLxe6PWTPEXRXDIHz2QAwiaBaP5/4a8= -github.com/mozilla/tls-observatory v0.0.0-20210609171429-7bc42856d2e5/go.mod h1:FUqVoUPHSEdDR0MnFM3Dh8AU0pZHLXUD127SAJGER/s= github.com/muesli/mango v0.1.0 h1:DZQK45d2gGbql1arsYA4vfg4d7I9Hfx5rX/GCmzsAvI= github.com/muesli/mango v0.1.0/go.mod h1:5XFpbC8jY5UUv89YQciiXNlbi+iJgt29VDC5xbzrLL4= github.com/muesli/mango-cobra v1.2.0 h1:DQvjzAM0PMZr85Iv9LIMaYISpTOliMEg+uMFtNbYvWg= @@ -967,79 +835,47 @@ github.com/muesli/termenv v0.12.1-0.20220615005108-4e9068de9898 h1:0j+cbZdhLgpNx github.com/muesli/termenv v0.12.1-0.20220615005108-4e9068de9898/go.mod h1:bN6sPNtkiahdhHv2Xm6RGU16LSCxfbIZvMfqjOCfrR4= 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/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= -github.com/mwitkow/go-proto-validators v0.2.0/go.mod h1:ZfA1hW+UH/2ZHOWvQ3HnQaU0DtnpXu850MZiy+YUgcc= github.com/nakabonne/nestif v0.3.1 h1:wm28nZjhQY5HyYPx+weN3Q65k6ilSBxDb8v5S81B81U= github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE= github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 h1:4kuARK6Y6FxaNu/BnU2OAaLF86eTVhP2hjTB6iMvItA= github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354/go.mod h1:KSVJerMDfblTH7p5MZaTt+8zaT2iEk3AkVb9PQdZuE8= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/nishanths/exhaustive v0.7.11 h1:xV/WU3Vdwh5BUH4N06JNUznb6d5zhRPOnlgCrpNYNKA= -github.com/nishanths/exhaustive v0.7.11/go.mod h1:gX+MP7DWMKJmNa1HfMozK+u04hQd3na9i0hyqf3/dOI= -github.com/nishanths/predeclared v0.0.0-20190419143655-18a43bb90ffc/go.mod h1:62PewwiQTlm/7Rj+cxVYqZvDIUc+JjZq6GHAC1fsObQ= +github.com/nishanths/exhaustive v0.8.1 h1:0QKNascWv9qIHY7zRoZSxeRr6kuk5aAT3YXLTiDmjTo= +github.com/nishanths/exhaustive v0.8.1/go.mod h1:qj+zJJUgJ76tR92+25+03oYUhzF4R7/2Wk7fGTfCHmg= 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/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= -github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/obalunenko/coverbadger v1.2.0 h1:MI69h8POfZrnSpiC8BUS8f3fHYiznngCVbIpNAgVpCI= github.com/obalunenko/coverbadger v1.2.0/go.mod h1:wzzMrsejYp8/+MpRPDzELQo1YUYvCrqx4ze2d+91bpE= github.com/obalunenko/version v1.1.0 h1:yVua7OHnK3+MJpendeMmAlfzVmq7R1h8MO3Ufz7HEec= github.com/obalunenko/version v1.1.0/go.mod h1:Or267aCQxNcAtgOeWA7yOe/RqJS4XDaMfcFwk3ohbOg= -github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.2/go.mod h1:rSAaSIOAGT9odnlyGlUfAJaoc5w2fSBUmeGDbRWPxyQ= 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 v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= -github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= -github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= -github.com/onsi/ginkgo/v2 v2.1.3 h1:e/3Cwtogj0HA+25nMP1jCMDIf8RtRYbGwGGuBIFztkc= -github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= -github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE= -github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs= -github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/onsi/ginkgo/v2 v2.1.4 h1:GNapqRSid3zijZ9H77KrgVG4/8KqiyRsxcSxe+7ApXY= +github.com/onsi/gomega v1.20.0 h1:8W0cWlwFkflGPLltQvLRB7ZVD5HuP6ng320w2IS245Q= github.com/otiai10/copy v1.2.0 h1:HvG945u96iNadPoG2/Ja2+AUJeW5YuFQMixq9yirC+k= github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw= 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/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= 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.0-beta.8/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= -github.com/pelletier/go-toml/v2 v2.0.0/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= -github.com/pelletier/go-toml/v2 v2.0.1 h1:8e3L2cCQzLFi2CR4g7vGFuFxX7Jl1kKX8gW+iV0GUKU= -github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= -github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/pelletier/go-toml/v2 v2.0.2 h1:+jQXlF3scKIcSEKkdHzXhCTDLPFi5r1wnK6yPS+49Gw= +github.com/pelletier/go-toml/v2 v2.0.2/go.mod h1:MovirKjgVRESsAvNZlAjtFwV867yGuwRkXbG66OzopI= github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d h1:CdDQnGF8Nq9ocOS/xlSptM1N3BbrA6/kmaep5ggwaIA= github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw= github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 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 v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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.0.0 h1:pDrQG0lrh68e602Wfp68BlUTRFoHn8PZYAjLgt2LFsM= -github.com/polyfloyd/go-errorlint v1.0.0/go.mod h1:KZy4xxPJyy88/gldCe5OdW6OQRtNO3EZE7hXzmnebgA= -github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= +github.com/polyfloyd/go-errorlint v1.0.2 h1:kp1yvHflYhTmw5m3MmBy8SCyQkKPjwDthVuMH0ug6Yk= +github.com/polyfloyd/go-errorlint v1.0.2/go.mod h1:APVvOesVSAnne5SClsPxPdfvZTVDojXh1/G3qb5wjGI= 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.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= github.com/prometheus/client_golang v1.12.1 h1:ZiaPsmm9uiBeaSMRznKsCDNtPCS0T3JVDGF+06gjBzk= @@ -1050,25 +886,21 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1: github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= github.com/prometheus/common v0.32.1 h1:hWIdL3N2HoUx3B8j3YN9mWor0qhY/NlEKZEaXxuIRh4= github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= 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/pseudomuto/protoc-gen-doc v1.3.2/go.mod h1:y5+P6n3iGrbKG+9O04V5ld71in3v/bX88wUwgt+U8EA= -github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= github.com/quasilyte/go-ruleguard v0.3.1-0.20210203134552-1b5a410e1cc8/go.mod h1:KsAh3x0e7Fkpgs+Q9pNLS5XpFSvYCEVl5gP9Pp1xp30= -github.com/quasilyte/go-ruleguard v0.3.16-0.20220213074421-6aa060fab41a h1:sWFavxtIctGrVs5SYZ5Ml1CvrDAs8Kf5kx2PI3C41dA= -github.com/quasilyte/go-ruleguard v0.3.16-0.20220213074421-6aa060fab41a/go.mod h1:VMX+OnnSw4LicdiEGtRSD/1X8kW7GuEscjYNr4cOIT4= +github.com/quasilyte/go-ruleguard v0.3.17 h1:cDdoaSbQg11LXPDQqiCK54QmQXsEQQCTIgdcpeULGSI= +github.com/quasilyte/go-ruleguard v0.3.17/go.mod h1:sST5PvaR7yb/Az5ksX8oc88usJ4EGjmJv7cK7y3jyig= github.com/quasilyte/go-ruleguard/dsl v0.3.0/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= -github.com/quasilyte/go-ruleguard/dsl v0.3.16/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= +github.com/quasilyte/go-ruleguard/dsl v0.3.21/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= github.com/quasilyte/go-ruleguard/rules v0.0.0-20201231183845-9e62ed36efe1/go.mod h1:7JTjp89EGyU1d6XfBiXihJNG37wB2VRkd125Q1u7Plc= github.com/quasilyte/go-ruleguard/rules v0.0.0-20211022131956-028d6511ab71/go.mod h1:4cgAphtvu7Ftv7vOT2ZOYhC6CvBxZixcasr8qIOTA50= github.com/quasilyte/gogrep v0.0.0-20220120141003-628d8b3623b5 h1:PDWGei+Rf2bBiuZIbZmM20J2ftEy9IeUCHA8HbQqed8= @@ -1080,33 +912,29 @@ github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567/go.mod h1:DWNGW8 github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.8.1 h1:geMPLpDpQOgVyCg5z5GoRwLHepNdb71NXb67XFkP+Eg= -github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= -github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/ryancurrah/gomodguard v1.2.3 h1:ww2fsjqocGCAFamzvv/b8IsRduuHHeK2MHTcTxZTQX8= -github.com/ryancurrah/gomodguard v1.2.3/go.mod h1:rYbA/4Tg5c54mV1sv4sQTP5WOPBcoLtnBZ7/TEhXAbg= +github.com/ryancurrah/gomodguard v1.2.4 h1:CpMSDKan0LtNGGhPrvupAoLeObRFjND8/tU1rEOtBp4= +github.com/ryancurrah/gomodguard v1.2.4/go.mod h1:+Kem4VjWwvFpUJRJSwa16s1tBJe+vbv02+naTow2f6M= github.com/ryanrolds/sqlclosecheck v0.3.0 h1:AZx+Bixh8zdUBxUA1NxbxVAS78vTPq4rCb8OUZI9xFw= github.com/ryanrolds/sqlclosecheck v0.3.0/go.mod h1:1gREqxyTGR3lVtpngyFo3hZAgk0KCtEdgEkHwDbigdA= -github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/sagikazarmark/crypt v0.5.0/go.mod h1:l+nzl7KWh51rpzp2h7t4MZWyiEWdhNpOAnclKvg+mdA= github.com/sanposhiho/wastedassign/v2 v2.0.6 h1:+6/hQIHKNJAUixEj6EmOngGIisyeI+T3335lYTyxRoA= github.com/sanposhiho/wastedassign/v2 v2.0.6/go.mod h1:KyZ0MWTwxxBmfwn33zh3k1dmsbF2ud9pAAGfoLfjhtI= github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b h1:qYTY2tN72LhgDj2rtWG+LI6TXFl2ygFQQ4YezfVaGQE= github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b/go.mod h1:/pA7k3zsXKdjjAiUhB5CjuKib9KJGCaLvZwtxGC8U0s= +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.13.0 h1:uObNudVEEHf6JbOJy5bgKJloA1bWjxR9fwgNFpPzKnI= +github.com/sashamelentyev/usestdlibvars v1.13.0/go.mod h1:D2Wb7niIYmTB+gB8z7kh8tyP5ccof1dQ+SFk+WW5NtY= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/securego/gosec/v2 v2.11.0 h1:+PDkpzR41OI2jrw1q6AdXZCbsNGNGT7pQjal0H0cArI= -github.com/securego/gosec/v2 v2.11.0/go.mod h1:SX8bptShuG8reGC0XS09+a4H2BoWSJi+fscA+Pulbpo= +github.com/securego/gosec/v2 v2.13.1 h1:7mU32qn2dyC81MH9L2kefnQyRMUarfDER3iQyMHcjYM= +github.com/securego/gosec/v2 v2.13.1/go.mod h1:EO1sImBMBWFjOTFzMWfTRrZW6M15gm60ljzrmy/wtHo= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= @@ -1116,48 +944,39 @@ github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9Nz github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= -github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/sivchari/containedctx v1.0.2 h1:0hLQKpgC53OVF1VT7CeoFHk9YKstur1XOgfYIc1yrHI= github.com/sivchari/containedctx v1.0.2/go.mod h1:PwZOeqm4/DLoJOqMSIJs3aKqXRX4YO+uXww087KZ7Bw= -github.com/sivchari/tenv v1.5.0 h1:wxW0mFpKI6DIb3s6m1jCDYvkWXCskrimXMuGd0K/kSQ= -github.com/sivchari/tenv v1.5.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= +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.0 h1:d4laZMBK6jpe5PWepxlV9S+LC0yXqvYHiq8E6ceoVVE= +github.com/sivchari/tenv v1.7.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= github.com/slack-go/slack v0.11.2 h1:IWl90Rk+jqPEVyiBytH27CSN/TFAg2vuDDfoPRog/nc= github.com/slack-go/slack v0.11.2/go.mod h1:hlGi5oXA+Gt+yWTPP0plCdRKmjsDxecdHxYQdlMQKOw= github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sonatard/noctx v0.0.1 h1:VC1Qhl6Oxx9vvWo3UDgrGXYCeKCe3Wbw7qAWL6FrmTY= github.com/sonatard/noctx v0.0.1/go.mod h1:9D2D/EoULe8Yy2joDHJj7bv3sZoq9AaSb8B4lqBjiZI= github.com/sourcegraph/go-diff v0.6.1 h1:hmA1LzxW0n1c3Q4YbrFgg4P99GSnebYa3x8gr0HZqLQ= github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.8.2 h1:xehSyVa0YnHWsJ49JFljMpg1HX19V6NDZ1fkm1Xznbo= github.com/spf13/afero v1.8.2/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo= -github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= 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 v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU= github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= -github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= 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.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= -github.com/spf13/viper v1.11.0/go.mod h1:djo0X/bA5+tYVoCn+C7cAYJGcVn/qYLFTG8gdUsX7Zk= github.com/spf13/viper v1.12.0 h1:CZ7eSOd3kZoaYDLbXnmzgQI5RlciuXBMA+18HwHRfZQ= github.com/spf13/viper v1.12.0/go.mod h1:b6COn30jlNxbm/V2IqWiNWkJ+vZNiMNksliPCiuKtSI= github.com/ssgreg/nlreturn/v2 v2.2.1 h1:X4XDI7jstt3ySqGU86YGAURbxw3oTDPK9sPEi6YEwQ0= @@ -1169,7 +988,6 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.4.0 h1:M2gUjqZET1qApGOWNSnZ49BAIMX4F/1plDv3+l31EJ4= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/testify v0.0.0-20170130113145-4d4bfba8f1d1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.1.4/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= @@ -1179,13 +997,13 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 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.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/subosito/gotenv v1.3.0 h1:mjC+YW8QpAdXibNi+vNWgzmgBH4+5l5dCXv8cNysBLI= -github.com/subosito/gotenv v1.3.0/go.mod h1:YzJjq/33h7nrwdY+iHMhEOEEbW0ovIz0tB6t6PwAXzs= -github.com/sylvia7788/contextcheck v1.0.4 h1:MsiVqROAdr0efZc/fOCt0c235qm9XJqHtWwM+2h2B04= -github.com/sylvia7788/contextcheck v1.0.4/go.mod h1:vuPKJMQ7MQ91ZTqfdyreNKwZjyUg6KO+IebVyQDedZQ= +github.com/subosito/gotenv v1.4.0 h1:yAzM1+SmVcz5R4tXGsNMu1jUl2aOJXoiWUCEwwnGrvs= +github.com/subosito/gotenv v1.4.0/go.mod h1:mZd6rFysKEcUhUHXJk0C/08wAgyDBFuwEYL7vWWGaGo= +github.com/sylvia7788/contextcheck v1.0.6 h1:o2EZgVPyMKE/Mtoqym61DInKEjwEbsmyoxg3VrmjNO4= +github.com/sylvia7788/contextcheck v1.0.6/go.mod h1:9XDxwvxyuKD+8N+a7Gs7bfWLityh5t70g/GjdEt2N2M= github.com/tdakkota/asciicheck v0.1.1 h1:PKzG7JUTUmVspQTDqtkX9eSiLGossXTybutHwTXuO0A= github.com/tdakkota/asciicheck v0.1.1/go.mod h1:yHp0ai0Z9gUljN3o0xMhYJnH/IcvkdTBOX2fmJ93JEM= github.com/technoweenie/multipartstreamer v1.0.1 h1:XRztA5MXiR1TIRHxH2uNxXxaIkKQDeX7m2XsSOlQEnM= @@ -1198,17 +1016,13 @@ github.com/tetafro/godot v1.4.11 h1:BVoBIqAf/2QdbFmSwAWnaIqDivZdOV0ZRwEm6jivLKw= github.com/tetafro/godot v1.4.11/go.mod h1:LR3CJpxDVGlYOWn3ZZg1PgNZdTUvzsZWu8xaEohUpn8= github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 h1:kl4KhGNsJIbDHS9/4U9yQo1UcPQM0kOMJHn29EoH/Ro= github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= -github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/tomarrell/wrapcheck/v2 v2.6.1 h1:Cf4a/iwuMp9s7kKrh74GTgijRVim0wEpKjgAsT7Wctw= -github.com/tomarrell/wrapcheck/v2 v2.6.1/go.mod h1:Eo+Opt6pyMW1b6cNllOcDSSoHO0aTJ+iF6BfCUbHltA= -github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4= +github.com/timonwong/logrlint v0.1.0 h1:phZCcypL/vtx6cGxObJgWZ5wexZF5SXFPLOM+ru0e/M= +github.com/timonwong/logrlint v0.1.0/go.mod h1:Zleg4Gw+kRxNej+Ra7o+tEaW5k1qthTaYKU7rSD39LU= +github.com/tomarrell/wrapcheck/v2 v2.6.2 h1:3dI6YNcrJTQ/CJQ6M/DUkc0gnqYSIk6o0rChn9E/D0M= +github.com/tomarrell/wrapcheck/v2 v2.6.2/go.mod h1:ao7l5p0aOlUNJKI0qVwB4Yjlqutd0IvAB9Rdwyilxvg= github.com/tommy-muehle/go-mnd/v2 v2.5.0 h1:iAj0a8e6+dXSL7Liq0aXPox36FiN1dBbjA6lt9fl65s= github.com/tommy-muehle/go-mnd/v2 v2.5.0/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= -github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= github.com/ulikunitz/xz v0.5.10 h1:t92gobL9l3HE202wg3rlk19F6X+JOxl9BBrCCMYEYd8= github.com/ulikunitz/xz v0.5.10/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= @@ -1216,11 +1030,8 @@ github.com/ultraware/funlen v0.0.3 h1:5ylVWm8wsNwH5aWo9438pwvsK0QiqVuUrt9bn7S/iL github.com/ultraware/funlen v0.0.3/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= 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/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/uudashr/gocognit v1.0.5 h1:rrSex7oHr3/pPLQ0xoWq108XMU8s678FJcQ+aSfOHa4= -github.com/uudashr/gocognit v1.0.5/go.mod h1:wgYz0mitoKOTysqxTDMOUXg+Jb5SvtihkfmugIZYpEA= -github.com/viki-org/dnscache v0.0.0-20130720023526-c70c1f23c5d8/go.mod h1:dniwbG03GafCjFohMDmz6Zc6oCuiqgH6tGNyXTkHzXE= +github.com/uudashr/gocognit v1.0.6 h1:2Cgi6MweCsdB6kpcVQp7EW4U23iBFQWfTXiWlyp842Y= +github.com/uudashr/gocognit v1.0.6/go.mod h1:nAIUuVBnYU7pcninia3BHOvQkpQCeO76Uscky5BOwcY= github.com/withfig/autocomplete-tools/integrations/cobra v1.2.1 h1:+dBg5k7nuTE38VVdoroRsT0Z88fmvdYrI2EjzJst35I= github.com/withfig/autocomplete-tools/integrations/cobra v1.2.1/go.mod h1:nmuySobZb4kFgFy6BptpXp/BBw+xFSyvVPP6auoJB4k= github.com/xanzy/go-gitlab v0.73.1 h1:UMagqUZLJdjss1SovIC+kJCH4k2AZWXl58gJd38Y/hI= @@ -1229,35 +1040,22 @@ github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6e github.com/xanzy/ssh-agent v0.3.1 h1:AmzO1SSWxw73zxFZPRwaMN1MohDw8UyHnmuxyceTEGo= github.com/xanzy/ssh-agent v0.3.1/go.mod h1:QIE4lCeL7nkC25x+yA3LBIYfwCc1TFziCtG7cBAac6w= github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= -github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= 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/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= -github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= -github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= 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= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.4.0/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= github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= -gitlab.com/bosi/decorder v0.2.1 h1:ehqZe8hI4w7O4b1vgsDZw1YU1PE7iJXrQWFMsocbQ1w= -gitlab.com/bosi/decorder v0.2.1/go.mod h1:6C/nhLSbF6qZbYD8bRmISBwc6vcWdNsiIBkRvjJFrH0= +gitlab.com/bosi/decorder v0.2.3 h1:gX4/RgK16ijY8V+BRQHAySfQAb354T7/xQpDB2n10P0= +gitlab.com/bosi/decorder v0.2.3/go.mod h1:9K1RB5+VPNQYtXtTDAzd2OEftsZb1oV0IrJrzChSdGE= gitlab.com/digitalxero/go-conventional-commit v1.0.7 h1:8/dO6WWG+98PMhlZowt/YjuiKhqhGlOCwlIV8SqqGh8= gitlab.com/digitalxero/go-conventional-commit v1.0.7/go.mod h1:05Xc2BFsSyC5tKhK0y+P3bs0AwUtNuTp+mTpbCU/DZ0= -go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= -go.etcd.io/etcd v0.0.0-20200513171258-e048e166ab9c/go.mod h1:xCI7ZzBfRuGgBXyXO6yfWfDmlWd35khcWpUa4L0xI/k= -go.etcd.io/etcd/api/v3 v3.5.2/go.mod h1:5GB2vv4A4AOn3yk7MftYGHkUfGtDHnEraIjym4dYz5A= -go.etcd.io/etcd/client/pkg/v3 v3.5.2/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= -go.etcd.io/etcd/client/v2 v2.305.2/go.mod h1:2D7ZejHVMIfog1221iLSYlQRzrtECw3kz4I4VAQm3qI= -go.mozilla.org/mozlog v0.0.0-20170222151521-4bb13139d403/go.mod h1:jHoPAGnDrCy6kaI2tAze5Prf0Nr0w/oNkROt2lw3n3o= go.opencensus.io v0.15.0/go.mod h1:UffZAU+4sDEINUGP/B7UfBBkq4fqLu9zXAX7ke6CHW0= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= @@ -1273,38 +1071,36 @@ go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +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.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= -go.uber.org/multierr v1.4.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8= go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= -go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= +go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= gocloud.dev v0.26.0 h1:4rM/SVL0lLs+rhC0Gmc+gt/82DBpb7nbpIZKXXnfMXg= gocloud.dev v0.26.0/go.mod h1:mkUgejbnbLotorqDyvedJO20XcZNTynmSeVSQS9btVg= -golang.org/x/crypto v0.0.0-20180501155221-613d6eafa307/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= 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-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= @@ -1312,10 +1108,9 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y 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.0.0-20211115234514-b4de73f9ece8/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220313003712-b769efc7c000/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA= -golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa h1:zuSxTR4o9y82ebqCUJYNGJbGPo6sKVl54f/TVDObg1c= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 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= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1326,9 +1121,11 @@ 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-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= -golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e h1:qyrTQ++p1afMkO4DPEeLGq/3oTsdlvdH4vqZUBWzUKM= -golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= +golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA= +golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA= +golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= +golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d h1:+W8Qf4iJtMGKkyAygcKohjxTk4JPsL9DpzApJ22m5Ic= +golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d/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= @@ -1356,13 +1153,12 @@ 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.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= -golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 h1:kQgndtyPBW/JIYERgdxfwMYh3AVStj88WQTlNDi2a+o= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 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-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -1375,8 +1171,6 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191112182307-2180aed22343/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -1385,11 +1179,9 @@ golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= @@ -1404,12 +1196,9 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211020060615-d418f374d309/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -1420,6 +1209,7 @@ golang.org/x/net v0.0.0-20220401154927-543a649e0bdd/go.mod h1:CfG3xpIq0wQ8r1q4Su golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48 h1:N9Vc/rorQUDes6B9CNdIxAn5jODGj2wzfrei2x4wNj4= golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -1450,7 +1240,6 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1458,15 +1247,12 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f h1:Ax0t5p6N38Ga0dThY21weqDEyz2oklo4IvDkpigvkD8= golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 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-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1479,31 +1265,23 @@ golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191112214154-59a1497f0cea/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1517,18 +1295,15 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w 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-20210112080510-489259a85091/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-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/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-20210502180810-71e4cd670f79/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1541,18 +1316,15 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211105183446-c75c47738b0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1562,13 +1334,15 @@ golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f/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-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/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-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 h1:WIoqL4EROvwiPdUtaip4VcDdpZ4kha7wBWZrbVKCIZg= -golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/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 h1:2QkjZIsXupsJbJIdSjjUOgWK3aEtzyuh2mPt3l/CkeU= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= @@ -1583,19 +1357,15 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 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= -golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20220224211638-0e9765cccd65/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 h1:ftMN5LMiBFjbzleLqtoBZk7KdJwhuybIU+FckUHgoyQ= golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190307163923-6a08e3108db3/go.mod h1:25r3+/G6/xytQM8iWZKq3Hn0kr0rgFKPUNVEL/dr3z4= @@ -1617,11 +1387,9 @@ golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190910044552-dd2b5c81c578/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190916130336-e45ffcd953cc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191010075000-0337d82405ff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -1631,7 +1399,6 @@ golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -1651,19 +1418,13 @@ golang.org/x/tools v0.0.0-20200325010219-a49f79bcc224/go.mod h1:Sl4aGygMT6LrqrWc golang.org/x/tools v0.0.0-20200329025819-fd4102a86c65/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200414032229-332987a829c3/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200426102838-f3a5411a4c3b/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200622203043-20e05c1c8ffa/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624225443-88f3c62a19ff/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200625211823-6506e20df31f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200626171337-aa94e735be7f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200630154851-b2d8b0336632/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200706234117-b22de6825cf7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= @@ -1678,10 +1439,8 @@ golang.org/x/tools v0.0.0-20201023174141-c8cfbd0f21e6/go.mod h1:emZCQorbCU4vsT4f 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-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201230224404-63754364767c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/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= @@ -1691,13 +1450,12 @@ golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= -golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.9-0.20211228192929-ee1ca4ffc4da/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= 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-0.20220316014157-77aa08bb151a h1:ofrrl6c6NG5/IOSx/R1cyiQxxjqlur0h/TvbUhkH0II= -golang.org/x/tools v0.1.11-0.20220316014157-77aa08bb151a/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= +golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= +golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1712,7 +1470,6 @@ google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEt google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.10.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= @@ -1760,14 +1517,11 @@ google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9Ywl 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.2/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 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181107211654-5fc9ac540362/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= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -1775,7 +1529,6 @@ google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRn google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= @@ -1789,15 +1542,12 @@ google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200626011028-ee7919e894b5/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200707001353-8e8330bf89df/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= 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= @@ -1867,19 +1617,15 @@ google.golang.org/genproto v0.0.0-20220523171625-347a074981d8/go.mod h1:RAyBrSAP google.golang.org/genproto v0.0.0-20220608133413-ed9918b62aac/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= google.golang.org/genproto v0.0.0-20220616135557-88e70c0c3a90 h1:4SPz2GL2CXJt28MTF8V6Ap/9ZiVbQlJeGSd9qtA7DLs= google.golang.org/genproto v0.0.0-20220616135557-88e70c0c3a90/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= -google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= 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= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.24.0/go.mod h1:XDChyiUovWa60DnaeDeZmSW86xtLtjtZbwvSiRnRtcA= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.0/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= 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= @@ -1929,27 +1675,19 @@ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= -gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= -gopkg.in/ini.v1 v1.66.4 h1:SsAcf+mM7mRZo2nJNGt8mZCjG8ZRaNGMURJw7BsIST4= -gopkg.in/ini.v1 v1.66.4/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.66.6 h1:LATuAqN/shcYAOkv3wl2L4rkaKqkcgTBQjOyYDvcPKI= +gopkg.in/ini.v1 v1.66.6/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mail.v2 v2.3.1 h1:WYFn/oANrAGP2C0dcV6/pbkPzv8yGzqTjPmTeO7qoXk= gopkg.in/mail.v2 v2.3.1/go.mod h1:htwXN1Qh09vZJ1NVKxQqHPBaCBbzKhp5GzuJEA4VJWw= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.6/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= @@ -1970,18 +1708,17 @@ 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.3.1 h1:1kJlrWJLkaGXgcaeosRXViwviqjI7nkBvU2+sZW0AYc= -honnef.co/go/tools v0.3.1/go.mod h1:vlRD9XErLMGT+mDuofSr0mMMquscM/1nQqtRSsh6m70= +honnef.co/go/tools v0.3.3 h1:oDx7VAwstgpYpb3wv0oxiZlxY+foCpRAwY7Vk6XpAgA= +honnef.co/go/tools v0.3.3/go.mod h1:jzwdWgg7Jdq75wlfblQxO4neNaFFSvgc1tD5Wv8U0Yw= mvdan.cc/gofumpt v0.3.1 h1:avhhrOmv0IuvQVK7fvwV91oFSGAk5/6Po8GXTzICeu8= mvdan.cc/gofumpt v0.3.1/go.mod h1:w3ymliuxvzVx8DAutBnVyDqYb1Niy/yCJt/lk821YCE= 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-20211214103731-d0ef000c54e5 h1:Jh3LAeMt1eGpxomyu3jVkmVZWW2MxZ1qIIV2TZ/nRio= -mvdan.cc/unparam v0.0.0-20211214103731-d0ef000c54e5/go.mod h1:b8RRCBm0eeiWR8cfN88xeq2G5SG3VKGO+5UPWi5FSOY= +mvdan.cc/unparam v0.0.0-20220706161116-678bad134442 h1:seuXWbRB1qPrS3NQnHmFKLJLtskWyueeIzmLXghMGgk= +mvdan.cc/unparam v0.0.0-20220706161116-678bad134442/go.mod h1:F/Cxw/6mVrNKqrR2YjFf5CaW0Bw4RL8RfbEf4GRggJk= nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= 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= -sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= diff --git a/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/analyzer.go b/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/analyzer.go index 984a6a9d..6425db13 100644 --- a/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/analyzer.go +++ b/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/analyzer.go @@ -98,7 +98,7 @@ func run(pass *analysis.Pass) (interface{}, error) { ast.Inspect(f, inspectPkgLevelVarsOnly) } - return nil, nil + return nil, nil //nolint:nilnil } func reportAboutErrorType(pass *analysis.Pass, typePos token.Pos, typeName string, isArrayType bool) { diff --git a/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/facts.go b/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/facts.go index ce57159b..8711f9cf 100644 --- a/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/facts.go +++ b/tools/vendor/github.com/Antonboom/errname/pkg/analyzer/facts.go @@ -8,10 +8,10 @@ import ( ) func isMethodError(f *ast.FuncDecl) (typeName string, ok bool) { - if f.Recv == nil { + if f.Recv == nil || len(f.Recv.List) != 1 { return "", false } - if f.Name.Name != "Error" { + if f.Name == nil || f.Name.Name != "Error" { return "", false } @@ -26,13 +26,24 @@ func isMethodError(f *ast.FuncDecl) (typeName string, ok bool) { var receiverType string - switch rt := f.Recv.List[0].Type.(type) { - case *ast.Ident: - receiverType = rt.Name - case *ast.StarExpr: - if i, ok := rt.X.(*ast.Ident); ok { - receiverType = i.Name + unwrapIdentName := func(e ast.Expr) string { + switch v := e.(type) { + case *ast.Ident: + return v.Name + case *ast.IndexExpr: + if i, ok := v.X.(*ast.Ident); ok { + return i.Name + } } + return "" + } + + switch rt := f.Recv.List[0].Type; v := rt.(type) { + case *ast.Ident, *ast.IndexExpr: // SomeError, SomeError[T] + receiverType = unwrapIdentName(rt) + + case *ast.StarExpr: // *SomeError, *SomeError[T] + receiverType = unwrapIdentName(v.X) } return receiverType, returnType.Name == "string" @@ -100,7 +111,7 @@ var knownErrConstructors = stringSet{ "errors.NewAssertionErrorWithWrappedErrf": {}, } -func isSentinelError( //nolint:gocognit +func isSentinelError( //nolint:gocognit,gocyclo v *ast.ValueSpec, pkgAliases map[string]string, allTypes, errorTypes, errorFuncs stringSet, @@ -151,6 +162,7 @@ func isSentinelError( //nolint:gocognit // var ErrEndOfFile = newErrEndOfFile() // var ErrEndOfFile = new(EndOfFileError) // const ErrEndOfFile = constError("end of file") + // var statusCodeError = new(SomePtrError[string]) case *ast.Ident: if isErrorType(fun.Name, allTypes, errorTypes) { return varName, true @@ -161,8 +173,13 @@ func isSentinelError( //nolint:gocognit } if fun.Name == "new" && len(vv.Args) == 1 { - if i, ok := vv.Args[0].(*ast.Ident); ok { + switch i := vv.Args[0].(type) { + case *ast.Ident: return varName, isErrorType(i.Name, allTypes, errorTypes) + case *ast.IndexExpr: + if ii, ok := i.X.(*ast.Ident); ok { + return varName, isErrorType(ii.Name, allTypes, errorTypes) + } } } @@ -172,19 +189,31 @@ func isSentinelError( //nolint:gocognit } // var ErrEndOfFile = &EndOfFileError{} + // var ErrOK = &SomePtrError[string]{Code: "200 OK"} case *ast.UnaryExpr: if vv.Op == token.AND { // & if lit, ok := vv.X.(*ast.CompositeLit); ok { - if i, ok := lit.Type.(*ast.Ident); ok { + switch i := lit.Type.(type) { + case *ast.Ident: return varName, isErrorType(i.Name, allTypes, errorTypes) + case *ast.IndexExpr: + if ii, ok := i.X.(*ast.Ident); ok { + return varName, isErrorType(ii.Name, allTypes, errorTypes) + } } } } // var ErrEndOfFile = EndOfFileError{} + // var ErrNotFound = SomeError[string]{Code: "Not Found"} case *ast.CompositeLit: - if i, ok := vv.Type.(*ast.Ident); ok { + switch i := vv.Type.(type) { + case *ast.Ident: return varName, isErrorType(i.Name, allTypes, errorTypes) + case *ast.IndexExpr: + if ii, ok := i.X.(*ast.Ident); ok { + return varName, isErrorType(ii.Name, allTypes, errorTypes) + } } } diff --git a/tools/vendor/github.com/BurntSushi/toml/.gitignore b/tools/vendor/github.com/BurntSushi/toml/.gitignore index cd11be96..fe79e3ad 100644 --- a/tools/vendor/github.com/BurntSushi/toml/.gitignore +++ b/tools/vendor/github.com/BurntSushi/toml/.gitignore @@ -1,2 +1,2 @@ -toml.test +/toml.test /toml-test diff --git a/tools/vendor/github.com/BurntSushi/toml/COMPATIBLE b/tools/vendor/github.com/BurntSushi/toml/COMPATIBLE deleted file mode 100644 index f621b011..00000000 --- a/tools/vendor/github.com/BurntSushi/toml/COMPATIBLE +++ /dev/null @@ -1 +0,0 @@ -Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0). diff --git a/tools/vendor/github.com/BurntSushi/toml/README.md b/tools/vendor/github.com/BurntSushi/toml/README.md index a999c356..3651cfa9 100644 --- a/tools/vendor/github.com/BurntSushi/toml/README.md +++ b/tools/vendor/github.com/BurntSushi/toml/README.md @@ -1,6 +1,5 @@ TOML stands for Tom's Obvious, Minimal Language. This Go package provides a -reflection interface similar to Go's standard library `json` and `xml` -packages. +reflection interface similar to Go's standard library `json` and `xml` packages. Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0). @@ -10,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; install it with: +This library requires Go 1.13 or newer; add it to your go.mod with: % go get github.com/BurntSushi/toml@latest @@ -19,16 +18,7 @@ It also comes with a TOML validator CLI tool: % go install github.com/BurntSushi/toml/cmd/tomlv@latest % tomlv some-toml-file.toml -### Testing -This package passes all tests in [toml-test] for both the decoder and the -encoder. - -[toml-test]: https://github.com/BurntSushi/toml-test - ### Examples -This package works similar to how the Go standard library handles XML and JSON. -Namely, data is loaded into Go values via reflection. - For the simplest example, consider some TOML file as just a list of keys and values: @@ -40,7 +30,7 @@ Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z ``` -Which could be defined in Go as: +Which can be decoded with: ```go type Config struct { @@ -48,20 +38,15 @@ type Config struct { Cats []string Pi float64 Perfection []int - DOB time.Time // requires `import time` + DOB time.Time } -``` - -And then decoded with: -```go var conf Config _, err := toml.Decode(tomlData, &conf) -// handle error ``` -You can also use struct tags if your struct field name doesn't map to a TOML -key value directly: +You can also use struct tags if your struct field name doesn't map to a TOML key +value directly: ```toml some_key_NAME = "wat" @@ -73,139 +58,63 @@ type TOML struct { } ``` -Beware that like other most other decoders **only exported fields** are -considered when encoding and decoding; private fields are silently ignored. +Beware that like other decoders **only exported fields** are considered when +encoding and decoding; private fields are silently ignored. ### Using the `Marshaler` and `encoding.TextUnmarshaler` interfaces -Here's an example that automatically parses duration strings into -`time.Duration` values: +Here's an example that automatically parses values in a `mail.Address`: ```toml -[[song]] -name = "Thunder Road" -duration = "4m49s" - -[[song]] -name = "Stairway to Heaven" -duration = "8m03s" -``` - -Which can be decoded with: - -```go -type song struct { - Name string - Duration duration -} -type songs struct { - Song []song -} -var favorites songs -if _, err := toml.Decode(blob, &favorites); err != nil { - log.Fatal(err) -} - -for _, s := range favorites.Song { - fmt.Printf("%s (%s)\n", s.Name, s.Duration) -} +contacts = [ + "Donald Duck ", + "Scrooge McDuck ", +] ``` -And you'll also need a `duration` type that satisfies the -`encoding.TextUnmarshaler` interface: +Can be decoded with: ```go -type duration struct { - time.Duration +// Create address type which satisfies the encoding.TextUnmarshaler interface. +type address struct { + *mail.Address } -func (d *duration) UnmarshalText(text []byte) error { +func (a *address) UnmarshalText(text []byte) error { var err error - d.Duration, err = time.ParseDuration(string(text)) + a.Address, err = mail.ParseAddress(string(text)) return err } + +// Decode it. +func decode() { + blob := ` + contacts = [ + "Donald Duck ", + "Scrooge McDuck ", + ] + ` + + var contacts struct { + Contacts []address + } + + _, err := toml.Decode(blob, &contacts) + if err != nil { + log.Fatal(err) + } + + for _, c := range contacts.Contacts { + fmt.Printf("%#v\n", c.Address) + } + + // Output: + // &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"} + // &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"} +} ``` To target TOML specifically you can implement `UnmarshalTOML` TOML interface in a similar way. ### More complex usage -Here's an example of how to load the example from the official spec page: - -```toml -# This is a TOML document. Boom. - -title = "TOML Example" - -[owner] -name = "Tom Preston-Werner" -organization = "GitHub" -bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." -dob = 1979-05-27T07:32:00Z # First class dates? Why not? - -[database] -server = "192.168.1.1" -ports = [ 8001, 8001, 8002 ] -connection_max = 5000 -enabled = true - -[servers] - - # You can indent as you please. Tabs or spaces. TOML don't care. - [servers.alpha] - ip = "10.0.0.1" - dc = "eqdc10" - - [servers.beta] - ip = "10.0.0.2" - dc = "eqdc10" - -[clients] -data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it - -# Line breaks are OK when inside arrays -hosts = [ - "alpha", - "omega" -] -``` - -And the corresponding Go types are: - -```go -type tomlConfig struct { - Title string - Owner ownerInfo - DB database `toml:"database"` - Servers map[string]server - Clients clients -} - -type ownerInfo struct { - Name string - Org string `toml:"organization"` - Bio string - DOB time.Time -} - -type database struct { - Server string - Ports []int - ConnMax int `toml:"connection_max"` - Enabled bool -} - -type server struct { - IP string - DC string -} - -type clients struct { - Data [][]interface{} - Hosts []string -} -``` - -Note that a case insensitive match will be tried if an exact match can't be -found. - -A working example of the above can be found in `_example/example.{go,toml}`. +See the [`_example/`](/_example) directory for a more complex example. diff --git a/tools/vendor/github.com/BurntSushi/toml/decode.go b/tools/vendor/github.com/BurntSushi/toml/decode.go index 6a871507..09523315 100644 --- a/tools/vendor/github.com/BurntSushi/toml/decode.go +++ b/tools/vendor/github.com/BurntSushi/toml/decode.go @@ -3,13 +3,16 @@ package toml import ( "bytes" "encoding" + "encoding/json" "fmt" "io" "io/ioutil" "math" "os" "reflect" + "strconv" "strings" + "time" ) // Unmarshaler is the interface implemented by objects that can unmarshal a @@ -18,7 +21,7 @@ type Unmarshaler interface { UnmarshalTOML(interface{}) error } -// Unmarshal decodes the contents of `p` in TOML format into a pointer `v`. +// Unmarshal decodes the contents of `data` in TOML format into a pointer `v`. func Unmarshal(data []byte, v interface{}) error { _, err := NewDecoder(bytes.NewReader(data)).Decode(v) return err @@ -75,6 +78,9 @@ const ( // TOML datetimes correspond to Go time.Time values. Local datetimes are parsed // in the local timezone. // +// time.Duration types are treated as nanoseconds if the TOML value is an +// integer, or they're parsed with time.ParseDuration() if they're strings. +// // All other TOML types (float, string, int, bool and array) correspond to the // obvious Go types. // @@ -82,7 +88,7 @@ const ( // interface, in which case any primitive TOML value (floats, strings, integers, // booleans, datetimes) will be converted to a []byte and given to the value's // UnmarshalText method. See the Unmarshaler example for a demonstration with -// time duration strings. +// email addresses. // // Key mapping // @@ -111,6 +117,7 @@ func NewDecoder(r io.Reader) *Decoder { var ( unmarshalToml = reflect.TypeOf((*Unmarshaler)(nil)).Elem() unmarshalText = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() + primitiveType = reflect.TypeOf((*Primitive)(nil)).Elem() ) // Decode TOML data in to the pointer `v`. @@ -122,10 +129,10 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { s = "%v" } - return MetaData{}, e("cannot decode to non-pointer "+s, reflect.TypeOf(v)) + return MetaData{}, fmt.Errorf("toml: cannot decode to non-pointer "+s, reflect.TypeOf(v)) } if rv.IsNil() { - return MetaData{}, e("cannot decode to nil value of %q", reflect.TypeOf(v)) + 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 @@ -135,7 +142,7 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map && !(rv.Kind() == reflect.Interface && rv.NumMethod() == 0) && !rt.Implements(unmarshalToml) && !rt.Implements(unmarshalText) { - return MetaData{}, e("cannot decode to type %s", rt) + return MetaData{}, fmt.Errorf("toml: cannot decode to type %s", rt) } // TODO: parser should read from io.Reader? Or at the very least, make it @@ -152,10 +159,11 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) { md := MetaData{ mapping: p.mapping, - types: p.types, + keyInfo: p.keyInfo, keys: p.ordered, decoded: make(map[string]struct{}, len(p.ordered)), context: nil, + data: data, } return md, md.unify(p.mapping, rv) } @@ -185,7 +193,7 @@ func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { func (md *MetaData) unify(data interface{}, rv reflect.Value) error { // Special case. Look for a `Primitive` value. // TODO: #76 would make this superfluous after implemented. - if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { + if rv.Type() == primitiveType { // Save the undecoded data and the key context into the primitive // value. context := make(Key, len(md.context)) @@ -197,17 +205,14 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { return nil } - // Special case. Unmarshaler Interface support. - if rv.CanAddr() { - if v, ok := rv.Addr().Interface().(Unmarshaler); ok { - return v.UnmarshalTOML(data) - } + rvi := rv.Interface() + if v, ok := rvi.(Unmarshaler); ok { + return v.UnmarshalTOML(data) } - - // Special case. Look for a value satisfying the TextUnmarshaler interface. - if v, ok := rv.Interface().(encoding.TextUnmarshaler); ok { + if v, ok := rvi.(encoding.TextUnmarshaler); ok { return md.unifyText(data, v) } + // TODO: // The behavior here is incorrect whenever a Go type satisfies the // encoding.TextUnmarshaler interface but also corresponds to a TOML hash or @@ -218,7 +223,6 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { k := rv.Kind() - // laziness if k >= reflect.Int && k <= reflect.Uint64 { return md.unifyInt(data, rv) } @@ -244,15 +248,14 @@ func (md *MetaData) unify(data interface{}, rv reflect.Value) error { case reflect.Bool: return md.unifyBool(data, rv) case reflect.Interface: - // we only support empty interfaces. - if rv.NumMethod() > 0 { - return e("unsupported type %s", rv.Type()) + if rv.NumMethod() > 0 { // Only support empty interfaces are supported. + return md.e("unsupported type %s", rv.Type()) } return md.unifyAnything(data, rv) case reflect.Float32, reflect.Float64: return md.unifyFloat64(data, rv) } - return e("unsupported type %s", rv.Kind()) + return md.e("unsupported type %s", rv.Kind()) } func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { @@ -261,7 +264,7 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { if mapping == nil { return nil } - return e("type mismatch for %s: expected table but found %T", + return md.e("type mismatch for %s: expected table but found %T", rv.Type().String(), mapping) } @@ -287,13 +290,14 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { if isUnifiable(subv) { md.decoded[md.context.add(key).String()] = struct{}{} md.context = append(md.context, key) + err := md.unify(datum, subv) if err != nil { return err } md.context = md.context[0 : len(md.context)-1] } else if f.name != "" { - return e("cannot write unexported field %s.%s", rv.Type().String(), f.name) + return md.e("cannot write unexported field %s.%s", rv.Type().String(), f.name) } } } @@ -301,10 +305,10 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { } func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { - if k := rv.Type().Key().Kind(); k != reflect.String { - return fmt.Errorf( - "toml: cannot decode to a map with non-string key type (%s in %q)", - k, rv.Type()) + 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{}) @@ -322,13 +326,22 @@ func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { md.context = append(md.context, k) rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) - if err := md.unify(v, rvval); err != nil { + + err := md.unify(v, indirect(rvval)) + if err != nil { return err } md.context = md.context[0 : len(md.context)-1] rvkey := indirect(reflect.New(rv.Type().Key())) - rvkey.SetString(k) + + switch keyType { + case reflect.Interface: + rvkey.Set(reflect.ValueOf(k)) + case reflect.String: + rvkey.SetString(k) + } + rv.SetMapIndex(rvkey, rvval) } return nil @@ -343,7 +356,7 @@ func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { return md.badtype("slice", data) } if l := datav.Len(); l != rv.Len() { - return e("expected array length %d; got TOML array of length %d", rv.Len(), l) + return md.e("expected array length %d; got TOML array of length %d", rv.Len(), l) } return md.unifySliceArray(datav, rv) } @@ -376,6 +389,18 @@ func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { } func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { + _, ok := rv.Interface().(json.Number) + if ok { + if i, ok := data.(int64); ok { + rv.SetString(strconv.FormatInt(i, 10)) + } else if f, ok := data.(float64); ok { + rv.SetString(strconv.FormatFloat(f, 'f', -1, 64)) + } else { + return md.badtype("string", data) + } + return nil + } + if s, ok := data.(string); ok { rv.SetString(s) return nil @@ -384,11 +409,13 @@ func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { } func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { + rvk := rv.Kind() + if num, ok := data.(float64); ok { - switch rv.Kind() { + switch rvk { case reflect.Float32: if num < -math.MaxFloat32 || num > math.MaxFloat32 { - return e("value %f is out of range for float32", num) + return md.parseErr(errParseRange{i: num, size: rvk.String()}) } fallthrough case reflect.Float64: @@ -400,20 +427,11 @@ func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { } if num, ok := data.(int64); ok { - switch rv.Kind() { - case reflect.Float32: - if num < -maxSafeFloat32Int || num > maxSafeFloat32Int { - return e("value %d is out of range for float32", num) - } - fallthrough - case reflect.Float64: - if num < -maxSafeFloat64Int || num > maxSafeFloat64Int { - return e("value %d is out of range for float64", num) - } - rv.SetFloat(float64(num)) - default: - panic("bug") + if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) || + (rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) } + rv.SetFloat(float64(num)) return nil } @@ -421,50 +439,46 @@ func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { } func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { - if num, ok := data.(int64); ok { - if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Int64 { - switch rv.Kind() { - case reflect.Int, reflect.Int64: - // No bounds checking necessary. - case reflect.Int8: - if num < math.MinInt8 || num > math.MaxInt8 { - return e("value %d is out of range for int8", num) - } - case reflect.Int16: - if num < math.MinInt16 || num > math.MaxInt16 { - return e("value %d is out of range for int16", num) - } - case reflect.Int32: - if num < math.MinInt32 || num > math.MaxInt32 { - return e("value %d is out of range for int32", num) - } - } - rv.SetInt(num) - } else if rv.Kind() >= reflect.Uint && rv.Kind() <= reflect.Uint64 { - unum := uint64(num) - switch rv.Kind() { - case reflect.Uint, reflect.Uint64: - // No bounds checking necessary. - case reflect.Uint8: - if num < 0 || unum > math.MaxUint8 { - return e("value %d is out of range for uint8", num) - } - case reflect.Uint16: - if num < 0 || unum > math.MaxUint16 { - return e("value %d is out of range for uint16", num) - } - case reflect.Uint32: - if num < 0 || unum > math.MaxUint32 { - return e("value %d is out of range for uint32", num) - } + _, ok := rv.Interface().(time.Duration) + if ok { + // Parse as string duration, and fall back to regular integer parsing + // (as nanosecond) if this is not a string. + if s, ok := data.(string); ok { + dur, err := time.ParseDuration(s) + if err != nil { + return md.parseErr(errParseDuration{s}) } - rv.SetUint(unum) - } else { - panic("unreachable") + rv.SetInt(int64(dur)) + return nil } - return nil } - return md.badtype("integer", data) + + num, ok := data.(int64) + if !ok { + return md.badtype("integer", data) + } + + rvk := rv.Kind() + switch { + case rvk >= reflect.Int && rvk <= reflect.Int64: + if (rvk == reflect.Int8 && (num < math.MinInt8 || num > math.MaxInt8)) || + (rvk == reflect.Int16 && (num < math.MinInt16 || num > math.MaxInt16)) || + (rvk == reflect.Int32 && (num < math.MinInt32 || num > math.MaxInt32)) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) + } + rv.SetInt(num) + case rvk >= reflect.Uint && rvk <= reflect.Uint64: + unum := uint64(num) + if rvk == reflect.Uint8 && (num < 0 || unum > math.MaxUint8) || + rvk == reflect.Uint16 && (num < 0 || unum > math.MaxUint16) || + rvk == reflect.Uint32 && (num < 0 || unum > math.MaxUint32) { + return md.parseErr(errParseRange{i: num, size: rvk.String()}) + } + rv.SetUint(unum) + default: + panic("unreachable") + } + return nil } func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { @@ -489,7 +503,7 @@ func (md *MetaData) unifyText(data interface{}, v encoding.TextUnmarshaler) erro return err } s = string(text) - case TextMarshaler: + case encoding.TextMarshaler: text, err := sdata.MarshalText() if err != nil { return err @@ -515,7 +529,30 @@ func (md *MetaData) unifyText(data interface{}, v encoding.TextUnmarshaler) erro } func (md *MetaData) badtype(dst string, data interface{}) error { - return e("incompatible types: TOML key %q has type %T; destination has type %s", md.context, data, dst) + return md.e("incompatible types: TOML value has type %T; destination has type %s", data, dst) +} + +func (md *MetaData) parseErr(err error) error { + k := md.context.String() + return ParseError{ + LastKey: k, + Position: md.keyInfo[k].pos, + Line: md.keyInfo[k].pos.Line, + err: err, + input: string(md.data), + } +} + +func (md *MetaData) e(format string, args ...interface{}) error { + f := "toml: " + if len(md.context) > 0 { + f = fmt.Sprintf("toml: (last key %q): ", md.context) + p := md.keyInfo[md.context.String()].pos + if p.Line > 0 { + f = fmt.Sprintf("toml: line %d (last key %q): ", p.Line, md.context) + } + } + return fmt.Errorf(f+format, args...) } // rvalue returns a reflect.Value of `v`. All pointers are resolved. @@ -534,7 +571,11 @@ func indirect(v reflect.Value) reflect.Value { if v.Kind() != reflect.Ptr { if v.CanSet() { pv := v.Addr() - if _, ok := pv.Interface().(encoding.TextUnmarshaler); ok { + pvi := pv.Interface() + if _, ok := pvi.(encoding.TextUnmarshaler); ok { + return pv + } + if _, ok := pvi.(Unmarshaler); ok { return pv } } @@ -550,12 +591,12 @@ func isUnifiable(rv reflect.Value) bool { if rv.CanSet() { return true } - if _, ok := rv.Interface().(encoding.TextUnmarshaler); ok { + rvi := rv.Interface() + if _, ok := rvi.(encoding.TextUnmarshaler); ok { + return true + } + if _, ok := rvi.(Unmarshaler); ok { return true } return false } - -func e(format string, args ...interface{}) error { - return fmt.Errorf("toml: "+format, args...) -} diff --git a/tools/vendor/github.com/BurntSushi/toml/encode.go b/tools/vendor/github.com/BurntSushi/toml/encode.go index e7d4eeb4..dc8568d1 100644 --- a/tools/vendor/github.com/BurntSushi/toml/encode.go +++ b/tools/vendor/github.com/BurntSushi/toml/encode.go @@ -3,6 +3,7 @@ package toml import ( "bufio" "encoding" + "encoding/json" "errors" "fmt" "io" @@ -63,6 +64,12 @@ var dblQuotedReplacer = strings.NewReplacer( "\x7f", `\u007f`, ) +var ( + marshalToml = reflect.TypeOf((*Marshaler)(nil)).Elem() + marshalText = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() + timeType = reflect.TypeOf((*time.Time)(nil)).Elem() +) + // Marshaler is the interface implemented by types that can marshal themselves // into valid TOML. type Marshaler interface { @@ -74,6 +81,9 @@ type Marshaler interface { // The mapping between Go values and TOML values should be precisely the same as // for the Decode* functions. // +// time.Time is encoded as a RFC 3339 string, and time.Duration as its string +// representation. +// // The toml.Marshaler and encoder.TextMarshaler interfaces are supported to // encoding the value as custom TOML. // @@ -85,6 +95,17 @@ type Marshaler interface { // // Go maps will be sorted alphabetically by key for deterministic output. // +// The toml struct tag can be used to provide the key name; if omitted the +// struct field name will be used. If the "omitempty" option is present the +// following value will be skipped: +// +// - arrays, slices, maps, and string with len of 0 +// - struct with all zero values +// - bool false +// +// If omitzero is given all int and float types with a value of 0 will be +// skipped. +// // Encoding Go values without a corresponding TOML representation will return an // error. Examples of this includes maps with non-string keys, slices with nil // elements, embedded non-struct types, and nested slices containing maps or @@ -136,18 +157,15 @@ func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { } func (enc *Encoder) encode(key Key, rv reflect.Value) { - // Special case: time needs to be in ISO8601 format. - // - // Special case: if we can marshal the type to text, then we used that. This - // prevents the encoder for handling these types as generic structs (or - // whatever the underlying type of a TextMarshaler is). - switch t := rv.Interface().(type) { - case time.Time, encoding.TextMarshaler, Marshaler: + // If we can marshal the type to text, then we use that. This prevents the + // encoder for handling these types as generic structs (or whatever the + // underlying type of a TextMarshaler is). + switch { + case isMarshaler(rv): enc.writeKeyValue(key, rv, false) return - // TODO: #76 would make this superfluous after implemented. - case Primitive: - enc.encode(key, reflect.ValueOf(t.undecoded)) + case rv.Type() == primitiveType: // TODO: #76 would make this superfluous after implemented. + enc.encode(key, reflect.ValueOf(rv.Interface().(Primitive).undecoded)) return } @@ -212,6 +230,9 @@ func (enc *Encoder) eElement(rv reflect.Value) { if err != nil { encPanic(err) } + if s == nil { + encPanic(errors.New("MarshalTOML returned nil and no error")) + } enc.w.Write(s) return case encoding.TextMarshaler: @@ -219,11 +240,34 @@ func (enc *Encoder) eElement(rv reflect.Value) { if err != nil { encPanic(err) } + if s == nil { + encPanic(errors.New("MarshalText returned nil and no error")) + } enc.writeQuoted(string(s)) return + case time.Duration: + enc.writeQuoted(v.String()) + return + case json.Number: + n, _ := rv.Interface().(json.Number) + + if n == "" { /// Useful zero value. + enc.w.WriteByte('0') + return + } else if v, err := n.Int64(); err == nil { + enc.eElement(reflect.ValueOf(v)) + return + } else if v, err := n.Float64(); err == nil { + enc.eElement(reflect.ValueOf(v)) + return + } + encPanic(errors.New(fmt.Sprintf("Unable to convert \"%s\" to neither int64 nor float64", n))) } switch rv.Kind() { + case reflect.Ptr: + enc.eElement(rv.Elem()) + return case reflect.String: enc.writeQuoted(rv.String()) case reflect.Bool: @@ -259,7 +303,7 @@ func (enc *Encoder) eElement(rv reflect.Value) { case reflect.Interface: enc.eElement(rv.Elem()) default: - encPanic(fmt.Errorf("unexpected primitive type: %T", rv.Interface())) + encPanic(fmt.Errorf("unexpected type: %T", rv.Interface())) } } @@ -280,7 +324,7 @@ func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { length := rv.Len() enc.wf("[") for i := 0; i < length; i++ { - elem := rv.Index(i) + elem := eindirect(rv.Index(i)) enc.eElement(elem) if i != length-1 { enc.wf(", ") @@ -294,7 +338,7 @@ func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { encPanic(errNoKey) } for i := 0; i < rv.Len(); i++ { - trv := rv.Index(i) + trv := eindirect(rv.Index(i)) if isNil(trv) { continue } @@ -319,7 +363,7 @@ func (enc *Encoder) eTable(key Key, rv reflect.Value) { } func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value, inline bool) { - switch rv := eindirect(rv); rv.Kind() { + switch rv.Kind() { case reflect.Map: enc.eMap(key, rv, inline) case reflect.Struct: @@ -341,7 +385,7 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { var mapKeysDirect, mapKeysSub []string for _, mapKey := range rv.MapKeys() { k := mapKey.String() - if typeIsTable(tomlTypeOfGo(rv.MapIndex(mapKey))) { + if typeIsTable(tomlTypeOfGo(eindirect(rv.MapIndex(mapKey)))) { mapKeysSub = append(mapKeysSub, k) } else { mapKeysDirect = append(mapKeysDirect, k) @@ -351,7 +395,7 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { var writeMapKeys = func(mapKeys []string, trailC bool) { sort.Strings(mapKeys) for i, mapKey := range mapKeys { - val := rv.MapIndex(reflect.ValueOf(mapKey)) + val := eindirect(rv.MapIndex(reflect.ValueOf(mapKey))) if isNil(val) { continue } @@ -379,6 +423,13 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { const is32Bit = (32 << (^uint(0) >> 63)) == 32 +func pointerTo(t reflect.Type) reflect.Type { + if t.Kind() == reflect.Ptr { + return pointerTo(t.Elem()) + } + return t +} + func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { // Write keys for fields directly under this key first, because if we write // a field that creates a new table then all keys under it will be in that @@ -395,7 +446,8 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { addFields = func(rt reflect.Type, rv reflect.Value, start []int) { for i := 0; i < rt.NumField(); i++ { f := rt.Field(i) - if f.PkgPath != "" && !f.Anonymous { /// Skip unexported fields. + isEmbed := f.Anonymous && pointerTo(f.Type).Kind() == reflect.Struct + if f.PkgPath != "" && !isEmbed { /// Skip unexported fields. continue } opts := getOptions(f.Tag) @@ -403,27 +455,16 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { continue } - frv := rv.Field(i) + frv := eindirect(rv.Field(i)) // Treat anonymous struct fields with tag names as though they are // not anonymous, like encoding/json does. // // Non-struct anonymous fields use the normal encoding logic. - if f.Anonymous { - t := f.Type - switch t.Kind() { - case reflect.Struct: - if getOptions(f.Tag).name == "" { - addFields(t, frv, append(start, f.Index...)) - continue - } - case reflect.Ptr: - if t.Elem().Kind() == reflect.Struct && getOptions(f.Tag).name == "" { - if !frv.IsNil() { - addFields(t.Elem(), frv.Elem(), append(start, f.Index...)) - } - continue - } + if isEmbed { + if getOptions(f.Tag).name == "" && frv.Kind() == reflect.Struct { + addFields(frv.Type(), frv, append(start, f.Index...)) + continue } } @@ -449,7 +490,7 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { writeFields := func(fields [][]int) { for _, fieldIndex := range fields { fieldType := rt.FieldByIndex(fieldIndex) - fieldVal := rv.FieldByIndex(fieldIndex) + fieldVal := eindirect(rv.FieldByIndex(fieldIndex)) if isNil(fieldVal) { /// Don't write anything for nil fields. continue @@ -502,6 +543,21 @@ func tomlTypeOfGo(rv reflect.Value) tomlType { if isNil(rv) || !rv.IsValid() { return nil } + + if rv.Kind() == reflect.Struct { + if rv.Type() == timeType { + return tomlDatetime + } + if isMarshaler(rv) { + return tomlString + } + return tomlHash + } + + if isMarshaler(rv) { + return tomlString + } + switch rv.Kind() { case reflect.Bool: return tomlBool @@ -513,7 +569,7 @@ func tomlTypeOfGo(rv reflect.Value) tomlType { case reflect.Float32, reflect.Float64: return tomlFloat case reflect.Array, reflect.Slice: - if typeEqual(tomlHash, tomlArrayType(rv)) { + if isTableArray(rv) { return tomlArrayHash } return tomlArray @@ -523,67 +579,35 @@ func tomlTypeOfGo(rv reflect.Value) tomlType { return tomlString case reflect.Map: return tomlHash - case reflect.Struct: - if _, ok := rv.Interface().(time.Time); ok { - return tomlDatetime - } - if isMarshaler(rv) { - return tomlString - } - return tomlHash default: - if isMarshaler(rv) { - return tomlString - } - encPanic(errors.New("unsupported type: " + rv.Kind().String())) panic("unreachable") } } func isMarshaler(rv reflect.Value) bool { - switch rv.Interface().(type) { - case encoding.TextMarshaler: - return true - case Marshaler: - return true - } - - // Someone used a pointer receiver: we can make it work for pointer values. - if rv.CanAddr() { - if _, ok := rv.Addr().Interface().(encoding.TextMarshaler); ok { - return true - } - if _, ok := rv.Addr().Interface().(Marshaler); ok { - return true - } - } - return false + return rv.Type().Implements(marshalText) || rv.Type().Implements(marshalToml) } -// tomlArrayType returns the element type of a TOML array. The type returned -// may be nil if it cannot be determined (e.g., a nil slice or a zero length -// slize). This function may also panic if it finds a type that cannot be -// expressed in TOML (such as nil elements, heterogeneous arrays or directly -// nested arrays of tables). -func tomlArrayType(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() || rv.Len() == 0 { - return nil +// isTableArray reports if all entries in the array or slice are a table. +func isTableArray(arr reflect.Value) bool { + if isNil(arr) || !arr.IsValid() || arr.Len() == 0 { + return false } - /// Don't allow nil. - rvlen := rv.Len() - for i := 1; i < rvlen; i++ { - if tomlTypeOfGo(rv.Index(i)) == nil { + ret := true + for i := 0; i < arr.Len(); i++ { + tt := tomlTypeOfGo(eindirect(arr.Index(i))) + // Don't allow nil. + if tt == nil { encPanic(errArrayNilElement) } - } - firstType := tomlTypeOfGo(rv.Index(0)) - if firstType == nil { - encPanic(errArrayNilElement) + if ret && !typeEqual(tomlHash, tt) { + ret = false + } } - return firstType + return ret } type tagOptions struct { @@ -628,6 +652,8 @@ func isEmpty(rv reflect.Value) bool { switch rv.Kind() { case reflect.Array, reflect.Slice, reflect.Map, reflect.String: return rv.Len() == 0 + case reflect.Struct: + return reflect.Zero(rv.Type()).Interface() == rv.Interface() case reflect.Bool: return !rv.Bool() } @@ -679,13 +705,25 @@ func encPanic(err error) { panic(tomlEncodeError{err}) } +// Resolve any level of pointers to the actual value (e.g. **string → string). func eindirect(v reflect.Value) reflect.Value { - switch v.Kind() { - case reflect.Ptr, reflect.Interface: - return eindirect(v.Elem()) - default: + if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { + if isMarshaler(v) { + return v + } + if v.CanAddr() { /// Special case for marshalers; see #358. + if pv := v.Addr(); isMarshaler(pv) { + return pv + } + } return v } + + if v.IsNil() { + return v + } + + return eindirect(v.Elem()) } func isNil(rv reflect.Value) bool { diff --git a/tools/vendor/github.com/BurntSushi/toml/error.go b/tools/vendor/github.com/BurntSushi/toml/error.go index d5728a41..2ac24e77 100644 --- a/tools/vendor/github.com/BurntSushi/toml/error.go +++ b/tools/vendor/github.com/BurntSushi/toml/error.go @@ -128,9 +128,13 @@ func (pe ParseError) ErrorWithPosition() string { func (pe ParseError) ErrorWithUsage() string { m := pe.ErrorWithPosition() if u, ok := pe.err.(interface{ Usage() string }); ok && u.Usage() != "" { - return m + "Error help:\n\n " + - strings.ReplaceAll(strings.TrimSpace(u.Usage()), "\n", "\n ") + - "\n" + lines := strings.Split(strings.TrimSpace(u.Usage()), "\n") + for i := range lines { + if lines[i] != "" { + lines[i] = " " + lines[i] + } + } + return m + "Error help:\n\n" + strings.Join(lines, "\n") + "\n" } return m } @@ -160,6 +164,11 @@ type ( errLexInvalidDate struct{ v string } errLexInlineTableNL struct{} errLexStringNL struct{} + errParseRange struct { + i interface{} // int or float + size string // "int64", "uint16", etc. + } + errParseDuration struct{ d string } ) func (e errLexControl) Error() string { @@ -179,6 +188,10 @@ func (e errLexInlineTableNL) Error() string { return "newlines not allowed withi 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 } const usageEscape = ` A '\' inside a "-delimited string is interpreted as an escape character. @@ -227,3 +240,37 @@ Instead use """ or ''' to split strings over multiple lines: string = """Hello, world!""" ` + +const usageIntOverflow = ` +This number is too large; this may be an error in the TOML, but it can also be a +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 + uint64 │ 0 │ 1.8 × 10¹⁸ + +int refers to int32 on 32-bit systems and int64 on 64-bit systems. +` + +const usageDuration = ` +A duration must be as "number", without any spaces. Valid units are: + + ns nanoseconds (billionth of a second) + us, µs microseconds (millionth of a second) + ms milliseconds (thousands of a second) + s seconds + m minutes + h hours + +You can combine multiple units; for example "5m10s" for 5 minutes and 10 +seconds. +` diff --git a/tools/vendor/github.com/BurntSushi/toml/lex.go b/tools/vendor/github.com/BurntSushi/toml/lex.go index ce7f546b..28ed4dd3 100644 --- a/tools/vendor/github.com/BurntSushi/toml/lex.go +++ b/tools/vendor/github.com/BurntSushi/toml/lex.go @@ -82,7 +82,7 @@ func (lx *lexer) nextItem() item { return item default: lx.state = lx.state(lx) - //fmt.Printf(" STATE %-24s current: %-10q stack: %s\n", lx.state, lx.current(), lx.stack) + //fmt.Printf(" STATE %-24s current: %-10s stack: %s\n", lx.state, lx.current(), lx.stack) } } } @@ -716,7 +716,17 @@ func lexMultilineString(lx *lexer) stateFn { if lx.peek() == '"' { /// Check if we already lexed 5 's; if so we have 6 now, and /// that's just too many man! - if strings.HasSuffix(lx.current(), `"""""`) { + /// + /// Second check is for the edge case: + /// + /// two quotes allowed. + /// vv + /// """lol \"""""" + /// ^^ ^^^---- closing three + /// escaped + /// + /// But ugly, but it works + if strings.HasSuffix(lx.current(), `"""""`) && !strings.HasSuffix(lx.current(), `\"""""`) { return lx.errorf(`unexpected '""""""'`) } lx.backup() @@ -807,8 +817,7 @@ func lexMultilineRawString(lx *lexer) stateFn { // lexMultilineStringEscape consumes an escaped character. It assumes that the // preceding '\\' has already been consumed. func lexMultilineStringEscape(lx *lexer) stateFn { - // Handle the special case first: - if isNL(lx.next()) { + if isNL(lx.next()) { /// \ escaping newline. return lexMultilineString } lx.backup() diff --git a/tools/vendor/github.com/BurntSushi/toml/meta.go b/tools/vendor/github.com/BurntSushi/toml/meta.go index 868619fb..d284f2a0 100644 --- a/tools/vendor/github.com/BurntSushi/toml/meta.go +++ b/tools/vendor/github.com/BurntSushi/toml/meta.go @@ -12,10 +12,11 @@ import ( type MetaData struct { context Key // Used only during decoding. + keyInfo map[string]keyInfo mapping map[string]interface{} - types map[string]tomlType keys []Key decoded map[string]struct{} + data []byte // Input file; for errors. } // IsDefined reports if the key exists in the TOML data. @@ -50,8 +51,8 @@ func (md *MetaData) IsDefined(key ...string) bool { // Type will return the empty string if given an empty key or a key that does // not exist. Keys are case sensitive. func (md *MetaData) Type(key ...string) string { - if typ, ok := md.types[Key(key).String()]; ok { - return typ.typeString() + if ki, ok := md.keyInfo[Key(key).String()]; ok { + return ki.tomlType.typeString() } return "" } diff --git a/tools/vendor/github.com/BurntSushi/toml/parse.go b/tools/vendor/github.com/BurntSushi/toml/parse.go index 0420b5ba..d2542d6f 100644 --- a/tools/vendor/github.com/BurntSushi/toml/parse.go +++ b/tools/vendor/github.com/BurntSushi/toml/parse.go @@ -16,12 +16,18 @@ type parser struct { currentKey string // Base key name for everything except hashes. pos Position // Current position in the TOML file. - ordered []Key // List of keys in the order that they appear in the TOML data. + 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. - types map[string]tomlType // Map keyname → TOML type. implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names"). } +type keyInfo struct { + pos Position + tomlType tomlType +} + func parse(data string) (p *parser, err error) { defer func() { if r := recover(); r != nil { @@ -57,8 +63,8 @@ func parse(data string) (p *parser, err error) { } p = &parser{ + keyInfo: make(map[string]keyInfo), mapping: make(map[string]interface{}), - types: make(map[string]tomlType), lx: lex(data), ordered: make([]Key, 0), implicits: make(map[string]struct{}), @@ -74,6 +80,15 @@ func parse(data string) (p *parser, err error) { return p, nil } +func (p *parser) panicErr(it item, err error) { + panic(ParseError{ + err: err, + Position: it.pos, + Line: it.pos.Len, + LastKey: p.current(), + }) +} + func (p *parser) panicItemf(it item, format string, v ...interface{}) { panic(ParseError{ Message: fmt.Sprintf(format, v...), @@ -94,7 +109,7 @@ func (p *parser) panicf(format string, v ...interface{}) { func (p *parser) next() item { it := p.lx.nextItem() - //fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.line, it.val) + //fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.pos.Line, it.val) if it.typ == itemError { if it.err != nil { panic(ParseError{ @@ -146,7 +161,7 @@ func (p *parser) topLevel(item item) { p.assertEqual(itemTableEnd, name.typ) p.addContext(key, false) - p.setType("", tomlHash) + p.setType("", tomlHash, item.pos) p.ordered = append(p.ordered, key) case itemArrayTableStart: // [[ .. ]] name := p.nextPos() @@ -158,7 +173,7 @@ func (p *parser) topLevel(item item) { p.assertEqual(itemArrayTableEnd, name.typ) p.addContext(key, true) - p.setType("", tomlArrayHash) + p.setType("", tomlArrayHash, item.pos) p.ordered = append(p.ordered, key) case itemKeyStart: // key = .. outerContext := p.context @@ -181,8 +196,9 @@ func (p *parser) topLevel(item item) { } /// Set value. - val, typ := p.value(p.next(), false) - p.set(p.currentKey, val, typ) + vItem := p.next() + val, typ := p.value(vItem, false) + p.set(p.currentKey, val, typ, vItem.pos) p.ordered = append(p.ordered, p.context.add(p.currentKey)) /// Remove the context we added (preserving any context from [tbl] lines). @@ -266,7 +282,7 @@ func (p *parser) valueInteger(it item) (interface{}, tomlType) { // So mark the former as a bug but the latter as a legitimate user // error. if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { - p.panicItemf(it, "Integer '%s' is out of the range of 64-bit signed integers.", it.val) + p.panicErr(it, errParseRange{i: it.val, size: "int64"}) } else { p.bug("Expected integer value, but got '%s'.", it.val) } @@ -304,7 +320,7 @@ func (p *parser) valueFloat(it item) (interface{}, tomlType) { num, err := strconv.ParseFloat(val, 64) if err != nil { if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { - p.panicItemf(it, "Float '%s' is out of the range of 64-bit IEEE-754 floating-point numbers.", it.val) + p.panicErr(it, errParseRange{i: it.val, size: "float64"}) } else { p.panicItemf(it, "Invalid float value: %q", it.val) } @@ -343,9 +359,8 @@ func (p *parser) valueDatetime(it item) (interface{}, tomlType) { } func (p *parser) valueArray(it item) (interface{}, tomlType) { - p.setType(p.currentKey, tomlArray) + p.setType(p.currentKey, tomlArray, it.pos) - // p.setType(p.currentKey, typ) var ( types []tomlType @@ -414,7 +429,7 @@ 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) + p.set(p.currentKey, val, typ, it.pos) p.ordered = append(p.ordered, p.context.add(p.currentKey)) hash[p.currentKey] = val @@ -533,9 +548,10 @@ func (p *parser) addContext(key Key, array bool) { } // set calls setValue and setType. -func (p *parser) set(key string, val interface{}, typ tomlType) { +func (p *parser) set(key string, val interface{}, typ tomlType, pos Position) { p.setValue(key, val) - p.setType(key, typ) + p.setType(key, typ, pos) + } // setValue sets the given key to the given value in the current context. @@ -599,7 +615,7 @@ func (p *parser) setValue(key string, value interface{}) { // // Note that if `key` is empty, then the type given will be applied to the // current context (which is either a table or an array of tables). -func (p *parser) setType(key string, typ tomlType) { +func (p *parser) setType(key string, typ tomlType, pos Position) { keyContext := make(Key, 0, len(p.context)+1) keyContext = append(keyContext, p.context...) if len(key) > 0 { // allow type setting for hashes @@ -611,7 +627,7 @@ func (p *parser) setType(key string, typ tomlType) { if len(keyContext) == 0 { keyContext = Key{""} } - p.types[keyContext.String()] = typ + p.keyInfo[keyContext.String()] = keyInfo{tomlType: typ, pos: pos} } // Implicit keys need to be created when tables are implied in "a.b.c.d = 1" and @@ -619,7 +635,7 @@ func (p *parser) setType(key string, typ tomlType) { func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} } func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) } func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok } -func (p *parser) isArray(key Key) bool { return p.types[key.String()] == tomlArray } +func (p *parser) isArray(key Key) bool { return p.keyInfo[key.String()].tomlType == tomlArray } func (p *parser) addImplicitContext(key Key) { p.addImplicit(key) p.addContext(key, false) @@ -710,10 +726,8 @@ func (p *parser) replaceEscapes(it item, str string) string { switch s[r] { default: p.bug("Expected valid escape code after \\, but got %q.", s[r]) - return "" case ' ', '\t': p.panicItemf(it, "invalid escape: '\\%c'", s[r]) - return "" case 'b': replaced = append(replaced, rune(0x0008)) r += 1 diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/analyzer.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/analyzer.go index 6719ac5c..279f2189 100644 --- a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/analyzer.go +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/analyzer.go @@ -3,11 +3,10 @@ package analyzer import ( "errors" "flag" - "fmt" "go/ast" "go/types" - "regexp" "strings" + "sync" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" @@ -21,13 +20,23 @@ var ( type analyzer struct { include PatternsList exclude PatternsList + + typesProcessCache map[types.Type]bool + typesProcessCacheMu sync.RWMutex + + structFieldsCache map[types.Type]*StructFields + structFieldsCacheMu sync.RWMutex } // NewAnalyzer returns a go/analysis-compatible analyzer. // -i arguments adds include patterns // -e arguments adds exclude patterns func NewAnalyzer(include []string, exclude []string) (*analysis.Analyzer, error) { - a := analyzer{} + a := analyzer{ //nolint:exhaustruct + typesProcessCache: map[types.Type]bool{}, + + structFieldsCache: map[types.Type]*StructFields{}, + } var err error @@ -41,7 +50,7 @@ func NewAnalyzer(include []string, exclude []string) (*analysis.Analyzer, error) return nil, err } - return &analysis.Analyzer{ + return &analysis.Analyzer{ //nolint:exhaustruct Name: "exhaustruct", Doc: "Checks if all structure fields are initialized", Run: a.run, @@ -80,7 +89,7 @@ func (a *analyzer) run(pass *analysis.Pass) (interface{}, error) { return nil, nil //nolint:nilnil } -//nolint:funlen,cyclop +//nolint:cyclop func (a *analyzer) newVisitor(pass *analysis.Pass) func(node ast.Node) { var ret *ast.ReturnStmt @@ -114,13 +123,7 @@ func (a *analyzer) newVisitor(pass *analysis.Pass) func(node ast.Node) { return } - if len(a.include) > 0 { - if !a.include.MatchesAny(typ.String()) { - return - } - } - - if a.exclude.MatchesAny(typ.String()) { + if !a.shouldProcessType(typ) { return } @@ -135,7 +138,7 @@ func (a *analyzer) newVisitor(pass *analysis.Pass) func(node ast.Node) { } } - missingFields := structMissingFields(lit, strct, typ, pass) + missingFields := a.structMissingFields(lit, strct, strings.HasPrefix(typ.String(), pass.Pkg.Path()+".")) if len(missingFields) == 1 { pass.Reportf(node.Pos(), "%s is missing in %s", missingFields[0], strctName) @@ -145,6 +148,74 @@ func (a *analyzer) newVisitor(pass *analysis.Pass) func(node ast.Node) { } } +func (a *analyzer) shouldProcessType(typ types.Type) bool { + if len(a.include) == 0 && len(a.exclude) == 0 { + // skip whole part with cache, since we have no restrictions and have to check everything + return true + } + + a.typesProcessCacheMu.RLock() + v, ok := a.typesProcessCache[typ] + a.typesProcessCacheMu.RUnlock() + + if !ok { + a.typesProcessCacheMu.Lock() + defer a.typesProcessCacheMu.Unlock() + + v = true + typStr := typ.String() + + if len(a.include) > 0 && !a.include.MatchesAny(typStr) { + v = false + } + + if v && a.exclude.MatchesAny(typStr) { + v = false + } + + a.typesProcessCache[typ] = v + } + + return v +} + +func (a *analyzer) structMissingFields(lit *ast.CompositeLit, strct *types.Struct, private bool) []string { + keys, unnamed := literalKeys(lit) + fields := a.structFields(strct) + + if unnamed { + if private { + return fields.All[len(keys):] + } + + return fields.Public[len(keys):] + } + + if private { + return difference(fields.AllRequired, keys) + } + + return difference(fields.PublicRequired, keys) +} + +func (a *analyzer) structFields(strct *types.Struct) *StructFields { + typ := strct.Underlying() + + a.structFieldsCacheMu.RLock() + fields, ok := a.structFieldsCache[typ] + a.structFieldsCacheMu.RUnlock() + + if !ok { + a.structFieldsCacheMu.Lock() + defer a.structFieldsCacheMu.Unlock() + + fields = NewStructFields(strct) + a.structFieldsCache[typ] = fields + } + + return fields +} + func returnContainsLiteral(ret *ast.ReturnStmt, lit *ast.CompositeLit) bool { for _, result := range ret.Results { if l, ok := result.(*ast.CompositeLit); ok { @@ -167,19 +238,6 @@ func returnContainsError(ret *ast.ReturnStmt, pass *analysis.Pass) bool { return false } -func structMissingFields(lit *ast.CompositeLit, strct *types.Struct, typ types.Type, pass *analysis.Pass) []string { - isSamePackage := strings.HasPrefix(typ.String(), pass.Pkg.Path()+".") - - keys, unnamed := literalKeys(lit) - fields := structFields(strct, isSamePackage) - - if unnamed { - return fields[len(keys):] - } - - return difference(fields, keys) -} - func literalKeys(lit *ast.CompositeLit) (keys []string, unnamed bool) { for _, elt := range lit.Elts { if k, ok := elt.(*ast.KeyValueExpr); ok { @@ -195,31 +253,17 @@ func literalKeys(lit *ast.CompositeLit) (keys []string, unnamed bool) { unnamed = true keys = make([]string, len(lit.Elts)) - break - } - - return keys, unnamed -} - -func structFields(strct *types.Struct, withPrivate bool) (keys []string) { - for i := 0; i < strct.NumFields(); i++ { - f := strct.Field(i) - - if !f.Exported() && !withPrivate { - continue - } - - keys = append(keys, f.Name()) + return } - return keys + return } // difference returns elements that are in `a` and not in `b`. func difference(a, b []string) (diff []string) { - mb := make(map[string]bool, len(b)) + mb := make(map[string]struct{}, len(b)) for _, x := range b { - mb[x] = true + mb[x] = struct{}{} } for _, x := range a { @@ -243,65 +287,3 @@ func exprName(expr ast.Expr) string { return s.Sel.Name } - -type PatternsList []*regexp.Regexp - -// MatchesAny matches provided string against all regexps in a slice. -func (l PatternsList) MatchesAny(str string) bool { - for _, r := range l { - if r.MatchString(str) { - return true - } - } - - return false -} - -// newPatternsList parses slice of strings to a slice of compiled regular -// expressions. -func newPatternsList(in []string) (PatternsList, error) { - list := PatternsList{} - - for _, str := range in { - re, err := strToRegexp(str) - if err != nil { - return nil, err - } - - list = append(list, re) - } - - return list, nil -} - -type reListVar struct { - values *PatternsList -} - -func (v *reListVar) Set(value string) error { - re, err := strToRegexp(value) - if err != nil { - return err - } - - *v.values = append(*v.values, re) - - return nil -} - -func (v *reListVar) String() string { - return "" -} - -func strToRegexp(str string) (*regexp.Regexp, error) { - if str == "" { - return nil, ErrEmptyPattern - } - - re, err := regexp.Compile(str) - if err != nil { - return nil, fmt.Errorf("unable to compile %s as regular expression: %w", str, err) - } - - return re, nil -} diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/patterns-list.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/patterns-list.go new file mode 100644 index 00000000..2884cab6 --- /dev/null +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/patterns-list.go @@ -0,0 +1,68 @@ +package analyzer + +import ( + "fmt" + "regexp" +) + +type PatternsList []*regexp.Regexp + +// MatchesAny matches provided string against all regexps in a slice. +func (l PatternsList) MatchesAny(str string) bool { + for _, r := range l { + if r.MatchString(str) { + return true + } + } + + return false +} + +// newPatternsList parses slice of strings to a slice of compiled regular +// expressions. +func newPatternsList(in []string) (PatternsList, error) { + list := PatternsList{} + + for _, str := range in { + re, err := strToRegexp(str) + if err != nil { + return nil, err + } + + list = append(list, re) + } + + return list, nil +} + +type reListVar struct { + values *PatternsList +} + +func (v *reListVar) Set(value string) error { + re, err := strToRegexp(value) + if err != nil { + return err + } + + *v.values = append(*v.values, re) + + return nil +} + +func (v *reListVar) String() string { + return "" +} + +func strToRegexp(str string) (*regexp.Regexp, error) { + if str == "" { + return nil, ErrEmptyPattern + } + + re, err := regexp.Compile(str) + if err != nil { + return nil, fmt.Errorf("unable to compile %s as regular expression: %w", str, err) + } + + return re, nil +} diff --git a/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/struct-fields.go b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/struct-fields.go new file mode 100644 index 00000000..56eda05f --- /dev/null +++ b/tools/vendor/github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer/struct-fields.go @@ -0,0 +1,61 @@ +package analyzer + +import ( + "go/types" + "reflect" + + "golang.org/x/exp/slices" +) + +type StructFields struct { + All []string + AllRequired []string + + Public []string + PublicRequired []string +} + +func NewStructFields(strct *types.Struct) *StructFields { + sf := StructFields{ + All: make([]string, strct.NumFields()), + AllRequired: make([]string, 0, strct.NumFields()), + Public: make([]string, 0, strct.NumFields()), + PublicRequired: make([]string, 0, strct.NumFields()), + } + + for i := 0; i < strct.NumFields(); i++ { + f := strct.Field(i) + isOptional := isFieldOptional(strct.Tag(i)) + + sf.All[i] = f.Name() + if !isOptional { + sf.AllRequired = append(sf.AllRequired, f.Name()) + } + + if f.Exported() { + sf.Public = append(sf.Public, f.Name()) + + if !isOptional { + sf.PublicRequired = append(sf.PublicRequired, f.Name()) + } + } + } + + sf.All = slices.Clip(sf.All) + sf.AllRequired = slices.Clip(sf.AllRequired) + sf.Public = slices.Clip(sf.Public) + sf.PublicRequired = slices.Clip(sf.PublicRequired) + + return &sf +} + +const ( + TagName = "exhaustruct" + OptionalTagValue = "optional" +) + +// isFieldOptional checks if field tags has an optional tag, and therefore can +// be omitted during structure initialization. +func isFieldOptional(tags string) bool { + return reflect.StructTag(tags).Get(TagName) == OptionalTagValue +} diff --git a/tools/vendor/github.com/alingse/asasalint/.gitignore b/tools/vendor/github.com/alingse/asasalint/.gitignore new file mode 100644 index 00000000..d0fc531c --- /dev/null +++ b/tools/vendor/github.com/alingse/asasalint/.gitignore @@ -0,0 +1,18 @@ +# 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 + +# Dependency directories (remove the comment below to include it) +# vendor/ +.vscode + +asasalint diff --git a/tools/vendor/github.com/alingse/asasalint/.goreleaser.yml b/tools/vendor/github.com/alingse/asasalint/.goreleaser.yml new file mode 100644 index 00000000..e45d5860 --- /dev/null +++ b/tools/vendor/github.com/alingse/asasalint/.goreleaser.yml @@ -0,0 +1,72 @@ +--- +project_name: asasalint + +release: + github: + owner: alingse + name: asasalint + +builds: + - binary: asasalint + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - arm64 + - arm + - 386 + - ppc64le + - s390x + - mips64 + - mips64le + - riscv64 + goarm: + - 6 + - 7 + gomips: + - hardfloat + env: + - CGO_ENABLED=0 + ignore: + - goos: darwin + goarch: 386 + - goos: freebsd + goarch: arm64 + main: ./cmd/asasalint/ + flags: + - -trimpath + ldflags: -s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}} -X main.date={{.Date}} + +archives: + - format: tar.gz + wrap_in_directory: true + format_overrides: + - goos: windows + format: zip + name_template: '{{ .ProjectName }}-{{ .Version }}-{{ .Os }}-{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' + files: + - LICENSE + - README.md + +snapshot: + name_template: SNAPSHOT-{{ .Commit }} + +checksum: + name_template: '{{ .ProjectName }}-{{ .Version }}-checksums.txt' + +changelog: + sort: asc + filters: + exclude: + - '(?i)^docs?:' + - '(?i)^docs\([^:]+\):' + - '(?i)^docs\[[^:]+\]:' + - '^tests?:' + - '(?i)^dev:' + - '^build\(deps\): bump .* in /docs \(#\d+\)' + - '^build\(deps\): bump .* in /\.github/peril \(#\d+\)' + - Merge pull request + - Merge branch diff --git a/tools/vendor/github.com/alingse/asasalint/LICENSE b/tools/vendor/github.com/alingse/asasalint/LICENSE new file mode 100644 index 00000000..a7c39f2e --- /dev/null +++ b/tools/vendor/github.com/alingse/asasalint/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 alingse + +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/alingse/asasalint/Makefile b/tools/vendor/github.com/alingse/asasalint/Makefile new file mode 100644 index 00000000..12f8ba92 --- /dev/null +++ b/tools/vendor/github.com/alingse/asasalint/Makefile @@ -0,0 +1,15 @@ +.PHONY: clean check test build + +default: clean check test build + +clean: + rm -rf dist/ cover.out + +test: clean + go test -v -cover ./... + +check: + golangci-lint run + +build: + go build -ldflags "-s -w" -trimpath ./cmd/asasalint/ diff --git a/tools/vendor/github.com/alingse/asasalint/README.md b/tools/vendor/github.com/alingse/asasalint/README.md new file mode 100644 index 00000000..3fa7e65b --- /dev/null +++ b/tools/vendor/github.com/alingse/asasalint/README.md @@ -0,0 +1,76 @@ +# asasalint +Golang linter, lint that pass any slice as any in variadic function + + +## Install + +```sh +go install github.com/alingse/asasalint/cmd/asasalint@latest +``` + +## Usage + +```sh +asasalint ./... +``` + +ignore some func that was by desgin + +```sh +asasalint -e append,Append ./... +``` + +## Why + +two kind of unexpected usage, and `go build` success + +```Go +package main + +import "fmt" + +func A(args ...any) int { + return len(args) +} + +func B(args ...any) int { + return A(args) +} + +func main() { + + // 1 + fmt.Println(B(1, 2, 3, 4)) +} +``` + + + +```Go +package main + +import "fmt" + +func errMsg(msg string, args ...any) string { + return fmt.Sprintf(msg, args...) +} + +func Err(msg string, args ...any) string { + return errMsg(msg, args) +} + +func main() { + + // p1 [hello world] p2 %!s(MISSING) + fmt.Println(Err("p1 %s p2 %s", "hello", "world")) +} +``` + + + +## TODO + +1. add to golangci-lint +2. given a SuggestEdition +3. add `append` to default exclude ? +4. ingore pattern `fn(a, b, []any{1,2,3})` , because `[]any{1,2,3}` is most likely by design diff --git a/tools/vendor/github.com/alingse/asasalint/asasalint.go b/tools/vendor/github.com/alingse/asasalint/asasalint.go new file mode 100644 index 00000000..f34516a4 --- /dev/null +++ b/tools/vendor/github.com/alingse/asasalint/asasalint.go @@ -0,0 +1,166 @@ +package asasalint + +import ( + "bytes" + "fmt" + "go/ast" + "go/printer" + "go/token" + "go/types" + "log" + "regexp" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +const BuiltinExclusions = `^(fmt|log|logger|t|)\.(Print|Fprint|Sprint|Fatal|Panic|Error|Warn|Warning|Info|Debug|Log)(|f|ln)$` + +type LinterSetting struct { + Exclude []string + NoBuiltinExclusions bool + IgnoreTest bool +} + +func NewAnalyzer(setting LinterSetting) (*analysis.Analyzer, error) { + a, err := newAnalyzer(setting) + if err != nil { + return nil, err + } + + return &analysis.Analyzer{ + Name: "asasalint", + Doc: "check for pass []any as any in variadic func(...any)", + Run: a.run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + }, nil +} + +type analyzer struct { + excludes []*regexp.Regexp + setting LinterSetting +} + +func newAnalyzer(setting LinterSetting) (*analyzer, error) { + a := &analyzer{ + setting: setting, + } + + if !a.setting.NoBuiltinExclusions { + a.excludes = append(a.excludes, regexp.MustCompile(BuiltinExclusions)) + } + + for _, exclude := range a.setting.Exclude { + if exclude != "" { + exp, err := regexp.Compile(exclude) + if err != nil { + return nil, err + } + + a.excludes = append(a.excludes, exp) + } + } + + return a, nil +} + +func (a *analyzer) run(pass *analysis.Pass) (interface{}, error) { + inspectorInfo := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + nodeFilter := []ast.Node{(*ast.CallExpr)(nil)} + + inspectorInfo.Preorder(nodeFilter, a.AsCheckVisitor(pass)) + return nil, nil +} + +func (a *analyzer) AsCheckVisitor(pass *analysis.Pass) func(ast.Node) { + return func(n ast.Node) { + if a.setting.IgnoreTest { + pos := pass.Fset.Position(n.Pos()) + if strings.HasSuffix(pos.Filename, "_test.go") { + return + } + } + + caller, ok := n.(*ast.CallExpr) + if !ok { + return + } + if caller.Ellipsis != token.NoPos { + return + } + if len(caller.Args) == 0 { + return + } + + fnName, err := getFuncName(pass.Fset, caller) + if err != nil { + log.Println(err) + return + } + + for _, exclude := range a.excludes { + if exclude.MatchString(fnName) { + return + } + } + + fnType := pass.TypesInfo.TypeOf(caller.Fun) + if !isSliceAnyVariadicFuncType(fnType) { + return + } + + fnSign := fnType.(*types.Signature) + if len(caller.Args) != fnSign.Params().Len() { + return + } + + lastArg := caller.Args[len(caller.Args)-1] + argType := pass.TypesInfo.TypeOf(lastArg) + if !isSliceAnyType(argType) { + return + } + node := lastArg + + d := analysis.Diagnostic{ + Pos: node.Pos(), + End: node.End(), + Message: fmt.Sprintf("pass []any as any to func %s %s", fnName, fnType.String()), + Category: "asasalint", + } + pass.Report(d) + } +} + +func getFuncName(fset *token.FileSet, caller *ast.CallExpr) (string, error) { + buf := new(bytes.Buffer) + if err := printer.Fprint(buf, fset, caller.Fun); err != nil { + return "", fmt.Errorf("unable to print node at %s: %w", fset.Position(caller.Fun.Pos()), err) + } + + return buf.String(), nil +} + +func isSliceAnyVariadicFuncType(typ types.Type) (r bool) { + fnSign, ok := typ.(*types.Signature) + if !ok || !fnSign.Variadic() { + return false + } + + params := fnSign.Params() + lastParam := params.At(params.Len() - 1) + return isSliceAnyType(lastParam.Type()) +} + +func isSliceAnyType(typ types.Type) (r bool) { + sliceType, ok := typ.(*types.Slice) + if !ok { + return + } + elemType, ok := sliceType.Elem().(*types.Interface) + if !ok { + return + } + return elemType.NumMethods() == 0 +} diff --git a/tools/vendor/github.com/curioswitch/go-reassign/.gitattributes b/tools/vendor/github.com/curioswitch/go-reassign/.gitattributes new file mode 100644 index 00000000..d020be8e --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/.gitattributes @@ -0,0 +1,2 @@ +*.go text eol=lf + diff --git a/tools/vendor/github.com/curioswitch/go-reassign/.gitignore b/tools/vendor/github.com/curioswitch/go-reassign/.gitignore new file mode 100644 index 00000000..59fa3361 --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/.gitignore @@ -0,0 +1,6 @@ +.idea +.VSCode +.envrc + +build +dist diff --git a/tools/vendor/github.com/curioswitch/go-reassign/.golangci.yml b/tools/vendor/github.com/curioswitch/go-reassign/.golangci.yml new file mode 100644 index 00000000..e3bf79ae --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/.golangci.yml @@ -0,0 +1,38 @@ +linters: + enable: + - asasalint + - bidichk + - bodyclose + - decorder + - durationcheck + - errchkjson + - errname + - errorlint + - execinquery + - exhaustive + - exportloopref + - gocritic + - goerr113 + - gofmt + - goimports + - goprintffuncname + - gosec + - importas + - misspell + - nolintlint + - nosnakecase + - prealloc + - predeclared + - promlinter + - revive + - stylecheck + - tagliatelle + - tenv + - thelper + - unconvert + - usestdlibvars +issues: + exclude-rules: + - path: magefile\.go + linters: + - deadcode diff --git a/tools/vendor/github.com/curioswitch/go-reassign/.goreleaser.yaml b/tools/vendor/github.com/curioswitch/go-reassign/.goreleaser.yaml new file mode 100644 index 00000000..25f2dc0c --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/.goreleaser.yaml @@ -0,0 +1,27 @@ +builds: + - main: ./cmd + env: + - CGO_ENABLED=0 + targets: + - linux_amd64 + - linux_arm64 + - darwin_amd64 + - darwin_arm64 + - windows_amd64 + - windows_arm64 +archives: + - format_overrides: + - goos: windows + format: zip +release: + mode: append +checksum: + name_template: 'checksums.txt' +snapshot: + name_template: "{{ incpatch .Version }}-next" +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' diff --git a/tools/vendor/github.com/curioswitch/go-reassign/LICENSE b/tools/vendor/github.com/curioswitch/go-reassign/LICENSE new file mode 100644 index 00000000..9f18bde0 --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Choko (choko@curioswitch.org) + +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/curioswitch/go-reassign/README.md b/tools/vendor/github.com/curioswitch/go-reassign/README.md new file mode 100644 index 00000000..ac9c131d --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/README.md @@ -0,0 +1,53 @@ +# reassign + +A linter that detects when reassigning a top-level variable in another package. + +## Install + +```bash +go install github.com/curioswitch/go-reassign +``` + +## Usage + +```bash +reassign ./... +``` + +Change the pattern to match against variables being reassigned. By default, only `EOF` and `Err*` variables are checked. + +```bash +reassign -pattern ".*" ./... +``` + +## Background + +Package variables are commonly used to define sentinel errors which callers can use with `errors.Is` to determine the +type of a returned `error`. Some examples exist in the standard [os](https://pkg.go.dev/os#pkg-variables) library. + +Unfortunately, as with any variable, these are mutable, and it is possible to write this very dangerous code. + +```go +package main +import "io" +func bad() { + // breaks file reading + io.EOF = nil +} +``` + +This caused a new pattern for [constant errors](https://dave.cheney.net/2016/04/07/constant-errors) +to gain popularity, but they don't work well with improvements to the `errors` package in recent versions of Go and may +be considered to be non-idiomatic compared to normal `errors.New`. If we can catch reassignment of sentinel errors, we +gain much of the safety of constant errors. + +This linter will catch reassignment of variables in other packages. By default it intends to apply to as many codebases +as possible and only checks a restricted set of variable names, `EOF` and `ErrFoo`, to restrict to sentinel errors. +Package variable reassignment is generally confusing, though, and we recommend avoiding it for all variables, not just errors. +The `pattern` flag can be set to a regular expression to define what variables cannot be reassigned, and `.*` is +recommended if it works with your code. + +## Limitations + +If a variable shadows the name of an import, an assignment of a field in the variable will trigger the linter. Shadowing +can be confusing, so it's recommended to rename the variable. diff --git a/tools/vendor/github.com/curioswitch/go-reassign/analyzer.go b/tools/vendor/github.com/curioswitch/go-reassign/analyzer.go new file mode 100644 index 00000000..48707ade --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/analyzer.go @@ -0,0 +1,13 @@ +package reassign + +import ( + "github.com/curioswitch/go-reassign/internal/analyzer" + "golang.org/x/tools/go/analysis" +) + +const FlagPattern = analyzer.FlagPattern + +// NewAnalyzer returns an analyzer for checking that package variables are not reassigned. +func NewAnalyzer() *analysis.Analyzer { + return analyzer.New() +} diff --git a/tools/vendor/github.com/curioswitch/go-reassign/internal/analyzer/analyzer.go b/tools/vendor/github.com/curioswitch/go-reassign/internal/analyzer/analyzer.go new file mode 100644 index 00000000..c4d5fd8c --- /dev/null +++ b/tools/vendor/github.com/curioswitch/go-reassign/internal/analyzer/analyzer.go @@ -0,0 +1,86 @@ +package analyzer + +import ( + "fmt" + "go/ast" + "regexp" + "strconv" + "strings" + + "golang.org/x/tools/go/analysis" +) + +const FlagPattern = "pattern" + +func New() *analysis.Analyzer { + a := &analysis.Analyzer{ + Name: "reassign", + Doc: "Checks that package variables are not reassigned", + Run: run, + } + a.Flags.String(FlagPattern, `^(Err.*|EOF)$`, "Pattern to match package variables against to prevent reassignment") + return a +} + +func run(pass *analysis.Pass) (interface{}, error) { + checkRE, err := regexp.Compile(pass.Analyzer.Flags.Lookup(FlagPattern).Value.String()) + if err != nil { + return nil, fmt.Errorf("invalid pattern: %w", err) + } + for _, f := range pass.Files { + state := &fileState{imports: make(map[string]struct{})} + ast.Inspect(f, func(node ast.Node) bool { + return inspect(pass, node, checkRE, state) + }) + } + return nil, nil +} + +type fileState struct { + imports map[string]struct{} +} + +func inspect(pass *analysis.Pass, node ast.Node, checkRE *regexp.Regexp, state *fileState) bool { + if importSpec, ok := node.(*ast.ImportSpec); ok { + if importSpec.Name != nil { + state.imports[importSpec.Name.Name] = struct{}{} + } else { + n, err := strconv.Unquote(importSpec.Path.Value) + if err != nil { + return true + } + if idx := strings.LastIndexByte(n, '/'); idx != -1 { + n = n[idx+1:] + } + state.imports[n] = struct{}{} + } + return true + } + + assignStmt, ok := node.(*ast.AssignStmt) + if !ok { + return true + } + + for _, lhs := range assignStmt.Lhs { + selector, ok := lhs.(*ast.SelectorExpr) + if !ok { + return true + } + + if !checkRE.MatchString(selector.Sel.Name) { + return true + } + + selectIdent, ok := selector.X.(*ast.Ident) + if !ok { + return true + } + + if _, ok := state.imports[selectIdent.Name]; ok { + pass.Reportf(node.Pos(), "reassigning variable %s in other package %s", selector.Sel.Name, selectIdent.Name) + } + } + + return true +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/analyzer/analyzer.go b/tools/vendor/github.com/daixiang0/gci/pkg/analyzer/analyzer.go deleted file mode 100644 index 10818a79..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/analyzer/analyzer.go +++ /dev/null @@ -1,131 +0,0 @@ -package analyzer - -import ( - "bytes" - "fmt" - "go/token" - "strings" - - "github.com/daixiang0/gci/pkg/configuration" - "github.com/daixiang0/gci/pkg/gci" - "github.com/daixiang0/gci/pkg/io" - - "golang.org/x/tools/go/analysis" - "golang.org/x/tools/go/analysis/passes/inspect" -) - -const ( - NoInlineCommentsFlag = "noInlineComments" - NoPrefixCommentsFlag = "noPrefixComments" - SectionsFlag = "Sections" - SectionSeparatorsFlag = "SectionSeparators" - SectionDelimiter = ";" -) - -var ( - noInlineComments bool - noPrefixComments bool - sectionsStr string - sectionSeparatorsStr string -) - -func init() { - Analyzer.Flags.BoolVar(&noInlineComments, NoInlineCommentsFlag, false, "If comments in the same line as the input should be present") - Analyzer.Flags.BoolVar(&noPrefixComments, NoPrefixCommentsFlag, false, "If comments above an input should be present") - Analyzer.Flags.StringVar(§ionsStr, SectionsFlag, "", "Specify the Sections format that should be used to check the file formatting") - Analyzer.Flags.StringVar(§ionSeparatorsStr, SectionSeparatorsFlag, "", "Specify the Sections that are inserted as Separators between Sections") -} - -var Analyzer = &analysis.Analyzer{ - Name: "gci", - Doc: "A tool that control golang package import order and make it always deterministic.", - Requires: []*analysis.Analyzer{inspect.Analyzer}, - Run: runAnalysis, -} - -func runAnalysis(pass *analysis.Pass) (interface{}, error) { - // TODO input validation - - var fileReferences []*token.File - // extract file references for all files in the analyzer pass - for _, pkgFile := range pass.Files { - fileForPos := pass.Fset.File(pkgFile.Package) - if fileForPos != nil { - fileReferences = append(fileReferences, fileForPos) - } - } - expectedNumFiles := len(pass.Files) - foundNumFiles := len(fileReferences) - if expectedNumFiles != foundNumFiles { - return nil, InvalidNumberOfFilesInAnalysis{expectedNumFiles, foundNumFiles} - } - - // read configuration options - gciCfg, err := parseGciConfiguration() - if err != nil { - return nil, err - } - - for _, file := range fileReferences { - filePath := file.Name() - unmodifiedFile, formattedFile, err := gci.LoadFormatGoFile(io.File{filePath}, *gciCfg) - if err != nil { - return nil, err - } - // search for a difference - fileRunes := bytes.Runes(unmodifiedFile) - formattedRunes := bytes.Runes(formattedFile) - diffIdx := compareRunes(fileRunes, formattedRunes) - switch diffIdx { - case -1: - // no difference - default: - diffPos := file.Position(file.Pos(diffIdx)) - // prevent invalid access to array - fileRune := "nil" - formattedRune := "nil" - if len(fileRunes)-1 >= diffIdx { - fileRune = fmt.Sprintf("%q", fileRunes[diffIdx]) - } - if len(formattedRunes)-1 >= diffIdx { - formattedRune = fmt.Sprintf("%q", formattedRunes[diffIdx]) - } - pass.Reportf(file.Pos(diffIdx), "Expected %s, Found %s at %s[line %d,col %d]", formattedRune, fileRune, filePath, diffPos.Line, diffPos.Column) - } - } - return nil, nil -} - -func compareRunes(a, b []rune) (differencePos int) { - // check shorter rune slice first to prevent invalid array access - shorterRune := a - if len(b) < len(a) { - shorterRune = b - } - // check for differences up to where the length is identical - for idx := 0; idx < len(shorterRune); idx++ { - if a[idx] != b[idx] { - return idx - } - } - // check that we have compared two equally long rune arrays - if len(a) != len(b) { - return len(shorterRune) + 1 - } - return -1 -} - -func parseGciConfiguration() (*gci.GciConfiguration, error) { - fmtCfg := configuration.FormatterConfiguration{noInlineComments, noPrefixComments, false} - - var sectionStrings []string - if sectionsStr != "" { - sectionStrings = strings.Split(sectionsStr, SectionDelimiter) - } - - var sectionSeparatorStrings []string - if sectionSeparatorsStr != "" { - sectionSeparatorStrings = strings.Split(sectionSeparatorsStr, SectionDelimiter) - } - return gci.GciStringConfiguration{fmtCfg, sectionStrings, sectionSeparatorStrings}.Parse() -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/analyzer/errors.go b/tools/vendor/github.com/daixiang0/gci/pkg/analyzer/errors.go deleted file mode 100644 index 83d78309..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/analyzer/errors.go +++ /dev/null @@ -1,16 +0,0 @@ -package analyzer - -import "fmt" - -type InvalidNumberOfFilesInAnalysis struct { - expectedNumFiles, foundNumFiles int -} - -func (i InvalidNumberOfFilesInAnalysis) Error() string { - return fmt.Sprintf("Expected %d files in Analyzer input, Found %d", i.expectedNumFiles, i.foundNumFiles) -} - -func (i InvalidNumberOfFilesInAnalysis) Is(err error) bool { - _, ok := err.(InvalidNumberOfFilesInAnalysis) - return ok -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/config/config.go b/tools/vendor/github.com/daixiang0/gci/pkg/config/config.go new file mode 100644 index 00000000..b32148b1 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/config/config.go @@ -0,0 +1,90 @@ +package config + +import ( + "io/ioutil" + "sort" + "strings" + + "gopkg.in/yaml.v3" + + "github.com/daixiang0/gci/pkg/section" +) + +var defaultOrder = map[string]int{ + section.StandardType: 0, + section.DefaultType: 1, + section.CustomType: 2, + section.BlankType: 3, + section.DotType: 4, +} + +type BoolConfig struct { + NoInlineComments bool `yaml:"no-inlineComments"` + NoPrefixComments bool `yaml:"no-prefixComments"` + Debug bool `yaml:"-"` + SkipGenerated bool `yaml:"skipGenerated"` + CustomOrder bool `yaml:"customOrder"` +} + +type Config struct { + BoolConfig + Sections section.SectionList + SectionSeparators section.SectionList +} + +type YamlConfig struct { + Cfg BoolConfig `yaml:",inline"` + SectionStrings []string `yaml:"sections"` + SectionSeparatorStrings []string `yaml:"sectionseparators"` +} + +func (g YamlConfig) Parse() (*Config, error) { + var err error + + sections, err := section.Parse(g.SectionStrings) + if err != nil { + return nil, err + } + if sections == nil { + sections = section.DefaultSections() + } + + // if default order sorted sections + if !g.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] + }) + } + + sectionSeparators, err := section.Parse(g.SectionSeparatorStrings) + if err != nil { + return nil, err + } + if sectionSeparators == nil { + sectionSeparators = section.DefaultSectionSeparators() + } + + return &Config{g.Cfg, sections, sectionSeparators}, nil +} + +func InitializeGciConfigFromYAML(filePath string) (*Config, error) { + config := YamlConfig{} + yamlData, err := ioutil.ReadFile(filePath) + if err != nil { + return nil, err + } + err = yaml.Unmarshal(yamlData, &config) + if err != nil { + return nil, err + } + gciCfg, err := config.Parse() + if err != nil { + return nil, err + } + return gciCfg, nil +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/configuration/formatter.go b/tools/vendor/github.com/daixiang0/gci/pkg/configuration/formatter.go deleted file mode 100644 index 6ac04847..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/configuration/formatter.go +++ /dev/null @@ -1,7 +0,0 @@ -package configuration - -type FormatterConfiguration struct { - NoInlineComments bool `yaml:"no-inlineComments"` - NoPrefixComments bool `yaml:"no-prefixComments"` - Debug bool `yaml:"-"` -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/constants/sequences.go b/tools/vendor/github.com/daixiang0/gci/pkg/constants/sequences.go deleted file mode 100644 index faf90d88..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/constants/sequences.go +++ /dev/null @@ -1,18 +0,0 @@ -package constants - -const ( - LineCommentFlag = "//" - BlockCommentStartFlag = "/*" - BlockCommentEndFlag = "*/" - ImportStartFlag = "\nimport (\n" - ImportEndFlag = "\n)" - - Blank = " " - Indent = "\t" - Linebreak = "\n" - - SectionSeparator = ":" - - ParameterOpeningBrackets = "(" - ParameterClosingBrackets = ")" -) diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/format/format.go b/tools/vendor/github.com/daixiang0/gci/pkg/format/format.go new file mode 100644 index 00000000..062701d2 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/format/format.go @@ -0,0 +1,46 @@ +package format + +import ( + "fmt" + + "github.com/daixiang0/gci/pkg/config" + "github.com/daixiang0/gci/pkg/log" + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/section" + "github.com/daixiang0/gci/pkg/specificity" +) + +type Block struct { + Start, End int +} + +type resultMap map[string][]*Block + +func Format(data []*parse.GciImports, cfg *config.Config) (resultMap, error) { + result := make(resultMap, len(cfg.Sections)) + for _, d := range data { + // determine match specificity for every available section + var bestSection section.Section + var bestSectionSpecificity specificity.MatchSpecificity = specificity.MisMatch{} + for _, section := range cfg.Sections { + sectionSpecificity := section.MatchSpecificity(d) + if sectionSpecificity.IsMoreSpecific(specificity.MisMatch{}) && sectionSpecificity.Equal(bestSectionSpecificity) { + // specificity is identical + // return nil, section.EqualSpecificityMatchError{} + return nil, nil + } + if sectionSpecificity.IsMoreSpecific(bestSectionSpecificity) { + // better match found + bestSectionSpecificity = sectionSpecificity + bestSection = section + } + } + if bestSection == nil { + return nil, section.NoMatchingSectionForImportError{Imports: d} + } + log.L().Debug(fmt.Sprintf("Matched import %v to section %s", d, bestSection)) + result[bestSection.String()] = append(result[bestSection.String()], &Block{d.Start, d.End}) + } + + return result, nil +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/configuration.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/configuration.go deleted file mode 100644 index f1ef7ed5..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/configuration.go +++ /dev/null @@ -1,58 +0,0 @@ -package gci - -import ( - "io/ioutil" - - "github.com/daixiang0/gci/pkg/configuration" - sectionsPkg "github.com/daixiang0/gci/pkg/gci/sections" - - "gopkg.in/yaml.v3" -) - -type GciConfiguration struct { - configuration.FormatterConfiguration - Sections SectionList - SectionSeparators SectionList -} - -type GciStringConfiguration struct { - Cfg configuration.FormatterConfiguration `yaml:",inline"` - SectionStrings []string `yaml:"sections"` - SectionSeparatorStrings []string `yaml:"sectionseparators"` -} - -func (g GciStringConfiguration) Parse() (*GciConfiguration, error) { - sections := DefaultSections() - var err error - if len(g.SectionStrings) > 0 { - sections, err = sectionsPkg.SectionParserInst.ParseSectionStrings(g.SectionStrings, true, true) - if err != nil { - return nil, err - } - } - sectionSeparators := DefaultSectionSeparators() - if len(g.SectionSeparatorStrings) > 0 { - sectionSeparators, err = sectionsPkg.SectionParserInst.ParseSectionStrings(g.SectionSeparatorStrings, false, false) - if err != nil { - return nil, err - } - } - return &GciConfiguration{g.Cfg, sections, sectionSeparators}, nil -} - -func initializeGciConfigFromYAML(filePath string) (*GciConfiguration, error) { - yamlCfg := GciStringConfiguration{} - yamlData, err := ioutil.ReadFile(filePath) - if err != nil { - return nil, err - } - err = yaml.Unmarshal(yamlData, &yamlCfg) - if err != nil { - return nil, err - } - gciCfg, err := yamlCfg.Parse() - if err != nil { - return nil, err - } - return gciCfg, nil -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/errors.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/errors.go deleted file mode 100644 index 6fde84f3..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/errors.go +++ /dev/null @@ -1,78 +0,0 @@ -package gci - -import ( - "errors" - "fmt" - - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - sectionsPkg "github.com/daixiang0/gci/pkg/gci/sections" -) - -type EqualSpecificityMatchError struct { - importDef importPkg.ImportDef - sectionA, sectionB sectionsPkg.Section -} - -func (e EqualSpecificityMatchError) Error() string { - return fmt.Sprintf("Import %s matched section %s and %s equally", e.importDef, e.sectionA, e.sectionB) -} - -func (e EqualSpecificityMatchError) Is(err error) bool { - _, ok := err.(EqualSpecificityMatchError) - return ok -} - -type NoMatchingSectionForImportError struct { - importDef importPkg.ImportDef -} - -func (n NoMatchingSectionForImportError) Error() string { - return fmt.Sprintf("No section found for Import: %v", n.importDef) -} - -func (n NoMatchingSectionForImportError) Is(err error) bool { - _, ok := err.(NoMatchingSectionForImportError) - return ok -} - -type InvalidImportSplitError struct { - segments []string -} - -func (i InvalidImportSplitError) Error() string { - return fmt.Sprintf("seperating the inline comment from the import yielded an invalid number of segments: %v", i.segments) -} - -func (i InvalidImportSplitError) Is(err error) bool { - _, ok := err.(InvalidImportSplitError) - return ok -} - -type InvalidAliasSplitError struct { - segments []string -} - -func (i InvalidAliasSplitError) Error() string { - return fmt.Sprintf("seperating the alias from the path yielded an invalid number of segments: %v", i.segments) -} - -func (i InvalidAliasSplitError) Is(err error) bool { - _, ok := err.(InvalidAliasSplitError) - return ok -} - -var MissingImportStatementError = FileParsingError{errors.New("no import statement present in File")} -var ImportStatementNotClosedError = FileParsingError{errors.New("import statement not closed")} - -type FileParsingError struct { - error -} - -func (f FileParsingError) Unwrap() error { - return f.error -} - -func (f FileParsingError) Is(err error) bool { - _, ok := err.(FileParsingError) - return ok -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/format.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/format.go deleted file mode 100644 index 10f762c3..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/format.go +++ /dev/null @@ -1,109 +0,0 @@ -package gci - -import ( - "bytes" - "fmt" - "strings" - - "github.com/daixiang0/gci/pkg/constants" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - sectionsPkg "github.com/daixiang0/gci/pkg/gci/sections" - "github.com/daixiang0/gci/pkg/gci/specificity" - - log "github.com/sirupsen/logrus" -) - -// Formats the import section of a Go file -func formatGoFile(input []byte, cfg GciConfiguration) ([]byte, error) { - startIndex := bytes.Index(input, []byte(constants.ImportStartFlag)) - if startIndex < 0 { - return nil, MissingImportStatementError - } - endIndexFromStart := bytes.Index(input[startIndex:], []byte(constants.ImportEndFlag)) - if endIndexFromStart < 0 { - return nil, ImportStatementNotClosedError - } - endIndex := startIndex + endIndexFromStart - - unformattedImports := input[startIndex+len(constants.ImportStartFlag) : endIndex] - formattedImports, err := formatImportBlock(unformattedImports, cfg) - if err != nil { - return nil, err - } - - var output []byte - output = append(output, input[:startIndex+len(constants.ImportStartFlag)]...) - output = append(output, formattedImports...) - output = append(output, input[endIndex+1:]...) - return output, nil -} - -// pprintImports prints the imports without quotes for logging -func pprintImports(imports []importPkg.ImportDef) string { - var sb strings.Builder - sb.WriteRune('[') - for i, imprt := range imports { - if i != 0 { - sb.WriteRune(' ') - } - sb.WriteString(imprt.UnquotedString()) - } - sb.WriteRune(']') - return sb.String() -} - -// Takes unsorted imports as byte array and formats them according to the specified sections -func formatImportBlock(input []byte, cfg GciConfiguration) ([]byte, error) { - //strings.ReplaceAll(input, "\r\n", linebreak) - lines := strings.Split(string(input), constants.Linebreak) - imports, err := parseToImportDefinitions(lines) - if err != nil { - return nil, fmt.Errorf("an error occured while trying to parse imports: %w", err) - } - log.WithField("imports", pprintImports(imports)).Debug("Parsed imports in file") - - // create mapping between sections and imports - sectionMap := make(map[sectionsPkg.Section][]importPkg.ImportDef, len(cfg.Sections)) - // find matching section for every importSpec - for _, i := range imports { - // determine match specificity for every available section - var bestSection sectionsPkg.Section - var bestSectionSpecificity specificity.MatchSpecificity = specificity.MisMatch{} - for _, section := range cfg.Sections { - sectionSpecificity := section.MatchSpecificity(i) - if sectionSpecificity.IsMoreSpecific(specificity.MisMatch{}) && sectionSpecificity.Equal(bestSectionSpecificity) { - // specificity is identical - return nil, EqualSpecificityMatchError{i, bestSection, section} - } - if sectionSpecificity.IsMoreSpecific(bestSectionSpecificity) { - // better match found - bestSectionSpecificity = sectionSpecificity - bestSection = section - } - } - if bestSection == nil { - return nil, NoMatchingSectionForImportError{i} - } - log.WithFields(log.Fields{"import": i.UnquotedString(), "section": bestSection}).Debug("Matched import to section") - - sectionMap[bestSection] = append(sectionMap[bestSection], i) - } - // format every section to a str - var sectionStrings []string - for _, section := range cfg.Sections { - sectionStr := section.Format(sectionMap[section], cfg.FormatterConfiguration) - // prevent adding an empty section which would cause a separator to be inserted - if sectionStr != "" { - log.WithFields(log.Fields{"imports": pprintImports(sectionMap[section]), "section": section}).Debug("Formatting section with imports") - sectionStrings = append(sectionStrings, sectionStr) - } - } - // format sectionSeparators - var sectionSeparatorStr string - for _, sectionSep := range cfg.SectionSeparators { - sectionSeparatorStr += sectionSep.Format([]importPkg.ImportDef{}, cfg.FormatterConfiguration) - } - // generate output by joining the sections - output := strings.Join(sectionStrings, sectionSeparatorStr) - return []byte(output), nil -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/gci.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/gci.go index 0d70f5df..a8a64a27 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/gci.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/gci/gci.go @@ -5,62 +5,50 @@ import ( "errors" "fmt" "os" - - sectionsPkg "github.com/daixiang0/gci/pkg/gci/sections" - "github.com/daixiang0/gci/pkg/io" + "sync" "github.com/hexops/gotextdiff" "github.com/hexops/gotextdiff/myers" "github.com/hexops/gotextdiff/span" - log "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" -) - -type SectionList []sectionsPkg.Section - -func (list SectionList) String() []string { - var output []string - for _, section := range list { - output = append(output, section.String()) - } - return output -} -func DefaultSections() SectionList { - return SectionList{sectionsPkg.StandardPackage{}, sectionsPkg.DefaultSection{nil, nil}} -} + "github.com/daixiang0/gci/pkg/config" + "github.com/daixiang0/gci/pkg/format" + "github.com/daixiang0/gci/pkg/io" + "github.com/daixiang0/gci/pkg/log" + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/section" + "github.com/daixiang0/gci/pkg/utils" +) -func DefaultSectionSeparators() SectionList { - return SectionList{sectionsPkg.NewLine{}} -} -func LocalFlagsToSections(localFlags []string) SectionList { - sections := DefaultSections() +func LocalFlagsToSections(localFlags []string) section.SectionList { + sections := section.DefaultSections() // Add all local arguments as ImportPrefix sections - for _, prefix := range localFlags { - sections = append(sections, sectionsPkg.Prefix{prefix, nil, nil}) - } + // for _, l := range localFlags { + // sections = append(sections, section.Section{l, nil, nil}) + // } return sections } -func PrintFormattedFiles(paths []string, cfg GciConfiguration) error { +func PrintFormattedFiles(paths []string, cfg config.Config) error { return processStdInAndGoFilesInPaths(paths, cfg, func(filePath string, unmodifiedFile, formattedFile []byte) error { fmt.Print(string(formattedFile)) return nil }) } -func WriteFormattedFiles(paths []string, cfg GciConfiguration) error { +func WriteFormattedFiles(paths []string, cfg config.Config) error { return processGoFilesInPaths(paths, cfg, func(filePath string, unmodifiedFile, formattedFile []byte) error { if bytes.Equal(unmodifiedFile, formattedFile) { - log.WithField("file", filePath).Debug("Skipping correctly formatted file") + log.L().Debug(fmt.Sprintf("Skipping correctly formatted File: %s", filePath)) return nil } - log.WithField("file", filePath).Info("Writing formatted file") - return os.WriteFile(filePath, formattedFile, 0644) + log.L().Info(fmt.Sprintf("Writing formatted File: %s", filePath)) + return os.WriteFile(filePath, formattedFile, 0o644) }) } -func DiffFormattedFiles(paths []string, cfg GciConfiguration) error { +func DiffFormattedFiles(paths []string, cfg config.Config) error { return processStdInAndGoFilesInPaths(paths, cfg, func(filePath string, unmodifiedFile, formattedFile []byte) error { fileURI := span.URIFromPath(filePath) edits := myers.ComputeEdits(fileURI, string(unmodifiedFile), string(formattedFile)) @@ -70,17 +58,31 @@ func DiffFormattedFiles(paths []string, cfg GciConfiguration) error { }) } +func DiffFormattedFilesToArray(paths []string, cfg config.Config, diffs *[]string, lock *sync.Mutex) error { + log.InitLogger() + defer log.L().Sync() + return processStdInAndGoFilesInPaths(paths, cfg, func(filePath string, unmodifiedFile, formattedFile []byte) error { + fileURI := span.URIFromPath(filePath) + edits := myers.ComputeEdits(fileURI, string(unmodifiedFile), string(formattedFile)) + unifiedEdits := gotextdiff.ToUnified(filePath, filePath, string(unmodifiedFile), edits) + lock.Lock() + *diffs = append(*diffs, fmt.Sprint(unifiedEdits)) + lock.Unlock() + return nil + }) +} + type fileFormattingFunc func(filePath string, unmodifiedFile, formattedFile []byte) error -func processStdInAndGoFilesInPaths(paths []string, cfg GciConfiguration, fileFunc fileFormattingFunc) error { - return processFiles(io.StdInGenerator.Combine(io.GoFilesInPathsGenerator(paths)), cfg, fileFunc) +func processStdInAndGoFilesInPaths(paths []string, cfg config.Config, fileFunc fileFormattingFunc) error { + return ProcessFiles(io.StdInGenerator.Combine(io.GoFilesInPathsGenerator(paths)), cfg, fileFunc) } -func processGoFilesInPaths(paths []string, cfg GciConfiguration, fileFunc fileFormattingFunc) error { - return processFiles(io.GoFilesInPathsGenerator(paths), cfg, fileFunc) +func processGoFilesInPaths(paths []string, cfg config.Config, fileFunc fileFormattingFunc) error { + return ProcessFiles(io.GoFilesInPathsGenerator(paths), cfg, fileFunc) } -func processFiles(fileGenerator io.FileGeneratorFunc, cfg GciConfiguration, fileFunc fileFormattingFunc) error { +func ProcessFiles(fileGenerator io.FileGeneratorFunc, cfg config.Config, fileFunc fileFormattingFunc) error { var taskGroup errgroup.Group files, err := fileGenerator() if err != nil { @@ -93,35 +95,96 @@ func processFiles(fileGenerator io.FileGeneratorFunc, cfg GciConfiguration, file return taskGroup.Wait() } -func processingFunc(file io.FileObj, cfg GciConfiguration, formattingFunc fileFormattingFunc) func() error { +func processingFunc(file io.FileObj, cfg config.Config, formattingFunc fileFormattingFunc) func() error { return func() error { unmodifiedFile, formattedFile, err := LoadFormatGoFile(file, cfg) if err != nil { - if errors.Is(err, FileParsingError{}) { - // do not process files that are improperly formatted - return nil - } + // if errors.Is(err, FileParsingError{}) { + // // do not process files that are improperly formatted + // return nil + // } return err } return formattingFunc(file.Path(), unmodifiedFile, formattedFile) } } -func LoadFormatGoFile(file io.FileObj, cfg GciConfiguration) (unmodifiedFile, formattedFile []byte, err error) { - unmodifiedFile, err = file.Load() - log.WithField("file", file.Path()).Debug("Loaded file") +func LoadFormatGoFile(file io.FileObj, cfg config.Config) (src, dist []byte, err error) { + src, err = file.Load() + log.L().Debug(fmt.Sprintf("Loaded File: %s", file.Path())) if err != nil { return nil, nil, err } - formattedFile, err = formatGoFile(unmodifiedFile, cfg) + if cfg.SkipGenerated && parse.IsGeneratedFileByComment(string(src)) { + return src, src, nil + } + + imports, headEnd, tailStart, err := parse.ParseFile(src, file.Path()) if err != nil { - // ignore missing import statements - if !errors.Is(err, MissingImportStatementError) { - return unmodifiedFile, nil, err + if errors.Is(err, parse.NoImportError{}) { + return src, src, nil } - log.WithField("file", file.Path()).Debug("File does not contain an import statement") - formattedFile = unmodifiedFile + return nil, nil, err + } + + // do not do format if only one import + if len(imports) == 1 { + return src, src, nil + } + + result, err := format.Format(imports, &cfg) + if err != nil { + return nil, nil, err + } + + head := src[:headEnd] + tail := src[tailStart:] + + firstWithIndex := true + + var body []byte + + // order by section list + for _, s := range cfg.Sections { + if len(result[s.String()]) > 0 { + if body != nil && len(body) > 0 { + body = append(body, utils.Linebreak) + } + for _, d := range result[s.String()] { + AddIndent(&body, &firstWithIndex) + body = append(body, src[d.Start:d.End]...) + } + } + } + + // remove breakline in the end + for body[len(body)-1] == utils.Linebreak { + body = body[:len(body)-1] + } + + if tail[0] != utils.Linebreak { + body = append(body, utils.Linebreak) + } + + var totalLen int + slices := [][]byte{head, body, tail} + for _, s := range slices { + totalLen += len(s) + } + dist = make([]byte, totalLen) + var i int + for _, s := range slices { + i += copy(dist[i:], s) + } + + return src, dist, nil +} + +func AddIndent(in *[]byte, first *bool) { + if *first { + *first = false + return } - return unmodifiedFile, formattedFile, nil + *in = append(*in, utils.Indent) } diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/imports/errors.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/imports/errors.go deleted file mode 100644 index 49baa6d3..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/imports/errors.go +++ /dev/null @@ -1,37 +0,0 @@ -package imports - -import ( - "errors" - "fmt" -) - -type ValidationError struct { - error -} - -func (v ValidationError) Unwrap() error { - return v.error -} - -func (v ValidationError) Is(err error) bool { - _, ok := err.(ValidationError) - return ok -} - -var MissingOpeningQuotesError = ValidationError{errors.New("path is missing starting quotes")} - -var MissingClosingQuotesError = ValidationError{errors.New("path is missing closing quotes")} - -type InvalidCharacterError struct { - char rune - alias string -} - -func (i InvalidCharacterError) Error() string { - return fmt.Sprintf("Found non-letter character %q in Alias: %s", i.char, i.alias) -} - -func (i InvalidCharacterError) Is(err error) bool { - _, ok := err.(InvalidCharacterError) - return ok -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/imports/import.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/imports/import.go deleted file mode 100644 index 202477ca..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/imports/import.go +++ /dev/null @@ -1,91 +0,0 @@ -package imports - -import ( - "sort" - "strings" - "unicode" - - "github.com/daixiang0/gci/pkg/configuration" - "github.com/daixiang0/gci/pkg/constants" -) - -type ImportDef struct { - Alias string - QuotedPath string - PrefixComment []string - InlineComment string -} - -func (i ImportDef) Path() string { - return strings.TrimSuffix(strings.TrimPrefix(i.QuotedPath, string('"')), string('"')) -} - -// Validate checks whether the contents are valid for an import -func (i ImportDef) Validate() error { - err := checkAlias(i.Alias) - if err != nil { - return ValidationError{err} - } - if !strings.HasPrefix(i.QuotedPath, string('"')) { - return MissingOpeningQuotesError - } - if !strings.HasSuffix(i.QuotedPath, string('"')) { - return MissingClosingQuotesError - } - return nil -} - -func checkAlias(alias string) error { - for idx, r := range alias { - if !unicode.IsLetter(r) { - if r != '_' && r != '.' { - if idx == 0 || !unicode.IsDigit(r) { - // aliases may not start with a digit - return InvalidCharacterError{r, alias} - } - } - } - } - return nil -} - -func (i ImportDef) String() string { - return i.QuotedPath -} - -// useful for logging statements -func (i ImportDef) UnquotedString() string { - return strings.Trim(i.QuotedPath, "\"") -} - -func (i ImportDef) Format(cfg configuration.FormatterConfiguration) string { - linePrefix := constants.Indent - var output string - if cfg.NoPrefixComments == false || i.QuotedPath == `"C"` { - for _, prefixComment := range i.PrefixComment { - output += linePrefix + prefixComment + constants.Linebreak - } - } - output += linePrefix - if i.Alias != "" { - output += i.Alias + constants.Blank - } - output += i.QuotedPath - if cfg.NoInlineComments == false { - if i.InlineComment != "" { - output += constants.Blank + i.InlineComment - } - } - output += constants.Linebreak - return output -} - -func SortImportsByPath(imports []ImportDef) []ImportDef { - sort.Slice( - imports, - func(i, j int) bool { - return sort.StringsAreSorted([]string{imports[i].Path(), imports[j].Path()}) - }, - ) - return imports -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/parse.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/parse.go deleted file mode 100644 index df310050..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/parse.go +++ /dev/null @@ -1,91 +0,0 @@ -package gci - -import ( - "strings" - - "github.com/daixiang0/gci/pkg/constants" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" -) - -// Recursively parses import lines into a list of ImportDefs -func parseToImportDefinitions(unformattedLines []string) ([]importPkg.ImportDef, error) { - newImport := importPkg.ImportDef{} - inBlockComment := false - for index, unformattedLine := range unformattedLines { - line := strings.TrimSpace(unformattedLine) - if line == "" { - //empty line --> starts a new import - return parseToImportDefinitions(unformattedLines[index+1:]) - } - if strings.HasPrefix(line, constants.LineCommentFlag) { - // comment line - newImport.PrefixComment = append(newImport.PrefixComment, line) - continue - } - - if blockCommentStartsOnThisLine := strings.HasPrefix(line, constants.BlockCommentStartFlag); inBlockComment || blockCommentStartsOnThisLine { - blockCommentEndIndex := strings.Index(line, constants.BlockCommentEndFlag) - blockCommentEndsOnThisLine := blockCommentEndIndex != -1 - contentStartsAtIndex := 0 - contentEndsAtIndex := len(line) - - if blockCommentStartsOnThisLine { - newImport.PrefixComment = append(newImport.PrefixComment, constants.BlockCommentStartFlag) - contentStartsAtIndex = len(constants.BlockCommentStartFlag) - } - - if blockCommentEndsOnThisLine { - contentEndsAtIndex = blockCommentEndIndex - } - - if content := strings.TrimSpace(line[contentStartsAtIndex:contentEndsAtIndex]); content != "" { - newImport.PrefixComment = append(newImport.PrefixComment, "\t"+content) - } - - inBlockComment = !blockCommentEndsOnThisLine - - if !blockCommentEndsOnThisLine { - continue - } - - newImport.PrefixComment = append(newImport.PrefixComment, constants.BlockCommentEndFlag) - line = line[blockCommentEndIndex+len(constants.BlockCommentEndFlag):] - - if line == "" { - continue - } - } - - // split inline comment from import - importSegments := strings.SplitN(line, constants.LineCommentFlag, 2) - switch len(importSegments) { - case 1: - // no inline comment - case 2: - // inline comment present - newImport.InlineComment = constants.LineCommentFlag + importSegments[1] - default: - return nil, InvalidImportSplitError{importSegments} - } - // split alias from path - pkgArray := strings.Fields(importSegments[0]) - switch len(pkgArray) { - case 1: - // only a path - newImport.QuotedPath = pkgArray[0] - case 2: - // alias + path - newImport.Alias = pkgArray[0] - newImport.QuotedPath = pkgArray[1] - default: - return nil, InvalidAliasSplitError{pkgArray} - } - err := newImport.Validate() - if err != nil { - return nil, err - } - followingImports, err := parseToImportDefinitions(unformattedLines[index+1:]) - return append([]importPkg.ImportDef{newImport}, followingImports...), err - } - return nil, nil -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/commentline.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/commentline.go deleted file mode 100644 index 428644b1..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/commentline.go +++ /dev/null @@ -1,51 +0,0 @@ -package sections - -import ( - "fmt" - "strings" - - "github.com/daixiang0/gci/pkg/configuration" - "github.com/daixiang0/gci/pkg/constants" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - "github.com/daixiang0/gci/pkg/gci/specificity" -) - -func init() { - commentLineType := SectionType{ - generatorFun: func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { - return CommentLine{parameter}, nil - }, - aliases: []string{"Comment", "CommentLine"}, - parameterHelp: "your text here", - description: "Prints the specified indented comment", - }.StandAloneSection() - SectionParserInst.registerSectionWithoutErr(&commentLineType) -} - -type CommentLine struct { - Comment string -} - -func (c CommentLine) MatchSpecificity(spec importPkg.ImportDef) specificity.MatchSpecificity { - return specificity.MisMatch{} -} - -func (c CommentLine) Format(imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string { - comment := constants.Indent + "//" + c.Comment - if !strings.HasSuffix(comment, constants.Linebreak) { - comment += constants.Linebreak - } - return comment -} - -func (c CommentLine) sectionPrefix() Section { - return nil -} - -func (c CommentLine) sectionSuffix() Section { - return nil -} - -func (c CommentLine) String() string { - return fmt.Sprintf("CommentLine(%s)", c.Comment) -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/default.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/default.go deleted file mode 100644 index aca04f4e..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/default.go +++ /dev/null @@ -1,43 +0,0 @@ -package sections - -import ( - "github.com/daixiang0/gci/pkg/configuration" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - "github.com/daixiang0/gci/pkg/gci/specificity" -) - -func init() { - defaultSectionType := SectionType{ - generatorFun: func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { - return DefaultSection{sectionPrefix, sectionSuffix}, nil - }, - aliases: []string{"Def", "Default"}, - description: "Contains all imports that could not be matched to another section type", - }.WithoutParameter() - SectionParserInst.registerSectionWithoutErr(&defaultSectionType) -} - -type DefaultSection struct { - Prefix Section - Suffix Section -} - -func (d DefaultSection) sectionPrefix() Section { - return d.Prefix -} - -func (d DefaultSection) sectionSuffix() Section { - return d.Suffix -} - -func (d DefaultSection) MatchSpecificity(spec importPkg.ImportDef) specificity.MatchSpecificity { - return specificity.Default{} -} - -func (d DefaultSection) Format(imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string { - return inorderSectionFormat(d, imports, cfg) -} - -func (d DefaultSection) String() string { - return sectionStringWithPrefixSuffix("Default", d) -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/errors.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/errors.go deleted file mode 100644 index 3cc720d5..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/errors.go +++ /dev/null @@ -1,68 +0,0 @@ -package sections - -import ( - "errors" - "fmt" - - "github.com/daixiang0/gci/pkg/constants" -) - -type SectionParsingError struct { - error -} - -func (s SectionParsingError) Unwrap() error { - return s.error -} - -func (s SectionParsingError) Wrap(sectionStr string) error { - return fmt.Errorf("failed to parse section %q: %w", sectionStr, s) -} - -func (s SectionParsingError) Is(err error) bool { - _, ok := err.(SectionParsingError) - return ok -} - -type TypeAlreadyRegisteredError struct { - duplicateAlias string - newType, existingType SectionType -} - -func (t TypeAlreadyRegisteredError) Error() string { - return fmt.Sprintf("New type %q could not be registered because alias %q was already defined in %q", t.newType, t.duplicateAlias, t.existingType) -} - -func (t TypeAlreadyRegisteredError) Is(err error) bool { - _, ok := err.(TypeAlreadyRegisteredError) - return ok -} - -var PrefixNotAllowedError = errors.New("section may not contain a Prefix") - -var SuffixNotAllowedError = errors.New("section may not contain a Suffix") - -var SectionFormatInvalidError = errors.New("section Definition does not match format [FormattingSection:]Section[:FormattingSection]") - -type SectionAliasNotRegisteredWithParser struct { - missingAlias string -} - -func (s SectionAliasNotRegisteredWithParser) Error() string { - return fmt.Sprintf("section alias %q not registered with parser", s.missingAlias) -} - -func (s SectionAliasNotRegisteredWithParser) Is(err error) bool { - _, ok := err.(SectionAliasNotRegisteredWithParser) - return ok -} - -var MissingParameterClosingBracketsError = fmt.Errorf("section parameter is missing closing %q", constants.ParameterClosingBrackets) - -var MoreThanOneOpeningQuotesError = fmt.Errorf("found more than one %q parameter start sequences", constants.ParameterClosingBrackets) - -var SectionTypeDoesNotAcceptParametersError = errors.New("section type does not accept a parameter") - -var SectionTypeDoesNotAcceptPrefixError = errors.New("section may not contain a Prefix") - -var SectionTypeDoesNotAcceptSuffixError = errors.New("section may not contain a Suffix") diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/newline.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/newline.go deleted file mode 100644 index b54788b6..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/newline.go +++ /dev/null @@ -1,41 +0,0 @@ -package sections - -import ( - "github.com/daixiang0/gci/pkg/configuration" - "github.com/daixiang0/gci/pkg/constants" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - "github.com/daixiang0/gci/pkg/gci/specificity" -) - -func init() { - newLineType := SectionType{ - generatorFun: func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { - return NewLine{}, nil - }, - aliases: []string{"NL", "NewLine"}, - description: "Prints an empty line", - }.StandAloneSection().WithoutParameter() - SectionParserInst.registerSectionWithoutErr(&newLineType) -} - -type NewLine struct{} - -func (n NewLine) sectionPrefix() Section { - return nil -} - -func (n NewLine) sectionSuffix() Section { - return nil -} - -func (n NewLine) MatchSpecificity(spec importPkg.ImportDef) specificity.MatchSpecificity { - return specificity.MisMatch{} -} - -func (n NewLine) Format(imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string { - return constants.Linebreak -} - -func (n NewLine) String() string { - return "NewLine" -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/prefix.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/prefix.go deleted file mode 100644 index 49b30b24..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/prefix.go +++ /dev/null @@ -1,51 +0,0 @@ -package sections - -import ( - "fmt" - "strings" - - "github.com/daixiang0/gci/pkg/configuration" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - "github.com/daixiang0/gci/pkg/gci/specificity" -) - -func init() { - prefixType := &SectionType{ - generatorFun: func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { - return Prefix{parameter, sectionPrefix, sectionSuffix}, nil - }, - aliases: []string{"Prefix", "pkgPrefix"}, - parameterHelp: "gitlab.com/myorg", - description: "Groups all imports with the specified Prefix. Imports will be matched to the longest Prefix.", - } - SectionParserInst.registerSectionWithoutErr(prefixType) -} - -type Prefix struct { - ImportPrefix string - Prefix Section - Suffix Section -} - -func (p Prefix) sectionPrefix() Section { - return p.Prefix -} - -func (p Prefix) sectionSuffix() Section { - return p.Suffix -} - -func (p Prefix) MatchSpecificity(spec importPkg.ImportDef) specificity.MatchSpecificity { - if len(p.ImportPrefix) > 0 && strings.HasPrefix(spec.Path(), p.ImportPrefix) { - return specificity.Match{len(p.ImportPrefix)} - } - return specificity.MisMatch{} -} - -func (p Prefix) Format(imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string { - return inorderSectionFormat(p, imports, cfg) -} - -func (p Prefix) String() string { - return sectionStringWithPrefixSuffix(fmt.Sprintf("Prefix(%s)", p.ImportPrefix), p) -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/section.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/section.go deleted file mode 100644 index cbfd4674..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/section.go +++ /dev/null @@ -1,58 +0,0 @@ -package sections - -import ( - "fmt" - - "github.com/daixiang0/gci/pkg/configuration" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - "github.com/daixiang0/gci/pkg/gci/specificity" -) - -// Section defines a part of the formatted output. -type Section interface { - // MatchSpecificity returns how well an Import matches to this Section - MatchSpecificity(spec importPkg.ImportDef) specificity.MatchSpecificity - // Format receives the array of imports that have matched this section and formats them according to it´s rules - Format(imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string - // Returns the Section that will be prefixed if this section is rendered - sectionPrefix() Section - // Returns the Section that will be suffixed if this section is rendered - sectionSuffix() Section - // String Implements the stringer interface - String() string -} - -//Unbound methods that are required until interface methods are supported - -// Default method for formatting a section -func inorderSectionFormat(section Section, imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string { - imports = importPkg.SortImportsByPath(imports) - var output string - if len(imports) > 0 && section.sectionPrefix() != nil { - // imports are not passed to a prefix section to prevent rendering them twice - output += section.sectionPrefix().Format([]importPkg.ImportDef{}, cfg) - } - for _, importDef := range imports { - output += importDef.Format(cfg) - } - if len(imports) > 0 && section.sectionSuffix() != nil { - // imports are not passed to a suffix section to prevent rendering them twice - output += section.sectionSuffix().Format([]importPkg.ImportDef{}, cfg) - } - return output -} - -// Default method for converting a section to a String representation -func sectionStringWithPrefixSuffix(mainSectionStr string, section Section) (output string) { - if section.sectionPrefix() != nil { - output += fmt.Sprintf("%v:", section.sectionPrefix()) - } else if section.sectionSuffix() != nil { - // insert empty prefix to make suffix distinguishable from prefix - output += ":" - } - output += mainSectionStr - if section.sectionSuffix() != nil { - output += fmt.Sprintf(":%v", section.sectionSuffix()) - } - return output -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/sectionparser.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/sectionparser.go deleted file mode 100644 index b0b89a14..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/sectionparser.go +++ /dev/null @@ -1,139 +0,0 @@ -package sections - -import ( - "fmt" - "strings" - - "github.com/daixiang0/gci/pkg/constants" -) - -var SectionParserInst = SectionParser{} - -type SectionParser struct { - sectionTypes []SectionType -} - -func (s *SectionParser) RegisterSection(newSectionType *SectionType) error { - for _, existingSectionType := range s.sectionTypes { - for _, alias := range existingSectionType.aliases { - for _, newAlias := range newSectionType.aliases { - if alias == newAlias { - return TypeAlreadyRegisteredError{alias, *newSectionType, existingSectionType} - } - } - } - } - s.sectionTypes = append(s.sectionTypes, *newSectionType) - return nil -} - -func (s *SectionParser) registerSectionWithoutErr(newSectionType *SectionType) { - err := s.RegisterSection(newSectionType) - if err != nil { - panic(err) - } -} - -func (s *SectionParser) ParseSectionStrings(sectionStrings []string, withSuffix, withPrefix bool) ([]Section, error) { - var parsedSections []Section - for _, sectionStr := range sectionStrings { - section, err := s.parseSectionString(sectionStr, withSuffix, withPrefix) - if err != nil { - return nil, SectionParsingError{err}.Wrap(sectionStr) - } - parsedSections = append(parsedSections, section) - } - return parsedSections, nil -} - -func (s *SectionParser) parseSectionString(sectionStr string, withSuffix, withPrefix bool) (Section, error) { - trimmedSection := strings.TrimSpace(sectionStr) - sectionSegments := strings.Split(trimmedSection, constants.SectionSeparator) - switch len(sectionSegments) { - case 1: - // section - return s.parseSectionStringComponents("", sectionSegments[0], "") - case 2: - // prefix + section - if !withPrefix { - return nil, PrefixNotAllowedError - } - return s.parseSectionStringComponents(sectionSegments[0], sectionSegments[1], "") - case 3: - // prefix + section + suffix - if !withPrefix { - return nil, PrefixNotAllowedError - } - if !withSuffix { - return nil, SuffixNotAllowedError - } - return s.parseSectionStringComponents(sectionSegments[0], sectionSegments[1], sectionSegments[2]) - } - return nil, SectionFormatInvalidError -} - -func (s *SectionParser) parseSectionStringComponents(sectionPrefixStr string, sectionStr string, sectionSuffixStr string) (Section, error) { - var sectionPrefix, sectionSuffix Section - var err error - if len(sectionPrefixStr) > 0 { - sectionPrefix, err = s.createSectionFromString(sectionPrefixStr, nil, nil) - if err != nil { - return nil, fmt.Errorf("section prefix %q could not be parsed: %w", sectionPrefixStr, err) - } - } - if len(sectionSuffixStr) > 0 { - sectionSuffix, err = s.createSectionFromString(sectionSuffixStr, nil, nil) - if err != nil { - return nil, fmt.Errorf("section suffix %q could not be parsed: %w", sectionSuffixStr, err) - } - } - section, err := s.createSectionFromString(sectionStr, sectionPrefix, sectionSuffix) - if err != nil { - return nil, err - } - return section, nil -} - -func (s *SectionParser) createSectionFromString(sectionStr string, prefixSection, suffixSection Section) (Section, error) { - // create map of all aliases - aliasMap := map[string]SectionType{} - for _, sectionType := range s.sectionTypes { - for _, alias := range sectionType.aliases { - aliasMap[strings.ToLower(alias)] = sectionType - } - } - // parse everything before the parameter brackets - sectionComponents := strings.Split(sectionStr, constants.ParameterOpeningBrackets) - alias := sectionComponents[0] - sectionType, exists := aliasMap[strings.ToLower(alias)] - if !exists { - return nil, SectionAliasNotRegisteredWithParser{alias} - } - switch len(sectionComponents) { - case 1: - return sectionType.generatorFun("", prefixSection, suffixSection) - case 2: - if strings.HasSuffix(sectionComponents[1], constants.ParameterClosingBrackets) { - return sectionType.generatorFun(strings.TrimSuffix(sectionComponents[1], constants.ParameterClosingBrackets), prefixSection, suffixSection) - } else { - return nil, MissingParameterClosingBracketsError - } - } - return nil, MoreThanOneOpeningQuotesError -} - -func (s *SectionParser) SectionHelpTexts() string { - help := "" - for _, sectionType := range s.sectionTypes { - var aliasesWithParameters []string - for _, alias := range sectionType.aliases { - parameterSuffix := "" - if sectionType.parameterHelp != "" { - parameterSuffix = "(" + sectionType.parameterHelp + ")" - } - aliasesWithParameters = append(aliasesWithParameters, alias+parameterSuffix) - } - help += fmt.Sprintf("%s - %s\n", strings.Join(aliasesWithParameters, " | "), sectionType.description) - } - return help -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/sectiontype.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/sectiontype.go deleted file mode 100644 index 30287678..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/sectiontype.go +++ /dev/null @@ -1,40 +0,0 @@ -package sections - -import ( - "fmt" -) - -// A SectionType is used to dynamically register Sections with the parser -type SectionType struct { - generatorFun func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) - aliases []string - parameterHelp string - description string -} - -func (t SectionType) WithoutParameter() SectionType { - generatorFun := func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { - if parameter != "" { - return nil, SectionTypeDoesNotAcceptParametersError - } - return t.generatorFun(parameter, sectionPrefix, sectionSuffix) - } - return SectionType{generatorFun, t.aliases, "", t.description} -} - -func (t SectionType) StandAloneSection() SectionType { - generatorFun := func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { - if sectionPrefix != nil { - return nil, SectionTypeDoesNotAcceptPrefixError - } - if sectionSuffix != nil { - return nil, SectionTypeDoesNotAcceptSuffixError - } - return t.generatorFun(parameter, sectionPrefix, sectionSuffix) - } - return SectionType{generatorFun, t.aliases, t.parameterHelp, t.description} -} - -func (t SectionType) String() string { - return fmt.Sprintf("Sectiontype(aliases: %v,description: %s)", t.aliases, t.description) -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/standardpackage.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/standardpackage.go deleted file mode 100644 index b53475b0..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/standardpackage.go +++ /dev/null @@ -1,51 +0,0 @@ -package sections - -import ( - "github.com/daixiang0/gci/pkg/configuration" - importPkg "github.com/daixiang0/gci/pkg/gci/imports" - "github.com/daixiang0/gci/pkg/gci/specificity" -) - -func init() { - standardPackageType := SectionType{ - generatorFun: func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { - return StandardPackage{sectionPrefix, sectionSuffix}, nil - }, - aliases: []string{"Std", "Standard"}, - description: "Captures all standard packages if they do not match another section", - }.WithoutParameter() - SectionParserInst.registerSectionWithoutErr(&standardPackageType) -} - -type StandardPackage struct { - prefix Section - suffix Section -} - -func (s StandardPackage) sectionPrefix() Section { - return s.prefix -} - -func (s StandardPackage) sectionSuffix() Section { - return s.suffix -} - -func (s StandardPackage) MatchSpecificity(spec importPkg.ImportDef) specificity.MatchSpecificity { - if isStandardPackage(spec.Path()) { - return specificity.StandardPackageMatch{} - } - return specificity.MisMatch{} -} - -func (s StandardPackage) Format(imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string { - return inorderSectionFormat(s, imports, cfg) -} - -func (s StandardPackage) String() string { - return sectionStringWithPrefixSuffix("Standard", s) -} - -func isStandardPackage(pkg string) bool { - _, ok := standardPackages[pkg] - return ok -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/standard.go b/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/standard.go deleted file mode 100644 index 30e8f8f9..00000000 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/standard.go +++ /dev/null @@ -1,20 +0,0 @@ -package specificity - -type StandardPackageMatch struct { -} - -func (s StandardPackageMatch) IsMoreSpecific(than MatchSpecificity) bool { - return isMoreSpecific(s, than) -} - -func (s StandardPackageMatch) Equal(to MatchSpecificity) bool { - return equalSpecificity(s, to) -} - -func (s StandardPackageMatch) class() specificityClass { - return StandardPackageClass -} - -func (s StandardPackageMatch) String() string { - return "Standard" -} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/io/stdin.go b/tools/vendor/github.com/daixiang0/gci/pkg/io/stdin.go index 5d92768d..ccab2844 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/io/stdin.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/io/stdin.go @@ -5,8 +5,7 @@ import ( "os" ) -type stdInFile struct { -} +type stdInFile struct{} func (s stdInFile) Load() ([]byte, error) { return ioutil.ReadAll(os.Stdin) diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/log/log.go b/tools/vendor/github.com/daixiang0/gci/pkg/log/log.go new file mode 100644 index 00000000..ab33739c --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/log/log.go @@ -0,0 +1,50 @@ +package log + +import ( + "sync" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +// Use L to log with Zap +var logger *zap.Logger + +// Keep the config to reference the atomicLevel for changing levels +var logConfig zap.Config + +var doOnce sync.Once + +// InitLogger sets up the logger +func InitLogger() { + doOnce.Do(func() { + logConfig = zap.NewDevelopmentConfig() + + logConfig.EncoderConfig.TimeKey = "timestamp" + logConfig.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + logConfig.Level.SetLevel(zapcore.InfoLevel) + logConfig.OutputPaths = []string{"stderr"} + + var err error + logger, err = logConfig.Build() + if err != nil { + panic(err) + } + }) +} + +// SetLevel allows you to set the level of the default gci logger. +// This will not work if you replace the logger +func SetLevel(level zapcore.Level) { + logConfig.Level.SetLevel(level) +} + +// L returns the logger +func L() *zap.Logger { + return logger +} + +// SetLogger allows you to set the logger to whatever you want +func SetLogger(l *zap.Logger) { + logger = l +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/parse/parse.go b/tools/vendor/github.com/daixiang0/gci/pkg/parse/parse.go new file mode 100644 index 00000000..d84ed133 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/parse/parse.go @@ -0,0 +1,139 @@ +package parse + +import ( + "go/ast" + "go/parser" + "go/token" + "sort" + "strings" +) + +type GciImports struct { + // original index of import group, include doc, name, path and comment + Start, End int + Name, Path string +} +type ImportList []*GciImports + +func (l ImportList) Len() int { + return len(l) +} + +func (l ImportList) Less(i, j int) bool { + if strings.Compare(l[i].Path, l[j].Path) == 0 { + return strings.Compare(l[i].Name, l[j].Name) < 0 + } + + return strings.Compare(l[i].Path, l[j].Path) < 0 +} + +func (l ImportList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } + +/* + * AST considers a import block as below: + * ``` + * Doc + * Name Path Comment + * ``` + * An example is like below: + * ``` + * // test + * test "fmt" // test + * ``` + * getImports return a import block with name, start and end index + */ +func getImports(imp *ast.ImportSpec) (start, end int, name string) { + if imp.Doc != nil { + // doc poc need minus one to get the first index of comment + start = int(imp.Doc.Pos()) - 1 + } else { + if imp.Name != nil { + // name pos need minus one too + start = int(imp.Name.Pos()) - 1 + } else { + // path pos start without quote, need minus one for it + start = int(imp.Path.Pos()) - 1 + } + } + + if imp.Name != nil { + name = imp.Name.Name + } + + if imp.Comment != nil { + end = int(imp.Comment.End()) + } else { + end = int(imp.Path.End()) + } + return +} + +func ParseFile(src []byte, filename string) (ImportList, int, int, error) { + fileSet := token.NewFileSet() + f, err := parser.ParseFile(fileSet, filename, src, parser.ParseComments) + if err != nil { + return nil, 0, 0, err + } + + if len(f.Imports) == 0 { + return nil, 0, 0, NoImportError{} + } + + var headEnd int + var tailStart int + + var data ImportList + for i, imp := range f.Imports { + start, end, name := getImports(imp) + + if i == 0 { + headEnd = start + } + if i == len(f.Imports)-1 { + tailStart = end + } + + data = append(data, &GciImports{ + Start: start, + End: end, + Name: name, + Path: strings.Trim(imp.Path.Value, `"`), + }) + } + + sort.Sort(data) + return data, headEnd, tailStart, nil +} + +// IsGeneratedFileByComment reports whether the source file is generated code. +// Using a bit laxer rules than https://golang.org/s/generatedcode to +// match more generated code. +// Taken from https://github.com/golangci/golangci-lint. +func IsGeneratedFileByComment(in string) bool { + const ( + genCodeGenerated = "code generated" + genDoNotEdit = "do not edit" + genAutoFile = "autogenerated file" // easyjson + ) + + markers := []string{genCodeGenerated, genDoNotEdit, genAutoFile} + in = strings.ToLower(in) + for _, marker := range markers { + if strings.Contains(in, marker) { + return true + } + } + + return false +} + +type NoImportError struct{} + +func (n NoImportError) Error() string { + return "No imports" +} + +func (i NoImportError) Is(err error) bool { + _, ok := err.(NoImportError) + return ok +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/blank.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/blank.go new file mode 100644 index 00000000..4a274177 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/blank.go @@ -0,0 +1,25 @@ +package section + +import ( + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +type Blank struct{} + +const BlankType = "blank" + +func (b Blank) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + if spec.Name == "_" { + return specificity.NameMatch{} + } + return specificity.MisMatch{} +} + +func (b Blank) String() string { + return BlankType +} + +func (b Blank) Type() string { + return BlankType +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/commentline.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/commentline.go new file mode 100644 index 00000000..c3ddd082 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/commentline.go @@ -0,0 +1,24 @@ +package section + +import ( + "fmt" + + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +type CommentLine struct { + Comment string +} + +func (c CommentLine) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + return specificity.MisMatch{} +} + +func (c CommentLine) String() string { + return fmt.Sprintf("commentline(%s)", c.Comment) +} + +func (c CommentLine) Type() string { + return "commentline" +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/default.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/default.go new file mode 100644 index 00000000..3af07a09 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/default.go @@ -0,0 +1,22 @@ +package section + +import ( + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +const DefaultType = "default" + +type Default struct{} + +func (d Default) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + return specificity.Default{} +} + +func (d Default) String() string { + return DefaultType +} + +func (d Default) Type() string { + return DefaultType +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/dot.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/dot.go new file mode 100644 index 00000000..8112eeb1 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/dot.go @@ -0,0 +1,25 @@ +package section + +import ( + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +type Dot struct{} + +const DotType = "dot" + +func (d Dot) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + if spec.Name == "." { + return specificity.NameMatch{} + } + return specificity.MisMatch{} +} + +func (d Dot) String() string { + return DotType +} + +func (d Dot) Type() string { + return DotType +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/errors.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/errors.go new file mode 100644 index 00000000..1aa42ecd --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/errors.go @@ -0,0 +1,107 @@ +package section + +import ( + "errors" + "fmt" + + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/utils" +) + +type SectionParsingError struct { + error +} + +func (s SectionParsingError) Unwrap() error { + return s.error +} + +func (s SectionParsingError) Wrap(sectionStr string) error { + return fmt.Errorf("failed to parse section %q: %w", sectionStr, s) +} + +func (s SectionParsingError) Is(err error) bool { + _, ok := err.(SectionParsingError) + return ok +} + +var MissingParameterClosingBracketsError = fmt.Errorf("section parameter is missing closing %q", utils.ParameterClosingBrackets) + +var MoreThanOneOpeningQuotesError = fmt.Errorf("found more than one %q parameter start sequences", utils.ParameterClosingBrackets) + +var SectionTypeDoesNotAcceptParametersError = errors.New("section type does not accept a parameter") + +var SectionTypeDoesNotAcceptPrefixError = errors.New("section may not contain a Prefix") + +var SectionTypeDoesNotAcceptSuffixError = errors.New("section may not contain a Suffix") + +type EqualSpecificityMatchError struct { + Imports *parse.GciImports + SectionA, SectionB Section +} + +func (e EqualSpecificityMatchError) Error() string { + return fmt.Sprintf("Import %v matched section %s and %s equally", e.Imports, e.SectionA, e.SectionB) +} + +func (e EqualSpecificityMatchError) Is(err error) bool { + _, ok := err.(EqualSpecificityMatchError) + return ok +} + +type NoMatchingSectionForImportError struct { + Imports *parse.GciImports +} + +func (n NoMatchingSectionForImportError) Error() string { + return fmt.Sprintf("No section found for Import: %v", n.Imports) +} + +func (n NoMatchingSectionForImportError) Is(err error) bool { + _, ok := err.(NoMatchingSectionForImportError) + return ok +} + +type InvalidImportSplitError struct { + segments []string +} + +func (i InvalidImportSplitError) Error() string { + return fmt.Sprintf("separating the inline comment from the import yielded an invalid number of segments: %v", i.segments) +} + +func (i InvalidImportSplitError) Is(err error) bool { + _, ok := err.(InvalidImportSplitError) + return ok +} + +type InvalidAliasSplitError struct { + segments []string +} + +func (i InvalidAliasSplitError) Error() string { + return fmt.Sprintf("separating the alias from the path yielded an invalid number of segments: %v", i.segments) +} + +func (i InvalidAliasSplitError) Is(err error) bool { + _, ok := err.(InvalidAliasSplitError) + return ok +} + +var ( + MissingImportStatementError = FileParsingError{errors.New("no import statement present in File")} + ImportStatementNotClosedError = FileParsingError{errors.New("import statement not closed")} +) + +type FileParsingError struct { + error +} + +func (f FileParsingError) Unwrap() error { + return f.error +} + +func (f FileParsingError) Is(err error) bool { + _, ok := err.(FileParsingError) + return ok +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/newline.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/newline.go new file mode 100644 index 00000000..4bff91b9 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/newline.go @@ -0,0 +1,22 @@ +package section + +import ( + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +const newLineName = "newline" + +type NewLine struct{} + +func (n NewLine) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + return specificity.MisMatch{} +} + +func (n NewLine) String() string { + return newLineName +} + +func (n NewLine) Type() string { + return newLineName +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/parser.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/parser.go new file mode 100644 index 00000000..9834dcd1 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/parser.go @@ -0,0 +1,44 @@ +package section + +import ( + "errors" + "fmt" + "strings" +) + +func Parse(data []string) (SectionList, error) { + if len(data) == 0 { + return nil, nil + } + + var list SectionList + var errString string + for _, d := range data { + s := strings.ToLower(d) + if len(s) == 0 { + return nil, nil + } + + if s == "default" { + list = append(list, Default{}) + } else if s == "standard" { + list = append(list, Standard{}) + } else if s == "newline" { + list = append(list, NewLine{}) + } else if strings.HasPrefix(s, "prefix(") && len(d) > 8 { + list = append(list, Custom{d[7 : len(d)-1]}) + } else if strings.HasPrefix(s, "commentline(") && len(d) > 13 { + list = append(list, Custom{d[12 : len(d)-1]}) + } else if s == "dot" { + list = append(list, Dot{}) + } else if s == "blank" { + list = append(list, Blank{}) + } else { + errString += fmt.Sprintf(" %s", s) + } + } + if errString != "" { + return nil, errors.New(fmt.Sprintf("invalid params:%s", errString)) + } + return list, nil +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/prefix.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/prefix.go new file mode 100644 index 00000000..92ef9637 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/prefix.go @@ -0,0 +1,30 @@ +package section + +import ( + "fmt" + "strings" + + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +type Custom struct { + Prefix string +} + +const CustomType = "custom" + +func (c Custom) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + if strings.HasPrefix(spec.Path, c.Prefix) { + return specificity.Match{Length: len(c.Prefix)} + } + return specificity.MisMatch{} +} + +func (c Custom) String() string { + return fmt.Sprintf("prefix(%s)", c.Prefix) +} + +func (c Custom) Type() string { + return CustomType +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/section.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/section.go new file mode 100644 index 00000000..cc0a43f2 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/section.go @@ -0,0 +1,36 @@ +package section + +import ( + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +// Section defines a part of the formatted output. +type Section interface { + // MatchSpecificity returns how well an Import matches to this Section + MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity + + // String Implements the stringer interface + String() string + + // return section type + Type() string +} + +type SectionList []Section + +func (list SectionList) String() []string { + var output []string + for _, section := range list { + output = append(output, section.String()) + } + return output +} + +func DefaultSections() SectionList { + return SectionList{Standard{}, Default{}} +} + +func DefaultSectionSeparators() SectionList { + return SectionList{NewLine{}} +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/section/standard.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/standard.go new file mode 100644 index 00000000..26c7e9dc --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/standard.go @@ -0,0 +1,30 @@ +package section + +import ( + "github.com/daixiang0/gci/pkg/parse" + "github.com/daixiang0/gci/pkg/specificity" +) + +const StandardType = "standard" + +type Standard struct{} + +func (s Standard) MatchSpecificity(spec *parse.GciImports) specificity.MatchSpecificity { + if isStandard(spec.Path) { + return specificity.StandardMatch{} + } + return specificity.MisMatch{} +} + +func (s Standard) String() string { + return StandardType +} + +func (s Standard) Type() string { + return StandardType +} + +func isStandard(pkg string) bool { + _, ok := standardPackages[pkg] + return ok +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/standardpackage_list.go b/tools/vendor/github.com/daixiang0/gci/pkg/section/standard_list.go similarity index 98% rename from tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/standardpackage_list.go rename to tools/vendor/github.com/daixiang0/gci/pkg/section/standard_list.go index 645233e0..b5d884d3 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/sections/standardpackage_list.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/section/standard_list.go @@ -1,6 +1,6 @@ -package sections +package section -// Code generated based on go1.18. DO NOT EDIT. +// Code generated based on go1.18.4. DO NOT EDIT. var standardPackages = map[string]struct{}{ "archive/tar": {}, diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/default.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/default.go similarity index 93% rename from tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/default.go rename to tools/vendor/github.com/daixiang0/gci/pkg/specificity/default.go index 2d91bd8b..f7ae4b87 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/default.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/default.go @@ -1,11 +1,11 @@ package specificity -type Default struct { -} +type Default struct{} func (d Default) IsMoreSpecific(than MatchSpecificity) bool { return isMoreSpecific(d, than) } + func (d Default) Equal(to MatchSpecificity) bool { return equalSpecificity(d, to) } diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/match.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/match.go similarity index 100% rename from tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/match.go rename to tools/vendor/github.com/daixiang0/gci/pkg/specificity/match.go diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/mismatch.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/mismatch.go similarity index 92% rename from tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/mismatch.go rename to tools/vendor/github.com/daixiang0/gci/pkg/specificity/mismatch.go index 78013e34..8e871114 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/mismatch.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/mismatch.go @@ -1,7 +1,6 @@ package specificity -type MisMatch struct { -} +type MisMatch struct{} func (m MisMatch) IsMoreSpecific(than MatchSpecificity) bool { return isMoreSpecific(m, than) @@ -17,5 +16,4 @@ func (m MisMatch) class() specificityClass { func (m MisMatch) String() string { return "Mismatch" - } diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/specificity/name.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/name.go new file mode 100644 index 00000000..1900a0ac --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/name.go @@ -0,0 +1,19 @@ +package specificity + +type NameMatch struct{} + +func (n NameMatch) IsMoreSpecific(than MatchSpecificity) bool { + return isMoreSpecific(n, than) +} + +func (n NameMatch) Equal(to MatchSpecificity) bool { + return equalSpecificity(n, to) +} + +func (n NameMatch) class() specificityClass { + return NameClass +} + +func (n NameMatch) String() string { + return "Name" +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/specificity.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/specificity.go similarity index 74% rename from tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/specificity.go rename to tools/vendor/github.com/daixiang0/gci/pkg/specificity/specificity.go index 32b6e280..842da185 100644 --- a/tools/vendor/github.com/daixiang0/gci/pkg/gci/specificity/specificity.go +++ b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/specificity.go @@ -3,10 +3,11 @@ package specificity type specificityClass int const ( - MisMatchClass = 0 - DefaultClass = 10 - StandardPackageClass = 20 - MatchClass = 30 + MisMatchClass = 0 + DefaultClass = 10 + StandardClass = 20 + MatchClass = 30 + NameClass = 40 ) // MatchSpecificity is used to determine which section matches an import best @@ -16,8 +17,6 @@ type MatchSpecificity interface { class() specificityClass } -//Unbound methods that are required until interface methods are supported - func isMoreSpecific(this, than MatchSpecificity) bool { return this.class() > than.class() } diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/specificity/standard.go b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/standard.go new file mode 100644 index 00000000..72ccaf7e --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/specificity/standard.go @@ -0,0 +1,19 @@ +package specificity + +type StandardMatch struct{} + +func (s StandardMatch) IsMoreSpecific(than MatchSpecificity) bool { + return isMoreSpecific(s, than) +} + +func (s StandardMatch) Equal(to MatchSpecificity) bool { + return equalSpecificity(s, to) +} + +func (s StandardMatch) class() specificityClass { + return StandardClass +} + +func (s StandardMatch) String() string { + return "Standard" +} diff --git a/tools/vendor/github.com/daixiang0/gci/pkg/utils/constants.go b/tools/vendor/github.com/daixiang0/gci/pkg/utils/constants.go new file mode 100644 index 00000000..b1de2ea2 --- /dev/null +++ b/tools/vendor/github.com/daixiang0/gci/pkg/utils/constants.go @@ -0,0 +1,11 @@ +package utils + +const ( + Indent = '\t' + Linebreak = '\n' + + SectionSeparator = ":" + + ParameterOpeningBrackets = "(" + ParameterClosingBrackets = ")" +) diff --git a/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go b/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go index 465cce2d..6ad97ab4 100644 --- a/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go +++ b/tools/vendor/github.com/firefart/nonamedreturns/analyzer/analyzer.go @@ -1,6 +1,7 @@ package analyzer import ( + "flag" "go/ast" "go/types" @@ -9,14 +10,26 @@ import ( "golang.org/x/tools/go/ast/inspector" ) +const FlagReportErrorInDefer = "report-error-in-defer" + var Analyzer = &analysis.Analyzer{ Name: "nonamedreturns", Doc: "Reports all named returns", + Flags: flags(), Run: run, Requires: []*analysis.Analyzer{inspect.Analyzer}, } +func flags() flag.FlagSet { + fs := flag.FlagSet{} + fs.Bool(FlagReportErrorInDefer, false, "report named error if it is assigned inside defer") + return fs +} + func run(pass *analysis.Pass) (interface{}, error) { + reportErrorInDefer := pass.Analyzer.Flags.Lookup(FlagReportErrorInDefer).Value.String() == "true" + errorType := types.Universe.Lookup("error").Type() + inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) // only filter function defintions @@ -27,12 +40,15 @@ func run(pass *analysis.Pass) (interface{}, error) { inspector.Preorder(nodeFilter, func(node ast.Node) { var funcResults *ast.FieldList + var funcBody *ast.BlockStmt switch n := node.(type) { case *ast.FuncLit: funcResults = n.Type.Results + funcBody = n.Body case *ast.FuncDecl: funcResults = n.Type.Results + funcBody = n.Body default: return } @@ -51,6 +67,16 @@ func run(pass *analysis.Pass) (interface{}, error) { } for _, n := range p.Names { + if n.Name == "_" { + continue + } + + if !reportErrorInDefer && + types.Identical(pass.TypesInfo.TypeOf(p.Type), errorType) && + findDeferWithVariableAssignment(funcBody, pass.TypesInfo, pass.TypesInfo.ObjectOf(n)) { + continue + } + pass.Reportf(node.Pos(), "named return %q with type %q found", n.Name, types.ExprString(p.Type)) } } @@ -58,3 +84,51 @@ func run(pass *analysis.Pass) (interface{}, error) { return nil, nil } + +func findDeferWithVariableAssignment(body *ast.BlockStmt, info *types.Info, variable types.Object) bool { + found := false + + ast.Inspect(body, func(node ast.Node) bool { + if found { + return false // stop inspection + } + + if d, ok := node.(*ast.DeferStmt); ok { + if fn, ok2 := d.Call.Fun.(*ast.FuncLit); ok2 { + if findVariableAssignment(fn.Body, info, variable) { + found = true + return false + } + } + } + + return true + }) + + return found +} + +func findVariableAssignment(body *ast.BlockStmt, info *types.Info, variable types.Object) bool { + found := false + + ast.Inspect(body, func(node ast.Node) bool { + if found { + return false // stop inspection + } + + if a, ok := node.(*ast.AssignStmt); ok { + for _, lh := range a.Lhs { + if i, ok2 := lh.(*ast.Ident); ok2 { + if info.ObjectOf(i) == variable { + found = true + return false + } + } + } + } + + return true + }) + + return found +} diff --git a/tools/vendor/github.com/fzipp/gocyclo/CHANGELOG.md b/tools/vendor/github.com/fzipp/gocyclo/CHANGELOG.md index 774a6112..c9bedfb3 100644 --- a/tools/vendor/github.com/fzipp/gocyclo/CHANGELOG.md +++ b/tools/vendor/github.com/fzipp/gocyclo/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.6.0] - 2022-06-15 +### Changed +- Breaking: remove meaningless `-total` and `-total-short` options + ## [0.5.1] - 2022-04-06 ### Fixed - Don't skip directories `.` and `..` diff --git a/tools/vendor/github.com/fzipp/gocyclo/README.md b/tools/vendor/github.com/fzipp/gocyclo/README.md index 3b009a9d..d357b8ef 100644 --- a/tools/vendor/github.com/fzipp/gocyclo/README.md +++ b/tools/vendor/github.com/fzipp/gocyclo/README.md @@ -51,8 +51,6 @@ Flags: -top N show the top N most complex functions only -avg, -avg-short show the average complexity over all functions; the short option prints the value without a label - -total, -total-short show the total complexity for all functions; - the short option prints the value without a label -ignore REGEX exclude files matching the given regular expression The output fields for each line are: diff --git a/tools/vendor/github.com/fzipp/gocyclo/stats.go b/tools/vendor/github.com/fzipp/gocyclo/stats.go index 90f5eefc..0a377e4b 100644 --- a/tools/vendor/github.com/fzipp/gocyclo/stats.go +++ b/tools/vendor/github.com/fzipp/gocyclo/stats.go @@ -52,7 +52,7 @@ func (s Stats) TotalComplexity() uint64 { func (s Stats) SortAndFilter(top, over int) Stats { result := make(Stats, len(s)) copy(result, s) - sort.Sort(byComplexityDesc(result)) + sort.Stable(byComplexityDesc(result)) for i, stat := range result { if i == top { return result[:i] diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/embedded_rules.go b/tools/vendor/github.com/go-critic/go-critic/checkers/embedded_rules.go index d9ede0bc..8a53ee5e 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/embedded_rules.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/embedded_rules.go @@ -15,7 +15,7 @@ import ( //go:generate go run ./rules/precompile.go -rules ./rules/rules.go -o ./rulesdata/rulesdata.go -func init() { +func InitEmbeddedRules() { filename := "rules/rules.go" fset := token.NewFileSet() 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 c430431a..910be180 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,7 @@ import ( "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/framework/linter" + "golang.org/x/exp/typeparams" ) func init() { @@ -49,8 +50,11 @@ func (c *hugeParamChecker) checkParams(params []*ast.Field) { for _, p := range params { for _, id := range p.Names { typ := c.ctx.TypeOf(id) - size := c.ctx.SizesInfo.Sizeof(typ) - if size >= c.sizeThreshold { + if _, ok := typ.(*typeparams.TypeParam); ok { + continue + } + size, ok := c.ctx.SizeOf(typ) + if ok && size >= c.sizeThreshold { c.warn(id, size) } } diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go index 8cdad4ee..c80e6f8b 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go @@ -5,6 +5,7 @@ import ( "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/framework/linter" + "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astequal" ) @@ -38,10 +39,12 @@ func (c *paramTypeCombineChecker) VisitFuncDecl(decl *ast.FuncDecl) { } func (c *paramTypeCombineChecker) optimizeFuncType(f *ast.FuncType) *ast.FuncType { - return &ast.FuncType{ - Params: c.optimizeParams(f.Params), - Results: c.optimizeParams(f.Results), - } + optimizedParamFunc := astcopy.FuncType(f) + + optimizedParamFunc.Params = c.optimizeParams(f.Params) + optimizedParamFunc.Results = c.optimizeParams(f.Results) + + return optimizedParamFunc } func (c *paramTypeCombineChecker) optimizeParams(params *ast.FieldList) *ast.FieldList { // To avoid false positives, skip unnamed param lists. diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go index 5615af46..813fff36 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go @@ -69,7 +69,7 @@ func (c *rangeExprCopyChecker) VisitStmt(stmt ast.Stmt) { if _, ok := tv.Type.(*types.Array); !ok { return } - if size := c.ctx.SizesInfo.Sizeof(tv.Type); size >= c.sizeThreshold { + if size, ok := c.ctx.SizeOf(tv.Type); ok && size >= c.sizeThreshold { c.warn(rng, size) } } diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go index b34aa5c2..eafc549d 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go @@ -5,6 +5,7 @@ import ( "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/framework/linter" + "golang.org/x/exp/typeparams" ) func init() { @@ -65,7 +66,10 @@ func (c *rangeValCopyChecker) VisitStmt(stmt ast.Stmt) { if typ == nil { return } - if size := c.ctx.SizesInfo.Sizeof(typ); size >= c.sizeThreshold { + if _, ok := typ.(*typeparams.TypeParam); ok { + return + } + if size, ok := c.ctx.SizeOf(typ); ok && size >= c.sizeThreshold { c.warn(rng, size) } } 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 e145ba4f..fd63c9b1 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 @@ -2060,6 +2060,71 @@ var PrecompiledRules = &ir.File{ }, { Line: 662, + 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: 667, + SyntaxPatterns: []ir.PatternString{{Line: 667, Value: "!$t.Before($tt)"}}, + ReportTemplate: "suggestion: $t.After($tt)", + SuggestTemplate: "$t.After($tt)", + WhereExpr: ir.FilterExpr{ + Line: 668, + Op: ir.FilterOrOp, + Src: "isTime(m[\"t\"])", + Args: []ir.FilterExpr{ + { + Line: 668, + Op: ir.FilterVarTypeIsOp, + Src: "m[\"t\"].Type.Is(`time.Time`)", + Value: "t", + Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, + }, + { + Line: 668, + Op: ir.FilterVarTypeIsOp, + Src: "m[\"t\"].Type.Is(`*time.Time`)", + Value: "t", + Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, + }, + }, + }, + }, + { + Line: 671, + SyntaxPatterns: []ir.PatternString{{Line: 671, Value: "!$t.After($tt)"}}, + ReportTemplate: "suggestion: $t.Before($tt)", + SuggestTemplate: "$t.Before($tt)", + WhereExpr: ir.FilterExpr{ + Line: 672, + Op: ir.FilterOrOp, + Src: "isTime(m[\"t\"])", + Args: []ir.FilterExpr{ + { + Line: 672, + Op: ir.FilterVarTypeIsOp, + Src: "m[\"t\"].Type.Is(`time.Time`)", + Value: "t", + Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`time.Time`", Value: "time.Time"}}, + }, + { + Line: 672, + Op: ir.FilterVarTypeIsOp, + Src: "m[\"t\"].Type.Is(`*time.Time`)", + Value: "t", + Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`*time.Time`", Value: "*time.Time"}}, + }, + }, + }, + }, + }, + }, + { + Line: 680, Name: "exposedSyncMutex", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -2068,57 +2133,57 @@ var PrecompiledRules = &ir.File{ DocAfter: "type Foo struct{ ...; mu sync.Mutex; ... }", Rules: []ir.Rule{ { - Line: 667, - SyntaxPatterns: []ir.PatternString{{Line: 667, Value: "type $x struct { $*_; sync.Mutex; $*_ }"}}, + Line: 685, + SyntaxPatterns: []ir.PatternString{{Line: 685, Value: "type $x struct { $*_; sync.Mutex; $*_ }"}}, ReportTemplate: "don't embed sync.Mutex", WhereExpr: ir.FilterExpr{ - Line: 668, + Line: 686, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 682, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, { - Line: 671, - SyntaxPatterns: []ir.PatternString{{Line: 671, Value: "type $x struct { $*_; *sync.Mutex; $*_ }"}}, + Line: 689, + SyntaxPatterns: []ir.PatternString{{Line: 689, Value: "type $x struct { $*_; *sync.Mutex; $*_ }"}}, ReportTemplate: "don't embed *sync.Mutex", WhereExpr: ir.FilterExpr{ - Line: 672, + Line: 690, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 682, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, { - Line: 675, - SyntaxPatterns: []ir.PatternString{{Line: 675, Value: "type $x struct { $*_; sync.RWMutex; $*_ }"}}, + Line: 693, + SyntaxPatterns: []ir.PatternString{{Line: 693, Value: "type $x struct { $*_; sync.RWMutex; $*_ }"}}, ReportTemplate: "don't embed sync.RWMutex", WhereExpr: ir.FilterExpr{ - Line: 676, + Line: 694, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 682, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, { - Line: 679, - SyntaxPatterns: []ir.PatternString{{Line: 679, Value: "type $x struct { $*_; *sync.RWMutex; $*_ }"}}, + Line: 697, + SyntaxPatterns: []ir.PatternString{{Line: 697, Value: "type $x struct { $*_; *sync.RWMutex; $*_ }"}}, ReportTemplate: "don't embed *sync.RWMutex", WhereExpr: ir.FilterExpr{ - Line: 680, + Line: 698, Op: ir.FilterVarTextMatchesOp, Src: "isExported(m[\"x\"])", Value: "x", - Args: []ir.FilterExpr{{Line: 664, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, + Args: []ir.FilterExpr{{Line: 682, Op: ir.FilterStringOp, Src: "`^\\p{Lu}`", Value: "^\\p{Lu}"}}, }, }, }, }, { - Line: 688, + Line: 706, Name: "badSorting", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2127,48 +2192,48 @@ var PrecompiledRules = &ir.File{ DocAfter: "sort.Strings(xs)", Rules: []ir.Rule{ { - Line: 689, - SyntaxPatterns: []ir.PatternString{{Line: 689, Value: "$x = sort.IntSlice($x)"}}, + Line: 707, + SyntaxPatterns: []ir.PatternString{{Line: 707, Value: "$x = sort.IntSlice($x)"}}, ReportTemplate: "suspicious sort.IntSlice usage, maybe sort.Ints was intended?", SuggestTemplate: "sort.Ints($x)", WhereExpr: ir.FilterExpr{ - Line: 690, + Line: 708, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]int`)", Value: "x", - Args: []ir.FilterExpr{{Line: 690, Op: ir.FilterStringOp, Src: "`[]int`", Value: "[]int"}}, + Args: []ir.FilterExpr{{Line: 708, Op: ir.FilterStringOp, Src: "`[]int`", Value: "[]int"}}, }, }, { - Line: 694, - SyntaxPatterns: []ir.PatternString{{Line: 694, Value: "$x = sort.Float64Slice($x)"}}, + Line: 712, + SyntaxPatterns: []ir.PatternString{{Line: 712, Value: "$x = sort.Float64Slice($x)"}}, ReportTemplate: "suspicious sort.Float64s usage, maybe sort.Float64s was intended?", SuggestTemplate: "sort.Float64s($x)", WhereExpr: ir.FilterExpr{ - Line: 695, + Line: 713, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]float64`)", Value: "x", - Args: []ir.FilterExpr{{Line: 695, Op: ir.FilterStringOp, Src: "`[]float64`", Value: "[]float64"}}, + Args: []ir.FilterExpr{{Line: 713, Op: ir.FilterStringOp, Src: "`[]float64`", Value: "[]float64"}}, }, }, { - Line: 699, - SyntaxPatterns: []ir.PatternString{{Line: 699, Value: "$x = sort.StringSlice($x)"}}, + Line: 717, + SyntaxPatterns: []ir.PatternString{{Line: 717, Value: "$x = sort.StringSlice($x)"}}, ReportTemplate: "suspicious sort.StringSlice usage, maybe sort.Strings was intended?", SuggestTemplate: "sort.Strings($x)", WhereExpr: ir.FilterExpr{ - Line: 700, + Line: 718, Op: ir.FilterVarTypeIsOp, Src: "m[\"x\"].Type.Is(`[]string`)", Value: "x", - Args: []ir.FilterExpr{{Line: 700, Op: ir.FilterStringOp, Src: "`[]string`", Value: "[]string"}}, + Args: []ir.FilterExpr{{Line: 718, Op: ir.FilterStringOp, Src: "`[]string`", Value: "[]string"}}, }, }, }, }, { - Line: 709, + Line: 727, Name: "externalErrorReassign", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2176,34 +2241,34 @@ var PrecompiledRules = &ir.File{ DocBefore: "io.EOF = nil", DocAfter: "/* don't do it */", Rules: []ir.Rule{{ - Line: 710, - SyntaxPatterns: []ir.PatternString{{Line: 710, Value: "$pkg.$err = $x"}}, + Line: 728, + SyntaxPatterns: []ir.PatternString{{Line: 728, Value: "$pkg.$err = $x"}}, ReportTemplate: "suspicious reassigment of error from another package", WhereExpr: ir.FilterExpr{ - Line: 711, + Line: 729, Op: ir.FilterAndOp, Src: "m[\"err\"].Type.Is(`error`) && m[\"pkg\"].Object.Is(`PkgName`)", Args: []ir.FilterExpr{ { - Line: 711, + Line: 729, Op: ir.FilterVarTypeIsOp, Src: "m[\"err\"].Type.Is(`error`)", Value: "err", - Args: []ir.FilterExpr{{Line: 711, Op: ir.FilterStringOp, Src: "`error`", Value: "error"}}, + Args: []ir.FilterExpr{{Line: 729, Op: ir.FilterStringOp, Src: "`error`", Value: "error"}}, }, { - Line: 711, + Line: 729, Op: ir.FilterVarObjectIsOp, Src: "m[\"pkg\"].Object.Is(`PkgName`)", Value: "pkg", - Args: []ir.FilterExpr{{Line: 711, Op: ir.FilterStringOp, Src: "`PkgName`", Value: "PkgName"}}, + Args: []ir.FilterExpr{{Line: 729, Op: ir.FilterStringOp, Src: "`PkgName`", Value: "PkgName"}}, }, }, }, }}, }, { - Line: 719, + Line: 737, Name: "emptyDecl", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2212,24 +2277,24 @@ var PrecompiledRules = &ir.File{ DocAfter: "/* nothing */", Rules: []ir.Rule{ { - Line: 720, - SyntaxPatterns: []ir.PatternString{{Line: 720, Value: "var()"}}, + Line: 738, + SyntaxPatterns: []ir.PatternString{{Line: 738, Value: "var()"}}, ReportTemplate: "empty var() block", }, { - Line: 721, - SyntaxPatterns: []ir.PatternString{{Line: 721, Value: "const()"}}, + Line: 739, + SyntaxPatterns: []ir.PatternString{{Line: 739, Value: "const()"}}, ReportTemplate: "empty const() block", }, { - Line: 722, - SyntaxPatterns: []ir.PatternString{{Line: 722, Value: "type()"}}, + Line: 740, + SyntaxPatterns: []ir.PatternString{{Line: 740, Value: "type()"}}, ReportTemplate: "empty type() block", }, }, }, { - Line: 729, + Line: 747, Name: "dynamicFmtString", MatcherName: "m", DocTags: []string{"diagnostic", "experimental"}, @@ -2238,16 +2303,16 @@ var PrecompiledRules = &ir.File{ DocAfter: "fmt.Errorf(\"%s\", msg)", Rules: []ir.Rule{ { - Line: 730, - SyntaxPatterns: []ir.PatternString{{Line: 730, Value: "fmt.Errorf($f)"}}, + Line: 748, + SyntaxPatterns: []ir.PatternString{{Line: 748, Value: "fmt.Errorf($f)"}}, ReportTemplate: "use errors.New($f) or fmt.Errorf(\"%s\", $f) instead", SuggestTemplate: "errors.New($f)", WhereExpr: ir.FilterExpr{ - Line: 731, + Line: 749, Op: ir.FilterNotOp, Src: "!m[\"f\"].Const", Args: []ir.FilterExpr{{ - Line: 731, + Line: 749, Op: ir.FilterVarConstOp, Src: "m[\"f\"].Const", Value: "f", @@ -2255,15 +2320,15 @@ var PrecompiledRules = &ir.File{ }, }, { - Line: 735, - SyntaxPatterns: []ir.PatternString{{Line: 735, Value: "fmt.Errorf($f($*args))"}}, + Line: 753, + SyntaxPatterns: []ir.PatternString{{Line: 753, Value: "fmt.Errorf($f($*args))"}}, ReportTemplate: "use errors.New($f($*args)) or fmt.Errorf(\"%s\", $f($*args)) instead", SuggestTemplate: "errors.New($f($*args))", }, }, }, { - Line: 744, + Line: 762, Name: "stringsCompare", MatcherName: "m", DocTags: []string{"style", "experimental"}, @@ -2272,25 +2337,25 @@ var PrecompiledRules = &ir.File{ DocAfter: "x < y", Rules: []ir.Rule{ { - Line: 745, - SyntaxPatterns: []ir.PatternString{{Line: 745, Value: "strings.Compare($s1, $s2) == 0"}}, + Line: 763, + SyntaxPatterns: []ir.PatternString{{Line: 763, Value: "strings.Compare($s1, $s2) == 0"}}, ReportTemplate: "suggestion: $s1 == $s2", SuggestTemplate: "$s1 == $s2", }, { - Line: 748, + Line: 766, SyntaxPatterns: []ir.PatternString{ - {Line: 748, Value: "strings.Compare($s1, $s2) == -1"}, - {Line: 749, Value: "strings.Compare($s1, $s2) < 0"}, + {Line: 766, Value: "strings.Compare($s1, $s2) == -1"}, + {Line: 767, Value: "strings.Compare($s1, $s2) < 0"}, }, ReportTemplate: "suggestion: $s1 < $s2", SuggestTemplate: "$s1 < $s2", }, { - Line: 752, + Line: 770, SyntaxPatterns: []ir.PatternString{ - {Line: 752, Value: "strings.Compare($s1, $s2) == 1"}, - {Line: 753, Value: "strings.Compare($s1, $s2) > 0"}, + {Line: 770, Value: "strings.Compare($s1, $s2) == 1"}, + {Line: 771, Value: "strings.Compare($s1, $s2) > 0"}, }, ReportTemplate: "suggestion: $s1 > $s2", SuggestTemplate: "$s1 > $s2", diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go index cd2346c7..9d40c2b6 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go @@ -96,8 +96,14 @@ func (c *truncateCmpChecker) checkCmp(cmpX, cmpY ast.Expr) { return } - xsize := c.ctx.SizesInfo.Sizeof(xtyp) - ysize := c.ctx.SizesInfo.Sizeof(ytyp) + xsize, ok := c.ctx.SizeOf(xtyp) + if !ok { + return + } + ysize, ok := c.ctx.SizeOf(ytyp) + if !ok { + return + } if xsize <= ysize { return } diff --git a/tools/vendor/github.com/go-critic/go-critic/checkers/typeDefFirst_checker.go b/tools/vendor/github.com/go-critic/go-critic/checkers/typeDefFirst_checker.go index 491e71df..bc59eef1 100644 --- a/tools/vendor/github.com/go-critic/go-critic/checkers/typeDefFirst_checker.go +++ b/tools/vendor/github.com/go-critic/go-critic/checkers/typeDefFirst_checker.go @@ -6,6 +6,7 @@ import ( "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/framework/linter" + "golang.org/x/exp/typeparams" ) func init() { @@ -78,6 +79,10 @@ func (c *typeDefFirstChecker) receiverType(e ast.Expr) string { return c.receiverType(e.X) case *ast.Ident: return e.Name + case *ast.IndexExpr: + return c.receiverType(e.X) + case *typeparams.IndexListExpr: + return c.receiverType(e.X) default: panic("unreachable") } diff --git a/tools/vendor/github.com/go-critic/go-critic/framework/linter/linter.go b/tools/vendor/github.com/go-critic/go-critic/framework/linter/linter.go index 1697ee7d..750ff7cd 100644 --- a/tools/vendor/github.com/go-critic/go-critic/framework/linter/linter.go +++ b/tools/vendor/github.com/go-critic/go-critic/framework/linter/linter.go @@ -6,6 +6,7 @@ import ( "go/types" "github.com/go-toolsmith/astfmt" + "golang.org/x/exp/typeparams" ) // CheckerCollection provides additional information for a group of checkers. @@ -314,6 +315,16 @@ func (ctx *CheckerContext) TypeOf(x ast.Expr) types.Type { return UnknownType } +// SizeOf returns the size of the typ in bytes. +// +// Unlike SizesInfo.SizeOf, it will not panic on generic types. +func (ctx *CheckerContext) SizeOf(typ types.Type) (int64, bool) { + if _, ok := typ.(*typeparams.TypeParam); ok { + return 0, false + } + return ctx.SizesInfo.Sizeof(typ), true +} + // FileWalker is an interface every checker should implement. // // The WalkFile method is executed for every Go file inside the diff --git a/tools/vendor/github.com/go-toolsmith/astcopy/astcopy.go b/tools/vendor/github.com/go-toolsmith/astcopy/astcopy.go index 2feffb19..393c5cab 100644 --- a/tools/vendor/github.com/go-toolsmith/astcopy/astcopy.go +++ b/tools/vendor/github.com/go-toolsmith/astcopy/astcopy.go @@ -3,6 +3,8 @@ package astcopy import ( "go/ast" + + "golang.org/x/exp/typeparams" ) // Node returns x node deep copy. @@ -341,6 +343,9 @@ func FuncType(x *ast.FuncType) *ast.FuncType { cp := *x cp.Params = FieldList(x.Params) cp.Results = FieldList(x.Results) + if typeParams := typeparams.ForFuncType(x); typeParams != nil { + *typeparams.ForFuncType(&cp) = *FieldList(typeParams) + } return &cp } @@ -429,6 +434,9 @@ func TypeSpec(x *ast.TypeSpec) *ast.TypeSpec { cp.Type = copyExpr(x.Type) cp.Doc = CommentGroup(x.Doc) cp.Comment = CommentGroup(x.Comment) + if typeParams := typeparams.ForTypeSpec(x); typeParams != nil { + *typeparams.ForTypeSpec(&cp) = *FieldList(typeParams) + } return &cp } diff --git a/tools/vendor/github.com/go-toolsmith/astequal/astequal.go b/tools/vendor/github.com/go-toolsmith/astequal/astequal.go index 6253fb49..b2ab0e64 100644 --- a/tools/vendor/github.com/go-toolsmith/astequal/astequal.go +++ b/tools/vendor/github.com/go-toolsmith/astequal/astequal.go @@ -4,6 +4,8 @@ package astequal import ( "go/ast" "go/token" + + "golang.org/x/exp/typeparams" ) // Node reports whether two AST nodes are structurally (deep) equal. @@ -316,7 +318,8 @@ func astFuncTypeEq(x, y *ast.FuncType) bool { return x == y } return astFieldListEq(x.Params, y.Params) && - astFieldListEq(x.Results, y.Results) + astFieldListEq(x.Results, y.Results) && + astFieldListEq(typeparams.ForFuncType(x), typeparams.ForFuncType(y)) } func astBasicLitEq(x, y *ast.BasicLit) bool { @@ -675,7 +678,8 @@ func astTypeSpecEq(x, y *ast.TypeSpec) bool { if x == nil || y == nil { return x == y } - return astIdentEq(x.Name, y.Name) && astExprEq(x.Type, y.Type) + return astIdentEq(x.Name, y.Name) && astExprEq(x.Type, y.Type) && + astFieldListEq(typeparams.ForTypeSpec(x), typeparams.ForTypeSpec(y)) } func astValueSpecEq(x, y *ast.ValueSpec) bool { diff --git a/tools/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go b/tools/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go index cc6606a3..fefb3998 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go +++ b/tools/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go @@ -58,7 +58,7 @@ func Open(dir string) (*Cache, error) { return nil, err } if !info.IsDir() { - return nil, &os.PathError{Op: "open", Path: dir, Err: fmt.Errorf("not a directory")} + return nil, &os.PathError{Op: "open", Path: dir, Err: errors.New("not a directory")} } for i := 0; i < 256; i++ { name := filepath.Join(dir, fmt.Sprintf("%02x", i)) @@ -504,7 +504,7 @@ func (c *Cache) copyFile(file io.ReadSeeker, out OutputID, size int64) error { sum := h.Sum(nil) if !bytes.Equal(sum, out[:]) { _ = f.Truncate(0) - return fmt.Errorf("file content changed underfoot") + return errors.New("file content changed underfoot") } // Commit cache file entry. diff --git a/tools/vendor/github.com/golangci/golangci-lint/internal/cache/default.go b/tools/vendor/github.com/golangci/golangci-lint/internal/cache/default.go index 66950062..4558fb26 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/internal/cache/default.go +++ b/tools/vendor/github.com/golangci/golangci-lint/internal/cache/default.go @@ -5,6 +5,7 @@ package cache import ( + "errors" "fmt" "log" "os" @@ -69,7 +70,7 @@ func DefaultDir() string { return } if defaultDir != "" { - defaultDirErr = fmt.Errorf("GOLANGCI_LINT_CACHE is not an absolute path") + defaultDirErr = errors.New("GOLANGCI_LINT_CACHE is not an absolute path") return } 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 ac3a3ee6..f95fdfae 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 @@ -8,7 +8,6 @@ import ( "github.com/spf13/cobra" "github.com/golangci/golangci-lint/internal/cache" - "github.com/golangci/golangci-lint/pkg/exitcodes" "github.com/golangci/golangci-lint/pkg/fsutils" "github.com/golangci/golangci-lint/pkg/logutils" ) @@ -17,67 +16,55 @@ func (e *Executor) initCache() { cacheCmd := &cobra.Command{ Use: "cache", Short: "Cache control and information", - Run: func(cmd *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint cache") - } - if err := cmd.Help(); err != nil { - e.log.Fatalf("Can't run cache: %s", err) - } + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return cmd.Help() }, } e.rootCmd.AddCommand(cacheCmd) cacheCmd.AddCommand(&cobra.Command{ - Use: "clean", - Short: "Clean cache", - Run: e.executeCleanCache, + Use: "clean", + Short: "Clean cache", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + RunE: e.executeCleanCache, }) cacheCmd.AddCommand(&cobra.Command{ - Use: "status", - Short: "Show cache status", - Run: e.executeCacheStatus, + Use: "status", + Short: "Show cache status", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + Run: e.executeCacheStatus, }) // TODO: add trim command? } -func (e *Executor) executeCleanCache(_ *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint cache clean") - } - +func (e *Executor) executeCleanCache(_ *cobra.Command, _ []string) error { cacheDir := cache.DefaultDir() if err := os.RemoveAll(cacheDir); err != nil { - e.log.Fatalf("Failed to remove dir %s: %s", cacheDir, err) + return fmt.Errorf("failed to remove dir %s: %w", cacheDir, err) } - os.Exit(exitcodes.Success) + return nil } -func (e *Executor) executeCacheStatus(_ *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint cache status") - } - +func (e *Executor) executeCacheStatus(_ *cobra.Command, _ []string) { cacheDir := cache.DefaultDir() 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)) } - - os.Exit(exitcodes.Success) } func dirSizeBytes(path string) (int64, error) { var size int64 err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if !info.IsDir() { - size += info.Size() + if err == nil && !info.IsDir() { + size = info.Size() } return err }) 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 e9546d32..a16ef631 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 @@ -15,21 +15,19 @@ func (e *Executor) initConfig() { cmd := &cobra.Command{ Use: "config", Short: "Config", - Run: func(cmd *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint config") - } - if err := cmd.Help(); err != nil { - e.log.Fatalf("Can't run help: %s", err) - } + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return cmd.Help() }, } e.rootCmd.AddCommand(cmd) pathCmd := &cobra.Command{ - Use: "path", - Short: "Print used config path", - Run: e.executePathCmd, + Use: "path", + Short: "Print used config path", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + Run: e.executePathCmd, } e.initRunConfiguration(pathCmd) // allow --config cmd.AddCommand(pathCmd) @@ -52,11 +50,7 @@ func (e *Executor) getUsedConfig() string { return prettyUsedConfigFile } -func (e *Executor) executePathCmd(_ *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint config path") - } - +func (e *Executor) executePathCmd(_ *cobra.Command, _ []string) { usedConfigFile := e.getUsedConfig() if usedConfigFile == "" { e.log.Warnf("No config file detected") @@ -64,5 +58,4 @@ func (e *Executor) executePathCmd(_ *cobra.Command, args []string) { } fmt.Println(usedConfigFile) - os.Exit(exitcodes.Success) } 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 index d9c747f6..2723f5c0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go @@ -117,11 +117,6 @@ func NewExecutor(version, commit, date string) *Executor { // recreate after getting config e.DBManager = lintersdb.NewManager(e.cfg, e.log).WithCustomLinters() - e.cfg.LintersSettings.Gocritic.InferEnabledChecks(e.log) - if err = e.cfg.LintersSettings.Gocritic.Validate(e.log); err != nil { - e.log.Fatalf("Invalid gocritic settings: %s", err) - } - // Slice options must be explicitly set for proper merging of config and command-line options. fixSlicesFlags(e.runCmd.Flags()) fixSlicesFlags(e.lintersCmd.Flags()) 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 a6ed4c84..61d362e7 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,14 +2,12 @@ package commands import ( "fmt" - "os" "sort" "strings" "github.com/fatih/color" "github.com/spf13/cobra" - "github.com/golangci/golangci-lint/pkg/exitcodes" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/logutils" ) @@ -18,21 +16,19 @@ func (e *Executor) initHelp() { helpCmd := &cobra.Command{ Use: "help", Short: "Help", - Run: func(cmd *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint help") - } - if err := cmd.Help(); err != nil { - e.log.Fatalf("Can't run help: %s", err) - } + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return cmd.Help() }, } e.rootCmd.SetHelpCommand(helpCmd) lintersHelpCmd := &cobra.Command{ - Use: "linters", - Short: "Help about linters", - Run: e.executeLintersHelp, + Use: "linters", + Short: "Help about linters", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + Run: e.executeLintersHelp, } helpCmd.AddCommand(lintersHelpCmd) } @@ -64,11 +60,7 @@ func printLinterConfigs(lcs []*linter.Config) { } } -func (e *Executor) executeLintersHelp(_ *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint help linters") - } - +func (e *Executor) executeLintersHelp(_ *cobra.Command, _ []string) { var enabledLCs, disabledLCs []*linter.Config for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { if lc.EnabledByDefault { @@ -93,6 +85,4 @@ func (e *Executor) executeLintersHelp(_ *cobra.Command, args []string) { sort.Strings(linterNames) fmt.Fprintf(logutils.StdOut, "%s: %s\n", color.YellowString(p), strings.Join(linterNames, ", ")) } - - os.Exit(exitcodes.Success) } 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 63328e4e..13bb944d 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 @@ -1,35 +1,31 @@ package commands import ( - "log" - "os" + "fmt" "github.com/fatih/color" "github.com/spf13/cobra" - "github.com/golangci/golangci-lint/pkg/exitcodes" "github.com/golangci/golangci-lint/pkg/lint/linter" ) func (e *Executor) initLinters() { e.lintersCmd = &cobra.Command{ - Use: "linters", - Short: "List current linters configuration", - Run: e.executeLinters, + Use: "linters", + Short: "List current linters configuration", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, + RunE: e.executeLinters, } e.rootCmd.AddCommand(e.lintersCmd) e.initRunConfiguration(e.lintersCmd) } // executeLinters runs the 'linters' CLI command, which displays the supported linters. -func (e *Executor) executeLinters(_ *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint linters") - } - +func (e *Executor) executeLinters(_ *cobra.Command, _ []string) error { enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap() if err != nil { - log.Fatalf("Can't get enabled linters: %s", err) + return fmt.Errorf("can't get enabled linters: %w", err) } color.Green("Enabled by your configuration linters:\n") @@ -49,5 +45,5 @@ func (e *Executor) executeLinters(_ *cobra.Command, args []string) { color.Red("\nDisabled by your configuration linters:\n") printLinterConfigs(disabledLCs) - os.Exit(exitcodes.Success) + 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 141fc87f..cc5a78dd 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 @@ -16,10 +16,10 @@ import ( "github.com/golangci/golangci-lint/pkg/logutils" ) -func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) { +func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) error { if e.cfg.Run.PrintVersion { - fmt.Fprintf(logutils.StdOut, "golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) - os.Exit(exitcodes.Success) + _, _ = fmt.Fprintf(logutils.StdOut, "golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) + os.Exit(exitcodes.Success) // a return nil is not enough to stop the process because we are inside the `preRun`. } runtime.GOMAXPROCS(e.cfg.Run.Concurrency) @@ -27,10 +27,10 @@ func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) { if e.cfg.Run.CPUProfilePath != "" { f, err := os.Create(e.cfg.Run.CPUProfilePath) if err != nil { - e.log.Fatalf("Can't create file %s: %s", e.cfg.Run.CPUProfilePath, err) + return fmt.Errorf("can't create file %s: %w", e.cfg.Run.CPUProfilePath, err) } if err := pprof.StartCPUProfile(f); err != nil { - e.log.Fatalf("Can't start CPU profiling: %s", err) + return fmt.Errorf("can't start CPU profiling: %w", err) } } @@ -43,22 +43,25 @@ func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) { if e.cfg.Run.TracePath != "" { f, err := os.Create(e.cfg.Run.TracePath) if err != nil { - e.log.Fatalf("Can't create file %s: %s", e.cfg.Run.TracePath, err) + return fmt.Errorf("can't create file %s: %w", e.cfg.Run.TracePath, err) } if err = trace.Start(f); err != nil { - e.log.Fatalf("Can't start tracing: %s", err) + return fmt.Errorf("can't start tracing: %w", err) } } + + return nil } -func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) { +func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) error { if e.cfg.Run.CPUProfilePath != "" { pprof.StopCPUProfile() } + if e.cfg.Run.MemProfilePath != "" { f, err := os.Create(e.cfg.Run.MemProfilePath) if err != nil { - e.log.Fatalf("Can't create file %s: %s", e.cfg.Run.MemProfilePath, err) + return fmt.Errorf("can't create file %s: %w", e.cfg.Run.MemProfilePath, err) } var ms runtime.MemStats @@ -66,15 +69,18 @@ func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) { printMemStats(&ms, e.log) if err := pprof.WriteHeapProfile(f); err != nil { - e.log.Fatalf("Can't write heap profile: %s", err) + return fmt.Errorf("cCan't write heap profile: %w", err) } - f.Close() + _ = f.Close() } + if e.cfg.Run.TracePath != "" { trace.Stop() } os.Exit(e.exitCode) + + return nil } func printMemStats(ms *runtime.MemStats, logger logutils.Log) { @@ -120,16 +126,12 @@ func (e *Executor) initRoot() { Use: "golangci-lint", Short: "golangci-lint is a smart linters runner.", Long: `Smart, fast linters runner. Run it in cloud for every GitHub pull request on https://golangci.com`, - Run: func(cmd *cobra.Command, args []string) { - if len(args) != 0 { - e.log.Fatalf("Usage: golangci-lint") - } - if err := cmd.Help(); err != nil { - e.log.Fatalf("Can't run help: %s", err) - } + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return cmd.Help() }, - PersistentPreRun: e.persistentPreRun, - PersistentPostRun: e.persistentPostRun, + PersistentPreRunE: e.persistentPreRun, + PersistentPostRunE: e.persistentPostRun, } initRootFlagSet(rootCmd.PersistentFlags(), e.cfg, e.needVersionOption()) 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 f4716d18..9f9d5ea4 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 @@ -279,10 +279,11 @@ func (e *Executor) initRun() { Use: "run", Short: "Run the linters", Run: e.executeRun, - PreRun: func(_ *cobra.Command, _ []string) { + PreRunE: func(_ *cobra.Command, _ []string) error { if ok := e.acquireFileLock(); !ok { - e.log.Fatalf("Parallel golangci-lint is running") + return errors.New("parallel golangci-lint is running") } + return nil }, PostRun: func(_ *cobra.Command, _ []string) { e.releaseFileLock() 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 8b48e515..93e4a8ed 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 @@ -3,6 +3,7 @@ package commands import ( "encoding/json" "fmt" + "os" "strings" "github.com/spf13/cobra" @@ -31,27 +32,28 @@ func initVersionFlagSet(fs *pflag.FlagSet, cfg *config.Config) { func (e *Executor) initVersion() { versionCmd := &cobra.Command{ - Use: "version", - Short: "Version", + Use: "version", + Short: "Version", + Args: cobra.NoArgs, + ValidArgsFunction: cobra.NoFileCompletions, RunE: func(cmd *cobra.Command, _ []string) error { switch strings.ToLower(e.cfg.Version.Format) { case "short": fmt.Println(e.version) + return nil + case "json": ver := jsonVersion{ Version: e.version, Commit: e.commit, Date: e.date, } - data, err := json.Marshal(&ver) - if err != nil { - return err - } - fmt.Println(string(data)) + return json.NewEncoder(os.Stdout).Encode(&ver) + default: fmt.Printf("golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) + return nil } - return nil }, } 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 0f9ac5f6..b2437ec9 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 @@ -97,7 +97,7 @@ var DefaultExcludePatterns = []ExcludePattern{ }, { ID: "EXC0015", - Pattern: `should have a package comment, unless it's in another file for this package`, + Pattern: `should have a package comment`, Linter: "revive", Why: "Annoying issue about not having a comment. The rare codebase has such comments", }, @@ -188,15 +188,16 @@ func GetDefaultExcludePatternsStrings() []string { return ret } +// TODO(ldez): this behavior must be changed in v2, because this is confusing. func GetExcludePatterns(include []string) []ExcludePattern { - includeMap := make(map[string]bool, len(include)) + includeMap := make(map[string]struct{}, len(include)) for _, inc := range include { - includeMap[inc] = true + includeMap[inc] = struct{}{} } var ret []ExcludePattern for _, p := range DefaultExcludePatterns { - if !includeMap[p.ID] { + if _, ok := includeMap[p.ID]; !ok { ret = append(ret, p) } } 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 3d479517..f1c36c38 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 @@ -7,6 +7,9 @@ import ( ) var defaultLintersSettings = LintersSettings{ + Asasalint: AsasalintSettings{ + UseBuiltinExclusions: true, + }, Decorder: DecorderSettings{ DecOrder: []string{"type", "const", "var", "func"}, DisableDecNumCheck: true, @@ -31,14 +34,14 @@ var defaultLintersSettings = LintersSettings{ ExcludeGodocExamples: true, }, Gci: GciSettings{ - Sections: []string{"standard", "default"}, - SectionSeparator: []string{"newline"}, + Sections: []string{"standard", "default"}, + SkipGenerated: true, }, Gocognit: GocognitSettings{ MinComplexity: 30, }, - Gocritic: GocriticSettings{ - SettingsPerCheck: map[string]GocriticCheckSettings{}, + Gocritic: GoCriticSettings{ + SettingsPerCheck: map[string]GoCriticCheckSettings{}, }, Godox: GodoxSettings{ Keywords: []string{}, @@ -74,7 +77,6 @@ var defaultLintersSettings = LintersSettings{ }, NoLintLint: NoLintLintSettings{ RequireExplanation: false, - AllowLeadingSpace: true, RequireSpecific: false, AllowUnused: false, }, @@ -88,7 +90,8 @@ var defaultLintersSettings = LintersSettings{ Qualified: false, }, Testpackage: TestpackageSettings{ - SkipRegexp: `(export|internal)_test\.go`, + SkipRegexp: `(export|internal)_test\.go`, + AllowPackages: []string{"main"}, }, Unparam: UnparamSettings{ Algo: "cha", @@ -112,6 +115,7 @@ var defaultLintersSettings = LintersSettings{ } type LintersSettings struct { + Asasalint AsasalintSettings BiDiChk BiDiChkSettings Cyclop Cyclop Decorder DecorderSettings @@ -129,7 +133,7 @@ type LintersSettings struct { Gci GciSettings Gocognit GocognitSettings Goconst GoConstSettings - Gocritic GocriticSettings + Gocritic GoCriticSettings Gocyclo GoCycloSettings Godot GodotSettings Godox GodoxSettings @@ -147,6 +151,7 @@ type LintersSettings struct { Grouper GrouperSettings Ifshort IfshortSettings ImportAs ImportAsSettings + InterfaceBloat InterfaceBloatSettings Ireturn IreturnSettings Lll LllSettings MaintIdx MaintIdxSettings @@ -158,9 +163,12 @@ type LintersSettings struct { NilNil NilNilSettings Nlreturn NlreturnSettings NoLintLint NoLintLintSettings + NoNamedReturns NoNamedReturnsSettings + ParallelTest ParallelTestSettings Prealloc PreallocSettings Predeclared PredeclaredSettings Promlinter PromlinterSettings + Reassign ReassignSettings Revive ReviveSettings RowsErrCheck RowsErrCheckSettings Staticcheck StaticCheckSettings @@ -172,6 +180,7 @@ type LintersSettings struct { Thelper ThelperSettings Unparam UnparamSettings Unused StaticCheckSettings + UseStdlibVars UseStdlibVarsSettings Varcheck VarCheckSettings Varnamelen VarnamelenSettings Whitespace WhitespaceSettings @@ -181,6 +190,12 @@ type LintersSettings struct { Custom map[string]CustomLinterSettings } +type AsasalintSettings struct { + Exclude []string `mapstructure:"exclude"` + UseBuiltinExclusions bool `mapstructure:"use-builtin-exclusions"` + IgnoreTest bool `mapstructure:"ignore-test"` +} + type BiDiChkSettings struct { LeftToRightEmbedding bool `mapstructure:"left-to-right-embedding"` RightToLeftEmbedding bool `mapstructure:"right-to-left-embedding"` @@ -272,11 +287,10 @@ type FunlenSettings struct { } type GciSettings struct { - LocalPrefixes string `mapstructure:"local-prefixes"` // Deprecated - NoInlineComments bool `mapstructure:"no-inline-comments"` - NoPrefixComments bool `mapstructure:"no-prefix-comments"` - Sections []string `mapstructure:"sections"` - SectionSeparator []string `mapstructure:"section-separators"` + LocalPrefixes string `mapstructure:"local-prefixes"` // Deprecated + Sections []string `mapstructure:"sections"` + SkipGenerated bool `mapstructure:"skip-generated"` + CustomOrder bool `mapstructure:"custom-order"` } type GocognitSettings struct { @@ -294,6 +308,16 @@ type GoConstSettings struct { IgnoreCalls bool `mapstructure:"ignore-calls"` } +type GoCriticSettings struct { + EnabledChecks []string `mapstructure:"enabled-checks"` + DisabledChecks []string `mapstructure:"disabled-checks"` + EnabledTags []string `mapstructure:"enabled-tags"` + DisabledTags []string `mapstructure:"disabled-tags"` + SettingsPerCheck map[string]GoCriticCheckSettings `mapstructure:"settings"` +} + +type GoCriticCheckSettings map[string]interface{} + type GoCycloSettings struct { MinComplexity int `mapstructure:"min-complexity"` } @@ -317,9 +341,11 @@ type GoFmtSettings struct { } type GofumptSettings struct { + ModulePath string `mapstructure:"module-path"` + ExtraRules bool `mapstructure:"extra-rules"` + + // Deprecated: use the global `run.go` instead. LangVersion string `mapstructure:"lang-version"` - ModulePath string `mapstructure:"module-path"` - ExtraRules bool `mapstructure:"extra-rules"` } type GoHeaderSettings struct { @@ -430,6 +456,10 @@ type ImportAsAlias struct { Alias string } +type InterfaceBloatSettings struct { + Max int `mapstructure:"max"` +} + type IreturnSettings struct { Allow []string `mapstructure:"allow"` Reject []string `mapstructure:"reject"` @@ -475,12 +505,18 @@ type NlreturnSettings struct { type NoLintLintSettings struct { RequireExplanation bool `mapstructure:"require-explanation"` - AllowLeadingSpace bool `mapstructure:"allow-leading-space"` RequireSpecific bool `mapstructure:"require-specific"` AllowNoExplanation []string `mapstructure:"allow-no-explanation"` AllowUnused bool `mapstructure:"allow-unused"` } +type NoNamedReturnsSettings struct { + ReportErrorInDefer bool `mapstructure:"report-error-in-defer"` +} +type ParallelTestSettings struct { + IgnoreMissing bool `mapstructure:"ignore-missing"` +} + type PreallocSettings struct { Simple bool RangeLoops bool `mapstructure:"range-loops"` @@ -497,6 +533,10 @@ type PromlinterSettings struct { DisabledLinters []string `mapstructure:"disabled-linters"` } +type ReassignSettings struct { + Patterns []string `mapstructure:"patterns"` +} + type ReviveSettings struct { MaxOpenFiles int `mapstructure:"max-open-files"` IgnoreGeneratedHeader bool `mapstructure:"ignore-generated-header"` @@ -522,6 +562,7 @@ type RowsErrCheckSettings struct { } type StaticCheckSettings struct { + // Deprecated: use the global `run.go` instead. GoVersion string `mapstructure:"go"` Checks []string `mapstructure:"checks"` @@ -546,7 +587,8 @@ type TagliatelleSettings struct { } type TestpackageSettings struct { - SkipRegexp string `mapstructure:"skip-regexp"` + SkipRegexp string `mapstructure:"skip-regexp"` + AllowPackages []string `mapstructure:"allow-packages"` } type ThelperSettings struct { @@ -566,6 +608,16 @@ type TenvSettings struct { All bool `mapstructure:"all"` } +type UseStdlibVarsSettings struct { + HTTPMethod bool `mapstructure:"http-method"` + HTTPStatusCode bool `mapstructure:"http-status-code"` + TimeWeekday bool `mapstructure:"time-weekday"` + TimeMonth bool `mapstructure:"time-month"` + TimeLayout bool `mapstructure:"time-layout"` + CryptoHash bool `mapstructure:"crypto-hash"` + DefaultRPCPathFlag bool `mapstructure:"default-rpc-path"` +} + type UnparamSettings struct { CheckExported bool `mapstructure:"check-exported"` Algo string @@ -617,12 +669,12 @@ 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 +// linters-settings: +// custom: +// example: +// path: /example.so +// description: The description of the linter +// original-url: github.com/golangci/example-linter type CustomLinterSettings struct { // Path to a plugin *.so file that implements the private linter. Path string diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters_settings_gocritic.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters_settings_gocritic.go deleted file mode 100644 index 9a3d03d9..00000000 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/linters_settings_gocritic.go +++ /dev/null @@ -1,366 +0,0 @@ -package config - -import ( - "fmt" - "sort" - "strings" - - _ "github.com/go-critic/go-critic/checkers" // this import register checkers - "github.com/go-critic/go-critic/framework/linter" - "github.com/pkg/errors" - - "github.com/golangci/golangci-lint/pkg/logutils" -) - -const gocriticDebugKey = "gocritic" - -var ( - gocriticDebugf = logutils.Debug(gocriticDebugKey) - isGocriticDebug = logutils.HaveDebugTag(gocriticDebugKey) - allGocriticCheckers = linter.GetCheckersInfo() - allGocriticCheckerMap = func() map[string]*linter.CheckerInfo { - checkInfoMap := make(map[string]*linter.CheckerInfo) - for _, checkInfo := range allGocriticCheckers { - checkInfoMap[checkInfo.Name] = checkInfo - } - return checkInfoMap - }() -) - -type GocriticCheckSettings map[string]interface{} - -type GocriticSettings struct { - EnabledChecks []string `mapstructure:"enabled-checks"` - DisabledChecks []string `mapstructure:"disabled-checks"` - EnabledTags []string `mapstructure:"enabled-tags"` - DisabledTags []string `mapstructure:"disabled-tags"` - SettingsPerCheck map[string]GocriticCheckSettings `mapstructure:"settings"` - - inferredEnabledChecks map[string]bool -} - -func debugChecksListf(checks []string, format string, args ...interface{}) { - if isGocriticDebug { - prefix := fmt.Sprintf(format, args...) - gocriticDebugf(prefix+" checks (%d): %s", len(checks), sprintStrings(checks)) - } -} - -func stringsSliceToSet(ss []string) map[string]bool { - ret := map[string]bool{} - for _, s := range ss { - ret[s] = true - } - - return ret -} - -func buildGocriticTagToCheckersMap() map[string][]string { - tagToCheckers := map[string][]string{} - for _, checker := range allGocriticCheckers { - for _, tag := range checker.Tags { - tagToCheckers[tag] = append(tagToCheckers[tag], checker.Name) - } - } - return tagToCheckers -} - -func gocriticCheckerTagsDebugf() { - if !isGocriticDebug { - return - } - - tagToCheckers := buildGocriticTagToCheckersMap() - - var allTags []string - 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 *GocriticSettings) gocriticDisabledCheckersDebugf() { - if !isGocriticDebug { - return - } - - var disabledCheckers []string - for _, checker := range allGocriticCheckers { - 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 *GocriticSettings) InferEnabledChecks(log logutils.Log) { - gocriticCheckerTagsDebugf() - - enabledByDefaultChecks := getDefaultEnabledGocriticCheckersNames() - debugChecksListf(enabledByDefaultChecks, "Enabled by default") - - disabledByDefaultChecks := getDefaultDisabledGocriticCheckersNames() - debugChecksListf(disabledByDefaultChecks, "Disabled by default") - - var enabledChecks []string - - // EnabledTags - if len(s.EnabledTags) != 0 { - tagToCheckers := buildGocriticTagToCheckersMap() - 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 = filterByDisableTags(enabledChecks, s.DisabledTags, log) - } - - // EnabledChecks - if len(s.EnabledChecks) != 0 { - debugChecksListf(s.EnabledChecks, "Enabled by config") - - alreadyEnabledChecksSet := stringsSliceToSet(enabledChecks) - for _, enabledCheck := range s.EnabledChecks { - if alreadyEnabledChecksSet[enabledCheck] { - log.Warnf("No need to enable check %q: it's already enabled", 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] { - log.Warnf("Gocritic 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.", 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.gocriticDisabledCheckersDebugf() -} - -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{}) - for _, s := range s1 { - s1Map[s] = struct{}{} - } - - result := make([]string, 0) - for _, s := range s2 { - if _, exists := s1Map[s]; exists { - result = append(result, s) - } - } - - return result -} - -func (s *GocriticSettings) Validate(log logutils.Log) 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 errors.Wrap(err, "validate enabled tags") - } - - tagToCheckers := buildGocriticTagToCheckersMap() - 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 := buildGocriticTagToCheckersMap() - 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 errors.Wrap(err, "validate enabled checks") - } - if err := validateStringsUniq(s.DisabledChecks); err != nil { - return errors.Wrap(err, "validate disabled checks") - } - - if err := s.validateCheckerNames(log); err != nil { - return errors.Wrap(err, "validation failed") - } - - return nil -} - -func (s *GocriticSettings) IsCheckEnabled(name string) bool { - return s.inferredEnabledChecks[strings.ToLower(name)] -} - -func sprintAllowedCheckerNames(allowedNames map[string]bool) string { - var namesSlice []string - for name := range allowedNames { - namesSlice = append(namesSlice, name) - } - return sprintStrings(namesSlice) -} - -func sprintStrings(ss []string) string { - sort.Strings(ss) - return fmt.Sprint(ss) -} - -// getAllCheckerNames returns a map containing all checker names supported by gocritic. -func getAllCheckerNames() map[string]bool { - allCheckerNames := map[string]bool{} - for _, checker := range allGocriticCheckers { - allCheckerNames[strings.ToLower(checker.Name)] = true - } - - return allCheckerNames -} - -func isEnabledByDefaultGocriticCheck(info *linter.CheckerInfo) bool { - return !info.HasTag("experimental") && - !info.HasTag("opinionated") && - !info.HasTag("performance") -} - -func getDefaultEnabledGocriticCheckersNames() []string { - var enabled []string - for _, info := range allGocriticCheckers { - enable := isEnabledByDefaultGocriticCheck(info) - if enable { - enabled = append(enabled, info.Name) - } - } - - return enabled -} - -func getDefaultDisabledGocriticCheckersNames() []string { - var disabled []string - for _, info := range allGocriticCheckers { - enable := isEnabledByDefaultGocriticCheck(info) - if !enable { - disabled = append(disabled, info.Name) - } - } - - return disabled -} - -func (s *GocriticSettings) validateCheckerNames(log logutils.Log) error { - allowedNames := 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) { - log.Warnf("Gocritic settings were provided for not enabled check %q", checkName) - } - } - - return nil -} - -func (s *GocriticSettings) GetLowercasedParams() map[string]GocriticCheckSettings { - ret := map[string]GocriticCheckSettings{} - for checker, params := range s.SettingsPerCheck { - ret[strings.ToLower(checker)] = params - } - return ret -} - -func filterByDisableTags(enabledChecks, disableTags []string, log logutils.Log) []string { - enabledChecksSet := stringsSliceToSet(enabledChecks) - for _, enabledCheck := range enabledChecks { - checkInfo, checkInfoExists := allGocriticCheckerMap[enabledCheck] - if !checkInfoExists { - log.Warnf("Gocritic check %q was not exists via filtering disabled tags", 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 -} 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 index c2c73e6f..2dfd3c06 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go @@ -79,7 +79,7 @@ func (r *FileReader) parseConfig() error { r.log.Infof("Used config file %s", usedConfigFile) usedConfigDir := filepath.Dir(usedConfigFile) if usedConfigDir, err = filepath.Abs(usedConfigDir); err != nil { - return fmt.Errorf("can't get config directory") + return errors.New("can't get config directory") } r.cfg.cfgDir = usedConfigDir @@ -216,7 +216,7 @@ func (r *FileReader) parseConfigOption() (string, error) { configFile := cfg.Run.Config if cfg.Run.NoConfig && configFile != "" { - return "", fmt.Errorf("can't combine option --config and --no-config") + return "", errors.New("can't combine option --config and --no-config") } if cfg.Run.NoConfig { @@ -225,7 +225,7 @@ func (r *FileReader) parseConfigOption() (string, error) { configFile, err := homedir.Expand(configFile) if err != nil { - return "", fmt.Errorf("failed to expand configuration path") + return "", errors.New("failed to expand configuration path") } return configFile, nil diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/linecache.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/linecache.go index ab408e7d..b0275153 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/linecache.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/fsutils/linecache.go @@ -21,7 +21,7 @@ func NewLineCache(fc *FileCache) *LineCache { } } -// GetLine returns a index1-th (1-based index) line from the file on filePath +// GetLine returns the index1-th (1-based index) line from the file on filePath func (lc *LineCache) GetLine(filePath string, index1 int) (string, error) { if index1 == 0 { // some linters, e.g. gosec can do it: it really means first line index1 = 1 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.go new file mode 100644 index 00000000..67dde799 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asasalint.go @@ -0,0 +1,30 @@ +package golinters + +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" +) + +func NewAsasalint(setting *config.AsasalintSettings) *goanalysis.Linter { + cfg := asasalint.LinterSetting{} + if setting != nil { + cfg.Exclude = setting.Exclude + cfg.NoBuiltinExclusions = !setting.UseBuiltinExclusions + cfg.IgnoreTest = setting.IgnoreTest + } + + a, err := asasalint.NewAnalyzer(cfg) + if err != nil { + linterLogger.Fatalf("asasalint: create analyzer: %v", err) + } + + 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/asciicheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck.go index 1bf8c7b7..df301b41 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/asciicheck.go @@ -11,9 +11,7 @@ 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(), - }, + []*analysis.Analyzer{asciicheck.NewAnalyzer()}, nil, ).WithLoadMode(goanalysis.LoadModeSyntax) } 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.go index 0e03813d..e56bd83f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/bodyclose.go @@ -8,14 +8,10 @@ import ( ) func NewBodyclose() *goanalysis.Linter { - analyzers := []*analysis.Analyzer{ - bodyclose.Analyzer, - } - return goanalysis.NewLinter( "bodyclose", "checks whether HTTP response body is closed successfully", - analyzers, + []*analysis.Analyzer{bodyclose.Analyzer}, nil, ).WithLoadMode(goanalysis.LoadModeTypesInfo) } 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.go index eb12ed4e..9ec35796 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/contextcheck.go @@ -5,14 +5,18 @@ import ( "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" ) func NewContextCheck() *goanalysis.Linter { - analyzer := contextcheck.NewAnalyzer() + analyzer := contextcheck.NewAnalyzer(contextcheck.Configuration{}) + return goanalysis.NewLinter( - "contextcheck", - "check the function whether use a non-inherited context", + analyzer.Name, + analyzer.Doc, []*analysis.Analyzer{analyzer}, nil, - ).WithLoadMode(goanalysis.LoadModeTypesInfo) + ).WithContextSetter(func(lintCtx *linter.Context) { + analyzer.Run = contextcheck.NewRun(lintCtx.Packages, false) + }).WithLoadMode(goanalysis.LoadModeTypesInfo) } 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 index 6ff38909..408b180b 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/deadcode.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/deadcode.go @@ -12,28 +12,36 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +const deadcodeName = "deadcode" + func NewDeadcode() *goanalysis.Linter { - const linterName = "deadcode" var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: linterName, + Name: deadcodeName, Doc: goanalysis.TheOnlyanalyzerDoc, Run: func(pass *analysis.Pass) (interface{}, 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: linterName, + FromLinter: deadcodeName, }, pass)) } + + if len(issues) == 0 { + return nil, nil + } + mu.Lock() resIssues = append(resIssues, res...) mu.Unlock() @@ -41,8 +49,9 @@ func NewDeadcode() *goanalysis.Linter { return nil, nil }, } + return goanalysis.NewLinter( - linterName, + deadcodeName, "Finds unused code", []*analysis.Analyzer{analyzer}, nil, 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.go index 672f206e..1c93acaa 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/decorder.go @@ -13,8 +13,6 @@ import ( func NewDecorder(settings *config.DecorderSettings) *goanalysis.Linter { a := decorder.Analyzer - analyzers := []*analysis.Analyzer{a} - // disable all rules/checks by default cfg := map[string]interface{}{ "disable-dec-num-check": true, @@ -32,7 +30,7 @@ func NewDecorder(settings *config.DecorderSettings) *goanalysis.Linter { return goanalysis.NewLinter( a.Name, a.Doc, - analyzers, + []*analysis.Analyzer{a}, map[string]map[string]interface{}{a.Name: cfg}, ).WithLoadMode(goanalysis.LoadModeSyntax) } 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.go index 523db79b..b9241d18 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/depguard.go @@ -15,23 +15,25 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -const depguardLinterName = "depguard" +const depguardName = "depguard" -func NewDepguard() *goanalysis.Linter { +func NewDepguard(settings *config.DepGuardSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: depguardLinterName, + Name: depguardName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( - depguardLinterName, + depguardName, "Go linter that checks if package imports are in a list of acceptable packages", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { - dg, err := newDepGuard(&lintCtx.Settings().Depguard) + dg, err := newDepGuard(settings) analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { if err != nil { @@ -120,7 +122,7 @@ func newGuardian(settings *config.DepGuardSettings) (*guardian, error) { return nil, err } - // if the list type was a blacklist the packages with error messages should be included in the blacklist package list + // if the list type was a denylist the packages with error messages should be included in the denylist package list if dg.ListType == depguard.LTBlacklist { noMessagePackages := make(map[string]bool) for _, pkg := range dg.Packages { @@ -153,7 +155,7 @@ func (g guardian) run(loadConfig *loader.Config, prog *loader.Program, pass *ana goanalysis.NewIssue(&result.Issue{ Pos: issue.Position, Text: g.createMsg(issue.PackageName), - FromLinter: depguardLinterName, + FromLinter: depguardName, }, pass), ) } @@ -162,9 +164,9 @@ func (g guardian) run(loadConfig *loader.Config, prog *loader.Program, pass *ana } func (g guardian) createMsg(pkgName string) string { - msgSuffix := "is in the blacklist" + msgSuffix := "is in the denylist" if g.ListType == depguard.LTWhitelist { - msgSuffix = "is not in the whitelist" + msgSuffix = "is not in the allowlist" } var userSuppliedMsgSuffix string 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.go index 8978ff91..00c32c2d 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dogsled.go @@ -8,51 +8,65 @@ 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/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const dogsledLinterName = "dogsled" +const dogsledName = "dogsled" -func NewDogsled() *goanalysis.Linter { +//nolint:dupl +func NewDogsled(settings *config.DogsledSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: dogsledLinterName, + Name: dogsledName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - dogsledLinterName, - "Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var pkgIssues []goanalysis.Issue - for _, f := range pass.Files { - v := returnsVisitor{ - maxBlanks: lintCtx.Settings().Dogsled.MaxBlankIdentifiers, - f: pass.Fset, - } - ast.Walk(&v, f) - for i := range v.issues { - pkgIssues = append(pkgIssues, goanalysis.NewIssue(&v.issues[i], pass)) - } + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runDogsled(pass, settings) + + if len(issues) == 0 { + return nil, nil } mu.Lock() - resIssues = append(resIssues, pkgIssues...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + dogsledName, + "Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } +func runDogsled(pass *analysis.Pass, settings *config.DogsledSettings) []goanalysis.Issue { + var reports []goanalysis.Issue + for _, f := range pass.Files { + v := &returnsVisitor{ + maxBlanks: settings.MaxBlankIdentifiers, + f: pass.Fset, + } + + ast.Walk(v, f) + + for i := range v.issues { + reports = append(reports, goanalysis.NewIssue(&v.issues[i], pass)) + } + } + + return reports +} + type returnsVisitor struct { f *token.FileSet maxBlanks int @@ -87,7 +101,7 @@ func (v *returnsVisitor) Visit(node ast.Node) ast.Visitor { if numBlank > v.maxBlanks { v.issues = append(v.issues, result.Issue{ - FromLinter: dogsledLinterName, + FromLinter: dogsledName, 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.go index ed1c4fcb..fe7b1277 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go @@ -9,36 +9,25 @@ import ( "github.com/pkg/errors" "golang.org/x/tools/go/analysis" + "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/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const duplLinterName = "dupl" +const duplName = "dupl" -func NewDupl() *goanalysis.Linter { +//nolint:dupl +func NewDupl(settings *config.DuplSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: duplLinterName, + Name: duplName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - duplLinterName, - "Tool for code clone detection", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var fileNames []string - for _, f := range pass.Files { - pos := pass.Fset.PositionFor(f.Pos(), false) - fileNames = append(fileNames, pos.Filename) - } - - issues, err := duplAPI.Run(fileNames, lintCtx.Settings().Dupl.Threshold) + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runDupl(pass, settings) if err != nil { return nil, err } @@ -47,37 +36,62 @@ func NewDupl() *goanalysis.Linter { return nil, nil } - res := make([]goanalysis.Issue, 0, len(issues)) - for _, i := range issues { - toFilename, err := fsutils.ShortestRelPath(i.To.Filename(), "") - if err != nil { - return nil, errors.Wrapf(err, "failed to get shortest rel path for %q", i.To.Filename()) - } - 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, lintCtx.Cfg)) - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: token.Position{ - Filename: i.From.Filename(), - Line: i.From.LineStart(), - }, - LineRange: &result.Range{ - From: i.From.LineStart(), - To: i.From.LineEnd(), - }, - Text: text, - FromLinter: duplLinterName, - }, pass)) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + duplName, + "Tool for code clone detection", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runDupl(pass *analysis.Pass, settings *config.DuplSettings) ([]goanalysis.Issue, error) { + fileNames := getFileNames(pass) + + issues, err := duplAPI.Run(fileNames, settings.Threshold) + if err != nil { + return nil, err + } + + if len(issues) == 0 { + return nil, nil + } + + res := make([]goanalysis.Issue, 0, len(issues)) + + for _, i := range issues { + toFilename, err := fsutils.ShortestRelPath(i.To.Filename(), "") + if err != nil { + return nil, errors.Wrapf(err, "failed to get shortest rel path for %q", i.To.Filename()) + } + + 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)) + + res = append(res, goanalysis.NewIssue(&result.Issue{ + Pos: token.Position{ + Filename: i.From.Filename(), + Line: i.From.LineStart(), + }, + LineRange: &result.Range{ + From: i.From.LineStart(), + To: i.From.LineEnd(), + }, + Text: text, + FromLinter: duplName, + }, pass)) + } + + return res, nil +} 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.go index 9c452af5..880de5d4 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/durationcheck.go @@ -10,6 +10,10 @@ import ( func NewDurationCheck() *goanalysis.Linter { a := durationcheck.Analyzer - return goanalysis.NewLinter(a.Name, a.Doc, []*analysis.Analyzer{a}, nil). - WithLoadMode(goanalysis.LoadModeTypesInfo) + 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/errcheck.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck.go index faea6bcc..53fe22e6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errcheck.go @@ -22,26 +22,27 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) -func NewErrcheck() *goanalysis.Linter { - const linterName = "errcheck" +const errcheckName = "errcheck" +func NewErrcheck(settings *config.ErrcheckSettings) *goanalysis.Linter { var mu sync.Mutex - var res []goanalysis.Issue + var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: linterName, + Name: errcheckName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } return goanalysis.NewLinter( - linterName, + errcheckName, "Errcheck is a program for checking for unchecked errors "+ "in go programs. These unchecked errors can be critical bugs in some cases", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { // copied from errcheck - checker, err := getChecker(&lintCtx.Settings().Errcheck) + checker, err := getChecker(settings) if err != nil { lintCtx.Log.Errorf("failed to get checker: %v", err) return @@ -50,56 +51,66 @@ func NewErrcheck() *goanalysis.Linter { checker.Tags = lintCtx.Cfg.Run.BuildTags analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - pkg := &packages.Package{ - Fset: pass.Fset, - Syntax: pass.Files, - Types: pass.Pkg, - TypesInfo: pass.TypesInfo, + issues := runErrCheck(lintCtx, pass, checker) + if err != nil { + return nil, err } - errcheckIssues := checker.CheckPackage(pkg).Unique() - if len(errcheckIssues.UncheckedErrors) == 0 { + if len(issues) == 0 { return nil, nil } - issues := make([]goanalysis.Issue, len(errcheckIssues.UncheckedErrors)) - for i, err := range errcheckIssues.UncheckedErrors { - var text string - if err.FuncName != "" { - code := err.SelectorName - if err.SelectorName == "" { - code = err.FuncName - } - - text = fmt.Sprintf( - "Error return value of %s is not checked", - formatCode(code, lintCtx.Cfg), - ) - } else { - text = "Error return value is not checked" - } - - issues[i] = goanalysis.NewIssue( - &result.Issue{ - FromLinter: linterName, - Text: text, - Pos: err.Pos, - }, - pass, - ) - } - mu.Lock() - res = append(res, issues...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil } }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return res + return resIssues }).WithLoadMode(goanalysis.LoadModeTypesInfo) } +func runErrCheck(lintCtx *linter.Context, pass *analysis.Pass, checker *errcheck.Checker) []goanalysis.Issue { + pkg := &packages.Package{ + Fset: pass.Fset, + Syntax: pass.Files, + Types: pass.Pkg, + TypesInfo: pass.TypesInfo, + } + + lintIssues := checker.CheckPackage(pkg).Unique() + if len(lintIssues.UncheckedErrors) == 0 { + return nil + } + + issues := make([]goanalysis.Issue, len(lintIssues.UncheckedErrors)) + + for i, err := range lintIssues.UncheckedErrors { + text := "Error return value is not checked" + + if err.FuncName != "" { + code := err.SelectorName + if err.SelectorName == "" { + code = err.FuncName + } + + text = fmt.Sprintf("Error return value of %s is not checked", formatCode(code, lintCtx.Cfg)) + } + + issues[i] = goanalysis.NewIssue( + &result.Issue{ + FromLinter: errcheckName, + Text: text, + Pos: err.Pos, + }, + pass, + ) + } + + return issues +} + // parseIgnoreConfig was taken from errcheck in order to keep the API identical. // https://github.com/kisielk/errcheck/blob/1787c4bee836470bf45018cfbc783650db3c6501/main.go#L25-L60 func parseIgnoreConfig(s string) (map[string]*regexp.Regexp, error) { 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 index 7ee81134..96564cfa 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/errname.go @@ -8,14 +8,10 @@ import ( ) func NewErrName() *goanalysis.Linter { - analyzers := []*analysis.Analyzer{ - analyzer.New(), - } - return goanalysis.NewLinter( "errname", "Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.", - analyzers, + []*analysis.Analyzer{analyzer.New()}, nil, ).WithLoadMode(goanalysis.LoadModeTypesInfo) } 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.go index ea264687..778dc004 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go @@ -23,6 +23,10 @@ func NewExhaustive(settings *config.ExhaustiveSettings) *goanalysis.Linter { } } - return goanalysis.NewLinter(a.Name, a.Doc, []*analysis.Analyzer{a}, cfg). - WithLoadMode(goanalysis.LoadModeTypesInfo) + 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.go index 8c843289..37ea055d 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustruct.go @@ -10,7 +10,6 @@ import ( func NewExhaustruct(settings *config.ExhaustructSettings) *goanalysis.Linter { var include, exclude []string - if settings != nil { include = settings.Include exclude = settings.Exclude @@ -21,6 +20,10 @@ func NewExhaustruct(settings *config.ExhaustructSettings) *goanalysis.Linter { linterLogger.Fatalf("exhaustruct configuration: %v", err) } - return goanalysis.NewLinter(a.Name, a.Doc, []*analysis.Analyzer{a}, nil). - WithLoadMode(goanalysis.LoadModeTypesInfo) + 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/forbidigo.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo.go index 2fa9d518..a8c256b9 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/forbidigo.go @@ -7,64 +7,76 @@ import ( "github.com/pkg/errors" "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" ) -func NewForbidigo() *goanalysis.Linter { - const linterName = "forbidigo" +const forbidigoName = "forbidigo" + +//nolint:dupl +func NewForbidigo(settings *config.ForbidigoSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: linterName, + Name: forbidigoName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - linterName, - "Forbids identifiers", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - s := &lintCtx.Settings().Forbidigo - - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var res []goanalysis.Issue - options := []forbidigo.Option{ - forbidigo.OptionExcludeGodocExamples(s.ExcludeGodocExamples), - // disable "//permit" directives so only "//nolint" directives matters within golangci lint - forbidigo.OptionIgnorePermitDirectives(true), - } - forbid, err := forbidigo.NewLinter(s.Forbid, options...) + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runForbidigo(pass, settings) if err != nil { - return nil, errors.Wrapf(err, "failed to create linter %q", linterName) - } - - for _, file := range pass.Files { - hints, err := forbid.Run(pass.Fset, file) - if err != nil { - return nil, errors.Wrapf(err, "forbidigo linter failed on file %q", file.Name.String()) - } - for _, hint := range hints { - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: hint.Position(), - Text: hint.Details(), - FromLinter: linterName, - }, pass)) - } + return nil, err } - if len(res) == 0 { + if len(issues) == 0 { return nil, nil } mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + forbidigoName, + "Forbids identifiers", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runForbidigo(pass *analysis.Pass, settings *config.ForbidigoSettings) ([]goanalysis.Issue, error) { + options := []forbidigo.Option{ + forbidigo.OptionExcludeGodocExamples(settings.ExcludeGodocExamples), + // disable "//permit" directives so only "//nolint" directives matters within golangci-lint + forbidigo.OptionIgnorePermitDirectives(true), + } + + forbid, err := forbidigo.NewLinter(settings.Forbid, options...) + if err != nil { + return nil, errors.Wrapf(err, "failed to create linter %q", forbidigoName) + } + + var issues []goanalysis.Issue + for _, file := range pass.Files { + hints, err := forbid.Run(pass.Fset, file) + if err != nil { + return nil, errors.Wrapf(err, "forbidigo linter failed on file %q", file.Name.String()) + } + + for _, hint := range hints { + issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Pos: hint.Position(), + Text: hint.Details(), + FromLinter: forbidigoName, + }, pass)) + } + } + + return issues, nil +} 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.go index 29cb6b7e..c562c2aa 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/funlen.go @@ -8,57 +8,69 @@ import ( "github.com/ultraware/funlen" "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 funlenLinterName = "funlen" +const funlenName = "funlen" -func NewFunlen() *goanalysis.Linter { +//nolint:dupl +func NewFunlen(settings *config.FunlenSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: funlenLinterName, + Name: funlenName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - funlenLinterName, - "Tool for detection of long functions", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var issues []funlen.Message - for _, file := range pass.Files { - fileIssues := funlen.Run(file, pass.Fset, lintCtx.Settings().Funlen.Lines, lintCtx.Settings().Funlen.Statements) - issues = append(issues, fileIssues...) - } + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runFunlen(pass, settings) if len(issues) == 0 { return nil, nil } - res := make([]goanalysis.Issue, len(issues)) - for k, i := range issues { - res[k] = goanalysis.NewIssue(&result.Issue{ - Pos: token.Position{ - Filename: i.Pos.Filename, - Line: i.Pos.Line, - }, - Text: strings.TrimRight(i.Message, "\n"), - FromLinter: funlenLinterName, - }, pass) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + funlenName, + "Tool for detection of long functions", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runFunlen(pass *analysis.Pass, settings *config.FunlenSettings) []goanalysis.Issue { + var lintIssues []funlen.Message + for _, file := range pass.Files { + fileIssues := funlen.Run(file, pass.Fset, settings.Lines, settings.Statements) + lintIssues = append(lintIssues, fileIssues...) + } + + if len(lintIssues) == 0 { + return nil + } + + issues := make([]goanalysis.Issue, len(lintIssues)) + for k, i := range lintIssues { + issues[k] = goanalysis.NewIssue(&result.Issue{ + Pos: token.Position{ + Filename: i.Pos.Filename, + Line: i.Pos.Line, + }, + Text: strings.TrimRight(i.Message, "\n"), + FromLinter: funlenName, + }, pass) + } + + return issues +} 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.go index c0c606a7..d07c2126 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gci.go @@ -3,8 +3,16 @@ package golinters import ( "fmt" "strings" + "sync" - gci "github.com/daixiang0/gci/pkg/analyzer" + 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/hexops/gotextdiff" + "github.com/hexops/gotextdiff/myers" + "github.com/hexops/gotextdiff/span" + "github.com/pkg/errors" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" @@ -15,34 +23,131 @@ import ( const gciName = "gci" func NewGci(settings *config.GciSettings) *goanalysis.Linter { - var linterCfg map[string]map[string]interface{} + var mu sync.Mutex + var resIssues []goanalysis.Issue + analyzer := &analysis.Analyzer{ + Name: gciName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, + } + + var cfg *gcicfg.Config if settings != nil { - cfg := map[string]interface{}{ - gci.NoInlineCommentsFlag: settings.NoInlineComments, - gci.NoPrefixCommentsFlag: settings.NoPrefixComments, - gci.SectionsFlag: strings.Join(settings.Sections, gci.SectionDelimiter), - gci.SectionSeparatorsFlag: strings.Join(settings.SectionSeparator, gci.SectionDelimiter), + rawCfg := gcicfg.YamlConfig{ + Cfg: gcicfg.BoolConfig{ + SkipGenerated: settings.SkipGenerated, + CustomOrder: settings.CustomOrder, + }, + SectionStrings: settings.Sections, } if settings.LocalPrefixes != "" { prefix := []string{"standard", "default", fmt.Sprintf("prefix(%s)", settings.LocalPrefixes)} - cfg[gci.SectionsFlag] = strings.Join(prefix, gci.SectionDelimiter) + rawCfg.SectionStrings = prefix } - linterCfg = map[string]map[string]interface{}{ - gci.Analyzer.Name: cfg, + var err error + cfg, err = rawCfg.Parse() + if err != nil { + linterLogger.Fatalf("gci: configuration parsing: %v", err) } } + var lock sync.Mutex + return goanalysis.NewLinter( gciName, "Gci controls golang package import order and makes it always deterministic.", - []*analysis.Analyzer{gci.Analyzer}, - linterCfg, + []*analysis.Analyzer{analyzer}, + nil, ).WithContextSetter(func(lintCtx *linter.Context) { - if settings.LocalPrefixes != "" { - lintCtx.Log.Warnf("gci: `local-prefixes` is deprecated, use `sections` and `prefix(%s)` instead.", settings.LocalPrefixes) + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { + issues, err := runGci(pass, lintCtx, cfg, &lock) + 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 runGci(pass *analysis.Pass, lintCtx *linter.Context, cfg *gcicfg.Config, lock *sync.Mutex) ([]goanalysis.Issue, error) { + fileNames := getFileNames(pass) + + var diffs []string + err := diffFormattedFilesToArray(fileNames, *cfg, &diffs, lock) + if err != nil { + return nil, err + } + + var issues []goanalysis.Issue + + for _, diff := range diffs { + if diff == "" { + continue + } + + is, err := extractIssuesFromPatch(diff, lintCtx, gciName) + if err != nil { + return nil, errors.Wrapf(err, "can't extract issues from gci diff output %s", diff) + } + + for i := range is { + issues = append(issues, goanalysis.NewIssue(&is[i], pass)) + } + } + + return issues, 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 +// https://github.com/daixiang0/gci/blob/6f5cb16718ba07f0342a58de9b830ec5a6d58790/pkg/gci/gci.go#L80 +func diffFormattedFilesToArray(paths []string, cfg gcicfg.Config, diffs *[]string, lock *sync.Mutex) error { + log.InitLogger() + defer func() { _ = log.L().Sync() }() + + return gci.ProcessFiles(io.GoFilesInPathsGenerator(paths), cfg, func(filePath string, unmodifiedFile, formattedFile []byte) error { + fileURI := span.URIFromPath(filePath) + edits := myers.ComputeEdits(fileURI, string(unmodifiedFile), string(formattedFile)) + unifiedEdits := gotextdiff.ToUnified(filePath, filePath, string(unmodifiedFile), edits) + lock.Lock() + *diffs = append(*diffs, fmt.Sprint(unifiedEdits)) + lock.Unlock() + return nil + }) +} + +func getErrorTextForGci(settings config.GciSettings) string { + text := "File is not `gci`-ed" + + hasOptions := settings.SkipGenerated || len(settings.Sections) > 0 + if !hasOptions { + return text + } + + text += " with" + + if settings.SkipGenerated { + text += " --skip-generated" + } + + if len(settings.Sections) > 0 { + text += " -s " + strings.Join(settings.Sections, ",") + } + + return text +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/linter.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/linter.go index ef49e428..50a4ca08 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/linter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/linter.go @@ -108,7 +108,7 @@ func (lnt *Linter) configureAnalyzer(a *analysis.Analyzer, cfg map[string]interf if f == nil { validFlagNames := allFlagNames(&a.Flags) if len(validFlagNames) == 0 { - return fmt.Errorf("analyzer doesn't have settings") + return errors.New("analyzer doesn't have settings") } return fmt.Errorf("analyzer doesn't have setting %q, valid settings: %v", @@ -211,3 +211,7 @@ func valueToString(v interface{}) string { return fmt.Sprint(v) } + +func DummyRun(_ *analysis.Pass) (interface{}, error) { + return nil, nil +} 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/golinters/goanalysis/runner_loadingpackage.go index 1ac6b83e..a5b5cccf 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_loadingpackage.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner_loadingpackage.go @@ -123,6 +123,7 @@ func (lp *loadingPackage) loadFromSource(loadMode LoadMode) error { pkg.TypesInfo = &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), + Instances: make(map[*ast.Ident]types.Instance), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), 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.go index f9715bda..bb0b783c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gochecknoinits.go @@ -41,6 +41,7 @@ func NewGochecknoinits() *goanalysis.Linter { return nil, nil }, } + return goanalysis.NewLinter( gochecknoinitsName, "Checks that no init functions are present in Go code", 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.go index eb42dd14..49146c52 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go @@ -8,6 +8,7 @@ import ( "github.com/uudashr/gocognit" "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" @@ -15,54 +16,65 @@ import ( const gocognitName = "gocognit" -func NewGocognit() *goanalysis.Linter { +//nolint:dupl +func NewGocognit(settings *config.GocognitSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: goanalysis.TheOnlyAnalyzerName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runGocognit(pass, settings) + + if len(issues) == 0 { + return nil, nil + } + + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() + + return nil, nil + }, } + return goanalysis.NewLinter( gocognitName, "Computes and checks the cognitive complexity of functions", []*analysis.Analyzer{analyzer}, nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var stats []gocognit.Stat - for _, f := range pass.Files { - stats = gocognit.ComplexityStats(f, pass.Fset, stats) - } - if len(stats) == 0 { - return nil, nil - } + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} - sort.SliceStable(stats, func(i, j int) bool { - return stats[i].Complexity > stats[j].Complexity - }) +func runGocognit(pass *analysis.Pass, settings *config.GocognitSettings) []goanalysis.Issue { + var stats []gocognit.Stat + for _, f := range pass.Files { + stats = gocognit.ComplexityStats(f, pass.Fset, stats) + } + if len(stats) == 0 { + return nil + } - res := make([]goanalysis.Issue, 0, len(stats)) - for _, s := range stats { - if s.Complexity <= lintCtx.Settings().Gocognit.MinComplexity { - break // Break as the stats is already sorted from greatest to least - } + sort.SliceStable(stats, func(i, j int) bool { + return stats[i].Complexity > stats[j].Complexity + }) - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: s.Pos, - Text: fmt.Sprintf("cognitive complexity %d of func %s is high (> %d)", - s.Complexity, formatCode(s.FuncName, lintCtx.Cfg), lintCtx.Settings().Gocognit.MinComplexity), - FromLinter: gocognitName, - }, pass)) - } + issues := make([]goanalysis.Issue, 0, len(stats)) + for _, s := range stats { + if s.Complexity <= settings.MinComplexity { + break // Break as the stats is already sorted from greatest to least + } - mu.Lock() - resIssues = append(resIssues, res...) - mu.Unlock() + 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, + }, pass)) + } - return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) + return issues } 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.go index bdec4e10..24d3198b 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goconst.go @@ -7,6 +7,7 @@ import ( goconstAPI "github.com/jgautheron/goconst" "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" @@ -14,40 +15,43 @@ import ( const goconstName = "goconst" -func NewGoconst() *goanalysis.Linter { +//nolint:dupl +func NewGoconst(settings *config.GoConstSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: goconstName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - goconstName, - "Finds repeated strings that could be replaced by a constant", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - issues, err := checkConstants(pass, lintCtx) - if err != nil || len(issues) == 0 { + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runGoconst(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 - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + goconstName, + "Finds repeated strings that could be replaced by a constant", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } -func checkConstants(pass *analysis.Pass, lintCtx *linter.Context) ([]goanalysis.Issue, error) { - settings := lintCtx.Settings().Goconst - +func runGoconst(pass *analysis.Pass, settings *config.GoConstSettings) ([]goanalysis.Issue, error) { cfg := goconstAPI.Config{ IgnoreTests: settings.IgnoreTests, MatchWithConstants: settings.MatchWithConstants, @@ -63,27 +67,28 @@ func checkConstants(pass *analysis.Pass, lintCtx *linter.Context) ([]goanalysis. cfg.ExcludeTypes[goconstAPI.Call] = true } - goconstIssues, err := goconstAPI.Run(pass.Files, pass.Fset, &cfg) + lintIssues, err := goconstAPI.Run(pass.Files, pass.Fset, &cfg) if err != nil { return nil, err } - if len(goconstIssues) == 0 { + if len(lintIssues) == 0 { return nil, nil } - res := make([]goanalysis.Issue, 0, len(goconstIssues)) - for _, i := range goconstIssues { - textBegin := fmt.Sprintf("string %s has %d occurrences", formatCode(i.Str, lintCtx.Cfg), i.OccurrencesCount) - var textEnd string + 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) + if i.MatchingConst == "" { - textEnd = ", make it a constant" + text += ", make it a constant" } else { - textEnd = fmt.Sprintf(", but such constant %s already exists", formatCode(i.MatchingConst, lintCtx.Cfg)) + text += fmt.Sprintf(", but such constant %s already exists", formatCode(i.MatchingConst, nil)) } + res = append(res, goanalysis.NewIssue(&result.Issue{ Pos: i.Pos, - Text: textBegin + textEnd, + Text: text, FromLinter: goconstName, }, 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 index ea3a3cbc..d15dabc6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go @@ -11,78 +11,196 @@ import ( "strings" "sync" + "github.com/go-critic/go-critic/checkers" gocriticlinter "github.com/go-critic/go-critic/framework/linter" + "github.com/pkg/errors" "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" +const goCriticName = "gocritic" -func NewGocritic() *goanalysis.Linter { +const goCriticDebugKey = "gocritic" + +var ( + goCriticDebugf = logutils.Debug(goCriticDebugKey) + isGoCriticDebug = logutils.HaveDebugTag(goCriticDebugKey) +) + +func NewGoCritic(settings *config.GoCriticSettings, cfg *config.Config) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue - sizes := types.SizesFor("gc", runtime.GOARCH) + wrapper := &goCriticWrapper{ + settings: settings, + cfg: cfg, + sizes: types.SizesFor("gc", runtime.GOARCH), + } analyzer := &analysis.Analyzer{ - Name: gocriticName, + Name: goCriticName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, 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, + 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(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - linterCtx := gocriticlinter.NewContext(pass.Fset, sizes) - enabledCheckers, err := buildEnabledCheckers(lintCtx, linterCtx) - if err != nil { - return nil, err - } + ). + WithContextSetter(func(context *linter.Context) { + wrapper.init() + }). + WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeTypesInfo) +} - linterCtx.SetPackageInfo(pass.TypesInfo, pass.Pkg) - pkgIssues := runGocriticOnPackage(linterCtx, enabledCheckers, pass.Files) - res := make([]goanalysis.Issue, 0, len(pkgIssues)) +type goCriticWrapper struct { + settings *config.GoCriticSettings + settingsWrapper *goCriticSettingsWrapper + cfg *config.Config + sizes types.Sizes + once sync.Once +} - for i := range pkgIssues { - res = append(res, goanalysis.NewIssue(&pkgIssues[i], pass)) - } - if len(res) == 0 { - return nil, nil +func (w *goCriticWrapper) init() { + if w.settings != nil { + // the 'defer' is here to catch the panic from checkers.InitEmbeddedRules() + defer func() { + if err := recover(); err != nil { + linterLogger.Fatalf("%s: %v: setting an explicit GOROOT can fix this problem.", goCriticName, err) + return } + }() + w.once.Do(checkers.InitEmbeddedRules) - mu.Lock() - resIssues = append(resIssues, res...) - mu.Unlock() + settingsWrapper := newGoCriticSettingsWrapper(w.settings) - return nil, nil + settingsWrapper.inferEnabledChecks(linterLogger) + if err := settingsWrapper.validate(linterLogger); err != nil { + linterLogger.Fatalf("%s: invalid settings: %s", goCriticName, err) } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) + + w.settingsWrapper = settingsWrapper + } } -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 +func (w *goCriticWrapper) run(pass *analysis.Pass) ([]goanalysis.Issue, error) { + if w.settingsWrapper == nil { + return nil, fmt.Errorf("the settings wrapper is nil") } - return ret + linterCtx := gocriticlinter.NewContext(pass.Fset, w.sizes) + + 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 configureCheckerInfo( - lintCtx *linter.Context, - info *gocriticlinter.CheckerInfo, - allParams map[string]config.GocriticCheckSettings) error { +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.Node.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.Node.End() - warn.Node.Pos()), + 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 @@ -92,7 +210,7 @@ func configureCheckerInfo( for k, p := range params { v, ok := infoParams[k] if ok { - v.Value = normalizeCheckerParamsValue(lintCtx, p) + v.Value = w.normalizeCheckerParamsValue(p) continue } @@ -115,12 +233,22 @@ func configureCheckerInfo( 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 normalizeCheckerParamsValue(lintCtx *linter.Context, p interface{}) interface{} { +func (w *goCriticWrapper) normalizeCheckerParamsValue(p interface{}) interface{} { rv := reflect.ValueOf(p) switch rv.Type().Kind() { case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: @@ -129,76 +257,383 @@ func normalizeCheckerParamsValue(lintCtx *linter.Context, p interface{}) interfa return rv.Bool() case reflect.String: // Perform variable substitution. - return strings.ReplaceAll(rv.String(), "${configDir}", lintCtx.Cfg.GetConfigDir()) + return strings.ReplaceAll(rv.String(), "${configDir}", w.cfg.GetConfigDir()) default: return p } } -func buildEnabledCheckers(lintCtx *linter.Context, linterCtx *gocriticlinter.Context) ([]*gocriticlinter.Checker, error) { - s := lintCtx.Settings().Gocritic - allParams := s.GetLowercasedParams() +// TODO(ldez): rewrite and simplify goCriticSettingsWrapper. - var enabledCheckers []*gocriticlinter.Checker - for _, info := range gocriticlinter.GetCheckersInfo() { - if !s.IsCheckEnabled(info.Name) { +type goCriticSettingsWrapper struct { + *config.GoCriticSettings + + allCheckers []*gocriticlinter.CheckerInfo + allCheckerMap map[string]*gocriticlinter.CheckerInfo + + inferredEnabledChecks map[string]bool +} + +func newGoCriticSettingsWrapper(settings *config.GoCriticSettings) *goCriticSettingsWrapper { + allCheckers := gocriticlinter.GetCheckersInfo() + + allCheckerMap := make(map[string]*gocriticlinter.CheckerInfo) + for _, checkInfo := range allCheckers { + allCheckerMap[checkInfo.Name] = checkInfo + } + + return &goCriticSettingsWrapper{ + GoCriticSettings: settings, + 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 } - if err := configureCheckerInfo(lintCtx, info, allParams); err != nil { - return nil, err + disabledCheckers = append(disabledCheckers, checker.Name) + } + + if len(disabledCheckers) == 0 { + goCriticDebugf("All checks are enabled") + } else { + debugChecksListf(disabledCheckers, "Final not used") + } +} + +func (s *goCriticSettingsWrapper) inferEnabledChecks(log logutils.Log) { + 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]...) } - c, err := gocriticlinter.NewChecker(linterCtx, info) - if err != nil { - return nil, err + 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, log) + } + + // EnabledChecks + if len(s.EnabledChecks) != 0 { + debugChecksListf(s.EnabledChecks, "Enabled by config") + + alreadyEnabledChecksSet := stringsSliceToSet(enabledChecks) + for _, enabledCheck := range s.EnabledChecks { + if alreadyEnabledChecksSet[enabledCheck] { + log.Warnf("No need to enable check %q: it's already enabled", enabledCheck) + continue + } + enabledChecks = append(enabledChecks, enabledCheck) } - enabledCheckers = append(enabledCheckers, c) } - return enabledCheckers, nil -} + // DisabledChecks + if len(s.DisabledChecks) != 0 { + debugChecksListf(s.DisabledChecks, "Disabled by config") -func runGocriticOnPackage(linterCtx *gocriticlinter.Context, checkers []*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) + enabledChecksSet := stringsSliceToSet(enabledChecks) + for _, disabledCheck := range s.DisabledChecks { + if !enabledChecksSet[disabledCheck] { + log.Warnf("Gocritic 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.", disabledCheck) + continue + } + delete(enabledChecksSet, disabledCheck) + } - issues := runGocriticOnFile(linterCtx, f, checkers) - res = append(res, issues...) + enabledChecks = nil + for enabledCheck := range enabledChecksSet { + enabledChecks = append(enabledChecks, enabledCheck) + } } - return res + + s.inferredEnabledChecks = map[string]bool{} + for _, check := range enabledChecks { + s.inferredEnabledChecks[strings.ToLower(check)] = true + } + + debugChecksListf(enabledChecks, "Final used") + + s.disabledCheckersDebugf() } -func runGocriticOnFile(ctx *gocriticlinter.Context, f *ast.File, checkers []*gocriticlinter.Checker) []result.Issue { - var res []result.Issue +func (s *goCriticSettingsWrapper) validate(log logutils.Log) 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 errors.Wrap(err, "validate enabled tags") + } - for _, c := range checkers { - // All checkers are expected to use *lint.Context - // as read-only structure, so no copying is required. - for _, warn := range c.Check(f) { - pos := ctx.FileSet.Position(warn.Node.Pos()) - issue := result.Issue{ - Pos: pos, - Text: fmt.Sprintf("%s: %s", c.Info.Name, warn.Text), - FromLinter: gocriticName, + 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 warn.HasQuickFix() { - issue.Replacement = &result.Replacement{ - Inline: &result.InlineFix{ - StartCol: pos.Column - 1, - Length: int(warn.Node.End() - warn.Node.Pos()), - NewString: string(warn.Suggestion.Replacement), - }, - } + 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) } + } + } - res = append(res, issue) + if err := validateStringsUniq(s.EnabledChecks); err != nil { + return errors.Wrap(err, "validate enabled checks") + } + + if err := validateStringsUniq(s.DisabledChecks); err != nil { + return errors.Wrap(err, "validate disabled checks") + } + + if err := s.validateCheckerNames(log); err != nil { + return errors.Wrap(err, "validation failed") + } + + 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 res + 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(log logutils.Log) 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) { + log.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, log logutils.Log) []string { + enabledChecksSet := stringsSliceToSet(enabledChecks) + + for _, enabledCheck := range enabledChecks { + checkInfo, checkInfoExists := s.allCheckerMap[enabledCheck] + if !checkInfoExists { + log.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 ...interface{}) { + 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/gocyclo.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go index 5c61fec7..ea821957 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go @@ -7,6 +7,7 @@ import ( "github.com/fzipp/gocyclo" "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" @@ -14,48 +15,62 @@ import ( const gocycloName = "gocyclo" -func NewGocyclo() *goanalysis.Linter { +//nolint:dupl +func NewGocyclo(settings *config.GoCycloSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: gocycloName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runGoCyclo(pass, settings) + + if len(issues) == 0 { + return nil, nil + } + + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() + + return nil, nil + }, } + return goanalysis.NewLinter( gocycloName, "Computes and checks the cyclomatic complexity of functions", []*analysis.Analyzer{analyzer}, nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var stats gocyclo.Stats - for _, f := range pass.Files { - stats = gocyclo.AnalyzeASTFile(f, pass.Fset, stats) - } - if len(stats) == 0 { - return nil, nil - } + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} - stats = stats.SortAndFilter(-1, lintCtx.Settings().Gocyclo.MinComplexity) +func runGoCyclo(pass *analysis.Pass, settings *config.GoCycloSettings) []goanalysis.Issue { + var stats gocyclo.Stats + for _, f := range pass.Files { + stats = gocyclo.AnalyzeASTFile(f, pass.Fset, stats) + } + if len(stats) == 0 { + return nil + } - res := make([]goanalysis.Issue, 0, len(stats)) - for _, s := range stats { - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: s.Pos, - Text: fmt.Sprintf("cyclomatic complexity %d of func %s is high (> %d)", - s.Complexity, formatCode(s.FuncName, lintCtx.Cfg), lintCtx.Settings().Gocyclo.MinComplexity), - FromLinter: gocycloName, - }, pass)) - } + stats = stats.SortAndFilter(-1, settings.MinComplexity) - mu.Lock() - resIssues = append(resIssues, res...) - mu.Unlock() + issues := make([]goanalysis.Issue, 0, len(stats)) - return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) + for _, s := range stats { + text := fmt.Sprintf("cyclomatic complexity %d of func %s is high (> %d)", + s.Complexity, formatCode(s.FuncName, nil), settings.MinComplexity) + + issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Pos: s.Pos, + Text: text, + FromLinter: gocycloName, + }, pass)) + } + + return issues } 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.go index 09eb9b5b..93ca7577 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go @@ -6,6 +6,7 @@ import ( "github.com/tetafro/godot" "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" @@ -13,73 +14,89 @@ import ( const godotName = "godot" -func NewGodot() *goanalysis.Linter { +func NewGodot(settings *config.GodotSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue - analyzer := &analysis.Analyzer{ - Name: godotName, - Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - godotName, - "Check if comments end in a period", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - cfg := lintCtx.Cfg.LintersSettings.Godot - settings := godot.Settings{ - Scope: godot.Scope(cfg.Scope), - Exclude: cfg.Exclude, - Period: cfg.Period, - Capital: cfg.Capital, + var dotSettings godot.Settings + + if settings != nil { + dotSettings = godot.Settings{ + Scope: godot.Scope(settings.Scope), + Exclude: settings.Exclude, + Period: settings.Period, + Capital: settings.Capital, } // Convert deprecated setting // todo(butuzov): remove on v2 release - if cfg.CheckAll { // nolint:staticcheck // Keep for retro-compatibility. - settings.Scope = godot.AllScope + if settings.CheckAll { //nolint:staticcheck // Keep for retro-compatibility. + dotSettings.Scope = godot.AllScope } + } - if settings.Scope == "" { - settings.Scope = godot.DeclScope - } + if dotSettings.Scope == "" { + dotSettings.Scope = godot.DeclScope + } - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var issues []godot.Issue - for _, file := range pass.Files { - iss, err := godot.Run(file, pass.Fset, settings) - if err != nil { - return nil, err - } - issues = append(issues, iss...) + analyzer := &analysis.Analyzer{ + Name: godotName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runGodot(pass, dotSettings) + if err != nil { + return nil, err } if len(issues) == 0 { return nil, nil } - res := make([]goanalysis.Issue, len(issues)) - for k, i := range issues { - issue := result.Issue{ - Pos: i.Pos, - Text: i.Message, - FromLinter: godotName, - Replacement: &result.Replacement{ - NewLines: []string{i.Replacement}, - }, - } - - res[k] = goanalysis.NewIssue(&issue, pass) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + godotName, + "Check if comments end in a period", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runGodot(pass *analysis.Pass, settings godot.Settings) ([]goanalysis.Issue, error) { + var lintIssues []godot.Issue + for _, file := range pass.Files { + iss, err := godot.Run(file, pass.Fset, settings) + if err != nil { + return nil, err + } + lintIssues = append(lintIssues, iss...) + } + + if len(lintIssues) == 0 { + return nil, nil + } + + issues := make([]goanalysis.Issue, len(lintIssues)) + for k, i := range lintIssues { + issue := result.Issue{ + Pos: i.Pos, + Text: i.Message, + FromLinter: godotName, + Replacement: &result.Replacement{ + NewLines: []string{i.Replacement}, + }, + } + + issues[k] = goanalysis.NewIssue(&issue, pass) + } + + return issues, nil +} 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.go index 2a4dd9fa..4dba9df0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/godox.go @@ -8,6 +8,7 @@ import ( "github.com/matoous/godox" "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" @@ -15,49 +16,61 @@ import ( const godoxName = "godox" -func NewGodox() *goanalysis.Linter { +//nolint:dupl +func NewGodox(settings *config.GodoxSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: godoxName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - godoxName, - "Tool for detection of FIXME, TODO and other comment keywords", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var issues []godox.Message - for _, file := range pass.Files { - issues = append(issues, godox.Run(file, pass.Fset, lintCtx.Settings().Godox.Keywords...)...) - } + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runGodox(pass, settings) if len(issues) == 0 { return nil, nil } - res := make([]goanalysis.Issue, len(issues)) - for k, i := range issues { - res[k] = goanalysis.NewIssue(&result.Issue{ - Pos: token.Position{ - Filename: i.Pos.Filename, - Line: i.Pos.Line, - }, - Text: strings.TrimRight(i.Message, "\n"), - FromLinter: godoxName, - }, pass) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + godoxName, + "Tool for detection of FIXME, TODO and other comment keywords", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runGodox(pass *analysis.Pass, settings *config.GodoxSettings) []goanalysis.Issue { + var messages []godox.Message + for _, file := range pass.Files { + messages = append(messages, godox.Run(file, pass.Fset, settings.Keywords...)...) + } + + if len(messages) == 0 { + return nil + } + + issues := make([]goanalysis.Issue, len(messages)) + + for k, i := range messages { + issues[k] = goanalysis.NewIssue(&result.Issue{ + Pos: token.Position{ + Filename: i.Pos.Filename, + Line: i.Pos.Line, + }, + Text: strings.TrimRight(i.Message, "\n"), + FromLinter: godoxName, + }, pass) + } + + return issues +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goerr113.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goerr113.go index 0c10005a..c97b6d58 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goerr113.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goerr113.go @@ -11,9 +11,7 @@ func NewGoerr113() *goanalysis.Linter { return goanalysis.NewLinter( "goerr113", "Golang linter to check the errors handling expressions", - []*analysis.Analyzer{ - err113.NewAnalyzer(), - }, + []*analysis.Analyzer{err113.NewAnalyzer()}, nil, ).WithLoadMode(goanalysis.LoadModeTypesInfo) } 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.go index aa340dcf..e8c02411 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go @@ -7,20 +7,23 @@ import ( "github.com/pkg/errors" "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" ) const gofmtName = "gofmt" -func NewGofmt() *goanalysis.Linter { +func NewGofmt(settings *config.GoFmtSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: gofmtName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( gofmtName, "Gofmt checks whether code was gofmt-ed. By default "+ @@ -29,31 +32,9 @@ func NewGofmt() *goanalysis.Linter { nil, ).WithContextSetter(func(lintCtx *linter.Context) { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var fileNames []string - for _, f := range pass.Files { - pos := pass.Fset.PositionFor(f.Pos(), false) - fileNames = append(fileNames, pos.Filename) - } - - var issues []goanalysis.Issue - - for _, f := range fileNames { - diff, err := gofmtAPI.Run(f, lintCtx.Settings().Gofmt.Simplify) - if err != nil { // TODO: skip - return nil, err - } - if diff == nil { - continue - } - - is, err := extractIssuesFromPatch(string(diff), lintCtx.Log, lintCtx, gofmtName) - if err != nil { - return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff)) - } - - for i := range is { - issues = append(issues, goanalysis.NewIssue(&is[i], pass)) - } + issues, err := runGofmt(lintCtx, pass, settings) + if err != nil { + return nil, err } if len(issues) == 0 { @@ -70,3 +51,30 @@ func NewGofmt() *goanalysis.Linter { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runGofmt(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoFmtSettings) ([]goanalysis.Issue, error) { + fileNames := getFileNames(pass) + + var issues []goanalysis.Issue + + for _, f := range fileNames { + diff, err := gofmtAPI.Run(f, settings.Simplify) + if err != nil { // TODO: skip + return nil, err + } + if diff == nil { + continue + } + + is, err := extractIssuesFromPatch(string(diff), lintCtx, gofmtName) + if err != nil { + return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff)) + } + + for i := range is { + issues = append(issues, goanalysis.NewIssue(&is[i], pass)) + } + } + + return issues, nil +} 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/gofmt_common.go index 4f63e7be..e9241742 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go @@ -9,6 +9,7 @@ import ( "github.com/pkg/errors" diffpkg "github.com/sourcegraph/go-diff/diff" + "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" @@ -49,12 +50,12 @@ type hunkChangesParser struct { func (p *hunkChangesParser) parseDiffLines(h *diffpkg.Hunk) { lines := bytes.Split(h.Body, []byte{'\n'}) - currentOriginalLineNumer := int(h.OrigStartLine) + currentOriginalLineNumber := int(h.OrigStartLine) var ret []diffLine for i, line := range lines { dl := diffLine{ - originalNumber: currentOriginalLineNumer, + originalNumber: currentOriginalLineNumber, } lineStr := string(line) @@ -62,7 +63,7 @@ func (p *hunkChangesParser) parseDiffLines(h *diffpkg.Hunk) { if strings.HasPrefix(lineStr, "-") { dl.typ = diffLineDeleted dl.data = strings.TrimPrefix(lineStr, "-") - currentOriginalLineNumer++ + currentOriginalLineNumber++ } else if strings.HasPrefix(lineStr, "+") { dl.typ = diffLineAdded dl.data = strings.TrimPrefix(lineStr, "+") @@ -74,7 +75,7 @@ func (p *hunkChangesParser) parseDiffLines(h *diffpkg.Hunk) { dl.typ = diffLineOriginal dl.data = strings.TrimPrefix(lineStr, " ") - currentOriginalLineNumer++ + currentOriginalLineNumber++ } ret = append(ret, dl) @@ -207,29 +208,31 @@ func (p *hunkChangesParser) parse(h *diffpkg.Hunk) []Change { return p.ret } -func getErrorTextForLinter(lintCtx *linter.Context, linterName string) string { +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 lintCtx.Settings().Gofumpt.ExtraRules { + if settings.Gofumpt.ExtraRules { text += " with `-extra`" } case gofmtName: text = "File is not `gofmt`-ed" - if lintCtx.Settings().Gofmt.Simplify { + if settings.Gofmt.Simplify { text += " with `-s`" } case goimportsName: text = "File is not `goimports`-ed" - if lintCtx.Settings().Goimports.LocalPrefixes != "" { - text += " with -local " + lintCtx.Settings().Goimports.LocalPrefixes + if settings.Goimports.LocalPrefixes != "" { + text += " with -local " + settings.Goimports.LocalPrefixes } } return text } -func extractIssuesFromPatch(patch string, log logutils.Log, lintCtx *linter.Context, linterName string) ([]result.Issue, error) { +func extractIssuesFromPatch(patch string, lintCtx *linter.Context, linterName string) ([]result.Issue, error) { diffs, err := diffpkg.ParseMultiFileDiff([]byte(patch)) if err != nil { return nil, errors.Wrap(err, "can't parse patch") @@ -239,18 +242,18 @@ func extractIssuesFromPatch(patch string, log logutils.Log, lintCtx *linter.Cont return nil, fmt.Errorf("got no diffs from patch parser: %v", diffs) } - issues := []result.Issue{} + var issues []result.Issue for _, d := range diffs { if len(d.Hunks) == 0 { - log.Warnf("Got no hunks in diff %+v", d) + lintCtx.Log.Warnf("Got no hunks in diff %+v", d) continue } for _, hunk := range d.Hunks { - p := hunkChangesParser{ - log: log, - } + p := hunkChangesParser{log: lintCtx.Log} + changes := p.parse(hunk) + for _, change := range changes { change := change // fix scope i := result.Issue{ @@ -259,7 +262,7 @@ func extractIssuesFromPatch(patch string, log logutils.Log, lintCtx *linter.Cont Filename: d.NewName, Line: change.LineRange.From, }, - Text: getErrorTextForLinter(lintCtx, linterName), + Text: getErrorTextForLinter(lintCtx.Settings(), linterName), Replacement: &change.Replacement, } if change.LineRange.From != change.LineRange.To { 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.go index f0523459..312dfd6d 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go @@ -3,6 +3,7 @@ package golinters import ( "bytes" "fmt" + "io" "os" "sync" @@ -18,71 +19,42 @@ import ( const gofumptName = "gofumpt" -func NewGofumpt() *goanalysis.Linter { +type differ interface { + Diff(out io.Writer, a io.ReadSeeker, b io.ReadSeeker) error +} + +func NewGofumpt(settings *config.GofumptSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue - differ := difflib.New() + + diff := difflib.New() + + var options format.Options + + if settings != nil { + options = format.Options{ + LangVersion: getLangVersion(settings), + ModulePath: settings.ModulePath, + ExtraRules: settings.ExtraRules, + } + } analyzer := &analysis.Analyzer{ Name: gofumptName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( gofumptName, "Gofumpt checks whether code was gofumpt-ed.", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { - settings := lintCtx.Settings().Gofumpt - - options := format.Options{ - LangVersion: getLangVersion(settings), - ModulePath: settings.ModulePath, - ExtraRules: settings.ExtraRules, - } - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var fileNames []string - for _, f := range pass.Files { - pos := pass.Fset.PositionFor(f.Pos(), false) - fileNames = append(fileNames, pos.Filename) - } - - var issues []goanalysis.Issue - - for _, f := range fileNames { - input, err := os.ReadFile(f) - if err != nil { - return nil, fmt.Errorf("unable to open file %s: %w", f, err) - } - - output, err := format.Source(input, options) - if err != nil { - return nil, fmt.Errorf("error while running gofumpt: %w", err) - } - - if !bytes.Equal(input, output) { - out := bytes.Buffer{} - _, err = out.WriteString(fmt.Sprintf("--- %[1]s\n+++ %[1]s\n", f)) - if err != nil { - return nil, fmt.Errorf("error while running gofumpt: %w", err) - } - - err = differ.Diff(&out, bytes.NewReader(input), bytes.NewReader(output)) - if err != nil { - return nil, fmt.Errorf("error while running gofumpt: %w", err) - } - - diff := out.String() - is, err := extractIssuesFromPatch(diff, lintCtx.Log, lintCtx, gofumptName) - if err != nil { - return nil, errors.Wrapf(err, "can't extract issues from gofumpt diff output %q", diff) - } - - for i := range is { - issues = append(issues, goanalysis.NewIssue(&is[i], pass)) - } - } + issues, err := runGofumpt(lintCtx, pass, diff, options) + if err != nil { + return nil, err } if len(issues) == 0 { @@ -100,8 +72,51 @@ func NewGofumpt() *goanalysis.Linter { }).WithLoadMode(goanalysis.LoadModeSyntax) } -func getLangVersion(settings config.GofumptSettings) string { - if settings.LangVersion == "" { +func runGofumpt(lintCtx *linter.Context, pass *analysis.Pass, diff differ, options format.Options) ([]goanalysis.Issue, error) { + fileNames := getFileNames(pass) + + var issues []goanalysis.Issue + + for _, f := range fileNames { + input, err := os.ReadFile(f) + if err != nil { + return nil, fmt.Errorf("unable to open file %s: %w", f, err) + } + + output, err := format.Source(input, options) + if err != nil { + return nil, fmt.Errorf("error while running gofumpt: %w", err) + } + + if !bytes.Equal(input, output) { + out := bytes.Buffer{} + _, err = out.WriteString(fmt.Sprintf("--- %[1]s\n+++ %[1]s\n", f)) + if err != nil { + return nil, fmt.Errorf("error while running gofumpt: %w", err) + } + + err = diff.Diff(&out, bytes.NewReader(input), bytes.NewReader(output)) + if err != nil { + return nil, fmt.Errorf("error while running gofumpt: %w", err) + } + + diff := out.String() + is, err := extractIssuesFromPatch(diff, lintCtx, gofumptName) + if err != nil { + return nil, errors.Wrapf(err, "can't extract issues from gofumpt diff output %q", diff) + } + + for i := range is { + issues = append(issues, goanalysis.NewIssue(&is[i], pass)) + } + } + } + + return issues, nil +} + +func getLangVersion(settings *config.GofumptSettings) string { + if settings == nil || settings.LangVersion == "" { // TODO: defaults to "1.15", in the future (v2) must be set by using build.Default.ReleaseTags like staticcheck. return "1.15" } 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.go index fe83f83c..d7d27326 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go @@ -7,6 +7,7 @@ import ( goheader "github.com/denis-tingaikin/go-header" "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" @@ -14,72 +15,90 @@ import ( const goHeaderName = "goheader" -func NewGoHeader() *goanalysis.Linter { +func NewGoHeader(settings *config.GoHeaderSettings) *goanalysis.Linter { var mu sync.Mutex - var issues []goanalysis.Issue + var resIssues []goanalysis.Issue + + conf := &goheader.Configuration{} + if settings != nil { + conf = &goheader.Configuration{ + Values: settings.Values, + Template: settings.Template, + TemplatePath: settings.TemplatePath, + } + } analyzer := &analysis.Analyzer{ Name: goHeaderName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - goHeaderName, - "Checks is file header matches to pattern", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - cfg := lintCtx.Cfg.LintersSettings.Goheader - c := &goheader.Configuration{ - Values: cfg.Values, - Template: cfg.Template, - TemplatePath: cfg.TemplatePath, - } - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - if c.TemplatePath == "" && c.Template == "" { - // User did not pass template, so then do not run go-header linter - return nil, nil - } - template, err := c.GetTemplate() - if err != nil { - return nil, err - } - values, err := c.GetValues() + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runGoHeader(pass, conf) if err != nil { return nil, err } - a := goheader.New(goheader.WithTemplate(template), goheader.WithValues(values)) - var res []goanalysis.Issue - for _, file := range pass.Files { - path := pass.Fset.Position(file.Pos()).Filename - i := a.Analyze(&goheader.Target{ - File: file, - Path: path, - }) - if i == nil { - continue - } - issue := result.Issue{ - Pos: token.Position{ - Line: i.Location().Line + 1, - Column: i.Location().Position, - Filename: path, - }, - Text: i.Message(), - FromLinter: goHeaderName, - } - res = append(res, goanalysis.NewIssue(&issue, pass)) - } - if len(res) == 0 { + + if len(issues) == 0 { return nil, nil } mu.Lock() - issues = append(issues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return issues + }, + } + + return goanalysis.NewLinter( + goHeaderName, + "Checks is file header matches to pattern", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runGoHeader(pass *analysis.Pass, conf *goheader.Configuration) ([]goanalysis.Issue, error) { + if conf.TemplatePath == "" && conf.Template == "" { + // User did not pass template, so then do not run go-header linter + return nil, nil + } + + template, err := conf.GetTemplate() + if err != nil { + return nil, err + } + + values, err := conf.GetValues() + if err != nil { + return nil, err + } + + a := goheader.New(goheader.WithTemplate(template), goheader.WithValues(values)) + + var issues []goanalysis.Issue + for _, file := range pass.Files { + path := pass.Fset.Position(file.Pos()).Filename + + i := a.Analyze(&goheader.Target{File: file, Path: path}) + + if i == nil { + continue + } + + issue := result.Issue{ + Pos: token.Position{ + Line: i.Location().Line + 1, + Column: i.Location().Position, + Filename: path, + }, + Text: i.Message(), + FromLinter: goHeaderName, + } + + issues = append(issues, goanalysis.NewIssue(&issue, pass)) + } + + return issues, nil +} 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.go index b58af196..42aa69b4 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go @@ -8,53 +8,35 @@ import ( "golang.org/x/tools/go/analysis" "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/lint/linter" ) const goimportsName = "goimports" -func NewGoimports() *goanalysis.Linter { +func NewGoimports(settings *config.GoImportsSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: goimportsName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( goimportsName, "In addition to fixing imports, goimports also formats your code in the same style as gofmt.", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { - imports.LocalPrefix = lintCtx.Settings().Goimports.LocalPrefixes - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var fileNames []string - for _, f := range pass.Files { - pos := pass.Fset.PositionFor(f.Pos(), false) - fileNames = append(fileNames, pos.Filename) - } + imports.LocalPrefix = settings.LocalPrefixes - var issues []goanalysis.Issue - - for _, f := range fileNames { - diff, err := goimportsAPI.Run(f) - if err != nil { // TODO: skip - return nil, err - } - if diff == nil { - continue - } - - is, err := extractIssuesFromPatch(string(diff), lintCtx.Log, lintCtx, goimportsName) - if err != nil { - return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff)) - } - - for i := range is { - issues = append(issues, goanalysis.NewIssue(&is[i], pass)) - } + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { + issues, err := runGoiImports(lintCtx, pass) + if err != nil { + return nil, err } if len(issues) == 0 { @@ -71,3 +53,30 @@ func NewGoimports() *goanalysis.Linter { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runGoiImports(lintCtx *linter.Context, pass *analysis.Pass) ([]goanalysis.Issue, error) { + fileNames := getFileNames(pass) + + var issues []goanalysis.Issue + + for _, f := range fileNames { + diff, err := goimportsAPI.Run(f) + if err != nil { // TODO: skip + return nil, err + } + if diff == nil { + continue + } + + is, err := extractIssuesFromPatch(string(diff), lintCtx, goimportsName) + if err != nil { + return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff)) + } + + for i := range is { + issues = append(issues, goanalysis.NewIssue(&is[i], pass)) + } + } + + return issues, nil +} 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 index 3b1b1b66..95c579e3 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/golint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/golint.go @@ -2,35 +2,71 @@ package golinters import ( "fmt" - "go/ast" - "go/token" - "go/types" "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" ) -func golintProcessPkg(minConfidence float64, files []*ast.File, fset *token.FileSet, - typesPkg *types.Package, typesInfo *types.Info) ([]result.Issue, error) { +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) (interface{}, 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(files, fset, typesPkg, typesInfo) + + 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(files), err) + return nil, fmt.Errorf("can't lint %d files: %s", len(pass.Files), err) } if len(ps) == 0 { return nil, nil } - issues := make([]result.Issue, 0, len(ps)) // This is worst case + lintIssues := make([]*result.Issue, 0, len(ps)) // This is worst case for idx := range ps { - if ps[idx].Confidence >= minConfidence { - issues = append(issues, result.Issue{ + if ps[idx].Confidence >= settings.MinConfidence { + lintIssues = append(lintIssues, &result.Issue{ Pos: ps[idx].Position, Text: ps[idx].Text, FromLinter: golintName, @@ -39,40 +75,10 @@ func golintProcessPkg(minConfidence float64, files []*ast.File, fset *token.File } } - return issues, nil -} - -const golintName = "golint" - -func NewGolint() *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: golintName, - Doc: goanalysis.TheOnlyanalyzerDoc, + issues := make([]goanalysis.Issue, 0, len(lintIssues)) + for _, issue := range lintIssues { + issues = append(issues, goanalysis.NewIssue(issue, pass)) } - return goanalysis.NewLinter( - golintName, - "Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - res, err := golintProcessPkg(lintCtx.Settings().Golint.MinConfidence, pass.Files, pass.Fset, pass.Pkg, pass.TypesInfo) - if err != nil || len(res) == 0 { - return nil, err - } - - mu.Lock() - for i := range res { - resIssues = append(resIssues, goanalysis.NewIssue(&res[i], pass)) - } - mu.Unlock() - return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeTypesInfo) + return issues, nil } 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.go index 40d3bf78..81831129 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomoddirectives.go @@ -30,6 +30,7 @@ func NewGoModDirectives(settings *config.GoModDirectivesSettings) *goanalysis.Li analyzer := &analysis.Analyzer{ Name: goanalysis.TheOnlyAnalyzerName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } return goanalysis.NewLinter( 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.go index 30ca6cc3..e21658d5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go @@ -6,6 +6,7 @@ import ( "github.com/ryancurrah/gomodguard" "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" @@ -19,31 +20,18 @@ const ( ) // NewGomodguard returns a new Gomodguard linter. -func NewGomodguard() *goanalysis.Linter { - var ( - issues []goanalysis.Issue - mu = sync.Mutex{} - analyzer = &analysis.Analyzer{ - Name: goanalysis.TheOnlyAnalyzerName, - Doc: goanalysis.TheOnlyanalyzerDoc, - } - ) - - return goanalysis.NewLinter( - gomodguardName, - gomodguardDesc, - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - linterCfg := lintCtx.Cfg.LintersSettings.Gomodguard - - processorCfg := &gomodguard.Configuration{} - processorCfg.Allowed.Modules = linterCfg.Allowed.Modules - processorCfg.Allowed.Domains = linterCfg.Allowed.Domains - processorCfg.Blocked.LocalReplaceDirectives = linterCfg.Blocked.LocalReplaceDirectives - - for n := range linterCfg.Blocked.Modules { - for k, v := range linterCfg.Blocked.Modules[n] { +func NewGomodguard(settings *config.GoModGuardSettings) *goanalysis.Linter { + var issues []goanalysis.Issue + var mu sync.Mutex + + processorCfg := &gomodguard.Configuration{} + if settings != nil { + processorCfg.Allowed.Modules = settings.Allowed.Modules + processorCfg.Allowed.Domains = settings.Allowed.Domains + processorCfg.Blocked.LocalReplaceDirectives = settings.Blocked.LocalReplaceDirectives + + for n := range settings.Blocked.Modules { + for k, v := range settings.Blocked.Modules[n] { m := map[string]gomodguard.BlockedModule{k: { Recommendations: v.Recommendations, Reason: v.Reason, @@ -53,8 +41,8 @@ func NewGomodguard() *goanalysis.Linter { } } - for n := range linterCfg.Blocked.Versions { - for k, v := range linterCfg.Blocked.Versions[n] { + for n := range settings.Blocked.Versions { + for k, v := range settings.Blocked.Versions[n] { m := map[string]gomodguard.BlockedVersion{k: { Version: v.Version, Reason: v.Reason, @@ -63,7 +51,20 @@ func NewGomodguard() *goanalysis.Linter { break } } + } + analyzer := &analysis.Analyzer{ + Name: goanalysis.TheOnlyAnalyzerName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, + } + + return goanalysis.NewLinter( + gomodguardName, + gomodguardDesc, + []*analysis.Analyzer{analyzer}, + nil, + ).WithContextSetter(func(lintCtx *linter.Context) { processor, err := gomodguard.NewProcessor(processorCfg) if err != nil { lintCtx.Log.Warnf("running gomodguard failed: %s: if you are not using go modules "+ @@ -72,13 +73,7 @@ func NewGomodguard() *goanalysis.Linter { } analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var files []string - - for _, file := range pass.Files { - files = append(files, pass.Fset.PositionFor(file.Pos(), false).Filename) - } - - gomodguardIssues := processor.ProcessFiles(files) + gomodguardIssues := processor.ProcessFiles(getFileNames(pass)) mu.Lock() defer mu.Unlock() 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.go index 600a6e0f..3b102a92 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go @@ -27,27 +27,32 @@ func NewGosec(settings *config.GoSecSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue - gasConfig := gosec.NewConfig() + conf := gosec.NewConfig() var filters []rules.RuleFilter if settings != nil { filters = gosecRuleFilters(settings.Includes, settings.Excludes) for k, v := range settings.Config { - // Uses ToUpper because the parsing of the map's key change the key to lowercase. - // The value is not impacted by that: the case is respected. - gasConfig.Set(strings.ToUpper(k), v) + if k != gosec.Globals { + // Uses ToUpper because the parsing of the map's key change the key to lowercase. + // The value is not impacted by that: the case is respected. + k = strings.ToUpper(k) + } + conf.Set(k, v) } } - ruleDefinitions := rules.Generate(false, filters...) - logger := log.New(io.Discard, "", 0) + ruleDefinitions := rules.Generate(false, filters...) + analyzer := &analysis.Analyzer{ Name: gosecName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( gosecName, "Inspects source code for security problems", @@ -55,64 +60,14 @@ func NewGosec(settings *config.GoSecSettings) *goanalysis.Linter { nil, ).WithContextSetter(func(lintCtx *linter.Context) { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - gosecAnalyzer := gosec.NewAnalyzer(gasConfig, true, settings.ExcludeGenerated, false, settings.Concurrency, logger) + // The `gosecAnalyzer` is here because of concurrency issue. + gosecAnalyzer := gosec.NewAnalyzer(conf, true, settings.ExcludeGenerated, false, settings.Concurrency, logger) gosecAnalyzer.LoadRules(ruleDefinitions.RulesInfo()) - pkg := &packages.Package{ - Fset: pass.Fset, - Syntax: pass.Files, - Types: pass.Pkg, - TypesInfo: pass.TypesInfo, - } - gosecAnalyzer.Check(pkg) - issues, _, _ := gosecAnalyzer.Report() - if len(issues) == 0 { - return nil, nil - } - severity, err := convertToScore(settings.Severity) - if err != nil { - lintCtx.Log.Warnf("The provided severity %v", err) - } - - confidence, err := convertToScore(settings.Confidence) - if err != nil { - lintCtx.Log.Warnf("The provided confidence %v", err) - } - issues = filterIssues(issues, severity, confidence) - res := make([]goanalysis.Issue, 0, len(issues)) - for _, i := range issues { - text := fmt.Sprintf("%s: %s", i.RuleID, i.What) // TODO: use severity and confidence - var r *result.Range - line, err := strconv.Atoi(i.Line) - if err != nil { - r = &result.Range{} - if n, rerr := fmt.Sscanf(i.Line, "%d-%d", &r.From, &r.To); rerr != nil || n != 2 { - lintCtx.Log.Warnf("Can't convert gosec line number %q of %v to int: %s", i.Line, i, err) - continue - } - line = r.From - } - - column, err := strconv.Atoi(i.Col) - if err != nil { - lintCtx.Log.Warnf("Can't convert gosec column number %q of %v to int: %s", i.Col, i, err) - continue - } - - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: token.Position{ - Filename: i.File, - Line: line, - Column: column, - }, - Text: text, - LineRange: r, - FromLinter: gosecName, - }, pass)) - } + issues := runGoSec(lintCtx, pass, settings, gosecAnalyzer) mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil @@ -122,6 +77,70 @@ func NewGosec(settings *config.GoSecSettings) *goanalysis.Linter { }).WithLoadMode(goanalysis.LoadModeTypesInfo) } +func runGoSec(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoSecSettings, analyzer *gosec.Analyzer) []goanalysis.Issue { + pkg := &packages.Package{ + Fset: pass.Fset, + Syntax: pass.Files, + Types: pass.Pkg, + TypesInfo: pass.TypesInfo, + } + + analyzer.Check(pkg) + + secIssues, _, _ := analyzer.Report() + if len(secIssues) == 0 { + return nil + } + + severity, err := convertToScore(settings.Severity) + if err != nil { + lintCtx.Log.Warnf("The provided severity %v", err) + } + + confidence, err := convertToScore(settings.Confidence) + if err != nil { + lintCtx.Log.Warnf("The provided confidence %v", err) + } + + secIssues = filterIssues(secIssues, severity, confidence) + + 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 + + var r *result.Range + + line, err := strconv.Atoi(i.Line) + if err != nil { + r = &result.Range{} + if n, rerr := fmt.Sscanf(i.Line, "%d-%d", &r.From, &r.To); rerr != nil || n != 2 { + lintCtx.Log.Warnf("Can't convert gosec line number %q of %v to int: %s", i.Line, i, err) + continue + } + line = r.From + } + + column, err := strconv.Atoi(i.Col) + if err != nil { + lintCtx.Log.Warnf("Can't convert gosec column number %q of %v to int: %s", i.Col, i, err) + continue + } + + issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Pos: token.Position{ + Filename: i.File, + Line: line, + Column: column, + }, + Text: text, + LineRange: r, + FromLinter: gosecName, + }, pass)) + } + + return issues +} + // based on https://github.com/securego/gosec/blob/569328eade2ccbad4ce2d0f21ee158ab5356a5cf/cmd/gosec/main.go#L170-L188 func gosecRuleFilters(includes, excludes []string) []rules.RuleFilter { var filters []rules.RuleFilter 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 index fa14f1a9..de60ded7 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosimple.go @@ -14,7 +14,7 @@ func NewGosimple(settings *config.StaticCheckSettings) *goanalysis.Linter { return goanalysis.NewLinter( "gosimple", - "Linter for Go source code that specializes in simplifying a code", + "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/govet.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet.go index c7a58af6..4991160a 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/govet.go @@ -119,33 +119,34 @@ var ( } ) -func NewGovet(cfg *config.GovetSettings) *goanalysis.Linter { - var settings map[string]map[string]interface{} - if cfg != nil { - settings = cfg.Settings +func NewGovet(settings *config.GovetSettings) *goanalysis.Linter { + var conf map[string]map[string]interface{} + if settings != nil { + conf = settings.Settings } + 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", - analyzersFromConfig(cfg), - settings, + analyzersFromConfig(settings), + conf, ).WithLoadMode(goanalysis.LoadModeTypesInfo) } -func analyzersFromConfig(cfg *config.GovetSettings) []*analysis.Analyzer { - if cfg == nil { +func analyzersFromConfig(settings *config.GovetSettings) []*analysis.Analyzer { + if settings == nil { return defaultAnalyzers } - if cfg.CheckShadowing { + if settings.CheckShadowing { // Keeping for backward compatibility. - cfg.Enable = append(cfg.Enable, shadow.Analyzer.Name) + settings.Enable = append(settings.Enable, shadow.Analyzer.Name) } var enabledAnalyzers []*analysis.Analyzer for _, a := range allAnalyzers { - if isAnalyzerEnabled(a.Name, cfg, defaultAnalyzers) { + if isAnalyzerEnabled(a.Name, settings, defaultAnalyzers) { enabledAnalyzers = append(enabledAnalyzers, a) } } @@ -154,11 +155,6 @@ func analyzersFromConfig(cfg *config.GovetSettings) []*analysis.Analyzer { } func isAnalyzerEnabled(name string, cfg *config.GovetSettings, defaultAnalyzers []*analysis.Analyzer) bool { - if (name == nilness.Analyzer.Name || name == unusedwrite.Analyzer.Name) && - config.IsGreaterThanOrEqualGo118(cfg.Go) { - return false - } - if cfg.EnableAll { for _, n := range cfg.Disable { if n == name { 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.go index d1f04282..1917bbb0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/importas.go @@ -4,7 +4,7 @@ import ( "fmt" "strconv" - "github.com/julz/importas" // nolint: misspell + "github.com/julz/importas" //nolint:misspell "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" @@ -25,7 +25,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.") //nolint:misspell } 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/interfacebloat.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat.go new file mode 100644 index 00000000..f9cf81c8 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacebloat.go @@ -0,0 +1,27 @@ +package golinters + +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" +) + +func NewInterfaceBloat(settings *config.InterfaceBloatSettings) *goanalysis.Linter { + a := analyzer.New() + + cfgMap := make(map[string]map[string]interface{}) + if settings != nil { + cfgMap[a.Name] = map[string]interface{}{ + analyzer.InterfaceMaxMethodsFlag: settings.Max, + } + } + + 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/interfacer.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacer.go index 1edbe894..59125c5c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacer.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/interfacer.go @@ -22,46 +22,61 @@ func NewInterfacer() *goanalysis.Linter { Name: interfacerName, Doc: goanalysis.TheOnlyanalyzerDoc, Requires: []*analysis.Analyzer{buildssa.Analyzer}, - } - return goanalysis.NewLinter( - interfacerName, - "Linter that suggests narrower interface types", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - ssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) - ssaPkg := ssa.Pkg - c := &check.Checker{} - prog := goanalysis.MakeFakeLoaderProgram(pass) - c.Program(prog) - c.ProgramSSA(ssaPkg.Prog) - - issues, err := c.Check() + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runInterfacer(pass) if err != nil { return nil, err } + if len(issues) == 0 { return nil, nil } - res := make([]goanalysis.Issue, 0, len(issues)) - for _, i := range issues { - pos := pass.Fset.Position(i.Pos()) - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: pos, - Text: i.Message(), - FromLinter: interfacerName, - }, pass)) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + 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/lll.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go index e0a9de63..8b5ebd3c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go @@ -11,11 +11,70 @@ 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/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) +const lllName = "lll" + +//nolint:dupl +func NewLLL(settings *config.LllSettings) *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue + + analyzer := &analysis.Analyzer{ + Name: lllName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runLll(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( + lllName, + "Reports long lines", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} + +func runLll(pass *analysis.Pass, settings *config.LllSettings) ([]goanalysis.Issue, error) { + fileNames := getFileNames(pass) + + spaces := strings.Repeat(" ", settings.TabWidth) + + var issues []goanalysis.Issue + for _, f := range fileNames { + lintIssues, err := getLLLIssuesForFile(f, settings.LineLength, spaces) + if err != nil { + return nil, err + } + + for i := range lintIssues { + issues = append(issues, goanalysis.NewIssue(&lintIssues[i], pass)) + } + } + + return issues, nil +} + func getLLLIssuesForFile(filename string, maxLineLen int, tabSpaces string) ([]result.Issue, error) { var res []result.Issue @@ -29,7 +88,7 @@ func getLLLIssuesForFile(filename string, maxLineLen int, tabSpaces string) ([]r scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() - line = strings.Replace(line, "\t", tabSpaces, -1) + line = strings.ReplaceAll(line, "\t", tabSpaces) lineLen := utf8.RuneCountInString(line) if lineLen > maxLineLen { res = append(res, result.Issue{ @@ -72,53 +131,3 @@ func getLLLIssuesForFile(filename string, maxLineLen int, tabSpaces string) ([]r return res, nil } - -const lllName = "lll" - -func NewLLL() *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: lllName, - Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - lllName, - "Reports long lines", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var fileNames []string - for _, f := range pass.Files { - pos := pass.Fset.PositionFor(f.Pos(), false) - fileNames = append(fileNames, pos.Filename) - } - - var res []goanalysis.Issue - spaces := strings.Repeat(" ", lintCtx.Settings().Lll.TabWidth) - for _, f := range fileNames { - issues, err := getLLLIssuesForFile(f, lintCtx.Settings().Lll.LineLength, spaces) - if err != nil { - return nil, err - } - for i := range issues { - res = append(res, goanalysis.NewIssue(&issues[i], pass)) - } - } - - if len(res) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, res...) - mu.Unlock() - - return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).WithLoadMode(goanalysis.LoadModeSyntax) -} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/logrlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/logrlint.go new file mode 100644 index 00000000..9899808c --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/logrlint.go @@ -0,0 +1,19 @@ +package golinters + +import ( + "github.com/timonwong/logrlint" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" +) + +func NewLogrLint() *goanalysis.Linter { + a := logrlint.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/maintidx.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx.go index 2b02b948..183006b0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maintidx.go @@ -24,9 +24,7 @@ func NewMaintIdx(cfg *config.MaintIdxSettings) *goanalysis.Linter { return goanalysis.NewLinter( analyzer.Name, analyzer.Doc, - []*analysis.Analyzer{ - analyzer, - }, + []*analysis.Analyzer{analyzer}, cfgMap, ).WithLoadMode(goanalysis.LoadModeSyntax) } 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.go index cdde0929..5d55f01e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/makezero.go @@ -7,6 +7,7 @@ import ( "github.com/pkg/errors" "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" @@ -14,47 +15,61 @@ import ( const makezeroName = "makezero" -func NewMakezero() *goanalysis.Linter { +//nolint:dupl +func NewMakezero(settings *config.MakezeroSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: makezeroName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - makezeroName, - "Finds slice declarations with non-zero initial length", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - s := &lintCtx.Settings().Makezero - - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var res []goanalysis.Issue - linter := makezero.NewLinter(s.Always) - for _, file := range pass.Files { - hints, err := linter.Run(pass.Fset, pass.TypesInfo, file) - if err != nil { - return nil, errors.Wrapf(err, "makezero linter failed on file %q", file.Name.String()) - } - for _, hint := range hints { - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: hint.Position(), - Text: hint.Details(), - FromLinter: makezeroName, - }, pass)) - } + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runMakeZero(pass, settings) + if err != nil { + return nil, err } - if len(res) == 0 { + + if len(issues) == 0 { return nil, nil } + mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() + return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + makezeroName, + "Finds slice declarations with non-zero initial length", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeTypesInfo) } + +func runMakeZero(pass *analysis.Pass, settings *config.MakezeroSettings) ([]goanalysis.Issue, error) { + zero := makezero.NewLinter(settings.Always) + + var issues []goanalysis.Issue + + for _, file := range pass.Files { + hints, err := zero.Run(pass.Fset, pass.TypesInfo, file) + if err != nil { + return nil, errors.Wrapf(err, "makezero linter failed on file %q", file.Name.String()) + } + + for _, hint := range hints { + issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Pos: hint.Position(), + Text: hint.Details(), + FromLinter: makezeroName, + }, pass)) + } + } + + return issues, nil +} 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 index 22422b8c..9c3ca8b5 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maligned.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/maligned.go @@ -7,52 +7,68 @@ import ( 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" ) -func NewMaligned() *goanalysis.Linter { - const linterName = "maligned" +const malignedName = "maligned" + +//nolint:dupl +func NewMaligned(settings *config.MalignedSettings) *goanalysis.Linter { var mu sync.Mutex var res []goanalysis.Issue + analyzer := &analysis.Analyzer{ - Name: linterName, + Name: malignedName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - linterName, - "Tool to detect Go structs that would take less memory if their fields were sorted", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - prog := goanalysis.MakeFakeLoaderProgram(pass) + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runMaligned(pass, settings) - malignedIssues := malignedAPI.Run(prog) - if len(malignedIssues) == 0 { + if len(issues) == 0 { return nil, 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 lintCtx.Settings().Maligned.SuggestNewOrder { - text += fmt.Sprintf(":\n%s", formatCodeBlock(i.NewStructDef, lintCtx.Cfg)) - } - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: text, - FromLinter: linterName, - }, pass)) - } - mu.Lock() res = append(res, issues...) mu.Unlock() + return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + 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/misspell.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go index 80ecf9bb..b5cc5c8a 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go @@ -9,119 +9,48 @@ import ( "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/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -func runMisspellOnFile(fileName string, r *misspell.Replacer, lintCtx *linter.Context) ([]result.Issue, error) { - var res []result.Issue - fileContent, err := lintCtx.FileCache.GetFileBytes(fileName) - if err != nil { - return nil, fmt.Errorf("can't get file %s contents: %s", fileName, err) - } - - // 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 := r.Replace(string(fileContent)) - 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, - Length: len(diff.Original), - NewString: diff.Corrected, - }, - } - - res = append(res, result.Issue{ - Pos: pos, - Text: text, - FromLinter: misspellName, - Replacement: replacement, - }) - } - - return res, nil -} - const misspellName = "misspell" -func NewMisspell() *goanalysis.Linter { +func NewMisspell(settings *config.MisspellSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue - var ruleErr error analyzer := &analysis.Analyzer{ Name: misspellName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( misspellName, "Finds commonly misspelled English words in comments", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { - r := misspell.Replacer{ - Replacements: misspell.DictMain, - } - - // Figure out regional variations - settings := lintCtx.Settings().Misspell - locale := settings.Locale - switch strings.ToUpper(locale) { - case "": - // nothing - case "US": - r.AddRuleList(misspell.DictAmerican) - case "UK", "GB": - r.AddRuleList(misspell.DictBritish) - case "NZ", "AU", "CA": - ruleErr = fmt.Errorf("unknown locale: %q", locale) - } - - if ruleErr == nil { - if len(settings.IgnoreWords) != 0 { - r.RemoveRule(settings.IgnoreWords) - } - - r.Compile() - } + replacer, ruleErr := createMisspellReplacer(settings) analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { if ruleErr != nil { return nil, ruleErr } - var fileNames []string - for _, f := range pass.Files { - pos := pass.Fset.PositionFor(f.Pos(), false) - fileNames = append(fileNames, pos.Filename) + issues, err := runMisspell(lintCtx, pass, replacer) + if err != nil { + return nil, err } - var res []goanalysis.Issue - for _, f := range fileNames { - issues, err := runMisspellOnFile(f, &r, lintCtx) - if err != nil { - return nil, err - } - for i := range issues { - res = append(res, goanalysis.NewIssue(&issues[i], pass)) - } - } - if len(res) == 0 { + if len(issues) == 0 { return nil, nil } mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil @@ -130,3 +59,85 @@ func NewMisspell() *goanalysis.Linter { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runMisspell(lintCtx *linter.Context, pass *analysis.Pass, replacer *misspell.Replacer) ([]goanalysis.Issue, error) { + fileNames := getFileNames(pass) + + var issues []goanalysis.Issue + for _, filename := range fileNames { + lintIssues, err := runMisspellOnFile(lintCtx, filename, replacer) + if err != nil { + return nil, err + } + for i := range lintIssues { + issues = append(issues, goanalysis.NewIssue(&lintIssues[i], pass)) + } + } + + return issues, nil +} + +func createMisspellReplacer(settings *config.MisspellSettings) (*misspell.Replacer, error) { + replacer := &misspell.Replacer{ + Replacements: misspell.DictMain, + } + + // Figure out regional variations + switch strings.ToUpper(settings.Locale) { + case "": + // nothing + case "US": + replacer.AddRuleList(misspell.DictAmerican) + case "UK", "GB": + replacer.AddRuleList(misspell.DictBritish) + case "NZ", "AU", "CA": + return nil, fmt.Errorf("unknown locale: %q", settings.Locale) + } + + if len(settings.IgnoreWords) != 0 { + replacer.RemoveRule(settings.IgnoreWords) + } + + // It can panic. + replacer.Compile() + + return replacer, nil +} + +func runMisspellOnFile(lintCtx *linter.Context, filename string, replacer *misspell.Replacer) ([]result.Issue, error) { + var res []result.Issue + fileContent, err := lintCtx.FileCache.GetFileBytes(filename) + if err != nil { + return nil, fmt.Errorf("can't get file %s contents: %s", filename, err) + } + + // 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)) + 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, + Length: len(diff.Original), + NewString: diff.Corrected, + }, + } + + res = append(res, result.Issue{ + Pos: pos, + Text: text, + FromLinter: misspellName, + Replacement: replacement, + }) + } + + return res, 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 index 86735a51..dc2de034 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nakedret.go @@ -8,11 +8,66 @@ 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/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) +const nakedretName = "nakedret" + +//nolint:dupl +func NewNakedret(settings *config.NakedretSettings) *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue + + analyzer := &analysis.Analyzer{ + Name: nakedretName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runNakedRet(pass, settings) + + if len(issues) == 0 { + return nil, nil + } + + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() + + return nil, nil + }, + } + + return goanalysis.NewLinter( + nakedretName, + "Finds naked returns in functions greater than a specified function length", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} + +func runNakedRet(pass *analysis.Pass, settings *config.NakedretSettings) []goanalysis.Issue { + var issues []goanalysis.Issue + + for _, file := range pass.Files { + v := nakedretVisitor{ + maxLength: settings.MaxFuncLines, + f: pass.Fset, + } + + ast.Walk(&v, file) + + for i := range v.issues { + issues = append(issues, goanalysis.NewIssue(&v.issues[i], pass)) + } + } + + return issues +} + type nakedretVisitor struct { maxLength int f *token.FileSet @@ -77,47 +132,3 @@ func (v *nakedretVisitor) Visit(node ast.Node) ast.Visitor { v.processFuncDecl(funcDecl) return v } - -const nakedretName = "nakedret" - -func NewNakedret() *goanalysis.Linter { - var mu sync.Mutex - var resIssues []goanalysis.Issue - - analyzer := &analysis.Analyzer{ - Name: nakedretName, - Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - nakedretName, - "Finds naked returns in functions greater than a specified function length", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var res []goanalysis.Issue - for _, file := range pass.Files { - v := nakedretVisitor{ - maxLength: lintCtx.Settings().Nakedret.MaxFuncLines, - f: pass.Fset, - } - ast.Walk(&v, file) - for i := range v.issues { - res = append(res, goanalysis.NewIssue(&v.issues[i], pass)) - } - } - - if len(res) == 0 { - return nil, nil - } - - mu.Lock() - resIssues = append(resIssues, res...) - mu.Unlock() - - return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return resIssues - }).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.go index 0998a8ce..78a516f9 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nestif.go @@ -7,6 +7,7 @@ import ( "github.com/nakabonne/nestif" "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" @@ -14,52 +15,65 @@ import ( const nestifName = "nestif" -func NewNestif() *goanalysis.Linter { +//nolint:dupl +func NewNestif(settings *config.NestifSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: goanalysis.TheOnlyAnalyzerName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - nestifName, - "Reports deeply nested if statements", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - checker := &nestif.Checker{ - MinComplexity: lintCtx.Settings().Nestif.MinComplexity, - } - var issues []nestif.Issue - for _, f := range pass.Files { - issues = append(issues, checker.Check(f, pass.Fset)...) - } + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runNestIf(pass, settings) + if len(issues) == 0 { return nil, nil } - sort.SliceStable(issues, func(i, j int) bool { - return issues[i].Complexity > issues[j].Complexity - }) - - res := make([]goanalysis.Issue, 0, len(issues)) - for _, i := range issues { - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: i.Message, - FromLinter: nestifName, - }, pass)) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + nestifName, + "Reports deeply nested if statements", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runNestIf(pass *analysis.Pass, settings *config.NestifSettings) []goanalysis.Issue { + checker := &nestif.Checker{ + MinComplexity: settings.MinComplexity, + } + + var lintIssues []nestif.Issue + for _, f := range pass.Files { + lintIssues = append(lintIssues, checker.Check(f, pass.Fset)...) + } + + if len(lintIssues) == 0 { + return nil + } + + sort.SliceStable(lintIssues, func(i, j int) bool { + return lintIssues[i].Complexity > lintIssues[j].Complexity + }) + + issues := make([]goanalysis.Issue, 0, len(lintIssues)) + for _, i := range lintIssues { + issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Pos: i.Pos, + Text: i.Message, + FromLinter: nestifName, + }, pass)) + } + + return issues +} 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.go index d8a9a613..2ea16f2f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nilerr.go @@ -9,6 +9,7 @@ import ( func NewNilErr() *goanalysis.Linter { a := nilerr.Analyzer + return goanalysis.NewLinter( a.Name, "Finds the code that returns nil even if it checks that the error is not nil.", 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 index b5c4a4be..b7fcd2a7 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go @@ -8,14 +8,10 @@ import ( ) func NewNoctx() *goanalysis.Linter { - analyzers := []*analysis.Analyzer{ - noctx.Analyzer, - } - return goanalysis.NewLinter( "noctx", "noctx finds sending http request without context.Context", - analyzers, + []*analysis.Analyzer{noctx.Analyzer}, 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 index 889cff86..a809f449 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint.go @@ -7,87 +7,99 @@ 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/golinters/nolintlint" "github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -const NolintlintName = "nolintlint" +const NoLintLintName = "nolintlint" -func NewNoLintLint() *goanalysis.Linter { +//nolint:dupl +func NewNoLintLint(settings *config.NoLintLintSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: NolintlintName, + Name: NoLintLintName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - NolintlintName, - "Reports ill-formed or insufficient nolint directives", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var needs nolintlint.Needs - settings := lintCtx.Settings().NoLintLint - if settings.RequireExplanation { - needs |= nolintlint.NeedsExplanation - } - if !settings.AllowLeadingSpace { - needs |= nolintlint.NeedsMachineOnly - } - if settings.RequireSpecific { - needs |= nolintlint.NeedsSpecific - } - if !settings.AllowUnused { - needs |= nolintlint.NeedsUnused - } - - lnt, err := nolintlint.NewLinter(needs, settings.AllowNoExplanation) + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runNoLintLint(pass, settings) if err != nil { return nil, err } - nodes := make([]ast.Node, 0, len(pass.Files)) - for _, n := range pass.Files { - nodes = append(nodes, n) - } - issues, err := lnt.Run(pass.Fset, nodes...) - if err != nil { - return nil, fmt.Errorf("linter failed to run: %s", err) - } - var res []goanalysis.Issue - for _, i := range issues { - 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(), - } - res = append(res, goanalysis.NewIssue(issue, pass)) - } - - if len(res) == 0 { + if len(issues) == 0 { return nil, nil } mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + 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/README.md index 3d440d5a..9f4604d1 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/README.md @@ -1,6 +1,6 @@ # nolintlint -nolintlint is a Go static analysis tool to find ill-formed or insufficiently explained `// nolint` directives for golangci +nolintlint is a Go static analysis tool to find ill-formed or insufficiently explained `//nolint` directives for golangci (or any other linter, using th ) ## Purpose @@ -8,10 +8,10 @@ nolintlint is a Go static analysis tool to find ill-formed or insufficiently exp To ensure that lint exceptions have explanations. Consider the case below: ```Go -import "crypto/md5" //nolint +import "crypto/md5" //nolint:all func hash(data []byte) []byte { - return md5.New().Sum(data) //nolint + return md5.New().Sum(data) //nolint:all } ``` @@ -27,5 +27,5 @@ func hash(data []byte) []byte { ``` `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` and that you mention what linter is being suppressed, as shown above when we write `//nolint:gosec`. +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/nolintlint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nolintlint/nolintlint.go index 064fd61a..9c6b10f3 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 @@ -152,7 +152,7 @@ func NewLinter(needs Needs, excludes []string) (*Linter, error) { } return &Linter{ - needs: needs, + needs: needs | NeedsMachineOnly, excludeByLinter: excludeByName, }, nil } @@ -184,12 +184,14 @@ func (l Linter) Run(fset *token.FileSet, nodes ...ast.Node) ([]Issue, error) { leadingSpace = leadingSpaceMatches[1] } - directiveWithOptionalLeadingSpace := comment.Text + directiveWithOptionalLeadingSpace := "//" if len(leadingSpace) > 0 { - split := strings.Split(strings.SplitN(comment.Text, ":", 2)[0], "//") - directiveWithOptionalLeadingSpace = "// " + strings.TrimSpace(split[1]) + 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()) @@ -227,8 +229,9 @@ func (l Linter) Run(fset *token.FileSet, nodes ...ast.Node) ([]Issue, error) { } lintersText, explanation := fullMatches[1], fullMatches[2] + var linters []string - if len(lintersText) > 0 { + 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:") 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.go index 8c943d83..3dff2f75 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nonamedreturns.go @@ -4,14 +4,26 @@ 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" ) -func NewNoNamedReturns() *goanalysis.Linter { +func NewNoNamedReturns(settings *config.NoNamedReturnsSettings) *goanalysis.Linter { + a := analyzer.Analyzer + + var cfg map[string]map[string]interface{} + if settings != nil { + cfg = map[string]map[string]interface{}{ + a.Name: { + analyzer.FlagReportErrorInDefer: settings.ReportErrorInDefer, + }, + } + } + return goanalysis.NewLinter( - "nonamedreturns", - "Reports all named returns", - []*analysis.Analyzer{analyzer.Analyzer}, - nil, - ).WithLoadMode(goanalysis.LoadModeSyntax) + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + cfg, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) } 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 new file mode 100644 index 00000000..26d5d6d4 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/nosnakecase.go @@ -0,0 +1,19 @@ +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/paralleltest.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest.go index 3b784baf..5f50a394 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/paralleltest.go @@ -4,18 +4,26 @@ 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() *goanalysis.Linter { - analyzers := []*analysis.Analyzer{ - paralleltest.NewAnalyzer(), +func NewParallelTest(settings *config.ParallelTestSettings) *goanalysis.Linter { + a := paralleltest.Analyzer + + var cfg map[string]map[string]interface{} + if settings != nil { + cfg = map[string]map[string]interface{}{ + a.Name: { + "i": settings.IgnoreMissing, + }, + } } return goanalysis.NewLinter( "paralleltest", "paralleltest detects missing usage of t.Parallel() method in your Go test", - analyzers, - nil, - ).WithLoadMode(goanalysis.LoadModeSyntax) + []*analysis.Analyzer{paralleltest.Analyzer}, + 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.go index 3d06cf14..75a9b4ec 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/prealloc.go @@ -7,6 +7,7 @@ import ( "github.com/alexkohler/prealloc/pkg" "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" @@ -14,44 +15,51 @@ import ( const preallocName = "prealloc" -func NewPrealloc() *goanalysis.Linter { +//nolint:dupl +func NewPreAlloc(settings *config.PreallocSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: preallocName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - preallocName, - "Finds slice declarations that could potentially be preallocated", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - s := &lintCtx.Settings().Prealloc - - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var res []goanalysis.Issue - hints := pkg.Check(pass.Files, s.Simple, s.RangeLoops, s.ForLoops) - for _, hint := range hints { - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: pass.Fset.Position(hint.Pos), - Text: fmt.Sprintf("Consider preallocating %s", formatCode(hint.DeclaredSliceName, lintCtx.Cfg)), - FromLinter: preallocName, - }, pass)) - } + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runPreAlloc(pass, settings) - if len(res) == 0 { + if len(issues) == 0 { return nil, nil } mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + preallocName, + "Finds slice declarations that could potentially be pre-allocated", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runPreAlloc(pass *analysis.Pass, settings *config.PreallocSettings) []goanalysis.Issue { + var issues []goanalysis.Issue + + hints := pkg.Check(pass.Files, settings.Simple, settings.RangeLoops, settings.ForLoops) + + 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, + }, pass)) + } + + return issues +} 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.go index 4fba3d27..f77847a4 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/promlinter.go @@ -7,57 +7,71 @@ import ( "github.com/yeya24/promlinter" "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" ) -func NewPromlinter() *goanalysis.Linter { +const promlinterName = "promlinter" + +func NewPromlinter(settings *config.PromlinterSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue - const linterName = "promlinter" - analyzer := &analysis.Analyzer{ - Name: linterName, - Doc: goanalysis.TheOnlyanalyzerDoc, + var promSettings promlinter.Setting + if settings != nil { + promSettings = promlinter.Setting{ + Strict: settings.Strict, + DisabledLintFuncs: settings.DisabledLinters, + } } - return goanalysis.NewLinter( - linterName, - "Check Prometheus metrics naming via promlint", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - strict := lintCtx.Cfg.LintersSettings.Promlinter.Strict - disabledLinters := lintCtx.Cfg.LintersSettings.Promlinter.DisabledLinters - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - issues := promlinter.RunLint(pass.Fset, pass.Files, promlinter.Setting{ - Strict: strict, - DisabledLintFuncs: disabledLinters, - }) + analyzer := &analysis.Analyzer{ + Name: promlinterName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runPromLinter(pass, promSettings) if len(issues) == 0 { return nil, nil } - res := make([]goanalysis.Issue, len(issues)) - for k, i := range issues { - issue := result.Issue{ - Pos: i.Pos, - Text: fmt.Sprintf("Metric: %s Error: %s", i.Metric, i.Text), - FromLinter: linterName, - } - - res[k] = goanalysis.NewIssue(&issue, pass) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + return goanalysis.NewLinter( + promlinterName, + "Check Prometheus metrics naming via promlint", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeSyntax) } + +func runPromLinter(pass *analysis.Pass, promSettings promlinter.Setting) []goanalysis.Issue { + lintIssues := promlinter.RunLint(pass.Fset, pass.Files, promSettings) + + if len(lintIssues) == 0 { + return nil + } + + issues := make([]goanalysis.Issue, len(lintIssues)) + for k, i := range lintIssues { + issue := result.Issue{ + Pos: i.Pos, + Text: fmt.Sprintf("Metric: %s Error: %s", i.Metric, i.Text), + FromLinter: promlinterName, + } + + issues[k] = goanalysis.NewIssue(&issue, pass) + } + + return issues +} 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.go new file mode 100644 index 00000000..a9ff67ee --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/reassign.go @@ -0,0 +1,32 @@ +package golinters + +import ( + "fmt" + "strings" + + "github.com/curioswitch/go-reassign" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" +) + +func NewReassign(settings *config.ReassignSettings) *goanalysis.Linter { + a := reassign.NewAnalyzer() + + var cfg map[string]map[string]interface{} + if settings != nil && len(settings.Patterns) > 0 { + cfg = map[string]map[string]interface{}{ + a.Name: { + reassign.FlagPattern: fmt.Sprintf("^(%s)$", strings.Join(settings.Patterns, "|")), + }, + } + } + + 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/revive.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive.go index 8fd5e980..5c160665 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/revive.go @@ -7,6 +7,7 @@ import ( "go/token" "os" "reflect" + "sync" "github.com/BurntSushi/toml" reviveConfig "github.com/mgechev/revive/config" @@ -33,12 +34,16 @@ type jsonObject struct { } // NewRevive returns a new Revive linter. -func NewRevive(cfg *config.ReviveSettings) *goanalysis.Linter { - var issues []goanalysis.Issue +// +//nolint:dupl +func NewRevive(settings *config.ReviveSettings) *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ Name: goanalysis.TheOnlyAnalyzerName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } return goanalysis.NewLinter( @@ -48,72 +53,86 @@ func NewRevive(cfg *config.ReviveSettings) *goanalysis.Linter { nil, ).WithContextSetter(func(lintCtx *linter.Context) { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var files []string - for _, file := range pass.Files { - files = append(files, pass.Fset.PositionFor(file.Pos(), false).Filename) - } - packages := [][]string{files} - - conf, err := getReviveConfig(cfg) + issues, err := runRevive(lintCtx, pass, settings) if err != nil { return nil, err } - formatter, err := reviveConfig.GetFormatter("json") - if err != nil { - return nil, err + if len(issues) == 0 { + return nil, nil } - revive := lint.New(os.ReadFile, cfg.MaxOpenFiles) + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() - lintingRules, err := reviveConfig.GetLintingRules(conf, []lint.Rule{}) - if err != nil { - return nil, err - } + return nil, nil + } + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} - failures, err := revive.Lint(packages, lintingRules, *conf) - if err != nil { - return nil, err - } +func runRevive(lintCtx *linter.Context, pass *analysis.Pass, settings *config.ReviveSettings) ([]goanalysis.Issue, error) { + packages := [][]string{getFileNames(pass)} - formatChan := make(chan lint.Failure) - exitChan := make(chan bool) + conf, err := getReviveConfig(settings) + if err != nil { + return nil, err + } - var output string - go func() { - output, err = formatter.Format(formatChan, *conf) - if err != nil { - lintCtx.Log.Errorf("Format error: %v", err) - } - exitChan <- true - }() + formatter, err := reviveConfig.GetFormatter("json") + if err != nil { + return nil, err + } - for f := range failures { - if f.Confidence < conf.Confidence { - continue - } + revive := lint.New(os.ReadFile, settings.MaxOpenFiles) - formatChan <- f - } + lintingRules, err := reviveConfig.GetLintingRules(conf, []lint.Rule{}) + if err != nil { + return nil, err + } - close(formatChan) - <-exitChan + failures, err := revive.Lint(packages, lintingRules, *conf) + if err != nil { + return nil, err + } - var results []jsonObject - err = json.Unmarshal([]byte(output), &results) - if err != nil { - return nil, err - } + formatChan := make(chan lint.Failure) + exitChan := make(chan bool) - for i := range results { - issues = append(issues, reviveToIssue(pass, &results[i])) - } + var output string + go func() { + output, err = formatter.Format(formatChan, *conf) + if err != nil { + lintCtx.Log.Errorf("Format error: %v", err) + } + exitChan <- true + }() - return nil, nil + for f := range failures { + if f.Confidence < conf.Confidence { + continue } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return issues - }).WithLoadMode(goanalysis.LoadModeSyntax) + + formatChan <- f + } + + close(formatChan) + <-exitChan + + var results []jsonObject + err = json.Unmarshal([]byte(output), &results) + if err != nil { + return nil, err + } + + var issues []goanalysis.Issue + for i := range results { + issues = append(issues, reviveToIssue(pass, &results[i])) + } + + return issues, nil } func reviveToIssue(pass *analysis.Pass, object *jsonObject) goanalysis.Issue { @@ -302,6 +321,7 @@ var allRules = append([]lint.Rule{ &rule.TimeEqualRule{}, &rule.BannedCharsRule{}, &rule.OptimizeOperandsOrderRule{}, + &rule.DataRaceRule{}, }, defaultRules...) const defaultConfidence = 0.8 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 index d4c89d38..5a66d62e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/rowserrcheck.go @@ -4,20 +4,22 @@ 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" - "github.com/golangci/golangci-lint/pkg/lint/linter" ) -func NewRowsErrCheck() *goanalysis.Linter { - analyzer := rowserr.NewAnalyzer() +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). - WithContextSetter(func(lintCtx *linter.Context) { - pkgs := lintCtx.Settings().RowsErrCheck.Packages - analyzer.Run = rowserr.NewRun(pkgs...) - }) + ).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 index ba3921e1..7054ef33 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/scopelint.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/scopelint.go @@ -15,6 +15,7 @@ import ( const scopelintName = "scopelint" +//nolint:dupl func NewScopelint() *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue @@ -22,43 +23,53 @@ func NewScopelint() *goanalysis.Linter { analyzer := &analysis.Analyzer{ Name: scopelintName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - scopelintName, - "Scopelint checks for unpinned variables in go programs", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var res []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: &res, - } - ast.Walk(&n, file) - } + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runScopeLint(pass) - if len(res) == 0 { + if len(issues) == 0 { return nil, nil } mu.Lock() - for i := range res { - resIssues = append(resIssues, goanalysis.NewIssue(&res[i], pass)) - } + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + }, + } + + 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. @@ -73,6 +84,7 @@ type Node struct { // 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) { @@ -162,6 +174,7 @@ func (f *Node) Visit(node ast.Node) ast.Visitor { // 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 ...interface{}) { pos := f.fset.Position(n.Pos()) 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 index 48ca246e..ff2c0c08 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go @@ -8,14 +8,12 @@ import ( ) func NewSQLCloseCheck() *goanalysis.Linter { - analyzers := []*analysis.Analyzer{ - analyzer.NewAnalyzer(), - } - return goanalysis.NewLinter( "sqlclosecheck", "Checks that sql.Rows and sql.Stmt are closed.", - analyzers, + []*analysis.Analyzer{ + analyzer.NewAnalyzer(), + }, 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.go index 2226eabb..67348463 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck.go @@ -9,12 +9,12 @@ import ( func NewStaticcheck(settings *config.StaticCheckSettings) *goanalysis.Linter { cfg := staticCheckConfig(settings) - analyzers := setupStaticCheckAnalyzers(staticcheck.Analyzers, getGoVersion(settings), cfg.Checks) return goanalysis.NewLinter( "staticcheck", - "Staticcheck is a go vet on steroids, applying a ton of static analysis checks", + "It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary."+ + " The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint.", analyzers, nil, ).WithLoadMode(goanalysis.LoadModeTypesInfo) 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/staticcheck_common.go index dc6360d7..b421d30c 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck_common.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/staticcheck_common.go @@ -24,8 +24,7 @@ func getGoVersion(settings *config.StaticCheckSettings) string { return goVersion } - // TODO: uses "1.13" for backward compatibility, but in the future (v2) must be set by using build.Default.ReleaseTags like staticcheck. - return "1.13" + return "1.17" } func setupStaticCheckAnalyzers(src []*lint.Analyzer, goVersion string, checks []string) []*analysis.Analyzer { @@ -99,7 +98,8 @@ func staticCheckConfig(settings *config.StaticCheckSettings) *scconfig.Config { } // https://github.com/dominikh/go-tools/blob/9bf17c0388a65710524ba04c2d821469e639fdc2/lintcmd/lint.go#L437-L477 -// nolint // Keep the original source code. +// +//nolint:gocritic // Keep the original source code. func filterAnalyzerNames(analyzers []string, checks []string) map[string]bool { allowedChecks := map[string]bool{} 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 index 7c16f8ec..fe49b1be 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/structcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/structcheck.go @@ -1,4 +1,4 @@ -package golinters // nolint:dupl +package golinters import ( "fmt" @@ -7,49 +7,65 @@ import ( 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" ) -func NewStructcheck() *goanalysis.Linter { - const linterName = "structcheck" +const structcheckName = "structcheck" + +//nolint:dupl +func NewStructcheck(settings *config.StructCheckSettings) *goanalysis.Linter { var mu sync.Mutex - var res []goanalysis.Issue + var resIssues []goanalysis.Issue + analyzer := &analysis.Analyzer{ - Name: linterName, + Name: structcheckName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - linterName, - "Finds unused struct fields", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - checkExported := lintCtx.Settings().Structcheck.CheckExportedFields - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - prog := goanalysis.MakeFakeLoaderProgram(pass) + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runStructCheck(pass, settings) - structcheckIssues := structcheckAPI.Run(prog, checkExported) - if len(structcheckIssues) == 0 { + if len(issues) == 0 { return nil, nil } - issues := make([]goanalysis.Issue, 0, len(structcheckIssues)) - for _, i := range structcheckIssues { - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: fmt.Sprintf("%s is unused", formatCode(i.FieldName, lintCtx.Cfg)), - FromLinter: linterName, - }, pass)) - } - mu.Lock() - res = append(res, issues...) + resIssues = append(resIssues, issues...) mu.Unlock() + return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return res + }, + } + + 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/tagliatelle.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle.go index 5f58fc1d..275670e1 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tagliatelle.go @@ -25,6 +25,10 @@ func NewTagliatelle(settings *config.TagliatelleSettings) *goanalysis.Linter { a := tagliatelle.New(cfg) - return goanalysis.NewLinter(a.Name, a.Doc, []*analysis.Analyzer{a}, nil). - WithLoadMode(goanalysis.LoadModeSyntax) + 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/tenv.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv.go index 8e3e9c61..174b0dd6 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tenv.go @@ -11,10 +11,6 @@ import ( func NewTenv(settings *config.TenvSettings) *goanalysis.Linter { a := tenv.Analyzer - analyzers := []*analysis.Analyzer{ - a, - } - var cfg map[string]map[string]interface{} if settings != nil { cfg = map[string]map[string]interface{}{ @@ -27,7 +23,7 @@ func NewTenv(settings *config.TenvSettings) *goanalysis.Linter { return goanalysis.NewLinter( a.Name, a.Doc, - analyzers, + []*analysis.Analyzer{a}, cfg, ).WithLoadMode(goanalysis.LoadModeSyntax) } 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.go index 1248e78f..2cc62759 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/testpackage.go @@ -1,6 +1,8 @@ package golinters import ( + "strings" + "github.com/maratori/testpackage/pkg/testpackage" "golang.org/x/tools/go/analysis" @@ -10,14 +12,17 @@ import ( func NewTestpackage(cfg *config.TestpackageSettings) *goanalysis.Linter { var a = testpackage.NewAnalyzer() + var settings map[string]map[string]interface{} if cfg != nil { settings = map[string]map[string]interface{}{ a.Name: { - testpackage.SkipRegexpFlagName: cfg.SkipRegexp, + testpackage.SkipRegexpFlagName: cfg.SkipRegexp, + testpackage.AllowPackagesFlagName: strings.Join(cfg.AllowPackages, ","), }, } } + return goanalysis.NewLinter(a.Name, a.Doc, []*analysis.Analyzer{a}, settings). WithLoadMode(goanalysis.LoadModeSyntax) } 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 index a4b96eb7..cbe97516 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/tparallel.go @@ -8,14 +8,10 @@ import ( ) func NewTparallel() *goanalysis.Linter { - analyzers := []*analysis.Analyzer{ - tparallel.Analyzer, - } - return goanalysis.NewLinter( "tparallel", "tparallel detects inappropriate usage of t.Parallel() method in your Go test codes", - analyzers, + []*analysis.Analyzer{tparallel.Analyzer}, 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 24f4339f..e9b26ef4 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 @@ -12,17 +12,13 @@ func NewTypecheck() *goanalysis.Linter { analyzer := &analysis.Analyzer{ Name: linterName, Doc: goanalysis.TheOnlyanalyzerDoc, - Run: func(pass *analysis.Pass) (interface{}, error) { - return nil, nil - }, + Run: goanalysis.DummyRun, } - linter := goanalysis.NewLinter( + return goanalysis.NewLinter( linterName, "Like the front-end of a Go compiler, parses and type-checks Go code", []*analysis.Analyzer{analyzer}, nil, ).WithLoadMode(goanalysis.LoadModeTypesInfo) - - return linter } 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.go index 456f6836..def9f156 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unconvert.go @@ -11,43 +11,57 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +const unconvertName = "unconvert" + +//nolint:dupl func NewUnconvert() *goanalysis.Linter { - const linterName = "unconvert" var mu sync.Mutex - var res []goanalysis.Issue + var resIssues []goanalysis.Issue + analyzer := &analysis.Analyzer{ - Name: linterName, + Name: unconvertName, Doc: goanalysis.TheOnlyanalyzerDoc, - } - return goanalysis.NewLinter( - linterName, - "Remove unnecessary type conversions", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - prog := goanalysis.MakeFakeLoaderProgram(pass) + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runUnconvert(pass) - positions := unconvertAPI.Run(prog) - if len(positions) == 0 { + if len(issues) == 0 { return nil, nil } - issues := make([]goanalysis.Issue, 0, len(positions)) - for _, pos := range positions { - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: pos, - Text: "unnecessary conversion", - FromLinter: linterName, - }, pass)) - } - mu.Lock() - res = append(res, issues...) + resIssues = append(resIssues, issues...) mu.Unlock() + return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return res + }, + } + + return goanalysis.NewLinter( + unconvertName, + "Remove unnecessary type conversions", + []*analysis.Analyzer{analyzer}, + nil, + ).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues }).WithLoadMode(goanalysis.LoadModeTypesInfo) } + +func runUnconvert(pass *analysis.Pass) []goanalysis.Issue { + prog := goanalysis.MakeFakeLoaderProgram(pass) + + positions := unconvertAPI.Run(prog) + if len(positions) == 0 { + return nil + } + + issues := make([]goanalysis.Issue, 0, len(positions)) + for _, pos := range positions { + issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Pos: pos, + Text: "unnecessary conversion", + FromLinter: unconvertName, + }, pass)) + } + + return issues +} 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.go index 33dd55c9..7accf295 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unparam.go @@ -8,69 +8,83 @@ import ( "golang.org/x/tools/go/packages" "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/lint/linter" "github.com/golangci/golangci-lint/pkg/result" ) -func NewUnparam() *goanalysis.Linter { - const linterName = "unparam" +const unparamName = "unparam" + +func NewUnparam(settings *config.UnparamSettings) *goanalysis.Linter { var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: linterName, + Name: unparamName, Doc: goanalysis.TheOnlyanalyzerDoc, Requires: []*analysis.Analyzer{buildssa.Analyzer}, - } - return goanalysis.NewLinter( - linterName, - "Reports unused function parameters", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - us := &lintCtx.Settings().Unparam - if us.Algo != "cha" { - lintCtx.Log.Warnf("`linters-settings.unparam.algo` isn't supported by the newest `unparam`") - } - - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - ssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) - ssaPkg := ssa.Pkg - - pkg := &packages.Package{ - Fset: pass.Fset, - Syntax: pass.Files, - Types: pass.Pkg, - TypesInfo: pass.TypesInfo, - } - - c := &check.Checker{} - c.CheckExportedFuncs(us.CheckExported) - c.Packages([]*packages.Package{pkg}) - c.ProgramSSA(ssaPkg.Prog) - - unparamIssues, err := c.Check() + Run: func(pass *analysis.Pass) (interface{}, error) { + issues, err := runUnparam(pass, settings) if err != nil { return nil, err } - var res []goanalysis.Issue - for _, i := range unparamIssues { - res = append(res, goanalysis.NewIssue(&result.Issue{ - Pos: pass.Fset.Position(i.Pos()), - Text: i.Message(), - FromLinter: linterName, - }, pass)) + if len(issues) == 0 { + return nil, nil } mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil + }, + } + + return goanalysis.NewLinter( + unparamName, + "Reports unused function parameters", + []*analysis.Analyzer{analyzer}, + nil, + ).WithContextSetter(func(lintCtx *linter.Context) { + if settings.Algo != "cha" { + lintCtx.Log.Warnf("`linters-settings.unparam.algo` isn't supported by the newest `unparam`") } }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeTypesInfo) } + +func runUnparam(pass *analysis.Pass, settings *config.UnparamSettings) ([]goanalysis.Issue, error) { + ssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) + ssaPkg := ssa.Pkg + + pkg := &packages.Package{ + Fset: pass.Fset, + Syntax: pass.Files, + Types: pass.Pkg, + TypesInfo: pass.TypesInfo, + } + + c := &check.Checker{} + c.CheckExportedFuncs(settings.CheckExported) + c.Packages([]*packages.Package{pkg}) + c.ProgramSSA(ssaPkg.Prog) + + unparamIssues, err := c.Check() + if err != nil { + return nil, err + } + + var issues []goanalysis.Issue + for _, i := range unparamIssues { + issues = append(issues, goanalysis.NewIssue(&result.Issue{ + Pos: pass.Fset.Position(i.Pos()), + Text: i.Message(), + FromLinter: unparamName, + }, pass)) + } + + return issues, nil +} 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.go index 13e05a50..35b43601 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go @@ -13,56 +13,28 @@ import ( "github.com/golangci/golangci-lint/pkg/result" ) +const unusedName = "unused" + type UnusedSettings struct { GoVersion string } func NewUnused(settings *config.StaticCheckSettings) *goanalysis.Linter { - const name = "unused" - var mu sync.Mutex var resIssues []goanalysis.Issue analyzer := &analysis.Analyzer{ - Name: name, + Name: unusedName, Doc: unused.Analyzer.Analyzer.Doc, Requires: unused.Analyzer.Analyzer.Requires, Run: func(pass *analysis.Pass) (interface{}, error) { - res, err := unused.Analyzer.Analyzer.Run(pass) + issues, err := runUnused(pass) if err != nil { return nil, err } - sr := unused.Serialize(pass, res.(unused.Result), pass.Fset) - - used := make(map[string]bool) - for _, obj := range sr.Used { - used[fmt.Sprintf("%s %d %s", obj.Position.Filename, obj.Position.Line, obj.Name)] = true - } - - var issues []goanalysis.Issue - // Inspired by https://github.com/dominikh/go-tools/blob/d694aadcb1f50c2d8ac0a1dd06217ebb9f654764/lintcmd/lint.go#L177-L197 - for _, object := range sr.Unused { - if object.Kind == "type param" { - continue - } - - if object.InGenerated { - continue - } - - key := fmt.Sprintf("%s %d %s", object.Position.Filename, object.Position.Line, object.Name) - if used[key] { - continue - } - - issue := goanalysis.NewIssue(&result.Issue{ - FromLinter: name, - Text: fmt.Sprintf("%s %s is unused", object.Kind, object.Name), - Pos: object.Position, - }, pass) - - issues = append(issues, issue) + if len(issues) == 0 { + return nil, nil } mu.Lock() @@ -75,14 +47,54 @@ func NewUnused(settings *config.StaticCheckSettings) *goanalysis.Linter { setAnalyzerGoVersion(analyzer, getGoVersion(settings)) - lnt := goanalysis.NewLinter( - name, + return goanalysis.NewLinter( + unusedName, "Checks Go code for unused constants, variables, functions and types", []*analysis.Analyzer{analyzer}, nil, ).WithIssuesReporter(func(lintCtx *linter.Context) []goanalysis.Issue { return resIssues }).WithLoadMode(goanalysis.LoadModeTypesInfo) +} + +func runUnused(pass *analysis.Pass) ([]goanalysis.Issue, error) { + res, err := unused.Analyzer.Analyzer.Run(pass) + if err != nil { + return nil, err + } + + sr := unused.Serialize(pass, res.(unused.Result), pass.Fset) + + used := make(map[string]bool) + for _, obj := range sr.Used { + used[fmt.Sprintf("%s %d %s", obj.Position.Filename, obj.Position.Line, obj.Name)] = true + } + + var issues []goanalysis.Issue + + // Inspired by https://github.com/dominikh/go-tools/blob/d694aadcb1f50c2d8ac0a1dd06217ebb9f654764/lintcmd/lint.go#L177-L197 + for _, object := range sr.Unused { + if object.Kind == "type param" { + continue + } + + if object.InGenerated { + continue + } + + key := fmt.Sprintf("%s %d %s", object.Position.Filename, object.Position.Line, object.Name) + if used[key] { + continue + } + + issue := goanalysis.NewIssue(&result.Issue{ + FromLinter: unusedName, + Text: fmt.Sprintf("%s %s is unused", object.Kind, object.Name), + Pos: object.Position, + }, pass) + + issues = append(issues, issue) + } - return lnt + return issues, nil } 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.go new file mode 100644 index 00000000..dbb6d953 --- /dev/null +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/usestdlibvars.go @@ -0,0 +1,33 @@ +package golinters + +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" +) + +func NewUseStdlibVars(cfg *config.UseStdlibVarsSettings) *goanalysis.Linter { + a := analyzer.New() + + cfgMap := make(map[string]map[string]interface{}) + if cfg != nil { + cfgMap[a.Name] = map[string]interface{}{ + analyzer.HTTPMethodFlag: cfg.HTTPMethod, + analyzer.HTTPStatusCodeFlag: cfg.HTTPStatusCode, + analyzer.TimeWeekdayFlag: cfg.TimeWeekday, + analyzer.TimeMonthFlag: cfg.TimeMonth, + analyzer.TimeLayoutFlag: cfg.TimeLayout, + analyzer.CryptoHashFlag: cfg.CryptoHash, + analyzer.DefaultRPCPathFlag: cfg.DefaultRPCPathFlag, + } + } + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + cfgMap, + ).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/util.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/util.go index 1940f30e..1044567a 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/util.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/util.go @@ -2,8 +2,11 @@ package golinters import ( "fmt" + "path/filepath" "strings" + "golang.org/x/tools/go/analysis" + "github.com/golangci/golangci-lint/pkg/config" ) @@ -22,3 +25,17 @@ func formatCodeBlock(code string, _ *config.Config) string { return fmt.Sprintf("```\n%s\n```", code) } + +func getFileNames(pass *analysis.Pass) []string { + var fileNames []string + for _, f := range pass.Files { + fileName := pass.Fset.PositionFor(f.Pos(), true).Filename + ext := filepath.Ext(fileName) + if ext != "" && ext != ".go" { + // position has been adjusted to a non-go file, revert to original file + fileName = pass.Fset.PositionFor(f.Pos(), false).Filename + } + fileNames = append(fileNames, fileName) + } + return fileNames +} 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 index dcf2e7de..c2c5b7aa 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varcheck.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/varcheck.go @@ -1,4 +1,4 @@ -package golinters // nolint:dupl +package golinters import ( "fmt" @@ -7,49 +7,66 @@ import ( 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" ) -func NewVarcheck() *goanalysis.Linter { - const linterName = "varcheck" +const varcheckName = "varcheck" + +func NewVarcheck(settings *config.VarCheckSettings) *goanalysis.Linter { var mu sync.Mutex - var res []goanalysis.Issue + var resIssues []goanalysis.Issue + analyzer := &analysis.Analyzer{ - Name: linterName, + Name: varcheckName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( - linterName, + varcheckName, "Finds unused global variables and constants", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { - checkExported := lintCtx.Settings().Varcheck.CheckExportedFields analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - prog := goanalysis.MakeFakeLoaderProgram(pass) + issues := runVarCheck(pass, settings) - varcheckIssues := varcheckAPI.Run(prog, checkExported) - if len(varcheckIssues) == 0 { + if len(issues) == 0 { return nil, nil } - issues := make([]goanalysis.Issue, 0, len(varcheckIssues)) - for _, i := range varcheckIssues { - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - Pos: i.Pos, - Text: fmt.Sprintf("%s is unused", formatCode(i.VarName, lintCtx.Cfg)), - FromLinter: linterName, - }, pass)) - } - mu.Lock() - res = append(res, issues...) + resIssues = append(resIssues, issues...) mu.Unlock() + return nil, nil } }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return res + 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/wastedassign.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign.go index d359fb01..92798d4f 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wastedassign.go @@ -8,14 +8,10 @@ import ( ) func NewWastedAssign() *goanalysis.Linter { - analyzers := []*analysis.Analyzer{ - wastedassign.Analyzer, - } - return goanalysis.NewLinter( "wastedassign", "wastedassign finds wasted assignment statements.", - analyzers, + []*analysis.Analyzer{wastedassign.Analyzer}, 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 index d475465a..1b32a7ad 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/whitespace.go @@ -8,73 +8,51 @@ import ( "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" ) -func NewWhitespace() *goanalysis.Linter { - const linterName = "whitespace" +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: linterName, + Name: whitespaceName, Doc: goanalysis.TheOnlyanalyzerDoc, + Run: goanalysis.DummyRun, } + return goanalysis.NewLinter( - linterName, + whitespaceName, "Tool for detection of leading and trailing whitespace", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { - cfg := lintCtx.Cfg.LintersSettings.Whitespace - settings := whitespace.Settings{MultiIf: cfg.MultiIf, MultiFunc: cfg.MultiFunc} - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var issues []whitespace.Message - for _, file := range pass.Files { - issues = append(issues, whitespace.Run(file, pass.Fset, settings)...) + issues, err := runWhitespace(lintCtx, pass, wsSettings) + if err != nil { + return nil, err } if len(issues) == 0 { return nil, nil } - res := make([]goanalysis.Issue, len(issues)) - for k, i := range issues { - 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: linterName, - Replacement: &result.Replacement{}, - } - - bracketLine, err := lintCtx.LineCache.GetLine(issue.Pos.Filename, issue.Pos.Line) - if err != nil { - return nil, errors.Wrapf(err, "failed to get line %s:%d", issue.Pos.Filename, issue.Pos.Line) - } - - 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} - - res[k] = goanalysis.NewIssue(&issue, pass) - } - mu.Lock() - resIssues = append(resIssues, res...) + resIssues = append(resIssues, issues...) mu.Unlock() return nil, nil @@ -83,3 +61,48 @@ func NewWhitespace() *goanalysis.Linter { 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, errors.Wrapf(err, "failed to get line %s:%d", issue.Pos.Filename, issue.Pos.Line) + } + + 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/wsl.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go index b5961cc1..9d7060b0 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go @@ -6,78 +6,85 @@ import ( "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 ( - name = "wsl" -) +const wslName = "wsl" // NewWSL returns a new WSL linter. -func NewWSL() *goanalysis.Linter { - var ( - issues []goanalysis.Issue - mu = sync.Mutex{} - analyzer = &analysis.Analyzer{ - Name: goanalysis.TheOnlyAnalyzerName, - Doc: goanalysis.TheOnlyanalyzerDoc, - } - ) +func NewWSL(settings *config.WSLSettings) *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue - return goanalysis.NewLinter( - name, - "Whitespace Linter - Forces you to use empty lines!", - []*analysis.Analyzer{analyzer}, - nil, - ).WithContextSetter(func(lintCtx *linter.Context) { - analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var ( - files = make([]string, 0, len(pass.Files)) - linterCfg = lintCtx.Cfg.LintersSettings.WSL - processorCfg = wsl.Configuration{ - StrictAppend: linterCfg.StrictAppend, - AllowAssignAndCallCuddle: linterCfg.AllowAssignAndCallCuddle, - AllowAssignAndAnythingCuddle: linterCfg.AllowAssignAndAnythingCuddle, - AllowMultiLineAssignCuddle: linterCfg.AllowMultiLineAssignCuddle, - AllowCuddleDeclaration: linterCfg.AllowCuddleDeclaration, - AllowTrailingComment: linterCfg.AllowTrailingComment, - AllowSeparatedLeadingComment: linterCfg.AllowSeparatedLeadingComment, - ForceCuddleErrCheckAndAssign: linterCfg.ForceCuddleErrCheckAndAssign, - ForceCaseTrailingWhitespaceLimit: linterCfg.ForceCaseTrailingWhitespaceLimit, - ForceExclusiveShortDeclarations: linterCfg.ForceExclusiveShortDeclarations, - AllowCuddleWithCalls: []string{"Lock", "RLock"}, - AllowCuddleWithRHS: []string{"Unlock", "RUnlock"}, - ErrorVariableNames: []string{"err"}, - } - ) - - for _, file := range pass.Files { - files = append(files, pass.Fset.PositionFor(file.Pos(), false).Filename) - } + conf := &wsl.Configuration{ + AllowCuddleWithCalls: []string{"Lock", "RLock"}, + AllowCuddleWithRHS: []string{"Unlock", "RUnlock"}, + ErrorVariableNames: []string{"err"}, + } + + if settings != nil { + conf.StrictAppend = settings.StrictAppend + conf.AllowAssignAndCallCuddle = settings.AllowAssignAndCallCuddle + conf.AllowAssignAndAnythingCuddle = settings.AllowAssignAndAnythingCuddle + conf.AllowMultiLineAssignCuddle = settings.AllowMultiLineAssignCuddle + conf.AllowCuddleDeclaration = settings.AllowCuddleDeclaration + conf.AllowTrailingComment = settings.AllowTrailingComment + conf.AllowSeparatedLeadingComment = settings.AllowSeparatedLeadingComment + conf.ForceCuddleErrCheckAndAssign = settings.ForceCuddleErrCheckAndAssign + conf.ForceCaseTrailingWhitespaceLimit = settings.ForceCaseTrailingWhitespaceLimit + conf.ForceExclusiveShortDeclarations = settings.ForceExclusiveShortDeclarations + } - wslErrors, _ := wsl.NewProcessorWithConfig(processorCfg). - ProcessFiles(files) + analyzer := &analysis.Analyzer{ + Name: goanalysis.TheOnlyAnalyzerName, + Doc: goanalysis.TheOnlyanalyzerDoc, + Run: func(pass *analysis.Pass) (interface{}, error) { + issues := runWSL(pass, conf) - if len(wslErrors) == 0 { + if len(issues) == 0 { return nil, nil } mu.Lock() - defer mu.Unlock() - - for _, err := range wslErrors { - issues = append(issues, goanalysis.NewIssue(&result.Issue{ - FromLinter: name, - Pos: err.Position, - Text: err.Reason, - }, pass)) - } + resIssues = append(resIssues, issues...) + mu.Unlock() return nil, nil - } - }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { - return issues + }, + } + + 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/lint/linter/config.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go index c8e06554..167ac462 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 @@ -66,7 +66,7 @@ func (lc *Config) WithLoadFiles() *Config { func (lc *Config) WithLoadForGoAnalysis() *Config { lc = lc.WithLoadFiles() - lc.LoadMode |= packages.NeedImports | packages.NeedDeps | packages.NeedExportsFile | packages.NeedTypesSizes + lc.LoadMode |= packages.NeedImports | packages.NeedDeps | packages.NeedExportFile | packages.NeedTypesSizes lc.IsSlow = true return lc } 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 01e21969..7d3b2260 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 @@ -21,8 +21,8 @@ type Noop struct { } func (n Noop) Run(_ context.Context, lintCtx *Context) ([]result.Issue, error) { - lintCtx.Log.Warnf("%s is disabled because of go1.18."+ - " You can track the evolution of the go1.18 support by following the https://github.com/golangci/golangci-lint/issues/2649.", n.name) + 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) return nil, nil } 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 9f72e637..b17ce3be 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 @@ -100,76 +100,172 @@ func enableLinterConfigs(lcs []*linter.Config, isEnabled func(lc *linter.Config) //nolint:funlen func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { - var bidichkCfg *config.BiDiChkSettings - var cyclopCfg *config.Cyclop - var decorderCfg *config.DecorderSettings - var errchkjsonCfg *config.ErrChkJSONSettings - var errorlintCfg *config.ErrorLintSettings - var exhaustiveCfg *config.ExhaustiveSettings - var exhaustiveStructCfg *config.ExhaustiveStructSettings - var exhaustructCfg *config.ExhaustructSettings - var gciCfg *config.GciSettings - var goModDirectivesCfg *config.GoModDirectivesSettings - var goMndCfg *config.GoMndSettings - var gosecCfg *config.GoSecSettings - var gosimpleCfg *config.StaticCheckSettings - var govetCfg *config.GovetSettings - var grouperCfg *config.GrouperSettings - var ifshortCfg *config.IfshortSettings - var importAsCfg *config.ImportAsSettings - var ireturnCfg *config.IreturnSettings - var maintIdxCfg *config.MaintIdxSettings - var nilNilCfg *config.NilNilSettings - var nlreturnCfg *config.NlreturnSettings - var predeclaredCfg *config.PredeclaredSettings - var reviveCfg *config.ReviveSettings - var staticcheckCfg *config.StaticCheckSettings - var stylecheckCfg *config.StaticCheckSettings - var tagliatelleCfg *config.TagliatelleSettings - var tenvCfg *config.TenvSettings - var testpackageCfg *config.TestpackageSettings - var thelperCfg *config.ThelperSettings - var unusedCfg *config.StaticCheckSettings - var varnamelenCfg *config.VarnamelenSettings - var wrapcheckCfg *config.WrapcheckSettings + var ( + asasalintCfg *config.AsasalintSettings + bidichkCfg *config.BiDiChkSettings + cyclopCfg *config.Cyclop + decorderCfg *config.DecorderSettings + depGuardCfg *config.DepGuardSettings + dogsledCfg *config.DogsledSettings + duplCfg *config.DuplSettings + 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 + 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 + govetCfg *config.GovetSettings + grouperCfg *config.GrouperSettings + ifshortCfg *config.IfshortSettings + importAsCfg *config.ImportAsSettings + interfaceBloatCfg *config.InterfaceBloatSettings + ireturnCfg *config.IreturnSettings + lllCfg *config.LllSettings + maintIdxCfg *config.MaintIdxSettings + makezeroCfg *config.MakezeroSettings + malignedCfg *config.MalignedSettings + misspellCfg *config.MisspellSettings + 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 + staticcheckCfg *config.StaticCheckSettings + structcheckCfg *config.StructCheckSettings + stylecheckCfg *config.StaticCheckSettings + tagliatelleCfg *config.TagliatelleSettings + tenvCfg *config.TenvSettings + testpackageCfg *config.TestpackageSettings + thelperCfg *config.ThelperSettings + unparamCfg *config.UnparamSettings + unusedCfg *config.StaticCheckSettings + 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 - errchkjsonCfg = &m.cfg.LintersSettings.ErrChkJSON decorderCfg = &m.cfg.LintersSettings.Decorder + depGuardCfg = &m.cfg.LintersSettings.Depguard + dogsledCfg = &m.cfg.LintersSettings.Dogsled + duplCfg = &m.cfg.LintersSettings.Dupl + 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 - goModDirectivesCfg = &m.cfg.LintersSettings.GoModDirectives + 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 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 maintIdxCfg = &m.cfg.LintersSettings.MaintIdx + makezeroCfg = &m.cfg.LintersSettings.Makezero + malignedCfg = &m.cfg.LintersSettings.Maligned + misspellCfg = &m.cfg.LintersSettings.Misspell + 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 staticcheckCfg = &m.cfg.LintersSettings.Staticcheck + structcheckCfg = &m.cfg.LintersSettings.Structcheck stylecheckCfg = &m.cfg.LintersSettings.Stylecheck tagliatelleCfg = &m.cfg.LintersSettings.Tagliatelle tenvCfg = &m.cfg.LintersSettings.Tenv testpackageCfg = &m.cfg.LintersSettings.Testpackage thelperCfg = &m.cfg.LintersSettings.Thelper + unparamCfg = &m.cfg.LintersSettings.Unparam unusedCfg = &m.cfg.LintersSettings.Unused + 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 } + + if gofumptCfg != nil && gofumptCfg.LangVersion == "" { + gofumptCfg.LangVersion = m.cfg.Run.Go + } + + if staticcheckCfg != nil && staticcheckCfg.GoVersion == "" { + staticcheckCfg.GoVersion = m.cfg.Run.Go + } + if gosimpleCfg != nil && gosimpleCfg.GoVersion == "" { + gosimpleCfg.GoVersion = m.cfg.Run.Go + } + if stylecheckCfg != nil && stylecheckCfg.GoVersion != "" { + stylecheckCfg.GoVersion = m.cfg.Run.Go + } + if unusedCfg != nil && unusedCfg.GoVersion == "" { + unusedCfg.GoVersion = m.cfg.Run.Go + } } const megacheckName = "megacheck" @@ -177,6 +273,12 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { // 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. lcs := []*linter.Config{ + 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). @@ -191,8 +293,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithSince("v1.18.0"). WithLoadForGoAnalysis(). WithPresets(linter.PresetPerformance, linter.PresetBugs). - WithURL("https://github.com/timakin/bodyclose"). - WithNoopFallback(m.cfg), + WithURL("https://github.com/timakin/bodyclose"), linter.NewConfig(golinters.NewContainedCtx()). WithSince("1.44.0"). @@ -203,8 +304,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithSince("v1.43.0"). WithPresets(linter.PresetBugs). WithLoadForGoAnalysis(). - WithURL("https://github.com/sylvia7788/contextcheck"). - WithNoopFallback(m.cfg), + WithURL("https://github.com/sylvia7788/contextcheck"), linter.NewConfig(golinters.NewCyclop(cyclopCfg)). WithSince("v1.37.0"). @@ -221,19 +321,20 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithSince("v1.0.0"). WithLoadForGoAnalysis(). WithPresets(linter.PresetUnused). - WithURL("https://github.com/remyoudompheng/go-misc/tree/master/deadcode"), + 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()). + 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()). + linter.NewConfig(golinters.NewDogsled(dogsledCfg)). WithSince("v1.19.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/alexkohler/dogsled"), - linter.NewConfig(golinters.NewDupl()). + linter.NewConfig(golinters.NewDupl(duplCfg)). WithSince("v1.0.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/mibk/dupl"), @@ -244,7 +345,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithLoadForGoAnalysis(). WithURL("https://github.com/charithe/durationcheck"), - linter.NewConfig(golinters.NewErrcheck()). + linter.NewConfig(golinters.NewErrcheck(errcheckCfg)). WithSince("v1.0.0"). WithLoadForGoAnalysis(). WithPresets(linter.PresetBugs, linter.PresetError). @@ -299,7 +400,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithLoadForGoAnalysis(). WithURL("https://github.com/kyoh86/exportloopref"), - linter.NewConfig(golinters.NewForbidigo()). + linter.NewConfig(golinters.NewForbidigo(forbidigoCfg)). WithSince("v1.34.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/ashanbrown/forbidigo"), @@ -309,7 +410,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetStyle). WithURL("https://github.com/gostaticanalysis/forcetypeassert"), - linter.NewConfig(golinters.NewFunlen()). + linter.NewConfig(golinters.NewFunlen(funlenCfg)). WithSince("v1.18.0"). WithPresets(linter.PresetComplexity). WithURL("https://github.com/ultraware/funlen"), @@ -329,34 +430,34 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetStyle). WithURL("https://github.com/leighmcculloch/gochecknoinits"), - linter.NewConfig(golinters.NewGocognit()). + linter.NewConfig(golinters.NewGocognit(gocognitCfg)). WithSince("v1.20.0"). WithPresets(linter.PresetComplexity). WithURL("https://github.com/uudashr/gocognit"), - linter.NewConfig(golinters.NewGoconst()). + linter.NewConfig(golinters.NewGoconst(goconstCfg)). WithSince("v1.0.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/jgautheron/goconst"), - linter.NewConfig(golinters.NewGocritic()). + 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()). + linter.NewConfig(golinters.NewGocyclo(gocycloCfg)). WithSince("v1.0.0"). WithPresets(linter.PresetComplexity). WithURL("https://github.com/fzipp/gocyclo"), - linter.NewConfig(golinters.NewGodot()). + 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()). + linter.NewConfig(golinters.NewGodox(godoxCfg)). WithSince("v1.19.0"). WithPresets(linter.PresetStyle, linter.PresetComment). WithURL("https://github.com/matoous/godox"), @@ -367,30 +468,30 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithLoadForGoAnalysis(). WithURL("https://github.com/Djarvur/go-err113"), - linter.NewConfig(golinters.NewGofmt()). + linter.NewConfig(golinters.NewGofmt(gofmtCfg)). WithSince("v1.0.0"). WithPresets(linter.PresetFormatting). WithAutoFix(). WithURL("https://golang.org/cmd/gofmt/"), - linter.NewConfig(golinters.NewGofumpt()). + linter.NewConfig(golinters.NewGofumpt(gofumptCfg)). WithSince("v1.28.0"). WithPresets(linter.PresetFormatting). WithAutoFix(). WithURL("https://github.com/mvdan/gofumpt"), - linter.NewConfig(golinters.NewGoHeader()). + linter.NewConfig(golinters.NewGoHeader(goheaderCfg)). WithSince("v1.28.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/denis-tingaikin/go-header"), - linter.NewConfig(golinters.NewGoimports()). + linter.NewConfig(golinters.NewGoimports(goimportsCfg)). WithSince("v1.20.0"). WithPresets(linter.PresetFormatting, linter.PresetImport). WithAutoFix(). WithURL("https://godoc.org/golang.org/x/tools/cmd/goimports"), - linter.NewConfig(golinters.NewGolint()). + linter.NewConfig(golinters.NewGolint(golintCfg)). WithSince("v1.0.0"). WithLoadForGoAnalysis(). WithPresets(linter.PresetStyle). @@ -407,7 +508,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetStyle, linter.PresetModule). WithURL("https://github.com/ldez/gomoddirectives"), - linter.NewConfig(golinters.NewGomodguard()). + linter.NewConfig(golinters.NewGomodguard(gomodguardCfg)). WithSince("v1.25.0"). WithPresets(linter.PresetStyle, linter.PresetImport, linter.PresetModule). WithURL("https://github.com/ryancurrah/gomodguard"), @@ -446,7 +547,8 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { linter.NewConfig(golinters.NewIfshort(ifshortCfg)). WithSince("v1.36.0"). WithPresets(linter.PresetStyle). - WithURL("https://github.com/esimonov/ifshort"), + 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"). @@ -459,13 +561,17 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { 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", ""). - WithNoopFallback(m.cfg), + Deprecated("The repository of the linter has been archived by the owner.", "v1.38.0", ""), linter.NewConfig(golinters.NewIreturn(ireturnCfg)). WithSince("v1.43.0"). @@ -473,40 +579,46 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithLoadForGoAnalysis(). WithURL("https://github.com/butuzov/ireturn"), - linter.NewConfig(golinters.NewLLL()). + linter.NewConfig(golinters.NewLLL(lllCfg)). WithSince("v1.8.0"). WithPresets(linter.PresetStyle), + linter.NewConfig(golinters.NewLogrLint()). + WithSince("v1.49.0"). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/timonwong/logrlint"), + linter.NewConfig(golinters.NewMaintIdx(maintIdxCfg)). WithSince("v1.44.0"). WithPresets(linter.PresetComplexity). WithURL("https://github.com/yagipy/maintidx"), - linter.NewConfig(golinters.NewMakezero()). + 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()). + 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.NewMisspell()). + linter.NewConfig(golinters.NewMisspell(misspellCfg)). WithSince("v1.8.0"). WithPresets(linter.PresetStyle, linter.PresetComment). WithAutoFix(). WithURL("https://github.com/client9/misspell"), - linter.NewConfig(golinters.NewNakedret()). + linter.NewConfig(golinters.NewNakedret(nakedretCfg)). WithSince("v1.19.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/alexkohler/nakedret"), - linter.NewConfig(golinters.NewNestif()). + linter.NewConfig(golinters.NewNestif(nestifCfg)). WithSince("v1.25.0"). WithPresets(linter.PresetComplexity). WithURL("https://github.com/nakabonne/nestif"), @@ -515,8 +627,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithSince("v1.38.0"). WithLoadForGoAnalysis(). WithPresets(linter.PresetBugs). - WithURL("https://github.com/gostaticanalysis/nilerr"). - WithNoopFallback(m.cfg), + WithURL("https://github.com/gostaticanalysis/nilerr"), linter.NewConfig(golinters.NewNilNil(nilNilCfg)). WithSince("v1.43.0"). @@ -533,25 +644,32 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithSince("v1.28.0"). WithLoadForGoAnalysis(). WithPresets(linter.PresetPerformance, linter.PresetBugs). - WithURL("https://github.com/sonatard/noctx"). - WithNoopFallback(m.cfg), + WithURL("https://github.com/sonatard/noctx"), - linter.NewConfig(golinters.NewNoNamedReturns()). + 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()). + linter.NewConfig(golinters.NewParallelTest(parallelTestCfg)). WithSince("v1.33.0"). + WithLoadForGoAnalysis(). WithPresets(linter.PresetStyle, linter.PresetTest). WithURL("https://github.com/kunwardeep/paralleltest"), - linter.NewConfig(golinters.NewPrealloc()). + linter.NewConfig(golinters.NewPreAlloc(preallocCfg)). WithSince("v1.19.0"). WithPresets(linter.PresetPerformance). WithURL("https://github.com/alexkohler/prealloc"), @@ -561,18 +679,23 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetStyle). WithURL("https://github.com/nishanths/predeclared"), - linter.NewConfig(golinters.NewPromlinter()). + linter.NewConfig(golinters.NewPromlinter(promlinterCfg)). WithSince("v1.40.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/yeya24/promlinter"), + linter.NewConfig(golinters.NewReassign(reassignCfg)). + WithSince("1.49.0"). + WithPresets(linter.PresetBugs). + 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()). + linter.NewConfig(golinters.NewRowsErrCheck(rowserrcheckCfg)). WithSince("v1.23.0"). WithLoadForGoAnalysis(). WithPresets(linter.PresetBugs, linter.PresetSQL). @@ -599,11 +722,12 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithAlternativeNames(megacheckName). WithURL("https://staticcheck.io/"), - linter.NewConfig(golinters.NewStructcheck()). + 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"). WithNoopFallback(m.cfg), linter.NewConfig(golinters.NewStylecheck(stylecheckCfg)). @@ -638,8 +762,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithSince("v1.32.0"). WithPresets(linter.PresetStyle, linter.PresetTest). WithLoadForGoAnalysis(). - WithURL("https://github.com/moricho/tparallel"). - WithNoopFallback(m.cfg), + WithURL("https://github.com/moricho/tparallel"), linter.NewConfig(golinters.NewTypecheck()). WithSince("v1.3.0"). @@ -653,12 +776,11 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetStyle). WithURL("https://github.com/mdempsky/unconvert"), - linter.NewConfig(golinters.NewUnparam()). + linter.NewConfig(golinters.NewUnparam(unparamCfg)). WithSince("v1.9.0"). WithPresets(linter.PresetUnused). WithLoadForGoAnalysis(). - WithURL("https://github.com/mvdan/unparam"). - WithNoopFallback(m.cfg), + WithURL("https://github.com/mvdan/unparam"), linter.NewConfig(golinters.NewUnused(unusedCfg)). WithSince("v1.20.0"). @@ -669,11 +791,17 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithChangeTypes(). WithURL("https://github.com/dominikh/go-tools/tree/master/unused"), - linter.NewConfig(golinters.NewVarcheck()). + 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"), + 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"). @@ -688,7 +816,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithURL("https://github.com/sanposhiho/wastedassign"). WithNoopFallback(m.cfg), - linter.NewConfig(golinters.NewWhitespace()). + linter.NewConfig(golinters.NewWhitespace(whitespaceCfg)). WithSince("v1.19.0"). WithPresets(linter.PresetStyle). WithAutoFix(). @@ -700,13 +828,13 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithLoadForGoAnalysis(). WithURL("https://github.com/tomarrell/wrapcheck"), - linter.NewConfig(golinters.NewWSL()). + linter.NewConfig(golinters.NewWSL(wslCfg)). WithSince("v1.20.0"). WithPresets(linter.PresetStyle). WithURL("https://github.com/bombsimon/wsl"), // nolintlint must be last because it looks at the results of all the previous linters for unused nolint directives - linter.NewConfig(golinters.NewNoLintLint()). + 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"), @@ -714,14 +842,11 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { enabledByDefault := map[string]bool{ golinters.NewGovet(nil).Name(): true, - golinters.NewErrcheck().Name(): true, + golinters.NewErrcheck(errcheckCfg).Name(): true, golinters.NewStaticcheck(staticcheckCfg).Name(): true, golinters.NewUnused(unusedCfg).Name(): true, golinters.NewGosimple(gosimpleCfg).Name(): true, - golinters.NewStructcheck().Name(): true, - golinters.NewVarcheck().Name(): true, golinters.NewIneffassign().Name(): true, - golinters.NewDeadcode().Name(): true, golinters.NewTypecheck().Name(): true, } return enableLinterConfigs(lcs, func(lc *linter.Config) bool { 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 2f003518..52a70d85 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 @@ -1,6 +1,7 @@ package lintersdb import ( + "errors" "fmt" "strings" @@ -47,7 +48,7 @@ func (v Validator) validatePresets(cfg *config.Linters) error { } if len(cfg.Presets) != 0 && cfg.EnableAll { - return fmt.Errorf("--presets is incompatible with --enable-all") + return errors.New("--presets is incompatible with --enable-all") } return nil @@ -55,12 +56,12 @@ func (v Validator) validatePresets(cfg *config.Linters) error { func (v Validator) validateAllDisableEnableOptions(cfg *config.Linters) error { if cfg.EnableAll && cfg.DisableAll { - return fmt.Errorf("--enable-all and --disable-all options must not be combined") + return errors.New("--enable-all and --disable-all options must not be combined") } if cfg.DisableAll { if len(cfg.Enable) == 0 && len(cfg.Presets) == 0 { - return fmt.Errorf("all linters were disabled, but no one linter was enabled: must enable at least one") + return errors.New("all linters were disabled, but no one linter was enabled: must enable at least one") } if len(cfg.Disable) != 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/load.go index a393a1d0..8935134e 100644 --- a/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go +++ b/tools/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go @@ -126,7 +126,7 @@ func stringifyLoadMode(mode packages.LoadMode) string { m := map[packages.LoadMode]string{ packages.NeedCompiledGoFiles: "compiled_files", packages.NeedDeps: "deps", - packages.NeedExportsFile: "exports_file", + packages.NeedExportFile: "exports_file", packages.NeedFiles: "files", packages.NeedImports: "imports", packages.NeedName: "name", @@ -192,7 +192,7 @@ func (cl *ContextLoader) loadPackages(ctx context.Context, loadMode packages.Loa Context: ctx, BuildFlags: buildFlags, Logf: cl.debugf, - //TODO: use fset, parsefile, overlay + // TODO: use fset, parsefile, overlay } args := cl.buildArgs() 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 57388f64..a11b68f7 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,7 +1,6 @@ package processors import ( - "fmt" "go/parser" "go/token" "path/filepath" @@ -103,7 +102,7 @@ func (p *AutogeneratedExclude) getOrCreateFileSummary(i *result.Issue) (*ageFile p.fileSummaryCache[i.FilePath()] = fs if i.FilePath() == "" { - return nil, fmt.Errorf("no file path for issue") + return nil, errors.New("no file path for issue") } doc, err := getDoc(i.FilePath()) 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 b6ce4f21..6958b9f2 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 @@ -58,7 +58,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 { //nolint:interfacer 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/nolint.go b/tools/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go index 12ae0fc2..96104eab 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,7 @@ package processors import ( - "fmt" + "errors" "go/ast" "go/parser" "go/token" @@ -33,7 +33,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 != golinters.NoLintLintName for _, linterName := range i.linters { if linterName == issue.FromLinter { @@ -48,7 +48,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 == golinters.NoLintLintName && issue.ExpectNoLint { if issue.ExpectedNoLintLinter != "" { return i.matchedIssueFromLinter[issue.ExpectedNoLintLinter] } @@ -105,7 +105,7 @@ func (p *Nolint) getOrCreateFileData(i *result.Issue) (*fileData, error) { p.cache[i.FilePath()] = fd if i.FilePath() == "" { - return nil, fmt.Errorf("no file path for issue") + return nil, errors.New("no file path for issue") } // TODO: migrate this parsing to go/analysis facts @@ -148,7 +148,7 @@ func (p *Nolint) buildIgnoredRangesForFile(f *ast.File, fset *token.FileSet, fil func (p *Nolint) shouldPassIssue(i *result.Issue) (bool, error) { nolintDebugf("got issue: %v", *i) - if i.FromLinter == golinters.NolintlintName && i.ExpectNoLint && i.ExpectedNoLintLinter != "" { + 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 { @@ -252,7 +252,7 @@ func (p *Nolint) extractInlineRangeFromComment(text string, g ast.Node, fset *to } } - if !strings.HasPrefix(text, "nolint:") { + if strings.HasPrefix(text, "nolint:all") || !strings.HasPrefix(text, "nolint:") { return buildRange(nil) // ignore all linters } @@ -260,8 +260,12 @@ func (p *Nolint) extractInlineRangeFromComment(text string, g ast.Node, fset *to var linters []string text = strings.Split(text, "//")[0] // allow another comment after this comment linterItems := strings.Split(strings.TrimPrefix(text, "nolint:"), ",") - for _, linter := range linterItems { - linterName := strings.ToLower(strings.TrimSpace(linter)) + for _, item := range linterItems { + linterName := strings.ToLower(strings.TrimSpace(item)) + if linterName == "all" { + p.unknownLintersSet = map[string]bool{} + return buildRange(nil) + } lcs := p.dbManager.GetLinterConfigs(linterName) if lcs == nil { @@ -302,7 +306,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 != golinters.NoLintLintName && issues[j].FromLinter == golinters.NoLintLintName } func (issues sortWithNolintlintLast) Swap(i, j int) { 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 484f7f1f..6b66bea8 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 @@ -31,8 +31,8 @@ func (p PathShortener) Name() string { func (p PathShortener) Process(issues []result.Issue) ([]result.Issue, error) { return transformIssues(issues, func(i *result.Issue) *result.Issue { newI := i - newI.Text = strings.Replace(newI.Text, p.wd+"/", "", -1) - newI.Text = strings.Replace(newI.Text, p.wd, "", -1) + newI.Text = strings.ReplaceAll(newI.Text, p.wd+"/", "") + newI.Text = strings.ReplaceAll(newI.Text, p.wd, "") return newI }), nil } diff --git a/tools/vendor/github.com/golangci/revgrep/.golangci.yml b/tools/vendor/github.com/golangci/revgrep/.golangci.yml new file mode 100644 index 00000000..b8ed6204 --- /dev/null +++ b/tools/vendor/github.com/golangci/revgrep/.golangci.yml @@ -0,0 +1,73 @@ +run: + timeout: 2m + +linters-settings: + govet: + check-shadowing: true + enable-all: true + disable: + - fieldalignment + gocyclo: + min-complexity: 30 # 30 by default (but we recommend 10-20) + goconst: + min-len: 3 + min-occurrences: 3 + misspell: + locale: US + funlen: + lines: -1 + statements: 80 # default 40 + gocognit: + min-complexity: 65 # default 30 + gofumpt: + extra-rules: true + godox: + keywords: + - FIXME + +linters: + enable-all: true + disable: + - maligned # Deprecated + - scopelint # Deprecated + - golint # Deprecated + - interfacer # Deprecated + - exhaustivestruct # Deprecated + - cyclop # duplicate of gocyclo + - dupl + - lll + - nestif + - gomnd + - goerr113 +# - wrapcheck + - nlreturn + - wsl + - exhaustive + - exhaustruct + - tparallel + - testpackage + - paralleltest + - ifshort + - forcetypeassert + - varnamelen + - prealloc # false-positives + - nosnakecase + - nonamedreturns + - nilerr + +issues: + exclude-use-default: false + max-per-linter: 0 + max-same-issues: 0 + exclude: + - 'ST1000: at least one file in a package should have a package comment' + exclude-rules: + - path: (.+)_test.go + linters: + - funlen + - goconst + - gosec + - maintidx + - path: cmd/revgrep/main.go + linters: + - forbidigo diff --git a/tools/vendor/github.com/golangci/revgrep/.travis.yml b/tools/vendor/github.com/golangci/revgrep/.travis.yml deleted file mode 100644 index d16d8b5b..00000000 --- a/tools/vendor/github.com/golangci/revgrep/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go -before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover -script: - - $HOME/gopath/bin/goveralls -service=travis-ci - diff --git a/tools/vendor/github.com/golangci/revgrep/Makefile b/tools/vendor/github.com/golangci/revgrep/Makefile new file mode 100644 index 00000000..5ac8725d --- /dev/null +++ b/tools/vendor/github.com/golangci/revgrep/Makefile @@ -0,0 +1,12 @@ +.PHONY: clean lint lint-fix test + +default: lint test + +test: + go test -v -cover ./... + +lint: + golangci-lint run + +lint-fix: + golangci-lint run --fix diff --git a/tools/vendor/github.com/golangci/revgrep/README.md b/tools/vendor/github.com/golangci/revgrep/README.md index 31faefee..97f25ffb 100644 --- a/tools/vendor/github.com/golangci/revgrep/README.md +++ b/tools/vendor/github.com/golangci/revgrep/README.md @@ -1,14 +1,11 @@ # Overview -[![Build Status](https://travis-ci.org/bradleyfalzon/revgrep.svg?branch=master)](https://travis-ci.org/bradleyfalzon/revgrep) [![Coverage -Status](https://coveralls.io/repos/github/bradleyfalzon/revgrep/badge.svg?branch=master)](https://coveralls.io/github/bradleyfalzon/revgrep?branch=master) [![GoDoc](https://godoc.org/github.com/bradleyfalzon/revgrep?status.svg)](https://godoc.org/github.com/bradleyfalzon/revgrep) - `revgrep` is a CLI tool used to filter static analysis tools to only lines changed based on a commit reference. # Install ```bash -go get -u github.com/bradleyfalzon/revgrep/... +go get -u github.com/golangci/revgrep/... ``` # Usage diff --git a/tools/vendor/github.com/golangci/revgrep/revgrep.go b/tools/vendor/github.com/golangci/revgrep/revgrep.go index f15d601a..4b990fa0 100644 --- a/tools/vendor/github.com/golangci/revgrep/revgrep.go +++ b/tools/vendor/github.com/golangci/revgrep/revgrep.go @@ -67,23 +67,7 @@ type Issue struct { Message string } -func (c *Checker) preparePatch() error { - // Check if patch is supplied, if not, retrieve from VCS - if c.Patch == nil { - var err error - c.Patch, c.NewFiles, err = GitPatch(c.RevisionFrom, c.RevisionTo) - if err != nil { - return fmt.Errorf("could not read git repo: %s", err) - } - if c.Patch == nil { - return errors.New("no version control repository found") - } - } - - return nil -} - -// InputIssue represents issue found by some linter +// InputIssue represents issue found by some linter. type InputIssue interface { FilePath() string Line() int @@ -94,6 +78,11 @@ type simpleInputIssue struct { lineNumber int } +type pos struct { + lineNo int // line number + hunkPos int // position relative to first @@ in file +} + func (i simpleInputIssue) FilePath() string { return i.filePath } @@ -102,16 +91,16 @@ func (i simpleInputIssue) Line() int { return i.lineNumber } -// Prepare extracts a patch and changed lines +// Prepare extracts a patch and changed lines. func (c *Checker) Prepare() error { returnErr := c.preparePatch() c.changes = c.linesChanged() return returnErr } -// IsNewIssue checks whether issue found by linter is new: it was found in changed lines -func (c Checker) IsNewIssue(i InputIssue) (hunkPos int, isNew bool) { - fchanges, ok := c.changes[i.FilePath()] +// IsNewIssue checks whether issue found by linter is new: it was found in changed lines. +func (c *Checker) IsNewIssue(i InputIssue) (hunkPos int, isNew bool) { + fchanges, ok := c.changes[filepath.ToSlash(i.FilePath())] if !ok { // file wasn't changed return 0, false } @@ -149,24 +138,24 @@ func (c Checker) IsNewIssue(i InputIssue) (hunkPos int, isNew bool) { // Check scans reader and writes any lines to writer that have been added in // Checker.Patch. // -// Returns issues written to writer when no error occurs. +// Returns the issues written to writer when no error occurs. // // If no VCS could be found or other VCS errors occur, all issues are written // to writer and an error is returned. // // File paths in reader must be relative to current working directory or // absolute. -func (c Checker) Check(reader io.Reader, writer io.Writer) (issues []Issue, err error) { +func (c *Checker) Check(reader io.Reader, writer io.Writer) (issues []Issue, err error) { returnErr := c.Prepare() writeAll := returnErr != nil // file.go:lineNo:colNo:message // colNo is optional, strip spaces before message - lineRE := regexp.MustCompile(`(.*?\.go):([0-9]+):([0-9]+)?:?\s*(.*)`) + lineRE := regexp.MustCompile(`(.+\.go):([0-9]+):([0-9]+)?:?\s*(.*)`) if c.Regexp != "" { lineRE, err = regexp.Compile(c.Regexp) if err != nil { - return nil, fmt.Errorf("could not parse regexp: %v", err) + return nil, fmt.Errorf("could not parse regexp: %w", err) } } @@ -178,7 +167,7 @@ func (c Checker) Check(reader io.Reader, writer io.Writer) (issues []Issue, err if absPath == "" { absPath, err = os.Getwd() if err != nil { - returnErr = fmt.Errorf("could not get current working directory: %s", err) + returnErr = fmt.Errorf("could not get current working directory: %w", err) } } @@ -192,7 +181,7 @@ func (c Checker) Check(reader io.Reader, writer io.Writer) (issues []Issue, err } if writeAll { - fmt.Fprintln(writer, scanner.Text()) + _, _ = fmt.Fprintln(writer, scanner.Text()) continue } @@ -224,11 +213,10 @@ func (c Checker) Check(reader io.Reader, writer io.Writer) (issues []Issue, err msg := string(line[4]) c.debugf("path: %q, lineNo: %v, colNo: %v, msg: %q", path, lno, cno, msg) - i := simpleInputIssue{ - filePath: path, - lineNumber: int(lno), - } - hunkPos, changed := c.IsNewIssue(i) + + simpleIssue := simpleInputIssue{filePath: path, lineNumber: int(lno)} + + hunkPos, changed := c.IsNewIssue(simpleIssue) if changed { issue := Issue{ File: path, @@ -239,33 +227,47 @@ func (c Checker) Check(reader io.Reader, writer io.Writer) (issues []Issue, err Message: msg, } issues = append(issues, issue) - fmt.Fprintln(writer, scanner.Text()) + + _, _ = fmt.Fprintln(writer, scanner.Text()) } else { c.debugf("unchanged: %s", scanner.Text()) } } + if err := scanner.Err(); err != nil { - returnErr = fmt.Errorf("error reading standard input: %s", err) + returnErr = fmt.Errorf("error reading standard input: %w", err) } + return issues, returnErr } -func (c Checker) debugf(format string, s ...interface{}) { +func (c *Checker) debugf(format string, s ...interface{}) { if c.Debug != nil { - fmt.Fprint(c.Debug, "DEBUG: ") - fmt.Fprintf(c.Debug, format+"\n", s...) + _, _ = fmt.Fprint(c.Debug, "DEBUG: ") + _, _ = fmt.Fprintf(c.Debug, format+"\n", s...) } } -type pos struct { - lineNo int // line number - hunkPos int // position relative to first @@ in file +func (c *Checker) preparePatch() error { + // Check if patch is supplied, if not, retrieve from VCS + if c.Patch == nil { + var err error + c.Patch, c.NewFiles, err = GitPatch(c.RevisionFrom, c.RevisionTo) + if err != nil { + return fmt.Errorf("could not read git repo: %w", err) + } + if c.Patch == nil { + return errors.New("no version control repository found") + } + } + + return nil } // linesChanges returns a map of file names to line numbers being changed. // If key is nil, the file has been recently added, else it contains a slice // of positions that have been added. -func (c Checker) linesChanged() map[string][]pos { +func (c *Checker) linesChanged() map[string][]pos { type state struct { file string lineNo int // current line number within chunk @@ -273,10 +275,7 @@ func (c Checker) linesChanged() map[string][]pos { changes []pos // position of changes } - var ( - s state - changes = make(map[string][]pos) - ) + changes := make(map[string][]pos) for _, file := range c.NewFiles { changes[file] = nil @@ -286,6 +285,8 @@ func (c Checker) linesChanged() map[string][]pos { return changes } + var s state + scanner := bufio.NewReader(c.Patch) var scanErr error for { @@ -330,11 +331,12 @@ func (c Checker) linesChanged() map[string][]pos { case strings.HasPrefix(line, "+"): s.changes = append(s.changes, pos{lineNo: s.lineNo, hunkPos: s.hunkPos}) } - } - if scanErr != nil && scanErr != io.EOF { - fmt.Fprintln(os.Stderr, "reading standard input:", scanErr) + + if !errors.Is(scanErr, io.EOF) { + _, _ = fmt.Fprintln(os.Stderr, "reading standard input:", scanErr) } + // record the last state changes[s.file] = s.changes @@ -353,17 +355,18 @@ func GitPatch(revisionFrom, revisionTo string) (io.Reader, []string, error) { var patch bytes.Buffer // check if git repo exists - if err := exec.Command("git", "status").Run(); err != nil { + if err := exec.Command("git", "status", "--porcelain").Run(); err != nil { // don't return an error, we assume the error is not repo exists return nil, nil, nil } // make a patch for untracked files - var newFiles []string ls, err := exec.Command("git", "ls-files", "--others", "--exclude-standard").CombinedOutput() if err != nil { - return nil, nil, fmt.Errorf("error executing git ls-files: %s", err) + return nil, nil, fmt.Errorf("error executing git ls-files: %w", err) } + + var newFiles []string 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 @@ -375,13 +378,15 @@ func GitPatch(revisionFrom, revisionTo string) (io.Reader, []string, error) { } if revisionFrom != "" { - cmd := exec.Command("git", "diff", "--relative", revisionFrom) + cmd := exec.Command("git", "diff", "--color=never", "--relative", revisionFrom) if revisionTo != "" { cmd.Args = append(cmd.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: %s", revisionFrom, revisionTo, err) + return nil, nil, fmt.Errorf("error executing git diff %q %q: %w", revisionFrom, revisionTo, err) } if revisionTo == "" { @@ -392,10 +397,10 @@ func GitPatch(revisionFrom, revisionTo string) (io.Reader, []string, error) { // make a patch for unstaged changes // use --no-prefix to remove b/ given: +++ b/main.go - cmd := exec.Command("git", "diff", "--relative") + cmd := exec.Command("git", "diff", "--color=never", "--relative", "--") cmd.Stdout = &patch if err := cmd.Run(); err != nil { - return nil, nil, fmt.Errorf("error executing git diff: %s", err) + return nil, nil, fmt.Errorf("error executing git diff: %w", err) } unstaged := patch.Len() > 0 @@ -407,10 +412,10 @@ func GitPatch(revisionFrom, revisionTo string) (io.Reader, []string, error) { // check for changes in recent commit - cmd = exec.Command("git", "diff", "--relative", "HEAD~") + cmd = exec.Command("git", "diff", "--color=never", "--relative", "HEAD~", "--") cmd.Stdout = &patch if err := cmd.Run(); err != nil { - return nil, nil, fmt.Errorf("error executing git diff HEAD~: %s", err) + return nil, nil, fmt.Errorf("error executing git diff HEAD~: %w", err) } return &patch, nil, nil diff --git a/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md b/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md index 2020c472..5f16dd14 100644 --- a/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md +++ b/tools/vendor/github.com/hashicorp/go-version/CHANGELOG.md @@ -1,4 +1,17 @@ -# 1.4.0 (January 5, 2021) +# 1.6.0 (June 28, 2022) + +FEATURES: + +- Add `Prerelease` function to `Constraint` to return true if the version includes a prerelease field ([#100](https://github.com/hashicorp/go-version/pull/100)) + +# 1.5.0 (May 18, 2022) + +FEATURES: + +- Use `encoding` `TextMarshaler` & `TextUnmarshaler` instead of JSON equivalents ([#95](https://github.com/hashicorp/go-version/pull/95)) +- Add JSON handlers to allow parsing from/to JSON ([#93](https://github.com/hashicorp/go-version/pull/93)) + +# 1.4.0 (January 5, 2022) FEATURES: diff --git a/tools/vendor/github.com/hashicorp/go-version/README.md b/tools/vendor/github.com/hashicorp/go-version/README.md index 851a337b..4d250509 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/master.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/master) +[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/main.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/main) [![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 1d880902..da5d1aca 100644 --- a/tools/vendor/github.com/hashicorp/go-version/constraint.go +++ b/tools/vendor/github.com/hashicorp/go-version/constraint.go @@ -163,6 +163,12 @@ func (c *Constraint) Check(v *Version) bool { return c.f(v, c.check) } +// Prerelease returns true if the version underlying this constraint +// contains a prerelease field. +func (c *Constraint) Prerelease() bool { + return len(c.check.Prerelease()) > 0 +} + func (c *Constraint) String() string { return c.original } diff --git a/tools/vendor/github.com/hashicorp/go-version/version.go b/tools/vendor/github.com/hashicorp/go-version/version.go index 116a7446..e87df699 100644 --- a/tools/vendor/github.com/hashicorp/go-version/version.go +++ b/tools/vendor/github.com/hashicorp/go-version/version.go @@ -388,3 +388,20 @@ func (v *Version) String() string { func (v *Version) Original() string { return v.original } + +// UnmarshalText implements encoding.TextUnmarshaler interface. +func (v *Version) UnmarshalText(b []byte) error { + temp, err := NewVersion(string(b)) + if err != nil { + return err + } + + *v = *temp + + return nil +} + +// MarshalText implements encoding.TextMarshaler interface. +func (v *Version) MarshalText() ([]byte, error) { + return []byte(v.String()), nil +} diff --git a/tools/vendor/github.com/kisielk/errcheck/errcheck/analyzer.go b/tools/vendor/github.com/kisielk/errcheck/errcheck/analyzer.go new file mode 100644 index 00000000..68593cc9 --- /dev/null +++ b/tools/vendor/github.com/kisielk/errcheck/errcheck/analyzer.go @@ -0,0 +1,77 @@ +package errcheck + +import ( + "fmt" + "go/ast" + "reflect" + "regexp" + + "golang.org/x/tools/go/analysis" +) + +var Analyzer = &analysis.Analyzer{ + Name: "errcheck", + Doc: "check for unchecked errors", + Run: runAnalyzer, + ResultType: reflect.TypeOf(Result{}), +} + +var ( + argBlank bool + argAsserts bool + argExcludeFile string + argExcludeOnly bool +) + +func init() { + Analyzer.Flags.BoolVar(&argBlank, "blank", false, "if true, check for errors assigned to blank identifier") + Analyzer.Flags.BoolVar(&argAsserts, "assert", false, "if true, check for ignored type assertion results") + Analyzer.Flags.StringVar(&argExcludeFile, "exclude", "", "Path to a file containing a list of functions to exclude from checking") + Analyzer.Flags.BoolVar(&argExcludeOnly, "excludeonly", false, "Use only excludes from exclude file") +} + +func runAnalyzer(pass *analysis.Pass) (interface{}, error) { + + exclude := map[string]bool{} + if !argExcludeOnly { + for _, name := range DefaultExcludedSymbols { + exclude[name] = true + } + } + if argExcludeFile != "" { + excludes, err := ReadExcludes(argExcludeFile) + if err != nil { + return nil, fmt.Errorf("Could not read exclude file: %v\n", err) + } + for _, name := range excludes { + exclude[name] = true + } + } + + var allErrors []UncheckedError + for _, f := range pass.Files { + v := &visitor{ + typesInfo: pass.TypesInfo, + fset: pass.Fset, + blank: argBlank, + asserts: argAsserts, + exclude: exclude, + ignore: map[string]*regexp.Regexp{}, // deprecated & not used + lines: make(map[string][]string), + errors: nil, + } + + ast.Walk(v, f) + + for _, err := range v.errors { + pass.Report(analysis.Diagnostic{ + Pos: pass.Fset.File(f.Pos()).Pos(err.Pos.Offset), + Message: "unchecked error", + }) + } + + allErrors = append(allErrors, v.errors...) + } + + return Result{UncheckedErrors: allErrors}, nil +} diff --git a/tools/vendor/github.com/kisielk/errcheck/errcheck/embedded_walker.go b/tools/vendor/github.com/kisielk/errcheck/errcheck/embedded_walker.go index 3b319258..dff39179 100644 --- a/tools/vendor/github.com/kisielk/errcheck/errcheck/embedded_walker.go +++ b/tools/vendor/github.com/kisielk/errcheck/errcheck/embedded_walker.go @@ -73,9 +73,8 @@ func walkThroughEmbeddedInterfaces(sel *types.Selection) ([]types.Type, bool) { // define the method, add it to our list, and loop. namedInterfaceT, ok := getEmbeddedInterfaceDefiningMethod(interfaceT, fn) if !ok { - // This should be impossible as long as we type-checked: either the - // interface or one of its embedded ones must implement the method... - panic(fmt.Sprintf("either %v or one of its embedded interfaces must implement %v", currentT, fn)) + // Returned a nil interface, we are done. + break } result = append(result, namedInterfaceT) interfaceT = namedInterfaceT.Underlying().(*types.Interface) @@ -102,7 +101,7 @@ func getTypeAtFieldIndex(startingAt types.Type, fieldIndex int) types.Type { func getEmbeddedInterfaceDefiningMethod(interfaceT *types.Interface, fn *types.Func) (*types.Named, bool) { for i := 0; i < interfaceT.NumEmbeddeds(); i++ { embedded := interfaceT.Embedded(i) - if definesMethod(embedded.Underlying().(*types.Interface), fn) { + if embedded != nil && definesMethod(embedded.Underlying().(*types.Interface), fn) { return embedded, true } } diff --git a/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go b/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go index 724e3e88..0a4067f9 100644 --- a/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go +++ b/tools/vendor/github.com/kisielk/errcheck/errcheck/errcheck.go @@ -25,45 +25,6 @@ func init() { var ( // ErrNoGoFiles is returned when CheckPackage is run on a package with no Go source files ErrNoGoFiles = errors.New("package contains no go source files") - - // 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", - - // 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)", - - // math/rand - "math/rand.Read", - "(*math/rand.Rand).Read", - - // strings - "(*strings.Builder).Write", - "(*strings.Builder).WriteByte", - "(*strings.Builder).WriteRune", - "(*strings.Builder).WriteString", - - // hash - "(hash.Hash).Write", - } ) // UncheckedError indicates the position of an unchecked error return. @@ -257,16 +218,17 @@ func (c *Checker) CheckPackage(pkg *packages.Package) Result { } v := &visitor{ - pkg: pkg, - ignore: ignore, - blank: !c.Exclusions.BlankAssignments, - asserts: !c.Exclusions.TypeAssertions, - lines: make(map[string][]string), - exclude: excludedSymbols, - errors: []UncheckedError{}, + typesInfo: pkg.TypesInfo, + fset: pkg.Fset, + ignore: ignore, + blank: !c.Exclusions.BlankAssignments, + asserts: !c.Exclusions.TypeAssertions, + lines: make(map[string][]string), + exclude: excludedSymbols, + errors: []UncheckedError{}, } - for _, astFile := range v.pkg.Syntax { + for _, astFile := range pkg.Syntax { if c.shouldSkipFile(astFile) { continue } @@ -277,12 +239,13 @@ func (c *Checker) CheckPackage(pkg *packages.Package) Result { // visitor implements the errcheck algorithm type visitor struct { - pkg *packages.Package - ignore map[string]*regexp.Regexp - blank bool - asserts bool - lines map[string][]string - exclude map[string]bool + typesInfo *types.Info + fset *token.FileSet + ignore map[string]*regexp.Regexp + blank bool + asserts bool + lines map[string][]string + exclude map[string]bool errors []UncheckedError } @@ -302,7 +265,7 @@ func (v *visitor) selectorAndFunc(call *ast.CallExpr) (*ast.SelectorExpr, *types return nil, nil, false } - fn, ok := v.pkg.TypesInfo.ObjectOf(sel.Sel).(*types.Func) + fn, ok := v.typesInfo.ObjectOf(sel.Sel).(*types.Func) if !ok { // Shouldn't happen, but be paranoid return nil, nil, false @@ -389,7 +352,7 @@ func (v *visitor) namesForExcludeCheck(call *ast.CallExpr) []string { // This will be missing for functions without a receiver (like fmt.Printf), // so just fall back to the the function's fullName in that case. - selection, ok := v.pkg.TypesInfo.Selections[sel] + selection, ok := v.typesInfo.Selections[sel] if !ok { return []string{name} } @@ -416,14 +379,14 @@ func (v *visitor) namesForExcludeCheck(call *ast.CallExpr) []string { func (v *visitor) argName(expr ast.Expr) string { // Special-case literal "os.Stdout" and "os.Stderr" if sel, ok := expr.(*ast.SelectorExpr); ok { - if obj := v.pkg.TypesInfo.ObjectOf(sel.Sel); obj != nil { + if obj := v.typesInfo.ObjectOf(sel.Sel); obj != nil { vr, ok := obj.(*types.Var) if ok && vr.Pkg() != nil && vr.Pkg().Name() == "os" && (vr.Name() == "Stderr" || vr.Name() == "Stdout") { return "os." + vr.Name() } } } - t := v.pkg.TypesInfo.TypeOf(expr) + t := v.typesInfo.TypeOf(expr) if t == nil { return "" } @@ -474,7 +437,7 @@ func (v *visitor) ignoreCall(call *ast.CallExpr) bool { return true } - if obj := v.pkg.TypesInfo.Uses[id]; obj != nil { + if obj := v.typesInfo.Uses[id]; obj != nil { if pkg := obj.Pkg(); pkg != nil { if re, ok := v.ignore[nonVendoredPkgPath(pkg.Path())]; ok { return re.MatchString(id.Name) @@ -500,7 +463,7 @@ func nonVendoredPkgPath(pkgPath string) string { // len(s) == number of return types of call // s[i] == true iff return type at position i from left is an error type func (v *visitor) errorsByArg(call *ast.CallExpr) []bool { - switch t := v.pkg.TypesInfo.Types[call].Type.(type) { + switch t := v.typesInfo.Types[call].Type.(type) { case *types.Named: // Single return return []bool{isErrorType(t)} @@ -542,15 +505,18 @@ func (v *visitor) callReturnsError(call *ast.CallExpr) bool { // isRecover returns true if the given CallExpr is a call to the built-in recover() function. func (v *visitor) isRecover(call *ast.CallExpr) bool { if fun, ok := call.Fun.(*ast.Ident); ok { - if _, ok := v.pkg.TypesInfo.Uses[fun].(*types.Builtin); ok { + if _, ok := v.typesInfo.Uses[fun].(*types.Builtin); ok { return fun.Name == "recover" } } return false } +// TODO (dtcaciuc) collect token.Pos and then convert them to UncheckedErrors +// after visitor is done running. This will allow to integrate more cleanly +// with analyzer so that we don't have to convert Position back to Pos. func (v *visitor) addErrorAtPosition(position token.Pos, call *ast.CallExpr) { - pos := v.pkg.Fset.Position(position) + pos := v.fset.Position(position) lines, ok := v.lines[pos.Filename] if !ok { lines = readfile(pos.Filename) @@ -577,6 +543,7 @@ func readfile(filename string) []string { if err != nil { return nil } + defer f.Close() var lines []string var scanner = bufio.NewScanner(f) diff --git a/tools/vendor/github.com/kisielk/errcheck/errcheck/excludes.go b/tools/vendor/github.com/kisielk/errcheck/errcheck/excludes.go new file mode 100644 index 00000000..22db9fe1 --- /dev/null +++ b/tools/vendor/github.com/kisielk/errcheck/errcheck/excludes.go @@ -0,0 +1,83 @@ +package errcheck + +import ( + "bufio" + "bytes" + "io/ioutil" + "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", + + // 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)", + + // io + "(*io.PipeReader).CloseWithError", + "(*io.PipeWriter).CloseWithError", + + // math/rand + "math/rand.Read", + "(*math/rand.Rand).Read", + + // strings + "(*strings.Builder).Write", + "(*strings.Builder).WriteByte", + "(*strings.Builder).WriteRune", + "(*strings.Builder).WriteString", + + // 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) + if err != nil { + return nil, err + } + + scanner := bufio.NewScanner(bytes.NewReader(buf)) + + for scanner.Scan() { + name := scanner.Text() + // Skip comments and empty lines. + if strings.HasPrefix(name, "//") || name == "" { + continue + } + excludes = append(excludes, name) + } + if err := scanner.Err(); err != nil { + return nil, err + } + + return excludes, nil +} diff --git a/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer.go b/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer.go index a5c5d4a9..a22fd6ac 100644 --- a/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer.go +++ b/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer.go @@ -262,6 +262,35 @@ func (t thelper) buildTestCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) }, true } +func (t thelper) buildFuzzCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) { + fObj := analysisutil.ObjectOf(pass, "testing", "F") + if fObj == nil { + return checkFuncOpts{}, true // fuzzing supports since go1.18, it's ok, that testig.F is missed. + } + + fHelper, _, _ := types.LookupFieldOrMethod(fObj.Type(), true, fObj.Pkg(), "Helper") + if fHelper == nil { + return checkFuncOpts{}, false + } + + tFuzz, _, _ := types.LookupFieldOrMethod(fObj.Type(), true, fObj.Pkg(), "Fuzz") + if tFuzz == nil { + return checkFuncOpts{}, false + } + + return checkFuncOpts{ + skipPrefix: "Fuzz", + varName: "f", + fnHelper: fHelper, + subRun: tFuzz, + hpType: types.NewPointer(fObj.Type()), + ctxType: ctxType, + checkBegin: t.enabledChecks.Enabled(checkFBegin), + checkFirst: t.enabledChecks.Enabled(checkFFirst), + checkName: t.enabledChecks.Enabled(checkFName), + }, true +} + func (t thelper) buildBenchmarkCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) { bObj := analysisutil.ObjectOf(pass, "testing", "B") if bObj == nil { diff --git a/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer_go117.go b/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer_go117.go deleted file mode 100644 index ea728a40..00000000 --- a/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer_go117.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !go1.18 -// +build !go1.18 - -package analyzer - -import ( - "go/types" - - "golang.org/x/tools/go/analysis" -) - -func (t thelper) buildFuzzCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) { - return checkFuncOpts{}, true -} diff --git a/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer_go118.go b/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer_go118.go deleted file mode 100644 index 14ed5a0e..00000000 --- a/tools/vendor/github.com/kulti/thelper/pkg/analyzer/analyzer_go118.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -package analyzer - -import ( - "go/types" - - "github.com/gostaticanalysis/analysisutil" - "golang.org/x/tools/go/analysis" -) - -func (t thelper) buildFuzzCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) { - fObj := analysisutil.ObjectOf(pass, "testing", "F") - if fObj == nil { - return checkFuncOpts{}, false - } - - fHelper, _, _ := types.LookupFieldOrMethod(fObj.Type(), true, fObj.Pkg(), "Helper") - if fHelper == nil { - return checkFuncOpts{}, false - } - - tFuzz, _, _ := types.LookupFieldOrMethod(fObj.Type(), true, fObj.Pkg(), "Fuzz") - if tFuzz == nil { - return checkFuncOpts{}, false - } - - return checkFuncOpts{ - skipPrefix: "Fuzz", - varName: "f", - fnHelper: fHelper, - subRun: tFuzz, - hpType: types.NewPointer(fObj.Type()), - ctxType: ctxType, - checkBegin: t.enabledChecks.Enabled(checkFBegin), - checkFirst: t.enabledChecks.Enabled(checkFFirst), - checkName: t.enabledChecks.Enabled(checkFName), - }, true -} diff --git a/tools/vendor/github.com/kunwardeep/paralleltest/LICENSE b/tools/vendor/github.com/kunwardeep/paralleltest/LICENSE index d06a809c..77f0d26a 100644 --- a/tools/vendor/github.com/kunwardeep/paralleltest/LICENSE +++ b/tools/vendor/github.com/kunwardeep/paralleltest/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2020 Isaev Denis +Copyright (c) 2020 Kunwardeep Bedi 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/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go b/tools/vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go index 0e359f76..c7da52a2 100644 --- a/tools/vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go +++ b/tools/vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go @@ -1,7 +1,9 @@ package paralleltest import ( + "flag" "go/ast" + "go/types" "strings" "golang.org/x/tools/go/analysis" @@ -14,16 +16,28 @@ It also checks that the t.Parallel is used if multiple tests cases are run as pa As part of ensuring parallel tests works as expected it checks for reinitialising of the range value over the test cases.(https://tinyurl.com/y6555cy6)` -func NewAnalyzer() *analysis.Analyzer { - return &analysis.Analyzer{ - Name: "paralleltest", - Doc: Doc, - Run: run, - Requires: []*analysis.Analyzer{inspect.Analyzer}, - } +var Analyzer = &analysis.Analyzer{ + Name: "paralleltest", + Doc: Doc, + Run: run, + Flags: flags(), + Requires: []*analysis.Analyzer{inspect.Analyzer}, +} + +const ignoreMissingFlag = "i" + +func flags() flag.FlagSet { + options := flag.NewFlagSet("", flag.ExitOnError) + options.Bool(ignoreMissingFlag, false, "ignore missing calls to t.Parallel") + return *options } +type boolValue bool + func run(pass *analysis.Pass) (interface{}, error) { + + ignoreMissing := pass.Analyzer.Flags.Lookup(ignoreMissingFlag).Value.(flag.Getter).Get().(bool) + inspector := inspector.New(pass.Files) nodeFilter := []ast.Node{ @@ -34,9 +48,8 @@ func run(pass *analysis.Pass) (interface{}, error) { funcDecl := node.(*ast.FuncDecl) var funcHasParallelMethod, rangeStatementOverTestCasesExists, - rangeStatementHasParallelMethod, - testLoopVariableReinitialised bool - var testRunLoopIdentifier string + rangeStatementHasParallelMethod bool + var loopVariableUsedInRun *string var numberOfTestRun int var positionOfTestRunNode []ast.Node var rangeNode ast.Node @@ -52,12 +65,12 @@ func run(pass *analysis.Pass) (interface{}, error) { case *ast.ExprStmt: ast.Inspect(v, func(n ast.Node) bool { - // Check if the test method is calling t.parallel + // Check if the test method is calling t.Parallel if !funcHasParallelMethod { funcHasParallelMethod = methodParallelIsCalledInTestFunction(n, testVar) } - // Check if the t.Run within the test function is calling t.parallel + // 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) @@ -77,10 +90,17 @@ func run(pass *analysis.Pass) (interface{}, error) { return true }) - // Check if the range over testcases is calling t.parallel + // Check if the range over testcases is calling t.Parallel case *ast.RangeStmt: rangeNode = v + var loopVars []types.Object + for _, expr := range []ast.Expr{v.Key, v.Value} { + if id, ok := expr.(*ast.Ident); ok { + loopVars = append(loopVars, pass.TypesInfo.ObjectOf(id)) + } + } + ast.Inspect(v, func(n ast.Node) bool { // nolint: gocritic switch r := n.(type) { @@ -90,49 +110,43 @@ func run(pass *analysis.Pass) (interface{}, error) { innerTestVar := getRunCallbackParameterName(r.X) rangeStatementOverTestCasesExists = true - testRunLoopIdentifier = methodRunFirstArgumentObjectName(r.X) if !rangeStatementHasParallelMethod { rangeStatementHasParallelMethod = methodParallelIsCalledInMethodRun(r.X, innerTestVar) } + + if loopVariableUsedInRun == nil { + if run, ok := r.X.(*ast.CallExpr); ok { + loopVariableUsedInRun = loopVarReferencedInRun(run, loopVars, pass.TypesInfo) + } + } } } return true }) - - // Check for the range loop value identifier re assignment - // More info here https://gist.github.com/kunwardeep/80c2e9f3d3256c894898bae82d9f75d0 - if rangeStatementOverTestCasesExists { - var rangeValueIdentifier string - if i, ok := v.Value.(*ast.Ident); ok { - rangeValueIdentifier = i.Name - } - - testLoopVariableReinitialised = testCaseLoopVariableReinitialised(v.Body.List, rangeValueIdentifier, testRunLoopIdentifier) - } } } - if !funcHasParallelMethod { + if !ignoreMissing && !funcHasParallelMethod { pass.Reportf(node.Pos(), "Function %s missing the call to method parallel\n", funcDecl.Name.Name) } if rangeStatementOverTestCasesExists && rangeNode != nil { if !rangeStatementHasParallelMethod { - pass.Reportf(rangeNode.Pos(), "Range statement for test %s missing the call to method parallel in test Run\n", funcDecl.Name.Name) - } else { - if testRunLoopIdentifier == "" { - pass.Reportf(rangeNode.Pos(), "Range statement for test %s does not use range value in test Run\n", funcDecl.Name.Name) - } else if !testLoopVariableReinitialised { - pass.Reportf(rangeNode.Pos(), "Range statement for test %s does not reinitialise the variable %s\n", funcDecl.Name.Name, testRunLoopIdentifier) + if !ignoreMissing { + pass.Reportf(rangeNode.Pos(), "Range statement for test %s missing the call to method parallel in test Run\n", funcDecl.Name.Name) } + } else if loopVariableUsedInRun != nil { + pass.Reportf(rangeNode.Pos(), "Range statement for test %s does not reinitialise the variable %s\n", funcDecl.Name.Name, *loopVariableUsedInRun) } } // Check if the t.Run is more than one as there is no point making one test parallel - if numberOfTestRun > 1 && len(positionOfTestRunNode) > 0 { - for _, n := range positionOfTestRunNode { - pass.Reportf(n.Pos(), "Function %s has missing the call to method parallel in the test run\n", funcDecl.Name.Name) + if !ignoreMissing { + if numberOfTestRun > 1 && len(positionOfTestRunNode) > 0 { + for _, n := range positionOfTestRunNode { + pass.Reportf(n.Pos(), "Function %s has missing the call to method parallel in the test run\n", funcDecl.Name.Name) + } } } }) @@ -140,38 +154,6 @@ func run(pass *analysis.Pass) (interface{}, error) { return nil, nil } -func testCaseLoopVariableReinitialised(statements []ast.Stmt, rangeValueIdentifier string, testRunLoopIdentifier string) bool { - if len(statements) > 1 { - for _, s := range statements { - leftIdentifier, rightIdentifier := getLeftAndRightIdentifier(s) - if leftIdentifier == testRunLoopIdentifier && rightIdentifier == rangeValueIdentifier { - return true - } - } - } - return false -} - -// Return the left hand side and the right hand side identifiers name -func getLeftAndRightIdentifier(s ast.Stmt) (string, string) { - var leftIdentifier, rightIdentifier string - // nolint: gocritic - switch v := s.(type) { - case *ast.AssignStmt: - if len(v.Rhs) == 1 { - if i, ok := v.Rhs[0].(*ast.Ident); ok { - rightIdentifier = i.Name - } - } - if len(v.Lhs) == 1 { - if i, ok := v.Lhs[0].(*ast.Ident); ok { - leftIdentifier = i.Name - } - } - } - return leftIdentifier, rightIdentifier -} - func methodParallelIsCalledInMethodRun(node ast.Node, testVar string) bool { var methodParallelCalled bool // nolint: gocritic @@ -247,22 +229,6 @@ func getRunCallbackParameterName(node ast.Node) string { return "" } -// Gets the object name `tc` from method t.Run(tc.Foo, func(t *testing.T) -func methodRunFirstArgumentObjectName(node ast.Node) string { - // nolint: gocritic - switch n := node.(type) { - case *ast.CallExpr: - for _, arg := range n.Args { - if s, ok := arg.(*ast.SelectorExpr); ok { - if i, ok := s.X.(*ast.Ident); ok { - return i.Name - } - } - } - } - return "" -} - // Checks if the function has the param type *testing.T; if it does, then the // parameter name is returned, too. func isTestFunction(funcDecl *ast.FuncDecl) (bool, string) { @@ -291,3 +257,24 @@ func isTestFunction(funcDecl *ast.FuncDecl) (bool, string) { return false, "" } + +func loopVarReferencedInRun(call *ast.CallExpr, vars []types.Object, typeInfo *types.Info) (found *string) { + if len(call.Args) != 2 { + return + } + + ast.Inspect(call.Args[1], func(n ast.Node) bool { + ident, ok := n.(*ast.Ident) + if !ok { + return true + } + for _, o := range vars { + if typeInfo.ObjectOf(ident) == o { + found = &ident.Name + } + } + return true + }) + + return +} diff --git a/tools/vendor/github.com/maratori/testpackage/pkg/testpackage/testpackage.go b/tools/vendor/github.com/maratori/testpackage/pkg/testpackage/testpackage.go index cad24e1a..2e057297 100644 --- a/tools/vendor/github.com/maratori/testpackage/pkg/testpackage/testpackage.go +++ b/tools/vendor/github.com/maratori/testpackage/pkg/testpackage/testpackage.go @@ -5,6 +5,8 @@ import ( "regexp" "strings" + "go/ast" + "golang.org/x/tools/go/analysis" ) @@ -14,20 +16,43 @@ const ( SkipRegexpFlagDefault = `(export|internal)_test\.go` ) -// NewAnalyzer returns Analyzer that makes you use a separate _test package +const ( + AllowPackagesFlagName = "allow-packages" + AllowPackagesFlagUsage = `comma separated list of packages that don't end with _test that tests are allowed to be in` + AllowPackagesFlagDefault = `main` +) + +func processTestFile(pass *analysis.Pass, f *ast.File, allowedPackages []string) { + packageName := f.Name.Name + + for _, p := range allowedPackages { + if p == packageName { + return + } + } + + if !strings.HasSuffix(packageName, "_test") { + pass.Reportf(f.Name.Pos(), "package should be `%s_test` instead of `%s`", packageName, packageName) + } +} + +// NewAnalyzer returns Analyzer that makes you use a separate _test package. func NewAnalyzer() *analysis.Analyzer { var ( - skipFileRegexp = SkipRegexpFlagDefault - fs flag.FlagSet + skipFileRegexp = SkipRegexpFlagDefault + allowPackagesStr = AllowPackagesFlagDefault + fs flag.FlagSet ) fs.StringVar(&skipFileRegexp, SkipRegexpFlagName, skipFileRegexp, SkipRegexpFlagUsage) + fs.StringVar(&allowPackagesStr, AllowPackagesFlagName, allowPackagesStr, AllowPackagesFlagUsage) return &analysis.Analyzer{ Name: "testpackage", Doc: "linter that makes you use a separate _test package", Flags: fs, Run: func(pass *analysis.Pass) (interface{}, error) { + allowedPackages := strings.Split(allowPackagesStr, ",") skipFile, err := regexp.Compile(skipFileRegexp) if err != nil { return nil, err @@ -35,16 +60,11 @@ func NewAnalyzer() *analysis.Analyzer { for _, f := range pass.Files { fileName := pass.Fset.Position(f.Pos()).Filename - if skipFile.MatchString(fileName) { + if !strings.HasSuffix(fileName, "_test.go") || skipFile.MatchString(fileName) { continue } - if strings.HasSuffix(fileName, "_test.go") { - packageName := f.Name.Name - if !strings.HasSuffix(packageName, "_test") { - pass.Reportf(f.Name.Pos(), "package should be `%s_test` instead of `%s`", packageName, packageName) - } - } + processTestFile(pass, f, allowedPackages) } 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 388517a3..5c63f35b 100644 --- a/tools/vendor/github.com/mgechev/revive/config/config.go +++ b/tools/vendor/github.com/mgechev/revive/config/config.go @@ -85,6 +85,7 @@ var allRules = append([]lint.Rule{ &rule.BannedCharsRule{}, &rule.OptimizeOperandsOrderRule{}, &rule.UseAnyRule{}, + &rule.DataRaceRule{}, }, defaultRules...) var allFormatters = []lint.Formatter{ @@ -122,7 +123,7 @@ func GetLintingRules(config *lint.Config, extraRules []lint.Rule) ([]lint.Rule, var lintingRules []lint.Rule for name, ruleConfig := range config.Rules { - rule, ok := rulesMap[name] + r, ok := rulesMap[name] if !ok { return nil, fmt.Errorf("cannot find rule: %s", name) } @@ -131,7 +132,7 @@ func GetLintingRules(config *lint.Config, extraRules []lint.Rule) ([]lint.Rule, continue // skip disabled rules } - lintingRules = append(lintingRules, rule) + lintingRules = append(lintingRules, r) } return lintingRules, nil @@ -155,8 +156,8 @@ func normalizeConfig(config *lint.Config) { } if config.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 := config.Rules[ruleName] if alreadyInConf { continue @@ -207,15 +208,15 @@ func GetConfig(configPath string) (*lint.Config, error) { // GetFormatter yields the formatter for lint failures func GetFormatter(formatterName string) (lint.Formatter, error) { formatters := getFormatters() - formatter := formatters["default"] + fmtr := formatters["default"] if formatterName != "" { f, ok := formatters[formatterName] if !ok { return nil, fmt.Errorf("unknown formatter %v", formatterName) } - formatter = f + fmtr = f } - return formatter, nil + return fmtr, nil } func defaultConfig() *lint.Config { diff --git a/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go b/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go index e7a451a5..33a3b2ca 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/checkstyle.go @@ -15,7 +15,7 @@ type Checkstyle struct { } // Name returns the name of the formatter -func (f *Checkstyle) Name() string { +func (*Checkstyle) Name() string { return "checkstyle" } @@ -29,7 +29,7 @@ type issue struct { } // Format formats the failures gotten from the lint. -func (f *Checkstyle) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { +func (*Checkstyle) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { issues := map[string][]issue{} for failure := range failures { buf := new(bytes.Buffer) diff --git a/tools/vendor/github.com/mgechev/revive/formatter/default.go b/tools/vendor/github.com/mgechev/revive/formatter/default.go index 145e6d54..f76a7b29 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/default.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/default.go @@ -13,12 +13,12 @@ type Default struct { } // Name returns the name of the formatter -func (f *Default) Name() string { +func (*Default) Name() string { return "default" } // Format formats the failures gotten from the lint. -func (f *Default) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { +func (*Default) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { for failure := range failures { fmt.Printf("%v: %s\n", failure.Position.Start, failure.Failure) } diff --git a/tools/vendor/github.com/mgechev/revive/formatter/friendly.go b/tools/vendor/github.com/mgechev/revive/formatter/friendly.go index f1637e44..ced8fa46 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/friendly.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/friendly.go @@ -10,16 +10,6 @@ import ( "github.com/olekukonko/tablewriter" ) -var newLines = map[rune]bool{ - 0x000A: true, - 0x000B: true, - 0x000C: true, - 0x000D: true, - 0x0085: true, - 0x2028: true, - 0x2029: true, -} - func getErrorEmoji() string { return color.RedString("✘") } @@ -35,7 +25,7 @@ type Friendly struct { } // Name returns the name of the formatter -func (f *Friendly) Name() string { +func (*Friendly) Name() string { return "friendly" } @@ -78,7 +68,7 @@ func (f *Friendly) printHeaderRow(failure lint.Failure, severity lint.Severity) fmt.Print(f.table([][]string{{emoji, "https://revive.run/r#" + failure.RuleName, color.GreenString(failure.Failure)}})) } -func (f *Friendly) printFilePosition(failure lint.Failure) { +func (*Friendly) printFilePosition(failure lint.Failure) { fmt.Printf(" %s:%d:%d", failure.GetFilename(), failure.Position.Start.Line, failure.Position.Start.Column) } @@ -87,7 +77,7 @@ type statEntry struct { failures int } -func (f *Friendly) printSummary(errors, warnings int) { +func (*Friendly) printSummary(errors, warnings int) { emoji := getWarningEmoji() if errors > 0 { emoji = getErrorEmoji() @@ -136,7 +126,7 @@ func (f *Friendly) printStatistics(header string, stats map[string]int) { fmt.Println(f.table(formatted)) } -func (f *Friendly) table(rows [][]string) string { +func (*Friendly) table(rows [][]string) string { buf := new(bytes.Buffer) table := tablewriter.NewWriter(buf) table.SetBorder(false) diff --git a/tools/vendor/github.com/mgechev/revive/formatter/json.go b/tools/vendor/github.com/mgechev/revive/formatter/json.go index 9c939fac..7cace89e 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/json.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/json.go @@ -13,7 +13,7 @@ type JSON struct { } // Name returns the name of the formatter -func (f *JSON) Name() string { +func (*JSON) Name() string { return "json" } @@ -24,7 +24,7 @@ type jsonObject struct { } // Format formats the failures gotten from the lint. -func (f *JSON) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { +func (*JSON) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { var slice []jsonObject for failure := range failures { obj := jsonObject{} diff --git a/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go b/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go index aa2b1d63..a02d9c80 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/ndjson.go @@ -14,12 +14,12 @@ type NDJSON struct { } // Name returns the name of the formatter -func (f *NDJSON) Name() string { +func (*NDJSON) Name() string { return "ndjson" } // Format formats the failures gotten from the lint. -func (f *NDJSON) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { +func (*NDJSON) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { enc := json.NewEncoder(os.Stdout) for failure := range failures { obj := jsonObject{} diff --git a/tools/vendor/github.com/mgechev/revive/formatter/plain.go b/tools/vendor/github.com/mgechev/revive/formatter/plain.go index a854d256..6e083bcf 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/plain.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/plain.go @@ -13,12 +13,12 @@ type Plain struct { } // Name returns the name of the formatter -func (f *Plain) Name() string { +func (*Plain) Name() string { return "plain" } // Format formats the failures gotten from the lint. -func (f *Plain) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { +func (*Plain) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { for failure := range failures { fmt.Printf("%v: %s %s\n", failure.Position.Start, failure.Failure, "https://revive.run/r#"+failure.RuleName) } diff --git a/tools/vendor/github.com/mgechev/revive/formatter/sarif.go b/tools/vendor/github.com/mgechev/revive/formatter/sarif.go index 8968c3ff..ee62adcc 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/sarif.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/sarif.go @@ -16,14 +16,14 @@ type Sarif struct { } // Name returns the name of the formatter -func (f *Sarif) Name() string { +func (*Sarif) Name() string { return "sarif" } const reviveSite = "https://revive.run" // Format formats the failures gotten from the lint. -func (f *Sarif) Format(failures <-chan lint.Failure, cfg lint.Config) (string, error) { +func (*Sarif) Format(failures <-chan lint.Failure, cfg lint.Config) (string, error) { sarifLog := newReviveRunLog(cfg) for failure := range failures { diff --git a/tools/vendor/github.com/mgechev/revive/formatter/stylish.go b/tools/vendor/github.com/mgechev/revive/formatter/stylish.go index ddafa501..828228c7 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/stylish.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/stylish.go @@ -16,7 +16,7 @@ type Stylish struct { } // Name returns the name of the formatter -func (f *Stylish) Name() string { +func (*Stylish) Name() string { return "stylish" } @@ -32,7 +32,7 @@ func formatFailure(failure lint.Failure, severity lint.Severity) []string { } // Format formats the failures gotten from the lint. -func (f *Stylish) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { +func (*Stylish) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { var result [][]string totalErrors := 0 total := 0 diff --git a/tools/vendor/github.com/mgechev/revive/formatter/unix.go b/tools/vendor/github.com/mgechev/revive/formatter/unix.go index b9ae62d3..ef2f1613 100644 --- a/tools/vendor/github.com/mgechev/revive/formatter/unix.go +++ b/tools/vendor/github.com/mgechev/revive/formatter/unix.go @@ -14,12 +14,12 @@ type Unix struct { } // Name returns the name of the formatter -func (f *Unix) Name() string { +func (*Unix) Name() string { return "unix" } // Format formats the failures gotten from the lint. -func (f *Unix) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { +func (*Unix) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { for failure := range failures { fmt.Printf("%v: [%s] %s\n", failure.Position.Start, failure.RuleName, failure.Failure) } diff --git a/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams.go b/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams.go new file mode 100644 index 00000000..33c4f203 --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams.go @@ -0,0 +1,29 @@ +// Package typeparams provides utilities for working with Go ASTs with support +// for type parameters when built with Go 1.18 and higher. +package typeparams + +import ( + "go/ast" +) + +// Enabled reports whether type parameters are enabled in the current build +// environment. +func Enabled() bool { + return enabled +} + +// ReceiverType returns the named type of the method receiver, sans "*" and type +// parameters, or "invalid-type" if fn.Recv is ill formed. +func ReceiverType(fn *ast.FuncDecl) string { + e := fn.Recv.List[0].Type + if s, ok := e.(*ast.StarExpr); ok { + e = s.X + } + if enabled { + e = unpackIndexExpr(e) + } + if id, ok := e.(*ast.Ident); ok { + return id.Name + } + return "invalid-type" +} diff --git a/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams_go117.go b/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams_go117.go new file mode 100644 index 00000000..913a7316 --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams_go117.go @@ -0,0 +1,12 @@ +//go:build !go1.18 +// +build !go1.18 + +package typeparams + +import ( + "go/ast" +) + +const enabled = false + +func unpackIndexExpr(e ast.Expr) ast.Expr { return e } diff --git a/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams_go118.go b/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams_go118.go new file mode 100644 index 00000000..0f7fd88d --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/internal/typeparams/typeparams_go118.go @@ -0,0 +1,20 @@ +//go:build go1.18 +// +build go1.18 + +package typeparams + +import ( + "go/ast" +) + +const enabled = true + +func unpackIndexExpr(e ast.Expr) ast.Expr { + switch e := e.(type) { + case *ast.IndexExpr: + return e.X + case *ast.IndexListExpr: + return e.X + } + return e +} diff --git a/tools/vendor/github.com/mgechev/revive/lint/file.go b/tools/vendor/github.com/mgechev/revive/lint/file.go index f859da6f..dcf0e608 100644 --- a/tools/vendor/github.com/mgechev/revive/lint/file.go +++ b/tools/vendor/github.com/mgechev/revive/lint/file.go @@ -77,7 +77,7 @@ func (f *File) IsUntypedConst(expr ast.Expr) (defType string, ok bool) { // Re-evaluate expr outside 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.Pkg.fset, f.Pkg.TypesPkg, expr.Pos(), exprStr) + tv, err := types.Eval(f.Pkg.fset, f.Pkg.TypesPkg(), expr.Pos(), exprStr) if err != nil { return "", false } @@ -249,7 +249,7 @@ func (f *File) disabledIntervals(rules []Rule, mustSpecifyDisableReason bool, fa return getEnabledDisabledIntervals() } -func (f *File) filterFailures(failures []Failure, disabledIntervals disabledIntervalsMap) []Failure { +func (File) filterFailures(failures []Failure, disabledIntervals disabledIntervalsMap) []Failure { result := []Failure{} for _, failure := range failures { fStart := failure.Position.Start.Line diff --git a/tools/vendor/github.com/mgechev/revive/lint/linter.go b/tools/vendor/github.com/mgechev/revive/lint/linter.go index 2743b7d9..fb1ab6f2 100644 --- a/tools/vendor/github.com/mgechev/revive/lint/linter.go +++ b/tools/vendor/github.com/mgechev/revive/lint/linter.go @@ -81,7 +81,6 @@ func (l *Linter) lintPackage(filenames []string, ruleSet []Rule, config Config, pkg := &Package{ fset: token.NewFileSet(), files: map[string]*File{}, - mu: sync.Mutex{}, } for _, filename := range filenames { content, err := l.readFile(filename) @@ -137,7 +136,7 @@ func addInvalidFileFailure(filename, errStr string, failures chan Failure) { // errPosRegexp matches with an NewFile error message // i.e. : corrupted.go:10:4: expected '}', found 'EOF // first group matches the line and the second group, the column -var errPosRegexp = regexp.MustCompile(".*:(\\d*):(\\d*):.*$") +var errPosRegexp = regexp.MustCompile(`.*:(\d*):(\d*):.*$`) // getPositionInvalidFile gets the position of the error in an invalid file func getPositionInvalidFile(filename, s string) FailurePosition { diff --git a/tools/vendor/github.com/mgechev/revive/lint/package.go b/tools/vendor/github.com/mgechev/revive/lint/package.go index 7b6046fd..5976acf9 100644 --- a/tools/vendor/github.com/mgechev/revive/lint/package.go +++ b/tools/vendor/github.com/mgechev/revive/lint/package.go @@ -2,11 +2,12 @@ package lint import ( "go/ast" + "go/importer" "go/token" "go/types" "sync" - "golang.org/x/tools/go/gcexportdata" + "github.com/mgechev/revive/internal/typeparams" ) // Package represents a package in the project. @@ -14,18 +15,14 @@ type Package struct { fset *token.FileSet files map[string]*File - TypesPkg *types.Package - TypesInfo *types.Info + typesPkg *types.Package + typesInfo *types.Info // sortable is the set of types in the package that implement sort.Interface. - Sortable map[string]bool + sortable map[string]bool // main is whether this is a "main" package. main int - mu sync.Mutex -} - -var newImporter = func(fset *token.FileSet) types.ImporterFrom { - return gcexportdata.NewImporter(fset, make(map[string]*types.Package)) + sync.RWMutex } var ( @@ -34,8 +31,16 @@ var ( notSet = 3 ) +// Files return package's files. +func (p *Package) Files() map[string]*File { + return p.files +} + // IsMain returns if that's the main package. func (p *Package) IsMain() bool { + p.Lock() + defer p.Unlock() + if p.main == trueValue { return true } else if p.main == falseValue { @@ -51,19 +56,41 @@ func (p *Package) IsMain() bool { return false } +// TypesPkg yields information on this package +func (p *Package) TypesPkg() *types.Package { + p.RLock() + defer p.RUnlock() + return p.typesPkg +} + +// TypesInfo yields type information of this package identifiers +func (p *Package) TypesInfo() *types.Info { + p.RLock() + defer p.RUnlock() + return p.typesInfo +} + +// Sortable yields a map of sortable types in this package +func (p *Package) Sortable() map[string]bool { + p.RLock() + defer p.RUnlock() + return p.sortable +} + // TypeCheck performs type checking for given package. func (p *Package) TypeCheck() error { - p.mu.Lock() + p.Lock() + defer p.Unlock() + // If type checking has already been performed // skip it. - if p.TypesInfo != nil || p.TypesPkg != nil { - p.mu.Unlock() + if p.typesInfo != nil || p.typesPkg != nil { return nil } 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), + Importer: importer.Default(), } info := &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), @@ -82,9 +109,9 @@ func (p *Package) TypeCheck() error { // Remember the typechecking info, even if config.Check failed, // since we will get partial information. - p.TypesPkg = typesPkg - p.TypesInfo = info - p.mu.Unlock() + p.typesPkg = typesPkg + p.typesInfo = info + return err } @@ -104,10 +131,10 @@ func check(config *types.Config, n string, fset *token.FileSet, astFiles []*ast. // TypeOf returns the type of an expression. func (p *Package) TypeOf(expr ast.Expr) types.Type { - if p.TypesInfo == nil { + if p.typesInfo == nil { return nil } - return p.TypesInfo.TypeOf(expr) + return p.typesInfo.TypeOf(expr) } type walker struct { @@ -121,7 +148,7 @@ func (w *walker) Visit(n ast.Node) ast.Visitor { return w } // TODO(dsymonds): We could check the signature to be more precise. - recv := receiverType(fn) + recv := typeparams.ReceiverType(fn) if i, ok := w.nmap[fn.Name.Name]; ok { w.has[recv] |= i } @@ -129,7 +156,7 @@ func (w *walker) Visit(n ast.Node) ast.Visitor { } func (p *Package) scanSortable() { - p.Sortable = make(map[string]bool) + p.sortable = make(map[string]bool) // bitfield for which methods exist on each type. const ( @@ -144,24 +171,9 @@ func (p *Package) scanSortable() { } for typ, ms := range has { if ms == Len|Less|Swap { - p.Sortable[typ] = true - } - } -} - -// 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 + p.sortable[typ] = true } } - // The parser accepts much more than just the legal forms. - return "invalid-type" } func (p *Package) lint(rules []Rule, config Config, failures chan Failure) { 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 530e2e9c..414be38c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/add-constant.go +++ b/tools/vendor/github.com/mgechev/revive/rule/add-constant.go @@ -5,6 +5,7 @@ import ( "go/ast" "strconv" "strings" + "sync" "github.com/mgechev/revive/lint" ) @@ -33,53 +34,12 @@ func (wl whiteList) add(kind, list string) { type AddConstantRule struct { whiteList whiteList strLitLimit int + sync.Mutex } // Apply applies the rule to given file. func (r *AddConstantRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { - if r.whiteList == nil { - r.strLitLimit = defaultStrLitLimit - r.whiteList = newWhiteList() - if len(arguments) > 0 { - args, ok := arguments[0].(map[string]interface{}) - if !ok { - panic(fmt.Sprintf("Invalid argument to the add-constant rule. Expecting a k,v map, got %T", arguments[0])) - } - for k, v := range args { - kind := "" - switch k { - case "allowFloats": - kind = kindFLOAT - fallthrough - case "allowInts": - if kind == "" { - kind = kindINT - } - fallthrough - case "allowStrs": - if kind == "" { - kind = kindSTRING - } - list, ok := v.(string) - if !ok { - panic(fmt.Sprintf("Invalid argument to the add-constant rule, string expected. Got '%v' (%T)", v, v)) - } - r.whiteList.add(kind, list) - case "maxLitCount": - sl, ok := v.(string) - if !ok { - panic(fmt.Sprintf("Invalid argument to the add-constant rule, expecting string representation of an integer. Got '%v' (%T)", v, v)) - } - - limit, err := strconv.Atoi(sl) - if err != nil { - panic(fmt.Sprintf("Invalid argument to the add-constant rule, expecting string representation of an integer. Got '%v'", v)) - } - r.strLitLimit = limit - } - } - } - } + r.configure(arguments) var failures []lint.Failure @@ -95,7 +55,7 @@ func (r *AddConstantRule) Apply(file *lint.File, arguments lint.Arguments) []lin } // Name returns the rule name. -func (r *AddConstantRule) Name() string { +func (*AddConstantRule) Name() string { return "add-constant" } @@ -154,3 +114,52 @@ func (w lintAddConstantRule) checkNumLit(kind string, n *ast.BasicLit) { Failure: fmt.Sprintf("avoid magic numbers like '%s', create a named constant for it", n.Value), }) } + +func (r *AddConstantRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() + + if r.whiteList == nil { + r.strLitLimit = defaultStrLitLimit + r.whiteList = newWhiteList() + if len(arguments) > 0 { + args, ok := arguments[0].(map[string]interface{}) + if !ok { + panic(fmt.Sprintf("Invalid argument to the add-constant rule. Expecting a k,v map, got %T", arguments[0])) + } + for k, v := range args { + kind := "" + switch k { + case "allowFloats": + kind = kindFLOAT + fallthrough + case "allowInts": + if kind == "" { + kind = kindINT + } + fallthrough + case "allowStrs": + if kind == "" { + kind = kindSTRING + } + list, ok := v.(string) + if !ok { + panic(fmt.Sprintf("Invalid argument to the add-constant rule, string expected. Got '%v' (%T)", v, v)) + } + r.whiteList.add(kind, list) + case "maxLitCount": + sl, ok := v.(string) + if !ok { + panic(fmt.Sprintf("Invalid argument to the add-constant rule, expecting string representation of an integer. Got '%v' (%T)", v, v)) + } + + limit, err := strconv.Atoi(sl) + if err != nil { + panic(fmt.Sprintf("Invalid argument to the add-constant rule, expecting string representation of an integer. Got '%v'", v)) + } + r.strLitLimit = limit + } + } + } + } +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/argument-limit.go b/tools/vendor/github.com/mgechev/revive/rule/argument-limit.go index b30df3be..8042da15 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/argument-limit.go +++ b/tools/vendor/github.com/mgechev/revive/rule/argument-limit.go @@ -3,6 +3,7 @@ package rule import ( "fmt" "go/ast" + "sync" "github.com/mgechev/revive/lint" ) @@ -10,10 +11,11 @@ import ( // ArgumentsLimitRule lints given else constructs. type ArgumentsLimitRule struct { total int + sync.Mutex } -// Apply applies the rule to given file. -func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *ArgumentsLimitRule) configure(arguments lint.Arguments) { + r.Lock() if r.total == 0 { checkNumberOfArguments(1, arguments, r.Name()) @@ -23,14 +25,21 @@ func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) [] } r.total = int(total) } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure + onFailure := func(failure lint.Failure) { + failures = append(failures, failure) + } walker := lintArgsNum{ - total: r.total, - onFailure: func(failure lint.Failure) { - failures = append(failures, failure) - }, + total: r.total, + onFailure: onFailure, } ast.Walk(walker, file.AST) @@ -39,7 +48,7 @@ func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) [] } // Name returns the rule name. -func (r *ArgumentsLimitRule) Name() string { +func (*ArgumentsLimitRule) Name() string { return "argument-limit" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/atomic.go b/tools/vendor/github.com/mgechev/revive/rule/atomic.go index 572e141d..287b28c2 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/atomic.go +++ b/tools/vendor/github.com/mgechev/revive/rule/atomic.go @@ -12,10 +12,10 @@ import ( type AtomicRule struct{} // Apply applies the rule to given file. -func (r *AtomicRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*AtomicRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure walker := atomic{ - pkgTypesInfo: file.Pkg.TypesInfo, + pkgTypesInfo: file.Pkg.TypesInfo(), onFailure: func(failure lint.Failure) { failures = append(failures, failure) }, @@ -27,7 +27,7 @@ func (r *AtomicRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *AtomicRule) Name() string { +func (*AtomicRule) Name() string { return "atomic" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/banned-characters.go b/tools/vendor/github.com/mgechev/revive/rule/banned-characters.go index 6911574a..76fa2235 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/banned-characters.go +++ b/tools/vendor/github.com/mgechev/revive/rule/banned-characters.go @@ -4,6 +4,7 @@ import ( "fmt" "go/ast" "strings" + "sync" "github.com/mgechev/revive/lint" ) @@ -11,16 +12,23 @@ import ( // BannedCharsRule checks if a file contains banned characters. type BannedCharsRule struct { bannedCharList []string + sync.Mutex } const bannedCharsRuleName = "banned-characters" -// Apply applied the rule to the given file. -func (r *BannedCharsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *BannedCharsRule) configure(arguments lint.Arguments) { + r.Lock() if r.bannedCharList == nil { checkNumberOfArguments(1, arguments, bannedCharsRuleName) r.bannedCharList = r.getBannedCharsList(arguments) } + r.Unlock() +} + +// Apply applied the rule to the given file. +func (r *BannedCharsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -31,12 +39,13 @@ func (r *BannedCharsRule) Apply(file *lint.File, arguments lint.Arguments) []lin bannedChars: r.bannedCharList, onFailure: onFailure, } + ast.Walk(w, file.AST) return failures } // Name returns the rule name -func (r *BannedCharsRule) Name() string { +func (*BannedCharsRule) Name() string { return bannedCharsRuleName } diff --git a/tools/vendor/github.com/mgechev/revive/rule/bare-return.go b/tools/vendor/github.com/mgechev/revive/rule/bare-return.go index b7780cd6..147fa84d 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/bare-return.go +++ b/tools/vendor/github.com/mgechev/revive/rule/bare-return.go @@ -10,7 +10,7 @@ import ( type BareReturnRule struct{} // Apply applies the rule to given file. -func (r *BareReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*BareReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -23,7 +23,7 @@ func (r *BareReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure } // Name returns the rule name. -func (r *BareReturnRule) Name() string { +func (*BareReturnRule) Name() string { return "bare-return" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/blank-imports.go b/tools/vendor/github.com/mgechev/revive/rule/blank-imports.go index be706c36..a3d50b4f 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/blank-imports.go +++ b/tools/vendor/github.com/mgechev/revive/rule/blank-imports.go @@ -11,7 +11,7 @@ import ( type BlankImportsRule struct{} // Name returns the rule name. -func (r *BlankImportsRule) Name() string { +func (*BlankImportsRule) Name() string { return "blank-imports" } @@ -62,7 +62,7 @@ func (r *BlankImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failu return failures } -func (r *BlankImportsRule) fileHasValidEmbedComment(fileAst *ast.File) bool { +func (*BlankImportsRule) fileHasValidEmbedComment(fileAst *ast.File) bool { for _, commentGroup := range fileAst.Comments { for _, comment := range commentGroup.List { if strings.HasPrefix(comment.Text, "//go:embed ") { diff --git a/tools/vendor/github.com/mgechev/revive/rule/bool-literal-in-expr.go b/tools/vendor/github.com/mgechev/revive/rule/bool-literal-in-expr.go index 34710963..d6150339 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/bool-literal-in-expr.go +++ b/tools/vendor/github.com/mgechev/revive/rule/bool-literal-in-expr.go @@ -11,7 +11,7 @@ import ( type BoolLiteralRule struct{} // Apply applies the rule to given file. -func (r *BoolLiteralRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*BoolLiteralRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -26,7 +26,7 @@ func (r *BoolLiteralRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *BoolLiteralRule) Name() string { +func (*BoolLiteralRule) Name() string { return "bool-literal-in-expr" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/call-to-gc.go b/tools/vendor/github.com/mgechev/revive/rule/call-to-gc.go index e3cb3af8..9c68380a 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/call-to-gc.go +++ b/tools/vendor/github.com/mgechev/revive/rule/call-to-gc.go @@ -10,7 +10,7 @@ import ( type CallToGCRule struct{} // Apply applies the rule to given file. -func (r *CallToGCRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*CallToGCRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { failures = append(failures, failure) @@ -27,7 +27,7 @@ func (r *CallToGCRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *CallToGCRule) Name() string { +func (*CallToGCRule) Name() string { return "call-to-gc" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/cognitive-complexity.go b/tools/vendor/github.com/mgechev/revive/rule/cognitive-complexity.go index ed7481fc..a9c11a7d 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/cognitive-complexity.go +++ b/tools/vendor/github.com/mgechev/revive/rule/cognitive-complexity.go @@ -4,6 +4,7 @@ import ( "fmt" "go/ast" "go/token" + "sync" "github.com/mgechev/revive/lint" "golang.org/x/tools/go/ast/astutil" @@ -12,10 +13,11 @@ import ( // CognitiveComplexityRule lints given else constructs. type CognitiveComplexityRule struct { maxComplexity int + sync.Mutex } -// Apply applies the rule to given file. -func (r *CognitiveComplexityRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *CognitiveComplexityRule) configure(arguments lint.Arguments) { + r.Lock() if r.maxComplexity == 0 { checkNumberOfArguments(1, arguments, r.Name()) @@ -25,8 +27,15 @@ func (r *CognitiveComplexityRule) Apply(file *lint.File, arguments lint.Argument } r.maxComplexity = int(complexity) } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *CognitiveComplexityRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure + linter := cognitiveComplexityLinter{ file: file, maxComplexity: r.maxComplexity, @@ -35,13 +44,13 @@ func (r *CognitiveComplexityRule) Apply(file *lint.File, arguments lint.Argument }, } - linter.lint() + linter.lintCognitiveComplexity() return failures } // Name returns the rule name. -func (r *CognitiveComplexityRule) Name() string { +func (*CognitiveComplexityRule) Name() string { return "cognitive-complexity" } @@ -51,7 +60,7 @@ type cognitiveComplexityLinter struct { onFailure func(lint.Failure) } -func (w cognitiveComplexityLinter) lint() { +func (w cognitiveComplexityLinter) lintCognitiveComplexity() { f := w.file for _, decl := range f.AST.Decls { if fn, ok := decl.(*ast.FuncDecl); ok && fn.Body != nil { 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 9cd3a18a..34cdb907 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/confusing-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/confusing-naming.go @@ -48,7 +48,7 @@ var allPkgs = packages{pkgs: make([]pkgMethods, 1)} type ConfusingNamingRule struct{} // Apply applies the rule to given file. -func (r *ConfusingNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ConfusingNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST pkgm := allPkgs.methodNames(file.Pkg) @@ -66,7 +66,7 @@ func (r *ConfusingNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } // Name returns the rule name. -func (r *ConfusingNamingRule) Name() string { +func (*ConfusingNamingRule) Name() string { return "confusing-naming" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/confusing-results.go b/tools/vendor/github.com/mgechev/revive/rule/confusing-results.go index 1d386b3d..1b79ada9 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/confusing-results.go +++ b/tools/vendor/github.com/mgechev/revive/rule/confusing-results.go @@ -10,7 +10,7 @@ import ( type ConfusingResultsRule struct{} // Apply applies the rule to given file. -func (r *ConfusingResultsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ConfusingResultsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -26,7 +26,7 @@ func (r *ConfusingResultsRule) Apply(file *lint.File, _ lint.Arguments) []lint.F } // Name returns the rule name. -func (r *ConfusingResultsRule) Name() string { +func (*ConfusingResultsRule) Name() string { return "confusing-results" } @@ -60,7 +60,6 @@ func (w lintConfusingResults) Visit(n ast.Node) ast.Visitor { break } lastType = t.Name - } return w 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 ba15412e..9abc95d6 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 @@ -25,7 +25,7 @@ func (r *ConstantLogicalExprRule) Apply(file *lint.File, _ lint.Arguments) []lin } // Name returns the rule name. -func (r *ConstantLogicalExprRule) Name() string { +func (*ConstantLogicalExprRule) Name() string { return "constant-logical-expr" } 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 09426298..3c400065 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 @@ -4,6 +4,7 @@ import ( "fmt" "go/ast" "strings" + "sync" "github.com/mgechev/revive/lint" ) @@ -11,21 +12,26 @@ import ( // ContextAsArgumentRule lints given else constructs. type ContextAsArgumentRule struct { allowTypesLUT map[string]struct{} + sync.Mutex } // Apply applies the rule to given file. func (r *ContextAsArgumentRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure { + r.Lock() if r.allowTypesLUT == nil { r.allowTypesLUT = getAllowTypesFromArguments(args) } + r.Unlock() var failures []lint.Failure + r.Lock() walker := lintContextArguments{ allowTypesLUT: r.allowTypesLUT, onFailure: func(failure lint.Failure) { failures = append(failures, failure) }, } + r.Unlock() ast.Walk(walker, file.AST) @@ -33,7 +39,7 @@ func (r *ContextAsArgumentRule) Apply(file *lint.File, args lint.Arguments) []li } // Name returns the rule name. -func (r *ContextAsArgumentRule) Name() string { +func (*ContextAsArgumentRule) Name() string { return "context-as-argument" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/context-keys-type.go b/tools/vendor/github.com/mgechev/revive/rule/context-keys-type.go index 9c2f0bbd..60ccec56 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/context-keys-type.go +++ b/tools/vendor/github.com/mgechev/revive/rule/context-keys-type.go @@ -12,7 +12,7 @@ import ( type ContextKeysType struct{} // Apply applies the rule to given file. -func (r *ContextKeysType) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ContextKeysType) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -31,7 +31,7 @@ func (r *ContextKeysType) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *ContextKeysType) Name() string { +func (*ContextKeysType) Name() string { return "context-keys-type" } @@ -68,7 +68,7 @@ func checkContextKeyType(w lintContextKeyTypes, x *ast.CallExpr) { if len(x.Args) != 3 { return } - key := f.Pkg.TypesInfo.Types[x.Args[1]] + key := f.Pkg.TypesInfo().Types[x.Args[1]] if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid { w.onFailure(lint.Failure{ diff --git a/tools/vendor/github.com/mgechev/revive/rule/cyclomatic.go b/tools/vendor/github.com/mgechev/revive/rule/cyclomatic.go index bdda5f59..afd41818 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/cyclomatic.go +++ b/tools/vendor/github.com/mgechev/revive/rule/cyclomatic.go @@ -4,6 +4,7 @@ import ( "fmt" "go/ast" "go/token" + "sync" "github.com/mgechev/revive/lint" ) @@ -13,10 +14,11 @@ import ( // CyclomaticRule lints given else constructs. type CyclomaticRule struct { maxComplexity int + sync.Mutex } -// Apply applies the rule to given file. -func (r *CyclomaticRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *CyclomaticRule) configure(arguments lint.Arguments) { + r.Lock() if r.maxComplexity == 0 { checkNumberOfArguments(1, arguments, r.Name()) @@ -26,9 +28,16 @@ func (r *CyclomaticRule) Apply(file *lint.File, arguments lint.Arguments) []lint } r.maxComplexity = int(complexity) } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *CyclomaticRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure fileAst := file.AST + walker := lintCyclomatic{ file: file, complexity: r.maxComplexity, @@ -43,7 +52,7 @@ func (r *CyclomaticRule) Apply(file *lint.File, arguments lint.Arguments) []lint } // Name returns the rule name. -func (r *CyclomaticRule) Name() string { +func (*CyclomaticRule) Name() string { return "cyclomatic" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/datarace.go b/tools/vendor/github.com/mgechev/revive/rule/datarace.go new file mode 100644 index 00000000..26fcadcd --- /dev/null +++ b/tools/vendor/github.com/mgechev/revive/rule/datarace.go @@ -0,0 +1,142 @@ +package rule + +import ( + "fmt" + "go/ast" + + "github.com/mgechev/revive/lint" +) + +// DataRaceRule lints assignments to value method-receivers. +type DataRaceRule struct{} + +// Apply applies the rule to given file. +func (*DataRaceRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { + var failures []lint.Failure + onFailure := func(failure lint.Failure) { + failures = append(failures, failure) + } + w := lintDataRaces{onFailure: onFailure} + + ast.Walk(w, file.AST) + + return failures +} + +// Name returns the rule name. +func (*DataRaceRule) Name() string { + return "datarace" +} + +type lintDataRaces struct { + onFailure func(failure lint.Failure) +} + +func (w lintDataRaces) Visit(n ast.Node) ast.Visitor { + node, ok := n.(*ast.FuncDecl) + if !ok { + return w // not function declaration + } + if node.Body == nil { + return nil // empty body + } + + results := node.Type.Results + + returnIDs := map[*ast.Object]struct{}{} + if results != nil { + returnIDs = w.ExtractReturnIDs(results.List) + } + fl := &lintFunctionForDataRaces{onFailure: w.onFailure, returnIDs: returnIDs, rangeIDs: map[*ast.Object]struct{}{}} + ast.Walk(fl, node.Body) + + return nil +} + +func (w lintDataRaces) ExtractReturnIDs(fields []*ast.Field) map[*ast.Object]struct{} { + r := map[*ast.Object]struct{}{} + for _, f := range fields { + for _, id := range f.Names { + r[id.Obj] = struct{}{} + } + } + + return r +} + +type lintFunctionForDataRaces struct { + _ struct{} + onFailure func(failure lint.Failure) + returnIDs map[*ast.Object]struct{} + rangeIDs map[*ast.Object]struct{} +} + +func (w lintFunctionForDataRaces) Visit(node ast.Node) ast.Visitor { + switch n := node.(type) { + case *ast.RangeStmt: + if n.Body == nil { + return nil + } + + getIds := func(exprs ...ast.Expr) []*ast.Ident { + r := []*ast.Ident{} + for _, expr := range exprs { + if id, ok := expr.(*ast.Ident); ok { + r = append(r, id) + } + } + return r + } + + ids := getIds(n.Key, n.Value) + for _, id := range ids { + w.rangeIDs[id.Obj] = struct{}{} + } + + ast.Walk(w, n.Body) + + for _, id := range ids { + delete(w.rangeIDs, id.Obj) + } + + return nil // do not visit the body of the range, it has been already visited + case *ast.GoStmt: + f := n.Call.Fun + funcLit, ok := f.(*ast.FuncLit) + if !ok { + return nil + } + selectIDs := func(n ast.Node) bool { + _, ok := n.(*ast.Ident) + return ok + } + + ids := pick(funcLit.Body, selectIDs, nil) + for _, id := range ids { + id := id.(*ast.Ident) + _, isRangeID := w.rangeIDs[id.Obj] + _, isReturnID := w.returnIDs[id.Obj] + + switch { + case isRangeID: + w.onFailure(lint.Failure{ + Confidence: 1, + Node: id, + Category: "logic", + Failure: fmt.Sprintf("datarace: range value %s is captured (by-reference) in goroutine", id.Name), + }) + case isReturnID: + w.onFailure(lint.Failure{ + Confidence: 0.8, + Node: id, + Category: "logic", + Failure: fmt.Sprintf("potential datarace: return value %s is captured (by-reference) in goroutine", id.Name), + }) + } + } + + return nil + } + + return w +} diff --git a/tools/vendor/github.com/mgechev/revive/rule/deep-exit.go b/tools/vendor/github.com/mgechev/revive/rule/deep-exit.go index cfc8fc57..918d4294 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/deep-exit.go +++ b/tools/vendor/github.com/mgechev/revive/rule/deep-exit.go @@ -11,7 +11,7 @@ import ( type DeepExitRule struct{} // Apply applies the rule to given file. -func (r *DeepExitRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*DeepExitRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { failures = append(failures, failure) @@ -36,7 +36,7 @@ func (r *DeepExitRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *DeepExitRule) Name() string { +func (*DeepExitRule) Name() string { return "deep-exit" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/defer.go b/tools/vendor/github.com/mgechev/revive/rule/defer.go index 4b62f34e..f8224fd4 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/defer.go +++ b/tools/vendor/github.com/mgechev/revive/rule/defer.go @@ -3,6 +3,7 @@ package rule import ( "fmt" "go/ast" + "sync" "github.com/mgechev/revive/lint" ) @@ -10,18 +11,25 @@ import ( // DeferRule lints unused params in functions. type DeferRule struct { allow map[string]bool + sync.Mutex } -// Apply applies the rule to given file. -func (r *DeferRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *DeferRule) configure(arguments lint.Arguments) { + r.Lock() if r.allow == nil { r.allow = r.allowFromArgs(arguments) } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *DeferRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + var failures []lint.Failure onFailure := func(failure lint.Failure) { failures = append(failures, failure) } - w := lintDeferRule{onFailure: onFailure, allow: r.allow} ast.Walk(w, file.AST) @@ -30,18 +38,19 @@ func (r *DeferRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Fail } // Name returns the rule name. -func (r *DeferRule) Name() string { +func (*DeferRule) Name() string { return "defer" } -func (r *DeferRule) allowFromArgs(args lint.Arguments) map[string]bool { +func (*DeferRule) allowFromArgs(args lint.Arguments) map[string]bool { if len(args) < 1 { allow := map[string]bool{ - "loop": true, - "call-chain": true, - "method-call": true, - "return": true, - "recover": true, + "loop": true, + "call-chain": true, + "method-call": true, + "return": true, + "recover": true, + "immediate-recover": true, } return allow @@ -89,11 +98,29 @@ func (w lintDeferRule) Visit(node ast.Node) ast.Visitor { } case *ast.CallExpr: if !w.inADefer && isIdent(n.Fun, "recover") { + // func fn() { recover() } + // // confidence is not 1 because recover can be in a function that is deferred elsewhere w.newFailure("recover must be called inside a deferred function", n, 0.8, "logic", "recover") + } else if w.inADefer && !w.inAFuncLit && isIdent(n.Fun, "recover") { + // defer helper(recover()) + // + // confidence is not truly 1 because this could be in a correctly-deferred func, + // but it is very likely to be a misunderstanding of defer's behavior around arguments. + w.newFailure("recover must be called inside a deferred function, this is executing recover immediately", n, 1, "logic", "immediate-recover") } case *ast.DeferStmt: + if isIdent(n.Call.Fun, "recover") { + // defer recover() + // + // confidence is not truly 1 because this could be in a correctly-deferred func, + // but normally this doesn't suppress a panic, and even if it did it would silently discard the value. + w.newFailure("recover must be called inside a deferred function, this is executing recover immediately", n, 1, "logic", "immediate-recover") + } w.visitSubtree(n.Call.Fun, true, false, false) + for _, a := range n.Call.Args { + w.visitSubtree(a, true, false, false) // check arguments, they should not contain recover() + } if w.inALoop { w.newFailure("prefer not to defer inside loops", n, 1.0, "bad practice", "loop") @@ -117,7 +144,7 @@ func (w lintDeferRule) Visit(node ast.Node) ast.Visitor { } func (w lintDeferRule) visitSubtree(n ast.Node, inADefer, inALoop, inAFuncLit bool) { - nw := &lintDeferRule{ + nw := lintDeferRule{ onFailure: w.onFailure, inADefer: inADefer, inALoop: inALoop, 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 78419d7d..25ff526c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/dot-imports.go +++ b/tools/vendor/github.com/mgechev/revive/rule/dot-imports.go @@ -10,7 +10,7 @@ import ( type DotImportsRule struct{} // Apply applies the rule to given file. -func (r *DotImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*DotImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -28,7 +28,7 @@ func (r *DotImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure } // Name returns the rule name. -func (r *DotImportsRule) Name() string { +func (*DotImportsRule) Name() string { return "dot-imports" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/duplicated-imports.go b/tools/vendor/github.com/mgechev/revive/rule/duplicated-imports.go index 485b6a2e..2b177fac 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/duplicated-imports.go +++ b/tools/vendor/github.com/mgechev/revive/rule/duplicated-imports.go @@ -10,7 +10,7 @@ import ( type DuplicatedImportsRule struct{} // Apply applies the rule to given file. -func (r *DuplicatedImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*DuplicatedImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure impPaths := map[string]struct{}{} @@ -34,6 +34,6 @@ func (r *DuplicatedImportsRule) Apply(file *lint.File, _ lint.Arguments) []lint. } // Name returns the rule name. -func (r *DuplicatedImportsRule) Name() string { +func (*DuplicatedImportsRule) Name() string { return "duplicated-imports" } 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 ffb568a8..bfbf6717 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/early-return.go +++ b/tools/vendor/github.com/mgechev/revive/rule/early-return.go @@ -10,7 +10,7 @@ import ( type EarlyReturnRule struct{} // Apply applies the rule to given file. -func (r *EarlyReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*EarlyReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -23,7 +23,7 @@ func (r *EarlyReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *EarlyReturnRule) Name() string { +func (*EarlyReturnRule) Name() string { return "early-return" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/empty-block.go b/tools/vendor/github.com/mgechev/revive/rule/empty-block.go index e505fde6..8a4a0fef 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/empty-block.go +++ b/tools/vendor/github.com/mgechev/revive/rule/empty-block.go @@ -10,7 +10,7 @@ import ( type EmptyBlockRule struct{} // Apply applies the rule to given file. -func (r *EmptyBlockRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*EmptyBlockRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -23,7 +23,7 @@ func (r *EmptyBlockRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure } // Name returns the rule name. -func (r *EmptyBlockRule) Name() string { +func (*EmptyBlockRule) Name() string { return "empty-block" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/empty-lines.go b/tools/vendor/github.com/mgechev/revive/rule/empty-lines.go index 61d9281b..12866072 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/empty-lines.go +++ b/tools/vendor/github.com/mgechev/revive/rule/empty-lines.go @@ -18,25 +18,25 @@ func (r *EmptyLinesRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure failures = append(failures, failure) } - w := lintEmptyLines{file, file.CommentMap(), onFailure} + w := lintEmptyLines{file, r.commentLines(file.CommentMap(), file), onFailure} ast.Walk(w, file.AST) return failures } // Name returns the rule name. -func (r *EmptyLinesRule) Name() string { +func (*EmptyLinesRule) Name() string { return "empty-lines" } type lintEmptyLines struct { file *lint.File - cmap ast.CommentMap + cmap map[int]struct{} onFailure func(lint.Failure) } func (w lintEmptyLines) Visit(node ast.Node) ast.Visitor { block, ok := node.(*ast.BlockStmt) - if !ok { + if !ok || len(block.List) == 0 { return w } @@ -47,67 +47,59 @@ func (w lintEmptyLines) Visit(node ast.Node) ast.Visitor { } func (w lintEmptyLines) checkStart(block *ast.BlockStmt) { - if len(block.List) == 0 { - return - } - - start := w.position(block.Lbrace) + blockStart := w.position(block.Lbrace) firstNode := block.List[0] + firstStmt := w.position(firstNode.Pos()) - if w.commentBetween(start, firstNode) { + firstBlockLineIsStmt := firstStmt.Line-(blockStart.Line+1) == 0 + _, firstBlockLineIsComment := w.cmap[blockStart.Line+1] + if firstBlockLineIsStmt || firstBlockLineIsComment { return } - first := w.position(firstNode.Pos()) - if first.Line-start.Line > 1 { - w.onFailure(lint.Failure{ - Confidence: 1, - Node: block, - Category: "style", - Failure: "extra empty line at the start of a block", - }) - } + w.onFailure(lint.Failure{ + Confidence: 1, + Node: block, + Category: "style", + Failure: "extra empty line at the start of a block", + }) } func (w lintEmptyLines) checkEnd(block *ast.BlockStmt) { - if len(block.List) < 1 { - return - } - - end := w.position(block.Rbrace) + blockEnd := w.position(block.Rbrace) lastNode := block.List[len(block.List)-1] + lastStmt := w.position(lastNode.End()) - if w.commentBetween(end, lastNode) { + lastBlockLineIsStmt := (blockEnd.Line-1)-lastStmt.Line == 0 + _, lastBlockLineIsComment := w.cmap[blockEnd.Line-1] + if lastBlockLineIsStmt || lastBlockLineIsComment { return } - last := w.position(lastNode.End()) - if end.Line-last.Line > 1 { - w.onFailure(lint.Failure{ - Confidence: 1, - Node: lastNode, - Category: "style", - Failure: "extra empty line at the end of a block", - }) - } + w.onFailure(lint.Failure{ + Confidence: 1, + Node: block, + Category: "style", + Failure: "extra empty line at the end of a block", + }) } -func (w lintEmptyLines) commentBetween(position token.Position, node ast.Node) bool { - comments := w.cmap.Filter(node).Comments() - if len(comments) == 0 { - return false - } +func (w lintEmptyLines) position(pos token.Pos) token.Position { + return w.file.ToPosition(pos) +} + +func (*EmptyLinesRule) commentLines(cmap ast.CommentMap, file *lint.File) map[int]struct{} { + result := map[int]struct{}{} - for _, comment := range comments { - start, end := w.position(comment.Pos()), w.position(comment.End()) - if start.Line-position.Line == 1 || position.Line-end.Line == 1 { - return true + for _, comments := range cmap { + for _, comment := range comments { + start := file.ToPosition(comment.Pos()) + end := file.ToPosition(comment.End()) + for i := start.Line; i <= end.Line; i++ { + result[i] = struct{}{} + } } } - return false -} - -func (w lintEmptyLines) position(pos token.Pos) token.Position { - return w.file.ToPosition(pos) + return result } diff --git a/tools/vendor/github.com/mgechev/revive/rule/error-naming.go b/tools/vendor/github.com/mgechev/revive/rule/error-naming.go index 3a108062..a4f24f3f 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/error-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/error-naming.go @@ -13,7 +13,7 @@ import ( type ErrorNamingRule struct{} // Apply applies the rule to given file. -func (r *ErrorNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ErrorNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -31,7 +31,7 @@ func (r *ErrorNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *ErrorNamingRule) Name() string { +func (*ErrorNamingRule) Name() string { return "error-naming" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/error-return.go b/tools/vendor/github.com/mgechev/revive/rule/error-return.go index 737d8c66..a724e001 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/error-return.go +++ b/tools/vendor/github.com/mgechev/revive/rule/error-return.go @@ -10,7 +10,7 @@ import ( type ErrorReturnRule struct{} // Apply applies the rule to given file. -func (r *ErrorReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ErrorReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -28,7 +28,7 @@ func (r *ErrorReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *ErrorReturnRule) Name() string { +func (*ErrorReturnRule) Name() string { return "error-return" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/error-strings.go b/tools/vendor/github.com/mgechev/revive/rule/error-strings.go index 8d630dc6..81ebda54 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/error-strings.go +++ b/tools/vendor/github.com/mgechev/revive/rule/error-strings.go @@ -4,6 +4,8 @@ import ( "go/ast" "go/token" "strconv" + "strings" + "sync" "unicode" "unicode/utf8" @@ -11,13 +13,20 @@ import ( ) // ErrorStringsRule lints given else constructs. -type ErrorStringsRule struct{} +type ErrorStringsRule struct { + errorFunctions map[string]map[string]struct{} + sync.Mutex +} -// Apply applies the rule to given file. -func (r *ErrorStringsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { - var failures []lint.Failure +func (r *ErrorStringsRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() - errorFunctions := map[string]map[string]struct{}{ + if r.errorFunctions != nil { + return + } + + r.errorFunctions = map[string]map[string]struct{}{ "fmt": { "Errorf": {}, }, @@ -31,11 +40,33 @@ func (r *ErrorStringsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failu }, } + var invalidCustomFunctions []string + for _, argument := range arguments { + if functionName, ok := argument.(string); ok { + fields := strings.Split(strings.TrimSpace(functionName), ".") + if len(fields) != 2 || len(fields[0]) == 0 || len(fields[1]) == 0 { + invalidCustomFunctions = append(invalidCustomFunctions, functionName) + continue + } + r.errorFunctions[fields[0]] = map[string]struct{}{fields[1]: {}} + } + } + if len(invalidCustomFunctions) != 0 { + panic("found invalid custom function: " + strings.Join(invalidCustomFunctions, ",")) + } +} + +// Apply applies the rule to given file. +func (r *ErrorStringsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + var failures []lint.Failure + + r.configure(arguments) + fileAst := file.AST walker := lintErrorStrings{ file: file, fileAst: fileAst, - errorFunctions: errorFunctions, + errorFunctions: r.errorFunctions, onFailure: func(failure lint.Failure) { failures = append(failures, failure) }, @@ -47,7 +78,7 @@ func (r *ErrorStringsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failu } // Name returns the rule name. -func (r *ErrorStringsRule) Name() string { +func (*ErrorStringsRule) Name() string { return "error-strings" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/errorf.go b/tools/vendor/github.com/mgechev/revive/rule/errorf.go index 1bffbab5..1588a745 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/errorf.go +++ b/tools/vendor/github.com/mgechev/revive/rule/errorf.go @@ -13,7 +13,7 @@ import ( type ErrorfRule struct{} // Apply applies the rule to given file. -func (r *ErrorfRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ErrorfRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -32,7 +32,7 @@ func (r *ErrorfRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *ErrorfRule) Name() string { +func (*ErrorfRule) Name() string { return "errorf" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/exported.go b/tools/vendor/github.com/mgechev/revive/rule/exported.go index 621fae54..b8663c48 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/exported.go +++ b/tools/vendor/github.com/mgechev/revive/rule/exported.go @@ -5,9 +5,11 @@ import ( "go/ast" "go/token" "strings" + "sync" "unicode" "unicode/utf8" + "github.com/mgechev/revive/internal/typeparams" "github.com/mgechev/revive/lint" ) @@ -17,19 +19,14 @@ type ExportedRule struct { checkPrivateReceivers bool disableStutteringCheck bool stuttersMsg string + sync.Mutex } -// Apply applies the rule to given file. -func (r *ExportedRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure { - var failures []lint.Failure - - if file.IsTest() { - return failures - } - +func (r *ExportedRule) configure(arguments lint.Arguments) { + r.Lock() if !r.configured { var sayRepetitiveInsteadOfStutters bool - r.checkPrivateReceivers, r.disableStutteringCheck, sayRepetitiveInsteadOfStutters = r.getConf(args) + r.checkPrivateReceivers, r.disableStutteringCheck, sayRepetitiveInsteadOfStutters = r.getConf(arguments) r.stuttersMsg = "stutters" if sayRepetitiveInsteadOfStutters { r.stuttersMsg = "is repetitive" @@ -37,8 +34,20 @@ func (r *ExportedRule) Apply(file *lint.File, args lint.Arguments) []lint.Failur r.configured = true } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *ExportedRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure { + r.configure(args) + + var failures []lint.Failure + if file.IsTest() { + return failures + } fileAst := file.AST + walker := lintExported{ file: file, fileAst: fileAst, @@ -57,7 +66,7 @@ func (r *ExportedRule) Apply(file *lint.File, args lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *ExportedRule) Name() string { +func (*ExportedRule) Name() string { return "exported" } @@ -108,7 +117,7 @@ func (w *lintExported) lintFuncDoc(fn *ast.FuncDecl) { if fn.Recv != nil && len(fn.Recv.List) > 0 { // method kind = "method" - recv := receiverType(fn) + recv := typeparams.ReceiverType(fn) if !w.checkPrivateReceivers && !ast.IsExported(recv) { // receiver is unexported return @@ -118,7 +127,8 @@ func (w *lintExported) lintFuncDoc(fn *ast.FuncDecl) { } switch name { case "Len", "Less", "Swap": - if w.file.Pkg.Sortable[recv] { + sortables := w.file.Pkg.Sortable() + if sortables[recv] { return } } @@ -241,7 +251,7 @@ func (w *lintExported) lintValueSpecDoc(vs *ast.ValueSpec, gd *ast.GenDecl, genD return } - if vs.Doc == nil && gd.Doc == nil { + if vs.Doc == nil && vs.Comment == nil && gd.Doc == nil { if genDeclMissingComments[gd] { return } @@ -264,10 +274,16 @@ func (w *lintExported) lintValueSpecDoc(vs *ast.ValueSpec, gd *ast.GenDecl, genD } // The relevant text to check will be on either vs.Doc or gd.Doc. // Use vs.Doc preferentially. - doc := vs.Doc - if doc == nil { + var doc *ast.CommentGroup + switch { + case vs.Doc != nil: + doc = vs.Doc + case vs.Comment != nil && gd.Doc == nil: + doc = vs.Comment + default: doc = gd.Doc } + prefix := name + " " s := normalizeText(doc.Text()) if !strings.HasPrefix(s, prefix) { diff --git a/tools/vendor/github.com/mgechev/revive/rule/file-header.go b/tools/vendor/github.com/mgechev/revive/rule/file-header.go index 17fd9ff5..76f548f5 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/file-header.go +++ b/tools/vendor/github.com/mgechev/revive/rule/file-header.go @@ -3,6 +3,7 @@ package rule import ( "fmt" "regexp" + "sync" "github.com/mgechev/revive/lint" ) @@ -10,15 +11,16 @@ import ( // FileHeaderRule lints given else constructs. type FileHeaderRule struct { header string + sync.Mutex } var ( - multiRegexp = regexp.MustCompile("^/\\*") + multiRegexp = regexp.MustCompile(`^/\*`) singleRegexp = regexp.MustCompile("^//") ) -// Apply applies the rule to given file. -func (r *FileHeaderRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *FileHeaderRule) configure(arguments lint.Arguments) { + r.Lock() if r.header == "" { checkNumberOfArguments(1, arguments, r.Name()) var ok bool @@ -27,6 +29,12 @@ func (r *FileHeaderRule) Apply(file *lint.File, arguments lint.Arguments) []lint panic(fmt.Sprintf("invalid argument for \"file-header\" rule: first argument should be a string, got %T", arguments[0])) } } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *FileHeaderRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) failure := []lint.Failure{ { @@ -67,6 +75,6 @@ func (r *FileHeaderRule) Apply(file *lint.File, arguments lint.Arguments) []lint } // Name returns the rule name. -func (r *FileHeaderRule) Name() string { +func (*FileHeaderRule) Name() string { return "file-header" } 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 0cc2208c..19a05f9f 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/flag-param.go +++ b/tools/vendor/github.com/mgechev/revive/rule/flag-param.go @@ -11,7 +11,7 @@ import ( type FlagParamRule struct{} // Apply applies the rule to given file. -func (r *FlagParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*FlagParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -24,7 +24,7 @@ func (r *FlagParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure } // Name returns the rule name. -func (r *FlagParamRule) Name() string { +func (*FlagParamRule) Name() string { return "flag-parameter" } 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 b213cc4f..717ddbf7 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/function-length.go +++ b/tools/vendor/github.com/mgechev/revive/rule/function-length.go @@ -4,6 +4,7 @@ import ( "fmt" "go/ast" "reflect" + "sync" "github.com/mgechev/revive/lint" ) @@ -12,15 +13,22 @@ import ( type FunctionLength struct { maxStmt int maxLines int + sync.Mutex } -// Apply applies the rule to given file. -func (r *FunctionLength) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *FunctionLength) configure(arguments lint.Arguments) { + r.Lock() if r.maxLines == 0 { maxStmt, maxLines := r.parseArguments(arguments) r.maxStmt = int(maxStmt) r.maxLines = int(maxLines) } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *FunctionLength) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure @@ -39,11 +47,11 @@ func (r *FunctionLength) Apply(file *lint.File, arguments lint.Arguments) []lint } // Name returns the rule name. -func (r *FunctionLength) Name() string { +func (*FunctionLength) Name() string { return "function-length" } -func (r *FunctionLength) parseArguments(arguments lint.Arguments) (maxStmt, maxLines int64) { +func (*FunctionLength) parseArguments(arguments lint.Arguments) (maxStmt, maxLines int64) { if len(arguments) != 2 { panic(fmt.Sprintf(`invalid configuration for "function-length" rule, expected 2 arguments but got %d`, len(arguments))) } @@ -64,7 +72,7 @@ func (r *FunctionLength) parseArguments(arguments lint.Arguments) (maxStmt, maxL panic(fmt.Sprintf(`the configuration value for max statements in "function-length" rule cannot be negative, got %d`, maxLines)) } - return + return maxStmt, maxLines } type lintFuncLength struct { diff --git a/tools/vendor/github.com/mgechev/revive/rule/function-result-limit.go b/tools/vendor/github.com/mgechev/revive/rule/function-result-limit.go index 5f715ddc..5d2b8731 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/function-result-limit.go +++ b/tools/vendor/github.com/mgechev/revive/rule/function-result-limit.go @@ -3,6 +3,7 @@ package rule import ( "fmt" "go/ast" + "sync" "github.com/mgechev/revive/lint" ) @@ -10,10 +11,11 @@ import ( // FunctionResultsLimitRule lints given else constructs. type FunctionResultsLimitRule struct { max int + sync.Mutex } -// Apply applies the rule to given file. -func (r *FunctionResultsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *FunctionResultsLimitRule) configure(arguments lint.Arguments) { + r.Lock() if r.max == 0 { checkNumberOfArguments(1, arguments, r.Name()) @@ -26,6 +28,12 @@ func (r *FunctionResultsLimitRule) Apply(file *lint.File, arguments lint.Argumen } r.max = int(max) } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *FunctionResultsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure @@ -42,7 +50,7 @@ func (r *FunctionResultsLimitRule) Apply(file *lint.File, arguments lint.Argumen } // Name returns the rule name. -func (r *FunctionResultsLimitRule) Name() string { +func (*FunctionResultsLimitRule) Name() string { return "function-result-limit" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/get-return.go b/tools/vendor/github.com/mgechev/revive/rule/get-return.go index 494ab666..600a40fa 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/get-return.go +++ b/tools/vendor/github.com/mgechev/revive/rule/get-return.go @@ -12,7 +12,7 @@ import ( type GetReturnRule struct{} // Apply applies the rule to given file. -func (r *GetReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*GetReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -25,7 +25,7 @@ func (r *GetReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure } // Name returns the rule name. -func (r *GetReturnRule) Name() string { +func (*GetReturnRule) Name() string { return "get-return" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/identical-branches.go b/tools/vendor/github.com/mgechev/revive/rule/identical-branches.go index 094a7914..b1a69097 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/identical-branches.go +++ b/tools/vendor/github.com/mgechev/revive/rule/identical-branches.go @@ -10,7 +10,7 @@ import ( type IdenticalBranchesRule struct{} // Apply applies the rule to given file. -func (r *IdenticalBranchesRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*IdenticalBranchesRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -24,7 +24,7 @@ func (r *IdenticalBranchesRule) Apply(file *lint.File, _ lint.Arguments) []lint. } // Name returns the rule name. -func (r *IdenticalBranchesRule) Name() string { +func (*IdenticalBranchesRule) Name() string { return "identical-branches" } @@ -57,7 +57,7 @@ func (w *lintIdenticalBranches) Visit(node ast.Node) ast.Visitor { return w } -func (w *lintIdenticalBranches) identicalBranches(branches []*ast.BlockStmt) bool { +func (lintIdenticalBranches) identicalBranches(branches []*ast.BlockStmt) bool { if len(branches) < 2 { return false } diff --git a/tools/vendor/github.com/mgechev/revive/rule/if-return.go b/tools/vendor/github.com/mgechev/revive/rule/if-return.go index c275d276..a6a3113a 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/if-return.go +++ b/tools/vendor/github.com/mgechev/revive/rule/if-return.go @@ -12,7 +12,7 @@ import ( type IfReturnRule struct{} // Apply applies the rule to given file. -func (r *IfReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*IfReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -26,7 +26,7 @@ func (r *IfReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *IfReturnRule) Name() string { +func (*IfReturnRule) Name() string { return "if-return" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/import-shadowing.go b/tools/vendor/github.com/mgechev/revive/rule/import-shadowing.go index 7b34c90f..2bab704d 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/import-shadowing.go +++ b/tools/vendor/github.com/mgechev/revive/rule/import-shadowing.go @@ -13,7 +13,7 @@ import ( type ImportShadowingRule struct{} // Apply applies the rule to given file. -func (r *ImportShadowingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ImportShadowingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure importNames := map[string]struct{}{} @@ -37,7 +37,7 @@ func (r *ImportShadowingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } // Name returns the rule name. -func (r *ImportShadowingRule) Name() string { +func (*ImportShadowingRule) Name() string { return "import-shadowing" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/imports-blacklist.go b/tools/vendor/github.com/mgechev/revive/rule/imports-blacklist.go index 68beb73a..71066281 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/imports-blacklist.go +++ b/tools/vendor/github.com/mgechev/revive/rule/imports-blacklist.go @@ -2,42 +2,63 @@ package rule import ( "fmt" + "regexp" + "sync" "github.com/mgechev/revive/lint" ) // ImportsBlacklistRule lints given else constructs. type ImportsBlacklistRule struct { - blacklist map[string]bool + blacklist []*regexp.Regexp + sync.Mutex } -// Apply applies the rule to given file. -func (r *ImportsBlacklistRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { - var failures []lint.Failure +var replaceRegexp = regexp.MustCompile(`/?\*\*/?`) - if file.IsTest() { - return failures // skip, test file - } +func (r *ImportsBlacklistRule) configure(arguments lint.Arguments) { + r.Lock() + defer r.Unlock() if r.blacklist == nil { - r.blacklist = make(map[string]bool, len(arguments)) + r.blacklist = 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)) } - // we add quotes if not present, because when parsed, the value of the AST node, will be quoted - if len(argStr) > 2 && argStr[0] != '"' && argStr[len(argStr)-1] != '"' { - argStr = fmt.Sprintf(`%q`, argStr) + regStr, err := regexp.Compile(fmt.Sprintf(`(?m)"%s"$`, replaceRegexp.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)) } - r.blacklist[argStr] = true + r.blacklist = append(r.blacklist, regStr) + } + } +} + +func (r *ImportsBlacklistRule) isBlacklisted(path string) bool { + for _, regex := range r.blacklist { + if regex.MatchString(path) { + return true } } + return false +} + +// Apply applies the rule to given file. +func (r *ImportsBlacklistRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + + var failures []lint.Failure + + if file.IsTest() { + return failures // skip, test file + } for _, is := range file.AST.Imports { path := is.Path - if path != nil && r.blacklist[path.Value] { + if path != nil && r.isBlacklisted(path.Value) { failures = append(failures, lint.Failure{ Confidence: 1, Failure: "should not use the following blacklisted import: " + path.Value, @@ -51,6 +72,6 @@ func (r *ImportsBlacklistRule) Apply(file *lint.File, arguments lint.Arguments) } // Name returns the rule name. -func (r *ImportsBlacklistRule) Name() string { +func (*ImportsBlacklistRule) Name() string { return "imports-blacklist" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/increment-decrement.go b/tools/vendor/github.com/mgechev/revive/rule/increment-decrement.go index 5d6b1767..34a8e1ec 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/increment-decrement.go +++ b/tools/vendor/github.com/mgechev/revive/rule/increment-decrement.go @@ -12,7 +12,7 @@ import ( type IncrementDecrementRule struct{} // Apply applies the rule to given file. -func (r *IncrementDecrementRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*IncrementDecrementRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -29,13 +29,12 @@ func (r *IncrementDecrementRule) Apply(file *lint.File, _ lint.Arguments) []lint } // Name returns the rule name. -func (r *IncrementDecrementRule) Name() string { +func (*IncrementDecrementRule) Name() string { return "increment-decrement" } type lintIncrementDecrement struct { file *lint.File - fileAst *ast.File onFailure func(lint.Failure) } 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 4c9799b2..e455801c 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 @@ -11,7 +11,7 @@ import ( type IndentErrorFlowRule struct{} // Apply applies the rule to given file. -func (r *IndentErrorFlowRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*IndentErrorFlowRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -24,7 +24,7 @@ func (r *IndentErrorFlowRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } // Name returns the rule name. -func (r *IndentErrorFlowRule) Name() string { +func (*IndentErrorFlowRule) Name() string { return "indent-error-flow" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/line-length-limit.go b/tools/vendor/github.com/mgechev/revive/rule/line-length-limit.go index c5177320..9e512c1c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/line-length-limit.go +++ b/tools/vendor/github.com/mgechev/revive/rule/line-length-limit.go @@ -6,6 +6,7 @@ import ( "fmt" "go/token" "strings" + "sync" "unicode/utf8" "github.com/mgechev/revive/lint" @@ -14,10 +15,11 @@ import ( // LineLengthLimitRule lints given else constructs. type LineLengthLimitRule struct { max int + sync.Mutex } -// Apply applies the rule to given file. -func (r *LineLengthLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *LineLengthLimitRule) configure(arguments lint.Arguments) { + r.Lock() if r.max == 0 { checkNumberOfArguments(1, arguments, r.Name()) @@ -28,8 +30,15 @@ func (r *LineLengthLimitRule) Apply(file *lint.File, arguments lint.Arguments) [ r.max = int(max) } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *LineLengthLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure + checker := lintLineLengthNum{ max: r.max, file: file, @@ -44,7 +53,7 @@ func (r *LineLengthLimitRule) Apply(file *lint.File, arguments lint.Arguments) [ } // Name returns the rule name. -func (r *LineLengthLimitRule) Name() string { +func (*LineLengthLimitRule) Name() string { return "line-length-limit" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/max-public-structs.go b/tools/vendor/github.com/mgechev/revive/rule/max-public-structs.go index 2a5fa7bc..e39f49c6 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/max-public-structs.go +++ b/tools/vendor/github.com/mgechev/revive/rule/max-public-structs.go @@ -3,6 +3,7 @@ package rule import ( "go/ast" "strings" + "sync" "github.com/mgechev/revive/lint" ) @@ -10,10 +11,11 @@ import ( // MaxPublicStructsRule lints given else constructs. type MaxPublicStructsRule struct { max int64 + sync.Mutex } -// Apply applies the rule to given file. -func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (r *MaxPublicStructsRule) configure(arguments lint.Arguments) { + r.Lock() if r.max < 1 { checkNumberOfArguments(1, arguments, r.Name()) @@ -23,10 +25,17 @@ func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) } r.max = max } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) var failures []lint.Failure fileAst := file.AST + walker := &lintMaxPublicStructs{ fileAst: fileAst, onFailure: func(failure lint.Failure) { @@ -49,7 +58,7 @@ func (r *MaxPublicStructsRule) Apply(file *lint.File, arguments lint.Arguments) } // Name returns the rule name. -func (r *MaxPublicStructsRule) Name() string { +func (*MaxPublicStructsRule) Name() string { return "max-public-structs" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/modifies-param.go b/tools/vendor/github.com/mgechev/revive/rule/modifies-param.go index 55136e6c..a68ae250 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/modifies-param.go +++ b/tools/vendor/github.com/mgechev/revive/rule/modifies-param.go @@ -11,7 +11,7 @@ import ( type ModifiesParamRule struct{} // Apply applies the rule to given file. -func (r *ModifiesParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ModifiesParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -24,7 +24,7 @@ func (r *ModifiesParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fail } // Name returns the rule name. -func (r *ModifiesParamRule) Name() string { +func (*ModifiesParamRule) Name() string { return "modifies-parameter" } 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 4fe22ddf..34e65155 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 @@ -11,7 +11,7 @@ import ( type ModifiesValRecRule struct{} // Apply applies the rule to given file. -func (r *ModifiesValRecRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ModifiesValRecRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -26,7 +26,7 @@ func (r *ModifiesValRecRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fai } // Name returns the rule name. -func (r *ModifiesValRecRule) Name() string { +func (*ModifiesValRecRule) Name() string { return "modifies-value-receiver" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/nested-structs.go b/tools/vendor/github.com/mgechev/revive/rule/nested-structs.go index deb202ec..b4f7352d 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/nested-structs.go +++ b/tools/vendor/github.com/mgechev/revive/rule/nested-structs.go @@ -10,13 +10,9 @@ import ( type NestedStructs struct{} // Apply applies the rule to given file. -func (r *NestedStructs) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (*NestedStructs) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure - if len(arguments) > 0 { - panic(r.Name() + " doesn't take any arguments") - } - walker := &lintNestedStructs{ fileAST: file.AST, onFailure: func(failure lint.Failure) { @@ -30,7 +26,7 @@ func (r *NestedStructs) Apply(file *lint.File, arguments lint.Arguments) []lint. } // Name returns the rule name. -func (r *NestedStructs) Name() string { +func (*NestedStructs) Name() string { return "nested-structs" } 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 ccb8a327..88928bb9 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 @@ -12,7 +12,7 @@ import ( type OptimizeOperandsOrderRule struct{} // Apply applies the rule to given file. -func (r *OptimizeOperandsOrderRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*OptimizeOperandsOrderRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -26,7 +26,7 @@ func (r *OptimizeOperandsOrderRule) Apply(file *lint.File, _ lint.Arguments) []l } // Name returns the rule name. -func (r *OptimizeOperandsOrderRule) Name() string { +func (*OptimizeOperandsOrderRule) Name() string { return "optimize-operands-order" } 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 035e1139..33963ab9 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/package-comments.go +++ b/tools/vendor/github.com/mgechev/revive/rule/package-comments.go @@ -5,6 +5,7 @@ import ( "go/ast" "go/token" "strings" + "sync" "github.com/mgechev/revive/lint" ) @@ -14,7 +15,9 @@ import ( // 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. -type PackageCommentsRule struct{} +type PackageCommentsRule struct { + checkPackageCommentCache sync.Map +} // Apply applies the rule to given file. func (r *PackageCommentsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { @@ -29,13 +32,13 @@ func (r *PackageCommentsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } fileAst := file.AST - w := &lintPackageComments{fileAst, file, onFailure} + w := &lintPackageComments{fileAst, file, onFailure, r} ast.Walk(w, fileAst) return failures } // Name returns the rule name. -func (r *PackageCommentsRule) Name() string { +func (*PackageCommentsRule) Name() string { return "package-comments" } @@ -43,6 +46,49 @@ type lintPackageComments struct { fileAst *ast.File file *lint.File onFailure func(lint.Failure) + rule *PackageCommentsRule +} + +func (l *lintPackageComments) checkPackageComment() []lint.Failure { + // deduplicate warnings in package + if _, exists := l.rule.checkPackageCommentCache.LoadOrStore(l.file.Pkg, struct{}{}); exists { + return nil + } + var docFile *ast.File // which name is doc.go + var packageFile *ast.File // which name is $package.go + var firstFile *ast.File + var firstFileName string + for name, file := range l.file.Pkg.Files() { + if file.AST.Doc != nil { + return nil + } + if name == "doc.go" { + docFile = file.AST + } + if name == file.AST.Name.String()+".go" { + packageFile = file.AST + } + if firstFileName == "" || firstFileName > name { + firstFile = file.AST + firstFileName = name + } + } + // prefer warning on doc.go, $package.go over first file + if docFile == nil { + docFile = packageFile + } + if docFile == nil { + docFile = firstFile + } + if docFile != nil { + return []lint.Failure{{ + Category: "comments", + Node: docFile, + Confidence: 1, + Failure: "should have a package comment", + }} + } + return nil } func (l *lintPackageComments) Visit(_ ast.Node) ast.Visitor { @@ -50,7 +96,6 @@ func (l *lintPackageComments) Visit(_ ast.Node) ast.Visitor { return nil } - const ref = styleGuideBase + "#package-comments" prefix := "Package " + l.fileAst.Name.Name + " " // Look for a detached package comment. @@ -90,12 +135,9 @@ func (l *lintPackageComments) Visit(_ ast.Node) ast.Visitor { } if l.fileAst.Doc == nil { - l.onFailure(lint.Failure{ - Category: "comments", - Node: l.fileAst, - Confidence: 0.2, - Failure: "should have a package comment, unless it's in another file for this package", - }) + for _, failure := range l.checkPackageComment() { + l.onFailure(failure) + } return nil } s := l.fileAst.Doc.Text() 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 1412955d..51ad8e10 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 @@ -13,7 +13,7 @@ import ( type RangeValAddress struct{} // Apply applies the rule to given file. -func (r *RangeValAddress) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*RangeValAddress) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure walker := rangeValAddress{ @@ -30,7 +30,7 @@ func (r *RangeValAddress) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *RangeValAddress) Name() string { +func (*RangeValAddress) Name() string { return "range-val-address" } 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 d961271e..1e85d0d0 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 @@ -11,7 +11,7 @@ import ( type RangeValInClosureRule struct{} // Apply applies the rule to given file. -func (r *RangeValInClosureRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*RangeValInClosureRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure walker := rangeValInClosure{ @@ -26,7 +26,7 @@ func (r *RangeValInClosureRule) Apply(file *lint.File, _ lint.Arguments) []lint. } // Name returns the rule name. -func (r *RangeValInClosureRule) Name() string { +func (*RangeValInClosureRule) Name() string { return "range-val-in-closure" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/range.go b/tools/vendor/github.com/mgechev/revive/rule/range.go index d18492c7..9d483a67 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/range.go +++ b/tools/vendor/github.com/mgechev/revive/rule/range.go @@ -12,7 +12,7 @@ import ( type RangeRule struct{} // Apply applies the rule to given file. -func (r *RangeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*RangeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -25,7 +25,7 @@ func (r *RangeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *RangeRule) Name() string { +func (*RangeRule) Name() string { return "range" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/receiver-naming.go b/tools/vendor/github.com/mgechev/revive/rule/receiver-naming.go index 589d5f0e..d79bb9fe 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/receiver-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/receiver-naming.go @@ -4,6 +4,7 @@ import ( "fmt" "go/ast" + "github.com/mgechev/revive/internal/typeparams" "github.com/mgechev/revive/lint" ) @@ -11,7 +12,7 @@ import ( type ReceiverNamingRule struct{} // Apply applies the rule to given file. -func (r *ReceiverNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*ReceiverNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -28,7 +29,7 @@ func (r *ReceiverNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fai } // Name returns the rule name. -func (r *ReceiverNamingRule) Name() string { +func (*ReceiverNamingRule) Name() string { return "receiver-naming" } @@ -47,7 +48,6 @@ func (w lintReceiverName) Visit(n ast.Node) ast.Visitor { return w } name := names[0].Name - const ref = styleGuideBase + "#receiver-names" if name == "_" { w.onFailure(lint.Failure{ Node: n, @@ -66,7 +66,7 @@ func (w lintReceiverName) Visit(n ast.Node) ast.Visitor { }) return w } - recv := receiverType(fn) + recv := typeparams.ReceiverType(fn) if prev, ok := w.typeReceiver[recv]; ok && prev != name { w.onFailure(lint.Failure{ Node: n, diff --git a/tools/vendor/github.com/mgechev/revive/rule/redefines-builtin-id.go b/tools/vendor/github.com/mgechev/revive/rule/redefines-builtin-id.go index 62cb7b61..23dd85a7 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/redefines-builtin-id.go +++ b/tools/vendor/github.com/mgechev/revive/rule/redefines-builtin-id.go @@ -34,39 +34,34 @@ var builtFunctions = map[string]bool{ } var builtInTypes = map[string]bool{ - "ComplexType": true, - "FloatType": true, - "IntegerType": true, - "Type": true, - "Type1": true, - "bool": true, - "byte": true, - "complex128": true, - "complex64": true, - "error": true, - "float32": true, - "float64": true, - "int": true, - "int16": true, - "int32": true, - "int64": true, - "int8": true, - "rune": true, - "string": true, - "uint": true, - "uint16": true, - "uint32": true, - "uint64": true, - "uint8": true, - "uintptr": true, - "any": true, + "bool": true, + "byte": true, + "complex128": true, + "complex64": true, + "error": true, + "float32": true, + "float64": true, + "int": true, + "int16": true, + "int32": true, + "int64": true, + "int8": true, + "rune": true, + "string": true, + "uint": true, + "uint16": true, + "uint32": true, + "uint64": true, + "uint8": true, + "uintptr": true, + "any": true, } // RedefinesBuiltinIDRule warns when a builtin identifier is shadowed. type RedefinesBuiltinIDRule struct{} // Apply applies the rule to given file. -func (r *RedefinesBuiltinIDRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*RedefinesBuiltinIDRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -81,7 +76,7 @@ func (r *RedefinesBuiltinIDRule) Apply(file *lint.File, _ lint.Arguments) []lint } // Name returns the rule name. -func (r *RedefinesBuiltinIDRule) Name() string { +func (*RedefinesBuiltinIDRule) Name() string { return "redefines-builtin-id" } @@ -164,7 +159,7 @@ func (w lintRedefinesBuiltinID) addFailure(node ast.Node, msg string) { }) } -func (w lintRedefinesBuiltinID) isBuiltIn(id string) (r bool, builtInKind string) { +func (lintRedefinesBuiltinID) isBuiltIn(id string) (r bool, builtInKind string) { if builtFunctions[id] { return true, "function" } 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 502e9231..e7841e8c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/string-format.go +++ b/tools/vendor/github.com/mgechev/revive/rule/string-format.go @@ -16,7 +16,7 @@ import ( type StringFormatRule struct{} // Apply applies the rule to the given file. -func (r *StringFormatRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { +func (*StringFormatRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -31,12 +31,12 @@ func (r *StringFormatRule) Apply(file *lint.File, arguments lint.Arguments) []li } // Name returns the rule name. -func (r *StringFormatRule) Name() string { +func (*StringFormatRule) Name() string { return "string-format" } // 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 (r *StringFormatRule) ParseArgumentsTest(arguments lint.Arguments) *string { +func (StringFormatRule) ParseArgumentsTest(arguments lint.Arguments) *string { w := lintStringFormatRule{} c := make(chan interface{}) // Parse the arguments in a goroutine, defer a recover() call, return the error encountered (or nil if there was no error) @@ -61,9 +61,7 @@ func (r *StringFormatRule) ParseArgumentsTest(arguments lint.Arguments) *string type lintStringFormatRule struct { onFailure func(lint.Failure) - - rules []stringFormatSubrule - stringDeclarations map[string]string + rules []stringFormatSubrule } type stringFormatSubrule struct { @@ -161,12 +159,12 @@ func (w lintStringFormatRule) parseArgument(argument interface{}, ruleNum int) ( } // Report an invalid config, this is specifically the user's fault -func (w lintStringFormatRule) configError(msg string, ruleNum, option int) { +func (lintStringFormatRule) configError(msg string, ruleNum, option int) { panic(fmt.Sprintf("invalid configuration for string-format: %s [argument %d, option %d]", msg, ruleNum, option)) } // Report a general config parsing failure, this may be the user's fault, but it isn't known for certain -func (w lintStringFormatRule) parseError(msg string, ruleNum, option int) { +func (lintStringFormatRule) parseError(msg string, ruleNum, option int) { panic(fmt.Sprintf("failed to parse configuration for string-format: %s [argument %d, option %d]", msg, ruleNum, option)) } @@ -197,7 +195,7 @@ func (w lintStringFormatRule) Visit(node ast.Node) ast.Visitor { } // Return the name of a call expression in the form of package.Func or Func -func (w lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, ok bool) { +func (lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, ok bool) { if ident, ok := call.Fun.(*ast.Ident); ok { // Local function call return ident.Name, true @@ -220,14 +218,14 @@ func (w lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, // #region Linting logic // Apply a single format rule to a call expression (should be done after verifying the that the call expression matches the rule's scope) -func (rule stringFormatSubrule) Apply(call *ast.CallExpr) { - if len(call.Args) <= rule.scope.argument { +func (r *stringFormatSubrule) Apply(call *ast.CallExpr) { + if len(call.Args) <= r.scope.argument { return } - arg := call.Args[rule.scope.argument] + arg := call.Args[r.scope.argument] var lit *ast.BasicLit - if len(rule.scope.field) > 0 { + if len(r.scope.field) > 0 { // Try finding the scope's Field, treating arg as a composite literal composite, ok := arg.(*ast.CompositeLit) if !ok { @@ -239,7 +237,7 @@ func (rule stringFormatSubrule) Apply(call *ast.CallExpr) { continue } key, ok := kv.Key.(*ast.Ident) - if !ok || key.Name != rule.scope.field { + if !ok || key.Name != r.scope.field { continue } @@ -259,21 +257,21 @@ func (rule stringFormatSubrule) Apply(call *ast.CallExpr) { } // Unquote the string literal before linting unquoted := lit.Value[1 : len(lit.Value)-1] - rule.lintMessage(unquoted, lit) + r.lintMessage(unquoted, lit) } -func (rule stringFormatSubrule) lintMessage(s string, node ast.Node) { +func (r *stringFormatSubrule) lintMessage(s string, node ast.Node) { // Fail if the string doesn't match the user's regex - if rule.regexp.MatchString(s) { + if r.regexp.MatchString(s) { return } var failure string - if len(rule.errorMessage) > 0 { - failure = rule.errorMessage + if len(r.errorMessage) > 0 { + failure = r.errorMessage } else { - failure = fmt.Sprintf("string literal doesn't match user defined regex /%s/", rule.regexp.String()) + failure = fmt.Sprintf("string literal doesn't match user defined regex /%s/", r.regexp.String()) } - rule.parent.onFailure(lint.Failure{ + r.parent.onFailure(lint.Failure{ Confidence: 1, Failure: failure, Node: node, diff --git a/tools/vendor/github.com/mgechev/revive/rule/string-of-int.go b/tools/vendor/github.com/mgechev/revive/rule/string-of-int.go index f9fe5a45..3bec1d6a 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/string-of-int.go +++ b/tools/vendor/github.com/mgechev/revive/rule/string-of-int.go @@ -11,7 +11,7 @@ import ( type StringOfIntRule struct{} // Apply applies the rule to given file. -func (r *StringOfIntRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*StringOfIntRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -28,7 +28,7 @@ func (r *StringOfIntRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *StringOfIntRule) Name() string { +func (*StringOfIntRule) Name() string { return "string-of-int" } 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 f890e9db..3accf58f 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/struct-tag.go +++ b/tools/vendor/github.com/mgechev/revive/rule/struct-tag.go @@ -14,7 +14,7 @@ import ( type StructTagRule struct{} // Apply applies the rule to given file. -func (r *StructTagRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*StructTagRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -29,13 +29,14 @@ func (r *StructTagRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure } // Name returns the rule name. -func (r *StructTagRule) Name() string { +func (*StructTagRule) Name() string { return "struct-tag" } type lintStructTagRule struct { - onFailure func(lint.Failure) - usedTagNbr map[string]bool // list of used tag numbers + onFailure func(lint.Failure) + usedTagNbr map[int]bool // list of used tag numbers + usedTagName map[string]bool // list of used tag keys } func (w lintStructTagRule) Visit(node ast.Node) ast.Visitor { @@ -44,7 +45,8 @@ func (w lintStructTagRule) Visit(node ast.Node) ast.Visitor { if n.Fields == nil || n.Fields.NumFields() < 1 { return nil // skip empty structs } - w.usedTagNbr = map[string]bool{} // init + w.usedTagNbr = map[int]bool{} // init + w.usedTagName = map[string]bool{} // init for _, f := range n.Fields.List { if f.Tag != nil { w.checkTaggedField(f) @@ -55,6 +57,53 @@ func (w lintStructTagRule) Visit(node ast.Node) ast.Visitor { return w } +func (w lintStructTagRule) checkTagNameIfNeed(tag *structtag.Tag) (string, bool) { + isUnnamedTag := tag.Name == "" || tag.Name == "-" + if isUnnamedTag { + return "", true + } + + needsToCheckTagName := tag.Key == "bson" || + tag.Key == "json" || + tag.Key == "xml" || + tag.Key == "yaml" || + tag.Key == "protobuf" + + if !needsToCheckTagName { + return "", true + } + + tagName := w.getTagName(tag) + if tagName == "" { + return "", true // No tag name found + } + + // We concat the key and name as the mapping key here + // to allow the same tag name in different tag type. + key := tag.Key + ":" + tagName + if _, ok := w.usedTagName[key]; ok { + return fmt.Sprintf("duplicate tag name: '%s'", tagName), false + } + + w.usedTagName[key] = true + + return "", true +} + +func (lintStructTagRule) getTagName(tag *structtag.Tag) string { + switch tag.Key { + case "protobuf": + for _, option := range tag.Options { + if strings.HasPrefix(option, "name=") { + return strings.TrimLeft(option, "name=") + } + } + return "" //protobuf tag lacks 'name' option + default: + return tag.Name + } +} + // checkTaggedField checks the tag of the given field. // precondition: the field has a tag func (w lintStructTagRule) checkTaggedField(f *ast.Field) { @@ -69,6 +118,10 @@ func (w lintStructTagRule) checkTaggedField(f *ast.Field) { } for _, tag := range tags.Tags() { + if msg, ok := w.checkTagNameIfNeed(tag); !ok { + w.addFailure(f.Tag, msg) + } + switch key := tag.Key; key { case "asn1": msg, ok := w.checkASN1Tag(f.Type, tag) @@ -90,7 +143,10 @@ func (w lintStructTagRule) checkTaggedField(f *ast.Field) { w.addFailure(f.Tag, msg) } case "protobuf": - // Not implemented yet + msg, ok := w.checkProtobufTag(tag) + if !ok { + w.addFailure(f.Tag, msg) + } case "required": if tag.Name != "true" && tag.Name != "false" { w.addFailure(f.Tag, "required should be 'true' or 'false'") @@ -121,10 +177,14 @@ func (w lintStructTagRule) checkASN1Tag(t ast.Expr, tag *structtag.Tag) (string, if strings.HasPrefix(opt, "tag:") { parts := strings.Split(opt, ":") tagNumber := parts[1] - if w.usedTagNbr[tagNumber] { - return fmt.Sprintf("duplicated tag number %s", tagNumber), false + number, err := strconv.Atoi(tagNumber) + if err != nil { + return fmt.Sprintf("ASN1 tag must be a number, got '%s'", tagNumber), false + } + if w.usedTagNbr[number] { + return fmt.Sprintf("duplicated tag number %v", number), false } - w.usedTagNbr[tagNumber] = true + w.usedTagNbr[number] = true continue } @@ -148,7 +208,7 @@ func (w lintStructTagRule) checkASN1Tag(t ast.Expr, tag *structtag.Tag) (string, return "", true } -func (w lintStructTagRule) checkBSONTag(options []string) (string, bool) { +func (lintStructTagRule) checkBSONTag(options []string) (string, bool) { for _, opt := range options { switch opt { case "inline", "minsize", "omitempty": @@ -160,7 +220,7 @@ func (w lintStructTagRule) checkBSONTag(options []string) (string, bool) { return "", true } -func (w lintStructTagRule) checkJSONTag(name string, options []string) (string, bool) { +func (lintStructTagRule) checkJSONTag(name string, options []string) (string, bool) { for _, opt := range options { switch opt { case "omitempty", "string": @@ -177,7 +237,7 @@ func (w lintStructTagRule) checkJSONTag(name string, options []string) (string, return "", true } -func (w lintStructTagRule) checkXMLTag(options []string) (string, bool) { +func (lintStructTagRule) checkXMLTag(options []string) (string, bool) { for _, opt := range options { switch opt { case "any", "attr", "cdata", "chardata", "comment", "innerxml", "omitempty", "typeattr": @@ -189,7 +249,7 @@ func (w lintStructTagRule) checkXMLTag(options []string) (string, bool) { return "", true } -func (w lintStructTagRule) checkYAMLTag(options []string) (string, bool) { +func (lintStructTagRule) checkYAMLTag(options []string) (string, bool) { for _, opt := range options { switch opt { case "flow", "inline", "omitempty": @@ -201,7 +261,7 @@ func (w lintStructTagRule) checkYAMLTag(options []string) (string, bool) { return "", true } -func (w lintStructTagRule) typeValueMatch(t ast.Expr, val string) bool { +func (lintStructTagRule) typeValueMatch(t ast.Expr, val string) bool { tID, ok := t.(*ast.Ident) if !ok { return true @@ -226,6 +286,57 @@ func (w lintStructTagRule) typeValueMatch(t ast.Expr, val string) bool { return typeMatches } +func (w lintStructTagRule) checkProtobufTag(tag *structtag.Tag) (string, bool) { + // check name + switch tag.Name { + case "bytes", "fixed32", "fixed64", "group", "varint", "zigzag32", "zigzag64": + // do nothing + default: + return fmt.Sprintf("invalid protobuf tag name '%s'", tag.Name), false + } + + // check options + seenOptions := map[string]bool{} + for _, opt := range tag.Options { + if number, err := strconv.Atoi(opt); err == nil { + _, alreadySeen := w.usedTagNbr[number] + if alreadySeen { + return fmt.Sprintf("duplicated tag number %v", number), false + } + w.usedTagNbr[number] = true + continue // option is an integer + } + + switch { + case opt == "opt" || opt == "proto3" || opt == "rep" || opt == "req": + // do nothing + case strings.Contains(opt, "="): + o := strings.Split(opt, "=")[0] + _, alreadySeen := seenOptions[o] + if alreadySeen { + return fmt.Sprintf("protobuf tag has duplicated option '%s'", o), false + } + seenOptions[o] = true + continue + } + } + _, hasName := seenOptions["name"] + if !hasName { + return "protobuf tag lacks mandatory option 'name'", false + } + + for k := range seenOptions { + switch k { + case "name", "json": + // do nothing + default: + return fmt.Sprintf("unknown option '%s' in protobuf tag", k), false + } + } + + return "", true +} + func (w lintStructTagRule) addFailure(n ast.Node, msg string) { w.onFailure(lint.Failure{ Node: n, 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 1bce093f..a9e4380c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/superfluous-else.go +++ b/tools/vendor/github.com/mgechev/revive/rule/superfluous-else.go @@ -12,7 +12,7 @@ import ( type SuperfluousElseRule struct{} // Apply applies the rule to given file. -func (r *SuperfluousElseRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*SuperfluousElseRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { failures = append(failures, failure) @@ -36,7 +36,7 @@ func (r *SuperfluousElseRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } // Name returns the rule name. -func (r *SuperfluousElseRule) Name() string { +func (*SuperfluousElseRule) Name() string { return "superfluous-else" } @@ -82,9 +82,9 @@ func (w lintSuperfluousElse) Visit(node ast.Node) ast.Visitor { lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1] switch stmt := lastStmt.(type) { case *ast.BranchStmt: - token := stmt.Tok.String() - if token != "fallthrough" { - w.onFailure(newFailure(ifStmt.Else, "if block ends with a "+token+" statement, so drop this else and outdent its block"+extra)) + tok := stmt.Tok.String() + if tok != "fallthrough" { + w.onFailure(newFailure(ifStmt.Else, "if block ends with a "+tok+" statement, so drop this else and outdent its block"+extra)) } case *ast.ExprStmt: if ce, ok := stmt.X.(*ast.CallExpr); ok { // it's a function call diff --git a/tools/vendor/github.com/mgechev/revive/rule/time-naming.go b/tools/vendor/github.com/mgechev/revive/rule/time-naming.go index 24a612e4..cea452e6 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/time-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/time-naming.go @@ -13,7 +13,7 @@ import ( type TimeNamingRule struct{} // Apply applies the rule to given file. -func (r *TimeNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*TimeNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -28,7 +28,7 @@ func (r *TimeNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure } // Name returns the rule name. -func (r *TimeNamingRule) Name() string { +func (*TimeNamingRule) Name() string { return "time-naming" } 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 930b486a..f0e83b0c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unconditional-recursion.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unconditional-recursion.go @@ -10,7 +10,7 @@ import ( type UnconditionalRecursionRule struct{} // Apply applies the rule to given file. -func (r *UnconditionalRecursionRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UnconditionalRecursionRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -23,7 +23,7 @@ func (r *UnconditionalRecursionRule) Apply(file *lint.File, _ lint.Arguments) [] } // Name returns the rule name. -func (r *UnconditionalRecursionRule) Name() string { +func (*UnconditionalRecursionRule) Name() string { return "unconditional-recursion" } @@ -151,7 +151,7 @@ var exitFunctions = map[string]map[string]bool{ }, } -func (w *lintUnconditionalRecursionRule) hasControlExit(node ast.Node) bool { +func (lintUnconditionalRecursionRule) hasControlExit(node ast.Node) bool { // isExit returns true if the given node makes control exit the function isExit := func(node ast.Node) bool { switch n := node.(type) { diff --git a/tools/vendor/github.com/mgechev/revive/rule/unexported-naming.go b/tools/vendor/github.com/mgechev/revive/rule/unexported-naming.go index 96cec3e4..0c2b39d4 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unexported-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unexported-naming.go @@ -12,7 +12,7 @@ import ( type UnexportedNamingRule struct{} // Apply applies the rule to given file. -func (r *UnexportedNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UnexportedNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { failures = append(failures, failure) @@ -25,7 +25,7 @@ func (r *UnexportedNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.F } // Name returns the rule name. -func (r *UnexportedNamingRule) Name() string { +func (*UnexportedNamingRule) Name() string { return "unexported-naming" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/unexported-return.go b/tools/vendor/github.com/mgechev/revive/rule/unexported-return.go index c9c8a41d..10f8e3fb 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unexported-return.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unexported-return.go @@ -5,6 +5,7 @@ import ( "go/ast" "go/types" + "github.com/mgechev/revive/internal/typeparams" "github.com/mgechev/revive/lint" ) @@ -12,7 +13,7 @@ import ( type UnexportedReturnRule struct{} // Apply applies the rule to given file. -func (r *UnexportedReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UnexportedReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -31,7 +32,7 @@ func (r *UnexportedReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.F } // Name returns the rule name. -func (r *UnexportedReturnRule) Name() string { +func (*UnexportedReturnRule) Name() string { return "unexported-return" } @@ -55,7 +56,7 @@ func (w lintUnexportedReturn) Visit(n ast.Node) ast.Visitor { thing := "func" if fn.Recv != nil && len(fn.Recv.List) > 0 { thing = "method" - if !ast.IsExported(receiverType(fn)) { + if !ast.IsExported(typeparams.ReceiverType(fn)) { // Don't report exported methods of unexported types, // such as private implementations of sort.Interface. return nil @@ -82,24 +83,24 @@ func (w lintUnexportedReturn) Visit(n ast.Node) ast.Visitor { // 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) { + switch t := typ.(type) { case *types.Named: - obj := T.Obj() + obj := t.Obj() switch { // Builtin types have no package. case obj.Pkg() == nil: case obj.Exported(): default: - _, ok := T.Underlying().(*types.Interface) + _, ok := t.Underlying().(*types.Interface) return ok } return true case *types.Map: - return exportedType(T.Key()) && exportedType(T.Elem()) + return exportedType(t.Key()) && exportedType(t.Elem()) case interface { Elem() types.Type }: // array, slice, pointer, chan - return exportedType(T.Elem()) + return exportedType(t.Elem()) } // Be conservative about other types, such as struct, interface, etc. return true 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 43217143..6cde24b7 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unhandled-error.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unhandled-error.go @@ -4,6 +4,7 @@ import ( "fmt" "go/ast" "go/types" + "sync" "github.com/mgechev/revive/lint" ) @@ -11,16 +12,17 @@ import ( // UnhandledErrorRule lints given else constructs. type UnhandledErrorRule struct { ignoreList ignoreListType + sync.Mutex } type ignoreListType map[string]struct{} -// Apply applies the rule to given file. -func (r *UnhandledErrorRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure { +func (r *UnhandledErrorRule) configure(arguments lint.Arguments) { + r.Lock() if r.ignoreList == nil { - r.ignoreList = make(ignoreListType, len(args)) + r.ignoreList = make(ignoreListType, len(arguments)) - for _, arg := range args { + for _, arg := range arguments { argStr, ok := arg.(string) if !ok { panic(fmt.Sprintf("Invalid argument to the unhandled-error rule. Expecting a string, got %T", arg)) @@ -29,6 +31,12 @@ func (r *UnhandledErrorRule) Apply(file *lint.File, args lint.Arguments) []lint. r.ignoreList[argStr] = struct{}{} } } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *UnhandledErrorRule) Apply(file *lint.File, args lint.Arguments) []lint.Failure { + r.configure(args) var failures []lint.Failure @@ -47,7 +55,7 @@ func (r *UnhandledErrorRule) Apply(file *lint.File, args lint.Arguments) []lint. } // Name returns the rule name. -func (r *UnhandledErrorRule) Name() string { +func (*UnhandledErrorRule) Name() string { return "unhandled-error" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/unnecessary-stmt.go b/tools/vendor/github.com/mgechev/revive/rule/unnecessary-stmt.go index 732d8a8b..8e0784ba 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unnecessary-stmt.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unnecessary-stmt.go @@ -11,7 +11,7 @@ import ( type UnnecessaryStmtRule struct{} // Apply applies the rule to given file. -func (r *UnnecessaryStmtRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UnnecessaryStmtRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { failures = append(failures, failure) @@ -23,7 +23,7 @@ func (r *UnnecessaryStmtRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } // Name returns the rule name. -func (r *UnnecessaryStmtRule) Name() string { +func (*UnnecessaryStmtRule) Name() string { return "unnecessary-stmt" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/unreachable-code.go b/tools/vendor/github.com/mgechev/revive/rule/unreachable-code.go index 9032f317..dcc5b790 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unreachable-code.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unreachable-code.go @@ -10,12 +10,17 @@ import ( type UnreachableCodeRule struct{} // Apply applies the rule to given file. -func (r *UnreachableCodeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UnreachableCodeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { failures = append(failures, failure) } + testingFunctions := map[string]bool{ + "Fatal": true, + "Fatalf": true, + "FailNow": true, + } branchingFunctions := map[string]map[string]bool{ "os": {"Exit": true}, "log": { @@ -26,6 +31,9 @@ func (r *UnreachableCodeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa "Panicf": true, "Panicln": true, }, + "t": testingFunctions, + "b": testingFunctions, + "f": testingFunctions, } w := lintUnreachableCode{onFailure, branchingFunctions} @@ -34,7 +42,7 @@ func (r *UnreachableCodeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } // Name returns the rule name. -func (r *UnreachableCodeRule) Name() string { +func (*UnreachableCodeRule) Name() string { return "unreachable-code" } 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 60df908d..ab3da453 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/unused-param.go +++ b/tools/vendor/github.com/mgechev/revive/rule/unused-param.go @@ -11,7 +11,7 @@ import ( type UnusedParamRule struct{} // Apply applies the rule to given file. -func (r *UnusedParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UnusedParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -26,7 +26,7 @@ func (r *UnusedParamRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur } // Name returns the rule name. -func (r *UnusedParamRule) Name() string { +func (*UnusedParamRule) Name() string { return "unused-parameter" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/use-any.go b/tools/vendor/github.com/mgechev/revive/rule/use-any.go index 5e75e2f8..bdf3c936 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/use-any.go +++ b/tools/vendor/github.com/mgechev/revive/rule/use-any.go @@ -10,7 +10,7 @@ import ( type UseAnyRule struct{} // Apply applies the rule to given file. -func (r *UseAnyRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UseAnyRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure walker := lintUseAny{ @@ -25,7 +25,7 @@ func (r *UseAnyRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *UseAnyRule) Name() string { +func (*UseAnyRule) Name() string { return "use-any" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/useless-break.go b/tools/vendor/github.com/mgechev/revive/rule/useless-break.go index a631bd1e..8db20c9b 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/useless-break.go +++ b/tools/vendor/github.com/mgechev/revive/rule/useless-break.go @@ -11,7 +11,7 @@ import ( type UselessBreak struct{} // Apply applies the rule to given file. -func (r *UselessBreak) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*UselessBreak) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -25,7 +25,7 @@ func (r *UselessBreak) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { } // Name returns the rule name. -func (r *UselessBreak) Name() string { +func (*UselessBreak) Name() string { return "useless-break" } diff --git a/tools/vendor/github.com/mgechev/revive/rule/utils.go b/tools/vendor/github.com/mgechev/revive/rule/utils.go index 2de97128..dca1674c 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/utils.go +++ b/tools/vendor/github.com/mgechev/revive/rule/utils.go @@ -13,8 +13,6 @@ import ( "github.com/mgechev/revive/lint" ) -const styleGuideBase = "https://golang.org/wiki/CodeReviewComments" - // 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 == "_" } @@ -28,19 +26,6 @@ var commonMethods = map[string]bool{ "Unwrap": true, } -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" -} - var knownNameExceptions = map[string]bool{ "LastInsertId": true, // must match database/sql "kWh": true, @@ -82,10 +67,10 @@ var zeroLiteral = map[string]bool{ "0i": true, } -func validType(T types.Type) bool { - return T != nil && - T != types.Typ[types.Invalid] && - !strings.Contains(T.String(), "invalid type") // good but not foolproof +func validType(t types.Type) bool { + return t != nil && + t != types.Typ[types.Invalid] && + !strings.Contains(t.String(), "invalid type") // good but not foolproof } // isPkgDot checks if the expression is . diff --git a/tools/vendor/github.com/mgechev/revive/rule/var-declarations.go b/tools/vendor/github.com/mgechev/revive/rule/var-declarations.go index 44113211..a15ff1eb 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/var-declarations.go +++ b/tools/vendor/github.com/mgechev/revive/rule/var-declarations.go @@ -13,7 +13,7 @@ import ( type VarDeclarationsRule struct{} // Apply applies the rule to given file. -func (r *VarDeclarationsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*VarDeclarationsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure fileAst := file.AST @@ -32,7 +32,7 @@ func (r *VarDeclarationsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa } // Name returns the rule name. -func (r *VarDeclarationsRule) Name() string { +func (*VarDeclarationsRule) Name() string { return "var-declaration" } 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 1de86081..3c0c19cd 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/var-naming.go +++ b/tools/vendor/github.com/mgechev/revive/rule/var-naming.go @@ -5,6 +5,7 @@ import ( "go/ast" "go/token" "strings" + "sync" "github.com/mgechev/revive/lint" ) @@ -14,12 +15,11 @@ type VarNamingRule struct { configured bool whitelist []string blacklist []string + sync.Mutex } -// Apply applies the rule to given file. -func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { - var failures []lint.Failure - +func (r *VarNamingRule) configure(arguments lint.Arguments) { + r.Lock() if !r.configured { if len(arguments) >= 1 { r.whitelist = getList(arguments[0], "whitelist") @@ -30,8 +30,17 @@ func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint. } r.configured = true } + r.Unlock() +} + +// Apply applies the rule to given file. +func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure { + r.configure(arguments) + + var failures []lint.Failure fileAst := file.AST + walker := lintNames{ file: file, fileAst: fileAst, @@ -47,7 +56,7 @@ func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint. walker.onFailure(lint.Failure{ Failure: "don't use an underscore in package name", Confidence: 1, - Node: walker.fileAst, + Node: walker.fileAst.Name, Category: "naming", }) } @@ -58,7 +67,7 @@ func (r *VarNamingRule) Apply(file *lint.File, arguments lint.Arguments) []lint. } // Name returns the rule name. -func (r *VarNamingRule) Name() string { +func (*VarNamingRule) Name() string { return "var-naming" } @@ -124,13 +133,11 @@ func check(id *ast.Ident, thing string, w *lintNames) { } type lintNames struct { - file *lint.File - fileAst *ast.File - lastGen *ast.GenDecl - genDeclMissingComments map[*ast.GenDecl]bool - onFailure func(lint.Failure) - whitelist []string - blacklist []string + file *lint.File + fileAst *ast.File + onFailure func(lint.Failure) + whitelist []string + blacklist []string } func (w *lintNames) Visit(n ast.Node) ast.Visitor { diff --git a/tools/vendor/github.com/mgechev/revive/rule/waitgroup-by-value.go b/tools/vendor/github.com/mgechev/revive/rule/waitgroup-by-value.go index b8692913..98644f41 100644 --- a/tools/vendor/github.com/mgechev/revive/rule/waitgroup-by-value.go +++ b/tools/vendor/github.com/mgechev/revive/rule/waitgroup-by-value.go @@ -10,7 +10,7 @@ import ( type WaitGroupByValueRule struct{} // Apply applies the rule to given file. -func (r *WaitGroupByValueRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { +func (*WaitGroupByValueRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { var failures []lint.Failure onFailure := func(failure lint.Failure) { @@ -23,7 +23,7 @@ func (r *WaitGroupByValueRule) Apply(file *lint.File, _ lint.Arguments) []lint.F } // Name returns the rule name. -func (r *WaitGroupByValueRule) Name() string { +func (*WaitGroupByValueRule) Name() string { return "waitgroup-by-value" } diff --git a/tools/vendor/github.com/nishanths/exhaustive/README.md b/tools/vendor/github.com/nishanths/exhaustive/README.md index b843ee86..3992704a 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/README.md +++ b/tools/vendor/github.com/nishanths/exhaustive/README.md @@ -15,6 +15,12 @@ The package provides an `Analyzer` that follows the guidelines in the [`go/analysis`][3] package; this should make it possible to integrate exhaustive with your own analysis driver program. +## Bugs + +`exhaustive` does not report missing cases if the switch statement +switches on a type parameterized type. See [this +issue](https://github.com/nishanths/exhaustive/issues/31) for details. + ## Example Given the enum diff --git a/tools/vendor/github.com/nishanths/exhaustive/comment.go b/tools/vendor/github.com/nishanths/exhaustive/comment.go index ea184d8e..cae8c64d 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/comment.go +++ b/tools/vendor/github.com/nishanths/exhaustive/comment.go @@ -44,22 +44,31 @@ func isGeneratedFile(file *ast.File) bool { return false } -var generatedCodeRx = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`) +var generatedCodeRe = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`) func isGeneratedFileComment(s string) bool { - return generatedCodeRx.MatchString(s) + return generatedCodeRe.MatchString(s) } // ignoreDirective is used to exclude checking of specific switch statements. const ignoreDirective = "//exhaustive:ignore" +const enforceDirective = "//exhaustive:enforce" -func containsIgnoreDirective(comments []*ast.CommentGroup) bool { +func containsDirective(comments []*ast.CommentGroup, directive string) bool { for _, c := range comments { for _, cc := range c.List { - if strings.HasPrefix(cc.Text, ignoreDirective) { + if strings.HasPrefix(cc.Text, directive) { return true } } } return false } + +func containsEnforceDirective(comments []*ast.CommentGroup) bool { + return containsDirective(comments, enforceDirective) +} + +func containsIgnoreDirective(comments []*ast.CommentGroup) bool { + return containsDirective(comments, ignoreDirective) +} diff --git a/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go b/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go index 5e12a657..e852df75 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go +++ b/tools/vendor/github.com/nishanths/exhaustive/exhaustive.go @@ -48,6 +48,10 @@ denoting constants (e.g. somepkg.Grassland) listed in a switch statement's cases can contribute towards satisfying exhaustiveness. Literal values, struct fields, re-assignable variables, etc. will not. +The analyzer will produce a diagnostic about unhandled enum members if the +required memebers are not listed in a switch statement's cases (this applies +even if the switch statement has a 'default' case). + Type aliases The analyzer handles type aliases for an enum type in the following manner. @@ -110,11 +114,18 @@ All of these flags are optional. flag type default value + -explicit-exhaustive-switch bool false -check-generated bool false -default-signifies-exhaustive bool false -ignore-enum-members string (none) -package-scope-only bool false + +If the -explicit-exhaustive-switch flag is enabled, the analyzer only runs on +switch statements explicitly marked with the comment text +("exhaustive:enforce"). Otherwise, it runs on every enum switch statement not +marked with the comment text ("exhaustive:ignore"). + If the -check-generated flag is enabled, switch statements in generated Go source files are also checked. Otherwise, by default, switch statements in generated files are not checked. See https://golang.org/s/generatedcode for the @@ -141,13 +152,21 @@ switch on all these enums. Skip analysis -To skip checking of a specific switch statement, associate the comment shown in -the example below with the switch statement. Note the lack of whitespace between -the comment marker ("//") and the comment text ("exhaustive:ignore"). +In implicitly exhaustive switch mode (-explicit-exhaustive-switch=false), skip +checking of a specific switch statement by associating the comment shown in +the example below with the switch statement. Note the lack of whitespace +between the comment marker ("//") and the comment text ("exhaustive:ignore"). //exhaustive:ignore switch v { ... } +In explicitly exhaustive switch mode (-explicit-exhaustive-switch=true), run +exhaustiveness checks on a specific switch statement by associating the +comment shown in the example below with the switch statement. + + //exhaustive:enforce + switch v { ... } + To ignore specific enum members, see the -ignore-enum-members flag. Switch statements in generated Go source files are not checked by default. @@ -195,7 +214,8 @@ func (v *regexpFlag) Set(expr string) error { func (v *regexpFlag) value() *regexp.Regexp { return v.r } func init() { - Analyzer.Flags.BoolVar(&fCheckGeneratedFiles, CheckGeneratedFlag, false, "check switch statements in generated files") + Analyzer.Flags.BoolVar(&fExplicitExhaustiveSwitch, ExplicitExhaustiveSwitchFlag, false, "only run exhaustive check on switches with \"//exhaustive:enforce\" comment") + Analyzer.Flags.BoolVar(&fCheckGenerated, CheckGeneratedFlag, false, "check switch statements in generated files") Analyzer.Flags.BoolVar(&fDefaultSignifiesExhaustive, DefaultSignifiesExhaustiveFlag, false, "presence of \"default\" case in switch statements satisfies exhaustiveness, even if all enum members are not listed") Analyzer.Flags.Var(&fIgnoreEnumMembers, IgnoreEnumMembersFlag, "enum members matching `regex` do not have to be listed in switch statements to satisfy exhaustiveness") Analyzer.Flags.BoolVar(&fPackageScopeOnly, PackageScopeOnlyFlag, false, "consider enums only in package scopes, not in inner scopes") @@ -208,6 +228,7 @@ func init() { // Flag names used by the analyzer. They are exported for use by analyzer // driver programs. const ( + ExplicitExhaustiveSwitchFlag = "explicit-exhaustive-switch" CheckGeneratedFlag = "check-generated" DefaultSignifiesExhaustiveFlag = "default-signifies-exhaustive" IgnoreEnumMembersFlag = "ignore-enum-members" @@ -218,7 +239,8 @@ const ( ) var ( - fCheckGeneratedFiles bool + fExplicitExhaustiveSwitch bool + fCheckGenerated bool fDefaultSignifiesExhaustive bool fIgnoreEnumMembers regexpFlag fPackageScopeOnly bool @@ -227,7 +249,8 @@ var ( // resetFlags resets the flag variables to their default values. // Useful in tests. func resetFlags() { - fCheckGeneratedFiles = false + fExplicitExhaustiveSwitch = false + fCheckGenerated = false fDefaultSignifiesExhaustive = false fIgnoreEnumMembers = regexpFlag{} fPackageScopeOnly = false @@ -248,11 +271,11 @@ func run(pass *analysis.Pass) (interface{}, error) { exportFact(pass, typ, members) } - cfg := config{ + checkSwitchStatements(pass, inspect, config{ + explicitExhaustiveSwitch: fExplicitExhaustiveSwitch, defaultSignifiesExhaustive: fDefaultSignifiesExhaustive, - checkGeneratedFiles: fCheckGeneratedFiles, + checkGeneratedFiles: fCheckGenerated, ignoreEnumMembers: fIgnoreEnumMembers.value(), - } - checkSwitchStatements(pass, inspect, cfg) + }) return nil, nil } diff --git a/tools/vendor/github.com/nishanths/exhaustive/fact.go b/tools/vendor/github.com/nishanths/exhaustive/fact.go index 5fc09bef..ecf0907b 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/fact.go +++ b/tools/vendor/github.com/nishanths/exhaustive/fact.go @@ -21,8 +21,7 @@ func exportFact(pass *analysis.Pass, enumTyp enumType, members enumMembers) { // An (_, false) return indicates that the enum type is not a known one. func importFact(pass *analysis.Pass, possibleEnumType enumType) (enumMembers, bool) { var f enumMembersFact - ok := pass.ImportObjectFact(possibleEnumType.factObject(), &f) - if !ok { + if !pass.ImportObjectFact(possibleEnumType.factObject(), &f) { return enumMembers{}, false } return f.Members, true diff --git a/tools/vendor/github.com/nishanths/exhaustive/switch.go b/tools/vendor/github.com/nishanths/exhaustive/switch.go index 22d74a4f..dcf3b6d0 100644 --- a/tools/vendor/github.com/nishanths/exhaustive/switch.go +++ b/tools/vendor/github.com/nishanths/exhaustive/switch.go @@ -23,22 +23,24 @@ type nodeVisitor func(n ast.Node, push bool, stack []ast.Node) (proceed bool, re // Result values returned by a node visitor constructed via switchStmtChecker. const ( - resultNotPush = "not push" - resultGeneratedFile = "generated file" - resultNoSwitchTag = "no switch tag" - resultTagNotValue = "switch tag not value type" - resultTagNotNamed = "switch tag not named type" - resultTagNoPkg = "switch tag does not belong to regular package" - resultTagNotEnum = "switch tag not known enum type" - resultSwitchIgnoreComment = "switch statement has ignore comment" - resultEnumMembersAccounted = "requisite enum members accounted for" - resultDefaultCaseSuffices = "default case presence satisfies exhaustiveness" - resultReportedDiagnostic = "reported diagnostic" + resultNotPush = "not push" + resultGeneratedFile = "generated file" + resultNoSwitchTag = "no switch tag" + resultTagNotValue = "switch tag not value type" + resultTagNotNamed = "switch tag not named type" + resultTagNoPkg = "switch tag does not belong to regular package" + resultTagNotEnum = "switch tag not known enum type" + resultSwitchIgnoreComment = "switch statement has ignore comment" + resultSwitchNoEnforceComment = "switch statement has no enforce comment" + resultEnumMembersAccounted = "requisite enum members accounted for" + resultDefaultCaseSuffices = "default case presence satisfies exhaustiveness" + resultReportedDiagnostic = "reported diagnostic" ) // switchStmtChecker returns a node visitor that checks exhaustiveness // of enum switch statements for the supplied pass, and reports diagnostics for // switch statements that are non-exhaustive. +// It expects to only see *ast.SwitchStmt nodes. func switchStmtChecker(pass *analysis.Pass, cfg config) nodeVisitor { generated := make(map[*ast.File]bool) // cached results comments := make(map[*ast.File]ast.CommentMap) // cached results @@ -69,12 +71,17 @@ func switchStmtChecker(pass *analysis.Pass, cfg config) nodeVisitor { if _, ok := comments[file]; !ok { comments[file] = ast.NewCommentMap(pass.Fset, file, file.Comments) } - if containsIgnoreDirective(comments[file].Filter(sw).Comments()) { + switchComments := comments[file][sw] + if !cfg.explicitExhaustiveSwitch && containsIgnoreDirective(switchComments) { // Skip checking of this switch statement due to ignore directive comment. // Still return true because there may be nested switch statements // that are not to be ignored. return true, resultSwitchIgnoreComment } + if cfg.explicitExhaustiveSwitch && !containsEnforceDirective(switchComments) { + // Skip checking of this switch statement due to missing enforce directive comment. + return true, resultSwitchNoEnforceComment + } if sw.Tag == nil { return true, resultNoSwitchTag @@ -108,7 +115,7 @@ func switchStmtChecker(pass *analysis.Pass, cfg config) nodeVisitor { checkUnexported := samePkg // we want to include unexported members in the exhaustiveness check only if we're in the same package checklist := makeChecklist(members, tagPkg, checkUnexported, cfg.ignoreEnumMembers) - hasDefaultCase := analyzeSwitchClauses(sw, tagPkg, members.NameToValue, pass.TypesInfo, func(val constantValue) { + hasDefaultCase := analyzeSwitchClauses(sw, pass.TypesInfo, func(val constantValue) { checklist.found(val) }) @@ -130,6 +137,7 @@ func switchStmtChecker(pass *analysis.Pass, cfg config) nodeVisitor { // config is configuration for checkSwitchStatements. type config struct { + explicitExhaustiveSwitch bool defaultSignifiesExhaustive bool checkGeneratedFiles bool ignoreEnumMembers *regexp.Regexp // can be nil @@ -163,14 +171,11 @@ func denotesPackage(ident *ast.Ident, info *types.Info) (*types.Package, bool) { } // analyzeSwitchClauses analyzes the clauses in the supplied switch statement. -// -// tagPkg is the package of the switch statement's tag value's type. // The info param should typically be pass.TypesInfo. The found function is // called for each enum member name found in the switch statement. -// // The hasDefaultCase return value indicates whether the switch statement has a // default clause. -func analyzeSwitchClauses(sw *ast.SwitchStmt, tagPkg *types.Package, members map[string]constantValue, info *types.Info, found func(val constantValue)) (hasDefaultCase bool) { +func analyzeSwitchClauses(sw *ast.SwitchStmt, info *types.Info, found func(val constantValue)) (hasDefaultCase bool) { for _, stmt := range sw.Body.List { caseCl := stmt.(*ast.CaseClause) if isDefaultCase(caseCl) { @@ -178,13 +183,13 @@ func analyzeSwitchClauses(sw *ast.SwitchStmt, tagPkg *types.Package, members map continue // nothing more to do if it's the default case } for _, expr := range caseCl.List { - analyzeCaseClauseExpr(expr, tagPkg, members, info, found) + analyzeCaseClauseExpr(expr, info, found) } } return hasDefaultCase } -func analyzeCaseClauseExpr(e ast.Expr, tagPkg *types.Package, members map[string]constantValue, info *types.Info, found func(val constantValue)) { +func analyzeCaseClauseExpr(e ast.Expr, info *types.Info, found func(val constantValue)) { handleIdent := func(ident *ast.Ident) { obj := info.Uses[ident] if obj == nil { @@ -282,6 +287,9 @@ func diagnosticEnumTypeName(enumType *types.TypeName, samePkg bool) string { return enumType.Pkg().Name() + "." + enumType.Name() } +// Makes a "missing cases in switch" diagnostic. +// samePkg should be true if the enum type and the switch statement are defined +// in the same package. func makeDiagnostic(sw *ast.SwitchStmt, samePkg bool, enumTyp enumType, allMembers enumMembers, missingMembers map[string]struct{}) analysis.Diagnostic { message := fmt.Sprintf("missing cases in switch of type %s: %s", diagnosticEnumTypeName(enumTyp.TypeName, samePkg), @@ -304,12 +312,12 @@ func makeDiagnostic(sw *ast.SwitchStmt, samePkg bool, enumTyp enumType, allMembe // The remaining method returns the member names not accounted for. // type checklist struct { - em enumMembers - names map[string]struct{} + em enumMembers + checkl map[string]struct{} } func makeChecklist(em enumMembers, enumPkg *types.Package, includeUnexported bool, ignore *regexp.Regexp) *checklist { - names := make(map[string]struct{}) + checkl := make(map[string]struct{}) add := func(memberName string) { if memberName == "_" { @@ -325,7 +333,7 @@ func makeChecklist(em enumMembers, enumPkg *types.Package, includeUnexported boo if ignore != nil && ignore.MatchString(enumPkg.Path()+"."+memberName) { return } - names[memberName] = struct{}{} + checkl[memberName] = struct{}{} } for _, name := range em.Names { @@ -333,18 +341,18 @@ func makeChecklist(em enumMembers, enumPkg *types.Package, includeUnexported boo } return &checklist{ - em: em, - names: names, + em: em, + checkl: checkl, } } func (c *checklist) found(val constantValue) { // Delete all of the same-valued names. for _, name := range c.em.ValueToNames[val] { - delete(c.names, name) + delete(c.checkl, name) } } func (c *checklist) remaining() map[string]struct{} { - return c.names + return c.checkl } 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 793fb184..3aa1840e 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml +++ b/tools/vendor/github.com/pelletier/go-toml/v2/.goreleaser.yaml @@ -16,7 +16,11 @@ builds: mod_timestamp: '{{ .CommitTimestamp }}' targets: - linux_amd64 + - linux_arm64 + - linux_arm - windows_amd64 + - windows_arm64 + - windows_arm - darwin_amd64 - darwin_arm64 - id: tomljson @@ -31,7 +35,11 @@ builds: mod_timestamp: '{{ .CommitTimestamp }}' targets: - linux_amd64 + - linux_arm64 + - linux_arm - windows_amd64 + - windows_arm64 + - windows_arm - darwin_amd64 - darwin_arm64 - id: jsontoml @@ -46,7 +54,11 @@ builds: mod_timestamp: '{{ .CommitTimestamp }}' targets: - linux_amd64 + - linux_arm64 + - linux_arm - windows_amd64 + - windows_arm64 + - windows_arm - darwin_amd64 - darwin_arm64 universal_binaries: 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 c14c1cea..4eb526bb 100644 --- a/tools/vendor/github.com/pelletier/go-toml/v2/marshaler.go +++ b/tools/vendor/github.com/pelletier/go-toml/v2/marshaler.go @@ -107,6 +107,13 @@ func (enc *Encoder) SetIndentTables(indent bool) *Encoder { // a newline character or a single quote. In that case they are emitted as // quoted strings. // +// Unsigned integers larger than math.MaxInt64 cannot be encoded. Doing so +// results in an error. This rule exists because the TOML specification only +// requires parsers to support at least the 64 bits integer range. Allowing +// larger numbers would create non-standard TOML documents, which may not be +// readable (at best) by other implementations. To encode such numbers, a +// solution is a custom type that implements encoding.TextMarshaler. +// // When encoding structs, fields are encoded in order of definition, with their // exact name. // @@ -303,7 +310,11 @@ func (enc *Encoder) encode(b []byte, ctx encoderCtx, v reflect.Value) ([]byte, e b = append(b, "false"...) } case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: - b = strconv.AppendUint(b, v.Uint(), 10) + x := v.Uint() + if x > uint64(math.MaxInt64) { + return nil, fmt.Errorf("toml: not encoding uint (%d) greater than max int64 (%d)", x, int64(math.MaxInt64)) + } + b = strconv.AppendUint(b, x, 10) case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: b = strconv.AppendInt(b, v.Int(), 10) default: 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 b5ecee4f..f3d81b57 100644 --- a/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/printf.go +++ b/tools/vendor/github.com/polyfloyd/go-errorlint/errorlint/printf.go @@ -53,22 +53,26 @@ func (pp *printfParser) parseVerb() (*verb, error) { } index := -1 - switch pp.peek() { - case '%': - pp.next() - return pp.parseVerb() - case '+', '#': - pp.next() - case '[': - var err error - index, err = pp.parseIndex() - if err != nil { - return nil, err + for { + switch pp.peek() { + case '%': + pp.next() + return pp.parseVerb() + case '+', '#': + pp.next() + continue + case '[': + var err error + index, err = pp.parseIndex() + if err != nil { + return nil, err + } + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.': + pp.parsePrecision() + case 0: + return nil, io.EOF } - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.': - pp.parsePrecision() - case 0: - return nil, io.EOF + break } format := pp.next() diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/engine.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/engine.go index 52b85fdb..a5e6ca4d 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/engine.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/engine.go @@ -17,6 +17,9 @@ import ( "github.com/quasilyte/go-ruleguard/internal/goenv" "github.com/quasilyte/go-ruleguard/ruleguard/ir" "github.com/quasilyte/go-ruleguard/ruleguard/quasigo" + "github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qfmt" + "github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrconv" + "github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrings" "github.com/quasilyte/go-ruleguard/ruleguard/typematch" "github.com/quasilyte/stdinfo" ) @@ -141,6 +144,9 @@ type engineState struct { func newEngineState() *engineState { env := quasigo.NewEnv() + qstrings.ImportAll(env) + qstrconv.ImportAll(env) + qfmt.ImportAll(env) state := &engineState{ env: env, pkgCache: make(map[string]*types.Package), diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/filters.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/filters.go index 52bfa643..604ae4a1 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/filters.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/filters.go @@ -9,6 +9,7 @@ import ( "github.com/quasilyte/gogrep" "github.com/quasilyte/gogrep/nodetag" + "golang.org/x/tools/go/ast/astutil" "github.com/quasilyte/go-ruleguard/internal/xtypes" "github.com/quasilyte/go-ruleguard/ruleguard/quasigo" @@ -160,6 +161,21 @@ func makeAddressableFilter(src, varname string) filterFunc { } } +func makeComparableFilter(src, varname string) filterFunc { + return func(params *filterParams) matchFilterResult { + if list, ok := params.subNode(varname).(gogrep.ExprSlice); ok { + return exprListFilterApply(src, list, func(x ast.Expr) bool { + return types.Comparable(params.typeofNode(x)) + }) + } + + if types.Comparable(params.typeofNode(params.subNode(varname))) { + return filterSuccess + } + return filterFailure(src) + } +} + func makeVarContainsFilter(src, varname string, pat *gogrep.Pattern) filterFunc { return func(params *filterParams) matchFilterResult { params.gogrepSubState.CapturePreset = params.match.CaptureList() @@ -186,7 +202,7 @@ func makeCustomVarFilter(src, varname string, fn *quasigo.Func) filterFunc { // We should probably catch the panic here, print trace and return "false" // from the filter (or even propagate that panic to let it crash). params.varname = varname - result := quasigo.Call(params.env, fn, params) + result := quasigo.Call(params.env, fn) if result.Value().(bool) { return filterSuccess } @@ -288,6 +304,21 @@ func makeTypesIdenticalFilter(src, lhsVarname, rhsVarname string) filterFunc { } } +func makeRootSinkTypeIsFilter(src string, pat *typematch.Pattern) filterFunc { + return func(params *filterParams) matchFilterResult { + // TODO(quasilyte): add variadic support? + e, ok := params.match.Node().(ast.Expr) + if ok { + parent, kv := findSinkRoot(params) + typ := findSinkType(params, parent, kv, e) + if pat.MatchIdentical(params.typematchState, typ) { + return filterSuccess + } + } + return filterFailure(src) + } +} + func makeTypeIsFilter(src, varname string, underlying bool, pat *typematch.Pattern) filterFunc { if underlying { return func(params *filterParams) matchFilterResult { @@ -645,3 +676,123 @@ func typeHasPointers(typ types.Type) bool { return true } } + +func findSinkRoot(params *filterParams) (ast.Node, *ast.KeyValueExpr) { + for i := 1; i < params.nodePath.Len(); i++ { + switch n := params.nodePath.NthParent(i).(type) { + case *ast.ParenExpr: + // Skip and continue. + continue + case *ast.KeyValueExpr: + return params.nodePath.NthParent(i + 1).(ast.Expr), n + default: + return n, nil + } + } + return nil, nil +} + +func findContainingFunc(params *filterParams) *types.Signature { + for i := 2; i < params.nodePath.Len(); i++ { + switch n := params.nodePath.NthParent(i).(type) { + case *ast.FuncDecl: + fn, ok := params.ctx.Types.TypeOf(n.Name).(*types.Signature) + if ok { + return fn + } + case *ast.FuncLit: + fn, ok := params.ctx.Types.TypeOf(n.Type).(*types.Signature) + if ok { + return fn + } + } + } + return nil +} + +func findSinkType(params *filterParams, parent ast.Node, kv *ast.KeyValueExpr, e ast.Expr) types.Type { + switch parent := parent.(type) { + case *ast.ValueSpec: + return params.ctx.Types.TypeOf(parent.Type) + + case *ast.ReturnStmt: + for i, result := range parent.Results { + if astutil.Unparen(result) != e { + continue + } + sig := findContainingFunc(params) + if sig == nil { + break + } + return sig.Results().At(i).Type() + } + + case *ast.IndexExpr: + if astutil.Unparen(parent.Index) == e { + switch typ := params.ctx.Types.TypeOf(parent.X).Underlying().(type) { + case *types.Map: + return typ.Key() + case *types.Slice, *types.Array: + return nil // TODO: some untyped int type? + } + } + + case *ast.AssignStmt: + if parent.Tok != token.ASSIGN || len(parent.Lhs) != len(parent.Rhs) { + break + } + for i, rhs := range parent.Rhs { + if rhs == e { + return params.ctx.Types.TypeOf(parent.Lhs[i]) + } + } + + case *ast.CompositeLit: + switch typ := params.ctx.Types.TypeOf(parent).Underlying().(type) { + case *types.Slice: + return typ.Elem() + case *types.Array: + return typ.Elem() + case *types.Map: + if astutil.Unparen(kv.Key) == e { + return typ.Key() + } + return typ.Elem() + case *types.Struct: + fieldName, ok := kv.Key.(*ast.Ident) + if !ok { + break + } + for i := 0; i < typ.NumFields(); i++ { + field := typ.Field(i) + if field.Name() == fieldName.String() { + return field.Type() + } + } + } + + case *ast.CallExpr: + switch typ := params.ctx.Types.TypeOf(parent.Fun).(type) { + case *types.Signature: + // A function call argument. + for i, arg := range parent.Args { + if astutil.Unparen(arg) != e { + continue + } + isVariadicArg := (i >= typ.Params().Len()-1) && typ.Variadic() + if isVariadicArg && !parent.Ellipsis.IsValid() { + return typ.Params().At(typ.Params().Len() - 1).Type().(*types.Slice).Elem() + } + if i < typ.Params().Len() { + return typ.Params().At(i).Type() + } + break + } + default: + // Probably a type cast. + return typ + } + } + + return invalidType +} diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go index 2574ac90..655fc5b8 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go @@ -38,6 +38,7 @@ type goRule struct { location string suggestion string filter matchFilter + do *quasigo.Func } type matchFilterResult string @@ -66,7 +67,8 @@ type filterParams struct { match matchData nodePath *nodePath - nodeText func(n ast.Node) []byte + nodeText func(n ast.Node) []byte + nodeString func(n ast.Node) string deadcode bool @@ -74,6 +76,10 @@ type filterParams struct { // varname is set only for custom filters before bytecode function is called. varname string + + // Both of these are Do() function related fields. + reportString string + suggestString string } func (params *filterParams) subNode(name string) ast.Node { @@ -104,7 +110,7 @@ func (params *filterParams) typeofNode(n ast.Node) types.Type { if typ := params.ctx.Types.TypeOf(e); typ != nil { return typ } - return types.Typ[types.Invalid] + return invalidType } func mergeRuleSets(toMerge []*goRuleSet) (*goRuleSet, error) { diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/filter_op.gen.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/filter_op.gen.go index 639724b0..c9401c02 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/filter_op.gen.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/filter_op.gen.go @@ -36,147 +36,154 @@ const ( // $Value type: string FilterVarAddressableOp FilterOp = 10 + // m[$Value].Comparable + // $Value type: string + FilterVarComparableOp FilterOp = 11 + // m[$Value].Pure // $Value type: string - FilterVarPureOp FilterOp = 11 + FilterVarPureOp FilterOp = 12 // m[$Value].Const // $Value type: string - FilterVarConstOp FilterOp = 12 + FilterVarConstOp FilterOp = 13 // m[$Value].ConstSlice // $Value type: string - FilterVarConstSliceOp FilterOp = 13 + FilterVarConstSliceOp FilterOp = 14 // m[$Value].Text // $Value type: string - FilterVarTextOp FilterOp = 14 + FilterVarTextOp FilterOp = 15 // m[$Value].Line // $Value type: string - FilterVarLineOp FilterOp = 15 + FilterVarLineOp FilterOp = 16 // m[$Value].Value.Int() // $Value type: string - FilterVarValueIntOp FilterOp = 16 + FilterVarValueIntOp FilterOp = 17 // m[$Value].Type.Size // $Value type: string - FilterVarTypeSizeOp FilterOp = 17 + FilterVarTypeSizeOp FilterOp = 18 // m[$Value].Type.HasPointers() // $Value type: string - FilterVarTypeHasPointersOp FilterOp = 18 + FilterVarTypeHasPointersOp FilterOp = 19 // m[$Value].Filter($Args[0]) // $Value type: string - FilterVarFilterOp FilterOp = 19 + FilterVarFilterOp FilterOp = 20 // m[$Value].Node.Is($Args[0]) // $Value type: string - FilterVarNodeIsOp FilterOp = 20 + FilterVarNodeIsOp FilterOp = 21 // m[$Value].Object.Is($Args[0]) // $Value type: string - FilterVarObjectIsOp FilterOp = 21 + FilterVarObjectIsOp FilterOp = 22 // m[$Value].Object.IsGlobal() // $Value type: string - FilterVarObjectIsGlobalOp FilterOp = 22 + FilterVarObjectIsGlobalOp FilterOp = 23 // m[$Value].Type.Is($Args[0]) // $Value type: string - FilterVarTypeIsOp FilterOp = 23 + FilterVarTypeIsOp FilterOp = 24 // m[$Value].Type.IdenticalTo($Args[0]) // $Value type: string - FilterVarTypeIdenticalToOp FilterOp = 24 + FilterVarTypeIdenticalToOp FilterOp = 25 // m[$Value].Type.Underlying().Is($Args[0]) // $Value type: string - FilterVarTypeUnderlyingIsOp FilterOp = 25 + FilterVarTypeUnderlyingIsOp FilterOp = 26 // m[$Value].Type.OfKind($Args[0]) // $Value type: string - FilterVarTypeOfKindOp FilterOp = 26 + FilterVarTypeOfKindOp FilterOp = 27 // m[$Value].Type.Underlying().OfKind($Args[0]) // $Value type: string - FilterVarTypeUnderlyingOfKindOp FilterOp = 27 + FilterVarTypeUnderlyingOfKindOp FilterOp = 28 // m[$Value].Type.ConvertibleTo($Args[0]) // $Value type: string - FilterVarTypeConvertibleToOp FilterOp = 28 + FilterVarTypeConvertibleToOp FilterOp = 29 // m[$Value].Type.AssignableTo($Args[0]) // $Value type: string - FilterVarTypeAssignableToOp FilterOp = 29 + FilterVarTypeAssignableToOp FilterOp = 30 // m[$Value].Type.Implements($Args[0]) // $Value type: string - FilterVarTypeImplementsOp FilterOp = 30 + FilterVarTypeImplementsOp FilterOp = 31 // m[$Value].Type.HasMethod($Args[0]) // $Value type: string - FilterVarTypeHasMethodOp FilterOp = 31 + FilterVarTypeHasMethodOp FilterOp = 32 // m[$Value].Text.Matches($Args[0]) // $Value type: string - FilterVarTextMatchesOp FilterOp = 32 + FilterVarTextMatchesOp FilterOp = 33 // m[$Value].Contains($Args[0]) // $Value type: string - FilterVarContainsOp FilterOp = 33 + FilterVarContainsOp FilterOp = 34 // m.Deadcode() - FilterDeadcodeOp FilterOp = 34 + FilterDeadcodeOp FilterOp = 35 // m.GoVersion().Eq($Value) // $Value type: string - FilterGoVersionEqOp FilterOp = 35 + FilterGoVersionEqOp FilterOp = 36 // m.GoVersion().LessThan($Value) // $Value type: string - FilterGoVersionLessThanOp FilterOp = 36 + FilterGoVersionLessThanOp FilterOp = 37 // m.GoVersion().GreaterThan($Value) // $Value type: string - FilterGoVersionGreaterThanOp FilterOp = 37 + FilterGoVersionGreaterThanOp FilterOp = 38 // m.GoVersion().LessEqThan($Value) // $Value type: string - FilterGoVersionLessEqThanOp FilterOp = 38 + FilterGoVersionLessEqThanOp FilterOp = 39 // m.GoVersion().GreaterEqThan($Value) // $Value type: string - FilterGoVersionGreaterEqThanOp FilterOp = 39 + FilterGoVersionGreaterEqThanOp FilterOp = 40 // m.File.Imports($Value) // $Value type: string - FilterFileImportsOp FilterOp = 40 + FilterFileImportsOp FilterOp = 41 // m.File.PkgPath.Matches($Value) // $Value type: string - FilterFilePkgPathMatchesOp FilterOp = 41 + FilterFilePkgPathMatchesOp FilterOp = 42 // m.File.Name.Matches($Value) // $Value type: string - FilterFileNameMatchesOp FilterOp = 42 + FilterFileNameMatchesOp FilterOp = 43 // $Value holds a function name // $Value type: string - FilterFilterFuncRefOp FilterOp = 43 + FilterFilterFuncRefOp FilterOp = 44 // $Value holds a string constant // $Value type: string - FilterStringOp FilterOp = 44 + FilterStringOp FilterOp = 45 // $Value holds an int64 constant // $Value type: int64 - FilterIntOp FilterOp = 45 + FilterIntOp FilterOp = 46 // m[`$$`].Node.Parent().Is($Args[0]) - FilterRootNodeParentIsOp FilterOp = 46 + FilterRootNodeParentIsOp FilterOp = 47 + + // m[`$$`].SinkType.Is($Args[0]) + FilterRootSinkTypeIsOp FilterOp = 48 ) var filterOpNames = map[FilterOp]string{ @@ -191,6 +198,7 @@ var filterOpNames = map[FilterOp]string{ FilterGtEqOp: `GtEq`, FilterLtEqOp: `LtEq`, FilterVarAddressableOp: `VarAddressable`, + FilterVarComparableOp: `VarComparable`, FilterVarPureOp: `VarPure`, FilterVarConstOp: `VarConst`, FilterVarConstSliceOp: `VarConstSlice`, @@ -227,6 +235,7 @@ var filterOpNames = map[FilterOp]string{ FilterStringOp: `String`, FilterIntOp: `Int`, FilterRootNodeParentIsOp: `RootNodeParentIs`, + FilterRootSinkTypeIsOp: `RootSinkTypeIs`, } var filterOpFlags = map[FilterOp]uint64{ FilterAndOp: flagIsBinaryExpr, @@ -238,6 +247,7 @@ var filterOpFlags = map[FilterOp]uint64{ FilterGtEqOp: flagIsBinaryExpr, FilterLtEqOp: flagIsBinaryExpr, FilterVarAddressableOp: flagHasVar, + FilterVarComparableOp: flagHasVar, FilterVarPureOp: flagHasVar, FilterVarConstOp: flagHasVar, FilterVarConstSliceOp: flagHasVar, diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/gen_filter_op.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/gen_filter_op.go index 3e9806d8..d3b74090 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/gen_filter_op.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/gen_filter_op.go @@ -41,6 +41,7 @@ func main() { {name: "LtEq", comment: "$Args[0] <= $Args[1]", flags: flagIsBinaryExpr}, {name: "VarAddressable", comment: "m[$Value].Addressable", valueType: "string", flags: flagHasVar}, + {name: "VarComparable", comment: "m[$Value].Comparable", valueType: "string", flags: flagHasVar}, {name: "VarPure", comment: "m[$Value].Pure", valueType: "string", flags: flagHasVar}, {name: "VarConst", comment: "m[$Value].Const", valueType: "string", flags: flagHasVar}, {name: "VarConstSlice", comment: "m[$Value].ConstSlice", valueType: "string", flags: flagHasVar}, @@ -85,6 +86,7 @@ func main() { {name: "Int", comment: "$Value holds an int64 constant", valueType: "int64", flags: flagIsBasicLit}, {name: "RootNodeParentIs", comment: "m[`$$`].Node.Parent().Is($Args[0])"}, + {name: "RootSinkTypeIs", comment: "m[`$$`].SinkType.Is($Args[0])"}, } var buf bytes.Buffer diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/ir.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/ir.go index 552ddd75..b8948116 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/ir.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ir/ir.go @@ -51,6 +51,7 @@ type Rule struct { ReportTemplate string SuggestTemplate string + DoFuncName string WhereExpr FilterExpr 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 ff107f97..c07a19f5 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 @@ -178,12 +178,12 @@ func (l *irLoader) compileFilterFuncs(filename string, irfile *ir.File) error { buf.WriteString("package gorules\n") buf.WriteString("import \"github.com/quasilyte/go-ruleguard/dsl\"\n") buf.WriteString("import \"github.com/quasilyte/go-ruleguard/dsl/types\"\n") - buf.WriteString("type _ = dsl.Matcher\n") - buf.WriteString("type _ = types.Type\n") for _, src := range irfile.CustomDecls { buf.WriteString(src) buf.WriteString("\n") } + buf.WriteString("type _ = dsl.Matcher\n") + buf.WriteString("type _ = types.Type\n") fset := token.NewFileSet() f, err := goutil.LoadGoFile(goutil.LoadConfig{ @@ -206,15 +206,16 @@ func (l *irLoader) compileFilterFuncs(filename string, irfile *ir.File) error { continue } ctx := &quasigo.CompileContext{ - Env: l.state.env, - Types: f.Types, - Fset: fset, + Env: l.state.env, + Package: f.Pkg, + Types: f.Types, + Fset: fset, } compiled, err := quasigo.Compile(ctx, decl) if err != nil { return err } - if l.ctx.DebugFilter == decl.Name.String() { + if l.ctx.DebugFunc == decl.Name.String() { l.ctx.DebugPrint(quasigo.Disasm(l.state.env, compiled)) } ctx.Env.AddFunc(f.Pkg.Path(), decl.Name.String(), compiled) @@ -272,6 +273,14 @@ func (l *irLoader) loadRule(group *ir.RuleGroup, rule *ir.Rule) error { location: rule.LocationVar, } + if rule.DoFuncName != "" { + doFn := l.state.env.GetFunc(l.file.PkgPath, rule.DoFuncName) + if doFn == nil { + return l.errorf(rule.Line, nil, "can't find a compiled version of %s", rule.DoFuncName) + } + proto.do = doFn + } + info := filterInfo{ Vars: make(map[string]struct{}), group: group, @@ -599,6 +608,18 @@ func (l *irLoader) newFilter(filter ir.FilterExpr, info *filterInfo) (matchFilte } result.fn = makeNodeIsFilter(result.src, filter.Value.(string), tag) + case ir.FilterRootSinkTypeIsOp: + typeString := l.unwrapStringExpr(filter.Args[0]) + if typeString == "" { + return result, l.errorf(filter.Line, nil, "expected a non-empty string argument") + } + ctx := typematch.Context{Itab: l.itab} + pat, err := typematch.Parse(&ctx, typeString) + if err != nil { + return result, l.errorf(filter.Line, err, "parse type expr") + } + result.fn = makeRootSinkTypeIsFilter(result.src, pat) + case ir.FilterVarTypeHasPointersOp: result.fn = makeTypeHasPointersFilter(result.src, filter.Value.(string)) @@ -682,6 +703,8 @@ func (l *irLoader) newFilter(filter ir.FilterExpr, info *filterInfo) (matchFilte result.fn = makeConstSliceFilter(result.src, filter.Value.(string)) case ir.FilterVarAddressableOp: result.fn = makeAddressableFilter(result.src, filter.Value.(string)) + case ir.FilterVarComparableOp: + result.fn = makeComparableFilter(result.src, filter.Value.(string)) case ir.FilterFileImportsOp: result.fn = makeFileImportsFilter(result.src, filter.Value.(string)) diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/irconv/irconv.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/irconv/irconv.go index 7ebd1fe3..646091fe 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/irconv/irconv.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/irconv/irconv.go @@ -95,6 +95,12 @@ func (conv *converter) ConvertFile(f *ast.File) *ir.File { conv.dslPkgname = imp.Name.Name } } + // Right now this list is hardcoded from the knowledge of which + // stdlib packages are supported inside the bytecode. + switch importPath { + case "fmt", "strings", "strconv": + conv.addCustomImport(result, importPath) + } } for _, decl := range f.Decls { @@ -161,6 +167,10 @@ func (conv *converter) convertInitFunc(dst *ir.File, decl *ast.FuncDecl) { } } +func (conv *converter) addCustomImport(dst *ir.File, pkgPath string) { + dst.CustomDecls = append(dst.CustomDecls, `import "`+pkgPath+`"`) +} + func (conv *converter) addCustomDecl(dst *ir.File, decl ast.Decl) { begin := conv.fset.Position(decl.Pos()) end := conv.fset.Position(decl.End()) @@ -436,6 +446,7 @@ func (conv *converter) convertRuleExpr(call *ast.CallExpr) { suggestArgs *[]ast.Expr reportArgs *[]ast.Expr atArgs *[]ast.Expr + doArgs *[]ast.Expr ) for { @@ -475,6 +486,8 @@ func (conv *converter) convertRuleExpr(call *ast.CallExpr) { panic(conv.errorf(chain.Sel, "Report() can't be repeated")) } reportArgs = &call.Args + case "Do": + doArgs = &call.Args case "At": if atArgs != nil { panic(conv.errorf(chain.Sel, "At() can't be repeated")) @@ -527,13 +540,27 @@ func (conv *converter) convertRuleExpr(call *ast.CallExpr) { rule.SuggestTemplate = conv.parseStringArg((*suggestArgs)[0]) } - if suggestArgs == nil && reportArgs == nil { - panic(conv.errorf(origCall, "missing Report() or Suggest() call")) + if suggestArgs == nil && reportArgs == nil && doArgs == nil { + panic(conv.errorf(origCall, "missing Report(), Suggest() or Do() call")) } - if reportArgs == nil { - rule.ReportTemplate = "suggestion: " + rule.SuggestTemplate + if doArgs != nil { + if suggestArgs != nil || reportArgs != nil { + panic(conv.errorf(origCall, "can't combine Report/Suggest with Do yet")) + } + if matchCommentArgs != nil { + panic(conv.errorf(origCall, "can't use Do() with MatchComment() yet")) + } + funcName, ok := (*doArgs)[0].(*ast.Ident) + if !ok { + panic(conv.errorf((*doArgs)[0], "only named function args are supported")) + } + rule.DoFuncName = funcName.String() } else { - rule.ReportTemplate = conv.parseStringArg((*reportArgs)[0]) + if reportArgs == nil { + rule.ReportTemplate = "suggestion: " + rule.SuggestTemplate + } else { + rule.ReportTemplate = conv.parseStringArg((*reportArgs)[0]) + } } for i, alt := range alternatives { @@ -636,6 +663,8 @@ func (conv *converter) convertFilterExprImpl(e ast.Expr) ir.FilterExpr { return ir.FilterExpr{Op: ir.FilterVarConstSliceOp, Value: op.varName} case "Addressable": return ir.FilterExpr{Op: ir.FilterVarAddressableOp, Value: op.varName} + case "Comparable": + return ir.FilterExpr{Op: ir.FilterVarComparableOp, Value: op.varName} case "Type.Size": return ir.FilterExpr{Op: ir.FilterVarTypeSizeOp, Value: op.varName} } @@ -717,6 +746,12 @@ func (conv *converter) convertFilterExprImpl(e ast.Expr) ir.FilterExpr { return ir.FilterExpr{Op: ir.FilterVarObjectIsOp, Value: op.varName, Args: args} case "Object.IsGlobal": return ir.FilterExpr{Op: ir.FilterVarObjectIsGlobalOp, Value: op.varName} + case "SinkType.Is": + if op.varName != "$$" { + // TODO: remove this restriction. + panic(conv.errorf(e.Args[0], "sink type is only implemented for $$ var")) + } + return ir.FilterExpr{Op: ir.FilterRootSinkTypeIsOp, Value: op.varName, Args: args} case "Type.HasPointers": return ir.FilterExpr{Op: ir.FilterVarTypeHasPointersOp, Value: op.varName} case "Type.Is": diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/libdsl.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/libdsl.go index 6202b7b8..d0e16161 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/libdsl.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/libdsl.go @@ -1,6 +1,7 @@ package ruleguard import ( + "fmt" "go/types" "github.com/quasilyte/go-ruleguard/internal/xtypes" @@ -28,12 +29,17 @@ import ( func initEnv(state *engineState, env *quasigo.Env) { nativeTypes := map[string]quasigoNative{ + `*github.com/quasilyte/go-ruleguard/dsl.MatchedText`: dslMatchedText{}, + `*github.com/quasilyte/go-ruleguard/dsl.DoVar`: dslDoVar{}, + `*github.com/quasilyte/go-ruleguard/dsl.DoContext`: dslDoContext{}, `*github.com/quasilyte/go-ruleguard/dsl.VarFilterContext`: dslVarFilterContext{state: state}, `github.com/quasilyte/go-ruleguard/dsl/types.Type`: dslTypesType{}, `*github.com/quasilyte/go-ruleguard/dsl/types.Interface`: dslTypesInterface{}, `*github.com/quasilyte/go-ruleguard/dsl/types.Pointer`: dslTypesPointer{}, + `*github.com/quasilyte/go-ruleguard/dsl/types.Struct`: dslTypesStruct{}, `*github.com/quasilyte/go-ruleguard/dsl/types.Array`: dslTypesArray{}, `*github.com/quasilyte/go-ruleguard/dsl/types.Slice`: dslTypesSlice{}, + `*github.com/quasilyte/go-ruleguard/dsl/types.Var`: dslTypesVar{}, } for qualifier, typ := range nativeTypes { @@ -162,6 +168,35 @@ func (dslTypesPointer) Elem(stack *quasigo.ValueStack) { stack.Push(stack.Pop().(*types.Pointer).Elem()) } +type dslTypesStruct struct{} + +func (native dslTypesStruct) funcs() map[string]func(*quasigo.ValueStack) { + return map[string]func(*quasigo.ValueStack){ + "Underlying": native.Underlying, + "String": native.String, + "NumFields": native.NumFields, + "Field": native.Field, + } +} + +func (dslTypesStruct) Underlying(stack *quasigo.ValueStack) { + stack.Push(stack.Pop().(*types.Struct).Underlying()) +} + +func (dslTypesStruct) String(stack *quasigo.ValueStack) { + stack.Push(stack.Pop().(*types.Struct).String()) +} + +func (dslTypesStruct) NumFields(stack *quasigo.ValueStack) { + stack.PushInt(stack.Pop().(*types.Struct).NumFields()) +} + +func (dslTypesStruct) Field(stack *quasigo.ValueStack) { + i := stack.PopInt() + typ := stack.Pop().(*types.Struct) + stack.Push(typ.Field(i)) +} + type dslTypesPackage struct{} func (native dslTypesPackage) funcs() map[string]func(*quasigo.ValueStack) { @@ -175,6 +210,7 @@ func (native dslTypesPackage) funcs() map[string]func(*quasigo.ValueStack) { "AsSlice": native.AsSlice, "AsPointer": native.AsPointer, "AsInterface": native.AsInterface, + "AsStruct": native.AsStruct, } } @@ -226,6 +262,95 @@ func (dslTypesPackage) AsInterface(stack *quasigo.ValueStack) { stack.Push(typ) } +func (dslTypesPackage) AsStruct(stack *quasigo.ValueStack) { + typ, _ := stack.Pop().(types.Type).(*types.Struct) + stack.Push(typ) +} + +type dslTypesVar struct{} + +func (native dslTypesVar) funcs() map[string]func(*quasigo.ValueStack) { + return map[string]func(*quasigo.ValueStack){ + "Embedded": native.Embedded, + "Type": native.Type, + } +} + +func (dslTypesVar) Embedded(stack *quasigo.ValueStack) { + stack.Push(stack.Pop().(*types.Var).Embedded()) +} + +func (dslTypesVar) Type(stack *quasigo.ValueStack) { + stack.Push(stack.Pop().(*types.Var).Type()) +} + +type dslDoContext struct{} + +func (native dslDoContext) funcs() map[string]func(*quasigo.ValueStack) { + return map[string]func(*quasigo.ValueStack){ + "SetReport": native.SetReport, + "SetSuggest": native.SetSuggest, + "Var": native.Var, + } +} + +func (native dslDoContext) Var(stack *quasigo.ValueStack) { + s := stack.Pop().(string) + params := stack.Pop().(*filterParams) + stack.Push(&dslDoVarRepr{params: params, name: s}) +} + +func (native dslDoContext) SetReport(stack *quasigo.ValueStack) { + s := stack.Pop().(string) + params := stack.Pop().(*filterParams) + params.reportString = s +} + +func (native dslDoContext) SetSuggest(stack *quasigo.ValueStack) { + s := stack.Pop().(string) + params := stack.Pop().(*filterParams) + params.suggestString = s +} + +type dslMatchedText struct{} + +func (native dslMatchedText) funcs() map[string]func(*quasigo.ValueStack) { + return map[string]func(*quasigo.ValueStack){ + "String": native.String, + } +} + +func (dslMatchedText) String(stack *quasigo.ValueStack) { + fmt.Printf("%T\n", stack.Pop()) + stack.Push("ok2") +} + +type dslDoVarRepr struct { + params *filterParams + name string +} + +type dslDoVar struct{} + +func (native dslDoVar) funcs() map[string]func(*quasigo.ValueStack) { + return map[string]func(*quasigo.ValueStack){ + "Text": native.Text, + "Type": native.Type, + } +} + +func (dslDoVar) Text(stack *quasigo.ValueStack) { + v := stack.Pop().(*dslDoVarRepr) + params := v.params + stack.Push(params.nodeString(params.subNode(v.name))) +} + +func (dslDoVar) Type(stack *quasigo.ValueStack) { + v := stack.Pop().(*dslDoVarRepr) + params := v.params + stack.Push(params.typeofNode(params.subNode(v.name))) +} + type dslVarFilterContext struct { state *engineState } diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/nodepath.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/nodepath.go index 98bfb399..b0f02f0a 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/nodepath.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/nodepath.go @@ -31,8 +31,8 @@ func (p nodePath) Current() ast.Node { } func (p nodePath) NthParent(n int) ast.Node { - index := len(p.stack) - n - 1 - if index >= 0 { + index := uint(len(p.stack) - n - 1) + if index < uint(len(p.stack)) { return p.stack[index] } return nil diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/compile.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/compile.go index 51584305..b81fb8f1 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/compile.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/compile.go @@ -54,7 +54,9 @@ type compiler struct { locals map[string]int constantsPool map[interface{}]int intConstantsPool map[int]int - params map[string]int + + params map[string]int + intParams map[string]int code []byte constants []interface{} @@ -89,20 +91,31 @@ func (cl *compiler) compileFunc(fn *ast.FuncDecl) *Func { panic(cl.errorUnsupportedType(fn.Name, cl.retType, "function result")) } - dbg := funcDebugInfo{ - paramNames: make([]string, cl.fnType.Params().Len()), - } - cl.params = make(map[string]int, cl.fnType.Params().Len()) + cl.intParams = make(map[string]int, cl.fnType.Params().Len()) for i := 0; i < cl.fnType.Params().Len(); i++ { p := cl.fnType.Params().At(i) paramName := p.Name() paramType := p.Type() - cl.params[paramName] = i - dbg.paramNames[i] = paramName if !cl.isSupportedType(paramType) { panic(cl.errorUnsupportedType(fn.Name, paramType, paramName+" param")) } + if typeIsInt(paramType) { + cl.intParams[paramName] = len(cl.intParams) + } else { + cl.params[paramName] = len(cl.params) + } + } + + dbg := funcDebugInfo{ + paramNames: make([]string, len(cl.params)), + intParamNames: make([]string, len(cl.intParams)), + } + for paramName, i := range cl.params { + dbg.paramNames[i] = paramName + } + for paramName, i := range cl.intParams { + dbg.intParamNames[i] = paramName } cl.compileStmt(fn.Body) @@ -111,9 +124,12 @@ func (cl *compiler) compileFunc(fn *ast.FuncDecl) *Func { } compiled := &Func{ - code: cl.code, - constants: cl.constants, - intConstants: cl.intConstants, + code: cl.code, + constants: cl.constants, + intConstants: cl.intConstants, + numObjectParams: len(cl.params), + numIntParams: len(cl.intParams), + name: cl.ctx.Package.Path() + "." + fn.Name.String(), } if len(cl.locals) != 0 { dbg.localNames = make([]string, len(cl.locals)) @@ -298,10 +314,20 @@ func (cl *compiler) compileAssignStmt(assign *ast.AssignStmt) { } } +func (cl *compiler) isParamName(varname string) bool { + if _, ok := cl.params[varname]; ok { + return true + } + if _, ok := cl.intParams[varname]; ok { + return true + } + return false +} + func (cl *compiler) getLocal(v ast.Expr, varname string) int { id, ok := cl.locals[varname] if !ok { - if _, ok := cl.params[varname]; ok { + if cl.isParamName(varname) { panic(cl.errorf(v, "can't assign to %s, params are readonly", varname)) } panic(cl.errorf(v, "%s is not a writeable local variable", varname)) @@ -552,19 +578,51 @@ func (cl *compiler) compileCallExpr(call *ast.CallExpr) { if sig.Variadic() { variadic = sig.Params().Len() - 1 } - if !cl.compileNativeCall(key, variadic, expr, call.Args) { - panic(cl.errorf(call.Fun, "can't compile a call to %s func", key)) + if expr != nil { + cl.compileExpr(expr) + } + if cl.compileNativeCall(key, variadic, expr, call.Args) { + return + } + if cl.compileCall(key, sig, call.Args) { + return } + panic(cl.errorf(call.Fun, "can't compile a call to %s func", key)) } -func (cl *compiler) compileNativeCall(key funcKey, variadic int, expr ast.Expr, args []ast.Expr) bool { - funcID, ok := cl.ctx.Env.nameToNativeFuncID[key] +func (cl *compiler) compileCall(key funcKey, sig *types.Signature, args []ast.Expr) bool { + if sig.Variadic() { + return false + } + + funcID, ok := cl.ctx.Env.nameToFuncID[key] if !ok { return false } - if expr != nil { - cl.compileExpr(expr) + + for _, arg := range args { + cl.compileExpr(arg) + } + + var op opcode + if sig.Results().Len() == 0 { + op = opVoidCall + } else if typeIsInt(sig.Results().At(0).Type()) { + op = opIntCall + } else { + op = opCall + } + + cl.emit16(op, int(funcID)) + return true +} + +func (cl *compiler) compileNativeCall(key funcKey, variadic int, funcExpr ast.Expr, args []ast.Expr) bool { + funcID, ok := cl.ctx.Env.nameToNativeFuncID[key] + if !ok { + return false } + if len(args) == 1 { // Check that it's not a f(g()) call, where g() returns // a multi-value result; we can't compile that yet. @@ -596,7 +654,7 @@ func (cl *compiler) compileNativeCall(key funcKey, variadic int, expr ast.Expr, } } if len(variadicArgs) > 255 { - panic(cl.errorf(expr, "too many variadic args")) + panic(cl.errorf(funcExpr, "too many variadic args")) } // Even if len(variadicArgs) is 0, we still need to overwrite // the old variadicLen value, so the variadic func is not confused @@ -645,7 +703,11 @@ func (cl *compiler) compileIdent(ident *ast.Ident) { return } if paramIndex, ok := cl.params[ident.String()]; ok { - cl.emit8(pickOp(typeIsInt(tv.Type), opPushIntParam, opPushParam), paramIndex) + cl.emit8(opPushParam, paramIndex) + return + } + if paramIndex, ok := cl.intParams[ident.String()]; ok { + cl.emit8(opPushIntParam, paramIndex) return } if localIndex, ok := cl.locals[ident.String()]; ok { diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/debug_info.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/debug_info.go index e42bbb76..057c02bc 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/debug_info.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/debug_info.go @@ -5,8 +5,9 @@ type debugInfo struct { } type funcDebugInfo struct { - paramNames []string - localNames []string + paramNames []string + intParamNames []string + localNames []string } func newDebugInfo() *debugInfo { diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/disasm.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/disasm.go index 8859dee9..cafc9ed5 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/disasm.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/disasm.go @@ -39,10 +39,18 @@ func disasm(env *Env, fn *Func) string { id := decode16(code, pc+1) arg = id comment = env.nativeFuncs[id].name - case opPushParam, opPushIntParam: + case opCall, opIntCall, opVoidCall: + id := decode16(code, pc+1) + arg = id + comment = env.userFuncs[id].name + case opPushParam: index := int(code[pc+1]) arg = index comment = dbg.paramNames[index] + case opPushIntParam: + index := int(code[pc+1]) + arg = index + comment = dbg.intParamNames[index] case opSetLocal, opSetIntLocal, opPushLocal, opPushIntLocal, opIncLocal, opDecLocal: index := int(code[pc+1]) arg = index diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/eval.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/eval.go index da16455f..311da15a 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/eval.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/eval.go @@ -38,22 +38,22 @@ func (s *ValueStack) dup() { s.objects = append(s.objects, s.objects[len(s.objec // Identical to s.Pop() without using the result. func (s *ValueStack) discard() { s.objects = s.objects[:len(s.objects)-1] } -func eval(env *EvalEnv, fn *Func, args []interface{}) CallResult { +func eval(env *EvalEnv, fn *Func, top, intTop int) CallResult { pc := 0 code := fn.code - stack := env.stack + stack := &env.Stack var locals [maxFuncLocals]interface{} var intLocals [maxFuncLocals]int for { switch op := opcode(code[pc]); op { case opPushParam: - index := code[pc+1] - stack.Push(args[index]) + index := int(code[pc+1]) + stack.Push(stack.objects[top+index]) pc += 2 case opPushIntParam: - index := code[pc+1] - stack.PushInt(args[index].(int)) + index := int(code[pc+1]) + stack.PushInt(stack.ints[intTop+index]) pc += 2 case opPushLocal: @@ -129,6 +129,23 @@ func eval(env *EvalEnv, fn *Func, args []interface{}) CallResult { fn := env.nativeFuncs[id].mappedFunc fn(stack) pc += 3 + case opCall: + id := decode16(code, pc+1) + fn := env.userFuncs[id] + result := eval(env, fn, len(stack.objects)-fn.numObjectParams, len(stack.ints)-fn.numIntParams) + stack.Push(result.Value()) + pc += 3 + case opIntCall: + id := decode16(code, pc+1) + fn := env.userFuncs[id] + result := eval(env, fn, len(stack.objects)-fn.numObjectParams, len(stack.ints)-fn.numIntParams) + stack.PushInt(result.IntValue()) + pc += 3 + case opVoidCall: + id := decode16(code, pc+1) + fn := env.userFuncs[id] + eval(env, fn, len(stack.objects)-fn.numObjectParams, len(stack.ints)-fn.numIntParams) + pc += 3 case opJump: offset := decode16(code, pc+1) diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/gen_opcodes.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/gen_opcodes.go index 6f8f26d5..c8d51203 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/gen_opcodes.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/gen_opcodes.go @@ -45,6 +45,9 @@ var opcodePrototypes = []opcodeProto{ {"SetVariadicLen", "op len:u8", stackUnchanged}, {"CallNative", "op funcid:u16", "(args...) -> (results...)"}, + {"Call", "op funcid:u16", "(args...) -> (result)"}, + {"IntCall", "op funcid:u16", "(args...) -> (result:int)"}, + {"VoidCall", "op funcid:u16", "(args...) -> ()"}, {"IsNil", "op", "(value) -> (result:bool)"}, {"IsNotNil", "op", "(value) -> (result:bool)"}, diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcode_string.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcode_string.go index 27dfc494..3136214b 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcode_string.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcode_string.go @@ -34,29 +34,32 @@ func _() { _ = x[opJumpTrue-23] _ = x[opSetVariadicLen-24] _ = x[opCallNative-25] - _ = x[opIsNil-26] - _ = x[opIsNotNil-27] - _ = x[opNot-28] - _ = x[opEqInt-29] - _ = x[opNotEqInt-30] - _ = x[opGtInt-31] - _ = x[opGtEqInt-32] - _ = x[opLtInt-33] - _ = x[opLtEqInt-34] - _ = x[opEqString-35] - _ = x[opNotEqString-36] - _ = x[opConcat-37] - _ = x[opAdd-38] - _ = x[opSub-39] - _ = x[opStringSlice-40] - _ = x[opStringSliceFrom-41] - _ = x[opStringSliceTo-42] - _ = x[opStringLen-43] + _ = x[opCall-26] + _ = x[opIntCall-27] + _ = x[opVoidCall-28] + _ = x[opIsNil-29] + _ = x[opIsNotNil-30] + _ = x[opNot-31] + _ = x[opEqInt-32] + _ = x[opNotEqInt-33] + _ = x[opGtInt-34] + _ = x[opGtEqInt-35] + _ = x[opLtInt-36] + _ = x[opLtEqInt-37] + _ = x[opEqString-38] + _ = x[opNotEqString-39] + _ = x[opConcat-40] + _ = x[opAdd-41] + _ = x[opSub-42] + _ = x[opStringSlice-43] + _ = x[opStringSliceFrom-44] + _ = x[opStringSliceTo-45] + _ = x[opStringLen-46] } -const _opcode_name = "InvalidPopDupPushParamPushIntParamPushLocalPushIntLocalPushFalsePushTruePushConstPushIntConstConvIntToIfaceSetLocalSetIntLocalIncLocalDecLocalReturnTopReturnIntTopReturnFalseReturnTrueReturnJumpJumpFalseJumpTrueSetVariadicLenCallNativeIsNilIsNotNilNotEqIntNotEqIntGtIntGtEqIntLtIntLtEqIntEqStringNotEqStringConcatAddSubStringSliceStringSliceFromStringSliceToStringLen" +const _opcode_name = "InvalidPopDupPushParamPushIntParamPushLocalPushIntLocalPushFalsePushTruePushConstPushIntConstConvIntToIfaceSetLocalSetIntLocalIncLocalDecLocalReturnTopReturnIntTopReturnFalseReturnTrueReturnJumpJumpFalseJumpTrueSetVariadicLenCallNativeCallIntCallVoidCallIsNilIsNotNilNotEqIntNotEqIntGtIntGtEqIntLtIntLtEqIntEqStringNotEqStringConcatAddSubStringSliceStringSliceFromStringSliceToStringLen" -var _opcode_index = [...]uint16{0, 7, 10, 13, 22, 34, 43, 55, 64, 72, 81, 93, 107, 115, 126, 134, 142, 151, 163, 174, 184, 190, 194, 203, 211, 225, 235, 240, 248, 251, 256, 264, 269, 276, 281, 288, 296, 307, 313, 316, 319, 330, 345, 358, 367} +var _opcode_index = [...]uint16{0, 7, 10, 13, 22, 34, 43, 55, 64, 72, 81, 93, 107, 115, 126, 134, 142, 151, 163, 174, 184, 190, 194, 203, 211, 225, 235, 239, 246, 254, 259, 267, 270, 275, 283, 288, 295, 300, 307, 315, 326, 332, 335, 338, 349, 364, 377, 386} func (i opcode) String() string { if i >= opcode(len(_opcode_index)-1) { diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcodes.gen.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcodes.gen.go index a12aecd5..a3ec270d 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcodes.gen.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/opcodes.gen.go @@ -108,77 +108,89 @@ const ( // Stack effect: (args...) -> (results...) opCallNative opcode = 25 - // Encoding: 0x1a (width=1) - // Stack effect: (value) -> (result:bool) - opIsNil opcode = 26 + // Encoding: 0x1a funcid:u16 (width=3) + // Stack effect: (args...) -> (result) + opCall opcode = 26 - // Encoding: 0x1b (width=1) - // Stack effect: (value) -> (result:bool) - opIsNotNil opcode = 27 + // Encoding: 0x1b funcid:u16 (width=3) + // Stack effect: (args...) -> (result:int) + opIntCall opcode = 27 - // Encoding: 0x1c (width=1) - // Stack effect: (value:bool) -> (result:bool) - opNot opcode = 28 + // Encoding: 0x1c funcid:u16 (width=3) + // Stack effect: (args...) -> () + opVoidCall opcode = 28 // Encoding: 0x1d (width=1) - // Stack effect: (x:int y:int) -> (result:bool) - opEqInt opcode = 29 + // Stack effect: (value) -> (result:bool) + opIsNil opcode = 29 // Encoding: 0x1e (width=1) - // Stack effect: (x:int y:int) -> (result:bool) - opNotEqInt opcode = 30 + // Stack effect: (value) -> (result:bool) + opIsNotNil opcode = 30 // Encoding: 0x1f (width=1) - // Stack effect: (x:int y:int) -> (result:bool) - opGtInt opcode = 31 + // Stack effect: (value:bool) -> (result:bool) + opNot opcode = 31 // Encoding: 0x20 (width=1) // Stack effect: (x:int y:int) -> (result:bool) - opGtEqInt opcode = 32 + opEqInt opcode = 32 // Encoding: 0x21 (width=1) // Stack effect: (x:int y:int) -> (result:bool) - opLtInt opcode = 33 + opNotEqInt opcode = 33 // Encoding: 0x22 (width=1) // Stack effect: (x:int y:int) -> (result:bool) - opLtEqInt opcode = 34 + opGtInt opcode = 34 // Encoding: 0x23 (width=1) - // Stack effect: (x:string y:string) -> (result:bool) - opEqString opcode = 35 + // Stack effect: (x:int y:int) -> (result:bool) + opGtEqInt opcode = 35 // Encoding: 0x24 (width=1) - // Stack effect: (x:string y:string) -> (result:bool) - opNotEqString opcode = 36 + // Stack effect: (x:int y:int) -> (result:bool) + opLtInt opcode = 36 // Encoding: 0x25 (width=1) - // Stack effect: (x:string y:string) -> (result:string) - opConcat opcode = 37 + // Stack effect: (x:int y:int) -> (result:bool) + opLtEqInt opcode = 37 // Encoding: 0x26 (width=1) - // Stack effect: (x:int y:int) -> (result:int) - opAdd opcode = 38 + // Stack effect: (x:string y:string) -> (result:bool) + opEqString opcode = 38 // Encoding: 0x27 (width=1) - // Stack effect: (x:int y:int) -> (result:int) - opSub opcode = 39 + // Stack effect: (x:string y:string) -> (result:bool) + opNotEqString opcode = 39 // Encoding: 0x28 (width=1) - // Stack effect: (s:string from:int to:int) -> (result:string) - opStringSlice opcode = 40 + // Stack effect: (x:string y:string) -> (result:string) + opConcat opcode = 40 // Encoding: 0x29 (width=1) - // Stack effect: (s:string from:int) -> (result:string) - opStringSliceFrom opcode = 41 + // Stack effect: (x:int y:int) -> (result:int) + opAdd opcode = 41 // Encoding: 0x2a (width=1) - // Stack effect: (s:string to:int) -> (result:string) - opStringSliceTo opcode = 42 + // Stack effect: (x:int y:int) -> (result:int) + opSub opcode = 42 // Encoding: 0x2b (width=1) + // Stack effect: (s:string from:int to:int) -> (result:string) + opStringSlice opcode = 43 + + // Encoding: 0x2c (width=1) + // Stack effect: (s:string from:int) -> (result:string) + opStringSliceFrom opcode = 44 + + // Encoding: 0x2d (width=1) + // Stack effect: (s:string to:int) -> (result:string) + opStringSliceTo opcode = 45 + + // Encoding: 0x2e (width=1) // Stack effect: (s:string) -> (result:int) - opStringLen opcode = 43 + opStringLen opcode = 46 ) type opcodeInfo struct { @@ -213,6 +225,9 @@ var opcodeInfoTable = [256]opcodeInfo{ opJumpTrue: {width: 3}, opSetVariadicLen: {width: 2}, opCallNative: {width: 3}, + opCall: {width: 3}, + opIntCall: {width: 3}, + opVoidCall: {width: 3}, opIsNil: {width: 1}, opIsNotNil: {width: 1}, opNot: {width: 1}, diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/quasigo.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/quasigo.go index 0f66bde2..8ac75771 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/quasigo.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/quasigo.go @@ -34,7 +34,7 @@ type EvalEnv struct { nativeFuncs []nativeFunc userFuncs []*Func - stack *ValueStack + Stack ValueStack } // NewEnv creates a new empty environment. @@ -47,7 +47,7 @@ func (env *Env) GetEvalEnv() *EvalEnv { return &EvalEnv{ nativeFuncs: env.nativeFuncs, userFuncs: env.userFuncs, - stack: &ValueStack{ + Stack: ValueStack{ objects: make([]interface{}, 0, 32), ints: make([]int, 0, 16), }, @@ -84,8 +84,9 @@ type CompileContext struct { // being compiled; then it should be used to execute these functions. Env *Env - Types *types.Info - Fset *token.FileSet + Package *types.Package + Types *types.Info + Fset *token.FileSet } // Compile prepares an executable version of fn. @@ -93,11 +94,19 @@ func Compile(ctx *CompileContext, fn *ast.FuncDecl) (compiled *Func, err error) return compile(ctx, fn) } -// Call invokes a given function with provided arguments. -func Call(env *EvalEnv, fn *Func, args ...interface{}) CallResult { - env.stack.objects = env.stack.objects[:0] - env.stack.ints = env.stack.ints[:0] - return eval(env, fn, args) +// Call invokes a given function. +// All arguments should be pushed to env.Stack prior to this call. +// +// Note that arguments are not popped off the stack, +// so you can bind the args once and use Call multiple times. +// If you want to reset arguments, do env.Stack.Reset(). +func Call(env *EvalEnv, fn *Func) CallResult { + numObjectArgs := len(env.Stack.objects) + numIntArgs := len(env.Stack.ints) + result := eval(env, fn, 0, 0) + env.Stack.objects = env.Stack.objects[:numObjectArgs] + env.Stack.ints = env.Stack.ints[:numIntArgs] + return result } // CallResult is a return value of Call function. @@ -128,6 +137,11 @@ type Func struct { constants []interface{} intConstants []int + + numObjectParams int + numIntParams int + + name string } // ValueStack is used to manipulate runtime values during the evaluation. @@ -143,6 +157,12 @@ type ValueStack struct { variadicLen int } +// Reset empties the stack. +func (s *ValueStack) Reset() { + s.objects = s.objects[:0] + s.ints = s.ints[:0] +} + // Pop removes the top stack element and returns it. // Important: for int-typed values, use PopInt. func (s *ValueStack) Pop() interface{} { diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qfmt/qfmt.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qfmt/qfmt.go new file mode 100644 index 00000000..249ac256 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qfmt/qfmt.go @@ -0,0 +1,17 @@ +package qfmt + +import ( + "fmt" + + "github.com/quasilyte/go-ruleguard/ruleguard/quasigo" +) + +func ImportAll(env *quasigo.Env) { + env.AddNativeFunc(`fmt`, `Sprintf`, Sprintf) +} + +func Sprintf(stack *quasigo.ValueStack) { + args := stack.PopVariadic() + format := stack.Pop().(string) + stack.Push(fmt.Sprintf(format, args...)) +} diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrconv/qstrconv.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrconv/qstrconv.go new file mode 100644 index 00000000..8bc2d943 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrconv/qstrconv.go @@ -0,0 +1,24 @@ +package qstrconv + +import ( + "strconv" + + "github.com/quasilyte/go-ruleguard/ruleguard/quasigo" +) + +func ImportAll(env *quasigo.Env) { + env.AddNativeFunc(`strconv`, `Atoi`, Atoi) + env.AddNativeFunc(`strconv`, `Itoa`, Itoa) +} + +func Atoi(stack *quasigo.ValueStack) { + s := stack.Pop().(string) + v, err := strconv.Atoi(s) + stack.PushInt(v) + stack.Push(err) +} + +func Itoa(stack *quasigo.ValueStack) { + i := stack.PopInt() + stack.Push(strconv.Itoa(i)) +} diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrings/qstrings.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrings/qstrings.go new file mode 100644 index 00000000..6b708ad9 --- /dev/null +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qstrings/qstrings.go @@ -0,0 +1,62 @@ +package qstrings + +import ( + "strings" + + "github.com/quasilyte/go-ruleguard/ruleguard/quasigo" +) + +func ImportAll(env *quasigo.Env) { + env.AddNativeFunc(`strings`, `Replace`, Replace) + env.AddNativeFunc(`strings`, `ReplaceAll`, ReplaceAll) + env.AddNativeFunc(`strings`, `TrimPrefix`, TrimPrefix) + env.AddNativeFunc(`strings`, `TrimSuffix`, TrimSuffix) + env.AddNativeFunc(`strings`, `HasPrefix`, HasPrefix) + env.AddNativeFunc(`strings`, `HasSuffix`, HasSuffix) + env.AddNativeFunc(`strings`, `Contains`, Contains) +} + +func Replace(stack *quasigo.ValueStack) { + n := stack.PopInt() + newPart := stack.Pop().(string) + oldPart := stack.Pop().(string) + s := stack.Pop().(string) + stack.Push(strings.Replace(s, oldPart, newPart, n)) +} + +func ReplaceAll(stack *quasigo.ValueStack) { + newPart := stack.Pop().(string) + oldPart := stack.Pop().(string) + s := stack.Pop().(string) + stack.Push(strings.ReplaceAll(s, oldPart, newPart)) +} + +func TrimPrefix(stack *quasigo.ValueStack) { + prefix := stack.Pop().(string) + s := stack.Pop().(string) + stack.Push(strings.TrimPrefix(s, prefix)) +} + +func TrimSuffix(stack *quasigo.ValueStack) { + prefix := stack.Pop().(string) + s := stack.Pop().(string) + stack.Push(strings.TrimSuffix(s, prefix)) +} + +func HasPrefix(stack *quasigo.ValueStack) { + prefix := stack.Pop().(string) + s := stack.Pop().(string) + stack.Push(strings.HasPrefix(s, prefix)) +} + +func HasSuffix(stack *quasigo.ValueStack) { + suffix := stack.Pop().(string) + s := stack.Pop().(string) + stack.Push(strings.HasSuffix(s, suffix)) +} + +func Contains(stack *quasigo.ValueStack) { + substr := stack.Pop().(string) + s := stack.Pop().(string) + stack.Push(strings.Contains(s, substr)) +} diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go index 896fedea..1a2e2f05 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go @@ -75,7 +75,7 @@ func (e *Engine) Run(ctx *RunContext, f *ast.File) error { } type LoadContext struct { - DebugFilter string + DebugFunc string DebugImports bool DebugPrint func(string) diff --git a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go index 8ad23933..92f6cc34 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go @@ -17,6 +17,7 @@ import ( "github.com/quasilyte/go-ruleguard/ruleguard/goutil" "github.com/quasilyte/go-ruleguard/ruleguard/profiling" + "github.com/quasilyte/go-ruleguard/ruleguard/quasigo" "github.com/quasilyte/go-ruleguard/ruleguard/typematch" "github.com/quasilyte/gogrep" "github.com/quasilyte/gogrep/nodetag" @@ -71,6 +72,7 @@ func newRulesRunner(ctx *RunContext, buildContext *build.Context, state *engineS gogrepState.Types = ctx.Types gogrepSubState := gogrep.NewMatcherState() gogrepSubState.Types = ctx.Types + evalEnv := state.env.GetEvalEnv() rr := &rulesRunner{ bgContext: context.Background(), ctx: ctx, @@ -82,20 +84,27 @@ func newRulesRunner(ctx *RunContext, buildContext *build.Context, state *engineS truncateLen: ctx.TruncateLen, filterParams: filterParams{ typematchState: typematch.NewMatcherState(), - env: state.env.GetEvalEnv(), + env: evalEnv, importer: importer, ctx: ctx, }, } + evalEnv.Stack.Push(&rr.filterParams) if ctx.TruncateLen == 0 { rr.truncateLen = 60 } rr.filterParams.nodeText = rr.nodeText + rr.filterParams.nodeString = rr.nodeString rr.filterParams.nodePath = &rr.nodePath rr.filterParams.gogrepSubState = &rr.gogrepSubState return rr } +func (rr *rulesRunner) nodeString(n ast.Node) string { + b := rr.nodeText(n) + return string(b) +} + func (rr *rulesRunner) nodeText(n ast.Node) []byte { if gogrep.IsEmptyNodeSlice(n) { return nil @@ -335,8 +344,11 @@ func (rr *rulesRunner) handleCommentMatch(rule goCommentRule, m commentMatchData } func (rr *rulesRunner) handleMatch(rule goRule, m gogrep.MatchData) bool { - if rule.filter.fn != nil { + if rule.filter.fn != nil || rule.do != nil { rr.filterParams.match = astMatchData{match: m} + } + + if rule.filter.fn != nil { filterResult := rule.filter.fn(&rr.filterParams) if !filterResult.Matched() { rr.reject(rule, filterResult.RejectReason(), astMatchData{match: m}) @@ -344,26 +356,51 @@ func (rr *rulesRunner) handleMatch(rule goRule, m gogrep.MatchData) bool { } } - message := rr.renderMessage(rule.msg, astMatchData{match: m}, true) node := m.Node if rule.location != "" { node, _ = m.CapturedByName(rule.location) } + + var messageText string + var suggestText string + if rule.do != nil { + rr.filterParams.reportString = "" + rr.filterParams.suggestString = "" + _ = quasigo.Call(rr.filterParams.env, rule.do) + messageText = rr.filterParams.reportString + if messageText == "" { + if rr.filterParams.suggestString != "" { + messageText = "suggestion: " + rr.filterParams.suggestString + } else { + messageText = "" + } + } + if rr.filterParams.suggestString != "" { + suggestText = rr.filterParams.suggestString + } + } else { + messageText = rr.renderMessage(rule.msg, astMatchData{match: m}, true) + if rule.suggestion != "" { + suggestText = rr.renderMessage(rule.suggestion, astMatchData{match: m}, false) + } + } + var suggestion *Suggestion - if rule.suggestion != "" { + if suggestText != "" { suggestion = &Suggestion{ - Replacement: []byte(rr.renderMessage(rule.suggestion, astMatchData{match: m}, false)), + Replacement: []byte(suggestText), From: node.Pos(), To: node.End(), } } + info := GoRuleInfo{ Group: rule.group, Line: rule.line, } rr.reportData.RuleInfo = info rr.reportData.Node = node - rr.reportData.Message = message + rr.reportData.Message = messageText rr.reportData.Suggestion = suggestion rr.reportData.Func = rr.filterParams.currentFunc 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 4e8adc85..962e9da2 100644 --- a/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go +++ b/tools/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go @@ -11,6 +11,8 @@ import ( "strings" ) +var invalidType = types.Typ[types.Invalid] + func regexpHasCaptureGroups(pattern string) bool { // regexp.Compile() uses syntax.Perl flags, so // we use the same flags here. diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml b/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml index fc05c0e3..0fbf6c04 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml +++ b/tools/vendor/github.com/ryancurrah/gomodguard/.golangci.yml @@ -7,7 +7,6 @@ linters-settings: severity: warning rules: - name: atomic - # - name: bare-return - name: blank-imports - name: bool-literal-in-expr - name: call-to-gc @@ -28,7 +27,6 @@ linters-settings: - name: error-strings - name: errorf - name: exported - # - name: flag-parameter - name: get-return - name: identical-branches - name: if-return @@ -50,11 +48,9 @@ linters-settings: - name: unconditional-recursion - name: unexported-naming - name: unexported-return - # - name: unhandled-error - name: unnecessary-stmt - name: unreachable-code - name: unused-parameter - # - name: unused-receiver - name: var-declaration - name: var-naming - name: waitgroup-by-value @@ -64,7 +60,6 @@ linters: enable: - asciicheck - bodyclose - # - cyclop - deadcode - dogsled - dupl @@ -72,13 +67,9 @@ linters: - errcheck - errorlint - exhaustive - # - exhaustivestruct - exportloopref - # - forbidigo - forcetypeassert - funlen - # - gci - # - gochecknoglobals - gochecknoinits - gocognit - goconst @@ -86,16 +77,13 @@ linters: - gocyclo - godot - godox - - goerr113 - goimports - - gomnd - gomoddirectives - gomodguard - goprintffuncname - gosec - gosimple - govet - # - ifshort - importas - ineffassign - lll @@ -104,20 +92,16 @@ linters: - nakedret - nestif - nilerr - # - nlreturn - noctx - nolintlint - # - paralleltest - prealloc - predeclared - # - promlinter - revive - rowserrcheck - sqlclosecheck - staticcheck - structcheck - stylecheck - # - tagliatelle - testpackage - thelper - tparallel @@ -126,7 +110,5 @@ linters: - unparam - unused - varcheck - # - wastedassign - whitespace - # - wrapcheck - wsl diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/Makefile b/tools/vendor/github.com/ryancurrah/gomodguard/Makefile index a1962834..76667579 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/Makefile +++ b/tools/vendor/github.com/ryancurrah/gomodguard/Makefile @@ -33,7 +33,7 @@ clean: rm -rf dist/ rm -f gomodguard coverage.xml coverage.out -.PHONY: install-tools-mac +.PHONY: install-mac-tools install-tools-mac: brew install goreleaser/tap/goreleaser diff --git a/tools/vendor/github.com/ryancurrah/gomodguard/gomodguard.go b/tools/vendor/github.com/ryancurrah/gomodguard/gomodguard.go index 7ef46236..efd0d17e 100644 --- a/tools/vendor/github.com/ryancurrah/gomodguard/gomodguard.go +++ b/tools/vendor/github.com/ryancurrah/gomodguard/gomodguard.go @@ -10,6 +10,7 @@ import ( "io/ioutil" "os" "os/exec" + "regexp" "strings" "github.com/Masterminds/semver" @@ -30,6 +31,11 @@ var ( "blocked modules list." blockReasonHasLocalReplaceDirective = "import of package `%s` is blocked because the module has a " + "local replace directive." + + // 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" + // probably indicates that the module is actually github.com/foo/bar/v2, not github.com/foo/bar. + startsWithVersion = regexp.MustCompile(`^\/v[0-9]+`) ) // BlockedVersion has a version constraint a reason why the the module version is blocked. @@ -438,6 +444,13 @@ func (p *Processor) SetBlockedModules() { //nolint:gocognit,funlen func (p *Processor) isBlockedPackageFromModFile(packageName string) []string { for blockedModuleName, blockReasons := range p.blockedModulesFromModFile { if strings.HasPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName)) { + // Test if a versioned module matched its base version + // ie github.com/foo/bar/v2 matched github.com/foo/bar, even though the former may be allowed. + suffix := strings.TrimPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName)) + if startsWithVersion.MatchString(suffix) { + continue + } + formattedReasons := make([]string, 0, len(blockReasons)) for _, blockReason := range blockReasons { diff --git a/tools/vendor/github.com/sashamelentyev/interfacebloat/LICENSE b/tools/vendor/github.com/sashamelentyev/interfacebloat/LICENSE new file mode 100644 index 00000000..a52602b3 --- /dev/null +++ b/tools/vendor/github.com/sashamelentyev/interfacebloat/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Sasha Melentyev + +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/sashamelentyev/interfacebloat/pkg/analyzer/analyzer.go b/tools/vendor/github.com/sashamelentyev/interfacebloat/pkg/analyzer/analyzer.go new file mode 100644 index 00000000..4a6afdf8 --- /dev/null +++ b/tools/vendor/github.com/sashamelentyev/interfacebloat/pkg/analyzer/analyzer.go @@ -0,0 +1,57 @@ +package analyzer + +import ( + "flag" + "go/ast" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +const InterfaceMaxMethodsFlag = "max" + +const defaultMaxMethods = 10 + +// New returns new interfacebloat analyzer. +func New() *analysis.Analyzer { + return &analysis.Analyzer{ + Name: "interfacebloat", + Doc: "A linter that checks the number of methods inside an interface.", + Run: run, + Flags: flags(), + Requires: []*analysis.Analyzer{inspect.Analyzer}, + } +} + +func flags() flag.FlagSet { + flags := flag.NewFlagSet("", flag.ExitOnError) + flags.Int(InterfaceMaxMethodsFlag, 10, "maximum number of methods") + return *flags +} + +func run(pass *analysis.Pass) (interface{}, error) { + maxMethods, ok := pass.Analyzer.Flags.Lookup(InterfaceMaxMethodsFlag).Value.(flag.Getter).Get().(int) + if !ok { + maxMethods = defaultMaxMethods + } + + insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + filter := []ast.Node{ + (*ast.InterfaceType)(nil), + } + + insp.Preorder(filter, func(node ast.Node) { + i, ok := node.(*ast.InterfaceType) + if !ok { + return + } + + if len(i.Methods.List) > maxMethods { + pass.Reportf(node.Pos(), `the interface has more than %d methods: %d`, maxMethods, len(i.Methods.List)) + } + }) + + return nil, nil +} diff --git a/tools/vendor/github.com/sashamelentyev/usestdlibvars/LICENSE b/tools/vendor/github.com/sashamelentyev/usestdlibvars/LICENSE new file mode 100644 index 00000000..a52602b3 --- /dev/null +++ b/tools/vendor/github.com/sashamelentyev/usestdlibvars/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Sasha Melentyev + +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/sashamelentyev/usestdlibvars/pkg/analyzer/analyzer.go b/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/analyzer.go new file mode 100644 index 00000000..63c2f716 --- /dev/null +++ b/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/analyzer.go @@ -0,0 +1,375 @@ +package analyzer + +import ( + "flag" + "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" + + "github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping" +) + +const ( + TimeWeekdayFlag = "time-weekday" + TimeMonthFlag = "time-month" + TimeLayoutFlag = "time-layout" + CryptoHashFlag = "crypto-hash" + HTTPMethodFlag = "http-method" + HTTPStatusCodeFlag = "http-status-code" + DefaultRPCPathFlag = "default-rpc-path" +) + +// New returns new usestdlibvars analyzer. +func New() *analysis.Analyzer { + return &analysis.Analyzer{ + Name: "usestdlibvars", + Doc: "A linter that detect the possibility to use variables/constants from the Go standard library.", + Run: run, + Flags: flags(), + Requires: []*analysis.Analyzer{inspect.Analyzer}, + } +} + +func flags() flag.FlagSet { + flags := flag.NewFlagSet("", flag.ExitOnError) + flags.Bool(HTTPMethodFlag, true, "suggest the use of http.MethodXX") + flags.Bool(HTTPStatusCodeFlag, true, "suggest the use of http.StatusXX") + flags.Bool(TimeWeekdayFlag, false, "suggest the use of time.Weekday") + flags.Bool(TimeMonthFlag, false, "suggest the use of time.Month") + flags.Bool(TimeLayoutFlag, false, "suggest the use of time.Layout") + flags.Bool(CryptoHashFlag, false, "suggest the use of crypto.Hash") + flags.Bool(DefaultRPCPathFlag, false, "suggest the use of rpc.DefaultXXPath") + return *flags +} + +func run(pass *analysis.Pass) (interface{}, error) { + insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + filter := []ast.Node{ + (*ast.CallExpr)(nil), + (*ast.BasicLit)(nil), + (*ast.CompositeLit)(nil), + (*ast.IfStmt)(nil), + (*ast.SwitchStmt)(nil), + } + + insp.Preorder(filter, func(node ast.Node) { + switch n := node.(type) { + case *ast.CallExpr: + selectorExpr, ok := n.Fun.(*ast.SelectorExpr) + if !ok { + return + } + + ident, ok := selectorExpr.X.(*ast.Ident) + if !ok { + return + } + + switch ident.Name { + case "http": + switch selectorExpr.Sel.Name { + case "NewRequest": + if !lookupFlag(pass, HTTPMethodFlag) { + return + } + + if basicLit := getBasicLitFromArgs(n.Args, 3, 0, token.STRING); basicLit != nil { + checkHTTPMethod(pass, basicLit) + } + + case "NewRequestWithContext": + if !lookupFlag(pass, HTTPMethodFlag) { + return + } + + if basicLit := getBasicLitFromArgs(n.Args, 4, 1, token.STRING); basicLit != nil { + checkHTTPMethod(pass, basicLit) + } + + case "Error": + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + + if basicLit := getBasicLitFromArgs(n.Args, 3, 2, token.INT); basicLit != nil { + checkHTTPStatusCode(pass, basicLit) + } + + case "StatusText": + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + + if basicLit := getBasicLitFromArgs(n.Args, 1, 0, token.INT); basicLit != nil { + checkHTTPStatusCode(pass, basicLit) + } + + case "Redirect": + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + + if basicLit := getBasicLitFromArgs(n.Args, 4, 3, token.INT); basicLit != nil { + checkHTTPStatusCode(pass, basicLit) + } + + case "RedirectHandler": + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + + if basicLit := getBasicLitFromArgs(n.Args, 2, 1, token.INT); basicLit != nil { + checkHTTPStatusCode(pass, basicLit) + } + } + default: + if selectorExpr.Sel.Name == "WriteHeader" { + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + + if basicLit := getBasicLitFromArgs(n.Args, 1, 0, token.INT); basicLit != nil { + checkHTTPStatusCode(pass, basicLit) + } + } + } + + case *ast.BasicLit: + currentVal := getBasicLitValue(n) + + if lookupFlag(pass, TimeWeekdayFlag) { + checkTimeWeekday(pass, n.Pos(), currentVal) + } + + if lookupFlag(pass, TimeMonthFlag) { + checkTimeMonth(pass, n.Pos(), currentVal) + } + + if lookupFlag(pass, TimeLayoutFlag) { + checkTimeLayout(pass, n.Pos(), currentVal) + } + + if lookupFlag(pass, CryptoHashFlag) { + checkCryptoHash(pass, n.Pos(), currentVal) + } + + if lookupFlag(pass, DefaultRPCPathFlag) { + checkDefaultRPCPath(pass, n.Pos(), currentVal) + } + + case *ast.CompositeLit: + selectorExpr, ok := n.Type.(*ast.SelectorExpr) + if !ok { + return + } + + ident, ok := selectorExpr.X.(*ast.Ident) + if !ok { + return + } + + if ident.Name == "http" { + switch selectorExpr.Sel.Name { + case "Request": + if !lookupFlag(pass, HTTPMethodFlag) { + return + } + + if basicLit := getBasicLitFromElts(n.Elts, "Method"); basicLit != nil { + checkHTTPMethod(pass, basicLit) + } + + case "Response": + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + + if basicLit := getBasicLitFromElts(n.Elts, "StatusCode"); basicLit != nil { + checkHTTPStatusCode(pass, basicLit) + } + } + } + + case *ast.IfStmt: + binaryExpr, ok := n.Cond.(*ast.BinaryExpr) + if !ok { + return + } + + selectorExpr, ok := binaryExpr.X.(*ast.SelectorExpr) + if !ok { + return + } + + basicLit, ok := binaryExpr.Y.(*ast.BasicLit) + if !ok { + return + } + + switch selectorExpr.Sel.Name { + case "StatusCode": + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + + checkHTTPStatusCode(pass, basicLit) + case "Method": + if !lookupFlag(pass, HTTPMethodFlag) { + return + } + + checkHTTPMethod(pass, basicLit) + } + + case *ast.SwitchStmt: + selectorExpr, ok := n.Tag.(*ast.SelectorExpr) + if !ok { + return + } + + var checkFunc func(pass *analysis.Pass, basicLit *ast.BasicLit) + + switch selectorExpr.Sel.Name { + case "StatusCode": + if !lookupFlag(pass, HTTPStatusCodeFlag) { + return + } + checkFunc = checkHTTPStatusCode + case "Method": + if !lookupFlag(pass, HTTPMethodFlag) { + return + } + checkFunc = checkHTTPMethod + default: + return + } + + for _, stmt := range n.Body.List { + caseClause, ok := stmt.(*ast.CaseClause) + if !ok { + continue + } + for _, expr := range caseClause.List { + basicLit, ok := expr.(*ast.BasicLit) + if !ok { + continue + } + checkFunc(pass, basicLit) + } + } + } + }) + + return nil, nil +} + +func lookupFlag(pass *analysis.Pass, name string) bool { + return pass.Analyzer.Flags.Lookup(name).Value.(flag.Getter).Get().(bool) +} + +func checkHTTPMethod(pass *analysis.Pass, basicLit *ast.BasicLit) { + currentVal := getBasicLitValue(basicLit) + + if newVal, ok := mapping.HTTPMethod[strings.ToUpper(currentVal)]; ok { + report(pass, basicLit.Pos(), currentVal, newVal) + } +} + +func checkHTTPStatusCode(pass *analysis.Pass, basicLit *ast.BasicLit) { + currentVal := getBasicLitValue(basicLit) + + if newVal, ok := mapping.HTTPStatusCode[currentVal]; ok { + report(pass, basicLit.Pos(), currentVal, newVal) + } +} + +func checkTimeWeekday(pass *analysis.Pass, pos token.Pos, currentVal string) { + if newVal, ok := mapping.TimeWeekday[currentVal]; ok { + report(pass, pos, currentVal, newVal) + } +} + +func checkTimeMonth(pass *analysis.Pass, pos token.Pos, currentVal string) { + if newVal, ok := mapping.TimeMonth[currentVal]; ok { + report(pass, pos, currentVal, newVal) + } +} + +func checkTimeLayout(pass *analysis.Pass, pos token.Pos, currentVal string) { + if newVal, ok := mapping.TimeLayout[currentVal]; ok { + report(pass, pos, currentVal, newVal) + } +} + +func checkCryptoHash(pass *analysis.Pass, pos token.Pos, currentVal string) { + if newVal, ok := mapping.CryptoHash[currentVal]; ok { + report(pass, pos, currentVal, newVal) + } +} + +func checkDefaultRPCPath(pass *analysis.Pass, pos token.Pos, currentVal string) { + if newVal, ok := mapping.DefaultRPCPath[currentVal]; ok { + report(pass, pos, currentVal, newVal) + } +} + +// getBasicLitFromArgs gets the *ast.BasicLit of a function argument. +// +// Arguments: +// - count - expected number of argument in function +// - idx - index of the argument to get the *ast.BasicLit +// - typ - argument type +func getBasicLitFromArgs(args []ast.Expr, count, idx int, typ token.Token) *ast.BasicLit { + if len(args) != count { + return nil + } + + basicLit, ok := args[idx].(*ast.BasicLit) + if !ok { + return nil + } + + if basicLit.Kind != typ { + return nil + } + + return basicLit +} + +// getBasicLitFromElts gets the *ast.BasicLit of a struct elements. +// +// Arguments: +// - key: name of key in struct +func getBasicLitFromElts(elts []ast.Expr, key string) *ast.BasicLit { + for _, e := range elts { + expr, ok := e.(*ast.KeyValueExpr) + if !ok { + continue + } + ident, ok := expr.Key.(*ast.Ident) + if !ok { + continue + } + if ident.Name != key { + continue + } + if basicLit, ok := expr.Value.(*ast.BasicLit); ok { + return basicLit + } + } + return nil +} + +// getBasicLitValue returns BasicLit value as string without quotes +func getBasicLitValue(basicLit *ast.BasicLit) string { + return strings.Trim(basicLit.Value, "\"") +} + +func report(pass *analysis.Pass, pos token.Pos, currentVal, newVal string) { + pass.Reportf(pos, `%q can be replaced by %s`, currentVal, newVal) +} diff --git a/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping/mapping.go b/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping/mapping.go new file mode 100644 index 00000000..56fae1bf --- /dev/null +++ b/tools/vendor/github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping/mapping.go @@ -0,0 +1,161 @@ +package mapping + +import ( + "crypto" + "net/http" + "net/rpc" + "strconv" + "time" +) + +var CryptoHash = map[string]string{ + crypto.MD4.String(): "crypto.MD4.String()", + crypto.MD5.String(): "crypto.MD5.String()", + crypto.SHA1.String(): "crypto.SHA1.String()", + crypto.SHA224.String(): "crypto.SHA224.String()", + crypto.SHA256.String(): "crypto.SHA256.String()", + crypto.SHA384.String(): "crypto.SHA384.String()", + crypto.SHA512.String(): "crypto.SHA512.String()", + crypto.MD5SHA1.String(): "crypto.MD5SHA1.String()", + crypto.RIPEMD160.String(): "crypto.RIPEMD160.String()", + crypto.SHA3_224.String(): "crypto.SHA3_224.String()", + crypto.SHA3_256.String(): "crypto.SHA3_256.String()", + crypto.SHA3_384.String(): "crypto.SHA3_384.String()", + crypto.SHA3_512.String(): "crypto.SHA3_512.String()", + crypto.SHA512_224.String(): "crypto.SHA512_224.String()", + crypto.SHA512_256.String(): "crypto.SHA512_256.String()", + crypto.BLAKE2s_256.String(): "crypto.BLAKE2s_256.String()", + crypto.BLAKE2b_256.String(): "crypto.BLAKE2b_256.String()", + crypto.BLAKE2b_384.String(): "crypto.BLAKE2b_384.String()", + crypto.BLAKE2b_512.String(): "crypto.BLAKE2b_512.String()", +} + +var HTTPMethod = map[string]string{ + http.MethodGet: "http.MethodGet", + http.MethodHead: "http.MethodHead", + http.MethodPost: "http.MethodPost", + http.MethodPut: "http.MethodPut", + http.MethodPatch: "http.MethodPatch", + http.MethodDelete: "http.MethodDelete", + http.MethodConnect: "http.MethodConnect", + http.MethodOptions: "http.MethodOptions", + http.MethodTrace: "http.MethodTrace", +} + +var HTTPStatusCode = map[string]string{ + strconv.Itoa(http.StatusContinue): "http.StatusContinue", + strconv.Itoa(http.StatusSwitchingProtocols): "http.StatusSwitchingProtocols", + strconv.Itoa(http.StatusProcessing): "http.StatusProcessing", + strconv.Itoa(http.StatusEarlyHints): "http.StatusEarlyHints", + + strconv.Itoa(http.StatusOK): "http.StatusOK", + strconv.Itoa(http.StatusCreated): "http.StatusCreated", + strconv.Itoa(http.StatusAccepted): "http.StatusAccepted", + strconv.Itoa(http.StatusNonAuthoritativeInfo): "http.StatusNonAuthoritativeInfo", + strconv.Itoa(http.StatusNoContent): "http.StatusNoContent", + strconv.Itoa(http.StatusResetContent): "http.StatusResetContent", + strconv.Itoa(http.StatusPartialContent): "http.StatusPartialContent", + strconv.Itoa(http.StatusMultiStatus): "http.StatusMultiStatus", + strconv.Itoa(http.StatusAlreadyReported): "http.StatusAlreadyReported", + strconv.Itoa(http.StatusIMUsed): "http.StatusIMUsed", + + strconv.Itoa(http.StatusMultipleChoices): "http.StatusMultipleChoices", + strconv.Itoa(http.StatusMovedPermanently): "http.StatusMovedPermanently", + strconv.Itoa(http.StatusFound): "http.StatusFound", + strconv.Itoa(http.StatusSeeOther): "http.StatusSeeOther", + strconv.Itoa(http.StatusNotModified): "http.StatusNotModified", + strconv.Itoa(http.StatusUseProxy): "http.StatusUseProxy", + strconv.Itoa(http.StatusTemporaryRedirect): "http.StatusTemporaryRedirect", + strconv.Itoa(http.StatusPermanentRedirect): "http.StatusPermanentRedirect", + + strconv.Itoa(http.StatusBadRequest): "http.StatusBadRequest", + strconv.Itoa(http.StatusUnauthorized): "http.StatusUnauthorized", + strconv.Itoa(http.StatusPaymentRequired): "http.StatusPaymentRequired", + strconv.Itoa(http.StatusForbidden): "http.StatusForbidden", + strconv.Itoa(http.StatusNotFound): "http.StatusNotFound", + strconv.Itoa(http.StatusMethodNotAllowed): "http.StatusMethodNotAllowed", + strconv.Itoa(http.StatusNotAcceptable): "http.StatusNotAcceptable", + strconv.Itoa(http.StatusProxyAuthRequired): "http.StatusProxyAuthRequired", + strconv.Itoa(http.StatusRequestTimeout): "http.StatusRequestTimeout", + strconv.Itoa(http.StatusConflict): "http.StatusConflict", + strconv.Itoa(http.StatusGone): "http.StatusGone", + strconv.Itoa(http.StatusLengthRequired): "http.StatusLengthRequired", + strconv.Itoa(http.StatusPreconditionFailed): "http.StatusPreconditionFailed", + strconv.Itoa(http.StatusRequestEntityTooLarge): "http.StatusRequestEntityTooLarge", + strconv.Itoa(http.StatusRequestURITooLong): "http.StatusRequestURITooLong", + strconv.Itoa(http.StatusUnsupportedMediaType): "http.StatusUnsupportedMediaType", + strconv.Itoa(http.StatusRequestedRangeNotSatisfiable): "http.StatusRequestedRangeNotSatisfiable", + strconv.Itoa(http.StatusExpectationFailed): "http.StatusExpectationFailed", + strconv.Itoa(http.StatusTeapot): "http.StatusTeapot", + strconv.Itoa(http.StatusMisdirectedRequest): "http.StatusMisdirectedRequest", + strconv.Itoa(http.StatusUnprocessableEntity): "http.StatusUnprocessableEntity", + strconv.Itoa(http.StatusLocked): "http.StatusLocked", + strconv.Itoa(http.StatusFailedDependency): "http.StatusFailedDependency", + strconv.Itoa(http.StatusTooEarly): "http.StatusTooEarly", + strconv.Itoa(http.StatusUpgradeRequired): "http.StatusUpgradeRequired", + strconv.Itoa(http.StatusPreconditionRequired): "http.StatusPreconditionRequired", + strconv.Itoa(http.StatusTooManyRequests): "http.StatusTooManyRequests", + strconv.Itoa(http.StatusRequestHeaderFieldsTooLarge): "http.StatusRequestHeaderFieldsTooLarge", + strconv.Itoa(http.StatusUnavailableForLegalReasons): "http.StatusUnavailableForLegalReasons", + + strconv.Itoa(http.StatusInternalServerError): "http.StatusInternalServerError", + strconv.Itoa(http.StatusNotImplemented): "http.StatusNotImplemented", + strconv.Itoa(http.StatusBadGateway): "http.StatusBadGateway", + strconv.Itoa(http.StatusServiceUnavailable): "http.StatusServiceUnavailable", + strconv.Itoa(http.StatusGatewayTimeout): "http.StatusGatewayTimeout", + strconv.Itoa(http.StatusHTTPVersionNotSupported): "http.StatusHTTPVersionNotSupported", + strconv.Itoa(http.StatusVariantAlsoNegotiates): "http.StatusVariantAlsoNegotiates", + strconv.Itoa(http.StatusInsufficientStorage): "http.StatusInsufficientStorage", + strconv.Itoa(http.StatusLoopDetected): "http.StatusLoopDetected", + strconv.Itoa(http.StatusNotExtended): "http.StatusNotExtended", + strconv.Itoa(http.StatusNetworkAuthenticationRequired): "http.StatusNetworkAuthenticationRequired", +} + +var DefaultRPCPath = map[string]string{ + rpc.DefaultRPCPath: "rpc.DefaultRPCPath", + rpc.DefaultDebugPath: "rpc.DefaultDebugPath", +} + +var TimeWeekday = map[string]string{ + time.Sunday.String(): "time.Sunday.String()", + time.Monday.String(): "time.Monday.String()", + time.Tuesday.String(): "time.Tuesday.String()", + time.Wednesday.String(): "time.Wednesday.String()", + time.Thursday.String(): "time.Thursday.String()", + time.Friday.String(): "time.Friday.String()", + time.Saturday.String(): "time.Saturday.String()", +} + +var TimeMonth = map[string]string{ + time.January.String(): "time.January.String()", + time.February.String(): "time.February.String()", + time.March.String(): "time.March.String()", + time.April.String(): "time.April.String()", + time.May.String(): "time.May.String()", + time.June.String(): "time.June.String()", + time.July.String(): "time.July.String()", + time.August.String(): "time.August.String()", + time.September.String(): "time.September.String()", + time.October.String(): "time.October.String()", + time.November.String(): "time.November.String()", + time.December.String(): "time.December.String()", +} + +var TimeLayout = map[string]string{ + time.Layout: "time.Layout", + time.ANSIC: "time.ANSIC", + time.UnixDate: "time.UnixDate", + time.RubyDate: "time.RubyDate", + time.RFC822: "time.RFC822", + time.RFC822Z: "time.RFC822Z", + time.RFC850: "time.RFC850", + time.RFC1123: "time.RFC1123", + time.RFC1123Z: "time.RFC1123Z", + time.RFC3339: "time.RFC3339", + time.RFC3339Nano: "time.RFC3339Nano", + time.Kitchen: "time.Kitchen", + time.Stamp: "time.Stamp", + time.StampMilli: "time.StampMilli", + time.StampMicro: "time.StampMicro", + time.StampNano: "time.StampNano", +} diff --git a/tools/vendor/github.com/securego/gosec/v2/Dockerfile b/tools/vendor/github.com/securego/gosec/v2/Dockerfile index 1d7f9133..b57c981f 100644 --- a/tools/vendor/github.com/securego/gosec/v2/Dockerfile +++ b/tools/vendor/github.com/securego/gosec/v2/Dockerfile @@ -1,6 +1,6 @@ ARG GO_VERSION FROM golang:${GO_VERSION}-alpine AS builder -RUN apk add --update --no-cache ca-certificates make git curl gcc libc-dev +RUN apk add --no-cache ca-certificates make git curl gcc libc-dev RUN mkdir -p /build WORKDIR /build COPY . /build/ @@ -8,7 +8,7 @@ RUN go mod download RUN make build-linux FROM golang:${GO_VERSION}-alpine -RUN apk add --update --no-cache ca-certificates bash git gcc libc-dev openssh +RUN apk add --no-cache ca-certificates bash git gcc libc-dev openssh ENV GO111MODULE on COPY --from=builder /build/gosec /bin/gosec COPY entrypoint.sh /bin/entrypoint.sh diff --git a/tools/vendor/github.com/securego/gosec/v2/README.md b/tools/vendor/github.com/securego/gosec/v2/README.md index 817b59c1..cc824393 100644 --- a/tools/vendor/github.com/securego/gosec/v2/README.md +++ b/tools/vendor/github.com/securego/gosec/v2/README.md @@ -144,6 +144,9 @@ directory you can supply `./...` as the input argument. - G109: Potential Integer overflow made by strconv.Atoi result conversion to int16/32 - G110: Potential DoS vulnerability via decompression bomb - G111: Potential directory traversal +- G112: Potential slowloris attack +- G113: Usage of Rat.SetString in math/big with an overflow (CVE-2022-23772) +- G114: Use of net/http serve function that has no support for setting timeouts - G201: SQL query construction using format string - G202: SQL query construction using string concatenation - G203: Use of unescaped data in HTML templates @@ -219,7 +222,7 @@ of functions which will be skipped when auditing the not checked errors: } ``` -You can also configure the hard-coded credentials rule `G101` with additional patters, or adjust the entropy threshold: +You can also configure the hard-coded credentials rule `G101` with additional patterns, or adjust the entropy threshold: ```JSON { diff --git a/tools/vendor/github.com/securego/gosec/v2/call_list.go b/tools/vendor/github.com/securego/gosec/v2/call_list.go index 4b3fcf05..4f2d6c54 100644 --- a/tools/vendor/github.com/securego/gosec/v2/call_list.go +++ b/tools/vendor/github.com/securego/gosec/v2/call_list.go @@ -47,7 +47,7 @@ func (c CallList) Add(selector, ident string) { } // Contains returns true if the package and function are -/// members of this call list. +// members of this call list. func (c CallList) Contains(selector, ident string) bool { if idents, ok := c[selector]; ok { _, found := idents[ident] @@ -77,17 +77,26 @@ func (c CallList) ContainsPkgCallExpr(n ast.Node, ctx *Context, stripVendor bool return nil } - // Use only explicit path (optionally strip vendor path prefix) to reduce conflicts - path, ok := GetImportPath(selector, ctx) - if !ok { - return nil + // Selector can have two forms: + // 1. A short name if a module function is called (expr.Name). + // E.g., "big" if called function from math/big. + // 2. A full name if a structure function is called (TypeOf(expr)). + // E.g., "math/big.Rat" if called function of Rat structure from math/big. + if !strings.ContainsRune(selector, '.') { + // Use only explicit path (optionally strip vendor path prefix) to reduce conflicts + path, ok := GetImportPath(selector, ctx) + if !ok { + return nil + } + selector = path } + if stripVendor { - if vendorIdx := strings.Index(path, vendorPath); vendorIdx >= 0 { - path = path[vendorIdx+len(vendorPath):] + if vendorIdx := strings.Index(selector, vendorPath); vendorIdx >= 0 { + selector = selector[vendorIdx+len(vendorPath):] } } - if !c.Contains(path, ident) { + if !c.Contains(selector, ident) { return nil } diff --git a/tools/vendor/github.com/securego/gosec/v2/config.go b/tools/vendor/github.com/securego/gosec/v2/config.go index 59f48bc5..443d45f7 100644 --- a/tools/vendor/github.com/securego/gosec/v2/config.go +++ b/tools/vendor/github.com/securego/gosec/v2/config.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" ) const ( @@ -64,7 +63,7 @@ func (c Config) convertGlobals() { // should be used with io.Reader to load configuration from // file or from string etc. func (c Config) ReadFrom(r io.Reader) (int64, error) { - data, err := ioutil.ReadAll(r) + data, err := io.ReadAll(r) if err != nil { return int64(len(data)), err } diff --git a/tools/vendor/github.com/securego/gosec/v2/cwe/data.go b/tools/vendor/github.com/securego/gosec/v2/cwe/data.go index 8789ddd6..0e377b96 100644 --- a/tools/vendor/github.com/securego/gosec/v2/cwe/data.go +++ b/tools/vendor/github.com/securego/gosec/v2/cwe/data.go @@ -89,6 +89,11 @@ var ( Description: "Creating and using insecure temporary files can leave application and system data vulnerable to attack.", Name: "Insecure Temporary File", }, + { + ID: "400", + Description: "The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.", + Name: "Uncontrolled Resource Consumption", + }, { ID: "409", Description: "The software does not handle or incorrectly handles a compressed input with a very high compression ratio that produces a large output.", diff --git a/tools/vendor/github.com/securego/gosec/v2/cwe/types.go b/tools/vendor/github.com/securego/gosec/v2/cwe/types.go index a14ccb53..562510a8 100644 --- a/tools/vendor/github.com/securego/gosec/v2/cwe/types.go +++ b/tools/vendor/github.com/securego/gosec/v2/cwe/types.go @@ -19,7 +19,11 @@ func (w *Weakness) SprintURL() string { // SprintID format the CWE ID func (w *Weakness) SprintID() string { - return fmt.Sprintf("%s-%s", Acronym, w.ID) + id := "0000" + if w != nil { + id = w.ID + } + return fmt.Sprintf("%s-%s", Acronym, id) } // MarshalJSON print only id and URL diff --git a/tools/vendor/github.com/securego/gosec/v2/helpers.go b/tools/vendor/github.com/securego/gosec/v2/helpers.go index e5f2218e..437d0324 100644 --- a/tools/vendor/github.com/securego/gosec/v2/helpers.go +++ b/tools/vendor/github.com/securego/gosec/v2/helpers.go @@ -34,12 +34,15 @@ import ( // initialization only imports. // // Usage: -// node, matched := MatchCallByPackage(n, ctx, "math/rand", "Read") // +// node, matched := MatchCallByPackage(n, ctx, "math/rand", "Read") func MatchCallByPackage(n ast.Node, c *Context, pkg string, names ...string) (*ast.CallExpr, bool) { importedName, found := GetImportedName(pkg, c) if !found { - return nil, false + importedName, found = GetAliasedName(pkg, c) + if !found { + return nil, false + } } if callExpr, ok := n.(*ast.CallExpr); ok { @@ -245,7 +248,7 @@ func GetBinaryExprOperands(be *ast.BinaryExpr) []ast.Node { } // GetImportedName returns the name used for the package within the -// code. It will resolve aliases and ignores initialization only imports. +// code. It will ignore initialization only imports. func GetImportedName(path string, ctx *Context) (string, bool) { importName, imported := ctx.Imports.Imported[path] if !imported { @@ -256,20 +259,39 @@ func GetImportedName(path string, ctx *Context) (string, bool) { return "", false } - if alias, ok := ctx.Imports.Aliased[path]; ok { - importName = alias + return importName, true +} + +// GetAliasedName returns the aliased name used for the package within the +// code. It will ignore initialization only imports. +func GetAliasedName(path string, ctx *Context) (string, bool) { + importName, imported := ctx.Imports.Aliased[path] + if !imported { + return "", false + } + + if _, initonly := ctx.Imports.InitOnly[path]; initonly { + return "", false } + return importName, true } // GetImportPath resolves the full import path of an identifier based on -// the imports in the current context. +// the imports in the current context(including aliases). func GetImportPath(name string, ctx *Context) (string, bool) { for path := range ctx.Imports.Imported { if imported, ok := GetImportedName(path, ctx); ok && imported == name { return path, true } } + + for path := range ctx.Imports.Aliased { + if imported, ok := GetAliasedName(path, ctx); ok && imported == name { + return path, true + } + } + return "", false } @@ -449,3 +471,28 @@ func RootPath(root string) (string, error) { root = strings.TrimSuffix(root, "...") return filepath.Abs(root) } + +// GoVersion returns parsed version of Go from runtime +func GoVersion() (int, int, int) { + return parseGoVersion(runtime.Version()) +} + +// parseGoVersion parses Go version. +// example: +// - go1.19rc2 +// - go1.19beta2 +// - go1.19.4 +// - go1.19 +func parseGoVersion(version string) (int, int, int) { + exp := regexp.MustCompile(`go(\d+).(\d+)(?:.(\d+))?.*`) + parts := exp.FindStringSubmatch(version) + if len(parts) <= 1 { + return 0, 0, 0 + } + + major, _ := strconv.Atoi(parts[1]) + minor, _ := strconv.Atoi(parts[2]) + build, _ := strconv.Atoi(parts[3]) + + return major, minor, build +} diff --git a/tools/vendor/github.com/securego/gosec/v2/issue.go b/tools/vendor/github.com/securego/gosec/v2/issue.go index ecda7073..32b9bc0c 100644 --- a/tools/vendor/github.com/securego/gosec/v2/issue.go +++ b/tools/vendor/github.com/securego/gosec/v2/issue.go @@ -64,6 +64,8 @@ var ruleToCWE = map[string]string{ "G109": "190", "G110": "409", "G111": "22", + "G112": "400", + "G113": "190", "G201": "89", "G202": "89", "G203": "79", @@ -181,7 +183,7 @@ func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, var code string if file, err := os.Open(fobj.Name()); err == nil { - defer file.Close() //#nosec + defer file.Close() // #nosec s := codeSnippetStartLine(node, fobj) e := codeSnippetEndLine(node, fobj) code, err = codeSnippet(file, s, e, node) diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/directory-traversal.go b/tools/vendor/github.com/securego/gosec/v2/rules/directory-traversal.go index 04237faa..c373427b 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/directory-traversal.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/directory-traversal.go @@ -43,7 +43,7 @@ func (r *traversal) matchCallExpr(assign *ast.CallExpr, ctx *gosec.Context) (*go // NewDirectoryTraversal attempts to find the use of http.Dir("/") func NewDirectoryTraversal(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { pattern := `http\.Dir\("\/"\)|http\.Dir\('\/'\)` - if val, ok := conf["G101"]; ok { + if val, ok := conf[id]; ok { conf := val.(map[string]interface{}) if configPattern, ok := conf["pattern"]; ok { if cfgPattern, ok := configPattern.(string); ok { diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/errors.go b/tools/vendor/github.com/securego/gosec/v2/rules/errors.go index f3360ec6..0838382b 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/errors.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/errors.go @@ -89,7 +89,7 @@ func NewNoErrorCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { whitelist.Add("hash.Hash", "Write") whitelist.Add("os", "Unsetenv") - if configured, ok := conf["G104"]; ok { + if configured, ok := conf[id]; ok { if whitelisted, ok := configured.(map[string]interface{}); ok { for pkg, funcs := range whitelisted { if funcs, ok := funcs.([]interface{}); ok { 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 93265dd3..a379a8c0 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/fileperms.go @@ -64,7 +64,7 @@ func (r *filePermissions) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, err // 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, "G306", 0o600) + mode := getConfiguredMode(conf, id, 0o600) return &filePermissions{ mode: mode, pkgs: []string{"io/ioutil", "os"}, @@ -81,7 +81,7 @@ func NewWritePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { // NewFilePerms creates a rule to detect file creation with a more permissive than configured // permission mask. func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - mode := getConfiguredMode(conf, "G302", 0o600) + mode := getConfiguredMode(conf, id, 0o600) return &filePermissions{ mode: mode, pkgs: []string{"os"}, @@ -98,7 +98,7 @@ func NewFilePerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { // NewMkdirPerms creates a rule to detect directory creation with more permissive than // configured permission mask. func NewMkdirPerms(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - mode := getConfiguredMode(conf, "G301", 0o750) + mode := getConfiguredMode(conf, id, 0o750) return &filePermissions{ mode: mode, pkgs: []string{"os"}, 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 791bb5dc..cf2e6638 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 @@ -122,7 +122,7 @@ func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.No perCharThreshold := 3.0 ignoreEntropy := false truncateString := 16 - if val, ok := conf["G101"]; ok { + if val, ok := conf[id]; ok { conf := val.(map[string]interface{}) if configPattern, ok := conf["pattern"]; ok { if cfgPattern, ok := configPattern.(string); ok { diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/http_serve.go b/tools/vendor/github.com/securego/gosec/v2/rules/http_serve.go new file mode 100644 index 00000000..e460b3a6 --- /dev/null +++ b/tools/vendor/github.com/securego/gosec/v2/rules/http_serve.go @@ -0,0 +1,38 @@ +package rules + +import ( + "go/ast" + + "github.com/securego/gosec/v2" +) + +type httpServeWithoutTimeouts struct { + gosec.MetaData + pkg string + calls []string +} + +func (r *httpServeWithoutTimeouts) ID() string { + return r.MetaData.ID +} + +func (r *httpServeWithoutTimeouts) Match(n ast.Node, c *gosec.Context) (gi *gosec.Issue, err error) { + if _, matches := gosec.MatchCallByPackage(n, c, r.pkg, r.calls...); matches { + return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil + } + return nil, nil +} + +// NewHTTPServeWithoutTimeouts detects use of net/http serve functions that have no support for setting timeouts. +func NewHTTPServeWithoutTimeouts(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + return &httpServeWithoutTimeouts{ + pkg: "net/http", + calls: []string{"ListenAndServe", "ListenAndServeTLS", "Serve", "ServeTLS"}, + MetaData: gosec.MetaData{ + ID: id, + What: "Use of net/http serve function that has no support for setting timeouts", + Severity: gosec.Medium, + Confidence: gosec.High, + }, + }, []ast.Node{(*ast.CallExpr)(nil)} +} diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go b/tools/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go index dfcda94a..f55211a9 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go @@ -61,7 +61,7 @@ func (i *integerOverflowCheck) Match(node ast.Node, ctx *gosec.Context) (*gosec. if fun, ok := n.Fun.(*ast.Ident); ok { if fun.Name == "int32" || fun.Name == "int16" { if idt, ok := n.Args[0].(*ast.Ident); ok { - if n, ok := atoiVarObj[idt.Obj]; ok { + if _, ok := atoiVarObj[idt.Obj]; ok { // Detect int32(v) and int16(v) return gosec.NewIssue(ctx, n, i.ID(), i.What, i.Severity, i.Confidence), nil } diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/math_big_rat.go b/tools/vendor/github.com/securego/gosec/v2/rules/math_big_rat.go new file mode 100644 index 00000000..69037e18 --- /dev/null +++ b/tools/vendor/github.com/securego/gosec/v2/rules/math_big_rat.go @@ -0,0 +1,44 @@ +package rules + +import ( + "go/ast" + + "github.com/securego/gosec/v2" +) + +type usingOldMathBig struct { + gosec.MetaData + calls gosec.CallList +} + +func (r *usingOldMathBig) ID() string { + return r.MetaData.ID +} + +func (r *usingOldMathBig) Match(node ast.Node, ctx *gosec.Context) (gi *gosec.Issue, err error) { + if callExpr := r.calls.ContainsPkgCallExpr(node, ctx, false); callExpr == nil { + return nil, nil + } + + confidence := gosec.Low + major, minor, build := gosec.GoVersion() + if major == 1 && (minor == 16 && build < 14 || minor == 17 && build < 7) { + confidence = gosec.Medium + } + + return gosec.NewIssue(ctx, node, r.ID(), r.What, r.Severity, confidence), nil +} + +// NewUsingOldMathBig rule detects the use of Rat.SetString from math/big. +func NewUsingOldMathBig(id string, _ gosec.Config) (gosec.Rule, []ast.Node) { + calls := gosec.NewCallList() + calls.Add("math/big.Rat", "SetString") + return &usingOldMathBig{ + calls: calls, + MetaData: gosec.MetaData{ + ID: id, + What: "Potential uncontrolled memory consumption in Rat.SetString (CVE-2022-23772)", + Severity: gosec.High, + }, + }, []ast.Node{(*ast.CallExpr)(nil)} +} diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/rulelist.go b/tools/vendor/github.com/securego/gosec/v2/rules/rulelist.go index bbe72faf..b97813ed 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/rulelist.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/rulelist.go @@ -74,6 +74,9 @@ func Generate(trackSuppressions bool, filters ...RuleFilter) RuleList { {"G109", "Converting strconv.Atoi result to int32/int16", NewIntegerOverflowCheck}, {"G110", "Detect io.Copy instead of io.CopyN when decompression", NewDecompressionBombCheck}, {"G111", "Detect http.Dir('/') as a potential risk", NewDirectoryTraversal}, + {"G112", "Detect ReadHeaderTimeout not configured as a potential risk", NewSlowloris}, + {"G113", "Usage of Rat.SetString in math/big with an overflow", NewUsingOldMathBig}, + {"G114", "Use of net/http serve function that has no support for setting timeouts", NewHTTPServeWithoutTimeouts}, // injection {"G201", "SQL query construction using format string", NewSQLStrFormat}, diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/slowloris.go b/tools/vendor/github.com/securego/gosec/v2/rules/slowloris.go new file mode 100644 index 00000000..60b5e952 --- /dev/null +++ b/tools/vendor/github.com/securego/gosec/v2/rules/slowloris.go @@ -0,0 +1,70 @@ +// (c) Copyright 2016 Hewlett Packard Enterprise Development LP +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package rules + +import ( + "go/ast" + + "github.com/securego/gosec/v2" +) + +type slowloris struct { + gosec.MetaData +} + +func (r *slowloris) ID() string { + return r.MetaData.ID +} + +func containsReadHeaderTimeout(node *ast.CompositeLit) bool { + if node == nil { + return false + } + for _, elt := range node.Elts { + if kv, ok := elt.(*ast.KeyValueExpr); ok { + if ident, ok := kv.Key.(*ast.Ident); ok { + if ident.Name == "ReadHeaderTimeout" || ident.Name == "ReadTimeout" { + return true + } + } + } + } + return false +} + +func (r *slowloris) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { + switch node := n.(type) { + case *ast.CompositeLit: + actualType := ctx.Info.TypeOf(node.Type) + if actualType != nil && actualType.String() == "net/http.Server" { + if !containsReadHeaderTimeout(node) { + return gosec.NewIssue(ctx, node, r.ID(), r.What, r.Severity, r.Confidence), nil + } + } + } + return nil, nil +} + +// NewSlowloris attempts to find the http.Server struct and check if the ReadHeaderTimeout is configured. +func NewSlowloris(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + return &slowloris{ + MetaData: gosec.MetaData{ + ID: id, + What: "Potential Slowloris Attack because ReadHeaderTimeout is not configured in the http.Server", + Confidence: gosec.Low, + Severity: gosec.Medium, + }, + }, []ast.Node{(*ast.CompositeLit)(nil)} +} diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/sql.go b/tools/vendor/github.com/securego/gosec/v2/rules/sql.go index 6f4dbf12..ee99737d 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/sql.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/sql.go @@ -15,9 +15,9 @@ package rules import ( + "fmt" "go/ast" "regexp" - "strings" "github.com/securego/gosec/v2" ) @@ -30,6 +30,51 @@ type sqlStatement struct { patterns []*regexp.Regexp } +var sqlCallIdents = map[string]map[string]int{ + "*database/sql.DB": { + "Exec": 0, + "ExecContext": 1, + "Query": 0, + "QueryContext": 1, + "QueryRow": 0, + "QueryRowContext": 1, + "Prepare": 0, + "PrepareContext": 1, + }, + "*database/sql.Tx": { + "Exec": 0, + "ExecContext": 1, + "Query": 0, + "QueryContext": 1, + "QueryRow": 0, + "QueryRowContext": 1, + "Prepare": 0, + "PrepareContext": 1, + }, +} + +// findQueryArg locates the argument taking raw SQL +func findQueryArg(call *ast.CallExpr, ctx *gosec.Context) (ast.Expr, error) { + typeName, fnName, err := gosec.GetCallInfo(call, ctx) + if err != nil { + return nil, err + } + i := -1 + if ni, ok := sqlCallIdents[typeName]; ok { + if i, ok = ni[fnName]; !ok { + i = -1 + } + } + if i == -1 { + return nil, fmt.Errorf("SQL argument index not found for %s.%s", typeName, fnName) + } + if i >= len(call.Args) { + return nil, nil + } + query := call.Args[i] + return query, nil +} + func (s *sqlStatement) ID() string { return s.MetaData.ID } @@ -69,16 +114,10 @@ func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool { // checkQuery verifies if the query parameters is a string concatenation func (s *sqlStrConcat) checkQuery(call *ast.CallExpr, ctx *gosec.Context) (*gosec.Issue, error) { - _, fnName, err := gosec.GetCallInfo(call, ctx) + query, err := findQueryArg(call, ctx) if err != nil { return nil, err } - var query ast.Node - if strings.HasSuffix(fnName, "Context") { - query = call.Args[1] - } else { - query = call.Args[0] - } if be, ok := query.(*ast.BinaryExpr); ok { operands := gosec.GetBinaryExprOperands(be) @@ -137,8 +176,11 @@ func NewSQLStrConcat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { }, } - rule.AddAll("*database/sql.DB", "Query", "QueryContext", "QueryRow", "QueryRowContext", "Exec", "ExecContext", "Prepare", "PrepareContext") - rule.AddAll("*database/sql.Tx", "Query", "QueryContext", "QueryRow", "QueryRowContext", "Exec", "ExecContext", "Prepare", "PrepareContext") + for s, si := range sqlCallIdents { + for i := range si { + rule.Add(s, i) + } + } return rule, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)} } @@ -171,16 +213,10 @@ func (s *sqlStrFormat) constObject(e ast.Expr, c *gosec.Context) bool { } func (s *sqlStrFormat) checkQuery(call *ast.CallExpr, ctx *gosec.Context) (*gosec.Issue, error) { - _, fnName, err := gosec.GetCallInfo(call, ctx) + query, err := findQueryArg(call, ctx) if err != nil { return nil, err } - var query ast.Node - if strings.HasSuffix(fnName, "Context") { - query = call.Args[1] - } else { - query = call.Args[0] - } if ident, ok := query.(*ast.Ident); ok && ident.Obj != nil { decl := ident.Obj.Decl @@ -306,8 +342,11 @@ func NewSQLStrFormat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { }, }, } - rule.AddAll("*database/sql.DB", "Query", "QueryContext", "QueryRow", "QueryRowContext", "Exec", "ExecContext", "Prepare", "PrepareContext") - rule.AddAll("*database/sql.Tx", "Query", "QueryContext", "QueryRow", "QueryRowContext", "Exec", "ExecContext", "Prepare", "PrepareContext") + for s, si := range sqlCallIdents { + for i := range si { + rule.Add(s, i) + } + } rule.fmtCalls.AddAll("fmt", "Sprint", "Sprintf", "Sprintln", "Fprintf") rule.noIssue.AddAll("os", "Stdout", "Stderr") rule.noIssueQuoted.Add("github.com/lib/pq", "QuoteIdentifier") diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/subproc.go b/tools/vendor/github.com/securego/gosec/v2/rules/subproc.go index 5d7cadda..2b6cb186 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/subproc.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/subproc.go @@ -77,6 +77,13 @@ func (r *subprocess) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { return gosec.NewIssue(c, n, r.ID(), "Subprocess launched with variable", gosec.Medium, gosec.High), nil } } + case *ast.ValueSpec: + _, valueSpec := ident.Obj.Decl.(*ast.ValueSpec) + if variable && valueSpec { + if !gosec.TryResolve(ident, c) { + return gosec.NewIssue(c, n, r.ID(), "Subprocess launched with variable", gosec.Medium, gosec.High), nil + } + } } } } else if !gosec.TryResolve(arg, c) { diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/templates.go b/tools/vendor/github.com/securego/gosec/v2/rules/templates.go index b9e7bb7b..1eec7fba 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/templates.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/templates.go @@ -54,7 +54,7 @@ func NewTemplateCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { ID: id, Severity: gosec.Medium, Confidence: gosec.Low, - What: "this method will not auto-escape HTML. Verify data is well formed.", + What: "The used method does not auto-escape HTML. This can potentially lead to 'Cross-site Scripting' vulnerabilities, in case the attacker controls the input.", }, }, []ast.Node{(*ast.CallExpr)(nil)} } diff --git a/tools/vendor/github.com/securego/gosec/v2/rules/tls.go b/tools/vendor/github.com/securego/gosec/v2/rules/tls.go index 21af8e54..76dfd84f 100644 --- a/tools/vendor/github.com/securego/gosec/v2/rules/tls.go +++ b/tools/vendor/github.com/securego/gosec/v2/rules/tls.go @@ -122,8 +122,10 @@ func (t *insecureConfigTLS) processTLSConfVal(n *ast.KeyValueExpr, c *gosec.Cont t.actualMinVersion = ival } else { if se, ok := n.Value.(*ast.SelectorExpr); ok { - if pkg, ok := se.X.(*ast.Ident); ok && pkg.Name == "tls" { - t.actualMinVersion = t.mapVersion(se.Sel.Name) + if pkg, ok := se.X.(*ast.Ident); ok { + if ip, ok := gosec.GetImportPath(pkg.Name, c); ok && ip == "crypto/tls" { + t.actualMinVersion = t.mapVersion(se.Sel.Name) + } } } } @@ -133,8 +135,10 @@ func (t *insecureConfigTLS) processTLSConfVal(n *ast.KeyValueExpr, c *gosec.Cont t.actualMaxVersion = ival } else { if se, ok := n.Value.(*ast.SelectorExpr); ok { - if pkg, ok := se.X.(*ast.Ident); ok && pkg.Name == "tls" { - t.actualMaxVersion = t.mapVersion(se.Sel.Name) + if pkg, ok := se.X.(*ast.Ident); ok { + if ip, ok := gosec.GetImportPath(pkg.Name, c); ok && ip == "crypto/tls" { + t.actualMaxVersion = t.mapVersion(se.Sel.Name) + } } } } diff --git a/tools/vendor/github.com/sirupsen/logrus/README.md b/tools/vendor/github.com/sirupsen/logrus/README.md index 5152b6aa..b042c896 100644 --- a/tools/vendor/github.com/sirupsen/logrus/README.md +++ b/tools/vendor/github.com/sirupsen/logrus/README.md @@ -1,4 +1,4 @@ -# Logrus :walrus: [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) +# Logrus :walrus: [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](https://pkg.go.dev/github.com/sirupsen/logrus) Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger. @@ -341,7 +341,7 @@ import ( log "github.com/sirupsen/logrus" ) -init() { +func init() { // do something here to set environment depending on an environment variable // or command-line flag if Environment == "production" { diff --git a/tools/vendor/github.com/sirupsen/logrus/buffer_pool.go b/tools/vendor/github.com/sirupsen/logrus/buffer_pool.go index 4545dec0..c7787f77 100644 --- a/tools/vendor/github.com/sirupsen/logrus/buffer_pool.go +++ b/tools/vendor/github.com/sirupsen/logrus/buffer_pool.go @@ -26,15 +26,6 @@ func (p *defaultPool) Get() *bytes.Buffer { return p.pool.Get().(*bytes.Buffer) } -func getBuffer() *bytes.Buffer { - return bufferPool.Get() -} - -func putBuffer(buf *bytes.Buffer) { - buf.Reset() - bufferPool.Put(buf) -} - // SetBufferPool allows to replace the default logrus buffer pool // to better meets the specific needs of an application. func SetBufferPool(bp BufferPool) { diff --git a/tools/vendor/github.com/sirupsen/logrus/entry.go b/tools/vendor/github.com/sirupsen/logrus/entry.go index 07a1e5fa..71cdbbc3 100644 --- a/tools/vendor/github.com/sirupsen/logrus/entry.go +++ b/tools/vendor/github.com/sirupsen/logrus/entry.go @@ -232,6 +232,7 @@ func (entry *Entry) log(level Level, msg string) { newEntry.Logger.mu.Lock() reportCaller := newEntry.Logger.ReportCaller + bufPool := newEntry.getBufferPool() newEntry.Logger.mu.Unlock() if reportCaller { @@ -239,11 +240,11 @@ func (entry *Entry) log(level Level, msg string) { } newEntry.fireHooks() - - buffer = getBuffer() + buffer = bufPool.Get() defer func() { newEntry.Buffer = nil - putBuffer(buffer) + buffer.Reset() + bufPool.Put(buffer) }() buffer.Reset() newEntry.Buffer = buffer @@ -260,6 +261,13 @@ func (entry *Entry) log(level Level, msg string) { } } +func (entry *Entry) getBufferPool() (pool BufferPool) { + if entry.Logger.BufferPool != nil { + return entry.Logger.BufferPool + } + return bufferPool +} + func (entry *Entry) fireHooks() { var tmpHooks LevelHooks entry.Logger.mu.Lock() @@ -276,18 +284,21 @@ func (entry *Entry) fireHooks() { } func (entry *Entry) write() { + entry.Logger.mu.Lock() + defer entry.Logger.mu.Unlock() serialized, err := entry.Logger.Formatter.Format(entry) if err != nil { fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) return } - entry.Logger.mu.Lock() - defer entry.Logger.mu.Unlock() if _, err := entry.Logger.Out.Write(serialized); err != nil { fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) } } +// Log will log a message at the level given as parameter. +// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. +// For this behaviour Entry.Panic or Entry.Fatal should be used instead. func (entry *Entry) Log(level Level, args ...interface{}) { if entry.Logger.IsLevelEnabled(level) { entry.log(level, fmt.Sprint(args...)) diff --git a/tools/vendor/github.com/sirupsen/logrus/logger.go b/tools/vendor/github.com/sirupsen/logrus/logger.go index 33770445..5ff0aef6 100644 --- a/tools/vendor/github.com/sirupsen/logrus/logger.go +++ b/tools/vendor/github.com/sirupsen/logrus/logger.go @@ -44,6 +44,9 @@ type Logger struct { entryPool sync.Pool // Function to exit the application, defaults to `os.Exit()` ExitFunc exitFunc + // The buffer pool used to format the log. If it is nil, the default global + // buffer pool will be used. + BufferPool BufferPool } type exitFunc func(int) @@ -192,6 +195,9 @@ func (logger *Logger) Panicf(format string, args ...interface{}) { logger.Logf(PanicLevel, format, args...) } +// Log will log a message at the level given as parameter. +// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. +// For this behaviour Logger.Panic or Logger.Fatal should be used instead. func (logger *Logger) Log(level Level, args ...interface{}) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() @@ -402,3 +408,10 @@ func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { logger.mu.Unlock() return oldHooks } + +// SetBufferPool sets the logger buffer pool. +func (logger *Logger) SetBufferPool(pool BufferPool) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.BufferPool = pool +} diff --git a/tools/vendor/github.com/sivchari/nosnakecase/.gitignore b/tools/vendor/github.com/sivchari/nosnakecase/.gitignore new file mode 100644 index 00000000..66fd13c9 --- /dev/null +++ b/tools/vendor/github.com/sivchari/nosnakecase/.gitignore @@ -0,0 +1,15 @@ +# 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 + +# Dependency directories (remove the comment below to include it) +# vendor/ diff --git a/tools/vendor/github.com/sivchari/nosnakecase/.golangci.yml b/tools/vendor/github.com/sivchari/nosnakecase/.golangci.yml new file mode 100644 index 00000000..31e05c4e --- /dev/null +++ b/tools/vendor/github.com/sivchari/nosnakecase/.golangci.yml @@ -0,0 +1,40 @@ +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/LICENSE b/tools/vendor/github.com/sivchari/nosnakecase/LICENSE new file mode 100644 index 00000000..fb412767 --- /dev/null +++ b/tools/vendor/github.com/sivchari/nosnakecase/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 sivchari + +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/sivchari/nosnakecase/README.md b/tools/vendor/github.com/sivchari/nosnakecase/README.md new file mode 100644 index 00000000..69bb6604 --- /dev/null +++ b/tools/vendor/github.com/sivchari/nosnakecase/README.md @@ -0,0 +1,224 @@ +# 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 new file mode 100644 index 00000000..88cf70e3 --- /dev/null +++ b/tools/vendor/github.com/sivchari/nosnakecase/nosnakecase.go @@ -0,0 +1,63 @@ +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/tenv.go b/tools/vendor/github.com/sivchari/tenv/tenv.go index 9cdeb69b..12db04cf 100644 --- a/tools/vendor/github.com/sivchari/tenv/tenv.go +++ b/tools/vendor/github.com/sivchari/tenv/tenv.go @@ -34,49 +34,58 @@ func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) nodeFilter := []ast.Node{ - (*ast.File)(nil), + (*ast.FuncDecl)(nil), + (*ast.FuncLit)(nil), } inspect.Preorder(nodeFilter, func(n ast.Node) { switch n := n.(type) { - case *ast.File: - for _, decl := range n.Decls { - - funcDecl, ok := decl.(*ast.FuncDecl) - if !ok { - continue - } - checkFunc(pass, funcDecl, pass.Fset.File(n.Pos()).Name()) - } + case *ast.FuncDecl: + checkFuncDecl(pass, n, pass.Fset.File(n.Pos()).Name()) + case *ast.FuncLit: + checkFuncLit(pass, n, pass.Fset.File(n.Pos()).Name()) } }) return nil, nil } -func checkFunc(pass *analysis.Pass, n *ast.FuncDecl, fileName string) { - argName, ok := targetRunner(n, fileName) - if ok { - for _, stmt := range n.Body.List { - switch stmt := stmt.(type) { - case *ast.ExprStmt: - if !checkExprStmt(pass, stmt, n, argName) { - continue - } - case *ast.IfStmt: - if !checkIfStmt(pass, stmt, n, argName) { - continue - } - case *ast.AssignStmt: - if !checkAssignStmt(pass, stmt, n, argName) { - continue - } +func checkFuncDecl(pass *analysis.Pass, f *ast.FuncDecl, fileName string) { + argName, ok := targetRunner(f.Type.Params.List, fileName) + if !ok { + return + } + checkStmts(pass, f.Body.List, f.Name.Name, argName) +} + +func checkFuncLit(pass *analysis.Pass, f *ast.FuncLit, fileName string) { + argName, ok := targetRunner(f.Type.Params.List, fileName) + if !ok { + return + } + checkStmts(pass, f.Body.List, "anonymous function", argName) +} + +func checkStmts(pass *analysis.Pass, stmts []ast.Stmt, funcName, argName string) { + for _, stmt := range stmts { + switch stmt := stmt.(type) { + case *ast.ExprStmt: + if !checkExprStmt(pass, stmt, funcName, argName) { + continue + } + case *ast.IfStmt: + if !checkIfStmt(pass, stmt, funcName, argName) { + continue + } + case *ast.AssignStmt: + if !checkAssignStmt(pass, stmt, funcName, argName) { + continue } } } } -func checkExprStmt(pass *analysis.Pass, stmt *ast.ExprStmt, n *ast.FuncDecl, argName string) bool { +func checkExprStmt(pass *analysis.Pass, stmt *ast.ExprStmt, funcName, argName string) bool { callExpr, ok := stmt.X.(*ast.CallExpr) if !ok { return false @@ -94,12 +103,12 @@ func checkExprStmt(pass *analysis.Pass, stmt *ast.ExprStmt, n *ast.FuncDecl, arg if argName == "" { argName = "testing" } - pass.Reportf(stmt.Pos(), "os.Setenv() can be replaced by `%s.Setenv()` in %s", argName, n.Name.Name) + pass.Reportf(stmt.Pos(), "os.Setenv() can be replaced by `%s.Setenv()` in %s", argName, funcName) } return true } -func checkIfStmt(pass *analysis.Pass, stmt *ast.IfStmt, n *ast.FuncDecl, argName string) bool { +func checkIfStmt(pass *analysis.Pass, stmt *ast.IfStmt, funcName, argName string) bool { assignStmt, ok := stmt.Init.(*ast.AssignStmt) if !ok { return false @@ -121,12 +130,12 @@ func checkIfStmt(pass *analysis.Pass, stmt *ast.IfStmt, n *ast.FuncDecl, argName if argName == "" { argName = "testing" } - pass.Reportf(stmt.Pos(), "os.Setenv() can be replaced by `%s.Setenv()` in %s", argName, n.Name.Name) + pass.Reportf(stmt.Pos(), "os.Setenv() can be replaced by `%s.Setenv()` in %s", argName, funcName) } return true } -func checkAssignStmt(pass *analysis.Pass, stmt *ast.AssignStmt, n *ast.FuncDecl, argName string) bool { +func checkAssignStmt(pass *analysis.Pass, stmt *ast.AssignStmt, funcName, argName string) bool { rhs, ok := stmt.Rhs[0].(*ast.CallExpr) if !ok { return false @@ -144,17 +153,19 @@ func checkAssignStmt(pass *analysis.Pass, stmt *ast.AssignStmt, n *ast.FuncDecl, if argName == "" { argName = "testing" } - pass.Reportf(stmt.Pos(), "os.Setenv() can be replaced by `%s.Setenv()` in %s", argName, n.Name.Name) + pass.Reportf(stmt.Pos(), "os.Setenv() can be replaced by `%s.Setenv()` in %s", argName, funcName) } return true } -func targetRunner(funcDecl *ast.FuncDecl, fileName string) (string, bool) { - params := funcDecl.Type.Params.List +func targetRunner(params []*ast.Field, fileName string) (string, bool) { for _, p := range params { switch typ := p.Type.(type) { case *ast.StarExpr: if checkStarExprTarget(typ) { + if len(p.Names) == 0 { + return "", false + } argName := p.Names[0].Name return argName, true } diff --git a/tools/vendor/github.com/subosito/gotenv/.gitignore b/tools/vendor/github.com/subosito/gotenv/.gitignore index 2b8d4561..7db37c1d 100644 --- a/tools/vendor/github.com/subosito/gotenv/.gitignore +++ b/tools/vendor/github.com/subosito/gotenv/.gitignore @@ -1,3 +1,4 @@ *.test *.out annotate.json +profile.cov diff --git a/tools/vendor/github.com/subosito/gotenv/.golangci.yaml b/tools/vendor/github.com/subosito/gotenv/.golangci.yaml new file mode 100644 index 00000000..8c82a762 --- /dev/null +++ b/tools/vendor/github.com/subosito/gotenv/.golangci.yaml @@ -0,0 +1,7 @@ +# Options for analysis running. +run: + timeout: 1m + +linters-settings: + gofmt: + simplify: true diff --git a/tools/vendor/github.com/subosito/gotenv/CHANGELOG.md b/tools/vendor/github.com/subosito/gotenv/CHANGELOG.md index 24b096b9..757caad2 100644 --- a/tools/vendor/github.com/subosito/gotenv/CHANGELOG.md +++ b/tools/vendor/github.com/subosito/gotenv/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## [1.4.0] - 2022-06-02 + +### Added + +- Add `Marshal` and `Unmarshal` helpers + +### Changed + +- The CI will now run a linter and the tests on PRs. + ## [1.3.0] - 2022-05-23 ### Added @@ -41,7 +51,7 @@ ### Added - Supports carriage return in env -- Handle files with UTF-8 BOM +- Handle files with UTF-8 BOM ### Changed diff --git a/tools/vendor/github.com/subosito/gotenv/README.md b/tools/vendor/github.com/subosito/gotenv/README.md index 3ce9a410..fc9616e3 100644 --- a/tools/vendor/github.com/subosito/gotenv/README.md +++ b/tools/vendor/github.com/subosito/gotenv/README.md @@ -28,7 +28,7 @@ Once loaded you can use `os.Getenv()` to get the value of the variable. Let's say you have `.env` file: -``` +```sh APP_ID=1234567 APP_SECRET=abcdef ``` @@ -78,7 +78,6 @@ Besides above functions, `gotenv` also provides another functions that overrides - `gotenv.OverLoad` - `gotenv.OverApply` - Here's the example of this overrides behavior: ```go diff --git a/tools/vendor/github.com/subosito/gotenv/gotenv.go b/tools/vendor/github.com/subosito/gotenv/gotenv.go index c4c1e50e..b7a83be2 100644 --- a/tools/vendor/github.com/subosito/gotenv/gotenv.go +++ b/tools/vendor/github.com/subosito/gotenv/gotenv.go @@ -6,7 +6,10 @@ import ( "fmt" "io" "os" + "path/filepath" "regexp" + "sort" + "strconv" "strings" ) @@ -24,41 +27,31 @@ const ( // Env holds key/value pair of valid environment variable type Env map[string]string -/* -Load is a function to load a file or multiple files and then export the valid variables into environment variables if they do not exist. -When it's called with no argument, it will load `.env` file on the current path and set the environment variables. -Otherwise, it will loop over the filenames parameter and set the proper environment variables. -*/ +// Load is a function to load a file or multiple files and then export the valid variables into environment variables if they do not exist. +// When it's called with no argument, it will load `.env` file on the current path and set the environment variables. +// Otherwise, it will loop over the filenames parameter and set the proper environment variables. func Load(filenames ...string) error { return loadenv(false, filenames...) } -/* -OverLoad is a function to load a file or multiple files and then export and override the valid variables into environment variables. -*/ +// OverLoad is a function to load a file or multiple files and then export and override the valid variables into environment variables. func OverLoad(filenames ...string) error { return loadenv(true, filenames...) } -/* -Must is wrapper function that will panic when supplied function returns an error. -*/ +// Must is wrapper function that will panic when supplied function returns an error. func Must(fn func(filenames ...string) error, filenames ...string) { if err := fn(filenames...); err != nil { panic(err.Error()) } } -/* -Apply is a function to load an io Reader then export the valid variables into environment variables if they do not exist. -*/ +// Apply is a function to load an io Reader then export the valid variables into environment variables if they do not exist. func Apply(r io.Reader) error { return parset(r, false) } -/* -OverApply is a function to load an io Reader then export and override the valid variables into environment variables. -*/ +// OverApply is a function to load an io Reader then export and override the valid variables into environment variables. func OverApply(r io.Reader) error { return parset(r, true) } @@ -75,11 +68,10 @@ func loadenv(override bool, filenames ...string) error { } err = parset(f, override) + f.Close() if err != nil { return err } - - f.Close() } return nil @@ -124,6 +116,63 @@ func StrictParse(r io.Reader) (Env, error) { return strictParse(r, false) } +// Read is a function to parse a file line by line and returns the valid Env key/value pair of valid variables. +// It expands the value of a variable from the environment variable but does not set the value to the environment itself. +// This function is skipping any invalid lines and only processing the valid one. +func Read(filename string) (Env, error) { + f, err := os.Open(filename) + if err != nil { + return nil, err + } + return strictParse(f, false) +} + +// Unmarshal reads a string line by line and returns the valid Env key/value pair of valid variables. +// It expands the value of a variable from the environment variable but does not set the value to the environment itself. +// This function is returning an error if there are any invalid lines. +func Unmarshal(str string) (Env, error) { + return strictParse(strings.NewReader(str), false) +} + +// Marshal outputs the given environment as a env file. +// Variables will be sorted by name. +func Marshal(env Env) (string, error) { + lines := make([]string, 0, len(env)) + for k, v := range env { + if d, err := strconv.Atoi(v); err == nil { + lines = append(lines, fmt.Sprintf(`%s=%d`, k, d)) + } else { + lines = append(lines, fmt.Sprintf(`%s=%q`, k, v)) + } + } + sort.Strings(lines) + return strings.Join(lines, "\n"), nil +} + +// Write serializes the given environment and writes it to a file +func Write(env Env, filename string) error { + content, err := Marshal(env) + if err != nil { + return err + } + // ensure the path exists + if err := os.MkdirAll(filepath.Dir(filename), 0o775); err != nil { + return err + } + // create or truncate the file + file, err := os.Create(filename) + if err != nil { + return err + } + defer file.Close() + _, err = file.WriteString(content + "\n") + if err != nil { + return err + } + + return file.Sync() +} + func strictParse(r io.Reader, override bool) (Env, error) { env := make(Env) scanner := bufio.NewScanner(r) @@ -143,28 +192,34 @@ func strictParse(r io.Reader, override bool) (Env, error) { } quote := "" + // look for the delimiter character idx := strings.Index(line, "=") if idx == -1 { idx = strings.Index(line, ":") } + // look for a quote character if idx > 0 && idx < len(line)-1 { val := strings.TrimSpace(line[idx+1:]) if val[0] == '"' || val[0] == '\'' { quote = val[:1] + // look for the closing quote character within the same line idx = strings.LastIndex(strings.TrimSpace(val[1:]), quote) if idx >= 0 && val[idx] != '\\' { quote = "" } } } + // look for the closing quote character for quote != "" && scanner.Scan() { l := scanner.Text() line += "\n" + l idx := strings.LastIndex(l, quote) if idx > 0 && l[idx-1] == '\\' { + // foud a matching quote character but it's escaped continue } if idx >= 0 { + // foud a matching quote quote = "" } } @@ -195,21 +250,23 @@ func parseLine(s string, env Env, override bool) error { return checkFormat(s, env) } - key := rm[1] - val := rm[2] - - // trim whitespace - val = strings.TrimSpace(val) + key := strings.TrimSpace(rm[1]) + val := strings.TrimSpace(rm[2]) - // determine if string has quote prefix - hdq := strings.HasPrefix(val, `"`) + var hsq, hdq bool - // determine if string has single quote prefix - hsq := strings.HasPrefix(val, `'`) + // check if the value is quoted + if l := len(val); l >= 2 { + l -= 1 + // has double quotes + hdq = val[0] == '"' && val[l] == '"' + // has single quotes + hsq = val[0] == '\'' && val[l] == '\'' - // remove quotes '' or "" - if l := len(val); (hsq || hdq) && l >= 2 { - val = val[1 : l-1] + // remove quotes '' or "" + if hsq || hdq { + val = val[1:l] + } } if hdq { @@ -220,11 +277,10 @@ func parseLine(s string, env Env, override bool) error { val = unescapeRgx.ReplaceAllString(val, "$1") } - fv := func(s string) string { - return varReplacement(s, hsq, env, override) - } - if !hsq { + fv := func(s string) string { + return varReplacement(s, hsq, env, override) + } val = varRgx.ReplaceAllStringFunc(val, fv) val = parseVal(val, env, hdq, override) } @@ -250,8 +306,13 @@ func parseExport(st string, env Env) error { var varNameRgx = regexp.MustCompile(`(\$)(\{?([A-Z0-9_]+)\}?)`) func varReplacement(s string, hsq bool, env Env, override bool) string { - if strings.HasPrefix(s, "\\") { - return strings.TrimPrefix(s, "\\") + if s == "" { + return s + } + + if s[0] == '\\' { + // the dollar sign is escaped + return s[1:] } if hsq { @@ -270,18 +331,17 @@ func varReplacement(s string, hsq bool, env Env, override bool) string { return replace } - replace, ok := env[v] - if !ok { - replace = os.Getenv(v) + if replace, ok := env[v]; ok { + return replace } - return replace + return os.Getenv(v) } func checkFormat(s string, env Env) error { st := strings.TrimSpace(s) - if (st == "") || strings.HasPrefix(st, "#") { + if st == "" || st[0] == '#' { return nil } diff --git a/tools/vendor/github.com/sylvia7788/contextcheck/README.md b/tools/vendor/github.com/sylvia7788/contextcheck/README.md index dc951aca..c6bb9895 100644 --- a/tools/vendor/github.com/sylvia7788/contextcheck/README.md +++ b/tools/vendor/github.com/sylvia7788/contextcheck/README.md @@ -17,6 +17,7 @@ func call1(ctx context.Context) { call2(context.Background()) // Non-inherited new context, use function like `context.WithXXX` instead call3() // Function `call3` should pass the context parameter + call4() // Function `call4->call3` should pass the context parameter ... } @@ -29,10 +30,68 @@ func call3() { call2(ctx) } +func call4() { + call3() +} + + +// if you want none-inherit ctx, use this function func getNewCtx(ctx context.Context) (newCtx context.Context) { ... return } + +/* ---------- check net/http.HandleFunc ---------- */ + +func call5(ctx context.Context, w http.ResponseWriter, r *http.Request) { +} + +func call6(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + call5(ctx, w, r) + call5(context.Background(), w, r) // Non-inherited new context, use function like `context.WithXXX` or `r.Context` instead +} + +func call7(in bool, w http.ResponseWriter, r *http.Request) { + call5(r.Context(), w, r) + call5(context.Background(), w, r) +} + +func call8() { + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + call5(r.Context(), w, r) + call5(context.Background(), w, r) // Non-inherited new context, use function like `context.WithXXX` or `r.Context` instead + + call6(w, r) + + // call7 should be like `func call7(ctx context.Context, in bool, w http.ResponseWriter, r *http.Request)` + call7(true, w, r) // Function `call7` should pass the context parameter + }) +} +``` + +## Tips + +You can break ctx inheritance by this way, eg: [issue](https://github.com/sylvia7788/contextcheck/issues/2). + +```go +func call1(ctx context.Context) { + ... + + newCtx, cancel := NoInheritCancel(ctx) + defer cancel() + + call2(newCtx) + ... +} + +func call2(ctx context.Context) { + ... +} + +func NoInheritCancel(_ context.Context) (context.Context,context.CancelFunc) { + return context.WithCancel(context.Background()) +} ``` ## Installation diff --git a/tools/vendor/github.com/sylvia7788/contextcheck/contextcheck.go b/tools/vendor/github.com/sylvia7788/contextcheck/contextcheck.go index 543a8020..6352191a 100644 --- a/tools/vendor/github.com/sylvia7788/contextcheck/contextcheck.go +++ b/tools/vendor/github.com/sylvia7788/contextcheck/contextcheck.go @@ -2,7 +2,6 @@ package contextcheck import ( "go/ast" - "go/token" "go/types" "strconv" "strings" @@ -11,49 +10,94 @@ import ( "github.com/gostaticanalysis/analysisutil" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/buildssa" + "golang.org/x/tools/go/packages" "golang.org/x/tools/go/ssa" ) -func NewAnalyzer() *analysis.Analyzer { - return &analysis.Analyzer{ +type Configuration struct { + DisableFact bool +} + +func NewAnalyzer(cfg Configuration) *analysis.Analyzer { + analyzer := &analysis.Analyzer{ Name: "contextcheck", Doc: "check the function whether use a non-inherited context", - Run: NewRun(), + Run: NewRun(nil, cfg.DisableFact), Requires: []*analysis.Analyzer{ buildssa.Analyzer, }, } + + if !cfg.DisableFact { + analyzer.FactTypes = append(analyzer.FactTypes, (*ctxFact)(nil)) + } + + return analyzer } const ( ctxPkg = "context" ctxName = "Context" + + httpPkg = "net/http" + httpRes = "ResponseWriter" + httpReq = "Request" ) const ( CtxIn int = 1 << iota // ctx in function's param CtxOut // ctx in function's results CtxInField // ctx in function's field param +) + +type entryType int - CtxInOut = CtxIn | CtxOut +const ( + EntryNone entryType = iota + EntryWithCtx // has ctx in + EntryWithHttpHandler // is http handler ) var ( - checkedMap = make(map[string]bool) - checkedMapLock sync.RWMutex + pkgFactMap = make(map[*types.Package]ctxFact) + pkgFactMu sync.RWMutex ) +type resInfo struct { + Valid bool + Funcs []string +} + +type ctxFact map[string]resInfo + +func (*ctxFact) String() string { return "ctxCheck" } +func (*ctxFact) AFact() {} + type runner struct { pass *analysis.Pass ctxTyp *types.Named ctxPTyp *types.Pointer - cmpPath string skipFile map[*ast.File]bool + + httpResTyps []types.Type + httpReqTyps []types.Type + + currentFact ctxFact + disableFact bool } -func NewRun() func(pass *analysis.Pass) (interface{}, error) { +func NewRun(pkgs []*packages.Package, disableFact bool) func(pass *analysis.Pass) (interface{}, error) { + m := make(map[string]bool) + for _, pkg := range pkgs { + m[strings.Split(pkg.PkgPath, "/")[0]] = true + } return func(pass *analysis.Pass) (interface{}, error) { - r := new(runner) + // skip different repo + if !m[strings.Split(pass.Pkg.Path(), "/")[0]] { + return nil, nil + } + + r := &runner{disableFact: disableFact} r.run(pass) return nil, nil } @@ -61,49 +105,90 @@ func NewRun() func(pass *analysis.Pass) (interface{}, error) { func (r *runner) run(pass *analysis.Pass) { r.pass = pass - r.cmpPath = strings.Split(pass.Pkg.Path(), "/")[0] pssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) funcs := pssa.SrcFuncs - name := pass.Pkg.Path() - _ = name - - pkg := pssa.Pkg.Prog.ImportedPackage(ctxPkg) - if pkg == nil { - return - } - ctxType := pkg.Type(ctxName) - if ctxType == nil { + // collect ctx obj + var ok bool + r.ctxTyp, r.ctxPTyp, ok = r.getRequiedType(pssa, ctxPkg, ctxName) + if !ok { return } - if resNamed, ok := ctxType.Object().Type().(*types.Named); !ok { - return - } else { - r.ctxTyp = resNamed - r.ctxPTyp = types.NewPointer(resNamed) - } + // collect http obj + r.collectHttpTyps(pssa) r.skipFile = make(map[*ast.File]bool) + r.currentFact = make(ctxFact) + type entryInfo struct { + f *ssa.Function // entryfunc + tp entryType // entrytype + } + var tmpFuncs []entryInfo for _, f := range funcs { // skip checked function key := f.RelString(nil) - _, ok := getValue(key) - if ok { + if _, ok := r.currentFact[key]; ok { continue } - if !r.checkIsEntry(f, f.Pos()) { + if entryType := r.checkIsEntry(f); entryType == EntryNone { + // record the result of nomal function + checkingMap := make(map[string]bool) + checkingMap[key] = true + r.setFact(key, r.checkFuncWithoutCtx(f, checkingMap), f.Name()) continue + } else { + tmpFuncs = append(tmpFuncs, entryInfo{f: f, tp: entryType}) + } + } + + for _, v := range tmpFuncs { + r.checkFuncWithCtx(v.f, v.tp) + } + + if len(r.currentFact) > 0 { + if r.disableFact { + setPkgFact(pass.Pkg, r.currentFact) + } else { + pass.ExportPackageFact(&r.currentFact) } + } +} + +func (r *runner) getRequiedType(pssa *buildssa.SSA, path, name string) (obj *types.Named, pobj *types.Pointer, ok bool) { + pkg := pssa.Pkg.Prog.ImportedPackage(path) + if pkg == nil { + return + } + + objTyp := pkg.Type(name) + if objTyp == nil { + return + } + obj, ok = objTyp.Object().Type().(*types.Named) + if !ok { + return + } + pobj = types.NewPointer(obj) + + return +} - r.checkFuncWithCtx(f) - setValue(key, true) +func (r *runner) collectHttpTyps(pssa *buildssa.SSA) { + objRes, pobjRes, ok := r.getRequiedType(pssa, httpPkg, httpRes) + if ok { + r.httpResTyps = append(r.httpResTyps, objRes, pobjRes) + } + + objReq, pobjReq, ok := r.getRequiedType(pssa, httpPkg, httpReq) + if ok { + r.httpReqTyps = append(r.httpReqTyps, objReq, pobjReq, types.NewPointer(pobjReq)) } } -func (r *runner) noImportedContext(f *ssa.Function) (ret bool) { +func (r *runner) noImportedContextAndHttp(f *ssa.Function) (ret bool) { if !f.Pos().IsValid() { return false } @@ -126,7 +211,7 @@ func (r *runner) noImportedContext(f *ssa.Function) (ret bool) { continue } path = analysisutil.RemoveVendor(path) - if path == ctxPkg { + if path == ctxPkg || path == httpPkg { return false } } @@ -134,16 +219,34 @@ func (r *runner) noImportedContext(f *ssa.Function) (ret bool) { return true } -func (r *runner) checkIsEntry(f *ssa.Function, pos token.Pos) (ret bool) { - if r.noImportedContext(f) { - return false +func (r *runner) checkIsEntry(f *ssa.Function) entryType { + if r.noImportedContextAndHttp(f) { + return EntryNone + } + + ctxIn, ctxOut := r.checkIsCtx(f) + if ctxOut { + // skip the function which generate ctx + return EntryNone + } else if ctxIn { + // has ctx in, ignore *http.Request.Context() + return EntryWithCtx } + // check is `func handler(w http.ResponseWriter, r *http.Request) {}` + if r.checkIsHttpHandler(f) { + return EntryWithHttpHandler + } + + return EntryNone +} + +func (r *runner) checkIsCtx(f *ssa.Function) (in, out bool) { // check params tuple := f.Signature.Params() for i := 0; i < tuple.Len(); i++ { if r.isCtxType(tuple.At(i).Type()) { - ret = true + in = true break } } @@ -151,7 +254,7 @@ func (r *runner) checkIsEntry(f *ssa.Function, pos token.Pos) (ret bool) { // check freevars for _, param := range f.FreeVars { if r.isCtxType(param.Type()) { - ret = true + in = true break } } @@ -159,17 +262,29 @@ func (r *runner) checkIsEntry(f *ssa.Function, pos token.Pos) (ret bool) { // check results tuple = f.Signature.Results() for i := 0; i < tuple.Len(); i++ { - // skip the function which generate ctx if r.isCtxType(tuple.At(i).Type()) { - ret = false + out = true break } } - return } -func (r *runner) collectCtxRef(f *ssa.Function) (refMap map[ssa.Instruction]bool, ok bool) { +func (r *runner) checkIsHttpHandler(f *ssa.Function) bool { + // must has no result + if f.Signature.Results().Len() > 0 { + return false + } + + // must be `func f(w http.ResponseWriter, r *http.Request) {}` + tuple := f.Signature.Params() + if tuple.Len() != 2 { + return false + } + return r.isHttpResType(tuple.At(0).Type()) && r.isHttpReqType(tuple.At(1).Type()) +} + +func (r *runner) collectCtxRef(f *ssa.Function, isHttpHandler bool) (refMap map[ssa.Instruction]bool, ok bool) { ok = true refMap = make(map[ssa.Instruction]bool) checkedRefMap := make(map[ssa.Value]bool) @@ -233,15 +348,21 @@ func (r *runner) collectCtxRef(f *ssa.Function) (refMap map[ssa.Instruction]bool } } - for _, param := range f.Params { - if r.isCtxType(param.Type()) { - checkRefs(param, false) + if isHttpHandler { + for _, v := range r.getHttpReqCtx(f) { + checkRefs(v, false) + } + } else { + for _, param := range f.Params { + if r.isCtxType(param.Type()) { + checkRefs(param, false) + } } - } - for _, param := range f.FreeVars { - if r.isCtxType(param.Type()) { - checkRefs(param, false) + for _, param := range f.FreeVars { + if r.isCtxType(param.Type()) { + checkRefs(param, false) + } } } @@ -264,23 +385,76 @@ func (r *runner) collectCtxRef(f *ssa.Function) (refMap map[ssa.Instruction]bool return } -func (r *runner) buildPkg(f *ssa.Function) { - if f.Blocks != nil { - return +func (r *runner) getHttpReqCtx(f *ssa.Function) (rets []ssa.Value) { + checkedRefMap := make(map[ssa.Value]bool) + + var checkRefs func(val ssa.Value, fromAddr bool) + var checkInstr func(instr ssa.Instruction, fromAddr bool) + + checkRefs = func(val ssa.Value, fromAddr bool) { + if val == nil || val.Referrers() == nil { + return + } + + if checkedRefMap[val] { + return + } + checkedRefMap[val] = true + + for _, instr := range *val.Referrers() { + checkInstr(instr, fromAddr) + } + } + + checkInstr = func(instr ssa.Instruction, fromAddr bool) { + switch i := instr.(type) { + case ssa.CallInstruction: + // r.Context() only has one recv + if len(i.Common().Args) != 1 { + break + } + + // find r.Context() + if r.getCallInstrCtxType(i)&CtxOut != CtxOut { + break + } + + // check is r.Context + f := r.getFunction(instr) + if f == nil || f.Name() != ctxName { + break + } + if f.Signature.Recv() != nil { + // collect the return of r.Context + rets = append(rets, i.Value()) + } + case *ssa.Store: + if !fromAddr { + checkRefs(i.Addr, true) + } + case *ssa.UnOp: + checkRefs(i, false) + case *ssa.Phi: + checkRefs(i, false) + case *ssa.MakeClosure: + case *ssa.Extract: + // http.Request can only be input + } } - // only build the pkg which is in the same repo - if r.checkIsSameRepo(f.Pkg.Pkg.Path()) { - f.Pkg.Build() + for _, param := range f.Params { + if r.isHttpReqType(param.Type()) { + checkRefs(param, false) + break + } } -} -func (r *runner) checkIsSameRepo(s string) bool { - return strings.HasPrefix(s, r.cmpPath+"/") + return } -func (r *runner) checkFuncWithCtx(f *ssa.Function) { - refMap, ok := r.collectCtxRef(f) +func (r *runner) checkFuncWithCtx(f *ssa.Function, tp entryType) { + isHttpHandler := tp == EntryWithHttpHandler + refMap, ok := r.collectCtxRef(f, isHttpHandler) if !ok { return } @@ -299,7 +473,11 @@ func (r *runner) checkFuncWithCtx(f *ssa.Function) { if tp&CtxIn != 0 { if !refMap[instr] { - r.pass.Reportf(instr.Pos(), "Non-inherited new context, use function like `context.WithXXX` instead") + if isHttpHandler { + r.pass.Reportf(instr.Pos(), "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") + } } } @@ -309,29 +487,10 @@ func (r *runner) checkFuncWithCtx(f *ssa.Function) { } key := ff.RelString(nil) - valid, ok := getValue(key) + res, ok := r.getValue(key, ff) if ok { - if !valid { - r.pass.Reportf(instr.Pos(), "Function `%s` should pass the context parameter", ff.Name()) - } - continue - } - - // check is thunk or bound - if strings.HasSuffix(key, "$thunk") || strings.HasSuffix(key, "$bound") { - continue - } - - // if ff has no ctx, start deep traversal check - if !r.checkIsEntry(ff, instr.Pos()) { - r.buildPkg(ff) - - checkingMap := make(map[string]bool) - checkingMap[key] = true - valid := r.checkFuncWithoutCtx(ff, checkingMap) - setValue(key, valid) - if !valid { - r.pass.Reportf(instr.Pos(), "Function `%s` should pass the context parameter", ff.Name()) + if !res.Valid { + r.pass.Reportf(instr.Pos(), "Function `%s` should pass the context parameter", strings.Join(reverse(res.Funcs), "->")) } } } @@ -340,6 +499,7 @@ func (r *runner) checkFuncWithCtx(f *ssa.Function) { func (r *runner) checkFuncWithoutCtx(f *ssa.Function, checkingMap map[string]bool) (ret bool) { ret = true + orgKey := f.RelString(nil) for _, b := range f.Blocks { for _, instr := range b.Instrs { tp, ok := r.getCtxType(instr) @@ -356,7 +516,6 @@ func (r *runner) checkFuncWithoutCtx(f *ssa.Function, checkingMap map[string]boo if tp&CtxInField == 0 { ret = false } - continue } ff := r.getFunction(instr) @@ -365,11 +524,13 @@ func (r *runner) checkFuncWithoutCtx(f *ssa.Function, checkingMap map[string]boo } key := ff.RelString(nil) - valid, ok := getValue(key) + res, ok := r.getValue(key, ff) if ok { - if !valid { + if !res.Valid { ret = false - r.pass.Reportf(instr.Pos(), "Function `%s` should pass the context parameter", ff.Name()) + + // save the call link + r.setFact(orgKey, res.Valid, res.Funcs...) } continue } @@ -379,20 +540,22 @@ func (r *runner) checkFuncWithoutCtx(f *ssa.Function, checkingMap map[string]boo continue } - if !r.checkIsEntry(ff, instr.Pos()) { - // handler ring call + if entryType := r.checkIsEntry(ff); entryType == EntryNone { + // cannot get info from fact, skip + if ff.Blocks == nil { + continue + } + + // handler cycle call if checkingMap[key] { continue } checkingMap[key] = true - r.buildPkg(ff) - valid := r.checkFuncWithoutCtx(ff, checkingMap) - setValue(key, valid) + r.setFact(orgKey, valid, ff.Name()) if !valid { ret = false - r.pass.Reportf(instr.Pos(), "Function `%s` should pass the context parameter", ff.Name()) } } } @@ -493,15 +656,78 @@ func (r *runner) isCtxType(tp types.Type) bool { return types.Identical(tp, r.ctxTyp) || types.Identical(tp, r.ctxPTyp) } -func getValue(key string) (valid, ok bool) { - checkedMapLock.RLock() - valid, ok = checkedMap[key] - checkedMapLock.RUnlock() +func (r *runner) isHttpResType(tp types.Type) bool { + for _, v := range r.httpResTyps { + if ok := types.Identical(v, v); ok { + return true + } + } + return false +} + +func (r *runner) isHttpReqType(tp types.Type) bool { + for _, v := range r.httpReqTyps { + if ok := types.Identical(tp, v); ok { + return true + } + } + return false +} + +func (r *runner) getValue(key string, f *ssa.Function) (res resInfo, ok bool) { + res, ok = r.currentFact[key] + if ok { + return + } + + if f.Pkg == nil { + return + } + + var fact ctxFact + var got bool + if r.disableFact { + fact, got = getPkgFact(f.Pkg.Pkg) + } else { + got = r.pass.ImportPackageFact(f.Pkg.Pkg, &fact) + } + if got { + res, ok = fact[key] + } + return +} + +func (r *runner) setFact(key string, valid bool, funcs ...string) { + r.currentFact[key] = resInfo{ + Valid: valid, + Funcs: append(r.currentFact[key].Funcs, funcs...), + } +} + +// setPkgFact save fact to mem +func setPkgFact(pkg *types.Package, fact ctxFact) { + pkgFactMu.Lock() + pkgFactMap[pkg] = fact + pkgFactMu.Unlock() +} + +// getPkgFact get fact from mem +func getPkgFact(pkg *types.Package) (fact ctxFact, ok bool) { + pkgFactMu.RLock() + fact, ok = pkgFactMap[pkg] + pkgFactMu.RUnlock() return } -func setValue(key string, valid bool) { - checkedMapLock.Lock() - checkedMap[key] = valid - checkedMapLock.Unlock() +func reverse(arr1 []string) (arr2 []string) { + l := len(arr1) + if l == 0 { + return + } + arr2 = make([]string, l) + for i := 0; i <= l/2; i++ { + arr2[i] = arr1[l-1-i] + arr2[l-1-i] = arr1[i] + } + return } diff --git a/tools/vendor/github.com/timonwong/logrlint/.gitignore b/tools/vendor/github.com/timonwong/logrlint/.gitignore new file mode 100644 index 00000000..955e8064 --- /dev/null +++ b/tools/vendor/github.com/timonwong/logrlint/.gitignore @@ -0,0 +1,5 @@ +.vscode/ +.idea/ + +bin/ +vendor/ diff --git a/tools/vendor/github.com/timonwong/logrlint/LICENSE b/tools/vendor/github.com/timonwong/logrlint/LICENSE new file mode 100644 index 00000000..fb653109 --- /dev/null +++ b/tools/vendor/github.com/timonwong/logrlint/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Timon Wong + +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/timonwong/logrlint/Makefile b/tools/vendor/github.com/timonwong/logrlint/Makefile new file mode 100644 index 00000000..ad63ec53 --- /dev/null +++ b/tools/vendor/github.com/timonwong/logrlint/Makefile @@ -0,0 +1,18 @@ +lint: + golangci-lint run ./... + +.PHONY: test-deps +test-deps: + cd testdata/src/a && go mod vendor + +.PHONY: test +test: test-deps + go test ./... + +.PHONY: build +build: + go build -o bin/logrlint ./cmd/logrlint + +.PHONY: build-plugin +build-plugin: + CGO_ENABLED=1 go build -o bin/logrlint.so -buildmode=plugin ./plugin diff --git a/tools/vendor/github.com/timonwong/logrlint/README.md b/tools/vendor/github.com/timonwong/logrlint/README.md new file mode 100644 index 00000000..6b3f7892 --- /dev/null +++ b/tools/vendor/github.com/timonwong/logrlint/README.md @@ -0,0 +1,3 @@ +# logrlint + +A linter checks the odd number of key and value pairs for [logr](https://github.com/go-logr/logr) diff --git a/tools/vendor/github.com/timonwong/logrlint/logrlint.go b/tools/vendor/github.com/timonwong/logrlint/logrlint.go new file mode 100644 index 00000000..5c45903c --- /dev/null +++ b/tools/vendor/github.com/timonwong/logrlint/logrlint.go @@ -0,0 +1,106 @@ +package logrlint + +import ( + "fmt" + "go/ast" + "go/types" + + "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 Doc = "Check logr arguments." + +var Analyzer = &analysis.Analyzer{ + Name: "logrlint", + Doc: Doc, + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, +} + +var isValidName = map[string]struct{}{ + "Error": {}, + "Info": {}, + "WithValues": {}, +} + +func isValidPackage(pass *analysis.Pass, fn *types.Func) bool { + // We allow only logr package import path + const packageName = "github.com/go-logr/logr" + + pkg := fn.Pkg() + if pkg == nil { + return false + } + pkgPath := pkg.Path() + // Fast path: for GOPATH or go mod enabled packages + if pkgPath == packageName { + return true + } + + // Special case for vendor + vendorPath := fmt.Sprintf("%s/vendor/%s", pass.Pkg.Name(), packageName) + return pkgPath == vendorPath +} + +func checkEvenArguments(pass *analysis.Pass, call *ast.CallExpr) { + fn, _ := typeutil.Callee(pass.TypesInfo, call).(*types.Func) + if fn == nil { + return // function pointer is not supported + } + + sig, ok := fn.Type().(*types.Signature) + if !ok || !sig.Variadic() { + return // not variadic + } + + if _, ok := isValidName[fn.Name()]; !ok { + return + } + + if !isValidPackage(pass, fn) { + return + } + + params := sig.Params() + nparams := params.Len() // variadic => nonzero + args := params.At(nparams - 1) + iface, ok := args.Type().(*types.Slice).Elem().(*types.Interface) + if !ok || !iface.Empty() { + return // final (args) param is not ...interface{} + } + + startIndex := nparams - 1 + variadicLen := len(call.Args) - (startIndex) + if variadicLen%2 != 0 { + firstArg := call.Args[startIndex] + lastArg := call.Args[len(call.Args)-1] + pass.Report(analysis.Diagnostic{ + Pos: firstArg.Pos(), + End: lastArg.End(), + Category: "logging", + Message: "odd number of arguments passed as key-value pairs for logging"}) + } +} + +func run(pass *analysis.Pass) (interface{}, error) { + insp := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + nodeFilter := []ast.Node{ + (*ast.CallExpr)(nil), + } + insp.Preorder(nodeFilter, func(node ast.Node) { + call := node.(*ast.CallExpr) + + typ := pass.TypesInfo.Types[call.Fun].Type + if typ == nil { + // Skip checking functions with unknown type. + return + } + + checkEvenArguments(pass, call) + }) + + return nil, nil +} diff --git a/tools/vendor/github.com/uudashr/gocognit/README.md b/tools/vendor/github.com/uudashr/gocognit/README.md index 4a884690..1e028c78 100644 --- a/tools/vendor/github.com/uudashr/gocognit/README.md +++ b/tools/vendor/github.com/uudashr/gocognit/README.md @@ -144,6 +144,13 @@ The following structures receive a nesting increment commensurate with their nes 3. `for` ## Installation + +``` +$ go install github.com/uudashr/gocognit/cmd/gocognit@latest +``` + +or + ``` $ go get github.com/uudashr/gocognit/cmd/gocognit ``` diff --git a/tools/vendor/github.com/uudashr/gocognit/gocognit.go b/tools/vendor/github.com/uudashr/gocognit/gocognit.go index 0687f5e2..1d539ee7 100644 --- a/tools/vendor/github.com/uudashr/gocognit/gocognit.go +++ b/tools/vendor/github.com/uudashr/gocognit/gocognit.go @@ -49,18 +49,6 @@ func funcName(fn *ast.FuncDecl) string { return fn.Name.Name } -// recvString returns a string representation of recv of the -// form "T", "*T", or "BADRECV" (if not a proper receiver type). -func recvString(recv ast.Expr) string { - switch t := recv.(type) { - case *ast.Ident: - return t.Name - case *ast.StarExpr: - return "*" + recvString(t.X) - } - return "BADRECV" -} - // Complexity calculates the cognitive complexity of a function. func Complexity(fn *ast.FuncDecl) int { v := complexityVisitor{ @@ -344,7 +332,7 @@ func mergeBinaryOps(x []token.Token, op token.Token, y []token.Token) []token.To const Doc = `Find complex function using cognitive complexity calculation. -The gocognit analysis repots functions or methods which the complexity is over +The gocognit analysis reports functions or methods which the complexity is over than the specified limit.` // Analyzer reports a diagnostic for every function or method which is diff --git a/tools/vendor/github.com/uudashr/gocognit/recv.go b/tools/vendor/github.com/uudashr/gocognit/recv.go new file mode 100644 index 00000000..2f20d843 --- /dev/null +++ b/tools/vendor/github.com/uudashr/gocognit/recv.go @@ -0,0 +1,24 @@ +//go:build go1.18 +// +build go1.18 + +package gocognit + +import ( + "go/ast" +) + +// recvString returns a string representation of recv of the +// form "T", "*T", or "BADRECV" (if not a proper receiver type). +func recvString(recv ast.Expr) string { + switch t := recv.(type) { + case *ast.Ident: + return t.Name + case *ast.StarExpr: + return "*" + recvString(t.X) + case *ast.IndexExpr: + return recvString(t.X) + case *ast.IndexListExpr: + return recvString(t.X) + } + return "BADRECV" +} diff --git a/tools/vendor/github.com/uudashr/gocognit/recv_pre118.go b/tools/vendor/github.com/uudashr/gocognit/recv_pre118.go new file mode 100644 index 00000000..9e0ebfd8 --- /dev/null +++ b/tools/vendor/github.com/uudashr/gocognit/recv_pre118.go @@ -0,0 +1,20 @@ +//go:build !go1.18 +// +build !go1.18 + +package gocognit + +import ( + "go/ast" +) + +// recvString returns a string representation of recv of the +// form "T", "*T", or "BADRECV" (if not a proper receiver type). +func recvString(recv ast.Expr) string { + switch t := recv.(type) { + case *ast.Ident: + return t.Name + case *ast.StarExpr: + return "*" + recvString(t.X) + } + return "BADRECV" +} diff --git a/tools/vendor/gitlab.com/bosi/decorder/.gitlab-ci.yml b/tools/vendor/gitlab.com/bosi/decorder/.gitlab-ci.yml index 810b6cb4..1ea3b03f 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.17.5@sha256:c72fa9afc50b3303e8044cf28fb358b48032a548e1825819420fd40155a131cb + image: golang:1.18.4@sha256:9349ed889adb906efa5ebc06485fe1b6a12fb265a01c9266a137bb1352565560 before_script: - set -eu - if [[ -f .env.pipeline ]];then cp .env.pipeline .env;fi @@ -27,14 +27,14 @@ test: lint:source-code: stage: test - image: golangci/golangci-lint:v1.43.0-alpine@sha256:24d773a07983d19963b6e07c7d5bce1b7835f8fb37486d34081e6a40302c17c5 + image: golangci/golangci-lint:v1.47.2-alpine@sha256:10ed4891fdd1f7249f5e39d7c17ea746ce26adada3c05686c6aa31290abcd180 script: - '### run linter ###' - golangci-lint run ./... license-check: stage: test - image: golang:1.17.5@sha256:c72fa9afc50b3303e8044cf28fb358b48032a548e1825819420fd40155a131cb + image: golang:1.18.4@sha256:9349ed889adb906efa5ebc06485fe1b6a12fb265a01c9266a137bb1352565560 before_script: - set -eu - if [[ -f .env.pipeline ]];then cp .env.pipeline .env;fi @@ -51,7 +51,7 @@ license-check: pages: stage: release - image: golang:1.17.5@sha256:c72fa9afc50b3303e8044cf28fb358b48032a548e1825819420fd40155a131cb + image: golang:1.18.4@sha256:9349ed889adb906efa5ebc06485fe1b6a12fb265a01c9266a137bb1352565560 only: - tags script: diff --git a/tools/vendor/gitlab.com/bosi/decorder/analyzer.go b/tools/vendor/gitlab.com/bosi/decorder/analyzer.go index 91a78475..308c96b9 100644 --- a/tools/vendor/gitlab.com/bosi/decorder/analyzer.go +++ b/tools/vendor/gitlab.com/bosi/decorder/analyzer.go @@ -75,7 +75,7 @@ func runInitFuncFirstCheck(pass *analysis.Pass) func(ast.Node) bool { return true } - if dec.Name.Name == "init" { + if dec.Name.Name == "init" && dec.Recv == nil { if nonInitFound { pass.Reportf(dec.Pos(), "init func must be the first function in file") } @@ -90,6 +90,12 @@ func runInitFuncFirstCheck(pass *analysis.Pass) func(ast.Node) bool { func runDeclNumAndDecOrderCheck(pass *analysis.Pass) func(ast.Node) bool { dnc := newDecNumChecker() + if disableDecNumCheck && disableDecOrderCheck { + return func(n ast.Node) bool { + return true + } + } + return func(n ast.Node) bool { fd, ok := n.(*ast.FuncDecl) if ok { @@ -105,9 +111,7 @@ func runDeclNumAndDecOrderCheck(pass *analysis.Pass) func(ast.Node) bool { return true } - if !disableDecNumCheck { - dnc.handleDecNumCheck(gd, pass) - } + dnc.handleGenDecl(gd, pass) if !disableDecOrderCheck { dnc.handleDecOrderCheck(gd, pass) @@ -152,12 +156,12 @@ func (dnc decNumChecker) isToLate(t token.Token) (string, bool) { return "", true } -func (dnc *decNumChecker) handleDecNumCheck(gd *ast.GenDecl, pass *analysis.Pass) { +func (dnc *decNumChecker) handleGenDecl(gd *ast.GenDecl, pass *analysis.Pass) { for _, t := range tokens { if gd.Tok == t { dnc.tokenCounts[t]++ - if dnc.tokenCounts[t] > 1 { + if !disableDecNumCheck && dnc.tokenCounts[t] > 1 { pass.Reportf(gd.Pos(), "multiple \"%s\" declarations are not allowed; use parentheses instead", t.String()) } } diff --git a/tools/vendor/gitlab.com/bosi/decorder/renovate.json b/tools/vendor/gitlab.com/bosi/decorder/renovate.json index 95cf1af0..5c0388c5 100644 --- a/tools/vendor/gitlab.com/bosi/decorder/renovate.json +++ b/tools/vendor/gitlab.com/bosi/decorder/renovate.json @@ -21,6 +21,9 @@ "updateLockFiles": true, "docker": { "pinDigests": true - } + }, + "postUpdateOptions": [ + "gomodTidy" + ] } diff --git a/tools/vendor/go.uber.org/atomic/.codecov.yml b/tools/vendor/go.uber.org/atomic/.codecov.yml new file mode 100644 index 00000000..571116cc --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/.codecov.yml @@ -0,0 +1,19 @@ +coverage: + range: 80..100 + round: down + precision: 2 + + status: + project: # measuring the overall project coverage + default: # context, you can create multiple ones with custom titles + enabled: yes # must be yes|true to enable this status + target: 100 # specify the target coverage for each commit status + # option: "auto" (must increase from parent commit or pull request base) + # option: "X%" a static target percentage to hit + if_not_found: success # if parent is not found report status as success, error, or failure + if_ci_failed: error # if ci fails report status as success, error, or failure + +# Also update COVER_IGNORE_PKGS in the Makefile. +ignore: + - /internal/gen-atomicint/ + - /internal/gen-valuewrapper/ diff --git a/tools/vendor/go.uber.org/atomic/.gitignore b/tools/vendor/go.uber.org/atomic/.gitignore new file mode 100644 index 00000000..2e337a0e --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/.gitignore @@ -0,0 +1,15 @@ +/bin +.DS_Store +/vendor +cover.html +cover.out +lint.log + +# Binaries +*.test + +# Profiling output +*.prof + +# Output of fossa analyzer +/fossa diff --git a/tools/vendor/go.uber.org/atomic/CHANGELOG.md b/tools/vendor/go.uber.org/atomic/CHANGELOG.md new file mode 100644 index 00000000..38f564e2 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/CHANGELOG.md @@ -0,0 +1,100 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.9.0] - 2021-07-15 +### Added +- Add `Float64.Swap` to match int atomic operations. +- Add `atomic.Time` type for atomic operations on `time.Time` values. + +[1.9.0]: https://github.com/uber-go/atomic/compare/v1.8.0...v1.9.0 + +## [1.8.0] - 2021-06-09 +### Added +- Add `atomic.Uintptr` type for atomic operations on `uintptr` values. +- Add `atomic.UnsafePointer` type for atomic operations on `unsafe.Pointer` values. + +[1.8.0]: https://github.com/uber-go/atomic/compare/v1.7.0...v1.8.0 + +## [1.7.0] - 2020-09-14 +### Added +- Support JSON serialization and deserialization of primitive atomic types. +- Support Text marshalling and unmarshalling for string atomics. + +### Changed +- Disallow incorrect comparison of atomic values in a non-atomic way. + +### Removed +- Remove dependency on `golang.org/x/{lint, tools}`. + +[1.7.0]: https://github.com/uber-go/atomic/compare/v1.6.0...v1.7.0 + +## [1.6.0] - 2020-02-24 +### Changed +- Drop library dependency on `golang.org/x/{lint, tools}`. + +[1.6.0]: https://github.com/uber-go/atomic/compare/v1.5.1...v1.6.0 + +## [1.5.1] - 2019-11-19 +- Fix bug where `Bool.CAS` and `Bool.Toggle` do work correctly together + causing `CAS` to fail even though the old value matches. + +[1.5.1]: https://github.com/uber-go/atomic/compare/v1.5.0...v1.5.1 + +## [1.5.0] - 2019-10-29 +### Changed +- With Go modules, only the `go.uber.org/atomic` import path is supported now. + If you need to use the old import path, please add a `replace` directive to + your `go.mod`. + +[1.5.0]: https://github.com/uber-go/atomic/compare/v1.4.0...v1.5.0 + +## [1.4.0] - 2019-05-01 +### Added + - Add `atomic.Error` type for atomic operations on `error` values. + +[1.4.0]: https://github.com/uber-go/atomic/compare/v1.3.2...v1.4.0 + +## [1.3.2] - 2018-05-02 +### Added +- Add `atomic.Duration` type for atomic operations on `time.Duration` values. + +[1.3.2]: https://github.com/uber-go/atomic/compare/v1.3.1...v1.3.2 + +## [1.3.1] - 2017-11-14 +### Fixed +- Revert optimization for `atomic.String.Store("")` which caused data races. + +[1.3.1]: https://github.com/uber-go/atomic/compare/v1.3.0...v1.3.1 + +## [1.3.0] - 2017-11-13 +### Added +- Add `atomic.Bool.CAS` for compare-and-swap semantics on bools. + +### Changed +- Optimize `atomic.String.Store("")` by avoiding an allocation. + +[1.3.0]: https://github.com/uber-go/atomic/compare/v1.2.0...v1.3.0 + +## [1.2.0] - 2017-04-12 +### Added +- Shadow `atomic.Value` from `sync/atomic`. + +[1.2.0]: https://github.com/uber-go/atomic/compare/v1.1.0...v1.2.0 + +## [1.1.0] - 2017-03-10 +### Added +- Add atomic `Float64` type. + +### Changed +- Support new `go.uber.org/atomic` import path. + +[1.1.0]: https://github.com/uber-go/atomic/compare/v1.0.0...v1.1.0 + +## [1.0.0] - 2016-07-18 + +- Initial release. + +[1.0.0]: https://github.com/uber-go/atomic/releases/tag/v1.0.0 diff --git a/tools/vendor/go.uber.org/atomic/LICENSE.txt b/tools/vendor/go.uber.org/atomic/LICENSE.txt new file mode 100644 index 00000000..8765c9fb --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2016 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. diff --git a/tools/vendor/go.uber.org/atomic/Makefile b/tools/vendor/go.uber.org/atomic/Makefile new file mode 100644 index 00000000..46c945b3 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/Makefile @@ -0,0 +1,79 @@ +# Directory to place `go install`ed binaries into. +export GOBIN ?= $(shell pwd)/bin + +GOLINT = $(GOBIN)/golint +GEN_ATOMICINT = $(GOBIN)/gen-atomicint +GEN_ATOMICWRAPPER = $(GOBIN)/gen-atomicwrapper +STATICCHECK = $(GOBIN)/staticcheck + +GO_FILES ?= $(shell find . '(' -path .git -o -path vendor ')' -prune -o -name '*.go' -print) + +# Also update ignore section in .codecov.yml. +COVER_IGNORE_PKGS = \ + go.uber.org/atomic/internal/gen-atomicint \ + go.uber.org/atomic/internal/gen-atomicwrapper + +.PHONY: build +build: + go build ./... + +.PHONY: test +test: + go test -race ./... + +.PHONY: gofmt +gofmt: + $(eval FMT_LOG := $(shell mktemp -t gofmt.XXXXX)) + gofmt -e -s -l $(GO_FILES) > $(FMT_LOG) || true + @[ ! -s "$(FMT_LOG)" ] || (echo "gofmt failed:" && cat $(FMT_LOG) && false) + +$(GOLINT): + cd tools && go install golang.org/x/lint/golint + +$(STATICCHECK): + cd tools && go install honnef.co/go/tools/cmd/staticcheck + +$(GEN_ATOMICWRAPPER): $(wildcard ./internal/gen-atomicwrapper/*) + go build -o $@ ./internal/gen-atomicwrapper + +$(GEN_ATOMICINT): $(wildcard ./internal/gen-atomicint/*) + go build -o $@ ./internal/gen-atomicint + +.PHONY: golint +golint: $(GOLINT) + $(GOLINT) ./... + +.PHONY: staticcheck +staticcheck: $(STATICCHECK) + $(STATICCHECK) ./... + +.PHONY: lint +lint: gofmt golint staticcheck generatenodirty + +# comma separated list of packages to consider for code coverage. +COVER_PKG = $(shell \ + go list -find ./... | \ + grep -v $(foreach pkg,$(COVER_IGNORE_PKGS),-e "^$(pkg)$$") | \ + paste -sd, -) + +.PHONY: cover +cover: + go test -coverprofile=cover.out -coverpkg $(COVER_PKG) -v ./... + go tool cover -html=cover.out -o cover.html + +.PHONY: generate +generate: $(GEN_ATOMICINT) $(GEN_ATOMICWRAPPER) + go generate ./... + +.PHONY: generatenodirty +generatenodirty: + @[ -z "$$(git status --porcelain)" ] || ( \ + echo "Working tree is dirty. Commit your changes first."; \ + git status; \ + exit 1 ) + @make generate + @status=$$(git status --porcelain); \ + [ -z "$$status" ] || ( \ + echo "Working tree is dirty after `make generate`:"; \ + echo "$$status"; \ + echo "Please ensure that the generated code is up-to-date." ) diff --git a/tools/vendor/go.uber.org/atomic/README.md b/tools/vendor/go.uber.org/atomic/README.md new file mode 100644 index 00000000..96b47a1f --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/README.md @@ -0,0 +1,63 @@ +# atomic [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] [![Go Report Card][reportcard-img]][reportcard] + +Simple wrappers for primitive types to enforce atomic access. + +## Installation + +```shell +$ go get -u go.uber.org/atomic@v1 +``` + +### Legacy Import Path + +As of v1.5.0, the import path `go.uber.org/atomic` is the only supported way +of using this package. If you are using Go modules, this package will fail to +compile with the legacy import path path `github.com/uber-go/atomic`. + +We recommend migrating your code to the new import path but if you're unable +to do so, or if your dependencies are still using the old import path, you +will have to add a `replace` directive to your `go.mod` file downgrading the +legacy import path to an older version. + +``` +replace github.com/uber-go/atomic => github.com/uber-go/atomic v1.4.0 +``` + +You can do so automatically by running the following command. + +```shell +$ go mod edit -replace github.com/uber-go/atomic=github.com/uber-go/atomic@v1.4.0 +``` + +## Usage + +The standard library's `sync/atomic` is powerful, but it's easy to forget which +variables must be accessed atomically. `go.uber.org/atomic` preserves all the +functionality of the standard library, but wraps the primitive types to +provide a safer, more convenient API. + +```go +var atom atomic.Uint32 +atom.Store(42) +atom.Sub(2) +atom.CAS(40, 11) +``` + +See the [documentation][doc] for a complete API specification. + +## Development Status + +Stable. + +--- + +Released under the [MIT License](LICENSE.txt). + +[doc-img]: https://godoc.org/github.com/uber-go/atomic?status.svg +[doc]: https://godoc.org/go.uber.org/atomic +[ci-img]: https://github.com/uber-go/atomic/actions/workflows/go.yml/badge.svg +[ci]: https://github.com/uber-go/atomic/actions/workflows/go.yml +[cov-img]: https://codecov.io/gh/uber-go/atomic/branch/master/graph/badge.svg +[cov]: https://codecov.io/gh/uber-go/atomic +[reportcard-img]: https://goreportcard.com/badge/go.uber.org/atomic +[reportcard]: https://goreportcard.com/report/go.uber.org/atomic diff --git a/tools/vendor/go.uber.org/atomic/bool.go b/tools/vendor/go.uber.org/atomic/bool.go new file mode 100644 index 00000000..209df7bb --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/bool.go @@ -0,0 +1,81 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" +) + +// Bool is an atomic type-safe wrapper for bool values. +type Bool struct { + _ nocmp // disallow non-atomic comparison + + v Uint32 +} + +var _zeroBool bool + +// NewBool creates a new Bool. +func NewBool(val bool) *Bool { + x := &Bool{} + if val != _zeroBool { + x.Store(val) + } + return x +} + +// Load atomically loads the wrapped bool. +func (x *Bool) Load() bool { + return truthy(x.v.Load()) +} + +// Store atomically stores the passed bool. +func (x *Bool) Store(val bool) { + x.v.Store(boolToInt(val)) +} + +// CAS is an atomic compare-and-swap for bool values. +func (x *Bool) CAS(old, new bool) (swapped bool) { + return x.v.CAS(boolToInt(old), boolToInt(new)) +} + +// Swap atomically stores the given bool and returns the old +// value. +func (x *Bool) Swap(val bool) (old bool) { + return truthy(x.v.Swap(boolToInt(val))) +} + +// MarshalJSON encodes the wrapped bool into JSON. +func (x *Bool) MarshalJSON() ([]byte, error) { + return json.Marshal(x.Load()) +} + +// UnmarshalJSON decodes a bool from JSON. +func (x *Bool) UnmarshalJSON(b []byte) error { + var v bool + if err := json.Unmarshal(b, &v); err != nil { + return err + } + x.Store(v) + return nil +} diff --git a/tools/vendor/go.uber.org/atomic/bool_ext.go b/tools/vendor/go.uber.org/atomic/bool_ext.go new file mode 100644 index 00000000..a2e60e98 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/bool_ext.go @@ -0,0 +1,53 @@ +// Copyright (c) 2020 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 atomic + +import ( + "strconv" +) + +//go:generate bin/gen-atomicwrapper -name=Bool -type=bool -wrapped=Uint32 -pack=boolToInt -unpack=truthy -cas -swap -json -file=bool.go + +func truthy(n uint32) bool { + return n == 1 +} + +func boolToInt(b bool) uint32 { + if b { + return 1 + } + return 0 +} + +// Toggle atomically negates the Boolean and returns the previous value. +func (b *Bool) Toggle() (old bool) { + for { + old := b.Load() + if b.CAS(old, !old) { + return old + } + } +} + +// String encodes the wrapped value as a string. +func (b *Bool) String() string { + return strconv.FormatBool(b.Load()) +} diff --git a/tools/vendor/go.uber.org/atomic/doc.go b/tools/vendor/go.uber.org/atomic/doc.go new file mode 100644 index 00000000..ae7390ee --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/doc.go @@ -0,0 +1,23 @@ +// Copyright (c) 2020 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 atomic provides simple wrappers around numerics to enforce atomic +// access. +package atomic diff --git a/tools/vendor/go.uber.org/atomic/duration.go b/tools/vendor/go.uber.org/atomic/duration.go new file mode 100644 index 00000000..207594f5 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/duration.go @@ -0,0 +1,82 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" + "time" +) + +// Duration is an atomic type-safe wrapper for time.Duration values. +type Duration struct { + _ nocmp // disallow non-atomic comparison + + v Int64 +} + +var _zeroDuration time.Duration + +// NewDuration creates a new Duration. +func NewDuration(val time.Duration) *Duration { + x := &Duration{} + if val != _zeroDuration { + x.Store(val) + } + return x +} + +// Load atomically loads the wrapped time.Duration. +func (x *Duration) Load() time.Duration { + return time.Duration(x.v.Load()) +} + +// Store atomically stores the passed time.Duration. +func (x *Duration) Store(val time.Duration) { + x.v.Store(int64(val)) +} + +// CAS is an atomic compare-and-swap for time.Duration values. +func (x *Duration) CAS(old, new time.Duration) (swapped bool) { + return x.v.CAS(int64(old), int64(new)) +} + +// Swap atomically stores the given time.Duration and returns the old +// value. +func (x *Duration) Swap(val time.Duration) (old time.Duration) { + return time.Duration(x.v.Swap(int64(val))) +} + +// MarshalJSON encodes the wrapped time.Duration into JSON. +func (x *Duration) MarshalJSON() ([]byte, error) { + return json.Marshal(x.Load()) +} + +// UnmarshalJSON decodes a time.Duration from JSON. +func (x *Duration) UnmarshalJSON(b []byte) error { + var v time.Duration + if err := json.Unmarshal(b, &v); err != nil { + return err + } + x.Store(v) + return nil +} diff --git a/tools/vendor/go.uber.org/atomic/duration_ext.go b/tools/vendor/go.uber.org/atomic/duration_ext.go new file mode 100644 index 00000000..4c18b0a9 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/duration_ext.go @@ -0,0 +1,40 @@ +// Copyright (c) 2020 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 atomic + +import "time" + +//go:generate bin/gen-atomicwrapper -name=Duration -type=time.Duration -wrapped=Int64 -pack=int64 -unpack=time.Duration -cas -swap -json -imports time -file=duration.go + +// Add atomically adds to the wrapped time.Duration and returns the new value. +func (d *Duration) Add(delta time.Duration) time.Duration { + return time.Duration(d.v.Add(int64(delta))) +} + +// Sub atomically subtracts from the wrapped time.Duration and returns the new value. +func (d *Duration) Sub(delta time.Duration) time.Duration { + return time.Duration(d.v.Sub(int64(delta))) +} + +// String encodes the wrapped value as a string. +func (d *Duration) String() string { + return d.Load().String() +} diff --git a/tools/vendor/go.uber.org/atomic/error.go b/tools/vendor/go.uber.org/atomic/error.go new file mode 100644 index 00000000..3be19c35 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/error.go @@ -0,0 +1,51 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020-2021 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 atomic + +// Error is an atomic type-safe wrapper for error values. +type Error struct { + _ nocmp // disallow non-atomic comparison + + v Value +} + +var _zeroError error + +// NewError creates a new Error. +func NewError(val error) *Error { + x := &Error{} + if val != _zeroError { + x.Store(val) + } + return x +} + +// Load atomically loads the wrapped error. +func (x *Error) Load() error { + return unpackError(x.v.Load()) +} + +// Store atomically stores the passed error. +func (x *Error) Store(val error) { + x.v.Store(packError(val)) +} diff --git a/tools/vendor/go.uber.org/atomic/error_ext.go b/tools/vendor/go.uber.org/atomic/error_ext.go new file mode 100644 index 00000000..ffe0be21 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/error_ext.go @@ -0,0 +1,39 @@ +// Copyright (c) 2020 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 atomic + +// atomic.Value panics on nil inputs, or if the underlying type changes. +// Stabilize by always storing a custom struct that we control. + +//go:generate bin/gen-atomicwrapper -name=Error -type=error -wrapped=Value -pack=packError -unpack=unpackError -file=error.go + +type packedError struct{ Value error } + +func packError(v error) interface{} { + return packedError{v} +} + +func unpackError(v interface{}) error { + if err, ok := v.(packedError); ok { + return err.Value + } + return nil +} diff --git a/tools/vendor/go.uber.org/atomic/float64.go b/tools/vendor/go.uber.org/atomic/float64.go new file mode 100644 index 00000000..8a136718 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/float64.go @@ -0,0 +1,77 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" + "math" +) + +// Float64 is an atomic type-safe wrapper for float64 values. +type Float64 struct { + _ nocmp // disallow non-atomic comparison + + v Uint64 +} + +var _zeroFloat64 float64 + +// NewFloat64 creates a new Float64. +func NewFloat64(val float64) *Float64 { + x := &Float64{} + if val != _zeroFloat64 { + x.Store(val) + } + return x +} + +// Load atomically loads the wrapped float64. +func (x *Float64) Load() float64 { + return math.Float64frombits(x.v.Load()) +} + +// Store atomically stores the passed float64. +func (x *Float64) Store(val float64) { + x.v.Store(math.Float64bits(val)) +} + +// Swap atomically stores the given float64 and returns the old +// value. +func (x *Float64) Swap(val float64) (old float64) { + return math.Float64frombits(x.v.Swap(math.Float64bits(val))) +} + +// MarshalJSON encodes the wrapped float64 into JSON. +func (x *Float64) MarshalJSON() ([]byte, error) { + return json.Marshal(x.Load()) +} + +// UnmarshalJSON decodes a float64 from JSON. +func (x *Float64) UnmarshalJSON(b []byte) error { + var v float64 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + x.Store(v) + return nil +} diff --git a/tools/vendor/go.uber.org/atomic/float64_ext.go b/tools/vendor/go.uber.org/atomic/float64_ext.go new file mode 100644 index 00000000..df36b010 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/float64_ext.go @@ -0,0 +1,69 @@ +// Copyright (c) 2020 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 atomic + +import ( + "math" + "strconv" +) + +//go:generate bin/gen-atomicwrapper -name=Float64 -type=float64 -wrapped=Uint64 -pack=math.Float64bits -unpack=math.Float64frombits -swap -json -imports math -file=float64.go + +// Add atomically adds to the wrapped float64 and returns the new value. +func (f *Float64) Add(delta float64) float64 { + for { + old := f.Load() + new := old + delta + if f.CAS(old, new) { + return new + } + } +} + +// Sub atomically subtracts from the wrapped float64 and returns the new value. +func (f *Float64) Sub(delta float64) float64 { + return f.Add(-delta) +} + +// CAS is an atomic compare-and-swap for float64 values. +// +// Note: CAS handles NaN incorrectly. NaN != NaN using Go's inbuilt operators +// but CAS allows a stored NaN to compare equal to a passed in NaN. +// This avoids typical CAS loops from blocking forever, e.g., +// +// for { +// old := atom.Load() +// new = f(old) +// if atom.CAS(old, new) { +// break +// } +// } +// +// If CAS did not match NaN to match, then the above would loop forever. +func (f *Float64) CAS(old, new float64) (swapped bool) { + return f.v.CAS(math.Float64bits(old), math.Float64bits(new)) +} + +// String encodes the wrapped value as a string. +func (f *Float64) String() string { + // 'g' is the behavior for floats with %v. + return strconv.FormatFloat(f.Load(), 'g', -1, 64) +} diff --git a/tools/vendor/go.uber.org/atomic/gen.go b/tools/vendor/go.uber.org/atomic/gen.go new file mode 100644 index 00000000..1e9ef4f8 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/gen.go @@ -0,0 +1,27 @@ +// Copyright (c) 2020 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 atomic + +//go:generate bin/gen-atomicint -name=Int32 -wrapped=int32 -file=int32.go +//go:generate bin/gen-atomicint -name=Int64 -wrapped=int64 -file=int64.go +//go:generate bin/gen-atomicint -name=Uint32 -wrapped=uint32 -unsigned -file=uint32.go +//go:generate bin/gen-atomicint -name=Uint64 -wrapped=uint64 -unsigned -file=uint64.go +//go:generate bin/gen-atomicint -name=Uintptr -wrapped=uintptr -unsigned -file=uintptr.go diff --git a/tools/vendor/go.uber.org/atomic/int32.go b/tools/vendor/go.uber.org/atomic/int32.go new file mode 100644 index 00000000..640ea36a --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/int32.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Int32 is an atomic wrapper around int32. +type Int32 struct { + _ nocmp // disallow non-atomic comparison + + v int32 +} + +// NewInt32 creates a new Int32. +func NewInt32(val int32) *Int32 { + return &Int32{v: val} +} + +// Load atomically loads the wrapped value. +func (i *Int32) Load() int32 { + return atomic.LoadInt32(&i.v) +} + +// Add atomically adds to the wrapped int32 and returns the new value. +func (i *Int32) Add(delta int32) int32 { + return atomic.AddInt32(&i.v, delta) +} + +// Sub atomically subtracts from the wrapped int32 and returns the new value. +func (i *Int32) Sub(delta int32) int32 { + return atomic.AddInt32(&i.v, -delta) +} + +// Inc atomically increments the wrapped int32 and returns the new value. +func (i *Int32) Inc() int32 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped int32 and returns the new value. +func (i *Int32) Dec() int32 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Int32) CAS(old, new int32) (swapped bool) { + return atomic.CompareAndSwapInt32(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Int32) Store(val int32) { + atomic.StoreInt32(&i.v, val) +} + +// Swap atomically swaps the wrapped int32 and returns the old value. +func (i *Int32) Swap(val int32) (old int32) { + return atomic.SwapInt32(&i.v, val) +} + +// MarshalJSON encodes the wrapped int32 into JSON. +func (i *Int32) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped int32. +func (i *Int32) UnmarshalJSON(b []byte) error { + var v int32 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Int32) String() string { + v := i.Load() + return strconv.FormatInt(int64(v), 10) +} diff --git a/tools/vendor/go.uber.org/atomic/int64.go b/tools/vendor/go.uber.org/atomic/int64.go new file mode 100644 index 00000000..9ab66b98 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/int64.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Int64 is an atomic wrapper around int64. +type Int64 struct { + _ nocmp // disallow non-atomic comparison + + v int64 +} + +// NewInt64 creates a new Int64. +func NewInt64(val int64) *Int64 { + return &Int64{v: val} +} + +// Load atomically loads the wrapped value. +func (i *Int64) Load() int64 { + return atomic.LoadInt64(&i.v) +} + +// Add atomically adds to the wrapped int64 and returns the new value. +func (i *Int64) Add(delta int64) int64 { + return atomic.AddInt64(&i.v, delta) +} + +// Sub atomically subtracts from the wrapped int64 and returns the new value. +func (i *Int64) Sub(delta int64) int64 { + return atomic.AddInt64(&i.v, -delta) +} + +// Inc atomically increments the wrapped int64 and returns the new value. +func (i *Int64) Inc() int64 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped int64 and returns the new value. +func (i *Int64) Dec() int64 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Int64) CAS(old, new int64) (swapped bool) { + return atomic.CompareAndSwapInt64(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Int64) Store(val int64) { + atomic.StoreInt64(&i.v, val) +} + +// Swap atomically swaps the wrapped int64 and returns the old value. +func (i *Int64) Swap(val int64) (old int64) { + return atomic.SwapInt64(&i.v, val) +} + +// MarshalJSON encodes the wrapped int64 into JSON. +func (i *Int64) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped int64. +func (i *Int64) UnmarshalJSON(b []byte) error { + var v int64 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Int64) String() string { + v := i.Load() + return strconv.FormatInt(int64(v), 10) +} diff --git a/tools/vendor/go.uber.org/atomic/nocmp.go b/tools/vendor/go.uber.org/atomic/nocmp.go new file mode 100644 index 00000000..a8201cb4 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/nocmp.go @@ -0,0 +1,35 @@ +// Copyright (c) 2020 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 atomic + +// nocmp is an uncomparable struct. Embed this inside another struct to make +// it uncomparable. +// +// type Foo struct { +// nocmp +// // ... +// } +// +// This DOES NOT: +// +// - Disallow shallow copies of structs +// - Disallow comparison of pointers to uncomparable structs +type nocmp [0]func() diff --git a/tools/vendor/go.uber.org/atomic/string.go b/tools/vendor/go.uber.org/atomic/string.go new file mode 100644 index 00000000..80df93d0 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/string.go @@ -0,0 +1,54 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020-2021 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 atomic + +// String is an atomic type-safe wrapper for string values. +type String struct { + _ nocmp // disallow non-atomic comparison + + v Value +} + +var _zeroString string + +// NewString creates a new String. +func NewString(val string) *String { + x := &String{} + if val != _zeroString { + x.Store(val) + } + return x +} + +// Load atomically loads the wrapped string. +func (x *String) Load() string { + if v := x.v.Load(); v != nil { + return v.(string) + } + return _zeroString +} + +// Store atomically stores the passed string. +func (x *String) Store(val string) { + x.v.Store(val) +} diff --git a/tools/vendor/go.uber.org/atomic/string_ext.go b/tools/vendor/go.uber.org/atomic/string_ext.go new file mode 100644 index 00000000..83d92eda --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/string_ext.go @@ -0,0 +1,45 @@ +// Copyright (c) 2020 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 atomic + +//go:generate bin/gen-atomicwrapper -name=String -type=string -wrapped=Value -file=string.go +// Note: No Swap as String wraps Value, which wraps the stdlib sync/atomic.Value which +// only supports Swap as of go1.17: https://github.com/golang/go/issues/39351 + +// String returns the wrapped value. +func (s *String) String() string { + return s.Load() +} + +// MarshalText encodes the wrapped string into a textual form. +// +// This makes it encodable as JSON, YAML, XML, and more. +func (s *String) MarshalText() ([]byte, error) { + return []byte(s.Load()), nil +} + +// UnmarshalText decodes text and replaces the wrapped string with it. +// +// This makes it decodable from JSON, YAML, XML, and more. +func (s *String) UnmarshalText(b []byte) error { + s.Store(string(b)) + return nil +} diff --git a/tools/vendor/go.uber.org/atomic/time.go b/tools/vendor/go.uber.org/atomic/time.go new file mode 100644 index 00000000..33460fc3 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/time.go @@ -0,0 +1,55 @@ +// @generated Code generated by gen-atomicwrapper. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "time" +) + +// Time is an atomic type-safe wrapper for time.Time values. +type Time struct { + _ nocmp // disallow non-atomic comparison + + v Value +} + +var _zeroTime time.Time + +// NewTime creates a new Time. +func NewTime(val time.Time) *Time { + x := &Time{} + if val != _zeroTime { + x.Store(val) + } + return x +} + +// Load atomically loads the wrapped time.Time. +func (x *Time) Load() time.Time { + return unpackTime(x.v.Load()) +} + +// Store atomically stores the passed time.Time. +func (x *Time) Store(val time.Time) { + x.v.Store(packTime(val)) +} diff --git a/tools/vendor/go.uber.org/atomic/time_ext.go b/tools/vendor/go.uber.org/atomic/time_ext.go new file mode 100644 index 00000000..1e3dc978 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/time_ext.go @@ -0,0 +1,36 @@ +// Copyright (c) 2021 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 atomic + +import "time" + +//go:generate bin/gen-atomicwrapper -name=Time -type=time.Time -wrapped=Value -pack=packTime -unpack=unpackTime -imports time -file=time.go + +func packTime(t time.Time) interface{} { + return t +} + +func unpackTime(v interface{}) time.Time { + if t, ok := v.(time.Time); ok { + return t + } + return time.Time{} +} diff --git a/tools/vendor/go.uber.org/atomic/uint32.go b/tools/vendor/go.uber.org/atomic/uint32.go new file mode 100644 index 00000000..7859a9cc --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/uint32.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Uint32 is an atomic wrapper around uint32. +type Uint32 struct { + _ nocmp // disallow non-atomic comparison + + v uint32 +} + +// NewUint32 creates a new Uint32. +func NewUint32(val uint32) *Uint32 { + return &Uint32{v: val} +} + +// Load atomically loads the wrapped value. +func (i *Uint32) Load() uint32 { + return atomic.LoadUint32(&i.v) +} + +// Add atomically adds to the wrapped uint32 and returns the new value. +func (i *Uint32) Add(delta uint32) uint32 { + return atomic.AddUint32(&i.v, delta) +} + +// Sub atomically subtracts from the wrapped uint32 and returns the new value. +func (i *Uint32) Sub(delta uint32) uint32 { + return atomic.AddUint32(&i.v, ^(delta - 1)) +} + +// Inc atomically increments the wrapped uint32 and returns the new value. +func (i *Uint32) Inc() uint32 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped uint32 and returns the new value. +func (i *Uint32) Dec() uint32 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Uint32) CAS(old, new uint32) (swapped bool) { + return atomic.CompareAndSwapUint32(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Uint32) Store(val uint32) { + atomic.StoreUint32(&i.v, val) +} + +// Swap atomically swaps the wrapped uint32 and returns the old value. +func (i *Uint32) Swap(val uint32) (old uint32) { + return atomic.SwapUint32(&i.v, val) +} + +// MarshalJSON encodes the wrapped uint32 into JSON. +func (i *Uint32) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped uint32. +func (i *Uint32) UnmarshalJSON(b []byte) error { + var v uint32 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Uint32) String() string { + v := i.Load() + return strconv.FormatUint(uint64(v), 10) +} diff --git a/tools/vendor/go.uber.org/atomic/uint64.go b/tools/vendor/go.uber.org/atomic/uint64.go new file mode 100644 index 00000000..2f2a7db6 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/uint64.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Uint64 is an atomic wrapper around uint64. +type Uint64 struct { + _ nocmp // disallow non-atomic comparison + + v uint64 +} + +// NewUint64 creates a new Uint64. +func NewUint64(val uint64) *Uint64 { + return &Uint64{v: val} +} + +// Load atomically loads the wrapped value. +func (i *Uint64) Load() uint64 { + return atomic.LoadUint64(&i.v) +} + +// Add atomically adds to the wrapped uint64 and returns the new value. +func (i *Uint64) Add(delta uint64) uint64 { + return atomic.AddUint64(&i.v, delta) +} + +// Sub atomically subtracts from the wrapped uint64 and returns the new value. +func (i *Uint64) Sub(delta uint64) uint64 { + return atomic.AddUint64(&i.v, ^(delta - 1)) +} + +// Inc atomically increments the wrapped uint64 and returns the new value. +func (i *Uint64) Inc() uint64 { + return i.Add(1) +} + +// Dec atomically decrements the wrapped uint64 and returns the new value. +func (i *Uint64) Dec() uint64 { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Uint64) CAS(old, new uint64) (swapped bool) { + return atomic.CompareAndSwapUint64(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Uint64) Store(val uint64) { + atomic.StoreUint64(&i.v, val) +} + +// Swap atomically swaps the wrapped uint64 and returns the old value. +func (i *Uint64) Swap(val uint64) (old uint64) { + return atomic.SwapUint64(&i.v, val) +} + +// MarshalJSON encodes the wrapped uint64 into JSON. +func (i *Uint64) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped uint64. +func (i *Uint64) UnmarshalJSON(b []byte) error { + var v uint64 + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Uint64) String() string { + v := i.Load() + return strconv.FormatUint(uint64(v), 10) +} diff --git a/tools/vendor/go.uber.org/atomic/uintptr.go b/tools/vendor/go.uber.org/atomic/uintptr.go new file mode 100644 index 00000000..ecf7a772 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/uintptr.go @@ -0,0 +1,102 @@ +// @generated Code generated by gen-atomicint. + +// Copyright (c) 2020-2021 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 atomic + +import ( + "encoding/json" + "strconv" + "sync/atomic" +) + +// Uintptr is an atomic wrapper around uintptr. +type Uintptr struct { + _ nocmp // disallow non-atomic comparison + + v uintptr +} + +// NewUintptr creates a new Uintptr. +func NewUintptr(val uintptr) *Uintptr { + return &Uintptr{v: val} +} + +// Load atomically loads the wrapped value. +func (i *Uintptr) Load() uintptr { + return atomic.LoadUintptr(&i.v) +} + +// Add atomically adds to the wrapped uintptr and returns the new value. +func (i *Uintptr) Add(delta uintptr) uintptr { + return atomic.AddUintptr(&i.v, delta) +} + +// Sub atomically subtracts from the wrapped uintptr and returns the new value. +func (i *Uintptr) Sub(delta uintptr) uintptr { + return atomic.AddUintptr(&i.v, ^(delta - 1)) +} + +// Inc atomically increments the wrapped uintptr and returns the new value. +func (i *Uintptr) Inc() uintptr { + return i.Add(1) +} + +// Dec atomically decrements the wrapped uintptr and returns the new value. +func (i *Uintptr) Dec() uintptr { + return i.Sub(1) +} + +// CAS is an atomic compare-and-swap. +func (i *Uintptr) CAS(old, new uintptr) (swapped bool) { + return atomic.CompareAndSwapUintptr(&i.v, old, new) +} + +// Store atomically stores the passed value. +func (i *Uintptr) Store(val uintptr) { + atomic.StoreUintptr(&i.v, val) +} + +// Swap atomically swaps the wrapped uintptr and returns the old value. +func (i *Uintptr) Swap(val uintptr) (old uintptr) { + return atomic.SwapUintptr(&i.v, val) +} + +// MarshalJSON encodes the wrapped uintptr into JSON. +func (i *Uintptr) MarshalJSON() ([]byte, error) { + return json.Marshal(i.Load()) +} + +// UnmarshalJSON decodes JSON into the wrapped uintptr. +func (i *Uintptr) UnmarshalJSON(b []byte) error { + var v uintptr + if err := json.Unmarshal(b, &v); err != nil { + return err + } + i.Store(v) + return nil +} + +// String encodes the wrapped value as a string. +func (i *Uintptr) String() string { + v := i.Load() + return strconv.FormatUint(uint64(v), 10) +} diff --git a/tools/vendor/go.uber.org/atomic/unsafe_pointer.go b/tools/vendor/go.uber.org/atomic/unsafe_pointer.go new file mode 100644 index 00000000..169f793d --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/unsafe_pointer.go @@ -0,0 +1,58 @@ +// Copyright (c) 2021 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 atomic + +import ( + "sync/atomic" + "unsafe" +) + +// UnsafePointer is an atomic wrapper around unsafe.Pointer. +type UnsafePointer struct { + _ nocmp // disallow non-atomic comparison + + v unsafe.Pointer +} + +// NewUnsafePointer creates a new UnsafePointer. +func NewUnsafePointer(val unsafe.Pointer) *UnsafePointer { + return &UnsafePointer{v: val} +} + +// Load atomically loads the wrapped value. +func (p *UnsafePointer) Load() unsafe.Pointer { + return atomic.LoadPointer(&p.v) +} + +// Store atomically stores the passed value. +func (p *UnsafePointer) Store(val unsafe.Pointer) { + atomic.StorePointer(&p.v, val) +} + +// Swap atomically swaps the wrapped unsafe.Pointer and returns the old value. +func (p *UnsafePointer) Swap(val unsafe.Pointer) (old unsafe.Pointer) { + return atomic.SwapPointer(&p.v, val) +} + +// CAS is an atomic compare-and-swap. +func (p *UnsafePointer) CAS(old, new unsafe.Pointer) (swapped bool) { + return atomic.CompareAndSwapPointer(&p.v, old, new) +} diff --git a/tools/vendor/go.uber.org/atomic/value.go b/tools/vendor/go.uber.org/atomic/value.go new file mode 100644 index 00000000..671f3a38 --- /dev/null +++ b/tools/vendor/go.uber.org/atomic/value.go @@ -0,0 +1,31 @@ +// Copyright (c) 2020 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 atomic + +import "sync/atomic" + +// Value shadows the type of the same name from sync/atomic +// https://godoc.org/sync/atomic#Value +type Value struct { + atomic.Value + + _ nocmp // disallow non-atomic comparison +} diff --git a/tools/vendor/go.uber.org/multierr/.codecov.yml b/tools/vendor/go.uber.org/multierr/.codecov.yml new file mode 100644 index 00000000..6d4d1be7 --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/.codecov.yml @@ -0,0 +1,15 @@ +coverage: + range: 80..100 + round: down + precision: 2 + + status: + project: # measuring the overall project coverage + default: # context, you can create multiple ones with custom titles + enabled: yes # must be yes|true to enable this status + target: 100 # specify the target coverage for each commit status + # option: "auto" (must increase from parent commit or pull request base) + # option: "X%" a static target percentage to hit + if_not_found: success # if parent is not found report status as success, error, or failure + if_ci_failed: error # if ci fails report status as success, error, or failure + diff --git a/tools/vendor/go.uber.org/multierr/.gitignore b/tools/vendor/go.uber.org/multierr/.gitignore new file mode 100644 index 00000000..b9a05e3d --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/.gitignore @@ -0,0 +1,4 @@ +/vendor +cover.html +cover.out +/bin diff --git a/tools/vendor/go.uber.org/multierr/CHANGELOG.md b/tools/vendor/go.uber.org/multierr/CHANGELOG.md new file mode 100644 index 00000000..3ba05276 --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/CHANGELOG.md @@ -0,0 +1,72 @@ +Releases +======== + +v1.8.0 (2022-02-28) +=================== + +- `Combine`: perform zero allocations when there are no errors. + + +v1.7.0 (2021-05-06) +=================== + +- Add `AppendInvoke` to append into errors from `defer` blocks. + + +v1.6.0 (2020-09-14) +=================== + +- Actually drop library dependency on development-time tooling. + + +v1.5.0 (2020-02-24) +=================== + +- Drop library dependency on development-time tooling. + + +v1.4.0 (2019-11-04) +=================== + +- Add `AppendInto` function to more ergonomically build errors inside a + loop. + + +v1.3.0 (2019-10-29) +=================== + +- Switch to Go modules. + + +v1.2.0 (2019-09-26) +=================== + +- Support extracting and matching against wrapped errors with `errors.As` + and `errors.Is`. + + +v1.1.0 (2017-06-30) +=================== + +- Added an `Errors(error) []error` function to extract the underlying list of + errors for a multierr error. + + +v1.0.0 (2017-05-31) +=================== + +No changes since v0.2.0. This release is committing to making no breaking +changes to the current API in the 1.X series. + + +v0.2.0 (2017-04-11) +=================== + +- Repeatedly appending to the same error is now faster due to fewer + allocations. + + +v0.1.0 (2017-31-03) +=================== + +- Initial release diff --git a/tools/vendor/go.uber.org/multierr/LICENSE.txt b/tools/vendor/go.uber.org/multierr/LICENSE.txt new file mode 100644 index 00000000..413e30f7 --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2017-2021 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. diff --git a/tools/vendor/go.uber.org/multierr/Makefile b/tools/vendor/go.uber.org/multierr/Makefile new file mode 100644 index 00000000..dcb6fe72 --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/Makefile @@ -0,0 +1,38 @@ +# Directory to put `go install`ed binaries in. +export GOBIN ?= $(shell pwd)/bin + +GO_FILES := $(shell \ + find . '(' -path '*/.*' -o -path './vendor' ')' -prune \ + -o -name '*.go' -print | cut -b3-) + +.PHONY: build +build: + go build ./... + +.PHONY: test +test: + go test -race ./... + +.PHONY: gofmt +gofmt: + $(eval FMT_LOG := $(shell mktemp -t gofmt.XXXXX)) + @gofmt -e -s -l $(GO_FILES) > $(FMT_LOG) || true + @[ ! -s "$(FMT_LOG)" ] || (echo "gofmt failed:" | cat - $(FMT_LOG) && false) + +.PHONY: golint +golint: + @cd tools && go install golang.org/x/lint/golint + @$(GOBIN)/golint ./... + +.PHONY: staticcheck +staticcheck: + @cd tools && go install honnef.co/go/tools/cmd/staticcheck + @$(GOBIN)/staticcheck ./... + +.PHONY: lint +lint: gofmt golint staticcheck + +.PHONY: cover +cover: + go test -race -coverprofile=cover.out -coverpkg=./... -v ./... + go tool cover -html=cover.out -o cover.html diff --git a/tools/vendor/go.uber.org/multierr/README.md b/tools/vendor/go.uber.org/multierr/README.md new file mode 100644 index 00000000..70aacecd --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/README.md @@ -0,0 +1,23 @@ +# multierr [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] + +`multierr` allows combining one or more Go `error`s together. + +## Installation + + go get -u go.uber.org/multierr + +## Status + +Stable: No breaking changes will be made before 2.0. + +------------------------------------------------------------------------------- + +Released under the [MIT License]. + +[MIT License]: LICENSE.txt +[doc-img]: https://pkg.go.dev/badge/go.uber.org/multierr +[doc]: https://pkg.go.dev/go.uber.org/multierr +[ci-img]: https://github.com/uber-go/multierr/actions/workflows/go.yml/badge.svg +[cov-img]: https://codecov.io/gh/uber-go/multierr/branch/master/graph/badge.svg +[ci]: https://github.com/uber-go/multierr/actions/workflows/go.yml +[cov]: https://codecov.io/gh/uber-go/multierr diff --git a/tools/vendor/go.uber.org/multierr/error.go b/tools/vendor/go.uber.org/multierr/error.go new file mode 100644 index 00000000..f45af149 --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/error.go @@ -0,0 +1,652 @@ +// Copyright (c) 2017-2021 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 multierr allows combining one or more errors together. +// +// Overview +// +// Errors can be combined with the use of the Combine function. +// +// multierr.Combine( +// reader.Close(), +// writer.Close(), +// conn.Close(), +// ) +// +// If only two errors are being combined, the Append function may be used +// instead. +// +// err = multierr.Append(reader.Close(), writer.Close()) +// +// The underlying list of errors for a returned error object may be retrieved +// with the Errors function. +// +// errors := multierr.Errors(err) +// if len(errors) > 0 { +// fmt.Println("The following errors occurred:", errors) +// } +// +// Appending from a loop +// +// You sometimes need to append into an error from a loop. +// +// var err error +// for _, item := range items { +// err = multierr.Append(err, process(item)) +// } +// +// Cases like this may require knowledge of whether an individual instance +// failed. This usually requires introduction of a new variable. +// +// var err error +// for _, item := range items { +// if perr := process(item); perr != nil { +// log.Warn("skipping item", item) +// err = multierr.Append(err, perr) +// } +// } +// +// multierr includes AppendInto to simplify cases like this. +// +// var err error +// for _, item := range items { +// if multierr.AppendInto(&err, process(item)) { +// log.Warn("skipping item", item) +// } +// } +// +// This will append the error into the err variable, and return true if that +// individual error was non-nil. +// +// See AppendInto for more information. +// +// Deferred Functions +// +// Go makes it possible to modify the return value of a function in a defer +// block if the function was using named returns. This makes it possible to +// record resource cleanup failures from deferred blocks. +// +// func sendRequest(req Request) (err error) { +// conn, err := openConnection() +// if err != nil { +// return err +// } +// defer func() { +// err = multierr.Append(err, conn.Close()) +// }() +// // ... +// } +// +// multierr provides the Invoker type and AppendInvoke function to make cases +// like the above simpler and obviate the need for a closure. The following is +// roughly equivalent to the example above. +// +// func sendRequest(req Request) (err error) { +// conn, err := openConnection() +// if err != nil { +// return err +// } +// defer multierr.AppendInvoke(&err, multierr.Close(conn)) +// // ... +// } +// +// See AppendInvoke and Invoker for more information. +// +// Advanced Usage +// +// Errors returned by Combine and Append MAY implement the following +// interface. +// +// type errorGroup interface { +// // Returns a slice containing the underlying list of errors. +// // +// // This slice MUST NOT be modified by the caller. +// Errors() []error +// } +// +// Note that if you need access to list of errors behind a multierr error, you +// should prefer using the Errors function. That said, if you need cheap +// read-only access to the underlying errors slice, you can attempt to cast +// the error to this interface. You MUST handle the failure case gracefully +// because errors returned by Combine and Append are not guaranteed to +// implement this interface. +// +// var errors []error +// group, ok := err.(errorGroup) +// if ok { +// errors = group.Errors() +// } else { +// errors = []error{err} +// } +package multierr // import "go.uber.org/multierr" + +import ( + "bytes" + "errors" + "fmt" + "io" + "strings" + "sync" + + "go.uber.org/atomic" +) + +var ( + // Separator for single-line error messages. + _singlelineSeparator = []byte("; ") + + // Prefix for multi-line messages + _multilinePrefix = []byte("the following errors occurred:") + + // Prefix for the first and following lines of an item in a list of + // multi-line error messages. + // + // For example, if a single item is: + // + // foo + // bar + // + // It will become, + // + // - foo + // bar + _multilineSeparator = []byte("\n - ") + _multilineIndent = []byte(" ") +) + +// _bufferPool is a pool of bytes.Buffers. +var _bufferPool = sync.Pool{ + New: func() interface{} { + return &bytes.Buffer{} + }, +} + +type errorGroup interface { + Errors() []error +} + +// Errors returns a slice containing zero or more errors that the supplied +// error is composed of. If the error is nil, a nil slice is returned. +// +// err := multierr.Append(r.Close(), w.Close()) +// errors := multierr.Errors(err) +// +// If the error is not composed of other errors, the returned slice contains +// just the error that was passed in. +// +// Callers of this function are free to modify the returned slice. +func Errors(err error) []error { + if err == nil { + return nil + } + + // Note that we're casting to multiError, not errorGroup. Our contract is + // that returned errors MAY implement errorGroup. Errors, however, only + // has special behavior for multierr-specific error objects. + // + // This behavior can be expanded in the future but I think it's prudent to + // start with as little as possible in terms of contract and possibility + // of misuse. + eg, ok := err.(*multiError) + if !ok { + return []error{err} + } + + errors := eg.Errors() + result := make([]error, len(errors)) + copy(result, errors) + return result +} + +// multiError is an error that holds one or more errors. +// +// An instance of this is guaranteed to be non-empty and flattened. That is, +// none of the errors inside multiError are other multiErrors. +// +// multiError formats to a semi-colon delimited list of error messages with +// %v and with a more readable multi-line format with %+v. +type multiError struct { + copyNeeded atomic.Bool + errors []error +} + +var _ errorGroup = (*multiError)(nil) + +// Errors returns the list of underlying errors. +// +// This slice MUST NOT be modified. +func (merr *multiError) Errors() []error { + if merr == nil { + return nil + } + return merr.errors +} + +// As attempts to find the first error in the error list that matches the type +// of the value that target points to. +// +// This function allows errors.As to traverse the values stored on the +// multierr error. +func (merr *multiError) As(target interface{}) bool { + for _, err := range merr.Errors() { + if errors.As(err, target) { + return true + } + } + return false +} + +// Is attempts to match the provided error against errors in the error list. +// +// This function allows errors.Is to traverse the values stored on the +// multierr error. +func (merr *multiError) Is(target error) bool { + for _, err := range merr.Errors() { + if errors.Is(err, target) { + return true + } + } + return false +} + +func (merr *multiError) Error() string { + if merr == nil { + return "" + } + + buff := _bufferPool.Get().(*bytes.Buffer) + buff.Reset() + + merr.writeSingleline(buff) + + result := buff.String() + _bufferPool.Put(buff) + return result +} + +func (merr *multiError) Format(f fmt.State, c rune) { + if c == 'v' && f.Flag('+') { + merr.writeMultiline(f) + } else { + merr.writeSingleline(f) + } +} + +func (merr *multiError) writeSingleline(w io.Writer) { + first := true + for _, item := range merr.errors { + if first { + first = false + } else { + w.Write(_singlelineSeparator) + } + io.WriteString(w, item.Error()) + } +} + +func (merr *multiError) writeMultiline(w io.Writer) { + w.Write(_multilinePrefix) + for _, item := range merr.errors { + w.Write(_multilineSeparator) + writePrefixLine(w, _multilineIndent, fmt.Sprintf("%+v", item)) + } +} + +// Writes s to the writer with the given prefix added before each line after +// the first. +func writePrefixLine(w io.Writer, prefix []byte, s string) { + first := true + for len(s) > 0 { + if first { + first = false + } else { + w.Write(prefix) + } + + idx := strings.IndexByte(s, '\n') + if idx < 0 { + idx = len(s) - 1 + } + + io.WriteString(w, s[:idx+1]) + s = s[idx+1:] + } +} + +type inspectResult struct { + // Number of top-level non-nil errors + Count int + + // Total number of errors including multiErrors + Capacity int + + // Index of the first non-nil error in the list. Value is meaningless if + // Count is zero. + FirstErrorIdx int + + // Whether the list contains at least one multiError + ContainsMultiError bool +} + +// Inspects the given slice of errors so that we can efficiently allocate +// space for it. +func inspect(errors []error) (res inspectResult) { + first := true + for i, err := range errors { + if err == nil { + continue + } + + res.Count++ + if first { + first = false + res.FirstErrorIdx = i + } + + if merr, ok := err.(*multiError); ok { + res.Capacity += len(merr.errors) + res.ContainsMultiError = true + } else { + res.Capacity++ + } + } + return +} + +// fromSlice converts the given list of errors into a single error. +func fromSlice(errors []error) error { + // Don't pay to inspect small slices. + switch len(errors) { + case 0: + return nil + case 1: + return errors[0] + } + + res := inspect(errors) + switch res.Count { + case 0: + return nil + case 1: + // only one non-nil entry + return errors[res.FirstErrorIdx] + case len(errors): + if !res.ContainsMultiError { + // Error list is flat. Make a copy of it + // Otherwise "errors" escapes to the heap + // unconditionally for all other cases. + // This lets us optimize for the "no errors" case. + out := make([]error, len(errors)) + copy(out, errors) + return &multiError{errors: out} + } + } + + nonNilErrs := make([]error, 0, res.Capacity) + for _, err := range errors[res.FirstErrorIdx:] { + if err == nil { + continue + } + + if nested, ok := err.(*multiError); ok { + nonNilErrs = append(nonNilErrs, nested.errors...) + } else { + nonNilErrs = append(nonNilErrs, err) + } + } + + return &multiError{errors: nonNilErrs} +} + +// Combine combines the passed errors into a single error. +// +// If zero arguments were passed or if all items are nil, a nil error is +// returned. +// +// Combine(nil, nil) // == nil +// +// If only a single error was passed, it is returned as-is. +// +// Combine(err) // == err +// +// Combine skips over nil arguments so this function may be used to combine +// together errors from operations that fail independently of each other. +// +// multierr.Combine( +// reader.Close(), +// writer.Close(), +// pipe.Close(), +// ) +// +// If any of the passed errors is a multierr error, it will be flattened along +// with the other errors. +// +// multierr.Combine(multierr.Combine(err1, err2), err3) +// // is the same as +// multierr.Combine(err1, err2, err3) +// +// The returned error formats into a readable multi-line error message if +// formatted with %+v. +// +// fmt.Sprintf("%+v", multierr.Combine(err1, err2)) +func Combine(errors ...error) error { + return fromSlice(errors) +} + +// Append appends the given errors together. Either value may be nil. +// +// This function is a specialization of Combine for the common case where +// there are only two errors. +// +// err = multierr.Append(reader.Close(), writer.Close()) +// +// The following pattern may also be used to record failure of deferred +// operations without losing information about the original error. +// +// func doSomething(..) (err error) { +// f := acquireResource() +// defer func() { +// err = multierr.Append(err, f.Close()) +// }() +func Append(left error, right error) error { + switch { + case left == nil: + return right + case right == nil: + return left + } + + if _, ok := right.(*multiError); !ok { + if l, ok := left.(*multiError); ok && !l.copyNeeded.Swap(true) { + // Common case where the error on the left is constantly being + // appended to. + errs := append(l.errors, right) + return &multiError{errors: errs} + } else if !ok { + // Both errors are single errors. + return &multiError{errors: []error{left, right}} + } + } + + // Either right or both, left and right, are multiErrors. Rely on usual + // expensive logic. + errors := [2]error{left, right} + return fromSlice(errors[0:]) +} + +// AppendInto appends an error into the destination of an error pointer and +// returns whether the error being appended was non-nil. +// +// var err error +// multierr.AppendInto(&err, r.Close()) +// multierr.AppendInto(&err, w.Close()) +// +// The above is equivalent to, +// +// err := multierr.Append(r.Close(), w.Close()) +// +// As AppendInto reports whether the provided error was non-nil, it may be +// used to build a multierr error in a loop more ergonomically. For example: +// +// var err error +// for line := range lines { +// var item Item +// if multierr.AppendInto(&err, parse(line, &item)) { +// continue +// } +// items = append(items, item) +// } +// +// Compare this with a version that relies solely on Append: +// +// var err error +// for line := range lines { +// var item Item +// if parseErr := parse(line, &item); parseErr != nil { +// err = multierr.Append(err, parseErr) +// continue +// } +// items = append(items, item) +// } +func AppendInto(into *error, err error) (errored bool) { + if into == nil { + // We panic if 'into' is nil. This is not documented above + // because suggesting that the pointer must be non-nil may + // confuse users into thinking that the error that it points + // to must be non-nil. + panic("misuse of multierr.AppendInto: into pointer must not be nil") + } + + if err == nil { + return false + } + *into = Append(*into, err) + return true +} + +// Invoker is an operation that may fail with an error. Use it with +// AppendInvoke to append the result of calling the function into an error. +// This allows you to conveniently defer capture of failing operations. +// +// See also, Close and Invoke. +type Invoker interface { + Invoke() error +} + +// Invoke wraps a function which may fail with an error to match the Invoker +// interface. Use it to supply functions matching this signature to +// AppendInvoke. +// +// For example, +// +// func processReader(r io.Reader) (err error) { +// scanner := bufio.NewScanner(r) +// defer multierr.AppendInvoke(&err, multierr.Invoke(scanner.Err)) +// for scanner.Scan() { +// // ... +// } +// // ... +// } +// +// In this example, the following line will construct the Invoker right away, +// but defer the invocation of scanner.Err() until the function returns. +// +// defer multierr.AppendInvoke(&err, multierr.Invoke(scanner.Err)) +type Invoke func() error + +// Invoke calls the supplied function and returns its result. +func (i Invoke) Invoke() error { return i() } + +// Close builds an Invoker that closes the provided io.Closer. Use it with +// AppendInvoke to close io.Closers and append their results into an error. +// +// For example, +// +// func processFile(path string) (err error) { +// f, err := os.Open(path) +// if err != nil { +// return err +// } +// defer multierr.AppendInvoke(&err, multierr.Close(f)) +// return processReader(f) +// } +// +// In this example, multierr.Close will construct the Invoker right away, but +// defer the invocation of f.Close until the function returns. +// +// defer multierr.AppendInvoke(&err, multierr.Close(f)) +func Close(closer io.Closer) Invoker { + return Invoke(closer.Close) +} + +// AppendInvoke appends the result of calling the given Invoker into the +// provided error pointer. Use it with named returns to safely defer +// invocation of fallible operations until a function returns, and capture the +// resulting errors. +// +// func doSomething(...) (err error) { +// // ... +// f, err := openFile(..) +// if err != nil { +// return err +// } +// +// // multierr will call f.Close() when this function returns and +// // if the operation fails, its append its error into the +// // returned error. +// defer multierr.AppendInvoke(&err, multierr.Close(f)) +// +// scanner := bufio.NewScanner(f) +// // Similarly, this scheduled scanner.Err to be called and +// // inspected when the function returns and append its error +// // into the returned error. +// defer multierr.AppendInvoke(&err, multierr.Invoke(scanner.Err)) +// +// // ... +// } +// +// Without defer, AppendInvoke behaves exactly like AppendInto. +// +// err := // ... +// multierr.AppendInvoke(&err, mutltierr.Invoke(foo)) +// +// // ...is roughly equivalent to... +// +// err := // ... +// multierr.AppendInto(&err, foo()) +// +// The advantage of the indirection introduced by Invoker is to make it easy +// to defer the invocation of a function. Without this indirection, the +// invoked function will be evaluated at the time of the defer block rather +// than when the function returns. +// +// // BAD: This is likely not what the caller intended. This will evaluate +// // foo() right away and append its result into the error when the +// // function returns. +// defer multierr.AppendInto(&err, foo()) +// +// // GOOD: This will defer invocation of foo unutil the function returns. +// defer multierr.AppendInvoke(&err, multierr.Invoke(foo)) +// +// multierr provides a few Invoker implementations out of the box for +// convenience. See Invoker for more information. +func AppendInvoke(into *error, invoker Invoker) { + AppendInto(into, invoker.Invoke()) +} diff --git a/tools/vendor/go.uber.org/multierr/glide.yaml b/tools/vendor/go.uber.org/multierr/glide.yaml new file mode 100644 index 00000000..6ef084ec --- /dev/null +++ b/tools/vendor/go.uber.org/multierr/glide.yaml @@ -0,0 +1,8 @@ +package: go.uber.org/multierr +import: +- package: go.uber.org/atomic + version: ^1 +testImport: +- package: github.com/stretchr/testify + subpackages: + - assert diff --git a/tools/vendor/go.uber.org/zap/.codecov.yml b/tools/vendor/go.uber.org/zap/.codecov.yml new file mode 100644 index 00000000..8e5ca7d3 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/.codecov.yml @@ -0,0 +1,17 @@ +coverage: + range: 80..100 + round: down + precision: 2 + + status: + project: # measuring the overall project coverage + default: # context, you can create multiple ones with custom titles + enabled: yes # must be yes|true to enable this status + target: 95% # specify the target coverage for each commit status + # option: "auto" (must increase from parent commit or pull request base) + # option: "X%" a static target percentage to hit + if_not_found: success # if parent is not found report status as success, error, or failure + if_ci_failed: error # if ci fails report status as success, error, or failure +ignore: + - internal/readme/readme.go + diff --git a/tools/vendor/go.uber.org/zap/.gitignore b/tools/vendor/go.uber.org/zap/.gitignore new file mode 100644 index 00000000..da9d9d00 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/.gitignore @@ -0,0 +1,32 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test +vendor + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof +*.pprof +*.out +*.log + +/bin +cover.out +cover.html diff --git a/tools/vendor/go.uber.org/zap/.readme.tmpl b/tools/vendor/go.uber.org/zap/.readme.tmpl new file mode 100644 index 00000000..92aa65d6 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/.readme.tmpl @@ -0,0 +1,109 @@ +# :zap: zap [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] + +Blazing fast, structured, leveled logging in Go. + +## Installation + +`go get -u go.uber.org/zap` + +Note that zap only supports the two most recent minor versions of Go. + +## Quick Start + +In contexts where performance is nice, but not critical, use the +`SugaredLogger`. It's 4-10x faster than other structured logging +packages and includes both structured and `printf`-style APIs. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() // flushes buffer, if any +sugar := logger.Sugar() +sugar.Infow("failed to fetch URL", + // Structured context as loosely typed key-value pairs. + "url", url, + "attempt", 3, + "backoff", time.Second, +) +sugar.Infof("Failed to fetch URL: %s", url) +``` + +When performance and type safety are critical, use the `Logger`. It's even +faster than the `SugaredLogger` and allocates far less, but it only supports +structured logging. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() +logger.Info("failed to fetch URL", + // Structured context as strongly typed Field values. + zap.String("url", url), + zap.Int("attempt", 3), + zap.Duration("backoff", time.Second), +) +``` + +See the [documentation][doc] and [FAQ](FAQ.md) for more details. + +## Performance + +For applications that log in the hot path, reflection-based serialization and +string formatting are prohibitively expensive — they're CPU-intensive +and make many small allocations. Put differently, using `encoding/json` and +`fmt.Fprintf` to log tons of `interface{}`s makes your application slow. + +Zap takes a different approach. It includes a reflection-free, zero-allocation +JSON encoder, and the base `Logger` strives to avoid serialization overhead +and allocations wherever possible. By building the high-level `SugaredLogger` +on that foundation, zap lets users *choose* when they need to count every +allocation and when they'd prefer a more familiar, loosely typed API. + +As measured by its own [benchmarking suite][], not only is zap more performant +than comparable structured logging packages — it's also faster than the +standard library. Like all benchmarks, take these with a grain of salt.[1](#footnote-versions) + +Log a message and 10 fields: + +{{.BenchmarkAddingFields}} + +Log a message with a logger that already has 10 fields of context: + +{{.BenchmarkAccumulatedContext}} + +Log a static string, without any context or `printf`-style templating: + +{{.BenchmarkWithoutFields}} + +## Development Status: Stable + +All APIs are finalized, and no breaking changes will be made in the 1.x series +of releases. Users of semver-aware dependency management systems should pin +zap to `^1`. + +## Contributing + +We encourage and support an active, healthy community of contributors — +including you! Details are in the [contribution guide](CONTRIBUTING.md) and +the [code of conduct](CODE_OF_CONDUCT.md). The zap maintainers keep an eye on +issues and pull requests, but you can also report any negative conduct to +oss-conduct@uber.com. That email list is a private, safe space; even the zap +maintainers don't have access, so don't hesitate to hold us to a high +standard. + +
+ +Released under the [MIT License](LICENSE.txt). + +1 In particular, keep in mind that we may be +benchmarking against slightly older versions of other packages. Versions are +pinned in the [benchmarks/go.mod][] file. [↩](#anchor-versions) + +[doc-img]: https://pkg.go.dev/badge/go.uber.org/zap +[doc]: https://pkg.go.dev/go.uber.org/zap +[ci-img]: https://github.com/uber-go/zap/actions/workflows/go.yml/badge.svg +[ci]: https://github.com/uber-go/zap/actions/workflows/go.yml +[cov-img]: https://codecov.io/gh/uber-go/zap/branch/master/graph/badge.svg +[cov]: https://codecov.io/gh/uber-go/zap +[benchmarking suite]: https://github.com/uber-go/zap/tree/master/benchmarks +[benchmarks/go.mod]: https://github.com/uber-go/zap/blob/master/benchmarks/go.mod + diff --git a/tools/vendor/go.uber.org/zap/CHANGELOG.md b/tools/vendor/go.uber.org/zap/CHANGELOG.md new file mode 100644 index 00000000..1793b08c --- /dev/null +++ b/tools/vendor/go.uber.org/zap/CHANGELOG.md @@ -0,0 +1,564 @@ +# Changelog +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## 1.21.0 (7 Feb 2022) + +Enhancements: +* [#1047][]: Add `zapcore.ParseLevel` to parse a `Level` from a string. +* [#1048][]: Add `zap.ParseAtomicLevel` to parse an `AtomicLevel` from a + string. + +Bugfixes: +* [#1058][]: Fix panic in JSON encoder when `EncodeLevel` is unset. + +Other changes: +* [#1052][]: Improve encoding performance when the `AddCaller` and + `AddStacktrace` options are used together. + +[#1047]: https://github.com/uber-go/zap/pull/1047 +[#1048]: https://github.com/uber-go/zap/pull/1048 +[#1052]: https://github.com/uber-go/zap/pull/1052 +[#1058]: https://github.com/uber-go/zap/pull/1058 + +Thanks to @aerosol and @Techassi for their contributions to this release. + +## 1.20.0 (4 Jan 2022) + +Enhancements: +* [#989][]: Add `EncoderConfig.SkipLineEnding` flag to disable adding newline + characters between log statements. +* [#1039][]: Add `EncoderConfig.NewReflectedEncoder` field to customize JSON + encoding of reflected log fields. + +Bugfixes: +* [#1011][]: Fix inaccurate precision when encoding complex64 as JSON. +* [#554][], [#1017][]: Close JSON namespaces opened in `MarshalLogObject` + methods when the methods return. +* [#1033][]: Avoid panicking in Sampler core if `thereafter` is zero. + +Other changes: +* [#1028][]: Drop support for Go < 1.15. + +[#554]: https://github.com/uber-go/zap/pull/554 +[#989]: https://github.com/uber-go/zap/pull/989 +[#1011]: https://github.com/uber-go/zap/pull/1011 +[#1017]: https://github.com/uber-go/zap/pull/1017 +[#1028]: https://github.com/uber-go/zap/pull/1028 +[#1033]: https://github.com/uber-go/zap/pull/1033 +[#1039]: https://github.com/uber-go/zap/pull/1039 + +Thanks to @psrajat, @lruggieri, @sammyrnycreal for their contributions to this release. + +## 1.19.1 (8 Sep 2021) + +Bugfixes: +* [#1001][]: JSON: Fix complex number encoding with negative imaginary part. Thanks to @hemantjadon. +* [#1003][]: JSON: Fix inaccurate precision when encoding float32. + +[#1001]: https://github.com/uber-go/zap/pull/1001 +[#1003]: https://github.com/uber-go/zap/pull/1003 + +## 1.19.0 (9 Aug 2021) + +Enhancements: +* [#975][]: Avoid panicking in Sampler core if the level is out of bounds. +* [#984][]: Reduce the size of BufferedWriteSyncer by aligning the fields + better. + +[#975]: https://github.com/uber-go/zap/pull/975 +[#984]: https://github.com/uber-go/zap/pull/984 + +Thanks to @lancoLiu and @thockin for their contributions to this release. + +## 1.18.1 (28 Jun 2021) + +Bugfixes: +* [#974][]: Fix nil dereference in logger constructed by `zap.NewNop`. + +[#974]: https://github.com/uber-go/zap/pull/974 + +## 1.18.0 (28 Jun 2021) + +Enhancements: +* [#961][]: Add `zapcore.BufferedWriteSyncer`, a new `WriteSyncer` that buffers + messages in-memory and flushes them periodically. +* [#971][]: Add `zapio.Writer` to use a Zap logger as an `io.Writer`. +* [#897][]: Add `zap.WithClock` option to control the source of time via the + new `zapcore.Clock` interface. +* [#949][]: Avoid panicking in `zap.SugaredLogger` when arguments of `*w` + methods don't match expectations. +* [#943][]: Add support for filtering by level or arbitrary matcher function to + `zaptest/observer`. +* [#691][]: Comply with `io.StringWriter` and `io.ByteWriter` in Zap's + `buffer.Buffer`. + +Thanks to @atrn0, @ernado, @heyanfu, @hnlq715, @zchee +for their contributions to this release. + +[#691]: https://github.com/uber-go/zap/pull/691 +[#897]: https://github.com/uber-go/zap/pull/897 +[#943]: https://github.com/uber-go/zap/pull/943 +[#949]: https://github.com/uber-go/zap/pull/949 +[#961]: https://github.com/uber-go/zap/pull/961 +[#971]: https://github.com/uber-go/zap/pull/971 + +## 1.17.0 (25 May 2021) + +Bugfixes: +* [#867][]: Encode `` for nil `error` instead of a panic. +* [#931][], [#936][]: Update minimum version constraints to address + vulnerabilities in dependencies. + +Enhancements: +* [#865][]: Improve alignment of fields of the Logger struct, reducing its + size from 96 to 80 bytes. +* [#881][]: Support `grpclog.LoggerV2` in zapgrpc. +* [#903][]: Support URL-encoded POST requests to the AtomicLevel HTTP handler + with the `application/x-www-form-urlencoded` content type. +* [#912][]: Support multi-field encoding with `zap.Inline`. +* [#913][]: Speed up SugaredLogger for calls with a single string. +* [#928][]: Add support for filtering by field name to `zaptest/observer`. + +Thanks to @ash2k, @FMLS, @jimmystewpot, @Oncilla, @tsoslow, @tylitianrui, @withshubh, and @wziww for their contributions to this release. + +## 1.16.0 (1 Sep 2020) + +Bugfixes: +* [#828][]: Fix missing newline in IncreaseLevel error messages. +* [#835][]: Fix panic in JSON encoder when encoding times or durations + without specifying a time or duration encoder. +* [#843][]: Honor CallerSkip when taking stack traces. +* [#862][]: Fix the default file permissions to use `0666` and rely on the umask instead. +* [#854][]: Encode `` for nil `Stringer` instead of a panic error log. + +Enhancements: +* [#629][]: Added `zapcore.TimeEncoderOfLayout` to easily create time encoders + for custom layouts. +* [#697][]: Added support for a configurable delimiter in the console encoder. +* [#852][]: Optimize console encoder by pooling the underlying JSON encoder. +* [#844][]: Add ability to include the calling function as part of logs. +* [#843][]: Add `StackSkip` for including truncated stacks as a field. +* [#861][]: Add options to customize Fatal behaviour for better testability. + +Thanks to @SteelPhase, @tmshn, @lixingwang, @wyxloading, @moul, @segevfiner, @andy-retailnext and @jcorbin for their contributions to this release. + +## 1.15.0 (23 Apr 2020) + +Bugfixes: +* [#804][]: Fix handling of `Time` values out of `UnixNano` range. +* [#812][]: Fix `IncreaseLevel` being reset after a call to `With`. + +Enhancements: +* [#806][]: Add `WithCaller` option to supersede the `AddCaller` option. This + allows disabling annotation of log entries with caller information if + previously enabled with `AddCaller`. +* [#813][]: Deprecate `NewSampler` constructor in favor of + `NewSamplerWithOptions` which supports a `SamplerHook` option. This option + adds support for monitoring sampling decisions through a hook. + +Thanks to @danielbprice for their contributions to this release. + +## 1.14.1 (14 Mar 2020) + +Bugfixes: +* [#791][]: Fix panic on attempting to build a logger with an invalid Config. +* [#795][]: Vendoring Zap with `go mod vendor` no longer includes Zap's + development-time dependencies. +* [#799][]: Fix issue introduced in 1.14.0 that caused invalid JSON output to + be generated for arrays of `time.Time` objects when using string-based time + formats. + +Thanks to @YashishDua for their contributions to this release. + +## 1.14.0 (20 Feb 2020) + +Enhancements: +* [#771][]: Optimize calls for disabled log levels. +* [#773][]: Add millisecond duration encoder. +* [#775][]: Add option to increase the level of a logger. +* [#786][]: Optimize time formatters using `Time.AppendFormat` where possible. + +Thanks to @caibirdme for their contributions to this release. + +## 1.13.0 (13 Nov 2019) + +Enhancements: +* [#758][]: Add `Intp`, `Stringp`, and other similar `*p` field constructors + to log pointers to primitives with support for `nil` values. + +Thanks to @jbizzle for their contributions to this release. + +## 1.12.0 (29 Oct 2019) + +Enhancements: +* [#751][]: Migrate to Go modules. + +## 1.11.0 (21 Oct 2019) + +Enhancements: +* [#725][]: Add `zapcore.OmitKey` to omit keys in an `EncoderConfig`. +* [#736][]: Add `RFC3339` and `RFC3339Nano` time encoders. + +Thanks to @juicemia, @uhthomas for their contributions to this release. + +## 1.10.0 (29 Apr 2019) + +Bugfixes: +* [#657][]: Fix `MapObjectEncoder.AppendByteString` not adding value as a + string. +* [#706][]: Fix incorrect call depth to determine caller in Go 1.12. + +Enhancements: +* [#610][]: Add `zaptest.WrapOptions` to wrap `zap.Option` for creating test + loggers. +* [#675][]: Don't panic when encoding a String field. +* [#704][]: Disable HTML escaping for JSON objects encoded using the + reflect-based encoder. + +Thanks to @iaroslav-ciupin, @lelenanam, @joa, @NWilson for their contributions +to this release. + +## v1.9.1 (06 Aug 2018) + +Bugfixes: + +* [#614][]: MapObjectEncoder should not ignore empty slices. + +## v1.9.0 (19 Jul 2018) + +Enhancements: +* [#602][]: Reduce number of allocations when logging with reflection. +* [#572][], [#606][]: Expose a registry for third-party logging sinks. + +Thanks to @nfarah86, @AlekSi, @JeanMertz, @philippgille, @etsangsplk, and +@dimroc for their contributions to this release. + +## v1.8.0 (13 Apr 2018) + +Enhancements: +* [#508][]: Make log level configurable when redirecting the standard + library's logger. +* [#518][]: Add a logger that writes to a `*testing.TB`. +* [#577][]: Add a top-level alias for `zapcore.Field` to clean up GoDoc. + +Bugfixes: +* [#574][]: Add a missing import comment to `go.uber.org/zap/buffer`. + +Thanks to @DiSiqueira and @djui for their contributions to this release. + +## v1.7.1 (25 Sep 2017) + +Bugfixes: +* [#504][]: Store strings when using AddByteString with the map encoder. + +## v1.7.0 (21 Sep 2017) + +Enhancements: + +* [#487][]: Add `NewStdLogAt`, which extends `NewStdLog` by allowing the user + to specify the level of the logged messages. + +## v1.6.0 (30 Aug 2017) + +Enhancements: + +* [#491][]: Omit zap stack frames from stacktraces. +* [#490][]: Add a `ContextMap` method to observer logs for simpler + field validation in tests. + +## v1.5.0 (22 Jul 2017) + +Enhancements: + +* [#460][] and [#470][]: Support errors produced by `go.uber.org/multierr`. +* [#465][]: Support user-supplied encoders for logger names. + +Bugfixes: + +* [#477][]: Fix a bug that incorrectly truncated deep stacktraces. + +Thanks to @richard-tunein and @pavius for their contributions to this release. + +## v1.4.1 (08 Jun 2017) + +This release fixes two bugs. + +Bugfixes: + +* [#435][]: Support a variety of case conventions when unmarshaling levels. +* [#444][]: Fix a panic in the observer. + +## v1.4.0 (12 May 2017) + +This release adds a few small features and is fully backward-compatible. + +Enhancements: + +* [#424][]: Add a `LineEnding` field to `EncoderConfig`, allowing users to + override the Unix-style default. +* [#425][]: Preserve time zones when logging times. +* [#431][]: Make `zap.AtomicLevel` implement `fmt.Stringer`, which makes a + variety of operations a bit simpler. + +## v1.3.0 (25 Apr 2017) + +This release adds an enhancement to zap's testing helpers as well as the +ability to marshal an AtomicLevel. It is fully backward-compatible. + +Enhancements: + +* [#415][]: Add a substring-filtering helper to zap's observer. This is + particularly useful when testing the `SugaredLogger`. +* [#416][]: Make `AtomicLevel` implement `encoding.TextMarshaler`. + +## v1.2.0 (13 Apr 2017) + +This release adds a gRPC compatibility wrapper. It is fully backward-compatible. + +Enhancements: + +* [#402][]: Add a `zapgrpc` package that wraps zap's Logger and implements + `grpclog.Logger`. + +## v1.1.0 (31 Mar 2017) + +This release fixes two bugs and adds some enhancements to zap's testing helpers. +It is fully backward-compatible. + +Bugfixes: + +* [#385][]: Fix caller path trimming on Windows. +* [#396][]: Fix a panic when attempting to use non-existent directories with + zap's configuration struct. + +Enhancements: + +* [#386][]: Add filtering helpers to zaptest's observing logger. + +Thanks to @moitias for contributing to this release. + +## v1.0.0 (14 Mar 2017) + +This is zap's first stable release. All exported APIs are now final, and no +further breaking changes will be made in the 1.x release series. Anyone using a +semver-aware dependency manager should now pin to `^1`. + +Breaking changes: + +* [#366][]: Add byte-oriented APIs to encoders to log UTF-8 encoded text without + casting from `[]byte` to `string`. +* [#364][]: To support buffering outputs, add `Sync` methods to `zapcore.Core`, + `zap.Logger`, and `zap.SugaredLogger`. +* [#371][]: Rename the `testutils` package to `zaptest`, which is less likely to + clash with other testing helpers. + +Bugfixes: + +* [#362][]: Make the ISO8601 time formatters fixed-width, which is friendlier + for tab-separated console output. +* [#369][]: Remove the automatic locks in `zapcore.NewCore`, which allows zap to + work with concurrency-safe `WriteSyncer` implementations. +* [#347][]: Stop reporting errors when trying to `fsync` standard out on Linux + systems. +* [#373][]: Report the correct caller from zap's standard library + interoperability wrappers. + +Enhancements: + +* [#348][]: Add a registry allowing third-party encodings to work with zap's + built-in `Config`. +* [#327][]: Make the representation of logger callers configurable (like times, + levels, and durations). +* [#376][]: Allow third-party encoders to use their own buffer pools, which + removes the last performance advantage that zap's encoders have over plugins. +* [#346][]: Add `CombineWriteSyncers`, a convenience function to tee multiple + `WriteSyncer`s and lock the result. +* [#365][]: Make zap's stacktraces compatible with mid-stack inlining (coming in + Go 1.9). +* [#372][]: Export zap's observing logger as `zaptest/observer`. This makes it + easier for particularly punctilious users to unit test their application's + logging. + +Thanks to @suyash, @htrendev, @flisky, @Ulexus, and @skipor for their +contributions to this release. + +## v1.0.0-rc.3 (7 Mar 2017) + +This is the third release candidate for zap's stable release. There are no +breaking changes. + +Bugfixes: + +* [#339][]: Byte slices passed to `zap.Any` are now correctly treated as binary blobs + rather than `[]uint8`. + +Enhancements: + +* [#307][]: Users can opt into colored output for log levels. +* [#353][]: In addition to hijacking the output of the standard library's + package-global logging functions, users can now construct a zap-backed + `log.Logger` instance. +* [#311][]: Frames from common runtime functions and some of zap's internal + machinery are now omitted from stacktraces. + +Thanks to @ansel1 and @suyash for their contributions to this release. + +## v1.0.0-rc.2 (21 Feb 2017) + +This is the second release candidate for zap's stable release. It includes two +breaking changes. + +Breaking changes: + +* [#316][]: Zap's global loggers are now fully concurrency-safe + (previously, users had to ensure that `ReplaceGlobals` was called before the + loggers were in use). However, they must now be accessed via the `L()` and + `S()` functions. Users can update their projects with + + ``` + gofmt -r "zap.L -> zap.L()" -w . + gofmt -r "zap.S -> zap.S()" -w . + ``` +* [#309][] and [#317][]: RC1 was mistakenly shipped with invalid + JSON and YAML struct tags on all config structs. This release fixes the tags + and adds static analysis to prevent similar bugs in the future. + +Bugfixes: + +* [#321][]: Redirecting the standard library's `log` output now + correctly reports the logger's caller. + +Enhancements: + +* [#325][] and [#333][]: Zap now transparently supports non-standard, rich + errors like those produced by `github.com/pkg/errors`. +* [#326][]: Though `New(nil)` continues to return a no-op logger, `NewNop()` is + now preferred. Users can update their projects with `gofmt -r 'zap.New(nil) -> + zap.NewNop()' -w .`. +* [#300][]: Incorrectly importing zap as `github.com/uber-go/zap` now returns a + more informative error. + +Thanks to @skipor and @chapsuk for their contributions to this release. + +## v1.0.0-rc.1 (14 Feb 2017) + +This is the first release candidate for zap's stable release. There are multiple +breaking changes and improvements from the pre-release version. Most notably: + +* **Zap's import path is now "go.uber.org/zap"** — all users will + need to update their code. +* User-facing types and functions remain in the `zap` package. Code relevant + largely to extension authors is now in the `zapcore` package. +* The `zapcore.Core` type makes it easy for third-party packages to use zap's + internals but provide a different user-facing API. +* `Logger` is now a concrete type instead of an interface. +* A less verbose (though slower) logging API is included by default. +* Package-global loggers `L` and `S` are included. +* A human-friendly console encoder is included. +* A declarative config struct allows common logger configurations to be managed + as configuration instead of code. +* Sampling is more accurate, and doesn't depend on the standard library's shared + timer heap. + +## v0.1.0-beta.1 (6 Feb 2017) + +This is a minor version, tagged to allow users to pin to the pre-1.0 APIs and +upgrade at their leisure. Since this is the first tagged release, there are no +backward compatibility concerns and all functionality is new. + +Early zap adopters should pin to the 0.1.x minor version until they're ready to +upgrade to the upcoming stable release. + +[#316]: https://github.com/uber-go/zap/pull/316 +[#309]: https://github.com/uber-go/zap/pull/309 +[#317]: https://github.com/uber-go/zap/pull/317 +[#321]: https://github.com/uber-go/zap/pull/321 +[#325]: https://github.com/uber-go/zap/pull/325 +[#333]: https://github.com/uber-go/zap/pull/333 +[#326]: https://github.com/uber-go/zap/pull/326 +[#300]: https://github.com/uber-go/zap/pull/300 +[#339]: https://github.com/uber-go/zap/pull/339 +[#307]: https://github.com/uber-go/zap/pull/307 +[#353]: https://github.com/uber-go/zap/pull/353 +[#311]: https://github.com/uber-go/zap/pull/311 +[#366]: https://github.com/uber-go/zap/pull/366 +[#364]: https://github.com/uber-go/zap/pull/364 +[#371]: https://github.com/uber-go/zap/pull/371 +[#362]: https://github.com/uber-go/zap/pull/362 +[#369]: https://github.com/uber-go/zap/pull/369 +[#347]: https://github.com/uber-go/zap/pull/347 +[#373]: https://github.com/uber-go/zap/pull/373 +[#348]: https://github.com/uber-go/zap/pull/348 +[#327]: https://github.com/uber-go/zap/pull/327 +[#376]: https://github.com/uber-go/zap/pull/376 +[#346]: https://github.com/uber-go/zap/pull/346 +[#365]: https://github.com/uber-go/zap/pull/365 +[#372]: https://github.com/uber-go/zap/pull/372 +[#385]: https://github.com/uber-go/zap/pull/385 +[#396]: https://github.com/uber-go/zap/pull/396 +[#386]: https://github.com/uber-go/zap/pull/386 +[#402]: https://github.com/uber-go/zap/pull/402 +[#415]: https://github.com/uber-go/zap/pull/415 +[#416]: https://github.com/uber-go/zap/pull/416 +[#424]: https://github.com/uber-go/zap/pull/424 +[#425]: https://github.com/uber-go/zap/pull/425 +[#431]: https://github.com/uber-go/zap/pull/431 +[#435]: https://github.com/uber-go/zap/pull/435 +[#444]: https://github.com/uber-go/zap/pull/444 +[#477]: https://github.com/uber-go/zap/pull/477 +[#465]: https://github.com/uber-go/zap/pull/465 +[#460]: https://github.com/uber-go/zap/pull/460 +[#470]: https://github.com/uber-go/zap/pull/470 +[#487]: https://github.com/uber-go/zap/pull/487 +[#490]: https://github.com/uber-go/zap/pull/490 +[#491]: https://github.com/uber-go/zap/pull/491 +[#504]: https://github.com/uber-go/zap/pull/504 +[#508]: https://github.com/uber-go/zap/pull/508 +[#518]: https://github.com/uber-go/zap/pull/518 +[#577]: https://github.com/uber-go/zap/pull/577 +[#574]: https://github.com/uber-go/zap/pull/574 +[#602]: https://github.com/uber-go/zap/pull/602 +[#572]: https://github.com/uber-go/zap/pull/572 +[#606]: https://github.com/uber-go/zap/pull/606 +[#614]: https://github.com/uber-go/zap/pull/614 +[#657]: https://github.com/uber-go/zap/pull/657 +[#706]: https://github.com/uber-go/zap/pull/706 +[#610]: https://github.com/uber-go/zap/pull/610 +[#675]: https://github.com/uber-go/zap/pull/675 +[#704]: https://github.com/uber-go/zap/pull/704 +[#725]: https://github.com/uber-go/zap/pull/725 +[#736]: https://github.com/uber-go/zap/pull/736 +[#751]: https://github.com/uber-go/zap/pull/751 +[#758]: https://github.com/uber-go/zap/pull/758 +[#771]: https://github.com/uber-go/zap/pull/771 +[#773]: https://github.com/uber-go/zap/pull/773 +[#775]: https://github.com/uber-go/zap/pull/775 +[#786]: https://github.com/uber-go/zap/pull/786 +[#791]: https://github.com/uber-go/zap/pull/791 +[#795]: https://github.com/uber-go/zap/pull/795 +[#799]: https://github.com/uber-go/zap/pull/799 +[#804]: https://github.com/uber-go/zap/pull/804 +[#812]: https://github.com/uber-go/zap/pull/812 +[#806]: https://github.com/uber-go/zap/pull/806 +[#813]: https://github.com/uber-go/zap/pull/813 +[#629]: https://github.com/uber-go/zap/pull/629 +[#697]: https://github.com/uber-go/zap/pull/697 +[#828]: https://github.com/uber-go/zap/pull/828 +[#835]: https://github.com/uber-go/zap/pull/835 +[#843]: https://github.com/uber-go/zap/pull/843 +[#844]: https://github.com/uber-go/zap/pull/844 +[#852]: https://github.com/uber-go/zap/pull/852 +[#854]: https://github.com/uber-go/zap/pull/854 +[#861]: https://github.com/uber-go/zap/pull/861 +[#862]: https://github.com/uber-go/zap/pull/862 +[#865]: https://github.com/uber-go/zap/pull/865 +[#867]: https://github.com/uber-go/zap/pull/867 +[#881]: https://github.com/uber-go/zap/pull/881 +[#903]: https://github.com/uber-go/zap/pull/903 +[#912]: https://github.com/uber-go/zap/pull/912 +[#913]: https://github.com/uber-go/zap/pull/913 +[#928]: https://github.com/uber-go/zap/pull/928 +[#931]: https://github.com/uber-go/zap/pull/931 +[#936]: https://github.com/uber-go/zap/pull/936 diff --git a/tools/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md b/tools/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..e327d9aa --- /dev/null +++ b/tools/vendor/go.uber.org/zap/CODE_OF_CONDUCT.md @@ -0,0 +1,75 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, +body size, disability, ethnicity, gender identity and expression, level of +experience, nationality, personal appearance, race, religion, or sexual +identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an +appointed representative at an online or offline event. Representation of a +project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at oss-conduct@uber.com. The project +team will review and investigate all complaints, and will respond in a way +that it deems appropriate to the circumstances. The project team is obligated +to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at +[http://contributor-covenant.org/version/1/4][version]. + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/tools/vendor/go.uber.org/zap/CONTRIBUTING.md b/tools/vendor/go.uber.org/zap/CONTRIBUTING.md new file mode 100644 index 00000000..5cd96568 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/CONTRIBUTING.md @@ -0,0 +1,75 @@ +# Contributing + +We'd love your help making zap the very best structured logging library in Go! + +If you'd like to add new exported APIs, please [open an issue][open-issue] +describing your proposal — discussing API changes ahead of time makes +pull request review much smoother. In your issue, pull request, and any other +communications, please remember to treat your fellow contributors with +respect! We take our [code of conduct](CODE_OF_CONDUCT.md) seriously. + +Note that you'll need to sign [Uber's Contributor License Agreement][cla] +before we can accept any of your contributions. If necessary, a bot will remind +you to accept the CLA when you open your pull request. + +## Setup + +[Fork][fork], then clone the repository: + +``` +mkdir -p $GOPATH/src/go.uber.org +cd $GOPATH/src/go.uber.org +git clone git@github.com:your_github_username/zap.git +cd zap +git remote add upstream https://github.com/uber-go/zap.git +git fetch upstream +``` + +Make sure that the tests and the linters pass: + +``` +make test +make lint +``` + +If you're not using the minor version of Go specified in the Makefile's +`LINTABLE_MINOR_VERSIONS` variable, `make lint` doesn't do anything. This is +fine, but it means that you'll only discover lint failures after you open your +pull request. + +## Making Changes + +Start by creating a new branch for your changes: + +``` +cd $GOPATH/src/go.uber.org/zap +git checkout master +git fetch upstream +git rebase upstream/master +git checkout -b cool_new_feature +``` + +Make your changes, then ensure that `make lint` and `make test` still pass. If +you're satisfied with your changes, push them to your fork. + +``` +git push origin cool_new_feature +``` + +Then use the GitHub UI to open a pull request. + +At this point, you're waiting on us to review your changes. We *try* to respond +to issues and pull requests within a few business days, and we may suggest some +improvements or alternatives. Once your changes are approved, one of the +project maintainers will merge them. + +We're much more likely to approve your changes if you: + +* Add tests for new functionality. +* Write a [good commit message][commit-message]. +* Maintain backward compatibility. + +[fork]: https://github.com/uber-go/zap/fork +[open-issue]: https://github.com/uber-go/zap/issues/new +[cla]: https://cla-assistant.io/uber-go/zap +[commit-message]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html diff --git a/tools/vendor/go.uber.org/zap/FAQ.md b/tools/vendor/go.uber.org/zap/FAQ.md new file mode 100644 index 00000000..b183b20b --- /dev/null +++ b/tools/vendor/go.uber.org/zap/FAQ.md @@ -0,0 +1,164 @@ +# Frequently Asked Questions + +## Design + +### Why spend so much effort on logger performance? + +Of course, most applications won't notice the impact of a slow logger: they +already take tens or hundreds of milliseconds for each operation, so an extra +millisecond doesn't matter. + +On the other hand, why *not* make structured logging fast? The `SugaredLogger` +isn't any harder to use than other logging packages, and the `Logger` makes +structured logging possible in performance-sensitive contexts. Across a fleet +of Go microservices, making each application even slightly more efficient adds +up quickly. + +### Why aren't `Logger` and `SugaredLogger` interfaces? + +Unlike the familiar `io.Writer` and `http.Handler`, `Logger` and +`SugaredLogger` interfaces would include *many* methods. As [Rob Pike points +out][go-proverbs], "The bigger the interface, the weaker the abstraction." +Interfaces are also rigid — *any* change requires releasing a new major +version, since it breaks all third-party implementations. + +Making the `Logger` and `SugaredLogger` concrete types doesn't sacrifice much +abstraction, and it lets us add methods without introducing breaking changes. +Your applications should define and depend upon an interface that includes +just the methods you use. + +### Why are some of my logs missing? + +Logs are dropped intentionally by zap when sampling is enabled. The production +configuration (as returned by `NewProductionConfig()` enables sampling which will +cause repeated logs within a second to be sampled. See more details on why sampling +is enabled in [Why sample application logs](https://github.com/uber-go/zap/blob/master/FAQ.md#why-sample-application-logs). + +### Why sample application logs? + +Applications often experience runs of errors, either because of a bug or +because of a misbehaving user. Logging errors is usually a good idea, but it +can easily make this bad situation worse: not only is your application coping +with a flood of errors, it's also spending extra CPU cycles and I/O logging +those errors. Since writes are typically serialized, logging limits throughput +when you need it most. + +Sampling fixes this problem by dropping repetitive log entries. Under normal +conditions, your application writes out every entry. When similar entries are +logged hundreds or thousands of times each second, though, zap begins dropping +duplicates to preserve throughput. + +### Why do the structured logging APIs take a message in addition to fields? + +Subjectively, we find it helpful to accompany structured context with a brief +description. This isn't critical during development, but it makes debugging +and operating unfamiliar systems much easier. + +More concretely, zap's sampling algorithm uses the message to identify +duplicate entries. In our experience, this is a practical middle ground +between random sampling (which often drops the exact entry that you need while +debugging) and hashing the complete entry (which is prohibitively expensive). + +### Why include package-global loggers? + +Since so many other logging packages include a global logger, many +applications aren't designed to accept loggers as explicit parameters. +Changing function signatures is often a breaking change, so zap includes +global loggers to simplify migration. + +Avoid them where possible. + +### Why include dedicated Panic and Fatal log levels? + +In general, application code should handle errors gracefully instead of using +`panic` or `os.Exit`. However, every rule has exceptions, and it's common to +crash when an error is truly unrecoverable. To avoid losing any information +— especially the reason for the crash — the logger must flush any +buffered entries before the process exits. + +Zap makes this easy by offering `Panic` and `Fatal` logging methods that +automatically flush before exiting. Of course, this doesn't guarantee that +logs will never be lost, but it eliminates a common error. + +See the discussion in uber-go/zap#207 for more details. + +### What's `DPanic`? + +`DPanic` stands for "panic in development." In development, it logs at +`PanicLevel`; otherwise, it logs at `ErrorLevel`. `DPanic` makes it easier to +catch errors that are theoretically possible, but shouldn't actually happen, +*without* crashing in production. + +If you've ever written code like this, you need `DPanic`: + +```go +if err != nil { + panic(fmt.Sprintf("shouldn't ever get here: %v", err)) +} +``` + +## Installation + +### What does the error `expects import "go.uber.org/zap"` mean? + +Either zap was installed incorrectly or you're referencing the wrong package +name in your code. + +Zap's source code happens to be hosted on GitHub, but the [import +path][import-path] is `go.uber.org/zap`. This gives us, the project +maintainers, the freedom to move the source code if necessary. However, it +means that you need to take a little care when installing and using the +package. + +If you follow two simple rules, everything should work: install zap with `go +get -u go.uber.org/zap`, and always import it in your code with `import +"go.uber.org/zap"`. Your code shouldn't contain *any* references to +`github.com/uber-go/zap`. + +## Usage + +### Does zap support log rotation? + +Zap doesn't natively support rotating log files, since we prefer to leave this +to an external program like `logrotate`. + +However, it's easy to integrate a log rotation package like +[`gopkg.in/natefinch/lumberjack.v2`][lumberjack] as a `zapcore.WriteSyncer`. + +```go +// lumberjack.Logger is already safe for concurrent use, so we don't need to +// lock it. +w := zapcore.AddSync(&lumberjack.Logger{ + Filename: "/var/log/myapp/foo.log", + MaxSize: 500, // megabytes + MaxBackups: 3, + MaxAge: 28, // days +}) +core := zapcore.NewCore( + zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), + w, + zap.InfoLevel, +) +logger := zap.New(core) +``` + +## Extensions + +We'd love to support every logging need within zap itself, but we're only +familiar with a handful of log ingestion systems, flag-parsing packages, and +the like. Rather than merging code that we can't effectively debug and +support, we'd rather grow an ecosystem of zap extensions. + +We're aware of the following extensions, but haven't used them ourselves: + +| Package | Integration | +| --- | --- | +| `github.com/tchap/zapext` | Sentry, syslog | +| `github.com/fgrosse/zaptest` | Ginkgo | +| `github.com/blendle/zapdriver` | Stackdriver | +| `github.com/moul/zapgorm` | Gorm | +| `github.com/moul/zapfilter` | Advanced filtering rules | + +[go-proverbs]: https://go-proverbs.github.io/ +[import-path]: https://golang.org/cmd/go/#hdr-Remote_import_paths +[lumberjack]: https://godoc.org/gopkg.in/natefinch/lumberjack.v2 diff --git a/tools/vendor/go.uber.org/zap/LICENSE.txt b/tools/vendor/go.uber.org/zap/LICENSE.txt new file mode 100644 index 00000000..6652bed4 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2016-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. diff --git a/tools/vendor/go.uber.org/zap/Makefile b/tools/vendor/go.uber.org/zap/Makefile new file mode 100644 index 00000000..9b1bc3b0 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/Makefile @@ -0,0 +1,73 @@ +export GOBIN ?= $(shell pwd)/bin + +GOLINT = $(GOBIN)/golint +STATICCHECK = $(GOBIN)/staticcheck +BENCH_FLAGS ?= -cpuprofile=cpu.pprof -memprofile=mem.pprof -benchmem + +# Directories containing independent Go modules. +# +# We track coverage only for the main module. +MODULE_DIRS = . ./benchmarks ./zapgrpc/internal/test + +# Many Go tools take file globs or directories as arguments instead of packages. +GO_FILES := $(shell \ + find . '(' -path '*/.*' -o -path './vendor' ')' -prune \ + -o -name '*.go' -print | cut -b3-) + +.PHONY: all +all: lint test + +.PHONY: lint +lint: $(GOLINT) $(STATICCHECK) + @rm -rf lint.log + @echo "Checking formatting..." + @gofmt -d -s $(GO_FILES) 2>&1 | tee lint.log + @echo "Checking vet..." + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && go vet ./... 2>&1) &&) true | tee -a lint.log + @echo "Checking lint..." + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && $(GOLINT) ./... 2>&1) &&) true | tee -a lint.log + @echo "Checking staticcheck..." + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && $(STATICCHECK) ./... 2>&1) &&) true | tee -a lint.log + @echo "Checking for unresolved FIXMEs..." + @git grep -i fixme | grep -v -e Makefile | tee -a lint.log + @echo "Checking for license headers..." + @./checklicense.sh | tee -a lint.log + @[ ! -s lint.log ] + @echo "Checking 'go mod tidy'..." + @make tidy + @if ! git diff --quiet; then \ + echo "'go mod tidy' resulted in changes or working tree is dirty:"; \ + git --no-pager diff; \ + fi + +$(GOLINT): + cd tools && go install golang.org/x/lint/golint + +$(STATICCHECK): + cd tools && go install honnef.co/go/tools/cmd/staticcheck + +.PHONY: test +test: + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && go test -race ./...) &&) true + +.PHONY: cover +cover: + go test -race -coverprofile=cover.out -coverpkg=./... ./... + go tool cover -html=cover.out -o cover.html + +.PHONY: bench +BENCH ?= . +bench: + @$(foreach dir,$(MODULE_DIRS), ( \ + cd $(dir) && \ + go list ./... | xargs -n1 go test -bench=$(BENCH) -run="^$$" $(BENCH_FLAGS) \ + ) &&) true + +.PHONY: updatereadme +updatereadme: + rm -f README.md + cat .readme.tmpl | go run internal/readme/readme.go > README.md + +.PHONY: tidy +tidy: + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && go mod tidy) &&) true diff --git a/tools/vendor/go.uber.org/zap/README.md b/tools/vendor/go.uber.org/zap/README.md new file mode 100644 index 00000000..9c9dfe1e --- /dev/null +++ b/tools/vendor/go.uber.org/zap/README.md @@ -0,0 +1,134 @@ +# :zap: zap [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] + +Blazing fast, structured, leveled logging in Go. + +## Installation + +`go get -u go.uber.org/zap` + +Note that zap only supports the two most recent minor versions of Go. + +## Quick Start + +In contexts where performance is nice, but not critical, use the +`SugaredLogger`. It's 4-10x faster than other structured logging +packages and includes both structured and `printf`-style APIs. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() // flushes buffer, if any +sugar := logger.Sugar() +sugar.Infow("failed to fetch URL", + // Structured context as loosely typed key-value pairs. + "url", url, + "attempt", 3, + "backoff", time.Second, +) +sugar.Infof("Failed to fetch URL: %s", url) +``` + +When performance and type safety are critical, use the `Logger`. It's even +faster than the `SugaredLogger` and allocates far less, but it only supports +structured logging. + +```go +logger, _ := zap.NewProduction() +defer logger.Sync() +logger.Info("failed to fetch URL", + // Structured context as strongly typed Field values. + zap.String("url", url), + zap.Int("attempt", 3), + zap.Duration("backoff", time.Second), +) +``` + +See the [documentation][doc] and [FAQ](FAQ.md) for more details. + +## Performance + +For applications that log in the hot path, reflection-based serialization and +string formatting are prohibitively expensive — they're CPU-intensive +and make many small allocations. Put differently, using `encoding/json` and +`fmt.Fprintf` to log tons of `interface{}`s makes your application slow. + +Zap takes a different approach. It includes a reflection-free, zero-allocation +JSON encoder, and the base `Logger` strives to avoid serialization overhead +and allocations wherever possible. By building the high-level `SugaredLogger` +on that foundation, zap lets users *choose* when they need to count every +allocation and when they'd prefer a more familiar, loosely typed API. + +As measured by its own [benchmarking suite][], not only is zap more performant +than comparable structured logging packages — it's also faster than the +standard library. Like all benchmarks, take these with a grain of salt.[1](#footnote-versions) + +Log a message and 10 fields: + +| Package | Time | Time % to zap | Objects Allocated | +| :------ | :--: | :-----------: | :---------------: | +| :zap: zap | 2900 ns/op | +0% | 5 allocs/op +| :zap: zap (sugared) | 3475 ns/op | +20% | 10 allocs/op +| zerolog | 10639 ns/op | +267% | 32 allocs/op +| go-kit | 14434 ns/op | +398% | 59 allocs/op +| logrus | 17104 ns/op | +490% | 81 allocs/op +| apex/log | 32424 ns/op | +1018% | 66 allocs/op +| log15 | 33579 ns/op | +1058% | 76 allocs/op + +Log a message with a logger that already has 10 fields of context: + +| Package | Time | Time % to zap | Objects Allocated | +| :------ | :--: | :-----------: | :---------------: | +| :zap: zap | 373 ns/op | +0% | 0 allocs/op +| :zap: zap (sugared) | 452 ns/op | +21% | 1 allocs/op +| zerolog | 288 ns/op | -23% | 0 allocs/op +| go-kit | 11785 ns/op | +3060% | 58 allocs/op +| logrus | 19629 ns/op | +5162% | 70 allocs/op +| log15 | 21866 ns/op | +5762% | 72 allocs/op +| apex/log | 30890 ns/op | +8182% | 55 allocs/op + +Log a static string, without any context or `printf`-style templating: + +| Package | Time | Time % to zap | Objects Allocated | +| :------ | :--: | :-----------: | :---------------: | +| :zap: zap | 381 ns/op | +0% | 0 allocs/op +| :zap: zap (sugared) | 410 ns/op | +8% | 1 allocs/op +| zerolog | 369 ns/op | -3% | 0 allocs/op +| standard library | 385 ns/op | +1% | 2 allocs/op +| go-kit | 606 ns/op | +59% | 11 allocs/op +| logrus | 1730 ns/op | +354% | 25 allocs/op +| apex/log | 1998 ns/op | +424% | 7 allocs/op +| log15 | 4546 ns/op | +1093% | 22 allocs/op + +## Development Status: Stable + +All APIs are finalized, and no breaking changes will be made in the 1.x series +of releases. Users of semver-aware dependency management systems should pin +zap to `^1`. + +## Contributing + +We encourage and support an active, healthy community of contributors — +including you! Details are in the [contribution guide](CONTRIBUTING.md) and +the [code of conduct](CODE_OF_CONDUCT.md). The zap maintainers keep an eye on +issues and pull requests, but you can also report any negative conduct to +oss-conduct@uber.com. That email list is a private, safe space; even the zap +maintainers don't have access, so don't hesitate to hold us to a high +standard. + +
+ +Released under the [MIT License](LICENSE.txt). + +1 In particular, keep in mind that we may be +benchmarking against slightly older versions of other packages. Versions are +pinned in the [benchmarks/go.mod][] file. [↩](#anchor-versions) + +[doc-img]: https://pkg.go.dev/badge/go.uber.org/zap +[doc]: https://pkg.go.dev/go.uber.org/zap +[ci-img]: https://github.com/uber-go/zap/actions/workflows/go.yml/badge.svg +[ci]: https://github.com/uber-go/zap/actions/workflows/go.yml +[cov-img]: https://codecov.io/gh/uber-go/zap/branch/master/graph/badge.svg +[cov]: https://codecov.io/gh/uber-go/zap +[benchmarking suite]: https://github.com/uber-go/zap/tree/master/benchmarks +[benchmarks/go.mod]: https://github.com/uber-go/zap/blob/master/benchmarks/go.mod + diff --git a/tools/vendor/go.uber.org/zap/array.go b/tools/vendor/go.uber.org/zap/array.go new file mode 100644 index 00000000..5be3704a --- /dev/null +++ b/tools/vendor/go.uber.org/zap/array.go @@ -0,0 +1,320 @@ +// Copyright (c) 2016 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 zap + +import ( + "time" + + "go.uber.org/zap/zapcore" +) + +// Array constructs a field with the given key and ArrayMarshaler. It provides +// a flexible, but still type-safe and efficient, way to add array-like types +// to the logging context. The struct's MarshalLogArray method is called lazily. +func Array(key string, val zapcore.ArrayMarshaler) Field { + return Field{Key: key, Type: zapcore.ArrayMarshalerType, Interface: val} +} + +// Bools constructs a field that carries a slice of bools. +func Bools(key string, bs []bool) Field { + return Array(key, bools(bs)) +} + +// ByteStrings constructs a field that carries a slice of []byte, each of which +// must be UTF-8 encoded text. +func ByteStrings(key string, bss [][]byte) Field { + return Array(key, byteStringsArray(bss)) +} + +// Complex128s constructs a field that carries a slice of complex numbers. +func Complex128s(key string, nums []complex128) Field { + return Array(key, complex128s(nums)) +} + +// Complex64s constructs a field that carries a slice of complex numbers. +func Complex64s(key string, nums []complex64) Field { + return Array(key, complex64s(nums)) +} + +// Durations constructs a field that carries a slice of time.Durations. +func Durations(key string, ds []time.Duration) Field { + return Array(key, durations(ds)) +} + +// Float64s constructs a field that carries a slice of floats. +func Float64s(key string, nums []float64) Field { + return Array(key, float64s(nums)) +} + +// Float32s constructs a field that carries a slice of floats. +func Float32s(key string, nums []float32) Field { + return Array(key, float32s(nums)) +} + +// Ints constructs a field that carries a slice of integers. +func Ints(key string, nums []int) Field { + return Array(key, ints(nums)) +} + +// Int64s constructs a field that carries a slice of integers. +func Int64s(key string, nums []int64) Field { + return Array(key, int64s(nums)) +} + +// Int32s constructs a field that carries a slice of integers. +func Int32s(key string, nums []int32) Field { + return Array(key, int32s(nums)) +} + +// Int16s constructs a field that carries a slice of integers. +func Int16s(key string, nums []int16) Field { + return Array(key, int16s(nums)) +} + +// Int8s constructs a field that carries a slice of integers. +func Int8s(key string, nums []int8) Field { + return Array(key, int8s(nums)) +} + +// Strings constructs a field that carries a slice of strings. +func Strings(key string, ss []string) Field { + return Array(key, stringArray(ss)) +} + +// Times constructs a field that carries a slice of time.Times. +func Times(key string, ts []time.Time) Field { + return Array(key, times(ts)) +} + +// Uints constructs a field that carries a slice of unsigned integers. +func Uints(key string, nums []uint) Field { + return Array(key, uints(nums)) +} + +// Uint64s constructs a field that carries a slice of unsigned integers. +func Uint64s(key string, nums []uint64) Field { + return Array(key, uint64s(nums)) +} + +// Uint32s constructs a field that carries a slice of unsigned integers. +func Uint32s(key string, nums []uint32) Field { + return Array(key, uint32s(nums)) +} + +// Uint16s constructs a field that carries a slice of unsigned integers. +func Uint16s(key string, nums []uint16) Field { + return Array(key, uint16s(nums)) +} + +// Uint8s constructs a field that carries a slice of unsigned integers. +func Uint8s(key string, nums []uint8) Field { + return Array(key, uint8s(nums)) +} + +// Uintptrs constructs a field that carries a slice of pointer addresses. +func Uintptrs(key string, us []uintptr) Field { + return Array(key, uintptrs(us)) +} + +// Errors constructs a field that carries a slice of errors. +func Errors(key string, errs []error) Field { + return Array(key, errArray(errs)) +} + +type bools []bool + +func (bs bools) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range bs { + arr.AppendBool(bs[i]) + } + return nil +} + +type byteStringsArray [][]byte + +func (bss byteStringsArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range bss { + arr.AppendByteString(bss[i]) + } + return nil +} + +type complex128s []complex128 + +func (nums complex128s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendComplex128(nums[i]) + } + return nil +} + +type complex64s []complex64 + +func (nums complex64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendComplex64(nums[i]) + } + return nil +} + +type durations []time.Duration + +func (ds durations) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range ds { + arr.AppendDuration(ds[i]) + } + return nil +} + +type float64s []float64 + +func (nums float64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendFloat64(nums[i]) + } + return nil +} + +type float32s []float32 + +func (nums float32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendFloat32(nums[i]) + } + return nil +} + +type ints []int + +func (nums ints) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt(nums[i]) + } + return nil +} + +type int64s []int64 + +func (nums int64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt64(nums[i]) + } + return nil +} + +type int32s []int32 + +func (nums int32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt32(nums[i]) + } + return nil +} + +type int16s []int16 + +func (nums int16s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt16(nums[i]) + } + return nil +} + +type int8s []int8 + +func (nums int8s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendInt8(nums[i]) + } + return nil +} + +type stringArray []string + +func (ss stringArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range ss { + arr.AppendString(ss[i]) + } + return nil +} + +type times []time.Time + +func (ts times) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range ts { + arr.AppendTime(ts[i]) + } + return nil +} + +type uints []uint + +func (nums uints) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint(nums[i]) + } + return nil +} + +type uint64s []uint64 + +func (nums uint64s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint64(nums[i]) + } + return nil +} + +type uint32s []uint32 + +func (nums uint32s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint32(nums[i]) + } + return nil +} + +type uint16s []uint16 + +func (nums uint16s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint16(nums[i]) + } + return nil +} + +type uint8s []uint8 + +func (nums uint8s) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUint8(nums[i]) + } + return nil +} + +type uintptrs []uintptr + +func (nums uintptrs) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range nums { + arr.AppendUintptr(nums[i]) + } + return nil +} diff --git a/tools/vendor/go.uber.org/zap/buffer/buffer.go b/tools/vendor/go.uber.org/zap/buffer/buffer.go new file mode 100644 index 00000000..9e929cd9 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/buffer/buffer.go @@ -0,0 +1,141 @@ +// Copyright (c) 2016 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 buffer provides a thin wrapper around a byte slice. Unlike the +// standard library's bytes.Buffer, it supports a portion of the strconv +// package's zero-allocation formatters. +package buffer // import "go.uber.org/zap/buffer" + +import ( + "strconv" + "time" +) + +const _size = 1024 // by default, create 1 KiB buffers + +// Buffer is a thin wrapper around a byte slice. It's intended to be pooled, so +// the only way to construct one is via a Pool. +type Buffer struct { + bs []byte + pool Pool +} + +// AppendByte writes a single byte to the Buffer. +func (b *Buffer) AppendByte(v byte) { + b.bs = append(b.bs, v) +} + +// AppendString writes a string to the Buffer. +func (b *Buffer) AppendString(s string) { + b.bs = append(b.bs, s...) +} + +// AppendInt appends an integer to the underlying buffer (assuming base 10). +func (b *Buffer) AppendInt(i int64) { + b.bs = strconv.AppendInt(b.bs, i, 10) +} + +// AppendTime appends the time formatted using the specified layout. +func (b *Buffer) AppendTime(t time.Time, layout string) { + b.bs = t.AppendFormat(b.bs, layout) +} + +// AppendUint appends an unsigned integer to the underlying buffer (assuming +// base 10). +func (b *Buffer) AppendUint(i uint64) { + b.bs = strconv.AppendUint(b.bs, i, 10) +} + +// AppendBool appends a bool to the underlying buffer. +func (b *Buffer) AppendBool(v bool) { + b.bs = strconv.AppendBool(b.bs, v) +} + +// AppendFloat appends a float to the underlying buffer. It doesn't quote NaN +// or +/- Inf. +func (b *Buffer) AppendFloat(f float64, bitSize int) { + b.bs = strconv.AppendFloat(b.bs, f, 'f', -1, bitSize) +} + +// Len returns the length of the underlying byte slice. +func (b *Buffer) Len() int { + return len(b.bs) +} + +// Cap returns the capacity of the underlying byte slice. +func (b *Buffer) Cap() int { + return cap(b.bs) +} + +// Bytes returns a mutable reference to the underlying byte slice. +func (b *Buffer) Bytes() []byte { + return b.bs +} + +// String returns a string copy of the underlying byte slice. +func (b *Buffer) String() string { + return string(b.bs) +} + +// Reset resets the underlying byte slice. Subsequent writes re-use the slice's +// backing array. +func (b *Buffer) Reset() { + b.bs = b.bs[:0] +} + +// Write implements io.Writer. +func (b *Buffer) Write(bs []byte) (int, error) { + b.bs = append(b.bs, bs...) + return len(bs), nil +} + +// WriteByte writes a single byte to the Buffer. +// +// Error returned is always nil, function signature is compatible +// with bytes.Buffer and bufio.Writer +func (b *Buffer) WriteByte(v byte) error { + b.AppendByte(v) + return nil +} + +// WriteString writes a string to the Buffer. +// +// Error returned is always nil, function signature is compatible +// with bytes.Buffer and bufio.Writer +func (b *Buffer) WriteString(s string) (int, error) { + b.AppendString(s) + return len(s), nil +} + +// TrimNewline trims any final "\n" byte from the end of the buffer. +func (b *Buffer) TrimNewline() { + if i := len(b.bs) - 1; i >= 0 { + if b.bs[i] == '\n' { + b.bs = b.bs[:i] + } + } +} + +// Free returns the Buffer to its Pool. +// +// Callers must not retain references to the Buffer after calling Free. +func (b *Buffer) Free() { + b.pool.put(b) +} diff --git a/tools/vendor/go.uber.org/zap/buffer/pool.go b/tools/vendor/go.uber.org/zap/buffer/pool.go new file mode 100644 index 00000000..8fb3e202 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/buffer/pool.go @@ -0,0 +1,49 @@ +// Copyright (c) 2016 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 buffer + +import "sync" + +// A Pool is a type-safe wrapper around a sync.Pool. +type Pool struct { + p *sync.Pool +} + +// NewPool constructs a new Pool. +func NewPool() Pool { + return Pool{p: &sync.Pool{ + New: func() interface{} { + return &Buffer{bs: make([]byte, 0, _size)} + }, + }} +} + +// Get retrieves a Buffer from the pool, creating one if necessary. +func (p Pool) Get() *Buffer { + buf := p.p.Get().(*Buffer) + buf.Reset() + buf.pool = p + return buf +} + +func (p Pool) put(buf *Buffer) { + p.p.Put(buf) +} diff --git a/tools/vendor/go.uber.org/zap/checklicense.sh b/tools/vendor/go.uber.org/zap/checklicense.sh new file mode 100644 index 00000000..345ac8b8 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/checklicense.sh @@ -0,0 +1,17 @@ +#!/bin/bash -e + +ERROR_COUNT=0 +while read -r file +do + case "$(head -1 "${file}")" in + *"Copyright (c) "*" Uber Technologies, Inc.") + # everything's cool + ;; + *) + echo "$file is missing license header." + (( ERROR_COUNT++ )) + ;; + esac +done < <(git ls-files "*\.go") + +exit $ERROR_COUNT diff --git a/tools/vendor/go.uber.org/zap/config.go b/tools/vendor/go.uber.org/zap/config.go new file mode 100644 index 00000000..55637fb0 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/config.go @@ -0,0 +1,264 @@ +// Copyright (c) 2016 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 zap + +import ( + "fmt" + "sort" + "time" + + "go.uber.org/zap/zapcore" +) + +// SamplingConfig sets a sampling strategy for the logger. Sampling caps the +// global CPU and I/O load that logging puts on your process while attempting +// to preserve a representative subset of your logs. +// +// If specified, the Sampler will invoke the Hook after each decision. +// +// Values configured here are per-second. See zapcore.NewSamplerWithOptions for +// details. +type SamplingConfig struct { + Initial int `json:"initial" yaml:"initial"` + Thereafter int `json:"thereafter" yaml:"thereafter"` + Hook func(zapcore.Entry, zapcore.SamplingDecision) `json:"-" yaml:"-"` +} + +// Config offers a declarative way to construct a logger. It doesn't do +// anything that can't be done with New, Options, and the various +// zapcore.WriteSyncer and zapcore.Core wrappers, but it's a simpler way to +// toggle common options. +// +// Note that Config intentionally supports only the most common options. More +// unusual logging setups (logging to network connections or message queues, +// splitting output between multiple files, etc.) are possible, but require +// direct use of the zapcore package. For sample code, see the package-level +// BasicConfiguration and AdvancedConfiguration examples. +// +// For an example showing runtime log level changes, see the documentation for +// AtomicLevel. +type Config struct { + // Level is the minimum enabled logging level. Note that this is a dynamic + // level, so calling Config.Level.SetLevel will atomically change the log + // level of all loggers descended from this config. + Level AtomicLevel `json:"level" yaml:"level"` + // Development puts the logger in development mode, which changes the + // behavior of DPanicLevel and takes stacktraces more liberally. + Development bool `json:"development" yaml:"development"` + // DisableCaller stops annotating logs with the calling function's file + // name and line number. By default, all logs are annotated. + DisableCaller bool `json:"disableCaller" yaml:"disableCaller"` + // DisableStacktrace completely disables automatic stacktrace capturing. By + // default, stacktraces are captured for WarnLevel and above logs in + // development and ErrorLevel and above in production. + DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"` + // Sampling sets a sampling policy. A nil SamplingConfig disables sampling. + Sampling *SamplingConfig `json:"sampling" yaml:"sampling"` + // Encoding sets the logger's encoding. Valid values are "json" and + // "console", as well as any third-party encodings registered via + // RegisterEncoder. + Encoding string `json:"encoding" yaml:"encoding"` + // EncoderConfig sets options for the chosen encoder. See + // zapcore.EncoderConfig for details. + EncoderConfig zapcore.EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"` + // OutputPaths is a list of URLs or file paths to write logging output to. + // See Open for details. + OutputPaths []string `json:"outputPaths" yaml:"outputPaths"` + // ErrorOutputPaths is a list of URLs to write internal logger errors to. + // The default is standard error. + // + // Note that this setting only affects internal errors; for sample code that + // sends error-level logs to a different location from info- and debug-level + // logs, see the package-level AdvancedConfiguration example. + ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"` + // InitialFields is a collection of fields to add to the root logger. + InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"` +} + +// NewProductionEncoderConfig returns an opinionated EncoderConfig for +// production environments. +func NewProductionEncoderConfig() zapcore.EncoderConfig { + return zapcore.EncoderConfig{ + TimeKey: "ts", + LevelKey: "level", + NameKey: "logger", + CallerKey: "caller", + FunctionKey: zapcore.OmitKey, + MessageKey: "msg", + StacktraceKey: "stacktrace", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.LowercaseLevelEncoder, + EncodeTime: zapcore.EpochTimeEncoder, + EncodeDuration: zapcore.SecondsDurationEncoder, + EncodeCaller: zapcore.ShortCallerEncoder, + } +} + +// NewProductionConfig is a reasonable production logging configuration. +// Logging is enabled at InfoLevel and above. +// +// It uses a JSON encoder, writes to standard error, and enables sampling. +// Stacktraces are automatically included on logs of ErrorLevel and above. +func NewProductionConfig() Config { + return Config{ + Level: NewAtomicLevelAt(InfoLevel), + Development: false, + Sampling: &SamplingConfig{ + Initial: 100, + Thereafter: 100, + }, + Encoding: "json", + EncoderConfig: NewProductionEncoderConfig(), + OutputPaths: []string{"stderr"}, + ErrorOutputPaths: []string{"stderr"}, + } +} + +// NewDevelopmentEncoderConfig returns an opinionated EncoderConfig for +// development environments. +func NewDevelopmentEncoderConfig() zapcore.EncoderConfig { + return zapcore.EncoderConfig{ + // Keys can be anything except the empty string. + TimeKey: "T", + LevelKey: "L", + NameKey: "N", + CallerKey: "C", + FunctionKey: zapcore.OmitKey, + MessageKey: "M", + StacktraceKey: "S", + LineEnding: zapcore.DefaultLineEnding, + EncodeLevel: zapcore.CapitalLevelEncoder, + EncodeTime: zapcore.ISO8601TimeEncoder, + EncodeDuration: zapcore.StringDurationEncoder, + EncodeCaller: zapcore.ShortCallerEncoder, + } +} + +// NewDevelopmentConfig is a reasonable development logging configuration. +// Logging is enabled at DebugLevel and above. +// +// It enables development mode (which makes DPanicLevel logs panic), uses a +// console encoder, writes to standard error, and disables sampling. +// Stacktraces are automatically included on logs of WarnLevel and above. +func NewDevelopmentConfig() Config { + return Config{ + Level: NewAtomicLevelAt(DebugLevel), + Development: true, + Encoding: "console", + EncoderConfig: NewDevelopmentEncoderConfig(), + OutputPaths: []string{"stderr"}, + ErrorOutputPaths: []string{"stderr"}, + } +} + +// Build constructs a logger from the Config and Options. +func (cfg Config) Build(opts ...Option) (*Logger, error) { + enc, err := cfg.buildEncoder() + if err != nil { + return nil, err + } + + sink, errSink, err := cfg.openSinks() + if err != nil { + return nil, err + } + + if cfg.Level == (AtomicLevel{}) { + return nil, fmt.Errorf("missing Level") + } + + log := New( + zapcore.NewCore(enc, sink, cfg.Level), + cfg.buildOptions(errSink)..., + ) + if len(opts) > 0 { + log = log.WithOptions(opts...) + } + return log, nil +} + +func (cfg Config) buildOptions(errSink zapcore.WriteSyncer) []Option { + opts := []Option{ErrorOutput(errSink)} + + if cfg.Development { + opts = append(opts, Development()) + } + + if !cfg.DisableCaller { + opts = append(opts, AddCaller()) + } + + stackLevel := ErrorLevel + if cfg.Development { + stackLevel = WarnLevel + } + if !cfg.DisableStacktrace { + opts = append(opts, AddStacktrace(stackLevel)) + } + + if scfg := cfg.Sampling; scfg != nil { + opts = append(opts, WrapCore(func(core zapcore.Core) zapcore.Core { + var samplerOpts []zapcore.SamplerOption + if scfg.Hook != nil { + samplerOpts = append(samplerOpts, zapcore.SamplerHook(scfg.Hook)) + } + return zapcore.NewSamplerWithOptions( + core, + time.Second, + cfg.Sampling.Initial, + cfg.Sampling.Thereafter, + samplerOpts..., + ) + })) + } + + if len(cfg.InitialFields) > 0 { + fs := make([]Field, 0, len(cfg.InitialFields)) + keys := make([]string, 0, len(cfg.InitialFields)) + for k := range cfg.InitialFields { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + fs = append(fs, Any(k, cfg.InitialFields[k])) + } + opts = append(opts, Fields(fs...)) + } + + return opts +} + +func (cfg Config) openSinks() (zapcore.WriteSyncer, zapcore.WriteSyncer, error) { + sink, closeOut, err := Open(cfg.OutputPaths...) + if err != nil { + return nil, nil, err + } + errSink, _, err := Open(cfg.ErrorOutputPaths...) + if err != nil { + closeOut() + return nil, nil, err + } + return sink, errSink, nil +} + +func (cfg Config) buildEncoder() (zapcore.Encoder, error) { + return newEncoder(cfg.Encoding, cfg.EncoderConfig) +} diff --git a/tools/vendor/go.uber.org/zap/doc.go b/tools/vendor/go.uber.org/zap/doc.go new file mode 100644 index 00000000..8638dd1b --- /dev/null +++ b/tools/vendor/go.uber.org/zap/doc.go @@ -0,0 +1,113 @@ +// Copyright (c) 2016 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 zap provides fast, structured, leveled logging. +// +// For applications that log in the hot path, reflection-based serialization +// and string formatting are prohibitively expensive - they're CPU-intensive +// and make many small allocations. Put differently, using json.Marshal and +// fmt.Fprintf to log tons of interface{} makes your application slow. +// +// Zap takes a different approach. It includes a reflection-free, +// zero-allocation JSON encoder, and the base Logger strives to avoid +// serialization overhead and allocations wherever possible. By building the +// high-level SugaredLogger on that foundation, zap lets users choose when +// they need to count every allocation and when they'd prefer a more familiar, +// loosely typed API. +// +// Choosing a Logger +// +// In contexts where performance is nice, but not critical, use the +// SugaredLogger. It's 4-10x faster than other structured logging packages and +// supports both structured and printf-style logging. Like log15 and go-kit, +// the SugaredLogger's structured logging APIs are loosely typed and accept a +// variadic number of key-value pairs. (For more advanced use cases, they also +// accept strongly typed fields - see the SugaredLogger.With documentation for +// details.) +// sugar := zap.NewExample().Sugar() +// defer sugar.Sync() +// sugar.Infow("failed to fetch URL", +// "url", "http://example.com", +// "attempt", 3, +// "backoff", time.Second, +// ) +// sugar.Infof("failed to fetch URL: %s", "http://example.com") +// +// By default, loggers are unbuffered. However, since zap's low-level APIs +// allow buffering, calling Sync before letting your process exit is a good +// habit. +// +// In the rare contexts where every microsecond and every allocation matter, +// use the Logger. It's even faster than the SugaredLogger and allocates far +// less, but it only supports strongly-typed, structured logging. +// logger := zap.NewExample() +// defer logger.Sync() +// logger.Info("failed to fetch URL", +// zap.String("url", "http://example.com"), +// zap.Int("attempt", 3), +// zap.Duration("backoff", time.Second), +// ) +// +// Choosing between the Logger and SugaredLogger doesn't need to be an +// application-wide decision: converting between the two is simple and +// inexpensive. +// logger := zap.NewExample() +// defer logger.Sync() +// sugar := logger.Sugar() +// plain := sugar.Desugar() +// +// Configuring Zap +// +// The simplest way to build a Logger is to use zap's opinionated presets: +// NewExample, NewProduction, and NewDevelopment. These presets build a logger +// with a single function call: +// logger, err := zap.NewProduction() +// if err != nil { +// log.Fatalf("can't initialize zap logger: %v", err) +// } +// defer logger.Sync() +// +// Presets are fine for small projects, but larger projects and organizations +// naturally require a bit more customization. For most users, zap's Config +// struct strikes the right balance between flexibility and convenience. See +// the package-level BasicConfiguration example for sample code. +// +// More unusual configurations (splitting output between files, sending logs +// to a message queue, etc.) are possible, but require direct use of +// go.uber.org/zap/zapcore. See the package-level AdvancedConfiguration +// example for sample code. +// +// Extending Zap +// +// The zap package itself is a relatively thin wrapper around the interfaces +// in go.uber.org/zap/zapcore. Extending zap to support a new encoding (e.g., +// BSON), a new log sink (e.g., Kafka), or something more exotic (perhaps an +// exception aggregation service, like Sentry or Rollbar) typically requires +// implementing the zapcore.Encoder, zapcore.WriteSyncer, or zapcore.Core +// interfaces. See the zapcore documentation for details. +// +// Similarly, package authors can use the high-performance Encoder and Core +// implementations in the zapcore package to build their own loggers. +// +// Frequently Asked Questions +// +// An FAQ covering everything from installation errors to design decisions is +// available at https://github.com/uber-go/zap/blob/master/FAQ.md. +package zap // import "go.uber.org/zap" diff --git a/tools/vendor/go.uber.org/zap/encoder.go b/tools/vendor/go.uber.org/zap/encoder.go new file mode 100644 index 00000000..08ed8335 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/encoder.go @@ -0,0 +1,79 @@ +// Copyright (c) 2016 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 zap + +import ( + "errors" + "fmt" + "sync" + + "go.uber.org/zap/zapcore" +) + +var ( + errNoEncoderNameSpecified = errors.New("no encoder name specified") + + _encoderNameToConstructor = map[string]func(zapcore.EncoderConfig) (zapcore.Encoder, error){ + "console": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { + return zapcore.NewConsoleEncoder(encoderConfig), nil + }, + "json": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { + return zapcore.NewJSONEncoder(encoderConfig), nil + }, + } + _encoderMutex sync.RWMutex +) + +// RegisterEncoder registers an encoder constructor, which the Config struct +// can then reference. By default, the "json" and "console" encoders are +// registered. +// +// Attempting to register an encoder whose name is already taken returns an +// error. +func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapcore.Encoder, error)) error { + _encoderMutex.Lock() + defer _encoderMutex.Unlock() + if name == "" { + return errNoEncoderNameSpecified + } + if _, ok := _encoderNameToConstructor[name]; ok { + return fmt.Errorf("encoder already registered for name %q", name) + } + _encoderNameToConstructor[name] = constructor + return nil +} + +func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { + if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil { + return nil, fmt.Errorf("missing EncodeTime in EncoderConfig") + } + + _encoderMutex.RLock() + defer _encoderMutex.RUnlock() + if name == "" { + return nil, errNoEncoderNameSpecified + } + constructor, ok := _encoderNameToConstructor[name] + if !ok { + return nil, fmt.Errorf("no encoder registered for name %q", name) + } + return constructor(encoderConfig) +} diff --git a/tools/vendor/go.uber.org/zap/error.go b/tools/vendor/go.uber.org/zap/error.go new file mode 100644 index 00000000..65982a51 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/error.go @@ -0,0 +1,80 @@ +// 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 zap + +import ( + "sync" + + "go.uber.org/zap/zapcore" +) + +var _errArrayElemPool = sync.Pool{New: func() interface{} { + return &errArrayElem{} +}} + +// Error is shorthand for the common idiom NamedError("error", err). +func Error(err error) Field { + return NamedError("error", err) +} + +// NamedError constructs a field that lazily stores err.Error() under the +// provided key. Errors which also implement fmt.Formatter (like those produced +// by github.com/pkg/errors) will also have their verbose representation stored +// under key+"Verbose". If passed a nil error, the field is a no-op. +// +// For the common case in which the key is simply "error", the Error function +// is shorter and less repetitive. +func NamedError(key string, err error) Field { + if err == nil { + return Skip() + } + return Field{Key: key, Type: zapcore.ErrorType, Interface: err} +} + +type errArray []error + +func (errs errArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range errs { + if errs[i] == nil { + continue + } + // To represent each error as an object with an "error" attribute and + // potentially an "errorVerbose" attribute, we need to wrap it in a + // type that implements LogObjectMarshaler. To prevent this from + // allocating, pool the wrapper type. + elem := _errArrayElemPool.Get().(*errArrayElem) + elem.error = errs[i] + arr.AppendObject(elem) + elem.error = nil + _errArrayElemPool.Put(elem) + } + return nil +} + +type errArrayElem struct { + error +} + +func (e *errArrayElem) MarshalLogObject(enc zapcore.ObjectEncoder) error { + // Re-use the error field's logic, which supports non-standard error types. + Error(e.error).AddTo(enc) + return nil +} diff --git a/tools/vendor/go.uber.org/zap/field.go b/tools/vendor/go.uber.org/zap/field.go new file mode 100644 index 00000000..bbb745db --- /dev/null +++ b/tools/vendor/go.uber.org/zap/field.go @@ -0,0 +1,549 @@ +// Copyright (c) 2016 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 zap + +import ( + "fmt" + "math" + "time" + + "go.uber.org/zap/zapcore" +) + +// Field is an alias for Field. Aliasing this type dramatically +// improves the navigability of this package's API documentation. +type Field = zapcore.Field + +var ( + _minTimeInt64 = time.Unix(0, math.MinInt64) + _maxTimeInt64 = time.Unix(0, math.MaxInt64) +) + +// Skip constructs a no-op field, which is often useful when handling invalid +// inputs in other Field constructors. +func Skip() Field { + return Field{Type: zapcore.SkipType} +} + +// nilField returns a field which will marshal explicitly as nil. See motivation +// in https://github.com/uber-go/zap/issues/753 . If we ever make breaking +// changes and add zapcore.NilType and zapcore.ObjectEncoder.AddNil, the +// implementation here should be changed to reflect that. +func nilField(key string) Field { return Reflect(key, nil) } + +// Binary constructs a field that carries an opaque binary blob. +// +// Binary data is serialized in an encoding-appropriate format. For example, +// zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text, +// use ByteString. +func Binary(key string, val []byte) Field { + return Field{Key: key, Type: zapcore.BinaryType, Interface: val} +} + +// Bool constructs a field that carries a bool. +func Bool(key string, val bool) Field { + var ival int64 + if val { + ival = 1 + } + return Field{Key: key, Type: zapcore.BoolType, Integer: ival} +} + +// Boolp constructs a field that carries a *bool. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Boolp(key string, val *bool) Field { + if val == nil { + return nilField(key) + } + return Bool(key, *val) +} + +// ByteString constructs a field that carries UTF-8 encoded text as a []byte. +// To log opaque binary blobs (which aren't necessarily valid UTF-8), use +// Binary. +func ByteString(key string, val []byte) Field { + return Field{Key: key, Type: zapcore.ByteStringType, Interface: val} +} + +// Complex128 constructs a field that carries a complex number. Unlike most +// numeric fields, this costs an allocation (to convert the complex128 to +// interface{}). +func Complex128(key string, val complex128) Field { + return Field{Key: key, Type: zapcore.Complex128Type, Interface: val} +} + +// Complex128p constructs a field that carries a *complex128. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Complex128p(key string, val *complex128) Field { + if val == nil { + return nilField(key) + } + return Complex128(key, *val) +} + +// Complex64 constructs a field that carries a complex number. Unlike most +// numeric fields, this costs an allocation (to convert the complex64 to +// interface{}). +func Complex64(key string, val complex64) Field { + return Field{Key: key, Type: zapcore.Complex64Type, Interface: val} +} + +// Complex64p constructs a field that carries a *complex64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Complex64p(key string, val *complex64) Field { + if val == nil { + return nilField(key) + } + return Complex64(key, *val) +} + +// Float64 constructs a field that carries a float64. The way the +// floating-point value is represented is encoder-dependent, so marshaling is +// necessarily lazy. +func Float64(key string, val float64) Field { + return Field{Key: key, Type: zapcore.Float64Type, Integer: int64(math.Float64bits(val))} +} + +// Float64p constructs a field that carries a *float64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Float64p(key string, val *float64) Field { + if val == nil { + return nilField(key) + } + return Float64(key, *val) +} + +// Float32 constructs a field that carries a float32. The way the +// floating-point value is represented is encoder-dependent, so marshaling is +// necessarily lazy. +func Float32(key string, val float32) Field { + return Field{Key: key, Type: zapcore.Float32Type, Integer: int64(math.Float32bits(val))} +} + +// Float32p constructs a field that carries a *float32. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Float32p(key string, val *float32) Field { + if val == nil { + return nilField(key) + } + return Float32(key, *val) +} + +// Int constructs a field with the given key and value. +func Int(key string, val int) Field { + return Int64(key, int64(val)) +} + +// Intp constructs a field that carries a *int. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Intp(key string, val *int) Field { + if val == nil { + return nilField(key) + } + return Int(key, *val) +} + +// Int64 constructs a field with the given key and value. +func Int64(key string, val int64) Field { + return Field{Key: key, Type: zapcore.Int64Type, Integer: val} +} + +// Int64p constructs a field that carries a *int64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int64p(key string, val *int64) Field { + if val == nil { + return nilField(key) + } + return Int64(key, *val) +} + +// Int32 constructs a field with the given key and value. +func Int32(key string, val int32) Field { + return Field{Key: key, Type: zapcore.Int32Type, Integer: int64(val)} +} + +// Int32p constructs a field that carries a *int32. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int32p(key string, val *int32) Field { + if val == nil { + return nilField(key) + } + return Int32(key, *val) +} + +// Int16 constructs a field with the given key and value. +func Int16(key string, val int16) Field { + return Field{Key: key, Type: zapcore.Int16Type, Integer: int64(val)} +} + +// Int16p constructs a field that carries a *int16. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int16p(key string, val *int16) Field { + if val == nil { + return nilField(key) + } + return Int16(key, *val) +} + +// Int8 constructs a field with the given key and value. +func Int8(key string, val int8) Field { + return Field{Key: key, Type: zapcore.Int8Type, Integer: int64(val)} +} + +// Int8p constructs a field that carries a *int8. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Int8p(key string, val *int8) Field { + if val == nil { + return nilField(key) + } + return Int8(key, *val) +} + +// String constructs a field with the given key and value. +func String(key string, val string) Field { + return Field{Key: key, Type: zapcore.StringType, String: val} +} + +// Stringp constructs a field that carries a *string. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Stringp(key string, val *string) Field { + if val == nil { + return nilField(key) + } + return String(key, *val) +} + +// Uint constructs a field with the given key and value. +func Uint(key string, val uint) Field { + return Uint64(key, uint64(val)) +} + +// Uintp constructs a field that carries a *uint. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uintp(key string, val *uint) Field { + if val == nil { + return nilField(key) + } + return Uint(key, *val) +} + +// Uint64 constructs a field with the given key and value. +func Uint64(key string, val uint64) Field { + return Field{Key: key, Type: zapcore.Uint64Type, Integer: int64(val)} +} + +// Uint64p constructs a field that carries a *uint64. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint64p(key string, val *uint64) Field { + if val == nil { + return nilField(key) + } + return Uint64(key, *val) +} + +// Uint32 constructs a field with the given key and value. +func Uint32(key string, val uint32) Field { + return Field{Key: key, Type: zapcore.Uint32Type, Integer: int64(val)} +} + +// Uint32p constructs a field that carries a *uint32. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint32p(key string, val *uint32) Field { + if val == nil { + return nilField(key) + } + return Uint32(key, *val) +} + +// Uint16 constructs a field with the given key and value. +func Uint16(key string, val uint16) Field { + return Field{Key: key, Type: zapcore.Uint16Type, Integer: int64(val)} +} + +// Uint16p constructs a field that carries a *uint16. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint16p(key string, val *uint16) Field { + if val == nil { + return nilField(key) + } + return Uint16(key, *val) +} + +// Uint8 constructs a field with the given key and value. +func Uint8(key string, val uint8) Field { + return Field{Key: key, Type: zapcore.Uint8Type, Integer: int64(val)} +} + +// Uint8p constructs a field that carries a *uint8. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uint8p(key string, val *uint8) Field { + if val == nil { + return nilField(key) + } + return Uint8(key, *val) +} + +// Uintptr constructs a field with the given key and value. +func Uintptr(key string, val uintptr) Field { + return Field{Key: key, Type: zapcore.UintptrType, Integer: int64(val)} +} + +// Uintptrp constructs a field that carries a *uintptr. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Uintptrp(key string, val *uintptr) Field { + if val == nil { + return nilField(key) + } + return Uintptr(key, *val) +} + +// Reflect constructs a field with the given key and an arbitrary object. It uses +// an encoding-appropriate, reflection-based function to lazily serialize nearly +// any object into the logging context, but it's relatively slow and +// allocation-heavy. Outside tests, Any is always a better choice. +// +// If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect +// includes the error message in the final log output. +func Reflect(key string, val interface{}) Field { + return Field{Key: key, Type: zapcore.ReflectType, Interface: val} +} + +// Namespace creates a named, isolated scope within the logger's context. All +// subsequent fields will be added to the new namespace. +// +// This helps prevent key collisions when injecting loggers into sub-components +// or third-party libraries. +func Namespace(key string) Field { + return Field{Key: key, Type: zapcore.NamespaceType} +} + +// Stringer constructs a field with the given key and the output of the value's +// String method. The Stringer's String method is called lazily. +func Stringer(key string, val fmt.Stringer) Field { + return Field{Key: key, Type: zapcore.StringerType, Interface: val} +} + +// Time constructs a Field with the given key and value. The encoder +// controls how the time is serialized. +func Time(key string, val time.Time) Field { + if val.Before(_minTimeInt64) || val.After(_maxTimeInt64) { + return Field{Key: key, Type: zapcore.TimeFullType, Interface: val} + } + return Field{Key: key, Type: zapcore.TimeType, Integer: val.UnixNano(), Interface: val.Location()} +} + +// Timep constructs a field that carries a *time.Time. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Timep(key string, val *time.Time) Field { + if val == nil { + return nilField(key) + } + return Time(key, *val) +} + +// Stack constructs a field that stores a stacktrace of the current goroutine +// under provided key. Keep in mind that taking a stacktrace is eager and +// expensive (relatively speaking); this function both makes an allocation and +// takes about two microseconds. +func Stack(key string) Field { + return StackSkip(key, 1) // skip Stack +} + +// StackSkip constructs a field similarly to Stack, but also skips the given +// number of frames from the top of the stacktrace. +func StackSkip(key string, skip int) Field { + // Returning the stacktrace as a string costs an allocation, but saves us + // from expanding the zapcore.Field union struct to include a byte slice. Since + // taking a stacktrace is already so expensive (~10us), the extra allocation + // is okay. + return String(key, takeStacktrace(skip+1)) // skip StackSkip +} + +// Duration constructs a field with the given key and value. The encoder +// controls how the duration is serialized. +func Duration(key string, val time.Duration) Field { + return Field{Key: key, Type: zapcore.DurationType, Integer: int64(val)} +} + +// Durationp constructs a field that carries a *time.Duration. The returned Field will safely +// and explicitly represent `nil` when appropriate. +func Durationp(key string, val *time.Duration) Field { + if val == nil { + return nilField(key) + } + return Duration(key, *val) +} + +// Object constructs a field with the given key and ObjectMarshaler. It +// provides a flexible, but still type-safe and efficient, way to add map- or +// struct-like user-defined types to the logging context. The struct's +// MarshalLogObject method is called lazily. +func Object(key string, val zapcore.ObjectMarshaler) Field { + return Field{Key: key, Type: zapcore.ObjectMarshalerType, Interface: val} +} + +// Inline constructs a Field that is similar to Object, but it +// will add the elements of the provided ObjectMarshaler to the +// current namespace. +func Inline(val zapcore.ObjectMarshaler) Field { + return zapcore.Field{ + Type: zapcore.InlineMarshalerType, + Interface: val, + } +} + +// Any takes a key and an arbitrary value and chooses the best way to represent +// them as a field, falling back to a reflection-based approach only if +// necessary. +// +// Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between +// them. To minimize surprises, []byte values are treated as binary blobs, byte +// values are treated as uint8, and runes are always treated as integers. +func Any(key string, value interface{}) Field { + switch val := value.(type) { + case zapcore.ObjectMarshaler: + return Object(key, val) + case zapcore.ArrayMarshaler: + return Array(key, val) + case bool: + return Bool(key, val) + case *bool: + return Boolp(key, val) + case []bool: + return Bools(key, val) + case complex128: + return Complex128(key, val) + case *complex128: + return Complex128p(key, val) + case []complex128: + return Complex128s(key, val) + case complex64: + return Complex64(key, val) + case *complex64: + return Complex64p(key, val) + case []complex64: + return Complex64s(key, val) + case float64: + return Float64(key, val) + case *float64: + return Float64p(key, val) + case []float64: + return Float64s(key, val) + case float32: + return Float32(key, val) + case *float32: + return Float32p(key, val) + case []float32: + return Float32s(key, val) + case int: + return Int(key, val) + case *int: + return Intp(key, val) + case []int: + return Ints(key, val) + case int64: + return Int64(key, val) + case *int64: + return Int64p(key, val) + case []int64: + return Int64s(key, val) + case int32: + return Int32(key, val) + case *int32: + return Int32p(key, val) + case []int32: + return Int32s(key, val) + case int16: + return Int16(key, val) + case *int16: + return Int16p(key, val) + case []int16: + return Int16s(key, val) + case int8: + return Int8(key, val) + case *int8: + return Int8p(key, val) + case []int8: + return Int8s(key, val) + case string: + return String(key, val) + case *string: + return Stringp(key, val) + case []string: + return Strings(key, val) + case uint: + return Uint(key, val) + case *uint: + return Uintp(key, val) + case []uint: + return Uints(key, val) + case uint64: + return Uint64(key, val) + case *uint64: + return Uint64p(key, val) + case []uint64: + return Uint64s(key, val) + case uint32: + return Uint32(key, val) + case *uint32: + return Uint32p(key, val) + case []uint32: + return Uint32s(key, val) + case uint16: + return Uint16(key, val) + case *uint16: + return Uint16p(key, val) + case []uint16: + return Uint16s(key, val) + case uint8: + return Uint8(key, val) + case *uint8: + return Uint8p(key, val) + case []byte: + return Binary(key, val) + case uintptr: + return Uintptr(key, val) + case *uintptr: + return Uintptrp(key, val) + case []uintptr: + return Uintptrs(key, val) + case time.Time: + return Time(key, val) + case *time.Time: + return Timep(key, val) + case []time.Time: + return Times(key, val) + case time.Duration: + return Duration(key, val) + case *time.Duration: + return Durationp(key, val) + case []time.Duration: + return Durations(key, val) + case error: + return NamedError(key, val) + case []error: + return Errors(key, val) + case fmt.Stringer: + return Stringer(key, val) + default: + return Reflect(key, val) + } +} diff --git a/tools/vendor/go.uber.org/zap/flag.go b/tools/vendor/go.uber.org/zap/flag.go new file mode 100644 index 00000000..13128750 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/flag.go @@ -0,0 +1,39 @@ +// Copyright (c) 2016 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 zap + +import ( + "flag" + + "go.uber.org/zap/zapcore" +) + +// LevelFlag uses the standard library's flag.Var to declare a global flag +// with the specified name, default, and usage guidance. The returned value is +// a pointer to the value of the flag. +// +// If you don't want to use the flag package's global state, you can use any +// non-nil *Level as a flag.Value with your own *flag.FlagSet. +func LevelFlag(name string, defaultLevel zapcore.Level, usage string) *zapcore.Level { + lvl := defaultLevel + flag.Var(&lvl, name, usage) + return &lvl +} diff --git a/tools/vendor/go.uber.org/zap/glide.yaml b/tools/vendor/go.uber.org/zap/glide.yaml new file mode 100644 index 00000000..8e1d05e9 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/glide.yaml @@ -0,0 +1,34 @@ +package: go.uber.org/zap +license: MIT +import: +- package: go.uber.org/atomic + version: ^1 +- package: go.uber.org/multierr + version: ^1 +testImport: +- package: github.com/satori/go.uuid +- package: github.com/sirupsen/logrus +- package: github.com/apex/log + subpackages: + - handlers/json +- package: github.com/go-kit/kit + subpackages: + - log +- package: github.com/stretchr/testify + subpackages: + - assert + - require +- package: gopkg.in/inconshreveable/log15.v2 +- package: github.com/mattn/goveralls +- package: github.com/pborman/uuid +- package: github.com/pkg/errors +- package: github.com/rs/zerolog +- package: golang.org/x/tools + subpackages: + - cover +- package: golang.org/x/lint + subpackages: + - golint +- package: github.com/axw/gocov + subpackages: + - gocov diff --git a/tools/vendor/go.uber.org/zap/global.go b/tools/vendor/go.uber.org/zap/global.go new file mode 100644 index 00000000..3cb46c9e --- /dev/null +++ b/tools/vendor/go.uber.org/zap/global.go @@ -0,0 +1,169 @@ +// Copyright (c) 2016 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 zap + +import ( + "bytes" + "fmt" + "log" + "os" + "sync" + + "go.uber.org/zap/zapcore" +) + +const ( + _stdLogDefaultDepth = 1 + _loggerWriterDepth = 2 + _programmerErrorTemplate = "You've found a bug in zap! Please file a bug at " + + "https://github.com/uber-go/zap/issues/new and reference this error: %v" +) + +var ( + _globalMu sync.RWMutex + _globalL = NewNop() + _globalS = _globalL.Sugar() +) + +// L returns the global Logger, which can be reconfigured with ReplaceGlobals. +// It's safe for concurrent use. +func L() *Logger { + _globalMu.RLock() + l := _globalL + _globalMu.RUnlock() + return l +} + +// S returns the global SugaredLogger, which can be reconfigured with +// ReplaceGlobals. It's safe for concurrent use. +func S() *SugaredLogger { + _globalMu.RLock() + s := _globalS + _globalMu.RUnlock() + return s +} + +// ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a +// function to restore the original values. It's safe for concurrent use. +func ReplaceGlobals(logger *Logger) func() { + _globalMu.Lock() + prev := _globalL + _globalL = logger + _globalS = logger.Sugar() + _globalMu.Unlock() + return func() { ReplaceGlobals(prev) } +} + +// NewStdLog returns a *log.Logger which writes to the supplied zap Logger at +// InfoLevel. To redirect the standard library's package-global logging +// functions, use RedirectStdLog instead. +func NewStdLog(l *Logger) *log.Logger { + logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) + f := logger.Info + return log.New(&loggerWriter{f}, "" /* prefix */, 0 /* flags */) +} + +// NewStdLogAt returns *log.Logger which writes to supplied zap logger at +// required level. +func NewStdLogAt(l *Logger, level zapcore.Level) (*log.Logger, error) { + logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) + logFunc, err := levelToFunc(logger, level) + if err != nil { + return nil, err + } + return log.New(&loggerWriter{logFunc}, "" /* prefix */, 0 /* flags */), nil +} + +// RedirectStdLog redirects output from the standard library's package-global +// logger to the supplied logger at InfoLevel. Since zap already handles caller +// annotations, timestamps, etc., it automatically disables the standard +// library's annotations and prefixing. +// +// It returns a function to restore the original prefix and flags and reset the +// standard library's output to os.Stderr. +func RedirectStdLog(l *Logger) func() { + f, err := redirectStdLogAt(l, InfoLevel) + if err != nil { + // Can't get here, since passing InfoLevel to redirectStdLogAt always + // works. + panic(fmt.Sprintf(_programmerErrorTemplate, err)) + } + return f +} + +// RedirectStdLogAt redirects output from the standard library's package-global +// logger to the supplied logger at the specified level. Since zap already +// handles caller annotations, timestamps, etc., it automatically disables the +// standard library's annotations and prefixing. +// +// It returns a function to restore the original prefix and flags and reset the +// standard library's output to os.Stderr. +func RedirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) { + return redirectStdLogAt(l, level) +} + +func redirectStdLogAt(l *Logger, level zapcore.Level) (func(), error) { + flags := log.Flags() + prefix := log.Prefix() + log.SetFlags(0) + log.SetPrefix("") + logger := l.WithOptions(AddCallerSkip(_stdLogDefaultDepth + _loggerWriterDepth)) + logFunc, err := levelToFunc(logger, level) + if err != nil { + return nil, err + } + log.SetOutput(&loggerWriter{logFunc}) + return func() { + log.SetFlags(flags) + log.SetPrefix(prefix) + log.SetOutput(os.Stderr) + }, nil +} + +func levelToFunc(logger *Logger, lvl zapcore.Level) (func(string, ...Field), error) { + switch lvl { + case DebugLevel: + return logger.Debug, nil + case InfoLevel: + return logger.Info, nil + case WarnLevel: + return logger.Warn, nil + case ErrorLevel: + return logger.Error, nil + case DPanicLevel: + return logger.DPanic, nil + case PanicLevel: + return logger.Panic, nil + case FatalLevel: + return logger.Fatal, nil + } + return nil, fmt.Errorf("unrecognized level: %q", lvl) +} + +type loggerWriter struct { + logFunc func(msg string, fields ...Field) +} + +func (l *loggerWriter) Write(p []byte) (int, error) { + p = bytes.TrimSpace(p) + l.logFunc(string(p)) + return len(p), nil +} diff --git a/tools/vendor/go.uber.org/zap/http_handler.go b/tools/vendor/go.uber.org/zap/http_handler.go new file mode 100644 index 00000000..1297c33b --- /dev/null +++ b/tools/vendor/go.uber.org/zap/http_handler.go @@ -0,0 +1,132 @@ +// Copyright (c) 2016 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 zap + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "go.uber.org/zap/zapcore" +) + +// ServeHTTP is a simple JSON endpoint that can report on or change the current +// logging level. +// +// GET +// +// The GET request returns a JSON description of the current logging level like: +// {"level":"info"} +// +// PUT +// +// The PUT request changes the logging level. It is perfectly safe to change the +// logging level while a program is running. Two content types are supported: +// +// Content-Type: application/x-www-form-urlencoded +// +// With this content type, the level can be provided through the request body or +// a query parameter. The log level is URL encoded like: +// +// level=debug +// +// The request body takes precedence over the query parameter, if both are +// specified. +// +// This content type is the default for a curl PUT request. Following are two +// example curl requests that both set the logging level to debug. +// +// curl -X PUT localhost:8080/log/level?level=debug +// curl -X PUT localhost:8080/log/level -d level=debug +// +// For any other content type, the payload is expected to be JSON encoded and +// look like: +// +// {"level":"info"} +// +// An example curl request could look like this: +// +// curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}' +// +func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) { + type errorResponse struct { + Error string `json:"error"` + } + type payload struct { + Level zapcore.Level `json:"level"` + } + + enc := json.NewEncoder(w) + + switch r.Method { + case http.MethodGet: + enc.Encode(payload{Level: lvl.Level()}) + case http.MethodPut: + requestedLvl, err := decodePutRequest(r.Header.Get("Content-Type"), r) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + enc.Encode(errorResponse{Error: err.Error()}) + return + } + lvl.SetLevel(requestedLvl) + enc.Encode(payload{Level: lvl.Level()}) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + enc.Encode(errorResponse{ + Error: "Only GET and PUT are supported.", + }) + } +} + +// Decodes incoming PUT requests and returns the requested logging level. +func decodePutRequest(contentType string, r *http.Request) (zapcore.Level, error) { + if contentType == "application/x-www-form-urlencoded" { + return decodePutURL(r) + } + return decodePutJSON(r.Body) +} + +func decodePutURL(r *http.Request) (zapcore.Level, error) { + lvl := r.FormValue("level") + if lvl == "" { + return 0, fmt.Errorf("must specify logging level") + } + var l zapcore.Level + if err := l.UnmarshalText([]byte(lvl)); err != nil { + return 0, err + } + return l, nil +} + +func decodePutJSON(body io.Reader) (zapcore.Level, error) { + var pld struct { + Level *zapcore.Level `json:"level"` + } + if err := json.NewDecoder(body).Decode(&pld); err != nil { + return 0, fmt.Errorf("malformed request body: %v", err) + } + if pld.Level == nil { + return 0, fmt.Errorf("must specify logging level") + } + return *pld.Level, nil + +} diff --git a/tools/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go b/tools/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go new file mode 100644 index 00000000..dad583aa --- /dev/null +++ b/tools/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go @@ -0,0 +1,31 @@ +// Copyright (c) 2016 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 bufferpool houses zap's shared internal buffer pool. Third-party +// packages can recreate the same functionality with buffers.NewPool. +package bufferpool + +import "go.uber.org/zap/buffer" + +var ( + _pool = buffer.NewPool() + // Get retrieves a buffer from the pool, creating one if necessary. + Get = _pool.Get +) diff --git a/tools/vendor/go.uber.org/zap/internal/color/color.go b/tools/vendor/go.uber.org/zap/internal/color/color.go new file mode 100644 index 00000000..c4d5d02a --- /dev/null +++ b/tools/vendor/go.uber.org/zap/internal/color/color.go @@ -0,0 +1,44 @@ +// Copyright (c) 2016 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 color adds coloring functionality for TTY output. +package color + +import "fmt" + +// Foreground colors. +const ( + Black Color = iota + 30 + Red + Green + Yellow + Blue + Magenta + Cyan + White +) + +// Color represents a text color. +type Color uint8 + +// Add adds the coloring to the given string. +func (c Color) Add(s string) string { + return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), s) +} diff --git a/tools/vendor/go.uber.org/zap/internal/exit/exit.go b/tools/vendor/go.uber.org/zap/internal/exit/exit.go new file mode 100644 index 00000000..dfc5b05f --- /dev/null +++ b/tools/vendor/go.uber.org/zap/internal/exit/exit.go @@ -0,0 +1,64 @@ +// Copyright (c) 2016 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 exit provides stubs so that unit tests can exercise code that calls +// os.Exit(1). +package exit + +import "os" + +var real = func() { os.Exit(1) } + +// Exit normally terminates the process by calling os.Exit(1). If the package +// is stubbed, it instead records a call in the testing spy. +func Exit() { + real() +} + +// A StubbedExit is a testing fake for os.Exit. +type StubbedExit struct { + Exited bool + prev func() +} + +// Stub substitutes a fake for the call to os.Exit(1). +func Stub() *StubbedExit { + s := &StubbedExit{prev: real} + real = s.exit + return s +} + +// WithStub runs the supplied function with Exit stubbed. It returns the stub +// used, so that users can test whether the process would have crashed. +func WithStub(f func()) *StubbedExit { + s := Stub() + defer s.Unstub() + f() + return s +} + +// Unstub restores the previous exit function. +func (se *StubbedExit) Unstub() { + real = se.prev +} + +func (se *StubbedExit) exit() { + se.Exited = true +} diff --git a/tools/vendor/go.uber.org/zap/level.go b/tools/vendor/go.uber.org/zap/level.go new file mode 100644 index 00000000..8f86c430 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/level.go @@ -0,0 +1,149 @@ +// Copyright (c) 2016 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 zap + +import ( + "go.uber.org/atomic" + "go.uber.org/zap/zapcore" +) + +const ( + // DebugLevel logs are typically voluminous, and are usually disabled in + // production. + DebugLevel = zapcore.DebugLevel + // InfoLevel is the default logging priority. + InfoLevel = zapcore.InfoLevel + // WarnLevel logs are more important than Info, but don't need individual + // human review. + WarnLevel = zapcore.WarnLevel + // ErrorLevel logs are high-priority. If an application is running smoothly, + // it shouldn't generate any error-level logs. + ErrorLevel = zapcore.ErrorLevel + // DPanicLevel logs are particularly important errors. In development the + // logger panics after writing the message. + DPanicLevel = zapcore.DPanicLevel + // PanicLevel logs a message, then panics. + PanicLevel = zapcore.PanicLevel + // FatalLevel logs a message, then calls os.Exit(1). + FatalLevel = zapcore.FatalLevel +) + +// LevelEnablerFunc is a convenient way to implement zapcore.LevelEnabler with +// an anonymous function. +// +// It's particularly useful when splitting log output between different +// outputs (e.g., standard error and standard out). For sample code, see the +// package-level AdvancedConfiguration example. +type LevelEnablerFunc func(zapcore.Level) bool + +// Enabled calls the wrapped function. +func (f LevelEnablerFunc) Enabled(lvl zapcore.Level) bool { return f(lvl) } + +// An AtomicLevel is an atomically changeable, dynamic logging level. It lets +// you safely change the log level of a tree of loggers (the root logger and +// any children created by adding context) at runtime. +// +// The AtomicLevel itself is an http.Handler that serves a JSON endpoint to +// alter its level. +// +// AtomicLevels must be created with the NewAtomicLevel constructor to allocate +// their internal atomic pointer. +type AtomicLevel struct { + l *atomic.Int32 +} + +// NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging +// enabled. +func NewAtomicLevel() AtomicLevel { + return AtomicLevel{ + l: atomic.NewInt32(int32(InfoLevel)), + } +} + +// NewAtomicLevelAt is a convenience function that creates an AtomicLevel +// and then calls SetLevel with the given level. +func NewAtomicLevelAt(l zapcore.Level) AtomicLevel { + a := NewAtomicLevel() + a.SetLevel(l) + return a +} + +// ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCII +// representation of the log level. If the provided ASCII representation is +// invalid an error is returned. +// +// This is particularly useful when dealing with text input to configure log +// levels. +func ParseAtomicLevel(text string) (AtomicLevel, error) { + a := NewAtomicLevel() + l, err := zapcore.ParseLevel(text) + if err != nil { + return a, err + } + + a.SetLevel(l) + return a, nil +} + +// Enabled implements the zapcore.LevelEnabler interface, which allows the +// AtomicLevel to be used in place of traditional static levels. +func (lvl AtomicLevel) Enabled(l zapcore.Level) bool { + return lvl.Level().Enabled(l) +} + +// Level returns the minimum enabled log level. +func (lvl AtomicLevel) Level() zapcore.Level { + return zapcore.Level(int8(lvl.l.Load())) +} + +// SetLevel alters the logging level. +func (lvl AtomicLevel) SetLevel(l zapcore.Level) { + lvl.l.Store(int32(l)) +} + +// String returns the string representation of the underlying Level. +func (lvl AtomicLevel) String() string { + return lvl.Level().String() +} + +// UnmarshalText unmarshals the text to an AtomicLevel. It uses the same text +// representations as the static zapcore.Levels ("debug", "info", "warn", +// "error", "dpanic", "panic", and "fatal"). +func (lvl *AtomicLevel) UnmarshalText(text []byte) error { + if lvl.l == nil { + lvl.l = &atomic.Int32{} + } + + var l zapcore.Level + if err := l.UnmarshalText(text); err != nil { + return err + } + + lvl.SetLevel(l) + return nil +} + +// MarshalText marshals the AtomicLevel to a byte slice. It uses the same +// text representation as the static zapcore.Levels ("debug", "info", "warn", +// "error", "dpanic", "panic", and "fatal"). +func (lvl AtomicLevel) MarshalText() (text []byte, err error) { + return lvl.Level().MarshalText() +} diff --git a/tools/vendor/go.uber.org/zap/logger.go b/tools/vendor/go.uber.org/zap/logger.go new file mode 100644 index 00000000..087c7422 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/logger.go @@ -0,0 +1,363 @@ +// Copyright (c) 2016 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 zap + +import ( + "fmt" + "io/ioutil" + "os" + "strings" + + "go.uber.org/zap/internal/bufferpool" + "go.uber.org/zap/zapcore" +) + +// A Logger provides fast, leveled, structured logging. All methods are safe +// for concurrent use. +// +// The Logger is designed for contexts in which every microsecond and every +// allocation matters, so its API intentionally favors performance and type +// safety over brevity. For most applications, the SugaredLogger strikes a +// better balance between performance and ergonomics. +type Logger struct { + core zapcore.Core + + development bool + addCaller bool + onFatal zapcore.CheckWriteAction // default is WriteThenFatal + + name string + errorOutput zapcore.WriteSyncer + + addStack zapcore.LevelEnabler + + callerSkip int + + clock zapcore.Clock +} + +// New constructs a new Logger from the provided zapcore.Core and Options. If +// the passed zapcore.Core is nil, it falls back to using a no-op +// implementation. +// +// This is the most flexible way to construct a Logger, but also the most +// verbose. For typical use cases, the highly-opinionated presets +// (NewProduction, NewDevelopment, and NewExample) or the Config struct are +// more convenient. +// +// For sample code, see the package-level AdvancedConfiguration example. +func New(core zapcore.Core, options ...Option) *Logger { + if core == nil { + return NewNop() + } + log := &Logger{ + core: core, + errorOutput: zapcore.Lock(os.Stderr), + addStack: zapcore.FatalLevel + 1, + clock: zapcore.DefaultClock, + } + return log.WithOptions(options...) +} + +// NewNop returns a no-op Logger. It never writes out logs or internal errors, +// and it never runs user-defined hooks. +// +// Using WithOptions to replace the Core or error output of a no-op Logger can +// re-enable logging. +func NewNop() *Logger { + return &Logger{ + core: zapcore.NewNopCore(), + errorOutput: zapcore.AddSync(ioutil.Discard), + addStack: zapcore.FatalLevel + 1, + clock: zapcore.DefaultClock, + } +} + +// NewProduction builds a sensible production Logger that writes InfoLevel and +// above logs to standard error as JSON. +// +// It's a shortcut for NewProductionConfig().Build(...Option). +func NewProduction(options ...Option) (*Logger, error) { + return NewProductionConfig().Build(options...) +} + +// NewDevelopment builds a development Logger that writes DebugLevel and above +// logs to standard error in a human-friendly format. +// +// It's a shortcut for NewDevelopmentConfig().Build(...Option). +func NewDevelopment(options ...Option) (*Logger, error) { + return NewDevelopmentConfig().Build(options...) +} + +// NewExample builds a Logger that's designed for use in zap's testable +// examples. It writes DebugLevel and above logs to standard out as JSON, but +// omits the timestamp and calling function to keep example output +// short and deterministic. +func NewExample(options ...Option) *Logger { + encoderCfg := zapcore.EncoderConfig{ + MessageKey: "msg", + LevelKey: "level", + NameKey: "logger", + EncodeLevel: zapcore.LowercaseLevelEncoder, + EncodeTime: zapcore.ISO8601TimeEncoder, + EncodeDuration: zapcore.StringDurationEncoder, + } + core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg), os.Stdout, DebugLevel) + return New(core).WithOptions(options...) +} + +// Sugar wraps the Logger to provide a more ergonomic, but slightly slower, +// API. Sugaring a Logger is quite inexpensive, so it's reasonable for a +// single application to use both Loggers and SugaredLoggers, converting +// between them on the boundaries of performance-sensitive code. +func (log *Logger) Sugar() *SugaredLogger { + core := log.clone() + core.callerSkip += 2 + return &SugaredLogger{core} +} + +// Named adds a new path segment to the logger's name. Segments are joined by +// periods. By default, Loggers are unnamed. +func (log *Logger) Named(s string) *Logger { + if s == "" { + return log + } + l := log.clone() + if log.name == "" { + l.name = s + } else { + l.name = strings.Join([]string{l.name, s}, ".") + } + return l +} + +// WithOptions clones the current Logger, applies the supplied Options, and +// returns the resulting Logger. It's safe to use concurrently. +func (log *Logger) WithOptions(opts ...Option) *Logger { + c := log.clone() + for _, opt := range opts { + opt.apply(c) + } + return c +} + +// With creates a child logger and adds structured context to it. Fields added +// to the child don't affect the parent, and vice versa. +func (log *Logger) With(fields ...Field) *Logger { + if len(fields) == 0 { + return log + } + l := log.clone() + l.core = l.core.With(fields) + return l +} + +// Check returns a CheckedEntry if logging a message at the specified level +// is enabled. It's a completely optional optimization; in high-performance +// applications, Check can help avoid allocating a slice to hold fields. +func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { + return log.check(lvl, msg) +} + +// Debug logs a message at DebugLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Debug(msg string, fields ...Field) { + if ce := log.check(DebugLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Info logs a message at InfoLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Info(msg string, fields ...Field) { + if ce := log.check(InfoLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Warn logs a message at WarnLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Warn(msg string, fields ...Field) { + if ce := log.check(WarnLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Error logs a message at ErrorLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +func (log *Logger) Error(msg string, fields ...Field) { + if ce := log.check(ErrorLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// DPanic logs a message at DPanicLevel. The message includes any fields +// passed at the log site, as well as any fields accumulated on the logger. +// +// If the logger is in development mode, it then panics (DPanic means +// "development panic"). This is useful for catching errors that are +// recoverable, but shouldn't ever happen. +func (log *Logger) DPanic(msg string, fields ...Field) { + if ce := log.check(DPanicLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Panic logs a message at PanicLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +// +// The logger then panics, even if logging at PanicLevel is disabled. +func (log *Logger) Panic(msg string, fields ...Field) { + if ce := log.check(PanicLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Fatal logs a message at FatalLevel. The message includes any fields passed +// at the log site, as well as any fields accumulated on the logger. +// +// The logger then calls os.Exit(1), even if logging at FatalLevel is +// disabled. +func (log *Logger) Fatal(msg string, fields ...Field) { + if ce := log.check(FatalLevel, msg); ce != nil { + ce.Write(fields...) + } +} + +// Sync calls the underlying Core's Sync method, flushing any buffered log +// entries. Applications should take care to call Sync before exiting. +func (log *Logger) Sync() error { + return log.core.Sync() +} + +// Core returns the Logger's underlying zapcore.Core. +func (log *Logger) Core() zapcore.Core { + return log.core +} + +func (log *Logger) clone() *Logger { + copy := *log + return © +} + +func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { + // Logger.check must always be called directly by a method in the + // Logger interface (e.g., Check, Info, Fatal). + // This skips Logger.check and the Info/Fatal/Check/etc. method that + // called it. + const callerSkipOffset = 2 + + // Check the level first to reduce the cost of disabled log calls. + // Since Panic and higher may exit, we skip the optimization for those levels. + if lvl < zapcore.DPanicLevel && !log.core.Enabled(lvl) { + return nil + } + + // Create basic checked entry thru the core; this will be non-nil if the + // log message will actually be written somewhere. + ent := zapcore.Entry{ + LoggerName: log.name, + Time: log.clock.Now(), + Level: lvl, + Message: msg, + } + ce := log.core.Check(ent, nil) + willWrite := ce != nil + + // Set up any required terminal behavior. + switch ent.Level { + case zapcore.PanicLevel: + ce = ce.Should(ent, zapcore.WriteThenPanic) + case zapcore.FatalLevel: + onFatal := log.onFatal + // Noop is the default value for CheckWriteAction, and it leads to + // continued execution after a Fatal which is unexpected. + if onFatal == zapcore.WriteThenNoop { + onFatal = zapcore.WriteThenFatal + } + ce = ce.Should(ent, onFatal) + case zapcore.DPanicLevel: + if log.development { + ce = ce.Should(ent, zapcore.WriteThenPanic) + } + } + + // Only do further annotation if we're going to write this message; checked + // entries that exist only for terminal behavior don't benefit from + // annotation. + if !willWrite { + return ce + } + + // Thread the error output through to the CheckedEntry. + ce.ErrorOutput = log.errorOutput + + addStack := log.addStack.Enabled(ce.Level) + if !log.addCaller && !addStack { + return ce + } + + // Adding the caller or stack trace requires capturing the callers of + // this function. We'll share information between these two. + stackDepth := stacktraceFirst + if addStack { + stackDepth = stacktraceFull + } + stack := captureStacktrace(log.callerSkip+callerSkipOffset, stackDepth) + defer stack.Free() + + if stack.Count() == 0 { + if log.addCaller { + fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", ent.Time.UTC()) + log.errorOutput.Sync() + } + return ce + } + + frame, more := stack.Next() + + if log.addCaller { + ce.Caller = zapcore.EntryCaller{ + Defined: frame.PC != 0, + PC: frame.PC, + File: frame.File, + Line: frame.Line, + Function: frame.Function, + } + } + + if addStack { + buffer := bufferpool.Get() + defer buffer.Free() + + stackfmt := newStackFormatter(buffer) + + // We've already extracted the first frame, so format that + // separately and defer to stackfmt for the rest. + stackfmt.FormatFrame(frame) + if more { + stackfmt.FormatStack(stack) + } + ce.Stack = buffer.String() + } + + return ce +} diff --git a/tools/vendor/go.uber.org/zap/options.go b/tools/vendor/go.uber.org/zap/options.go new file mode 100644 index 00000000..e9e66161 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/options.go @@ -0,0 +1,148 @@ +// Copyright (c) 2016 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 zap + +import ( + "fmt" + + "go.uber.org/zap/zapcore" +) + +// An Option configures a Logger. +type Option interface { + apply(*Logger) +} + +// optionFunc wraps a func so it satisfies the Option interface. +type optionFunc func(*Logger) + +func (f optionFunc) apply(log *Logger) { + f(log) +} + +// WrapCore wraps or replaces the Logger's underlying zapcore.Core. +func WrapCore(f func(zapcore.Core) zapcore.Core) Option { + return optionFunc(func(log *Logger) { + log.core = f(log.core) + }) +} + +// Hooks registers functions which will be called each time the Logger writes +// out an Entry. Repeated use of Hooks is additive. +// +// Hooks are useful for simple side effects, like capturing metrics for the +// number of emitted logs. More complex side effects, including anything that +// requires access to the Entry's structured fields, should be implemented as +// a zapcore.Core instead. See zapcore.RegisterHooks for details. +func Hooks(hooks ...func(zapcore.Entry) error) Option { + return optionFunc(func(log *Logger) { + log.core = zapcore.RegisterHooks(log.core, hooks...) + }) +} + +// Fields adds fields to the Logger. +func Fields(fs ...Field) Option { + return optionFunc(func(log *Logger) { + log.core = log.core.With(fs) + }) +} + +// ErrorOutput sets the destination for errors generated by the Logger. Note +// that this option only affects internal errors; for sample code that sends +// error-level logs to a different location from info- and debug-level logs, +// see the package-level AdvancedConfiguration example. +// +// The supplied WriteSyncer must be safe for concurrent use. The Open and +// zapcore.Lock functions are the simplest ways to protect files with a mutex. +func ErrorOutput(w zapcore.WriteSyncer) Option { + return optionFunc(func(log *Logger) { + log.errorOutput = w + }) +} + +// Development puts the logger in development mode, which makes DPanic-level +// logs panic instead of simply logging an error. +func Development() Option { + return optionFunc(func(log *Logger) { + log.development = true + }) +} + +// AddCaller configures the Logger to annotate each message with the filename, +// line number, and function name of zap's caller. See also WithCaller. +func AddCaller() Option { + return WithCaller(true) +} + +// WithCaller configures the Logger to annotate each message with the filename, +// line number, and function name of zap's caller, or not, depending on the +// value of enabled. This is a generalized form of AddCaller. +func WithCaller(enabled bool) Option { + return optionFunc(func(log *Logger) { + log.addCaller = enabled + }) +} + +// AddCallerSkip increases the number of callers skipped by caller annotation +// (as enabled by the AddCaller option). When building wrappers around the +// Logger and SugaredLogger, supplying this Option prevents zap from always +// reporting the wrapper code as the caller. +func AddCallerSkip(skip int) Option { + return optionFunc(func(log *Logger) { + log.callerSkip += skip + }) +} + +// AddStacktrace configures the Logger to record a stack trace for all messages at +// or above a given level. +func AddStacktrace(lvl zapcore.LevelEnabler) Option { + return optionFunc(func(log *Logger) { + log.addStack = lvl + }) +} + +// IncreaseLevel increase the level of the logger. It has no effect if +// the passed in level tries to decrease the level of the logger. +func IncreaseLevel(lvl zapcore.LevelEnabler) Option { + return optionFunc(func(log *Logger) { + core, err := zapcore.NewIncreaseLevelCore(log.core, lvl) + if err != nil { + fmt.Fprintf(log.errorOutput, "failed to IncreaseLevel: %v\n", err) + } else { + log.core = core + } + }) +} + +// OnFatal sets the action to take on fatal logs. +func OnFatal(action zapcore.CheckWriteAction) Option { + return optionFunc(func(log *Logger) { + log.onFatal = action + }) +} + +// WithClock specifies the clock used by the logger to determine the current +// time for logged entries. Defaults to the system clock with time.Now. +func WithClock(clock zapcore.Clock) Option { + return optionFunc(func(log *Logger) { + log.clock = clock + }) +} diff --git a/tools/vendor/go.uber.org/zap/sink.go b/tools/vendor/go.uber.org/zap/sink.go new file mode 100644 index 00000000..df46fa87 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/sink.go @@ -0,0 +1,161 @@ +// Copyright (c) 2016 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 zap + +import ( + "errors" + "fmt" + "io" + "net/url" + "os" + "strings" + "sync" + + "go.uber.org/zap/zapcore" +) + +const schemeFile = "file" + +var ( + _sinkMutex sync.RWMutex + _sinkFactories map[string]func(*url.URL) (Sink, error) // keyed by scheme +) + +func init() { + resetSinkRegistry() +} + +func resetSinkRegistry() { + _sinkMutex.Lock() + defer _sinkMutex.Unlock() + + _sinkFactories = map[string]func(*url.URL) (Sink, error){ + schemeFile: newFileSink, + } +} + +// Sink defines the interface to write to and close logger destinations. +type Sink interface { + zapcore.WriteSyncer + io.Closer +} + +type nopCloserSink struct{ zapcore.WriteSyncer } + +func (nopCloserSink) Close() error { return nil } + +type errSinkNotFound struct { + scheme string +} + +func (e *errSinkNotFound) Error() string { + return fmt.Sprintf("no sink found for scheme %q", e.scheme) +} + +// RegisterSink registers a user-supplied factory for all sinks with a +// particular scheme. +// +// All schemes must be ASCII, valid under section 3.1 of RFC 3986 +// (https://tools.ietf.org/html/rfc3986#section-3.1), and must not already +// have a factory registered. Zap automatically registers a factory for the +// "file" scheme. +func RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error { + _sinkMutex.Lock() + defer _sinkMutex.Unlock() + + if scheme == "" { + return errors.New("can't register a sink factory for empty string") + } + normalized, err := normalizeScheme(scheme) + if err != nil { + return fmt.Errorf("%q is not a valid scheme: %v", scheme, err) + } + if _, ok := _sinkFactories[normalized]; ok { + return fmt.Errorf("sink factory already registered for scheme %q", normalized) + } + _sinkFactories[normalized] = factory + return nil +} + +func newSink(rawURL string) (Sink, error) { + u, err := url.Parse(rawURL) + if err != nil { + return nil, fmt.Errorf("can't parse %q as a URL: %v", rawURL, err) + } + if u.Scheme == "" { + u.Scheme = schemeFile + } + + _sinkMutex.RLock() + factory, ok := _sinkFactories[u.Scheme] + _sinkMutex.RUnlock() + if !ok { + return nil, &errSinkNotFound{u.Scheme} + } + return factory(u) +} + +func newFileSink(u *url.URL) (Sink, error) { + if u.User != nil { + return nil, fmt.Errorf("user and password not allowed with file URLs: got %v", u) + } + if u.Fragment != "" { + return nil, fmt.Errorf("fragments not allowed with file URLs: got %v", u) + } + if u.RawQuery != "" { + return nil, fmt.Errorf("query parameters not allowed with file URLs: got %v", u) + } + // Error messages are better if we check hostname and port separately. + if u.Port() != "" { + return nil, fmt.Errorf("ports not allowed with file URLs: got %v", u) + } + if hn := u.Hostname(); hn != "" && hn != "localhost" { + return nil, fmt.Errorf("file URLs must leave host empty or use localhost: got %v", u) + } + switch u.Path { + case "stdout": + return nopCloserSink{os.Stdout}, nil + case "stderr": + return nopCloserSink{os.Stderr}, nil + } + return os.OpenFile(u.Path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) +} + +func normalizeScheme(s string) (string, error) { + // https://tools.ietf.org/html/rfc3986#section-3.1 + s = strings.ToLower(s) + if first := s[0]; 'a' > first || 'z' < first { + return "", errors.New("must start with a letter") + } + for i := 1; i < len(s); i++ { // iterate over bytes, not runes + c := s[i] + switch { + case 'a' <= c && c <= 'z': + continue + case '0' <= c && c <= '9': + continue + case c == '.' || c == '+' || c == '-': + continue + } + return "", fmt.Errorf("may not contain %q", c) + } + return s, nil +} diff --git a/tools/vendor/go.uber.org/zap/stacktrace.go b/tools/vendor/go.uber.org/zap/stacktrace.go new file mode 100644 index 00000000..3d187fa5 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/stacktrace.go @@ -0,0 +1,176 @@ +// Copyright (c) 2016 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 zap + +import ( + "runtime" + "sync" + + "go.uber.org/zap/buffer" + "go.uber.org/zap/internal/bufferpool" +) + +var _stacktracePool = sync.Pool{ + New: func() interface{} { + return &stacktrace{ + storage: make([]uintptr, 64), + } + }, +} + +type stacktrace struct { + pcs []uintptr // program counters; always a subslice of storage + frames *runtime.Frames + + // The size of pcs varies depending on requirements: + // it will be one if the only the first frame was requested, + // and otherwise it will reflect the depth of the call stack. + // + // storage decouples the slice we need (pcs) from the slice we pool. + // We will always allocate a reasonably large storage, but we'll use + // only as much of it as we need. + storage []uintptr +} + +// stacktraceDepth specifies how deep of a stack trace should be captured. +type stacktraceDepth int + +const ( + // stacktraceFirst captures only the first frame. + stacktraceFirst stacktraceDepth = iota + + // stacktraceFull captures the entire call stack, allocating more + // storage for it if needed. + stacktraceFull +) + +// captureStacktrace captures a stack trace of the specified depth, skipping +// the provided number of frames. skip=0 identifies the caller of +// captureStacktrace. +// +// The caller must call Free on the returned stacktrace after using it. +func captureStacktrace(skip int, depth stacktraceDepth) *stacktrace { + stack := _stacktracePool.Get().(*stacktrace) + + switch depth { + case stacktraceFirst: + stack.pcs = stack.storage[:1] + case stacktraceFull: + stack.pcs = stack.storage + } + + // Unlike other "skip"-based APIs, skip=0 identifies runtime.Callers + // itself. +2 to skip captureStacktrace and runtime.Callers. + numFrames := runtime.Callers( + skip+2, + stack.pcs, + ) + + // runtime.Callers truncates the recorded stacktrace if there is no + // room in the provided slice. For the full stack trace, keep expanding + // storage until there are fewer frames than there is room. + if depth == stacktraceFull { + pcs := stack.pcs + for numFrames == len(pcs) { + pcs = make([]uintptr, len(pcs)*2) + numFrames = runtime.Callers(skip+2, pcs) + } + + // Discard old storage instead of returning it to the pool. + // This will adjust the pool size over time if stack traces are + // consistently very deep. + stack.storage = pcs + stack.pcs = pcs[:numFrames] + } else { + stack.pcs = stack.pcs[:numFrames] + } + + stack.frames = runtime.CallersFrames(stack.pcs) + return stack +} + +// Free releases resources associated with this stacktrace +// and returns it back to the pool. +func (st *stacktrace) Free() { + st.frames = nil + st.pcs = nil + _stacktracePool.Put(st) +} + +// Count reports the total number of frames in this stacktrace. +// Count DOES NOT change as Next is called. +func (st *stacktrace) Count() int { + return len(st.pcs) +} + +// Next returns the next frame in the stack trace, +// and a boolean indicating whether there are more after it. +func (st *stacktrace) Next() (_ runtime.Frame, more bool) { + return st.frames.Next() +} + +func takeStacktrace(skip int) string { + stack := captureStacktrace(skip+1, stacktraceFull) + defer stack.Free() + + buffer := bufferpool.Get() + defer buffer.Free() + + stackfmt := newStackFormatter(buffer) + stackfmt.FormatStack(stack) + return buffer.String() +} + +// stackFormatter formats a stack trace into a readable string representation. +type stackFormatter struct { + b *buffer.Buffer + nonEmpty bool // whehther we've written at least one frame already +} + +// newStackFormatter builds a new stackFormatter. +func newStackFormatter(b *buffer.Buffer) stackFormatter { + return stackFormatter{b: b} +} + +// FormatStack formats all remaining frames in the provided stacktrace -- minus +// the final runtime.main/runtime.goexit frame. +func (sf *stackFormatter) FormatStack(stack *stacktrace) { + // Note: On the last iteration, frames.Next() returns false, with a valid + // frame, but we ignore this frame. The last frame is a a runtime frame which + // adds noise, since it's only either runtime.main or runtime.goexit. + for frame, more := stack.Next(); more; frame, more = stack.Next() { + sf.FormatFrame(frame) + } +} + +// FormatFrame formats the given frame. +func (sf *stackFormatter) FormatFrame(frame runtime.Frame) { + if sf.nonEmpty { + sf.b.AppendByte('\n') + } + sf.nonEmpty = true + sf.b.AppendString(frame.Function) + sf.b.AppendByte('\n') + sf.b.AppendByte('\t') + sf.b.AppendString(frame.File) + sf.b.AppendByte(':') + sf.b.AppendInt(int64(frame.Line)) +} diff --git a/tools/vendor/go.uber.org/zap/sugar.go b/tools/vendor/go.uber.org/zap/sugar.go new file mode 100644 index 00000000..0b965198 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/sugar.go @@ -0,0 +1,315 @@ +// Copyright (c) 2016 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 zap + +import ( + "fmt" + + "go.uber.org/zap/zapcore" + + "go.uber.org/multierr" +) + +const ( + _oddNumberErrMsg = "Ignored key without a value." + _nonStringKeyErrMsg = "Ignored key-value pairs with non-string keys." +) + +// A SugaredLogger wraps the base Logger functionality in a slower, but less +// verbose, API. Any Logger can be converted to a SugaredLogger with its Sugar +// method. +// +// Unlike the Logger, the SugaredLogger doesn't insist on structured logging. +// For each log level, it exposes three methods: one for loosely-typed +// structured logging, one for println-style formatting, and one for +// printf-style formatting. For example, SugaredLoggers can produce InfoLevel +// output with Infow ("info with" structured context), Info, or Infof. +type SugaredLogger struct { + base *Logger +} + +// Desugar unwraps a SugaredLogger, exposing the original Logger. Desugaring +// is quite inexpensive, so it's reasonable for a single application to use +// both Loggers and SugaredLoggers, converting between them on the boundaries +// of performance-sensitive code. +func (s *SugaredLogger) Desugar() *Logger { + base := s.base.clone() + base.callerSkip -= 2 + return base +} + +// Named adds a sub-scope to the logger's name. See Logger.Named for details. +func (s *SugaredLogger) Named(name string) *SugaredLogger { + return &SugaredLogger{base: s.base.Named(name)} +} + +// With adds a variadic number of fields to the logging context. It accepts a +// mix of strongly-typed Field objects and loosely-typed key-value pairs. When +// processing pairs, the first element of the pair is used as the field key +// and the second as the field value. +// +// For example, +// sugaredLogger.With( +// "hello", "world", +// "failure", errors.New("oh no"), +// Stack(), +// "count", 42, +// "user", User{Name: "alice"}, +// ) +// is the equivalent of +// unsugared.With( +// String("hello", "world"), +// String("failure", "oh no"), +// Stack(), +// Int("count", 42), +// Object("user", User{Name: "alice"}), +// ) +// +// Note that the keys in key-value pairs should be strings. In development, +// passing a non-string key panics. In production, the logger is more +// forgiving: a separate error is logged, but the key-value pair is skipped +// and execution continues. Passing an orphaned key triggers similar behavior: +// panics in development and errors in production. +func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger { + return &SugaredLogger{base: s.base.With(s.sweetenFields(args)...)} +} + +// Debug uses fmt.Sprint to construct and log a message. +func (s *SugaredLogger) Debug(args ...interface{}) { + s.log(DebugLevel, "", args, nil) +} + +// Info uses fmt.Sprint to construct and log a message. +func (s *SugaredLogger) Info(args ...interface{}) { + s.log(InfoLevel, "", args, nil) +} + +// Warn uses fmt.Sprint to construct and log a message. +func (s *SugaredLogger) Warn(args ...interface{}) { + s.log(WarnLevel, "", args, nil) +} + +// Error uses fmt.Sprint to construct and log a message. +func (s *SugaredLogger) Error(args ...interface{}) { + s.log(ErrorLevel, "", args, nil) +} + +// DPanic uses fmt.Sprint to construct and log a message. In development, the +// logger then panics. (See DPanicLevel for details.) +func (s *SugaredLogger) DPanic(args ...interface{}) { + s.log(DPanicLevel, "", args, nil) +} + +// Panic uses fmt.Sprint to construct and log a message, then panics. +func (s *SugaredLogger) Panic(args ...interface{}) { + s.log(PanicLevel, "", args, nil) +} + +// Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit. +func (s *SugaredLogger) Fatal(args ...interface{}) { + s.log(FatalLevel, "", args, nil) +} + +// Debugf uses fmt.Sprintf to log a templated message. +func (s *SugaredLogger) Debugf(template string, args ...interface{}) { + s.log(DebugLevel, template, args, nil) +} + +// Infof uses fmt.Sprintf to log a templated message. +func (s *SugaredLogger) Infof(template string, args ...interface{}) { + s.log(InfoLevel, template, args, nil) +} + +// Warnf uses fmt.Sprintf to log a templated message. +func (s *SugaredLogger) Warnf(template string, args ...interface{}) { + s.log(WarnLevel, template, args, nil) +} + +// Errorf uses fmt.Sprintf to log a templated message. +func (s *SugaredLogger) Errorf(template string, args ...interface{}) { + s.log(ErrorLevel, template, args, nil) +} + +// DPanicf uses fmt.Sprintf to log a templated message. In development, the +// logger then panics. (See DPanicLevel for details.) +func (s *SugaredLogger) DPanicf(template string, args ...interface{}) { + s.log(DPanicLevel, template, args, nil) +} + +// Panicf uses fmt.Sprintf to log a templated message, then panics. +func (s *SugaredLogger) Panicf(template string, args ...interface{}) { + s.log(PanicLevel, template, args, nil) +} + +// Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit. +func (s *SugaredLogger) Fatalf(template string, args ...interface{}) { + s.log(FatalLevel, template, args, nil) +} + +// Debugw logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +// +// When debug-level logging is disabled, this is much faster than +// s.With(keysAndValues).Debug(msg) +func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{}) { + s.log(DebugLevel, msg, nil, keysAndValues) +} + +// Infow logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{}) { + s.log(InfoLevel, msg, nil, keysAndValues) +} + +// Warnw logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{}) { + s.log(WarnLevel, msg, nil, keysAndValues) +} + +// Errorw logs a message with some additional context. The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{}) { + s.log(ErrorLevel, msg, nil, keysAndValues) +} + +// DPanicw logs a message with some additional context. In development, the +// logger then panics. (See DPanicLevel for details.) The variadic key-value +// pairs are treated as they are in With. +func (s *SugaredLogger) DPanicw(msg string, keysAndValues ...interface{}) { + s.log(DPanicLevel, msg, nil, keysAndValues) +} + +// Panicw logs a message with some additional context, then panics. The +// variadic key-value pairs are treated as they are in With. +func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{}) { + s.log(PanicLevel, msg, nil, keysAndValues) +} + +// Fatalw logs a message with some additional context, then calls os.Exit. The +// variadic key-value pairs are treated as they are in With. +func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{}) { + s.log(FatalLevel, msg, nil, keysAndValues) +} + +// Sync flushes any buffered log entries. +func (s *SugaredLogger) Sync() error { + return s.base.Sync() +} + +func (s *SugaredLogger) log(lvl zapcore.Level, template string, fmtArgs []interface{}, context []interface{}) { + // If logging at this level is completely disabled, skip the overhead of + // string formatting. + if lvl < DPanicLevel && !s.base.Core().Enabled(lvl) { + return + } + + msg := getMessage(template, fmtArgs) + if ce := s.base.Check(lvl, msg); ce != nil { + ce.Write(s.sweetenFields(context)...) + } +} + +// getMessage format with Sprint, Sprintf, or neither. +func getMessage(template string, fmtArgs []interface{}) string { + if len(fmtArgs) == 0 { + return template + } + + if template != "" { + return fmt.Sprintf(template, fmtArgs...) + } + + if len(fmtArgs) == 1 { + if str, ok := fmtArgs[0].(string); ok { + return str + } + } + return fmt.Sprint(fmtArgs...) +} + +func (s *SugaredLogger) sweetenFields(args []interface{}) []Field { + if len(args) == 0 { + return nil + } + + // Allocate enough space for the worst case; if users pass only structured + // fields, we shouldn't penalize them with extra allocations. + fields := make([]Field, 0, len(args)) + var invalid invalidPairs + + for i := 0; i < len(args); { + // This is a strongly-typed field. Consume it and move on. + if f, ok := args[i].(Field); ok { + fields = append(fields, f) + i++ + continue + } + + // Make sure this element isn't a dangling key. + if i == len(args)-1 { + s.base.Error(_oddNumberErrMsg, Any("ignored", args[i])) + break + } + + // Consume this value and the next, treating them as a key-value pair. If the + // key isn't a string, add this pair to the slice of invalid pairs. + key, val := args[i], args[i+1] + if keyStr, ok := key.(string); !ok { + // Subsequent errors are likely, so allocate once up front. + if cap(invalid) == 0 { + invalid = make(invalidPairs, 0, len(args)/2) + } + invalid = append(invalid, invalidPair{i, key, val}) + } else { + fields = append(fields, Any(keyStr, val)) + } + i += 2 + } + + // If we encountered any invalid key-value pairs, log an error. + if len(invalid) > 0 { + s.base.Error(_nonStringKeyErrMsg, Array("invalid", invalid)) + } + return fields +} + +type invalidPair struct { + position int + key, value interface{} +} + +func (p invalidPair) MarshalLogObject(enc zapcore.ObjectEncoder) error { + enc.AddInt64("position", int64(p.position)) + Any("key", p.key).AddTo(enc) + Any("value", p.value).AddTo(enc) + return nil +} + +type invalidPairs []invalidPair + +func (ps invalidPairs) MarshalLogArray(enc zapcore.ArrayEncoder) error { + var err error + for i := range ps { + err = multierr.Append(err, enc.AppendObject(ps[i])) + } + return err +} diff --git a/tools/vendor/go.uber.org/zap/time.go b/tools/vendor/go.uber.org/zap/time.go new file mode 100644 index 00000000..c5a1f162 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/time.go @@ -0,0 +1,27 @@ +// Copyright (c) 2016 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 zap + +import "time" + +func timeToMillis(t time.Time) int64 { + return t.UnixNano() / int64(time.Millisecond) +} diff --git a/tools/vendor/go.uber.org/zap/writer.go b/tools/vendor/go.uber.org/zap/writer.go new file mode 100644 index 00000000..86a709ab --- /dev/null +++ b/tools/vendor/go.uber.org/zap/writer.go @@ -0,0 +1,99 @@ +// Copyright (c) 2016 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 zap + +import ( + "fmt" + "io" + "io/ioutil" + + "go.uber.org/zap/zapcore" + + "go.uber.org/multierr" +) + +// Open is a high-level wrapper that takes a variadic number of URLs, opens or +// creates each of the specified resources, and combines them into a locked +// WriteSyncer. It also returns any error encountered and a function to close +// any opened files. +// +// Passing no URLs returns a no-op WriteSyncer. Zap handles URLs without a +// scheme and URLs with the "file" scheme. Third-party code may register +// factories for other schemes using RegisterSink. +// +// URLs with the "file" scheme must use absolute paths on the local +// filesystem. No user, password, port, fragments, or query parameters are +// allowed, and the hostname must be empty or "localhost". +// +// Since it's common to write logs to the local filesystem, URLs without a +// scheme (e.g., "/var/log/foo.log") are treated as local file paths. Without +// a scheme, the special paths "stdout" and "stderr" are interpreted as +// os.Stdout and os.Stderr. When specified without a scheme, relative file +// paths also work. +func Open(paths ...string) (zapcore.WriteSyncer, func(), error) { + writers, close, err := open(paths) + if err != nil { + return nil, nil, err + } + + writer := CombineWriteSyncers(writers...) + return writer, close, nil +} + +func open(paths []string) ([]zapcore.WriteSyncer, func(), error) { + writers := make([]zapcore.WriteSyncer, 0, len(paths)) + closers := make([]io.Closer, 0, len(paths)) + close := func() { + for _, c := range closers { + c.Close() + } + } + + var openErr error + for _, path := range paths { + sink, err := newSink(path) + if err != nil { + openErr = multierr.Append(openErr, fmt.Errorf("couldn't open sink %q: %v", path, err)) + continue + } + writers = append(writers, sink) + closers = append(closers, sink) + } + if openErr != nil { + close() + return writers, nil, openErr + } + + return writers, close, nil +} + +// CombineWriteSyncers is a utility that combines multiple WriteSyncers into a +// single, locked WriteSyncer. If no inputs are supplied, it returns a no-op +// WriteSyncer. +// +// It's provided purely as a convenience; the result is no different from +// using zapcore.NewMultiWriteSyncer and zapcore.Lock individually. +func CombineWriteSyncers(writers ...zapcore.WriteSyncer) zapcore.WriteSyncer { + if len(writers) == 0 { + return zapcore.AddSync(ioutil.Discard) + } + return zapcore.Lock(zapcore.NewMultiWriteSyncer(writers...)) +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go b/tools/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go new file mode 100644 index 00000000..ef2f7d96 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go @@ -0,0 +1,188 @@ +// Copyright (c) 2021 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 zapcore + +import ( + "bufio" + "sync" + "time" + + "go.uber.org/multierr" +) + +const ( + // _defaultBufferSize specifies the default size used by Buffer. + _defaultBufferSize = 256 * 1024 // 256 kB + + // _defaultFlushInterval specifies the default flush interval for + // Buffer. + _defaultFlushInterval = 30 * time.Second +) + +// A BufferedWriteSyncer is a WriteSyncer that buffers writes in-memory before +// flushing them to a wrapped WriteSyncer after reaching some limit, or at some +// fixed interval--whichever comes first. +// +// BufferedWriteSyncer is safe for concurrent use. You don't need to use +// zapcore.Lock for WriteSyncers with BufferedWriteSyncer. +type BufferedWriteSyncer struct { + // WS is the WriteSyncer around which BufferedWriteSyncer will buffer + // writes. + // + // This field is required. + WS WriteSyncer + + // Size specifies the maximum amount of data the writer will buffered + // before flushing. + // + // Defaults to 256 kB if unspecified. + Size int + + // FlushInterval specifies how often the writer should flush data if + // there have been no writes. + // + // Defaults to 30 seconds if unspecified. + FlushInterval time.Duration + + // Clock, if specified, provides control of the source of time for the + // writer. + // + // Defaults to the system clock. + Clock Clock + + // unexported fields for state + mu sync.Mutex + initialized bool // whether initialize() has run + stopped bool // whether Stop() has run + writer *bufio.Writer + ticker *time.Ticker + stop chan struct{} // closed when flushLoop should stop + done chan struct{} // closed when flushLoop has stopped +} + +func (s *BufferedWriteSyncer) initialize() { + size := s.Size + if size == 0 { + size = _defaultBufferSize + } + + flushInterval := s.FlushInterval + if flushInterval == 0 { + flushInterval = _defaultFlushInterval + } + + if s.Clock == nil { + s.Clock = DefaultClock + } + + s.ticker = s.Clock.NewTicker(flushInterval) + s.writer = bufio.NewWriterSize(s.WS, size) + s.stop = make(chan struct{}) + s.done = make(chan struct{}) + s.initialized = true + go s.flushLoop() +} + +// Write writes log data into buffer syncer directly, multiple Write calls will be batched, +// and log data will be flushed to disk when the buffer is full or periodically. +func (s *BufferedWriteSyncer) Write(bs []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if !s.initialized { + s.initialize() + } + + // To avoid partial writes from being flushed, we manually flush the existing buffer if: + // * The current write doesn't fit into the buffer fully, and + // * The buffer is not empty (since bufio will not split large writes when the buffer is empty) + if len(bs) > s.writer.Available() && s.writer.Buffered() > 0 { + if err := s.writer.Flush(); err != nil { + return 0, err + } + } + + return s.writer.Write(bs) +} + +// Sync flushes buffered log data into disk directly. +func (s *BufferedWriteSyncer) Sync() error { + s.mu.Lock() + defer s.mu.Unlock() + + var err error + if s.initialized { + err = s.writer.Flush() + } + + return multierr.Append(err, s.WS.Sync()) +} + +// flushLoop flushes the buffer at the configured interval until Stop is +// called. +func (s *BufferedWriteSyncer) flushLoop() { + defer close(s.done) + + for { + select { + case <-s.ticker.C: + // we just simply ignore error here + // because the underlying bufio writer stores any errors + // and we return any error from Sync() as part of the close + _ = s.Sync() + case <-s.stop: + return + } + } +} + +// Stop closes the buffer, cleans up background goroutines, and flushes +// remaining unwritten data. +func (s *BufferedWriteSyncer) Stop() (err error) { + var stopped bool + + // Critical section. + func() { + s.mu.Lock() + defer s.mu.Unlock() + + if !s.initialized { + return + } + + stopped = s.stopped + if stopped { + return + } + s.stopped = true + + s.ticker.Stop() + close(s.stop) // tell flushLoop to stop + <-s.done // and wait until it has + }() + + // Don't call Sync on consecutive Stops. + if !stopped { + err = s.Sync() + } + + return err +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/clock.go b/tools/vendor/go.uber.org/zap/zapcore/clock.go new file mode 100644 index 00000000..422fd82a --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/clock.go @@ -0,0 +1,48 @@ +// Copyright (c) 2021 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 zapcore + +import "time" + +// DefaultClock is the default clock used by Zap in operations that require +// time. This clock uses the system clock for all operations. +var DefaultClock = systemClock{} + +// Clock is a source of time for logged entries. +type Clock interface { + // Now returns the current local time. + Now() time.Time + + // NewTicker returns *time.Ticker that holds a channel + // that delivers "ticks" of a clock. + NewTicker(time.Duration) *time.Ticker +} + +// systemClock implements default Clock that uses system time. +type systemClock struct{} + +func (systemClock) Now() time.Time { + return time.Now() +} + +func (systemClock) NewTicker(duration time.Duration) *time.Ticker { + return time.NewTicker(duration) +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/console_encoder.go b/tools/vendor/go.uber.org/zap/zapcore/console_encoder.go new file mode 100644 index 00000000..1aa5dc36 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/console_encoder.go @@ -0,0 +1,157 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "fmt" + "sync" + + "go.uber.org/zap/buffer" + "go.uber.org/zap/internal/bufferpool" +) + +var _sliceEncoderPool = sync.Pool{ + New: func() interface{} { + return &sliceArrayEncoder{elems: make([]interface{}, 0, 2)} + }, +} + +func getSliceEncoder() *sliceArrayEncoder { + return _sliceEncoderPool.Get().(*sliceArrayEncoder) +} + +func putSliceEncoder(e *sliceArrayEncoder) { + e.elems = e.elems[:0] + _sliceEncoderPool.Put(e) +} + +type consoleEncoder struct { + *jsonEncoder +} + +// NewConsoleEncoder creates an encoder whose output is designed for human - +// rather than machine - consumption. It serializes the core log entry data +// (message, level, timestamp, etc.) in a plain-text format and leaves the +// structured context as JSON. +// +// Note that although the console encoder doesn't use the keys specified in the +// encoder configuration, it will omit any element whose key is set to the empty +// string. +func NewConsoleEncoder(cfg EncoderConfig) Encoder { + if cfg.ConsoleSeparator == "" { + // Use a default delimiter of '\t' for backwards compatibility + cfg.ConsoleSeparator = "\t" + } + return consoleEncoder{newJSONEncoder(cfg, true)} +} + +func (c consoleEncoder) Clone() Encoder { + return consoleEncoder{c.jsonEncoder.Clone().(*jsonEncoder)} +} + +func (c consoleEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { + line := bufferpool.Get() + + // We don't want the entry's metadata to be quoted and escaped (if it's + // encoded as strings), which means that we can't use the JSON encoder. The + // simplest option is to use the memory encoder and fmt.Fprint. + // + // If this ever becomes a performance bottleneck, we can implement + // ArrayEncoder for our plain-text format. + arr := getSliceEncoder() + if c.TimeKey != "" && c.EncodeTime != nil { + c.EncodeTime(ent.Time, arr) + } + if c.LevelKey != "" && c.EncodeLevel != nil { + c.EncodeLevel(ent.Level, arr) + } + if ent.LoggerName != "" && c.NameKey != "" { + nameEncoder := c.EncodeName + + if nameEncoder == nil { + // Fall back to FullNameEncoder for backward compatibility. + nameEncoder = FullNameEncoder + } + + nameEncoder(ent.LoggerName, arr) + } + if ent.Caller.Defined { + if c.CallerKey != "" && c.EncodeCaller != nil { + c.EncodeCaller(ent.Caller, arr) + } + if c.FunctionKey != "" { + arr.AppendString(ent.Caller.Function) + } + } + for i := range arr.elems { + if i > 0 { + line.AppendString(c.ConsoleSeparator) + } + fmt.Fprint(line, arr.elems[i]) + } + putSliceEncoder(arr) + + // Add the message itself. + if c.MessageKey != "" { + c.addSeparatorIfNecessary(line) + line.AppendString(ent.Message) + } + + // Add any structured context. + c.writeContext(line, fields) + + // If there's no stacktrace key, honor that; this allows users to force + // single-line output. + if ent.Stack != "" && c.StacktraceKey != "" { + line.AppendByte('\n') + line.AppendString(ent.Stack) + } + + line.AppendString(c.LineEnding) + return line, nil +} + +func (c consoleEncoder) writeContext(line *buffer.Buffer, extra []Field) { + context := c.jsonEncoder.Clone().(*jsonEncoder) + defer func() { + // putJSONEncoder assumes the buffer is still used, but we write out the buffer so + // we can free it. + context.buf.Free() + putJSONEncoder(context) + }() + + addFields(context, extra) + context.closeOpenNamespaces() + if context.buf.Len() == 0 { + return + } + + c.addSeparatorIfNecessary(line) + line.AppendByte('{') + line.Write(context.buf.Bytes()) + line.AppendByte('}') +} + +func (c consoleEncoder) addSeparatorIfNecessary(line *buffer.Buffer) { + if line.Len() > 0 { + line.AppendString(c.ConsoleSeparator) + } +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/core.go b/tools/vendor/go.uber.org/zap/zapcore/core.go new file mode 100644 index 00000000..a1ef8b03 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/core.go @@ -0,0 +1,113 @@ +// Copyright (c) 2016 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 zapcore + +// Core is a minimal, fast logger interface. It's designed for library authors +// to wrap in a more user-friendly API. +type Core interface { + LevelEnabler + + // With adds structured context to the Core. + With([]Field) Core + // Check determines whether the supplied Entry should be logged (using the + // embedded LevelEnabler and possibly some extra logic). If the entry + // should be logged, the Core adds itself to the CheckedEntry and returns + // the result. + // + // Callers must use Check before calling Write. + Check(Entry, *CheckedEntry) *CheckedEntry + // Write serializes the Entry and any Fields supplied at the log site and + // writes them to their destination. + // + // If called, Write should always log the Entry and Fields; it should not + // replicate the logic of Check. + Write(Entry, []Field) error + // Sync flushes buffered logs (if any). + Sync() error +} + +type nopCore struct{} + +// NewNopCore returns a no-op Core. +func NewNopCore() Core { return nopCore{} } +func (nopCore) Enabled(Level) bool { return false } +func (n nopCore) With([]Field) Core { return n } +func (nopCore) Check(_ Entry, ce *CheckedEntry) *CheckedEntry { return ce } +func (nopCore) Write(Entry, []Field) error { return nil } +func (nopCore) Sync() error { return nil } + +// NewCore creates a Core that writes logs to a WriteSyncer. +func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core { + return &ioCore{ + LevelEnabler: enab, + enc: enc, + out: ws, + } +} + +type ioCore struct { + LevelEnabler + enc Encoder + out WriteSyncer +} + +func (c *ioCore) With(fields []Field) Core { + clone := c.clone() + addFields(clone.enc, fields) + return clone +} + +func (c *ioCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + if c.Enabled(ent.Level) { + return ce.AddCore(ent, c) + } + return ce +} + +func (c *ioCore) Write(ent Entry, fields []Field) error { + buf, err := c.enc.EncodeEntry(ent, fields) + if err != nil { + return err + } + _, err = c.out.Write(buf.Bytes()) + buf.Free() + if err != nil { + return err + } + if ent.Level > ErrorLevel { + // Since we may be crashing the program, sync the output. Ignore Sync + // errors, pending a clean solution to issue #370. + c.Sync() + } + return nil +} + +func (c *ioCore) Sync() error { + return c.out.Sync() +} + +func (c *ioCore) clone() *ioCore { + return &ioCore{ + LevelEnabler: c.LevelEnabler, + enc: c.enc.Clone(), + out: c.out, + } +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/doc.go b/tools/vendor/go.uber.org/zap/zapcore/doc.go new file mode 100644 index 00000000..31000e91 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/doc.go @@ -0,0 +1,24 @@ +// Copyright (c) 2016 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 zapcore defines and implements the low-level interfaces upon which +// zap is built. By providing alternate implementations of these interfaces, +// external packages can extend zap's capabilities. +package zapcore // import "go.uber.org/zap/zapcore" diff --git a/tools/vendor/go.uber.org/zap/zapcore/encoder.go b/tools/vendor/go.uber.org/zap/zapcore/encoder.go new file mode 100644 index 00000000..6e5fd565 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/encoder.go @@ -0,0 +1,448 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "encoding/json" + "io" + "time" + + "go.uber.org/zap/buffer" +) + +// DefaultLineEnding defines the default line ending when writing logs. +// Alternate line endings specified in EncoderConfig can override this +// behavior. +const DefaultLineEnding = "\n" + +// OmitKey defines the key to use when callers want to remove a key from log output. +const OmitKey = "" + +// A LevelEncoder serializes a Level to a primitive type. +type LevelEncoder func(Level, PrimitiveArrayEncoder) + +// LowercaseLevelEncoder serializes a Level to a lowercase string. For example, +// InfoLevel is serialized to "info". +func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + enc.AppendString(l.String()) +} + +// LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring. +// For example, InfoLevel is serialized to "info" and colored blue. +func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + s, ok := _levelToLowercaseColorString[l] + if !ok { + s = _unknownLevelColor.Add(l.String()) + } + enc.AppendString(s) +} + +// CapitalLevelEncoder serializes a Level to an all-caps string. For example, +// InfoLevel is serialized to "INFO". +func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + enc.AppendString(l.CapitalString()) +} + +// CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color. +// For example, InfoLevel is serialized to "INFO" and colored blue. +func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { + s, ok := _levelToCapitalColorString[l] + if !ok { + s = _unknownLevelColor.Add(l.CapitalString()) + } + enc.AppendString(s) +} + +// UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshaled to +// CapitalLevelEncoder, "coloredCapital" is unmarshaled to CapitalColorLevelEncoder, +// "colored" is unmarshaled to LowercaseColorLevelEncoder, and anything else +// is unmarshaled to LowercaseLevelEncoder. +func (e *LevelEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "capital": + *e = CapitalLevelEncoder + case "capitalColor": + *e = CapitalColorLevelEncoder + case "color": + *e = LowercaseColorLevelEncoder + default: + *e = LowercaseLevelEncoder + } + return nil +} + +// A TimeEncoder serializes a time.Time to a primitive type. +type TimeEncoder func(time.Time, PrimitiveArrayEncoder) + +// EpochTimeEncoder serializes a time.Time to a floating-point number of seconds +// since the Unix epoch. +func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + nanos := t.UnixNano() + sec := float64(nanos) / float64(time.Second) + enc.AppendFloat64(sec) +} + +// EpochMillisTimeEncoder serializes a time.Time to a floating-point number of +// milliseconds since the Unix epoch. +func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + nanos := t.UnixNano() + millis := float64(nanos) / float64(time.Millisecond) + enc.AppendFloat64(millis) +} + +// EpochNanosTimeEncoder serializes a time.Time to an integer number of +// nanoseconds since the Unix epoch. +func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + enc.AppendInt64(t.UnixNano()) +} + +func encodeTimeLayout(t time.Time, layout string, enc PrimitiveArrayEncoder) { + type appendTimeEncoder interface { + AppendTimeLayout(time.Time, string) + } + + if enc, ok := enc.(appendTimeEncoder); ok { + enc.AppendTimeLayout(t, layout) + return + } + + enc.AppendString(t.Format(layout)) +} + +// ISO8601TimeEncoder serializes a time.Time to an ISO8601-formatted string +// with millisecond precision. +// +// If enc supports AppendTimeLayout(t time.Time,layout string), it's used +// instead of appending a pre-formatted string value. +func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, "2006-01-02T15:04:05.000Z0700", enc) +} + +// RFC3339TimeEncoder serializes a time.Time to an RFC3339-formatted string. +// +// If enc supports AppendTimeLayout(t time.Time,layout string), it's used +// instead of appending a pre-formatted string value. +func RFC3339TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, time.RFC3339, enc) +} + +// RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339-formatted string +// with nanosecond precision. +// +// If enc supports AppendTimeLayout(t time.Time,layout string), it's used +// instead of appending a pre-formatted string value. +func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, time.RFC3339Nano, enc) +} + +// TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using +// given layout. +func TimeEncoderOfLayout(layout string) TimeEncoder { + return func(t time.Time, enc PrimitiveArrayEncoder) { + encodeTimeLayout(t, layout, enc) + } +} + +// UnmarshalText unmarshals text to a TimeEncoder. +// "rfc3339nano" and "RFC3339Nano" are unmarshaled to RFC3339NanoTimeEncoder. +// "rfc3339" and "RFC3339" are unmarshaled to RFC3339TimeEncoder. +// "iso8601" and "ISO8601" are unmarshaled to ISO8601TimeEncoder. +// "millis" is unmarshaled to EpochMillisTimeEncoder. +// "nanos" is unmarshaled to EpochNanosEncoder. +// Anything else is unmarshaled to EpochTimeEncoder. +func (e *TimeEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "rfc3339nano", "RFC3339Nano": + *e = RFC3339NanoTimeEncoder + case "rfc3339", "RFC3339": + *e = RFC3339TimeEncoder + case "iso8601", "ISO8601": + *e = ISO8601TimeEncoder + case "millis": + *e = EpochMillisTimeEncoder + case "nanos": + *e = EpochNanosTimeEncoder + default: + *e = EpochTimeEncoder + } + return nil +} + +// UnmarshalYAML unmarshals YAML to a TimeEncoder. +// If value is an object with a "layout" field, it will be unmarshaled to TimeEncoder with given layout. +// timeEncoder: +// layout: 06/01/02 03:04pm +// If value is string, it uses UnmarshalText. +// timeEncoder: iso8601 +func (e *TimeEncoder) UnmarshalYAML(unmarshal func(interface{}) error) error { + var o struct { + Layout string `json:"layout" yaml:"layout"` + } + if err := unmarshal(&o); err == nil { + *e = TimeEncoderOfLayout(o.Layout) + return nil + } + + var s string + if err := unmarshal(&s); err != nil { + return err + } + return e.UnmarshalText([]byte(s)) +} + +// UnmarshalJSON unmarshals JSON to a TimeEncoder as same way UnmarshalYAML does. +func (e *TimeEncoder) UnmarshalJSON(data []byte) error { + return e.UnmarshalYAML(func(v interface{}) error { + return json.Unmarshal(data, v) + }) +} + +// A DurationEncoder serializes a time.Duration to a primitive type. +type DurationEncoder func(time.Duration, PrimitiveArrayEncoder) + +// SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed. +func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendFloat64(float64(d) / float64(time.Second)) +} + +// NanosDurationEncoder serializes a time.Duration to an integer number of +// nanoseconds elapsed. +func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendInt64(int64(d)) +} + +// MillisDurationEncoder serializes a time.Duration to an integer number of +// milliseconds elapsed. +func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendInt64(d.Nanoseconds() / 1e6) +} + +// StringDurationEncoder serializes a time.Duration using its built-in String +// method. +func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendString(d.String()) +} + +// UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaled +// to StringDurationEncoder, and anything else is unmarshaled to +// NanosDurationEncoder. +func (e *DurationEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "string": + *e = StringDurationEncoder + case "nanos": + *e = NanosDurationEncoder + case "ms": + *e = MillisDurationEncoder + default: + *e = SecondsDurationEncoder + } + return nil +} + +// A CallerEncoder serializes an EntryCaller to a primitive type. +type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder) + +// FullCallerEncoder serializes a caller in /full/path/to/package/file:line +// format. +func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { + // TODO: consider using a byte-oriented API to save an allocation. + enc.AppendString(caller.String()) +} + +// ShortCallerEncoder serializes a caller in package/file:line format, trimming +// all but the final directory from the full path. +func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { + // TODO: consider using a byte-oriented API to save an allocation. + enc.AppendString(caller.TrimmedPath()) +} + +// UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshaled to +// FullCallerEncoder and anything else is unmarshaled to ShortCallerEncoder. +func (e *CallerEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "full": + *e = FullCallerEncoder + default: + *e = ShortCallerEncoder + } + return nil +} + +// A NameEncoder serializes a period-separated logger name to a primitive +// type. +type NameEncoder func(string, PrimitiveArrayEncoder) + +// FullNameEncoder serializes the logger name as-is. +func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder) { + enc.AppendString(loggerName) +} + +// UnmarshalText unmarshals text to a NameEncoder. Currently, everything is +// unmarshaled to FullNameEncoder. +func (e *NameEncoder) UnmarshalText(text []byte) error { + switch string(text) { + case "full": + *e = FullNameEncoder + default: + *e = FullNameEncoder + } + return nil +} + +// An EncoderConfig allows users to configure the concrete encoders supplied by +// zapcore. +type EncoderConfig struct { + // Set the keys used for each log entry. If any key is empty, that portion + // of the entry is omitted. + MessageKey string `json:"messageKey" yaml:"messageKey"` + LevelKey string `json:"levelKey" yaml:"levelKey"` + TimeKey string `json:"timeKey" yaml:"timeKey"` + NameKey string `json:"nameKey" yaml:"nameKey"` + CallerKey string `json:"callerKey" yaml:"callerKey"` + FunctionKey string `json:"functionKey" yaml:"functionKey"` + StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"` + SkipLineEnding bool `json:"skipLineEnding" yaml:"skipLineEnding"` + LineEnding string `json:"lineEnding" yaml:"lineEnding"` + // Configure the primitive representations of common complex types. For + // example, some users may want all time.Times serialized as floating-point + // seconds since epoch, while others may prefer ISO8601 strings. + EncodeLevel LevelEncoder `json:"levelEncoder" yaml:"levelEncoder"` + EncodeTime TimeEncoder `json:"timeEncoder" yaml:"timeEncoder"` + EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"` + EncodeCaller CallerEncoder `json:"callerEncoder" yaml:"callerEncoder"` + // Unlike the other primitive type encoders, EncodeName is optional. The + // zero value falls back to FullNameEncoder. + EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"` + // Configure the encoder for interface{} type objects. + // If not provided, objects are encoded using json.Encoder + NewReflectedEncoder func(io.Writer) ReflectedEncoder `json:"-" yaml:"-"` + // Configures the field separator used by the console encoder. Defaults + // to tab. + ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"` +} + +// ObjectEncoder is a strongly-typed, encoding-agnostic interface for adding a +// map- or struct-like object to the logging context. Like maps, ObjectEncoders +// aren't safe for concurrent use (though typical use shouldn't require locks). +type ObjectEncoder interface { + // Logging-specific marshalers. + AddArray(key string, marshaler ArrayMarshaler) error + AddObject(key string, marshaler ObjectMarshaler) error + + // Built-in types. + AddBinary(key string, value []byte) // for arbitrary bytes + AddByteString(key string, value []byte) // for UTF-8 encoded bytes + AddBool(key string, value bool) + AddComplex128(key string, value complex128) + AddComplex64(key string, value complex64) + AddDuration(key string, value time.Duration) + AddFloat64(key string, value float64) + AddFloat32(key string, value float32) + AddInt(key string, value int) + AddInt64(key string, value int64) + AddInt32(key string, value int32) + AddInt16(key string, value int16) + AddInt8(key string, value int8) + AddString(key, value string) + AddTime(key string, value time.Time) + AddUint(key string, value uint) + AddUint64(key string, value uint64) + AddUint32(key string, value uint32) + AddUint16(key string, value uint16) + AddUint8(key string, value uint8) + AddUintptr(key string, value uintptr) + + // AddReflected uses reflection to serialize arbitrary objects, so it can be + // slow and allocation-heavy. + AddReflected(key string, value interface{}) error + // OpenNamespace opens an isolated namespace where all subsequent fields will + // be added. Applications can use namespaces to prevent key collisions when + // injecting loggers into sub-components or third-party libraries. + OpenNamespace(key string) +} + +// ArrayEncoder is a strongly-typed, encoding-agnostic interface for adding +// array-like objects to the logging context. Of note, it supports mixed-type +// arrays even though they aren't typical in Go. Like slices, ArrayEncoders +// aren't safe for concurrent use (though typical use shouldn't require locks). +type ArrayEncoder interface { + // Built-in types. + PrimitiveArrayEncoder + + // Time-related types. + AppendDuration(time.Duration) + AppendTime(time.Time) + + // Logging-specific marshalers. + AppendArray(ArrayMarshaler) error + AppendObject(ObjectMarshaler) error + + // AppendReflected uses reflection to serialize arbitrary objects, so it's + // slow and allocation-heavy. + AppendReflected(value interface{}) error +} + +// PrimitiveArrayEncoder is the subset of the ArrayEncoder interface that deals +// only in Go's built-in types. It's included only so that Duration- and +// TimeEncoders cannot trigger infinite recursion. +type PrimitiveArrayEncoder interface { + // Built-in types. + AppendBool(bool) + AppendByteString([]byte) // for UTF-8 encoded bytes + AppendComplex128(complex128) + AppendComplex64(complex64) + AppendFloat64(float64) + AppendFloat32(float32) + AppendInt(int) + AppendInt64(int64) + AppendInt32(int32) + AppendInt16(int16) + AppendInt8(int8) + AppendString(string) + AppendUint(uint) + AppendUint64(uint64) + AppendUint32(uint32) + AppendUint16(uint16) + AppendUint8(uint8) + AppendUintptr(uintptr) +} + +// Encoder is a format-agnostic interface for all log entry marshalers. Since +// log encoders don't need to support the same wide range of use cases as +// general-purpose marshalers, it's possible to make them faster and +// lower-allocation. +// +// Implementations of the ObjectEncoder interface's methods can, of course, +// freely modify the receiver. However, the Clone and EncodeEntry methods will +// be called concurrently and shouldn't modify the receiver. +type Encoder interface { + ObjectEncoder + + // Clone copies the encoder, ensuring that adding fields to the copy doesn't + // affect the original. + Clone() Encoder + + // EncodeEntry encodes an entry and fields, along with any accumulated + // context, into a byte buffer and returns it. Any fields that are empty, + // including fields on the `Entry` type, should be omitted. + EncodeEntry(Entry, []Field) (*buffer.Buffer, error) +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/entry.go b/tools/vendor/go.uber.org/zap/zapcore/entry.go new file mode 100644 index 00000000..0885505b --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/entry.go @@ -0,0 +1,262 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "fmt" + "runtime" + "strings" + "sync" + "time" + + "go.uber.org/zap/internal/bufferpool" + "go.uber.org/zap/internal/exit" + + "go.uber.org/multierr" +) + +var ( + _cePool = sync.Pool{New: func() interface{} { + // Pre-allocate some space for cores. + return &CheckedEntry{ + cores: make([]Core, 4), + } + }} +) + +func getCheckedEntry() *CheckedEntry { + ce := _cePool.Get().(*CheckedEntry) + ce.reset() + return ce +} + +func putCheckedEntry(ce *CheckedEntry) { + if ce == nil { + return + } + _cePool.Put(ce) +} + +// NewEntryCaller makes an EntryCaller from the return signature of +// runtime.Caller. +func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller { + if !ok { + return EntryCaller{} + } + return EntryCaller{ + PC: pc, + File: file, + Line: line, + Defined: true, + } +} + +// EntryCaller represents the caller of a logging function. +type EntryCaller struct { + Defined bool + PC uintptr + File string + Line int + Function string +} + +// String returns the full path and line number of the caller. +func (ec EntryCaller) String() string { + return ec.FullPath() +} + +// FullPath returns a /full/path/to/package/file:line description of the +// caller. +func (ec EntryCaller) FullPath() string { + if !ec.Defined { + return "undefined" + } + buf := bufferpool.Get() + buf.AppendString(ec.File) + buf.AppendByte(':') + buf.AppendInt(int64(ec.Line)) + caller := buf.String() + buf.Free() + return caller +} + +// TrimmedPath returns a package/file:line description of the caller, +// preserving only the leaf directory name and file name. +func (ec EntryCaller) TrimmedPath() string { + if !ec.Defined { + return "undefined" + } + // nb. To make sure we trim the path correctly on Windows too, we + // counter-intuitively need to use '/' and *not* os.PathSeparator here, + // because the path given originates from Go stdlib, specifically + // runtime.Caller() which (as of Mar/17) returns forward slashes even on + // Windows. + // + // See https://github.com/golang/go/issues/3335 + // and https://github.com/golang/go/issues/18151 + // + // for discussion on the issue on Go side. + // + // Find the last separator. + // + idx := strings.LastIndexByte(ec.File, '/') + if idx == -1 { + return ec.FullPath() + } + // Find the penultimate separator. + idx = strings.LastIndexByte(ec.File[:idx], '/') + if idx == -1 { + return ec.FullPath() + } + buf := bufferpool.Get() + // Keep everything after the penultimate separator. + buf.AppendString(ec.File[idx+1:]) + buf.AppendByte(':') + buf.AppendInt(int64(ec.Line)) + caller := buf.String() + buf.Free() + return caller +} + +// An Entry represents a complete log message. The entry's structured context +// is already serialized, but the log level, time, message, and call site +// information are available for inspection and modification. Any fields left +// empty will be omitted when encoding. +// +// Entries are pooled, so any functions that accept them MUST be careful not to +// retain references to them. +type Entry struct { + Level Level + Time time.Time + LoggerName string + Message string + Caller EntryCaller + Stack string +} + +// CheckWriteAction indicates what action to take after a log entry is +// processed. Actions are ordered in increasing severity. +type CheckWriteAction uint8 + +const ( + // WriteThenNoop indicates that nothing special needs to be done. It's the + // default behavior. + WriteThenNoop CheckWriteAction = iota + // WriteThenGoexit runs runtime.Goexit after Write. + WriteThenGoexit + // WriteThenPanic causes a panic after Write. + WriteThenPanic + // WriteThenFatal causes a fatal os.Exit after Write. + WriteThenFatal +) + +// CheckedEntry is an Entry together with a collection of Cores that have +// already agreed to log it. +// +// CheckedEntry references should be created by calling AddCore or Should on a +// nil *CheckedEntry. References are returned to a pool after Write, and MUST +// NOT be retained after calling their Write method. +type CheckedEntry struct { + Entry + ErrorOutput WriteSyncer + dirty bool // best-effort detection of pool misuse + should CheckWriteAction + cores []Core +} + +func (ce *CheckedEntry) reset() { + ce.Entry = Entry{} + ce.ErrorOutput = nil + ce.dirty = false + ce.should = WriteThenNoop + for i := range ce.cores { + // don't keep references to cores + ce.cores[i] = nil + } + ce.cores = ce.cores[:0] +} + +// Write writes the entry to the stored Cores, returns any errors, and returns +// the CheckedEntry reference to a pool for immediate re-use. Finally, it +// executes any required CheckWriteAction. +func (ce *CheckedEntry) Write(fields ...Field) { + if ce == nil { + return + } + + if ce.dirty { + if ce.ErrorOutput != nil { + // Make a best effort to detect unsafe re-use of this CheckedEntry. + // If the entry is dirty, log an internal error; because the + // CheckedEntry is being used after it was returned to the pool, + // the message may be an amalgamation from multiple call sites. + fmt.Fprintf(ce.ErrorOutput, "%v Unsafe CheckedEntry re-use near Entry %+v.\n", ce.Time, ce.Entry) + ce.ErrorOutput.Sync() + } + return + } + ce.dirty = true + + var err error + for i := range ce.cores { + err = multierr.Append(err, ce.cores[i].Write(ce.Entry, fields)) + } + if err != nil && ce.ErrorOutput != nil { + fmt.Fprintf(ce.ErrorOutput, "%v write error: %v\n", ce.Time, err) + ce.ErrorOutput.Sync() + } + + should, msg := ce.should, ce.Message + putCheckedEntry(ce) + + switch should { + case WriteThenPanic: + panic(msg) + case WriteThenFatal: + exit.Exit() + case WriteThenGoexit: + runtime.Goexit() + } +} + +// AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be +// used by Core.Check implementations, and is safe to call on nil CheckedEntry +// references. +func (ce *CheckedEntry) AddCore(ent Entry, core Core) *CheckedEntry { + if ce == nil { + ce = getCheckedEntry() + ce.Entry = ent + } + ce.cores = append(ce.cores, core) + return ce +} + +// Should sets this CheckedEntry's CheckWriteAction, which controls whether a +// Core will panic or fatal after writing this log entry. Like AddCore, it's +// safe to call on nil CheckedEntry references. +func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry { + if ce == nil { + ce = getCheckedEntry() + ce.Entry = ent + } + ce.should = should + return ce +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/error.go b/tools/vendor/go.uber.org/zap/zapcore/error.go new file mode 100644 index 00000000..74919b0c --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/error.go @@ -0,0 +1,132 @@ +// 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 zapcore + +import ( + "fmt" + "reflect" + "sync" +) + +// Encodes the given error into fields of an object. A field with the given +// name is added for the error message. +// +// If the error implements fmt.Formatter, a field with the name ${key}Verbose +// is also added with the full verbose error message. +// +// Finally, if the error implements errorGroup (from go.uber.org/multierr) or +// causer (from github.com/pkg/errors), a ${key}Causes field is added with an +// array of objects containing the errors this error was comprised of. +// +// { +// "error": err.Error(), +// "errorVerbose": fmt.Sprintf("%+v", err), +// "errorCauses": [ +// ... +// ], +// } +func encodeError(key string, err error, enc ObjectEncoder) (retErr error) { + // Try to capture panics (from nil references or otherwise) when calling + // the Error() method + defer func() { + if rerr := recover(); rerr != nil { + // If it's a nil pointer, just say "". The likeliest causes are a + // error that fails to guard against nil or a nil pointer for a + // value receiver, and in either case, "" is a nice result. + if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { + enc.AddString(key, "") + return + } + + retErr = fmt.Errorf("PANIC=%v", rerr) + } + }() + + basic := err.Error() + enc.AddString(key, basic) + + switch e := err.(type) { + case errorGroup: + return enc.AddArray(key+"Causes", errArray(e.Errors())) + case fmt.Formatter: + verbose := fmt.Sprintf("%+v", e) + if verbose != basic { + // This is a rich error type, like those produced by + // github.com/pkg/errors. + enc.AddString(key+"Verbose", verbose) + } + } + return nil +} + +type errorGroup interface { + // Provides read-only access to the underlying list of errors, preferably + // without causing any allocs. + Errors() []error +} + +// Note that errArray and errArrayElem are very similar to the version +// implemented in the top-level error.go file. We can't re-use this because +// that would require exporting errArray as part of the zapcore API. + +// Encodes a list of errors using the standard error encoding logic. +type errArray []error + +func (errs errArray) MarshalLogArray(arr ArrayEncoder) error { + for i := range errs { + if errs[i] == nil { + continue + } + + el := newErrArrayElem(errs[i]) + arr.AppendObject(el) + el.Free() + } + return nil +} + +var _errArrayElemPool = sync.Pool{New: func() interface{} { + return &errArrayElem{} +}} + +// Encodes any error into a {"error": ...} re-using the same errors logic. +// +// May be passed in place of an array to build a single-element array. +type errArrayElem struct{ err error } + +func newErrArrayElem(err error) *errArrayElem { + e := _errArrayElemPool.Get().(*errArrayElem) + e.err = err + return e +} + +func (e *errArrayElem) MarshalLogArray(arr ArrayEncoder) error { + return arr.AppendObject(e) +} + +func (e *errArrayElem) MarshalLogObject(enc ObjectEncoder) error { + return encodeError("error", e.err, enc) +} + +func (e *errArrayElem) Free() { + e.err = nil + _errArrayElemPool.Put(e) +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/field.go b/tools/vendor/go.uber.org/zap/zapcore/field.go new file mode 100644 index 00000000..95bdb0a1 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/field.go @@ -0,0 +1,233 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "bytes" + "fmt" + "math" + "reflect" + "time" +) + +// A FieldType indicates which member of the Field union struct should be used +// and how it should be serialized. +type FieldType uint8 + +const ( + // UnknownType is the default field type. Attempting to add it to an encoder will panic. + UnknownType FieldType = iota + // ArrayMarshalerType indicates that the field carries an ArrayMarshaler. + ArrayMarshalerType + // ObjectMarshalerType indicates that the field carries an ObjectMarshaler. + ObjectMarshalerType + // BinaryType indicates that the field carries an opaque binary blob. + BinaryType + // BoolType indicates that the field carries a bool. + BoolType + // ByteStringType indicates that the field carries UTF-8 encoded bytes. + ByteStringType + // Complex128Type indicates that the field carries a complex128. + Complex128Type + // Complex64Type indicates that the field carries a complex128. + Complex64Type + // DurationType indicates that the field carries a time.Duration. + DurationType + // Float64Type indicates that the field carries a float64. + Float64Type + // Float32Type indicates that the field carries a float32. + Float32Type + // Int64Type indicates that the field carries an int64. + Int64Type + // Int32Type indicates that the field carries an int32. + Int32Type + // Int16Type indicates that the field carries an int16. + Int16Type + // Int8Type indicates that the field carries an int8. + Int8Type + // StringType indicates that the field carries a string. + StringType + // TimeType indicates that the field carries a time.Time that is + // representable by a UnixNano() stored as an int64. + TimeType + // TimeFullType indicates that the field carries a time.Time stored as-is. + TimeFullType + // Uint64Type indicates that the field carries a uint64. + Uint64Type + // Uint32Type indicates that the field carries a uint32. + Uint32Type + // Uint16Type indicates that the field carries a uint16. + Uint16Type + // Uint8Type indicates that the field carries a uint8. + Uint8Type + // UintptrType indicates that the field carries a uintptr. + UintptrType + // ReflectType indicates that the field carries an interface{}, which should + // be serialized using reflection. + ReflectType + // NamespaceType signals the beginning of an isolated namespace. All + // subsequent fields should be added to the new namespace. + NamespaceType + // StringerType indicates that the field carries a fmt.Stringer. + StringerType + // ErrorType indicates that the field carries an error. + ErrorType + // SkipType indicates that the field is a no-op. + SkipType + + // InlineMarshalerType indicates that the field carries an ObjectMarshaler + // that should be inlined. + InlineMarshalerType +) + +// A Field is a marshaling operation used to add a key-value pair to a logger's +// context. Most fields are lazily marshaled, so it's inexpensive to add fields +// to disabled debug-level log statements. +type Field struct { + Key string + Type FieldType + Integer int64 + String string + Interface interface{} +} + +// AddTo exports a field through the ObjectEncoder interface. It's primarily +// useful to library authors, and shouldn't be necessary in most applications. +func (f Field) AddTo(enc ObjectEncoder) { + var err error + + switch f.Type { + case ArrayMarshalerType: + err = enc.AddArray(f.Key, f.Interface.(ArrayMarshaler)) + case ObjectMarshalerType: + err = enc.AddObject(f.Key, f.Interface.(ObjectMarshaler)) + case InlineMarshalerType: + err = f.Interface.(ObjectMarshaler).MarshalLogObject(enc) + case BinaryType: + enc.AddBinary(f.Key, f.Interface.([]byte)) + case BoolType: + enc.AddBool(f.Key, f.Integer == 1) + case ByteStringType: + enc.AddByteString(f.Key, f.Interface.([]byte)) + case Complex128Type: + enc.AddComplex128(f.Key, f.Interface.(complex128)) + case Complex64Type: + enc.AddComplex64(f.Key, f.Interface.(complex64)) + case DurationType: + enc.AddDuration(f.Key, time.Duration(f.Integer)) + case Float64Type: + enc.AddFloat64(f.Key, math.Float64frombits(uint64(f.Integer))) + case Float32Type: + enc.AddFloat32(f.Key, math.Float32frombits(uint32(f.Integer))) + case Int64Type: + enc.AddInt64(f.Key, f.Integer) + case Int32Type: + enc.AddInt32(f.Key, int32(f.Integer)) + case Int16Type: + enc.AddInt16(f.Key, int16(f.Integer)) + case Int8Type: + enc.AddInt8(f.Key, int8(f.Integer)) + case StringType: + enc.AddString(f.Key, f.String) + case TimeType: + if f.Interface != nil { + enc.AddTime(f.Key, time.Unix(0, f.Integer).In(f.Interface.(*time.Location))) + } else { + // Fall back to UTC if location is nil. + enc.AddTime(f.Key, time.Unix(0, f.Integer)) + } + case TimeFullType: + enc.AddTime(f.Key, f.Interface.(time.Time)) + case Uint64Type: + enc.AddUint64(f.Key, uint64(f.Integer)) + case Uint32Type: + enc.AddUint32(f.Key, uint32(f.Integer)) + case Uint16Type: + enc.AddUint16(f.Key, uint16(f.Integer)) + case Uint8Type: + enc.AddUint8(f.Key, uint8(f.Integer)) + case UintptrType: + enc.AddUintptr(f.Key, uintptr(f.Integer)) + case ReflectType: + err = enc.AddReflected(f.Key, f.Interface) + case NamespaceType: + enc.OpenNamespace(f.Key) + case StringerType: + err = encodeStringer(f.Key, f.Interface, enc) + case ErrorType: + err = encodeError(f.Key, f.Interface.(error), enc) + case SkipType: + break + default: + panic(fmt.Sprintf("unknown field type: %v", f)) + } + + if err != nil { + enc.AddString(fmt.Sprintf("%sError", f.Key), err.Error()) + } +} + +// Equals returns whether two fields are equal. For non-primitive types such as +// errors, marshalers, or reflect types, it uses reflect.DeepEqual. +func (f Field) Equals(other Field) bool { + if f.Type != other.Type { + return false + } + if f.Key != other.Key { + return false + } + + switch f.Type { + case BinaryType, ByteStringType: + return bytes.Equal(f.Interface.([]byte), other.Interface.([]byte)) + case ArrayMarshalerType, ObjectMarshalerType, ErrorType, ReflectType: + return reflect.DeepEqual(f.Interface, other.Interface) + default: + return f == other + } +} + +func addFields(enc ObjectEncoder, fields []Field) { + for i := range fields { + fields[i].AddTo(enc) + } +} + +func encodeStringer(key string, stringer interface{}, enc ObjectEncoder) (retErr error) { + // Try to capture panics (from nil references or otherwise) when calling + // the String() method, similar to https://golang.org/src/fmt/print.go#L540 + defer func() { + if err := recover(); err != nil { + // If it's a nil pointer, just say "". The likeliest causes are a + // Stringer that fails to guard against nil or a nil pointer for a + // value receiver, and in either case, "" is a nice result. + if v := reflect.ValueOf(stringer); v.Kind() == reflect.Ptr && v.IsNil() { + enc.AddString(key, "") + return + } + + retErr = fmt.Errorf("PANIC=%v", err) + } + }() + + enc.AddString(key, stringer.(fmt.Stringer).String()) + return nil +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/hook.go b/tools/vendor/go.uber.org/zap/zapcore/hook.go new file mode 100644 index 00000000..5db4afb3 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/hook.go @@ -0,0 +1,68 @@ +// Copyright (c) 2016 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 zapcore + +import "go.uber.org/multierr" + +type hooked struct { + Core + funcs []func(Entry) error +} + +// RegisterHooks wraps a Core and runs a collection of user-defined callback +// hooks each time a message is logged. Execution of the callbacks is blocking. +// +// This offers users an easy way to register simple callbacks (e.g., metrics +// collection) without implementing the full Core interface. +func RegisterHooks(core Core, hooks ...func(Entry) error) Core { + funcs := append([]func(Entry) error{}, hooks...) + return &hooked{ + Core: core, + funcs: funcs, + } +} + +func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + // Let the wrapped Core decide whether to log this message or not. This + // also gives the downstream a chance to register itself directly with the + // CheckedEntry. + if downstream := h.Core.Check(ent, ce); downstream != nil { + return downstream.AddCore(ent, h) + } + return ce +} + +func (h *hooked) With(fields []Field) Core { + return &hooked{ + Core: h.Core.With(fields), + funcs: h.funcs, + } +} + +func (h *hooked) Write(ent Entry, _ []Field) error { + // Since our downstream had a chance to register itself directly with the + // CheckedMessage, we don't need to call it here. + var err error + for i := range h.funcs { + err = multierr.Append(err, h.funcs[i](ent)) + } + return err +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/increase_level.go b/tools/vendor/go.uber.org/zap/zapcore/increase_level.go new file mode 100644 index 00000000..5a174926 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/increase_level.go @@ -0,0 +1,66 @@ +// Copyright (c) 2020 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 zapcore + +import "fmt" + +type levelFilterCore struct { + core Core + level LevelEnabler +} + +// NewIncreaseLevelCore creates a core that can be used to increase the level of +// an existing Core. It cannot be used to decrease the logging level, as it acts +// as a filter before calling the underlying core. If level decreases the log level, +// an error is returned. +func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error) { + for l := _maxLevel; l >= _minLevel; l-- { + if !core.Enabled(l) && level.Enabled(l) { + return nil, fmt.Errorf("invalid increase level, as level %q is allowed by increased level, but not by existing core", l) + } + } + + return &levelFilterCore{core, level}, nil +} + +func (c *levelFilterCore) Enabled(lvl Level) bool { + return c.level.Enabled(lvl) +} + +func (c *levelFilterCore) With(fields []Field) Core { + return &levelFilterCore{c.core.With(fields), c.level} +} + +func (c *levelFilterCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + if !c.Enabled(ent.Level) { + return ce + } + + return c.core.Check(ent, ce) +} + +func (c *levelFilterCore) Write(ent Entry, fields []Field) error { + return c.core.Write(ent, fields) +} + +func (c *levelFilterCore) Sync() error { + return c.core.Sync() +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/json_encoder.go b/tools/vendor/go.uber.org/zap/zapcore/json_encoder.go new file mode 100644 index 00000000..c5d751b8 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/json_encoder.go @@ -0,0 +1,560 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "encoding/base64" + "math" + "sync" + "time" + "unicode/utf8" + + "go.uber.org/zap/buffer" + "go.uber.org/zap/internal/bufferpool" +) + +// For JSON-escaping; see jsonEncoder.safeAddString below. +const _hex = "0123456789abcdef" + +var _jsonPool = sync.Pool{New: func() interface{} { + return &jsonEncoder{} +}} + +func getJSONEncoder() *jsonEncoder { + return _jsonPool.Get().(*jsonEncoder) +} + +func putJSONEncoder(enc *jsonEncoder) { + if enc.reflectBuf != nil { + enc.reflectBuf.Free() + } + enc.EncoderConfig = nil + enc.buf = nil + enc.spaced = false + enc.openNamespaces = 0 + enc.reflectBuf = nil + enc.reflectEnc = nil + _jsonPool.Put(enc) +} + +type jsonEncoder struct { + *EncoderConfig + buf *buffer.Buffer + spaced bool // include spaces after colons and commas + openNamespaces int + + // for encoding generic values by reflection + reflectBuf *buffer.Buffer + reflectEnc ReflectedEncoder +} + +// NewJSONEncoder creates a fast, low-allocation JSON encoder. The encoder +// appropriately escapes all field keys and values. +// +// Note that the encoder doesn't deduplicate keys, so it's possible to produce +// a message like +// {"foo":"bar","foo":"baz"} +// This is permitted by the JSON specification, but not encouraged. Many +// libraries will ignore duplicate key-value pairs (typically keeping the last +// pair) when unmarshaling, but users should attempt to avoid adding duplicate +// keys. +func NewJSONEncoder(cfg EncoderConfig) Encoder { + return newJSONEncoder(cfg, false) +} + +func newJSONEncoder(cfg EncoderConfig, spaced bool) *jsonEncoder { + if cfg.SkipLineEnding { + cfg.LineEnding = "" + } else if cfg.LineEnding == "" { + cfg.LineEnding = DefaultLineEnding + } + + // If no EncoderConfig.NewReflectedEncoder is provided by the user, then use default + if cfg.NewReflectedEncoder == nil { + cfg.NewReflectedEncoder = defaultReflectedEncoder + } + + return &jsonEncoder{ + EncoderConfig: &cfg, + buf: bufferpool.Get(), + spaced: spaced, + } +} + +func (enc *jsonEncoder) AddArray(key string, arr ArrayMarshaler) error { + enc.addKey(key) + return enc.AppendArray(arr) +} + +func (enc *jsonEncoder) AddObject(key string, obj ObjectMarshaler) error { + enc.addKey(key) + return enc.AppendObject(obj) +} + +func (enc *jsonEncoder) AddBinary(key string, val []byte) { + enc.AddString(key, base64.StdEncoding.EncodeToString(val)) +} + +func (enc *jsonEncoder) AddByteString(key string, val []byte) { + enc.addKey(key) + enc.AppendByteString(val) +} + +func (enc *jsonEncoder) AddBool(key string, val bool) { + enc.addKey(key) + enc.AppendBool(val) +} + +func (enc *jsonEncoder) AddComplex128(key string, val complex128) { + enc.addKey(key) + enc.AppendComplex128(val) +} + +func (enc *jsonEncoder) AddComplex64(key string, val complex64) { + enc.addKey(key) + enc.AppendComplex64(val) +} + +func (enc *jsonEncoder) AddDuration(key string, val time.Duration) { + enc.addKey(key) + enc.AppendDuration(val) +} + +func (enc *jsonEncoder) AddFloat64(key string, val float64) { + enc.addKey(key) + enc.AppendFloat64(val) +} + +func (enc *jsonEncoder) AddFloat32(key string, val float32) { + enc.addKey(key) + enc.AppendFloat32(val) +} + +func (enc *jsonEncoder) AddInt64(key string, val int64) { + enc.addKey(key) + enc.AppendInt64(val) +} + +func (enc *jsonEncoder) resetReflectBuf() { + if enc.reflectBuf == nil { + enc.reflectBuf = bufferpool.Get() + enc.reflectEnc = enc.NewReflectedEncoder(enc.reflectBuf) + } else { + enc.reflectBuf.Reset() + } +} + +var nullLiteralBytes = []byte("null") + +// Only invoke the standard JSON encoder if there is actually something to +// encode; otherwise write JSON null literal directly. +func (enc *jsonEncoder) encodeReflected(obj interface{}) ([]byte, error) { + if obj == nil { + return nullLiteralBytes, nil + } + enc.resetReflectBuf() + if err := enc.reflectEnc.Encode(obj); err != nil { + return nil, err + } + enc.reflectBuf.TrimNewline() + return enc.reflectBuf.Bytes(), nil +} + +func (enc *jsonEncoder) AddReflected(key string, obj interface{}) error { + valueBytes, err := enc.encodeReflected(obj) + if err != nil { + return err + } + enc.addKey(key) + _, err = enc.buf.Write(valueBytes) + return err +} + +func (enc *jsonEncoder) OpenNamespace(key string) { + enc.addKey(key) + enc.buf.AppendByte('{') + enc.openNamespaces++ +} + +func (enc *jsonEncoder) AddString(key, val string) { + enc.addKey(key) + enc.AppendString(val) +} + +func (enc *jsonEncoder) AddTime(key string, val time.Time) { + enc.addKey(key) + enc.AppendTime(val) +} + +func (enc *jsonEncoder) AddUint64(key string, val uint64) { + enc.addKey(key) + enc.AppendUint64(val) +} + +func (enc *jsonEncoder) AppendArray(arr ArrayMarshaler) error { + enc.addElementSeparator() + enc.buf.AppendByte('[') + err := arr.MarshalLogArray(enc) + enc.buf.AppendByte(']') + return err +} + +func (enc *jsonEncoder) AppendObject(obj ObjectMarshaler) error { + // Close ONLY new openNamespaces that are created during + // AppendObject(). + old := enc.openNamespaces + enc.openNamespaces = 0 + enc.addElementSeparator() + enc.buf.AppendByte('{') + err := obj.MarshalLogObject(enc) + enc.buf.AppendByte('}') + enc.closeOpenNamespaces() + enc.openNamespaces = old + return err +} + +func (enc *jsonEncoder) AppendBool(val bool) { + enc.addElementSeparator() + enc.buf.AppendBool(val) +} + +func (enc *jsonEncoder) AppendByteString(val []byte) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.safeAddByteString(val) + enc.buf.AppendByte('"') +} + +// appendComplex appends the encoded form of the provided complex128 value. +// precision specifies the encoding precision for the real and imaginary +// components of the complex number. +func (enc *jsonEncoder) appendComplex(val complex128, precision int) { + enc.addElementSeparator() + // Cast to a platform-independent, fixed-size type. + r, i := float64(real(val)), float64(imag(val)) + enc.buf.AppendByte('"') + // Because we're always in a quoted string, we can use strconv without + // special-casing NaN and +/-Inf. + enc.buf.AppendFloat(r, precision) + // If imaginary part is less than 0, minus (-) sign is added by default + // by AppendFloat. + if i >= 0 { + enc.buf.AppendByte('+') + } + enc.buf.AppendFloat(i, precision) + enc.buf.AppendByte('i') + enc.buf.AppendByte('"') +} + +func (enc *jsonEncoder) AppendDuration(val time.Duration) { + cur := enc.buf.Len() + if e := enc.EncodeDuration; e != nil { + e(val, enc) + } + if cur == enc.buf.Len() { + // User-supplied EncodeDuration is a no-op. Fall back to nanoseconds to keep + // JSON valid. + enc.AppendInt64(int64(val)) + } +} + +func (enc *jsonEncoder) AppendInt64(val int64) { + enc.addElementSeparator() + enc.buf.AppendInt(val) +} + +func (enc *jsonEncoder) AppendReflected(val interface{}) error { + valueBytes, err := enc.encodeReflected(val) + if err != nil { + return err + } + enc.addElementSeparator() + _, err = enc.buf.Write(valueBytes) + return err +} + +func (enc *jsonEncoder) AppendString(val string) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.safeAddString(val) + enc.buf.AppendByte('"') +} + +func (enc *jsonEncoder) AppendTimeLayout(time time.Time, layout string) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.buf.AppendTime(time, layout) + enc.buf.AppendByte('"') +} + +func (enc *jsonEncoder) AppendTime(val time.Time) { + cur := enc.buf.Len() + if e := enc.EncodeTime; e != nil { + e(val, enc) + } + if cur == enc.buf.Len() { + // User-supplied EncodeTime is a no-op. Fall back to nanos since epoch to keep + // output JSON valid. + enc.AppendInt64(val.UnixNano()) + } +} + +func (enc *jsonEncoder) AppendUint64(val uint64) { + enc.addElementSeparator() + enc.buf.AppendUint(val) +} + +func (enc *jsonEncoder) AddInt(k string, v int) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddInt32(k string, v int32) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddInt16(k string, v int16) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddInt8(k string, v int8) { enc.AddInt64(k, int64(v)) } +func (enc *jsonEncoder) AddUint(k string, v uint) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUint32(k string, v uint32) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUint16(k string, v uint16) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUint8(k string, v uint8) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AddUintptr(k string, v uintptr) { enc.AddUint64(k, uint64(v)) } +func (enc *jsonEncoder) AppendComplex64(v complex64) { enc.appendComplex(complex128(v), 32) } +func (enc *jsonEncoder) AppendComplex128(v complex128) { enc.appendComplex(complex128(v), 64) } +func (enc *jsonEncoder) AppendFloat64(v float64) { enc.appendFloat(v, 64) } +func (enc *jsonEncoder) AppendFloat32(v float32) { enc.appendFloat(float64(v), 32) } +func (enc *jsonEncoder) AppendInt(v int) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendInt32(v int32) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendInt16(v int16) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendInt8(v int8) { enc.AppendInt64(int64(v)) } +func (enc *jsonEncoder) AppendUint(v uint) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUint32(v uint32) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUint16(v uint16) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUint8(v uint8) { enc.AppendUint64(uint64(v)) } +func (enc *jsonEncoder) AppendUintptr(v uintptr) { enc.AppendUint64(uint64(v)) } + +func (enc *jsonEncoder) Clone() Encoder { + clone := enc.clone() + clone.buf.Write(enc.buf.Bytes()) + return clone +} + +func (enc *jsonEncoder) clone() *jsonEncoder { + clone := getJSONEncoder() + clone.EncoderConfig = enc.EncoderConfig + clone.spaced = enc.spaced + clone.openNamespaces = enc.openNamespaces + clone.buf = bufferpool.Get() + return clone +} + +func (enc *jsonEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { + final := enc.clone() + final.buf.AppendByte('{') + + if final.LevelKey != "" && final.EncodeLevel != nil { + final.addKey(final.LevelKey) + cur := final.buf.Len() + final.EncodeLevel(ent.Level, final) + if cur == final.buf.Len() { + // User-supplied EncodeLevel was a no-op. Fall back to strings to keep + // output JSON valid. + final.AppendString(ent.Level.String()) + } + } + if final.TimeKey != "" { + final.AddTime(final.TimeKey, ent.Time) + } + if ent.LoggerName != "" && final.NameKey != "" { + final.addKey(final.NameKey) + cur := final.buf.Len() + nameEncoder := final.EncodeName + + // if no name encoder provided, fall back to FullNameEncoder for backwards + // compatibility + if nameEncoder == nil { + nameEncoder = FullNameEncoder + } + + nameEncoder(ent.LoggerName, final) + if cur == final.buf.Len() { + // User-supplied EncodeName was a no-op. Fall back to strings to + // keep output JSON valid. + final.AppendString(ent.LoggerName) + } + } + if ent.Caller.Defined { + if final.CallerKey != "" { + final.addKey(final.CallerKey) + cur := final.buf.Len() + final.EncodeCaller(ent.Caller, final) + if cur == final.buf.Len() { + // User-supplied EncodeCaller was a no-op. Fall back to strings to + // keep output JSON valid. + final.AppendString(ent.Caller.String()) + } + } + if final.FunctionKey != "" { + final.addKey(final.FunctionKey) + final.AppendString(ent.Caller.Function) + } + } + if final.MessageKey != "" { + final.addKey(enc.MessageKey) + final.AppendString(ent.Message) + } + if enc.buf.Len() > 0 { + final.addElementSeparator() + final.buf.Write(enc.buf.Bytes()) + } + addFields(final, fields) + final.closeOpenNamespaces() + if ent.Stack != "" && final.StacktraceKey != "" { + final.AddString(final.StacktraceKey, ent.Stack) + } + final.buf.AppendByte('}') + final.buf.AppendString(final.LineEnding) + + ret := final.buf + putJSONEncoder(final) + return ret, nil +} + +func (enc *jsonEncoder) truncate() { + enc.buf.Reset() +} + +func (enc *jsonEncoder) closeOpenNamespaces() { + for i := 0; i < enc.openNamespaces; i++ { + enc.buf.AppendByte('}') + } + enc.openNamespaces = 0 +} + +func (enc *jsonEncoder) addKey(key string) { + enc.addElementSeparator() + enc.buf.AppendByte('"') + enc.safeAddString(key) + enc.buf.AppendByte('"') + enc.buf.AppendByte(':') + if enc.spaced { + enc.buf.AppendByte(' ') + } +} + +func (enc *jsonEncoder) addElementSeparator() { + last := enc.buf.Len() - 1 + if last < 0 { + return + } + switch enc.buf.Bytes()[last] { + case '{', '[', ':', ',', ' ': + return + default: + enc.buf.AppendByte(',') + if enc.spaced { + enc.buf.AppendByte(' ') + } + } +} + +func (enc *jsonEncoder) appendFloat(val float64, bitSize int) { + enc.addElementSeparator() + switch { + case math.IsNaN(val): + enc.buf.AppendString(`"NaN"`) + case math.IsInf(val, 1): + enc.buf.AppendString(`"+Inf"`) + case math.IsInf(val, -1): + enc.buf.AppendString(`"-Inf"`) + default: + enc.buf.AppendFloat(val, bitSize) + } +} + +// safeAddString JSON-escapes a string and appends it to the internal buffer. +// Unlike the standard library's encoder, it doesn't attempt to protect the +// user from browser vulnerabilities or JSONP-related problems. +func (enc *jsonEncoder) safeAddString(s string) { + for i := 0; i < len(s); { + if enc.tryAddRuneSelf(s[i]) { + i++ + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + if enc.tryAddRuneError(r, size) { + i++ + continue + } + enc.buf.AppendString(s[i : i+size]) + i += size + } +} + +// safeAddByteString is no-alloc equivalent of safeAddString(string(s)) for s []byte. +func (enc *jsonEncoder) safeAddByteString(s []byte) { + for i := 0; i < len(s); { + if enc.tryAddRuneSelf(s[i]) { + i++ + continue + } + r, size := utf8.DecodeRune(s[i:]) + if enc.tryAddRuneError(r, size) { + i++ + continue + } + enc.buf.Write(s[i : i+size]) + i += size + } +} + +// tryAddRuneSelf appends b if it is valid UTF-8 character represented in a single byte. +func (enc *jsonEncoder) tryAddRuneSelf(b byte) bool { + if b >= utf8.RuneSelf { + return false + } + if 0x20 <= b && b != '\\' && b != '"' { + enc.buf.AppendByte(b) + return true + } + switch b { + case '\\', '"': + enc.buf.AppendByte('\\') + enc.buf.AppendByte(b) + case '\n': + enc.buf.AppendByte('\\') + enc.buf.AppendByte('n') + case '\r': + enc.buf.AppendByte('\\') + enc.buf.AppendByte('r') + case '\t': + enc.buf.AppendByte('\\') + enc.buf.AppendByte('t') + default: + // Encode bytes < 0x20, except for the escape sequences above. + enc.buf.AppendString(`\u00`) + enc.buf.AppendByte(_hex[b>>4]) + enc.buf.AppendByte(_hex[b&0xF]) + } + return true +} + +func (enc *jsonEncoder) tryAddRuneError(r rune, size int) bool { + if r == utf8.RuneError && size == 1 { + enc.buf.AppendString(`\ufffd`) + return true + } + return false +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/level.go b/tools/vendor/go.uber.org/zap/zapcore/level.go new file mode 100644 index 00000000..56e88dc0 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/level.go @@ -0,0 +1,187 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "bytes" + "errors" + "fmt" +) + +var errUnmarshalNilLevel = errors.New("can't unmarshal a nil *Level") + +// A Level is a logging priority. Higher levels are more important. +type Level int8 + +const ( + // DebugLevel logs are typically voluminous, and are usually disabled in + // production. + DebugLevel Level = iota - 1 + // InfoLevel is the default logging priority. + InfoLevel + // WarnLevel logs are more important than Info, but don't need individual + // human review. + WarnLevel + // ErrorLevel logs are high-priority. If an application is running smoothly, + // it shouldn't generate any error-level logs. + ErrorLevel + // DPanicLevel logs are particularly important errors. In development the + // logger panics after writing the message. + DPanicLevel + // PanicLevel logs a message, then panics. + PanicLevel + // FatalLevel logs a message, then calls os.Exit(1). + FatalLevel + + _minLevel = DebugLevel + _maxLevel = FatalLevel +) + +// ParseLevel parses a level based on the lower-case or all-caps ASCII +// representation of the log level. If the provided ASCII representation is +// invalid an error is returned. +// +// This is particularly useful when dealing with text input to configure log +// levels. +func ParseLevel(text string) (Level, error) { + var level Level + err := level.UnmarshalText([]byte(text)) + return level, err +} + +// String returns a lower-case ASCII representation of the log level. +func (l Level) String() string { + switch l { + case DebugLevel: + return "debug" + case InfoLevel: + return "info" + case WarnLevel: + return "warn" + case ErrorLevel: + return "error" + case DPanicLevel: + return "dpanic" + case PanicLevel: + return "panic" + case FatalLevel: + return "fatal" + default: + return fmt.Sprintf("Level(%d)", l) + } +} + +// CapitalString returns an all-caps ASCII representation of the log level. +func (l Level) CapitalString() string { + // Printing levels in all-caps is common enough that we should export this + // functionality. + switch l { + case DebugLevel: + return "DEBUG" + case InfoLevel: + return "INFO" + case WarnLevel: + return "WARN" + case ErrorLevel: + return "ERROR" + case DPanicLevel: + return "DPANIC" + case PanicLevel: + return "PANIC" + case FatalLevel: + return "FATAL" + default: + return fmt.Sprintf("LEVEL(%d)", l) + } +} + +// MarshalText marshals the Level to text. Note that the text representation +// drops the -Level suffix (see example). +func (l Level) MarshalText() ([]byte, error) { + return []byte(l.String()), nil +} + +// UnmarshalText unmarshals text to a level. Like MarshalText, UnmarshalText +// expects the text representation of a Level to drop the -Level suffix (see +// example). +// +// In particular, this makes it easy to configure logging levels using YAML, +// TOML, or JSON files. +func (l *Level) UnmarshalText(text []byte) error { + if l == nil { + return errUnmarshalNilLevel + } + if !l.unmarshalText(text) && !l.unmarshalText(bytes.ToLower(text)) { + return fmt.Errorf("unrecognized level: %q", text) + } + return nil +} + +func (l *Level) unmarshalText(text []byte) bool { + switch string(text) { + case "debug", "DEBUG": + *l = DebugLevel + case "info", "INFO", "": // make the zero value useful + *l = InfoLevel + case "warn", "WARN": + *l = WarnLevel + case "error", "ERROR": + *l = ErrorLevel + case "dpanic", "DPANIC": + *l = DPanicLevel + case "panic", "PANIC": + *l = PanicLevel + case "fatal", "FATAL": + *l = FatalLevel + default: + return false + } + return true +} + +// Set sets the level for the flag.Value interface. +func (l *Level) Set(s string) error { + return l.UnmarshalText([]byte(s)) +} + +// Get gets the level for the flag.Getter interface. +func (l *Level) Get() interface{} { + return *l +} + +// Enabled returns true if the given level is at or above this level. +func (l Level) Enabled(lvl Level) bool { + return lvl >= l +} + +// LevelEnabler decides whether a given logging level is enabled when logging a +// message. +// +// Enablers are intended to be used to implement deterministic filters; +// concerns like sampling are better implemented as a Core. +// +// Each concrete Level value implements a static LevelEnabler which returns +// true for itself and all higher logging levels. For example WarnLevel.Enabled() +// will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, and +// FatalLevel, but return false for InfoLevel and DebugLevel. +type LevelEnabler interface { + Enabled(Level) bool +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/level_strings.go b/tools/vendor/go.uber.org/zap/zapcore/level_strings.go new file mode 100644 index 00000000..7af8dadc --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/level_strings.go @@ -0,0 +1,46 @@ +// Copyright (c) 2016 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 zapcore + +import "go.uber.org/zap/internal/color" + +var ( + _levelToColor = map[Level]color.Color{ + DebugLevel: color.Magenta, + InfoLevel: color.Blue, + WarnLevel: color.Yellow, + ErrorLevel: color.Red, + DPanicLevel: color.Red, + PanicLevel: color.Red, + FatalLevel: color.Red, + } + _unknownLevelColor = color.Red + + _levelToLowercaseColorString = make(map[Level]string, len(_levelToColor)) + _levelToCapitalColorString = make(map[Level]string, len(_levelToColor)) +) + +func init() { + for level, color := range _levelToColor { + _levelToLowercaseColorString[level] = color.Add(level.String()) + _levelToCapitalColorString[level] = color.Add(level.CapitalString()) + } +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/marshaler.go b/tools/vendor/go.uber.org/zap/zapcore/marshaler.go new file mode 100644 index 00000000..c3c55ba0 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/marshaler.go @@ -0,0 +1,61 @@ +// Copyright (c) 2016 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 zapcore + +// ObjectMarshaler allows user-defined types to efficiently add themselves to the +// logging context, and to selectively omit information which shouldn't be +// included in logs (e.g., passwords). +// +// Note: ObjectMarshaler is only used when zap.Object is used or when +// passed directly to zap.Any. It is not used when reflection-based +// encoding is used. +type ObjectMarshaler interface { + MarshalLogObject(ObjectEncoder) error +} + +// ObjectMarshalerFunc is a type adapter that turns a function into an +// ObjectMarshaler. +type ObjectMarshalerFunc func(ObjectEncoder) error + +// MarshalLogObject calls the underlying function. +func (f ObjectMarshalerFunc) MarshalLogObject(enc ObjectEncoder) error { + return f(enc) +} + +// ArrayMarshaler allows user-defined types to efficiently add themselves to the +// logging context, and to selectively omit information which shouldn't be +// included in logs (e.g., passwords). +// +// Note: ArrayMarshaler is only used when zap.Array is used or when +// passed directly to zap.Any. It is not used when reflection-based +// encoding is used. +type ArrayMarshaler interface { + MarshalLogArray(ArrayEncoder) error +} + +// ArrayMarshalerFunc is a type adapter that turns a function into an +// ArrayMarshaler. +type ArrayMarshalerFunc func(ArrayEncoder) error + +// MarshalLogArray calls the underlying function. +func (f ArrayMarshalerFunc) MarshalLogArray(enc ArrayEncoder) error { + return f(enc) +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/memory_encoder.go b/tools/vendor/go.uber.org/zap/zapcore/memory_encoder.go new file mode 100644 index 00000000..dfead082 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/memory_encoder.go @@ -0,0 +1,179 @@ +// Copyright (c) 2016 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 zapcore + +import "time" + +// MapObjectEncoder is an ObjectEncoder backed by a simple +// map[string]interface{}. It's not fast enough for production use, but it's +// helpful in tests. +type MapObjectEncoder struct { + // Fields contains the entire encoded log context. + Fields map[string]interface{} + // cur is a pointer to the namespace we're currently writing to. + cur map[string]interface{} +} + +// NewMapObjectEncoder creates a new map-backed ObjectEncoder. +func NewMapObjectEncoder() *MapObjectEncoder { + m := make(map[string]interface{}) + return &MapObjectEncoder{ + Fields: m, + cur: m, + } +} + +// AddArray implements ObjectEncoder. +func (m *MapObjectEncoder) AddArray(key string, v ArrayMarshaler) error { + arr := &sliceArrayEncoder{elems: make([]interface{}, 0)} + err := v.MarshalLogArray(arr) + m.cur[key] = arr.elems + return err +} + +// AddObject implements ObjectEncoder. +func (m *MapObjectEncoder) AddObject(k string, v ObjectMarshaler) error { + newMap := NewMapObjectEncoder() + m.cur[k] = newMap.Fields + return v.MarshalLogObject(newMap) +} + +// AddBinary implements ObjectEncoder. +func (m *MapObjectEncoder) AddBinary(k string, v []byte) { m.cur[k] = v } + +// AddByteString implements ObjectEncoder. +func (m *MapObjectEncoder) AddByteString(k string, v []byte) { m.cur[k] = string(v) } + +// AddBool implements ObjectEncoder. +func (m *MapObjectEncoder) AddBool(k string, v bool) { m.cur[k] = v } + +// AddDuration implements ObjectEncoder. +func (m MapObjectEncoder) AddDuration(k string, v time.Duration) { m.cur[k] = v } + +// AddComplex128 implements ObjectEncoder. +func (m *MapObjectEncoder) AddComplex128(k string, v complex128) { m.cur[k] = v } + +// AddComplex64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddComplex64(k string, v complex64) { m.cur[k] = v } + +// AddFloat64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddFloat64(k string, v float64) { m.cur[k] = v } + +// AddFloat32 implements ObjectEncoder. +func (m *MapObjectEncoder) AddFloat32(k string, v float32) { m.cur[k] = v } + +// AddInt implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt(k string, v int) { m.cur[k] = v } + +// AddInt64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt64(k string, v int64) { m.cur[k] = v } + +// AddInt32 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt32(k string, v int32) { m.cur[k] = v } + +// AddInt16 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt16(k string, v int16) { m.cur[k] = v } + +// AddInt8 implements ObjectEncoder. +func (m *MapObjectEncoder) AddInt8(k string, v int8) { m.cur[k] = v } + +// AddString implements ObjectEncoder. +func (m *MapObjectEncoder) AddString(k string, v string) { m.cur[k] = v } + +// AddTime implements ObjectEncoder. +func (m MapObjectEncoder) AddTime(k string, v time.Time) { m.cur[k] = v } + +// AddUint implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint(k string, v uint) { m.cur[k] = v } + +// AddUint64 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint64(k string, v uint64) { m.cur[k] = v } + +// AddUint32 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint32(k string, v uint32) { m.cur[k] = v } + +// AddUint16 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint16(k string, v uint16) { m.cur[k] = v } + +// AddUint8 implements ObjectEncoder. +func (m *MapObjectEncoder) AddUint8(k string, v uint8) { m.cur[k] = v } + +// AddUintptr implements ObjectEncoder. +func (m *MapObjectEncoder) AddUintptr(k string, v uintptr) { m.cur[k] = v } + +// AddReflected implements ObjectEncoder. +func (m *MapObjectEncoder) AddReflected(k string, v interface{}) error { + m.cur[k] = v + return nil +} + +// OpenNamespace implements ObjectEncoder. +func (m *MapObjectEncoder) OpenNamespace(k string) { + ns := make(map[string]interface{}) + m.cur[k] = ns + m.cur = ns +} + +// sliceArrayEncoder is an ArrayEncoder backed by a simple []interface{}. Like +// the MapObjectEncoder, it's not designed for production use. +type sliceArrayEncoder struct { + elems []interface{} +} + +func (s *sliceArrayEncoder) AppendArray(v ArrayMarshaler) error { + enc := &sliceArrayEncoder{} + err := v.MarshalLogArray(enc) + s.elems = append(s.elems, enc.elems) + return err +} + +func (s *sliceArrayEncoder) AppendObject(v ObjectMarshaler) error { + m := NewMapObjectEncoder() + err := v.MarshalLogObject(m) + s.elems = append(s.elems, m.Fields) + return err +} + +func (s *sliceArrayEncoder) AppendReflected(v interface{}) error { + s.elems = append(s.elems, v) + return nil +} + +func (s *sliceArrayEncoder) AppendBool(v bool) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendByteString(v []byte) { s.elems = append(s.elems, string(v)) } +func (s *sliceArrayEncoder) AppendComplex128(v complex128) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendComplex64(v complex64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendDuration(v time.Duration) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendFloat64(v float64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendFloat32(v float32) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt(v int) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt64(v int64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt32(v int32) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt16(v int16) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendInt8(v int8) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendString(v string) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendTime(v time.Time) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint(v uint) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint64(v uint64) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint32(v uint32) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint16(v uint16) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUint8(v uint8) { s.elems = append(s.elems, v) } +func (s *sliceArrayEncoder) AppendUintptr(v uintptr) { s.elems = append(s.elems, v) } diff --git a/tools/vendor/go.uber.org/zap/zapcore/reflected_encoder.go b/tools/vendor/go.uber.org/zap/zapcore/reflected_encoder.go new file mode 100644 index 00000000..8746360e --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/reflected_encoder.go @@ -0,0 +1,41 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "encoding/json" + "io" +) + +// ReflectedEncoder serializes log fields that can't be serialized with Zap's +// JSON encoder. These have the ReflectType field type. +// Use EncoderConfig.NewReflectedEncoder to set this. +type ReflectedEncoder interface { + // Encode encodes and writes to the underlying data stream. + Encode(interface{}) error +} + +func defaultReflectedEncoder(w io.Writer) ReflectedEncoder { + enc := json.NewEncoder(w) + // For consistency with our custom JSON encoder. + enc.SetEscapeHTML(false) + return enc +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/sampler.go b/tools/vendor/go.uber.org/zap/zapcore/sampler.go new file mode 100644 index 00000000..8c116049 --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/sampler.go @@ -0,0 +1,221 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "time" + + "go.uber.org/atomic" +) + +const ( + _numLevels = _maxLevel - _minLevel + 1 + _countersPerLevel = 4096 +) + +type counter struct { + resetAt atomic.Int64 + counter atomic.Uint64 +} + +type counters [_numLevels][_countersPerLevel]counter + +func newCounters() *counters { + return &counters{} +} + +func (cs *counters) get(lvl Level, key string) *counter { + i := lvl - _minLevel + j := fnv32a(key) % _countersPerLevel + return &cs[i][j] +} + +// fnv32a, adapted from "hash/fnv", but without a []byte(string) alloc +func fnv32a(s string) uint32 { + const ( + offset32 = 2166136261 + prime32 = 16777619 + ) + hash := uint32(offset32) + for i := 0; i < len(s); i++ { + hash ^= uint32(s[i]) + hash *= prime32 + } + return hash +} + +func (c *counter) IncCheckReset(t time.Time, tick time.Duration) uint64 { + tn := t.UnixNano() + resetAfter := c.resetAt.Load() + if resetAfter > tn { + return c.counter.Inc() + } + + c.counter.Store(1) + + newResetAfter := tn + tick.Nanoseconds() + if !c.resetAt.CAS(resetAfter, newResetAfter) { + // We raced with another goroutine trying to reset, and it also reset + // the counter to 1, so we need to reincrement the counter. + return c.counter.Inc() + } + + return 1 +} + +// SamplingDecision is a decision represented as a bit field made by sampler. +// More decisions may be added in the future. +type SamplingDecision uint32 + +const ( + // LogDropped indicates that the Sampler dropped a log entry. + LogDropped SamplingDecision = 1 << iota + // LogSampled indicates that the Sampler sampled a log entry. + LogSampled +) + +// optionFunc wraps a func so it satisfies the SamplerOption interface. +type optionFunc func(*sampler) + +func (f optionFunc) apply(s *sampler) { + f(s) +} + +// SamplerOption configures a Sampler. +type SamplerOption interface { + apply(*sampler) +} + +// nopSamplingHook is the default hook used by sampler. +func nopSamplingHook(Entry, SamplingDecision) {} + +// SamplerHook registers a function which will be called when Sampler makes a +// decision. +// +// This hook may be used to get visibility into the performance of the sampler. +// For example, use it to track metrics of dropped versus sampled logs. +// +// var dropped atomic.Int64 +// zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) { +// if dec&zapcore.LogDropped > 0 { +// dropped.Inc() +// } +// }) +func SamplerHook(hook func(entry Entry, dec SamplingDecision)) SamplerOption { + return optionFunc(func(s *sampler) { + s.hook = hook + }) +} + +// NewSamplerWithOptions creates a Core that samples incoming entries, which +// caps the CPU and I/O load of logging while attempting to preserve a +// representative subset of your logs. +// +// Zap samples by logging the first N entries with a given level and message +// each tick. If more Entries with the same level and message are seen during +// the same interval, every Mth message is logged and the rest are dropped. +// +// For example, +// +// core = NewSamplerWithOptions(core, time.Second, 10, 5) +// +// This will log the first 10 log entries with the same level and message +// in a one second interval as-is. Following that, it will allow through +// every 5th log entry with the same level and message in that interval. +// +// If thereafter is zero, the Core will drop all log entries after the first N +// in that interval. +// +// Sampler can be configured to report sampling decisions with the SamplerHook +// option. +// +// Keep in mind that Zap's sampling implementation is optimized for speed over +// absolute precision; under load, each tick may be slightly over- or +// under-sampled. +func NewSamplerWithOptions(core Core, tick time.Duration, first, thereafter int, opts ...SamplerOption) Core { + s := &sampler{ + Core: core, + tick: tick, + counts: newCounters(), + first: uint64(first), + thereafter: uint64(thereafter), + hook: nopSamplingHook, + } + for _, opt := range opts { + opt.apply(s) + } + + return s +} + +type sampler struct { + Core + + counts *counters + tick time.Duration + first, thereafter uint64 + hook func(Entry, SamplingDecision) +} + +// NewSampler creates a Core that samples incoming entries, which +// caps the CPU and I/O load of logging while attempting to preserve a +// representative subset of your logs. +// +// Zap samples by logging the first N entries with a given level and message +// each tick. If more Entries with the same level and message are seen during +// the same interval, every Mth message is logged and the rest are dropped. +// +// Keep in mind that zap's sampling implementation is optimized for speed over +// absolute precision; under load, each tick may be slightly over- or +// under-sampled. +// +// Deprecated: use NewSamplerWithOptions. +func NewSampler(core Core, tick time.Duration, first, thereafter int) Core { + return NewSamplerWithOptions(core, tick, first, thereafter) +} + +func (s *sampler) With(fields []Field) Core { + return &sampler{ + Core: s.Core.With(fields), + tick: s.tick, + counts: s.counts, + first: s.first, + thereafter: s.thereafter, + hook: s.hook, + } +} + +func (s *sampler) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + if !s.Enabled(ent.Level) { + return ce + } + + if ent.Level >= _minLevel && ent.Level <= _maxLevel { + counter := s.counts.get(ent.Level, ent.Message) + n := counter.IncCheckReset(ent.Time, s.tick) + if n > s.first && (s.thereafter == 0 || (n-s.first)%s.thereafter != 0) { + s.hook(ent, LogDropped) + return ce + } + s.hook(ent, LogSampled) + } + return s.Core.Check(ent, ce) +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/tee.go b/tools/vendor/go.uber.org/zap/zapcore/tee.go new file mode 100644 index 00000000..07a32eef --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/tee.go @@ -0,0 +1,81 @@ +// Copyright (c) 2016 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 zapcore + +import "go.uber.org/multierr" + +type multiCore []Core + +// NewTee creates a Core that duplicates log entries into two or more +// underlying Cores. +// +// Calling it with a single Core returns the input unchanged, and calling +// it with no input returns a no-op Core. +func NewTee(cores ...Core) Core { + switch len(cores) { + case 0: + return NewNopCore() + case 1: + return cores[0] + default: + return multiCore(cores) + } +} + +func (mc multiCore) With(fields []Field) Core { + clone := make(multiCore, len(mc)) + for i := range mc { + clone[i] = mc[i].With(fields) + } + return clone +} + +func (mc multiCore) Enabled(lvl Level) bool { + for i := range mc { + if mc[i].Enabled(lvl) { + return true + } + } + return false +} + +func (mc multiCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { + for i := range mc { + ce = mc[i].Check(ent, ce) + } + return ce +} + +func (mc multiCore) Write(ent Entry, fields []Field) error { + var err error + for i := range mc { + err = multierr.Append(err, mc[i].Write(ent, fields)) + } + return err +} + +func (mc multiCore) Sync() error { + var err error + for i := range mc { + err = multierr.Append(err, mc[i].Sync()) + } + return err +} diff --git a/tools/vendor/go.uber.org/zap/zapcore/write_syncer.go b/tools/vendor/go.uber.org/zap/zapcore/write_syncer.go new file mode 100644 index 00000000..d4a1af3d --- /dev/null +++ b/tools/vendor/go.uber.org/zap/zapcore/write_syncer.go @@ -0,0 +1,122 @@ +// Copyright (c) 2016 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 zapcore + +import ( + "io" + "sync" + + "go.uber.org/multierr" +) + +// A WriteSyncer is an io.Writer that can also flush any buffered data. Note +// that *os.File (and thus, os.Stderr and os.Stdout) implement WriteSyncer. +type WriteSyncer interface { + io.Writer + Sync() error +} + +// AddSync converts an io.Writer to a WriteSyncer. It attempts to be +// intelligent: if the concrete type of the io.Writer implements WriteSyncer, +// we'll use the existing Sync method. If it doesn't, we'll add a no-op Sync. +func AddSync(w io.Writer) WriteSyncer { + switch w := w.(type) { + case WriteSyncer: + return w + default: + return writerWrapper{w} + } +} + +type lockedWriteSyncer struct { + sync.Mutex + ws WriteSyncer +} + +// Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. In +// particular, *os.Files must be locked before use. +func Lock(ws WriteSyncer) WriteSyncer { + if _, ok := ws.(*lockedWriteSyncer); ok { + // no need to layer on another lock + return ws + } + return &lockedWriteSyncer{ws: ws} +} + +func (s *lockedWriteSyncer) Write(bs []byte) (int, error) { + s.Lock() + n, err := s.ws.Write(bs) + s.Unlock() + return n, err +} + +func (s *lockedWriteSyncer) Sync() error { + s.Lock() + err := s.ws.Sync() + s.Unlock() + return err +} + +type writerWrapper struct { + io.Writer +} + +func (w writerWrapper) Sync() error { + return nil +} + +type multiWriteSyncer []WriteSyncer + +// NewMultiWriteSyncer creates a WriteSyncer that duplicates its writes +// and sync calls, much like io.MultiWriter. +func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer { + if len(ws) == 1 { + return ws[0] + } + return multiWriteSyncer(ws) +} + +// See https://golang.org/src/io/multi.go +// When not all underlying syncers write the same number of bytes, +// the smallest number is returned even though Write() is called on +// all of them. +func (ws multiWriteSyncer) Write(p []byte) (int, error) { + var writeErr error + nWritten := 0 + for _, w := range ws { + n, err := w.Write(p) + writeErr = multierr.Append(writeErr, err) + if nWritten == 0 && n != 0 { + nWritten = n + } else if n < nWritten { + nWritten = n + } + } + return nWritten, writeErr +} + +func (ws multiWriteSyncer) Sync() error { + var err error + for _, w := range ws { + err = multierr.Append(err, w.Sync()) + } + return err +} diff --git a/tools/vendor/golang.org/x/crypto/AUTHORS b/tools/vendor/golang.org/x/crypto/AUTHORS deleted file mode 100644 index 2b00ddba..00000000 --- a/tools/vendor/golang.org/x/crypto/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at https://tip.golang.org/AUTHORS. diff --git a/tools/vendor/golang.org/x/crypto/CONTRIBUTORS b/tools/vendor/golang.org/x/crypto/CONTRIBUTORS deleted file mode 100644 index 1fbd3e97..00000000 --- a/tools/vendor/golang.org/x/crypto/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at https://tip.golang.org/CONTRIBUTORS. diff --git a/tools/vendor/golang.org/x/crypto/curve25519/curve25519.go b/tools/vendor/golang.org/x/crypto/curve25519/curve25519.go index cda3fdd3..bc62161d 100644 --- a/tools/vendor/golang.org/x/crypto/curve25519/curve25519.go +++ b/tools/vendor/golang.org/x/crypto/curve25519/curve25519.go @@ -9,7 +9,8 @@ package curve25519 // import "golang.org/x/crypto/curve25519" import ( "crypto/subtle" - "fmt" + "errors" + "strconv" "golang.org/x/crypto/curve25519/internal/field" ) @@ -124,10 +125,10 @@ func X25519(scalar, point []byte) ([]byte, error) { func x25519(dst *[32]byte, scalar, point []byte) ([]byte, error) { var in [32]byte if l := len(scalar); l != 32 { - return nil, fmt.Errorf("bad scalar length: %d, expected %d", l, 32) + return nil, errors.New("bad scalar length: " + strconv.Itoa(l) + ", expected 32") } if l := len(point); l != 32 { - return nil, fmt.Errorf("bad point length: %d, expected %d", l, 32) + return nil, errors.New("bad point length: " + strconv.Itoa(l) + ", expected 32") } copy(in[:], scalar) if &point[0] == &Basepoint[0] { @@ -138,7 +139,7 @@ func x25519(dst *[32]byte, scalar, point []byte) ([]byte, error) { copy(base[:], point) ScalarMult(dst, &in, &base) if subtle.ConstantTimeCompare(dst[:], zero[:]) == 1 { - return nil, fmt.Errorf("bad input point: low order point") + return nil, errors.New("bad input point: low order point") } } return dst[:], nil diff --git a/tools/vendor/golang.org/x/crypto/ssh/agent/client.go b/tools/vendor/golang.org/x/crypto/ssh/agent/client.go index dbc79d58..3c4d18a1 100644 --- a/tools/vendor/golang.org/x/crypto/ssh/agent/client.go +++ b/tools/vendor/golang.org/x/crypto/ssh/agent/client.go @@ -772,7 +772,7 @@ func (s *agentKeyringSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, } func (s *agentKeyringSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*ssh.Signature, error) { - if algorithm == "" || algorithm == s.pub.Type() { + if algorithm == "" || algorithm == underlyingAlgo(s.pub.Type()) { return s.Sign(rand, data) } @@ -791,6 +791,33 @@ func (s *agentKeyringSigner) SignWithAlgorithm(rand io.Reader, data []byte, algo var _ ssh.AlgorithmSigner = &agentKeyringSigner{} +// certKeyAlgoNames is a mapping from known certificate algorithm names to the +// corresponding public key signature algorithm. +// +// This map must be kept in sync with the one in certs.go. +var certKeyAlgoNames = map[string]string{ + ssh.CertAlgoRSAv01: ssh.KeyAlgoRSA, + ssh.CertAlgoRSASHA256v01: ssh.KeyAlgoRSASHA256, + ssh.CertAlgoRSASHA512v01: ssh.KeyAlgoRSASHA512, + ssh.CertAlgoDSAv01: ssh.KeyAlgoDSA, + ssh.CertAlgoECDSA256v01: ssh.KeyAlgoECDSA256, + ssh.CertAlgoECDSA384v01: ssh.KeyAlgoECDSA384, + ssh.CertAlgoECDSA521v01: ssh.KeyAlgoECDSA521, + ssh.CertAlgoSKECDSA256v01: ssh.KeyAlgoSKECDSA256, + ssh.CertAlgoED25519v01: ssh.KeyAlgoED25519, + ssh.CertAlgoSKED25519v01: ssh.KeyAlgoSKED25519, +} + +// underlyingAlgo returns the signature algorithm associated with algo (which is +// an advertised or negotiated public key or host key algorithm). These are +// usually the same, except for certificate algorithms. +func underlyingAlgo(algo string) string { + if a, ok := certKeyAlgoNames[algo]; ok { + return a + } + return algo +} + // Calls an extension method. It is up to the agent implementation as to whether or not // any particular extension is supported and may always return an error. Because the // type of the response is up to the implementation, this returns the bytes of the diff --git a/tools/vendor/golang.org/x/crypto/ssh/certs.go b/tools/vendor/golang.org/x/crypto/ssh/certs.go index a69e2249..4600c207 100644 --- a/tools/vendor/golang.org/x/crypto/ssh/certs.go +++ b/tools/vendor/golang.org/x/crypto/ssh/certs.go @@ -460,6 +460,8 @@ func (c *Certificate) SignCert(rand io.Reader, authority Signer) error { // certKeyAlgoNames is a mapping from known certificate algorithm names to the // corresponding public key signature algorithm. +// +// This map must be kept in sync with the one in agent/client.go. var certKeyAlgoNames = map[string]string{ CertAlgoRSAv01: KeyAlgoRSA, CertAlgoRSASHA256v01: KeyAlgoRSASHA256, diff --git a/tools/vendor/golang.org/x/exp/LICENSE b/tools/vendor/golang.org/x/exp/LICENSE new file mode 100644 index 00000000..6a66aea5 --- /dev/null +++ b/tools/vendor/golang.org/x/exp/LICENSE @@ -0,0 +1,27 @@ +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/golang.org/x/exp/PATENTS b/tools/vendor/golang.org/x/exp/PATENTS new file mode 100644 index 00000000..73309904 --- /dev/null +++ b/tools/vendor/golang.org/x/exp/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/tools/vendor/golang.org/x/exp/constraints/constraints.go b/tools/vendor/golang.org/x/exp/constraints/constraints.go new file mode 100644 index 00000000..2c033dff --- /dev/null +++ b/tools/vendor/golang.org/x/exp/constraints/constraints.go @@ -0,0 +1,50 @@ +// 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 constraints defines a set of useful constraints to be used +// with type parameters. +package constraints + +// Signed is a constraint that permits any signed integer type. +// If future releases of Go add new predeclared signed integer types, +// this constraint will be modified to include them. +type Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +// Unsigned is a constraint that permits any unsigned integer type. +// If future releases of Go add new predeclared unsigned integer types, +// this constraint will be modified to include them. +type Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +// Integer is a constraint that permits any integer type. +// If future releases of Go add new predeclared integer types, +// this constraint will be modified to include them. +type Integer interface { + Signed | Unsigned +} + +// Float is a constraint that permits any floating-point type. +// If future releases of Go add new predeclared floating-point types, +// this constraint will be modified to include them. +type Float interface { + ~float32 | ~float64 +} + +// Complex is a constraint that permits any complex numeric type. +// If future releases of Go add new predeclared complex numeric types, +// this constraint will be modified to include them. +type Complex interface { + ~complex64 | ~complex128 +} + +// Ordered is a constraint that permits any ordered type: any type +// that supports the operators < <= >= >. +// If future releases of Go add new ordered types, +// this constraint will be modified to include them. +type Ordered interface { + Integer | Float | ~string +} diff --git a/tools/vendor/golang.org/x/exp/slices/slices.go b/tools/vendor/golang.org/x/exp/slices/slices.go new file mode 100644 index 00000000..8a237c5d --- /dev/null +++ b/tools/vendor/golang.org/x/exp/slices/slices.go @@ -0,0 +1,218 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package 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" + +// 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 { + if len(s1) != len(s2) { + return false + } + for i := range s1 { + if s1[i] != s2[i] { + return false + } + } + return true +} + +// EqualFunc reports whether two slices are equal using a comparison +// 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 { + if len(s1) != len(s2) { + return false + } + for i, v1 := range s1 { + v2 := s2[i] + if !eq(v1, v2) { + return false + } + } + return true +} + +// Compare compares the elements of s1 and s2. +// 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) + for i, v1 := range s1 { + if i >= s2len { + return +1 + } + v2 := s2[i] + switch { + case v1 < v2: + return -1 + case v1 > v2: + return +1 + } + } + if len(s1) < s2len { + 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. +// 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) + for i, v1 := range s1 { + if i >= s2len { + return +1 + } + v2 := s2[i] + if c := cmp(v1, v2); c != 0 { + return c + } + } + if len(s1) < s2len { + return -1 + } + return 0 +} + +// 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 { + for i, vs := range s { + if v == vs { + return i + } + } + return -1 +} + +// 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 { + for i, v := range s { + if f(v) { + return i + } + } + return -1 +} + +// Contains reports whether v is present in s. +func Contains[E comparable](s []E, v E) bool { + return Index(s, v) >= 0 +} + +// Insert inserts the values v... into s at index i, +// returning the modified slice. +// In the returned slice r, r[i] == v[0]. +// 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:]) + copy(s2[i:], v) + return s2 + } + s2 := make(S, tot) + copy(s2, s[:i]) + copy(s2[i:], v) + copy(s2[i+len(v):], s[i:]) + return s2 +} + +// 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-i)), 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. +func Delete[S ~[]E, E any](s S, i, j int) S { + return append(s[:i], s[j:]...) +} + +// Clone returns a copy of the slice. +// The elements are copied using assignment, so this is a shallow clone. +func Clone[S ~[]E, E any](s S) S { + // Preserve nil in case it matters. + if s == nil { + return nil + } + return append(S([]E{}), 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. +func Compact[S ~[]E, E comparable](s S) S { + if len(s) == 0 { + return s + } + i := 1 + last := s[0] + for _, v := range s[1:] { + if v != last { + s[i] = v + i++ + last = v + } + } + return s[:i] +} + +// CompactFunc is like Compact but uses a comparison function. +func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S { + if len(s) == 0 { + return s + } + i := 1 + last := s[0] + for _, v := range s[1:] { + if !eq(v, last) { + s[i] = v + i++ + last = v + } + } + return s[:i] +} + +// Grow increases the slice's capacity, if necessary, to guarantee space for +// another n elements. After Grow(n), at least n elements can be appended +// to the slice without another allocation. Grow may modify elements of the +// slice between the length and the capacity. If n is negative or too large to +// allocate the memory, Grow panics. +func Grow[S ~[]E, E any](s S, n int) S { + return append(s, make(S, n)...)[:len(s)] +} + +// Clip removes unused capacity from the slice, returning s[:len(s):len(s)]. +func Clip[S ~[]E, E any](s S) S { + return s[:len(s):len(s)] +} diff --git a/tools/vendor/golang.org/x/exp/slices/sort.go b/tools/vendor/golang.org/x/exp/slices/sort.go new file mode 100644 index 00000000..c22e74bd --- /dev/null +++ b/tools/vendor/golang.org/x/exp/slices/sort.go @@ -0,0 +1,127 @@ +// 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 slices + +import ( + "math/bits" + + "golang.org/x/exp/constraints" +) + +// 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) { + 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 requires that less 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) { + n := len(x) + pdqsortLessFunc(x, 0, n, bits.Len(uint(n)), less) +} + +// SortStable 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) +} + +// IsSorted reports whether x is sorted in ascending order. +func IsSorted[E constraints.Ordered](x []E) bool { + for i := len(x) - 1; i > 0; i-- { + if 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 { + for i := len(x) - 1; i > 0; i-- { + if less(x[i], x[i-1]) { + return false + } + } + return true +} + +// 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) { + // search returns the leftmost position where f returns true, or len(x) if f + // returns false for all x. This is the insertion position for target in x, + // and could point to an element that's either == target or not. + pos := search(len(x), func(i int) bool { return x[i] >= target }) + if pos >= len(x) || x[pos] != target { + return pos, false + } else { + return pos, true + } +} + +// 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(a, b) is expected to return an integer comparing the two +// parameters: 0 if a == b, a negative number if a < b and a positive number if +// a > b. +func BinarySearchFunc[E any](x []E, target E, cmp func(E, E) int) (int, bool) { + pos := search(len(x), func(i int) bool { return cmp(x[i], target) >= 0 }) + if pos >= len(x) || cmp(x[pos], target) != 0 { + return pos, false + } else { + return pos, true + } +} + +func search(n int, f func(int) bool) int { + // Define f(-1) == false and f(n) == true. + // Invariant: f(i-1) == false, f(j) == true. + i, j := 0, n + for i < j { + h := int(uint(i+j) >> 1) // avoid overflow when computing h + // i ≤ h < j + if !f(h) { + i = h + 1 // preserves f(i-1) == false + } else { + j = h // preserves f(j) == true + } + } + // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i. + return i +} + +type sortedHint int // hint for pdqsort when choosing the pivot + +const ( + unknownHint sortedHint = iota + increasingHint + decreasingHint +) + +// xorshift paper: https://www.jstatsoft.org/article/view/v008i14/xorshift.pdf +type xorshift uint64 + +func (r *xorshift) Next() uint64 { + *r ^= *r << 13 + *r ^= *r >> 17 + *r ^= *r << 5 + return uint64(*r) +} + +func nextPowerOfTwo(length int) uint { + return 1 << bits.Len(uint(length)) +} diff --git a/tools/vendor/golang.org/x/exp/slices/zsortfunc.go b/tools/vendor/golang.org/x/exp/slices/zsortfunc.go new file mode 100644 index 00000000..2a632476 --- /dev/null +++ b/tools/vendor/golang.org/x/exp/slices/zsortfunc.go @@ -0,0 +1,479 @@ +// Code generated by gen_sort_variants.go; DO NOT EDIT. + +// 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 slices + +// insertionSortLessFunc sorts data[a:b] using insertion sort. +func insertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { + for i := a + 1; i < b; i++ { + for j := i; j > a && less(data[j], data[j-1]); j-- { + data[j], data[j-1] = data[j-1], data[j] + } + } +} + +// siftDownLessFunc 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) { + root := lo + for { + child := 2*root + 1 + if child >= hi { + break + } + if child+1 < hi && less(data[first+child], data[first+child+1]) { + child++ + } + if !less(data[first+root], data[first+child]) { + return + } + data[first+root], data[first+child] = data[first+child], data[first+root] + root = child + } +} + +func heapSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { + 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) + } + + // 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) + } +} + +// pdqsortLessFunc 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) { + const maxInsertion = 12 + + var ( + wasBalanced = true // whether the last partitioning was reasonably balanced + wasPartitioned = true // whether the slice was already partitioned + ) + + for { + length := b - a + + if length <= maxInsertion { + insertionSortLessFunc(data, a, b, less) + return + } + + // Fall back to heapsort if too many bad choices were made. + if limit == 0 { + heapSortLessFunc(data, a, b, less) + return + } + + // If the last partitioning was imbalanced, we need to breaking patterns. + if !wasBalanced { + breakPatternsLessFunc(data, a, b, less) + limit-- + } + + pivot, hint := choosePivotLessFunc(data, a, b, less) + if hint == decreasingHint { + reverseRangeLessFunc(data, a, b, less) + // 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. + pivot = (b - 1) - (pivot - a) + hint = increasingHint + } + + // The slice is likely already sorted. + if wasBalanced && wasPartitioned && hint == increasingHint { + if partialInsertionSortLessFunc(data, a, b, less) { + 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) + a = mid + continue + } + + mid, alreadyPartitioned := partitionLessFunc(data, a, b, pivot, less) + wasPartitioned = alreadyPartitioned + + leftLen, rightLen := mid-a, b-mid + balanceThreshold := length / 8 + if leftLen < rightLen { + wasBalanced = leftLen >= balanceThreshold + pdqsortLessFunc(data, a, mid, limit, less) + a = mid + 1 + } else { + wasBalanced = rightLen >= balanceThreshold + pdqsortLessFunc(data, mid+1, b, limit, less) + b = mid + } + } +} + +// partitionLessFunc 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) { + 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]) { + i++ + } + for i <= j && !less(data[j], data[a]) { + j-- + } + if i > j { + data[j], data[a] = data[a], data[j] + return j, true + } + data[i], data[j] = data[j], data[i] + i++ + j-- + + for { + for i <= j && less(data[i], data[a]) { + i++ + } + for i <= j && !less(data[j], data[a]) { + j-- + } + if i > j { + break + } + data[i], data[j] = data[j], data[i] + i++ + j-- + } + data[j], data[a] = data[a], data[j] + return j, false +} + +// partitionEqualLessFunc 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) { + 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]) { + i++ + } + for i <= j && less(data[a], data[j]) { + j-- + } + if i > j { + break + } + data[i], data[j] = data[j], data[i] + i++ + j-- + } + 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 { + 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]) { + i++ + } + + if i == b { + return true + } + + if b-a < shortestShifting { + return false + } + + data[i], data[i-1] = data[i-1], data[i] + + // 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]) { + break + } + data[j], data[j-1] = data[j-1], data[j] + } + } + // 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]) { + break + } + data[j], data[j-1] = data[j-1], data[j] + } + } + } + return false +} + +// breakPatternsLessFunc 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) { + length := b - a + if length >= 8 { + random := xorshift(length) + modulus := nextPowerOfTwo(length) + + for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ { + other := int(uint(random.Next()) & (modulus - 1)) + if other >= length { + other -= length + } + data[idx], data[a+other] = data[a+other], data[idx] + } + } +} + +// choosePivotLessFunc 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) { + const ( + shortestNinther = 50 + maxSwaps = 4 * 3 + ) + + l := b - a + + var ( + swaps int + i = a + l/4*1 + j = a + l/4*2 + k = a + l/4*3 + ) + + 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) + } + // Find the median among i, j, k and stores it into j. + j = medianLessFunc(data, i, j, k, &swaps, less) + } + + switch swaps { + case 0: + return j, increasingHint + case maxSwaps: + return j, decreasingHint + default: + return j, unknownHint + } +} + +// 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]) { + *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) + 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) +} + +func reverseRangeLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { + i := a + j := b - 1 + for i < j { + data[i], data[j] = data[j], data[i] + i++ + j-- + } +} + +func swapRangeLessFunc[E any](data []E, a, b, n int, less func(a, b E) bool) { + 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) { + blockSize := 20 // must be > 0 + a, b := 0, blockSize + for b <= n { + insertionSortLessFunc(data, a, b, less) + a = b + b += blockSize + } + insertionSortLessFunc(data, a, n, less) + + for blockSize < n { + a, b = 0, 2*blockSize + for b <= n { + symMergeLessFunc(data, a, a+blockSize, b, less) + a = b + b += 2 * blockSize + } + if m := a + blockSize; m < n { + symMergeLessFunc(data, a, m, n, less) + } + blockSize *= 2 + } +} + +// symMergeLessFunc 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 +// Computer Science, pages 714-723. Springer, 2004. +// +// Let M = m-a and N = b-n. Wolog M < N. +// The recursion depth is bound by ceil(log(N+M)). +// The algorithm needs O(M*log(N/M + 1)) calls to data.Less. +// The algorithm needs O((M+N)*log(M)) calls to data.Swap. +// +// The paper gives O((M+N)*log(M)) as the number of assignments assuming a +// rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation +// in the paper carries through for Swap operations, especially as the block +// swapping rotate uses only O(M+N) Swaps. +// +// 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) { + // Avoid unnecessary recursions of symMerge + // by direct insertion of data[a] into data[m:b] + // if data[a:m] only contains one element. + if m-a == 1 { + // Use binary search to find the lowest index i + // such that data[i] >= data[a] for m <= i < b. + // Exit the search loop with i == b in case no such index exists. + i := m + j := b + for i < j { + h := int(uint(i+j) >> 1) + if less(data[h], data[a]) { + i = h + 1 + } else { + j = h + } + } + // Swap values until data[a] reaches the position before i. + for k := a; k < i-1; k++ { + data[k], data[k+1] = data[k+1], data[k] + } + return + } + + // Avoid unnecessary recursions of symMerge + // by direct insertion of data[m] into data[a:m] + // if data[m:b] only contains one element. + if b-m == 1 { + // Use binary search to find the lowest index i + // such that data[i] > data[m] for a <= i < m. + // Exit the search loop with i == m in case no such index exists. + i := a + j := m + for i < j { + h := int(uint(i+j) >> 1) + if !less(data[m], data[h]) { + i = h + 1 + } else { + j = h + } + } + // Swap values until data[m] reaches the position i. + for k := m; k > i; k-- { + data[k], data[k-1] = data[k-1], data[k] + } + return + } + + mid := int(uint(a+b) >> 1) + n := mid + m + var start, r int + if m > mid { + start = n - b + r = mid + } else { + start = a + r = m + } + p := n - 1 + + for start < r { + c := int(uint(start+r) >> 1) + if !less(data[p-c], data[c]) { + start = c + 1 + } else { + r = c + } + } + + end := n - start + if start < m && m < end { + rotateLessFunc(data, start, m, end, less) + } + if a < start && start < mid { + symMergeLessFunc(data, a, start, mid, less) + } + if mid < end && end < b { + symMergeLessFunc(data, mid, end, b, less) + } +} + +// rotateLessFunc 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) { + i := m - a + j := b - m + + for i != j { + if i > j { + swapRangeLessFunc(data, m-i, m, j, less) + i -= j + } else { + swapRangeLessFunc(data, m-i, m+j-i, i, less) + j -= i + } + } + // i == j + swapRangeLessFunc(data, m-i, m, i, less) +} diff --git a/tools/vendor/golang.org/x/exp/slices/zsortordered.go b/tools/vendor/golang.org/x/exp/slices/zsortordered.go new file mode 100644 index 00000000..efaa1c8b --- /dev/null +++ b/tools/vendor/golang.org/x/exp/slices/zsortordered.go @@ -0,0 +1,481 @@ +// Code generated by gen_sort_variants.go; DO NOT EDIT. + +// 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 slices + +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-- { + data[j], data[j-1] = data[j-1], data[j] + } + } +} + +// siftDownOrdered implements the heap property on data[lo:hi]. +// first is an offset into the array where the root of the heap lies. +func siftDownOrdered[E constraints.Ordered](data []E, lo, hi, first int) { + root := lo + for { + child := 2*root + 1 + if child >= hi { + break + } + if child+1 < hi && (data[first+child] < data[first+child+1]) { + child++ + } + if !(data[first+root] < data[first+child]) { + return + } + data[first+root], data[first+child] = data[first+child], data[first+root] + root = child + } +} + +func heapSortOrdered[E constraints.Ordered](data []E, a, b int) { + first := a + lo := 0 + hi := b - a + + // Build heap with greatest element at top. + for i := (hi - 1) / 2; i >= 0; i-- { + siftDownOrdered(data, i, hi, first) + } + + // 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] + siftDownOrdered(data, lo, i, first) + } +} + +// pdqsortOrdered 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 pdqsortOrdered[E constraints.Ordered](data []E, a, b, limit int) { + const maxInsertion = 12 + + var ( + wasBalanced = true // whether the last partitioning was reasonably balanced + wasPartitioned = true // whether the slice was already partitioned + ) + + for { + length := b - a + + if length <= maxInsertion { + insertionSortOrdered(data, a, b) + return + } + + // Fall back to heapsort if too many bad choices were made. + if limit == 0 { + heapSortOrdered(data, a, b) + return + } + + // If the last partitioning was imbalanced, we need to breaking patterns. + if !wasBalanced { + breakPatternsOrdered(data, a, b) + limit-- + } + + pivot, hint := choosePivotOrdered(data, a, b) + if hint == decreasingHint { + reverseRangeOrdered(data, a, b) + // 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. + pivot = (b - 1) - (pivot - a) + hint = increasingHint + } + + // The slice is likely already sorted. + if wasBalanced && wasPartitioned && hint == increasingHint { + if partialInsertionSortOrdered(data, a, b) { + return + } + } + + // 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]) { + mid := partitionEqualOrdered(data, a, b, pivot) + a = mid + continue + } + + mid, alreadyPartitioned := partitionOrdered(data, a, b, pivot) + wasPartitioned = alreadyPartitioned + + leftLen, rightLen := mid-a, b-mid + balanceThreshold := length / 8 + if leftLen < rightLen { + wasBalanced = leftLen >= balanceThreshold + pdqsortOrdered(data, a, mid, limit) + a = mid + 1 + } else { + wasBalanced = rightLen >= balanceThreshold + pdqsortOrdered(data, mid+1, b, limit) + b = mid + } + } +} + +// partitionOrdered 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 partitionOrdered[E constraints.Ordered](data []E, a, b, pivot 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 && (data[i] < data[a]) { + i++ + } + for i <= j && !(data[j] < data[a]) { + j-- + } + if i > j { + data[j], data[a] = data[a], data[j] + return j, true + } + data[i], data[j] = data[j], data[i] + i++ + j-- + + for { + for i <= j && (data[i] < data[a]) { + i++ + } + for i <= j && !(data[j] < data[a]) { + j-- + } + if i > j { + break + } + data[i], data[j] = data[j], data[i] + i++ + j-- + } + data[j], data[a] = data[a], data[j] + return j, false +} + +// partitionEqualOrdered 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 partitionEqualOrdered[E constraints.Ordered](data []E, a, b, pivot 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 && !(data[a] < data[i]) { + i++ + } + for i <= j && (data[a] < data[j]) { + j-- + } + if i > j { + break + } + data[i], data[j] = data[j], data[i] + i++ + j-- + } + return i +} + +// partialInsertionSortOrdered partially sorts a slice, returns true if the slice is sorted at the end. +func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b 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 && !(data[i] < data[i-1]) { + i++ + } + + if i == b { + return true + } + + if b-a < shortestShifting { + return false + } + + data[i], data[i-1] = data[i-1], data[i] + + // Shift the smaller one to the left. + if i-a >= 2 { + for j := i - 1; j >= 1; j-- { + if !(data[j] < data[j-1]) { + break + } + data[j], data[j-1] = data[j-1], data[j] + } + } + // Shift the greater one to the right. + if b-i >= 2 { + for j := i + 1; j < b; j++ { + if !(data[j] < data[j-1]) { + break + } + data[j], data[j-1] = data[j-1], data[j] + } + } + } + return false +} + +// breakPatternsOrdered scatters some elements around in an attempt to break some patterns +// that might cause imbalanced partitions in quicksort. +func breakPatternsOrdered[E constraints.Ordered](data []E, a, b int) { + length := b - a + if length >= 8 { + random := xorshift(length) + modulus := nextPowerOfTwo(length) + + for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ { + other := int(uint(random.Next()) & (modulus - 1)) + if other >= length { + other -= length + } + data[idx], data[a+other] = data[a+other], data[idx] + } + } +} + +// choosePivotOrdered 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 choosePivotOrdered[E constraints.Ordered](data []E, a, b int) (pivot int, hint sortedHint) { + const ( + shortestNinther = 50 + maxSwaps = 4 * 3 + ) + + l := b - a + + var ( + swaps int + i = a + l/4*1 + j = a + l/4*2 + k = a + l/4*3 + ) + + if l >= 8 { + if l >= shortestNinther { + // Tukey ninther method, the idea came from Rust's implementation. + i = medianAdjacentOrdered(data, i, &swaps) + j = medianAdjacentOrdered(data, j, &swaps) + k = medianAdjacentOrdered(data, k, &swaps) + } + // Find the median among i, j, k and stores it into j. + j = medianOrdered(data, i, j, k, &swaps) + } + + switch swaps { + case 0: + return j, increasingHint + case maxSwaps: + return j, decreasingHint + default: + return j, unknownHint + } +} + +// 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] { + *swaps++ + return b, a + } + return a, b +} + +// medianOrdered returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c. +func medianOrdered[E constraints.Ordered](data []E, a, b, c int, swaps *int) int { + a, b = order2Ordered(data, a, b, swaps) + b, c = order2Ordered(data, b, c, swaps) + a, b = order2Ordered(data, a, b, swaps) + return b +} + +// medianAdjacentOrdered finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a. +func medianAdjacentOrdered[E constraints.Ordered](data []E, a int, swaps *int) int { + return medianOrdered(data, a-1, a, a+1, swaps) +} + +func reverseRangeOrdered[E constraints.Ordered](data []E, a, b int) { + i := a + j := b - 1 + for i < j { + data[i], data[j] = data[j], data[i] + i++ + j-- + } +} + +func swapRangeOrdered[E constraints.Ordered](data []E, a, b, n int) { + for i := 0; i < n; i++ { + data[a+i], data[b+i] = data[b+i], data[a+i] + } +} + +func stableOrdered[E constraints.Ordered](data []E, n int) { + blockSize := 20 // must be > 0 + a, b := 0, blockSize + for b <= n { + insertionSortOrdered(data, a, b) + a = b + b += blockSize + } + insertionSortOrdered(data, a, n) + + for blockSize < n { + a, b = 0, 2*blockSize + for b <= n { + symMergeOrdered(data, a, a+blockSize, b) + a = b + b += 2 * blockSize + } + if m := a + blockSize; m < n { + symMergeOrdered(data, a, m, n) + } + blockSize *= 2 + } +} + +// symMergeOrdered 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 +// Computer Science, pages 714-723. Springer, 2004. +// +// Let M = m-a and N = b-n. Wolog M < N. +// The recursion depth is bound by ceil(log(N+M)). +// The algorithm needs O(M*log(N/M + 1)) calls to data.Less. +// The algorithm needs O((M+N)*log(M)) calls to data.Swap. +// +// The paper gives O((M+N)*log(M)) as the number of assignments assuming a +// rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation +// in the paper carries through for Swap operations, especially as the block +// swapping rotate uses only O(M+N) Swaps. +// +// symMerge assumes non-degenerate arguments: a < m && m < b. +// Having the caller check this condition eliminates many leaf recursion calls, +// which improves performance. +func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) { + // Avoid unnecessary recursions of symMerge + // by direct insertion of data[a] into data[m:b] + // if data[a:m] only contains one element. + if m-a == 1 { + // Use binary search to find the lowest index i + // such that data[i] >= data[a] for m <= i < b. + // Exit the search loop with i == b in case no such index exists. + i := m + j := b + for i < j { + h := int(uint(i+j) >> 1) + if data[h] < data[a] { + i = h + 1 + } else { + j = h + } + } + // Swap values until data[a] reaches the position before i. + for k := a; k < i-1; k++ { + data[k], data[k+1] = data[k+1], data[k] + } + return + } + + // Avoid unnecessary recursions of symMerge + // by direct insertion of data[m] into data[a:m] + // if data[m:b] only contains one element. + if b-m == 1 { + // Use binary search to find the lowest index i + // such that data[i] > data[m] for a <= i < m. + // Exit the search loop with i == m in case no such index exists. + i := a + j := m + for i < j { + h := int(uint(i+j) >> 1) + if !(data[m] < data[h]) { + i = h + 1 + } else { + j = h + } + } + // Swap values until data[m] reaches the position i. + for k := m; k > i; k-- { + data[k], data[k-1] = data[k-1], data[k] + } + return + } + + mid := int(uint(a+b) >> 1) + n := mid + m + var start, r int + if m > mid { + start = n - b + r = mid + } else { + start = a + r = m + } + p := n - 1 + + for start < r { + c := int(uint(start+r) >> 1) + if !(data[p-c] < data[c]) { + start = c + 1 + } else { + r = c + } + } + + end := n - start + if start < m && m < end { + rotateOrdered(data, start, m, end) + } + if a < start && start < mid { + symMergeOrdered(data, a, start, mid) + } + if mid < end && end < b { + symMergeOrdered(data, mid, end, b) + } +} + +// rotateOrdered 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 rotateOrdered[E constraints.Ordered](data []E, a, m, b int) { + i := m - a + j := b - m + + for i != j { + if i > j { + swapRangeOrdered(data, m-i, m, j) + i -= j + } else { + swapRangeOrdered(data, m-i, m+j-i, i) + j -= i + } + } + // i == j + swapRangeOrdered(data, m-i, m, i) +} diff --git a/tools/vendor/golang.org/x/exp/typeparams/common.go b/tools/vendor/golang.org/x/exp/typeparams/common.go index e697083b..7f867cf8 100644 --- a/tools/vendor/golang.org/x/exp/typeparams/common.go +++ b/tools/vendor/golang.org/x/exp/typeparams/common.go @@ -5,10 +5,6 @@ // Package typeparams contains common utilities for writing tools that interact // with generic Go code, as introduced with Go 1.18. // -// THIS PACKAGE IS CURRENTLY EXPERIMENTAL AND MAY CHANGE. While the API is -// being tested, we may find the need for improvement. This caveat will be -// removed shortly. -// // 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 @@ -127,15 +123,15 @@ func OriginMethod(fn *types.Func) *types.Func { // // For example, consider the following type declarations: // -// type Interface[T any] interface { -// Accept(T) -// } +// type Interface[T any] interface { +// Accept(T) +// } // -// type Container[T any] struct { -// Element T -// } +// type Container[T any] struct { +// Element T +// } // -// func (c Container[T]) Accept(t T) { c.Element = t } +// func (c Container[T]) Accept(t T) { c.Element = t } // // In this case, GenericAssignableTo reports that instantiations of Container // are assignable to the corresponding instantiation of Interface. diff --git a/tools/vendor/golang.org/x/exp/typeparams/normalize.go b/tools/vendor/golang.org/x/exp/typeparams/normalize.go index 55c788a3..6cf71f04 100644 --- a/tools/vendor/golang.org/x/exp/typeparams/normalize.go +++ b/tools/vendor/golang.org/x/exp/typeparams/normalize.go @@ -21,28 +21,28 @@ var ErrEmptyTypeSet = errors.New("empty type set") // NormalTerms returns a slice of terms representing the normalized structural // type restrictions of a type, if any. // -// For all types other than *types.TypeParam, *types.Interface, and -// *types.Union, this is just a single term with Tilde() == false and -// Type() == typ. For *types.TypeParam, *types.Interface, and *types.Union, see -// below. +// For all types whose underlying type is not *types.TypeParam, +// *types.Interface, or *types.Union, this is just a single term with Tilde() +// == false and Type() == typ. For types whose underlying type is +// *types.TypeParam, *types.Interface, and *types.Union, see below. // // Structural type restrictions of a type parameter are created via // non-interface types embedded in its constraint interface (directly, or via a -// chain of interface embeddings). For example, in the declaration type -// T[P interface{~int; m()}] int the structural restriction of the type +// chain of interface embeddings). For example, in the declaration type T[P +// interface{~int; m()}] int is the structural restriction of the type // parameter P is ~int. // // With interface embedding and unions, the specification of structural type // restrictions may be arbitrarily complex. For example, consider the // following: // -// type A interface{ ~string|~[]byte } +// type A interface{ ~string|~[]byte } // -// type B interface{ int|string } +// type B interface{ int|string } // -// type C interface { ~string|~int } +// type C interface { ~string|~int } // -// type T[P interface{ A|B; C }] int +// type T[P interface{ A|B; C }] int // // In this example, the structural type restriction of P is ~string|int: A|B // expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, diff --git a/tools/vendor/golang.org/x/exp/typeparams/typeterm.go b/tools/vendor/golang.org/x/exp/typeparams/typeterm.go index 7ddee28d..7350bb70 100644 --- a/tools/vendor/golang.org/x/exp/typeparams/typeterm.go +++ b/tools/vendor/golang.org/x/exp/typeparams/typeterm.go @@ -10,11 +10,10 @@ import "go/types" // A term describes elementary type sets: // -// ∅: (*term)(nil) == ∅ // set of no types (empty set) -// 𝓤: &term{} == 𝓤 // set of all types (𝓤niverse) -// T: &term{false, T} == {T} // set of type T -// ~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t -// +// ∅: (*term)(nil) == ∅ // set of no types (empty set) +// 𝓤: &term{} == 𝓤 // set of all types (𝓤niverse) +// T: &term{false, T} == {T} // set of type T +// ~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t type term struct { tilde bool // valid if typ != nil typ types.Type diff --git a/tools/vendor/golang.org/x/mod/modfile/read.go b/tools/vendor/golang.org/x/mod/modfile/read.go index 956f30cb..70947ee7 100644 --- a/tools/vendor/golang.org/x/mod/modfile/read.go +++ b/tools/vendor/golang.org/x/mod/modfile/read.go @@ -285,7 +285,6 @@ func (x *Line) Span() (start, end Position) { // "x" // "y" // ) -// type LineBlock struct { Comments Start Position diff --git a/tools/vendor/golang.org/x/mod/module/module.go b/tools/vendor/golang.org/x/mod/module/module.go index 355b5a45..c26d1d29 100644 --- a/tools/vendor/golang.org/x/mod/module/module.go +++ b/tools/vendor/golang.org/x/mod/module/module.go @@ -15,7 +15,7 @@ // but additional checking functions, most notably Check, verify that // a particular path, version pair is valid. // -// Escaped Paths +// # Escaped Paths // // Module paths appear as substrings of file system paths // (in the download cache) and of web server URLs in the proxy protocol. @@ -55,7 +55,7 @@ // Import paths have never allowed exclamation marks, so there is no // need to define how to escape a literal !. // -// Unicode Restrictions +// # Unicode Restrictions // // Today, paths are disallowed from using Unicode. // @@ -102,9 +102,9 @@ import ( "strings" "unicode" "unicode/utf8" + "errors" "golang.org/x/mod/semver" - errors "golang.org/x/xerrors" ) // A Version (for clients, a module.Version) is defined by a module path and version pair. diff --git a/tools/vendor/golang.org/x/sync/AUTHORS b/tools/vendor/golang.org/x/sync/AUTHORS deleted file mode 100644 index 15167cd7..00000000 --- a/tools/vendor/golang.org/x/sync/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/tools/vendor/golang.org/x/sync/CONTRIBUTORS b/tools/vendor/golang.org/x/sync/CONTRIBUTORS deleted file mode 100644 index 1c4577e9..00000000 --- a/tools/vendor/golang.org/x/sync/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go b/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go index 87dd5e30..bbaba18b 100644 --- a/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go +++ b/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go @@ -41,13 +41,10 @@ func archInit() { switch runtime.GOOS { case "freebsd": readARM64Registers() - case "linux", "netbsd": + case "linux", "netbsd", "openbsd": doinit() default: - // Most platforms don't seem to allow reading these registers. - // - // OpenBSD: - // See https://golang.org/issue/31746 + // Many platforms don't seem to allow reading these registers. setMinimalFeatures() } } diff --git a/tools/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go b/tools/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go new file mode 100644 index 00000000..85b64d5c --- /dev/null +++ b/tools/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go @@ -0,0 +1,65 @@ +// 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 cpu + +import ( + "syscall" + "unsafe" +) + +// Minimal copy of functionality from x/sys/unix so the cpu package can call +// sysctl without depending on x/sys/unix. + +const ( + // From OpenBSD's sys/sysctl.h. + _CTL_MACHDEP = 7 + + // From OpenBSD's machine/cpu.h. + _CPU_ID_AA64ISAR0 = 2 + _CPU_ID_AA64ISAR1 = 3 +) + +// Implemented in the runtime package (runtime/sys_openbsd3.go) +func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) + +//go:linkname syscall_syscall6 syscall.syscall6 + +func sysctl(mib []uint32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + _, _, errno := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(unsafe.Pointer(&mib[0])), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if errno != 0 { + return errno + } + return nil +} + +var libc_sysctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sysctl sysctl "libc.so" + +func sysctlUint64(mib []uint32) (uint64, bool) { + var out uint64 + nout := unsafe.Sizeof(out) + if err := sysctl(mib, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0); err != nil { + return 0, false + } + return out, true +} + +func doinit() { + setMinimalFeatures() + + // Get ID_AA64ISAR0 and ID_AA64ISAR1 from sysctl. + isar0, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR0}) + if !ok { + return + } + isar1, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR1}) + if !ok { + return + } + parseARM64SystemRegisters(isar0, isar1, 0) + + Initialized = true +} diff --git a/tools/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s b/tools/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s new file mode 100644 index 00000000..054ba05d --- /dev/null +++ b/tools/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s @@ -0,0 +1,11 @@ +// 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. + +#include "textflag.h" + +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) diff --git a/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go b/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go index f8c484f5..f3cde129 100644 --- a/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go +++ b/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.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 !linux && !netbsd && arm64 -// +build !linux,!netbsd,arm64 +//go:build !linux && !netbsd && !openbsd && arm64 +// +build !linux,!netbsd,!openbsd,arm64 package cpu diff --git a/tools/vendor/golang.org/x/sys/unix/mkall.sh b/tools/vendor/golang.org/x/sys/unix/mkall.sh index dcef4de6..6fc18353 100644 --- a/tools/vendor/golang.org/x/sys/unix/mkall.sh +++ b/tools/vendor/golang.org/x/sys/unix/mkall.sh @@ -73,12 +73,12 @@ aix_ppc64) darwin_amd64) mkerrors="$mkerrors -m64" mktypes="GOARCH=$GOARCH go tool cgo -godefs" - mkasm="go run mkasm_darwin.go" + mkasm="go run mkasm.go" ;; darwin_arm64) mkerrors="$mkerrors -m64" mktypes="GOARCH=$GOARCH go tool cgo -godefs" - mkasm="go run mkasm_darwin.go" + mkasm="go run mkasm.go" ;; dragonfly_amd64) mkerrors="$mkerrors -m64" @@ -142,17 +142,17 @@ netbsd_arm64) mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_386) + mkasm="go run mkasm.go" mkerrors="$mkerrors -m32" - mksyscall="go run mksyscall.go -l32 -openbsd" + mksyscall="go run mksyscall.go -l32 -openbsd -libc" mksysctl="go run mksysctl_openbsd.go" - mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_amd64) + mkasm="go run mkasm.go" mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -openbsd" + mksyscall="go run mksyscall.go -openbsd -libc" mksysctl="go run mksysctl_openbsd.go" - mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_arm) @@ -165,10 +165,10 @@ openbsd_arm) mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; openbsd_arm64) + mkasm="go run mkasm.go" mkerrors="$mkerrors -m64" - mksyscall="go run mksyscall.go -openbsd" + mksyscall="go run mksyscall.go -openbsd -libc" mksysctl="go run mksysctl_openbsd.go" - mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'" # Let the type of C char be signed for making the bare syscall # API consistent across platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" @@ -232,5 +232,5 @@ esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi - if [ -n "$mkasm" ]; then echo "$mkasm $GOARCH"; fi + if [ -n "$mkasm" ]; then echo "$mkasm $GOOS $GOARCH"; fi ) | $run 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 e2a30e88..2db1b51e 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_aix.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_aix.go @@ -253,7 +253,7 @@ func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Sockle var empty bool if len(oob) > 0 { // send at least one normal byte - empty := emptyIovecs(iov) + empty = emptyIovecs(iov) if empty { var iova [1]Iovec iova[0].Base = &dummy 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 c437fc5d..eda42671 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -363,7 +363,7 @@ func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Sockle var empty bool if len(oob) > 0 { // send at least one normal byte - empty := emptyIovecs(iov) + empty = emptyIovecs(iov) if empty { var iova [1]Iovec iova[0].Base = &dummy 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 5e4a94f7..ecb0f27f 100644 --- a/tools/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1541,7 +1541,7 @@ func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Sockle var dummy byte var empty bool if len(oob) > 0 { - empty := emptyIovecs(iov) + empty = emptyIovecs(iov) if empty { var sockType int sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) 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 new file mode 100644 index 00000000..e23c33de --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go @@ -0,0 +1,27 @@ +// 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 (openbsd && 386) || (openbsd && amd64) || (openbsd && arm64) +// +build openbsd,386 openbsd,amd64 openbsd,arm64 + +package unix + +import _ "unsafe" + +// Implemented in the runtime package (runtime/sys_openbsd3.go) +func syscall_syscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) +func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) +func syscall_syscall10(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 uintptr) (r1, r2 uintptr, err Errno) +func syscall_rawSyscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) +func syscall_rawSyscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) + +//go:linkname syscall_syscall syscall.syscall +//go:linkname syscall_syscall6 syscall.syscall6 +//go:linkname syscall_syscall10 syscall.syscall10 +//go:linkname syscall_rawSyscall syscall.rawSyscall +//go:linkname syscall_rawSyscall6 syscall.rawSyscall6 + +func syscall_syscall9(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err Errno) { + return syscall_syscall10(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, 0) +} 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 274e2dab..36c0dfc7 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include -m32 +// mkerrors.sh -Wall -Werror -static -I/tmp/386/include -m32 // 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/include -m32 _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/386/include -m32 _const.go package unix 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 95b6eeed..4ff94270 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include -m64 +// mkerrors.sh -Wall -Werror -static -I/tmp/amd64/include -m64 // 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/include -m64 _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/amd64/include -m64 _const.go package unix 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 918cd130..3eaa0fb7 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/arm/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/arm/include _const.go package unix 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 3907dc5a..d7995bdc 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include -fsigned-char +// mkerrors.sh -Wall -Werror -static -I/tmp/arm64/include -fsigned-char // 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/include -fsigned-char _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/arm64/include -fsigned-char _const.go package unix 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 03d5c105..928e24c2 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/loong64/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/loong64/include _const.go package unix 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 bd794e01..179bffb4 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/mips/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/mips/include _const.go package unix 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 6c741b05..1fba17bd 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/mips64/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/mips64/include _const.go package unix 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 807b8cd2..b77dde31 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/mips64le/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/mips64le/include _const.go package unix 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 a39e4f5c..78c6c751 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/mipsle/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/mipsle/include _const.go package unix 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 c0fcda86..1c0d31f0 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/ppc/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/ppc/include _const.go package unix 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 f3b72407..959dd9bb 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/ppc64/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/ppc64/include _const.go package unix 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 72f2a45d..5a873cdb 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/ppc64le/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/ppc64le/include _const.go package unix 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 45b214b4..e336d141 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/riscv64/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/riscv64/include _const.go package unix 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 1897f207..390c01d9 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include -fsigned-char +// mkerrors.sh -Wall -Werror -static -I/tmp/s390x/include -fsigned-char // 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/include -fsigned-char _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/s390x/include -fsigned-char _const.go package unix 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 1fb7a395..98a6e5f1 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 @@ -1,11 +1,11 @@ -// mkerrors.sh -Wall -Werror -static -I/tmp/include +// mkerrors.sh -Wall -Werror -static -I/tmp/sparc64/include // 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/include _const.go +// cgo -godefs -- -Wall -Werror -static -I/tmp/sparc64/include _const.go package unix diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.s index d6c3e25c..f5bb40ed 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_13.s @@ -1,4 +1,4 @@ -// go run mkasm_darwin.go amd64 +// go run mkasm.go darwin amd64 // Code generated by the command above; DO NOT EDIT. //go:build go1.13 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 7e308a47..b41467a0 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 @@ -1,4 +1,4 @@ -// go run mkasm_darwin.go amd64 +// go run mkasm.go darwin amd64 // Code generated by the command above; DO NOT EDIT. //go:build go1.12 diff --git a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.s b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.s index 35798972..0c3f76bc 100644 --- a/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.s +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.s @@ -1,4 +1,4 @@ -// go run mkasm_darwin.go arm64 +// go run mkasm.go darwin arm64 // Code generated by the command above; DO NOT EDIT. //go:build go1.13 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 b09e5bb0..e1f9204a 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 @@ -1,4 +1,4 @@ -// go run mkasm_darwin.go arm64 +// go run mkasm.go darwin arm64 // Code generated by the command above; DO NOT EDIT. //go:build go1.12 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 a057fc5d..2925fe0a 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 @@ -1,4 +1,4 @@ -// go run mksyscall.go -l32 -openbsd -tags openbsd,386 syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go +// go run mksyscall.go -l32 -openbsd -libc -tags openbsd,386 syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && 386 @@ -16,7 +16,7 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -24,20 +24,28 @@ func getgroups(ngid int, gid *_Gid_t) (n int, err error) { return } +var libc_getgroups_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getgroups getgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setgroups_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setgroups setgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -45,10 +53,14 @@ func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err return } +var libc_wait4_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_wait4 wait4 "libc.so" + // 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(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -56,30 +68,42 @@ func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { return } +var libc_accept_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_accept accept "libc.so" + // 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(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_bind_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_bind bind "libc.so" + // 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(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_connect_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_connect connect "libc.so" + // 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 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -87,66 +111,94 @@ func socket(domain int, typ int, proto int) (fd int, err error) { return } +var libc_socket_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_socket socket "libc.so" + // 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 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getsockopt_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsockopt getsockopt "libc.so" + // 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 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setsockopt_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setsockopt setsockopt "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getpeername_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpeername getpeername "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getsockname_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsockname getsockname "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_shutdown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_shutdown shutdown "libc.so" + // 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 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_socketpair_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_socketpair socketpair "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { @@ -156,7 +208,7 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -164,6 +216,10 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl return } +var libc_recvfrom_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_recvfrom recvfrom "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { @@ -173,17 +229,21 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sendto_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sendto sendto "libc.so" + // 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(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -191,10 +251,14 @@ func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +var libc_recvmsg_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_recvmsg recvmsg "libc.so" + // 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(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -202,10 +266,14 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +var libc_sendmsg_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sendmsg sendmsg "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -213,6 +281,10 @@ func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, ne return } +var libc_kevent_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kevent kevent "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { @@ -221,27 +293,35 @@ func utimes(path string, timeval *[2]Timeval) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_utimes_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_utimes utimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_futimes_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_futimes futimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { - r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -249,6 +329,10 @@ func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { return } +var libc_poll_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_poll poll "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { @@ -258,13 +342,17 @@ func Madvise(b []byte, behav int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_madvise_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_madvise madvise "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { @@ -274,23 +362,31 @@ func Mlock(b []byte) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mlock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mlock mlock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mlockall_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mlockall mlockall "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { @@ -300,13 +396,17 @@ func Mprotect(b []byte, prot int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mprotect_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mprotect mprotect "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { @@ -316,13 +416,17 @@ func Msync(b []byte, flags int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_msync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_msync msync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { @@ -332,33 +436,45 @@ func Munlock(b []byte) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munlock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munlock munlock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munlockall_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munlockall munlockall "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_pipe2_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pipe2 pipe2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { @@ -368,7 +484,7 @@ func Getdents(fd int, buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -376,6 +492,10 @@ func Getdents(fd int, buf []byte) (n int, err error) { return } +var libc_getdents_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getdents getdents "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { @@ -385,7 +505,7 @@ func Getcwd(buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -393,16 +513,24 @@ func Getcwd(buf []byte) (n int, err error) { return } +var libc_getcwd_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getcwd getcwd "libc.so" + // 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)) + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // 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) { @@ -412,17 +540,21 @@ func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sysctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sysctl sysctl "libc.so" + // 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 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + 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) if e1 != 0 { err = errnoErr(e1) @@ -430,6 +562,10 @@ func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, return } +var libc_ppoll_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ppoll ppoll "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { @@ -438,23 +574,31 @@ func Access(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_access_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_access access "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_adjtime_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_adjtime adjtime "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { @@ -463,13 +607,17 @@ func Chdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chdir chdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { @@ -478,13 +626,17 @@ func Chflags(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chflags_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chflags chflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { @@ -493,13 +645,17 @@ func Chmod(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chmod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chmod chmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { @@ -508,13 +664,17 @@ func Chown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chown chown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { @@ -523,27 +683,35 @@ func Chroot(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chroot_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chroot chroot "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_close_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_close close "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -551,33 +719,49 @@ func Dup(fd int) (nfd int, err error) { return } +var libc_dup_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup dup "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_dup2_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup2 dup2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_dup3_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup3 dup3 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) return } +var libc_exit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_exit exit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { @@ -586,43 +770,59 @@ func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_faccessat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_faccessat faccessat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchdir fchdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchflags_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchflags fchflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchmod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchmod fchmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { @@ -631,23 +831,31 @@ func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchmodat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" + // 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(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchown fchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { @@ -656,27 +864,35 @@ func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchownat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchownat fchownat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_flock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_flock flock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -684,16 +900,24 @@ func Fpathconf(fd int, name int) (val int, err error) { return } +var libc_fpathconf_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstat fstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { @@ -702,71 +926,99 @@ func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstatat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstatat fstatat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstatfs_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstatfs fstatfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fsync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fsync fsync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_ftruncate_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) egid = int(r0) return } +var libc_getegid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getegid getegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) uid = int(r0) return } +var libc_geteuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_geteuid geteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) gid = int(r0) return } +var libc_getgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getgid getgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -774,34 +1026,50 @@ func Getpgid(pid int) (pgid int, err error) { return } +var libc_getpgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpgid getpgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) pgrp = int(r0) return } +var libc_getpgrp_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) pid = int(r0) return } +var libc_getpid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpid getpid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) ppid = int(r0) return } +var libc_getppid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getppid getppid "libc.so" + // 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(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -809,20 +1077,28 @@ func Getpriority(which int, who int) (prio int, err error) { return } +var libc_getpriority_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpriority getpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getrlimit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { - r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) rtable = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -830,20 +1106,28 @@ func Getrtable() (rtable int, err error) { return } +var libc_getrtable_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrtable getrtable "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getrusage_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrusage getrusage "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -851,46 +1135,66 @@ func Getsid(pid int) (sid int, err error) { return } +var libc_getsid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsid getsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_gettimeofday_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) uid = int(r0) return } +var libc_getuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getuid getuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) tainted = bool(r0 != 0) return } +var libc_issetugid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_issetugid issetugid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_kill_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kill kill "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -898,6 +1202,10 @@ func Kqueue() (fd int, err error) { return } +var libc_kqueue_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kqueue kqueue "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { @@ -906,13 +1214,17 @@ func Lchown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_lchown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lchown lchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { @@ -926,13 +1238,17 @@ func Link(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_link_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_link link "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { @@ -946,23 +1262,31 @@ func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err er if err != nil { return } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_linkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_linkat linkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_listen_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_listen listen "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { @@ -971,13 +1295,17 @@ func Lstat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_lstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lstat lstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { @@ -986,13 +1314,17 @@ func Mkdir(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkdir mkdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { @@ -1001,13 +1333,17 @@ func Mkdirat(dirfd int, path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkdirat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { @@ -1016,13 +1352,17 @@ func Mkfifo(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkfifo_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { @@ -1031,13 +1371,17 @@ func Mkfifoat(dirfd int, path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkfifoat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkfifoat mkfifoat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { @@ -1046,13 +1390,17 @@ func Mknod(path string, mode uint32, dev int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mknod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mknod mknod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { @@ -1061,23 +1409,31 @@ func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mknodat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mknodat mknodat "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(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_nanosleep_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { @@ -1086,7 +1442,7 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1094,6 +1450,10 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { return } +var libc_open_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_open open "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { @@ -1102,7 +1462,7 @@ func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1110,6 +1470,10 @@ func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { return } +var libc_openat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_openat openat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { @@ -1118,7 +1482,7 @@ func Pathconf(path string, name int) (val int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1126,6 +1490,10 @@ func Pathconf(path string, name int) (val int, err error) { return } +var libc_pathconf_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pathconf pathconf "libc.so" + // 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) { @@ -1135,7 +1503,7 @@ func pread(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1143,6 +1511,10 @@ func pread(fd int, p []byte, offset int64) (n int, err error) { return } +var libc_pread_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pread pread "libc.so" + // 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) { @@ -1152,7 +1524,7 @@ func pwrite(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1160,6 +1532,10 @@ func pwrite(fd int, p []byte, offset int64) (n int, err error) { return } +var libc_pwrite_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pwrite pwrite "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { @@ -1169,7 +1545,7 @@ func read(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1177,6 +1553,10 @@ func read(fd int, p []byte) (n int, err error) { return } +var libc_read_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_read read "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { @@ -1191,7 +1571,7 @@ func Readlink(path string, buf []byte) (n int, err error) { } else { _p1 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1199,6 +1579,10 @@ func Readlink(path string, buf []byte) (n int, err error) { return } +var libc_readlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readlink readlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { @@ -1213,7 +1597,7 @@ func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { } else { _p1 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1221,6 +1605,10 @@ func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { return } +var libc_readlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readlinkat readlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { @@ -1234,13 +1622,17 @@ func Rename(from string, to string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_rename_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_rename rename "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { @@ -1254,13 +1646,17 @@ func Renameat(fromfd int, from string, tofd int, to string) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_renameat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renameat renameat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { @@ -1269,13 +1665,17 @@ func Revoke(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_revoke_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_revoke revoke "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { @@ -1284,17 +1684,21 @@ func Rmdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_rmdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_rmdir rmdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) + r0, r1, e1 := syscall_syscall6(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(whence), 0, 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) @@ -1302,10 +1706,14 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { return } +var libc_lseek_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lseek lseek "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1313,36 +1721,52 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err return } +var libc_select_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_select select "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setegid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setegid setegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_seteuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_seteuid seteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setgid setgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { @@ -1351,97 +1775,133 @@ func Setlogin(name string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setlogin_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setlogin setlogin "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setpgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setpgid setpgid "libc.so" + // 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(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setpriority_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setpriority setpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setregid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setregid setregid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setreuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setreuid setreuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setresgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setresgid setresgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setresuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setresuid setresuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := syscall_rawSyscall(libc_setrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setrlimit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setrlimit setrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setrtable_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setrtable setrtable "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1449,26 +1909,38 @@ func Setsid() (pid int, err error) { return } +var libc_setsid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setsid setsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_settimeofday_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_settimeofday settimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setuid setuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { @@ -1477,13 +1949,17 @@ func Stat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_stat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_stat stat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { @@ -1492,13 +1968,17 @@ func Statfs(path string, stat *Statfs_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_statfs_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_statfs statfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { @@ -1512,13 +1992,17 @@ func Symlink(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_symlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_symlink symlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { @@ -1532,23 +2016,31 @@ func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_symlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_symlinkat symlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sync sync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { @@ -1557,21 +2049,29 @@ func Truncate(path string, length int64) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), uintptr(length>>32)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_truncate_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_truncate truncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) oldmask = int(r0) return } +var libc_umask_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_umask umask "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { @@ -1580,13 +2080,17 @@ func Unlink(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unlink unlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { @@ -1595,13 +2099,17 @@ func Unlinkat(dirfd int, path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { @@ -1610,13 +2118,17 @@ func Unmount(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unmount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unmount unmount "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { @@ -1626,7 +2138,7 @@ func write(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1634,10 +2146,14 @@ func write(fd int, p []byte) (n int, err error) { return } +var libc_write_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_write write "libc.so" + // 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 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) + r0, _, e1 := syscall_syscall9(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos), uintptr(pos>>32), 0, 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) @@ -1645,20 +2161,28 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( return } +var libc_mmap_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mmap mmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munmap_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munmap munmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1669,7 +2193,7 @@ func readlen(fd int, buf *byte, nbuf int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1685,9 +2209,13 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error if err != nil { return } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } + +var libc_utimensat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_utimensat utimensat "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 new file mode 100644 index 00000000..75eb2f5f --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s @@ -0,0 +1,796 @@ +// go run mkasm.go openbsd 386 +// Code generated by the command above; DO NOT EDIT. + +#include "textflag.h" + +TEXT libc_getgroups_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getgroups(SB) + +GLOBL ·libc_getgroups_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getgroups_trampoline_addr(SB)/4, $libc_getgroups_trampoline<>(SB) + +TEXT libc_setgroups_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setgroups(SB) + +GLOBL ·libc_setgroups_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setgroups_trampoline_addr(SB)/4, $libc_setgroups_trampoline<>(SB) + +TEXT libc_wait4_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_wait4(SB) + +GLOBL ·libc_wait4_trampoline_addr(SB), RODATA, $4 +DATA ·libc_wait4_trampoline_addr(SB)/4, $libc_wait4_trampoline<>(SB) + +TEXT libc_accept_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_accept(SB) + +GLOBL ·libc_accept_trampoline_addr(SB), RODATA, $4 +DATA ·libc_accept_trampoline_addr(SB)/4, $libc_accept_trampoline<>(SB) + +TEXT libc_bind_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_bind(SB) + +GLOBL ·libc_bind_trampoline_addr(SB), RODATA, $4 +DATA ·libc_bind_trampoline_addr(SB)/4, $libc_bind_trampoline<>(SB) + +TEXT libc_connect_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_connect(SB) + +GLOBL ·libc_connect_trampoline_addr(SB), RODATA, $4 +DATA ·libc_connect_trampoline_addr(SB)/4, $libc_connect_trampoline<>(SB) + +TEXT libc_socket_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_socket(SB) + +GLOBL ·libc_socket_trampoline_addr(SB), RODATA, $4 +DATA ·libc_socket_trampoline_addr(SB)/4, $libc_socket_trampoline<>(SB) + +TEXT libc_getsockopt_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsockopt(SB) + +GLOBL ·libc_getsockopt_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getsockopt_trampoline_addr(SB)/4, $libc_getsockopt_trampoline<>(SB) + +TEXT libc_setsockopt_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setsockopt(SB) + +GLOBL ·libc_setsockopt_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setsockopt_trampoline_addr(SB)/4, $libc_setsockopt_trampoline<>(SB) + +TEXT libc_getpeername_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpeername(SB) + +GLOBL ·libc_getpeername_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getpeername_trampoline_addr(SB)/4, $libc_getpeername_trampoline<>(SB) + +TEXT libc_getsockname_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsockname(SB) + +GLOBL ·libc_getsockname_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getsockname_trampoline_addr(SB)/4, $libc_getsockname_trampoline<>(SB) + +TEXT libc_shutdown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_shutdown(SB) + +GLOBL ·libc_shutdown_trampoline_addr(SB), RODATA, $4 +DATA ·libc_shutdown_trampoline_addr(SB)/4, $libc_shutdown_trampoline<>(SB) + +TEXT libc_socketpair_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_socketpair(SB) + +GLOBL ·libc_socketpair_trampoline_addr(SB), RODATA, $4 +DATA ·libc_socketpair_trampoline_addr(SB)/4, $libc_socketpair_trampoline<>(SB) + +TEXT libc_recvfrom_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_recvfrom(SB) + +GLOBL ·libc_recvfrom_trampoline_addr(SB), RODATA, $4 +DATA ·libc_recvfrom_trampoline_addr(SB)/4, $libc_recvfrom_trampoline<>(SB) + +TEXT libc_sendto_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sendto(SB) + +GLOBL ·libc_sendto_trampoline_addr(SB), RODATA, $4 +DATA ·libc_sendto_trampoline_addr(SB)/4, $libc_sendto_trampoline<>(SB) + +TEXT libc_recvmsg_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_recvmsg(SB) + +GLOBL ·libc_recvmsg_trampoline_addr(SB), RODATA, $4 +DATA ·libc_recvmsg_trampoline_addr(SB)/4, $libc_recvmsg_trampoline<>(SB) + +TEXT libc_sendmsg_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sendmsg(SB) + +GLOBL ·libc_sendmsg_trampoline_addr(SB), RODATA, $4 +DATA ·libc_sendmsg_trampoline_addr(SB)/4, $libc_sendmsg_trampoline<>(SB) + +TEXT libc_kevent_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kevent(SB) + +GLOBL ·libc_kevent_trampoline_addr(SB), RODATA, $4 +DATA ·libc_kevent_trampoline_addr(SB)/4, $libc_kevent_trampoline<>(SB) + +TEXT libc_utimes_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_utimes(SB) + +GLOBL ·libc_utimes_trampoline_addr(SB), RODATA, $4 +DATA ·libc_utimes_trampoline_addr(SB)/4, $libc_utimes_trampoline<>(SB) + +TEXT libc_futimes_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_futimes(SB) + +GLOBL ·libc_futimes_trampoline_addr(SB), RODATA, $4 +DATA ·libc_futimes_trampoline_addr(SB)/4, $libc_futimes_trampoline<>(SB) + +TEXT libc_poll_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_poll(SB) + +GLOBL ·libc_poll_trampoline_addr(SB), RODATA, $4 +DATA ·libc_poll_trampoline_addr(SB)/4, $libc_poll_trampoline<>(SB) + +TEXT libc_madvise_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_madvise(SB) + +GLOBL ·libc_madvise_trampoline_addr(SB), RODATA, $4 +DATA ·libc_madvise_trampoline_addr(SB)/4, $libc_madvise_trampoline<>(SB) + +TEXT libc_mlock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mlock(SB) + +GLOBL ·libc_mlock_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mlock_trampoline_addr(SB)/4, $libc_mlock_trampoline<>(SB) + +TEXT libc_mlockall_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mlockall(SB) + +GLOBL ·libc_mlockall_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mlockall_trampoline_addr(SB)/4, $libc_mlockall_trampoline<>(SB) + +TEXT libc_mprotect_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mprotect(SB) + +GLOBL ·libc_mprotect_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mprotect_trampoline_addr(SB)/4, $libc_mprotect_trampoline<>(SB) + +TEXT libc_msync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_msync(SB) + +GLOBL ·libc_msync_trampoline_addr(SB), RODATA, $4 +DATA ·libc_msync_trampoline_addr(SB)/4, $libc_msync_trampoline<>(SB) + +TEXT libc_munlock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munlock(SB) + +GLOBL ·libc_munlock_trampoline_addr(SB), RODATA, $4 +DATA ·libc_munlock_trampoline_addr(SB)/4, $libc_munlock_trampoline<>(SB) + +TEXT libc_munlockall_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munlockall(SB) + +GLOBL ·libc_munlockall_trampoline_addr(SB), RODATA, $4 +DATA ·libc_munlockall_trampoline_addr(SB)/4, $libc_munlockall_trampoline<>(SB) + +TEXT libc_pipe2_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pipe2(SB) + +GLOBL ·libc_pipe2_trampoline_addr(SB), RODATA, $4 +DATA ·libc_pipe2_trampoline_addr(SB)/4, $libc_pipe2_trampoline<>(SB) + +TEXT libc_getdents_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getdents(SB) + +GLOBL ·libc_getdents_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getdents_trampoline_addr(SB)/4, $libc_getdents_trampoline<>(SB) + +TEXT libc_getcwd_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getcwd(SB) + +GLOBL ·libc_getcwd_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getcwd_trampoline_addr(SB)/4, $libc_getcwd_trampoline<>(SB) + +TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ioctl(SB) + +GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $4 +DATA ·libc_ioctl_trampoline_addr(SB)/4, $libc_ioctl_trampoline<>(SB) + +TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sysctl(SB) + +GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $4 +DATA ·libc_sysctl_trampoline_addr(SB)/4, $libc_sysctl_trampoline<>(SB) + +TEXT libc_ppoll_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ppoll(SB) + +GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $4 +DATA ·libc_ppoll_trampoline_addr(SB)/4, $libc_ppoll_trampoline<>(SB) + +TEXT libc_access_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_access(SB) + +GLOBL ·libc_access_trampoline_addr(SB), RODATA, $4 +DATA ·libc_access_trampoline_addr(SB)/4, $libc_access_trampoline<>(SB) + +TEXT libc_adjtime_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_adjtime(SB) + +GLOBL ·libc_adjtime_trampoline_addr(SB), RODATA, $4 +DATA ·libc_adjtime_trampoline_addr(SB)/4, $libc_adjtime_trampoline<>(SB) + +TEXT libc_chdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chdir(SB) + +GLOBL ·libc_chdir_trampoline_addr(SB), RODATA, $4 +DATA ·libc_chdir_trampoline_addr(SB)/4, $libc_chdir_trampoline<>(SB) + +TEXT libc_chflags_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chflags(SB) + +GLOBL ·libc_chflags_trampoline_addr(SB), RODATA, $4 +DATA ·libc_chflags_trampoline_addr(SB)/4, $libc_chflags_trampoline<>(SB) + +TEXT libc_chmod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chmod(SB) + +GLOBL ·libc_chmod_trampoline_addr(SB), RODATA, $4 +DATA ·libc_chmod_trampoline_addr(SB)/4, $libc_chmod_trampoline<>(SB) + +TEXT libc_chown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chown(SB) + +GLOBL ·libc_chown_trampoline_addr(SB), RODATA, $4 +DATA ·libc_chown_trampoline_addr(SB)/4, $libc_chown_trampoline<>(SB) + +TEXT libc_chroot_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chroot(SB) + +GLOBL ·libc_chroot_trampoline_addr(SB), RODATA, $4 +DATA ·libc_chroot_trampoline_addr(SB)/4, $libc_chroot_trampoline<>(SB) + +TEXT libc_close_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_close(SB) + +GLOBL ·libc_close_trampoline_addr(SB), RODATA, $4 +DATA ·libc_close_trampoline_addr(SB)/4, $libc_close_trampoline<>(SB) + +TEXT libc_dup_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup(SB) + +GLOBL ·libc_dup_trampoline_addr(SB), RODATA, $4 +DATA ·libc_dup_trampoline_addr(SB)/4, $libc_dup_trampoline<>(SB) + +TEXT libc_dup2_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup2(SB) + +GLOBL ·libc_dup2_trampoline_addr(SB), RODATA, $4 +DATA ·libc_dup2_trampoline_addr(SB)/4, $libc_dup2_trampoline<>(SB) + +TEXT libc_dup3_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup3(SB) + +GLOBL ·libc_dup3_trampoline_addr(SB), RODATA, $4 +DATA ·libc_dup3_trampoline_addr(SB)/4, $libc_dup3_trampoline<>(SB) + +TEXT libc_exit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_exit(SB) + +GLOBL ·libc_exit_trampoline_addr(SB), RODATA, $4 +DATA ·libc_exit_trampoline_addr(SB)/4, $libc_exit_trampoline<>(SB) + +TEXT libc_faccessat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_faccessat(SB) + +GLOBL ·libc_faccessat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_faccessat_trampoline_addr(SB)/4, $libc_faccessat_trampoline<>(SB) + +TEXT libc_fchdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchdir(SB) + +GLOBL ·libc_fchdir_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fchdir_trampoline_addr(SB)/4, $libc_fchdir_trampoline<>(SB) + +TEXT libc_fchflags_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchflags(SB) + +GLOBL ·libc_fchflags_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fchflags_trampoline_addr(SB)/4, $libc_fchflags_trampoline<>(SB) + +TEXT libc_fchmod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchmod(SB) + +GLOBL ·libc_fchmod_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fchmod_trampoline_addr(SB)/4, $libc_fchmod_trampoline<>(SB) + +TEXT libc_fchmodat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchmodat(SB) + +GLOBL ·libc_fchmodat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fchmodat_trampoline_addr(SB)/4, $libc_fchmodat_trampoline<>(SB) + +TEXT libc_fchown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchown(SB) + +GLOBL ·libc_fchown_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fchown_trampoline_addr(SB)/4, $libc_fchown_trampoline<>(SB) + +TEXT libc_fchownat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchownat(SB) + +GLOBL ·libc_fchownat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fchownat_trampoline_addr(SB)/4, $libc_fchownat_trampoline<>(SB) + +TEXT libc_flock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_flock(SB) + +GLOBL ·libc_flock_trampoline_addr(SB), RODATA, $4 +DATA ·libc_flock_trampoline_addr(SB)/4, $libc_flock_trampoline<>(SB) + +TEXT libc_fpathconf_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fpathconf(SB) + +GLOBL ·libc_fpathconf_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fpathconf_trampoline_addr(SB)/4, $libc_fpathconf_trampoline<>(SB) + +TEXT libc_fstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstat(SB) + +GLOBL ·libc_fstat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fstat_trampoline_addr(SB)/4, $libc_fstat_trampoline<>(SB) + +TEXT libc_fstatat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstatat(SB) + +GLOBL ·libc_fstatat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fstatat_trampoline_addr(SB)/4, $libc_fstatat_trampoline<>(SB) + +TEXT libc_fstatfs_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstatfs(SB) + +GLOBL ·libc_fstatfs_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fstatfs_trampoline_addr(SB)/4, $libc_fstatfs_trampoline<>(SB) + +TEXT libc_fsync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fsync(SB) + +GLOBL ·libc_fsync_trampoline_addr(SB), RODATA, $4 +DATA ·libc_fsync_trampoline_addr(SB)/4, $libc_fsync_trampoline<>(SB) + +TEXT libc_ftruncate_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ftruncate(SB) + +GLOBL ·libc_ftruncate_trampoline_addr(SB), RODATA, $4 +DATA ·libc_ftruncate_trampoline_addr(SB)/4, $libc_ftruncate_trampoline<>(SB) + +TEXT libc_getegid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getegid(SB) + +GLOBL ·libc_getegid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getegid_trampoline_addr(SB)/4, $libc_getegid_trampoline<>(SB) + +TEXT libc_geteuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_geteuid(SB) + +GLOBL ·libc_geteuid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_geteuid_trampoline_addr(SB)/4, $libc_geteuid_trampoline<>(SB) + +TEXT libc_getgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getgid(SB) + +GLOBL ·libc_getgid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getgid_trampoline_addr(SB)/4, $libc_getgid_trampoline<>(SB) + +TEXT libc_getpgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpgid(SB) + +GLOBL ·libc_getpgid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getpgid_trampoline_addr(SB)/4, $libc_getpgid_trampoline<>(SB) + +TEXT libc_getpgrp_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpgrp(SB) + +GLOBL ·libc_getpgrp_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getpgrp_trampoline_addr(SB)/4, $libc_getpgrp_trampoline<>(SB) + +TEXT libc_getpid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpid(SB) + +GLOBL ·libc_getpid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getpid_trampoline_addr(SB)/4, $libc_getpid_trampoline<>(SB) + +TEXT libc_getppid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getppid(SB) + +GLOBL ·libc_getppid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getppid_trampoline_addr(SB)/4, $libc_getppid_trampoline<>(SB) + +TEXT libc_getpriority_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpriority(SB) + +GLOBL ·libc_getpriority_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getpriority_trampoline_addr(SB)/4, $libc_getpriority_trampoline<>(SB) + +TEXT libc_getrlimit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrlimit(SB) + +GLOBL ·libc_getrlimit_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getrlimit_trampoline_addr(SB)/4, $libc_getrlimit_trampoline<>(SB) + +TEXT libc_getrtable_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrtable(SB) + +GLOBL ·libc_getrtable_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getrtable_trampoline_addr(SB)/4, $libc_getrtable_trampoline<>(SB) + +TEXT libc_getrusage_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrusage(SB) + +GLOBL ·libc_getrusage_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getrusage_trampoline_addr(SB)/4, $libc_getrusage_trampoline<>(SB) + +TEXT libc_getsid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsid(SB) + +GLOBL ·libc_getsid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getsid_trampoline_addr(SB)/4, $libc_getsid_trampoline<>(SB) + +TEXT libc_gettimeofday_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_gettimeofday(SB) + +GLOBL ·libc_gettimeofday_trampoline_addr(SB), RODATA, $4 +DATA ·libc_gettimeofday_trampoline_addr(SB)/4, $libc_gettimeofday_trampoline<>(SB) + +TEXT libc_getuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getuid(SB) + +GLOBL ·libc_getuid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_getuid_trampoline_addr(SB)/4, $libc_getuid_trampoline<>(SB) + +TEXT libc_issetugid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_issetugid(SB) + +GLOBL ·libc_issetugid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_issetugid_trampoline_addr(SB)/4, $libc_issetugid_trampoline<>(SB) + +TEXT libc_kill_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kill(SB) + +GLOBL ·libc_kill_trampoline_addr(SB), RODATA, $4 +DATA ·libc_kill_trampoline_addr(SB)/4, $libc_kill_trampoline<>(SB) + +TEXT libc_kqueue_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kqueue(SB) + +GLOBL ·libc_kqueue_trampoline_addr(SB), RODATA, $4 +DATA ·libc_kqueue_trampoline_addr(SB)/4, $libc_kqueue_trampoline<>(SB) + +TEXT libc_lchown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lchown(SB) + +GLOBL ·libc_lchown_trampoline_addr(SB), RODATA, $4 +DATA ·libc_lchown_trampoline_addr(SB)/4, $libc_lchown_trampoline<>(SB) + +TEXT libc_link_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_link(SB) + +GLOBL ·libc_link_trampoline_addr(SB), RODATA, $4 +DATA ·libc_link_trampoline_addr(SB)/4, $libc_link_trampoline<>(SB) + +TEXT libc_linkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_linkat(SB) + +GLOBL ·libc_linkat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_linkat_trampoline_addr(SB)/4, $libc_linkat_trampoline<>(SB) + +TEXT libc_listen_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_listen(SB) + +GLOBL ·libc_listen_trampoline_addr(SB), RODATA, $4 +DATA ·libc_listen_trampoline_addr(SB)/4, $libc_listen_trampoline<>(SB) + +TEXT libc_lstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lstat(SB) + +GLOBL ·libc_lstat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_lstat_trampoline_addr(SB)/4, $libc_lstat_trampoline<>(SB) + +TEXT libc_mkdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkdir(SB) + +GLOBL ·libc_mkdir_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mkdir_trampoline_addr(SB)/4, $libc_mkdir_trampoline<>(SB) + +TEXT libc_mkdirat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkdirat(SB) + +GLOBL ·libc_mkdirat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mkdirat_trampoline_addr(SB)/4, $libc_mkdirat_trampoline<>(SB) + +TEXT libc_mkfifo_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkfifo(SB) + +GLOBL ·libc_mkfifo_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mkfifo_trampoline_addr(SB)/4, $libc_mkfifo_trampoline<>(SB) + +TEXT libc_mkfifoat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkfifoat(SB) + +GLOBL ·libc_mkfifoat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mkfifoat_trampoline_addr(SB)/4, $libc_mkfifoat_trampoline<>(SB) + +TEXT libc_mknod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mknod(SB) + +GLOBL ·libc_mknod_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mknod_trampoline_addr(SB)/4, $libc_mknod_trampoline<>(SB) + +TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mknodat(SB) + +GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mknodat_trampoline_addr(SB)/4, $libc_mknodat_trampoline<>(SB) + +TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_nanosleep(SB) + +GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $4 +DATA ·libc_nanosleep_trampoline_addr(SB)/4, $libc_nanosleep_trampoline<>(SB) + +TEXT libc_open_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_open(SB) + +GLOBL ·libc_open_trampoline_addr(SB), RODATA, $4 +DATA ·libc_open_trampoline_addr(SB)/4, $libc_open_trampoline<>(SB) + +TEXT libc_openat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_openat(SB) + +GLOBL ·libc_openat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_openat_trampoline_addr(SB)/4, $libc_openat_trampoline<>(SB) + +TEXT libc_pathconf_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pathconf(SB) + +GLOBL ·libc_pathconf_trampoline_addr(SB), RODATA, $4 +DATA ·libc_pathconf_trampoline_addr(SB)/4, $libc_pathconf_trampoline<>(SB) + +TEXT libc_pread_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pread(SB) + +GLOBL ·libc_pread_trampoline_addr(SB), RODATA, $4 +DATA ·libc_pread_trampoline_addr(SB)/4, $libc_pread_trampoline<>(SB) + +TEXT libc_pwrite_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pwrite(SB) + +GLOBL ·libc_pwrite_trampoline_addr(SB), RODATA, $4 +DATA ·libc_pwrite_trampoline_addr(SB)/4, $libc_pwrite_trampoline<>(SB) + +TEXT libc_read_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_read(SB) + +GLOBL ·libc_read_trampoline_addr(SB), RODATA, $4 +DATA ·libc_read_trampoline_addr(SB)/4, $libc_read_trampoline<>(SB) + +TEXT libc_readlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readlink(SB) + +GLOBL ·libc_readlink_trampoline_addr(SB), RODATA, $4 +DATA ·libc_readlink_trampoline_addr(SB)/4, $libc_readlink_trampoline<>(SB) + +TEXT libc_readlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readlinkat(SB) + +GLOBL ·libc_readlinkat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_readlinkat_trampoline_addr(SB)/4, $libc_readlinkat_trampoline<>(SB) + +TEXT libc_rename_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_rename(SB) + +GLOBL ·libc_rename_trampoline_addr(SB), RODATA, $4 +DATA ·libc_rename_trampoline_addr(SB)/4, $libc_rename_trampoline<>(SB) + +TEXT libc_renameat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renameat(SB) + +GLOBL ·libc_renameat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_renameat_trampoline_addr(SB)/4, $libc_renameat_trampoline<>(SB) + +TEXT libc_revoke_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_revoke(SB) + +GLOBL ·libc_revoke_trampoline_addr(SB), RODATA, $4 +DATA ·libc_revoke_trampoline_addr(SB)/4, $libc_revoke_trampoline<>(SB) + +TEXT libc_rmdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_rmdir(SB) + +GLOBL ·libc_rmdir_trampoline_addr(SB), RODATA, $4 +DATA ·libc_rmdir_trampoline_addr(SB)/4, $libc_rmdir_trampoline<>(SB) + +TEXT libc_lseek_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lseek(SB) + +GLOBL ·libc_lseek_trampoline_addr(SB), RODATA, $4 +DATA ·libc_lseek_trampoline_addr(SB)/4, $libc_lseek_trampoline<>(SB) + +TEXT libc_select_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_select(SB) + +GLOBL ·libc_select_trampoline_addr(SB), RODATA, $4 +DATA ·libc_select_trampoline_addr(SB)/4, $libc_select_trampoline<>(SB) + +TEXT libc_setegid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setegid(SB) + +GLOBL ·libc_setegid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setegid_trampoline_addr(SB)/4, $libc_setegid_trampoline<>(SB) + +TEXT libc_seteuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_seteuid(SB) + +GLOBL ·libc_seteuid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_seteuid_trampoline_addr(SB)/4, $libc_seteuid_trampoline<>(SB) + +TEXT libc_setgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setgid(SB) + +GLOBL ·libc_setgid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setgid_trampoline_addr(SB)/4, $libc_setgid_trampoline<>(SB) + +TEXT libc_setlogin_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setlogin(SB) + +GLOBL ·libc_setlogin_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setlogin_trampoline_addr(SB)/4, $libc_setlogin_trampoline<>(SB) + +TEXT libc_setpgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setpgid(SB) + +GLOBL ·libc_setpgid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setpgid_trampoline_addr(SB)/4, $libc_setpgid_trampoline<>(SB) + +TEXT libc_setpriority_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setpriority(SB) + +GLOBL ·libc_setpriority_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setpriority_trampoline_addr(SB)/4, $libc_setpriority_trampoline<>(SB) + +TEXT libc_setregid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setregid(SB) + +GLOBL ·libc_setregid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setregid_trampoline_addr(SB)/4, $libc_setregid_trampoline<>(SB) + +TEXT libc_setreuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setreuid(SB) + +GLOBL ·libc_setreuid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setreuid_trampoline_addr(SB)/4, $libc_setreuid_trampoline<>(SB) + +TEXT libc_setresgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setresgid(SB) + +GLOBL ·libc_setresgid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setresgid_trampoline_addr(SB)/4, $libc_setresgid_trampoline<>(SB) + +TEXT libc_setresuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setresuid(SB) + +GLOBL ·libc_setresuid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setresuid_trampoline_addr(SB)/4, $libc_setresuid_trampoline<>(SB) + +TEXT libc_setrlimit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setrlimit(SB) + +GLOBL ·libc_setrlimit_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setrlimit_trampoline_addr(SB)/4, $libc_setrlimit_trampoline<>(SB) + +TEXT libc_setrtable_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setrtable(SB) + +GLOBL ·libc_setrtable_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setrtable_trampoline_addr(SB)/4, $libc_setrtable_trampoline<>(SB) + +TEXT libc_setsid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setsid(SB) + +GLOBL ·libc_setsid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setsid_trampoline_addr(SB)/4, $libc_setsid_trampoline<>(SB) + +TEXT libc_settimeofday_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_settimeofday(SB) + +GLOBL ·libc_settimeofday_trampoline_addr(SB), RODATA, $4 +DATA ·libc_settimeofday_trampoline_addr(SB)/4, $libc_settimeofday_trampoline<>(SB) + +TEXT libc_setuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setuid(SB) + +GLOBL ·libc_setuid_trampoline_addr(SB), RODATA, $4 +DATA ·libc_setuid_trampoline_addr(SB)/4, $libc_setuid_trampoline<>(SB) + +TEXT libc_stat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_stat(SB) + +GLOBL ·libc_stat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_stat_trampoline_addr(SB)/4, $libc_stat_trampoline<>(SB) + +TEXT libc_statfs_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_statfs(SB) + +GLOBL ·libc_statfs_trampoline_addr(SB), RODATA, $4 +DATA ·libc_statfs_trampoline_addr(SB)/4, $libc_statfs_trampoline<>(SB) + +TEXT libc_symlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_symlink(SB) + +GLOBL ·libc_symlink_trampoline_addr(SB), RODATA, $4 +DATA ·libc_symlink_trampoline_addr(SB)/4, $libc_symlink_trampoline<>(SB) + +TEXT libc_symlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_symlinkat(SB) + +GLOBL ·libc_symlinkat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_symlinkat_trampoline_addr(SB)/4, $libc_symlinkat_trampoline<>(SB) + +TEXT libc_sync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sync(SB) + +GLOBL ·libc_sync_trampoline_addr(SB), RODATA, $4 +DATA ·libc_sync_trampoline_addr(SB)/4, $libc_sync_trampoline<>(SB) + +TEXT libc_truncate_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_truncate(SB) + +GLOBL ·libc_truncate_trampoline_addr(SB), RODATA, $4 +DATA ·libc_truncate_trampoline_addr(SB)/4, $libc_truncate_trampoline<>(SB) + +TEXT libc_umask_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_umask(SB) + +GLOBL ·libc_umask_trampoline_addr(SB), RODATA, $4 +DATA ·libc_umask_trampoline_addr(SB)/4, $libc_umask_trampoline<>(SB) + +TEXT libc_unlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unlink(SB) + +GLOBL ·libc_unlink_trampoline_addr(SB), RODATA, $4 +DATA ·libc_unlink_trampoline_addr(SB)/4, $libc_unlink_trampoline<>(SB) + +TEXT libc_unlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unlinkat(SB) + +GLOBL ·libc_unlinkat_trampoline_addr(SB), RODATA, $4 +DATA ·libc_unlinkat_trampoline_addr(SB)/4, $libc_unlinkat_trampoline<>(SB) + +TEXT libc_unmount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unmount(SB) + +GLOBL ·libc_unmount_trampoline_addr(SB), RODATA, $4 +DATA ·libc_unmount_trampoline_addr(SB)/4, $libc_unmount_trampoline<>(SB) + +TEXT libc_write_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_write(SB) + +GLOBL ·libc_write_trampoline_addr(SB), RODATA, $4 +DATA ·libc_write_trampoline_addr(SB)/4, $libc_write_trampoline<>(SB) + +TEXT libc_mmap_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mmap(SB) + +GLOBL ·libc_mmap_trampoline_addr(SB), RODATA, $4 +DATA ·libc_mmap_trampoline_addr(SB)/4, $libc_mmap_trampoline<>(SB) + +TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munmap(SB) + +GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $4 +DATA ·libc_munmap_trampoline_addr(SB)/4, $libc_munmap_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) 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 04db8fa2..98446d2b 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 @@ -1,4 +1,4 @@ -// go run mksyscall.go -openbsd -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go +// go run mksyscall.go -openbsd -libc -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && amd64 @@ -16,7 +16,7 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -24,20 +24,28 @@ func getgroups(ngid int, gid *_Gid_t) (n int, err error) { return } +var libc_getgroups_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getgroups getgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setgroups_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setgroups setgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -45,10 +53,14 @@ func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err return } +var libc_wait4_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_wait4 wait4 "libc.so" + // 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(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -56,30 +68,42 @@ func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { return } +var libc_accept_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_accept accept "libc.so" + // 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(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_bind_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_bind bind "libc.so" + // 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(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_connect_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_connect connect "libc.so" + // 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 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -87,66 +111,94 @@ func socket(domain int, typ int, proto int) (fd int, err error) { return } +var libc_socket_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_socket socket "libc.so" + // 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 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getsockopt_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsockopt getsockopt "libc.so" + // 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 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setsockopt_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setsockopt setsockopt "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getpeername_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpeername getpeername "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getsockname_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsockname getsockname "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_shutdown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_shutdown shutdown "libc.so" + // 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 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_socketpair_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_socketpair socketpair "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { @@ -156,7 +208,7 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -164,6 +216,10 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl return } +var libc_recvfrom_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_recvfrom recvfrom "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { @@ -173,17 +229,21 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sendto_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sendto sendto "libc.so" + // 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(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -191,10 +251,14 @@ func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +var libc_recvmsg_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_recvmsg recvmsg "libc.so" + // 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(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -202,10 +266,14 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +var libc_sendmsg_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sendmsg sendmsg "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -213,6 +281,10 @@ func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, ne return } +var libc_kevent_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kevent kevent "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { @@ -221,27 +293,35 @@ func utimes(path string, timeval *[2]Timeval) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_utimes_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_utimes utimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_futimes_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_futimes futimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { - r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -249,6 +329,10 @@ func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { return } +var libc_poll_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_poll poll "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { @@ -258,13 +342,17 @@ func Madvise(b []byte, behav int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_madvise_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_madvise madvise "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { @@ -274,23 +362,31 @@ func Mlock(b []byte) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mlock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mlock mlock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mlockall_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mlockall mlockall "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { @@ -300,13 +396,17 @@ func Mprotect(b []byte, prot int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mprotect_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mprotect mprotect "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { @@ -316,13 +416,17 @@ func Msync(b []byte, flags int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_msync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_msync msync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { @@ -332,33 +436,45 @@ func Munlock(b []byte) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munlock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munlock munlock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munlockall_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munlockall munlockall "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_pipe2_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pipe2 pipe2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { @@ -368,7 +484,7 @@ func Getdents(fd int, buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -376,6 +492,10 @@ func Getdents(fd int, buf []byte) (n int, err error) { return } +var libc_getdents_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getdents getdents "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { @@ -385,7 +505,7 @@ func Getcwd(buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -393,16 +513,24 @@ func Getcwd(buf []byte) (n int, err error) { return } +var libc_getcwd_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getcwd getcwd "libc.so" + // 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)) + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // 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) { @@ -412,17 +540,21 @@ func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sysctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sysctl sysctl "libc.so" + // 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 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + 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) if e1 != 0 { err = errnoErr(e1) @@ -430,6 +562,10 @@ func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, return } +var libc_ppoll_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ppoll ppoll "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { @@ -438,23 +574,31 @@ func Access(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_access_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_access access "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_adjtime_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_adjtime adjtime "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { @@ -463,13 +607,17 @@ func Chdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chdir chdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { @@ -478,13 +626,17 @@ func Chflags(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chflags_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chflags chflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { @@ -493,13 +645,17 @@ func Chmod(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chmod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chmod chmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { @@ -508,13 +664,17 @@ func Chown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chown chown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { @@ -523,27 +683,35 @@ func Chroot(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chroot_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chroot chroot "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_close_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_close close "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -551,33 +719,49 @@ func Dup(fd int) (nfd int, err error) { return } +var libc_dup_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup dup "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_dup2_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup2 dup2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_dup3_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup3 dup3 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) return } +var libc_exit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_exit exit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { @@ -586,43 +770,59 @@ func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_faccessat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_faccessat faccessat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchdir fchdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchflags_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchflags fchflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchmod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchmod fchmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { @@ -631,23 +831,31 @@ func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchmodat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" + // 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(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchown fchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { @@ -656,27 +864,35 @@ func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchownat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchownat fchownat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_flock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_flock flock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -684,16 +900,24 @@ func Fpathconf(fd int, name int) (val int, err error) { return } +var libc_fpathconf_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstat fstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { @@ -702,71 +926,99 @@ func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstatat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstatat fstatat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstatfs_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstatfs fstatfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fsync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fsync fsync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_ftruncate_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) egid = int(r0) return } +var libc_getegid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getegid getegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) uid = int(r0) return } +var libc_geteuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_geteuid geteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) gid = int(r0) return } +var libc_getgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getgid getgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -774,34 +1026,50 @@ func Getpgid(pid int) (pgid int, err error) { return } +var libc_getpgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpgid getpgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) pgrp = int(r0) return } +var libc_getpgrp_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) pid = int(r0) return } +var libc_getpid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpid getpid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) ppid = int(r0) return } +var libc_getppid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getppid getppid "libc.so" + // 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(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -809,20 +1077,28 @@ func Getpriority(which int, who int) (prio int, err error) { return } +var libc_getpriority_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpriority getpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getrlimit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { - r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) rtable = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -830,20 +1106,28 @@ func Getrtable() (rtable int, err error) { return } +var libc_getrtable_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrtable getrtable "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getrusage_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrusage getrusage "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -851,46 +1135,66 @@ func Getsid(pid int) (sid int, err error) { return } +var libc_getsid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsid getsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_gettimeofday_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) uid = int(r0) return } +var libc_getuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getuid getuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) tainted = bool(r0 != 0) return } +var libc_issetugid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_issetugid issetugid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_kill_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kill kill "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -898,6 +1202,10 @@ func Kqueue() (fd int, err error) { return } +var libc_kqueue_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kqueue kqueue "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { @@ -906,13 +1214,17 @@ func Lchown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_lchown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lchown lchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { @@ -926,13 +1238,17 @@ func Link(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_link_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_link link "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { @@ -946,23 +1262,31 @@ func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err er if err != nil { return } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_linkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_linkat linkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_listen_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_listen listen "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { @@ -971,13 +1295,17 @@ func Lstat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_lstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lstat lstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { @@ -986,13 +1314,17 @@ func Mkdir(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkdir mkdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { @@ -1001,13 +1333,17 @@ func Mkdirat(dirfd int, path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkdirat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { @@ -1016,13 +1352,17 @@ func Mkfifo(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkfifo_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { @@ -1031,13 +1371,17 @@ func Mkfifoat(dirfd int, path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkfifoat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkfifoat mkfifoat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { @@ -1046,13 +1390,17 @@ func Mknod(path string, mode uint32, dev int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mknod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mknod mknod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { @@ -1061,23 +1409,31 @@ func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mknodat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mknodat mknodat "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(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_nanosleep_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { @@ -1086,7 +1442,7 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1094,6 +1450,10 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { return } +var libc_open_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_open open "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { @@ -1102,7 +1462,7 @@ func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1110,6 +1470,10 @@ func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { return } +var libc_openat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_openat openat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { @@ -1118,7 +1482,7 @@ func Pathconf(path string, name int) (val int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1126,6 +1490,10 @@ func Pathconf(path string, name int) (val int, err error) { return } +var libc_pathconf_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pathconf pathconf "libc.so" + // 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) { @@ -1135,7 +1503,7 @@ func pread(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1143,6 +1511,10 @@ func pread(fd int, p []byte, offset int64) (n int, err error) { return } +var libc_pread_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pread pread "libc.so" + // 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) { @@ -1152,7 +1524,7 @@ func pwrite(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1160,6 +1532,10 @@ func pwrite(fd int, p []byte, offset int64) (n int, err error) { return } +var libc_pwrite_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pwrite pwrite "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { @@ -1169,7 +1545,7 @@ func read(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1177,6 +1553,10 @@ func read(fd int, p []byte) (n int, err error) { return } +var libc_read_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_read read "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { @@ -1191,7 +1571,7 @@ func Readlink(path string, buf []byte) (n int, err error) { } else { _p1 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1199,6 +1579,10 @@ func Readlink(path string, buf []byte) (n int, err error) { return } +var libc_readlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readlink readlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { @@ -1213,7 +1597,7 @@ func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { } else { _p1 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1221,6 +1605,10 @@ func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { return } +var libc_readlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readlinkat readlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { @@ -1234,13 +1622,17 @@ func Rename(from string, to string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_rename_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_rename rename "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { @@ -1254,13 +1646,17 @@ func Renameat(fromfd int, from string, tofd int, to string) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_renameat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renameat renameat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { @@ -1269,13 +1665,17 @@ func Revoke(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_revoke_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_revoke revoke "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { @@ -1284,17 +1684,21 @@ func Rmdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_rmdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_rmdir rmdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) @@ -1302,10 +1706,14 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { return } +var libc_lseek_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lseek lseek "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1313,36 +1721,52 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err return } +var libc_select_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_select select "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setegid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setegid setegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_seteuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_seteuid seteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setgid setgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { @@ -1351,97 +1775,133 @@ func Setlogin(name string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setlogin_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setlogin setlogin "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setpgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setpgid setpgid "libc.so" + // 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(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setpriority_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setpriority setpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setregid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setregid setregid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setreuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setreuid setreuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setresgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setresgid setresgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setresuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setresuid setresuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := syscall_rawSyscall(libc_setrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setrlimit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setrlimit setrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setrtable_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setrtable setrtable "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1449,26 +1909,38 @@ func Setsid() (pid int, err error) { return } +var libc_setsid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setsid setsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_settimeofday_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_settimeofday settimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setuid setuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { @@ -1477,13 +1949,17 @@ func Stat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_stat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_stat stat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { @@ -1492,13 +1968,17 @@ func Statfs(path string, stat *Statfs_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_statfs_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_statfs statfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { @@ -1512,13 +1992,17 @@ func Symlink(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_symlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_symlink symlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { @@ -1532,23 +2016,31 @@ func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_symlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_symlinkat symlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sync sync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { @@ -1557,21 +2049,29 @@ func Truncate(path string, length int64) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_truncate_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_truncate truncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) oldmask = int(r0) return } +var libc_umask_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_umask umask "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { @@ -1580,13 +2080,17 @@ func Unlink(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unlink unlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { @@ -1595,13 +2099,17 @@ func Unlinkat(dirfd int, path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { @@ -1610,13 +2118,17 @@ func Unmount(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unmount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unmount unmount "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { @@ -1626,7 +2138,7 @@ func write(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1634,10 +2146,14 @@ func write(fd int, p []byte) (n int, err error) { return } +var libc_write_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_write write "libc.so" + // 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 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) @@ -1645,20 +2161,28 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( return } +var libc_mmap_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mmap mmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munmap_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munmap munmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1669,7 +2193,7 @@ func readlen(fd int, buf *byte, nbuf int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1685,9 +2209,13 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error if err != nil { return } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } + +var libc_utimensat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_utimensat utimensat "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 new file mode 100644 index 00000000..243a6663 --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s @@ -0,0 +1,796 @@ +// go run mkasm.go openbsd amd64 +// Code generated by the command above; DO NOT EDIT. + +#include "textflag.h" + +TEXT libc_getgroups_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getgroups(SB) + +GLOBL ·libc_getgroups_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getgroups_trampoline_addr(SB)/8, $libc_getgroups_trampoline<>(SB) + +TEXT libc_setgroups_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setgroups(SB) + +GLOBL ·libc_setgroups_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setgroups_trampoline_addr(SB)/8, $libc_setgroups_trampoline<>(SB) + +TEXT libc_wait4_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_wait4(SB) + +GLOBL ·libc_wait4_trampoline_addr(SB), RODATA, $8 +DATA ·libc_wait4_trampoline_addr(SB)/8, $libc_wait4_trampoline<>(SB) + +TEXT libc_accept_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_accept(SB) + +GLOBL ·libc_accept_trampoline_addr(SB), RODATA, $8 +DATA ·libc_accept_trampoline_addr(SB)/8, $libc_accept_trampoline<>(SB) + +TEXT libc_bind_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_bind(SB) + +GLOBL ·libc_bind_trampoline_addr(SB), RODATA, $8 +DATA ·libc_bind_trampoline_addr(SB)/8, $libc_bind_trampoline<>(SB) + +TEXT libc_connect_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_connect(SB) + +GLOBL ·libc_connect_trampoline_addr(SB), RODATA, $8 +DATA ·libc_connect_trampoline_addr(SB)/8, $libc_connect_trampoline<>(SB) + +TEXT libc_socket_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_socket(SB) + +GLOBL ·libc_socket_trampoline_addr(SB), RODATA, $8 +DATA ·libc_socket_trampoline_addr(SB)/8, $libc_socket_trampoline<>(SB) + +TEXT libc_getsockopt_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsockopt(SB) + +GLOBL ·libc_getsockopt_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getsockopt_trampoline_addr(SB)/8, $libc_getsockopt_trampoline<>(SB) + +TEXT libc_setsockopt_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setsockopt(SB) + +GLOBL ·libc_setsockopt_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setsockopt_trampoline_addr(SB)/8, $libc_setsockopt_trampoline<>(SB) + +TEXT libc_getpeername_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpeername(SB) + +GLOBL ·libc_getpeername_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpeername_trampoline_addr(SB)/8, $libc_getpeername_trampoline<>(SB) + +TEXT libc_getsockname_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsockname(SB) + +GLOBL ·libc_getsockname_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getsockname_trampoline_addr(SB)/8, $libc_getsockname_trampoline<>(SB) + +TEXT libc_shutdown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_shutdown(SB) + +GLOBL ·libc_shutdown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_shutdown_trampoline_addr(SB)/8, $libc_shutdown_trampoline<>(SB) + +TEXT libc_socketpair_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_socketpair(SB) + +GLOBL ·libc_socketpair_trampoline_addr(SB), RODATA, $8 +DATA ·libc_socketpair_trampoline_addr(SB)/8, $libc_socketpair_trampoline<>(SB) + +TEXT libc_recvfrom_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_recvfrom(SB) + +GLOBL ·libc_recvfrom_trampoline_addr(SB), RODATA, $8 +DATA ·libc_recvfrom_trampoline_addr(SB)/8, $libc_recvfrom_trampoline<>(SB) + +TEXT libc_sendto_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sendto(SB) + +GLOBL ·libc_sendto_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sendto_trampoline_addr(SB)/8, $libc_sendto_trampoline<>(SB) + +TEXT libc_recvmsg_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_recvmsg(SB) + +GLOBL ·libc_recvmsg_trampoline_addr(SB), RODATA, $8 +DATA ·libc_recvmsg_trampoline_addr(SB)/8, $libc_recvmsg_trampoline<>(SB) + +TEXT libc_sendmsg_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sendmsg(SB) + +GLOBL ·libc_sendmsg_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sendmsg_trampoline_addr(SB)/8, $libc_sendmsg_trampoline<>(SB) + +TEXT libc_kevent_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kevent(SB) + +GLOBL ·libc_kevent_trampoline_addr(SB), RODATA, $8 +DATA ·libc_kevent_trampoline_addr(SB)/8, $libc_kevent_trampoline<>(SB) + +TEXT libc_utimes_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_utimes(SB) + +GLOBL ·libc_utimes_trampoline_addr(SB), RODATA, $8 +DATA ·libc_utimes_trampoline_addr(SB)/8, $libc_utimes_trampoline<>(SB) + +TEXT libc_futimes_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_futimes(SB) + +GLOBL ·libc_futimes_trampoline_addr(SB), RODATA, $8 +DATA ·libc_futimes_trampoline_addr(SB)/8, $libc_futimes_trampoline<>(SB) + +TEXT libc_poll_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_poll(SB) + +GLOBL ·libc_poll_trampoline_addr(SB), RODATA, $8 +DATA ·libc_poll_trampoline_addr(SB)/8, $libc_poll_trampoline<>(SB) + +TEXT libc_madvise_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_madvise(SB) + +GLOBL ·libc_madvise_trampoline_addr(SB), RODATA, $8 +DATA ·libc_madvise_trampoline_addr(SB)/8, $libc_madvise_trampoline<>(SB) + +TEXT libc_mlock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mlock(SB) + +GLOBL ·libc_mlock_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mlock_trampoline_addr(SB)/8, $libc_mlock_trampoline<>(SB) + +TEXT libc_mlockall_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mlockall(SB) + +GLOBL ·libc_mlockall_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mlockall_trampoline_addr(SB)/8, $libc_mlockall_trampoline<>(SB) + +TEXT libc_mprotect_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mprotect(SB) + +GLOBL ·libc_mprotect_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mprotect_trampoline_addr(SB)/8, $libc_mprotect_trampoline<>(SB) + +TEXT libc_msync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_msync(SB) + +GLOBL ·libc_msync_trampoline_addr(SB), RODATA, $8 +DATA ·libc_msync_trampoline_addr(SB)/8, $libc_msync_trampoline<>(SB) + +TEXT libc_munlock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munlock(SB) + +GLOBL ·libc_munlock_trampoline_addr(SB), RODATA, $8 +DATA ·libc_munlock_trampoline_addr(SB)/8, $libc_munlock_trampoline<>(SB) + +TEXT libc_munlockall_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munlockall(SB) + +GLOBL ·libc_munlockall_trampoline_addr(SB), RODATA, $8 +DATA ·libc_munlockall_trampoline_addr(SB)/8, $libc_munlockall_trampoline<>(SB) + +TEXT libc_pipe2_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pipe2(SB) + +GLOBL ·libc_pipe2_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pipe2_trampoline_addr(SB)/8, $libc_pipe2_trampoline<>(SB) + +TEXT libc_getdents_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getdents(SB) + +GLOBL ·libc_getdents_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getdents_trampoline_addr(SB)/8, $libc_getdents_trampoline<>(SB) + +TEXT libc_getcwd_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getcwd(SB) + +GLOBL ·libc_getcwd_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getcwd_trampoline_addr(SB)/8, $libc_getcwd_trampoline<>(SB) + +TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ioctl(SB) + +GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_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_ppoll_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ppoll(SB) + +GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 +DATA ·libc_ppoll_trampoline_addr(SB)/8, $libc_ppoll_trampoline<>(SB) + +TEXT libc_access_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_access(SB) + +GLOBL ·libc_access_trampoline_addr(SB), RODATA, $8 +DATA ·libc_access_trampoline_addr(SB)/8, $libc_access_trampoline<>(SB) + +TEXT libc_adjtime_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_adjtime(SB) + +GLOBL ·libc_adjtime_trampoline_addr(SB), RODATA, $8 +DATA ·libc_adjtime_trampoline_addr(SB)/8, $libc_adjtime_trampoline<>(SB) + +TEXT libc_chdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chdir(SB) + +GLOBL ·libc_chdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chdir_trampoline_addr(SB)/8, $libc_chdir_trampoline<>(SB) + +TEXT libc_chflags_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chflags(SB) + +GLOBL ·libc_chflags_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chflags_trampoline_addr(SB)/8, $libc_chflags_trampoline<>(SB) + +TEXT libc_chmod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chmod(SB) + +GLOBL ·libc_chmod_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chmod_trampoline_addr(SB)/8, $libc_chmod_trampoline<>(SB) + +TEXT libc_chown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chown(SB) + +GLOBL ·libc_chown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chown_trampoline_addr(SB)/8, $libc_chown_trampoline<>(SB) + +TEXT libc_chroot_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chroot(SB) + +GLOBL ·libc_chroot_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chroot_trampoline_addr(SB)/8, $libc_chroot_trampoline<>(SB) + +TEXT libc_close_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_close(SB) + +GLOBL ·libc_close_trampoline_addr(SB), RODATA, $8 +DATA ·libc_close_trampoline_addr(SB)/8, $libc_close_trampoline<>(SB) + +TEXT libc_dup_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup(SB) + +GLOBL ·libc_dup_trampoline_addr(SB), RODATA, $8 +DATA ·libc_dup_trampoline_addr(SB)/8, $libc_dup_trampoline<>(SB) + +TEXT libc_dup2_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup2(SB) + +GLOBL ·libc_dup2_trampoline_addr(SB), RODATA, $8 +DATA ·libc_dup2_trampoline_addr(SB)/8, $libc_dup2_trampoline<>(SB) + +TEXT libc_dup3_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup3(SB) + +GLOBL ·libc_dup3_trampoline_addr(SB), RODATA, $8 +DATA ·libc_dup3_trampoline_addr(SB)/8, $libc_dup3_trampoline<>(SB) + +TEXT libc_exit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_exit(SB) + +GLOBL ·libc_exit_trampoline_addr(SB), RODATA, $8 +DATA ·libc_exit_trampoline_addr(SB)/8, $libc_exit_trampoline<>(SB) + +TEXT libc_faccessat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_faccessat(SB) + +GLOBL ·libc_faccessat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_faccessat_trampoline_addr(SB)/8, $libc_faccessat_trampoline<>(SB) + +TEXT libc_fchdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchdir(SB) + +GLOBL ·libc_fchdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchdir_trampoline_addr(SB)/8, $libc_fchdir_trampoline<>(SB) + +TEXT libc_fchflags_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchflags(SB) + +GLOBL ·libc_fchflags_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchflags_trampoline_addr(SB)/8, $libc_fchflags_trampoline<>(SB) + +TEXT libc_fchmod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchmod(SB) + +GLOBL ·libc_fchmod_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchmod_trampoline_addr(SB)/8, $libc_fchmod_trampoline<>(SB) + +TEXT libc_fchmodat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchmodat(SB) + +GLOBL ·libc_fchmodat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchmodat_trampoline_addr(SB)/8, $libc_fchmodat_trampoline<>(SB) + +TEXT libc_fchown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchown(SB) + +GLOBL ·libc_fchown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchown_trampoline_addr(SB)/8, $libc_fchown_trampoline<>(SB) + +TEXT libc_fchownat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchownat(SB) + +GLOBL ·libc_fchownat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchownat_trampoline_addr(SB)/8, $libc_fchownat_trampoline<>(SB) + +TEXT libc_flock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_flock(SB) + +GLOBL ·libc_flock_trampoline_addr(SB), RODATA, $8 +DATA ·libc_flock_trampoline_addr(SB)/8, $libc_flock_trampoline<>(SB) + +TEXT libc_fpathconf_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fpathconf(SB) + +GLOBL ·libc_fpathconf_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fpathconf_trampoline_addr(SB)/8, $libc_fpathconf_trampoline<>(SB) + +TEXT libc_fstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstat(SB) + +GLOBL ·libc_fstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fstat_trampoline_addr(SB)/8, $libc_fstat_trampoline<>(SB) + +TEXT libc_fstatat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstatat(SB) + +GLOBL ·libc_fstatat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fstatat_trampoline_addr(SB)/8, $libc_fstatat_trampoline<>(SB) + +TEXT libc_fstatfs_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstatfs(SB) + +GLOBL ·libc_fstatfs_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fstatfs_trampoline_addr(SB)/8, $libc_fstatfs_trampoline<>(SB) + +TEXT libc_fsync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fsync(SB) + +GLOBL ·libc_fsync_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fsync_trampoline_addr(SB)/8, $libc_fsync_trampoline<>(SB) + +TEXT libc_ftruncate_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ftruncate(SB) + +GLOBL ·libc_ftruncate_trampoline_addr(SB), RODATA, $8 +DATA ·libc_ftruncate_trampoline_addr(SB)/8, $libc_ftruncate_trampoline<>(SB) + +TEXT libc_getegid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getegid(SB) + +GLOBL ·libc_getegid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getegid_trampoline_addr(SB)/8, $libc_getegid_trampoline<>(SB) + +TEXT libc_geteuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_geteuid(SB) + +GLOBL ·libc_geteuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_geteuid_trampoline_addr(SB)/8, $libc_geteuid_trampoline<>(SB) + +TEXT libc_getgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getgid(SB) + +GLOBL ·libc_getgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getgid_trampoline_addr(SB)/8, $libc_getgid_trampoline<>(SB) + +TEXT libc_getpgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpgid(SB) + +GLOBL ·libc_getpgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpgid_trampoline_addr(SB)/8, $libc_getpgid_trampoline<>(SB) + +TEXT libc_getpgrp_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpgrp(SB) + +GLOBL ·libc_getpgrp_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpgrp_trampoline_addr(SB)/8, $libc_getpgrp_trampoline<>(SB) + +TEXT libc_getpid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpid(SB) + +GLOBL ·libc_getpid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpid_trampoline_addr(SB)/8, $libc_getpid_trampoline<>(SB) + +TEXT libc_getppid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getppid(SB) + +GLOBL ·libc_getppid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getppid_trampoline_addr(SB)/8, $libc_getppid_trampoline<>(SB) + +TEXT libc_getpriority_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpriority(SB) + +GLOBL ·libc_getpriority_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpriority_trampoline_addr(SB)/8, $libc_getpriority_trampoline<>(SB) + +TEXT libc_getrlimit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrlimit(SB) + +GLOBL ·libc_getrlimit_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getrlimit_trampoline_addr(SB)/8, $libc_getrlimit_trampoline<>(SB) + +TEXT libc_getrtable_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrtable(SB) + +GLOBL ·libc_getrtable_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getrtable_trampoline_addr(SB)/8, $libc_getrtable_trampoline<>(SB) + +TEXT libc_getrusage_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrusage(SB) + +GLOBL ·libc_getrusage_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getrusage_trampoline_addr(SB)/8, $libc_getrusage_trampoline<>(SB) + +TEXT libc_getsid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsid(SB) + +GLOBL ·libc_getsid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getsid_trampoline_addr(SB)/8, $libc_getsid_trampoline<>(SB) + +TEXT libc_gettimeofday_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_gettimeofday(SB) + +GLOBL ·libc_gettimeofday_trampoline_addr(SB), RODATA, $8 +DATA ·libc_gettimeofday_trampoline_addr(SB)/8, $libc_gettimeofday_trampoline<>(SB) + +TEXT libc_getuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getuid(SB) + +GLOBL ·libc_getuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getuid_trampoline_addr(SB)/8, $libc_getuid_trampoline<>(SB) + +TEXT libc_issetugid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_issetugid(SB) + +GLOBL ·libc_issetugid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_issetugid_trampoline_addr(SB)/8, $libc_issetugid_trampoline<>(SB) + +TEXT libc_kill_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kill(SB) + +GLOBL ·libc_kill_trampoline_addr(SB), RODATA, $8 +DATA ·libc_kill_trampoline_addr(SB)/8, $libc_kill_trampoline<>(SB) + +TEXT libc_kqueue_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kqueue(SB) + +GLOBL ·libc_kqueue_trampoline_addr(SB), RODATA, $8 +DATA ·libc_kqueue_trampoline_addr(SB)/8, $libc_kqueue_trampoline<>(SB) + +TEXT libc_lchown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lchown(SB) + +GLOBL ·libc_lchown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_lchown_trampoline_addr(SB)/8, $libc_lchown_trampoline<>(SB) + +TEXT libc_link_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_link(SB) + +GLOBL ·libc_link_trampoline_addr(SB), RODATA, $8 +DATA ·libc_link_trampoline_addr(SB)/8, $libc_link_trampoline<>(SB) + +TEXT libc_linkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_linkat(SB) + +GLOBL ·libc_linkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_linkat_trampoline_addr(SB)/8, $libc_linkat_trampoline<>(SB) + +TEXT libc_listen_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_listen(SB) + +GLOBL ·libc_listen_trampoline_addr(SB), RODATA, $8 +DATA ·libc_listen_trampoline_addr(SB)/8, $libc_listen_trampoline<>(SB) + +TEXT libc_lstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lstat(SB) + +GLOBL ·libc_lstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_lstat_trampoline_addr(SB)/8, $libc_lstat_trampoline<>(SB) + +TEXT libc_mkdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkdir(SB) + +GLOBL ·libc_mkdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkdir_trampoline_addr(SB)/8, $libc_mkdir_trampoline<>(SB) + +TEXT libc_mkdirat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkdirat(SB) + +GLOBL ·libc_mkdirat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkdirat_trampoline_addr(SB)/8, $libc_mkdirat_trampoline<>(SB) + +TEXT libc_mkfifo_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkfifo(SB) + +GLOBL ·libc_mkfifo_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkfifo_trampoline_addr(SB)/8, $libc_mkfifo_trampoline<>(SB) + +TEXT libc_mkfifoat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkfifoat(SB) + +GLOBL ·libc_mkfifoat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkfifoat_trampoline_addr(SB)/8, $libc_mkfifoat_trampoline<>(SB) + +TEXT libc_mknod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mknod(SB) + +GLOBL ·libc_mknod_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mknod_trampoline_addr(SB)/8, $libc_mknod_trampoline<>(SB) + +TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mknodat(SB) + +GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) + +TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_nanosleep(SB) + +GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 +DATA ·libc_nanosleep_trampoline_addr(SB)/8, $libc_nanosleep_trampoline<>(SB) + +TEXT libc_open_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_open(SB) + +GLOBL ·libc_open_trampoline_addr(SB), RODATA, $8 +DATA ·libc_open_trampoline_addr(SB)/8, $libc_open_trampoline<>(SB) + +TEXT libc_openat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_openat(SB) + +GLOBL ·libc_openat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_openat_trampoline_addr(SB)/8, $libc_openat_trampoline<>(SB) + +TEXT libc_pathconf_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pathconf(SB) + +GLOBL ·libc_pathconf_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pathconf_trampoline_addr(SB)/8, $libc_pathconf_trampoline<>(SB) + +TEXT libc_pread_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pread(SB) + +GLOBL ·libc_pread_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pread_trampoline_addr(SB)/8, $libc_pread_trampoline<>(SB) + +TEXT libc_pwrite_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pwrite(SB) + +GLOBL ·libc_pwrite_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pwrite_trampoline_addr(SB)/8, $libc_pwrite_trampoline<>(SB) + +TEXT libc_read_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_read(SB) + +GLOBL ·libc_read_trampoline_addr(SB), RODATA, $8 +DATA ·libc_read_trampoline_addr(SB)/8, $libc_read_trampoline<>(SB) + +TEXT libc_readlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readlink(SB) + +GLOBL ·libc_readlink_trampoline_addr(SB), RODATA, $8 +DATA ·libc_readlink_trampoline_addr(SB)/8, $libc_readlink_trampoline<>(SB) + +TEXT libc_readlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readlinkat(SB) + +GLOBL ·libc_readlinkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_readlinkat_trampoline_addr(SB)/8, $libc_readlinkat_trampoline<>(SB) + +TEXT libc_rename_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_rename(SB) + +GLOBL ·libc_rename_trampoline_addr(SB), RODATA, $8 +DATA ·libc_rename_trampoline_addr(SB)/8, $libc_rename_trampoline<>(SB) + +TEXT libc_renameat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renameat(SB) + +GLOBL ·libc_renameat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renameat_trampoline_addr(SB)/8, $libc_renameat_trampoline<>(SB) + +TEXT libc_revoke_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_revoke(SB) + +GLOBL ·libc_revoke_trampoline_addr(SB), RODATA, $8 +DATA ·libc_revoke_trampoline_addr(SB)/8, $libc_revoke_trampoline<>(SB) + +TEXT libc_rmdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_rmdir(SB) + +GLOBL ·libc_rmdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_rmdir_trampoline_addr(SB)/8, $libc_rmdir_trampoline<>(SB) + +TEXT libc_lseek_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lseek(SB) + +GLOBL ·libc_lseek_trampoline_addr(SB), RODATA, $8 +DATA ·libc_lseek_trampoline_addr(SB)/8, $libc_lseek_trampoline<>(SB) + +TEXT libc_select_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_select(SB) + +GLOBL ·libc_select_trampoline_addr(SB), RODATA, $8 +DATA ·libc_select_trampoline_addr(SB)/8, $libc_select_trampoline<>(SB) + +TEXT libc_setegid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setegid(SB) + +GLOBL ·libc_setegid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setegid_trampoline_addr(SB)/8, $libc_setegid_trampoline<>(SB) + +TEXT libc_seteuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_seteuid(SB) + +GLOBL ·libc_seteuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_seteuid_trampoline_addr(SB)/8, $libc_seteuid_trampoline<>(SB) + +TEXT libc_setgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setgid(SB) + +GLOBL ·libc_setgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setgid_trampoline_addr(SB)/8, $libc_setgid_trampoline<>(SB) + +TEXT libc_setlogin_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setlogin(SB) + +GLOBL ·libc_setlogin_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setlogin_trampoline_addr(SB)/8, $libc_setlogin_trampoline<>(SB) + +TEXT libc_setpgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setpgid(SB) + +GLOBL ·libc_setpgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setpgid_trampoline_addr(SB)/8, $libc_setpgid_trampoline<>(SB) + +TEXT libc_setpriority_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setpriority(SB) + +GLOBL ·libc_setpriority_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setpriority_trampoline_addr(SB)/8, $libc_setpriority_trampoline<>(SB) + +TEXT libc_setregid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setregid(SB) + +GLOBL ·libc_setregid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setregid_trampoline_addr(SB)/8, $libc_setregid_trampoline<>(SB) + +TEXT libc_setreuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setreuid(SB) + +GLOBL ·libc_setreuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setreuid_trampoline_addr(SB)/8, $libc_setreuid_trampoline<>(SB) + +TEXT libc_setresgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setresgid(SB) + +GLOBL ·libc_setresgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setresgid_trampoline_addr(SB)/8, $libc_setresgid_trampoline<>(SB) + +TEXT libc_setresuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setresuid(SB) + +GLOBL ·libc_setresuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setresuid_trampoline_addr(SB)/8, $libc_setresuid_trampoline<>(SB) + +TEXT libc_setrlimit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setrlimit(SB) + +GLOBL ·libc_setrlimit_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setrlimit_trampoline_addr(SB)/8, $libc_setrlimit_trampoline<>(SB) + +TEXT libc_setrtable_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setrtable(SB) + +GLOBL ·libc_setrtable_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setrtable_trampoline_addr(SB)/8, $libc_setrtable_trampoline<>(SB) + +TEXT libc_setsid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setsid(SB) + +GLOBL ·libc_setsid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setsid_trampoline_addr(SB)/8, $libc_setsid_trampoline<>(SB) + +TEXT libc_settimeofday_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_settimeofday(SB) + +GLOBL ·libc_settimeofday_trampoline_addr(SB), RODATA, $8 +DATA ·libc_settimeofday_trampoline_addr(SB)/8, $libc_settimeofday_trampoline<>(SB) + +TEXT libc_setuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setuid(SB) + +GLOBL ·libc_setuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setuid_trampoline_addr(SB)/8, $libc_setuid_trampoline<>(SB) + +TEXT libc_stat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_stat(SB) + +GLOBL ·libc_stat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_stat_trampoline_addr(SB)/8, $libc_stat_trampoline<>(SB) + +TEXT libc_statfs_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_statfs(SB) + +GLOBL ·libc_statfs_trampoline_addr(SB), RODATA, $8 +DATA ·libc_statfs_trampoline_addr(SB)/8, $libc_statfs_trampoline<>(SB) + +TEXT libc_symlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_symlink(SB) + +GLOBL ·libc_symlink_trampoline_addr(SB), RODATA, $8 +DATA ·libc_symlink_trampoline_addr(SB)/8, $libc_symlink_trampoline<>(SB) + +TEXT libc_symlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_symlinkat(SB) + +GLOBL ·libc_symlinkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_symlinkat_trampoline_addr(SB)/8, $libc_symlinkat_trampoline<>(SB) + +TEXT libc_sync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sync(SB) + +GLOBL ·libc_sync_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sync_trampoline_addr(SB)/8, $libc_sync_trampoline<>(SB) + +TEXT libc_truncate_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_truncate(SB) + +GLOBL ·libc_truncate_trampoline_addr(SB), RODATA, $8 +DATA ·libc_truncate_trampoline_addr(SB)/8, $libc_truncate_trampoline<>(SB) + +TEXT libc_umask_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_umask(SB) + +GLOBL ·libc_umask_trampoline_addr(SB), RODATA, $8 +DATA ·libc_umask_trampoline_addr(SB)/8, $libc_umask_trampoline<>(SB) + +TEXT libc_unlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unlink(SB) + +GLOBL ·libc_unlink_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unlink_trampoline_addr(SB)/8, $libc_unlink_trampoline<>(SB) + +TEXT libc_unlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unlinkat(SB) + +GLOBL ·libc_unlinkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unlinkat_trampoline_addr(SB)/8, $libc_unlinkat_trampoline<>(SB) + +TEXT libc_unmount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unmount(SB) + +GLOBL ·libc_unmount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unmount_trampoline_addr(SB)/8, $libc_unmount_trampoline<>(SB) + +TEXT libc_write_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_write(SB) + +GLOBL ·libc_write_trampoline_addr(SB), RODATA, $8 +DATA ·libc_write_trampoline_addr(SB)/8, $libc_write_trampoline<>(SB) + +TEXT libc_mmap_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mmap(SB) + +GLOBL ·libc_mmap_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mmap_trampoline_addr(SB)/8, $libc_mmap_trampoline<>(SB) + +TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munmap(SB) + +GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 +DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_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) 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 c96a5051..800aab6e 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 @@ -1,4 +1,4 @@ -// go run mksyscall.go -openbsd -tags openbsd,arm64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm64.go +// go run mksyscall.go -openbsd -libc -tags openbsd,arm64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm64.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build openbsd && arm64 @@ -16,7 +16,7 @@ var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + r0, _, e1 := syscall_rawSyscall(libc_getgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -24,20 +24,28 @@ func getgroups(ngid int, gid *_Gid_t) (n int, err error) { return } +var libc_getgroups_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getgroups getgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + _, _, e1 := syscall_rawSyscall(libc_setgroups_trampoline_addr, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setgroups_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setgroups setgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + r0, _, e1 := syscall_syscall6(libc_wait4_trampoline_addr, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -45,10 +53,14 @@ func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err return } +var libc_wait4_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_wait4 wait4 "libc.so" + // 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(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + r0, _, e1 := syscall_syscall(libc_accept_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -56,30 +68,42 @@ func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { return } +var libc_accept_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_accept accept "libc.so" + // 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(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall_syscall(libc_bind_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_bind_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_bind bind "libc.so" + // 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(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall_syscall(libc_connect_trampoline_addr, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_connect_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_connect connect "libc.so" + // 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 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + r0, _, e1 := syscall_rawSyscall(libc_socket_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -87,66 +111,94 @@ func socket(domain int, typ int, proto int) (fd int, err error) { return } +var libc_socket_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_socket socket "libc.so" + // 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 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + _, _, e1 := syscall_syscall6(libc_getsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getsockopt_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsockopt getsockopt "libc.so" + // 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 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + _, _, e1 := syscall_syscall6(libc_setsockopt_trampoline_addr, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setsockopt_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setsockopt setsockopt "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := syscall_rawSyscall(libc_getpeername_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getpeername_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpeername getpeername "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := syscall_rawSyscall(libc_getsockname_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getsockname_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsockname getsockname "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + _, _, e1 := syscall_syscall(libc_shutdown_trampoline_addr, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_shutdown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_shutdown shutdown "libc.so" + // 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 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + _, _, e1 := syscall_rawSyscall6(libc_socketpair_trampoline_addr, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_socketpair_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_socketpair socketpair "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { @@ -156,7 +208,7 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + r0, _, e1 := syscall_syscall6(libc_recvfrom_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -164,6 +216,10 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl return } +var libc_recvfrom_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_recvfrom recvfrom "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { @@ -173,17 +229,21 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + _, _, e1 := syscall_syscall6(libc_sendto_trampoline_addr, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sendto_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sendto sendto "libc.so" + // 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(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall_syscall(libc_recvmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -191,10 +251,14 @@ func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +var libc_recvmsg_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_recvmsg recvmsg "libc.so" + // 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(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall_syscall(libc_sendmsg_trampoline_addr, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -202,10 +266,14 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +var libc_sendmsg_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sendmsg sendmsg "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + r0, _, e1 := syscall_syscall6(libc_kevent_trampoline_addr, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -213,6 +281,10 @@ func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, ne return } +var libc_kevent_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kevent kevent "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { @@ -221,27 +293,35 @@ func utimes(path string, timeval *[2]Timeval) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall_syscall(libc_utimes_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_utimes_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_utimes utimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall_syscall(libc_futimes_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_futimes_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_futimes futimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { - r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) + r0, _, e1 := syscall_syscall(libc_poll_trampoline_addr, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -249,6 +329,10 @@ func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { return } +var libc_poll_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_poll poll "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, behav int) (err error) { @@ -258,13 +342,17 @@ func Madvise(b []byte, behav int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav)) + _, _, e1 := syscall_syscall(libc_madvise_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(behav)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_madvise_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_madvise madvise "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { @@ -274,23 +362,31 @@ func Mlock(b []byte) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) + _, _, e1 := syscall_syscall(libc_mlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mlock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mlock mlock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { - _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall(libc_mlockall_trampoline_addr, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mlockall_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mlockall mlockall "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { @@ -300,13 +396,17 @@ func Mprotect(b []byte, prot int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) + _, _, e1 := syscall_syscall(libc_mprotect_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mprotect_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mprotect mprotect "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Msync(b []byte, flags int) (err error) { @@ -316,13 +416,17 @@ func Msync(b []byte, flags int) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_msync_trampoline_addr, uintptr(_p0), uintptr(len(b)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_msync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_msync msync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { @@ -332,33 +436,45 @@ func Munlock(b []byte) (err error) { } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) + _, _, e1 := syscall_syscall(libc_munlock_trampoline_addr, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munlock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munlock munlock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { - _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) + _, _, e1 := syscall_syscall(libc_munlockall_trampoline_addr, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munlockall_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munlockall munlockall "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + _, _, e1 := syscall_rawSyscall(libc_pipe2_trampoline_addr, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_pipe2_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pipe2 pipe2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { @@ -368,7 +484,7 @@ func Getdents(fd int, buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + r0, _, e1 := syscall_syscall(libc_getdents_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -376,6 +492,10 @@ func Getdents(fd int, buf []byte) (n int, err error) { return } +var libc_getdents_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getdents getdents "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { @@ -385,7 +505,7 @@ func Getcwd(buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + r0, _, e1 := syscall_syscall(libc_getcwd_trampoline_addr, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -393,16 +513,24 @@ func Getcwd(buf []byte) (n int, err error) { return } +var libc_getcwd_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getcwd getcwd "libc.so" + // 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)) + _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // 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) { @@ -412,17 +540,21 @@ func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + _, _, e1 := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sysctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sysctl sysctl "libc.so" + // 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 := Syscall6(SYS_PPOLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)), 0, 0) + 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) if e1 != 0 { err = errnoErr(e1) @@ -430,6 +562,10 @@ func ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, return } +var libc_ppoll_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ppoll ppoll "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { @@ -438,23 +574,31 @@ func Access(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_access_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_access_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_access access "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + _, _, e1 := syscall_syscall(libc_adjtime_trampoline_addr, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_adjtime_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_adjtime adjtime "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { @@ -463,13 +607,17 @@ func Chdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_chdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chdir chdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { @@ -478,13 +626,17 @@ func Chflags(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_chflags_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chflags_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chflags chflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { @@ -493,13 +645,17 @@ func Chmod(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_chmod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chmod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chmod chmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { @@ -508,13 +664,17 @@ func Chown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_chown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chown chown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { @@ -523,27 +683,35 @@ func Chroot(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_chroot_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_chroot_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_chroot chroot "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_close_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_close_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_close close "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + r0, _, e1 := syscall_syscall(libc_dup_trampoline_addr, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -551,33 +719,49 @@ func Dup(fd int) (nfd int, err error) { return } +var libc_dup_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup dup "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + _, _, e1 := syscall_syscall(libc_dup2_trampoline_addr, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_dup2_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup2 dup2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(from int, to int, flags int) (err error) { - _, _, e1 := Syscall(SYS_DUP3, uintptr(from), uintptr(to), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_dup3_trampoline_addr, uintptr(from), uintptr(to), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_dup3_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_dup3 dup3 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT, uintptr(code), 0, 0) + syscall_syscall(libc_exit_trampoline_addr, uintptr(code), 0, 0) return } +var libc_exit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_exit exit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { @@ -586,43 +770,59 @@ func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_faccessat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_faccessat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_faccessat faccessat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_fchdir_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchdir fchdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_fchflags_trampoline_addr, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchflags_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchflags fchflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_fchmod_trampoline_addr, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchmod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchmod fchmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { @@ -631,23 +831,31 @@ func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_fchmodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchmodat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchmodat fchmodat "libc.so" + // 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(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_fchown_trampoline_addr, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchown fchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { @@ -656,27 +864,35 @@ func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) + _, _, e1 := syscall_syscall6(libc_fchownat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fchownat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fchownat fchownat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + _, _, e1 := syscall_syscall(libc_flock_trampoline_addr, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_flock_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_flock flock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + r0, _, e1 := syscall_syscall(libc_fpathconf_trampoline_addr, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -684,16 +900,24 @@ func Fpathconf(fd int, name int) (val int, err error) { return } +var libc_fpathconf_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstat fstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { @@ -702,71 +926,99 @@ func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_fstatat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstatat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstatat fstatat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_fstatfs_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fstatfs_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fstatfs fstatfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + _, _, e1 := syscall_syscall(libc_fsync_trampoline_addr, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_fsync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_fsync fsync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) + _, _, e1 := syscall_syscall(libc_ftruncate_trampoline_addr, uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_ftruncate_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getegid_trampoline_addr, 0, 0, 0) egid = int(r0) return } +var libc_getegid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getegid getegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_geteuid_trampoline_addr, 0, 0, 0) uid = int(r0) return } +var libc_geteuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_geteuid geteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getgid_trampoline_addr, 0, 0, 0) gid = int(r0) return } +var libc_getgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getgid getgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getpgid_trampoline_addr, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -774,34 +1026,50 @@ func Getpgid(pid int) (pgid int, err error) { return } +var libc_getpgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpgid getpgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getpgrp_trampoline_addr, 0, 0, 0) pgrp = int(r0) return } +var libc_getpgrp_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getpid_trampoline_addr, 0, 0, 0) pid = int(r0) return } +var libc_getpid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpid getpid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getppid_trampoline_addr, 0, 0, 0) ppid = int(r0) return } +var libc_getppid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getppid getppid "libc.so" + // 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(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + r0, _, e1 := syscall_syscall(libc_getpriority_trampoline_addr, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -809,20 +1077,28 @@ func Getpriority(which int, who int) (prio int, err error) { return } +var libc_getpriority_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getpriority getpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := syscall_rawSyscall(libc_getrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getrlimit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrtable() (rtable int, err error) { - r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getrtable_trampoline_addr, 0, 0, 0) rtable = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -830,20 +1106,28 @@ func Getrtable() (rtable int, err error) { return } +var libc_getrtable_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrtable getrtable "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + _, _, e1 := syscall_rawSyscall(libc_getrusage_trampoline_addr, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_getrusage_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getrusage getrusage "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_getsid_trampoline_addr, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -851,46 +1135,66 @@ func Getsid(pid int) (sid int, err error) { return } +var libc_getsid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getsid getsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_gettimeofday_trampoline_addr, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_gettimeofday_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _, _ := syscall_rawSyscall(libc_getuid_trampoline_addr, 0, 0, 0) uid = int(r0) return } +var libc_getuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_getuid getuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + r0, _, _ := syscall_syscall(libc_issetugid_trampoline_addr, 0, 0, 0) tainted = bool(r0 != 0) return } +var libc_issetugid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_issetugid issetugid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_kill_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kill kill "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + r0, _, e1 := syscall_syscall(libc_kqueue_trampoline_addr, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -898,6 +1202,10 @@ func Kqueue() (fd int, err error) { return } +var libc_kqueue_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_kqueue kqueue "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { @@ -906,13 +1214,17 @@ func Lchown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall_syscall(libc_lchown_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_lchown_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lchown lchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { @@ -926,13 +1238,17 @@ func Link(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_link_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_link_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_link link "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err error) { @@ -946,23 +1262,31 @@ func Linkat(pathfd int, path string, linkfd int, link string, flags int) (err er if err != nil { return } - _, _, e1 := Syscall6(SYS_LINKAT, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) + _, _, e1 := syscall_syscall6(libc_linkat_trampoline_addr, uintptr(pathfd), uintptr(unsafe.Pointer(_p0)), uintptr(linkfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_linkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_linkat linkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + _, _, e1 := syscall_syscall(libc_listen_trampoline_addr, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_listen_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_listen listen "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { @@ -971,13 +1295,17 @@ func Lstat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_lstat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_lstat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lstat lstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { @@ -986,13 +1314,17 @@ func Mkdir(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_mkdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkdir mkdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { @@ -1001,13 +1333,17 @@ func Mkdirat(dirfd int, path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + _, _, e1 := syscall_syscall(libc_mkdirat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkdirat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkdirat mkdirat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { @@ -1016,13 +1352,17 @@ func Mkfifo(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall_syscall(libc_mkfifo_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkfifo_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifoat(dirfd int, path string, mode uint32) (err error) { @@ -1031,13 +1371,17 @@ func Mkfifoat(dirfd int, path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKFIFOAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) + _, _, e1 := syscall_syscall(libc_mkfifoat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mkfifoat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mkfifoat mkfifoat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { @@ -1046,13 +1390,17 @@ func Mknod(path string, mode uint32, dev int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + _, _, e1 := syscall_syscall(libc_mknod_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mknod_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mknod mknod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { @@ -1061,23 +1409,31 @@ func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + _, _, e1 := syscall_syscall6(libc_mknodat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_mknodat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mknodat mknodat "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(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + _, _, e1 := syscall_syscall(libc_nanosleep_trampoline_addr, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_nanosleep_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { @@ -1086,7 +1442,7 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + r0, _, e1 := syscall_syscall(libc_open_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1094,6 +1450,10 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { return } +var libc_open_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_open open "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { @@ -1102,7 +1462,7 @@ func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) + r0, _, e1 := syscall_syscall6(libc_openat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1110,6 +1470,10 @@ func Openat(dirfd int, path string, mode int, perm uint32) (fd int, err error) { return } +var libc_openat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_openat openat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { @@ -1118,7 +1482,7 @@ func Pathconf(path string, name int) (val int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + r0, _, e1 := syscall_syscall(libc_pathconf_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1126,6 +1490,10 @@ func Pathconf(path string, name int) (val int, err error) { return } +var libc_pathconf_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pathconf pathconf "libc.so" + // 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) { @@ -1135,7 +1503,7 @@ func pread(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + r0, _, e1 := syscall_syscall6(libc_pread_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1143,6 +1511,10 @@ func pread(fd int, p []byte, offset int64) (n int, err error) { return } +var libc_pread_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pread pread "libc.so" + // 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) { @@ -1152,7 +1524,7 @@ func pwrite(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + r0, _, e1 := syscall_syscall6(libc_pwrite_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1160,6 +1532,10 @@ func pwrite(fd int, p []byte, offset int64) (n int, err error) { return } +var libc_pwrite_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_pwrite pwrite "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { @@ -1169,7 +1545,7 @@ func read(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1177,6 +1553,10 @@ func read(fd int, p []byte) (n int, err error) { return } +var libc_read_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_read read "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { @@ -1191,7 +1571,7 @@ func Readlink(path string, buf []byte) (n int, err error) { } else { _p1 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + r0, _, e1 := syscall_syscall(libc_readlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1199,6 +1579,10 @@ func Readlink(path string, buf []byte) (n int, err error) { return } +var libc_readlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readlink readlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { @@ -1213,7 +1597,7 @@ func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { } else { _p1 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) + r0, _, e1 := syscall_syscall6(libc_readlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1221,6 +1605,10 @@ func Readlinkat(dirfd int, path string, buf []byte) (n int, err error) { return } +var libc_readlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_readlinkat readlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { @@ -1234,13 +1622,17 @@ func Rename(from string, to string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_rename_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_rename_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_rename rename "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(fromfd int, from string, tofd int, to string) (err error) { @@ -1254,13 +1646,17 @@ func Renameat(fromfd int, from string, tofd int, to string) (err error) { if err != nil { return } - _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) + _, _, e1 := syscall_syscall6(libc_renameat_trampoline_addr, uintptr(fromfd), uintptr(unsafe.Pointer(_p0)), uintptr(tofd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_renameat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_renameat renameat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { @@ -1269,13 +1665,17 @@ func Revoke(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_revoke_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_revoke_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_revoke revoke "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { @@ -1284,17 +1684,21 @@ func Rmdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_rmdir_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_rmdir_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_rmdir rmdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) + r0, _, e1 := syscall_syscall(libc_lseek_trampoline_addr, uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) @@ -1302,10 +1706,14 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { return } +var libc_lseek_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_lseek lseek "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + r0, _, e1 := syscall_syscall6(libc_select_trampoline_addr, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1313,36 +1721,52 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err return } +var libc_select_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_select select "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setegid_trampoline_addr, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setegid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setegid setegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_seteuid_trampoline_addr, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_seteuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_seteuid seteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setgid_trampoline_addr, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setgid setgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { @@ -1351,97 +1775,133 @@ func Setlogin(name string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_setlogin_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setlogin_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setlogin setlogin "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + _, _, e1 := syscall_rawSyscall(libc_setpgid_trampoline_addr, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setpgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setpgid setpgid "libc.so" + // 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(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + _, _, e1 := syscall_syscall(libc_setpriority_trampoline_addr, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setpriority_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setpriority setpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + _, _, e1 := syscall_rawSyscall(libc_setregid_trampoline_addr, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setregid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setregid setregid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + _, _, e1 := syscall_rawSyscall(libc_setreuid_trampoline_addr, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setreuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setreuid setreuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresgid(rgid int, egid int, sgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESGID, uintptr(rgid), uintptr(egid), uintptr(sgid)) + _, _, e1 := syscall_rawSyscall(libc_setresgid_trampoline_addr, uintptr(rgid), uintptr(egid), uintptr(sgid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setresgid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setresgid setresgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setresuid(ruid int, euid int, suid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRESUID, uintptr(ruid), uintptr(euid), uintptr(suid)) + _, _, e1 := syscall_rawSyscall(libc_setresuid_trampoline_addr, uintptr(ruid), uintptr(euid), uintptr(suid)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setresuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setresuid setresuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := syscall_rawSyscall(libc_setrlimit_trampoline_addr, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setrlimit_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setrlimit setrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrtable(rtable int) (err error) { - _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setrtable_trampoline_addr, uintptr(rtable), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setrtable_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setrtable setrtable "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + r0, _, e1 := syscall_rawSyscall(libc_setsid_trampoline_addr, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1449,26 +1909,38 @@ func Setsid() (pid int, err error) { return } +var libc_setsid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setsid setsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_settimeofday_trampoline_addr, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_settimeofday_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_settimeofday settimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + _, _, e1 := syscall_rawSyscall(libc_setuid_trampoline_addr, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_setuid_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_setuid setuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { @@ -1477,13 +1949,17 @@ func Stat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_stat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_stat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_stat stat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { @@ -1492,13 +1968,17 @@ func Statfs(path string, stat *Statfs_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall_syscall(libc_statfs_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_statfs_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_statfs statfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { @@ -1512,13 +1992,17 @@ func Symlink(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall_syscall(libc_symlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_symlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_symlink symlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { @@ -1532,23 +2016,31 @@ func Symlinkat(oldpath string, newdirfd int, newpath string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) + _, _, e1 := syscall_syscall(libc_symlinkat_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) if e1 != 0 { err = errnoErr(e1) } return } +var libc_symlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_symlinkat symlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + _, _, e1 := syscall_syscall(libc_sync_trampoline_addr, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_sync_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_sync sync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { @@ -1557,21 +2049,29 @@ func Truncate(path string, length int64) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) + _, _, e1 := syscall_syscall(libc_truncate_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_truncate_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_truncate truncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + r0, _, _ := syscall_syscall(libc_umask_trampoline_addr, uintptr(newmask), 0, 0) oldmask = int(r0) return } +var libc_umask_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_umask umask "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { @@ -1580,13 +2080,17 @@ func Unlink(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall_syscall(libc_unlink_trampoline_addr, uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unlink_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unlink unlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlinkat(dirfd int, path string, flags int) (err error) { @@ -1595,13 +2099,17 @@ func Unlinkat(dirfd int, path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + _, _, e1 := syscall_syscall(libc_unlinkat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unlinkat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { @@ -1610,13 +2118,17 @@ func Unmount(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall_syscall(libc_unmount_trampoline_addr, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_unmount_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_unmount unmount "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { @@ -1626,7 +2138,7 @@ func write(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1634,10 +2146,14 @@ func write(fd int, p []byte) (n int, err error) { return } +var libc_write_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_write write "libc.so" + // 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 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) + r0, _, e1 := syscall_syscall6(libc_mmap_trampoline_addr, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) @@ -1645,20 +2161,28 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( return } +var libc_mmap_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_mmap mmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + _, _, e1 := syscall_syscall(libc_munmap_trampoline_addr, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +var libc_munmap_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_munmap munmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1669,7 +2193,7 @@ func readlen(fd int, buf *byte, nbuf int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1685,9 +2209,13 @@ func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error if err != nil { return } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) + _, _, e1 := syscall_syscall6(libc_utimensat_trampoline_addr, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } + +var libc_utimensat_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_utimensat utimensat "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 new file mode 100644 index 00000000..4efeff9a --- /dev/null +++ b/tools/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s @@ -0,0 +1,796 @@ +// go run mkasm.go openbsd arm64 +// Code generated by the command above; DO NOT EDIT. + +#include "textflag.h" + +TEXT libc_getgroups_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getgroups(SB) + +GLOBL ·libc_getgroups_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getgroups_trampoline_addr(SB)/8, $libc_getgroups_trampoline<>(SB) + +TEXT libc_setgroups_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setgroups(SB) + +GLOBL ·libc_setgroups_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setgroups_trampoline_addr(SB)/8, $libc_setgroups_trampoline<>(SB) + +TEXT libc_wait4_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_wait4(SB) + +GLOBL ·libc_wait4_trampoline_addr(SB), RODATA, $8 +DATA ·libc_wait4_trampoline_addr(SB)/8, $libc_wait4_trampoline<>(SB) + +TEXT libc_accept_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_accept(SB) + +GLOBL ·libc_accept_trampoline_addr(SB), RODATA, $8 +DATA ·libc_accept_trampoline_addr(SB)/8, $libc_accept_trampoline<>(SB) + +TEXT libc_bind_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_bind(SB) + +GLOBL ·libc_bind_trampoline_addr(SB), RODATA, $8 +DATA ·libc_bind_trampoline_addr(SB)/8, $libc_bind_trampoline<>(SB) + +TEXT libc_connect_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_connect(SB) + +GLOBL ·libc_connect_trampoline_addr(SB), RODATA, $8 +DATA ·libc_connect_trampoline_addr(SB)/8, $libc_connect_trampoline<>(SB) + +TEXT libc_socket_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_socket(SB) + +GLOBL ·libc_socket_trampoline_addr(SB), RODATA, $8 +DATA ·libc_socket_trampoline_addr(SB)/8, $libc_socket_trampoline<>(SB) + +TEXT libc_getsockopt_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsockopt(SB) + +GLOBL ·libc_getsockopt_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getsockopt_trampoline_addr(SB)/8, $libc_getsockopt_trampoline<>(SB) + +TEXT libc_setsockopt_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setsockopt(SB) + +GLOBL ·libc_setsockopt_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setsockopt_trampoline_addr(SB)/8, $libc_setsockopt_trampoline<>(SB) + +TEXT libc_getpeername_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpeername(SB) + +GLOBL ·libc_getpeername_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpeername_trampoline_addr(SB)/8, $libc_getpeername_trampoline<>(SB) + +TEXT libc_getsockname_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsockname(SB) + +GLOBL ·libc_getsockname_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getsockname_trampoline_addr(SB)/8, $libc_getsockname_trampoline<>(SB) + +TEXT libc_shutdown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_shutdown(SB) + +GLOBL ·libc_shutdown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_shutdown_trampoline_addr(SB)/8, $libc_shutdown_trampoline<>(SB) + +TEXT libc_socketpair_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_socketpair(SB) + +GLOBL ·libc_socketpair_trampoline_addr(SB), RODATA, $8 +DATA ·libc_socketpair_trampoline_addr(SB)/8, $libc_socketpair_trampoline<>(SB) + +TEXT libc_recvfrom_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_recvfrom(SB) + +GLOBL ·libc_recvfrom_trampoline_addr(SB), RODATA, $8 +DATA ·libc_recvfrom_trampoline_addr(SB)/8, $libc_recvfrom_trampoline<>(SB) + +TEXT libc_sendto_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sendto(SB) + +GLOBL ·libc_sendto_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sendto_trampoline_addr(SB)/8, $libc_sendto_trampoline<>(SB) + +TEXT libc_recvmsg_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_recvmsg(SB) + +GLOBL ·libc_recvmsg_trampoline_addr(SB), RODATA, $8 +DATA ·libc_recvmsg_trampoline_addr(SB)/8, $libc_recvmsg_trampoline<>(SB) + +TEXT libc_sendmsg_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sendmsg(SB) + +GLOBL ·libc_sendmsg_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sendmsg_trampoline_addr(SB)/8, $libc_sendmsg_trampoline<>(SB) + +TEXT libc_kevent_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kevent(SB) + +GLOBL ·libc_kevent_trampoline_addr(SB), RODATA, $8 +DATA ·libc_kevent_trampoline_addr(SB)/8, $libc_kevent_trampoline<>(SB) + +TEXT libc_utimes_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_utimes(SB) + +GLOBL ·libc_utimes_trampoline_addr(SB), RODATA, $8 +DATA ·libc_utimes_trampoline_addr(SB)/8, $libc_utimes_trampoline<>(SB) + +TEXT libc_futimes_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_futimes(SB) + +GLOBL ·libc_futimes_trampoline_addr(SB), RODATA, $8 +DATA ·libc_futimes_trampoline_addr(SB)/8, $libc_futimes_trampoline<>(SB) + +TEXT libc_poll_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_poll(SB) + +GLOBL ·libc_poll_trampoline_addr(SB), RODATA, $8 +DATA ·libc_poll_trampoline_addr(SB)/8, $libc_poll_trampoline<>(SB) + +TEXT libc_madvise_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_madvise(SB) + +GLOBL ·libc_madvise_trampoline_addr(SB), RODATA, $8 +DATA ·libc_madvise_trampoline_addr(SB)/8, $libc_madvise_trampoline<>(SB) + +TEXT libc_mlock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mlock(SB) + +GLOBL ·libc_mlock_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mlock_trampoline_addr(SB)/8, $libc_mlock_trampoline<>(SB) + +TEXT libc_mlockall_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mlockall(SB) + +GLOBL ·libc_mlockall_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mlockall_trampoline_addr(SB)/8, $libc_mlockall_trampoline<>(SB) + +TEXT libc_mprotect_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mprotect(SB) + +GLOBL ·libc_mprotect_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mprotect_trampoline_addr(SB)/8, $libc_mprotect_trampoline<>(SB) + +TEXT libc_msync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_msync(SB) + +GLOBL ·libc_msync_trampoline_addr(SB), RODATA, $8 +DATA ·libc_msync_trampoline_addr(SB)/8, $libc_msync_trampoline<>(SB) + +TEXT libc_munlock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munlock(SB) + +GLOBL ·libc_munlock_trampoline_addr(SB), RODATA, $8 +DATA ·libc_munlock_trampoline_addr(SB)/8, $libc_munlock_trampoline<>(SB) + +TEXT libc_munlockall_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munlockall(SB) + +GLOBL ·libc_munlockall_trampoline_addr(SB), RODATA, $8 +DATA ·libc_munlockall_trampoline_addr(SB)/8, $libc_munlockall_trampoline<>(SB) + +TEXT libc_pipe2_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pipe2(SB) + +GLOBL ·libc_pipe2_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pipe2_trampoline_addr(SB)/8, $libc_pipe2_trampoline<>(SB) + +TEXT libc_getdents_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getdents(SB) + +GLOBL ·libc_getdents_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getdents_trampoline_addr(SB)/8, $libc_getdents_trampoline<>(SB) + +TEXT libc_getcwd_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getcwd(SB) + +GLOBL ·libc_getcwd_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getcwd_trampoline_addr(SB)/8, $libc_getcwd_trampoline<>(SB) + +TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ioctl(SB) + +GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 +DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_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_ppoll_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ppoll(SB) + +GLOBL ·libc_ppoll_trampoline_addr(SB), RODATA, $8 +DATA ·libc_ppoll_trampoline_addr(SB)/8, $libc_ppoll_trampoline<>(SB) + +TEXT libc_access_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_access(SB) + +GLOBL ·libc_access_trampoline_addr(SB), RODATA, $8 +DATA ·libc_access_trampoline_addr(SB)/8, $libc_access_trampoline<>(SB) + +TEXT libc_adjtime_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_adjtime(SB) + +GLOBL ·libc_adjtime_trampoline_addr(SB), RODATA, $8 +DATA ·libc_adjtime_trampoline_addr(SB)/8, $libc_adjtime_trampoline<>(SB) + +TEXT libc_chdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chdir(SB) + +GLOBL ·libc_chdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chdir_trampoline_addr(SB)/8, $libc_chdir_trampoline<>(SB) + +TEXT libc_chflags_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chflags(SB) + +GLOBL ·libc_chflags_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chflags_trampoline_addr(SB)/8, $libc_chflags_trampoline<>(SB) + +TEXT libc_chmod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chmod(SB) + +GLOBL ·libc_chmod_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chmod_trampoline_addr(SB)/8, $libc_chmod_trampoline<>(SB) + +TEXT libc_chown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chown(SB) + +GLOBL ·libc_chown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chown_trampoline_addr(SB)/8, $libc_chown_trampoline<>(SB) + +TEXT libc_chroot_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_chroot(SB) + +GLOBL ·libc_chroot_trampoline_addr(SB), RODATA, $8 +DATA ·libc_chroot_trampoline_addr(SB)/8, $libc_chroot_trampoline<>(SB) + +TEXT libc_close_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_close(SB) + +GLOBL ·libc_close_trampoline_addr(SB), RODATA, $8 +DATA ·libc_close_trampoline_addr(SB)/8, $libc_close_trampoline<>(SB) + +TEXT libc_dup_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup(SB) + +GLOBL ·libc_dup_trampoline_addr(SB), RODATA, $8 +DATA ·libc_dup_trampoline_addr(SB)/8, $libc_dup_trampoline<>(SB) + +TEXT libc_dup2_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup2(SB) + +GLOBL ·libc_dup2_trampoline_addr(SB), RODATA, $8 +DATA ·libc_dup2_trampoline_addr(SB)/8, $libc_dup2_trampoline<>(SB) + +TEXT libc_dup3_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_dup3(SB) + +GLOBL ·libc_dup3_trampoline_addr(SB), RODATA, $8 +DATA ·libc_dup3_trampoline_addr(SB)/8, $libc_dup3_trampoline<>(SB) + +TEXT libc_exit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_exit(SB) + +GLOBL ·libc_exit_trampoline_addr(SB), RODATA, $8 +DATA ·libc_exit_trampoline_addr(SB)/8, $libc_exit_trampoline<>(SB) + +TEXT libc_faccessat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_faccessat(SB) + +GLOBL ·libc_faccessat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_faccessat_trampoline_addr(SB)/8, $libc_faccessat_trampoline<>(SB) + +TEXT libc_fchdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchdir(SB) + +GLOBL ·libc_fchdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchdir_trampoline_addr(SB)/8, $libc_fchdir_trampoline<>(SB) + +TEXT libc_fchflags_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchflags(SB) + +GLOBL ·libc_fchflags_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchflags_trampoline_addr(SB)/8, $libc_fchflags_trampoline<>(SB) + +TEXT libc_fchmod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchmod(SB) + +GLOBL ·libc_fchmod_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchmod_trampoline_addr(SB)/8, $libc_fchmod_trampoline<>(SB) + +TEXT libc_fchmodat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchmodat(SB) + +GLOBL ·libc_fchmodat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchmodat_trampoline_addr(SB)/8, $libc_fchmodat_trampoline<>(SB) + +TEXT libc_fchown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchown(SB) + +GLOBL ·libc_fchown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchown_trampoline_addr(SB)/8, $libc_fchown_trampoline<>(SB) + +TEXT libc_fchownat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fchownat(SB) + +GLOBL ·libc_fchownat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fchownat_trampoline_addr(SB)/8, $libc_fchownat_trampoline<>(SB) + +TEXT libc_flock_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_flock(SB) + +GLOBL ·libc_flock_trampoline_addr(SB), RODATA, $8 +DATA ·libc_flock_trampoline_addr(SB)/8, $libc_flock_trampoline<>(SB) + +TEXT libc_fpathconf_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fpathconf(SB) + +GLOBL ·libc_fpathconf_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fpathconf_trampoline_addr(SB)/8, $libc_fpathconf_trampoline<>(SB) + +TEXT libc_fstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstat(SB) + +GLOBL ·libc_fstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fstat_trampoline_addr(SB)/8, $libc_fstat_trampoline<>(SB) + +TEXT libc_fstatat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstatat(SB) + +GLOBL ·libc_fstatat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fstatat_trampoline_addr(SB)/8, $libc_fstatat_trampoline<>(SB) + +TEXT libc_fstatfs_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fstatfs(SB) + +GLOBL ·libc_fstatfs_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fstatfs_trampoline_addr(SB)/8, $libc_fstatfs_trampoline<>(SB) + +TEXT libc_fsync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_fsync(SB) + +GLOBL ·libc_fsync_trampoline_addr(SB), RODATA, $8 +DATA ·libc_fsync_trampoline_addr(SB)/8, $libc_fsync_trampoline<>(SB) + +TEXT libc_ftruncate_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_ftruncate(SB) + +GLOBL ·libc_ftruncate_trampoline_addr(SB), RODATA, $8 +DATA ·libc_ftruncate_trampoline_addr(SB)/8, $libc_ftruncate_trampoline<>(SB) + +TEXT libc_getegid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getegid(SB) + +GLOBL ·libc_getegid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getegid_trampoline_addr(SB)/8, $libc_getegid_trampoline<>(SB) + +TEXT libc_geteuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_geteuid(SB) + +GLOBL ·libc_geteuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_geteuid_trampoline_addr(SB)/8, $libc_geteuid_trampoline<>(SB) + +TEXT libc_getgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getgid(SB) + +GLOBL ·libc_getgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getgid_trampoline_addr(SB)/8, $libc_getgid_trampoline<>(SB) + +TEXT libc_getpgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpgid(SB) + +GLOBL ·libc_getpgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpgid_trampoline_addr(SB)/8, $libc_getpgid_trampoline<>(SB) + +TEXT libc_getpgrp_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpgrp(SB) + +GLOBL ·libc_getpgrp_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpgrp_trampoline_addr(SB)/8, $libc_getpgrp_trampoline<>(SB) + +TEXT libc_getpid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpid(SB) + +GLOBL ·libc_getpid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpid_trampoline_addr(SB)/8, $libc_getpid_trampoline<>(SB) + +TEXT libc_getppid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getppid(SB) + +GLOBL ·libc_getppid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getppid_trampoline_addr(SB)/8, $libc_getppid_trampoline<>(SB) + +TEXT libc_getpriority_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getpriority(SB) + +GLOBL ·libc_getpriority_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getpriority_trampoline_addr(SB)/8, $libc_getpriority_trampoline<>(SB) + +TEXT libc_getrlimit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrlimit(SB) + +GLOBL ·libc_getrlimit_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getrlimit_trampoline_addr(SB)/8, $libc_getrlimit_trampoline<>(SB) + +TEXT libc_getrtable_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrtable(SB) + +GLOBL ·libc_getrtable_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getrtable_trampoline_addr(SB)/8, $libc_getrtable_trampoline<>(SB) + +TEXT libc_getrusage_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getrusage(SB) + +GLOBL ·libc_getrusage_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getrusage_trampoline_addr(SB)/8, $libc_getrusage_trampoline<>(SB) + +TEXT libc_getsid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getsid(SB) + +GLOBL ·libc_getsid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getsid_trampoline_addr(SB)/8, $libc_getsid_trampoline<>(SB) + +TEXT libc_gettimeofday_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_gettimeofday(SB) + +GLOBL ·libc_gettimeofday_trampoline_addr(SB), RODATA, $8 +DATA ·libc_gettimeofday_trampoline_addr(SB)/8, $libc_gettimeofday_trampoline<>(SB) + +TEXT libc_getuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_getuid(SB) + +GLOBL ·libc_getuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_getuid_trampoline_addr(SB)/8, $libc_getuid_trampoline<>(SB) + +TEXT libc_issetugid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_issetugid(SB) + +GLOBL ·libc_issetugid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_issetugid_trampoline_addr(SB)/8, $libc_issetugid_trampoline<>(SB) + +TEXT libc_kill_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kill(SB) + +GLOBL ·libc_kill_trampoline_addr(SB), RODATA, $8 +DATA ·libc_kill_trampoline_addr(SB)/8, $libc_kill_trampoline<>(SB) + +TEXT libc_kqueue_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_kqueue(SB) + +GLOBL ·libc_kqueue_trampoline_addr(SB), RODATA, $8 +DATA ·libc_kqueue_trampoline_addr(SB)/8, $libc_kqueue_trampoline<>(SB) + +TEXT libc_lchown_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lchown(SB) + +GLOBL ·libc_lchown_trampoline_addr(SB), RODATA, $8 +DATA ·libc_lchown_trampoline_addr(SB)/8, $libc_lchown_trampoline<>(SB) + +TEXT libc_link_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_link(SB) + +GLOBL ·libc_link_trampoline_addr(SB), RODATA, $8 +DATA ·libc_link_trampoline_addr(SB)/8, $libc_link_trampoline<>(SB) + +TEXT libc_linkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_linkat(SB) + +GLOBL ·libc_linkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_linkat_trampoline_addr(SB)/8, $libc_linkat_trampoline<>(SB) + +TEXT libc_listen_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_listen(SB) + +GLOBL ·libc_listen_trampoline_addr(SB), RODATA, $8 +DATA ·libc_listen_trampoline_addr(SB)/8, $libc_listen_trampoline<>(SB) + +TEXT libc_lstat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lstat(SB) + +GLOBL ·libc_lstat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_lstat_trampoline_addr(SB)/8, $libc_lstat_trampoline<>(SB) + +TEXT libc_mkdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkdir(SB) + +GLOBL ·libc_mkdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkdir_trampoline_addr(SB)/8, $libc_mkdir_trampoline<>(SB) + +TEXT libc_mkdirat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkdirat(SB) + +GLOBL ·libc_mkdirat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkdirat_trampoline_addr(SB)/8, $libc_mkdirat_trampoline<>(SB) + +TEXT libc_mkfifo_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkfifo(SB) + +GLOBL ·libc_mkfifo_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkfifo_trampoline_addr(SB)/8, $libc_mkfifo_trampoline<>(SB) + +TEXT libc_mkfifoat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mkfifoat(SB) + +GLOBL ·libc_mkfifoat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mkfifoat_trampoline_addr(SB)/8, $libc_mkfifoat_trampoline<>(SB) + +TEXT libc_mknod_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mknod(SB) + +GLOBL ·libc_mknod_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mknod_trampoline_addr(SB)/8, $libc_mknod_trampoline<>(SB) + +TEXT libc_mknodat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mknodat(SB) + +GLOBL ·libc_mknodat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mknodat_trampoline_addr(SB)/8, $libc_mknodat_trampoline<>(SB) + +TEXT libc_nanosleep_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_nanosleep(SB) + +GLOBL ·libc_nanosleep_trampoline_addr(SB), RODATA, $8 +DATA ·libc_nanosleep_trampoline_addr(SB)/8, $libc_nanosleep_trampoline<>(SB) + +TEXT libc_open_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_open(SB) + +GLOBL ·libc_open_trampoline_addr(SB), RODATA, $8 +DATA ·libc_open_trampoline_addr(SB)/8, $libc_open_trampoline<>(SB) + +TEXT libc_openat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_openat(SB) + +GLOBL ·libc_openat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_openat_trampoline_addr(SB)/8, $libc_openat_trampoline<>(SB) + +TEXT libc_pathconf_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pathconf(SB) + +GLOBL ·libc_pathconf_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pathconf_trampoline_addr(SB)/8, $libc_pathconf_trampoline<>(SB) + +TEXT libc_pread_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pread(SB) + +GLOBL ·libc_pread_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pread_trampoline_addr(SB)/8, $libc_pread_trampoline<>(SB) + +TEXT libc_pwrite_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_pwrite(SB) + +GLOBL ·libc_pwrite_trampoline_addr(SB), RODATA, $8 +DATA ·libc_pwrite_trampoline_addr(SB)/8, $libc_pwrite_trampoline<>(SB) + +TEXT libc_read_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_read(SB) + +GLOBL ·libc_read_trampoline_addr(SB), RODATA, $8 +DATA ·libc_read_trampoline_addr(SB)/8, $libc_read_trampoline<>(SB) + +TEXT libc_readlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readlink(SB) + +GLOBL ·libc_readlink_trampoline_addr(SB), RODATA, $8 +DATA ·libc_readlink_trampoline_addr(SB)/8, $libc_readlink_trampoline<>(SB) + +TEXT libc_readlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_readlinkat(SB) + +GLOBL ·libc_readlinkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_readlinkat_trampoline_addr(SB)/8, $libc_readlinkat_trampoline<>(SB) + +TEXT libc_rename_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_rename(SB) + +GLOBL ·libc_rename_trampoline_addr(SB), RODATA, $8 +DATA ·libc_rename_trampoline_addr(SB)/8, $libc_rename_trampoline<>(SB) + +TEXT libc_renameat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_renameat(SB) + +GLOBL ·libc_renameat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_renameat_trampoline_addr(SB)/8, $libc_renameat_trampoline<>(SB) + +TEXT libc_revoke_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_revoke(SB) + +GLOBL ·libc_revoke_trampoline_addr(SB), RODATA, $8 +DATA ·libc_revoke_trampoline_addr(SB)/8, $libc_revoke_trampoline<>(SB) + +TEXT libc_rmdir_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_rmdir(SB) + +GLOBL ·libc_rmdir_trampoline_addr(SB), RODATA, $8 +DATA ·libc_rmdir_trampoline_addr(SB)/8, $libc_rmdir_trampoline<>(SB) + +TEXT libc_lseek_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_lseek(SB) + +GLOBL ·libc_lseek_trampoline_addr(SB), RODATA, $8 +DATA ·libc_lseek_trampoline_addr(SB)/8, $libc_lseek_trampoline<>(SB) + +TEXT libc_select_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_select(SB) + +GLOBL ·libc_select_trampoline_addr(SB), RODATA, $8 +DATA ·libc_select_trampoline_addr(SB)/8, $libc_select_trampoline<>(SB) + +TEXT libc_setegid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setegid(SB) + +GLOBL ·libc_setegid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setegid_trampoline_addr(SB)/8, $libc_setegid_trampoline<>(SB) + +TEXT libc_seteuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_seteuid(SB) + +GLOBL ·libc_seteuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_seteuid_trampoline_addr(SB)/8, $libc_seteuid_trampoline<>(SB) + +TEXT libc_setgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setgid(SB) + +GLOBL ·libc_setgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setgid_trampoline_addr(SB)/8, $libc_setgid_trampoline<>(SB) + +TEXT libc_setlogin_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setlogin(SB) + +GLOBL ·libc_setlogin_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setlogin_trampoline_addr(SB)/8, $libc_setlogin_trampoline<>(SB) + +TEXT libc_setpgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setpgid(SB) + +GLOBL ·libc_setpgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setpgid_trampoline_addr(SB)/8, $libc_setpgid_trampoline<>(SB) + +TEXT libc_setpriority_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setpriority(SB) + +GLOBL ·libc_setpriority_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setpriority_trampoline_addr(SB)/8, $libc_setpriority_trampoline<>(SB) + +TEXT libc_setregid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setregid(SB) + +GLOBL ·libc_setregid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setregid_trampoline_addr(SB)/8, $libc_setregid_trampoline<>(SB) + +TEXT libc_setreuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setreuid(SB) + +GLOBL ·libc_setreuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setreuid_trampoline_addr(SB)/8, $libc_setreuid_trampoline<>(SB) + +TEXT libc_setresgid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setresgid(SB) + +GLOBL ·libc_setresgid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setresgid_trampoline_addr(SB)/8, $libc_setresgid_trampoline<>(SB) + +TEXT libc_setresuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setresuid(SB) + +GLOBL ·libc_setresuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setresuid_trampoline_addr(SB)/8, $libc_setresuid_trampoline<>(SB) + +TEXT libc_setrlimit_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setrlimit(SB) + +GLOBL ·libc_setrlimit_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setrlimit_trampoline_addr(SB)/8, $libc_setrlimit_trampoline<>(SB) + +TEXT libc_setrtable_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setrtable(SB) + +GLOBL ·libc_setrtable_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setrtable_trampoline_addr(SB)/8, $libc_setrtable_trampoline<>(SB) + +TEXT libc_setsid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setsid(SB) + +GLOBL ·libc_setsid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setsid_trampoline_addr(SB)/8, $libc_setsid_trampoline<>(SB) + +TEXT libc_settimeofday_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_settimeofday(SB) + +GLOBL ·libc_settimeofday_trampoline_addr(SB), RODATA, $8 +DATA ·libc_settimeofday_trampoline_addr(SB)/8, $libc_settimeofday_trampoline<>(SB) + +TEXT libc_setuid_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_setuid(SB) + +GLOBL ·libc_setuid_trampoline_addr(SB), RODATA, $8 +DATA ·libc_setuid_trampoline_addr(SB)/8, $libc_setuid_trampoline<>(SB) + +TEXT libc_stat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_stat(SB) + +GLOBL ·libc_stat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_stat_trampoline_addr(SB)/8, $libc_stat_trampoline<>(SB) + +TEXT libc_statfs_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_statfs(SB) + +GLOBL ·libc_statfs_trampoline_addr(SB), RODATA, $8 +DATA ·libc_statfs_trampoline_addr(SB)/8, $libc_statfs_trampoline<>(SB) + +TEXT libc_symlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_symlink(SB) + +GLOBL ·libc_symlink_trampoline_addr(SB), RODATA, $8 +DATA ·libc_symlink_trampoline_addr(SB)/8, $libc_symlink_trampoline<>(SB) + +TEXT libc_symlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_symlinkat(SB) + +GLOBL ·libc_symlinkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_symlinkat_trampoline_addr(SB)/8, $libc_symlinkat_trampoline<>(SB) + +TEXT libc_sync_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sync(SB) + +GLOBL ·libc_sync_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sync_trampoline_addr(SB)/8, $libc_sync_trampoline<>(SB) + +TEXT libc_truncate_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_truncate(SB) + +GLOBL ·libc_truncate_trampoline_addr(SB), RODATA, $8 +DATA ·libc_truncate_trampoline_addr(SB)/8, $libc_truncate_trampoline<>(SB) + +TEXT libc_umask_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_umask(SB) + +GLOBL ·libc_umask_trampoline_addr(SB), RODATA, $8 +DATA ·libc_umask_trampoline_addr(SB)/8, $libc_umask_trampoline<>(SB) + +TEXT libc_unlink_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unlink(SB) + +GLOBL ·libc_unlink_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unlink_trampoline_addr(SB)/8, $libc_unlink_trampoline<>(SB) + +TEXT libc_unlinkat_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unlinkat(SB) + +GLOBL ·libc_unlinkat_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unlinkat_trampoline_addr(SB)/8, $libc_unlinkat_trampoline<>(SB) + +TEXT libc_unmount_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_unmount(SB) + +GLOBL ·libc_unmount_trampoline_addr(SB), RODATA, $8 +DATA ·libc_unmount_trampoline_addr(SB)/8, $libc_unmount_trampoline<>(SB) + +TEXT libc_write_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_write(SB) + +GLOBL ·libc_write_trampoline_addr(SB), RODATA, $8 +DATA ·libc_write_trampoline_addr(SB)/8, $libc_write_trampoline<>(SB) + +TEXT libc_mmap_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_mmap(SB) + +GLOBL ·libc_mmap_trampoline_addr(SB), RODATA, $8 +DATA ·libc_mmap_trampoline_addr(SB)/8, $libc_mmap_trampoline<>(SB) + +TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_munmap(SB) + +GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 +DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_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) 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 62192e1d..c9c4ad03 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include -m32 /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/386/include -m32 /tmp/386/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && linux 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 490aab5d..12ff3417 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include -m64 /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/amd64/include -m64 /tmp/amd64/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && linux 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 aca17b6f..c3fb5e77 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/arm/include /tmp/arm/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && linux 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 54b4dfa5..358c847a 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include -fsigned-char /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/arm64/include -fsigned-char /tmp/arm64/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && linux 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 44a764c9..81c4849b 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/loong64/include /tmp/loong64/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build loong64 && linux 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 65a99efc..202a57e9 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/mips/include /tmp/mips/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips && linux 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 841c8a66..1fbceb52 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/mips64/include /tmp/mips64/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && linux 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 e26a7c76..b4ffb7a2 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/mips64le/include /tmp/mips64le/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64le && linux 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 26447260..867985f9 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/mipsle/include /tmp/mipsle/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mipsle && linux 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 26aefc18..a8cce69e 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/ppc/include /tmp/ppc/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && linux 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 8d4cd9d9..d44c5b39 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/ppc64/include /tmp/ppc64/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && linux 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 3b405d1f..4214dd9c 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/ppc64le/include /tmp/ppc64le/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64le && linux 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 3a9c96b2..3e594a8c 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/riscv64/include /tmp/riscv64/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && linux 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 8ffa6646..7ea46520 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include -fsigned-char /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/s390x/include -fsigned-char /tmp/s390x/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build s390x && linux 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 6a39640e..92f628ef 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 @@ -1,4 +1,4 @@ -// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h +// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/sparc64/include /tmp/sparc64/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. //go:build sparc64 && linux 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 817edbf9..59773381 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 @@ -6,6 +6,7 @@ package unix +// Deprecated: Use libc wrappers instead of direct syscalls. const ( SYS_EXIT = 1 // { void sys_exit(int rval); } SYS_FORK = 2 // { int sys_fork(void); } 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 ea453614..16af2918 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 @@ -6,6 +6,7 @@ package unix +// Deprecated: Use libc wrappers instead of direct syscalls. const ( SYS_EXIT = 1 // { void sys_exit(int rval); } SYS_FORK = 2 // { int sys_fork(void); } 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 32eec5ed..721ef591 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 @@ -6,6 +6,7 @@ package unix +// Deprecated: Use libc wrappers instead of direct syscalls. const ( SYS_EXIT = 1 // { void sys_exit(int rval); } SYS_FORK = 2 // { int sys_fork(void); } 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 86984798..ff688116 100644 --- a/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -945,6 +945,9 @@ type PerfEventAttr struct { Aux_watermark uint32 Sample_max_stack uint16 _ uint16 + Aux_sample_size uint32 + _ uint32 + Sig_data uint64 } type PerfEventMmapPage struct { @@ -1463,6 +1466,11 @@ const ( IFLA_ALT_IFNAME = 0x35 IFLA_PERM_ADDRESS = 0x36 IFLA_PROTO_DOWN_REASON = 0x37 + IFLA_PARENT_DEV_NAME = 0x38 + IFLA_PARENT_DEV_BUS_NAME = 0x39 + IFLA_GRO_MAX_SIZE = 0x3a + IFLA_TSO_MAX_SIZE = 0x3b + IFLA_TSO_MAX_SEGS = 0x3c IFLA_PROTO_DOWN_REASON_UNSPEC = 0x0 IFLA_PROTO_DOWN_REASON_MASK = 0x1 IFLA_PROTO_DOWN_REASON_VALUE = 0x2 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 7551af48..26360440 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m32 linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/386/cgo -- -Wall -Werror -static -I/tmp/386/include -m32 linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && linux 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 3e738ac0..8187489d 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m64 linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/amd64/cgo -- -Wall -Werror -static -I/tmp/amd64/include -m64 linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build amd64 && linux 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 6183eef4..d1612335 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/arm/cgo -- -Wall -Werror -static -I/tmp/arm/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm && linux 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 968cecb1..c28e5556 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/arm64/cgo -- -Wall -Werror -static -I/tmp/arm64/include -fsigned-char linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build arm64 && linux 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 8fe4c522..187061f9 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/loong64/cgo -- -Wall -Werror -static -I/tmp/loong64/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build loong64 && linux 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 11426a30..36912991 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/mips/cgo -- -Wall -Werror -static -I/tmp/mips/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips && linux 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 ad1c3b3d..7473468d 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/mips64/cgo -- -Wall -Werror -static -I/tmp/mips64/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64 && linux 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 15fd84e4..ed944852 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/mips64le/cgo -- -Wall -Werror -static -I/tmp/mips64le/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mips64le && linux 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 49c49825..0892a73a 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/mipsle/cgo -- -Wall -Werror -static -I/tmp/mipsle/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build mipsle && linux 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 cd36d0da..e1dd4833 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/ppc/cgo -- -Wall -Werror -static -I/tmp/ppc/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && linux 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 8c6fce03..d9f654c7 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/ppc64/cgo -- -Wall -Werror -static -I/tmp/ppc64/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64 && linux 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 20910f2a..74acda9f 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/ppc64le/cgo -- -Wall -Werror -static -I/tmp/ppc64le/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc64le && linux 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 71b7b333..50ebe69e 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/riscv64/cgo -- -Wall -Werror -static -I/tmp/riscv64/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build riscv64 && linux 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 71184cc2..75b34c25 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/s390x/cgo -- -Wall -Werror -static -I/tmp/s390x/include -fsigned-char linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build s390x && linux 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 06156285..429c3bf7 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 @@ -1,4 +1,4 @@ -// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go +// cgo -godefs -objdir=/tmp/sparc64/cgo -- -Wall -Werror -static -I/tmp/sparc64/include linux/types.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build sparc64 && linux 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 be3ec2bd..e2791381 100644 --- a/tools/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/tools/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -417,6 +417,7 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb uint32) (err error) = psapi.GetModuleInformation //sys GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size uint32) (err error) = psapi.GetModuleFileNameExW //sys GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uint32) (err error) = psapi.GetModuleBaseNameW +//sys QueryWorkingSetEx(process Handle, pv uintptr, cb uint32) (err error) = psapi.QueryWorkingSetEx // NT Native APIs //sys rtlNtStatusToDosErrorNoTeb(ntstatus NTStatus) (ret syscall.Errno) = ntdll.RtlNtStatusToDosErrorNoTeb @@ -971,6 +972,32 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, int32, error) { return unsafe.Pointer(&sa.raw), sl, nil } +type RawSockaddrBth struct { + AddressFamily [2]byte + BtAddr [8]byte + ServiceClassId [16]byte + Port [4]byte +} + +type SockaddrBth struct { + BtAddr uint64 + ServiceClassId GUID + Port uint32 + + raw RawSockaddrBth +} + +func (sa *SockaddrBth) sockaddr() (unsafe.Pointer, int32, error) { + family := AF_BTH + sa.raw = RawSockaddrBth{ + AddressFamily: *(*[2]byte)(unsafe.Pointer(&family)), + BtAddr: *(*[8]byte)(unsafe.Pointer(&sa.BtAddr)), + Port: *(*[4]byte)(unsafe.Pointer(&sa.Port)), + ServiceClassId: *(*[16]byte)(unsafe.Pointer(&sa.ServiceClassId)), + } + return unsafe.Pointer(&sa.raw), int32(unsafe.Sizeof(sa.raw)), nil +} + func (rsa *RawSockaddrAny) Sockaddr() (Sockaddr, error) { switch rsa.Addr.Family { case AF_UNIX: @@ -1707,3 +1734,71 @@ func LoadResourceData(module, resInfo Handle) (data []byte, err error) { h.Cap = int(size) return } + +// PSAPI_WORKING_SET_EX_BLOCK contains extended working set information for a page. +type PSAPI_WORKING_SET_EX_BLOCK uint64 + +// Valid returns the validity of this page. +// If this bit is 1, the subsequent members are valid; otherwise they should be ignored. +func (b PSAPI_WORKING_SET_EX_BLOCK) Valid() bool { + return (b & 1) == 1 +} + +// ShareCount is the number of processes that share this page. The maximum value of this member is 7. +func (b PSAPI_WORKING_SET_EX_BLOCK) ShareCount() uint64 { + return b.intField(1, 3) +} + +// Win32Protection is the memory protection attributes of the page. For a list of values, see +// https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants +func (b PSAPI_WORKING_SET_EX_BLOCK) Win32Protection() uint64 { + return b.intField(4, 11) +} + +// Shared returns the shared status of this page. +// If this bit is 1, the page can be shared. +func (b PSAPI_WORKING_SET_EX_BLOCK) Shared() bool { + return (b & (1 << 15)) == 1 +} + +// Node is the NUMA node. The maximum value of this member is 63. +func (b PSAPI_WORKING_SET_EX_BLOCK) Node() uint64 { + return b.intField(16, 6) +} + +// Locked returns the locked status of this page. +// If this bit is 1, the virtual page is locked in physical memory. +func (b PSAPI_WORKING_SET_EX_BLOCK) Locked() bool { + return (b & (1 << 22)) == 1 +} + +// LargePage returns the large page status of this page. +// If this bit is 1, the page is a large page. +func (b PSAPI_WORKING_SET_EX_BLOCK) LargePage() bool { + return (b & (1 << 23)) == 1 +} + +// Bad returns the bad status of this page. +// If this bit is 1, the page is has been reported as bad. +func (b PSAPI_WORKING_SET_EX_BLOCK) Bad() bool { + return (b & (1 << 31)) == 1 +} + +// intField extracts an integer field in the PSAPI_WORKING_SET_EX_BLOCK union. +func (b PSAPI_WORKING_SET_EX_BLOCK) intField(start, length int) uint64 { + var mask PSAPI_WORKING_SET_EX_BLOCK + for pos := start; pos < start+length; pos++ { + mask |= (1 << pos) + } + + masked := b & mask + return uint64(masked >> start) +} + +// PSAPI_WORKING_SET_EX_INFORMATION contains extended working set information for a process. +type PSAPI_WORKING_SET_EX_INFORMATION struct { + // The virtual address. + VirtualAddress Pointer + // A PSAPI_WORKING_SET_EX_BLOCK union that indicates the attributes of the page at VirtualAddress. + VirtualAttributes PSAPI_WORKING_SET_EX_BLOCK +} 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 678262cd..52d4742c 100644 --- a/tools/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/tools/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -408,6 +408,7 @@ var ( procGetModuleBaseNameW = modpsapi.NewProc("GetModuleBaseNameW") procGetModuleFileNameExW = modpsapi.NewProc("GetModuleFileNameExW") procGetModuleInformation = modpsapi.NewProc("GetModuleInformation") + procQueryWorkingSetEx = modpsapi.NewProc("QueryWorkingSetEx") procSubscribeServiceChangeNotifications = modsechost.NewProc("SubscribeServiceChangeNotifications") procUnsubscribeServiceChangeNotifications = modsechost.NewProc("UnsubscribeServiceChangeNotifications") procGetUserNameExW = modsecur32.NewProc("GetUserNameExW") @@ -3504,6 +3505,14 @@ func GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb return } +func QueryWorkingSetEx(process Handle, pv uintptr, cb uint32) (err error) { + r1, _, e1 := syscall.Syscall(procQueryWorkingSetEx.Addr(), 3, uintptr(process), uintptr(pv), uintptr(cb)) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func SubscribeServiceChangeNotifications(service Handle, eventType uint32, callback uintptr, callbackCtx uintptr, subscription *uintptr) (ret error) { ret = procSubscribeServiceChangeNotifications.Find() if ret != nil { diff --git a/tools/vendor/golang.org/x/tools/AUTHORS b/tools/vendor/golang.org/x/tools/AUTHORS deleted file mode 100644 index 15167cd7..00000000 --- a/tools/vendor/golang.org/x/tools/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/tools/vendor/golang.org/x/tools/CONTRIBUTORS b/tools/vendor/golang.org/x/tools/CONTRIBUTORS deleted file mode 100644 index 1c4577e9..00000000 --- a/tools/vendor/golang.org/x/tools/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/tools/vendor/golang.org/x/tools/cmd/cover/cover.go b/tools/vendor/golang.org/x/tools/cmd/cover/cover.go index 42a7e37a..0c7db102 100644 --- a/tools/vendor/golang.org/x/tools/cmd/cover/cover.go +++ b/tools/vendor/golang.org/x/tools/cmd/cover/cover.go @@ -300,7 +300,6 @@ var slashslash = []byte("//") // whitespace and line comments. Any +build directives must appear // within this region. This approach is more reliable than using // go/printer to print a modified AST containing comments. -// func initialComments(content []byte) []byte { // Derived from go/build.Context.shouldBuild. end := 0 @@ -453,7 +452,7 @@ func (f *File) newCounter(start, end token.Pos, numStmt int) ast.Stmt { // S1 // if cond { // S2 -// } +// } // S3 // // counters will be added before S1 and before S3. The block containing S2 diff --git a/tools/vendor/golang.org/x/tools/cmd/cover/doc.go b/tools/vendor/golang.org/x/tools/cmd/cover/doc.go index f903d850..77dce442 100644 --- a/tools/vendor/golang.org/x/tools/cmd/cover/doc.go +++ b/tools/vendor/golang.org/x/tools/cmd/cover/doc.go @@ -18,6 +18,7 @@ For instance, it does not probe inside && and || expressions, and can be mildly confused by single statements with multiple function literals. For usage information, please see: + go help testflag go tool cover -help */ diff --git a/tools/vendor/golang.org/x/tools/cmd/goimports/doc.go b/tools/vendor/golang.org/x/tools/cmd/goimports/doc.go index 5a5b9005..18a3ad44 100644 --- a/tools/vendor/golang.org/x/tools/cmd/goimports/doc.go +++ b/tools/vendor/golang.org/x/tools/cmd/goimports/doc.go @@ -3,29 +3,33 @@ // license that can be found in the LICENSE file. /* - Command goimports updates your Go import lines, adding missing ones and removing unreferenced ones. - $ go install golang.org/x/tools/cmd/goimports@latest + $ go install golang.org/x/tools/cmd/goimports@latest In addition to fixing imports, goimports also formats your code in the same style as gofmt so it can be used as a replacement for your editor's gofmt-on-save hook. For emacs, make sure you have the latest go-mode.el: - https://github.com/dominikh/go-mode.el + + https://github.com/dominikh/go-mode.el + Then in your .emacs file: - (setq gofmt-command "goimports") - (add-hook 'before-save-hook 'gofmt-before-save) + + (setq gofmt-command "goimports") + (add-hook 'before-save-hook 'gofmt-before-save) For vim, set "gofmt_command" to "goimports": - https://golang.org/change/39c724dd7f252 - https://golang.org/wiki/IDEsAndTextEditorPlugins - etc + + https://golang.org/change/39c724dd7f252 + https://golang.org/wiki/IDEsAndTextEditorPlugins + etc For GoSublime, follow the steps described here: - http://michaelwhatcott.com/gosublime-goimports/ + + http://michaelwhatcott.com/gosublime-goimports/ For other editors, you probably know what to do. @@ -39,9 +43,8 @@ working and see what goimports is doing. File bugs or feature requests at: - https://golang.org/issues/new?title=x/tools/cmd/goimports:+ + https://golang.org/issues/new?title=x/tools/cmd/goimports:+ Happy hacking! - */ package main // import "golang.org/x/tools/cmd/goimports" diff --git a/tools/vendor/golang.org/x/tools/cmd/stringer/stringer.go b/tools/vendor/golang.org/x/tools/cmd/stringer/stringer.go index 558a234d..b079985b 100644 --- a/tools/vendor/golang.org/x/tools/cmd/stringer/stringer.go +++ b/tools/vendor/golang.org/x/tools/cmd/stringer/stringer.go @@ -5,7 +5,9 @@ // Stringer is a tool to automate the creation of methods that satisfy the fmt.Stringer // interface. Given the name of a (signed or unsigned) integer type T that has constants // defined, stringer will create a new self-contained Go source file implementing +// // func (t T) String() string +// // The file is created in the same package and directory as the package that defines T. // It has helpful defaults designed for use with go generate. // @@ -215,7 +217,7 @@ type Package struct { // parsePackage exits if there is an error. func (g *Generator) parsePackage(patterns []string, tags []string) { cfg := &packages.Config{ - Mode: packages.LoadSyntax, + Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax, // TODO: Need to think about constants in test files. Maybe write type_string_test.go // in a separate pass? For later. Tests: false, @@ -570,6 +572,7 @@ func (g *Generator) buildOneRun(runs [][]Value, typeName string) { } // Arguments to format are: +// // [1]: type name // [2]: size of index element (8 for uint8 etc.) // [3]: less than zero check (for signed types) 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 94a3bd5d..03c31525 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/doc.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/doc.go @@ -3,12 +3,10 @@ // license that can be found in the LICENSE file. /* - Package analysis defines the interface between a modular static analysis and an analysis driver program. - -Background +# Background A static analysis is a function that inspects a package of Go code and reports a set of diagnostics (typically mistakes in the code), and @@ -32,8 +30,7 @@ frameworks, code review tools, code-base indexers (such as SourceGraph), documentation viewers (such as godoc), batch pipelines for large code bases, and so on. - -Analyzer +# Analyzer The primary type in the API is Analyzer. An Analyzer statically describes an analysis function: its name, documentation, flags, @@ -115,8 +112,7 @@ Finally, the Run field contains a function to be called by the driver to execute the analysis on a single package. The driver passes it an instance of the Pass type. - -Pass +# Pass A Pass describes a single unit of work: the application of a particular Analyzer to a particular package of Go code. @@ -202,8 +198,7 @@ raw text file, use the following sequence: ... pass.Reportf(tf.LineStart(line), "oops") - -Modular analysis with Facts +# Modular analysis with Facts To improve efficiency and scalability, large programs are routinely built using separate compilation: units of the program are compiled @@ -246,6 +241,9 @@ Consequently, Facts must be serializable. The API requires that drivers use the gob encoding, an efficient, robust, self-describing binary protocol. A fact type may implement the GobEncoder/GobDecoder interfaces if the default encoding is unsuitable. Facts should be stateless. +Because serialized facts may appear within build outputs, the gob encoding +of a fact must be deterministic, to avoid spurious cache misses in +build systems that use content-addressable caches. The Pass type has functions to import and export facts, associated either with an object or with a package: @@ -280,8 +278,7 @@ this fact is built in to the analyzer so that it correctly checks calls to log.Printf even when run in a driver that does not apply it to standard packages. We would like to remove this limitation in future. - -Testing an Analyzer +# Testing an Analyzer The analysistest subpackage provides utilities for testing an Analyzer. In a few lines of code, it is possible to run an analyzer on a package @@ -289,8 +286,7 @@ of testdata files and check that it reported all the expected diagnostics and facts (and no more). Expectations are expressed using "// want ..." comments in the input code. - -Standalone commands +# Standalone commands Analyzers are provided in the form of packages that a driver program is expected to import. The vet command imports a set of several analyzers, @@ -316,6 +312,5 @@ entirety as: A tool that provides multiple analyzers can use multichecker in a similar way, giving it the list of Analyzers. - */ package analysis 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 new file mode 100644 index 00000000..d8211afd --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go118.go @@ -0,0 +1,12 @@ +// 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 new file mode 100644 index 00000000..3018383e --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/asmdecl/arches_go119.go @@ -0,0 +1,14 @@ +// 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 7b82d0b6..6fbfe7e1 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 @@ -90,8 +90,8 @@ var ( asmArchMipsLE = asmArch{name: "mipsle", bigEndian: false, stack: "R29", lr: true} asmArchMips64 = asmArch{name: "mips64", bigEndian: true, stack: "R29", lr: true} asmArchMips64LE = asmArch{name: "mips64le", bigEndian: false, stack: "R29", lr: true} - asmArchPpc64 = asmArch{name: "ppc64", bigEndian: true, stack: "R1", lr: true} - asmArchPpc64LE = asmArch{name: "ppc64le", bigEndian: false, stack: "R1", lr: true} + asmArchPpc64 = asmArch{name: "ppc64", bigEndian: true, stack: "R1", lr: true, retRegs: []string{"R3", "F1"}} + asmArchPpc64LE = asmArch{name: "ppc64le", bigEndian: false, stack: "R1", lr: true, retRegs: []string{"R3", "F1"}} asmArchRISCV64 = asmArch{name: "riscv64", bigEndian: false, stack: "SP", lr: true} asmArchS390X = asmArch{name: "s390x", bigEndian: true, stack: "R15", lr: true} asmArchWasm = asmArch{name: "wasm", bigEndian: false, stack: "SP", lr: false} @@ -114,6 +114,7 @@ var ( ) func init() { + arches = append(arches, additionalArches()...) for _, arch := range arches { arch.sizes = types.SizesFor("gc", arch.name) if arch.sizes == nil { @@ -731,7 +732,7 @@ func asmCheckVar(badf func(string, ...interface{}), fn *asmFunc, line, expr stri src = 8 } } - case "mips", "mipsle", "mips64", "mips64le": + case "loong64", "mips", "mipsle", "mips64", "mips64le": switch op { case "MOVB", "MOVBU": src = 1 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 5ae47d89..0d8b0bf4 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 @@ -94,8 +94,10 @@ func (op boolOp) commutativeSets(info *types.Info, e *ast.BinaryExpr, seen map[* } // checkRedundant checks for expressions of the form -// e && e -// e || e +// +// e && e +// e || e +// // Exprs must contain only side effect free expressions. func (op boolOp) checkRedundant(pass *analysis.Pass, exprs []ast.Expr) { seen := make(map[string]bool) @@ -110,8 +112,10 @@ func (op boolOp) checkRedundant(pass *analysis.Pass, exprs []ast.Expr) { } // checkSuspect checks for expressions of the form -// x != c1 || x != c2 -// x == c1 && x == c2 +// +// x != c1 || x != c2 +// x == c1 && x == c2 +// // where c1 and c2 are constant expressions. // If c1 and c2 are the same then it's redundant; // if c1 and c2 are different then it's always true or always false. 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 02b7b18b..4ec0e73f 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 @@ -48,7 +48,8 @@ func run(pass *analysis.Pass) (interface{}, error) { // Some Analyzers may need GlobalDebug, in which case we'll have // to set it globally, but let's wait till we need it. - mode := ssa.BuilderMode(0) + // Monomorphize at least until type parameters are available. + mode := ssa.InstantiateGenerics prog := ssa.NewProgram(pass.Fset, mode) 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 5768d0b9..b61ee5c3 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 @@ -122,8 +122,8 @@ func checkCgo(fset *token.FileSet, f *ast.File, info *types.Info, reportf func(t // For example, for each raw cgo source file in the original package, // such as this one: // -// package p -// import "C" +// package p +// import "C" // import "fmt" // type T int // const k = 3 @@ -147,9 +147,9 @@ func checkCgo(fset *token.FileSet, f *ast.File, info *types.Info, reportf func(t // the receiver into the first parameter; // and all functions are renamed to "_". // -// package p -// import . "·this·" // declares T, k, x, y, f, g, T.f -// import "C" +// package p +// import . "·this·" // declares T, k, x, y, f, g, T.f +// import "C" // import "fmt" // const _ = 3 // var _, _ = fmt.Println() @@ -169,7 +169,6 @@ func checkCgo(fset *token.FileSet, f *ast.File, info *types.Info, reportf func(t // C.f would resolve to "·this·"._C_func_f, for example. But we have // limited ourselves here to preserving function bodies and initializer // expressions since that is all that the cgocall analyzer needs. -// func typeCheckCgoSourceFiles(fset *token.FileSet, pkg *types.Package, files []*ast.File, info *types.Info, sizes types.Sizes) ([]*ast.File, *types.Info, error) { const thispkg = "·this·" @@ -284,8 +283,9 @@ func typeCheckCgoSourceFiles(fset *token.FileSet, pkg *types.Package, files []*a // cgoBaseType tries to look through type conversions involving // unsafe.Pointer to find the real type. It converts: -// unsafe.Pointer(x) => x -// *(*unsafe.Pointer)(unsafe.Pointer(&x)) => x +// +// unsafe.Pointer(x) => x +// *(*unsafe.Pointer)(unsafe.Pointer(&x)) => x func cgoBaseType(info *types.Info, arg ast.Expr) types.Type { switch arg := arg.(type) { case *ast.CallExpr: 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 d3670aca..64e184d3 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 @@ -7,6 +7,7 @@ package composite import ( + "fmt" "go/ast" "go/types" "strings" @@ -83,7 +84,8 @@ func run(pass *analysis.Pass) (interface{}, error) { } for _, typ := range structuralTypes { under := deref(typ.Underlying()) - if _, ok := under.(*types.Struct); !ok { + strct, ok := under.(*types.Struct) + if !ok { // skip non-struct composite literals continue } @@ -92,20 +94,47 @@ func run(pass *analysis.Pass) (interface{}, error) { continue } - // check if the CompositeLit contains an unkeyed field + // check if the struct contains an unkeyed field allKeyValue := true - for _, e := range cl.Elts { + var suggestedFixAvailable = len(cl.Elts) == strct.NumFields() + var missingKeys []analysis.TextEdit + for i, e := range cl.Elts { if _, ok := e.(*ast.KeyValueExpr); !ok { allKeyValue = false - break + if i >= strct.NumFields() { + break + } + field := strct.Field(i) + if !field.Exported() { + // Adding unexported field names for structs not defined + // locally will not work. + suggestedFixAvailable = false + break + } + missingKeys = append(missingKeys, analysis.TextEdit{ + Pos: e.Pos(), + End: e.Pos(), + NewText: []byte(fmt.Sprintf("%s: ", field.Name())), + }) } } if allKeyValue { - // all the composite literal fields are keyed + // all the struct fields are keyed continue } - pass.ReportRangef(cl, "%s composite literal uses unkeyed fields", typeName) + diag := analysis.Diagnostic{ + Pos: cl.Pos(), + End: cl.End(), + Message: fmt.Sprintf("%s struct literal uses unkeyed fields", typeName), + } + if suggestedFixAvailable { + diag.SuggestedFixes = []analysis.SuggestedFix{{ + Message: "Add field names to struct literal", + TextEdits: missingKeys, + }} + } + pass.Report(diag) return } }) 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 350dc4e0..8cc93e94 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 @@ -128,7 +128,7 @@ func checkCopyLocksCallExpr(pass *analysis.Pass, ce *ast.CallExpr) { } if fun, ok := pass.TypesInfo.Uses[id].(*types.Builtin); ok { switch fun.Name() { - case "new", "len", "cap", "Sizeof": + case "new", "len", "cap", "Sizeof", "Offsetof", "Alignof": return } } 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 384f0255..96adad3e 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 @@ -7,6 +7,7 @@ package errorsas import ( + "errors" "go/ast" "go/types" @@ -50,26 +51,39 @@ func run(pass *analysis.Pass) (interface{}, error) { if len(call.Args) < 2 { return // not enough arguments, e.g. called with return values of another function } - if fn.FullName() == "errors.As" && !pointerToInterfaceOrError(pass, call.Args[1]) { - pass.ReportRangef(call, "second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type") + if fn.FullName() != "errors.As" { + return + } + if err := checkAsTarget(pass, call.Args[1]); err != nil { + pass.ReportRangef(call, "%v", err) } }) return nil, nil } -var errorType = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) +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. -func pointerToInterfaceOrError(pass *analysis.Pass, e ast.Expr) bool { + +// 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 if it, ok := t.Underlying().(*types.Interface); ok && it.NumMethods() == 0 { - return true + // A target of interface{} is always allowed, since it often indicates + // a value forwarded from another source. + return nil } pt, ok := t.Underlying().(*types.Pointer) if !ok { - return false + return errors.New("second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type") + } + if pt.Elem() == errorType { + return errors.New("second argument to errors.As should not be *error") } _, ok = pt.Elem().Underlying().(*types.Interface) - return ok || types.Implements(pt.Elem(), errorType) + if ok || types.Implements(pt.Elem(), errorType.Underlying().(*types.Interface)) { + return nil + } + return errors.New("second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface 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 78afe94a..aff66304 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 @@ -23,7 +23,7 @@ import ( const Doc = `find structs that would use less memory if their fields were sorted This analyzer find structs that can be rearranged to use less memory, and provides -a suggested edit with the optimal order. +a suggested edit with the most compact order. Note that there are two different diagnostics reported. One checks struct size, and the other reports "pointer bytes" used. Pointer bytes is how many bytes of the @@ -41,6 +41,11 @@ has 24 pointer bytes because it has to scan further through the *uint32. struct { string; uint32 } has 8 because it can stop immediately after the string pointer. + +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. ` var Analyzer = &analysis.Analyzer{ 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 fd9e2af2..3b9168c6 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 @@ -62,15 +62,23 @@ func run(pass *analysis.Pass) (interface{}, error) { // Find the innermost containing block, and get the list // of statements starting with the one containing call. - stmts := restOfBlock(stack) + stmts, ncalls := restOfBlock(stack) if len(stmts) < 2 { - return true // the call to the http function is the last statement of the block. + // The call to the http function is the last statement of the block. + return true + } + + // Skip cases in which the call is wrapped by another (#52661). + // Example: resp, err := checkError(http.Get(url)) + if ncalls > 1 { + return true } asg, ok := stmts[0].(*ast.AssignStmt) if !ok { return true // the first statement is not assignment. } + resp := rootIdent(asg.Lhs[0]) if resp == nil { return true // could not find the http.Response in the assignment. @@ -130,20 +138,25 @@ func isHTTPFuncOrMethodOnClient(info *types.Info, expr *ast.CallExpr) bool { } // restOfBlock, given a traversal stack, finds the innermost containing -// block and returns the suffix of its statements starting with the -// current node (the last element of stack). -func restOfBlock(stack []ast.Node) []ast.Stmt { +// block and returns the suffix of its statements starting with the current +// node, along with the number of call expressions encountered. +func restOfBlock(stack []ast.Node) ([]ast.Stmt, int) { + var ncalls int for i := len(stack) - 1; i >= 0; i-- { if b, ok := stack[i].(*ast.BlockStmt); ok { for j, v := range b.List { if v == stack[i+1] { - return b.List[j:] + return b.List[j:], ncalls } } break } + + if _, ok := stack[i].(*ast.CallExpr); ok { + ncalls++ + } } - return nil + return nil, 0 } // rootIdent finds the root identifier x in a chain of selections x.y.z, or nil if not found. diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/inspect/inspect.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/inspect/inspect.go index 4bb652a7..c1c1127d 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/inspect/inspect.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/inspect/inspect.go @@ -19,14 +19,13 @@ // Requires: []*analysis.Analyzer{inspect.Analyzer}, // } // -// func run(pass *analysis.Pass) (interface{}, error) { -// inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) -// inspect.Preorder(nil, func(n ast.Node) { -// ... -// }) -// return nil -// } -// +// func run(pass *analysis.Pass) (interface{}, error) { +// inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) +// inspect.Preorder(nil, func(n ast.Node) { +// ... +// }) +// return nil +// } package inspect import ( diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/loopclosure.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/loopclosure.go index 3ea91574..98de9a9b 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/loopclosure.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/loopclosure/loopclosure.go @@ -128,9 +128,9 @@ func run(pass *analysis.Pass) (interface{}, error) { // (but not awaited) in another goroutine as a consequence of the call. // For example, given the g.Go call below, it returns the function literal expression. // -// import "sync/errgroup" -// var g errgroup.Group -// g.Go(func() error { ... }) +// import "sync/errgroup" +// var g errgroup.Group +// g.Go(func() error { ... }) // // Currently only "golang.org/x/sync/errgroup.Group()" is considered. func goInvokes(info *types.Info, call *ast.CallExpr) ast.Expr { 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 2eb782b4..8db18c73 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 @@ -62,6 +62,7 @@ var Analyzer = &analysis.Analyzer{ func run(pass *analysis.Pass) (interface{}, error) { ssainput := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) + // TODO(48525): ssainput.SrcFuncs is missing fn._Instances(). runFunc will be skipped. for _, fn := range ssainput.SrcFuncs { runFunc(pass, fn) } @@ -250,7 +251,7 @@ func (n nilness) String() string { return nilnessStrings[n+1] } // or unknown given the dominating stack of facts. func nilnessOf(stack []fact, v ssa.Value) nilness { switch v := v.(type) { - // unwrap ChangeInterface values recursively, to detect if underlying + // unwrap ChangeInterface and Slice values recursively, to detect if underlying // values have any facts recorded or are otherwise known with regard to nilness. // // This work must be in addition to expanding facts about @@ -264,6 +265,10 @@ func nilnessOf(stack []fact, v ssa.Value) nilness { if underlying := nilnessOf(stack, v.X); underlying != unknown { return underlying } + case *ssa.Slice: + if underlying := nilnessOf(stack, v.X); underlying != unknown { + return underlying + } case *ssa.SliceToArrayPointer: nn := nilnessOf(stack, v.X) if slice2ArrayPtrLen(v) > 0 { @@ -342,7 +347,7 @@ func eq(b *ssa.BasicBlock) (op *ssa.BinOp, tsucc, fsucc *ssa.BasicBlock) { // ChangeInterface, have transitive nilness, such that if you know the // underlying value is nil, you also know the value itself is nil, and vice // versa. This operation allows callers to match on any of the related values -// in analyses, rather than just the one form of the value that happend to +// in analyses, rather than just the one form of the value that happened to // appear in a comparison. // // This work must be in addition to unwrapping values within nilnessOf because diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/pkgfact/pkgfact.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/pkgfact/pkgfact.go index 2262fc4f..f4f5616e 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/pkgfact/pkgfact.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/pkgfact/pkgfact.go @@ -10,14 +10,14 @@ // Each key/value pair comes from a top-level constant declaration // whose name starts and ends with "_". For example: // -// package p +// package p // -// const _greeting_ = "hello" -// const _audience_ = "world" +// const _greeting_ = "hello" +// const _audience_ = "world" // // the pkgfact analysis output for package p would be: // -// {"greeting": "hello", "audience": "world"}. +// {"greeting": "hello", "audience": "world"}. // // In addition, the analysis reports a diagnostic at each import // showing which key/value pairs it contributes. 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 dee37d78..c4ccc95b 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 @@ -342,7 +342,6 @@ func checkPrintfFwd(pass *analysis.Pass, w *printfWrapper, call *ast.CallExpr, k // not do so with gccgo, and nor do some other build systems. // TODO(adonovan): eliminate the redundant facts once this restriction // is lifted. -// var isPrint = stringSet{ "fmt.Errorf": true, "fmt.Fprint": true, @@ -931,9 +930,9 @@ func okPrintfArg(pass *analysis.Pass, call *ast.CallExpr, state *formatState) (o // 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 (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 diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/shadow/shadow.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/shadow/shadow.go index b160dcf5..a19cecd1 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/shadow/shadow.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/shadow/shadow.go @@ -120,7 +120,6 @@ func run(pass *analysis.Pass) (interface{}, error) { // the block, we should complain about it but don't. // - A variable declared inside a function literal can falsely be identified // as shadowing a variable in the outer function. -// type span struct { min token.Pos max token.Pos diff --git a/tools/vendor/golang.org/x/tools/go/analysis/passes/sigchanyzer/sigchanyzer.go b/tools/vendor/golang.org/x/tools/go/analysis/passes/sigchanyzer/sigchanyzer.go index 0d6c8ebf..c490a84e 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/passes/sigchanyzer/sigchanyzer.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/passes/sigchanyzer/sigchanyzer.go @@ -50,7 +50,7 @@ func run(pass *analysis.Pass) (interface{}, error) { } case *ast.CallExpr: // Only signal.Notify(make(chan os.Signal), os.Interrupt) is safe, - // conservatively treate others as not safe, see golang/go#45043 + // conservatively treat others as not safe, see golang/go#45043 if isBuiltinMake(pass.TypesInfo, arg) { return } 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 ffa5205d..cab2fa20 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 @@ -84,7 +84,7 @@ func run(pass *analysis.Pass) (interface{}, error) { return nil, nil } -// Checks the contents of a fuzz function. +// checkFuzz checks the contents of a fuzz function. func checkFuzz(pass *analysis.Pass, fn *ast.FuncDecl) { params := checkFuzzCall(pass, fn) if params != nil { @@ -92,15 +92,17 @@ func checkFuzz(pass *analysis.Pass, fn *ast.FuncDecl) { } } -// Check the arguments of f.Fuzz() calls : -// 1. f.Fuzz() should call a function and it should be of type (*testing.F).Fuzz(). -// 2. The called function in f.Fuzz(func(){}) should not return result. -// 3. First argument of func() should be of type *testing.T -// 4. Second argument onwards should be of type []byte, string, bool, byte, -// rune, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, -// uint32, uint64 -// 5. func() must not call any *F methods, e.g. (*F).Log, (*F).Error, (*F).Skip -// The only *F methods that are allowed in the (*F).Fuzz function are (*F).Failed and (*F).Name. +// checkFuzzCall checks the arguments of f.Fuzz() calls: +// +// 1. f.Fuzz() should call a function and it should be of type (*testing.F).Fuzz(). +// 2. The called function in f.Fuzz(func(){}) should not return result. +// 3. First argument of func() should be of type *testing.T +// 4. Second argument onwards should be of type []byte, string, bool, byte, +// rune, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, +// uint32, uint64 +// 5. func() must not call any *F methods, e.g. (*F).Log, (*F).Error, (*F).Skip +// The only *F methods that are allowed in the (*F).Fuzz function are (*F).Failed and (*F).Name. +// // Returns the list of parameters to the fuzz function, if they are valid fuzz parameters. func checkFuzzCall(pass *analysis.Pass, fn *ast.FuncDecl) (params *types.Tuple) { ast.Inspect(fn, func(n ast.Node) bool { @@ -160,7 +162,7 @@ func checkFuzzCall(pass *analysis.Pass, fn *ast.FuncDecl) (params *types.Tuple) return params } -// Check that the arguments of f.Add() calls have the same number and type of arguments as +// checkAddCalls checks that the arguments of f.Add calls have the same number and type of arguments as // the signature of the function passed to (*testing.F).Fuzz func checkAddCalls(pass *analysis.Pass, fn *ast.FuncDecl, params *types.Tuple) { ast.Inspect(fn, func(n ast.Node) bool { @@ -473,10 +475,12 @@ func checkTest(pass *analysis.Pass, fn *ast.FuncDecl, prefix string) { if tparams := typeparams.ForFuncType(fn.Type); 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) } 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) } } 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 37a0e784..9cc45e0a 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 @@ -41,7 +41,7 @@ Another example is about non-pointer receiver: ` // Analyzer reports instances of writes to struct fields and arrays -//that are never read. +// that are never read. var Analyzer = &analysis.Analyzer{ Name: "unusedwrite", Doc: Doc, @@ -50,40 +50,49 @@ var Analyzer = &analysis.Analyzer{ } func run(pass *analysis.Pass) (interface{}, error) { - // Check the writes to struct and array objects. - checkStore := func(store *ssa.Store) { - // Consider field/index writes to an object whose elements are copied and not shared. - // MapUpdate is excluded since only the reference of the map is copied. - switch addr := store.Addr.(type) { - case *ssa.FieldAddr: - if isDeadStore(store, addr.X, addr) { - // Report the bug. + ssainput := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) + for _, fn := range ssainput.SrcFuncs { + // TODO(taking): Iterate over fn._Instantiations() once exported. If so, have 1 report per Pos(). + reports := checkStores(fn) + for _, store := range reports { + switch addr := store.Addr.(type) { + case *ssa.FieldAddr: pass.Reportf(store.Pos(), "unused write to field %s", getFieldName(addr.X.Type(), addr.Field)) - } - case *ssa.IndexAddr: - if isDeadStore(store, addr.X, addr) { - // Report the bug. + case *ssa.IndexAddr: pass.Reportf(store.Pos(), "unused write to array index %s", addr.Index) } } } + return nil, nil +} - ssainput := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) - for _, fn := range ssainput.SrcFuncs { - // Visit each block. No need to visit fn.Recover. - for _, blk := range fn.Blocks { - for _, instr := range blk.Instrs { - // Identify writes. - if store, ok := instr.(*ssa.Store); ok { - checkStore(store) +// checkStores returns *Stores in fn whose address is written to but never used. +func checkStores(fn *ssa.Function) []*ssa.Store { + var reports []*ssa.Store + // Visit each block. No need to visit fn.Recover. + for _, blk := range fn.Blocks { + for _, instr := range blk.Instrs { + // Identify writes. + if store, ok := instr.(*ssa.Store); ok { + // Consider field/index writes to an object whose elements are copied and not shared. + // MapUpdate is excluded since only the reference of the map is copied. + switch addr := store.Addr.(type) { + case *ssa.FieldAddr: + if isDeadStore(store, addr.X, addr) { + reports = append(reports, store) + } + case *ssa.IndexAddr: + if isDeadStore(store, addr.X, addr) { + reports = append(reports, store) + } } } } } - return nil, nil + return reports } // isDeadStore determines whether a field/index write to an object is dead. 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 23e57bf0..9da5692a 100644 --- a/tools/vendor/golang.org/x/tools/go/analysis/validate.go +++ b/tools/vendor/golang.org/x/tools/go/analysis/validate.go @@ -14,6 +14,8 @@ import ( // Validate reports an error if any of the analyzers are misconfigured. // Checks include: // that the name is a valid identifier; +// that the Doc is not empty; +// that the Run is non-nil; // that the Requires graph is acyclic; // that analyzer fact types are unique; // that each fact type is a pointer. @@ -46,6 +48,9 @@ func Validate(analyzers []*Analyzer) error { return fmt.Errorf("analyzer %q is undocumented", a) } + if a.Run == nil { + return fmt.Errorf("analyzer %q has nil Run", a) + } // fact types for _, f := range a.FactTypes { if f == nil { 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 a5c6d6d4..9fa5aa19 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 @@ -22,9 +22,9 @@ import ( // additional whitespace abutting a node to be enclosed by it. // In this example: // -// z := x + y // add them -// <-A-> -// <----B-----> +// z := x + y // add them +// <-A-> +// <----B-----> // // the ast.BinaryExpr(+) node is considered to enclose interval B // even though its [Pos()..End()) is actually only interval A. @@ -43,10 +43,10 @@ import ( // interior whitespace of path[0]. // In this example: // -// z := x + y // add them -// <--C--> <---E--> -// ^ -// D +// z := x + y // add them +// <--C--> <---E--> +// ^ +// D // // intervals C, D and E are inexact. C is contained by the // z-assignment statement, because it spans three of its children (:=, @@ -54,12 +54,11 @@ import ( // interior whitespace of the assignment. E is considered interior // whitespace of the BlockStmt containing the assignment. // -// Precondition: [start, end) both lie within the same file as root. -// TODO(adonovan): return (nil, false) in this case and remove precond. -// Requires FileSet; see loader.tokenFileContainsPos. -// -// Postcondition: path is never nil; it always contains at least 'root'. -// +// The resulting path is never empty; it always contains at least the +// 'root' *ast.File. Ideally PathEnclosingInterval would reject +// intervals that lie wholly or partially outside the range of the +// file, but unfortunately ast.File records only the token.Pos of +// the 'package' keyword, but not of the start of the file itself. func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Node, exact bool) { // fmt.Printf("EnclosingInterval %d %d\n", start, end) // debugging @@ -135,6 +134,7 @@ func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Nod return false // inexact: overlaps multiple children } + // Ensure [start,end) is nondecreasing. if start > end { start, end = end, start } @@ -162,7 +162,6 @@ func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Nod // tokenNode is a dummy implementation of ast.Node for a single token. // They are used transiently by PathEnclosingInterval but never escape // this package. -// type tokenNode struct { pos token.Pos end token.Pos @@ -183,7 +182,6 @@ func tok(pos token.Pos, len int) ast.Node { // childrenOf returns the direct non-nil children of ast.Node n. // It may include fake ast.Node implementations for bare tokens. // it is not safe to call (e.g.) ast.Walk on such nodes. -// func childrenOf(n ast.Node) []ast.Node { var children []ast.Node @@ -488,7 +486,6 @@ func (sl byPos) Swap(i, j int) { // TODO(adonovan): in some cases (e.g. Field, FieldList, Ident, // StarExpr) we could be much more specific given the path to the AST // root. Perhaps we should do that. -// func NodeDescription(n ast.Node) string { switch n := n.(type) { case *ast.ArrayType: diff --git a/tools/vendor/golang.org/x/tools/go/ast/astutil/imports.go b/tools/vendor/golang.org/x/tools/go/ast/astutil/imports.go index 2087ceec..18d1adb0 100644 --- a/tools/vendor/golang.org/x/tools/go/ast/astutil/imports.go +++ b/tools/vendor/golang.org/x/tools/go/ast/astutil/imports.go @@ -22,8 +22,11 @@ func AddImport(fset *token.FileSet, f *ast.File, path string) (added bool) { // If name is not empty, it is used to rename the import. // // For example, calling +// // AddNamedImport(fset, f, "pathpkg", "path") +// // adds +// // import pathpkg "path" func AddNamedImport(fset *token.FileSet, f *ast.File, name, path string) (added bool) { if imports(f, name, path) { @@ -270,8 +273,8 @@ func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (del } if j > 0 { lastImpspec := gen.Specs[j-1].(*ast.ImportSpec) - lastLine := fset.Position(lastImpspec.Path.ValuePos).Line - line := fset.Position(impspec.Path.ValuePos).Line + lastLine := fset.PositionFor(lastImpspec.Path.ValuePos, false).Line + line := fset.PositionFor(impspec.Path.ValuePos, false).Line // We deleted an entry but now there may be // a blank line-sized hole where the import was. 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 6d9ca23e..f430b21b 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 @@ -41,7 +41,6 @@ type ApplyFunc func(*Cursor) bool // Children are traversed in the order in which they appear in the // respective node's struct definition. A package's files are // traversed in the filenames' alphabetical order. -// func Apply(root ast.Node, pre, post ApplyFunc) (result ast.Node) { parent := &struct{ ast.Node }{root} defer func() { @@ -65,8 +64,8 @@ var abort = new(int) // singleton, to signal termination of Apply // c.Parent(), and f is the field identifier with name c.Name(), // the following invariants hold: // -// p.f == c.Node() if c.Index() < 0 -// p.f[c.Index()] == c.Node() if c.Index() >= 0 +// p.f == c.Node() if c.Index() < 0 +// p.f[c.Index()] == c.Node() if c.Index() >= 0 // // The methods Replace, Delete, InsertBefore, and InsertAfter // can be used to change the AST without disrupting Apply. @@ -294,6 +293,9 @@ 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 { + a.apply(n, "TypeParams", nil, tparams) + } a.apply(n, "Params", nil, n.Params) a.apply(n, "Results", nil, n.Results) @@ -406,6 +408,9 @@ 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 { + a.apply(n, "TypeParams", nil, tparams) + } a.apply(n, "Type", nil, n.Type) a.apply(n, "Comment", nil, n.Comment) 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 11f4fc36..11ab2bc8 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 @@ -77,12 +77,14 @@ const ( // typeOf returns a distinct single-bit value that represents the type of n. // // Various implementations were benchmarked with BenchmarkNewInspector: -// GOGC=off -// - type switch 4.9-5.5ms 2.1ms -// - binary search over a sorted list of types 5.5-5.9ms 2.5ms -// - linear scan, frequency-ordered list 5.9-6.1ms 2.7ms -// - linear scan, unordered list 6.4ms 2.7ms -// - hash table 6.5ms 3.1ms +// +// GOGC=off +// - type switch 4.9-5.5ms 2.1ms +// - binary search over a sorted list of types 5.5-5.9ms 2.5ms +// - linear scan, frequency-ordered list 5.9-6.1ms 2.7ms +// - linear scan, unordered list 6.4ms 2.7ms +// - hash table 6.5ms 3.1ms +// // A perfect hash seemed like overkill. // // The compiler's switch statement is the clear winner @@ -90,7 +92,6 @@ const ( // with constant conditions and good branch prediction. // (Sadly it is the most verbose in source code.) // Binary search suffered from poor branch prediction. -// func typeOf(n ast.Node) uint64 { // Fast path: nearly half of all nodes are identifiers. if _, ok := n.(*ast.Ident); ok { diff --git a/tools/vendor/golang.org/x/tools/go/buildutil/allpackages.go b/tools/vendor/golang.org/x/tools/go/buildutil/allpackages.go index c0cb03e7..dfb8cd6c 100644 --- a/tools/vendor/golang.org/x/tools/go/buildutil/allpackages.go +++ b/tools/vendor/golang.org/x/tools/go/buildutil/allpackages.go @@ -28,7 +28,6 @@ import ( // // All I/O is done via the build.Context file system interface, // which must be concurrency-safe. -// func AllPackages(ctxt *build.Context) []string { var list []string ForEachPackage(ctxt, func(pkg string, _ error) { @@ -48,7 +47,6 @@ func AllPackages(ctxt *build.Context) []string { // // All I/O is done via the build.Context file system interface, // which must be concurrency-safe. -// func ForEachPackage(ctxt *build.Context, found func(importPath string, err error)) { ch := make(chan item) @@ -127,19 +125,18 @@ func allPackages(ctxt *build.Context, root string, ch chan<- item) { // ExpandPatterns returns the set of packages matched by patterns, // which may have the following forms: // -// golang.org/x/tools/cmd/guru # a single package -// golang.org/x/tools/... # all packages beneath dir -// ... # the entire workspace. +// golang.org/x/tools/cmd/guru # a single package +// golang.org/x/tools/... # all packages beneath dir +// ... # the entire workspace. // // Order is significant: a pattern preceded by '-' removes matching // packages from the set. For example, these patterns match all encoding // packages except encoding/xml: // -// encoding/... -encoding/xml +// encoding/... -encoding/xml // // A trailing slash in a pattern is ignored. (Path components of Go // package names are separated by slash, not the platform's path separator.) -// func ExpandPatterns(ctxt *build.Context, patterns []string) map[string]bool { // TODO(adonovan): support other features of 'go list': // - "std"/"cmd"/"all" meta-packages diff --git a/tools/vendor/golang.org/x/tools/go/buildutil/fakecontext.go b/tools/vendor/golang.org/x/tools/go/buildutil/fakecontext.go index 5fc672fd..15025f64 100644 --- a/tools/vendor/golang.org/x/tools/go/buildutil/fakecontext.go +++ b/tools/vendor/golang.org/x/tools/go/buildutil/fakecontext.go @@ -30,7 +30,6 @@ import ( // /go/src/ including, for instance, "math" and "math/big". // ReadDir("/go/src/math/big") would return all the files in the // "math/big" package. -// func FakeContext(pkgs map[string]map[string]string) *build.Context { clean := func(filename string) string { f := path.Clean(filepath.ToSlash(filename)) diff --git a/tools/vendor/golang.org/x/tools/go/buildutil/overlay.go b/tools/vendor/golang.org/x/tools/go/buildutil/overlay.go index 8e239086..bdbfd931 100644 --- a/tools/vendor/golang.org/x/tools/go/buildutil/overlay.go +++ b/tools/vendor/golang.org/x/tools/go/buildutil/overlay.go @@ -60,8 +60,7 @@ func OverlayContext(orig *build.Context, overlay map[string][]byte) *build.Conte // ParseOverlayArchive parses an archive containing Go files and their // contents. The result is intended to be used with OverlayContext. // -// -// Archive format +// # Archive format // // The archive consists of a series of files. Each file consists of a // name, a decimal file size and the file contents, separated by 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 6da0ce48..7cf523bc 100644 --- a/tools/vendor/golang.org/x/tools/go/buildutil/tags.go +++ b/tools/vendor/golang.org/x/tools/go/buildutil/tags.go @@ -20,7 +20,8 @@ const TagsFlagDoc = "a list of `build tags` to consider satisfied during the bui // See $GOROOT/src/cmd/go/doc.go for description of 'go build -tags' flag. // // Example: -// flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc) +// +// flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc) type TagsFlag []string func (v *TagsFlag) Set(s string) error { diff --git a/tools/vendor/golang.org/x/tools/go/buildutil/util.go b/tools/vendor/golang.org/x/tools/go/buildutil/util.go index fc923d7a..d771b18e 100644 --- a/tools/vendor/golang.org/x/tools/go/buildutil/util.go +++ b/tools/vendor/golang.org/x/tools/go/buildutil/util.go @@ -28,7 +28,6 @@ import ( // filename that will be attached to the ASTs. // // TODO(adonovan): call this from go/loader.parseFiles when the tree thaws. -// func ParseFile(fset *token.FileSet, ctxt *build.Context, displayPath func(string) string, dir string, file string, mode parser.Mode) (*ast.File, error) { if !IsAbsPath(ctxt, file) { file = JoinPath(ctxt, dir, file) @@ -51,7 +50,6 @@ func ParseFile(fset *token.FileSet, ctxt *build.Context, displayPath func(string // // The '...Files []string' fields of the resulting build.Package are not // populated (build.FindOnly mode). -// func ContainingPackage(ctxt *build.Context, dir, filename string) (*build.Package, error) { if !IsAbsPath(ctxt, filename) { filename = JoinPath(ctxt, dir, filename) @@ -196,7 +194,6 @@ func SplitPathList(ctxt *build.Context, s string) []string { // sameFile returns true if x and y have the same basename and denote // the same file. -// func sameFile(x, y string) bool { if path.Clean(x) == path.Clean(y) { return true 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 7f95a296..dad6a444 100644 --- a/tools/vendor/golang.org/x/tools/go/cfg/builder.go +++ b/tools/vendor/golang.org/x/tools/go/cfg/builder.go @@ -443,7 +443,6 @@ func (b *builder) rangeStmt(s *ast.RangeStmt, label *lblock) { // Destinations associated with unlabeled for/switch/select stmts. // We push/pop one of these as we enter/leave each construct and for // each BranchStmt we scan for the innermost target of the right type. -// type targets struct { tail *targets // rest of stack _break *Block @@ -454,7 +453,6 @@ type targets struct { // Destinations associated with a labeled block. // We populate these as labels are encountered in forward gotos or // labeled statements. -// type lblock struct { _goto *Block _break *Block @@ -463,7 +461,6 @@ 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] if lb == nil { 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 3ebc65f6..37d799f4 100644 --- a/tools/vendor/golang.org/x/tools/go/cfg/cfg.go +++ b/tools/vendor/golang.org/x/tools/go/cfg/cfg.go @@ -20,14 +20,14 @@ // // produces this CFG: // -// 1: x := f() -// x != nil -// succs: 2, 3 -// 2: T() -// succs: 4 -// 3: F() -// succs: 4 -// 4: +// 1: x := f() +// x != nil +// succs: 2, 3 +// 2: T() +// succs: 4 +// 3: F() +// succs: 4 +// 4: // // The CFG does contain Return statements; even implicit returns are // materialized (at the position of the function's closing brace). @@ -36,7 +36,6 @@ // edges, nor the short-circuit semantics of the && and || operators, // nor abnormal control flow caused by panic. If you need this // information, use golang.org/x/tools/go/ssa instead. -// package cfg import ( 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 cec819d6..2ed25a75 100644 --- a/tools/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go +++ b/tools/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go @@ -17,32 +17,47 @@ // developer tools, which will then be able to consume both Go 1.7 and // Go 1.8 export data files, so they will work before and after the // Go update. (See discussion at https://golang.org/issue/15651.) -// package gcexportdata // import "golang.org/x/tools/go/gcexportdata" import ( "bufio" "bytes" + "encoding/json" "fmt" "go/token" "go/types" "io" "io/ioutil" + "os/exec" "golang.org/x/tools/go/internal/gcimporter" ) // Find returns the name of an object (.o) or archive (.a) file // containing type information for the specified import path, -// using the workspace layout conventions of go/build. +// using the go command. // If no file was found, an empty filename is returned. // // A relative srcDir is interpreted relative to the current working directory. // // Find also returns the package's resolved (canonical) import path, // reflecting the effects of srcDir and vendoring on importPath. +// +// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages, +// which is more efficient. func Find(importPath, srcDir string) (filename, path string) { - return gcimporter.FindPkg(importPath, srcDir) + cmd := exec.Command("go", "list", "-json", "-export", "--", importPath) + cmd.Dir = srcDir + out, err := cmd.CombinedOutput() + if err != nil { + return "", "" + } + var data struct { + ImportPath string + Export string + } + json.Unmarshal(out, &data) + return data.Export, data.ImportPath } // NewReader returns a reader for the export data section of an object @@ -101,13 +116,29 @@ func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, // The indexed export format starts with an 'i'; the older // binary export format starts with a 'c', 'd', or 'v' // (from "version"). Select appropriate importer. - if len(data) > 0 && data[0] == 'i' { - _, pkg, err := gcimporter.IImportData(fset, imports, data[1:], path) - return pkg, err - } + if len(data) > 0 { + switch data[0] { + case 'i': + _, pkg, err := gcimporter.IImportData(fset, imports, data[1:], path) + return pkg, err + + case 'v', 'c', 'd': + _, pkg, err := gcimporter.BImportData(fset, imports, data, path) + return pkg, err - _, pkg, err := gcimporter.BImportData(fset, imports, data, path) - return pkg, err + case 'u': + _, pkg, err := gcimporter.UImportData(fset, imports, data[1:], path) + return pkg, err + + default: + l := len(data) + if l > 10 { + l = 10 + } + return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), path) + } + } + return nil, fmt.Errorf("empty export data for %s", path) } // Write writes encoded type information for the specified package to out. diff --git a/tools/vendor/golang.org/x/tools/go/gcexportdata/importer.go b/tools/vendor/golang.org/x/tools/go/gcexportdata/importer.go index efe221e7..37a7247e 100644 --- a/tools/vendor/golang.org/x/tools/go/gcexportdata/importer.go +++ b/tools/vendor/golang.org/x/tools/go/gcexportdata/importer.go @@ -23,6 +23,8 @@ import ( // or to control the FileSet or access the imports map populated during // package loading. // +// Deprecated: Use the higher-level API in golang.org/x/tools/go/packages, +// which is more efficient. func NewImporter(fset *token.FileSet, imports map[string]*types.Package) types.ImporterFrom { return importer{fset, imports} } 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 d01fb04a..3fce4800 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 @@ -69,7 +69,6 @@ import ( // ProcessFiles invokes the cgo preprocessor on bp.CgoFiles, parses // the output and returns the resulting ASTs. -// func ProcessFiles(bp *build.Package, fset *token.FileSet, DisplayPath func(path string) string, mode parser.Mode) ([]*ast.File, error) { tmpdir, err := ioutil.TempDir("", strings.Replace(bp.ImportPath, "/", "_", -1)+"_C") if err != nil { diff --git a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/bexport.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/bexport.go index 0a3cdb9a..196cb3f9 100644 --- a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/bexport.go +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/bexport.go @@ -35,16 +35,18 @@ import ( const debugFormat = false // default: false // Current export format version. Increase with each format change. +// // Note: The latest binary (non-indexed) export format is at version 6. -// This exporter is still at level 4, but it doesn't matter since -// the binary importer can handle older versions just fine. -// 6: package height (CL 105038) -- NOT IMPLEMENTED HERE -// 5: improved position encoding efficiency (issue 20080, CL 41619) -- NOT IMPLEMEMTED HERE -// 4: type name objects support type aliases, uses aliasTag -// 3: Go1.8 encoding (same as version 2, aliasTag defined but never used) -// 2: removed unused bool in ODCL export (compiler only) -// 1: header format change (more regular), export package for _ struct fields -// 0: Go1.7 encoding +// This exporter is still at level 4, but it doesn't matter since +// the binary importer can handle older versions just fine. +// +// 6: package height (CL 105038) -- NOT IMPLEMENTED HERE +// 5: improved position encoding efficiency (issue 20080, CL 41619) -- NOT IMPLEMENTED HERE +// 4: type name objects support type aliases, uses aliasTag +// 3: Go1.8 encoding (same as version 2, aliasTag defined but never used) +// 2: removed unused bool in ODCL export (compiler only) +// 1: header format change (more regular), export package for _ struct fields +// 0: Go1.7 encoding const exportVersion = 4 // trackAllTypes enables cycle tracking for all types, not just named diff --git a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go index 3ab66830..e96c3960 100644 --- a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go @@ -45,7 +45,6 @@ var pkgExts = [...]string{".a", ".o"} // the build.Default build.Context). A relative srcDir is interpreted // relative to the current working directory. // If no file was found, an empty filename is returned. -// func FindPkg(path, srcDir string) (filename, id string) { if path == "" { return @@ -109,7 +108,6 @@ func FindPkg(path, srcDir string) (filename, id string) { // If packages[id] contains the completely imported package, that package // can be used directly, and there is no need to call this function (but // there is also no harm but for extra time used). -// func ImportData(packages map[string]*types.Package, filename, id string, data io.Reader) (pkg *types.Package, err error) { // support for parser error handling defer func() { @@ -133,7 +131,6 @@ func ImportData(packages map[string]*types.Package, filename, id string, data io // Import imports a gc-generated package given its import path and srcDir, adds // the corresponding package object to the packages map, and returns the object. // The packages map must contain all packages already imported. -// func Import(packages map[string]*types.Package, path, srcDir string, lookup func(path string) (io.ReadCloser, error)) (pkg *types.Package, err error) { var rc io.ReadCloser var filename, id string @@ -184,8 +181,9 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func defer rc.Close() var hdr string + var size int64 buf := bufio.NewReader(rc) - if hdr, _, err = FindExportData(buf); err != nil { + if hdr, size, err = FindExportData(buf); err != nil { return } @@ -213,10 +211,27 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func // The indexed export format starts with an 'i'; the older // binary export format starts with a 'c', 'd', or 'v' // (from "version"). Select appropriate importer. - if len(data) > 0 && data[0] == 'i' { - _, pkg, err = IImportData(fset, packages, data[1:], id) - } else { - _, pkg, err = BImportData(fset, packages, data, id) + if len(data) > 0 { + switch data[0] { + case 'i': + _, pkg, err := IImportData(fset, packages, data[1:], id) + return pkg, err + + case 'v', 'c', 'd': + _, pkg, err := BImportData(fset, packages, data, id) + return pkg, err + + case 'u': + _, pkg, err := UImportData(fset, packages, data[1:size], id) + return pkg, err + + default: + l := len(data) + if l > 10 { + l = 10 + } + return nil, fmt.Errorf("unexpected export data with prefix %q for path %s", string(data[:l]), id) + } } default: @@ -348,8 +363,9 @@ func (p *parser) expectKeyword(keyword string) { // ---------------------------------------------------------------------------- // Qualified and unqualified names -// PackageId = string_lit . +// parsePackageID parses a PackageId: // +// PackageId = string_lit . func (p *parser) parsePackageID() string { id, err := strconv.Unquote(p.expect(scanner.String)) if err != nil { @@ -363,13 +379,16 @@ func (p *parser) parsePackageID() string { return id } -// PackageName = ident . +// parsePackageName parse a PackageName: // +// PackageName = ident . func (p *parser) parsePackageName() string { return p.expect(scanner.Ident) } -// dotIdentifier = ( ident | '·' ) { ident | int | '·' } . +// parseDotIdent parses a dotIdentifier: +// +// dotIdentifier = ( ident | '·' ) { ident | int | '·' } . func (p *parser) parseDotIdent() string { ident := "" if p.tok != scanner.Int { @@ -386,8 +405,9 @@ func (p *parser) parseDotIdent() string { return ident } -// QualifiedName = "@" PackageId "." ( "?" | dotIdentifier ) . +// parseQualifiedName parses a QualifiedName: // +// QualifiedName = "@" PackageId "." ( "?" | dotIdentifier ) . func (p *parser) parseQualifiedName() (id, name string) { p.expect('@') id = p.parsePackageID() @@ -410,7 +430,6 @@ func (p *parser) parseQualifiedName() (id, name string) { // id identifies a package, usually by a canonical package path like // "encoding/json" but possibly by a non-canonical import path like // "./json". -// func (p *parser) getPkg(id, name string) *types.Package { // package unsafe is not in the packages maps - handle explicitly if id == "unsafe" { @@ -446,7 +465,6 @@ func (p *parser) getPkg(id, name string) *types.Package { // parseExportedName is like parseQualifiedName, but // the package id is resolved to an imported *types.Package. -// func (p *parser) parseExportedName() (pkg *types.Package, name string) { id, name := p.parseQualifiedName() pkg = p.getPkg(id, "") @@ -456,8 +474,9 @@ func (p *parser) parseExportedName() (pkg *types.Package, name string) { // ---------------------------------------------------------------------------- // Types -// BasicType = identifier . +// parseBasicType parses a BasicType: // +// BasicType = identifier . func (p *parser) parseBasicType() types.Type { id := p.expect(scanner.Ident) obj := types.Universe.Lookup(id) @@ -468,8 +487,9 @@ func (p *parser) parseBasicType() types.Type { return nil } -// ArrayType = "[" int_lit "]" Type . +// parseArrayType parses an ArrayType: // +// ArrayType = "[" int_lit "]" Type . func (p *parser) parseArrayType(parent *types.Package) types.Type { // "[" already consumed and lookahead known not to be "]" lit := p.expect(scanner.Int) @@ -482,8 +502,9 @@ func (p *parser) parseArrayType(parent *types.Package) types.Type { return types.NewArray(elem, n) } -// MapType = "map" "[" Type "]" Type . +// parseMapType parses a MapType: // +// MapType = "map" "[" Type "]" Type . func (p *parser) parseMapType(parent *types.Package) types.Type { p.expectKeyword("map") p.expect('[') @@ -493,7 +514,9 @@ func (p *parser) parseMapType(parent *types.Package) types.Type { return types.NewMap(key, elem) } -// Name = identifier | "?" | QualifiedName . +// parseName parses a Name: +// +// Name = identifier | "?" | QualifiedName . // // For unqualified and anonymous names, the returned package is the parent // package unless parent == nil, in which case the returned package is the @@ -505,7 +528,6 @@ func (p *parser) parseMapType(parent *types.Package) types.Type { // it doesn't exist yet) unless materializePkg is set (which creates an // unnamed package with valid package path). In the latter case, a // subsequent import clause is expected to provide a name for the package. -// func (p *parser) parseName(parent *types.Package, materializePkg bool) (pkg *types.Package, name string) { pkg = parent if pkg == nil { @@ -539,8 +561,9 @@ func deref(typ types.Type) types.Type { return typ } -// Field = Name Type [ string_lit ] . +// parseField parses a Field: // +// Field = Name Type [ string_lit ] . func (p *parser) parseField(parent *types.Package) (*types.Var, string) { pkg, name := p.parseName(parent, true) @@ -583,9 +606,10 @@ func (p *parser) parseField(parent *types.Package) (*types.Var, string) { return types.NewField(token.NoPos, pkg, name, typ, anonymous), tag } -// StructType = "struct" "{" [ FieldList ] "}" . -// FieldList = Field { ";" Field } . +// parseStructType parses a StructType: // +// StructType = "struct" "{" [ FieldList ] "}" . +// FieldList = Field { ";" Field } . func (p *parser) parseStructType(parent *types.Package) types.Type { var fields []*types.Var var tags []string @@ -610,8 +634,9 @@ func (p *parser) parseStructType(parent *types.Package) types.Type { return types.NewStruct(fields, tags) } -// Parameter = ( identifier | "?" ) [ "..." ] Type [ string_lit ] . +// parseParameter parses a Parameter: // +// Parameter = ( identifier | "?" ) [ "..." ] Type [ string_lit ] . func (p *parser) parseParameter() (par *types.Var, isVariadic bool) { _, name := p.parseName(nil, false) // remove gc-specific parameter numbering @@ -635,9 +660,10 @@ func (p *parser) parseParameter() (par *types.Var, isVariadic bool) { return } -// Parameters = "(" [ ParameterList ] ")" . -// ParameterList = { Parameter "," } Parameter . +// parseParameters parses a Parameters: // +// Parameters = "(" [ ParameterList ] ")" . +// ParameterList = { Parameter "," } Parameter . func (p *parser) parseParameters() (list []*types.Var, isVariadic bool) { p.expect('(') for p.tok != ')' && p.tok != scanner.EOF { @@ -658,9 +684,10 @@ func (p *parser) parseParameters() (list []*types.Var, isVariadic bool) { return } -// Signature = Parameters [ Result ] . -// Result = Type | Parameters . +// parseSignature parses a Signature: // +// Signature = Parameters [ Result ] . +// Result = Type | Parameters . func (p *parser) parseSignature(recv *types.Var) *types.Signature { params, isVariadic := p.parseParameters() @@ -677,14 +704,15 @@ func (p *parser) parseSignature(recv *types.Var) *types.Signature { return types.NewSignature(recv, types.NewTuple(params...), types.NewTuple(results...), isVariadic) } -// InterfaceType = "interface" "{" [ MethodList ] "}" . -// MethodList = Method { ";" Method } . -// Method = Name Signature . +// parseInterfaceType parses an InterfaceType: +// +// InterfaceType = "interface" "{" [ MethodList ] "}" . +// MethodList = Method { ";" Method } . +// Method = Name Signature . // // The methods of embedded interfaces are always "inlined" // by the compiler and thus embedded interfaces are never // visible in the export data. -// func (p *parser) parseInterfaceType(parent *types.Package) types.Type { var methods []*types.Func @@ -705,8 +733,9 @@ func (p *parser) parseInterfaceType(parent *types.Package) types.Type { return newInterface(methods, nil).Complete() } -// ChanType = ( "chan" [ "<-" ] | "<-" "chan" ) Type . +// parseChanType parses a ChanType: // +// ChanType = ( "chan" [ "<-" ] | "<-" "chan" ) Type . func (p *parser) parseChanType(parent *types.Package) types.Type { dir := types.SendRecv if p.tok == scanner.Ident { @@ -724,17 +753,18 @@ func (p *parser) parseChanType(parent *types.Package) types.Type { return types.NewChan(dir, elem) } -// Type = -// BasicType | TypeName | ArrayType | SliceType | StructType | -// PointerType | FuncType | InterfaceType | MapType | ChanType | -// "(" Type ")" . +// parseType parses a Type: // -// BasicType = ident . -// TypeName = ExportedName . -// SliceType = "[" "]" Type . -// PointerType = "*" Type . -// FuncType = "func" Signature . +// Type = +// BasicType | TypeName | ArrayType | SliceType | StructType | +// PointerType | FuncType | InterfaceType | MapType | ChanType | +// "(" Type ")" . // +// BasicType = ident . +// TypeName = ExportedName . +// SliceType = "[" "]" Type . +// PointerType = "*" Type . +// FuncType = "func" Signature . func (p *parser) parseType(parent *types.Package) types.Type { switch p.tok { case scanner.Ident: @@ -786,16 +816,18 @@ func (p *parser) parseType(parent *types.Package) types.Type { // ---------------------------------------------------------------------------- // Declarations -// ImportDecl = "import" PackageName PackageId . +// parseImportDecl parses an ImportDecl: // +// ImportDecl = "import" PackageName PackageId . func (p *parser) parseImportDecl() { p.expectKeyword("import") name := p.parsePackageName() p.getPkg(p.parsePackageID(), name) } -// int_lit = [ "+" | "-" ] { "0" ... "9" } . +// parseInt parses an int_lit: // +// int_lit = [ "+" | "-" ] { "0" ... "9" } . func (p *parser) parseInt() string { s := "" switch p.tok { @@ -808,8 +840,9 @@ func (p *parser) parseInt() string { return s + p.expect(scanner.Int) } -// number = int_lit [ "p" int_lit ] . +// parseNumber parses a number: // +// number = int_lit [ "p" int_lit ] . func (p *parser) parseNumber() (typ *types.Basic, val constant.Value) { // mantissa mant := constant.MakeFromLiteral(p.parseInt(), token.INT, 0) @@ -844,13 +877,14 @@ func (p *parser) parseNumber() (typ *types.Basic, val constant.Value) { return } -// ConstDecl = "const" ExportedName [ Type ] "=" Literal . -// Literal = bool_lit | int_lit | float_lit | complex_lit | rune_lit | string_lit . -// bool_lit = "true" | "false" . -// complex_lit = "(" float_lit "+" float_lit "i" ")" . -// rune_lit = "(" int_lit "+" int_lit ")" . -// string_lit = `"` { unicode_char } `"` . +// parseConstDecl parses a ConstDecl: // +// ConstDecl = "const" ExportedName [ Type ] "=" Literal . +// Literal = bool_lit | int_lit | float_lit | complex_lit | rune_lit | string_lit . +// bool_lit = "true" | "false" . +// complex_lit = "(" float_lit "+" float_lit "i" ")" . +// rune_lit = "(" int_lit "+" int_lit ")" . +// string_lit = `"` { unicode_char } `"` . func (p *parser) parseConstDecl() { p.expectKeyword("const") pkg, name := p.parseExportedName() @@ -920,8 +954,9 @@ func (p *parser) parseConstDecl() { pkg.Scope().Insert(types.NewConst(token.NoPos, pkg, name, typ0, val)) } -// TypeDecl = "type" ExportedName Type . +// parseTypeDecl parses a TypeDecl: // +// TypeDecl = "type" ExportedName Type . func (p *parser) parseTypeDecl() { p.expectKeyword("type") pkg, name := p.parseExportedName() @@ -939,8 +974,9 @@ func (p *parser) parseTypeDecl() { } } -// VarDecl = "var" ExportedName Type . +// parseVarDecl parses a VarDecl: // +// VarDecl = "var" ExportedName Type . func (p *parser) parseVarDecl() { p.expectKeyword("var") pkg, name := p.parseExportedName() @@ -948,9 +984,10 @@ func (p *parser) parseVarDecl() { pkg.Scope().Insert(types.NewVar(token.NoPos, pkg, name, typ)) } -// Func = Signature [ Body ] . -// Body = "{" ... "}" . +// parseFunc parses a Func: // +// Func = Signature [ Body ] . +// Body = "{" ... "}" . func (p *parser) parseFunc(recv *types.Var) *types.Signature { sig := p.parseSignature(recv) if p.tok == '{' { @@ -967,9 +1004,10 @@ func (p *parser) parseFunc(recv *types.Var) *types.Signature { return sig } -// MethodDecl = "func" Receiver Name Func . -// Receiver = "(" ( identifier | "?" ) [ "*" ] ExportedName ")" . +// parseMethodDecl parses a MethodDecl: // +// MethodDecl = "func" Receiver Name Func . +// Receiver = "(" ( identifier | "?" ) [ "*" ] ExportedName ")" . func (p *parser) parseMethodDecl() { // "func" already consumed p.expect('(') @@ -992,8 +1030,9 @@ func (p *parser) parseMethodDecl() { base.AddMethod(types.NewFunc(token.NoPos, pkg, name, sig)) } -// FuncDecl = "func" ExportedName Func . +// parseFuncDecl parses a FuncDecl: // +// FuncDecl = "func" ExportedName Func . func (p *parser) parseFuncDecl() { // "func" already consumed pkg, name := p.parseExportedName() @@ -1001,8 +1040,9 @@ func (p *parser) parseFuncDecl() { pkg.Scope().Insert(types.NewFunc(token.NoPos, pkg, name, typ)) } -// Decl = [ ImportDecl | ConstDecl | TypeDecl | VarDecl | FuncDecl | MethodDecl ] "\n" . +// parseDecl parses a Decl: // +// Decl = [ ImportDecl | ConstDecl | TypeDecl | VarDecl | FuncDecl | MethodDecl ] "\n" . func (p *parser) parseDecl() { if p.tok == scanner.Ident { switch p.lit { @@ -1029,9 +1069,10 @@ func (p *parser) parseDecl() { // ---------------------------------------------------------------------------- // Export -// Export = "PackageClause { Decl } "$$" . -// PackageClause = "package" PackageName [ "safe" ] "\n" . +// parseExport parses an Export: // +// Export = "PackageClause { Decl } "$$" . +// PackageClause = "package" PackageName [ "safe" ] "\n" . func (p *parser) parseExport() *types.Package { p.expectKeyword("package") name := p.parsePackageName() diff --git a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iexport.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iexport.go index 20955340..9a4ff329 100644 --- a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iexport.go +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iexport.go @@ -251,7 +251,10 @@ func (p *iexporter) stringOff(s string) uint64 { // pushDecl adds n to the declaration work queue, if not already present. func (p *iexporter) pushDecl(obj types.Object) { // Package unsafe is known to the compiler and predeclared. - assert(obj.Pkg() != types.Unsafe) + // Caller should not ask us to do export it. + if obj.Pkg() == types.Unsafe { + panic("cannot export package unsafe") + } if _, ok := p.declIndex[obj]; ok { return diff --git a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iimport.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iimport.go index 84cfb807..4caa0f55 100644 --- a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iimport.go +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/iimport.go @@ -17,6 +17,7 @@ import ( "go/token" "go/types" "io" + "math/big" "sort" "strings" @@ -53,7 +54,7 @@ const ( ) type ident struct { - pkg string + pkg *types.Package name string } @@ -100,7 +101,9 @@ func iimportCommon(fset *token.FileSet, imports map[string]*types.Package, data if !debug { defer func() { if e := recover(); e != nil { - if version > currentVersion { + if bundle { + err = fmt.Errorf("%v", e) + } else if version > currentVersion { err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) } else { err = fmt.Errorf("cannot import %q (%v), possibly version skew - reinstall package", path, e) @@ -461,7 +464,7 @@ func (r *importReader) obj(name string) { // To handle recursive references to the typeparam within its // bound, save the partial type in tparamIndex before reading the bounds. - id := ident{r.currPkg.Name(), name} + id := ident{r.currPkg, name} r.p.tparamIndex[id] = t var implicit bool if r.p.version >= iexportVersionGo1_18 { @@ -510,7 +513,9 @@ func (r *importReader) value() (typ types.Type, val constant.Value) { val = constant.MakeString(r.string()) case types.IsInteger: - val = r.mpint(b) + var x big.Int + r.mpint(&x, b) + val = constant.Make(&x) case types.IsFloat: val = r.mpfloat(b) @@ -559,8 +564,8 @@ func intSize(b *types.Basic) (signed bool, maxBytes uint) { return } -func (r *importReader) mpint(b *types.Basic) constant.Value { - signed, maxBytes := intSize(b) +func (r *importReader) mpint(x *big.Int, typ *types.Basic) { + signed, maxBytes := intSize(typ) maxSmall := 256 - maxBytes if signed { @@ -579,7 +584,8 @@ func (r *importReader) mpint(b *types.Basic) constant.Value { v = ^v } } - return constant.MakeInt64(v) + x.SetInt64(v) + return } v := -n @@ -589,47 +595,23 @@ func (r *importReader) mpint(b *types.Basic) constant.Value { if v < 1 || uint(v) > maxBytes { errorf("weird decoding: %v, %v => %v", n, signed, v) } - - buf := make([]byte, v) - io.ReadFull(&r.declReader, buf) - - // convert to little endian - // TODO(gri) go/constant should have a more direct conversion function - // (e.g., once it supports a big.Float based implementation) - for i, j := 0, len(buf)-1; i < j; i, j = i+1, j-1 { - buf[i], buf[j] = buf[j], buf[i] - } - - x := constant.MakeFromBytes(buf) + b := make([]byte, v) + io.ReadFull(&r.declReader, b) + x.SetBytes(b) if signed && n&1 != 0 { - x = constant.UnaryOp(token.SUB, x, 0) + x.Neg(x) } - return x } -func (r *importReader) mpfloat(b *types.Basic) constant.Value { - x := r.mpint(b) - if constant.Sign(x) == 0 { - return x - } - - exp := r.int64() - switch { - case exp > 0: - x = constant.Shift(x, token.SHL, uint(exp)) - // Ensure that the imported Kind is Float, else this constant may run into - // bitsize limits on overlarge integers. Eventually we can instead adopt - // the approach of CL 288632, but that CL relies on go/constant APIs that - // were introduced in go1.13. - // - // TODO(rFindley): sync the logic here with tip Go once we no longer - // support go1.12. - x = constant.ToFloat(x) - case exp < 0: - d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp)) - x = constant.BinaryOp(x, token.QUO, d) +func (r *importReader) mpfloat(typ *types.Basic) constant.Value { + var mant big.Int + r.mpint(&mant, typ) + var f big.Float + f.SetInt(&mant) + if f.Sign() != 0 { + f.SetMantExp(&f, int(r.int64())) } - return x + return constant.Make(&f) } func (r *importReader) ident() string { @@ -777,7 +759,7 @@ func (r *importReader) doType(base *types.Named) (res types.Type) { errorf("unexpected type param type") } pkg, name := r.qualifiedIdent() - id := ident{pkg.Name(), name} + id := ident{pkg, name} if t, ok := r.p.tparamIndex[id]; ok { // We're already in the process of importing this typeparam. return t diff --git a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/unified_no.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/unified_no.go new file mode 100644 index 00000000..286bf445 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/unified_no.go @@ -0,0 +1,10 @@ +// 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 && goexperiment.unified) +// +build !go1.18 !goexperiment.unified + +package gcimporter + +const unifiedIR = false diff --git a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/unified_yes.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/unified_yes.go new file mode 100644 index 00000000..b5d69ffb --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/unified_yes.go @@ -0,0 +1,10 @@ +// 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 && goexperiment.unified +// +build go1.18,goexperiment.unified + +package gcimporter + +const unifiedIR = true diff --git a/tools/vendor/golang.org/x/tools/go/internal/gcimporter/ureader_no.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/ureader_no.go new file mode 100644 index 00000000..8eb20729 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/ureader_no.go @@ -0,0 +1,19 @@ +// 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/go/internal/gcimporter/ureader_yes.go b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/ureader_yes.go new file mode 100644 index 00000000..3c1a4375 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/gcimporter/ureader_yes.go @@ -0,0 +1,612 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Derived from go/internal/gcimporter/ureader.go + +//go:build go1.18 +// +build go1.18 + +package gcimporter + +import ( + "go/token" + "go/types" + "strings" + + "golang.org/x/tools/go/internal/pkgbits" +) + +// A pkgReader holds the shared state for reading a unified IR package +// description. +type pkgReader struct { + pkgbits.PkgDecoder + + fake fakeFileSet + + ctxt *types.Context + imports map[string]*types.Package // previously imported packages, indexed by path + + // lazily initialized arrays corresponding to the unified IR + // PosBase, Pkg, and Type sections, respectively. + posBases []string // position bases (i.e., file names) + pkgs []*types.Package + typs []types.Type + + // laterFns holds functions that need to be invoked at the end of + // import reading. + laterFns []func() +} + +// later adds a function to be invoked at the end of import reading. +func (pr *pkgReader) later(fn func()) { + pr.laterFns = append(pr.laterFns, fn) +} + +// See cmd/compile/internal/noder.derivedInfo. +type derivedInfo struct { + idx pkgbits.Index + needed bool +} + +// See cmd/compile/internal/noder.typeInfo. +type typeInfo struct { + idx pkgbits.Index + derived bool +} + +func UImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { + s := string(data) + s = s[:strings.LastIndex(s, "\n$$\n")] + input := pkgbits.NewPkgDecoder(path, s) + pkg = readUnifiedPackage(fset, nil, imports, input) + return +} + +// readUnifiedPackage reads a package description from the given +// unified IR export data decoder. +func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[string]*types.Package, input pkgbits.PkgDecoder) *types.Package { + pr := pkgReader{ + PkgDecoder: input, + + fake: fakeFileSet{ + fset: fset, + files: make(map[string]*fileInfo), + }, + + ctxt: ctxt, + imports: imports, + + posBases: make([]string, input.NumElems(pkgbits.RelocPosBase)), + pkgs: make([]*types.Package, input.NumElems(pkgbits.RelocPkg)), + typs: make([]types.Type, input.NumElems(pkgbits.RelocType)), + } + defer pr.fake.setLines() + + r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic) + pkg := r.pkg() + r.Bool() // has init + + for i, n := 0, r.Len(); i < n; i++ { + // As if r.obj(), but avoiding the Scope.Lookup call, + // to avoid eager loading of imports. + r.Sync(pkgbits.SyncObject) + assert(!r.Bool()) + r.p.objIdx(r.Reloc(pkgbits.RelocObj)) + assert(r.Len() == 0) + } + + r.Sync(pkgbits.SyncEOF) + + for _, fn := range pr.laterFns { + fn() + } + + pkg.MarkComplete() + return pkg +} + +// A reader holds the state for reading a single unified IR element +// within a package. +type reader struct { + pkgbits.Decoder + + p *pkgReader + + dict *readerDict +} + +// A readerDict holds the state for type parameters that parameterize +// the current unified IR element. +type readerDict struct { + // bounds is a slice of typeInfos corresponding to the underlying + // bounds of the element's type parameters. + bounds []typeInfo + + // tparams is a slice of the constructed TypeParams for the element. + tparams []*types.TypeParam + + // devived is a slice of types derived from tparams, which may be + // instantiated while reading the current element. + derived []derivedInfo + derivedTypes []types.Type // lazily instantiated from derived +} + +func (pr *pkgReader) newReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader { + return &reader{ + Decoder: pr.NewDecoder(k, idx, marker), + p: pr, + } +} + +// @@@ Positions + +func (r *reader) pos() token.Pos { + r.Sync(pkgbits.SyncPos) + if !r.Bool() { + return token.NoPos + } + + // TODO(mdempsky): Delta encoding. + posBase := r.posBase() + line := r.Uint() + col := r.Uint() + return r.p.fake.pos(posBase, int(line), int(col)) +} + +func (r *reader) posBase() string { + return r.p.posBaseIdx(r.Reloc(pkgbits.RelocPosBase)) +} + +func (pr *pkgReader) posBaseIdx(idx pkgbits.Index) string { + if b := pr.posBases[idx]; b != "" { + return b + } + + r := pr.newReader(pkgbits.RelocPosBase, idx, pkgbits.SyncPosBase) + + // Within types2, position bases have a lot more details (e.g., + // keeping track of where //line directives appeared exactly). + // + // For go/types, we just track the file name. + + filename := r.String() + + if r.Bool() { // file base + // Was: "b = token.NewTrimmedFileBase(filename, true)" + } else { // line base + pos := r.pos() + line := r.Uint() + col := r.Uint() + + // Was: "b = token.NewLineBase(pos, filename, true, line, col)" + _, _, _ = pos, line, col + } + + b := filename + pr.posBases[idx] = b + return b +} + +// @@@ Packages + +func (r *reader) pkg() *types.Package { + r.Sync(pkgbits.SyncPkg) + return r.p.pkgIdx(r.Reloc(pkgbits.RelocPkg)) +} + +func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Package { + // TODO(mdempsky): Consider using some non-nil pointer to indicate + // the universe scope, so we don't need to keep re-reading it. + if pkg := pr.pkgs[idx]; pkg != nil { + return pkg + } + + pkg := pr.newReader(pkgbits.RelocPkg, idx, pkgbits.SyncPkgDef).doPkg() + pr.pkgs[idx] = pkg + return pkg +} + +func (r *reader) doPkg() *types.Package { + path := r.String() + switch path { + case "": + path = r.p.PkgPath() + case "builtin": + return nil // universe + case "unsafe": + return types.Unsafe + } + + if pkg := r.p.imports[path]; pkg != nil { + return pkg + } + + name := r.String() + + pkg := types.NewPackage(path, name) + r.p.imports[path] = pkg + + imports := make([]*types.Package, r.Len()) + for i := range imports { + imports[i] = r.pkg() + } + pkg.SetImports(imports) + + return pkg +} + +// @@@ Types + +func (r *reader) typ() types.Type { + return r.p.typIdx(r.typInfo(), r.dict) +} + +func (r *reader) typInfo() typeInfo { + r.Sync(pkgbits.SyncType) + if r.Bool() { + return typeInfo{idx: pkgbits.Index(r.Len()), derived: true} + } + return typeInfo{idx: r.Reloc(pkgbits.RelocType), derived: false} +} + +func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict) types.Type { + idx := info.idx + var where *types.Type + if info.derived { + where = &dict.derivedTypes[idx] + idx = dict.derived[idx].idx + } else { + where = &pr.typs[idx] + } + + if typ := *where; typ != nil { + return typ + } + + r := pr.newReader(pkgbits.RelocType, idx, pkgbits.SyncTypeIdx) + r.dict = dict + + typ := r.doTyp() + assert(typ != nil) + + // See comment in pkgReader.typIdx explaining how this happens. + if prev := *where; prev != nil { + return prev + } + + *where = typ + return typ +} + +func (r *reader) doTyp() (res types.Type) { + switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag { + default: + errorf("unhandled type tag: %v", tag) + panic("unreachable") + + case pkgbits.TypeBasic: + return types.Typ[r.Len()] + + case pkgbits.TypeNamed: + obj, targs := r.obj() + name := obj.(*types.TypeName) + if len(targs) != 0 { + t, _ := types.Instantiate(r.p.ctxt, name.Type(), targs, false) + return t + } + return name.Type() + + case pkgbits.TypeTypeParam: + return r.dict.tparams[r.Len()] + + case pkgbits.TypeArray: + len := int64(r.Uint64()) + return types.NewArray(r.typ(), len) + case pkgbits.TypeChan: + dir := types.ChanDir(r.Len()) + return types.NewChan(dir, r.typ()) + case pkgbits.TypeMap: + return types.NewMap(r.typ(), r.typ()) + case pkgbits.TypePointer: + return types.NewPointer(r.typ()) + case pkgbits.TypeSignature: + return r.signature(nil, nil, nil) + case pkgbits.TypeSlice: + return types.NewSlice(r.typ()) + case pkgbits.TypeStruct: + return r.structType() + case pkgbits.TypeInterface: + return r.interfaceType() + case pkgbits.TypeUnion: + return r.unionType() + } +} + +func (r *reader) structType() *types.Struct { + fields := make([]*types.Var, r.Len()) + var tags []string + for i := range fields { + pos := r.pos() + pkg, name := r.selector() + ftyp := r.typ() + tag := r.String() + embedded := r.Bool() + + fields[i] = types.NewField(pos, pkg, name, ftyp, embedded) + if tag != "" { + for len(tags) < i { + tags = append(tags, "") + } + tags = append(tags, tag) + } + } + return types.NewStruct(fields, tags) +} + +func (r *reader) unionType() *types.Union { + terms := make([]*types.Term, r.Len()) + for i := range terms { + terms[i] = types.NewTerm(r.Bool(), r.typ()) + } + return types.NewUnion(terms) +} + +func (r *reader) interfaceType() *types.Interface { + methods := make([]*types.Func, r.Len()) + embeddeds := make([]types.Type, r.Len()) + implicit := len(methods) == 0 && len(embeddeds) == 1 && r.Bool() + + for i := range methods { + pos := r.pos() + pkg, name := r.selector() + mtyp := r.signature(nil, nil, nil) + methods[i] = types.NewFunc(pos, pkg, name, mtyp) + } + + for i := range embeddeds { + embeddeds[i] = r.typ() + } + + iface := types.NewInterfaceType(methods, embeddeds) + if implicit { + iface.MarkImplicit() + } + return iface +} + +func (r *reader) signature(recv *types.Var, rtparams, tparams []*types.TypeParam) *types.Signature { + r.Sync(pkgbits.SyncSignature) + + params := r.params() + results := r.params() + variadic := r.Bool() + + return types.NewSignatureType(recv, rtparams, tparams, params, results, variadic) +} + +func (r *reader) params() *types.Tuple { + r.Sync(pkgbits.SyncParams) + + params := make([]*types.Var, r.Len()) + for i := range params { + params[i] = r.param() + } + + return types.NewTuple(params...) +} + +func (r *reader) param() *types.Var { + r.Sync(pkgbits.SyncParam) + + pos := r.pos() + pkg, name := r.localIdent() + typ := r.typ() + + return types.NewParam(pos, pkg, name, typ) +} + +// @@@ Objects + +func (r *reader) obj() (types.Object, []types.Type) { + r.Sync(pkgbits.SyncObject) + + assert(!r.Bool()) + + pkg, name := r.p.objIdx(r.Reloc(pkgbits.RelocObj)) + obj := pkgScope(pkg).Lookup(name) + + targs := make([]types.Type, r.Len()) + for i := range targs { + targs[i] = r.typ() + } + + return obj, targs +} + +func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) { + rname := pr.newReader(pkgbits.RelocName, idx, pkgbits.SyncObject1) + + objPkg, objName := rname.qualifiedIdent() + assert(objName != "") + + tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj)) + + if tag == pkgbits.ObjStub { + assert(objPkg == nil || objPkg == types.Unsafe) + return objPkg, objName + } + + if objPkg.Scope().Lookup(objName) == nil { + dict := pr.objDictIdx(idx) + + r := pr.newReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1) + r.dict = dict + + declare := func(obj types.Object) { + objPkg.Scope().Insert(obj) + } + + switch tag { + default: + panic("weird") + + case pkgbits.ObjAlias: + pos := r.pos() + typ := r.typ() + declare(types.NewTypeName(pos, objPkg, objName, typ)) + + case pkgbits.ObjConst: + pos := r.pos() + typ := r.typ() + val := r.Value() + declare(types.NewConst(pos, objPkg, objName, typ, val)) + + case pkgbits.ObjFunc: + pos := r.pos() + tparams := r.typeParamNames() + sig := r.signature(nil, nil, tparams) + declare(types.NewFunc(pos, objPkg, objName, sig)) + + case pkgbits.ObjType: + pos := r.pos() + + obj := types.NewTypeName(pos, objPkg, objName, nil) + named := types.NewNamed(obj, nil, nil) + declare(obj) + + named.SetTypeParams(r.typeParamNames()) + + // TODO(mdempsky): Rewrite receiver types to underlying is an + // Interface? The go/types importer does this (I think because + // unit tests expected that), but cmd/compile doesn't care + // about it, so maybe we can avoid worrying about that here. + rhs := r.typ() + r.p.later(func() { + underlying := rhs.Underlying() + named.SetUnderlying(underlying) + }) + + for i, n := 0, r.Len(); i < n; i++ { + named.AddMethod(r.method()) + } + + case pkgbits.ObjVar: + pos := r.pos() + typ := r.typ() + declare(types.NewVar(pos, objPkg, objName, typ)) + } + } + + return objPkg, objName +} + +func (pr *pkgReader) objDictIdx(idx pkgbits.Index) *readerDict { + r := pr.newReader(pkgbits.RelocObjDict, idx, pkgbits.SyncObject1) + + var dict readerDict + + if implicits := r.Len(); implicits != 0 { + errorf("unexpected object with %v implicit type parameter(s)", implicits) + } + + dict.bounds = make([]typeInfo, r.Len()) + for i := range dict.bounds { + dict.bounds[i] = r.typInfo() + } + + dict.derived = make([]derivedInfo, r.Len()) + dict.derivedTypes = make([]types.Type, len(dict.derived)) + for i := range dict.derived { + dict.derived[i] = derivedInfo{r.Reloc(pkgbits.RelocType), r.Bool()} + } + + // function references follow, but reader doesn't need those + + return &dict +} + +func (r *reader) typeParamNames() []*types.TypeParam { + r.Sync(pkgbits.SyncTypeParamNames) + + // Note: This code assumes it only processes objects without + // implement type parameters. This is currently fine, because + // reader is only used to read in exported declarations, which are + // always package scoped. + + if len(r.dict.bounds) == 0 { + return nil + } + + // Careful: Type parameter lists may have cycles. To allow for this, + // we construct the type parameter list in two passes: first we + // create all the TypeNames and TypeParams, then we construct and + // set the bound type. + + r.dict.tparams = make([]*types.TypeParam, len(r.dict.bounds)) + for i := range r.dict.bounds { + pos := r.pos() + pkg, name := r.localIdent() + + tname := types.NewTypeName(pos, pkg, name, nil) + r.dict.tparams[i] = types.NewTypeParam(tname, nil) + } + + typs := make([]types.Type, len(r.dict.bounds)) + for i, bound := range r.dict.bounds { + typs[i] = r.p.typIdx(bound, r.dict) + } + + // TODO(mdempsky): This is subtle, elaborate further. + // + // We have to save tparams outside of the closure, because + // typeParamNames() can be called multiple times with the same + // dictionary instance. + // + // Also, this needs to happen later to make sure SetUnderlying has + // been called. + // + // TODO(mdempsky): Is it safe to have a single "later" slice or do + // we need to have multiple passes? See comments on CL 386002 and + // go.dev/issue/52104. + tparams := r.dict.tparams + r.p.later(func() { + for i, typ := range typs { + tparams[i].SetConstraint(typ) + } + }) + + return r.dict.tparams +} + +func (r *reader) method() *types.Func { + r.Sync(pkgbits.SyncMethod) + pos := r.pos() + pkg, name := r.selector() + + rparams := r.typeParamNames() + sig := r.signature(r.param(), rparams, nil) + + _ = r.pos() // TODO(mdempsky): Remove; this is a hacker for linker.go. + return types.NewFunc(pos, pkg, name, sig) +} + +func (r *reader) qualifiedIdent() (*types.Package, string) { return r.ident(pkgbits.SyncSym) } +func (r *reader) localIdent() (*types.Package, string) { return r.ident(pkgbits.SyncLocalIdent) } +func (r *reader) selector() (*types.Package, string) { return r.ident(pkgbits.SyncSelector) } + +func (r *reader) ident(marker pkgbits.SyncMarker) (*types.Package, string) { + r.Sync(marker) + return r.pkg(), r.String() +} + +// pkgScope returns pkg.Scope(). +// If pkg is nil, it returns types.Universe instead. +// +// TODO(mdempsky): Remove after x/tools can depend on Go 1.19. +func pkgScope(pkg *types.Package) *types.Scope { + if pkg != nil { + return pkg.Scope() + } + return types.Universe +} diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/codes.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/codes.go new file mode 100644 index 00000000..f0cabde9 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/codes.go @@ -0,0 +1,77 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +// A Code is an enum value that can be encoded into bitstreams. +// +// Code types are preferable for enum types, because they allow +// Decoder to detect desyncs. +type Code interface { + // Marker returns the SyncMarker for the Code's dynamic type. + Marker() SyncMarker + + // Value returns the Code's ordinal value. + Value() int +} + +// A CodeVal distinguishes among go/constant.Value encodings. +type CodeVal int + +func (c CodeVal) Marker() SyncMarker { return SyncVal } +func (c CodeVal) Value() int { return int(c) } + +// Note: These values are public and cannot be changed without +// updating the go/types importers. + +const ( + ValBool CodeVal = iota + ValString + ValInt64 + ValBigInt + ValBigRat + ValBigFloat +) + +// A CodeType distinguishes among go/types.Type encodings. +type CodeType int + +func (c CodeType) Marker() SyncMarker { return SyncType } +func (c CodeType) Value() int { return int(c) } + +// Note: These values are public and cannot be changed without +// updating the go/types importers. + +const ( + TypeBasic CodeType = iota + TypeNamed + TypePointer + TypeSlice + TypeArray + TypeChan + TypeMap + TypeSignature + TypeStruct + TypeInterface + TypeUnion + TypeTypeParam +) + +// A CodeObj distinguishes among go/types.Object encodings. +type CodeObj int + +func (c CodeObj) Marker() SyncMarker { return SyncCodeObj } +func (c CodeObj) Value() int { return int(c) } + +// Note: These values are public and cannot be changed without +// updating the go/types importers. + +const ( + ObjAlias CodeObj = iota + ObjConst + ObjType + ObjFunc + ObjVar + ObjStub +) diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/decoder.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/decoder.go new file mode 100644 index 00000000..2bc79366 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/decoder.go @@ -0,0 +1,433 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +import ( + "encoding/binary" + "fmt" + "go/constant" + "go/token" + "math/big" + "os" + "runtime" + "strings" +) + +// A PkgDecoder provides methods for decoding a package's Unified IR +// export data. +type PkgDecoder struct { + // version is the file format version. + version uint32 + + // sync indicates whether the file uses sync markers. + sync bool + + // pkgPath is the package path for the package to be decoded. + // + // TODO(mdempsky): Remove; unneeded since CL 391014. + pkgPath string + + // elemData is the full data payload of the encoded package. + // Elements are densely and contiguously packed together. + // + // The last 8 bytes of elemData are the package fingerprint. + elemData string + + // elemEnds stores the byte-offset end positions of element + // bitstreams within elemData. + // + // For example, element I's bitstream data starts at elemEnds[I-1] + // (or 0, if I==0) and ends at elemEnds[I]. + // + // Note: elemEnds is indexed by absolute indices, not + // section-relative indices. + elemEnds []uint32 + + // elemEndsEnds stores the index-offset end positions of relocation + // sections within elemEnds. + // + // For example, section K's end positions start at elemEndsEnds[K-1] + // (or 0, if K==0) and end at elemEndsEnds[K]. + elemEndsEnds [numRelocs]uint32 +} + +// PkgPath returns the package path for the package +// +// TODO(mdempsky): Remove; unneeded since CL 391014. +func (pr *PkgDecoder) PkgPath() string { return pr.pkgPath } + +// SyncMarkers reports whether pr uses sync markers. +func (pr *PkgDecoder) SyncMarkers() bool { return pr.sync } + +// NewPkgDecoder returns a PkgDecoder initialized to read the Unified +// IR export data from input. pkgPath is the package path for the +// compilation unit that produced the export data. +// +// TODO(mdempsky): Remove pkgPath parameter; unneeded since CL 391014. +func NewPkgDecoder(pkgPath, input string) PkgDecoder { + pr := PkgDecoder{ + pkgPath: pkgPath, + } + + // TODO(mdempsky): Implement direct indexing of input string to + // avoid copying the position information. + + r := strings.NewReader(input) + + assert(binary.Read(r, binary.LittleEndian, &pr.version) == nil) + + switch pr.version { + default: + panic(fmt.Errorf("unsupported version: %v", pr.version)) + case 0: + // no flags + case 1: + var flags uint32 + assert(binary.Read(r, binary.LittleEndian, &flags) == nil) + pr.sync = flags&flagSyncMarkers != 0 + } + + assert(binary.Read(r, binary.LittleEndian, pr.elemEndsEnds[:]) == nil) + + pr.elemEnds = make([]uint32, pr.elemEndsEnds[len(pr.elemEndsEnds)-1]) + assert(binary.Read(r, binary.LittleEndian, pr.elemEnds[:]) == nil) + + pos, err := r.Seek(0, os.SEEK_CUR) + assert(err == nil) + + pr.elemData = input[pos:] + assert(len(pr.elemData)-8 == int(pr.elemEnds[len(pr.elemEnds)-1])) + + return pr +} + +// NumElems returns the number of elements in section k. +func (pr *PkgDecoder) NumElems(k RelocKind) int { + count := int(pr.elemEndsEnds[k]) + if k > 0 { + count -= int(pr.elemEndsEnds[k-1]) + } + return count +} + +// TotalElems returns the total number of elements across all sections. +func (pr *PkgDecoder) TotalElems() int { + return len(pr.elemEnds) +} + +// Fingerprint returns the package fingerprint. +func (pr *PkgDecoder) Fingerprint() [8]byte { + var fp [8]byte + copy(fp[:], pr.elemData[len(pr.elemData)-8:]) + return fp +} + +// AbsIdx returns the absolute index for the given (section, index) +// pair. +func (pr *PkgDecoder) AbsIdx(k RelocKind, idx Index) int { + absIdx := int(idx) + if k > 0 { + absIdx += int(pr.elemEndsEnds[k-1]) + } + if absIdx >= int(pr.elemEndsEnds[k]) { + errorf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds) + } + return absIdx +} + +// DataIdx returns the raw element bitstream for the given (section, +// index) pair. +func (pr *PkgDecoder) DataIdx(k RelocKind, idx Index) string { + absIdx := pr.AbsIdx(k, idx) + + var start uint32 + if absIdx > 0 { + start = pr.elemEnds[absIdx-1] + } + end := pr.elemEnds[absIdx] + + return pr.elemData[start:end] +} + +// StringIdx returns the string value for the given string index. +func (pr *PkgDecoder) StringIdx(idx Index) string { + return pr.DataIdx(RelocString, idx) +} + +// NewDecoder returns a Decoder for the given (section, index) pair, +// and decodes the given SyncMarker from the element bitstream. +func (pr *PkgDecoder) NewDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder { + r := pr.NewDecoderRaw(k, idx) + r.Sync(marker) + return r +} + +// NewDecoderRaw returns a Decoder for the given (section, index) pair. +// +// Most callers should use NewDecoder instead. +func (pr *PkgDecoder) NewDecoderRaw(k RelocKind, idx Index) Decoder { + r := Decoder{ + common: pr, + k: k, + Idx: idx, + } + + // TODO(mdempsky) r.data.Reset(...) after #44505 is resolved. + r.Data = *strings.NewReader(pr.DataIdx(k, idx)) + + r.Sync(SyncRelocs) + r.Relocs = make([]RelocEnt, r.Len()) + for i := range r.Relocs { + r.Sync(SyncReloc) + r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())} + } + + return r +} + +// A Decoder provides methods for decoding an individual element's +// bitstream data. +type Decoder struct { + common *PkgDecoder + + Relocs []RelocEnt + Data strings.Reader + + k RelocKind + Idx Index +} + +func (r *Decoder) checkErr(err error) { + if err != nil { + errorf("unexpected decoding error: %w", err) + } +} + +func (r *Decoder) rawUvarint() uint64 { + x, err := binary.ReadUvarint(&r.Data) + r.checkErr(err) + return x +} + +func (r *Decoder) rawVarint() int64 { + ux := r.rawUvarint() + + // Zig-zag decode. + x := int64(ux >> 1) + if ux&1 != 0 { + x = ^x + } + return x +} + +func (r *Decoder) rawReloc(k RelocKind, idx int) Index { + e := r.Relocs[idx] + assert(e.Kind == k) + return e.Idx +} + +// Sync decodes a sync marker from the element bitstream and asserts +// that it matches the expected marker. +// +// If r.common.sync is false, then Sync is a no-op. +func (r *Decoder) Sync(mWant SyncMarker) { + if !r.common.sync { + return + } + + pos, _ := r.Data.Seek(0, os.SEEK_CUR) // TODO(mdempsky): io.SeekCurrent after #44505 is resolved + mHave := SyncMarker(r.rawUvarint()) + writerPCs := make([]int, r.rawUvarint()) + for i := range writerPCs { + writerPCs[i] = int(r.rawUvarint()) + } + + if mHave == mWant { + return + } + + // There's some tension here between printing: + // + // (1) full file paths that tools can recognize (e.g., so emacs + // hyperlinks the "file:line" text for easy navigation), or + // + // (2) short file paths that are easier for humans to read (e.g., by + // omitting redundant or irrelevant details, so it's easier to + // focus on the useful bits that remain). + // + // The current formatting favors the former, as it seems more + // helpful in practice. But perhaps the formatting could be improved + // to better address both concerns. For example, use relative file + // paths if they would be shorter, or rewrite file paths to contain + // "$GOROOT" (like objabi.AbsFile does) if tools can be taught how + // to reliably expand that again. + + fmt.Printf("export data desync: package %q, section %v, index %v, offset %v\n", r.common.pkgPath, r.k, r.Idx, pos) + + fmt.Printf("\nfound %v, written at:\n", mHave) + if len(writerPCs) == 0 { + fmt.Printf("\t[stack trace unavailable; recompile package %q with -d=syncframes]\n", r.common.pkgPath) + } + for _, pc := range writerPCs { + fmt.Printf("\t%s\n", r.common.StringIdx(r.rawReloc(RelocString, pc))) + } + + fmt.Printf("\nexpected %v, reading at:\n", mWant) + var readerPCs [32]uintptr // TODO(mdempsky): Dynamically size? + n := runtime.Callers(2, readerPCs[:]) + for _, pc := range fmtFrames(readerPCs[:n]...) { + fmt.Printf("\t%s\n", pc) + } + + // We already printed a stack trace for the reader, so now we can + // simply exit. Printing a second one with panic or base.Fatalf + // would just be noise. + os.Exit(1) +} + +// Bool decodes and returns a bool value from the element bitstream. +func (r *Decoder) Bool() bool { + r.Sync(SyncBool) + x, err := r.Data.ReadByte() + r.checkErr(err) + assert(x < 2) + return x != 0 +} + +// Int64 decodes and returns an int64 value from the element bitstream. +func (r *Decoder) Int64() int64 { + r.Sync(SyncInt64) + return r.rawVarint() +} + +// Int64 decodes and returns a uint64 value from the element bitstream. +func (r *Decoder) Uint64() uint64 { + r.Sync(SyncUint64) + return r.rawUvarint() +} + +// Len decodes and returns a non-negative int value from the element bitstream. +func (r *Decoder) Len() int { x := r.Uint64(); v := int(x); assert(uint64(v) == x); return v } + +// Int decodes and returns an int value from the element bitstream. +func (r *Decoder) Int() int { x := r.Int64(); v := int(x); assert(int64(v) == x); return v } + +// Uint decodes and returns a uint value from the element bitstream. +func (r *Decoder) Uint() uint { x := r.Uint64(); v := uint(x); assert(uint64(v) == x); return v } + +// Code decodes a Code value from the element bitstream and returns +// its ordinal value. It's the caller's responsibility to convert the +// result to an appropriate Code type. +// +// TODO(mdempsky): Ideally this method would have signature "Code[T +// Code] T" instead, but we don't allow generic methods and the +// compiler can't depend on generics yet anyway. +func (r *Decoder) Code(mark SyncMarker) int { + r.Sync(mark) + return r.Len() +} + +// Reloc decodes a relocation of expected section k from the element +// bitstream and returns an index to the referenced element. +func (r *Decoder) Reloc(k RelocKind) Index { + r.Sync(SyncUseReloc) + return r.rawReloc(k, r.Len()) +} + +// String decodes and returns a string value from the element +// bitstream. +func (r *Decoder) String() string { + r.Sync(SyncString) + return r.common.StringIdx(r.Reloc(RelocString)) +} + +// Strings decodes and returns a variable-length slice of strings from +// the element bitstream. +func (r *Decoder) Strings() []string { + res := make([]string, r.Len()) + for i := range res { + res[i] = r.String() + } + return res +} + +// Value decodes and returns a constant.Value from the element +// bitstream. +func (r *Decoder) Value() constant.Value { + r.Sync(SyncValue) + isComplex := r.Bool() + val := r.scalar() + if isComplex { + val = constant.BinaryOp(val, token.ADD, constant.MakeImag(r.scalar())) + } + return val +} + +func (r *Decoder) scalar() constant.Value { + switch tag := CodeVal(r.Code(SyncVal)); tag { + default: + panic(fmt.Errorf("unexpected scalar tag: %v", tag)) + + case ValBool: + return constant.MakeBool(r.Bool()) + case ValString: + return constant.MakeString(r.String()) + case ValInt64: + return constant.MakeInt64(r.Int64()) + case ValBigInt: + return constant.Make(r.bigInt()) + case ValBigRat: + num := r.bigInt() + denom := r.bigInt() + return constant.Make(new(big.Rat).SetFrac(num, denom)) + case ValBigFloat: + return constant.Make(r.bigFloat()) + } +} + +func (r *Decoder) bigInt() *big.Int { + v := new(big.Int).SetBytes([]byte(r.String())) + if r.Bool() { + v.Neg(v) + } + return v +} + +func (r *Decoder) bigFloat() *big.Float { + v := new(big.Float).SetPrec(512) + assert(v.UnmarshalText([]byte(r.String())) == nil) + return v +} + +// @@@ Helpers + +// TODO(mdempsky): These should probably be removed. I think they're a +// smell that the export data format is not yet quite right. + +// PeekPkgPath returns the package path for the specified package +// index. +func (pr *PkgDecoder) PeekPkgPath(idx Index) string { + r := pr.NewDecoder(RelocPkg, idx, SyncPkgDef) + path := r.String() + if path == "" { + path = pr.pkgPath + } + return path +} + +// PeekObj returns the package path, object name, and CodeObj for the +// specified object index. +func (pr *PkgDecoder) PeekObj(idx Index) (string, string, CodeObj) { + r := pr.NewDecoder(RelocName, idx, SyncObject1) + r.Sync(SyncSym) + r.Sync(SyncPkg) + path := pr.PeekPkgPath(r.Reloc(RelocPkg)) + name := r.String() + assert(name != "") + + tag := CodeObj(r.Code(SyncCodeObj)) + + return path, name, tag +} diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/doc.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/doc.go new file mode 100644 index 00000000..c8a2796b --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/doc.go @@ -0,0 +1,32 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package pkgbits implements low-level coding abstractions for +// Unified IR's export data format. +// +// At a low-level, a package is a collection of bitstream elements. +// Each element has a "kind" and a dense, non-negative index. +// Elements can be randomly accessed given their kind and index. +// +// Individual elements are sequences of variable-length values (e.g., +// integers, booleans, strings, go/constant values, cross-references +// to other elements). Package pkgbits provides APIs for encoding and +// decoding these low-level values, but the details of mapping +// higher-level Go constructs into elements is left to higher-level +// abstractions. +// +// Elements may cross-reference each other with "relocations." For +// example, an element representing a pointer type has a relocation +// referring to the element type. +// +// Go constructs may be composed as a constellation of multiple +// elements. For example, a declared function may have one element to +// describe the object (e.g., its name, type, position), and a +// separate element to describe its function body. This allows readers +// some flexibility in efficiently seeking or re-reading data (e.g., +// inlining requires re-reading the function body for each inlined +// call, without needing to re-read the object-level details). +// +// This is a copy of internal/pkgbits in the Go implementation. +package pkgbits diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/encoder.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/encoder.go new file mode 100644 index 00000000..c50c838c --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/encoder.go @@ -0,0 +1,379 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +import ( + "bytes" + "crypto/md5" + "encoding/binary" + "go/constant" + "io" + "math/big" + "runtime" +) + +// currentVersion is the current version number. +// +// - v0: initial prototype +// +// - v1: adds the flags uint32 word +const currentVersion uint32 = 1 + +// A PkgEncoder provides methods for encoding a package's Unified IR +// export data. +type PkgEncoder struct { + // elems holds the bitstream for previously encoded elements. + elems [numRelocs][]string + + // stringsIdx maps previously encoded strings to their index within + // the RelocString section, to allow deduplication. That is, + // elems[RelocString][stringsIdx[s]] == s (if present). + stringsIdx map[string]Index + + // syncFrames is the number of frames to write at each sync + // marker. A negative value means sync markers are omitted. + syncFrames int +} + +// SyncMarkers reports whether pw uses sync markers. +func (pw *PkgEncoder) SyncMarkers() bool { return pw.syncFrames >= 0 } + +// NewPkgEncoder returns an initialized PkgEncoder. +// +// syncFrames is the number of caller frames that should be serialized +// at Sync points. Serializing additional frames results in larger +// export data files, but can help diagnosing desync errors in +// higher-level Unified IR reader/writer code. If syncFrames is +// negative, then sync markers are omitted entirely. +func NewPkgEncoder(syncFrames int) PkgEncoder { + return PkgEncoder{ + stringsIdx: make(map[string]Index), + syncFrames: syncFrames, + } +} + +// DumpTo writes the package's encoded data to out0 and returns the +// package fingerprint. +func (pw *PkgEncoder) DumpTo(out0 io.Writer) (fingerprint [8]byte) { + h := md5.New() + out := io.MultiWriter(out0, h) + + writeUint32 := func(x uint32) { + assert(binary.Write(out, binary.LittleEndian, x) == nil) + } + + writeUint32(currentVersion) + + var flags uint32 + if pw.SyncMarkers() { + flags |= flagSyncMarkers + } + writeUint32(flags) + + // Write elemEndsEnds. + var sum uint32 + for _, elems := range &pw.elems { + sum += uint32(len(elems)) + writeUint32(sum) + } + + // Write elemEnds. + sum = 0 + for _, elems := range &pw.elems { + for _, elem := range elems { + sum += uint32(len(elem)) + writeUint32(sum) + } + } + + // Write elemData. + for _, elems := range &pw.elems { + for _, elem := range elems { + _, err := io.WriteString(out, elem) + assert(err == nil) + } + } + + // Write fingerprint. + copy(fingerprint[:], h.Sum(nil)) + _, err := out0.Write(fingerprint[:]) + assert(err == nil) + + return +} + +// StringIdx adds a string value to the strings section, if not +// already present, and returns its index. +func (pw *PkgEncoder) StringIdx(s string) Index { + if idx, ok := pw.stringsIdx[s]; ok { + assert(pw.elems[RelocString][idx] == s) + return idx + } + + idx := Index(len(pw.elems[RelocString])) + pw.elems[RelocString] = append(pw.elems[RelocString], s) + pw.stringsIdx[s] = idx + return idx +} + +// NewEncoder returns an Encoder for a new element within the given +// section, and encodes the given SyncMarker as the start of the +// element bitstream. +func (pw *PkgEncoder) NewEncoder(k RelocKind, marker SyncMarker) Encoder { + e := pw.NewEncoderRaw(k) + e.Sync(marker) + return e +} + +// NewEncoderRaw returns an Encoder for a new element within the given +// section. +// +// Most callers should use NewEncoder instead. +func (pw *PkgEncoder) NewEncoderRaw(k RelocKind) Encoder { + idx := Index(len(pw.elems[k])) + pw.elems[k] = append(pw.elems[k], "") // placeholder + + return Encoder{ + p: pw, + k: k, + Idx: idx, + } +} + +// An Encoder provides methods for encoding an individual element's +// bitstream data. +type Encoder struct { + p *PkgEncoder + + Relocs []RelocEnt + Data bytes.Buffer // accumulated element bitstream data + + encodingRelocHeader bool + + k RelocKind + Idx Index // index within relocation section +} + +// Flush finalizes the element's bitstream and returns its Index. +func (w *Encoder) Flush() Index { + var sb bytes.Buffer // TODO(mdempsky): strings.Builder after #44505 is resolved + + // Backup the data so we write the relocations at the front. + var tmp bytes.Buffer + io.Copy(&tmp, &w.Data) + + // TODO(mdempsky): Consider writing these out separately so they're + // easier to strip, along with function bodies, so that we can prune + // down to just the data that's relevant to go/types. + if w.encodingRelocHeader { + panic("encodingRelocHeader already true; recursive flush?") + } + w.encodingRelocHeader = true + w.Sync(SyncRelocs) + w.Len(len(w.Relocs)) + for _, rEnt := range w.Relocs { + w.Sync(SyncReloc) + w.Len(int(rEnt.Kind)) + w.Len(int(rEnt.Idx)) + } + + io.Copy(&sb, &w.Data) + io.Copy(&sb, &tmp) + w.p.elems[w.k][w.Idx] = sb.String() + + return w.Idx +} + +func (w *Encoder) checkErr(err error) { + if err != nil { + errorf("unexpected encoding error: %v", err) + } +} + +func (w *Encoder) rawUvarint(x uint64) { + var buf [binary.MaxVarintLen64]byte + n := binary.PutUvarint(buf[:], x) + _, err := w.Data.Write(buf[:n]) + w.checkErr(err) +} + +func (w *Encoder) rawVarint(x int64) { + // Zig-zag encode. + ux := uint64(x) << 1 + if x < 0 { + ux = ^ux + } + + w.rawUvarint(ux) +} + +func (w *Encoder) rawReloc(r RelocKind, idx Index) int { + // TODO(mdempsky): Use map for lookup; this takes quadratic time. + for i, rEnt := range w.Relocs { + if rEnt.Kind == r && rEnt.Idx == idx { + return i + } + } + + i := len(w.Relocs) + w.Relocs = append(w.Relocs, RelocEnt{r, idx}) + return i +} + +func (w *Encoder) Sync(m SyncMarker) { + if !w.p.SyncMarkers() { + return + } + + // Writing out stack frame string references requires working + // relocations, but writing out the relocations themselves involves + // sync markers. To prevent infinite recursion, we simply trim the + // stack frame for sync markers within the relocation header. + var frames []string + if !w.encodingRelocHeader && w.p.syncFrames > 0 { + pcs := make([]uintptr, w.p.syncFrames) + n := runtime.Callers(2, pcs) + frames = fmtFrames(pcs[:n]...) + } + + // TODO(mdempsky): Save space by writing out stack frames as a + // linked list so we can share common stack frames. + w.rawUvarint(uint64(m)) + w.rawUvarint(uint64(len(frames))) + for _, frame := range frames { + w.rawUvarint(uint64(w.rawReloc(RelocString, w.p.StringIdx(frame)))) + } +} + +// Bool encodes and writes a bool value into the element bitstream, +// and then returns the bool value. +// +// For simple, 2-alternative encodings, the idiomatic way to call Bool +// is something like: +// +// if w.Bool(x != 0) { +// // alternative #1 +// } else { +// // alternative #2 +// } +// +// For multi-alternative encodings, use Code instead. +func (w *Encoder) Bool(b bool) bool { + w.Sync(SyncBool) + var x byte + if b { + x = 1 + } + err := w.Data.WriteByte(x) + w.checkErr(err) + return b +} + +// Int64 encodes and writes an int64 value into the element bitstream. +func (w *Encoder) Int64(x int64) { + w.Sync(SyncInt64) + w.rawVarint(x) +} + +// Uint64 encodes and writes a uint64 value into the element bitstream. +func (w *Encoder) Uint64(x uint64) { + w.Sync(SyncUint64) + w.rawUvarint(x) +} + +// Len encodes and writes a non-negative int value into the element bitstream. +func (w *Encoder) Len(x int) { assert(x >= 0); w.Uint64(uint64(x)) } + +// Int encodes and writes an int value into the element bitstream. +func (w *Encoder) Int(x int) { w.Int64(int64(x)) } + +// Len encodes and writes a uint value into the element bitstream. +func (w *Encoder) Uint(x uint) { w.Uint64(uint64(x)) } + +// Reloc encodes and writes a relocation for the given (section, +// index) pair into the element bitstream. +// +// Note: Only the index is formally written into the element +// bitstream, so bitstream decoders must know from context which +// section an encoded relocation refers to. +func (w *Encoder) Reloc(r RelocKind, idx Index) { + w.Sync(SyncUseReloc) + w.Len(w.rawReloc(r, idx)) +} + +// Code encodes and writes a Code value into the element bitstream. +func (w *Encoder) Code(c Code) { + w.Sync(c.Marker()) + w.Len(c.Value()) +} + +// String encodes and writes a string value into the element +// bitstream. +// +// Internally, strings are deduplicated by adding them to the strings +// section (if not already present), and then writing a relocation +// into the element bitstream. +func (w *Encoder) String(s string) { + w.Sync(SyncString) + w.Reloc(RelocString, w.p.StringIdx(s)) +} + +// Strings encodes and writes a variable-length slice of strings into +// the element bitstream. +func (w *Encoder) Strings(ss []string) { + w.Len(len(ss)) + for _, s := range ss { + w.String(s) + } +} + +// Value encodes and writes a constant.Value into the element +// bitstream. +func (w *Encoder) Value(val constant.Value) { + w.Sync(SyncValue) + if w.Bool(val.Kind() == constant.Complex) { + w.scalar(constant.Real(val)) + w.scalar(constant.Imag(val)) + } else { + w.scalar(val) + } +} + +func (w *Encoder) scalar(val constant.Value) { + switch v := constant.Val(val).(type) { + default: + errorf("unhandled %v (%v)", val, val.Kind()) + case bool: + w.Code(ValBool) + w.Bool(v) + case string: + w.Code(ValString) + w.String(v) + case int64: + w.Code(ValInt64) + w.Int64(v) + case *big.Int: + w.Code(ValBigInt) + w.bigInt(v) + case *big.Rat: + w.Code(ValBigRat) + w.bigInt(v.Num()) + w.bigInt(v.Denom()) + case *big.Float: + w.Code(ValBigFloat) + w.bigFloat(v) + } +} + +func (w *Encoder) bigInt(v *big.Int) { + b := v.Bytes() + w.String(string(b)) // TODO: More efficient encoding. + w.Bool(v.Sign() < 0) +} + +func (w *Encoder) bigFloat(v *big.Float) { + b := v.Append(nil, 'p', -1) + w.String(string(b)) // TODO: More efficient encoding. +} diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/flags.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/flags.go new file mode 100644 index 00000000..65422274 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/flags.go @@ -0,0 +1,9 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +const ( + flagSyncMarkers = 1 << iota // file format contains sync markers +) diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/frames_go1.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/frames_go1.go new file mode 100644 index 00000000..5294f6a6 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/frames_go1.go @@ -0,0 +1,21 @@ +// 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.7 +// +build !go1.7 + +// TODO(mdempsky): Remove after #44505 is resolved + +package pkgbits + +import "runtime" + +func walkFrames(pcs []uintptr, visit frameVisitor) { + for _, pc := range pcs { + fn := runtime.FuncForPC(pc) + file, line := fn.FileLine(pc) + + visit(file, line, fn.Name(), pc-fn.Entry()) + } +} diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/frames_go17.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/frames_go17.go new file mode 100644 index 00000000..2324ae7a --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/frames_go17.go @@ -0,0 +1,28 @@ +// 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.7 +// +build go1.7 + +package pkgbits + +import "runtime" + +// walkFrames calls visit for each call frame represented by pcs. +// +// pcs should be a slice of PCs, as returned by runtime.Callers. +func walkFrames(pcs []uintptr, visit frameVisitor) { + if len(pcs) == 0 { + return + } + + frames := runtime.CallersFrames(pcs) + for { + frame, more := frames.Next() + visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry) + if !more { + return + } + } +} diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/reloc.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/reloc.go new file mode 100644 index 00000000..7a8f04ab --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/reloc.go @@ -0,0 +1,42 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +// A RelocKind indicates a particular section within a unified IR export. +type RelocKind int + +// An Index represents a bitstream element index within a particular +// section. +type Index int + +// A relocEnt (relocation entry) is an entry in an element's local +// reference table. +// +// TODO(mdempsky): Rename this too. +type RelocEnt struct { + Kind RelocKind + Idx Index +} + +// Reserved indices within the meta relocation section. +const ( + PublicRootIdx Index = 0 + PrivateRootIdx Index = 1 +) + +const ( + RelocString RelocKind = iota + RelocMeta + RelocPosBase + RelocPkg + RelocName + RelocType + RelocObj + RelocObjExt + RelocObjDict + RelocBody + + numRelocs = iota +) diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/support.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/support.go new file mode 100644 index 00000000..ad26d3b2 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/support.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +import "fmt" + +func assert(b bool) { + if !b { + panic("assertion failed") + } +} + +func errorf(format string, args ...interface{}) { + panic(fmt.Errorf(format, args...)) +} diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/sync.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/sync.go new file mode 100644 index 00000000..5bd51ef7 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/sync.go @@ -0,0 +1,113 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkgbits + +import ( + "fmt" + "strings" +) + +// fmtFrames formats a backtrace for reporting reader/writer desyncs. +func fmtFrames(pcs ...uintptr) []string { + res := make([]string, 0, len(pcs)) + walkFrames(pcs, func(file string, line int, name string, offset uintptr) { + // Trim package from function name. It's just redundant noise. + name = strings.TrimPrefix(name, "cmd/compile/internal/noder.") + + res = append(res, fmt.Sprintf("%s:%v: %s +0x%v", file, line, name, offset)) + }) + return res +} + +type frameVisitor func(file string, line int, name string, offset uintptr) + +// SyncMarker is an enum type that represents markers that may be +// written to export data to ensure the reader and writer stay +// synchronized. +type SyncMarker int + +//go:generate stringer -type=SyncMarker -trimprefix=Sync + +const ( + _ SyncMarker = iota + + // Public markers (known to go/types importers). + + // Low-level coding markers. + SyncEOF + SyncBool + SyncInt64 + SyncUint64 + SyncString + SyncValue + SyncVal + SyncRelocs + SyncReloc + SyncUseReloc + + // Higher-level object and type markers. + SyncPublic + SyncPos + SyncPosBase + SyncObject + SyncObject1 + SyncPkg + SyncPkgDef + SyncMethod + SyncType + SyncTypeIdx + SyncTypeParamNames + SyncSignature + SyncParams + SyncParam + SyncCodeObj + SyncSym + SyncLocalIdent + SyncSelector + + // Private markers (only known to cmd/compile). + SyncPrivate + + SyncFuncExt + SyncVarExt + SyncTypeExt + SyncPragma + + SyncExprList + SyncExprs + SyncExpr + SyncExprType + SyncAssign + SyncOp + SyncFuncLit + SyncCompLit + + SyncDecl + SyncFuncBody + SyncOpenScope + SyncCloseScope + SyncCloseAnotherScope + SyncDeclNames + SyncDeclName + + SyncStmts + SyncBlockStmt + SyncIfStmt + SyncForStmt + SyncSwitchStmt + SyncRangeStmt + SyncCaseClause + SyncCommClause + SyncSelectStmt + SyncDecls + SyncLabeledStmt + SyncUseObjLocal + SyncAddLocal + SyncLinkname + SyncStmt1 + SyncStmtsEnd + SyncLabel + SyncOptLabel +) diff --git a/tools/vendor/golang.org/x/tools/go/internal/pkgbits/syncmarker_string.go b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/syncmarker_string.go new file mode 100644 index 00000000..4a5b0ca5 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/internal/pkgbits/syncmarker_string.go @@ -0,0 +1,89 @@ +// Code generated by "stringer -type=SyncMarker -trimprefix=Sync"; DO NOT EDIT. + +package pkgbits + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[SyncEOF-1] + _ = x[SyncBool-2] + _ = x[SyncInt64-3] + _ = x[SyncUint64-4] + _ = x[SyncString-5] + _ = x[SyncValue-6] + _ = x[SyncVal-7] + _ = x[SyncRelocs-8] + _ = x[SyncReloc-9] + _ = x[SyncUseReloc-10] + _ = x[SyncPublic-11] + _ = x[SyncPos-12] + _ = x[SyncPosBase-13] + _ = x[SyncObject-14] + _ = x[SyncObject1-15] + _ = x[SyncPkg-16] + _ = x[SyncPkgDef-17] + _ = x[SyncMethod-18] + _ = x[SyncType-19] + _ = x[SyncTypeIdx-20] + _ = x[SyncTypeParamNames-21] + _ = x[SyncSignature-22] + _ = x[SyncParams-23] + _ = x[SyncParam-24] + _ = x[SyncCodeObj-25] + _ = x[SyncSym-26] + _ = x[SyncLocalIdent-27] + _ = x[SyncSelector-28] + _ = x[SyncPrivate-29] + _ = x[SyncFuncExt-30] + _ = x[SyncVarExt-31] + _ = x[SyncTypeExt-32] + _ = x[SyncPragma-33] + _ = x[SyncExprList-34] + _ = x[SyncExprs-35] + _ = x[SyncExpr-36] + _ = x[SyncExprType-37] + _ = x[SyncAssign-38] + _ = x[SyncOp-39] + _ = x[SyncFuncLit-40] + _ = x[SyncCompLit-41] + _ = x[SyncDecl-42] + _ = x[SyncFuncBody-43] + _ = x[SyncOpenScope-44] + _ = x[SyncCloseScope-45] + _ = x[SyncCloseAnotherScope-46] + _ = x[SyncDeclNames-47] + _ = x[SyncDeclName-48] + _ = x[SyncStmts-49] + _ = x[SyncBlockStmt-50] + _ = x[SyncIfStmt-51] + _ = x[SyncForStmt-52] + _ = x[SyncSwitchStmt-53] + _ = x[SyncRangeStmt-54] + _ = x[SyncCaseClause-55] + _ = x[SyncCommClause-56] + _ = x[SyncSelectStmt-57] + _ = x[SyncDecls-58] + _ = x[SyncLabeledStmt-59] + _ = x[SyncUseObjLocal-60] + _ = x[SyncAddLocal-61] + _ = x[SyncLinkname-62] + _ = x[SyncStmt1-63] + _ = x[SyncStmtsEnd-64] + _ = x[SyncLabel-65] + _ = x[SyncOptLabel-66] +} + +const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabel" + +var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458} + +func (i SyncMarker) String() string { + i -= 1 + if i < 0 || i >= SyncMarker(len(_SyncMarker_index)-1) { + return "SyncMarker(" + strconv.FormatInt(int64(i+1), 10) + ")" + } + return _SyncMarker_name[_SyncMarker_index[i]:_SyncMarker_index[i+1]] +} diff --git a/tools/vendor/golang.org/x/tools/go/loader/doc.go b/tools/vendor/golang.org/x/tools/go/loader/doc.go index c5aa31c1..e35b1fd7 100644 --- a/tools/vendor/golang.org/x/tools/go/loader/doc.go +++ b/tools/vendor/golang.org/x/tools/go/loader/doc.go @@ -20,36 +20,35 @@ // be called any number of times. Finally, these are followed by a // call to Load() to actually load and type-check the program. // -// var conf loader.Config +// var conf loader.Config // -// // Use the command-line arguments to specify -// // a set of initial packages to load from source. -// // See FromArgsUsage for help. -// rest, err := conf.FromArgs(os.Args[1:], wantTests) +// // Use the command-line arguments to specify +// // a set of initial packages to load from source. +// // See FromArgsUsage for help. +// rest, err := conf.FromArgs(os.Args[1:], wantTests) // -// // Parse the specified files and create an ad hoc package with path "foo". -// // All files must have the same 'package' declaration. -// conf.CreateFromFilenames("foo", "foo.go", "bar.go") +// // Parse the specified files and create an ad hoc package with path "foo". +// // All files must have the same 'package' declaration. +// conf.CreateFromFilenames("foo", "foo.go", "bar.go") // -// // Create an ad hoc package with path "foo" from -// // the specified already-parsed files. -// // All ASTs must have the same 'package' declaration. -// conf.CreateFromFiles("foo", parsedFiles) +// // Create an ad hoc package with path "foo" from +// // the specified already-parsed files. +// // All ASTs must have the same 'package' declaration. +// conf.CreateFromFiles("foo", parsedFiles) // -// // Add "runtime" to the set of packages to be loaded. -// conf.Import("runtime") +// // Add "runtime" to the set of packages to be loaded. +// conf.Import("runtime") // -// // Adds "fmt" and "fmt_test" to the set of packages -// // to be loaded. "fmt" will include *_test.go files. -// conf.ImportWithTests("fmt") +// // Adds "fmt" and "fmt_test" to the set of packages +// // to be loaded. "fmt" will include *_test.go files. +// conf.ImportWithTests("fmt") // -// // Finally, load all the packages specified by the configuration. -// prog, err := conf.Load() +// // Finally, load all the packages specified by the configuration. +// prog, err := conf.Load() // // See examples_test.go for examples of API usage. // -// -// CONCEPTS AND TERMINOLOGY +// # CONCEPTS AND TERMINOLOGY // // The WORKSPACE is the set of packages accessible to the loader. The // workspace is defined by Config.Build, a *build.Context. The @@ -92,7 +91,6 @@ // The INITIAL packages are those specified in the configuration. A // DEPENDENCY is a package loaded to satisfy an import in an initial // package or another dependency. -// package loader // IMPLEMENTATION NOTES 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 3ba91f7c..edf62c2c 100644 --- a/tools/vendor/golang.org/x/tools/go/loader/loader.go +++ b/tools/vendor/golang.org/x/tools/go/loader/loader.go @@ -179,7 +179,6 @@ type Program struct { // for a single package. // // Not mutated once exposed via the API. -// type PackageInfo struct { Pkg *types.Package Importable bool // true if 'import "Pkg.Path()"' would resolve to this @@ -217,7 +216,6 @@ func (conf *Config) fset() *token.FileSet { // src specifies the parser input as a string, []byte, or io.Reader, and // filename is its apparent name. If src is nil, the contents of // filename are read from the file system. -// func (conf *Config) ParseFile(filename string, src interface{}) (*ast.File, error) { // TODO(adonovan): use conf.build() etc like parseFiles does. return parser.ParseFile(conf.fset(), filename, src, conf.ParserMode) @@ -262,7 +260,6 @@ A '--' argument terminates the list of packages. // // Only superficial errors are reported at this stage; errors dependent // on I/O are detected during Load. -// func (conf *Config) FromArgs(args []string, xtest bool) ([]string, error) { var rest []string for i, arg := range args { @@ -300,14 +297,12 @@ func (conf *Config) FromArgs(args []string, xtest bool) ([]string, error) { // CreateFromFilenames is a convenience function that adds // a conf.CreatePkgs entry to create a package of the specified *.go // files. -// func (conf *Config) CreateFromFilenames(path string, filenames ...string) { conf.CreatePkgs = append(conf.CreatePkgs, PkgSpec{Path: path, Filenames: filenames}) } // CreateFromFiles is a convenience function that adds a conf.CreatePkgs // entry to create package of the specified path and parsed files. -// func (conf *Config) CreateFromFiles(path string, files ...*ast.File) { conf.CreatePkgs = append(conf.CreatePkgs, PkgSpec{Path: path, Files: files}) } @@ -321,12 +316,10 @@ func (conf *Config) CreateFromFiles(path string, files ...*ast.File) { // In addition, if any *_test.go files contain a "package x_test" // declaration, an additional package comprising just those files will // be added to CreatePkgs. -// func (conf *Config) ImportWithTests(path string) { conf.addImport(path, true) } // Import is a convenience function that adds path to ImportPkgs, the // set of initial packages that will be imported from source. -// func (conf *Config) Import(path string) { conf.addImport(path, false) } func (conf *Config) addImport(path string, tests bool) { @@ -345,7 +338,6 @@ func (conf *Config) addImport(path string, tests bool) { // exact is defined as for astutil.PathEnclosingInterval. // // The zero value is returned if not found. -// func (prog *Program) PathEnclosingInterval(start, end token.Pos) (pkg *PackageInfo, path []ast.Node, exact bool) { for _, info := range prog.AllPackages { for _, f := range info.Files { @@ -368,7 +360,6 @@ func (prog *Program) PathEnclosingInterval(start, end token.Pos) (pkg *PackageIn // InitialPackages returns a new slice containing the set of initial // packages (Created + Imported) in unspecified order. -// func (prog *Program) InitialPackages() []*PackageInfo { infos := make([]*PackageInfo, 0, len(prog.Created)+len(prog.Imported)) infos = append(infos, prog.Created...) @@ -435,7 +426,6 @@ type findpkgValue struct { // Upon completion, exactly one of info and err is non-nil: // info on successful creation of a package, err otherwise. // A successful package may still contain type errors. -// type importInfo struct { path string // import path info *PackageInfo // results of typechecking (including errors) @@ -475,7 +465,6 @@ type importError struct { // false, Load will fail if any package had an error. // // It is an error if no packages were loaded. -// func (conf *Config) Load() (*Program, error) { // Create a simple default error handler for parse/type errors. if conf.TypeChecker.Error == nil { @@ -732,10 +721,10 @@ func (conf *Config) build() *build.Context { // errors that were encountered. // // 'which' indicates which files to include: -// 'g': include non-test *.go source files (GoFiles + processed CgoFiles) -// 't': include in-package *_test.go source files (TestGoFiles) -// 'x': include external *_test.go source files. (XTestGoFiles) // +// 'g': include non-test *.go source files (GoFiles + processed CgoFiles) +// 't': include in-package *_test.go source files (TestGoFiles) +// 'x': include external *_test.go source files. (XTestGoFiles) func (conf *Config) parsePackageFiles(bp *build.Package, which rune) ([]*ast.File, []error) { if bp.ImportPath == "unsafe" { return nil, nil @@ -776,7 +765,6 @@ func (conf *Config) parsePackageFiles(bp *build.Package, which rune) ([]*ast.Fil // in the package's PackageInfo). // // Idempotent. -// func (imp *importer) doImport(from *PackageInfo, to string) (*types.Package, error) { if to == "C" { // This should be unreachable, but ad hoc packages are @@ -868,7 +856,6 @@ func (imp *importer) findPackage(importPath, fromDir string, mode build.ImportMo // // fromDir is the directory containing the import declaration that // caused these imports. -// func (imp *importer) importAll(fromPath, fromDir string, imports map[string]bool, mode build.ImportMode) (infos []*PackageInfo, errors []importError) { if fromPath != "" { // We're loading a set of imports. @@ -951,7 +938,6 @@ func (imp *importer) findPath(from, to string) []string { // caller must call awaitCompletion() before accessing its info field. // // startLoad is concurrency-safe and idempotent. -// func (imp *importer) startLoad(bp *build.Package) *importInfo { path := bp.ImportPath imp.importedMu.Lock() @@ -995,7 +981,6 @@ func (imp *importer) load(bp *build.Package) *PackageInfo { // // cycleCheck determines whether the imports within files create // dependency edges that should be checked for potential cycles. -// func (imp *importer) addFiles(info *PackageInfo, files []*ast.File, cycleCheck bool) { // Ensure the dependencies are loaded, in parallel. var fromPath string diff --git a/tools/vendor/golang.org/x/tools/go/loader/util.go b/tools/vendor/golang.org/x/tools/go/loader/util.go index 7f38dd74..3a80acae 100644 --- a/tools/vendor/golang.org/x/tools/go/loader/util.go +++ b/tools/vendor/golang.org/x/tools/go/loader/util.go @@ -27,7 +27,6 @@ var ioLimit = make(chan bool, 10) // // I/O is done via ctxt, which may specify a virtual file system. // displayPath is used to transform the filenames attached to the ASTs. -// func parseFiles(fset *token.FileSet, ctxt *build.Context, displayPath func(string) string, dir string, files []string, mode parser.Mode) ([]*ast.File, []error) { if displayPath == nil { displayPath = func(path string) string { return path } 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 4bfe28a5..da4ab89f 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/doc.go +++ b/tools/vendor/golang.org/x/tools/go/packages/doc.go @@ -67,7 +67,6 @@ Most tools should pass their command-line arguments (after any flags) uninterpreted to the loader, so that the loader can interpret them according to the conventions of the underlying build system. See the Example function for typical usage. - */ package packages // import "golang.org/x/tools/go/packages" 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 0e1e7f11..de881562 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/golist.go +++ b/tools/vendor/golang.org/x/tools/go/packages/golist.go @@ -26,7 +26,6 @@ import ( "golang.org/x/tools/go/internal/packagesdriver" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/packagesinternal" - "golang.org/x/xerrors" ) // debug controls verbose logging. @@ -303,11 +302,12 @@ func (state *golistState) runContainsQueries(response *responseDeduper, queries } dirResponse, err := state.createDriverResponse(pattern) - // If there was an error loading the package, or the package is returned - // with errors, try to load the file as an ad-hoc package. + // If there was an error loading the package, or no packages are returned, + // or the package is returned with errors, try to load the file as an + // ad-hoc package. // Usually the error will appear in a returned package, but may not if we're // in module mode and the ad-hoc is located outside a module. - if err != nil || len(dirResponse.Packages) == 1 && len(dirResponse.Packages[0].GoFiles) == 0 && + if err != nil || len(dirResponse.Packages) == 0 || len(dirResponse.Packages) == 1 && len(dirResponse.Packages[0].GoFiles) == 0 && len(dirResponse.Packages[0].Errors) == 1 { var queryErr error if dirResponse, queryErr = state.adhocPackage(pattern, query); queryErr != nil { @@ -393,6 +393,8 @@ type jsonPackage struct { CompiledGoFiles []string IgnoredGoFiles []string IgnoredOtherFiles []string + EmbedPatterns []string + EmbedFiles []string CFiles []string CgoFiles []string CXXFiles []string @@ -444,7 +446,11 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse // Run "go list" for complete // information on the specified packages. - buf, err := state.invokeGo("list", golistargs(state.cfg, words)...) + goVersion, err := state.getGoVersion() + if err != nil { + return nil, err + } + buf, err := state.invokeGo("list", golistargs(state.cfg, words, goVersion)...) if err != nil { return nil, err } @@ -565,6 +571,8 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse GoFiles: absJoin(p.Dir, p.GoFiles, p.CgoFiles), CompiledGoFiles: absJoin(p.Dir, p.CompiledGoFiles), OtherFiles: absJoin(p.Dir, otherFiles(p)...), + EmbedFiles: absJoin(p.Dir, p.EmbedFiles), + EmbedPatterns: absJoin(p.Dir, p.EmbedPatterns), IgnoredFiles: absJoin(p.Dir, p.IgnoredGoFiles, p.IgnoredOtherFiles), forTest: p.ForTest, depsErrors: p.DepsErrors, @@ -805,17 +813,83 @@ func absJoin(dir string, fileses ...[]string) (res []string) { return res } -func golistargs(cfg *Config, words []string) []string { +func jsonFlag(cfg *Config, goVersion int) string { + if goVersion < 19 { + return "-json" + } + var fields []string + added := make(map[string]bool) + addFields := func(fs ...string) { + for _, f := range fs { + if !added[f] { + added[f] = true + fields = append(fields, f) + } + } + } + addFields("Name", "ImportPath", "Error") // These fields are always needed + if cfg.Mode&NeedFiles != 0 || cfg.Mode&NeedTypes != 0 { + addFields("Dir", "GoFiles", "IgnoredGoFiles", "IgnoredOtherFiles", "CFiles", + "CgoFiles", "CXXFiles", "MFiles", "HFiles", "FFiles", "SFiles", + "SwigFiles", "SwigCXXFiles", "SysoFiles") + if cfg.Tests { + addFields("TestGoFiles", "XTestGoFiles") + } + } + if cfg.Mode&NeedTypes != 0 { + // CompiledGoFiles seems to be required for the test case TestCgoNoSyntax, + // even when -compiled isn't passed in. + // TODO(#52435): Should we make the test ask for -compiled, or automatically + // request CompiledGoFiles in certain circumstances? + addFields("Dir", "CompiledGoFiles") + } + if cfg.Mode&NeedCompiledGoFiles != 0 { + addFields("Dir", "CompiledGoFiles", "Export") + } + if cfg.Mode&NeedImports != 0 { + // When imports are requested, DepOnly is used to distinguish between packages + // explicitly requested and transitive imports of those packages. + addFields("DepOnly", "Imports", "ImportMap") + if cfg.Tests { + addFields("TestImports", "XTestImports") + } + } + if cfg.Mode&NeedDeps != 0 { + addFields("DepOnly") + } + if usesExportData(cfg) { + // Request Dir in the unlikely case Export is not absolute. + addFields("Dir", "Export") + } + if cfg.Mode&needInternalForTest != 0 { + addFields("ForTest") + } + if cfg.Mode&needInternalDepsErrors != 0 { + addFields("DepsErrors") + } + if cfg.Mode&NeedModule != 0 { + addFields("Module") + } + if cfg.Mode&NeedEmbedFiles != 0 { + addFields("EmbedFiles") + } + if cfg.Mode&NeedEmbedPatterns != 0 { + addFields("EmbedPatterns") + } + return "-json=" + strings.Join(fields, ",") +} + +func golistargs(cfg *Config, words []string, goVersion int) []string { const findFlags = NeedImports | NeedTypes | NeedSyntax | NeedTypesInfo fullargs := []string{ - "-e", "-json", + "-e", jsonFlag(cfg, goVersion), fmt.Sprintf("-compiled=%t", cfg.Mode&(NeedCompiledGoFiles|NeedSyntax|NeedTypes|NeedTypesInfo|NeedTypesSizes) != 0), fmt.Sprintf("-test=%t", cfg.Tests), fmt.Sprintf("-export=%t", usesExportData(cfg)), fmt.Sprintf("-deps=%t", cfg.Mode&NeedImports != 0), // go list doesn't let you pass -test and -find together, // probably because you'd just get the TestMain. - fmt.Sprintf("-find=%t", !cfg.Tests && cfg.Mode&findFlags == 0), + fmt.Sprintf("-find=%t", !cfg.Tests && cfg.Mode&findFlags == 0 && !usesExportData(cfg)), } fullargs = append(fullargs, cfg.BuildFlags...) fullargs = append(fullargs, "--") @@ -879,7 +953,7 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, if !ok { // Catastrophic error: // - context cancellation - return nil, xerrors.Errorf("couldn't run 'go': %w", err) + return nil, fmt.Errorf("couldn't run 'go': %w", err) } // Old go version? diff --git a/tools/vendor/golang.org/x/tools/go/packages/loadmode_string.go b/tools/vendor/golang.org/x/tools/go/packages/loadmode_string.go index 7ea37e7e..5c080d21 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/loadmode_string.go +++ b/tools/vendor/golang.org/x/tools/go/packages/loadmode_string.go @@ -15,7 +15,7 @@ var allModes = []LoadMode{ NeedCompiledGoFiles, NeedImports, NeedDeps, - NeedExportsFile, + NeedExportFile, NeedTypes, NeedSyntax, NeedTypesInfo, @@ -28,7 +28,7 @@ var modeStrings = []string{ "NeedCompiledGoFiles", "NeedImports", "NeedDeps", - "NeedExportsFile", + "NeedExportFile", "NeedTypes", "NeedSyntax", "NeedTypesInfo", 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 1b5424e7..a93dc6ad 100644 --- a/tools/vendor/golang.org/x/tools/go/packages/packages.go +++ b/tools/vendor/golang.org/x/tools/go/packages/packages.go @@ -39,9 +39,6 @@ import ( // Load may return more information than requested. type LoadMode int -// TODO(matloob): When a V2 of go/packages is released, rename NeedExportsFile to -// NeedExportFile to make it consistent with the Package field it's adding. - const ( // NeedName adds Name and PkgPath. NeedName LoadMode = 1 << iota @@ -59,8 +56,8 @@ const ( // NeedDeps adds the fields requested by the LoadMode in the packages in Imports. NeedDeps - // NeedExportsFile adds ExportFile. - NeedExportsFile + // NeedExportFile adds ExportFile. + NeedExportFile // NeedTypes adds Types, Fset, and IllTyped. NeedTypes @@ -74,12 +71,25 @@ const ( // NeedTypesSizes adds TypesSizes. NeedTypesSizes + // needInternalDepsErrors adds the internal deps errors field for use by gopls. + needInternalDepsErrors + + // needInternalForTest adds the internal forTest field. + // Tests must also be set on the context for this field to be populated. + needInternalForTest + // typecheckCgo enables full support for type checking cgo. Requires Go 1.15+. // Modifies CompiledGoFiles and Types, and has no effect on its own. typecheckCgo // NeedModule adds Module. NeedModule + + // NeedEmbedFiles adds EmbedFiles. + NeedEmbedFiles + + // NeedEmbedPatterns adds EmbedPatterns. + NeedEmbedPatterns ) const ( @@ -102,6 +112,9 @@ const ( // Deprecated: LoadAllSyntax exists for historical compatibility // and should not be used. Please directly specify the needed fields using the Need values. LoadAllSyntax = LoadSyntax | NeedDeps + + // Deprecated: NeedExportsFile is a historical misspelling of NeedExportFile. + NeedExportsFile = NeedExportFile ) // A Config specifies details about how packages should be loaded. @@ -296,6 +309,14 @@ type Package struct { // including assembly, C, C++, Fortran, Objective-C, SWIG, and so on. OtherFiles []string + // EmbedFiles lists the absolute file paths of the package's files + // embedded with go:embed. + EmbedFiles []string + + // EmbedPatterns lists the absolute file patterns of the package's + // files embedded with go:embed. + EmbedPatterns []string + // IgnoredFiles lists source files that are not part of the package // using the current build configuration but that might be part of // the package using other build configurations. @@ -389,6 +410,8 @@ func init() { config.(*Config).modFlag = value } packagesinternal.TypecheckCgo = int(typecheckCgo) + packagesinternal.DepsErrors = int(needInternalDepsErrors) + packagesinternal.ForTest = int(needInternalForTest) } // An Error describes a problem with a package's metadata, syntax, or types. @@ -431,6 +454,8 @@ type flatPackage struct { GoFiles []string `json:",omitempty"` CompiledGoFiles []string `json:",omitempty"` OtherFiles []string `json:",omitempty"` + EmbedFiles []string `json:",omitempty"` + EmbedPatterns []string `json:",omitempty"` IgnoredFiles []string `json:",omitempty"` ExportFile string `json:",omitempty"` Imports map[string]string `json:",omitempty"` @@ -454,6 +479,8 @@ func (p *Package) MarshalJSON() ([]byte, error) { GoFiles: p.GoFiles, CompiledGoFiles: p.CompiledGoFiles, OtherFiles: p.OtherFiles, + EmbedFiles: p.EmbedFiles, + EmbedPatterns: p.EmbedPatterns, IgnoredFiles: p.IgnoredFiles, ExportFile: p.ExportFile, } @@ -481,6 +508,8 @@ func (p *Package) UnmarshalJSON(b []byte) error { GoFiles: flat.GoFiles, CompiledGoFiles: flat.CompiledGoFiles, OtherFiles: flat.OtherFiles, + EmbedFiles: flat.EmbedFiles, + EmbedPatterns: flat.EmbedPatterns, ExportFile: flat.ExportFile, } if len(flat.Imports) > 0 { @@ -614,7 +643,7 @@ func (ld *loader) refine(roots []string, list ...*Package) ([]*Package, error) { needsrc := ((ld.Mode&(NeedSyntax|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) || // ... or if we need types and the exportData is invalid. We fall back to (incompletely) // typechecking packages from source if they fail to compile. - (ld.Mode&NeedTypes|NeedTypesInfo != 0 && exportDataInvalid)) && pkg.PkgPath != "unsafe" + (ld.Mode&(NeedTypes|NeedTypesInfo) != 0 && exportDataInvalid)) && pkg.PkgPath != "unsafe" lpkg := &loaderPackage{ Package: pkg, needtypes: needtypes, @@ -752,13 +781,19 @@ func (ld *loader) refine(roots []string, list ...*Package) ([]*Package, error) { ld.pkgs[i].OtherFiles = nil ld.pkgs[i].IgnoredFiles = nil } + if ld.requestedMode&NeedEmbedFiles == 0 { + ld.pkgs[i].EmbedFiles = nil + } + if ld.requestedMode&NeedEmbedPatterns == 0 { + ld.pkgs[i].EmbedPatterns = nil + } if ld.requestedMode&NeedCompiledGoFiles == 0 { ld.pkgs[i].CompiledGoFiles = nil } if ld.requestedMode&NeedImports == 0 { ld.pkgs[i].Imports = nil } - if ld.requestedMode&NeedExportsFile == 0 { + if ld.requestedMode&NeedExportFile == 0 { ld.pkgs[i].ExportFile = "" } if ld.requestedMode&NeedTypes == 0 { @@ -1053,7 +1088,6 @@ func (ld *loader) parseFile(filename string) (*ast.File, error) { // // Because files are scanned in parallel, the token.Pos // positions of the resulting ast.Files are not ordered. -// func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) { var wg sync.WaitGroup n := len(filenames) @@ -1097,7 +1131,6 @@ func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) { // sameFile returns true if x and y have the same basename and denote // the same file. -// func sameFile(x, y string) bool { if x == y { // It could be the case that y doesn't exist. @@ -1210,8 +1243,13 @@ func (ld *loader) loadFromExportData(lpkg *loaderPackage) (*types.Package, error if err != nil { return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err) } + if _, ok := view["go.shape"]; ok { + // Account for the pseudopackage "go.shape" that gets + // created by generic code. + viewLen++ + } if viewLen != len(view) { - log.Fatalf("Unexpected package creation during export data loading") + log.Panicf("golang.org/x/tools/go/packages: unexpected new packages during load of %s", lpkg.PkgPath) } lpkg.Types = tpkg @@ -1222,17 +1260,8 @@ func (ld *loader) loadFromExportData(lpkg *loaderPackage) (*types.Package, error // impliedLoadMode returns loadMode with its dependencies. func impliedLoadMode(loadMode LoadMode) LoadMode { - if loadMode&NeedTypesInfo != 0 && loadMode&NeedImports == 0 { - // If NeedTypesInfo, go/packages needs to do typechecking itself so it can - // associate type info with the AST. To do so, we need the export data - // for dependencies, which means we need to ask for the direct dependencies. - // NeedImports is used to ask for the direct dependencies. - loadMode |= NeedImports - } - - if loadMode&NeedDeps != 0 && loadMode&NeedImports == 0 { - // With NeedDeps we need to load at least direct dependencies. - // NeedImports is used to ask for the direct dependencies. + if loadMode&(NeedDeps|NeedTypes|NeedTypesInfo) != 0 { + // All these things require knowing the import graph. loadMode |= NeedImports } @@ -1240,5 +1269,5 @@ func impliedLoadMode(loadMode LoadMode) LoadMode { } func usesExportData(cfg *Config) bool { - return cfg.Mode&NeedExportsFile != 0 || cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedDeps == 0 + return cfg.Mode&NeedExportFile != 0 || cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedDeps == 0 } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/block.go b/tools/vendor/golang.org/x/tools/go/ssa/block.go index 35f31733..28170c78 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/block.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/block.go @@ -19,14 +19,12 @@ func (b *BasicBlock) Parent() *Function { return b.parent } // String returns a human-readable label of this block. // It is not guaranteed unique within the function. -// func (b *BasicBlock) String() string { return fmt.Sprintf("%d", b.Index) } // emit appends an instruction to the current basic block. // If the instruction defines a Value, it is returned. -// func (b *BasicBlock) emit(i Instruction) Value { i.setBlock(b) b.Instrs = append(b.Instrs, i) @@ -63,7 +61,6 @@ func (b *BasicBlock) phis() []Instruction { // replacePred replaces all occurrences of p in b's predecessor list with q. // Ordinarily there should be at most one. -// func (b *BasicBlock) replacePred(p, q *BasicBlock) { for i, pred := range b.Preds { if pred == p { @@ -74,7 +71,6 @@ func (b *BasicBlock) replacePred(p, q *BasicBlock) { // replaceSucc replaces all occurrences of p in b's successor list with q. // Ordinarily there should be at most one. -// func (b *BasicBlock) replaceSucc(p, q *BasicBlock) { for i, succ := range b.Succs { if succ == p { @@ -86,7 +82,6 @@ func (b *BasicBlock) replaceSucc(p, q *BasicBlock) { // removePred removes all occurrences of p in b's // predecessor list and φ-nodes. // Ordinarily there should be at most one. -// func (b *BasicBlock) removePred(p *BasicBlock) { phis := b.phis() diff --git a/tools/vendor/golang.org/x/tools/go/ssa/blockopt.go b/tools/vendor/golang.org/x/tools/go/ssa/blockopt.go index e79260a2..7dabce8c 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/blockopt.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/blockopt.go @@ -31,7 +31,6 @@ func markReachable(b *BasicBlock) { // deleteUnreachableBlocks marks all reachable blocks of f and // eliminates (nils) all others, including possibly cyclic subgraphs. -// func deleteUnreachableBlocks(f *Function) { const white, black = 0, -1 // We borrow b.Index temporarily as the mark bit. @@ -61,7 +60,6 @@ func deleteUnreachableBlocks(f *Function) { // jumpThreading attempts to apply simple jump-threading to block b, // in which a->b->c become a->c if b is just a Jump. // The result is true if the optimization was applied. -// func jumpThreading(f *Function, b *BasicBlock) bool { if b.Index == 0 { return false // don't apply to entry block @@ -108,7 +106,6 @@ func jumpThreading(f *Function, b *BasicBlock) bool { // fuseBlocks attempts to apply the block fusion optimization to block // a, in which a->b becomes ab if len(a.Succs)==len(b.Preds)==1. // The result is true if the optimization was applied. -// func fuseBlocks(f *Function, a *BasicBlock) bool { if len(a.Succs) != 1 { return false @@ -150,7 +147,6 @@ func fuseBlocks(f *Function, a *BasicBlock) bool { // optimizeBlocks() performs some simple block optimizations on a // completed function: dead block elimination, block fusion, jump // threading. -// func optimizeBlocks(f *Function) { deleteUnreachableBlocks(f) 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 4d537414..b36775a4 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/builder.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/builder.go @@ -24,10 +24,83 @@ package ssa // TODO(adonovan): indeed, building functions is now embarrassingly parallel. // Audit for concurrency then benchmark using more goroutines. // -// The builder's and Program's indices (maps) are populated and +// State: +// +// 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. +// +// 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. +// +// Locks: +// +// 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. +// +// Synthetics: +// +// 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. +// +// Runtime types: +// +// 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) + } + return callee } // Local var. return emitLoad(fn, fn.lookup(obj, false)) // var (address) case *ast.SelectorExpr: - sel, ok := fn.info.Selections[e] - if !ok { + sel := fn.selection(e) + if sel == nil { // builtin unsafe.{Add,Slice} if obj, ok := fn.info.Uses[e.Sel].(*types.Builtin); ok { - return &Builtin{name: obj.Name(), sig: tv.Type.(*types.Signature)} + return &Builtin{name: obj.Name(), sig: fn.typ(tv.Type).(*types.Signature)} } // qualified identifier return b.expr(fn, e.Sel) } - switch sel.Kind() { + switch sel.kind { case types.MethodExpr: // (*T).f or T.f, the method f from the method-set of type T. // The result is a "thunk". - return emitConv(fn, makeThunk(fn.Prog, sel), tv.Type) + thunk := makeThunk(fn.Prog, sel, b.created) + return emitConv(fn, thunk, fn.typ(tv.Type)) case types.MethodVal: // e.f where e is an expression and f is a method. // The result is a "bound". - obj := sel.Obj().(*types.Func) - rt := recvType(obj) + obj := sel.obj.(*types.Func) + rt := fn.typ(recvType(obj)) wantAddr := isPointer(rt) escaping := true v := b.receiver(fn, e.X, wantAddr, escaping, sel) @@ -725,53 +816,74 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { // We use: typeassert v.(I). emitTypeAssert(fn, v, rt, token.NoPos) } + if targs := receiverTypeArgs(obj); len(targs) > 0 { + // obj is generic. + obj = fn.Prog.canon.instantiateMethod(obj, fn.subst.types(targs), fn.Prog.ctxt) + } c := &MakeClosure{ - Fn: makeBound(fn.Prog, obj), + Fn: makeBound(fn.Prog, obj, b.created), Bindings: []Value{v}, } c.setPos(e.Sel.Pos()) - c.setType(tv.Type) + c.setType(fn.typ(tv.Type)) return fn.emit(c) case types.FieldVal: - indices := sel.Index() + indices := sel.index last := len(indices) - 1 v := b.expr(fn, e.X) - v = emitImplicitSelections(fn, v, indices[:last]) + v = emitImplicitSelections(fn, v, indices[:last], e.Pos()) v = emitFieldSelection(fn, v, indices[last], false, e.Sel) return v } panic("unexpected expression-relative selector") + case *typeparams.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") + } + return b.expr(fn, e.X) // Handle instantiation within the *Ident or *SelectorExpr cases. + case *ast.IndexExpr: + if instance(fn.info, e.X) { + return b.expr(fn, e.X) // Handle instantiation within the *Ident or *SelectorExpr cases. + } + // not a generic instantiation. switch t := fn.typeOf(e.X).Underlying().(type) { case *types.Array: // Non-addressable array (in a register). + index := b.expr(fn, e.Index) + if isUntyped(index.Type()) { + index = emitConv(fn, index, tInt) + } v := &Index{ X: b.expr(fn, e.X), - Index: emitConv(fn, b.expr(fn, e.Index), tInt), + Index: index, } v.setPos(e.Lbrack) v.setType(t.Elem()) return fn.emit(v) case *types.Map: - // Maps are not addressable. - mapt := fn.typeOf(e.X).Underlying().(*types.Map) v := &Lookup{ X: b.expr(fn, e.X), - Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()), + Index: emitConv(fn, b.expr(fn, e.Index), t.Key()), } v.setPos(e.Lbrack) - v.setType(mapt.Elem()) + v.setType(t.Elem()) return fn.emit(v) case *types.Basic: // => string // Strings are not addressable. + index := b.expr(fn, e.Index) + if isUntyped(index.Type()) { + index = emitConv(fn, index, tInt) + } v := &Lookup{ X: b.expr(fn, e.X), - Index: b.expr(fn, e.Index), + Index: index, } v.setPos(e.Lbrack) v.setType(tByte) @@ -806,21 +918,21 @@ func (b *builder) stmtList(fn *Function, list []ast.Stmt) { // selections of sel. // // wantAddr requests that the result is an an address. If -// !sel.Indirect(), this may require that e be built in addr() mode; it +// !sel.indirect, this may require that e be built in addr() mode; it // must thus be addressable. // // escaping is defined as per builder.addr(). -// -func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *types.Selection) Value { +func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *selection) Value { var v Value - if wantAddr && !sel.Indirect() && !isPointer(fn.typeOf(e)) { + if wantAddr && !sel.indirect && !isPointer(fn.typeOf(e)) { v = b.addr(fn, e, escaping).address(fn) } else { v = b.expr(fn, e) } - last := len(sel.Index()) - 1 - v = emitImplicitSelections(fn, v, sel.Index()[:last]) + 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 !wantAddr && isPointer(v.Type()) { v = emitLoad(fn, v) } @@ -830,16 +942,16 @@ func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, se // setCallFunc populates the function parts of a CallCommon structure // (Func, Method, Recv, Args[0]) based on the kind of invocation // occurring in e. -// func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) { c.pos = e.Lparen // Is this a method call? if selector, ok := unparen(e.Fun).(*ast.SelectorExpr); ok { - sel, ok := fn.info.Selections[selector] - if ok && sel.Kind() == types.MethodVal { - obj := sel.Obj().(*types.Func) + sel := fn.selection(selector) + if sel != nil && sel.kind == types.MethodVal { + obj := sel.obj.(*types.Func) recv := recvType(obj) + wantAddr := isPointer(recv) escaping := true v := b.receiver(fn, selector.X, wantAddr, escaping, sel) @@ -849,13 +961,17 @@ func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) { c.Method = obj } else { // "Call"-mode call. - c.Value = fn.Prog.declaredFunc(obj) + callee := fn.Prog.originFunc(obj) + if len(callee._TypeParams) > 0 { + callee = fn.Prog.needsInstance(callee, receiverTypeArgs(obj), b.created) + } + c.Value = callee c.Args = append(c.Args, v) } return } - // sel.Kind()==MethodExpr indicates T.f() or (*T).f(): + // sel.kind==MethodExpr indicates T.f() or (*T).f(): // a statically dispatched call to the method f in the // method-set of T or *T. T may be an interface. // @@ -893,7 +1009,6 @@ func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) { // emitCallArgs emits to f code for the actual parameters of call e to // a (possibly built-in) function of effective type sig. // The argument values are appended to args, which is then returned. -// func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallExpr, args []Value) []Value { // f(x, y, z...): pass slice z straight through. if e.Ellipsis != 0 { @@ -965,7 +1080,6 @@ func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallEx // setCall emits to fn code to evaluate all the parameters of a function // call e, and populates *c with those values. -// func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) { // First deal with the f(...) part and optional receiver. b.setCallFunc(fn, e, c) @@ -980,13 +1094,11 @@ 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, pos token.Pos) { - oldv := loc.load(fn) - loc.store(fn, emitArith(fn, op, oldv, emitConv(fn, val, oldv.Type()), loc.typ(), pos)) + loc.store(fn, emitArith(fn, op, loc.load(fn), val, loc.typ(), pos)) } // localValueSpec emits to fn code to define all of the vars in the // function-local ValueSpec, spec. -// func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { switch { case len(spec.Values) == len(spec.Names): @@ -1029,7 +1141,6 @@ func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { // isDef is true if this is a short variable declaration (:=). // // Note the similarity with localValueSpec. -// func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool) { // Side effects of all LHSs and RHSs must occur in left-to-right order. lvals := make([]lvalue, len(lhss)) @@ -1095,8 +1206,10 @@ func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 { // // Because the elements of a composite literal may refer to the // variables being updated, as in the second line below, +// // x := T{a: 1} // x = T{a: x.a} +// // all the reads must occur before all the writes. Thus all stores to // loc are emitted to the storebuf sb for later execution. // @@ -1104,7 +1217,6 @@ func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 { // case when the type name is implicit. e.g. in []*T{{}}, the inner // 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)) switch t := typ.Underlying().(type) { @@ -1243,7 +1355,6 @@ func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero // switchStmt emits to fn code for the switch statement s, optionally // labelled by label. -// func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) { // We treat SwitchStmt like a sequential if-else chain. // Multiway dispatch can be recovered later by ssautil.Switches() @@ -1297,7 +1408,7 @@ func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) { // instead of BinOp(EQL, tag, b.expr(cond)) // followed by If. Don't forget conversions // though. - cond := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), token.NoPos) + cond := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), cond.Pos()) emitIf(fn, cond, body, nextCond) fn.currentBlock = nextCond } @@ -1329,7 +1440,6 @@ func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) { // typeSwitchStmt emits to fn code for the type switch statement s, optionally // labelled by label. -// func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lblock) { // We treat TypeSwitchStmt like a sequential if-else chain. // Multiway dispatch can be recovered later by ssautil.Switches(). @@ -1375,7 +1485,6 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl // ...SD... // goto done // .done: - if s.Init != nil { b.stmt(fn, s.Init) } @@ -1408,7 +1517,7 @@ func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lbl casetype = fn.typeOf(cond) var condv Value if casetype == tUntypedNil { - condv = emitCompare(fn, token.EQL, x, nilConst(x.Type()), token.NoPos) + condv = emitCompare(fn, token.EQL, x, nilConst(x.Type()), cond.Pos()) ti = x } else { yok := emitTypeTest(fn, x, casetype, cc.Case) @@ -1453,7 +1562,6 @@ func (b *builder) typeCaseBody(fn *Function, cc *ast.CaseClause, x Value, done * // selectStmt emits to fn code for the select statement s, optionally // labelled by label. -// func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) { // A blocking select of a single case degenerates to a // simple send or receive. @@ -1492,12 +1600,12 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) { case *ast.SendStmt: // ch<- i ch := b.expr(fn, comm.Chan) + chtyp := fn.typ(ch.Type()).Underlying().(*types.Chan) st = &SelectState{ Dir: types.SendOnly, Chan: ch, - Send: emitConv(fn, b.expr(fn, comm.Value), - ch.Type().Underlying().(*types.Chan).Elem()), - Pos: comm.Arrow, + Send: emitConv(fn, b.expr(fn, comm.Value), chtyp.Elem()), + Pos: comm.Arrow, } if debugInfo { st.DebugNode = comm @@ -1549,7 +1657,8 @@ func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) { vars = append(vars, varIndex, varOk) for _, st := range states { if st.Dir == types.RecvOnly { - tElem := st.Chan.Type().Underlying().(*types.Chan).Elem() + chtyp := fn.typ(st.Chan.Type()).Underlying().(*types.Chan) + tElem := chtyp.Elem() vars = append(vars, anonVar(tElem)) } } @@ -1635,7 +1744,6 @@ 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 @@ -1692,7 +1800,6 @@ func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) { // 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) @@ -1787,7 +1894,6 @@ func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.P // Range/Next/Extract to iterate over map or string value x. // tk and tv are the types of the key/value results k and v, or nil // 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 @@ -1851,7 +1957,6 @@ func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token. // tk is the channel's element type, or nil if the k result is // not wanted // pos is the position of the '=' or ':=' token. -// func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) { // // loop: (target of continue) @@ -1890,7 +1995,6 @@ func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) // 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) { var tk, tv types.Type if s.Key != nil && !isBlankIdent(s.Key) { @@ -2158,6 +2262,18 @@ 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() + } +} + +// 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 } @@ -2167,7 +2283,11 @@ func (b *builder) buildFunction(fn *Function) { var functype *ast.FuncType switch n := fn.syntax.(type) { case nil: - return // not a Go source function. (Synthetic, or from object file.) + // TODO(taking): Temporarily this can be the body of a generic function. + if fn.Params != nil { + return // not a Go source function. (Synthetic, or from object file.) + } + // fn.Params == nil is handled within body == nil case. case *ast.FuncDecl: functype = n.Type recvField = n.Recv @@ -2219,22 +2339,45 @@ func (b *builder) buildFunction(fn *Function) { fn.finishBody() } -// buildFuncDecl builds SSA code for the function or method declared -// by decl in package pkg. +// buildCreated does the BUILD phase for each function created by builder that is not yet BUILT. +// Functions are built using buildFunction. // -func (b *builder) buildFuncDecl(pkg *Package, decl *ast.FuncDecl) { - id := decl.Name - if isBlankIdent(id) { - return // discard +// 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) } - fn := pkg.objects[pkg.info.Defs[id]].(*Function) - if decl.Recv == nil && id.Name == "init" { - var v Call - v.Call.Value = fn - v.setType(types.NewTuple()) - pkg.init.emit(&v) +} + +// 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 + } + prog := b.created.At(0).Prog + + var rtypes []types.Type + for ; b.rtypes < b.finished; b.rtypes++ { + fn := b.created.At(b.rtypes) + rtypes = append(rtypes, mayNeedRuntimeTypes(fn)...) + } + + // 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) + + for _, T := range rtypes { + prog.needMethodsOf(T, b.created) } - b.buildFunction(fn) +} + +func (b *builder) done() bool { + return b.rtypes >= b.created.Len() } // Build calls Package.Build for each package in prog. @@ -2244,7 +2387,6 @@ func (b *builder) buildFuncDecl(pkg *Package, decl *ast.FuncDecl) { // need only build a single package. // // Build is idempotent and thread-safe. -// func (prog *Program) Build() { var wg sync.WaitGroup for _, p := range prog.packages { @@ -2268,7 +2410,6 @@ func (prog *Program) Build() { // error-free). // // Build is idempotent and thread-safe. -// func (p *Package) Build() { p.buildOnce.Do(p.build) } func (p *Package) build() { @@ -2277,16 +2418,20 @@ func (p *Package) build() { } // 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 { - if ast.IsExported(name) { - p.Prog.needMethodsOf(mem.Type()) + if ast.IsExported(name) && !isGeneric(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() @@ -2315,8 +2460,6 @@ func (p *Package) build() { } } - var b builder - // Initialize package-level vars in correct order. for _, varinit := range p.info.InitOrder { if init.Prog.mode&LogSource != 0 { @@ -2344,13 +2487,18 @@ func (p *Package) build() { } } - // Build all package-level functions, init functions - // and methods, including unreachable/blank ones. - // We build them in source order, but it's not significant. + // 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 { - b.buildFuncDecl(p, decl) + id := decl.Name + if !isBlankIdent(id) && id.Name == "init" && decl.Recv == nil { + fn := p.objects[p.info.Defs[id]].(*Function) + var v Call + v.Call.Value = fn + v.setType(types.NewTuple()) + p.init.emit(&v) + } } } } @@ -2362,8 +2510,28 @@ func (p *Package) build() { } 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.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) 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 f43792e7..dc182d96 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/const.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/const.go @@ -16,7 +16,6 @@ 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{typ, val} } @@ -29,7 +28,6 @@ func intConst(i int64) *Const { // 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) } @@ -42,7 +40,6 @@ func stringConst(s string) *Const { // zeroConst returns a new "zero" constant of the specified type, // which must not be an array or struct type: the zero values of // aggregates are well-defined but cannot be represented by Const. -// func zeroConst(t types.Type) *Const { switch t := t.(type) { case *types.Basic: @@ -119,7 +116,6 @@ func (c *Const) IsNil() bool { // Int64 returns the numeric value of this constant truncated to fit // a signed 64-bit integer. -// func (c *Const) Int64() int64 { switch x := constant.ToInt(c.Value); x.Kind() { case constant.Int: @@ -136,7 +132,6 @@ func (c *Const) Int64() int64 { // Uint64 returns the numeric value of this constant truncated to fit // an unsigned 64-bit integer. -// func (c *Const) Uint64() uint64 { switch x := constant.ToInt(c.Value); x.Kind() { case constant.Int: @@ -153,7 +148,6 @@ func (c *Const) Uint64() uint64 { // Float64 returns the numeric value of this constant truncated to fit // a float64. -// func (c *Const) Float64() float64 { f, _ := constant.Float64Val(c.Value) return f @@ -161,7 +155,6 @@ func (c *Const) Float64() float64 { // Complex128 returns the complex value of this constant truncated to // fit a complex128. -// func (c *Const) Complex128() complex128 { re, _ := constant.Float64Val(constant.Real(c.Value)) im, _ := constant.Float64Val(constant.Imag(c.Value)) 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 69cd9371..345d9acf 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/create.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/create.go @@ -16,24 +16,29 @@ import ( "sync" "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/typeparams" ) // NewProgram returns a new SSA Program. // // mode controls diagnostics and checking during SSA construction. -// 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[*types.Func]*Function), - mode: mode, + 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)}, } h := typeutil.MakeHasher() // protected by methodsMu, in effect prog.methodSets.SetHasher(h) + prog.runtimeTypes.SetHasher(h) return prog } @@ -44,7 +49,6 @@ func NewProgram(fset *token.FileSet, mode BuilderMode) *Program { // 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) { name := obj.Name() switch obj := obj.(type) { @@ -85,19 +89,39 @@ 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.TypeParam + for i, rtparams := 0, typeparams.RecvTypeParams(sig); i < rtparams.Len(); i++ { + tparams = append(tparams, rtparams.At(i)) + } + for i, sigparams := 0, typeparams.ForSignature(sig); i < sigparams.Len(); i++ { + tparams = append(tparams, sigparams.At(i)) + } + fn := &Function{ - name: name, - object: obj, - Signature: sig, - syntax: syntax, - pos: obj.Pos(), - Pkg: pkg, - Prog: pkg.Prog, - info: pkg.info, + 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 len(tparams) > 0 { + fn.Prog.createInstanceSet(fn) + } + if len(tparams) > 0 && syntax != nil { + fn.Synthetic = "generic function" + // TODO(taking): Allow for the function to be built once type params are supported. + fn.syntax = nil // Treating as an external function temporarily. + } pkg.objects[obj] = fn if sig.Recv() == nil { @@ -112,7 +136,6 @@ 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) { switch decl := decl.(type) { case *ast.GenDecl: // import, const, type or var @@ -152,6 +175,19 @@ func membersFromDecl(pkg *Package, decl ast.Decl) { } } +// 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 // specified type-checked, error-free file ASTs, and populates its // Members mapping. @@ -161,7 +197,6 @@ func membersFromDecl(pkg *Package, decl ast.Decl) { // // The real work of building SSA form for each function is not done // 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, @@ -182,6 +217,7 @@ func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info * info: p.info, } p.Members[p.init.name] = p.init + p.created.Add(p.init) // CREATE phase. // Allocate all package members: vars, funcs, consts and types. @@ -243,7 +279,6 @@ var printMu sync.Mutex // AllPackages returns a new slice containing all packages in the // program prog in unspecified order. -// func (prog *Program) AllPackages() []*Package { pkgs := make([]*Package, 0, len(prog.packages)) for _, pkg := range prog.packages { @@ -265,7 +300,6 @@ func (prog *Program) AllPackages() []*Package { // false---yet this function remains very convenient. // Clients should use (*Program).Package instead where possible. // SSA doesn't really need a string-keyed map of packages. -// func (prog *Program) ImportedPackage(path string) *Package { return prog.imported[path] } 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 6885bedb..13d02413 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/doc.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/doc.go @@ -41,60 +41,60 @@ // // 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 // concrete type which of these interfaces it implements. // -// Value? Instruction? Member? -// *Alloc ✔ ✔ -// *BinOp ✔ ✔ -// *Builtin ✔ -// *Call ✔ ✔ -// *ChangeInterface ✔ ✔ -// *ChangeType ✔ ✔ -// *Const ✔ -// *Convert ✔ ✔ -// *DebugRef ✔ -// *Defer ✔ -// *Extract ✔ ✔ -// *Field ✔ ✔ -// *FieldAddr ✔ ✔ -// *FreeVar ✔ -// *Function ✔ ✔ (func) -// *Global ✔ ✔ (var) -// *Go ✔ -// *If ✔ -// *Index ✔ ✔ -// *IndexAddr ✔ ✔ -// *Jump ✔ -// *Lookup ✔ ✔ -// *MakeChan ✔ ✔ -// *MakeClosure ✔ ✔ -// *MakeInterface ✔ ✔ -// *MakeMap ✔ ✔ -// *MakeSlice ✔ ✔ -// *MapUpdate ✔ -// *NamedConst ✔ (const) -// *Next ✔ ✔ -// *Panic ✔ -// *Parameter ✔ -// *Phi ✔ ✔ -// *Range ✔ ✔ -// *Return ✔ -// *RunDefers ✔ -// *Select ✔ ✔ -// *Send ✔ -// *Slice ✔ ✔ -// *SliceToArrayPointer ✔ ✔ -// *Store ✔ -// *Type ✔ (type) -// *TypeAssert ✔ ✔ -// *UnOp ✔ ✔ +// Value? Instruction? Member? +// *Alloc ✔ ✔ +// *BinOp ✔ ✔ +// *Builtin ✔ +// *Call ✔ ✔ +// *ChangeInterface ✔ ✔ +// *ChangeType ✔ ✔ +// *Const ✔ +// *Convert ✔ ✔ +// *DebugRef ✔ +// *Defer ✔ +// *Extract ✔ ✔ +// *Field ✔ ✔ +// *FieldAddr ✔ ✔ +// *FreeVar ✔ +// *Function ✔ ✔ (func) +// *Global ✔ ✔ (var) +// *Go ✔ +// *If ✔ +// *Index ✔ ✔ +// *IndexAddr ✔ ✔ +// *Jump ✔ +// *Lookup ✔ ✔ +// *MakeChan ✔ ✔ +// *MakeClosure ✔ ✔ +// *MakeInterface ✔ ✔ +// *MakeMap ✔ ✔ +// *MakeSlice ✔ ✔ +// *MapUpdate ✔ +// *NamedConst ✔ (const) +// *Next ✔ ✔ +// *Panic ✔ +// *Parameter ✔ +// *Phi ✔ ✔ +// *Range ✔ ✔ +// *Return ✔ +// *RunDefers ✔ +// *Select ✔ ✔ +// *Send ✔ +// *Slice ✔ ✔ +// *SliceToArrayPointer ✔ ✔ +// *Store ✔ +// *Type ✔ (type) +// *TypeAssert ✔ ✔ +// *UnOp ✔ ✔ // // Other key types in this package include: Program, Package, Function // and BasicBlock. @@ -122,5 +122,4 @@ // of trying to determine corresponding elements across the four // domains of source locations, ast.Nodes, types.Objects, // ssa.Values/Instructions. -// package ssa // import "golang.org/x/tools/go/ssa" 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 822fe977..ce2473ca 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/dom.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/dom.go @@ -29,12 +29,10 @@ import ( // its parent in the dominator tree, if any. // Neither the entry node (b.Index==0) nor recover node // (b==b.Parent().Recover()) have a parent. -// func (b *BasicBlock) Idom() *BasicBlock { return b.dom.idom } // Dominees returns the list of blocks that b immediately dominates: // its children in the dominator tree. -// func (b *BasicBlock) Dominees() []*BasicBlock { return b.dom.children } // Dominates reports whether b dominates c. @@ -50,7 +48,6 @@ 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. -// func (f *Function) DomPreorder() []*BasicBlock { n := len(f.Blocks) order := make(byDomPreorder, n) @@ -110,7 +107,6 @@ func (lt *ltState) link(v, w *BasicBlock) { // buildDomTree computes the dominator tree of f using the LT algorithm. // Precondition: all blocks are reachable (e.g. optimizeBlocks has been run). -// func buildDomTree(f *Function) { // The step numbers refer to the original LT paper; the // reordering is due to Georgiadis. @@ -210,7 +206,6 @@ func buildDomTree(f *Function) { // numberDomTree sets the pre- and post-order numbers of a depth-first // traversal of the dominator tree rooted at v. These are used to // answer dominance queries in constant time. -// func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) { v.dom.pre = pre pre++ @@ -228,7 +223,6 @@ func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) { // computed by the LT algorithm by comparing against the dominance // relation computed by a naive Kildall-style forward dataflow // analysis (Algorithm 10.16 from the "Dragon" book). -// func sanityCheckDomTree(f *Function) { n := len(f.Blocks) 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 576e0245..fb11c355 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/emit.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/emit.go @@ -15,7 +15,6 @@ import ( // 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} v.setType(types.NewPointer(typ)) @@ -26,7 +25,6 @@ func emitNew(f *Function, typ types.Type, pos token.Pos) *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(deref(addr.Type())) @@ -36,7 +34,6 @@ func emitLoad(f *Function, addr Value) *UnOp { // emitDebugRef emits to f a DebugRef pseudo-instruction associating // expression e with value v. -// func emitDebugRef(f *Function, e ast.Expr, v Value, isAddr bool) { if !f.debugInfo() { return // debugging not enabled @@ -68,7 +65,6 @@ func emitDebugRef(f *Function, e ast.Expr, v Value, isAddr bool) { // where op is an eager shift, logical or arithmetic operation. // (Use emitCompare() for comparisons and Builder.logicalBinop() for // non-eager operations.) -// func emitArith(f *Function, op token.Token, x, y Value, t types.Type, pos token.Pos) Value { switch op { case token.SHL, token.SHR: @@ -78,7 +74,7 @@ func emitArith(f *Function, op token.Token, x, y Value, t types.Type, pos token. // There is a runtime panic if y is signed and <0. Instead of inserting a check for y<0 // and converting to an unsigned value (like the compiler) leave y as is. - if b, ok := y.Type().Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 { + if isUntyped(y.Type().Underlying()) { // Untyped conversion: // Spec https://go.dev/ref/spec#Operators: // The right operand in a shift expression must have integer type or be an untyped constant @@ -106,7 +102,6 @@ func emitArith(f *Function, op token.Token, x, y Value, t types.Type, pos token. // emitCompare emits to f code compute the boolean result of // comparison comparison 'x op y'. -// func emitCompare(f *Function, op token.Token, x, y Value, pos token.Pos) Value { xt := x.Type().Underlying() yt := y.Type().Underlying() @@ -151,7 +146,6 @@ 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. -// func isValuePreserving(ut_src, ut_dst types.Type) bool { // Identical underlying types? if structTypesIdentical(ut_dst, ut_src) { @@ -176,7 +170,6 @@ func isValuePreserving(ut_src, ut_dst types.Type) bool { // and returns the converted value. Implicit conversions are required // by language assignability rules in assignments, parameter passing, // etc. -// func emitConv(f *Function, val Value, typ types.Type) Value { t_src := val.Type() @@ -214,7 +207,6 @@ func emitConv(f *Function, val Value, typ types.Type) Value { val = emitConv(f, val, types.Default(ut_src)) } - f.Pkg.Prog.needMethodsOf(val.Type()) mi := &MakeInterface{X: val} mi.setType(typ) return f.emit(mi) @@ -261,7 +253,6 @@ func emitConv(f *Function, val 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 { s := &Store{ Addr: addr, @@ -274,7 +265,6 @@ func emitStore(f *Function, addr, val Value, pos token.Pos) *Store { // emitJump emits to f a jump to target, and updates the control-flow graph. // Postcondition: f.currentBlock is nil. -// func emitJump(f *Function, target *BasicBlock) { b := f.currentBlock b.emit(new(Jump)) @@ -285,7 +275,6 @@ func emitJump(f *Function, target *BasicBlock) { // emitIf emits to f a conditional jump to tblock or fblock based on // cond, and updates the control-flow graph. // Postcondition: f.currentBlock is nil. -// func emitIf(f *Function, cond Value, tblock, fblock *BasicBlock) { b := f.currentBlock b.emit(&If{Cond: cond}) @@ -296,7 +285,6 @@ func emitIf(f *Function, cond Value, tblock, fblock *BasicBlock) { // emitExtract emits to f an instruction to extract the index'th // component of tuple. It returns the extracted value. -// func emitExtract(f *Function, tuple Value, index int) Value { e := &Extract{Tuple: tuple, Index: index} e.setType(tuple.Type().(*types.Tuple).At(index).Type()) @@ -305,7 +293,6 @@ func emitExtract(f *Function, tuple Value, index int) Value { // emitTypeAssert emits to f a type assertion value := x.(t) and // returns the value. x.Type() must be an interface. -// func emitTypeAssert(f *Function, x Value, t types.Type, pos token.Pos) Value { a := &TypeAssert{X: x, AssertedType: t} a.setPos(pos) @@ -315,7 +302,6 @@ func emitTypeAssert(f *Function, x Value, t types.Type, pos token.Pos) Value { // emitTypeTest emits to f a type test value,ok := x.(t) and returns // a (value, ok) tuple. x.Type() must be an interface. -// func emitTypeTest(f *Function, x Value, t types.Type, pos token.Pos) Value { a := &TypeAssert{ X: x, @@ -335,7 +321,6 @@ func emitTypeTest(f *Function, x Value, t types.Type, pos token.Pos) Value { // Intended for wrapper methods. // Precondition: f does/will not use deferred procedure calls. // Postcondition: f.currentBlock is nil. -// func emitTailCall(f *Function, call *Call) { tresults := f.Signature.Results() nr := tresults.Len() @@ -372,8 +357,7 @@ func emitTailCall(f *Function, call *Call) { // If v is the address of a struct, the result will be the address of // a field; if it is the value of a struct, the result will be the // value of a field. -// -func emitImplicitSelections(f *Function, v Value, indices []int) Value { +func emitImplicitSelections(f *Function, v Value, indices []int, pos token.Pos) Value { for _, index := range indices { fld := deref(v.Type()).Underlying().(*types.Struct).Field(index) @@ -382,6 +366,7 @@ func emitImplicitSelections(f *Function, v Value, indices []int) Value { X: v, Field: index, } + instr.setPos(pos) instr.setType(types.NewPointer(fld.Type())) v = f.emit(instr) // Load the field's value iff indirectly embedded. @@ -393,6 +378,7 @@ func emitImplicitSelections(f *Function, v Value, indices []int) Value { X: v, Field: index, } + instr.setPos(pos) instr.setType(fld.Type()) v = f.emit(instr) } @@ -406,7 +392,6 @@ func emitImplicitSelections(f *Function, v Value, indices []int) Value { // will be the field's address; otherwise the result will be the // 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 { fld := deref(v.Type()).Underlying().(*types.Struct).Field(index) if isPointer(v.Type()) { @@ -436,7 +421,6 @@ 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) Value { switch t.Underlying().(type) { case *types.Struct, *types.Array: @@ -454,7 +438,6 @@ func zeroValue(f *Function, t types.Type) Value { // type. // // Idempotent. -// func createRecoverBlock(f *Function) { if f.Recover != nil { return // already created 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 8fc089e5..c598ff83 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/func.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/func.go @@ -15,6 +15,8 @@ import ( "io" "os" "strings" + + "golang.org/x/tools/internal/typeparams" ) // Like ObjectOf, but panics instead of returning nil. @@ -31,15 +33,62 @@ func (f *Function) objectOf(id *ast.Ident) types.Object { // Only valid during f's create and build phases. func (f *Function) typeOf(e ast.Expr) types.Type { if T := f.info.TypeOf(e); T != nil { - return T + return f.typ(T) } 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. +func (f *Function) typ(T types.Type) types.Type { + return f.subst.typ(T) +} + +// 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 { + return t.Type + } + return f.typeOf(id) +} + +// selection returns a *selection corresponding to f.info.Selections[selector] +// with potential updates for type substitution. +func (f *Function) selection(selector *ast.SelectorExpr) *selection { + sel := f.info.Selections[selector] + if sel == nil { + return nil + } + + switch sel.Kind() { + case types.MethodExpr, types.MethodVal: + if recv := f.typ(sel.Recv()); recv != sel.Recv() { + // recv changed during type substitution. + pkg := f.declaredPackage().Pkg + obj, index, indirect := types.LookupFieldOrMethod(recv, true, pkg, sel.Obj().Name()) + + // sig replaces sel.Type(). See (types.Selection).Typ() for details. + sig := obj.Type().(*types.Signature) + sig = changeRecv(sig, newVar(sig.Recv().Name(), recv)) + if sel.Kind() == types.MethodExpr { + sig = recvAsFirstArg(sig) + } + return &selection{ + kind: sel.Kind(), + recv: recv, + typ: sig, + obj: obj, + index: index, + indirect: indirect, + } + } + } + return toSelection(sel) +} + // Destinations associated with unlabelled for/switch/select stmts. // We push/pop one of these as we enter/leave each construct and for // each BranchStmt we scan for the innermost target of the right type. -// type targets struct { tail *targets // rest of stack _break *BasicBlock @@ -50,7 +99,6 @@ type targets struct { // Destinations associated with a labelled block. // We populate these as labels are encountered in forward gotos or // labelled statements. -// type lblock struct { _goto *BasicBlock _break *BasicBlock @@ -59,22 +107,21 @@ type lblock struct { // labelledBlock returns the branch target associated with the // specified label, creating it if needed. -// func (f *Function) labelledBlock(label *ast.Ident) *lblock { - lb := f.lblocks[label.Obj] + obj := f.objectOf(label) + lb := f.lblocks[obj] if lb == nil { lb = &lblock{_goto: f.newBasicBlock(label.Name)} if f.lblocks == nil { - f.lblocks = make(map[*ast.Object]*lblock) + f.lblocks = make(map[types.Object]*lblock) } - f.lblocks[label.Obj] = lb + f.lblocks[obj] = 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, @@ -91,7 +138,7 @@ func (f *Function) addParamObj(obj types.Object) *Parameter { if name == "" { name = fmt.Sprintf("arg%d", len(f.Params)) } - param := f.addParam(name, obj.Type(), obj.Pos()) + param := f.addParam(name, f.typ(obj.Type()), obj.Pos()) param.object = obj return param } @@ -99,11 +146,10 @@ func (f *Function) addParamObj(obj types.Object) *Parameter { // 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(obj.Type())) + spill.setType(types.NewPointer(param.Type())) spill.setPos(obj.Pos()) f.objects[obj] = spill f.Locals = append(f.Locals, spill) @@ -113,7 +159,6 @@ func (f *Function) addSpilledParam(obj types.Object) { // startBody initializes the function prior to generating SSA code for its body. // 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 @@ -127,7 +172,6 @@ func (f *Function) startBody() { // f.startBody() was called. f.info != nil. // Postcondition: // len(f.Params) == len(f.Signature.Params) + (f.Signature.Recv() ? 1 : 0) -// func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.FuncType) { // Receiver (at most one inner iteration). if recv != nil { @@ -174,7 +218,6 @@ type setNumable interface { // numberRegisters assigns numbers to all SSA registers // (value-defining Instructions) in f, to aid debugging. // (Non-Instruction Values are named at construction.) -// func numberRegisters(f *Function) { v := 0 for _, b := range f.Blocks { @@ -207,7 +250,22 @@ func buildReferrers(f *Function) { } } -// finishBody() finalizes the function after SSA code generation of its body. +// mayNeedRuntimeTypes returns all of the types in the body of fn that might need runtime types. +func mayNeedRuntimeTypes(fn *Function) []types.Type { + 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()) + } + } + } + return ts +} + +// 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 @@ -248,23 +306,38 @@ func (f *Function) finishBody() { // clear remaining stateful variables f.namedResults = nil // (used by lifting) f.info = nil + f.subst = nil - numberRegisters(f) + numberRegisters(f) // uses f.namedRegisters +} - if f.Prog.mode&PrintFunctions != 0 { - printMu.Lock() - f.WriteTo(os.Stdout) - printMu.Unlock() - } +// After this, function is done with BUILD phase. +func (f *Function) done() { + assert(f.parent == nil, "done called on an anonymous function") + + var visit func(*Function) + visit = func(f *Function) { + for _, anon := range f.AnonFuncs { + visit(anon) // anon is done building before f. + } + + f.built = true // function is done with BUILD phase + + if f.Prog.mode&PrintFunctions != 0 { + printMu.Lock() + f.WriteTo(os.Stdout) + printMu.Unlock() + } - if f.Prog.mode&SanityCheckFunctions != 0 { - mustSanityCheck(f, nil) + if f.Prog.mode&SanityCheckFunctions != 0 { + mustSanityCheck(f, nil) + } } + visit(f) } // removeNilBlocks eliminates nils from f.Blocks and updates each // BasicBlock.Index. Use this after any pass that may delete blocks. -// func (f *Function) removeNilBlocks() { j := 0 for _, b := range f.Blocks { @@ -285,7 +358,6 @@ func (f *Function) removeNilBlocks() { // functions will include full debug info. This greatly increases the // 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 @@ -299,7 +371,6 @@ func (f *Function) debugInfo() bool { // 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() @@ -313,8 +384,8 @@ func (f *Function) addLocalForIdent(id *ast.Ident) *Alloc { // 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) @@ -327,7 +398,6 @@ func (f *Function) addLocal(typ types.Type, pos token.Pos) *Alloc { // 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 { @@ -365,13 +435,14 @@ func (f *Function) emit(instr Instruction) Value { // The specific formatting rules are not guaranteed and may change. // // Examples: -// "math.IsNaN" // a package-level function -// "(*bytes.Buffer).Bytes" // a declared method or a wrapper -// "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) -// "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) -// "main.main$1" // an anonymous function in main -// "main.init#1" // a declared init function -// "main.init" // the synthesized package initializer +// +// "math.IsNaN" // a package-level function +// "(*bytes.Buffer).Bytes" // a declared method or a wrapper +// "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) +// "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) +// "main.main$1" // an anonymous function in main +// "main.init#1" // a declared init function +// "main.init" // the synthesized package initializer // // When these functions are referred to from within the same package // (i.e. from == f.Pkg.Object), they are rendered without the package path. @@ -381,7 +452,6 @@ func (f *Function) emit(instr Instruction) Value { // (But two methods may have the same name "(T).f" if one is a synthetic // wrapper promoting a non-exported method "f" from another package; in // that case, the strings are equal but the identifiers "f" are distinct.) -// func (f *Function) RelString(from *types.Package) string { // Anonymous? if f.parent != nil { @@ -404,7 +474,7 @@ func (f *Function) RelString(from *types.Package) string { // Thunk? if f.method != nil { - return f.relMethod(from, f.method.Recv()) + return f.relMethod(from, f.method.recv) } // Bound? @@ -448,9 +518,8 @@ func (fn *Function) declaredPackage() *Package { switch { case fn.Pkg != nil: return fn.Pkg // non-generic function - // generics: - // case fn.Origin != nil: - // return fn.Origin.pkg // instance of a named generic function + case fn._Origin != nil: + return fn._Origin.Pkg // instance of a named generic function case fn.parent != nil: return fn.parent.declaredPackage() // instance of an anonymous [generic] function default: @@ -572,7 +641,6 @@ func WriteFunction(buf *bytes.Buffer, f *Function) { // newBasicBlock adds to f a new basic block and returns it. It does // not automatically become the current block for subsequent calls to emit. // comment is an optional string for more readable debugging output. -// func (f *Function) newBasicBlock(comment string) *BasicBlock { b := &BasicBlock{ Index: len(f.Blocks), @@ -598,7 +666,6 @@ func (f *Function) newBasicBlock(comment string) *BasicBlock { // "reflect" package, etc. // // TODO(adonovan): think harder about the API here. -// func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function { return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance} } @@ -616,5 +683,4 @@ func (n extentNode) End() token.Pos { return n[1] } // 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 } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/instantiate.go b/tools/vendor/golang.org/x/tools/go/ssa/instantiate.go new file mode 100644 index 00000000..049b5348 --- /dev/null +++ b/tools/vendor/golang.org/x/tools/go/ssa/instantiate.go @@ -0,0 +1,161 @@ +// 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 ssa + +import ( + "fmt" + "go/ast" + "go/types" + + "golang.org/x/tools/internal/typeparams" +) + +// 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 len(fn._TypeParams) == 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 // len(fn._TypeParams) > 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 +} + +// createInstanceSet adds a new instanceSet for a generic function fn if one does not exist. +// +// Precondition: fn is a package level declaration (function or method). +// +// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodMu) +func (prog *Program) createInstanceSet(fn *Function) { + assert(len(fn._TypeParams) > 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, + } + } +} + +// needsInstance returns an Function that that is the instantiation of fn with the type arguments targs. +// +// Any CREATEd instance is added to cr. +// +// 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.instances[fn].lookupOrCreate(targs, cr) +} + +// lookupOrCreate returns the instantiation of insts.fn using targs. +// If the instantiation is reported, this is added to cr. +func (insts *instanceSet) lookupOrCreate(targs []types.Type, cr *creator) *Function { + if insts.instances == nil { + insts.instances = make(map[*typeList]*Function) + } + + // canonicalize on a tuple of targs. Sig is not unique. + // + // func A[T any]() { + // var x T + // fmt.Println("%T", x) + // } + key := insts.fn.Prog.canon.List(targs) + if inst, ok := insts.instances[key]; ok { + return inst + } + + var syntax ast.Node + if insts.syntax != nil { + syntax = insts.syntax + } + instance := createInstance(insts.fn, targs, insts.info, syntax, cr) + insts.instances[key] = instance + return instance +} + +// createInstance returns an CREATEd instantiation of fn using targs. +// +// Function is added to cr. +func createInstance(fn *Function, targs []types.Type, info *types.Info, syntax ast.Node, cr *creator) *Function { + prog := fn.Prog + 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) + sig = obj.Type().(*types.Signature) + } else { + instSig, err := typeparams.Instantiate(prog.ctxt, fn.Signature, targs, false) + if err != nil { + panic(err) + } + instance, ok := instSig.(*types.Signature) + if !ok { + panic("Instantiate of a Signature returned a non-signature") + } + obj = fn.object.(*types.Func) // instantiation does not exist yet + sig = prog.canon.Type(instance).(*types.Signature) + } + + name := fmt.Sprintf("%s%s", fn.Name(), targs) // may not be unique + synthetic := fmt.Sprintf("instantiation of %s", fn.Name()) + instance := &Function{ + name: name, + object: obj, + Signature: sig, + Synthetic: synthetic, + _Origin: fn, + pos: obj.Pos(), + Pkg: nil, + Prog: fn.Prog, + _TypeParams: fn._TypeParams, + _TypeArgs: targs, + info: info, // on synthetic packages info is nil. + subst: makeSubster(prog.ctxt, fn._TypeParams, targs, false), + } + if prog.mode&InstantiateGenerics != 0 { + instance.syntax = syntax // otherwise treat instance as an external function. + } + cr.Add(instance) + return instance +} 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 048e9b03..c350481d 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/lift.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/lift.go @@ -61,7 +61,6 @@ const debugLifting = false // // domFrontier's methods mutate the slice's elements but not its // length, so their receivers needn't be pointers. -// type domFrontier [][]*BasicBlock func (df domFrontier) add(u, v *BasicBlock) { @@ -127,7 +126,6 @@ func removeInstr(refs []Instruction, instr Instruction) []Instruction { // - fn has no dead blocks (blockopt has run). // - Def/use info (Operands and Referrers) is up-to-date. // - The dominator tree is up-to-date. -// func lift(fn *Function) { // TODO(adonovan): opt: lots of little optimizations may be // worthwhile here, especially if they cause us to avoid @@ -382,7 +380,6 @@ type newPhiMap map[*BasicBlock][]newPhi // and returns true. // // fresh is a source of fresh ids for phi nodes. -// func liftAlloc(df domFrontier, alloc *Alloc, newPhis newPhiMap, fresh *int) bool { // Don't lift aggregates into registers, because we don't have // a way to express their zero-constants. @@ -491,7 +488,6 @@ func liftAlloc(df domFrontier, alloc *Alloc, newPhis newPhiMap, fresh *int) bool // replaceAll replaces all intraprocedural uses of x with y, // updating x.Referrers and y.Referrers. // Precondition: x.Referrers() != nil, i.e. x must be local to some function. -// func replaceAll(x, y Value) { var rands []*Value pxrefs := x.Referrers() @@ -514,7 +510,6 @@ func replaceAll(x, y Value) { // renamed returns the value to which alloc is being renamed, // constructing it lazily if it's the implicit zero initialization. -// func renamed(renaming []Value, alloc *Alloc) Value { v := renaming[alloc.index] if v == nil { @@ -533,7 +528,6 @@ func renamed(renaming []Value, alloc *Alloc) Value { // renaming is a map from *Alloc (keyed by index number) to its // dominating stored value; newPhis[x] is the set of new φ-nodes to be // prepended to block x. -// func rename(u *BasicBlock, renaming []Value, newPhis newPhiMap) { // Each φ-node becomes the new name for its associated Alloc. for _, np := range newPhis[u] { 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 4d85be3e..64262def 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/lvalue.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/lvalue.go @@ -16,7 +16,6 @@ import ( // An lvalue represents an assignable location that may appear on the // left-hand side of an assignment. This is a generalization of a // pointer to permit updates to elements of maps. -// type lvalue interface { store(fn *Function, v Value) // stores v into the location load(fn *Function) Value // loads the contents of the location @@ -60,7 +59,6 @@ func (a *address) typ() types.Type { // element of a map or string. These locations are not addressable // since pointers cannot be formed from them, but they do support // load(), and in the case of maps, store(). -// type element struct { m, k Value // map or string t types.Type // map element type or string byte type @@ -97,7 +95,6 @@ func (e *element) typ() types.Type { // A blank is a dummy variable whose name is "_". // It is not reified: loads are illegal and stores are ignored. -// type blank struct{} func (bl blank) load(fn *Function) Value { 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 22e1f3f0..6954e17b 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/methods.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/methods.go @@ -9,40 +9,55 @@ package ssa import ( "fmt" "go/types" + + "golang.org/x/tools/internal/typeparams" ) // MethodValue returns the Function implementing method sel, building // wrapper methods on demand. It returns nil if sel denotes an -// abstract (interface) method. +// abstract (interface or parameterized) method. // // Precondition: sel.Kind() == MethodVal. // // Thread-safe. // // EXCLUSIVE_LOCKS_ACQUIRED(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 isInterface(T) { - return nil // abstract method + return nil // abstract method (interface) } if prog.mode&LogSource != 0 { defer logStack("MethodValue %s %v", T, sel)() } + var m *Function + b := builder{created: &creator{}} + prog.methodsMu.Lock() - defer prog.methodsMu.Unlock() + // 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) + } + prog.methodsMu.Unlock() - return prog.addMethod(prog.createMethodSet(T), sel) + if m == nil { + return nil // abstract method (generic) + } + for !b.done() { + b.buildCreated() + b.needsRuntimeTypes() + } + return m } // 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. -// func (prog *Program) LookupMethod(T types.Type, pkg *types.Package, name string) *Function { sel := prog.MethodSets.MethodSet(T).Lookup(pkg, name) if sel == nil { @@ -51,15 +66,20 @@ func (prog *Program) LookupMethod(T types.Type, pkg *types.Package, name string) return prog.MethodValue(sel) } -// methodSet contains the (concrete) methods of a non-interface type. +// 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 } -// Precondition: !isInterface(T). +// 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 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)} @@ -68,22 +88,29 @@ func (prog *Program) createMethodSet(T types.Type) *methodSet { 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) *Function { +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 { - obj := sel.Obj().(*types.Func) + sel := toSelection(sel) + obj := sel.obj.(*types.Func) - needsPromotion := len(sel.Index()) > 1 - needsIndirection := !isPointer(recvType(obj)) && isPointer(sel.Recv()) + needsPromotion := len(sel.index) > 1 + needsIndirection := !isPointer(recvType(obj)) && isPointer(sel.recv) if needsPromotion || needsIndirection { - fn = makeWrapper(prog, sel) + fn = makeWrapper(prog, sel, cr) } else { - fn = prog.declaredFunc(obj) + fn = prog.originFunc(obj) + if len(fn._TypeParams) > 0 { // instantiate + targs := receiverTypeArgs(obj) + fn = prog.instances[fn].lookupOrCreate(targs, cr) + } } if fn.Signature.Recv() == nil { panic(fn) // missing receiver @@ -100,7 +127,6 @@ func (prog *Program) addMethod(mset *methodSet, sel *types.Selection) *Function // Thread-safe. // // EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) -// func (prog *Program) RuntimeTypes() []types.Type { prog.methodsMu.Lock() defer prog.methodsMu.Unlock() @@ -116,7 +142,6 @@ func (prog *Program) RuntimeTypes() []types.Type { // 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) @@ -132,26 +157,28 @@ func (prog *Program) declaredFunc(obj *types.Func) *Function { // 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. // -// Thread-safe. (Called via emitConv from multiple builder goroutines.) +// Thread-safe. (Called via Package.build from multiple builder goroutines.) // // 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) { +func (prog *Program) needMethodsOf(T types.Type, cr *creator) { prog.methodsMu.Lock() - prog.needMethods(T, false) + 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) { +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 @@ -170,7 +197,7 @@ func (prog *Program) needMethods(T types.Type, skip bool) { mset.complete = true n := tmset.Len() for i := 0; i < n; i++ { - prog.addMethod(mset, tmset.At(i)) + prog.addMethod(mset, tmset.At(i), cr) } } } @@ -178,8 +205,8 @@ func (prog *Program) needMethods(T types.Type, skip bool) { // 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) - prog.needMethods(sig.Results(), false) + prog.needMethods(sig.Params(), false, cr) + prog.needMethods(sig.Results(), false, cr) } switch t := T.(type) { @@ -190,49 +217,55 @@ func (prog *Program) needMethods(T types.Type, skip bool) { // nop---handled by recursion over method set. case *types.Pointer: - prog.needMethods(t.Elem(), false) + prog.needMethods(t.Elem(), false, cr) case *types.Slice: - prog.needMethods(t.Elem(), false) + prog.needMethods(t.Elem(), false, cr) case *types.Chan: - prog.needMethods(t.Elem(), false) + prog.needMethods(t.Elem(), false, cr) case *types.Map: - prog.needMethods(t.Key(), false) - prog.needMethods(t.Elem(), false) + prog.needMethods(t.Key(), false, cr) + prog.needMethods(t.Elem(), false, cr) case *types.Signature: if t.Recv() != nil { panic(fmt.Sprintf("Signature %s has Recv %s", t, t.Recv())) } - prog.needMethods(t.Params(), false) - prog.needMethods(t.Results(), false) + 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) + 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) + prog.needMethods(t.Underlying(), true, cr) case *types.Array: - prog.needMethods(t.Elem(), false) + 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) + prog.needMethods(t.Field(i).Type(), false, cr) } case *types.Tuple: for i, n := 0, t.Len(); i < n; i++ { - prog.needMethods(t.At(i).Type(), false) + prog.needMethods(t.At(i).Type(), false, cr) } + case *typeparams.TypeParam: + panic(T) // type parameters are always abstract. + + case *typeparams.Union: + // nop + default: panic(T) } diff --git a/tools/vendor/golang.org/x/tools/go/ssa/mode.go b/tools/vendor/golang.org/x/tools/go/ssa/mode.go index 298f24b9..8381639a 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/mode.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/mode.go @@ -15,9 +15,8 @@ import ( // // *BuilderMode satisfies the flag.Value interface. Example: // -// var mode = ssa.BuilderMode(0) -// func init() { flag.Var(&mode, "build", ssa.BuilderModeDoc) } -// +// var mode = ssa.BuilderMode(0) +// func init() { flag.Var(&mode, "build", ssa.BuilderModeDoc) } type BuilderMode uint const ( @@ -29,6 +28,7 @@ const ( BuildSerially // Build packages serially, not in parallel. GlobalDebug // Enable debug info for all packages BareInits // Build init functions without guards or calls to dependent inits + InstantiateGenerics // Instantiate generics functions (monomorphize) while building ) const BuilderModeDoc = `Options controlling the SSA builder. @@ -41,6 +41,7 @@ S log [S]ource locations as SSA builder progresses. L build distinct packages seria[L]ly instead of in parallel. N build [N]aive SSA form: don't replace local loads/stores with registers. I build bare [I]nit functions: no init guards or calls to dependent inits. +G instantiate [G]eneric function bodies via monomorphization ` func (m BuilderMode) String() string { @@ -69,6 +70,9 @@ func (m BuilderMode) String() string { if m&BareInits != 0 { buf.WriteByte('I') } + if m&InstantiateGenerics != 0 { + buf.WriteByte('G') + } return buf.String() } @@ -93,6 +97,8 @@ func (m *BuilderMode) Set(s string) error { mode |= BuildSerially case 'I': mode |= BareInits + case 'G': + mode |= InstantiateGenerics default: return fmt.Errorf("unknown BuilderMode option: %q", c) } 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 d0f3bbf7..b8e53923 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/print.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/print.go @@ -24,7 +24,6 @@ import ( // Functions (including methods) and Globals use RelString and // all types are displayed with relType, so that only cross-package // references are package-qualified. -// func relName(v Value, i Instruction) string { var from *types.Package if i != nil { 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 6e65d760..7d713027 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/sanity.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/sanity.go @@ -30,7 +30,6 @@ type sanity struct { // // Sanity-checking is intended to facilitate the debugging of code // transformation passes. -// func sanityCheck(fn *Function, reporter io.Writer) bool { if reporter == nil { reporter = os.Stderr @@ -40,7 +39,6 @@ func sanityCheck(fn *Function, reporter io.Writer) bool { // mustSanityCheck is like sanityCheck but panics instead of returning // a negative result. -// func mustSanityCheck(fn *Function, reporter io.Writer) { if !sanityCheck(fn, reporter) { fn.WriteTo(os.Stderr) @@ -404,6 +402,8 @@ func (s *sanity) checkFunction(fn *Function) bool { // - check params match signature // - check transient fields are nil // - warn if any fn.Locals do not appear among block instructions. + + // TODO(taking): Sanity check _Origin, _TypeParams, and _TypeArgs. s.fn = fn if fn.Prog == nil { s.errorf("nil Prog") @@ -419,14 +419,20 @@ func (s *sanity) checkFunction(fn *Function) bool { if strings.HasPrefix(fn.Synthetic, "wrapper ") || strings.HasPrefix(fn.Synthetic, "bound ") || strings.HasPrefix(fn.Synthetic, "thunk ") || - strings.HasSuffix(fn.name, "Error") { + strings.HasSuffix(fn.name, "Error") || + strings.HasPrefix(fn.Synthetic, "instantiation") || + (fn.parent != nil && len(fn._TypeArgs) > 0) /* anon fun in instance */ { // ok } else { s.errorf("nil Pkg") } } if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn { - s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn) + if strings.HasPrefix(fn.Synthetic, "instantiation") && fn.Prog.mode&InstantiateGenerics != 0 { + // ok + } else { + 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/golang.org/x/tools/go/ssa/source.go b/tools/vendor/golang.org/x/tools/go/ssa/source.go index 7e2a369d..b9a08363 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/source.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/source.go @@ -14,6 +14,8 @@ import ( "go/ast" "go/token" "go/types" + + "golang.org/x/tools/internal/typeparams" ) // EnclosingFunction returns the function that contains the syntax @@ -23,11 +25,10 @@ import ( // enclosed by the package's init() function. // // Returns nil if not found; reasons might include: -// - the node is not enclosed by any function. -// - the node is within an anonymous function (FuncLit) and -// its SSA function has not been created yet -// (pkg.Build() has not yet been called). -// +// - the node is not enclosed by any function. +// - the node is within an anonymous function (FuncLit) and +// its SSA function has not been created yet +// (pkg.Build() has not yet been called). func EnclosingFunction(pkg *Package, path []ast.Node) *Function { // Start with package-level function... fn := findEnclosingPackageLevelFunction(pkg, path) @@ -65,14 +66,12 @@ outer: // depend on whether SSA code for pkg has been built, so it can be // used to quickly reject check inputs that will cause // EnclosingFunction to fail, prior to SSA building. -// func HasEnclosingFunction(pkg *Package, path []ast.Node) bool { return findEnclosingPackageLevelFunction(pkg, path) != nil } // findEnclosingPackageLevelFunction returns the Function // corresponding to the package-level function enclosing path. -// func findEnclosingPackageLevelFunction(pkg *Package, path []ast.Node) *Function { if n := len(path); n >= 2 { // [... {Gen,Func}Decl File] switch decl := path[n-2].(type) { @@ -107,7 +106,6 @@ func findEnclosingPackageLevelFunction(pkg *Package, path []ast.Node) *Function // findNamedFunc returns the named function whose FuncDecl.Ident is at // position pos. -// func findNamedFunc(pkg *Package, pos token.Pos) *Function { // Look at all package members and method sets of named types. // Not very efficient. @@ -135,13 +133,13 @@ func findNamedFunc(pkg *Package, pos token.Pos) *Function { // expression e. // // It returns nil if no value was found, e.g. -// - the expression is not lexically contained within f; -// - f was not built with debug information; or -// - e is a constant expression. (For efficiency, no debug -// information is stored for constants. Use -// go/types.Info.Types[e].Value instead.) -// - e is a reference to nil or a built-in function. -// - the value was optimised away. +// - the expression is not lexically contained within f; +// - f was not built with debug information; or +// - e is a constant expression. (For efficiency, no debug +// information is stored for constants. Use +// go/types.Info.Types[e].Value instead.) +// - e is a reference to nil or a built-in function. +// - the value was optimised away. // // If e is an addressable expression used in an lvalue context, // value is the address denoted by e, and isAddr is true. @@ -153,7 +151,6 @@ func findNamedFunc(pkg *Package, pos token.Pos) *Function { // astutil.PathEnclosingInterval to locate the ast.Node, then // EnclosingFunction to locate the Function, then ValueForExpr to find // the ssa.Value.) -// func (f *Function) ValueForExpr(e ast.Expr) (value Value, isAddr bool) { if f.debugInfo() { // (opt) e = unparen(e) @@ -175,7 +172,6 @@ func (f *Function) ValueForExpr(e ast.Expr) (value Value, isAddr bool) { // 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] } @@ -184,7 +180,6 @@ func (prog *Program) Package(obj *types.Package) *Package { // 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. -// func (prog *Program) packageLevelMember(obj types.Object) Member { if pkg, ok := prog.packages[obj.Pkg()]; ok { return pkg.objects[obj] @@ -192,12 +187,17 @@ 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. -// func (prog *Program) FuncValue(obj *types.Func) *Function { fn, _ := prog.packageLevelMember(obj).(*Function) return fn @@ -205,7 +205,6 @@ func (prog *Program) FuncValue(obj *types.Func) *Function { // ConstValue returns the SSA Value denoted by the source-level named // constant obj. -// func (prog *Program) ConstValue(obj *types.Const) *Const { // TODO(adonovan): opt: share (don't reallocate) // Consts for const objects and constant ast.Exprs. @@ -237,8 +236,9 @@ func (prog *Program) ConstValue(obj *types.Const) *Const { // If the identifier is a field selector and its base expression is // non-addressable, then VarValue returns the value of that field. // For example: -// func f() struct {x int} -// f().x // VarValue(x) returns a *Field instruction of type int +// +// func f() struct {x int} +// f().x // VarValue(x) returns a *Field instruction of type int // // All other identifiers denote addressable locations (variables). // For them, VarValue may return either the variable's address or its @@ -247,14 +247,14 @@ func (prog *Program) ConstValue(obj *types.Const) *Const { // // If !isAddr, the returned value is the one associated with the // specific identifier. For example, -// var x int // VarValue(x) returns Const 0 here -// x = 1 // VarValue(x) returns Const 1 here +// +// var x int // VarValue(x) returns Const 0 here +// x = 1 // VarValue(x) returns Const 1 here // // It is not specified whether the value or the address is returned in // any particular case, as it may depend upon optimizations performed // during SSA code generation, such as registerization, constant // folding, avoidance of materialization of subexpressions, etc. -// func (prog *Program) VarValue(obj *types.Var, pkg *Package, ref []ast.Node) (value Value, isAddr bool) { // All references to a var are local to some function, possibly init. fn := EnclosingFunction(pkg, ref) 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 ea5b68e2..cbc638c8 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/ssa.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/ssa.go @@ -16,6 +16,7 @@ import ( "sync" "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/typeparams" ) // A Program is a partial or complete Go program converted to SSA form. @@ -26,13 +27,16 @@ type Program struct { mode BuilderMode // set of mode bits for SSA construction MethodSets typeutil.MethodSetCache // cache of type-checker's method-sets - canon canonizer // type canonicalization map + canon *canonizer // type canonicalization map + ctxt *typeparams.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[*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 // 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 is parameterized. } // A Package is a single analyzed Go package containing Members for @@ -43,7 +47,6 @@ type Program struct { // Members also contains entries for "init" (the synthetic package // initializer) and "init#%d", the nth declared init function, // and unspecified other things too. -// type Package struct { Prog *Program // the owning program Pkg *types.Package // the corresponding go/types.Package @@ -58,12 +61,12 @@ type Package struct { 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) } // A Member is a member of a Go package, implemented by *NamedConst, // *Global, *Function, or *Type; they are created by package-level // const, var, func and type declarations respectively. -// type Member interface { Name() string // declared name of the package member String() string // package-qualified name of the package member @@ -89,7 +92,6 @@ type Type struct { // // NB: a NamedConst is not a Value; it contains a constant Value, which // it augments with the name and position of its 'const' declaration. -// type NamedConst struct { object *types.Const Value *Const @@ -165,7 +167,6 @@ type Value interface { // An Instruction that defines a value (e.g. BinOp) also implements // the Value interface; an Instruction that only has an effect (e.g. Store) // does not. -// type Instruction interface { // String returns the disassembled form of this value. // @@ -242,7 +243,6 @@ type Instruction interface { // Node is provided to simplify SSA graph algorithms. Clients should // use the more specific and informative Value or Instruction // interfaces where appropriate. -// type Node interface { // Common methods: String() string @@ -294,10 +294,20 @@ type Node interface { // // Type() returns the function's Signature. // +// A function is generic iff it has a non-empty TypeParams list and an +// empty TypeArgs list. TypeParams lists the type parameters of the +// function's Signature or the receiver's type parameters for a method. +// +// The instantiation of a generic function is a concrete function. These +// are a list of n>0 TypeParams and n TypeArgs. An instantiation will +// have a generic Origin function. There is at most one instantiation +// of each origin type per Identical() type list. Instantiations do not +// belong to any Pkg. The generic function and the instantiations will +// share the same source Pos for the functions and the instructions. type Function struct { name string - object types.Object // a declared *types.Func or one of its wrappers - method *types.Selection // info about provenance of synthetic methods + object types.Object // a declared *types.Func or one of its wrappers + method *selection // info about provenance of synthetic methods; thunk => non-nil Signature *types.Signature pos token.Pos @@ -313,15 +323,21 @@ type Function struct { Recover *BasicBlock // optional; control transfers here after recovered panic AnonFuncs []*Function // anonymous functions directly beneath this one referrers []Instruction // referring instructions (iff Parent() != nil) + built bool // function has completed both CREATE and BUILD phase. + + _Origin *Function // the origin function if this the instantiation of a generic function. nil if Parent() != nil. + _TypeParams []*typeparams.TypeParam // the type paramaters of this function. len(TypeParams) == len(_TypeArgs) => runtime function + _TypeArgs []types.Type // type arguments for for an instantiation. len(_TypeArgs) != 0 => instantiation // 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 - targets *targets // linked stack of branch targets - lblocks map[*ast.Object]*lblock // labelled blocks - info *types.Info // *types.Info to build from. nil for wrappers. + currentBlock *BasicBlock // where to emit code + objects map[types.Object]Value // addresses of local variables + namedResults []*Alloc // tuple of named 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 // type substitution cache } // BasicBlock represents an SSA basic block. @@ -343,7 +359,6 @@ type Function struct { // // The order of Preds and Succs is significant (to Phi and If // instructions, respectively). -// type BasicBlock struct { Index int // index of this block within Parent().Blocks Comment string // optional label; no semantic significance @@ -373,7 +388,6 @@ type BasicBlock struct { // // Pos() returns the position of the value that was captured, which // belongs to an enclosing function. -// type FreeVar struct { name string typ types.Type @@ -386,7 +400,6 @@ 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 @@ -412,10 +425,10 @@ type Parameter struct { // Pos() returns token.NoPos. // // Example printed form: -// 42:int +// +// 42:int // "hello":untyped string // 3+4i:MyComplex -// type Const struct { typ types.Type Value constant.Value @@ -426,7 +439,6 @@ type Const struct { // // Pos() returns the position of the ast.ValueSpec.Names[*] // identifier. -// type Global struct { name string object types.Object // a *types.Var; may be nil for synthetics e.g. init$guard @@ -445,16 +457,15 @@ type Global struct { // Go spec (excluding "make" and "new") or one of these ssa-defined // intrinsics: // -// // wrapnilchk returns ptr if non-nil, panics otherwise. -// // (For use in indirection wrappers.) -// func ssa:wrapnilchk(ptr *T, recvType, methodName string) *T +// // wrapnilchk returns ptr if non-nil, panics otherwise. +// // (For use in indirection wrappers.) +// func ssa:wrapnilchk(ptr *T, recvType, methodName string) *T // // Object() returns a *types.Builtin for built-ins defined by the spec, // nil for others. // // Type() returns a *types.Signature representing the effective // signature of the built-in for this call. -// type Builtin struct { name string sig *types.Signature @@ -489,9 +500,9 @@ type Builtin struct { // allocates a varargs slice. // // Example printed form: -// t0 = local int -// t1 = new int // +// t0 = local int +// t1 = new int type Alloc struct { register Comment string @@ -509,8 +520,8 @@ type Alloc struct { // during SSA renaming. // // Example printed form: -// t2 = phi [0: t0, 1: t1] // +// t2 = phi [0: t0, 1: t1] type Phi struct { register Comment string // a hint as to its purpose @@ -528,10 +539,10 @@ type Phi struct { // Pos() returns the ast.CallExpr.Lparen, if explicit in the source. // // Example printed form: -// t2 = println(t0, t1) -// t4 = t3() -// t7 = invoke t5.Println(...t6) // +// t2 = println(t0, t1) +// t4 = t3() +// t7 = invoke t5.Println(...t6) type Call struct { register Call CallCommon @@ -542,8 +553,8 @@ type Call struct { // Pos() returns the ast.BinaryExpr.OpPos, if explicit in the source. // // Example printed form: -// t1 = t0 + 1:int // +// t1 = t0 + 1:int type BinOp struct { register // One of: @@ -573,9 +584,9 @@ type BinOp struct { // specified. // // Example printed form: -// t0 = *x -// t2 = <-t1,ok // +// t0 = *x +// t2 = <-t1,ok type UnOp struct { register Op token.Token // One of: NOT SUB ARROW MUL XOR ! - <- * ^ @@ -587,11 +598,11 @@ type UnOp struct { // change to Type(). // // Type changes are permitted: -// - between a named type and its underlying type. -// - between two named types of the same underlying type. -// - between (possibly named) pointers to identical base types. -// - from a bidirectional channel to a read- or write-channel, -// optionally adding/removing a name. +// - between a named type and its underlying type. +// - between two named types of the same underlying type. +// - between (possibly named) pointers to identical base types. +// - from a bidirectional channel to a read- or write-channel, +// optionally adding/removing a name. // // This operation cannot fail dynamically. // @@ -599,8 +610,8 @@ type UnOp struct { // from an explicit conversion in the source. // // Example printed form: -// t1 = changetype *int <- IntPtr (t0) // +// t1 = changetype *int <- IntPtr (t0) type ChangeType struct { register X Value @@ -611,12 +622,13 @@ type ChangeType struct { // // A conversion may change the value and representation of its operand. // Conversions are permitted: -// - between real numeric types. -// - between complex numeric types. -// - between string and []byte or []rune. -// - between pointers and unsafe.Pointer. -// - between unsafe.Pointer and uintptr. -// - from (Unicode) integer to (UTF-8) string. +// - between real numeric types. +// - between complex numeric types. +// - between string and []byte or []rune. +// - between pointers and unsafe.Pointer. +// - between unsafe.Pointer and uintptr. +// - from (Unicode) integer to (UTF-8) string. +// // A conversion may imply a type name change also. // // This operation cannot fail dynamically. @@ -628,8 +640,8 @@ type ChangeType struct { // from an explicit conversion in the source. // // Example printed form: -// t1 = convert []byte <- string (t0) // +// t1 = convert []byte <- string (t0) type Convert struct { register X Value @@ -645,8 +657,8 @@ type Convert struct { // otherwise. // // Example printed form: -// t1 = change interface interface{} <- I (t0) // +// t1 = change interface interface{} <- I (t0) type ChangeInterface struct { register X Value @@ -659,8 +671,8 @@ type ChangeInterface struct { // from an explicit conversion in the source. // // Example printed form: -// t1 = slice to array pointer *[4]byte <- []byte (t0) // +// t1 = slice to array pointer *[4]byte <- []byte (t0) type SliceToArrayPointer struct { register X Value @@ -673,15 +685,16 @@ type SliceToArrayPointer struct { // of X, and Program.MethodValue(m) to find the implementation of a method. // // To construct the zero value of an interface type T, use: -// NewConst(constant.MakeNil(), T, pos) +// +// NewConst(constant.MakeNil(), T, pos) // // Pos() returns the ast.CallExpr.Lparen, if the instruction arose // from an explicit conversion in the source. // // Example printed form: -// t1 = make interface{} <- int (42:int) -// t2 = make Stringer <- t0 // +// t1 = make interface{} <- int (42:int) +// t2 = make Stringer <- t0 type MakeInterface struct { register X Value @@ -696,9 +709,9 @@ type MakeInterface struct { // closure or the ast.SelectorExpr.Sel for a bound method closure. // // Example printed form: -// t0 = make closure anon@1.2 [x y z] -// t1 = make closure bound$(main.I).add [i] // +// t0 = make closure anon@1.2 [x y z] +// t1 = make closure bound$(main.I).add [i] type MakeClosure struct { register Fn Value // always a *Function @@ -714,9 +727,9 @@ type MakeClosure struct { // the ast.CompositeLit.Lbrack if created by a literal. // // Example printed form: -// t1 = make map[string]int t0 -// t1 = make StringIntMap t0 // +// t1 = make map[string]int t0 +// t1 = make StringIntMap t0 type MakeMap struct { register Reserve Value // initial space reservation; nil => default @@ -731,9 +744,9 @@ type MakeMap struct { // created it. // // Example printed form: -// t0 = make chan int 0 -// t0 = make IntChan 0 // +// t0 = make chan int 0 +// t0 = make IntChan 0 type MakeChan struct { register Size Value // int; size of buffer; zero => synchronous. @@ -753,9 +766,9 @@ type MakeChan struct { // created it. // // Example printed form: -// t1 = make []string 1:int t0 -// t1 = make StringSlice 1:int t0 // +// t1 = make []string 1:int t0 +// t1 = make StringSlice 1:int t0 type MakeSlice struct { register Len Value @@ -776,8 +789,8 @@ type MakeSlice struct { // NoPos if not explicit in the source (e.g. a variadic argument slice). // // Example printed form: -// t1 = slice t0[1:] // +// t1 = slice t0[1:] type Slice struct { register X Value // slice, string, or *array @@ -795,11 +808,12 @@ type Slice struct { // Type() returns a (possibly named) *types.Pointer. // // Pos() returns the position of the ast.SelectorExpr.Sel for the -// field, if explicit in the source. +// field, if explicit in the source. For implicit selections, returns +// the position of the inducing explicit selection. // // Example printed form: -// t1 = &t0.name [#1] // +// t1 = &t0.name [#1] type FieldAddr struct { register X Value // *struct @@ -813,11 +827,12 @@ type FieldAddr struct { // package-local identifiers and permit compact representations. // // Pos() returns the position of the ast.SelectorExpr.Sel for the -// field, if explicit in the source. -// +// field, if explicit in the source. For implicit selections, returns +// the position of the inducing explicit selection. + // Example printed form: -// t1 = t0.name [#1] // +// t1 = t0.name [#1] type Field struct { register X Value // struct @@ -839,8 +854,8 @@ type Field struct { // explicit in the source. // // Example printed form: -// t2 = &t0[t1] // +// t2 = &t0[t1] type IndexAddr struct { register X Value // slice or *array, @@ -853,8 +868,8 @@ type IndexAddr struct { // explicit in the source. // // Example printed form: -// t2 = t0[t1] // +// t2 = t0[t1] type Index struct { register X Value // array @@ -872,9 +887,9 @@ type Index struct { // Pos() returns the ast.IndexExpr.Lbrack, if explicit in the source. // // Example printed form: -// t2 = t0[t1] -// t5 = t3[t4],ok // +// t2 = t0[t1] +// t5 = t3[t4],ok type Lookup struct { register X Value // string or map @@ -884,7 +899,6 @@ type Lookup struct { // SelectState is a helper for Select. // It represents one goal state and its corresponding communication. -// type SelectState struct { Dir types.ChanDir // direction of case (SendOnly or RecvOnly) Chan Value // channel to use (for send or receive) @@ -899,7 +913,9 @@ type SelectState struct { // Let n be the number of States for which Dir==RECV and T_i (0<=i= 2 { if i, ok := b.Instrs[n-1].(*ssa.If); ok { @@ -216,7 +213,6 @@ func isComparisonBlock(b *ssa.BasicBlock) (v ssa.Value, k *ssa.Const) { // isTypeAssertBlock returns the operands (y, x, T) if a block ends with // a type assertion "if y, ok := x.(T); ok {". -// func isTypeAssertBlock(b *ssa.BasicBlock) (y, x ssa.Value, T types.Type) { if n := len(b.Instrs); n >= 4 { if i, ok := b.Instrs[n-1].(*ssa.If); ok { 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 3424e8a3..5f27050b 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 @@ -18,7 +18,6 @@ import "golang.org/x/tools/go/ssa" // synthetic wrappers. // // Precondition: all packages are built. -// func AllFunctions(prog *ssa.Program) map[*ssa.Function]bool { visit := visitor{ prog: prog, 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 0e9263fd..b29130ea 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/subst.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/subst.go @@ -143,6 +143,15 @@ func (subst *subster) typ(t types.Type) (res types.Type) { } } +// types returns the result of {subst.typ(ts[i])}. +func (subst *subster) types(ts []types.Type) []types.Type { + res := make([]types.Type, len(ts)) + for i := range ts { + res[i] = subst.typ(ts[i]) + } + return res +} + func (subst *subster) tuple(t *types.Tuple) *types.Tuple { if t != nil { if vars := subst.varlist(t); vars != nil { @@ -360,7 +369,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 types.NewSignature(recv, params, results, t.Variadic()) + return typeparams.NewSignatureType(recv, nil, nil, params, results, t.Variadic()) } return t } 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 01021936..80c7d5cb 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/util.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/util.go @@ -17,6 +17,7 @@ import ( "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/typeparams" ) //// Sanity checking utilities @@ -35,7 +36,6 @@ func unparen(e ast.Expr) ast.Expr { return astutil.Unparen(e) } // isBlankIdent returns true iff e is an Ident with name "_". // They have no associated types.Object, and thus no type. -// func isBlankIdent(e ast.Expr) bool { id, ok := e.(*ast.Ident) return ok && id.Name == "_" @@ -64,11 +64,16 @@ func recvType(obj *types.Func) types.Type { return obj.Type().(*types.Signature).Recv().Type() } +// isUntyped returns true for types that are untyped. +func isUntyped(typ types.Type) bool { + b, ok := typ.(*types.Basic) + return ok && b.Info()&types.IsUntyped != 0 +} + // 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. // Don't forget trailing parens! -// func logStack(format string, args ...interface{}) func() { msg := fmt.Sprintf(format, args...) io.WriteString(os.Stderr, msg) @@ -100,25 +105,134 @@ 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 _, basic := T.(*types.Basic); !basic { + if !added[T] { + added[T] = true + filtered = append(filtered, T) + } + } + } + return filtered +} + +// isGeneric returns true if a package-level member is generic. +func isGeneric(m Member) bool { + switch m := m.(type) { + case *NamedConst, *Global: + return false + case *Type: + // lifted from types.isGeneric. + named, _ := m.Type().(*types.Named) + return named != nil && named.Obj() != nil && typeparams.NamedTypeArgs(named) == nil && typeparams.ForNamed(named) != nil + case *Function: + return len(m._TypeParams) != len(m._TypeArgs) + default: + panic("unreachable") + } +} + +// receiverTypeArgs returns the type arguments to a function's reciever. +// Returns an empty list if obj does not have a reciever or its reciever does not have type arguments. +func receiverTypeArgs(obj *types.Func) []types.Type { + rtype := recvType(obj) + if rtype == nil { + return nil + } + if isPointer(rtype) { + rtype = rtype.(*types.Pointer).Elem() + } + named, ok := rtype.(*types.Named) + if !ok { + return nil + } + ts := typeparams.NamedTypeArgs(named) + if ts.Len() == 0 { + return nil + } + targs := make([]types.Type, ts.Len()) + for i := 0; i < ts.Len(); i++ { + targs[i] = ts.At(i) + } + return targs +} + +// recvAsFirstArg takes a method signature and returns a function +// signature with receiver as the first parameter. +func recvAsFirstArg(sig *types.Signature) *types.Signature { + params := make([]*types.Var, 0, 1+sig.Params().Len()) + params = append(params, sig.Recv()) + 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()) +} + +// instance returns whether an expression is a simple or qualified identifier +// that is a generic instantiation. +func instance(info *types.Info, expr ast.Expr) bool { + // Compare the logic here against go/types.instantiatedIdent, + // which also handles *IndexExpr and *IndexListExpr. + var id *ast.Ident + switch x := expr.(type) { + case *ast.Ident: + id = x + case *ast.SelectorExpr: + id = x.Sel + default: + return false + } + _, ok := typeparams.GetInstances(info)[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 + if targList == nil { + return nil + } + + targs := make([]types.Type, targList.Len()) + for i, n := 0, targList.Len(); i < n; i++ { + targs[i] = targList.At(i) + } + return targs +} + // Mapping of a type T to a canonical instance C s.t. types.Indentical(T, C). // Thread-safe. type canonizer struct { mu sync.Mutex - canon typeutil.Map // map from type to a canonical instance + types typeutil.Map // map from type to a canonical instance + lists typeListMap // map from a list of types to a canonical instance +} + +func newCanonizer() *canonizer { + c := &canonizer{} + h := typeutil.MakeHasher() + c.types.SetHasher(h) + c.lists.hasher = h + return c } -// Tuple returns a canonical representative of a Tuple of types. -// Representative of the empty Tuple is nil. -func (c *canonizer) Tuple(ts []types.Type) *types.Tuple { +// List returns a canonical representative of a list of types. +// Representative of the empty list is nil. +func (c *canonizer) List(ts []types.Type) *typeList { if len(ts) == 0 { return nil } - vars := make([]*types.Var, len(ts)) - for i, t := range ts { - vars[i] = anonVar(t) - } - tuple := types.NewTuple(vars...) - return c.Type(tuple).(*types.Tuple) + + c.mu.Lock() + defer c.mu.Unlock() + return c.lists.rep(ts) } // Type returns a canonical representative of type T. @@ -126,9 +240,90 @@ func (c *canonizer) Type(T types.Type) types.Type { c.mu.Lock() defer c.mu.Unlock() - if r := c.canon.At(T); r != nil { + if r := c.types.At(T); r != nil { return r.(types.Type) } - c.canon.Set(T, T) + c.types.Set(T, T) return T } + +// A type for representating an canonized list of types. +type typeList []types.Type + +func (l *typeList) identical(ts []types.Type) bool { + if l == nil { + return len(ts) == 0 + } + n := len(*l) + if len(ts) != n { + return false + } + for i, left := range *l { + right := ts[i] + if !types.Identical(left, right) { + return false + } + } + return true +} + +type typeListMap struct { + hasher typeutil.Hasher + buckets map[uint32][]*typeList +} + +// rep returns a canonical representative of a slice of types. +func (m *typeListMap) rep(ts []types.Type) *typeList { + if m == nil || len(ts) == 0 { + return nil + } + + if m.buckets == nil { + m.buckets = make(map[uint32][]*typeList) + } + + h := m.hash(ts) + bucket := m.buckets[h] + for _, l := range bucket { + if l.identical(ts) { + return l + } + } + + // not present. create a representative. + cp := make(typeList, len(ts)) + copy(cp, ts) + rep := &cp + + m.buckets[h] = append(bucket, rep) + return rep +} + +func (m *typeListMap) hash(ts []types.Type) uint32 { + if m == nil { + return 0 + } + // Some smallish prime far away from typeutil.Hash. + n := len(ts) + h := uint32(13619) + 2*uint32(n) + for i := 0; i < n; i++ { + h += 3 * m.hasher.Hash(ts[i]) + } + return h +} + +// 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 { + recv := recvType(m) + if p, ok := recv.(*types.Pointer); ok { + recv = p.Elem() + } + named := recv.(*types.Named) + inst, err := typeparams.Instantiate(ctxt, typeparams.NamedTypeOrigin(named), targs, false) + if err != nil { + panic(err) + } + rep := canon.Type(inst) + obj, _, _ := types.LookupFieldOrMethod(rep, true, m.Pkg(), m.Name()) + return obj.(*types.Func) +} 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 90ddc9df..3f2267c8 100644 --- a/tools/vendor/golang.org/x/tools/go/ssa/wrappers.go +++ b/tools/vendor/golang.org/x/tools/go/ssa/wrappers.go @@ -22,6 +22,7 @@ package ssa import ( "fmt" + "go/token" "go/types" ) @@ -41,16 +42,15 @@ import ( // - the result may be a thunk or a wrapper. // // EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) -// -func makeWrapper(prog *Program, sel *types.Selection) *Function { - obj := sel.Obj().(*types.Func) // the declared function - sig := sel.Type().(*types.Signature) // type of this wrapper +func makeWrapper(prog *Program, sel *selection, cr *creator) *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 { + if sel.kind == types.MethodExpr { name += "$thunk" description = "thunk" recv = sig.Params().At(0) @@ -60,7 +60,7 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { recv = sig.Recv() } - description = fmt.Sprintf("%s for %s", description, sel.Obj()) + description = fmt.Sprintf("%s for %s", description, sel.obj) if prog.mode&LogSource != 0 { defer logStack("make %s to (%s)", description, recv.Type())() } @@ -74,14 +74,15 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { pos: obj.Pos(), info: nil, // info is not set on wrappers. } + cr.Add(fn) fn.startBody() fn.addSpilledParam(recv) createParams(fn, start) - indices := sel.Index() + indices := sel.index var v Value = fn.Locals[0] // spilled receiver - if isPointer(sel.Recv()) { + if isPointer(sel.recv) { v = emitLoad(fn, v) // For simple indirection wrappers, perform an informative nil-check: @@ -91,13 +92,13 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { 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(sel.recv), anonVar(tString), anonVar(tString)), + types.NewTuple(anonVar(sel.recv)), false), } c.Call.Args = []Value{ v, - stringConst(deref(sel.Recv()).String()), - stringConst(sel.Obj().Name()), + stringConst(deref(sel.recv).String()), + stringConst(sel.obj.Name()), } c.setType(v.Type()) v = fn.emit(&c) @@ -112,7 +113,7 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { // Load) in preference to value extraction (Field possibly // preceded by Load). - v = emitImplicitSelections(fn, v, indices[:len(indices)-1]) + v = emitImplicitSelections(fn, v, indices[:len(indices)-1], token.NoPos) // Invariant: v is a pointer, either // value of implicit *C field, or @@ -123,7 +124,11 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { if !isPointer(r) { v = emitLoad(fn, v) } - c.Call.Value = prog.declaredFunc(obj) + callee := prog.originFunc(obj) + if len(callee._TypeParams) > 0 { + callee = prog.instances[callee].lookupOrCreate(receiverTypeArgs(obj), cr) + } + c.Call.Value = callee c.Call.Args = append(c.Call.Args, v) } else { c.Call.Method = obj @@ -134,13 +139,13 @@ func makeWrapper(prog *Program, sel *types.Selection) *Function { } emitTailCall(fn, &c) fn.finishBody() + fn.done() return fn } // createParams creates parameters for wrapper method fn based on its // Signature.Params, which do not include the receiver. // start is the index of the first regular parameter to use. -// func createParams(fn *Function, start int) { tparams := fn.Signature.Params() for i, n := start, tparams.Len(); i < n; i++ { @@ -159,26 +164,28 @@ func createParams(fn *Function, start int) { // Use MakeClosure with such a wrapper to construct a bound method // closure. e.g.: // -// type T int or: type T interface { meth() } -// func (t T) meth() -// var t T -// f := t.meth -// f() // calls t.meth() +// type T int or: type T interface { meth() } +// func (t T) meth() +// var t T +// f := t.meth +// f() // calls t.meth() // // f is a closure of a synthetic wrapper defined as if by: // -// f := func() { return t.meth() } +// f := func() { return t.meth() } // // Unlike makeWrapper, makeBound 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) *Function { +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[obj] + fn, ok := prog.bounds[key] if !ok { description := fmt.Sprintf("bound method wrapper for %s", obj) if prog.mode&LogSource != 0 { @@ -193,6 +200,7 @@ func makeBound(prog *Program, obj *types.Func) *Function { 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} @@ -201,7 +209,11 @@ func makeBound(prog *Program, obj *types.Func) *Function { var c Call if !isInterface(recvType(obj)) { // concrete - c.Call.Value = prog.declaredFunc(obj) + callee := prog.originFunc(obj) + if len(callee._TypeParams) > 0 { + callee = prog.instances[callee].lookupOrCreate(targs, cr) + } + c.Call.Value = callee c.Call.Args = []Value{fv} } else { c.Call.Value = fv @@ -212,8 +224,9 @@ func makeBound(prog *Program, obj *types.Func) *Function { } emitTailCall(fn, &c) fn.finishBody() + fn.done() - prog.bounds[obj] = fn + prog.bounds[key] = fn } return fn } @@ -221,41 +234,40 @@ func makeBound(prog *Program, obj *types.Func) *Function { // -- thunks ----------------------------------------------------------- // makeThunk returns a thunk, a synthetic function that delegates to a -// concrete or interface method denoted by sel.Obj(). The resulting +// concrete or interface method denoted by sel.obj. The resulting // function has no receiver, but has an additional (first) regular // parameter. // -// Precondition: sel.Kind() == types.MethodExpr. +// Precondition: sel.kind == types.MethodExpr. // -// type T int or: type T interface { meth() } -// func (t T) meth() -// f := T.meth -// var t T -// f(t) // calls t.meth() +// type T int or: type T interface { meth() } +// func (t T) meth() +// f := T.meth +// var t T +// f(t) // calls t.meth() // // f is a synthetic wrapper defined as if by: // -// f := func(t T) { return t.meth() } +// 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 { +func makeThunk(prog *Program, sel *selection, cr *creator) *Function { + if sel.kind != types.MethodExpr { panic(sel) } - // Canonicalize sel.Recv() to avoid constructing duplicate thunks. - canonRecv := prog.canon.Type(sel.Recv()) + // Canonicalize sel.recv to avoid constructing duplicate thunks. + canonRecv := prog.canon.Type(sel.recv) key := selectionKey{ - kind: sel.Kind(), + kind: sel.kind, recv: canonRecv, - obj: sel.Obj(), - index: fmt.Sprint(sel.Index()), - indirect: sel.Indirect(), + obj: sel.obj, + index: fmt.Sprint(sel.index), + indirect: sel.indirect, } prog.methodsMu.Lock() @@ -263,7 +275,7 @@ func makeThunk(prog *Program, sel *types.Selection) *Function { fn, ok := prog.thunks[key] if !ok { - fn = makeWrapper(prog, sel) + fn = makeWrapper(prog, sel, cr) if fn.Signature.Recv() != nil { panic(fn) // unexpected receiver } @@ -284,3 +296,31 @@ type selectionKey struct { 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 { + kind types.SelectionKind + recv types.Type + typ types.Type + obj types.Object + index []int + indirect bool +} + +func toSelection(sel *types.Selection) *selection { + return &selection{ + kind: sel.Kind(), + recv: sel.Recv(), + typ: sel.Type(), + obj: sel.Obj(), + index: sel.Index(), + indirect: sel.Indirect(), + } +} 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 7e96fc23..c160acb6 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 @@ -14,8 +14,10 @@ // distinct but logically equivalent. // // A single object may have multiple paths. In this example, -// type A struct{ X int } -// type B A +// +// type A struct{ X int } +// type B A +// // the field X has two paths due to its membership of both A and B. // The For(obj) function always returns one of these paths, arbitrarily // but consistently. @@ -45,30 +47,30 @@ type Path string // The sequences represent a path through the package/object/type graph. // We classify these operators by their type: // -// PO package->object Package.Scope.Lookup -// OT object->type Object.Type -// TT type->type Type.{Elem,Key,Params,Results,Underlying} [EKPRU] -// TO type->object Type.{At,Field,Method,Obj} [AFMO] +// PO package->object Package.Scope.Lookup +// OT object->type Object.Type +// TT type->type Type.{Elem,Key,Params,Results,Underlying} [EKPRU] +// TO type->object Type.{At,Field,Method,Obj} [AFMO] // // All valid paths start with a package and end at an object // and thus may be defined by the regular language: // -// objectpath = PO (OT TT* TO)* +// objectpath = PO (OT TT* TO)* // // The concrete encoding follows directly: -// - The only PO operator is Package.Scope.Lookup, which requires an identifier. -// - The only OT operator is Object.Type, -// which we encode as '.' because dot cannot appear in an identifier. -// - The TT operators are encoded as [EKPRUTC]; -// one of these (TypeParam) requires an integer operand, -// which is encoded as a string of decimal digits. -// - The TO operators are encoded as [AFMO]; -// three of these (At,Field,Method) require an integer operand, -// which is encoded as a string of decimal digits. -// These indices are stable across different representations -// of the same package, even source and export data. -// The indices used are implementation specific and may not correspond to -// the argument to the go/types function. +// - 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, +// which is encoded as a string of decimal digits. +// - The TO operators are encoded as [AFMO]; +// three of these (At,Field,Method) require an integer operand, +// which is encoded as a string of decimal digits. +// These indices are stable across different representations +// of the same package, even source and export data. +// The indices used are implementation specific and may not correspond to +// the argument to the go/types function. // // In the example below, // @@ -81,15 +83,14 @@ type Path string // field X has the path "T.UM0.RA1.F0", // representing the following sequence of operations: // -// p.Lookup("T") T -// .Type().Underlying().Method(0). f -// .Type().Results().At(1) b -// .Type().Field(0) X +// p.Lookup("T") T +// .Type().Underlying().Method(0). f +// .Type().Results().At(1) b +// .Type().Field(0) X // // The encoding is not maximally compact---every R or P is // followed by an A, for example---but this simplifies the // encoder and decoder. -// const ( // object->type operators opType = '.' // .Type() (Object) @@ -136,10 +137,10 @@ const ( // // For(X) would return a path that denotes the following sequence of operations: // -// p.Scope().Lookup("T") (TypeName T) -// .Type().Underlying().Method(0). (method Func f) -// .Type().Results().At(1) (field Var b) -// .Type().Field(0) (field Var X) +// p.Scope().Lookup("T") (TypeName T) +// .Type().Underlying().Method(0). (method Func f) +// .Type().Results().At(1) (field Var b) +// .Type().Field(0) (field Var X) // // where p is the package (*types.Package) to which X belongs. func For(obj types.Object) (Path, error) { @@ -223,10 +224,11 @@ func For(obj types.Object) (Path, error) { if recv := obj.Type().(*types.Signature).Recv(); recv == nil { return "", fmt.Errorf("func is not a method: %v", obj) } - // TODO(adonovan): opt: if the method is concrete, - // do a specialized version of the rest of this function so - // that it's O(1) not O(|scope|). Basically 'find' is needed - // only for struct fields and interface methods. + + if path, ok := concreteMethod(obj); ok { + // Fast path for concrete methods that avoids looping over scope. + return path, nil + } default: panic(obj) @@ -254,18 +256,18 @@ func For(obj types.Object) (Path, error) { if tname.IsAlias() { // type alias - if r := find(obj, T, path); r != nil { + 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); r != nil { + if r := findTypeParam(obj, typeparams.ForNamed(named), path, nil); r != nil { // generic named type return Path(r), nil } } // defined (named) type - if r := find(obj, T.Underlying(), append(path, opUnderlying)); r != nil { + if r := find(obj, T.Underlying(), append(path, opUnderlying), nil); r != nil { return Path(r), nil } } @@ -279,7 +281,7 @@ func For(obj types.Object) (Path, error) { if _, ok := o.(*types.TypeName); !ok { if o.Exported() { // exported non-type (const, var, func) - if r := find(obj, o.Type(), append(path, opType)); r != nil { + if r := find(obj, o.Type(), append(path, opType), nil); r != nil { return Path(r), nil } } @@ -299,7 +301,7 @@ func For(obj types.Object) (Path, error) { if m == obj { return Path(path2), nil // found declared method } - if r := find(obj, m.Type(), append(path2, opType)); r != nil { + if r := find(obj, m.Type(), append(path2, opType), nil); r != nil { return Path(r), nil } } @@ -315,42 +317,136 @@ func appendOpArg(path []byte, op byte, arg int) []byte { return path } +// concreteMethod returns the path for meth, which must have a non-nil receiver. +// The second return value indicates success and may be false if the method is +// an interface method or if it is an instantiated method. +// +// This function is just an optimization that avoids the general scope walking +// approach. You are expected to fall back to the general approach if this +// function fails. +func concreteMethod(meth *types.Func) (Path, bool) { + // Concrete methods can only be declared on package-scoped named types. For + // that reason we can skip the expensive walk over the package scope: the + // path will always be package -> named type -> method. We can trivially get + // the type name from the receiver, and only have to look over the type's + // methods to find the method index. + // + // Methods on generic types require special consideration, however. Consider + // the following package: + // + // L1: type S[T any] struct{} + // L2: func (recv S[A]) Foo() { recv.Bar() } + // L3: func (recv S[B]) Bar() { } + // L4: type Alias = S[int] + // L5: func _[T any]() { var s S[int]; s.Foo() } + // + // The receivers of methods on generic types are instantiations. L2 and L3 + // instantiate S with the type-parameters A and B, which are scoped to the + // respective methods. L4 and L5 each instantiate S with int. Each of these + // instantiations has its own method set, full of methods (and thus objects) + // with receivers whose types are the respective instantiations. In other + // words, we have + // + // S[A].Foo, S[A].Bar + // S[B].Foo, S[B].Bar + // S[int].Foo, S[int].Bar + // + // We may thus be trying to produce object paths for any of these objects. + // + // S[A].Foo and S[B].Bar are the origin methods, and their paths are S.Foo + // and S.Bar, which are the paths that this function naturally produces. + // + // S[A].Bar, S[B].Foo, and both methods on S[int] are instantiations that + // don't correspond to the origin methods. For S[int], this is significant. + // The most precise object path for S[int].Foo, for example, is Alias.Foo, + // not S.Foo. Our function, however, would produce S.Foo, which would + // resolve to a different object. + // + // For S[A].Bar and S[B].Foo it could be argued that S.Bar and S.Foo are + // still the correct paths, since only the origin methods have meaningful + // paths. But this is likely only true for trivial cases and has edge cases. + // Since this function is only an optimization, we err on the side of giving + // up, deferring to the slower but definitely correct algorithm. Most users + // of objectpath will only be giving us origin methods, anyway, as referring + // to instantiated methods is usually not useful. + + if typeparams.OriginMethod(meth) != 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 { + return "", false + } + + if types.IsInterface(named) { + // Named interfaces don't have to be package-scoped + // + // TODO(dominikh): opt: if scope.Lookup(name) == named, then we can apply this optimization to interface + // methods, too, I think. + return "", false + } + + // Preallocate space for the name, opType, opMethod, and some digits. + name := named.Obj().Name() + path := make([]byte, 0, len(name)+8) + path = append(path, name...) + path = append(path, opType) + canonical := canonicalize(named) + for i, m := range canonical { + if m == meth { + path = appendOpArg(path, opMethod, i) + return Path(path), true + } + } + + panic(fmt.Sprintf("couldn't find method %s on type %s", meth, named)) +} + // find finds obj within type T, returning the path to it, or nil if not found. -func find(obj types.Object, T types.Type, path []byte) []byte { +// +// The seen map is used to short circuit cycles through type parameters. If +// 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 *types.Basic, *types.Named: // Named types belonging to pkg were handled already, // so T must belong to another package. No path. return nil case *types.Pointer: - return find(obj, T.Elem(), append(path, opElem)) + return find(obj, T.Elem(), append(path, opElem), seen) case *types.Slice: - return find(obj, T.Elem(), append(path, opElem)) + return find(obj, T.Elem(), append(path, opElem), seen) case *types.Array: - return find(obj, T.Elem(), append(path, opElem)) + return find(obj, T.Elem(), append(path, opElem), seen) case *types.Chan: - return find(obj, T.Elem(), append(path, opElem)) + return find(obj, T.Elem(), append(path, opElem), seen) case *types.Map: - if r := find(obj, T.Key(), append(path, opKey)); r != nil { + if r := find(obj, T.Key(), append(path, opKey), seen); r != nil { return r } - return find(obj, T.Elem(), append(path, opElem)) + return find(obj, T.Elem(), append(path, opElem), seen) case *types.Signature: - if r := findTypeParam(obj, typeparams.ForSignature(T), path); r != nil { + if r := findTypeParam(obj, typeparams.ForSignature(T), path, seen); r != nil { return r } - if r := find(obj, T.Params(), append(path, opParams)); r != nil { + if r := find(obj, T.Params(), append(path, opParams), seen); r != nil { return r } - return find(obj, T.Results(), append(path, opResults)) + return find(obj, T.Results(), append(path, opResults), seen) case *types.Struct: for i := 0; i < T.NumFields(); i++ { - f := T.Field(i) + fld := T.Field(i) path2 := appendOpArg(path, opField, i) - if f == obj { + if fld == obj { return path2 // found field var } - if r := find(obj, f.Type(), append(path2, opType)); r != nil { + if r := find(obj, fld.Type(), append(path2, opType), seen); r != nil { return r } } @@ -362,7 +458,7 @@ func find(obj types.Object, T types.Type, path []byte) []byte { if v == obj { return path2 // found param/result var } - if r := find(obj, v.Type(), append(path2, opType)); r != nil { + if r := find(obj, v.Type(), append(path2, opType), seen); r != nil { return r } } @@ -374,7 +470,7 @@ func find(obj types.Object, T types.Type, path []byte) []byte { if m == obj { return path2 // found interface method } - if r := find(obj, m.Type(), append(path2, opType)); r != nil { + if r := find(obj, m.Type(), append(path2, opType), seen); r != nil { return r } } @@ -384,7 +480,14 @@ func find(obj types.Object, T types.Type, path []byte) []byte { if name == obj { return append(path, opObj) } - if r := find(obj, T.Constraint(), append(path, opConstraint)); r != nil { + if seen[name] { + return nil + } + if seen == nil { + seen = make(map[*types.TypeName]bool) + } + seen[name] = true + if r := find(obj, T.Constraint(), append(path, opConstraint), seen); r != nil { return r } return nil @@ -392,11 +495,11 @@ func find(obj types.Object, T types.Type, path []byte) []byte { panic(T) } -func findTypeParam(obj types.Object, list *typeparams.TypeParamList, path []byte) []byte { +func findTypeParam(obj types.Object, list *typeparams.TypeParamList, path []byte, seen map[*types.TypeName]bool) []byte { for i := 0; i < list.Len(); i++ { tparam := list.At(i) path2 := appendOpArg(path, opTypeParam, i) - if r := find(obj, tparam, path2); r != nil { + if r := find(obj, tparam, path2, seen); r != nil { return r } } diff --git a/tools/vendor/golang.org/x/tools/go/types/typeutil/imports.go b/tools/vendor/golang.org/x/tools/go/types/typeutil/imports.go index 9c441dba..b81ce0c3 100644 --- a/tools/vendor/golang.org/x/tools/go/types/typeutil/imports.go +++ b/tools/vendor/golang.org/x/tools/go/types/typeutil/imports.go @@ -12,7 +12,6 @@ import "go/types" // package Q, Q appears earlier than P in the result. // The algorithm follows import statements in the order they // appear in the source code, so the result is a total order. -// func Dependencies(pkgs ...*types.Package) []*types.Package { var result []*types.Package seen := make(map[*types.Package]bool) 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 c9f8f25a..dcc029b8 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 @@ -24,7 +24,6 @@ import ( // Just as with map[K]V, a nil *Map is a valid empty map. // // Not thread-safe. -// type Map struct { hasher Hasher // shared by many Maps table map[uint32][]entry // maps hash to bucket; entry.key==nil means unused @@ -57,14 +56,12 @@ type entry struct { // // If SetHasher is not called, the Map will create a private hasher at // the first call to Insert. -// func (m *Map) SetHasher(hasher Hasher) { m.hasher = hasher } // Delete removes the entry with the given key, if any. // It returns true if the entry was found. -// func (m *Map) Delete(key types.Type) bool { if m != nil && m.table != nil { hash := m.hasher.Hash(key) @@ -84,7 +81,6 @@ 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{} { if m != nil && m.table != nil { for _, e := range m.table[m.hasher.Hash(key)] { @@ -145,7 +141,6 @@ 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{})) { if m != nil { for _, bucket := range m.table { @@ -190,14 +185,12 @@ func (m *Map) toString(values bool) string { // String returns a string representation of the map's entries. // Values are printed using fmt.Sprintf("%v", v). // Order is unspecified. -// func (m *Map) String() string { return m.toString(true) } // KeysString returns a string representation of the map's key set. // Order is unspecified. -// func (m *Map) KeysString() string { return m.toString(false) } 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 32084610..a5d93108 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 @@ -25,7 +25,6 @@ type MethodSetCache struct { // If cache is nil, this function is equivalent to types.NewMethodSet(T). // Utility functions can thus expose an optional *MethodSetCache // parameter to clients that care about performance. -// func (cache *MethodSetCache) MethodSet(T types.Type) *types.MethodSet { if cache == nil { return types.NewMethodSet(T) 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 9849c24c..fa55b0a1 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 @@ -22,7 +22,6 @@ import "go/types" // this function is intended only for user interfaces. // // The order of the result is as for types.MethodSet(T). -// func IntuitiveMethodSet(T types.Type, msets *MethodSetCache) []*types.Selection { isPointerToConcrete := func(T types.Type) bool { ptr, ok := T.(*types.Pointer) diff --git a/tools/vendor/golang.org/x/tools/imports/forward.go b/tools/vendor/golang.org/x/tools/imports/forward.go index 8be18a66..d2547c74 100644 --- a/tools/vendor/golang.org/x/tools/imports/forward.go +++ b/tools/vendor/golang.org/x/tools/imports/forward.go @@ -40,7 +40,7 @@ var LocalPrefix string // // Note that filename's directory influences which imports can be chosen, // so it is important that filename be accurate. -// To process data ``as if'' it were in filename, pass the data as a non-nil src. +// To process data “as if” it were in filename, pass the data as a non-nil src. func Process(filename string, src []byte, opt *Options) ([]byte, error) { var err error if src == nil { diff --git a/tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go b/tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go index 78ee2c06..e32152ac 100644 --- a/tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go +++ b/tools/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go @@ -11,10 +11,7 @@ import ( "go/ast" "go/token" "go/types" - "strings" - - "golang.org/x/tools/go/ast/astutil" - "golang.org/x/tools/internal/lsp/fuzzy" + "strconv" ) // Flag to gate diagnostics for fuzz tests in 1.18. @@ -37,7 +34,7 @@ func TypeErrorEndPos(fset *token.FileSet, src []byte, start token.Pos) token.Pos return end } -func ZeroValue(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { +func ZeroValue(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { under := typ if n, ok := typ.(*types.Named); ok { under = n.Underlying() @@ -57,7 +54,7 @@ func ZeroValue(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.T case *types.Chan, *types.Interface, *types.Map, *types.Pointer, *types.Signature, *types.Slice, *types.Array: return ast.NewIdent("nil") case *types.Struct: - texpr := TypeExpr(fset, f, pkg, typ) // typ because we want the name here. + texpr := TypeExpr(f, pkg, typ) // typ because we want the name here. if texpr == nil { return nil } @@ -81,7 +78,7 @@ func IsZeroValue(expr ast.Expr) bool { } } -func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { +func TypeExpr(f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { switch t := typ.(type) { case *types.Basic: switch t.Kind() { @@ -91,7 +88,7 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty return ast.NewIdent(t.Name()) } case *types.Pointer: - x := TypeExpr(fset, f, pkg, t.Elem()) + x := TypeExpr(f, pkg, t.Elem()) if x == nil { return nil } @@ -100,7 +97,7 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty X: x, } case *types.Array: - elt := TypeExpr(fset, f, pkg, t.Elem()) + elt := TypeExpr(f, pkg, t.Elem()) if elt == nil { return nil } @@ -112,7 +109,7 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty Elt: elt, } case *types.Slice: - elt := TypeExpr(fset, f, pkg, t.Elem()) + elt := TypeExpr(f, pkg, t.Elem()) if elt == nil { return nil } @@ -120,8 +117,8 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty Elt: elt, } case *types.Map: - key := TypeExpr(fset, f, pkg, t.Key()) - value := TypeExpr(fset, f, pkg, t.Elem()) + key := TypeExpr(f, pkg, t.Key()) + value := TypeExpr(f, pkg, t.Elem()) if key == nil || value == nil { return nil } @@ -134,7 +131,7 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty if t.Dir() == types.SendRecv { dir = ast.SEND | ast.RECV } - value := TypeExpr(fset, f, pkg, t.Elem()) + value := TypeExpr(f, pkg, t.Elem()) if value == nil { return nil } @@ -145,7 +142,7 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty case *types.Signature: var params []*ast.Field for i := 0; i < t.Params().Len(); i++ { - p := TypeExpr(fset, f, pkg, t.Params().At(i).Type()) + p := TypeExpr(f, pkg, t.Params().At(i).Type()) if p == nil { return nil } @@ -160,7 +157,7 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty } var returns []*ast.Field for i := 0; i < t.Results().Len(); i++ { - r := TypeExpr(fset, f, pkg, t.Results().At(i).Type()) + r := TypeExpr(f, pkg, t.Results().At(i).Type()) if r == nil { return nil } @@ -184,13 +181,12 @@ func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty return ast.NewIdent(t.Obj().Name()) } pkgName := t.Obj().Pkg().Name() + // If the file already imports the package under another name, use that. - for _, group := range astutil.Imports(fset, f) { - for _, cand := range group { - if strings.Trim(cand.Path.Value, `"`) == t.Obj().Pkg().Path() { - if cand.Name != nil && cand.Name.Name != "" { - pkgName = cand.Name.Name - } + 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 } } } @@ -399,30 +395,3 @@ func equivalentTypes(want, got types.Type) bool { } return types.AssignableTo(want, got) } - -// FindBestMatch employs fuzzy matching to evaluate the similarity of each given identifier to the -// given pattern. We return the identifier whose name is most similar to the pattern. -func FindBestMatch(pattern string, idents []*ast.Ident) ast.Expr { - fuzz := fuzzy.NewMatcher(pattern) - var bestFuzz ast.Expr - highScore := float32(0) // minimum score is 0 (no match) - for _, ident := range idents { - // TODO: Improve scoring algorithm. - score := fuzz.Score(ident.Name) - if score > highScore { - highScore = score - bestFuzz = ident - } else if score == 0 { - // Order matters in the fuzzy matching algorithm. If we find no match - // when matching the target to the identifier, try matching the identifier - // to the target. - revFuzz := fuzzy.NewMatcher(ident.Name) - revScore := revFuzz.Score(pattern) - if revScore > highScore { - highScore = revScore - bestFuzz = ident - } - } - } - return bestFuzz -} diff --git a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go index 9887f7e7..798fe599 100644 --- a/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go +++ b/tools/vendor/golang.org/x/tools/internal/fastwalk/fastwalk.go @@ -40,12 +40,12 @@ var ErrSkipFiles = errors.New("fastwalk: skip remaining files in directory") // If fastWalk returns filepath.SkipDir, the directory is skipped. // // Unlike filepath.Walk: -// * file stat calls must be done by the user. +// - 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 +// - multiple goroutines stat the filesystem concurrently. The provided // walkFn must be safe for concurrent use. -// * fastWalk can follow symlinks if walkFn returns the TraverseLink +// - fastWalk can follow symlinks if walkFn returns the TraverseLink // sentinel error. It is the walkFn's responsibility to prevent // fastWalk from going into symlink cycles. func Walk(root string, walkFn func(path string, typ os.FileMode) error) error { 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 f7533683..67256dc3 100644 --- a/tools/vendor/golang.org/x/tools/internal/gocommand/invoke.go +++ b/tools/vendor/golang.org/x/tools/internal/gocommand/invoke.go @@ -264,8 +264,10 @@ func cmdDebugStr(cmd *exec.Cmd) string { env := make(map[string]string) for _, kv := range cmd.Env { split := strings.SplitN(kv, "=", 2) - k, v := split[0], split[1] - env[k] = v + if len(split) == 2 { + k, v := split[0], split[1] + env[k] = v + } } var args []string 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 925ff535..16840532 100644 --- a/tools/vendor/golang.org/x/tools/internal/gopathwalk/walk.go +++ b/tools/vendor/golang.org/x/tools/internal/gopathwalk/walk.go @@ -175,8 +175,8 @@ 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 { - dir := filepath.Dir(path) 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. @@ -209,12 +209,7 @@ func (w *walker) walk(path string, typ os.FileMode) error { // Emacs noise. return nil } - fi, err := os.Lstat(path) - if err != nil { - // Just ignore it. - return nil - } - if w.shouldTraverse(dir, fi) { + if w.shouldTraverse(path) { return fastwalk.ErrTraverseLink } } @@ -224,13 +219,8 @@ func (w *walker) walk(path string, typ os.FileMode) error { // 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(dir string, fi os.FileInfo) bool { - path := filepath.Join(dir, fi.Name()) - target, err := filepath.EvalSymlinks(path) - if err != nil { - return false - } - ts, err := os.Stat(target) +func (w *walker) shouldTraverse(path string) bool { + ts, err := os.Stat(path) if err != nil { fmt.Fprintln(os.Stderr, err) return false @@ -238,7 +228,7 @@ func (w *walker) shouldTraverse(dir string, fi os.FileInfo) bool { if !ts.IsDir() { return false } - if w.shouldSkipDir(ts, dir) { + if w.shouldSkipDir(ts, filepath.Dir(path)) { return false } // Check for symlink loops by statting each directory component 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 d859617b..9e373d64 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/fix.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/fix.go @@ -796,7 +796,7 @@ 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"} +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. @@ -906,7 +906,7 @@ func (e *ProcessEnv) GetResolver() (Resolver, error) { if err := e.init(); err != nil { return nil, err } - if len(e.Env["GOMOD"]) == 0 { + if len(e.Env["GOMOD"]) == 0 && len(e.Env["GOWORK"]) == 0 { e.resolver = newGopathResolver(e) return e.resolver, nil } 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 25973989..95a88383 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/imports.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/imports.go @@ -103,12 +103,17 @@ func ApplyFixes(fixes []*ImportFix, filename string, src []byte, opt *Options, e return formatFile(fileSet, file, src, nil, opt) } -func formatFile(fileSet *token.FileSet, file *ast.File, src []byte, adjust func(orig []byte, src []byte) []byte, opt *Options) ([]byte, error) { - mergeImports(fileSet, file) - sortImports(opt.LocalPrefix, fileSet, file) - imps := astutil.Imports(fileSet, file) +// formatFile formats the file syntax tree. +// It may mutate the token.FileSet. +// +// If an adjust function is provided, it is called after formatting +// with the original source (formatFile's src parameter) and the +// formatted file, and returns the postpocessed result. +func formatFile(fset *token.FileSet, file *ast.File, src []byte, adjust func(orig []byte, src []byte) []byte, opt *Options) ([]byte, error) { + mergeImports(file) + sortImports(opt.LocalPrefix, fset.File(file.Pos()), file) var spacesBefore []string // import paths we need spaces before - for _, impSection := range imps { + for _, impSection := range astutil.Imports(fset, file) { // Within each block of contiguous imports, see if any // import lines are in different group numbers. If so, // we'll need to put a space between them so it's @@ -132,7 +137,7 @@ func formatFile(fileSet *token.FileSet, file *ast.File, src []byte, adjust func( printConfig := &printer.Config{Mode: printerMode, Tabwidth: opt.TabWidth} var buf bytes.Buffer - err := printConfig.Fprint(&buf, fileSet, file) + err := printConfig.Fprint(&buf, fset, file) if err != nil { return nil, err } @@ -276,11 +281,11 @@ func cutSpace(b []byte) (before, middle, after []byte) { } // matchSpace reformats src to use the same space context as orig. -// 1) If orig begins with blank lines, matchSpace inserts them at the beginning of src. -// 2) matchSpace copies the indentation of the first non-blank line in orig -// to every non-blank line in src. -// 3) matchSpace copies the trailing space from orig and uses it in place -// of src's trailing space. +// 1. If orig begins with blank lines, matchSpace inserts them at the beginning of src. +// 2. matchSpace copies the indentation of the first non-blank line in orig +// to every non-blank line in src. +// 3. matchSpace copies the trailing space from orig and uses it in place +// of src's trailing space. func matchSpace(orig []byte, src []byte) []byte { before, _, after := cutSpace(orig) i := bytes.LastIndex(before, []byte{'\n'}) 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 2bcf41f5..46693f24 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/mod.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/mod.go @@ -70,9 +70,17 @@ func (r *ModuleResolver) init() error { Logf: r.env.Logf, WorkingDir: r.env.WorkingDir, } - vendorEnabled, mainModVendor, err := gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner) - if err != nil { - return err + + 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 { + vendorEnabled, mainModVendor, err = gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner) + if err != nil { + return err + } } if mainModVendor != nil && vendorEnabled { 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 dc52372e..85144db1 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/sortimports.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/sortimports.go @@ -3,6 +3,7 @@ // license that can be found in the LICENSE file. // Hacked up copy of go/ast/import.go +// Modified to use a single token.File in preference to a FileSet. package imports @@ -16,7 +17,9 @@ 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. -func sortImports(localPrefix string, fset *token.FileSet, f *ast.File) { +// +// It may mutate the token.File. +func sortImports(localPrefix string, tokFile *token.File, f *ast.File) { for i, d := range f.Decls { d, ok := d.(*ast.GenDecl) if !ok || d.Tok != token.IMPORT { @@ -39,21 +42,21 @@ func sortImports(localPrefix string, fset *token.FileSet, f *ast.File) { i := 0 specs := d.Specs[:0] for j, s := range d.Specs { - if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line { + if j > i && tokFile.Line(s.Pos()) > 1+tokFile.Line(d.Specs[j-1].End()) { // j begins a new run. End this one. - specs = append(specs, sortSpecs(localPrefix, fset, f, d.Specs[i:j])...) + specs = append(specs, sortSpecs(localPrefix, tokFile, f, d.Specs[i:j])...) i = j } } - specs = append(specs, sortSpecs(localPrefix, fset, f, d.Specs[i:])...) + specs = append(specs, sortSpecs(localPrefix, tokFile, f, d.Specs[i:])...) d.Specs = specs // Deduping can leave a blank line before the rparen; clean that up. if len(d.Specs) > 0 { lastSpec := d.Specs[len(d.Specs)-1] - lastLine := fset.Position(lastSpec.Pos()).Line - if rParenLine := fset.Position(d.Rparen).Line; rParenLine > lastLine+1 { - fset.File(d.Rparen).MergeLine(rParenLine - 1) + lastLine := tokFile.PositionFor(lastSpec.Pos(), false).Line + if rParenLine := tokFile.PositionFor(d.Rparen, false).Line; rParenLine > lastLine+1 { + tokFile.MergeLine(rParenLine - 1) // has side effects! } } } @@ -62,7 +65,7 @@ func sortImports(localPrefix string, fset *token.FileSet, f *ast.File) { // mergeImports merges all the import declarations into the first one. // Taken from golang.org/x/tools/ast/astutil. // This does not adjust line numbers properly -func mergeImports(fset *token.FileSet, f *ast.File) { +func mergeImports(f *ast.File) { if len(f.Decls) <= 1 { return } @@ -144,7 +147,9 @@ type posSpan struct { End token.Pos } -func sortSpecs(localPrefix string, fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec { +// sortSpecs sorts the import specs within each import decl. +// It may mutate the token.File. +func sortSpecs(localPrefix string, tokFile *token.File, f *ast.File, specs []ast.Spec) []ast.Spec { // Can't short-circuit here even if specs are already sorted, // since they might yet need deduplication. // A lone import, however, may be safely ignored. @@ -160,7 +165,7 @@ func sortSpecs(localPrefix string, fset *token.FileSet, f *ast.File, specs []ast // Identify comments in this range. // Any comment from pos[0].Start to the final line counts. - lastLine := fset.Position(pos[len(pos)-1].End).Line + lastLine := tokFile.Line(pos[len(pos)-1].End) cstart := len(f.Comments) cend := len(f.Comments) for i, g := range f.Comments { @@ -170,7 +175,7 @@ func sortSpecs(localPrefix string, fset *token.FileSet, f *ast.File, specs []ast if i < cstart { cstart = i } - if fset.Position(g.End()).Line > lastLine { + if tokFile.Line(g.End()) > lastLine { cend = i break } @@ -203,7 +208,7 @@ func sortSpecs(localPrefix string, fset *token.FileSet, f *ast.File, specs []ast deduped = append(deduped, s) } else { p := s.Pos() - fset.File(p).MergeLine(fset.Position(p).Line) + tokFile.MergeLine(tokFile.Line(p)) // has side effects! } } specs = deduped @@ -234,21 +239,21 @@ func sortSpecs(localPrefix string, fset *token.FileSet, f *ast.File, specs []ast // Fixup comments can insert blank lines, because import specs are on different lines. // We remove those blank lines here by merging import spec to the first import spec line. - firstSpecLine := fset.Position(specs[0].Pos()).Line + firstSpecLine := tokFile.Line(specs[0].Pos()) for _, s := range specs[1:] { p := s.Pos() - line := fset.File(p).Line(p) + line := tokFile.Line(p) for previousLine := line - 1; previousLine >= firstSpecLine; { // MergeLine can panic. Avoid the panic at the cost of not removing the blank line // golang/go#50329 - if previousLine > 0 && previousLine < fset.File(p).LineCount() { - fset.File(p).MergeLine(previousLine) + if previousLine > 0 && previousLine < tokFile.LineCount() { + tokFile.MergeLine(previousLine) // has side effects! previousLine-- } else { // try to gather some data to diagnose how this could happen req := "Please report what the imports section of your go file looked like." log.Printf("panic avoided: first:%d line:%d previous:%d max:%d. %s", - firstSpecLine, line, previousLine, fset.File(p).LineCount(), req) + firstSpecLine, line, previousLine, tokFile.LineCount(), req) } } } diff --git a/tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go b/tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go index 7de2be9b..437fbb78 100644 --- a/tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go +++ b/tools/vendor/golang.org/x/tools/internal/imports/zstdlib.go @@ -88,6 +88,7 @@ var stdlib = map[string][]string{ "ContainsAny", "ContainsRune", "Count", + "Cut", "Equal", "EqualFold", "ErrTooLarge", @@ -711,6 +712,11 @@ var stdlib = map[string][]string{ "ValueConverter", "Valuer", }, + "debug/buildinfo": []string{ + "BuildInfo", + "Read", + "ReadFile", + }, "debug/dwarf": []string{ "AddrType", "ArrayType", @@ -1944,6 +1950,7 @@ var stdlib = map[string][]string{ "R_PPC64_REL24_NOTOC", "R_PPC64_REL32", "R_PPC64_REL64", + "R_PPC64_RELATIVE", "R_PPC64_SECTOFF_DS", "R_PPC64_SECTOFF_LO_DS", "R_PPC64_TLS", @@ -2547,6 +2554,7 @@ var stdlib = map[string][]string{ "Symbol", }, "debug/plan9obj": []string{ + "ErrNoSymbols", "File", "FileHeader", "Magic386", @@ -2906,6 +2914,7 @@ var stdlib = map[string][]string{ "Importer", "IncDecStmt", "IndexExpr", + "IndexListExpr", "Inspect", "InterfaceType", "IsExported", @@ -3179,6 +3188,7 @@ var stdlib = map[string][]string{ "SUB", "SUB_ASSIGN", "SWITCH", + "TILDE", "TYPE", "Token", "UnaryPrec", @@ -3187,6 +3197,7 @@ var stdlib = map[string][]string{ "XOR_ASSIGN", }, "go/types": []string{ + "ArgumentError", "Array", "AssertableTo", "AssignableTo", @@ -3205,6 +3216,7 @@ var stdlib = map[string][]string{ "Complex64", "Config", "Const", + "Context", "ConvertibleTo", "DefPredeclaredTestFuncs", "Default", @@ -3224,6 +3236,8 @@ var stdlib = map[string][]string{ "ImporterFrom", "Info", "Initializer", + "Instance", + "Instantiate", "Int", "Int16", "Int32", @@ -3254,6 +3268,7 @@ var stdlib = map[string][]string{ "NewChan", "NewChecker", "NewConst", + "NewContext", "NewField", "NewFunc", "NewInterface", @@ -3268,10 +3283,14 @@ var stdlib = map[string][]string{ "NewPointer", "NewScope", "NewSignature", + "NewSignatureType", "NewSlice", "NewStruct", + "NewTerm", "NewTuple", "NewTypeName", + "NewTypeParam", + "NewUnion", "NewVar", "Nil", "Object", @@ -3296,11 +3315,15 @@ var stdlib = map[string][]string{ "StdSizes", "String", "Struct", + "Term", "Tuple", "Typ", "Type", "TypeAndValue", + "TypeList", "TypeName", + "TypeParam", + "TypeParamList", "TypeString", "Uint", "Uint16", @@ -3308,6 +3331,7 @@ var stdlib = map[string][]string{ "Uint64", "Uint8", "Uintptr", + "Union", "Universe", "Unsafe", "UnsafePointer", @@ -4080,9 +4104,11 @@ var stdlib = map[string][]string{ "SRV", "SplitHostPort", "TCPAddr", + "TCPAddrFromAddrPort", "TCPConn", "TCPListener", "UDPAddr", + "UDPAddrFromAddrPort", "UDPConn", "UnixAddr", "UnixConn", @@ -4142,6 +4168,7 @@ var stdlib = map[string][]string{ "ListenAndServe", "ListenAndServeTLS", "LocalAddrContextKey", + "MaxBytesHandler", "MaxBytesReader", "MethodConnect", "MethodDelete", @@ -4338,6 +4365,25 @@ var stdlib = map[string][]string{ "ParseDate", "ReadMessage", }, + "net/netip": []string{ + "Addr", + "AddrFrom16", + "AddrFrom4", + "AddrFromSlice", + "AddrPort", + "AddrPortFrom", + "IPv4Unspecified", + "IPv6LinkLocalAllNodes", + "IPv6Unspecified", + "MustParseAddr", + "MustParseAddrPort", + "MustParsePrefix", + "ParseAddr", + "ParseAddrPort", + "ParsePrefix", + "Prefix", + "PrefixFrom", + }, "net/rpc": []string{ "Accept", "Call", @@ -4641,6 +4687,8 @@ var stdlib = map[string][]string{ "Method", "New", "NewAt", + "Pointer", + "PointerTo", "Ptr", "PtrTo", "RecvDir", @@ -4819,9 +4867,11 @@ var stdlib = map[string][]string{ }, "runtime/debug": []string{ "BuildInfo", + "BuildSetting", "FreeOSMemory", "GCStats", "Module", + "ParseBuildInfo", "PrintStack", "ReadBuildInfo", "ReadGCStats", @@ -4939,11 +4989,13 @@ var stdlib = map[string][]string{ }, "strings": []string{ "Builder", + "Clone", "Compare", "Contains", "ContainsAny", "ContainsRune", "Count", + "Cut", "EqualFold", "Fields", "FieldsFunc", @@ -9793,6 +9845,7 @@ var stdlib = map[string][]string{ "Syscall18", "Syscall6", "Syscall9", + "SyscallN", "Sysctl", "SysctlUint32", "Sysctlnode", @@ -10202,7 +10255,6 @@ var stdlib = map[string][]string{ "Value", "ValueError", "ValueOf", - "Wrapper", }, "testing": []string{ "AllocsPerRun", @@ -10213,9 +10265,11 @@ var stdlib = map[string][]string{ "CoverBlock", "CoverMode", "Coverage", + "F", "Init", "InternalBenchmark", "InternalExample", + "InternalFuzzTarget", "InternalTest", "M", "Main", @@ -10313,9 +10367,11 @@ var stdlib = map[string][]string{ "ActionNode", "BoolNode", "BranchNode", + "BreakNode", "ChainNode", "CommandNode", "CommentNode", + "ContinueNode", "DotNode", "FieldNode", "IdentifierNode", @@ -10329,9 +10385,11 @@ var stdlib = map[string][]string{ "Node", "NodeAction", "NodeBool", + "NodeBreak", "NodeChain", "NodeCommand", "NodeComment", + "NodeContinue", "NodeDot", "NodeField", "NodeIdentifier", @@ -10727,6 +10785,7 @@ var stdlib = map[string][]string{ "IsSurrogate", }, "unicode/utf8": []string{ + "AppendRune", "DecodeLastRune", "DecodeLastRuneInString", "DecodeRune", diff --git a/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/input.go b/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/input.go deleted file mode 100644 index c1038163..00000000 --- a/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/input.go +++ /dev/null @@ -1,183 +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 fuzzy - -import ( - "unicode" -) - -// RuneRole specifies the role of a rune in the context of an input. -type RuneRole byte - -const ( - // RNone specifies a rune without any role in the input (i.e., whitespace/non-ASCII). - RNone RuneRole = iota - // RSep specifies a rune with the role of segment separator. - RSep - // RTail specifies a rune which is a lower-case tail in a word in the input. - RTail - // RUCTail specifies a rune which is an upper-case tail in a word in the input. - RUCTail - // RHead specifies a rune which is the first character in a word in the input. - RHead -) - -// RuneRoles detects the roles of each byte rune in an input string and stores it in the output -// slice. The rune role depends on the input type. Stops when it parsed all the runes in the string -// or when it filled the output. If output is nil, then it gets created. -func RuneRoles(candidate []byte, reuse []RuneRole) []RuneRole { - var output []RuneRole - if cap(reuse) < len(candidate) { - output = make([]RuneRole, 0, len(candidate)) - } else { - output = reuse[:0] - } - - prev, prev2 := rtNone, rtNone - for i := 0; i < len(candidate); i++ { - r := rune(candidate[i]) - - role := RNone - - curr := rtLower - if candidate[i] <= unicode.MaxASCII { - curr = runeType(rt[candidate[i]] - '0') - } - - if curr == rtLower { - if prev == rtNone || prev == rtPunct { - role = RHead - } else { - role = RTail - } - } else if curr == rtUpper { - role = RHead - - if prev == rtUpper { - // This and previous characters are both upper case. - - if i+1 == len(candidate) { - // This is last character, previous was also uppercase -> this is UCTail - // i.e., (current char is C): aBC / BC / ABC - role = RUCTail - } - } - } else if curr == rtPunct { - switch r { - case '.', ':': - role = RSep - } - } - if curr != rtLower { - if i > 1 && output[i-1] == RHead && prev2 == rtUpper && (output[i-2] == RHead || output[i-2] == RUCTail) { - // The previous two characters were uppercase. The current one is not a lower case, so the - // previous one can't be a HEAD. Make it a UCTail. - // i.e., (last char is current char - B must be a UCTail): ABC / ZABC / AB. - output[i-1] = RUCTail - } - } - - output = append(output, role) - prev2 = prev - prev = curr - } - return output -} - -type runeType byte - -const ( - rtNone runeType = iota - rtPunct - rtLower - rtUpper -) - -const rt = "00000000000000000000000000000000000000000000001122222222221000000333333333333333333333333330000002222222222222222222222222200000" - -// LastSegment returns the substring representing the last segment from the input, where each -// byte has an associated RuneRole in the roles slice. This makes sense only for inputs of Symbol -// or Filename type. -func LastSegment(input string, roles []RuneRole) string { - // Exclude ending separators. - end := len(input) - 1 - for end >= 0 && roles[end] == RSep { - end-- - } - if end < 0 { - return "" - } - - start := end - 1 - for start >= 0 && roles[start] != RSep { - start-- - } - - return input[start+1 : end+1] -} - -// fromChunks copies string chunks into the given buffer. -func fromChunks(chunks []string, buffer []byte) []byte { - ii := 0 - for _, chunk := range chunks { - for i := 0; i < len(chunk); i++ { - if ii >= cap(buffer) { - break - } - buffer[ii] = chunk[i] - ii++ - } - } - return buffer[:ii] -} - -// toLower transforms the input string to lower case, which is stored in the output byte slice. -// The lower casing considers only ASCII values - non ASCII values are left unmodified. -// Stops when parsed all input or when it filled the output slice. If output is nil, then it gets -// created. -func toLower(input []byte, reuse []byte) []byte { - output := reuse - if cap(reuse) < len(input) { - output = make([]byte, len(input)) - } - - for i := 0; i < len(input); i++ { - r := rune(input[i]) - if input[i] <= unicode.MaxASCII { - if 'A' <= r && r <= 'Z' { - r += 'a' - 'A' - } - } - output[i] = byte(r) - } - return output[:len(input)] -} - -// WordConsumer defines a consumer for a word delimited by the [start,end) byte offsets in an input -// (start is inclusive, end is exclusive). -type WordConsumer func(start, end int) - -// Words find word delimiters in an input based on its bytes' mappings to rune roles. The offset -// delimiters for each word are fed to the provided consumer function. -func Words(roles []RuneRole, consume WordConsumer) { - var wordStart int - for i, r := range roles { - switch r { - case RUCTail, RTail: - case RHead, RNone, RSep: - if i != wordStart { - consume(wordStart, i) - } - wordStart = i - if r != RHead { - // Skip this character. - wordStart = i + 1 - } - } - } - if wordStart != len(roles) { - consume(wordStart, len(roles)) - } -} diff --git a/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/matcher.go b/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/matcher.go deleted file mode 100644 index 265cdcf1..00000000 --- a/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/matcher.go +++ /dev/null @@ -1,407 +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 fuzzy implements a fuzzy matching algorithm. -package fuzzy - -import ( - "bytes" - "fmt" -) - -const ( - // MaxInputSize is the maximum size of the input scored against the fuzzy matcher. Longer inputs - // will be truncated to this size. - MaxInputSize = 127 - // MaxPatternSize is the maximum size of the pattern used to construct the fuzzy matcher. Longer - // inputs are truncated to this size. - MaxPatternSize = 63 -) - -type scoreVal int - -func (s scoreVal) val() int { - return int(s) >> 1 -} - -func (s scoreVal) prevK() int { - return int(s) & 1 -} - -func score(val int, prevK int /*0 or 1*/) scoreVal { - return scoreVal(val<<1 + prevK) -} - -// Matcher implements a fuzzy matching algorithm for scoring candidates against a pattern. -// The matcher does not support parallel usage. -type Matcher struct { - pattern string - patternLower []byte // lower-case version of the pattern - patternShort []byte // first characters of the pattern - caseSensitive bool // set if the pattern is mix-cased - - patternRoles []RuneRole // the role of each character in the pattern - roles []RuneRole // the role of each character in the tested string - - scores [MaxInputSize + 1][MaxPatternSize + 1][2]scoreVal - - scoreScale float32 - - lastCandidateLen int // in bytes - lastCandidateMatched bool - - // Reusable buffers to avoid allocating for every candidate. - // - inputBuf stores the concatenated input chunks - // - lowerBuf stores the last candidate in lower-case - // - rolesBuf stores the calculated roles for each rune in the last - // candidate. - inputBuf [MaxInputSize]byte - lowerBuf [MaxInputSize]byte - rolesBuf [MaxInputSize]RuneRole -} - -func (m *Matcher) bestK(i, j int) int { - if m.scores[i][j][0].val() < m.scores[i][j][1].val() { - return 1 - } - return 0 -} - -// NewMatcher returns a new fuzzy matcher for scoring candidates against the provided pattern. -func NewMatcher(pattern string) *Matcher { - if len(pattern) > MaxPatternSize { - pattern = pattern[:MaxPatternSize] - } - - m := &Matcher{ - pattern: pattern, - patternLower: toLower([]byte(pattern), nil), - } - - for i, c := range m.patternLower { - if pattern[i] != c { - m.caseSensitive = true - break - } - } - - if len(pattern) > 3 { - m.patternShort = m.patternLower[:3] - } else { - m.patternShort = m.patternLower - } - - m.patternRoles = RuneRoles([]byte(pattern), nil) - - if len(pattern) > 0 { - maxCharScore := 4 - m.scoreScale = 1 / float32(maxCharScore*len(pattern)) - } - - return m -} - -// Score returns the score returned by matching the candidate to the pattern. -// This is not designed for parallel use. Multiple candidates must be scored sequentially. -// Returns a score between 0 and 1 (0 - no match, 1 - perfect match). -func (m *Matcher) Score(candidate string) float32 { - return m.ScoreChunks([]string{candidate}) -} - -func (m *Matcher) ScoreChunks(chunks []string) float32 { - candidate := fromChunks(chunks, m.inputBuf[:]) - if len(candidate) > MaxInputSize { - candidate = candidate[:MaxInputSize] - } - lower := toLower(candidate, m.lowerBuf[:]) - m.lastCandidateLen = len(candidate) - - if len(m.pattern) == 0 { - // Empty patterns perfectly match candidates. - return 1 - } - - if m.match(candidate, lower) { - sc := m.computeScore(candidate, lower) - if sc > minScore/2 && !m.poorMatch() { - m.lastCandidateMatched = true - if len(m.pattern) == len(candidate) { - // Perfect match. - return 1 - } - - if sc < 0 { - sc = 0 - } - normalizedScore := float32(sc) * m.scoreScale - if normalizedScore > 1 { - normalizedScore = 1 - } - - return normalizedScore - } - } - - m.lastCandidateMatched = false - return 0 -} - -const minScore = -10000 - -// MatchedRanges returns matches ranges for the last scored string as a flattened array of -// [begin, end) byte offset pairs. -func (m *Matcher) MatchedRanges() []int { - if len(m.pattern) == 0 || !m.lastCandidateMatched { - return nil - } - i, j := m.lastCandidateLen, len(m.pattern) - if m.scores[i][j][0].val() < minScore/2 && m.scores[i][j][1].val() < minScore/2 { - return nil - } - - var ret []int - k := m.bestK(i, j) - for i > 0 { - take := (k == 1) - k = m.scores[i][j][k].prevK() - if take { - if len(ret) == 0 || ret[len(ret)-1] != i { - ret = append(ret, i) - ret = append(ret, i-1) - } else { - ret[len(ret)-1] = i - 1 - } - j-- - } - i-- - } - // Reverse slice. - for i := 0; i < len(ret)/2; i++ { - ret[i], ret[len(ret)-1-i] = ret[len(ret)-1-i], ret[i] - } - return ret -} - -func (m *Matcher) match(candidate []byte, candidateLower []byte) bool { - i, j := 0, 0 - for ; i < len(candidateLower) && j < len(m.patternLower); i++ { - if candidateLower[i] == m.patternLower[j] { - j++ - } - } - if j != len(m.patternLower) { - return false - } - - // The input passes the simple test against pattern, so it is time to classify its characters. - // Character roles are used below to find the last segment. - m.roles = RuneRoles(candidate, m.rolesBuf[:]) - - return true -} - -func (m *Matcher) computeScore(candidate []byte, candidateLower []byte) int { - pattLen, candLen := len(m.pattern), len(candidate) - - for j := 0; j <= len(m.pattern); j++ { - m.scores[0][j][0] = minScore << 1 - m.scores[0][j][1] = minScore << 1 - } - m.scores[0][0][0] = score(0, 0) // Start with 0. - - segmentsLeft, lastSegStart := 1, 0 - for i := 0; i < candLen; i++ { - if m.roles[i] == RSep { - segmentsLeft++ - lastSegStart = i + 1 - } - } - - // A per-character bonus for a consecutive match. - consecutiveBonus := 2 - wordIdx := 0 // Word count within segment. - for i := 1; i <= candLen; i++ { - - role := m.roles[i-1] - isHead := role == RHead - - if isHead { - wordIdx++ - } else if role == RSep && segmentsLeft > 1 { - wordIdx = 0 - segmentsLeft-- - } - - var skipPenalty int - if i == 1 || (i-1) == lastSegStart { - // Skipping the start of first or last segment. - skipPenalty++ - } - - for j := 0; j <= pattLen; j++ { - // By default, we don't have a match. Fill in the skip data. - m.scores[i][j][1] = minScore << 1 - - // Compute the skip score. - k := 0 - if m.scores[i-1][j][0].val() < m.scores[i-1][j][1].val() { - k = 1 - } - - skipScore := m.scores[i-1][j][k].val() - // Do not penalize missing characters after the last matched segment. - if j != pattLen { - skipScore -= skipPenalty - } - m.scores[i][j][0] = score(skipScore, k) - - if j == 0 || candidateLower[i-1] != m.patternLower[j-1] { - // Not a match. - continue - } - pRole := m.patternRoles[j-1] - - if role == RTail && pRole == RHead { - if j > 1 { - // Not a match: a head in the pattern matches a tail character in the candidate. - continue - } - // Special treatment for the first character of the pattern. We allow - // matches in the middle of a word if they are long enough, at least - // min(3, pattern.length) characters. - if !bytes.HasPrefix(candidateLower[i-1:], m.patternShort) { - continue - } - } - - // Compute the char score. - var charScore int - // Bonus 1: the char is in the candidate's last segment. - if segmentsLeft <= 1 { - charScore++ - } - // Bonus 2: Case match or a Head in the pattern aligns with one in the word. - // Single-case patterns lack segmentation signals and we assume any character - // can be a head of a segment. - if candidate[i-1] == m.pattern[j-1] || role == RHead && (!m.caseSensitive || pRole == RHead) { - charScore++ - } - - // Penalty 1: pattern char is Head, candidate char is Tail. - if role == RTail && pRole == RHead { - charScore-- - } - // Penalty 2: first pattern character matched in the middle of a word. - if j == 1 && role == RTail { - charScore -= 4 - } - - // Third dimension encodes whether there is a gap between the previous match and the current - // one. - for k := 0; k < 2; k++ { - sc := m.scores[i-1][j-1][k].val() + charScore - - isConsecutive := k == 1 || i-1 == 0 || i-1 == lastSegStart - if isConsecutive { - // Bonus 3: a consecutive match. First character match also gets a bonus to - // ensure prefix final match score normalizes to 1.0. - // Logically, this is a part of charScore, but we have to compute it here because it - // only applies for consecutive matches (k == 1). - sc += consecutiveBonus - } - if k == 0 { - // Penalty 3: Matching inside a segment (and previous char wasn't matched). Penalize for the lack - // of alignment. - if role == RTail || role == RUCTail { - sc -= 3 - } - } - - if sc > m.scores[i][j][1].val() { - m.scores[i][j][1] = score(sc, k) - } - } - } - } - - result := m.scores[len(candidate)][len(m.pattern)][m.bestK(len(candidate), len(m.pattern))].val() - - return result -} - -// ScoreTable returns the score table computed for the provided candidate. Used only for debugging. -func (m *Matcher) ScoreTable(candidate string) string { - var buf bytes.Buffer - - var line1, line2, separator bytes.Buffer - line1.WriteString("\t") - line2.WriteString("\t") - for j := 0; j < len(m.pattern); j++ { - line1.WriteString(fmt.Sprintf("%c\t\t", m.pattern[j])) - separator.WriteString("----------------") - } - - buf.WriteString(line1.String()) - buf.WriteString("\n") - buf.WriteString(separator.String()) - buf.WriteString("\n") - - for i := 1; i <= len(candidate); i++ { - line1.Reset() - line2.Reset() - - line1.WriteString(fmt.Sprintf("%c\t", candidate[i-1])) - line2.WriteString("\t") - - for j := 1; j <= len(m.pattern); j++ { - line1.WriteString(fmt.Sprintf("M%6d(%c)\t", m.scores[i][j][0].val(), dir(m.scores[i][j][0].prevK()))) - line2.WriteString(fmt.Sprintf("H%6d(%c)\t", m.scores[i][j][1].val(), dir(m.scores[i][j][1].prevK()))) - } - buf.WriteString(line1.String()) - buf.WriteString("\n") - buf.WriteString(line2.String()) - buf.WriteString("\n") - buf.WriteString(separator.String()) - buf.WriteString("\n") - } - - return buf.String() -} - -func dir(prevK int) rune { - if prevK == 0 { - return 'M' - } - return 'H' -} - -func (m *Matcher) poorMatch() bool { - if len(m.pattern) < 2 { - return false - } - - i, j := m.lastCandidateLen, len(m.pattern) - k := m.bestK(i, j) - - var counter, len int - for i > 0 { - take := (k == 1) - k = m.scores[i][j][k].prevK() - if take { - len++ - if k == 0 && len < 3 && m.roles[i-1] == RTail { - // Short match in the middle of a word - counter++ - if counter > 1 { - return true - } - } - j-- - } else { - len = 0 - } - i-- - } - return false -} diff --git a/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/symbol.go b/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/symbol.go deleted file mode 100644 index df9fbd51..00000000 --- a/tools/vendor/golang.org/x/tools/internal/lsp/fuzzy/symbol.go +++ /dev/null @@ -1,236 +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. - -package fuzzy - -import ( - "unicode" -) - -// SymbolMatcher implements a fuzzy matching algorithm optimized for Go symbols -// of the form: -// example.com/path/to/package.object.field -// -// Knowing that we are matching symbols like this allows us to make the -// following optimizations: -// - We can incorporate right-to-left relevance directly into the score -// calculation. -// - We can match from right to left, discarding leading bytes if the input is -// too long. -// - We just take the right-most match without losing too much precision. This -// allows us to use an O(n) algorithm. -// - We can operate directly on chunked strings; in many cases we will -// be storing the package path and/or package name separately from the -// symbol or identifiers, so doing this avoids allocating strings. -// - We can return the index of the right-most match, allowing us to trim -// irrelevant qualification. -// -// This implementation is experimental, serving as a reference fast algorithm -// to compare to the fuzzy algorithm implemented by Matcher. -type SymbolMatcher struct { - // Using buffers of length 256 is both a reasonable size for most qualified - // symbols, and makes it easy to avoid bounds checks by using uint8 indexes. - pattern [256]rune - patternLen uint8 - inputBuffer [256]rune // avoid allocating when considering chunks - roles [256]uint32 // which roles does a rune play (word start, etc.) - segments [256]uint8 // how many segments from the right is each rune -} - -const ( - segmentStart uint32 = 1 << iota - wordStart - separator -) - -// NewSymbolMatcher creates a SymbolMatcher that may be used to match the given -// search pattern. -// -// Currently this matcher only accepts case-insensitive fuzzy patterns. -// -// An empty pattern matches no input. -func NewSymbolMatcher(pattern string) *SymbolMatcher { - m := &SymbolMatcher{} - for _, p := range pattern { - m.pattern[m.patternLen] = unicode.ToLower(p) - m.patternLen++ - if m.patternLen == 255 || int(m.patternLen) == len(pattern) { - // break at 255 so that we can represent patternLen with a uint8. - break - } - } - return m -} - -// Match looks for the right-most match of the search pattern within the symbol -// represented by concatenating the given chunks, returning its offset and -// score. -// -// If a match is found, the first return value will hold the absolute byte -// offset within all chunks for the start of the symbol. In other words, the -// index of the match within strings.Join(chunks, ""). If no match is found, -// the first return value will be -1. -// -// The second return value will be the score of the match, which is always -// between 0 and 1, inclusive. A score of 0 indicates no match. -func (m *SymbolMatcher) Match(chunks []string) (int, float64) { - // Explicit behavior for an empty pattern. - // - // As a minor optimization, this also avoids nilness checks later on, since - // the compiler can prove that m != nil. - if m.patternLen == 0 { - return -1, 0 - } - - // First phase: populate the input buffer with lower-cased runes. - // - // We could also check for a forward match here, but since we'd have to write - // the entire input anyway this has negligible impact on performance. - - var ( - inputLen = uint8(0) - modifiers = wordStart | segmentStart - ) - -input: - for _, chunk := range chunks { - for _, r := range chunk { - if r == '.' || r == '/' { - modifiers |= separator - } - // optimization: avoid calls to unicode.ToLower, which can't be inlined. - l := r - if r <= unicode.MaxASCII { - if 'A' <= r && r <= 'Z' { - l = r + 'a' - 'A' - } - } else { - l = unicode.ToLower(r) - } - if l != r { - modifiers |= wordStart - } - m.inputBuffer[inputLen] = l - m.roles[inputLen] = modifiers - inputLen++ - if m.roles[inputLen-1]&separator != 0 { - modifiers = wordStart | segmentStart - } else { - modifiers = 0 - } - // TODO: we should prefer the right-most input if it overflows, rather - // than the left-most as we're doing here. - if inputLen == 255 { - break input - } - } - } - - // Second phase: find the right-most match, and count segments from the - // right. - - var ( - pi = uint8(m.patternLen - 1) // pattern index - p = m.pattern[pi] // pattern rune - start = -1 // start offset of match - rseg = uint8(0) - ) - const maxSeg = 3 // maximum number of segments from the right to count, for scoring purposes. - - for ii := inputLen - 1; ; ii-- { - r := m.inputBuffer[ii] - if rseg < maxSeg && m.roles[ii]&separator != 0 { - rseg++ - } - m.segments[ii] = rseg - if p == r { - if pi == 0 { - start = int(ii) - break - } - pi-- - p = m.pattern[pi] - } - // Don't check ii >= 0 in the loop condition: ii is a uint8. - if ii == 0 { - break - } - } - - if start < 0 { - // no match: skip scoring - return -1, 0 - } - - // Third phase: find the shortest match, and compute the score. - - // Score is the average score for each character. - // - // A character score is the multiple of: - // 1. 1.0 if the character starts a segment, .8 if the character start a - // mid-segment word, otherwise 0.6. This carries over to immediately - // following characters. - // 2. For the final character match, the multiplier from (1) is reduced to - // .8 if the next character in the input is a mid-segment word, or 0.6 if - // the next character in the input is not a word or segment start. This - // ensures that we favor whole-word or whole-segment matches over prefix - // matches. - // 3. 1.0 if the character is part of the last segment, otherwise - // 1.0-.2*, with a max segment count of 3. - // - // This is a very naive algorithm, but it is fast. There's lots of prior art - // here, and we should leverage it. For example, we could explicitly consider - // character distance, and exact matches of words or segments. - // - // Also note that this might not actually find the highest scoring match, as - // doing so could require a non-linear algorithm, depending on how the score - // is calculated. - - pi = 0 - p = m.pattern[pi] - - const ( - segStreak = 1.0 - wordStreak = 0.8 - noStreak = 0.6 - perSegment = 0.2 // we count at most 3 segments above - ) - - streakBonus := noStreak - totScore := 0.0 - for ii := uint8(start); ii < inputLen; ii++ { - r := m.inputBuffer[ii] - if r == p { - pi++ - p = m.pattern[pi] - // Note: this could be optimized with some bit operations. - switch { - case m.roles[ii]&segmentStart != 0 && segStreak > streakBonus: - streakBonus = segStreak - case m.roles[ii]&wordStart != 0 && wordStreak > streakBonus: - streakBonus = wordStreak - } - finalChar := pi >= m.patternLen - // finalCost := 1.0 - if finalChar && streakBonus > noStreak { - switch { - case ii == inputLen-1 || m.roles[ii+1]&segmentStart != 0: - // Full segment: no reduction - case m.roles[ii+1]&wordStart != 0: - streakBonus = wordStreak - default: - streakBonus = noStreak - } - } - totScore += streakBonus * (1.0 - float64(m.segments[ii])*perSegment) - if finalChar { - break - } - } else { - streakBonus = noStreak - } - } - - return start, totScore / float64(m.patternLen) -} 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 9702094c..d9950b1f 100644 --- a/tools/vendor/golang.org/x/tools/internal/packagesinternal/packages.go +++ b/tools/vendor/golang.org/x/tools/internal/packagesinternal/packages.go @@ -23,6 +23,8 @@ 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 var SetModFlag = func(config interface{}, value string) {} var SetModFile = func(config interface{}, value string) {} 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 ab6b30b8..25a1426d 100644 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/common.go +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/common.go @@ -16,11 +16,10 @@ // 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 -// restrictions on a type parameter. In the future, this API may be available -// from go/types. +// restrictions on a type parameter. // -// See the example/README.md for a more detailed guide on how to update tools -// to support generics. +// An external version of these APIs is available in the +// golang.org/x/exp/typeparams module. package typeparams import ( @@ -121,15 +120,15 @@ func OriginMethod(fn *types.Func) *types.Func { // // For example, consider the following type declarations: // -// type Interface[T any] interface { -// Accept(T) -// } +// type Interface[T any] interface { +// Accept(T) +// } // -// type Container[T any] struct { -// Element T -// } +// type Container[T any] struct { +// Element T +// } // -// func (c Container[T]) Accept(t T) { c.Element = t } +// func (c Container[T]) Accept(t T) { c.Element = t } // // In this case, GenericAssignableTo reports that instantiations of Container // are assignable to the corresponding instantiation of Interface. diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/coretype.go b/tools/vendor/golang.org/x/tools/internal/typeparams/coretype.go new file mode 100644 index 00000000..993135ec --- /dev/null +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/coretype.go @@ -0,0 +1,122 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typeparams + +import ( + "go/types" +) + +// CoreType returns the core type of T or nil if T does not have a core type. +// +// See https://go.dev/ref/spec#Core_types for the definition of a core type. +func CoreType(T types.Type) types.Type { + U := T.Underlying() + if _, ok := U.(*types.Interface); !ok { + return U // for non-interface types, + } + + terms, err := _NormalTerms(U) + if len(terms) == 0 || err != nil { + // len(terms) -> empty type set of interface. + // err != nil => U is invalid, exceeds complexity bounds, or has an empty type set. + return nil // no core type. + } + + U = terms[0].Type().Underlying() + var identical int // i in [0,identical) => Identical(U, terms[i].Type().Underlying()) + for identical = 1; identical < len(terms); identical++ { + if !types.Identical(U, terms[identical].Type().Underlying()) { + break + } + } + + if identical == len(terms) { + // https://go.dev/ref/spec#Core_types + // "There is a single type U which is the underlying type of all types in the type set of T" + return U + } + ch, ok := U.(*types.Chan) + if !ok { + return nil // no core type as identical < len(terms) and U is not a channel. + } + // https://go.dev/ref/spec#Core_types + // "the type chan E if T contains only bidirectional channels, or the type chan<- E or + // <-chan E depending on the direction of the directional channels present." + for chans := identical; chans < len(terms); chans++ { + curr, ok := terms[chans].Type().Underlying().(*types.Chan) + if !ok { + return nil + } + if !types.Identical(ch.Elem(), curr.Elem()) { + return nil // channel elements are not identical. + } + if ch.Dir() == types.SendRecv { + // ch is bidirectional. We can safely always use curr's direction. + ch = curr + } else if curr.Dir() != types.SendRecv && ch.Dir() != curr.Dir() { + // ch and curr are not bidirectional and not the same direction. + return nil + } + } + return ch +} + +// _NormalTerms returns a slice of terms representing the normalized structural +// type restrictions of a type, if any. +// +// For all types other than *types.TypeParam, *types.Interface, and +// *types.Union, this is just a single term with Tilde() == false and +// Type() == typ. For *types.TypeParam, *types.Interface, and *types.Union, see +// below. +// +// Structural type restrictions of a type parameter are created via +// non-interface types embedded in its constraint interface (directly, or via a +// chain of interface embeddings). For example, in the declaration type +// T[P interface{~int; m()}] int the structural restriction of the type +// parameter P is ~int. +// +// With interface embedding and unions, the specification of structural type +// restrictions may be arbitrarily complex. For example, consider the +// following: +// +// type A interface{ ~string|~[]byte } +// +// type B interface{ int|string } +// +// type C interface { ~string|~int } +// +// type T[P interface{ A|B; C }] int +// +// In this example, the structural type restriction of P is ~string|int: A|B +// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, +// which when intersected with C (~string|~int) yields ~string|int. +// +// _NormalTerms computes these expansions and reductions, producing a +// "normalized" form of the embeddings. A structural restriction is normalized +// if it is a single union containing no interface terms, and is minimal in the +// sense that removing any term changes the set of types satisfying the +// constraint. It is left as a proof for the reader that, modulo sorting, there +// is exactly one such normalized form. +// +// Because the minimal representation always takes this form, _NormalTerms +// returns a slice of tilde terms corresponding to the terms of the union in +// the normalized structural restriction. An error is returned if the type is +// invalid, exceeds complexity bounds, or has an empty type set. In the latter +// case, _NormalTerms returns ErrEmptyTypeSet. +// +// _NormalTerms makes no guarantees about the order of terms, except that it +// is deterministic. +func _NormalTerms(typ types.Type) ([]*Term, error) { + switch typ := typ.(type) { + case *TypeParam: + return StructuralTerms(typ) + case *Union: + return UnionTermSet(typ) + case *types.Interface: + return InterfaceTermSet(typ) + default: + return []*Term{NewTerm(false, typ)}, nil + } +} 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 090f142a..9c631b65 100644 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/normalize.go +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/normalize.go @@ -24,20 +24,22 @@ var ErrEmptyTypeSet = errors.New("empty type set") // Structural type restrictions of a type parameter are created via // non-interface types embedded in its constraint interface (directly, or via a // chain of interface embeddings). For example, in the declaration -// type T[P interface{~int; m()}] int +// +// type T[P interface{~int; m()}] int +// // the structural restriction of the type parameter P is ~int. // // With interface embedding and unions, the specification of structural type // restrictions may be arbitrarily complex. For example, consider the // following: // -// type A interface{ ~string|~[]byte } +// type A interface{ ~string|~[]byte } // -// type B interface{ int|string } +// type B interface{ int|string } // -// type C interface { ~string|~int } +// type C interface { ~string|~int } // -// type T[P interface{ A|B; C }] int +// type T[P interface{ A|B; C }] int // // In this example, the structural type restriction of P is ~string|int: A|B // expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, diff --git a/tools/vendor/golang.org/x/tools/internal/typeparams/termlist.go b/tools/vendor/golang.org/x/tools/internal/typeparams/termlist.go index 10857d50..933106a2 100644 --- a/tools/vendor/golang.org/x/tools/internal/typeparams/termlist.go +++ b/tools/vendor/golang.org/x/tools/internal/typeparams/termlist.go @@ -97,15 +97,6 @@ func (xl termlist) norm() termlist { return rl } -// If the type set represented by xl is specified by a single (non-𝓤) term, -// structuralType returns that type. Otherwise it returns nil. -func (xl termlist) structuralType() types.Type { - if nl := xl.norm(); len(nl) == 1 { - return nl[0].typ // if nl.isAll() then typ is nil, which is ok - } - return nil -} - // union returns the union xl ∪ yl. func (xl termlist) union(yl termlist) termlist { return append(xl, yl...).norm() diff --git a/tools/vendor/gopkg.in/ini.v1/.golangci.yml b/tools/vendor/gopkg.in/ini.v1/.golangci.yml index b7256bae..631e3692 100644 --- a/tools/vendor/gopkg.in/ini.v1/.golangci.yml +++ b/tools/vendor/gopkg.in/ini.v1/.golangci.yml @@ -1,4 +1,9 @@ linters-settings: + staticcheck: + checks: [ + "all", + "-SA1019" # There are valid use cases of strings.Title + ] nakedret: max-func-lines: 0 # Disallow any unnamed return statement @@ -19,3 +24,4 @@ linters: - rowserrcheck - unconvert - goimports + - unparam diff --git a/tools/vendor/gopkg.in/ini.v1/README.md b/tools/vendor/gopkg.in/ini.v1/README.md index 1e429445..30606d97 100644 --- a/tools/vendor/gopkg.in/ini.v1/README.md +++ b/tools/vendor/gopkg.in/ini.v1/README.md @@ -1,6 +1,6 @@ # INI -[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/go-ini/ini/Go?logo=github&style=for-the-badge)](https://github.com/go-ini/ini/actions?query=workflow%3AGo) +[![GitHub Workflow Status](https://img.shields.io/github/checks-status/go-ini/ini/main?logo=github&style=for-the-badge)](https://github.com/go-ini/ini/actions?query=branch%3Amain) [![codecov](https://img.shields.io/codecov/c/github/go-ini/ini/master?logo=codecov&style=for-the-badge)](https://codecov.io/gh/go-ini/ini) [![GoDoc](https://img.shields.io/badge/GoDoc-Reference-blue?style=for-the-badge&logo=go)](https://pkg.go.dev/github.com/go-ini/ini?tab=doc) [![Sourcegraph](https://img.shields.io/badge/view%20on-Sourcegraph-brightgreen.svg?style=for-the-badge&logo=sourcegraph)](https://sourcegraph.com/github.com/go-ini/ini) @@ -24,7 +24,7 @@ Package ini provides INI file read and write functionality in Go. ## Installation -The minimum requirement of Go is **1.12**. +The minimum requirement of Go is **1.13**. ```sh $ go get gopkg.in/ini.v1 diff --git a/tools/vendor/gopkg.in/ini.v1/codecov.yml b/tools/vendor/gopkg.in/ini.v1/codecov.yml index 31f646ee..e02ec84b 100644 --- a/tools/vendor/gopkg.in/ini.v1/codecov.yml +++ b/tools/vendor/gopkg.in/ini.v1/codecov.yml @@ -4,6 +4,13 @@ coverage: project: default: threshold: 1% + informational: true + patch: + defualt: + only_pulls: true + informational: true comment: layout: 'diff' + +github_checks: false diff --git a/tools/vendor/gopkg.in/ini.v1/error.go b/tools/vendor/gopkg.in/ini.v1/error.go index d88347c5..f66bc94b 100644 --- a/tools/vendor/gopkg.in/ini.v1/error.go +++ b/tools/vendor/gopkg.in/ini.v1/error.go @@ -32,3 +32,18 @@ func IsErrDelimiterNotFound(err error) bool { func (err ErrDelimiterNotFound) Error() string { return fmt.Sprintf("key-value delimiter not found: %s", err.Line) } + +// ErrEmptyKeyName indicates the error type of no key name is found which there should be one. +type ErrEmptyKeyName struct { + Line string +} + +// IsErrEmptyKeyName returns true if the given error is an instance of ErrEmptyKeyName. +func IsErrEmptyKeyName(err error) bool { + _, ok := err.(ErrEmptyKeyName) + return ok +} + +func (err ErrEmptyKeyName) Error() string { + return fmt.Sprintf("empty key name: %s", err.Line) +} diff --git a/tools/vendor/gopkg.in/ini.v1/file.go b/tools/vendor/gopkg.in/ini.v1/file.go index 9d91c31a..f8b22408 100644 --- a/tools/vendor/gopkg.in/ini.v1/file.go +++ b/tools/vendor/gopkg.in/ini.v1/file.go @@ -342,6 +342,7 @@ func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { // Use buffer to make sure target is safe until finish encoding. buf := bytes.NewBuffer(nil) + lastSectionIdx := len(f.sectionList) - 1 for i, sname := range f.sectionList { sec := f.SectionWithIndex(sname, f.sectionIndexes[i]) if len(sec.Comment) > 0 { @@ -371,12 +372,13 @@ func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { } } + isLastSection := i == lastSectionIdx if sec.isRawSection { if _, err := buf.WriteString(sec.rawBody); err != nil { return nil, err } - if PrettySection { + if PrettySection && !isLastSection { // Put a line between sections if _, err := buf.WriteString(LineBreak); err != nil { return nil, err @@ -448,9 +450,7 @@ func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { } if key.isBooleanType { - if kname != sec.keyList[len(sec.keyList)-1] { - buf.WriteString(LineBreak) - } + buf.WriteString(LineBreak) return true, nil } @@ -496,7 +496,7 @@ func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { } } - if PrettySection { + if PrettySection && !isLastSection { // Put a line between sections if _, err := buf.WriteString(LineBreak); err != nil { return nil, err diff --git a/tools/vendor/gopkg.in/ini.v1/parser.go b/tools/vendor/gopkg.in/ini.v1/parser.go index ac1c980a..44fc526c 100644 --- a/tools/vendor/gopkg.in/ini.v1/parser.go +++ b/tools/vendor/gopkg.in/ini.v1/parser.go @@ -164,6 +164,10 @@ func readKeyName(delimiters string, in []byte) (string, int, error) { if endIdx < 0 { return "", -1, ErrDelimiterNotFound{line} } + if endIdx == 0 { + return "", -1, ErrEmptyKeyName{line} + } + return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil } @@ -463,8 +467,9 @@ func (f *File) parse(reader io.Reader) (err error) { kname, offset, err := readKeyName(f.options.KeyValueDelimiters, line) if err != nil { + switch { // Treat as boolean key when desired, and whole line is key name. - if IsErrDelimiterNotFound(err) { + case IsErrDelimiterNotFound(err): switch { case f.options.AllowBooleanKeys: kname, err := p.readValue(line, parserBufferSize) @@ -482,6 +487,8 @@ func (f *File) parse(reader io.Reader) (err error) { case f.options.SkipUnrecognizableLines: continue } + case IsErrEmptyKeyName(err) && f.options.SkipUnrecognizableLines: + continue } return err } 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 3480152f..db7debc2 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/code/code.go +++ b/tools/vendor/honnef.co/go/tools/analysis/code/code.go @@ -10,7 +10,9 @@ import ( "go/types" "strings" - "honnef.co/go/tools/analysis/facts" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/facts/purity" + "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/pattern" @@ -195,7 +197,7 @@ func IsCallToAny(pass *analysis.Pass, node ast.Node, names ...string) bool { } func File(pass *analysis.Pass, node Positioner) *ast.File { - m := pass.ResultOf[facts.TokenFile].(map[*token.File]*ast.File) + m := pass.ResultOf[tokenfile.Analyzer].(map[*token.File]*ast.File) return m[pass.Fset.File(node.Pos())] } @@ -208,9 +210,9 @@ func IsGenerated(pass *analysis.Pass, pos token.Pos) bool { // Generator returns the generator that generated the file containing // pos. It ignores //line directives. -func Generator(pass *analysis.Pass, pos token.Pos) (facts.Generator, bool) { +func Generator(pass *analysis.Pass, pos token.Pos) (generated.Generator, bool) { file := pass.Fset.PositionFor(pos, false).Filename - m := pass.ResultOf[facts.Generated].(map[string]facts.Generator) + m := pass.ResultOf[generated.Analyzer].(map[string]generated.Generator) g, ok := m[file] return g, ok } @@ -220,7 +222,7 @@ func Generator(pass *analysis.Pass, pos token.Pos) (facts.Generator, bool) { // syntactic check, meaning that any function call may have side // effects, regardless of the called function's body. Otherwise, // purity will be consulted to determine the purity of function calls. -func MayHaveSideEffects(pass *analysis.Pass, expr ast.Expr, purity facts.PurityResult) bool { +func MayHaveSideEffects(pass *analysis.Pass, expr ast.Expr, purity purity.Result) bool { switch expr := expr.(type) { case *ast.BadExpr: return true @@ -340,3 +342,17 @@ func IsIntegerLiteral(pass *analysis.Pass, node ast.Node, value constant.Value) } return constant.Compare(tv.Value, token.EQL, value) } + +// IsMethod reports whether expr is a method call of a named method with signature meth. +// If name is empty, it is not checked. +// For now, method expressions (Type.Method(recv, ..)) are not considered method calls. +func IsMethod(pass *analysis.Pass, expr *ast.SelectorExpr, name string, meth *types.Signature) bool { + if name != "" && expr.Sel.Name != name { + return false + } + sel, ok := pass.TypesInfo.Selections[expr] + if !ok || sel.Kind() != types.MethodVal { + return false + } + return types.Identical(sel.Type(), meth) +} diff --git a/tools/vendor/honnef.co/go/tools/analysis/facts/deprecated.go b/tools/vendor/honnef.co/go/tools/analysis/facts/deprecated/deprecated.go similarity index 95% rename from tools/vendor/honnef.co/go/tools/analysis/facts/deprecated.go rename to tools/vendor/honnef.co/go/tools/analysis/facts/deprecated/deprecated.go index dbc5ede5..c558fabb 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/facts/deprecated.go +++ b/tools/vendor/honnef.co/go/tools/analysis/facts/deprecated/deprecated.go @@ -1,4 +1,4 @@ -package facts +package deprecated import ( "go/ast" @@ -15,17 +15,17 @@ type IsDeprecated struct{ Msg string } func (*IsDeprecated) AFact() {} func (d *IsDeprecated) String() string { return "Deprecated: " + d.Msg } -type DeprecatedResult struct { +type Result struct { Objects map[types.Object]*IsDeprecated Packages map[*types.Package]*IsDeprecated } -var Deprecated = &analysis.Analyzer{ +var Analyzer = &analysis.Analyzer{ Name: "fact_deprecated", Doc: "Mark deprecated objects", Run: deprecated, FactTypes: []analysis.Fact{(*IsDeprecated)(nil)}, - ResultType: reflect.TypeOf(DeprecatedResult{}), + ResultType: reflect.TypeOf(Result{}), } func deprecated(pass *analysis.Pass) (interface{}, error) { @@ -129,7 +129,7 @@ func deprecated(pass *analysis.Pass) (interface{}, error) { ast.Inspect(f, fn) } - out := DeprecatedResult{ + out := Result{ Objects: map[types.Object]*IsDeprecated{}, Packages: map[*types.Package]*IsDeprecated{}, } diff --git a/tools/vendor/honnef.co/go/tools/analysis/facts/directives.go b/tools/vendor/honnef.co/go/tools/analysis/facts/directives/directives.go similarity index 88% rename from tools/vendor/honnef.co/go/tools/analysis/facts/directives.go rename to tools/vendor/honnef.co/go/tools/analysis/facts/directives/directives.go index 800fce2e..a8c3522d 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/facts/directives.go +++ b/tools/vendor/honnef.co/go/tools/analysis/facts/directives/directives.go @@ -1,4 +1,4 @@ -package facts +package directives import ( "reflect" @@ -11,7 +11,7 @@ func directives(pass *analysis.Pass) (interface{}, error) { return lint.ParseDirectives(pass.Files, pass.Fset), nil } -var Directives = &analysis.Analyzer{ +var Analyzer = &analysis.Analyzer{ Name: "directives", Doc: "extracts linter directives", Run: directives, diff --git a/tools/vendor/honnef.co/go/tools/analysis/facts/generated.go b/tools/vendor/honnef.co/go/tools/analysis/facts/generated/generated.go similarity index 97% rename from tools/vendor/honnef.co/go/tools/analysis/facts/generated.go rename to tools/vendor/honnef.co/go/tools/analysis/facts/generated/generated.go index 058fd892..240d0666 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/facts/generated.go +++ b/tools/vendor/honnef.co/go/tools/analysis/facts/generated/generated.go @@ -1,4 +1,4 @@ -package facts +package generated import ( "bufio" @@ -78,7 +78,7 @@ func isGenerated(path string) (Generator, bool) { return 0, false } -var Generated = &analysis.Analyzer{ +var Analyzer = &analysis.Analyzer{ Name: "isgenerated", Doc: "annotate file names that have been code generated", Run: func(pass *analysis.Pass) (interface{}, error) { diff --git a/tools/vendor/honnef.co/go/tools/analysis/facts/purity.go b/tools/vendor/honnef.co/go/tools/analysis/facts/purity/purity.go similarity index 96% rename from tools/vendor/honnef.co/go/tools/analysis/facts/purity.go rename to tools/vendor/honnef.co/go/tools/analysis/facts/purity/purity.go index 582b6209..4afc7a6a 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/facts/purity.go +++ b/tools/vendor/honnef.co/go/tools/analysis/facts/purity/purity.go @@ -1,4 +1,4 @@ -package facts +package purity import ( "go/types" @@ -16,15 +16,15 @@ type IsPure struct{} func (*IsPure) AFact() {} func (d *IsPure) String() string { return "is pure" } -type PurityResult map[*types.Func]*IsPure +type Result map[*types.Func]*IsPure -var Purity = &analysis.Analyzer{ +var Analyzer = &analysis.Analyzer{ Name: "fact_purity", Doc: "Mark pure functions", Run: purity, Requires: []*analysis.Analyzer{buildir.Analyzer}, FactTypes: []analysis.Fact{(*IsPure)(nil)}, - ResultType: reflect.TypeOf(PurityResult{}), + ResultType: reflect.TypeOf(Result{}), } var pureStdlib = map[string]struct{}{ @@ -170,7 +170,7 @@ func purity(pass *analysis.Pass) (interface{}, error) { check(fn) } - out := PurityResult{} + out := Result{} for _, fact := range pass.AllObjectFacts() { out[fact.Object.(*types.Func)] = fact.Fact.(*IsPure) } diff --git a/tools/vendor/honnef.co/go/tools/analysis/facts/token.go b/tools/vendor/honnef.co/go/tools/analysis/facts/tokenfile/token.go similarity index 89% rename from tools/vendor/honnef.co/go/tools/analysis/facts/token.go rename to tools/vendor/honnef.co/go/tools/analysis/facts/tokenfile/token.go index 26e76ff7..e7f747f0 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/facts/token.go +++ b/tools/vendor/honnef.co/go/tools/analysis/facts/tokenfile/token.go @@ -1,4 +1,4 @@ -package facts +package tokenfile import ( "go/ast" @@ -8,7 +8,7 @@ import ( "golang.org/x/tools/go/analysis" ) -var TokenFile = &analysis.Analyzer{ +var Analyzer = &analysis.Analyzer{ Name: "tokenfileanalyzer", Doc: "creates a mapping of *token.File to *ast.File", Run: func(pass *analysis.Pass) (interface{}, error) { 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 f7cd64ab..d52945e7 100644 --- a/tools/vendor/honnef.co/go/tools/analysis/report/report.go +++ b/tools/vendor/honnef.co/go/tools/analysis/report/report.go @@ -10,7 +10,7 @@ import ( "strconv" "strings" - "honnef.co/go/tools/analysis/facts" + "honnef.co/go/tools/analysis/facts/generated" "honnef.co/go/tools/go/ast/astutil" "golang.org/x/tools/go/analysis" @@ -172,7 +172,7 @@ func Report(pass *analysis.Pass, node Positioner, message string, opts ...Option file := DisplayPosition(pass.Fset, node.Pos()).Filename if cfg.FilterGenerated { - m := pass.ResultOf[facts.Generated].(map[string]facts.Generator) + m := pass.ResultOf[generated.Analyzer].(map[string]generated.Generator) if _, ok := m[file]; ok { return } 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 7cef5f1e..e5566ade 100644 --- a/tools/vendor/honnef.co/go/tools/go/ir/builder.go +++ b/tools/vendor/honnef.co/go/tools/go/ir/builder.go @@ -669,17 +669,24 @@ func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { } case *ast.SliceExpr: - var low, high, max Value var x Value - switch typeutil.CoreType(fn.Pkg.typeOf(e.X)).Underlying().(type) { - case *types.Array: - // Potentially escaping. - x = b.addr(fn, e.X, true).address(fn) - case *types.Basic, *types.Slice, *types.Pointer: // *array + if core := typeutil.CoreType(fn.Pkg.typeOf(e.X)); core != nil { + switch core.Underlying().(type) { + case *types.Array: + // Potentially escaping. + x = b.addr(fn, e.X, true).address(fn) + case *types.Basic, *types.Slice, *types.Pointer: // *array + x = b.expr(fn, e.X) + default: + panic("unreachable") + } + } else { + // We're indexing a string | []byte. Note that other combinations such as []byte | [4]byte are currently not + // allowed by the language. x = b.expr(fn, e.X) - default: - panic("unreachable") } + + var low, high, max Value if e.High != nil { high = b.expr(fn, e.High) } diff --git a/tools/vendor/honnef.co/go/tools/go/types/typeutil/typeparams.go b/tools/vendor/honnef.co/go/tools/go/types/typeutil/typeparams.go index c05af1d2..9bfe8a38 100644 --- a/tools/vendor/honnef.co/go/tools/go/types/typeutil/typeparams.go +++ b/tools/vendor/honnef.co/go/tools/go/types/typeutil/typeparams.go @@ -52,6 +52,10 @@ func (ts TypeSet) CoreType() types.Type { // typ is currently a bidirectional channel. The term's type is either also bidirectional, or // unidirectional. Use the term's type. typ = ut + } else if ch2.Dir() == types.SendRecv { + // typ is currently a unidirectional channel and the term's type is bidirectional, which means it has no + // effect. + continue } else if ch1.Dir() != ch2.Dir() { // typ is not bidirectional and typ and term disagree about the direction return nil 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 63c93ac2..6e4cdff2 100644 --- a/tools/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go +++ b/tools/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go @@ -8,7 +8,8 @@ import ( "honnef.co/go/tools/analysis/code" "honnef.co/go/tools/analysis/edit" - "honnef.co/go/tools/analysis/facts" + "honnef.co/go/tools/analysis/facts/generated" + "honnef.co/go/tools/analysis/facts/tokenfile" "honnef.co/go/tools/analysis/report" "honnef.co/go/tools/go/ast/astutil" "honnef.co/go/tools/go/ir" @@ -118,7 +119,7 @@ func RedundantTypeInDeclarationChecker(verb string, flagHelpfulTypes bool) *anal } gen, _ := code.Generator(pass, decl.Pos()) - if gen == facts.Cgo { + if gen == generated.Cgo { // TODO(dh): remove this exception once we can use UsesCgo return } @@ -203,6 +204,6 @@ func RedundantTypeInDeclarationChecker(verb string, flagHelpfulTypes bool) *anal return &analysis.Analyzer{ Run: fn, - Requires: []*analysis.Analyzer{facts.Generated, inspect.Analyzer, facts.TokenFile, facts.Generated}, + Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer, tokenfile.Analyzer}, } } diff --git a/tools/vendor/honnef.co/go/tools/knowledge/signatures.go b/tools/vendor/honnef.co/go/tools/knowledge/signatures.go new file mode 100644 index 00000000..d072e61a --- /dev/null +++ b/tools/vendor/honnef.co/go/tools/knowledge/signatures.go @@ -0,0 +1,107 @@ +package knowledge + +import ( + "go/token" + "go/types" +) + +var Signatures = map[string]*types.Signature{ + "(io.Seeker).Seek": types.NewSignature(nil, + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.Typ[types.Int64]), + types.NewParam(token.NoPos, nil, "", types.Typ[types.Int]), + ), + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.Typ[types.Int64]), + types.NewParam(token.NoPos, nil, "", types.Universe.Lookup("error").Type()), + ), + false, + ), + + "(io.Writer).Write": types.NewSignature(nil, + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.NewSlice(types.Typ[types.Byte])), + ), + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.Typ[types.Int]), + types.NewParam(token.NoPos, nil, "", types.Universe.Lookup("error").Type()), + ), + false, + ), + + "(io.StringWriter).WriteString": types.NewSignature(nil, + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.Typ[types.String]), + ), + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.Typ[types.Int]), + types.NewParam(token.NoPos, nil, "", types.Universe.Lookup("error").Type()), + ), + false, + ), + + "(encoding.TextMarshaler).MarshalText": types.NewSignature(nil, + types.NewTuple(), + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.NewSlice(types.Typ[types.Byte])), + types.NewParam(token.NoPos, nil, "", types.Universe.Lookup("error").Type()), + ), + false, + ), + + "(encoding/json.Marshaler).MarshalJSON": types.NewSignature(nil, + types.NewTuple(), + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.NewSlice(types.Typ[types.Byte])), + types.NewParam(token.NoPos, nil, "", types.Universe.Lookup("error").Type()), + ), + false, + ), + + "(fmt.Stringer).String": types.NewSignature(nil, + types.NewTuple(), + types.NewTuple( + types.NewParam(token.NoPos, nil, "", types.Typ[types.String]), + ), + false, + ), +} + +var Interfaces = map[string]*types.Interface{ + "fmt.Stringer": types.NewInterfaceType( + []*types.Func{ + types.NewFunc(token.NoPos, nil, "String", Signatures["(fmt.Stringer).String"]), + }, + nil, + ).Complete(), + + "error": types.Universe.Lookup("error").Type().Underlying().(*types.Interface), + + "io.Writer": types.NewInterfaceType( + []*types.Func{ + types.NewFunc(token.NoPos, nil, "Write", Signatures["(io.Writer).Write"]), + }, + nil, + ).Complete(), + + "io.StringWriter": types.NewInterfaceType( + []*types.Func{ + types.NewFunc(token.NoPos, nil, "WriteString", Signatures["(io.StringWriter).WriteString"]), + }, + nil, + ).Complete(), + + "encoding.TextMarshaler": types.NewInterfaceType( + []*types.Func{ + types.NewFunc(token.NoPos, nil, "MarshalText", Signatures["(encoding.TextMarshaler).MarshalText"]), + }, + nil, + ).Complete(), + + "encoding/json.Marshaler": types.NewInterfaceType( + []*types.Func{ + types.NewFunc(token.NoPos, nil, "MarshalJSON", Signatures["(encoding/json.Marshaler).MarshalJSON"]), + }, + nil, + ).Complete(), +} diff --git a/tools/vendor/honnef.co/go/tools/pattern/convert.go b/tools/vendor/honnef.co/go/tools/pattern/convert.go index bfbd0783..34e2cd45 100644 --- a/tools/vendor/honnef.co/go/tools/pattern/convert.go +++ b/tools/vendor/honnef.co/go/tools/pattern/convert.go @@ -148,7 +148,7 @@ func NodeToAST(node Node, state State) interface{} { default: return v } - case Builtin, Any, Object, Function, Not, Or: + case Builtin, Any, Object, Symbol, Not, Or: panic("XXX") case List: if (node == List{}) { diff --git a/tools/vendor/honnef.co/go/tools/pattern/doc.go b/tools/vendor/honnef.co/go/tools/pattern/doc.go index 97461754..c963bf71 100644 --- a/tools/vendor/honnef.co/go/tools/pattern/doc.go +++ b/tools/vendor/honnef.co/go/tools/pattern/doc.go @@ -185,15 +185,15 @@ Subsequent occurrences of 'true' no longer refer to the pre-declared identifier. (Object name) matches an identifier by name, but yields the types.Object it refers to. -(Function name) matches ast.Idents and ast.SelectorExprs that refer to a function with a given fully qualified name. +(Symbol name) matches ast.Idents and ast.SelectorExprs that refer to a symbol with a given fully qualified name. For example, "net/url.PathEscape" matches the PathEscape function in the net/url package, and "(net/url.EscapeError).Error" refers to the Error method on the net/url.EscapeError type, either on an instance of the type, or on the type itself. For example, the following patterns match the following lines of code: - (CallExpr (Function "fmt.Println") _) // pattern 1 - (CallExpr (Function "(net/url.EscapeError).Error") _) // pattern 2 + (CallExpr (Symbol "fmt.Println") _) // pattern 1 + (CallExpr (Symbol "(net/url.EscapeError).Error") _) // pattern 2 fmt.Println("hello, world") // matches pattern 1 var x url.EscapeError diff --git a/tools/vendor/honnef.co/go/tools/pattern/match.go b/tools/vendor/honnef.co/go/tools/pattern/match.go index 4d939b2c..b4edac94 100644 --- a/tools/vendor/honnef.co/go/tools/pattern/match.go +++ b/tools/vendor/honnef.co/go/tools/pattern/match.go @@ -474,7 +474,7 @@ func (obj Object) Match(m *Matcher, node interface{}) (interface{}, bool) { return id, ok } -func (fn Function) Match(m *Matcher, node interface{}) (interface{}, bool) { +func (fn Symbol) Match(m *Matcher, node interface{}) (interface{}, bool) { var name string var obj types.Object @@ -503,31 +503,37 @@ func (fn Function) Match(m *Matcher, node interface{}) (interface{}, bool) { switch fun := fun.(type) { case *ast.Ident: obj = m.TypesInfo.ObjectOf(fun) - switch obj := obj.(type) { - case *types.Func: - // OPT(dh): optimize this similar to code.FuncName - name = obj.FullName() - case *types.Builtin: - name = obj.Name() - case *types.TypeName: - name = types.TypeString(obj.Type(), nil) - default: - return nil, false - } case *ast.SelectorExpr: obj = m.TypesInfo.ObjectOf(fun.Sel) - switch obj := obj.(type) { - case *types.Func: - // OPT(dh): optimize this similar to code.FuncName - name = obj.FullName() - case *types.TypeName: - name = types.TypeString(obj.Type(), nil) - default: + default: + panic("unreachable") + } + switch obj := obj.(type) { + case *types.Func: + // OPT(dh): optimize this similar to code.FuncName + name = obj.FullName() + 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 + } + name = types.TypeString(obj.Type(), nil) + case *types.Const, *types.Var: + if obj.Pkg() == nil { + return nil, false + } + if obj.Parent() != obj.Pkg().Scope() { return nil, false } + name = fmt.Sprintf("%s.%s", obj.Pkg().Path(), obj.Name()) default: - panic("unreachable") + return nil, false } + _, ok = match(m, fn.Name, name) return obj, ok } @@ -612,7 +618,7 @@ var ( _ matcher = Nil{} _ matcher = Builtin{} _ matcher = Object{} - _ matcher = Function{} + _ matcher = Symbol{} _ matcher = Or{} _ matcher = Not{} _ matcher = IntegerLiteral{} diff --git a/tools/vendor/honnef.co/go/tools/pattern/parser.go b/tools/vendor/honnef.co/go/tools/pattern/parser.go index a21f7964..2529051d 100644 --- a/tools/vendor/honnef.co/go/tools/pattern/parser.go +++ b/tools/vendor/honnef.co/go/tools/pattern/parser.go @@ -97,7 +97,7 @@ var nodeToASTTypes = map[reflect.Type][]reflect.Type{ reflect.TypeOf(List{}): {reflect.TypeOf((*ast.BlockStmt)(nil)), reflect.TypeOf((*ast.FieldList)(nil))}, reflect.TypeOf(Builtin{}): {reflect.TypeOf((*ast.Ident)(nil))}, reflect.TypeOf(Object{}): {reflect.TypeOf((*ast.Ident)(nil))}, - reflect.TypeOf(Function{}): {reflect.TypeOf((*ast.Ident)(nil)), reflect.TypeOf((*ast.SelectorExpr)(nil))}, + reflect.TypeOf(Symbol{}): {reflect.TypeOf((*ast.Ident)(nil)), reflect.TypeOf((*ast.SelectorExpr)(nil))}, reflect.TypeOf(Any{}): allTypes, reflect.TypeOf(RangeStmt{}): {reflect.TypeOf((*ast.RangeStmt)(nil))}, reflect.TypeOf(AssignStmt{}): {reflect.TypeOf((*ast.AssignStmt)(nil))}, @@ -145,9 +145,11 @@ var nodeToASTTypes = map[reflect.Type][]reflect.Type{ } var requiresTypeInfo = map[string]bool{ - "Function": true, - "Builtin": true, - "Object": true, + "Symbol": true, + "Builtin": true, + "Object": true, + "IntegerLiteral": true, + "TrulyConstantExpression": true, } type Parser struct { @@ -355,7 +357,7 @@ var structNodes = map[string]reflect.Type{ "IncDecStmt": reflect.TypeOf(IncDecStmt{}), "BasicLit": reflect.TypeOf(BasicLit{}), "Object": reflect.TypeOf(Object{}), - "Function": reflect.TypeOf(Function{}), + "Symbol": reflect.TypeOf(Symbol{}), "Or": reflect.TypeOf(Or{}), "Not": reflect.TypeOf(Not{}), "IntegerLiteral": reflect.TypeOf(IntegerLiteral{}), diff --git a/tools/vendor/honnef.co/go/tools/pattern/pattern.go b/tools/vendor/honnef.co/go/tools/pattern/pattern.go index abb8a425..fbbafdfa 100644 --- a/tools/vendor/honnef.co/go/tools/pattern/pattern.go +++ b/tools/vendor/honnef.co/go/tools/pattern/pattern.go @@ -59,14 +59,14 @@ var ( _ Node = BasicLit{} _ Node = Nil{} _ Node = Object{} - _ Node = Function{} + _ Node = Symbol{} _ Node = Not{} _ Node = Or{} _ Node = IntegerLiteral{} _ Node = TrulyConstantExpression{} ) -type Function struct { +type Symbol struct { Name Node } @@ -401,7 +401,7 @@ func (stmt TypeSwitchStmt) String() string { return stringify(stmt) } func (nil Nil) String() string { return "nil" } func (builtin Builtin) String() string { return stringify(builtin) } func (obj Object) String() string { return stringify(obj) } -func (fn Function) String() string { return stringify(fn) } +func (fn Symbol) String() string { return stringify(fn) } func (el Ellipsis) String() string { return stringify(el) } func (not Not) String() string { return stringify(not) } func (lit IntegerLiteral) String() string { return stringify(lit) } @@ -509,7 +509,7 @@ func (TypeSwitchStmt) isNode() {} func (Nil) isNode() {} func (Builtin) isNode() {} func (Object) isNode() {} -func (Function) isNode() {} +func (Symbol) isNode() {} func (Ellipsis) isNode() {} func (Or) isNode() {} func (List) isNode() {} diff --git a/tools/vendor/honnef.co/go/tools/simple/analysis.go b/tools/vendor/honnef.co/go/tools/simple/analysis.go index a32071dd..a67a3209 100644 --- a/tools/vendor/honnef.co/go/tools/simple/analysis.go +++ b/tools/vendor/honnef.co/go/tools/simple/analysis.go @@ -3,7 +3,7 @@ package simple import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" - "honnef.co/go/tools/analysis/facts" + "honnef.co/go/tools/analysis/facts/generated" "honnef.co/go/tools/analysis/lint" "honnef.co/go/tools/internal/passes/buildir" ) @@ -11,95 +11,95 @@ import ( var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ "S1000": { Run: CheckSingleCaseSelect, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1001": { Run: CheckLoopCopy, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1002": { Run: CheckIfBoolCmp, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1003": { Run: CheckStringsContains, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1004": { Run: CheckBytesCompare, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1005": { Run: CheckUnnecessaryBlank, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1006": { Run: CheckForTrue, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1007": { Run: CheckRegexpRaw, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1008": { Run: CheckIfReturn, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1009": { Run: CheckRedundantNilCheckWithLen, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1010": { Run: CheckSlicing, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1011": { Run: CheckLoopAppend, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1012": { Run: CheckTimeSince, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1016": { Run: CheckSimplerStructConversion, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1017": { Run: CheckTrim, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1018": { Run: CheckLoopSlide, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1019": { Run: CheckMakeLenCap, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1020": { Run: CheckAssertNotNil, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1021": { Run: CheckDeclareAssign, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1023": { Run: CheckRedundantBreak, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1024": { Run: CheckTimeUntil, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1025": { Run: CheckRedundantSprintf, - Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer, generated.Analyzer}, }, "S1028": { Run: CheckErrorsNewSprintf, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1029": { Run: CheckRangeStringRunes, @@ -107,27 +107,27 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "S1030": { Run: CheckBytesBufferConversions, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1031": { Run: CheckNilCheckAroundRange, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1032": { Run: CheckSortHelpers, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1033": { Run: CheckGuardedDelete, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1034": { Run: CheckSimplifyTypeSwitch, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1035": { Run: CheckRedundantCanonicalHeaderKey, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1036": { Run: CheckUnnecessaryGuard, @@ -135,18 +135,18 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "S1037": { Run: CheckElaborateSleep, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1038": { Run: CheckPrintSprintf, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1039": { Run: CheckSprintLiteral, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, "S1040": { Run: CheckSameTypeTypeAssertion, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer}, }, }) diff --git a/tools/vendor/honnef.co/go/tools/simple/lint.go b/tools/vendor/honnef.co/go/tools/simple/lint.go index 7d81e8ab..0abc5aef 100644 --- a/tools/vendor/honnef.co/go/tools/simple/lint.go +++ b/tools/vendor/honnef.co/go/tools/simple/lint.go @@ -68,7 +68,7 @@ var ( [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))]) (ForStmt (AssignStmt key@(Ident _) ":=" (IntegerLiteral "0")) - (BinaryExpr key "<" (CallExpr (Function "len") [src])) + (BinaryExpr key "<" (CallExpr (Symbol "len") [src])) (IncDecStmt key "++") [(AssignStmt (IndexExpr dst key) "=" (IndexExpr src key))]))`) ) @@ -385,7 +385,7 @@ func CheckStringsContains(pass *analysis.Pass) (interface{}, error) { } var ( - checkBytesCompareQ = pattern.MustParse(`(BinaryExpr (CallExpr (Function "bytes.Compare") args) op@(Or "==" "!=") (IntegerLiteral "0"))`) + 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))`) ) @@ -659,8 +659,7 @@ func CheckRedundantNilCheckWithLen(pass *analysis.Pass) (interface{}, error) { if !ok { return } - yxFun, ok := yx.Fun.(*ast.Ident) - if !ok || yxFun.Name != "len" || len(yx.Args) != 1 { + if !code.IsCallTo(pass, yx, "len") { return } yxArg, ok := yx.Args[knowledge.Arg("len.v")].(*ast.Ident) @@ -817,7 +816,7 @@ func CheckLoopAppend(pass *analysis.Pass) (interface{}, error) { } var ( - checkTimeSinceQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (Function "time.Now") []) (Function "(time.Time).Sub")) [arg])`) + checkTimeSinceQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (Symbol "time.Now") []) (Symbol "(time.Time).Sub")) [arg])`) checkTimeSinceR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Since")) [arg])`) ) @@ -834,7 +833,7 @@ func CheckTimeSince(pass *analysis.Pass) (interface{}, error) { } var ( - checkTimeUntilQ = pattern.MustParse(`(CallExpr (Function "(time.Time).Sub") [(CallExpr (Function "time.Now") [])])`) + checkTimeUntilQ = pattern.MustParse(`(CallExpr (Symbol "(time.Time).Sub") [(CallExpr (Symbol "time.Now") [])])`) checkTimeUntilR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Until")) [arg])`) ) @@ -1488,30 +1487,6 @@ func CheckRedundantBreak(pass *analysis.Pass) (interface{}, error) { return nil, nil } -func isStringer(T types.Type, msCache *typeutil.MethodSetCache) bool { - ms := msCache.MethodSet(T) - sel := ms.Lookup(nil, "String") - 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() != 0 { - return false - } - if sig.Results().Len() != 1 { - return false - } - if !typeutil.IsType(sig.Results().At(0).Type(), "string") { - return false - } - return true -} - func isFormatter(T types.Type, msCache *typeutil.MethodSetCache) bool { // TODO(dh): this function also exists in staticcheck/lint.go – deduplicate. @@ -1537,7 +1512,7 @@ func isFormatter(T types.Type, msCache *typeutil.MethodSetCache) bool { return true } -var checkRedundantSprintfQ = pattern.MustParse(`(CallExpr (Function "fmt.Sprintf") [format arg])`) +var checkRedundantSprintfQ = pattern.MustParse(`(CallExpr (Symbol "fmt.Sprintf") [format arg])`) func CheckRedundantSprintf(pass *analysis.Pass) (interface{}, error) { fn := func(node ast.Node) { @@ -1571,7 +1546,7 @@ func CheckRedundantSprintf(pass *analysis.Pass) (interface{}, error) { return } - if isStringer(typ, &irpkg.Prog.MethodSets) { + if types.Implements(typ, knowledge.Interfaces["fmt.Stringer"]) { replacement := &ast.CallExpr{ Fun: &ast.SelectorExpr{ X: arg, @@ -1609,7 +1584,7 @@ func CheckRedundantSprintf(pass *analysis.Pass) (interface{}, error) { } var ( - checkErrorsNewSprintfQ = pattern.MustParse(`(CallExpr (Function "errors.New") [(CallExpr (Function "fmt.Sprintf") args)])`) + checkErrorsNewSprintfQ = pattern.MustParse(`(CallExpr (Symbol "errors.New") [(CallExpr (Symbol "fmt.Sprintf") args)])`) checkErrorsNewSprintfR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "fmt") (Ident "Errorf")) args)`) ) @@ -1923,7 +1898,7 @@ func CheckUnnecessaryGuard(pass *analysis.Pass) (interface{}, error) { } var ( - checkElaborateSleepQ = pattern.MustParse(`(SelectStmt (CommClause (UnaryExpr "<-" (CallExpr (Function "time.After") [arg])) body))`) + checkElaborateSleepQ = pattern.MustParse(`(SelectStmt (CommClause (UnaryExpr "<-" (CallExpr (Symbol "time.After") [arg])) body))`) checkElaborateSleepR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Sleep")) [arg])`) ) @@ -1953,16 +1928,16 @@ var ( (Or (CallExpr fn@(Or - (Function "fmt.Print") - (Function "fmt.Sprint") - (Function "fmt.Println") - (Function "fmt.Sprintln")) - [(CallExpr (Function "fmt.Sprintf") f:_)]) + (Symbol "fmt.Print") + (Symbol "fmt.Sprint") + (Symbol "fmt.Println") + (Symbol "fmt.Sprintln")) + [(CallExpr (Symbol "fmt.Sprintf") f:_)]) (CallExpr fn@(Or - (Function "fmt.Fprint") - (Function "fmt.Fprintln")) - [_ (CallExpr (Function "fmt.Sprintf") f:_)]))`) + (Symbol "fmt.Fprint") + (Symbol "fmt.Fprintln")) + [_ (CallExpr (Symbol "fmt.Sprintf") f:_)]))`) checkTestingErrorSprintfQ = pattern.MustParse(` (CallExpr @@ -1979,11 +1954,11 @@ var ( "Print" "Println" "Skip"))) - [(CallExpr (Function "fmt.Sprintf") args)])`) + [(CallExpr (Symbol "fmt.Sprintf") args)])`) checkLogSprintfQ = pattern.MustParse(` (CallExpr - (Function + (Symbol (Or "log.Fatal" "log.Fatalln" @@ -1991,7 +1966,7 @@ var ( "log.Panicln" "log.Print" "log.Println")) - [(CallExpr (Function "fmt.Sprintf") args)])`) + [(CallExpr (Symbol "fmt.Sprintf") args)])`) checkSprintfMapping = map[string]struct { recv string @@ -2106,8 +2081,8 @@ func CheckPrintSprintf(pass *analysis.Pass) (interface{}, error) { var checkSprintLiteralQ = pattern.MustParse(` (CallExpr fn@(Or - (Function "fmt.Sprint") - (Function "fmt.Sprintf")) + (Symbol "fmt.Sprint") + (Symbol "fmt.Sprintf")) [lit@(BasicLit "STRING" _)])`) func CheckSprintLiteral(pass *analysis.Pass) (interface{}, error) { diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go b/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go index f45dab09..171467a8 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/analysis.go @@ -1,8 +1,11 @@ package staticcheck import ( - "honnef.co/go/tools/analysis/facts" + "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" @@ -12,7 +15,7 @@ import ( ) func makeCallCheckerAnalyzer(rules map[string]CallCheck, extraReqs ...*analysis.Analyzer) *analysis.Analyzer { - reqs := []*analysis.Analyzer{buildir.Analyzer, facts.TokenFile} + reqs := []*analysis.Analyzer{buildir.Analyzer, tokenfile.Analyzer} reqs = append(reqs, extraReqs...) return &analysis.Analyzer{ Run: callChecker(rules), @@ -68,7 +71,7 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ "SA1018": makeCallCheckerAnalyzer(checkStringsReplaceZeroRules), "SA1019": { Run: CheckDeprecated, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Deprecated, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, deprecated.Analyzer, generated.Analyzer}, }, "SA1020": makeCallCheckerAnalyzer(checkListenAddressRules), "SA1021": makeCallCheckerAnalyzer(checkBytesEqualIPRules), @@ -115,7 +118,7 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ "SA4000": { Run: CheckLhsRhsIdentical, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.TokenFile, facts.Generated}, + Requires: []*analysis.Analyzer{inspect.Analyzer, tokenfile.Analyzer, generated.Analyzer}, }, "SA4001": { Run: CheckIneffectiveCopy, @@ -135,7 +138,7 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "SA4006": { Run: CheckUnreadVariableValues, - Requires: []*analysis.Analyzer{buildir.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, }, "SA4008": { Run: CheckLoopCondition, @@ -168,19 +171,19 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ "SA4015": makeCallCheckerAnalyzer(checkMathIntRules), "SA4016": { Run: CheckSillyBitwiseOps, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.TokenFile}, + Requires: []*analysis.Analyzer{inspect.Analyzer, tokenfile.Analyzer}, }, "SA4017": { Run: CheckPureFunctions, - Requires: []*analysis.Analyzer{buildir.Analyzer, facts.Purity}, + Requires: []*analysis.Analyzer{buildir.Analyzer, purity.Analyzer}, }, "SA4018": { Run: CheckSelfAssignment, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated, facts.TokenFile, facts.Purity}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer, purity.Analyzer}, }, "SA4019": { Run: CheckDuplicateBuildConstraints, - Requires: []*analysis.Analyzer{facts.Generated}, + Requires: []*analysis.Analyzer{generated.Analyzer}, }, "SA4020": { Run: CheckUnreachableTypeCases, @@ -188,7 +191,7 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "SA4021": { Run: CheckSingleArgAppend, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated, facts.TokenFile}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer}, }, "SA4022": { Run: CheckAddressIsNil, @@ -228,7 +231,7 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "SA4031": { Run: CheckAllocationNilCheck, - Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer, facts.TokenFile}, + Requires: []*analysis.Analyzer{buildir.Analyzer, inspect.Analyzer, tokenfile.Analyzer}, }, "SA5000": { @@ -266,7 +269,7 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ "SA5009": makeCallCheckerAnalyzer(checkPrintfRules), "SA5010": { Run: CheckImpossibleTypeAssertion, - Requires: []*analysis.Analyzer{buildir.Analyzer, facts.TokenFile}, + Requires: []*analysis.Analyzer{buildir.Analyzer, tokenfile.Analyzer}, }, "SA5011": { Run: CheckMaybeNil, @@ -303,14 +306,14 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "SA9003": { Run: CheckEmptyBranch, - Requires: []*analysis.Analyzer{buildir.Analyzer, facts.TokenFile, facts.Generated}, + 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, facts.Generated), + "SA9005": makeCallCheckerAnalyzer(checkNoopMarshal, generated.Analyzer), "SA9006": { Run: CheckStaticBitShift, Requires: []*analysis.Analyzer{inspect.Analyzer}, @@ -322,6 +325,6 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ "SA9008": { Run: CheckTypeAssertionShadowingElse, - Requires: []*analysis.Analyzer{inspect.Analyzer, buildir.Analyzer, facts.TokenFile}, + Requires: []*analysis.Analyzer{inspect.Analyzer, buildir.Analyzer, tokenfile.Analyzer}, }, }) diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/fakejson/encode.go b/tools/vendor/honnef.co/go/tools/staticcheck/fakejson/encode.go index 6b9ed75f..15e302de 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/fakejson/encode.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/fakejson/encode.go @@ -11,13 +11,14 @@ package fakejson import ( - "go/token" "go/types" "sort" "strings" "unicode" "golang.org/x/exp/typeparams" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/knowledge" "honnef.co/go/tools/staticcheck/fakereflect" ) @@ -31,9 +32,7 @@ func parseTag(tag string) string { } func Marshal(v types.Type) *UnsupportedTypeError { - enc := encoder{ - seen: map[fakereflect.TypeAndCanAddr]struct{}{}, - } + enc := encoder{} return enc.newTypeEncoder(fakereflect.TypeAndCanAddr{Type: v}, "x") } @@ -44,46 +43,35 @@ type UnsupportedTypeError struct { Path string } -var marshalerType = types.NewInterfaceType([]*types.Func{ - types.NewFunc(token.NoPos, nil, "MarshalJSON", types.NewSignature(nil, - types.NewTuple(), - types.NewTuple( - types.NewVar(token.NoPos, nil, "", types.NewSlice(types.Typ[types.Byte])), - types.NewVar(0, nil, "", types.Universe.Lookup("error").Type())), - false, - )), -}, nil).Complete() - -var textMarshalerType = types.NewInterfaceType([]*types.Func{ - types.NewFunc(token.NoPos, nil, "MarshalText", types.NewSignature(nil, - types.NewTuple(), - types.NewTuple( - types.NewVar(token.NoPos, nil, "", types.NewSlice(types.Typ[types.Byte])), - types.NewVar(0, nil, "", types.Universe.Lookup("error").Type())), - false, - )), -}, nil).Complete() - type encoder struct { - seen map[fakereflect.TypeAndCanAddr]struct{} + // TODO we track addressable and non-addressable instances separately out of an abundance of caution. We don't know + // if this is actually required for correctness. + seenCanAddr typeutil.Map + seenCantAddr typeutil.Map } func (enc *encoder) newTypeEncoder(t fakereflect.TypeAndCanAddr, stack string) *UnsupportedTypeError { - if _, ok := enc.seen[t]; ok { + var m *typeutil.Map + if t.CanAddr() { + m = &enc.seenCanAddr + } else { + m = &enc.seenCantAddr + } + if ok := m.At(t.Type); ok != nil { return nil } - enc.seen[t] = struct{}{} + m.Set(t.Type, struct{}{}) - if t.Implements(marshalerType) { + if t.Implements(knowledge.Interfaces["encoding/json.Marshaler"]) { return nil } - if !t.IsPtr() && t.CanAddr() && fakereflect.PtrTo(t).Implements(marshalerType) { + if !t.IsPtr() && t.CanAddr() && fakereflect.PtrTo(t).Implements(knowledge.Interfaces["encoding/json.Marshaler"]) { return nil } - if t.Implements(textMarshalerType) { + if t.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return nil } - if !t.IsPtr() && t.CanAddr() && fakereflect.PtrTo(t).Implements(textMarshalerType) { + if !t.IsPtr() && t.CanAddr() && fakereflect.PtrTo(t).Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return nil } @@ -118,7 +106,7 @@ func (enc *encoder) newMapEncoder(t fakereflect.TypeAndCanAddr, stack string) *U switch t.Key().Type.Underlying().(type) { case *types.Basic: default: - if !t.Key().Implements(textMarshalerType) { + if !t.Key().Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return &UnsupportedTypeError{ Type: t.Type, Path: stack, @@ -133,7 +121,7 @@ func (enc *encoder) newSliceEncoder(t fakereflect.TypeAndCanAddr, stack string) basic, ok := t.Elem().Type.Underlying().(*types.Basic) if ok && basic.Kind() == types.Uint8 { p := fakereflect.PtrTo(t.Elem()) - if !p.Implements(marshalerType) && !p.Implements(textMarshalerType) { + if !p.Implements(knowledge.Interfaces["encoding/json.Marshaler"]) && !p.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return nil } } 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 7b2f97c2..e592bfca 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/marshal.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/fakexml/marshal.go @@ -14,10 +14,10 @@ package fakexml import ( "fmt" - "go/token" "go/types" "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/knowledge" "honnef.co/go/tools/staticcheck/fakereflect" ) @@ -26,13 +26,14 @@ func Marshal(v types.Type) error { } type Encoder struct { - seen map[fakereflect.TypeAndCanAddr]struct{} + // TODO we track addressable and non-addressable instances separately out of an abundance of caution. We don't know + // if this is actually required for correctness. + seenCanAddr typeutil.Map + seenCantAddr typeutil.Map } func NewEncoder() *Encoder { - e := &Encoder{ - seen: map[fakereflect.TypeAndCanAddr]struct{}{}, - } + e := &Encoder{} return e } @@ -101,18 +102,6 @@ func implementsMarshalerAttr(v fakereflect.TypeAndCanAddr) bool { return true } -var textMarshalerType = types.NewInterfaceType([]*types.Func{ - types.NewFunc(token.NoPos, nil, "MarshalText", types.NewSignature(nil, - types.NewTuple(), - types.NewTuple( - types.NewVar(token.NoPos, nil, "", types.NewSlice(types.Typ[types.Byte])), - types.NewVar(0, nil, "", types.Universe.Lookup("error").Type())), - false, - )), -}, nil).Complete() - -var N = 0 - type CyclicTypeError struct { Type types.Type Path string @@ -125,10 +114,16 @@ func (err *CyclicTypeError) Error() string { // marshalValue writes one or more XML elements representing val. // If val was obtained from a struct field, finfo must have its details. func (e *Encoder) marshalValue(val fakereflect.TypeAndCanAddr, finfo *fieldInfo, startTemplate *StartElement, stack string) error { - if _, ok := e.seen[val]; ok { + var m *typeutil.Map + if val.CanAddr() { + m = &e.seenCanAddr + } else { + m = &e.seenCantAddr + } + if ok := m.At(val.Type); ok != nil { return nil } - e.seen[val] = struct{}{} + m.Set(val.Type, struct{}{}) // Drill into interfaces and pointers. seen := map[fakereflect.TypeAndCanAddr]struct{}{} @@ -156,12 +151,12 @@ func (e *Encoder) marshalValue(val fakereflect.TypeAndCanAddr, finfo *fieldInfo, } // Check for text marshaler. - if val.Implements(textMarshalerType) { + if val.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return nil } if val.CanAddr() { pv := fakereflect.PtrTo(val) - if pv.Implements(textMarshalerType) { + if pv.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return nil } } @@ -260,13 +255,13 @@ func (e *Encoder) marshalAttr(start *StartElement, name Name, val fakereflect.Ty } } - if val.Implements(textMarshalerType) { + if val.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return nil } if val.CanAddr() { pv := fakereflect.PtrTo(val) - if pv.Implements(textMarshalerType) { + if pv.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { return nil } } @@ -335,12 +330,12 @@ func (e *Encoder) marshalStruct(tinfo *typeInfo, val fakereflect.TypeAndCanAddr, switch finfo.flags & fMode { case fCDATA, fCharData: - if vf.Implements(textMarshalerType) { + if vf.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { continue } if vf.CanAddr() { pv := fakereflect.PtrTo(vf) - if pv.Implements(textMarshalerType) { + if pv.Implements(knowledge.Interfaces["encoding.TextMarshaler"]) { continue } } diff --git a/tools/vendor/honnef.co/go/tools/staticcheck/lint.go b/tools/vendor/honnef.co/go/tools/staticcheck/lint.go index 2301ba35..3dd0fece 100644 --- a/tools/vendor/honnef.co/go/tools/staticcheck/lint.go +++ b/tools/vendor/honnef.co/go/tools/staticcheck/lint.go @@ -20,8 +20,10 @@ import ( "honnef.co/go/tools/analysis/code" "honnef.co/go/tools/analysis/edit" - "honnef.co/go/tools/analysis/facts" + "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" @@ -500,51 +502,6 @@ func checkPrintfCallImpl(carg *Argument, f ir.Value, args []ir.Value) { return ok && basic.Info()&info != 0 } - isStringer := func(T types.Type, ms *types.MethodSet) bool { - sel := ms.Lookup(nil, "String") - 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() != 0 { - return false - } - if sig.Results().Len() != 1 { - return false - } - if !typeutil.IsType(sig.Results().At(0).Type(), "string") { - return false - } - return true - } - isError := func(T types.Type, ms *types.MethodSet) bool { - sel := ms.Lookup(nil, "Error") - 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() != 0 { - return false - } - if sig.Results().Len() != 1 { - return false - } - if !typeutil.IsType(sig.Results().At(0).Type(), "string") { - return false - } - return true - } - isFormatter := func(T types.Type, ms *types.MethodSet) bool { sel := ms.Lookup(nil, "Format") if sel == nil { @@ -567,18 +524,16 @@ func checkPrintfCallImpl(carg *Argument, f ir.Value, args []ir.Value) { return true } - seen := map[types.Type]bool{} + var seen typeutil.Map var checkType func(verb rune, T types.Type, top bool) bool checkType = func(verb rune, T types.Type, top bool) bool { if top { - for k := range seen { - delete(seen, k) - } + seen = typeutil.Map{} } - if seen[T] { + if ok := seen.At(T); ok != nil { return true } - seen[T] = true + seen.Set(T, struct{}{}) if int(verb) >= len(verbs) { // Unknown verb return true @@ -596,7 +551,7 @@ func checkPrintfCallImpl(carg *Argument, f ir.Value, args []ir.Value) { return true } - if flags&isString != 0 && (isStringer(T, ms) || isError(T, ms)) { + 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 } @@ -652,7 +607,7 @@ func checkPrintfCallImpl(carg *Argument, f ir.Value, args []ir.Value) { return true } } - if isStringer(T, ms) || isError(T, ms) { + if types.Implements(T, knowledge.Interfaces["fmt.Stringer"]) || types.Implements(T, knowledge.Interfaces["error"]) { return true } } @@ -1034,7 +989,8 @@ func CheckTemplate(pass *analysis.Pass) (interface{}, error) { } if err != nil { // TODO(dominikh): whitelist other parse errors, if any - if strings.Contains(err.Error(), "unexpected") { + 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()) } } @@ -1044,7 +1000,7 @@ func CheckTemplate(pass *analysis.Pass) (interface{}, error) { } var ( - checkTimeSleepConstantPatternQ = pattern.MustParse(`(CallExpr (Function "time.Sleep") lit@(IntegerLiteral value))`) + 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")))`) ) @@ -1081,7 +1037,7 @@ var checkWaitgroupAddQ = pattern.MustParse(` (CallExpr (FuncLit _ - call@(CallExpr (Function "(*sync.WaitGroup).Add") _):_) _))`) + call@(CallExpr (Symbol "(*sync.WaitGroup).Add") _):_) _))`) func CheckWaitgroupAdd(pass *analysis.Pass) (interface{}, error) { fn := func(node ast.Node) { @@ -1796,7 +1752,7 @@ func CheckUnreadVariableValues(pass *analysis.Pass) (interface{}, error) { if node == nil { continue } - if gen, ok := code.Generator(pass, node.Pos()); ok && gen == facts.Goyacc { + 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. @@ -2372,7 +2328,7 @@ func CheckIneffectiveLoop(pass *analysis.Pass) (interface{}, error) { return nil, nil } -var checkNilContextQ = pattern.MustParse(`(CallExpr fun@(Function _) (Builtin "nil"):_)`) +var checkNilContextQ = pattern.MustParse(`(CallExpr fun@(Symbol _) (Builtin "nil"):_)`) func CheckNilContext(pass *analysis.Pass) (interface{}, error) { todo := &ast.CallExpr{ @@ -2413,13 +2369,16 @@ func CheckNilContext(pass *analysis.Pass) (interface{}, error) { } var ( - checkSeekerQ = pattern.MustParse(`(CallExpr fun@(SelectorExpr _ (Ident "Seek")) [arg1@(SelectorExpr (Ident "io") (Ident (Or "SeekStart" "SeekCurrent" "SeekEnd"))) arg2])`) + 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 _, edits, ok := code.MatchAndEdit(pass, checkSeekerQ, checkSeekerR, node); ok { + 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...))) } @@ -3051,7 +3010,7 @@ func CheckNonOctalFileMode(pass *analysis.Pass) (interface{}, error) { } func CheckPureFunctions(pass *analysis.Pass) (interface{}, error) { - pure := pass.ResultOf[facts.Purity].(facts.PurityResult) + pure := pass.ResultOf[purity.Analyzer].(purity.Result) fnLoop: for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { @@ -3105,19 +3064,92 @@ fnLoop: } func CheckDeprecated(pass *analysis.Pass) (interface{}, error) { - deprs := pass.ResultOf[facts.Deprecated].(facts.DeprecatedResult) + deprs := pass.ResultOf[deprecated.Analyzer].(deprecated.Result) // Selectors can appear outside of function literals, e.g. when // declaring package level variables. - isStdlib := func(obj types.Object) bool { + 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(obj.Pkg().Path(), ".") + 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 { + switch std.AlternativeAvailableSince { + case knowledge.DeprecatedNeverUse: + // This should never be used, regardless of the + // targeted Go version. Examples include insecure + // cryptography or inherently broken APIs. + // + // We always want to flag these. + case knowledge.DeprecatedUseNoLonger: + // This should no longer be used. Using it with + // older Go versions might still make sense. + if !code.IsGoVersion(pass, std.DeprecatedSince) { + return + } + default: + if std.AlternativeAvailableSince < 0 { + panic(fmt.Sprintf("unhandled case %d", std.AlternativeAvailableSince)) + } + // Look for the first available alternative, not the first + // version something was deprecated in. If a function was + // deprecated in Go 1.6, an alternative has been available + // already in 1.0, and we're targeting 1.2, it still + // makes sense to use the alternative from 1.0, to be + // future-proof. + if !code.IsGoVersion(pass, std.AlternativeAvailableSince) { + 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 @@ -3152,70 +3184,7 @@ func CheckDeprecated(pass *analysis.Pass) (interface{}, error) { } if depr, ok := deprs.Objects[obj]; ok { - // 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[code.SelectorName(pass, sel)] - if !ok && isStdlib(obj) { - // 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 true - } - if ok { - switch std.AlternativeAvailableSince { - case knowledge.DeprecatedNeverUse: - // This should never be used, regardless of the - // targeted Go version. Examples include insecure - // cryptography or inherently broken APIs. - // - // We always want to flag these. - case knowledge.DeprecatedUseNoLonger: - // This should no longer be used. Using it with - // older Go versions might still make sense. - if !code.IsGoVersion(pass, std.DeprecatedSince) { - return true - } - default: - if std.AlternativeAvailableSince < 0 { - panic(fmt.Sprintf("unhandled case %d", std.AlternativeAvailableSince)) - } - // Look for the first available alternative, not the first - // version something was deprecated in. If a function was - // deprecated in Go 1.6, an alternative has been available - // already in 1.0, and we're targeting 1.2, it still - // makes sense to use the alternative from 1.0, to be - // future-proof. - if !code.IsGoVersion(pass, std.AlternativeAvailableSince) { - return true - } - } - } - - if tfn != nil { - if _, ok := deprs.Objects[tfn]; ok { - // functions that are deprecated may use deprecated - // symbols - return true - } - } - - if ok { - if std.AlternativeAvailableSince == knowledge.DeprecatedNeverUse { - report.Report(pass, sel, fmt.Sprintf("%s has been deprecated since Go 1.%d because it shouldn't be used: %s", report.Render(pass, sel), std.DeprecatedSince, depr.Msg)) - } else if std.AlternativeAvailableSince == std.DeprecatedSince || std.AlternativeAvailableSince == knowledge.DeprecatedUseNoLonger { - report.Report(pass, sel, fmt.Sprintf("%s has been deprecated since Go 1.%d: %s", report.Render(pass, sel), std.DeprecatedSince, depr.Msg)) - } else { - report.Report(pass, sel, fmt.Sprintf("%s has been deprecated since Go 1.%d and an alternative has been available since Go 1.%d: %s", report.Render(pass, sel), std.DeprecatedSince, std.AlternativeAvailableSince, depr.Msg)) - } - } else { - report.Report(pass, sel, fmt.Sprintf("%s is deprecated: %s", report.Render(pass, sel), depr.Msg)) - } - return true + handleDeprecation(depr, sel, code.SelectorName(pass, sel), obj.Pkg().Path(), tfn) } return true } @@ -3234,11 +3203,12 @@ func CheckDeprecated(pass *analysis.Pass) (interface{}, error) { 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 == facts.ProtocGenGo { + if ok && gen == generated.ProtocGenGo { return } } - report.Report(pass, spec, fmt.Sprintf("package %s is deprecated: %s", path, depr.Msg)) + + handleDeprecation(depr, spec.Path, path, path, nil) } } pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Nodes(nil, fn) @@ -3501,7 +3471,7 @@ func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { } func CheckSelfAssignment(pass *analysis.Pass) (interface{}, error) { - pure := pass.ResultOf[facts.Purity].(facts.PurityResult) + pure := pass.ResultOf[purity.Analyzer].(purity.Result) fn := func(node ast.Node) { assign := node.(*ast.AssignStmt) @@ -3740,7 +3710,7 @@ func CheckTimerResetReturnValue(pass *analysis.Pass) (interface{}, error) { var ( checkToLowerToUpperComparisonQ = pattern.MustParse(` (BinaryExpr - (CallExpr fun@(Function (Or "strings.ToLower" "strings.ToUpper")) [a]) + (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])`) @@ -3922,22 +3892,23 @@ func checkJSONTag(pass *analysis.Pass, field *ast.Field, tag string) { //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])) } } - var co, cs, ci int + options := make(map[string]int) for _, s := range fields[1:] { switch s { - case "omitempty": - co++ case "": // allow stuff like "-," case "string": - cs++ // 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 @@ -3954,20 +3925,23 @@ func checkJSONTag(pass *analysis.Pass, field *ast.Field, tag string) { } } } - case "inline": - ci++ + case "omitzero", "omitempty", "nocase", "inline", "unknown": + options[s]++ default: report.Report(pass, field.Tag, fmt.Sprintf("unknown JSON option %q", s)) } } - if co > 1 { - report.Report(pass, field.Tag, `duplicate JSON option "omitempty"`) - } - if cs > 1 { - report.Report(pass, field.Tag, `duplicate JSON option "string"`) + var duplicates []string + for option, n := range options { + if n > 1 { + duplicates = append(duplicates, option) + } } - if ci > 1 { - report.Report(pass, field.Tag, `duplicate JSON option "inline"`) + if len(duplicates) > 0 { + sort.Strings(duplicates) + for _, option := range duplicates { + report.Report(pass, field.Tag, fmt.Sprintf("duplicate JSON option %q", option)) + } } } @@ -4965,6 +4939,10 @@ func CheckTypeAssertionShadowingElse(pass *analysis.Pass) (interface{}, error) { 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 { @@ -5017,7 +4995,7 @@ func CheckTypeAssertionShadowingElse(pass *analysis.Pass) (interface{}, error) { return nil, nil } -var ineffectiveSortQ = pattern.MustParse(`(AssignStmt target@(Ident _) "=" (CallExpr typ@(Function (Or "sort.Float64Slice" "sort.IntSlice" "sort.StringSlice")) [target]))`) +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) { @@ -5066,7 +5044,7 @@ func CheckIneffectiveSort(pass *analysis.Pass) (interface{}, error) { var ineffectiveRandIntQ = pattern.MustParse(` (CallExpr - (Function + (Symbol name@(Or "math/rand.Int31n" "math/rand.Int63n" @@ -5096,7 +5074,9 @@ var allocationNilCheckQ = pattern.MustParse(`(IfStmt _ cond@(BinaryExpr lhs op@( func CheckAllocationNilCheck(pass *analysis.Pass) (interface{}, error) { irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg - fn := func(node ast.Node) { + + var path []ast.Node + fn := func(node ast.Node, stack []ast.Node) { m, ok := code.Match(pass, allocationNilCheckQ, node) if !ok { return @@ -5107,12 +5087,15 @@ func CheckAllocationNilCheck(pass *analysis.Pass) (interface{}, error) { return } lhs := m.State["lhs"].(ast.Expr) - path, exact := astutil.PathEnclosingInterval(code.File(pass, lhs), lhs.Pos(), lhs.Pos()) - if !exact { - // TODO(dh): when can this happen? - return + 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 @@ -5208,8 +5191,7 @@ func CheckAllocationNilCheck(pass *analysis.Pass) (interface{}, error) { report.Report(pass, cond, fallback) } } - } - code.Preorder(pass, fn, (*ast.IfStmt)(nil)) + code.PreorderStack(pass, fn, (*ast.IfStmt)(nil)) 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 32a888ae..d560d972 100644 --- a/tools/vendor/honnef.co/go/tools/stylecheck/analysis.go +++ b/tools/vendor/honnef.co/go/tools/stylecheck/analysis.go @@ -1,7 +1,8 @@ package stylecheck import ( - "honnef.co/go/tools/analysis/facts" + "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" @@ -17,11 +18,11 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "ST1001": { Run: CheckDotImports, - Requires: []*analysis.Analyzer{facts.Generated, config.Analyzer}, + Requires: []*analysis.Analyzer{generated.Analyzer, config.Analyzer}, }, "ST1003": { Run: CheckNames, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated, config.Analyzer}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, config.Analyzer}, }, "ST1005": { Run: CheckErrorStrings, @@ -29,7 +30,7 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "ST1006": { Run: CheckReceiverNames, - Requires: []*analysis.Analyzer{buildir.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, }, "ST1008": { Run: CheckErrorReturn, @@ -44,20 +45,20 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "ST1013": { Run: CheckHTTPStatusCodes, - // TODO(dh): why does this depend on facts.TokenFile? - Requires: []*analysis.Analyzer{facts.Generated, facts.TokenFile, config.Analyzer, inspect.Analyzer}, + // 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, facts.Generated, facts.TokenFile}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer}, }, "ST1016": { Run: CheckReceiverNamesIdentical, - Requires: []*analysis.Analyzer{buildir.Analyzer, facts.Generated}, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer}, }, "ST1017": { Run: CheckYodaConditions, - Requires: []*analysis.Analyzer{inspect.Analyzer, facts.Generated, facts.TokenFile}, + Requires: []*analysis.Analyzer{inspect.Analyzer, generated.Analyzer, tokenfile.Analyzer}, }, "ST1018": { Run: CheckInvisibleCharacters, @@ -65,19 +66,19 @@ var Analyzers = lint.InitializeAnalyzers(Docs, map[string]*analysis.Analyzer{ }, "ST1019": { Run: CheckDuplicatedImports, - Requires: []*analysis.Analyzer{facts.Generated}, + Requires: []*analysis.Analyzer{generated.Analyzer}, }, "ST1020": { Run: CheckExportedFunctionDocs, - Requires: []*analysis.Analyzer{facts.Generated, inspect.Analyzer}, + Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, }, "ST1021": { Run: CheckExportedTypeDocs, - Requires: []*analysis.Analyzer{facts.Generated, inspect.Analyzer}, + Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, }, "ST1022": { Run: CheckExportedVarDocs, - Requires: []*analysis.Analyzer{facts.Generated, inspect.Analyzer}, + Requires: []*analysis.Analyzer{generated.Analyzer, inspect.Analyzer}, }, "ST1023": sharedcheck.RedundantTypeInDeclarationChecker("should", false), }) diff --git a/tools/vendor/honnef.co/go/tools/stylecheck/lint.go b/tools/vendor/honnef.co/go/tools/stylecheck/lint.go index c80dd37b..4203c610 100644 --- a/tools/vendor/honnef.co/go/tools/stylecheck/lint.go +++ b/tools/vendor/honnef.co/go/tools/stylecheck/lint.go @@ -649,15 +649,48 @@ func CheckHTTPStatusCodes(pass *analysis.Pass) (interface{}, error) { } 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 && i != 0 && i != len(list)-1 { - report.Report(pass, c, "default case should be first or last in switch statement", report.FilterGenerated()) + 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/unused/unused.go b/tools/vendor/honnef.co/go/tools/unused/unused.go index 3d69dbb6..f703ed3d 100644 --- a/tools/vendor/honnef.co/go/tools/unused/unused.go +++ b/tools/vendor/honnef.co/go/tools/unused/unused.go @@ -13,7 +13,8 @@ import ( "strings" "honnef.co/go/tools/analysis/code" - "honnef.co/go/tools/analysis/facts" + "honnef.co/go/tools/analysis/facts/directives" + "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" @@ -432,7 +433,7 @@ var Analyzer = &lint.Analyzer{ Name: "U1000", Doc: "Unused code", Run: run, - Requires: []*analysis.Analyzer{buildir.Analyzer, facts.Generated, facts.Directives}, + Requires: []*analysis.Analyzer{buildir.Analyzer, generated.Analyzer, directives.Analyzer}, ResultType: reflect.TypeOf(Result{}), }, } @@ -520,7 +521,7 @@ func debugf(f string, v ...interface{}) { func run(pass *analysis.Pass) (interface{}, error) { irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR) - dirs := pass.ResultOf[facts.Directives].([]lint.Directive) + dirs := pass.ResultOf[directives.Analyzer].([]lint.Directive) pkg := &pkg{ Fset: pass.Fset, Files: pass.Files, diff --git a/tools/vendor/modules.txt b/tools/vendor/modules.txt index 400ca562..fa68c55d 100644 --- a/tools/vendor/modules.txt +++ b/tools/vendor/modules.txt @@ -31,7 +31,7 @@ code.gitea.io/sdk/gitea # github.com/AlekSi/pointer v1.2.0 ## explicit; go 1.18 github.com/AlekSi/pointer -# github.com/Antonboom/errname v0.1.6 +# github.com/Antonboom/errname v0.1.7 ## explicit; go 1.18 github.com/Antonboom/errname/pkg/analyzer # github.com/Antonboom/nilnil v0.1.1 @@ -78,15 +78,15 @@ github.com/Azure/go-autorest/logger # github.com/Azure/go-autorest/tracing v0.6.0 ## explicit; go 1.12 github.com/Azure/go-autorest/tracing -# github.com/BurntSushi/toml v1.1.0 +# github.com/BurntSushi/toml v1.2.0 ## explicit; go 1.16 github.com/BurntSushi/toml github.com/BurntSushi/toml/internal # github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 ## explicit; go 1.13 github.com/Djarvur/go-err113 -# github.com/GaijinEntertainment/go-exhaustruct/v2 v2.1.0 -## explicit; go 1.18 +# github.com/GaijinEntertainment/go-exhaustruct/v2 v2.3.0 +## explicit; go 1.19 github.com/GaijinEntertainment/go-exhaustruct/v2/pkg/analyzer # github.com/Masterminds/goutils v1.1.1 ## explicit @@ -132,6 +132,9 @@ github.com/acomagu/bufpipe # github.com/alexkohler/prealloc v1.0.0 ## explicit; go 1.15 github.com/alexkohler/prealloc/pkg +# github.com/alingse/asasalint v0.0.11 +## explicit; go 1.18 +github.com/alingse/asasalint # github.com/ashanbrown/forbidigo v1.3.0 ## explicit; go 1.12 github.com/ashanbrown/forbidigo/forbidigo @@ -371,22 +374,27 @@ github.com/charithe/durationcheck # github.com/charmbracelet/lipgloss v0.5.1-0.20220615005615-2e17a8a06096 ## explicit; go 1.15 github.com/charmbracelet/lipgloss -# github.com/chavacava/garif v0.0.0-20220316182200-5cad0b5181d4 +# github.com/chavacava/garif v0.0.0-20220630083739-93517212f375 ## explicit; go 1.16 github.com/chavacava/garif # github.com/cpuguy83/go-md2man/v2 v2.0.2 ## explicit; go 1.11 github.com/cpuguy83/go-md2man/v2/md2man -# github.com/daixiang0/gci v0.3.3 -## explicit; go 1.17 -github.com/daixiang0/gci/pkg/analyzer -github.com/daixiang0/gci/pkg/configuration -github.com/daixiang0/gci/pkg/constants +# github.com/curioswitch/go-reassign v0.1.2 +## explicit; go 1.18 +github.com/curioswitch/go-reassign +github.com/curioswitch/go-reassign/internal/analyzer +# github.com/daixiang0/gci v0.6.3 +## explicit; go 1.18 +github.com/daixiang0/gci/pkg/config +github.com/daixiang0/gci/pkg/format github.com/daixiang0/gci/pkg/gci -github.com/daixiang0/gci/pkg/gci/imports -github.com/daixiang0/gci/pkg/gci/sections -github.com/daixiang0/gci/pkg/gci/specificity github.com/daixiang0/gci/pkg/io +github.com/daixiang0/gci/pkg/log +github.com/daixiang0/gci/pkg/parse +github.com/daixiang0/gci/pkg/section +github.com/daixiang0/gci/pkg/specificity +github.com/daixiang0/gci/pkg/utils # github.com/davecgh/go-spew v1.1.1 ## explicit github.com/davecgh/go-spew/spew @@ -440,16 +448,16 @@ 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.1 +# github.com/firefart/nonamedreturns v1.0.4 ## explicit; go 1.18 github.com/firefart/nonamedreturns/analyzer # github.com/fsnotify/fsnotify v1.5.4 ## explicit; go 1.16 github.com/fsnotify/fsnotify -# github.com/fzipp/gocyclo v0.5.1 +# github.com/fzipp/gocyclo v0.6.0 ## explicit; go 1.18 github.com/fzipp/gocyclo -# github.com/go-critic/go-critic v0.6.3 +# github.com/go-critic/go-critic v0.6.4 ## explicit; go 1.16 github.com/go-critic/go-critic/checkers github.com/go-critic/go-critic/checkers/internal/astwalk @@ -520,11 +528,11 @@ github.com/go-telegram-bot-api/telegram-bot-api # github.com/go-toolsmith/astcast v1.0.0 ## explicit github.com/go-toolsmith/astcast -# github.com/go-toolsmith/astcopy v1.0.0 -## explicit +# github.com/go-toolsmith/astcopy v1.0.1 +## explicit; go 1.16 github.com/go-toolsmith/astcopy -# github.com/go-toolsmith/astequal v1.0.1 -## explicit +# github.com/go-toolsmith/astequal v1.0.2 +## explicit; go 1.16 github.com/go-toolsmith/astequal # github.com/go-toolsmith/astfmt v1.0.0 ## explicit @@ -587,8 +595,8 @@ github.com/golangci/go-misc/deadcode ## explicit github.com/golangci/gofmt/gofmt github.com/golangci/gofmt/goimports -# github.com/golangci/golangci-lint v1.46.2 -## explicit; go 1.18 +# github.com/golangci/golangci-lint v1.49.0 +## explicit; go 1.19 github.com/golangci/golangci-lint/cmd/golangci-lint github.com/golangci/golangci-lint/internal/cache github.com/golangci/golangci-lint/internal/errorutil @@ -624,8 +632,8 @@ github.com/golangci/maligned # github.com/golangci/misspell v0.3.5 ## explicit github.com/golangci/misspell -# github.com/golangci/revgrep v0.0.0-20210930125155-c22e5001d4f2 -## explicit; go 1.13 +# github.com/golangci/revgrep v0.0.0-20220804021717-745bb2f7c2e6 +## explicit; go 1.17 github.com/golangci/revgrep # github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 ## explicit @@ -799,7 +807,7 @@ github.com/hashicorp/go-multierror # github.com/hashicorp/go-retryablehttp v0.7.1 ## explicit; go 1.13 github.com/hashicorp/go-retryablehttp -# github.com/hashicorp/go-version v1.4.0 +# github.com/hashicorp/go-version v1.6.0 ## explicit github.com/hashicorp/go-version # github.com/hashicorp/hcl v1.0.0 @@ -858,7 +866,7 @@ github.com/julz/importas # github.com/kevinburke/ssh_config v1.1.0 ## explicit github.com/kevinburke/ssh_config -# github.com/kisielk/errcheck v1.6.0 +# github.com/kisielk/errcheck v1.6.2 ## explicit; go 1.14 github.com/kisielk/errcheck/errcheck # github.com/kisielk/gotool v1.0.0 @@ -877,11 +885,11 @@ github.com/klauspost/compress/zstd/internal/xxhash # github.com/klauspost/pgzip v1.2.5 ## explicit github.com/klauspost/pgzip -# github.com/kulti/thelper v0.6.2 +# github.com/kulti/thelper v0.6.3 ## explicit; go 1.18 github.com/kulti/thelper/pkg/analyzer -# github.com/kunwardeep/paralleltest v1.0.3 -## explicit; go 1.14 +# github.com/kunwardeep/paralleltest v1.0.6 +## explicit; go 1.17 github.com/kunwardeep/paralleltest/pkg/paralleltest # github.com/kyoh86/exportloopref v0.1.8 ## explicit; go 1.14 @@ -909,8 +917,8 @@ github.com/lufeee/execinquery # github.com/magiconair/properties v1.8.6 ## explicit; go 1.13 github.com/magiconair/properties -# github.com/maratori/testpackage v1.0.1 -## explicit; go 1.12 +# github.com/maratori/testpackage v1.1.0 +## explicit; go 1.18 github.com/maratori/testpackage/pkg/testpackage # github.com/matm/gocov-html v0.0.0-20200509184451-71874e2e203b ## explicit; go 1.12 @@ -919,14 +927,14 @@ github.com/matm/gocov-html/cov # github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 ## explicit; go 1.13 github.com/matoous/godox -# github.com/mattn/go-colorable v0.1.12 -## explicit; go 1.13 +# github.com/mattn/go-colorable v0.1.13 +## explicit; go 1.15 github.com/mattn/go-colorable # github.com/mattn/go-ieproxy v0.0.1 ## explicit; go 1.14 github.com/mattn/go-ieproxy -# github.com/mattn/go-isatty v0.0.14 -## explicit; go 1.12 +# github.com/mattn/go-isatty v0.0.16 +## explicit; go 1.15 github.com/mattn/go-isatty # github.com/mattn/go-runewidth v0.0.13 ## explicit; go 1.9 @@ -940,10 +948,11 @@ 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.2.1 -## explicit; go 1.12 +# github.com/mgechev/revive v1.2.3 +## explicit; go 1.19 github.com/mgechev/revive/config github.com/mgechev/revive/formatter +github.com/mgechev/revive/internal/typeparams github.com/mgechev/revive/lint github.com/mgechev/revive/rule # github.com/mitchellh/copystructure v1.2.0 @@ -998,7 +1007,7 @@ github.com/nbutton23/zxcvbn-go/match github.com/nbutton23/zxcvbn-go/matching github.com/nbutton23/zxcvbn-go/scoring github.com/nbutton23/zxcvbn-go/utils/math -# github.com/nishanths/exhaustive v0.7.11 +# github.com/nishanths/exhaustive v0.8.1 ## explicit; go 1.14 github.com/nishanths/exhaustive # github.com/nishanths/predeclared v0.2.2 @@ -1017,7 +1026,7 @@ 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.1 +# github.com/pelletier/go-toml/v2 v2.0.2 ## explicit; go 1.16 github.com/pelletier/go-toml/v2 github.com/pelletier/go-toml/v2/internal/ast @@ -1032,7 +1041,7 @@ github.com/pkg/errors # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib -# github.com/polyfloyd/go-errorlint v1.0.0 +# github.com/polyfloyd/go-errorlint v1.0.2 ## explicit; go 1.13 github.com/polyfloyd/go-errorlint/errorlint # github.com/prometheus/client_golang v1.12.1 @@ -1053,7 +1062,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.3.16-0.20220213074421-6aa060fab41a +# github.com/quasilyte/go-ruleguard v0.3.17 ## explicit; go 1.17 github.com/quasilyte/go-ruleguard/internal/goenv github.com/quasilyte/go-ruleguard/internal/golist @@ -1065,6 +1074,9 @@ github.com/quasilyte/go-ruleguard/ruleguard/ir github.com/quasilyte/go-ruleguard/ruleguard/irconv github.com/quasilyte/go-ruleguard/ruleguard/profiling github.com/quasilyte/go-ruleguard/ruleguard/quasigo +github.com/quasilyte/go-ruleguard/ruleguard/quasigo/stdlib/qfmt +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/gogrep v0.0.0-20220120141003-628d8b3623b5 @@ -1084,7 +1096,7 @@ github.com/rivo/uniseg # github.com/russross/blackfriday/v2 v2.1.0 ## explicit github.com/russross/blackfriday/v2 -# github.com/ryancurrah/gomodguard v1.2.3 +# github.com/ryancurrah/gomodguard v1.2.4 ## explicit; go 1.16 github.com/ryancurrah/gomodguard # github.com/ryanrolds/sqlclosecheck v0.3.0 @@ -1096,8 +1108,15 @@ github.com/sanposhiho/wastedassign/v2 # github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b ## explicit; go 1.16 github.com/sasha-s/go-csync -# github.com/securego/gosec/v2 v2.11.0 -## explicit; go 1.16 +# github.com/sashamelentyev/interfacebloat v1.1.0 +## explicit; go 1.18 +github.com/sashamelentyev/interfacebloat/pkg/analyzer +# github.com/sashamelentyev/usestdlibvars v1.13.0 +## explicit; go 1.19 +github.com/sashamelentyev/usestdlibvars/pkg/analyzer +github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping +# github.com/securego/gosec/v2 v2.13.1 +## explicit; go 1.19 github.com/securego/gosec/v2 github.com/securego/gosec/v2/cwe github.com/securego/gosec/v2/rules @@ -1107,13 +1126,16 @@ github.com/sergi/go-diff/diffmatchpatch # github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c ## explicit github.com/shazow/go-diff/difflib -# github.com/sirupsen/logrus v1.8.1 +# github.com/sirupsen/logrus v1.9.0 ## explicit; go 1.13 github.com/sirupsen/logrus # github.com/sivchari/containedctx v1.0.2 ## explicit; go 1.17 github.com/sivchari/containedctx -# github.com/sivchari/tenv v1.5.0 +# github.com/sivchari/nosnakecase v1.7.0 +## explicit; go 1.18 +github.com/sivchari/nosnakecase +# github.com/sivchari/tenv v1.7.0 ## explicit; go 1.18 github.com/sivchari/tenv # github.com/slack-go/slack v0.11.2 @@ -1172,10 +1194,10 @@ github.com/stretchr/objx ## explicit; go 1.13 github.com/stretchr/testify/assert github.com/stretchr/testify/mock -# github.com/subosito/gotenv v1.3.0 +# github.com/subosito/gotenv v1.4.0 ## explicit; go 1.18 github.com/subosito/gotenv -# github.com/sylvia7788/contextcheck v1.0.4 +# github.com/sylvia7788/contextcheck v1.0.6 ## explicit; go 1.15 github.com/sylvia7788/contextcheck # github.com/tdakkota/asciicheck v0.1.1 @@ -1190,8 +1212,11 @@ github.com/tetafro/godot # github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144 ## explicit; go 1.12 github.com/timakin/bodyclose/passes/bodyclose -# github.com/tomarrell/wrapcheck/v2 v2.6.1 +# github.com/timonwong/logrlint v0.1.0 ## explicit; go 1.16 +github.com/timonwong/logrlint +# github.com/tomarrell/wrapcheck/v2 v2.6.2 +## explicit; go 1.18 github.com/tomarrell/wrapcheck/v2/wrapcheck # github.com/tommy-muehle/go-mnd/v2 v2.5.0 ## explicit; go 1.12 @@ -1210,7 +1235,7 @@ github.com/ultraware/funlen # github.com/ultraware/whitespace v0.0.5 ## explicit github.com/ultraware/whitespace -# github.com/uudashr/gocognit v1.0.5 +# github.com/uudashr/gocognit v1.0.6 ## explicit; go 1.16 github.com/uudashr/gocognit # github.com/withfig/autocomplete-tools/integrations/cobra v1.2.1 @@ -1230,7 +1255,7 @@ github.com/yagipy/maintidx/pkg/halstvol # github.com/yeya24/promlinter v0.2.0 ## explicit; go 1.16 github.com/yeya24/promlinter -# gitlab.com/bosi/decorder v0.2.1 +# gitlab.com/bosi/decorder v0.2.3 ## explicit; go 1.17 gitlab.com/bosi/decorder # gitlab.com/digitalxero/go-conventional-commit v1.0.7 @@ -1255,6 +1280,20 @@ go.opencensus.io/trace go.opencensus.io/trace/internal go.opencensus.io/trace/propagation go.opencensus.io/trace/tracestate +# go.uber.org/atomic v1.9.0 +## explicit; go 1.13 +go.uber.org/atomic +# go.uber.org/multierr v1.8.0 +## explicit; go 1.14 +go.uber.org/multierr +# go.uber.org/zap v1.21.0 +## explicit; go 1.13 +go.uber.org/zap +go.uber.org/zap/buffer +go.uber.org/zap/internal/bufferpool +go.uber.org/zap/internal/color +go.uber.org/zap/internal/exit +go.uber.org/zap/zapcore # gocloud.dev v0.26.0 ## explicit; go 1.12 gocloud.dev/aws @@ -1276,7 +1315,7 @@ gocloud.dev/secrets/awskms gocloud.dev/secrets/azurekeyvault gocloud.dev/secrets/driver gocloud.dev/secrets/gcpkms -# golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 +# golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa ## explicit; go 1.17 golang.org/x/crypto/blowfish golang.org/x/crypto/cast5 @@ -1300,10 +1339,14 @@ golang.org/x/crypto/ssh golang.org/x/crypto/ssh/agent golang.org/x/crypto/ssh/internal/bcrypt_pbkdf golang.org/x/crypto/ssh/knownhosts -# golang.org/x/exp/typeparams v0.0.0-20220218215828-6cf2b201936e +# golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e +## explicit; go 1.18 +golang.org/x/exp/constraints +golang.org/x/exp/slices +# golang.org/x/exp/typeparams v0.0.0-20220613132600-b0d781184e0d ## explicit; go 1.18 golang.org/x/exp/typeparams -# golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 +# golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 ## explicit; go 1.17 golang.org/x/mod/internal/lazyregexp golang.org/x/mod/modfile @@ -1331,10 +1374,10 @@ golang.org/x/oauth2/google/internal/externalaccount golang.org/x/oauth2/internal golang.org/x/oauth2/jws golang.org/x/oauth2/jwt -# golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f +# golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 ## explicit golang.org/x/sync/errgroup -# golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 +# golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab ## explicit; go 1.17 golang.org/x/sys/cpu golang.org/x/sys/execabs @@ -1356,8 +1399,8 @@ golang.org/x/text/width # golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 ## explicit golang.org/x/time/rate -# golang.org/x/tools v0.1.11-0.20220316014157-77aa08bb151a -## explicit; go 1.17 +# golang.org/x/tools v0.1.12 +## explicit; go 1.18 golang.org/x/tools/cmd/cover golang.org/x/tools/cmd/goimports golang.org/x/tools/cmd/stringer @@ -1412,6 +1455,7 @@ golang.org/x/tools/go/gcexportdata golang.org/x/tools/go/internal/cgo golang.org/x/tools/go/internal/gcimporter golang.org/x/tools/go/internal/packagesdriver +golang.org/x/tools/go/internal/pkgbits golang.org/x/tools/go/loader golang.org/x/tools/go/packages golang.org/x/tools/go/ssa @@ -1428,7 +1472,6 @@ golang.org/x/tools/internal/fastwalk golang.org/x/tools/internal/gocommand golang.org/x/tools/internal/gopathwalk golang.org/x/tools/internal/imports -golang.org/x/tools/internal/lsp/fuzzy golang.org/x/tools/internal/packagesinternal golang.org/x/tools/internal/typeparams golang.org/x/tools/internal/typesinternal @@ -1588,7 +1631,7 @@ google.golang.org/protobuf/types/known/wrapperspb # gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc ## explicit gopkg.in/alexcesaro/quotedprintable.v3 -# gopkg.in/ini.v1 v1.66.4 +# gopkg.in/ini.v1 v1.66.6 ## explicit gopkg.in/ini.v1 # gopkg.in/mail.v2 v2.3.1 @@ -1615,12 +1658,16 @@ gotest.tools/gotestsum/internal/filewatcher gotest.tools/gotestsum/internal/junitxml gotest.tools/gotestsum/log gotest.tools/gotestsum/testjson -# honnef.co/go/tools v0.3.1 +# honnef.co/go/tools v0.3.3 ## explicit; go 1.17 honnef.co/go/tools/analysis/code honnef.co/go/tools/analysis/edit -honnef.co/go/tools/analysis/facts +honnef.co/go/tools/analysis/facts/deprecated +honnef.co/go/tools/analysis/facts/directives +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/analysis/report @@ -1651,6 +1698,6 @@ mvdan.cc/interfacer/check # mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b ## explicit mvdan.cc/lint -# mvdan.cc/unparam v0.0.0-20211214103731-d0ef000c54e5 -## explicit; go 1.16 +# mvdan.cc/unparam v0.0.0-20220706161116-678bad134442 +## explicit; go 1.17 mvdan.cc/unparam/check diff --git a/tools/vendor/mvdan.cc/unparam/check/check.go b/tools/vendor/mvdan.cc/unparam/check/check.go index b738c273..dcc54106 100644 --- a/tools/vendor/mvdan.cc/unparam/check/check.go +++ b/tools/vendor/mvdan.cc/unparam/check/check.go @@ -21,6 +21,7 @@ import ( "sort" "strings" + "golang.org/x/exp/typeparams" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/ssa" "golang.org/x/tools/go/ssa/ssautil" @@ -44,7 +45,7 @@ func UnusedParams(tests, exported, debug bool, args ...string) ([]string, error) return c.lines(args...) } -// Checker finds unused parameterss in a program. You probably want to use +// Checker finds unused parameters in a program. You probably want to use // UnusedParams instead, unless you want to use a *loader.Program and // *ssa.Program directly. type Checker struct { @@ -877,8 +878,23 @@ func recvPrefix(recv *ast.FieldList) string { } expr = star.X } - id := expr.(*ast.Ident) - return id.Name + "." + switch expr := expr.(type) { + case *ast.Ident: + return expr.Name + "." + default: + x, _, _, _ := typeparams.UnpackIndexExpr(expr) + if x == nil { + panic(fmt.Sprintf("unexepected receiver AST node: %T", expr)) + } + return x.(*ast.Ident).Name + "." + // TODO: remove the use of x/exp/typeparams once we drop Go 1.17 + // case *ast.IndexExpr: + // return expr.X.(*ast.Ident).Name + "." + // case *ast.IndexListExpr: + // return expr.X.(*ast.Ident).Name + "." + // default: + // panic(fmt.Sprintf("unexepected receiver AST node: %T", expr)) + } } // multipleImpls reports whether a function has multiple implementations in the