prysm-pulse/tools/analyzers/uintcast/testdata/data.go
Preston Van Loon c1197d7881
Add static analysis for unsafe uint casting (#10318)
* Add static analysis for unsafe uint casting

* Fix violations of uintcast

* go mod tidy

* Add exclusion to nogo for darwin build

* Add test for math.Int

* Move some things to const so they are assured not to exceed int64

* Self review

* lint

* fix tests

* fix test

* Add init check for non 64 bit OS

* Move new deps from WORKSPACE to deps.bzl

* fix bazel build for go analysis runs

* Update BUILD.bazel

Remove TODO

* add math.AddInt method

* Add new test casts

* Add case where builtin functions and declared functions are covered

* Fix new findings

* cleanup

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Nishant Das <nishdas93@gmail.com>
2022-03-11 09:34:30 +00:00

88 lines
1.7 KiB
Go

package testdata
import (
"math"
"time"
)
// Uint64CastToInt --
func Uint64CastToInt() {
a := uint64(math.MaxUint64)
b := int(a) // want "Unsafe cast from uint64 to int."
_ = b
}
// Uint64CastToIntIfStatement --
func Uint64CastToIntIfStatement() {
var b []string
a := uint64(math.MaxUint64)
if len(b) < int(a) { // want "Unsafe cast from uint64 to int."
return
}
}
type Slot = uint64
// BaseTypes should alert on alias like Slot.
func BaseTypes() {
var slot Slot
bad := int(slot) // want "Unsafe cast from uint64 to int."
_ = bad
}
func Uint64CastInStruct() {
type S struct {
a int
}
s := S{
a: int(uint64(5)), // want "Unsafe cast from uint64 to int."
}
_ = s
}
func Uint64CastFunctionReturn() {
fn := func() uint64 {
return 5
}
a := int(fn()) // want "Unsafe cast from uint64 to int."
_ = a
}
// IgnoredResult should not report an error.
func IgnoredResult() {
a := uint64(math.MaxUint64)
b := int(a) // lint:ignore uintcast -- test code
_ = b
}
// IgnoredIfStatement should not report an error.
func IgnoredIfStatement() {
var balances []int
var numDeposits uint64
var i int
var balance int
// lint:ignore uintcast -- test code
if len(balances) == int(numDeposits) {
balance = balances[i]
}
_ = balance
}
func IgnoreInFunctionCall() bool {
var timestamp uint64
var timeout time.Time
return time.Unix(int64(timestamp), 0).Before(timeout) // lint:ignore uintcast -- test code
}
func IgnoreWithOtherComments() bool {
var timestamp uint64
var timeout time.Time
// I plan to live forever. Maybe we should not do this?
return time.Unix(int64(timestamp), 0).Before(timeout) // lint:ignore uintcast -- timestamp will not exceed int64 in your lifetime.
}