text
stringlengths 2
1.1M
| id
stringlengths 11
117
| metadata
dict | __index_level_0__
int64 0
885
|
---|---|---|---|
// compile
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package p
type NodeLink struct{}
// A role our end of NodeLink is intended to play
type LinkRole int64
const (
LinkServer LinkRole = iota // link created as server
LinkClient // link created as client
// for testing:
linkNoRecvSend LinkRole = 1 << 16 // do not spawn serveRecv & serveSend
linkFlagsMask LinkRole = (1<<32 - 1) << 16
)
func NewNodeLink(role LinkRole) *NodeLink {
var nextConnId uint32
switch role &^ linkFlagsMask {
case LinkServer:
nextConnId = 0 // all initiated by us connId will be even
case LinkClient:
nextConnId = 1 // ----//---- odd
default:
panic("invalid conn role")
}
_ = nextConnId
return nil
}
|
go/test/fixedbugs/issue19555.go/0
|
{
"file_path": "go/test/fixedbugs/issue19555.go",
"repo_id": "go",
"token_count": 274
}
| 504 |
// rundir
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The compiler was using an incomplete symbol name for reflect name data,
// permitting an invalid merge in the linker, producing an incorrect
// exported flag bit.
package ignored
|
go/test/fixedbugs/issue21120.go/0
|
{
"file_path": "go/test/fixedbugs/issue21120.go",
"repo_id": "go",
"token_count": 86
}
| 505 |
// run
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 21887: println(^uint(0)) fails to compile
package main
import "strconv"
func main() {
if strconv.IntSize == 32 {
println(^uint(0))
} else {
println(^uint32(0))
}
if strconv.IntSize == 64 {
println(^uint(0))
} else {
println(^uint64(0))
}
}
|
go/test/fixedbugs/issue21887.go/0
|
{
"file_path": "go/test/fixedbugs/issue21887.go",
"repo_id": "go",
"token_count": 160
}
| 506 |
// compile
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Using a multi-result function as an argument to
// append should compile successfully. Previously there
// was a missing *int -> interface{} conversion that caused
// the compiler to ICE.
package p
func f() ([]interface{}, *int) {
return nil, nil
}
var _ = append(f())
|
go/test/fixedbugs/issue22327.go/0
|
{
"file_path": "go/test/fixedbugs/issue22327.go",
"repo_id": "go",
"token_count": 122
}
| 507 |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type S struct{ i int }
type SS = S
func sub()
func main() {
sub()
}
|
go/test/fixedbugs/issue22877.dir/p.go/0
|
{
"file_path": "go/test/fixedbugs/issue22877.dir/p.go",
"repo_id": "go",
"token_count": 75
}
| 508 |
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 23546: type..eq function not generated when
// DWARF is disabled.
package main
func main() {
use(f() == f())
}
func f() [2]interface{} {
var out [2]interface{}
return out
}
//go:noinline
func use(bool) {}
|
go/test/fixedbugs/issue23546.go/0
|
{
"file_path": "go/test/fixedbugs/issue23546.go",
"repo_id": "go",
"token_count": 129
}
| 509 |
// compile
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// A couple of aliases cases that gccgo incorrectly gave errors for.
package p
func F1() {
type E = struct{}
type X struct{}
var x X
var y E = x
_ = y
}
func F2() {
type E = struct{}
type S []E
type T []struct{}
type X struct{}
var x X
s := S{E{}}
t := T{struct{}{}}
_ = append(s, x)
_ = append(s, t[0])
_ = append(s, t...)
}
|
go/test/fixedbugs/issue23912.go/0
|
{
"file_path": "go/test/fixedbugs/issue23912.go",
"repo_id": "go",
"token_count": 199
}
| 510 |
// compile
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type T interface {
M(P)
}
type M interface {
F() P
}
type P = interface {
// The compiler cannot handle this case. Disabled for now.
// See issue #25838.
// I() M
}
func main() {}
|
go/test/fixedbugs/issue24939.go/0
|
{
"file_path": "go/test/fixedbugs/issue24939.go",
"repo_id": "go",
"token_count": 119
}
| 511 |
// compile -N
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 25966: liveness code complains autotmp live on
// function entry.
package p
var F = []func(){
func() func() { return (func())(nil) }(),
}
var A = []int{}
type ss struct {
string
float64
i int
}
var V = A[ss{}.i]
|
go/test/fixedbugs/issue25966.go/0
|
{
"file_path": "go/test/fixedbugs/issue25966.go",
"repo_id": "go",
"token_count": 137
}
| 512 |
// run
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// gccgo mishandled passing a struct with an empty field through
// reflect.Value.Call.
package main
import (
"reflect"
)
type Empty struct {
f1, f2 *byte
empty struct{}
}
func F(e Empty, s []string) {
if len(s) != 1 || s[0] != "hi" {
panic("bad slice")
}
}
func main() {
reflect.ValueOf(F).Call([]reflect.Value{
reflect.ValueOf(Empty{}),
reflect.ValueOf([]string{"hi"}),
})
}
|
go/test/fixedbugs/issue26335.go/0
|
{
"file_path": "go/test/fixedbugs/issue26335.go",
"repo_id": "go",
"token_count": 203
}
| 513 |
// compile
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package p
// 1st test case from issue
type F = func(E) // compiles if not type alias or moved below E struct
type E struct {
f F
}
var x = E{func(E) {}}
// 2nd test case from issue
type P = *S
type S struct {
p P
}
|
go/test/fixedbugs/issue27267.go/0
|
{
"file_path": "go/test/fixedbugs/issue27267.go",
"repo_id": "go",
"token_count": 127
}
| 514 |
// runindir -goexperiment fieldtrack
// 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.
// Test case for issue 30862. This test as written will
// fail for the main 'gc' compiler unless GOEXPERIMENT=fieldtrack
// is set when building it, whereas gccgo has field tracking
// enabled by default (hence the build tag below).
package ignored
|
go/test/fixedbugs/issue30862.go/0
|
{
"file_path": "go/test/fixedbugs/issue30862.go",
"repo_id": "go",
"token_count": 119
}
| 515 |
// errorcheck
// 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 p
const (
f = 1.0
c = 1.0i
_ = ^f // ERROR "invalid operation|expected integer"
_ = ^c // ERROR "invalid operation|expected integer"
_ = f % f // ERROR "invalid operation|expected integer"
_ = c % c // ERROR "invalid operation|expected integer"
_ = f & f // ERROR "invalid operation|expected integer"
_ = c & c // ERROR "invalid operation|expected integer"
_ = f | f // ERROR "invalid operation|expected integer"
_ = c | c // ERROR "invalid operation|expected integer"
_ = f ^ f // ERROR "invalid operation|expected integer"
_ = c ^ c // ERROR "invalid operation|expected integer"
_ = f &^ f // ERROR "invalid operation|expected integer"
_ = c &^ c // ERROR "invalid operation|expected integer"
)
|
go/test/fixedbugs/issue31060.go/0
|
{
"file_path": "go/test/fixedbugs/issue31060.go",
"repo_id": "go",
"token_count": 274
}
| 516 |
a
b
c
|
go/test/fixedbugs/issue31636.out/0
|
{
"file_path": "go/test/fixedbugs/issue31636.out",
"repo_id": "go",
"token_count": 6
}
| 517 |
42
|
go/test/fixedbugs/issue32175.out/0
|
{
"file_path": "go/test/fixedbugs/issue32175.out",
"repo_id": "go",
"token_count": 2
}
| 518 |
// errorcheck
// Copyright 2020 The Go Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in
// the LICENSE file.
// Test that the compiler does not crash on a []byte conversion of an
// untyped expression.
package p
var v uint
var x = []byte((1 << v) + 1) // ERROR "cannot convert|non-integer type for left operand of shift"
|
go/test/fixedbugs/issue33308.go/0
|
{
"file_path": "go/test/fixedbugs/issue33308.go",
"repo_id": "go",
"token_count": 110
}
| 519 |
// run
// 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.
// Test that a binary with a large data section can load. This failed on wasm.
package main
var test = [100 * 1024 * 1024]byte{42}
func main() {
if test[0] != 42 {
panic("bad")
}
}
|
go/test/fixedbugs/issue34395.go/0
|
{
"file_path": "go/test/fixedbugs/issue34395.go",
"repo_id": "go",
"token_count": 114
}
| 520 |
// errorcheck -0 -l -m=2
// 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.
// This test makes sure that -m=2's escape analysis diagnostics don't
// go into an infinite loop when handling negative dereference
// cycles. The critical thing being tested here is that compilation
// succeeds ("errorcheck -0"), not any particular diagnostic output,
// hence the very lax ERROR patterns below.
package p
type Node struct {
Orig *Node
}
var sink *Node
func f1() {
var n Node // ERROR "."
n.Orig = &n
m := n // ERROR "."
sink = &m
}
func f2() {
var n1, n2 Node // ERROR "."
n1.Orig = &n2
n2 = n1
m := n2 // ERROR "."
sink = &m
}
func f3() {
var n1, n2 Node // ERROR "."
n1.Orig = &n1
n1.Orig = &n2
sink = n1.Orig.Orig
}
|
go/test/fixedbugs/issue35518.go/0
|
{
"file_path": "go/test/fixedbugs/issue35518.go",
"repo_id": "go",
"token_count": 296
}
| 521 |
// compile
// 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 main
func rotate(s []int, m int) {
l := len(s)
m = m % l
buf := make([]int, m)
copy(buf, s)
copy(s, s[m:])
copy(s[l-m:], buf)
}
func main() {
a0 := [...]int{1,2,3,4,5}
println(a0[0])
rotate(a0[:], 1)
println(a0[0])
rotate(a0[:], -3)
println(a0[0])
}
|
go/test/fixedbugs/issue36259.go/0
|
{
"file_path": "go/test/fixedbugs/issue36259.go",
"repo_id": "go",
"token_count": 221
}
| 522 |
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Make sure runtime.panicmakeslice* are called.
package main
import "strings"
func main() {
// Test typechecking passes if len is valid
// but cap is out of range for len's type.
var x byte
_ = make([]int, x, 300)
capOutOfRange := func() {
i := 2
s := make([]int, i, 1)
s[0] = 1
}
lenOutOfRange := func() {
i := -1
s := make([]int, i, 3)
s[0] = 1
}
tests := []struct {
f func()
panicStr string
}{
{capOutOfRange, "cap out of range"},
{lenOutOfRange, "len out of range"},
}
for _, tc := range tests {
shouldPanic(tc.panicStr, tc.f)
}
}
func shouldPanic(str string, f func()) {
defer func() {
err := recover()
runtimeErr := err.(error).Error()
if !strings.Contains(runtimeErr, str) {
panic("got panic " + runtimeErr + ", want " + str)
}
}()
f()
}
|
go/test/fixedbugs/issue37975.go/0
|
{
"file_path": "go/test/fixedbugs/issue37975.go",
"repo_id": "go",
"token_count": 389
}
| 523 |
// compile -N
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package p
func f(x float64) bool {
x += 1
return (x != 0) == (x != 0)
}
|
go/test/fixedbugs/issue39472.go/0
|
{
"file_path": "go/test/fixedbugs/issue39472.go",
"repo_id": "go",
"token_count": 82
}
| 524 |
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build cgo
package main
import (
"runtime/cgo"
"unsafe"
)
type S struct {
_ cgo.Incomplete
x int
}
func main() {
var i int
p := (*S)(unsafe.Pointer(uintptr(unsafe.Pointer(&i))))
v := uintptr(unsafe.Pointer(p))
// p is a pointer to a not-in-heap type. Like some C libraries,
// we stored an integer in that pointer. That integer just happens
// to be the address of i.
// v is also the address of i.
// p has a base type which is marked not-in-heap, so it
// should not be adjusted when the stack is copied.
recurse(100, p, v)
}
func recurse(n int, p *S, v uintptr) {
if n > 0 {
recurse(n-1, p, v)
}
if uintptr(unsafe.Pointer(p)) != v {
panic("adjusted notinheap pointer")
}
}
|
go/test/fixedbugs/issue40954.go/0
|
{
"file_path": "go/test/fixedbugs/issue40954.go",
"repo_id": "go",
"token_count": 325
}
| 525 |
// errorcheck
// Copyright 2020 The Go Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package p
var c chan [2 << 16]byte // GC_ERROR "channel element type too large"
type T [1 << 17]byte
var x chan T // GC_ERROR "channel element type too large"
|
go/test/fixedbugs/issue42058a.go/0
|
{
"file_path": "go/test/fixedbugs/issue42058a.go",
"repo_id": "go",
"token_count": 101
}
| 526 |
// run
// Copyright 2012 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.
// Issue 4316: the stack overflow check in the linker
// is confused when it encounters a split-stack function
// that needs 0 bytes of stack space.
package main
type Peano *Peano
func makePeano(n int) *Peano {
if n == 0 {
return nil
}
p := Peano(makePeano(n - 1))
return &p
}
var countArg Peano
var countResult int
func countPeano() {
if countArg == nil {
countResult = 0
return
}
countArg = *countArg
countPeano()
countResult++
}
var s = "(())"
var pT = 0
func p() {
if pT >= len(s) {
return
}
if s[pT] == '(' {
pT += 1
p()
if pT < len(s) && s[pT] == ')' {
pT += 1
} else {
return
}
p()
}
}
func main() {
countArg = makePeano(4096)
countPeano()
if countResult != 4096 {
println("countResult =", countResult)
panic("countResult != 4096")
}
p()
}
|
go/test/fixedbugs/issue4316.go/0
|
{
"file_path": "go/test/fixedbugs/issue4316.go",
"repo_id": "go",
"token_count": 386
}
| 527 |
e a b c d
|
go/test/fixedbugs/issue43444.out/0
|
{
"file_path": "go/test/fixedbugs/issue43444.out",
"repo_id": "go",
"token_count": 6
}
| 528 |
// errorcheck
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that fields hide promoted methods.
// https://golang.org/issue/4365
package main
type T interface {
M()
}
type M struct{}
func (M) M() {}
type Foo struct {
M
}
func main() {
var v T = Foo{} // ERROR "has no methods|not a method|cannot use"
_ = v
}
|
go/test/fixedbugs/issue4365.go/0
|
{
"file_path": "go/test/fixedbugs/issue4365.go",
"repo_id": "go",
"token_count": 173
}
| 529 |
// compile
// Copyright 2012 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.
// Issue 4399: 8g would print "gins LEAQ nil *A".
package main
type A struct{ a int }
func main() {
println(((*A)(nil)).a)
}
|
go/test/fixedbugs/issue4399.go/0
|
{
"file_path": "go/test/fixedbugs/issue4399.go",
"repo_id": "go",
"token_count": 96
}
| 530 |
// run
// 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 main
import "fmt"
//go:noinline
func repro(b []byte, bit int32) {
_ = b[3]
v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 | 1<<(bit&31)
b[0] = byte(v)
b[1] = byte(v >> 8)
b[2] = byte(v >> 16)
b[3] = byte(v >> 24)
}
func main() {
var b [8]byte
repro(b[:], 32)
want := [8]byte{1, 0, 0, 0, 0, 0, 0, 0}
if b != want {
panic(fmt.Sprintf("got %v, want %v\n", b, want))
}
}
|
go/test/fixedbugs/issue45242.go/0
|
{
"file_path": "go/test/fixedbugs/issue45242.go",
"repo_id": "go",
"token_count": 271
}
| 531 |
// errorcheck -e
// 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 p
type T struct{}
var s string
var b bool
var i int
var t T
var a [1]int
var (
_ = s == nil // ERROR "invalid operation:.*mismatched types string and (untyped )?nil"
_ = b == nil // ERROR "invalid operation:.*mismatched types bool and (untyped )?nil"
_ = i == nil // ERROR "invalid operation:.*mismatched types int and (untyped )?nil"
_ = t == nil // ERROR "invalid operation:.*mismatched types T and (untyped )?nil"
_ = a == nil // ERROR "invalid operation:.*mismatched types \[1\]int and (untyped )?nil"
)
|
go/test/fixedbugs/issue48784.go/0
|
{
"file_path": "go/test/fixedbugs/issue48784.go",
"repo_id": "go",
"token_count": 238
}
| 532 |
// compile
// 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 main
var B []bool
var N int
func f(p bool, m map[bool]bool) bool {
var q bool
_ = p || N&N < N || B[0] || B[0]
return p && q && m[q]
}
|
go/test/fixedbugs/issue49122.go/0
|
{
"file_path": "go/test/fixedbugs/issue49122.go",
"repo_id": "go",
"token_count": 114
}
| 533 |
// compile
// 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 p
func f(i int) {
var s1 struct {
s struct{ s struct{ i int } }
}
var s2, s3 struct {
a struct{ i int }
b int
}
func() {
i = 1 + 2*i + s3.a.i + func() int {
s2.a, s2.b = s3.a, s3.b
return 0
}() + func(*int) int {
return s1.s.s.i
}(new(int))
}()
}
|
go/test/fixedbugs/issue49378.go/0
|
{
"file_path": "go/test/fixedbugs/issue49378.go",
"repo_id": "go",
"token_count": 203
}
| 534 |
// compile
// 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 main
type T1 struct {
A T5
B T2
C T7
D T4
}
type T2 struct {
T3
A float64
E float64
C float64
}
type T3 struct {
F float64
G float64
H float64
I float64
J float64
K float64
L float64
}
type T4 struct {
M float64
N float64
O float64
P float64
}
type T5 struct {
Q float64
R float64
S float64
T float64
U float64
V float64
}
type T6 struct {
T9
C T10
}
type T7 struct {
T10
T11
}
type T8 struct {
T9
C T7
}
type T9 struct {
A T5
B T3
D T4
}
type T10 struct {
W float64
}
type T11 struct {
X float64
Y float64
}
func MainTest(x T1, y T8, z T6) float64 {
return Test(x.B, x.A, x.D, x.C, y.B, y.A, y.D, y.C, z.B, z.A, z.D,
T7{
T10: T10{
W: z.C.W,
},
T11: T11{},
},
)
}
func Test(a T2, b T5, c T4, d T7, e T3, f T5, g T4, h T7, i T3, j T5, k T4, l T7) float64
|
go/test/fixedbugs/issue53454.go/0
|
{
"file_path": "go/test/fixedbugs/issue53454.go",
"repo_id": "go",
"token_count": 505
}
| 535 |
// run
// 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 main
func main() {
F[T[int]]()
}
func F[X interface{ M() }]() {
var x X
x.M()
}
type T[X any] struct{ E }
type E struct{}
func (h E) M() {}
|
go/test/fixedbugs/issue54348.go/0
|
{
"file_path": "go/test/fixedbugs/issue54348.go",
"repo_id": "go",
"token_count": 121
}
| 536 |
// compile
// 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 p
import (
"sync/atomic"
)
type I interface {
M()
}
type S struct{}
func (*S) M() {}
type T struct {
I
x atomic.Int64
}
func F() {
t := &T{I: &S{}}
t.M()
}
|
go/test/fixedbugs/issue54991.go/0
|
{
"file_path": "go/test/fixedbugs/issue54991.go",
"repo_id": "go",
"token_count": 134
}
| 537 |
// run
// 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 main
import (
"log"
"reflect"
"sort"
)
func main() {
const length = 257
x := make([]int64, length)
for i := 0; i < length; i++ {
x[i] = int64(i) * 27644437 % int64(length)
}
isLessStatic := func(i, j int) bool {
return x[i] < x[j]
}
isLessReflect := reflect.MakeFunc(reflect.TypeOf(isLessStatic), func(args []reflect.Value) []reflect.Value {
i := args[0].Int()
j := args[1].Int()
b := x[i] < x[j]
return []reflect.Value{reflect.ValueOf(b)}
}).Interface().(func(i, j int) bool)
sort.SliceStable(x, isLessReflect)
for i := 0; i < length-1; i++ {
if x[i] >= x[i+1] {
log.Fatalf("not sorted! (length=%v, idx=%v)\n%v\n", length, i, x)
}
}
}
|
go/test/fixedbugs/issue57184.go/0
|
{
"file_path": "go/test/fixedbugs/issue57184.go",
"repo_id": "go",
"token_count": 361
}
| 538 |
main.f
main.g
|
go/test/fixedbugs/issue58300.out/0
|
{
"file_path": "go/test/fixedbugs/issue58300.out",
"repo_id": "go",
"token_count": 8
}
| 539 |
// run
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func g[P any](...P) P { var zero P; return zero }
var (
_ int = g(1, 2)
_ rune = g(1, 'a')
_ float64 = g(1, 'a', 2.3)
_ float64 = g('a', 2.3)
_ complex128 = g(2.3, 'a', 1i)
)
func main() {}
|
go/test/fixedbugs/issue58671.go/0
|
{
"file_path": "go/test/fixedbugs/issue58671.go",
"repo_id": "go",
"token_count": 172
}
| 540 |
package surprise
var X int
|
go/test/fixedbugs/issue5957.dir/a.go/0
|
{
"file_path": "go/test/fixedbugs/issue5957.dir/a.go",
"repo_id": "go",
"token_count": 8
}
| 541 |
// compile
//go:build !386 && !arm && !mips && !mipsle && !amd64p32
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 6036: 6g's backend generates OINDREG with
// offsets larger than 32-bit.
package main
type T struct {
Large [1 << 31]byte
A int
B int
}
func F(t *T) {
t.B = t.A
}
type T2 [1<<31 + 2]byte
func F2(t *T2) {
t[1<<31+1] = 42
}
type T3 [1<<15 + 1][1<<15 + 1]int
func F3(t *T3) {
t[1<<15][1<<15] = 42
}
type S struct {
A int32
B int32
}
type T4 [1<<29 + 1]S
func F4(t *T4) {
t[1<<29].B = 42
}
|
go/test/fixedbugs/issue6036.go/0
|
{
"file_path": "go/test/fixedbugs/issue6036.go",
"repo_id": "go",
"token_count": 295
}
| 542 |
// compile
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.package main
package main
type Stringer interface {
String() string
}
type (
stringer struct{}
stringers [2]stringer
foo struct {
stringers
}
)
func (stringer) String() string { return "" }
func toString(s Stringer) string { return s.String() }
func (v stringers) toStrings() []string {
return []string{toString(v[0]), toString(v[1])}
}
func main() {
_ = stringers{}
}
|
go/test/fixedbugs/issue65808.go/0
|
{
"file_path": "go/test/fixedbugs/issue65808.go",
"repo_id": "go",
"token_count": 192
}
| 543 |
// errorcheck
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package p
func f1() {
for a, a := range []int{1, 2, 3} { // ERROR "a.* repeated on left side of :=|a redeclared"
println(a)
}
}
func f2() {
var a int
for a, a := range []int{1, 2, 3} { // ERROR "a.* repeated on left side of :=|a redeclared"
println(a)
}
println(a)
}
|
go/test/fixedbugs/issue6772.go/0
|
{
"file_path": "go/test/fixedbugs/issue6772.go",
"repo_id": "go",
"token_count": 168
}
| 544 |
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 6902: confusing printing of large floating point constants
package main
import (
"os"
)
var x = -1e-10000
func main() {
if x != 0 {
os.Exit(1)
}
}
|
go/test/fixedbugs/issue6902.go/0
|
{
"file_path": "go/test/fixedbugs/issue6902.go",
"repo_id": "go",
"token_count": 110
}
| 545 |
// runoutput
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 7316
// This test exercises all types of numeric conversions, which was one
// of the sources of etype mismatch during register allocation in 8g.
package main
import "fmt"
const tpl = `
func init() {
var i %s
j := %s(i)
_ = %s(j)
}
`
func main() {
fmt.Println("package main")
ntypes := []string{
"byte", "rune", "uintptr",
"float32", "float64",
"int", "int8", "int16", "int32", "int64",
"uint", "uint8", "uint16", "uint32", "uint64",
}
for i, from := range ntypes {
for _, to := range ntypes[i:] {
fmt.Printf(tpl, from, to, from)
}
}
fmt.Println("func main() {}")
}
|
go/test/fixedbugs/issue7316.go/0
|
{
"file_path": "go/test/fixedbugs/issue7316.go",
"repo_id": "go",
"token_count": 296
}
| 546 |
package main
import "./x1"
func main() {
s := x1.F(&x1.P)
if s != "100 100\n" {
println("BUG:", s)
}
}
|
go/test/fixedbugs/issue7995b.dir/x2.go/0
|
{
"file_path": "go/test/fixedbugs/issue7995b.dir/x2.go",
"repo_id": "go",
"token_count": 58
}
| 547 |
// run
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 8325: corrupted byte operations during optimization
// pass.
package main
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
func main() {
var bytes = []byte{10, 20, 30, 40, 50}
for i, b := range bytes {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
for _, b := range bytes {
switch {
case '0' <= b && b <= '9',
'A' <= b && b <= 'Z':
default:
println("found a bad character", string(b))
panic("BUG")
}
}
}
|
go/test/fixedbugs/issue8325.go/0
|
{
"file_path": "go/test/fixedbugs/issue8325.go",
"repo_id": "go",
"token_count": 235
}
| 548 |
// errorcheck
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Checking that line number is correct in error message.
package main
type Cint int
func foobar(*Cint, Cint, Cint, *Cint)
func main() {
a := Cint(1)
foobar(
&a,
0,
0,
42, // ERROR ".*"
)
}
|
go/test/fixedbugs/issue8836.go/0
|
{
"file_path": "go/test/fixedbugs/issue8836.go",
"repo_id": "go",
"token_count": 138
}
| 549 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package a
type X struct {
T [32]byte
}
func (x *X) Get() []byte {
t := x.T
return t[:]
}
func (x *X) RetPtr(i int) *int {
i++
return &i
}
func (x *X) RetRPtr(i int) (r1 int, r2 *int) {
r1 = i + 1
r2 = &r1
return
}
|
go/test/fixedbugs/issue9537.dir/a.go/0
|
{
"file_path": "go/test/fixedbugs/issue9537.dir/a.go",
"repo_id": "go",
"token_count": 162
}
| 550 |
// run
// Copyright 2009 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.
// Test floating-point literal syntax.
package main
var bad bool
func pow10(pow int) float64 {
if pow < 0 {
return 1 / pow10(-pow)
}
if pow > 0 {
return pow10(pow-1) * 10
}
return 1
}
func close(da float64, ia, ib int64, pow int) bool {
db := float64(ia) / float64(ib)
db *= pow10(pow)
if da == 0 || db == 0 {
if da == 0 && db == 0 {
return true
}
return false
}
de := (da - db) / da
if de < 0 {
de = -de
}
if de < 1e-14 {
return true
}
if !bad {
println("BUG")
bad = true
}
return false
}
func main() {
if !close(0., 0, 1, 0) {
print("0. is ", 0., "\n")
}
if !close(+10., 10, 1, 0) {
print("+10. is ", +10., "\n")
}
if !close(-210., -210, 1, 0) {
print("-210. is ", -210., "\n")
}
if !close(.0, 0, 1, 0) {
print(".0 is ", .0, "\n")
}
if !close(+.01, 1, 100, 0) {
print("+.01 is ", +.01, "\n")
}
if !close(-.012, -12, 1000, 0) {
print("-.012 is ", -.012, "\n")
}
if !close(0.0, 0, 1, 0) {
print("0.0 is ", 0.0, "\n")
}
if !close(+10.01, 1001, 100, 0) {
print("+10.01 is ", +10.01, "\n")
}
if !close(-210.012, -210012, 1000, 0) {
print("-210.012 is ", -210.012, "\n")
}
if !close(0E+1, 0, 1, 0) {
print("0E+1 is ", 0E+1, "\n")
}
if !close(+10e2, 10, 1, 2) {
print("+10e2 is ", +10e2, "\n")
}
if !close(-210e3, -210, 1, 3) {
print("-210e3 is ", -210e3, "\n")
}
if !close(0E-1, 0, 1, 0) {
print("0E-1 is ", 0E-1, "\n")
}
if !close(+0e23, 0, 1, 1) {
print("+0e23 is ", +0e23, "\n")
}
if !close(-0e345, 0, 1, 1) {
print("-0e345 is ", -0e345, "\n")
}
if !close(0E1, 0, 1, 1) {
print("0E1 is ", 0E1, "\n")
}
if !close(+10e23, 10, 1, 23) {
print("+10e23 is ", +10e23, "\n")
}
if !close(-210e34, -210, 1, 34) {
print("-210e34 is ", -210e34, "\n")
}
if !close(0.E1, 0, 1, 1) {
print("0.E1 is ", 0.E1, "\n")
}
if !close(+10.e+2, 10, 1, 2) {
print("+10.e+2 is ", +10.e+2, "\n")
}
if !close(-210.e-3, -210, 1, -3) {
print("-210.e-3 is ", -210.e-3, "\n")
}
if !close(.0E1, 0, 1, 1) {
print(".0E1 is ", .0E1, "\n")
}
if !close(+.01e2, 1, 100, 2) {
print("+.01e2 is ", +.01e2, "\n")
}
if !close(-.012e3, -12, 1000, 3) {
print("-.012e3 is ", -.012e3, "\n")
}
if !close(0.0E1, 0, 1, 0) {
print("0.0E1 is ", 0.0E1, "\n")
}
if !close(+10.01e2, 1001, 100, 2) {
print("+10.01e2 is ", +10.01e2, "\n")
}
if !close(-210.012e3, -210012, 1000, 3) {
print("-210.012e3 is ", -210.012e3, "\n")
}
if !close(0.E+12, 0, 1, 0) {
print("0.E+12 is ", 0.E+12, "\n")
}
if !close(+10.e23, 10, 1, 23) {
print("+10.e23 is ", +10.e23, "\n")
}
if !close(-210.e33, -210, 1, 33) {
print("-210.e33 is ", -210.e33, "\n")
}
if !close(.0E-12, 0, 1, 0) {
print(".0E-12 is ", .0E-12, "\n")
}
if !close(+.01e23, 1, 100, 23) {
print("+.01e23 is ", +.01e23, "\n")
}
if !close(-.012e34, -12, 1000, 34) {
print("-.012e34 is ", -.012e34, "\n")
}
if !close(0.0E12, 0, 1, 12) {
print("0.0E12 is ", 0.0E12, "\n")
}
if !close(+10.01e23, 1001, 100, 23) {
print("+10.01e23 is ", +10.01e23, "\n")
}
if !close(-210.012e33, -210012, 1000, 33) {
print("-210.012e33 is ", -210.012e33, "\n")
}
if !close(0.E123, 0, 1, 123) {
print("0.E123 is ", 0.E123, "\n")
}
if !close(+10.e+23, 10, 1, 23) {
print("+10.e+234 is ", +10.e+234, "\n")
}
if !close(-210.e-35, -210, 1, -35) {
print("-210.e-35 is ", -210.e-35, "\n")
}
if !close(.0E123, 0, 1, 123) {
print(".0E123 is ", .0E123, "\n")
}
if !close(+.01e29, 1, 100, 29) {
print("+.01e29 is ", +.01e29, "\n")
}
if !close(-.012e29, -12, 1000, 29) {
print("-.012e29 is ", -.012e29, "\n")
}
if !close(0.0E123, 0, 1, 123) {
print("0.0E123 is ", 0.0E123, "\n")
}
if !close(+10.01e31, 1001, 100, 31) {
print("+10.01e31 is ", +10.01e31, "\n")
}
if !close(-210.012e19, -210012, 1000, 19) {
print("-210.012e19 is ", -210.012e19, "\n")
}
if bad {
panic("float_lit")
}
}
|
go/test/float_lit.go/0
|
{
"file_path": "go/test/float_lit.go",
"repo_id": "go",
"token_count": 2179
}
| 551 |
// errorcheck -0 -d=ssa/late_fuse/debug=1
//go:build (amd64 && !gcflags_noopt) || (arm64 && !gcflags_noopt)
// 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 main
import "strings"
const Cf2 = 2.0
func fEqEq(a int, f float64) bool {
return a == 0 && f > Cf2 || a == 0 && f < -Cf2 // ERROR "Redirect Eq64 based on Eq64$"
}
func fEqNeq(a int32, f float64) bool {
return a == 0 && f > Cf2 || a != 0 && f < -Cf2 // ERROR "Redirect Neq32 based on Eq32$"
}
func fEqLess(a int8, f float64) bool {
return a == 0 && f > Cf2 || a < 0 && f < -Cf2
}
func fEqLeq(a float64, f float64) bool {
return a == 0 && f > Cf2 || a <= 0 && f < -Cf2
}
func fEqLessU(a uint, f float64) bool {
return a == 0 && f > Cf2 || a < 0 && f < -Cf2
}
func fEqLeqU(a uint64, f float64) bool {
return a == 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Eq64 based on Eq64$"
}
func fNeqEq(a int, f float64) bool {
return a != 0 && f > Cf2 || a == 0 && f < -Cf2 // ERROR "Redirect Eq64 based on Neq64$"
}
func fNeqNeq(a int32, f float64) bool {
return a != 0 && f > Cf2 || a != 0 && f < -Cf2 // ERROR "Redirect Neq32 based on Neq32$"
}
func fNeqLess(a float32, f float64) bool {
// TODO: Add support for floating point numbers in prove
return a != 0 && f > Cf2 || a < 0 && f < -Cf2
}
func fNeqLeq(a int16, f float64) bool {
return a != 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Leq16 based on Neq16$"
}
func fNeqLessU(a uint, f float64) bool {
return a != 0 && f > Cf2 || a < 0 && f < -Cf2
}
func fNeqLeqU(a uint32, f float64) bool {
return a != 2 && f > Cf2 || a <= 2 && f < -Cf2 // ERROR "Redirect Leq32U based on Neq32$"
}
func fLessEq(a int, f float64) bool {
return a < 0 && f > Cf2 || a == 0 && f < -Cf2
}
func fLessNeq(a int32, f float64) bool {
return a < 0 && f > Cf2 || a != 0 && f < -Cf2
}
func fLessLess(a float32, f float64) bool {
return a < 0 && f > Cf2 || a < 0 && f < -Cf2 // ERROR "Redirect Less32F based on Less32F$"
}
func fLessLeq(a float64, f float64) bool {
return a < 0 && f > Cf2 || a <= 0 && f < -Cf2
}
func fLeqEq(a float64, f float64) bool {
return a <= 0 && f > Cf2 || a == 0 && f < -Cf2
}
func fLeqNeq(a int16, f float64) bool {
return a <= 0 && f > Cf2 || a != 0 && f < -Cf2 // ERROR "Redirect Neq16 based on Leq16$"
}
func fLeqLess(a float32, f float64) bool {
return a <= 0 && f > Cf2 || a < 0 && f < -Cf2
}
func fLeqLeq(a int8, f float64) bool {
return a <= 0 && f > Cf2 || a <= 0 && f < -Cf2 // ERROR "Redirect Leq8 based on Leq8$"
}
func fLessUEq(a uint8, f float64) bool {
return a < 0 && f > Cf2 || a == 0 && f < -Cf2
}
func fLessUNeq(a uint16, f float64) bool {
return a < 0 && f > Cf2 || a != 0 && f < -Cf2
}
func fLessULessU(a uint32, f float64) bool {
return a < 0 && f > Cf2 || a < 0 && f < -Cf2
}
func fLessULeqU(a uint64, f float64) bool {
return a < 0 && f > Cf2 || a <= 0 && f < -Cf2
}
func fLeqUEq(a uint8, f float64) bool {
return a <= 2 && f > Cf2 || a == 2 && f < -Cf2 // ERROR "Redirect Eq8 based on Leq8U$"
}
func fLeqUNeq(a uint16, f float64) bool {
return a <= 2 && f > Cf2 || a != 2 && f < -Cf2 // ERROR "Redirect Neq16 based on Leq16U$"
}
func fLeqLessU(a uint32, f float64) bool {
return a <= 0 && f > Cf2 || a < 0 && f < -Cf2
}
func fLeqLeqU(a uint64, f float64) bool {
return a <= 2 && f > Cf2 || a <= 2 && f < -Cf2 // ERROR "Redirect Leq64U based on Leq64U$"
}
// Arg tests are disabled because the op name is different on amd64 and arm64.
func fEqPtrEqPtr(a, b *int, f float64) bool {
return a == b && f > Cf2 || a == b && f < -Cf2 // ERROR "Redirect EqPtr based on EqPtr$"
}
func fEqPtrNeqPtr(a, b *int, f float64) bool {
return a == b && f > Cf2 || a != b && f < -Cf2 // ERROR "Redirect NeqPtr based on EqPtr$"
}
func fNeqPtrEqPtr(a, b *int, f float64) bool {
return a != b && f > Cf2 || a == b && f < -Cf2 // ERROR "Redirect EqPtr based on NeqPtr$"
}
func fNeqPtrNeqPtr(a, b *int, f float64) bool {
return a != b && f > Cf2 || a != b && f < -Cf2 // ERROR "Redirect NeqPtr based on NeqPtr$"
}
func fEqInterEqInter(a interface{}, f float64) bool {
return a == nil && f > Cf2 || a == nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
}
func fEqInterNeqInter(a interface{}, f float64) bool {
return a == nil && f > Cf2 || a != nil && f < -Cf2
}
func fNeqInterEqInter(a interface{}, f float64) bool {
return a != nil && f > Cf2 || a == nil && f < -Cf2
}
func fNeqInterNeqInter(a interface{}, f float64) bool {
return a != nil && f > Cf2 || a != nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
}
func fEqSliceEqSlice(a []int, f float64) bool {
return a == nil && f > Cf2 || a == nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
}
func fEqSliceNeqSlice(a []int, f float64) bool {
return a == nil && f > Cf2 || a != nil && f < -Cf2
}
func fNeqSliceEqSlice(a []int, f float64) bool {
return a != nil && f > Cf2 || a == nil && f < -Cf2
}
func fNeqSliceNeqSlice(a []int, f float64) bool {
return a != nil && f > Cf2 || a != nil && f < -Cf2 // ERROR "Redirect IsNonNil based on IsNonNil$"
}
func fPhi(a, b string) string {
aslash := strings.HasSuffix(a, "/") // ERROR "Redirect Phi based on Phi$"
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
func main() {
}
|
go/test/fuse.go/0
|
{
"file_path": "go/test/fuse.go",
"repo_id": "go",
"token_count": 2340
}
| 552 |
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that all the types from import2.go made it
// intact and with the same meaning, by assigning to or using them.
package main
import "./import2"
func f3(func() func() int)
func main() {
p.F3(p.F1)
p.F3(p.F2())
f3(p.F1)
f3(p.F2())
p.C1 = (chan<- (chan int))(nil)
p.C2 = (chan (<-chan int))(nil)
p.C3 = (<-chan (chan int))(nil)
p.C4 = (chan (chan<- int))(nil)
p.C5 = (<-chan (<-chan int))(nil)
p.C6 = (chan<- (<-chan int))(nil)
p.C7 = (chan<- (chan<- int))(nil)
p.C8 = (<-chan (<-chan (chan int)))(nil)
p.C9 = (<-chan (chan<- (chan int)))(nil)
p.C10 = (chan<- (<-chan (chan int)))(nil)
p.C11 = (chan<- (chan<- (chan int)))(nil)
p.C12 = (chan (chan<- (<-chan int)))(nil)
p.C13 = (chan (chan<- (chan<- int)))(nil)
p.R1 = (chan <- chan int)(nil)
p.R3 = (<- chan chan int)(nil)
p.R4 = (chan chan <- int)(nil)
p.R5 = (<- chan <- chan int)(nil)
p.R6 = (chan <- <- chan int)(nil)
p.R7 = (chan <- chan <- int)(nil)
p.R8 = (<- chan <- chan chan int)(nil)
p.R9 = (<- chan chan <- chan int)(nil)
p.R10 = (chan <- <- chan chan int)(nil)
p.R11 = (chan <- chan <- chan int)(nil)
p.R12 = (chan chan <- <- chan int)(nil)
p.R13 = (chan chan <- chan <- int)(nil)
}
|
go/test/import2.dir/import3.go/0
|
{
"file_path": "go/test/import2.dir/import3.go",
"repo_id": "go",
"token_count": 619
}
| 553 |
// errorcheck -t 10
// 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 p
// The init cycle diagnosis used to take exponential time
// to traverse the call graph paths. This test case takes
// at least two minutes on a modern laptop with the bug
// and runs in a fraction of a second without it.
// 10 seconds (-t 10 above) should be plenty if the code is working.
var x = f() + z() // ERROR "initialization cycle"
func f() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func z() int { return x }
func a1() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func a2() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func a3() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func a4() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func a5() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func a6() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func a7() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func a8() int { return b1() + b2() + b3() + b4() + b5() + b6() + b7() }
func b1() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func b2() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func b3() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func b4() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func b5() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func b6() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func b7() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
func b8() int { return a1() + a2() + a3() + a4() + a5() + a6() + a7() }
|
go/test/initexp.go/0
|
{
"file_path": "go/test/initexp.go",
"repo_id": "go",
"token_count": 761
}
| 554 |
// run
// Copyright 2009 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.
// Test big vs. small, pointer vs. value interface methods.
package main
type I interface { M() int64 }
type BigPtr struct { a, b, c, d int64 }
func (z *BigPtr) M() int64 { return z.a+z.b+z.c+z.d }
type SmallPtr struct { a int32 }
func (z *SmallPtr) M() int64 { return int64(z.a) }
type IntPtr int32
func (z *IntPtr) M() int64 { return int64(*z) }
var bad bool
func test(name string, i I) {
m := i.M()
if m != 12345 {
println(name, m)
bad = true
}
}
func ptrs() {
var bigptr BigPtr = BigPtr{ 10000, 2000, 300, 45 }
var smallptr SmallPtr = SmallPtr{ 12345 }
var intptr IntPtr = 12345
// test("bigptr", bigptr)
test("&bigptr", &bigptr)
// test("smallptr", smallptr)
test("&smallptr", &smallptr)
// test("intptr", intptr)
test("&intptr", &intptr)
}
type Big struct { a, b, c, d int64 }
func (z Big) M() int64 { return z.a+z.b+z.c+z.d }
type Small struct { a int32 }
func (z Small) M() int64 { return int64(z.a) }
type Int int32
func (z Int) M() int64 { return int64(z) }
func nonptrs() {
var big Big = Big{ 10000, 2000, 300, 45 }
var small Small = Small{ 12345 }
var int Int = 12345
test("big", big)
test("&big", &big)
test("small", small)
test("&small", &small)
test("int", int)
test("&int", &int)
}
func main() {
ptrs()
nonptrs()
if bad {
println("BUG: interface4")
}
}
|
go/test/interface/bigdata.go/0
|
{
"file_path": "go/test/interface/bigdata.go",
"repo_id": "go",
"token_count": 591
}
| 555 |
// errorcheck
// Copyright 2009 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.
// Test that interface{M()} = *interface{M()} produces a compiler error.
// Does not compile.
package main
type Inst interface {
Next() *Inst
}
type Regexp struct {
code []Inst
start Inst
}
type Start struct {
foo *Inst
}
func (start *Start) Next() *Inst { return nil }
func AddInst(Inst) *Inst {
print("ok in addinst\n")
return nil
}
func main() {
print("call addinst\n")
var _ Inst = AddInst(new(Start)) // ERROR "pointer to interface|incompatible type"
print("return from addinst\n")
var _ *Inst = new(Start) // ERROR "pointer to interface|incompatible type"
}
|
go/test/interface/pointer.go/0
|
{
"file_path": "go/test/interface/pointer.go",
"repo_id": "go",
"token_count": 244
}
| 556 |
// run
// Copyright 2009 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.
// Test arrays and slices.
package main
func setpd(a []int) {
// print("setpd a=", a, " len=", len(a), " cap=", cap(a), "\n");
for i := 0; i < len(a); i++ {
a[i] = i
}
}
func sumpd(a []int) int {
// print("sumpd a=", a, " len=", len(a), " cap=", cap(a), "\n");
t := 0
for i := 0; i < len(a); i++ {
t += a[i]
}
// print("sumpd t=", t, "\n");
return t
}
func setpf(a *[20]int) {
// print("setpf a=", a, " len=", len(a), " cap=", cap(a), "\n");
for i := 0; i < len(a); i++ {
a[i] = i
}
}
func sumpf(a *[20]int) int {
// print("sumpf a=", a, " len=", len(a), " cap=", cap(a), "\n");
t := 0
for i := 0; i < len(a); i++ {
t += a[i]
}
// print("sumpf t=", t, "\n");
return t
}
func res(t int, lb, hb int) {
sb := (hb - lb) * (hb + lb - 1) / 2
if t != sb {
print("lb=", lb,
"; hb=", hb,
"; t=", t,
"; sb=", sb,
"\n")
panic("res")
}
}
// call ptr dynamic with ptr dynamic
func testpdpd() {
a := make([]int, 10, 100)
if len(a) != 10 && cap(a) != 100 {
print("len and cap from new: ", len(a), " ", cap(a), "\n")
panic("fail")
}
a = a[0:100]
setpd(a)
a = a[0:10]
res(sumpd(a), 0, 10)
a = a[5:25]
res(sumpd(a), 5, 25)
a = a[30:95]
res(sumpd(a), 35, 100)
}
// call ptr fixed with ptr fixed
func testpfpf() {
var a [20]int
setpf(&a)
res(sumpf(&a), 0, 20)
}
// call ptr dynamic with ptr fixed from new
func testpdpf1() {
a := new([40]int)
setpd(a[0:])
res(sumpd(a[0:]), 0, 40)
b := (*a)[5:30]
res(sumpd(b), 5, 30)
}
// call ptr dynamic with ptr fixed from var
func testpdpf2() {
var a [80]int
setpd(a[0:])
res(sumpd(a[0:]), 0, 80)
}
// generate bounds error with ptr dynamic
func testpdfault() {
a := make([]int, 100)
print("good\n")
for i := 0; i < 100; i++ {
a[i] = 0
}
print("should fault\n")
a[100] = 0
print("bad\n")
}
// generate bounds error with ptr fixed
func testfdfault() {
var a [80]int
print("good\n")
for i := 0; i < 80; i++ {
a[i] = 0
}
print("should fault\n")
x := 80
a[x] = 0
print("bad\n")
}
func main() {
testpdpd()
testpfpf()
testpdpf1()
testpdpf2()
// print("testpdfault\n"); testpdfault();
// print("testfdfault\n"); testfdfault();
}
|
go/test/ken/array.go/0
|
{
"file_path": "go/test/ken/array.go",
"repo_id": "go",
"token_count": 1138
}
| 557 |
// run
// Copyright 2009 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.
// Test interfaces on basic types.
package main
type myint int
type mystring string
type I0 interface{}
func f() {
var ia, ib I0
var i myint
var s mystring
if ia != ib {
panic("1")
}
i = 1
ia = i
ib = i
if ia != ib {
panic("2")
}
if ia == nil {
panic("3")
}
i = 2
ia = i
if ia == ib {
panic("4")
}
ia = nil
if ia == ib {
panic("5")
}
ib = nil
if ia != ib {
panic("6")
}
if ia != nil {
panic("7")
}
s = "abc"
ia = s
ib = nil
if ia == ib {
panic("8")
}
s = "def"
ib = s
if ia == ib {
panic("9")
}
s = "abc"
ib = s
if ia != ib {
panic("a")
}
}
func main() {
var ia [20]I0
var b bool
var s string
var i8 int8
var i16 int16
var i32 int32
var i64 int64
var u8 uint8
var u16 uint16
var u32 uint32
var u64 uint64
f()
ia[0] = "xxx"
ia[1] = 12345
ia[2] = true
s = "now is"
ia[3] = s
b = false
ia[4] = b
i8 = 29
ia[5] = i8
i16 = 994
ia[6] = i16
i32 = 3434
ia[7] = i32
i64 = 1234567
ia[8] = i64
u8 = 12
ia[9] = u8
u16 = 799
ia[10] = u16
u32 = 4455
ia[11] = u32
u64 = 765432
ia[12] = u64
s = ia[0].(string)
if s != "xxx" {
println(0, s)
panic("fail")
}
i32 = int32(ia[1].(int))
if i32 != 12345 {
println(1, i32)
panic("fail")
}
b = ia[2].(bool)
if b != true {
println(2, b)
panic("fail")
}
s = ia[3].(string)
if s != "now is" {
println(3, s)
panic("fail")
}
b = ia[4].(bool)
if b != false {
println(4, b)
panic("fail")
}
i8 = ia[5].(int8)
if i8 != 29 {
println(5, i8)
panic("fail")
}
i16 = ia[6].(int16)
if i16 != 994 {
println(6, i16)
panic("fail")
}
i32 = ia[7].(int32)
if i32 != 3434 {
println(7, i32)
panic("fail")
}
i64 = ia[8].(int64)
if i64 != 1234567 {
println(8, i64)
panic("fail")
}
u8 = ia[9].(uint8)
if u8 != 12 {
println(5, u8)
panic("fail")
}
u16 = ia[10].(uint16)
if u16 != 799 {
println(6, u16)
panic("fail")
}
u32 = ia[11].(uint32)
if u32 != 4455 {
println(7, u32)
panic("fail")
}
u64 = ia[12].(uint64)
if u64 != 765432 {
println(8, u64)
panic("fail")
}
}
|
go/test/ken/interbasic.go/0
|
{
"file_path": "go/test/ken/interbasic.go",
"repo_id": "go",
"token_count": 1177
}
| 558 |
// run
// Copyright 2009 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.
// Test basic operations on bool.
package main
type s struct {
a bool;
b bool;
}
func
main() {
var a,b bool;
a = true;
b = false;
if !a { panic(1); }
if b { panic(2); }
if !!!a { panic(3); }
if !!b { panic(4); }
a = !b;
if !a { panic(5); }
if !!!a { panic(6); }
var x *s;
x = new(s);
x.a = true;
x.b = false;
if !x.a { panic(7); }
if x.b { panic(8); }
if !!!x.a { panic(9); }
if !!x.b { panic(10); }
x.a = !x.b;
if !x.a { panic(11); }
if !!!x.a { panic(12); }
/*
* test &&
*/
a = true;
b = true;
if !(a && b) { panic(21); }
if a && !b { panic(22); }
if !a && b { panic(23); }
if !a && !b { panic(24); }
a = false;
b = true;
if !(!a && b) { panic(31); }
if !a && !b { panic(32); }
if a && b { panic(33); }
if a && !b { panic(34); }
a = true;
b = false;
if !(a && !b) { panic(41); }
if a && b { panic(41); }
if !a && !b { panic(41); }
if !a && b { panic(44); }
a = false;
b = false;
if !(!a && !b) { panic(51); }
if !a && b { panic(52); }
if a && !b { panic(53); }
if a && b { panic(54); }
/*
* test ||
*/
a = true;
b = true;
if !(a || b) { panic(61); }
if !(a || !b) { panic(62); }
if !(!a || b) { panic(63); }
if !a || !b { panic(64); }
a = false;
b = true;
if !(!a || b) { panic(71); }
if !(!a || !b) { panic(72); }
if !(a || b) { panic(73); }
if a || !b { panic(74); }
a = true;
b = false;
if !(a || !b) { panic(81); }
if !(a || b) { panic(82); }
if !(!a || !b) { panic(83); }
if !a || b { panic(84); }
a = false;
b = false;
if !(!a || !b) { panic(91); }
if !(!a || b) { panic(92); }
if !(a || !b) { panic(93); }
if a || b { panic(94); }
}
|
go/test/ken/simpbool.go/0
|
{
"file_path": "go/test/ken/simpbool.go",
"repo_id": "go",
"token_count": 883
}
| 559 |
package main
import _ "./linkname1"
import "./linkname2"
func main() { // ERROR "can inline main"
str := "hello/world"
bs := []byte(str) // ERROR "\(\[\]byte\)\(str\) escapes to heap"
if y.ContainsSlash(bs) { // ERROR "inlining call to y.ContainsSlash"
}
}
|
go/test/linkname.dir/linkname3.go/0
|
{
"file_path": "go/test/linkname.dir/linkname3.go",
"repo_id": "go",
"token_count": 108
}
| 560 |
// errorcheck -0 -d=ssa/prove/debug=1
//go:build amd64
package main
import "math"
func f0a(a []int) int {
x := 0
for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
x += a[i] // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func f0b(a []int) int {
x := 0
for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
b := a[i:] // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
x += b[0]
}
return x
}
func f0c(a []int) int {
x := 0
for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
b := a[:i+1] // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
x += b[0]
}
return x
}
func f1(a []int) int {
x := 0
for _, i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
x += i
}
return x
}
func f2(a []int) int {
x := 0
for i := 1; i < len(a); i++ { // ERROR "Induction variable: limits \[1,\?\), increment 1$"
x += a[i] // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func f4(a [10]int) int {
x := 0
for i := 0; i < len(a); i += 2 { // ERROR "Induction variable: limits \[0,8\], increment 2$"
x += a[i] // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func f5(a [10]int) int {
x := 0
for i := -10; i < len(a); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
x += a[i+10]
}
return x
}
func f5_int32(a [10]int) int {
x := 0
for i := int32(-10); i < int32(len(a)); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
x += a[i+10]
}
return x
}
func f5_int16(a [10]int) int {
x := 0
for i := int16(-10); i < int16(len(a)); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
x += a[i+10]
}
return x
}
func f5_int8(a [10]int) int {
x := 0
for i := int8(-10); i < int8(len(a)); i += 2 { // ERROR "Induction variable: limits \[-10,8\], increment 2$"
x += a[i+10]
}
return x
}
func f6(a []int) {
for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
b := a[0:i] // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
f6(b)
}
}
func g0a(a string) int {
x := 0
for i := 0; i < len(a); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func g0b(a string) int {
x := 0
for i := 0; len(a) > i; i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func g0c(a string) int {
x := 0
for i := len(a); i > 0; i-- { // ERROR "Induction variable: limits \(0,\?\], increment 1$"
x += int(a[i-1]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func g0d(a string) int {
x := 0
for i := len(a); 0 < i; i-- { // ERROR "Induction variable: limits \(0,\?\], increment 1$"
x += int(a[i-1]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func g0e(a string) int {
x := 0
for i := len(a) - 1; i >= 0; i-- { // ERROR "Induction variable: limits \[0,\?\], increment 1$"
x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func g0f(a string) int {
x := 0
for i := len(a) - 1; 0 <= i; i-- { // ERROR "Induction variable: limits \[0,\?\], increment 1$"
x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func g1() int {
a := "evenlength"
x := 0
for i := 0; i < len(a); i += 2 { // ERROR "Induction variable: limits \[0,8\], increment 2$"
x += int(a[i]) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return x
}
func g2() int {
a := "evenlength"
x := 0
for i := 0; i < len(a); i += 2 { // ERROR "Induction variable: limits \[0,8\], increment 2$"
j := i
if a[i] == 'e' { // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
j = j + 1
}
x += int(a[j])
}
return x
}
func g3a() {
a := "this string has length 25"
for i := 0; i < len(a); i += 5 { // ERROR "Induction variable: limits \[0,20\], increment 5$"
useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useString(a[:i+3]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useString(a[:i+5]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useString(a[:i+6])
}
}
func g3b(a string) {
for i := 0; i < len(a); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
useString(a[i+1:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
}
}
func g3c(a string) {
for i := 0; i < len(a); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
useString(a[:i+1]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
}
}
func h1(a []byte) {
c := a[:128]
for i := range c { // ERROR "Induction variable: limits \[0,128\), increment 1$"
c[i] = byte(i) // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
}
func h2(a []byte) {
for i := range a[:128] { // ERROR "Induction variable: limits \[0,128\), increment 1$"
a[i] = byte(i)
}
}
func k0(a [100]int) [100]int {
for i := 10; i < 90; i++ { // ERROR "Induction variable: limits \[10,90\), increment 1$"
if a[0] == 0xdeadbeef {
// This is a trick to prohibit sccp to optimize out the following out of bound check
continue
}
a[i-11] = i
a[i-10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i-5] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i+5] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i+11] = i
}
return a
}
func k1(a [100]int) [100]int {
for i := 10; i < 90; i++ { // ERROR "Induction variable: limits \[10,90\), increment 1$"
if a[0] == 0xdeadbeef {
// This is a trick to prohibit sccp to optimize out the following out of bound check
continue
}
useSlice(a[:i-11])
useSlice(a[:i-10]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[:i-5]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[:i]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[:i+5]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[:i+10]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[:i+11]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[:i+12])
}
return a
}
func k2(a [100]int) [100]int {
for i := 10; i < 90; i++ { // ERROR "Induction variable: limits \[10,90\), increment 1$"
if a[0] == 0xdeadbeef {
// This is a trick to prohibit sccp to optimize out the following out of bound check
continue
}
useSlice(a[i-11:])
useSlice(a[i-10:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[i-5:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[i+5:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[i+10:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[i+11:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
useSlice(a[i+12:])
}
return a
}
func k3(a [100]int) [100]int {
for i := -10; i < 90; i++ { // ERROR "Induction variable: limits \[-10,90\), increment 1$"
if a[0] == 0xdeadbeef {
// This is a trick to prohibit sccp to optimize out the following out of bound check
continue
}
a[i+9] = i
a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i+11] = i
}
return a
}
func k3neg(a [100]int) [100]int {
for i := 89; i > -11; i-- { // ERROR "Induction variable: limits \(-11,89\], increment 1$"
if a[0] == 0xdeadbeef {
// This is a trick to prohibit sccp to optimize out the following out of bound check
continue
}
a[i+9] = i
a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i+11] = i
}
return a
}
func k3neg2(a [100]int) [100]int {
for i := 89; i >= -10; i-- { // ERROR "Induction variable: limits \[-10,89\], increment 1$"
if a[0] == 0xdeadbeef {
// This is a trick to prohibit sccp to optimize out the following out of bound check
continue
}
a[i+9] = i
a[i+10] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i+11] = i
}
return a
}
func k4(a [100]int) [100]int {
min := (-1) << 63
for i := min; i < min+50; i++ { // ERROR "Induction variable: limits \[-9223372036854775808,-9223372036854775758\), increment 1$"
a[i-min] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return a
}
func k5(a [100]int) [100]int {
max := (1 << 63) - 1
for i := max - 50; i < max; i++ { // ERROR "Induction variable: limits \[9223372036854775757,9223372036854775807\), increment 1$"
a[i-max+50] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
a[i-(max-70)] = i // ERROR "(\([0-9]+\) )?Proved IsInBounds$"
}
return a
}
func d1(a [100]int) [100]int {
for i := 0; i < 100; i++ { // ERROR "Induction variable: limits \[0,100\), increment 1$"
for j := 0; j < i; j++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
a[j] = 0 // ERROR "Proved IsInBounds$"
a[j+1] = 0 // FIXME: this boundcheck should be eliminated
a[j+2] = 0
}
}
return a
}
func d2(a [100]int) [100]int {
for i := 0; i < 100; i++ { // ERROR "Induction variable: limits \[0,100\), increment 1$"
for j := 0; i > j; j++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
a[j] = 0 // ERROR "Proved IsInBounds$"
a[j+1] = 0 // FIXME: this boundcheck should be eliminated
a[j+2] = 0
}
}
return a
}
func d3(a [100]int) [100]int {
for i := 0; i <= 99; i++ { // ERROR "Induction variable: limits \[0,99\], increment 1$"
for j := 0; j <= i-1; j++ {
a[j] = 0
a[j+1] = 0 // ERROR "Proved IsInBounds$"
a[j+2] = 0
}
}
return a
}
func d4() {
for i := int64(math.MaxInt64 - 9); i < math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775798,9223372036854775802\], increment 4$"
useString("foo")
}
for i := int64(math.MaxInt64 - 8); i < math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775799,9223372036854775803\], increment 4$"
useString("foo")
}
for i := int64(math.MaxInt64 - 7); i < math.MaxInt64-2; i += 4 {
useString("foo")
}
for i := int64(math.MaxInt64 - 6); i < math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775801,9223372036854775801\], increment 4$"
useString("foo")
}
for i := int64(math.MaxInt64 - 9); i <= math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775798,9223372036854775802\], increment 4$"
useString("foo")
}
for i := int64(math.MaxInt64 - 8); i <= math.MaxInt64-2; i += 4 { // ERROR "Induction variable: limits \[9223372036854775799,9223372036854775803\], increment 4$"
useString("foo")
}
for i := int64(math.MaxInt64 - 7); i <= math.MaxInt64-2; i += 4 {
useString("foo")
}
for i := int64(math.MaxInt64 - 6); i <= math.MaxInt64-2; i += 4 {
useString("foo")
}
}
func d5() {
for i := int64(math.MinInt64 + 9); i > math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775803,-9223372036854775799\], increment 4"
useString("foo")
}
for i := int64(math.MinInt64 + 8); i > math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775804,-9223372036854775800\], increment 4"
useString("foo")
}
for i := int64(math.MinInt64 + 7); i > math.MinInt64+2; i -= 4 {
useString("foo")
}
for i := int64(math.MinInt64 + 6); i > math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775802,-9223372036854775802\], increment 4"
useString("foo")
}
for i := int64(math.MinInt64 + 9); i >= math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775803,-9223372036854775799\], increment 4"
useString("foo")
}
for i := int64(math.MinInt64 + 8); i >= math.MinInt64+2; i -= 4 { // ERROR "Induction variable: limits \[-9223372036854775804,-9223372036854775800\], increment 4"
useString("foo")
}
for i := int64(math.MinInt64 + 7); i >= math.MinInt64+2; i -= 4 {
useString("foo")
}
for i := int64(math.MinInt64 + 6); i >= math.MinInt64+2; i -= 4 {
useString("foo")
}
}
func bce1() {
// tests overflow of max-min
a := int64(9223372036854774057)
b := int64(-1547)
z := int64(1337)
if a%z == b%z {
panic("invalid test: modulos should differ")
}
for i := b; i < a; i += z { // ERROR "Induction variable: limits \[-1547,9223372036854772720\], increment 1337"
useString("foobar")
}
}
func nobce2(a string) {
for i := int64(0); i < int64(len(a)); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
}
for i := int64(0); i < int64(len(a))-31337; i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
}
for i := int64(0); i < int64(len(a))+int64(-1<<63); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
}
j := int64(len(a)) - 123
for i := int64(0); i < j+123+int64(-1<<63); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
useString(a[i:]) // ERROR "(\([0-9]+\) )?Proved IsSliceInBounds$"
}
for i := int64(0); i < j+122+int64(-1<<63); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
// len(a)-123+122+MinInt overflows when len(a) == 0, so a bound check is needed here
useString(a[i:])
}
}
func nobce3(a [100]int64) [100]int64 {
min := int64((-1) << 63)
max := int64((1 << 63) - 1)
for i := min; i < max; i++ { // ERROR "Induction variable: limits \[-9223372036854775808,9223372036854775807\), increment 1$"
}
return a
}
func issue26116a(a []int) {
// There is no induction variable here. The comparison is in the wrong direction.
for i := 3; i > 6; i++ {
a[i] = 0
}
for i := 7; i < 3; i-- {
a[i] = 1
}
}
func stride1(x *[7]int) int {
s := 0
for i := 0; i <= 8; i += 3 { // ERROR "Induction variable: limits \[0,6\], increment 3"
s += x[i] // ERROR "Proved IsInBounds"
}
return s
}
func stride2(x *[7]int) int {
s := 0
for i := 0; i < 9; i += 3 { // ERROR "Induction variable: limits \[0,6\], increment 3"
s += x[i] // ERROR "Proved IsInBounds"
}
return s
}
//go:noinline
func useString(a string) {
}
//go:noinline
func useSlice(a []int) {
}
func main() {
}
|
go/test/loopbce.go/0
|
{
"file_path": "go/test/loopbce.go",
"repo_id": "go",
"token_count": 6457
}
| 561 |
// run
// Copyright 2009 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.
// Test methods on slices.
package main
type T []int
func (t T) Len() int { return len(t) }
type I interface {
Len() int
}
func main() {
var t T = T{0, 1, 2, 3, 4}
var i I
i = t
if i.Len() != 5 {
println("i.Len", i.Len())
panic("fail")
}
if T.Len(t) != 5 {
println("T.Len", T.Len(t))
panic("fail")
}
if (*T).Len(&t) != 5 {
println("(*T).Len", (*T).Len(&t))
panic("fail")
}
}
|
go/test/method3.go/0
|
{
"file_path": "go/test/method3.go",
"repo_id": "go",
"token_count": 238
}
| 562 |
// errorcheck -0 -d=nil
//go:build !wasm && !aix
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that nil checks are removed.
// Optimization is enabled.
package p
func f5(p *float32, q *float64, r *float32, s *float64) float64 {
x := float64(*p) // ERROR "removed nil check"
y := *q // ERROR "removed nil check"
*r = 7 // ERROR "removed nil check"
*s = 9 // ERROR "removed nil check"
return x + y
}
type T struct{ b [29]byte }
func f6(p, q *T) {
x := *p // ERROR "removed nil check"
*q = x // ERROR "removed nil check"
}
// make sure to remove nil check for memory move (issue #18003)
func f8(t *struct{ b [8]int }) struct{ b [8]int } {
return *t // ERROR "removed nil check"
}
|
go/test/nilptr5.go/0
|
{
"file_path": "go/test/nilptr5.go",
"repo_id": "go",
"token_count": 323
}
| 563 |
// errorcheck -0 -d=ssa/prove/debug=1
//go:build amd64
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "math"
func f0(a []int) int {
a[0] = 1
a[0] = 1 // ERROR "Proved IsInBounds$"
a[6] = 1
a[6] = 1 // ERROR "Proved IsInBounds$"
a[5] = 1 // ERROR "Proved IsInBounds$"
a[5] = 1 // ERROR "Proved IsInBounds$"
return 13
}
func f1(a []int) int {
if len(a) <= 5 {
return 18
}
a[0] = 1 // ERROR "Proved IsInBounds$"
a[0] = 1 // ERROR "Proved IsInBounds$"
a[6] = 1
a[6] = 1 // ERROR "Proved IsInBounds$"
a[5] = 1 // ERROR "Proved IsInBounds$"
a[5] = 1 // ERROR "Proved IsInBounds$"
return 26
}
func f1b(a []int, i int, j uint) int {
if i >= 0 && i < len(a) {
return a[i] // ERROR "Proved IsInBounds$"
}
if i >= 10 && i < len(a) {
return a[i] // ERROR "Proved IsInBounds$"
}
if i >= 10 && i < len(a) {
return a[i] // ERROR "Proved IsInBounds$"
}
if i >= 10 && i < len(a) {
return a[i-10] // ERROR "Proved IsInBounds$"
}
if j < uint(len(a)) {
return a[j] // ERROR "Proved IsInBounds$"
}
return 0
}
func f1c(a []int, i int64) int {
c := uint64(math.MaxInt64 + 10) // overflows int
d := int64(c)
if i >= d && i < int64(len(a)) {
// d overflows, should not be handled.
return a[i]
}
return 0
}
func f2(a []int) int {
for i := range a { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
a[i+1] = i
a[i+1] = i // ERROR "Proved IsInBounds$"
}
return 34
}
func f3(a []uint) int {
for i := uint(0); i < uint(len(a)); i++ {
a[i] = i // ERROR "Proved IsInBounds$"
}
return 41
}
func f4a(a, b, c int) int {
if a < b {
if a == b { // ERROR "Disproved Eq64$"
return 47
}
if a > b { // ERROR "Disproved Less64$"
return 50
}
if a < b { // ERROR "Proved Less64$"
return 53
}
// We can't get to this point and prove knows that, so
// there's no message for the next (obvious) branch.
if a != a {
return 56
}
return 61
}
return 63
}
func f4b(a, b, c int) int {
if a <= b {
if a >= b {
if a == b { // ERROR "Proved Eq64$"
return 70
}
return 75
}
return 77
}
return 79
}
func f4c(a, b, c int) int {
if a <= b {
if a >= b {
if a != b { // ERROR "Disproved Neq64$"
return 73
}
return 75
}
return 77
}
return 79
}
func f4d(a, b, c int) int {
if a < b {
if a < c {
if a < b { // ERROR "Proved Less64$"
if a < c { // ERROR "Proved Less64$"
return 87
}
return 89
}
return 91
}
return 93
}
return 95
}
func f4e(a, b, c int) int {
if a < b {
if b > a { // ERROR "Proved Less64$"
return 101
}
return 103
}
return 105
}
func f4f(a, b, c int) int {
if a <= b {
if b > a {
if b == a { // ERROR "Disproved Eq64$"
return 112
}
return 114
}
if b >= a { // ERROR "Proved Leq64$"
if b == a { // ERROR "Proved Eq64$"
return 118
}
return 120
}
return 122
}
return 124
}
func f5(a, b uint) int {
if a == b {
if a <= b { // ERROR "Proved Leq64U$"
return 130
}
return 132
}
return 134
}
// These comparisons are compile time constants.
func f6a(a uint8) int {
if a < a { // ERROR "Disproved Less8U$"
return 140
}
return 151
}
func f6b(a uint8) int {
if a < a { // ERROR "Disproved Less8U$"
return 140
}
return 151
}
func f6x(a uint8) int {
if a > a { // ERROR "Disproved Less8U$"
return 143
}
return 151
}
func f6d(a uint8) int {
if a <= a { // ERROR "Proved Leq8U$"
return 146
}
return 151
}
func f6e(a uint8) int {
if a >= a { // ERROR "Proved Leq8U$"
return 149
}
return 151
}
func f7(a []int, b int) int {
if b < len(a) {
a[b] = 3
if b < len(a) { // ERROR "Proved Less64$"
a[b] = 5 // ERROR "Proved IsInBounds$"
}
}
return 161
}
func f8(a, b uint) int {
if a == b {
return 166
}
if a > b {
return 169
}
if a < b { // ERROR "Proved Less64U$"
return 172
}
return 174
}
func f9(a, b bool) int {
if a {
return 1
}
if a || b { // ERROR "Disproved Arg$"
return 2
}
return 3
}
func f10(a string) int {
n := len(a)
// We optimize comparisons with small constant strings (see cmd/compile/internal/gc/walk.go),
// so this string literal must be long.
if a[:n>>1] == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" {
return 0
}
return 1
}
func f11a(a []int, i int) {
useInt(a[i])
useInt(a[i]) // ERROR "Proved IsInBounds$"
}
func f11b(a []int, i int) {
useSlice(a[i:])
useSlice(a[i:]) // ERROR "Proved IsSliceInBounds$"
}
func f11c(a []int, i int) {
useSlice(a[:i])
useSlice(a[:i]) // ERROR "Proved IsSliceInBounds$"
}
func f11d(a []int, i int) {
useInt(a[2*i+7])
useInt(a[2*i+7]) // ERROR "Proved IsInBounds$"
}
func f12(a []int, b int) {
useSlice(a[:b])
}
func f13a(a, b, c int, x bool) int {
if a > 12 {
if x {
if a < 12 { // ERROR "Disproved Less64$"
return 1
}
}
if x {
if a <= 12 { // ERROR "Disproved Leq64$"
return 2
}
}
if x {
if a == 12 { // ERROR "Disproved Eq64$"
return 3
}
}
if x {
if a >= 12 { // ERROR "Proved Leq64$"
return 4
}
}
if x {
if a > 12 { // ERROR "Proved Less64$"
return 5
}
}
return 6
}
return 0
}
func f13b(a int, x bool) int {
if a == -9 {
if x {
if a < -9 { // ERROR "Disproved Less64$"
return 7
}
}
if x {
if a <= -9 { // ERROR "Proved Leq64$"
return 8
}
}
if x {
if a == -9 { // ERROR "Proved Eq64$"
return 9
}
}
if x {
if a >= -9 { // ERROR "Proved Leq64$"
return 10
}
}
if x {
if a > -9 { // ERROR "Disproved Less64$"
return 11
}
}
return 12
}
return 0
}
func f13c(a int, x bool) int {
if a < 90 {
if x {
if a < 90 { // ERROR "Proved Less64$"
return 13
}
}
if x {
if a <= 90 { // ERROR "Proved Leq64$"
return 14
}
}
if x {
if a == 90 { // ERROR "Disproved Eq64$"
return 15
}
}
if x {
if a >= 90 { // ERROR "Disproved Leq64$"
return 16
}
}
if x {
if a > 90 { // ERROR "Disproved Less64$"
return 17
}
}
return 18
}
return 0
}
func f13d(a int) int {
if a < 5 {
if a < 9 { // ERROR "Proved Less64$"
return 1
}
}
return 0
}
func f13e(a int) int {
if a > 9 {
if a > 5 { // ERROR "Proved Less64$"
return 1
}
}
return 0
}
func f13f(a, b int64) int64 {
if b != math.MaxInt64 {
return 42
}
if a > b {
if a == 0 { // ERROR "Disproved Eq64$"
return 1
}
}
return 0
}
func f13g(a int) int {
if a < 3 {
return 5
}
if a > 3 {
return 6
}
if a == 3 { // ERROR "Proved Eq64$"
return 7
}
return 8
}
func f13h(a int) int {
if a < 3 {
if a > 1 {
if a == 2 { // ERROR "Proved Eq64$"
return 5
}
}
}
return 0
}
func f13i(a uint) int {
if a == 0 {
return 1
}
if a > 0 { // ERROR "Proved Less64U$"
return 2
}
return 3
}
func f14(p, q *int, a []int) {
// This crazy ordering usually gives i1 the lowest value ID,
// j the middle value ID, and i2 the highest value ID.
// That used to confuse CSE because it ordered the args
// of the two + ops below differently.
// That in turn foiled bounds check elimination.
i1 := *p
j := *q
i2 := *p
useInt(a[i1+j])
useInt(a[i2+j]) // ERROR "Proved IsInBounds$"
}
func f15(s []int, x int) {
useSlice(s[x:])
useSlice(s[:x]) // ERROR "Proved IsSliceInBounds$"
}
func f16(s []int) []int {
if len(s) >= 10 {
return s[:10] // ERROR "Proved IsSliceInBounds$"
}
return nil
}
func f17(b []int) {
for i := 0; i < len(b); i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
// This tests for i <= cap, which we can only prove
// using the derived relation between len and cap.
// This depends on finding the contradiction, since we
// don't query this condition directly.
useSlice(b[:i]) // ERROR "Proved IsSliceInBounds$"
}
}
func f18(b []int, x int, y uint) {
_ = b[x]
_ = b[y]
if x > len(b) { // ERROR "Disproved Less64$"
return
}
if y > uint(len(b)) { // ERROR "Disproved Less64U$"
return
}
if int(y) > len(b) { // ERROR "Disproved Less64$"
return
}
}
func f19() (e int64, err error) {
// Issue 29502: slice[:0] is incorrectly disproved.
var stack []int64
stack = append(stack, 123)
if len(stack) > 1 {
panic("too many elements")
}
last := len(stack) - 1
e = stack[last]
// Buggy compiler prints "Disproved Leq64" for the next line.
stack = stack[:last]
return e, nil
}
func sm1(b []int, x int) {
// Test constant argument to slicemask.
useSlice(b[2:8]) // ERROR "Proved slicemask not needed$"
// Test non-constant argument with known limits.
if cap(b) > 10 {
useSlice(b[2:])
}
}
func lim1(x, y, z int) {
// Test relations between signed and unsigned limits.
if x > 5 {
if uint(x) > 5 { // ERROR "Proved Less64U$"
return
}
}
if y >= 0 && y < 4 {
if uint(y) > 4 { // ERROR "Disproved Less64U$"
return
}
if uint(y) < 5 { // ERROR "Proved Less64U$"
return
}
}
if z < 4 {
if uint(z) > 4 { // Not provable without disjunctions.
return
}
}
}
// fence1–4 correspond to the four fence-post implications.
func fence1(b []int, x, y int) {
// Test proofs that rely on fence-post implications.
if x+1 > y {
if x < y { // ERROR "Disproved Less64$"
return
}
}
if len(b) < cap(b) {
// This eliminates the growslice path.
b = append(b, 1) // ERROR "Disproved Less64U$"
}
}
func fence2(x, y int) {
if x-1 < y {
if x > y { // ERROR "Disproved Less64$"
return
}
}
}
func fence3(b, c []int, x, y int64) {
if x-1 >= y {
if x <= y { // Can't prove because x may have wrapped.
return
}
}
if x != math.MinInt64 && x-1 >= y {
if x <= y { // ERROR "Disproved Leq64$"
return
}
}
c[len(c)-1] = 0 // Can't prove because len(c) might be 0
if n := len(b); n > 0 {
b[n-1] = 0 // ERROR "Proved IsInBounds$"
}
}
func fence4(x, y int64) {
if x >= y+1 {
if x <= y {
return
}
}
if y != math.MaxInt64 && x >= y+1 {
if x <= y { // ERROR "Disproved Leq64$"
return
}
}
}
// Check transitive relations
func trans1(x, y int64) {
if x > 5 {
if y > x {
if y > 2 { // ERROR "Proved Less64$"
return
}
} else if y == x {
if y > 5 { // ERROR "Proved Less64$"
return
}
}
}
if x >= 10 {
if y > x {
if y > 10 { // ERROR "Proved Less64$"
return
}
}
}
}
func trans2(a, b []int, i int) {
if len(a) != len(b) {
return
}
_ = a[i]
_ = b[i] // ERROR "Proved IsInBounds$"
}
func trans3(a, b []int, i int) {
if len(a) > len(b) {
return
}
_ = a[i]
_ = b[i] // ERROR "Proved IsInBounds$"
}
func trans4(b []byte, x int) {
// Issue #42603: slice len/cap transitive relations.
switch x {
case 0:
if len(b) < 20 {
return
}
_ = b[:2] // ERROR "Proved IsSliceInBounds$"
case 1:
if len(b) < 40 {
return
}
_ = b[:2] // ERROR "Proved IsSliceInBounds$"
}
}
// Derived from nat.cmp
func natcmp(x, y []uint) (r int) {
m := len(x)
n := len(y)
if m != n || m == 0 {
return
}
i := m - 1
for i > 0 && // ERROR "Induction variable: limits \(0,\?\], increment 1$"
x[i] == // ERROR "Proved IsInBounds$"
y[i] { // ERROR "Proved IsInBounds$"
i--
}
switch {
case x[i] < // todo, cannot prove this because it's dominated by i<=0 || x[i]==y[i]
y[i]: // ERROR "Proved IsInBounds$"
r = -1
case x[i] > // ERROR "Proved IsInBounds$"
y[i]: // ERROR "Proved IsInBounds$"
r = 1
}
return
}
func suffix(s, suffix string) bool {
// todo, we're still not able to drop the bound check here in the general case
return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}
func constsuffix(s string) bool {
return suffix(s, "abc") // ERROR "Proved IsSliceInBounds$"
}
// oforuntil tests the pattern created by OFORUNTIL blocks. These are
// handled by addLocalInductiveFacts rather than findIndVar.
func oforuntil(b []int) {
i := 0
if len(b) > i {
top:
println(b[i]) // ERROR "Induction variable: limits \[0,\?\), increment 1$" "Proved IsInBounds$"
i++
if i < len(b) {
goto top
}
}
}
func atexit(foobar []func()) {
for i := len(foobar) - 1; i >= 0; i-- { // ERROR "Induction variable: limits \[0,\?\], increment 1"
f := foobar[i]
foobar = foobar[:i] // ERROR "IsSliceInBounds"
f()
}
}
func make1(n int) []int {
s := make([]int, n)
for i := 0; i < n; i++ { // ERROR "Induction variable: limits \[0,\?\), increment 1"
s[i] = 1 // ERROR "Proved IsInBounds$"
}
return s
}
func make2(n int) []int {
s := make([]int, n)
for i := range s { // ERROR "Induction variable: limits \[0,\?\), increment 1"
s[i] = 1 // ERROR "Proved IsInBounds$"
}
return s
}
// The range tests below test the index variable of range loops.
// range1 compiles to the "efficiently indexable" form of a range loop.
func range1(b []int) {
for i, v := range b { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
b[i] = v + 1 // ERROR "Proved IsInBounds$"
if i < len(b) { // ERROR "Proved Less64$"
println("x")
}
if i >= 0 { // ERROR "Proved Leq64$"
println("x")
}
}
}
// range2 elements are larger, so they use the general form of a range loop.
func range2(b [][32]int) {
for i, v := range b { // ERROR "Induction variable: limits \[0,\?\), increment 1$"
b[i][0] = v[0] + 1 // ERROR "Proved IsInBounds$"
if i < len(b) { // ERROR "Proved Less64$"
println("x")
}
if i >= 0 { // ERROR "Proved Leq64$"
println("x")
}
}
}
// signhint1-2 test whether the hint (int >= 0) is propagated into the loop.
func signHint1(i int, data []byte) {
if i >= 0 {
for i < len(data) { // ERROR "Induction variable: limits \[\?,\?\), increment 1$"
_ = data[i] // ERROR "Proved IsInBounds$"
i++
}
}
}
func signHint2(b []byte, n int) {
if n < 0 {
panic("")
}
_ = b[25]
for i := n; i <= 25; i++ { // ERROR "Induction variable: limits \[\?,25\], increment 1$"
b[i] = 123 // ERROR "Proved IsInBounds$"
}
}
// indexGT0 tests whether prove learns int index >= 0 from bounds check.
func indexGT0(b []byte, n int) {
_ = b[n]
_ = b[25]
for i := n; i <= 25; i++ { // ERROR "Induction variable: limits \[\?,25\], increment 1$"
b[i] = 123 // ERROR "Proved IsInBounds$"
}
}
// Induction variable in unrolled loop.
func unrollUpExcl(a []int) int {
var i, x int
for i = 0; i < len(a)-1; i += 2 { // ERROR "Induction variable: limits \[0,\?\), increment 2$"
x += a[i] // ERROR "Proved IsInBounds$"
x += a[i+1]
}
if i == len(a)-1 {
x += a[i]
}
return x
}
// Induction variable in unrolled loop.
func unrollUpIncl(a []int) int {
var i, x int
for i = 0; i <= len(a)-2; i += 2 { // ERROR "Induction variable: limits \[0,\?\], increment 2$"
x += a[i] // ERROR "Proved IsInBounds$"
x += a[i+1]
}
if i == len(a)-1 {
x += a[i]
}
return x
}
// Induction variable in unrolled loop.
func unrollDownExcl0(a []int) int {
var i, x int
for i = len(a) - 1; i > 0; i -= 2 { // ERROR "Induction variable: limits \(0,\?\], increment 2$"
x += a[i] // ERROR "Proved IsInBounds$"
x += a[i-1] // ERROR "Proved IsInBounds$"
}
if i == 0 {
x += a[i]
}
return x
}
// Induction variable in unrolled loop.
func unrollDownExcl1(a []int) int {
var i, x int
for i = len(a) - 1; i >= 1; i -= 2 { // ERROR "Induction variable: limits \(0,\?\], increment 2$"
x += a[i] // ERROR "Proved IsInBounds$"
x += a[i-1] // ERROR "Proved IsInBounds$"
}
if i == 0 {
x += a[i]
}
return x
}
// Induction variable in unrolled loop.
func unrollDownInclStep(a []int) int {
var i, x int
for i = len(a); i >= 2; i -= 2 { // ERROR "Induction variable: limits \[2,\?\], increment 2$"
x += a[i-1] // ERROR "Proved IsInBounds$"
x += a[i-2] // ERROR "Proved IsInBounds$"
}
if i == 1 {
x += a[i-1]
}
return x
}
// Not an induction variable (step too large)
func unrollExclStepTooLarge(a []int) int {
var i, x int
for i = 0; i < len(a)-1; i += 3 {
x += a[i]
x += a[i+1]
}
if i == len(a)-1 {
x += a[i]
}
return x
}
// Not an induction variable (step too large)
func unrollInclStepTooLarge(a []int) int {
var i, x int
for i = 0; i <= len(a)-2; i += 3 {
x += a[i]
x += a[i+1]
}
if i == len(a)-1 {
x += a[i]
}
return x
}
// Not an induction variable (min too small, iterating down)
func unrollDecMin(a []int, b int) int {
if b != math.MinInt64 {
return 42
}
var i, x int
for i = len(a); i >= b; i -= 2 {
x += a[i-1]
x += a[i-2]
}
if i == 1 { // ERROR "Disproved Eq64$"
x += a[i-1]
}
return x
}
// Not an induction variable (min too small, iterating up -- perhaps could allow, but why bother?)
func unrollIncMin(a []int, b int) int {
if b != math.MinInt64 {
return 42
}
var i, x int
for i = len(a); i >= b; i += 2 {
x += a[i-1]
x += a[i-2]
}
if i == 1 { // ERROR "Disproved Eq64$"
x += a[i-1]
}
return x
}
// The 4 xxxxExtNto64 functions below test whether prove is looking
// through value-preserving sign/zero extensions of index values (issue #26292).
// Look through all extensions
func signExtNto64(x []int, j8 int8, j16 int16, j32 int32) int {
if len(x) < 22 {
return 0
}
if j8 >= 0 && j8 < 22 {
return x[j8] // ERROR "Proved IsInBounds$"
}
if j16 >= 0 && j16 < 22 {
return x[j16] // ERROR "Proved IsInBounds$"
}
if j32 >= 0 && j32 < 22 {
return x[j32] // ERROR "Proved IsInBounds$"
}
return 0
}
func zeroExtNto64(x []int, j8 uint8, j16 uint16, j32 uint32) int {
if len(x) < 22 {
return 0
}
if j8 >= 0 && j8 < 22 {
return x[j8] // ERROR "Proved IsInBounds$"
}
if j16 >= 0 && j16 < 22 {
return x[j16] // ERROR "Proved IsInBounds$"
}
if j32 >= 0 && j32 < 22 {
return x[j32] // ERROR "Proved IsInBounds$"
}
return 0
}
// Process fence-post implications through 32to64 extensions (issue #29964)
func signExt32to64Fence(x []int, j int32) int {
if x[j] != 0 {
return 1
}
if j > 0 && x[j-1] != 0 { // ERROR "Proved IsInBounds$"
return 1
}
return 0
}
func zeroExt32to64Fence(x []int, j uint32) int {
if x[j] != 0 {
return 1
}
if j > 0 && x[j-1] != 0 { // ERROR "Proved IsInBounds$"
return 1
}
return 0
}
// Ensure that bounds checks with negative indexes are not incorrectly removed.
func negIndex() {
n := make([]int, 1)
for i := -1; i <= 0; i++ { // ERROR "Induction variable: limits \[-1,0\], increment 1$"
n[i] = 1
}
}
func negIndex2(n int) {
a := make([]int, 5)
b := make([]int, 5)
c := make([]int, 5)
for i := -1; i <= 0; i-- {
b[i] = i
n++
if n > 10 {
break
}
}
useSlice(a)
useSlice(c)
}
// Check that prove is zeroing these right shifts of positive ints by bit-width - 1.
// e.g (Rsh64x64 <t> n (Const64 <typ.UInt64> [63])) && ft.isNonNegative(n) -> 0
func sh64(n int64) int64 {
if n < 0 {
return n
}
return n >> 63 // ERROR "Proved Rsh64x64 shifts to zero"
}
func sh32(n int32) int32 {
if n < 0 {
return n
}
return n >> 31 // ERROR "Proved Rsh32x64 shifts to zero"
}
func sh32x64(n int32) int32 {
if n < 0 {
return n
}
return n >> uint64(31) // ERROR "Proved Rsh32x64 shifts to zero"
}
func sh16(n int16) int16 {
if n < 0 {
return n
}
return n >> 15 // ERROR "Proved Rsh16x64 shifts to zero"
}
func sh64noopt(n int64) int64 {
return n >> 63 // not optimized; n could be negative
}
// These cases are division of a positive signed integer by a power of 2.
// The opt pass doesnt have sufficient information to see that n is positive.
// So, instead, opt rewrites the division with a less-than-optimal replacement.
// Prove, which can see that n is nonnegative, cannot see the division because
// opt, an earlier pass, has already replaced it.
// The fix for this issue allows prove to zero a right shift that was added as
// part of the less-than-optimal reqwrite. That change by prove then allows
// lateopt to clean up all the unnecessary parts of the original division
// replacement. See issue #36159.
func divShiftClean(n int) int {
if n < 0 {
return n
}
return n / int(8) // ERROR "Proved Rsh64x64 shifts to zero"
}
func divShiftClean64(n int64) int64 {
if n < 0 {
return n
}
return n / int64(16) // ERROR "Proved Rsh64x64 shifts to zero"
}
func divShiftClean32(n int32) int32 {
if n < 0 {
return n
}
return n / int32(16) // ERROR "Proved Rsh32x64 shifts to zero"
}
// Bounds check elimination
func sliceBCE1(p []string, h uint) string {
if len(p) == 0 {
return ""
}
i := h & uint(len(p)-1)
return p[i] // ERROR "Proved IsInBounds$"
}
func sliceBCE2(p []string, h int) string {
if len(p) == 0 {
return ""
}
i := h & (len(p) - 1)
return p[i] // ERROR "Proved IsInBounds$"
}
func and(p []byte) ([]byte, []byte) { // issue #52563
const blocksize = 16
fullBlocks := len(p) &^ (blocksize - 1)
blk := p[:fullBlocks] // ERROR "Proved IsSliceInBounds$"
rem := p[fullBlocks:] // ERROR "Proved IsSliceInBounds$"
return blk, rem
}
func rshu(x, y uint) int {
z := x >> y
if z <= x { // ERROR "Proved Leq64U$"
return 1
}
return 0
}
func divu(x, y uint) int {
z := x / y
if z <= x { // ERROR "Proved Leq64U$"
return 1
}
return 0
}
func modu1(x, y uint) int {
z := x % y
if z < y { // ERROR "Proved Less64U$"
return 1
}
return 0
}
func modu2(x, y uint) int {
z := x % y
if z <= x { // ERROR "Proved Leq64U$"
return 1
}
return 0
}
func issue57077(s []int) (left, right []int) {
middle := len(s) / 2
left = s[:middle] // ERROR "Proved IsSliceInBounds$"
right = s[middle:] // ERROR "Proved IsSliceInBounds$"
return
}
func issue51622(b []byte) int {
if len(b) >= 3 && b[len(b)-3] == '#' { // ERROR "Proved IsInBounds$"
return len(b)
}
return 0
}
func issue45928(x int) {
combinedFrac := x / (x | (1 << 31)) // ERROR "Proved Neq64$"
useInt(combinedFrac)
}
//go:noinline
func useInt(a int) {
}
//go:noinline
func useSlice(a []int) {
}
func main() {
}
|
go/test/prove.go/0
|
{
"file_path": "go/test/prove.go",
"repo_id": "go",
"token_count": 9824
}
| 564 |
// errorcheck
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package p
var array *[10]int
var slice []int
var str string
var i, j, k int
func f() {
// check what missing arguments are allowed
_ = array[:]
_ = array[i:]
_ = array[:j]
_ = array[i:j]
_ = array[::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
_ = array[i::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
_ = array[:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
_ = array[i:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
_ = array[::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
_ = array[i::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
_ = array[:j:k]
_ = array[i:j:k]
_ = slice[:]
_ = slice[i:]
_ = slice[:j]
_ = slice[i:j]
_ = slice[::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
_ = slice[i::] // ERROR "middle index required in 3-index slice|invalid slice indices" "final index required in 3-index slice"
_ = slice[:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
_ = slice[i:j:] // ERROR "final index required in 3-index slice|invalid slice indices"
_ = slice[::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
_ = slice[i::k] // ERROR "middle index required in 3-index slice|invalid slice indices"
_ = slice[:j:k]
_ = slice[i:j:k]
_ = str[:]
_ = str[i:]
_ = str[:j]
_ = str[i:j]
_ = str[::] // ERROR "3-index slice of string" "middle index required in 3-index slice" "final index required in 3-index slice"
_ = str[i::] // ERROR "3-index slice of string" "middle index required in 3-index slice" "final index required in 3-index slice"
_ = str[:j:] // ERROR "3-index slice of string" "final index required in 3-index slice"
_ = str[i:j:] // ERROR "3-index slice of string" "final index required in 3-index slice"
_ = str[::k] // ERROR "3-index slice of string" "middle index required in 3-index slice"
_ = str[i::k] // ERROR "3-index slice of string" "middle index required in 3-index slice"
_ = str[:j:k] // ERROR "3-index slice of string"
_ = str[i:j:k] // ERROR "3-index slice of string"
// check invalid indices
_ = array[1:2]
_ = array[2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = array[2:2]
_ = array[i:1]
_ = array[1:j]
_ = array[1:2:3]
_ = array[1:3:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = array[2:1:3] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = array[2:3:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = array[3:1:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = array[3:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = array[i:1:2]
_ = array[i:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = array[1:j:2]
_ = array[2:j:1] // ERROR "invalid slice index|invalid slice indices"
_ = array[1:2:k]
_ = array[2:1:k] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[1:2]
_ = slice[2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[2:2]
_ = slice[i:1]
_ = slice[1:j]
_ = slice[1:2:3]
_ = slice[1:3:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[2:1:3] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[2:3:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[3:1:2] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[3:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[i:1:2]
_ = slice[i:2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[1:j:2]
_ = slice[2:j:1] // ERROR "invalid slice index|invalid slice indices"
_ = slice[1:2:k]
_ = slice[2:1:k] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = str[1:2]
_ = str[2:1] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = str[2:2]
_ = str[i:1]
_ = str[1:j]
// check out of bounds indices on array
_ = array[11:11] // ERROR "out of bounds"
_ = array[11:12] // ERROR "out of bounds"
_ = array[11:] // ERROR "out of bounds"
_ = array[:11] // ERROR "out of bounds"
_ = array[1:11] // ERROR "out of bounds"
_ = array[1:11:12] // ERROR "out of bounds"
_ = array[1:2:11] // ERROR "out of bounds"
_ = array[1:11:3] // ERROR "out of bounds|invalid slice index"
_ = array[11:2:3] // ERROR "out of bounds|inverted slice|invalid slice index"
_ = array[11:12:13] // ERROR "out of bounds"
// slice bounds not checked
_ = slice[11:11]
_ = slice[11:12]
_ = slice[11:]
_ = slice[:11]
_ = slice[1:11]
_ = slice[1:11:12]
_ = slice[1:2:11]
_ = slice[1:11:3] // ERROR "invalid slice index|invalid slice indices"
_ = slice[11:2:3] // ERROR "invalid slice index|invalid slice indices|inverted slice"
_ = slice[11:12:13]
}
|
go/test/slice3err.go/0
|
{
"file_path": "go/test/slice3err.go",
"repo_id": "go",
"token_count": 1944
}
| 565 |
// run
// Copyright 2009 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.
// Test switch statements.
package main
import "os"
func assert(cond bool, msg string) {
if !cond {
print("assertion fail: ", msg, "\n")
panic(1)
}
}
func main() {
i5 := 5
i7 := 7
hello := "hello"
switch true {
case i5 < 5:
assert(false, "<")
case i5 == 5:
assert(true, "!")
case i5 > 5:
assert(false, ">")
}
switch {
case i5 < 5:
assert(false, "<")
case i5 == 5:
assert(true, "!")
case i5 > 5:
assert(false, ">")
}
switch x := 5; true {
case i5 < x:
assert(false, "<")
case i5 == x:
assert(true, "!")
case i5 > x:
assert(false, ">")
}
switch x := 5; true {
case i5 < x:
assert(false, "<")
case i5 == x:
assert(true, "!")
case i5 > x:
assert(false, ">")
}
switch i5 {
case 0:
assert(false, "0")
case 1:
assert(false, "1")
case 2:
assert(false, "2")
case 3:
assert(false, "3")
case 4:
assert(false, "4")
case 5:
assert(true, "5")
case 6:
assert(false, "6")
case 7:
assert(false, "7")
case 8:
assert(false, "8")
case 9:
assert(false, "9")
default:
assert(false, "default")
}
switch i5 {
case 0, 1, 2, 3, 4:
assert(false, "4")
case 5:
assert(true, "5")
case 6, 7, 8, 9:
assert(false, "9")
default:
assert(false, "default")
}
switch i5 {
case 0:
case 1:
case 2:
case 3:
case 4:
assert(false, "4")
case 5:
assert(true, "5")
case 6:
case 7:
case 8:
case 9:
default:
assert(i5 == 5, "good")
}
switch i5 {
case 0:
dummy := 0
_ = dummy
fallthrough
case 1:
dummy := 0
_ = dummy
fallthrough
case 2:
dummy := 0
_ = dummy
fallthrough
case 3:
dummy := 0
_ = dummy
fallthrough
case 4:
dummy := 0
_ = dummy
assert(false, "4")
case 5:
dummy := 0
_ = dummy
fallthrough
case 6:
dummy := 0
_ = dummy
fallthrough
case 7:
dummy := 0
_ = dummy
fallthrough
case 8:
dummy := 0
_ = dummy
fallthrough
case 9:
dummy := 0
_ = dummy
fallthrough
default:
dummy := 0
_ = dummy
assert(i5 == 5, "good")
}
fired := false
switch i5 {
case 0:
dummy := 0
_ = dummy
fallthrough // tests scoping of cases
case 1:
dummy := 0
_ = dummy
fallthrough
case 2:
dummy := 0
_ = dummy
fallthrough
case 3:
dummy := 0
_ = dummy
fallthrough
case 4:
dummy := 0
_ = dummy
assert(false, "4")
case 5:
dummy := 0
_ = dummy
fallthrough
case 6:
dummy := 0
_ = dummy
fallthrough
case 7:
dummy := 0
_ = dummy
fallthrough
case 8:
dummy := 0
_ = dummy
fallthrough
case 9:
dummy := 0
_ = dummy
fallthrough
default:
dummy := 0
_ = dummy
fired = !fired
assert(i5 == 5, "good")
}
assert(fired, "fired")
count := 0
switch i5 {
case 0:
count = count + 1
fallthrough
case 1:
count = count + 1
fallthrough
case 2:
count = count + 1
fallthrough
case 3:
count = count + 1
fallthrough
case 4:
count = count + 1
assert(false, "4")
case 5:
count = count + 1
fallthrough
case 6:
count = count + 1
fallthrough
case 7:
count = count + 1
fallthrough
case 8:
count = count + 1
fallthrough
case 9:
count = count + 1
fallthrough
default:
assert(i5 == count, "good")
}
assert(fired, "fired")
switch hello {
case "wowie":
assert(false, "wowie")
case "hello":
assert(true, "hello")
case "jumpn":
assert(false, "jumpn")
default:
assert(false, "default")
}
fired = false
switch i := i5 + 2; i {
case i7:
fired = true
default:
assert(false, "fail")
}
assert(fired, "var")
// switch on nil-only comparison types
switch f := func() {}; f {
case nil:
assert(false, "f should not be nil")
default:
}
switch m := make(map[int]int); m {
case nil:
assert(false, "m should not be nil")
default:
}
switch a := make([]int, 1); a {
case nil:
assert(false, "m should not be nil")
default:
}
// switch on interface.
switch i := interface{}("hello"); i {
case 42:
assert(false, `i should be "hello"`)
case "hello":
assert(true, "hello")
default:
assert(false, `i should be "hello"`)
}
// switch on implicit bool converted to interface
// was broken: see issue 3980
switch i := interface{}(true); {
case i:
assert(true, "true")
case false:
assert(false, "i should be true")
default:
assert(false, "i should be true")
}
// switch on interface with constant cases differing by type.
// was rejected by compiler: see issue 4781
type T int
type B bool
type F float64
type S string
switch i := interface{}(float64(1.0)); i {
case nil:
assert(false, "i should be float64(1.0)")
case (*int)(nil):
assert(false, "i should be float64(1.0)")
case 1:
assert(false, "i should be float64(1.0)")
case T(1):
assert(false, "i should be float64(1.0)")
case F(1.0):
assert(false, "i should be float64(1.0)")
case 1.0:
assert(true, "true")
case "hello":
assert(false, "i should be float64(1.0)")
case S("hello"):
assert(false, "i should be float64(1.0)")
case true, B(false):
assert(false, "i should be float64(1.0)")
case false, B(true):
assert(false, "i should be float64(1.0)")
}
// switch on array.
switch ar := [3]int{1, 2, 3}; ar {
case [3]int{1, 2, 3}:
assert(true, "[1 2 3]")
case [3]int{4, 5, 6}:
assert(false, "ar should be [1 2 3]")
default:
assert(false, "ar should be [1 2 3]")
}
// switch on channel
switch c1, c2 := make(chan int), make(chan int); c1 {
case nil:
assert(false, "c1 did not match itself")
case c2:
assert(false, "c1 did not match itself")
case c1:
assert(true, "chan")
default:
assert(false, "c1 did not match itself")
}
// empty switch
switch {
}
// empty switch with default case.
fired = false
switch {
default:
fired = true
}
assert(fired, "fail")
// Default and fallthrough.
count = 0
switch {
default:
count++
fallthrough
case false:
count++
}
assert(count == 2, "fail")
// fallthrough to default, which is not at end.
count = 0
switch i5 {
case 5:
count++
fallthrough
default:
count++
case 6:
count++
}
assert(count == 2, "fail")
i := 0
switch x := 5; {
case i < x:
os.Exit(0)
case i == x:
case i > x:
os.Exit(1)
}
// Unified IR converts the tag and all case values to empty
// interface, when any of the case values aren't assignable to the
// tag value's type. Make sure that `case nil:` compares against the
// tag type's nil value (i.e., `(*int)(nil)`), not nil interface
// (i.e., `any(nil)`).
switch (*int)(nil) {
case nil:
// ok
case any(nil):
assert(false, "case any(nil) matched")
default:
assert(false, "default matched")
}
}
|
go/test/switch.go/0
|
{
"file_path": "go/test/switch.go",
"repo_id": "go",
"token_count": 2875
}
| 566 |
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type Numeric interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64 |
~complex64 | ~complex128
}
// numericAbs matches numeric types with an Abs method.
type numericAbs[T any] interface {
Numeric
Abs() T
}
// AbsDifference computes the absolute value of the difference of
// a and b, where the absolute value is determined by the Abs method.
func absDifference[T numericAbs[T]](a, b T) T {
d := a - b
return d.Abs()
}
// orderedNumeric matches numeric types that support the < operator.
type orderedNumeric interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64
}
// Complex matches the two complex types, which do not have a < operator.
type Complex interface {
~complex64 | ~complex128
}
// For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
// // orderedAbs is a helper type that defines an Abs method for
// // ordered numeric types.
// type orderedAbs[T orderedNumeric] T
//
// func (a orderedAbs[T]) Abs() orderedAbs[T] {
// if a < 0 {
// return -a
// }
// return a
// }
//
// // complexAbs is a helper type that defines an Abs method for
// // complex types.
// type complexAbs[T Complex] T
//
// func (a complexAbs[T]) Abs() complexAbs[T] {
// r := float64(real(a))
// i := float64(imag(a))
// d := math.Sqrt(r*r + i*i)
// return complexAbs[T](complex(d, 0))
// }
//
// // OrderedAbsDifference returns the absolute value of the difference
// // between a and b, where a and b are of an ordered type.
// func orderedAbsDifference[T orderedNumeric](a, b T) T {
// return T(absDifference(orderedAbs[T](a), orderedAbs[T](b)))
// }
//
// // ComplexAbsDifference returns the absolute value of the difference
// // between a and b, where a and b are of a complex type.
// func complexAbsDifference[T Complex](a, b T) T {
// return T(absDifference(complexAbs[T](a), complexAbs[T](b)))
// }
func main() {
// // For now, a lone type parameter is not permitted as RHS in a type declaration (issue #45639).
// if got, want := orderedAbsDifference(1.0, -2.0), 3.0; got != want {
// panic(fmt.Sprintf("got = %v, want = %v", got, want))
// }
// if got, want := orderedAbsDifference(-1.0, 2.0), 3.0; got != want {
// panic(fmt.Sprintf("got = %v, want = %v", got, want))
// }
// if got, want := orderedAbsDifference(-20, 15), 35; got != want {
// panic(fmt.Sprintf("got = %v, want = %v", got, want))
// }
//
// if got, want := complexAbsDifference(5.0+2.0i, 2.0-2.0i), 5+0i; got != want {
// panic(fmt.Sprintf("got = %v, want = %v", got, want))
// }
// if got, want := complexAbsDifference(2.0-2.0i, 5.0+2.0i), 5+0i; got != want {
// panic(fmt.Sprintf("got = %v, want = %v", got, want))
// }
}
|
go/test/typeparam/absdiff.go/0
|
{
"file_path": "go/test/typeparam/absdiff.go",
"repo_id": "go",
"token_count": 1089
}
| 567 |
// run
// 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 chans provides utility functions for working with channels.
package main
import (
"context"
"fmt"
"runtime"
"sort"
"sync"
"time"
)
// _Equal reports whether two slices are equal: the same length and all
// elements equal. All floating point NaNs are considered equal.
func _SliceEqual[Elem comparable](s1, s2 []Elem) bool {
if len(s1) != len(s2) {
return false
}
for i, v1 := range s1 {
v2 := s2[i]
if v1 != v2 {
isNaN := func(f Elem) bool { return f != f }
if !isNaN(v1) || !isNaN(v2) {
return false
}
}
}
return true
}
// _ReadAll reads from c until the channel is closed or the context is
// canceled, returning all the values read.
func _ReadAll[Elem any](ctx context.Context, c <-chan Elem) []Elem {
var r []Elem
for {
select {
case <-ctx.Done():
return r
case v, ok := <-c:
if !ok {
return r
}
r = append(r, v)
}
}
}
// _Merge merges two channels into a single channel.
// This will leave a goroutine running until either both channels are closed
// or the context is canceled, at which point the returned channel is closed.
func _Merge[Elem any](ctx context.Context, c1, c2 <-chan Elem) <-chan Elem {
r := make(chan Elem)
go func(ctx context.Context, c1, c2 <-chan Elem, r chan<- Elem) {
defer close(r)
for c1 != nil || c2 != nil {
select {
case <-ctx.Done():
return
case v1, ok := <-c1:
if ok {
r <- v1
} else {
c1 = nil
}
case v2, ok := <-c2:
if ok {
r <- v2
} else {
c2 = nil
}
}
}
}(ctx, c1, c2, r)
return r
}
// _Filter calls f on each value read from c. If f returns true the value
// is sent on the returned channel. This will leave a goroutine running
// until c is closed or the context is canceled, at which point the
// returned channel is closed.
func _Filter[Elem any](ctx context.Context, c <-chan Elem, f func(Elem) bool) <-chan Elem {
r := make(chan Elem)
go func(ctx context.Context, c <-chan Elem, f func(Elem) bool, r chan<- Elem) {
defer close(r)
for {
select {
case <-ctx.Done():
return
case v, ok := <-c:
if !ok {
return
}
if f(v) {
r <- v
}
}
}
}(ctx, c, f, r)
return r
}
// _Sink returns a channel that discards all values sent to it.
// This will leave a goroutine running until the context is canceled
// or the returned channel is closed.
func _Sink[Elem any](ctx context.Context) chan<- Elem {
r := make(chan Elem)
go func(ctx context.Context, r <-chan Elem) {
for {
select {
case <-ctx.Done():
return
case _, ok := <-r:
if !ok {
return
}
}
}
}(ctx, r)
return r
}
// An Exclusive is a value that may only be used by a single goroutine
// at a time. This is implemented using channels rather than a mutex.
type _Exclusive[Val any] struct {
c chan Val
}
// _MakeExclusive makes an initialized exclusive value.
func _MakeExclusive[Val any](initial Val) *_Exclusive[Val] {
r := &_Exclusive[Val]{
c: make(chan Val, 1),
}
r.c <- initial
return r
}
// _Acquire acquires the exclusive value for private use.
// It must be released using the Release method.
func (e *_Exclusive[Val]) Acquire() Val {
return <-e.c
}
// TryAcquire attempts to acquire the value. The ok result reports whether
// the value was acquired. If the value is acquired, it must be released
// using the Release method.
func (e *_Exclusive[Val]) TryAcquire() (v Val, ok bool) {
select {
case r := <-e.c:
return r, true
default:
return v, false
}
}
// Release updates and releases the value.
// This method panics if the value has not been acquired.
func (e *_Exclusive[Val]) Release(v Val) {
select {
case e.c <- v:
default:
panic("_Exclusive Release without Acquire")
}
}
// Ranger returns a Sender and a Receiver. The Receiver provides a
// Next method to retrieve values. The Sender provides a Send method
// to send values and a Close method to stop sending values. The Next
// method indicates when the Sender has been closed, and the Send
// method indicates when the Receiver has been freed.
//
// This is a convenient way to exit a goroutine sending values when
// the receiver stops reading them.
func _Ranger[Elem any]() (*_Sender[Elem], *_Receiver[Elem]) {
c := make(chan Elem)
d := make(chan struct{})
s := &_Sender[Elem]{
values: c,
done: d,
}
r := &_Receiver[Elem]{
values: c,
done: d,
}
runtime.SetFinalizer(r, (*_Receiver[Elem]).finalize)
return s, r
}
// A _Sender is used to send values to a Receiver.
type _Sender[Elem any] struct {
values chan<- Elem
done <-chan struct{}
}
// Send sends a value to the receiver. It reports whether the value was sent.
// The value will not be sent if the context is closed or the receiver
// is freed.
func (s *_Sender[Elem]) Send(ctx context.Context, v Elem) bool {
select {
case <-ctx.Done():
return false
case s.values <- v:
return true
case <-s.done:
return false
}
}
// Close tells the receiver that no more values will arrive.
// After Close is called, the _Sender may no longer be used.
func (s *_Sender[Elem]) Close() {
close(s.values)
}
// A _Receiver receives values from a _Sender.
type _Receiver[Elem any] struct {
values <-chan Elem
done chan<- struct{}
}
// Next returns the next value from the channel. The bool result indicates
// whether the value is valid.
func (r *_Receiver[Elem]) Next(ctx context.Context) (v Elem, ok bool) {
select {
case <-ctx.Done():
case v, ok = <-r.values:
}
return v, ok
}
// finalize is a finalizer for the receiver.
func (r *_Receiver[Elem]) finalize() {
close(r.done)
}
func TestReadAll() {
c := make(chan int)
go func() {
c <- 4
c <- 2
c <- 5
close(c)
}()
got := _ReadAll(context.Background(), c)
want := []int{4, 2, 5}
if !_SliceEqual(got, want) {
panic(fmt.Sprintf("_ReadAll returned %v, want %v", got, want))
}
}
func TestMerge() {
c1 := make(chan int)
c2 := make(chan int)
go func() {
c1 <- 1
c1 <- 3
c1 <- 5
close(c1)
}()
go func() {
c2 <- 2
c2 <- 4
c2 <- 6
close(c2)
}()
ctx := context.Background()
got := _ReadAll(ctx, _Merge(ctx, c1, c2))
sort.Ints(got)
want := []int{1, 2, 3, 4, 5, 6}
if !_SliceEqual(got, want) {
panic(fmt.Sprintf("_Merge returned %v, want %v", got, want))
}
}
func TestFilter() {
c := make(chan int)
go func() {
c <- 1
c <- 2
c <- 3
close(c)
}()
even := func(i int) bool { return i%2 == 0 }
ctx := context.Background()
got := _ReadAll(ctx, _Filter(ctx, c, even))
want := []int{2}
if !_SliceEqual(got, want) {
panic(fmt.Sprintf("_Filter returned %v, want %v", got, want))
}
}
func TestSink() {
c := _Sink[int](context.Background())
after := time.NewTimer(time.Minute)
defer after.Stop()
send := func(v int) {
select {
case c <- v:
case <-after.C:
panic("timed out sending to _Sink")
}
}
send(1)
send(2)
send(3)
close(c)
}
func TestExclusive() {
val := 0
ex := _MakeExclusive(&val)
var wg sync.WaitGroup
f := func() {
defer wg.Done()
for i := 0; i < 10; i++ {
p := ex.Acquire()
(*p)++
ex.Release(p)
}
}
wg.Add(2)
go f()
go f()
wg.Wait()
if val != 20 {
panic(fmt.Sprintf("after Acquire/Release loop got %d, want 20", val))
}
}
func TestExclusiveTry() {
s := ""
ex := _MakeExclusive(&s)
p, ok := ex.TryAcquire()
if !ok {
panic("TryAcquire failed")
}
*p = "a"
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
_, ok := ex.TryAcquire()
if ok {
panic(fmt.Sprintf("TryAcquire succeeded unexpectedly"))
}
}()
wg.Wait()
ex.Release(p)
p, ok = ex.TryAcquire()
if !ok {
panic(fmt.Sprintf("TryAcquire failed"))
}
}
func TestRanger() {
s, r := _Ranger[int]()
ctx := context.Background()
go func() {
// Receive one value then exit.
v, ok := r.Next(ctx)
if !ok {
panic(fmt.Sprintf("did not receive any values"))
} else if v != 1 {
panic(fmt.Sprintf("received %d, want 1", v))
}
}()
c1 := make(chan bool)
c2 := make(chan bool)
go func() {
defer close(c2)
if !s.Send(ctx, 1) {
panic(fmt.Sprintf("Send failed unexpectedly"))
}
close(c1)
if s.Send(ctx, 2) {
panic(fmt.Sprintf("Send succeeded unexpectedly"))
}
}()
<-c1
// Force a garbage collection to try to get the finalizers to run.
runtime.GC()
select {
case <-c2:
case <-time.After(time.Minute):
panic("_Ranger Send should have failed, but timed out")
}
}
func main() {
TestReadAll()
TestMerge()
TestFilter()
TestSink()
TestExclusive()
TestExclusiveTry()
TestRanger()
}
|
go/test/typeparam/chans.go/0
|
{
"file_path": "go/test/typeparam/chans.go",
"repo_id": "go",
"token_count": 3470
}
| 568 |
// run
// 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 main
func f[T any](x interface{}) T {
return x.(T)
}
func f2[T any](x interface{}) (T, bool) {
t, ok := x.(T)
return t, ok
}
type I interface {
foo()
}
type myint int
func (myint) foo() {
}
type myfloat float64
func (myfloat) foo() {
}
func g[T I](x I) T {
return x.(T)
}
func g2[T I](x I) (T, bool) {
t, ok := x.(T)
return t, ok
}
func h[T any](x interface{}) struct{ a, b T } {
return x.(struct{ a, b T })
}
func k[T any](x interface{}) interface{ bar() T } {
return x.(interface{ bar() T })
}
type mybar int
func (x mybar) bar() int {
return int(x)
}
func main() {
var i interface{} = int(3)
var j I = myint(3)
var x interface{} = float64(3)
var y I = myfloat(3)
println(f[int](i))
shouldpanic(func() { f[int](x) })
println(f2[int](i))
println(f2[int](x))
println(g[myint](j))
shouldpanic(func() { g[myint](y) })
println(g2[myint](j))
println(g2[myint](y))
println(h[int](struct{ a, b int }{3, 5}).a)
println(k[int](mybar(3)).bar())
type large struct {a,b,c,d,e,f int}
println(f[large](large{}).a)
l2, ok := f2[large](large{})
println(l2.a, ok)
}
func shouldpanic(x func()) {
defer func() {
e := recover()
if e == nil {
panic("didn't panic")
}
}()
x()
}
|
go/test/typeparam/dottype.go/0
|
{
"file_path": "go/test/typeparam/dottype.go",
"repo_id": "go",
"token_count": 611
}
| 569 |
// run
// 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 main
import (
"fmt"
)
type s[T any] struct {
a T
}
func (x s[T]) f() T {
return x.a
}
func main() {
x := s[int]{a: 7}
f := x.f
if got, want := f(), 7; got != want {
panic(fmt.Sprintf("got %d, want %d", got, want))
}
}
|
go/test/typeparam/issue45817.go/0
|
{
"file_path": "go/test/typeparam/issue45817.go",
"repo_id": "go",
"token_count": 165
}
| 570 |
// run
// 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 main
func main() {
d := diff([]int{}, func(int) string {
return "foo"
})
d()
}
func diff[T any](previous []T, uniqueKey func(T) string) func() {
return func() {
newJSON := map[string]T{}
for _, prev := range previous {
delete(newJSON, uniqueKey(prev))
}
}
}
|
go/test/typeparam/issue47676.go/0
|
{
"file_path": "go/test/typeparam/issue47676.go",
"repo_id": "go",
"token_count": 163
}
| 571 |
// run
// 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 main
type C[T any] struct {
}
func (c *C[T]) reset() {
}
func New[T any]() {
c := &C[T]{}
i = c.reset
z(c.reset)
}
var i interface{}
func z(interface{}) {
}
func main() {
New[int]()
}
|
go/test/typeparam/issue47775b.go/0
|
{
"file_path": "go/test/typeparam/issue47775b.go",
"repo_id": "go",
"token_count": 146
}
| 572 |
// run
// 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 main
type I[T any] interface {
foo()
}
type J[T any] interface {
foo()
bar()
}
//go:noinline
func f[T J[T]](x T, g func(T) T) I[T] {
// contains a cast between two nonempty interfaces
// Also make sure we don't evaluate g(x) twice.
return I[T](J[T](g(x)))
}
type S struct {
x int
}
func (s *S) foo() {}
func (s *S) bar() {}
var cnt int
func inc(s *S) *S {
cnt++
return s
}
func main() {
i := f(&S{x: 7}, inc)
if i.(*S).x != 7 {
panic("bad")
}
if cnt != 1 {
panic("multiple calls")
}
}
|
go/test/typeparam/issue47925d.go/0
|
{
"file_path": "go/test/typeparam/issue47925d.go",
"repo_id": "go",
"token_count": 285
}
| 573 |
// run
// 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 main
//go:noinline
func CopyMap[M interface{ ~map[K]V }, K comparable, V any](m M) M {
out := make(M, len(m))
for k, v := range m {
out[k] = v
}
return out
}
func main() {
var m map[*string]int
CopyMap(m)
}
|
go/test/typeparam/issue48453.go/0
|
{
"file_path": "go/test/typeparam/issue48453.go",
"repo_id": "go",
"token_count": 146
}
| 574 |
func(func(int) bool)
|
go/test/typeparam/issue48645a.out/0
|
{
"file_path": "go/test/typeparam/issue48645a.out",
"repo_id": "go",
"token_count": 9
}
| 575 |
// 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 a
type Option[T any] interface {
ToSeq() Seq[T]
}
type Seq[T any] []T
func (r Seq[T]) Find(p func(v T) bool) Option[T] {
panic("")
}
|
go/test/typeparam/issue49893.dir/a.go/0
|
{
"file_path": "go/test/typeparam/issue49893.dir/a.go",
"repo_id": "go",
"token_count": 110
}
| 576 |
// compile
// 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 main
type F func() F
func do[T any]() F {
return nil
}
type G[T any] func() G[T]
//go:noinline
func dog[T any]() G[T] {
return nil
}
func main() {
do[int]()
dog[int]()
}
|
go/test/typeparam/issue51832.go/0
|
{
"file_path": "go/test/typeparam/issue51832.go",
"repo_id": "go",
"token_count": 134
}
| 577 |
// compile
// 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 p
func F() *Cache[error] { return nil }
type Cache[T any] struct{ l *List[entry[T]] }
type entry[T any] struct{ value T }
type List[T any] struct{ len int }
func (c *Cache[V]) Len() int { return c.l.Len() }
func (l *List[T]) Len() int { return l.len }
|
go/test/typeparam/issue55101.go/0
|
{
"file_path": "go/test/typeparam/issue55101.go",
"repo_id": "go",
"token_count": 146
}
| 578 |
// 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 a
// SliceEqual reports whether two slices are equal: the same length and all
// elements equal. All floating point NaNs are considered equal.
func SliceEqual[Elem comparable](s1, s2 []Elem) bool {
if len(s1) != len(s2) {
return false
}
for i, v1 := range s1 {
v2 := s2[i]
if v1 != v2 {
isNaN := func(f Elem) bool { return f != f }
if !isNaN(v1) || !isNaN(v2) {
return false
}
}
}
return true
}
// Keys returns the keys of the map m.
// The keys will be an indeterminate order.
func Keys[K comparable, V any](m map[K]V) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
// Values returns the values of the map m.
// The values will be in an indeterminate order.
func Values[K comparable, V any](m map[K]V) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
// Equal reports whether two maps contain the same key/value pairs.
// Values are compared using ==.
func Equal[K, V comparable](m1, m2 map[K]V) bool {
if len(m1) != len(m2) {
return false
}
for k, v1 := range m1 {
if v2, ok := m2[k]; !ok || v1 != v2 {
return false
}
}
return true
}
// Copy returns a copy of m.
func Copy[K comparable, V any](m map[K]V) map[K]V {
r := make(map[K]V, len(m))
for k, v := range m {
r[k] = v
}
return r
}
// Add adds all key/value pairs in m2 to m1. Keys in m2 that are already
// present in m1 will be overwritten with the value in m2.
func Add[K comparable, V any](m1, m2 map[K]V) {
for k, v := range m2 {
m1[k] = v
}
}
// Sub removes all keys in m2 from m1. Keys in m2 that are not present
// in m1 are ignored. The values in m2 are ignored.
func Sub[K comparable, V any](m1, m2 map[K]V) {
for k := range m2 {
delete(m1, k)
}
}
// Intersect removes all keys from m1 that are not present in m2.
// Keys in m2 that are not in m1 are ignored. The values in m2 are ignored.
func Intersect[K comparable, V any](m1, m2 map[K]V) {
for k := range m1 {
if _, ok := m2[k]; !ok {
delete(m1, k)
}
}
}
// Filter deletes any key/value pairs from m for which f returns false.
func Filter[K comparable, V any](m map[K]V, f func(K, V) bool) {
for k, v := range m {
if !f(k, v) {
delete(m, k)
}
}
}
// TransformValues applies f to each value in m. The keys remain unchanged.
func TransformValues[K comparable, V any](m map[K]V, f func(V) V) {
for k, v := range m {
m[k] = f(v)
}
}
|
go/test/typeparam/mapsimp.dir/a.go/0
|
{
"file_path": "go/test/typeparam/mapsimp.dir/a.go",
"repo_id": "go",
"token_count": 1042
}
| 579 |
// run
// 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.
// Test that implicit conversions of derived types to interface type
// in range loops work correctly.
package main
import (
"fmt"
"reflect"
)
func main() {
test{"int", "V"}.match(RangeArrayAny[V]())
test{"int", "V"}.match(RangeArrayIface[V]())
test{"V"}.match(RangeChanAny[V]())
test{"V"}.match(RangeChanIface[V]())
test{"K", "V"}.match(RangeMapAny[K, V]())
test{"K", "V"}.match(RangeMapIface[K, V]())
test{"int", "V"}.match(RangeSliceAny[V]())
test{"int", "V"}.match(RangeSliceIface[V]())
}
type test []string
func (t test) match(args ...any) {
if len(t) != len(args) {
fmt.Printf("FAIL: want %v values, have %v\n", len(t), len(args))
return
}
for i, want := range t {
if have := reflect.TypeOf(args[i]).Name(); want != have {
fmt.Printf("FAIL: %v: want type %v, have %v\n", i, want, have)
}
}
}
type iface interface{ M() int }
type K int
type V int
func (K) M() int { return 0 }
func (V) M() int { return 0 }
func RangeArrayAny[V any]() (k, v any) {
for k, v = range [...]V{zero[V]()} {
}
return
}
func RangeArrayIface[V iface]() (k any, v iface) {
for k, v = range [...]V{zero[V]()} {
}
return
}
func RangeChanAny[V any]() (v any) {
for v = range chanOf(zero[V]()) {
}
return
}
func RangeChanIface[V iface]() (v iface) {
for v = range chanOf(zero[V]()) {
}
return
}
func RangeMapAny[K comparable, V any]() (k, v any) {
for k, v = range map[K]V{zero[K](): zero[V]()} {
}
return
}
func RangeMapIface[K interface {
iface
comparable
}, V iface]() (k, v iface) {
for k, v = range map[K]V{zero[K](): zero[V]()} {
}
return
}
func RangeSliceAny[V any]() (k, v any) {
for k, v = range []V{zero[V]()} {
}
return
}
func RangeSliceIface[V iface]() (k any, v iface) {
for k, v = range []V{zero[V]()} {
}
return
}
func chanOf[T any](elems ...T) chan T {
c := make(chan T, len(elems))
for _, elem := range elems {
c <- elem
}
close(c)
return c
}
func zero[T any]() (_ T) { return }
|
go/test/typeparam/mdempsky/17.go/0
|
{
"file_path": "go/test/typeparam/mdempsky/17.go",
"repo_id": "go",
"token_count": 913
}
| 580 |
panic: 5.3
panic: hello
|
go/test/typeparam/recoverimp.out/0
|
{
"file_path": "go/test/typeparam/recoverimp.out",
"repo_id": "go",
"token_count": 10
}
| 581 |
// compile
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file checks simple code using type parameters.
package smoketest
// type parameters for functions
func f1[P any]() {}
func f2[P1, P2 any, P3 any]() {}
func f3[P interface{}](x P, y T1[int]) {}
// function instantiations
var _ = f1[int]
var _ = f2[int, string, struct{}]
var _ = f3[bool]
// type parameters for types
type T1[P any] struct{}
type T2[P1, P2 any, P3 any] struct{}
type T3[P interface{}] interface{}
// type instantiations
type _ T1[int]
type _ T2[int, string, struct{}]
type _ T3[bool]
// methods
func (T1[P]) m1() {}
func (T1[_]) m2() {}
func (x T2[P1, P2, P3]) m() {}
// type lists
type _ interface {
m1()
m2()
int | float32 | string
m3()
}
// embedded instantiated types
type _ struct {
f1, f2 int
T1[int]
T2[int, string, struct{}]
T3[bool]
}
type _ interface {
m1()
m2()
T3[bool]
}
|
go/test/typeparam/smoketest.go/0
|
{
"file_path": "go/test/typeparam/smoketest.go",
"repo_id": "go",
"token_count": 418
}
| 582 |
T
int
int32/int16
struct{T,T}
other
T
int32/int16
T
int
|
go/test/typeparam/typeswitch1.out/0
|
{
"file_path": "go/test/typeparam/typeswitch1.out",
"repo_id": "go",
"token_count": 31
}
| 583 |
// run
// 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 main
import "fmt"
type value[T any] struct {
val T
}
func get[T any](v *value[T]) T {
return v.val
}
func set[T any](v *value[T], val T) {
v.val = val
}
func (v *value[T]) set(val T) {
v.val = val
}
func (v *value[T]) get() T {
return v.val
}
func main() {
var v1 value[int]
set(&v1, 1)
if got, want := get(&v1), 1; got != want {
panic(fmt.Sprintf("get() == %d, want %d", got, want))
}
v1.set(2)
if got, want := v1.get(), 2; got != want {
panic(fmt.Sprintf("get() == %d, want %d", got, want))
}
v1p := new(value[int])
set(v1p, 3)
if got, want := get(v1p), 3; got != want {
panic(fmt.Sprintf("get() == %d, want %d", got, want))
}
v1p.set(4)
if got, want := v1p.get(), 4; got != want {
panic(fmt.Sprintf("get() == %d, want %d", got, want))
}
var v2 value[string]
set(&v2, "a")
if got, want := get(&v2), "a"; got != want {
panic(fmt.Sprintf("get() == %q, want %q", got, want))
}
v2.set("b")
if got, want := get(&v2), "b"; got != want {
panic(fmt.Sprintf("get() == %q, want %q", got, want))
}
v2p := new(value[string])
set(v2p, "c")
if got, want := get(v2p), "c"; got != want {
panic(fmt.Sprintf("get() == %d, want %d", got, want))
}
v2p.set("d")
if got, want := v2p.get(), "d"; got != want {
panic(fmt.Sprintf("get() == %d, want %d", got, want))
}
}
|
go/test/typeparam/value.go/0
|
{
"file_path": "go/test/typeparam/value.go",
"repo_id": "go",
"token_count": 673
}
| 584 |
// run
// 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 main
import (
"math"
"unsafe"
)
const maxUintptr = 1 << (8 * unsafe.Sizeof(uintptr(0)))
func main() {
var p [10]byte
// unsafe.Add
{
p1 := unsafe.Pointer(&p[1])
assert(unsafe.Add(p1, 1) == unsafe.Pointer(&p[2]))
assert(unsafe.Add(p1, -1) == unsafe.Pointer(&p[0]))
}
// unsafe.Slice
{
s := unsafe.Slice(&p[0], len(p))
assert(&s[0] == &p[0])
assert(len(s) == len(p))
assert(cap(s) == len(p))
// nil pointer with zero length returns nil
assert(unsafe.Slice((*int)(nil), 0) == nil)
// nil pointer with positive length panics
mustPanic(func() { _ = unsafe.Slice((*int)(nil), 1) })
// negative length
var neg int = -1
mustPanic(func() { _ = unsafe.Slice(new(byte), neg) })
// length too large
var tooBig uint64 = math.MaxUint64
mustPanic(func() { _ = unsafe.Slice(new(byte), tooBig) })
// size overflows address space
mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8) })
mustPanic(func() { _ = unsafe.Slice(new(uint64), maxUintptr/8+1) })
// sliced memory overflows address space
last := (*byte)(unsafe.Pointer(^uintptr(0)))
_ = unsafe.Slice(last, 1)
mustPanic(func() { _ = unsafe.Slice(last, 2) })
}
// unsafe.String
{
s := unsafe.String(&p[0], len(p))
assert(s == string(p[:]))
assert(len(s) == len(p))
// the empty string
assert(unsafe.String(nil, 0) == "")
// nil pointer with positive length panics
mustPanic(func() { _ = unsafe.String(nil, 1) })
// negative length
var neg int = -1
mustPanic(func() { _ = unsafe.String(new(byte), neg) })
// length too large
var tooBig uint64 = math.MaxUint64
mustPanic(func() { _ = unsafe.String(new(byte), tooBig) })
// string memory overflows address space
last := (*byte)(unsafe.Pointer(^uintptr(0)))
_ = unsafe.String(last, 1)
mustPanic(func() { _ = unsafe.String(last, 2) })
}
// unsafe.StringData
{
var s = "string"
assert(string(unsafe.Slice(unsafe.StringData(s), len(s))) == s)
}
//unsafe.SliceData
{
var s = []byte("slice")
assert(unsafe.String(unsafe.SliceData(s), len(s)) == string(s))
}
}
func assert(ok bool) {
if !ok {
panic("FAIL")
}
}
func mustPanic(f func()) {
defer func() {
assert(recover() != nil)
}()
f()
}
|
go/test/unsafebuiltins.go/0
|
{
"file_path": "go/test/unsafebuiltins.go",
"repo_id": "go",
"token_count": 980
}
| 585 |
/*
Copyright 2013 Google Inc.
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 groupcache
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"github.com/golang/groupcache/consistenthash"
pb "github.com/golang/groupcache/groupcachepb"
"github.com/golang/protobuf/proto"
)
const defaultBasePath = "/_groupcache/"
const defaultReplicas = 50
// HTTPPool implements PeerPicker for a pool of HTTP peers.
type HTTPPool struct {
// Context optionally specifies a context for the server to use when it
// receives a request.
// If nil, the server uses the request's context
Context func(*http.Request) context.Context
// Transport optionally specifies an http.RoundTripper for the client
// to use when it makes a request.
// If nil, the client uses http.DefaultTransport.
Transport func(context.Context) http.RoundTripper
// this peer's base URL, e.g. "https://example.net:8000"
self string
// opts specifies the options.
opts HTTPPoolOptions
mu sync.Mutex // guards peers and httpGetters
peers *consistenthash.Map
httpGetters map[string]*httpGetter // keyed by e.g. "http://10.0.0.2:8008"
}
// HTTPPoolOptions are the configurations of a HTTPPool.
type HTTPPoolOptions struct {
// BasePath specifies the HTTP path that will serve groupcache requests.
// If blank, it defaults to "/_groupcache/".
BasePath string
// Replicas specifies the number of key replicas on the consistent hash.
// If blank, it defaults to 50.
Replicas int
// HashFn specifies the hash function of the consistent hash.
// If blank, it defaults to crc32.ChecksumIEEE.
HashFn consistenthash.Hash
}
// NewHTTPPool initializes an HTTP pool of peers, and registers itself as a PeerPicker.
// For convenience, it also registers itself as an http.Handler with http.DefaultServeMux.
// The self argument should be a valid base URL that points to the current server,
// for example "http://example.net:8000".
func NewHTTPPool(self string) *HTTPPool {
p := NewHTTPPoolOpts(self, nil)
http.Handle(p.opts.BasePath, p)
return p
}
var httpPoolMade bool
// NewHTTPPoolOpts initializes an HTTP pool of peers with the given options.
// Unlike NewHTTPPool, this function does not register the created pool as an HTTP handler.
// The returned *HTTPPool implements http.Handler and must be registered using http.Handle.
func NewHTTPPoolOpts(self string, o *HTTPPoolOptions) *HTTPPool {
if httpPoolMade {
panic("groupcache: NewHTTPPool must be called only once")
}
httpPoolMade = true
p := &HTTPPool{
self: self,
httpGetters: make(map[string]*httpGetter),
}
if o != nil {
p.opts = *o
}
if p.opts.BasePath == "" {
p.opts.BasePath = defaultBasePath
}
if p.opts.Replicas == 0 {
p.opts.Replicas = defaultReplicas
}
p.peers = consistenthash.New(p.opts.Replicas, p.opts.HashFn)
RegisterPeerPicker(func() PeerPicker { return p })
return p
}
// Set updates the pool's list of peers.
// Each peer value should be a valid base URL,
// for example "http://example.net:8000".
func (p *HTTPPool) Set(peers ...string) {
p.mu.Lock()
defer p.mu.Unlock()
p.peers = consistenthash.New(p.opts.Replicas, p.opts.HashFn)
p.peers.Add(peers...)
p.httpGetters = make(map[string]*httpGetter, len(peers))
for _, peer := range peers {
p.httpGetters[peer] = &httpGetter{transport: p.Transport, baseURL: peer + p.opts.BasePath}
}
}
func (p *HTTPPool) PickPeer(key string) (ProtoGetter, bool) {
p.mu.Lock()
defer p.mu.Unlock()
if p.peers.IsEmpty() {
return nil, false
}
if peer := p.peers.Get(key); peer != p.self {
return p.httpGetters[peer], true
}
return nil, false
}
func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Parse request.
if !strings.HasPrefix(r.URL.Path, p.opts.BasePath) {
panic("HTTPPool serving unexpected path: " + r.URL.Path)
}
parts := strings.SplitN(r.URL.Path[len(p.opts.BasePath):], "/", 2)
if len(parts) != 2 {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
groupName := parts[0]
key := parts[1]
// Fetch the value for this group/key.
group := GetGroup(groupName)
if group == nil {
http.Error(w, "no such group: "+groupName, http.StatusNotFound)
return
}
var ctx context.Context
if p.Context != nil {
ctx = p.Context(r)
} else {
ctx = r.Context()
}
group.Stats.ServerRequests.Add(1)
var value []byte
err := group.Get(ctx, key, AllocatingByteSliceSink(&value))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the value to the response body as a proto message.
body, err := proto.Marshal(&pb.GetResponse{Value: value})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/x-protobuf")
w.Write(body)
}
type httpGetter struct {
transport func(context.Context) http.RoundTripper
baseURL string
}
var bufferPool = sync.Pool{
New: func() interface{} { return new(bytes.Buffer) },
}
func (h *httpGetter) Get(ctx context.Context, in *pb.GetRequest, out *pb.GetResponse) error {
u := fmt.Sprintf(
"%v%v/%v",
h.baseURL,
url.QueryEscape(in.GetGroup()),
url.QueryEscape(in.GetKey()),
)
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
tr := http.DefaultTransport
if h.transport != nil {
tr = h.transport(ctx)
}
res, err := tr.RoundTrip(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("server returned: %v", res.Status)
}
b := bufferPool.Get().(*bytes.Buffer)
b.Reset()
defer bufferPool.Put(b)
_, err = io.Copy(b, res.Body)
if err != nil {
return fmt.Errorf("reading response body: %v", err)
}
err = proto.Unmarshal(b.Bytes(), out)
if err != nil {
return fmt.Errorf("decoding response body: %v", err)
}
return nil
}
|
groupcache/http.go/0
|
{
"file_path": "groupcache/http.go",
"repo_id": "groupcache",
"token_count": 2256
}
| 586 |
;;; golint.el --- lint for the Go source code
;; Copyright 2013 The Go Authors. All rights reserved.
;; License: BSD-3-clause
;; URL: https://github.com/golang/lint
;;; Commentary:
;; To install golint, add the following lines to your .emacs file:
;; (add-to-list 'load-path "PATH CONTAINING golint.el" t)
;; (require 'golint)
;;
;; After this, type M-x golint on Go source code.
;;
;; Usage:
;; C-x `
;; Jump directly to the line in your code which caused the first message.
;;
;; For more usage, see Compilation-Mode:
;; http://www.gnu.org/software/emacs/manual/html_node/emacs/Compilation-Mode.html
;;; Code:
(require 'compile)
(defun go-lint-buffer-name (mode)
"*Golint*")
(defun golint-process-setup ()
"Setup compilation variables and buffer for `golint'."
(run-hooks 'golint-setup-hook))
(define-compilation-mode golint-mode "golint"
"Golint is a linter for Go source code."
(set (make-local-variable 'compilation-scroll-output) nil)
(set (make-local-variable 'compilation-disable-input) t)
(set (make-local-variable 'compilation-process-setup-function)
'golint-process-setup))
;;;###autoload
(defun golint ()
"Run golint on the current file and populate the fix list.
Pressing \"C-x `\" jumps directly to the line in your code which
caused the first message."
(interactive)
(compilation-start
(mapconcat #'shell-quote-argument
(list "golint" (expand-file-name buffer-file-name)) " ")
'golint-mode))
(provide 'golint)
;;; golint.el ends here
|
lint/misc/emacs/golint.el/0
|
{
"file_path": "lint/misc/emacs/golint.el",
"repo_id": "lint",
"token_count": 561
}
| 587 |
// Test for not using fmt.Errorf or testing.Errorf.
// Package foo ...
package foo
import (
"errors"
"fmt"
"testing"
)
func f(x int) error {
if x > 10 {
return errors.New(fmt.Sprintf("something %d", x)) // MATCH /should replace.*errors\.New\(fmt\.Sprintf\(\.\.\.\)\).*fmt\.Errorf\(\.\.\.\)/ -> ` return fmt.Errorf("something %d", x)`
}
if x > 5 {
return errors.New(g("blah")) // ok
}
if x > 4 {
return errors.New("something else") // ok
}
return nil
}
// TestF is a dummy test
func TestF(t *testing.T) error {
x := 1
if x > 10 {
return t.Error(fmt.Sprintf("something %d", x)) // MATCH /should replace.*t\.Error\(fmt\.Sprintf\(\.\.\.\)\).*t\.Errorf\(\.\.\.\)/
}
if x > 5 {
return t.Error(g("blah")) // ok
}
if x > 4 {
return t.Error("something else") // ok
}
return nil
}
func g(s string) string { return "prefix: " + s }
|
lint/testdata/errorf.go/0
|
{
"file_path": "lint/testdata/errorf.go",
"repo_id": "lint",
"token_count": 362
}
| 588 |
// Test of time suffixes.
// Package foo ...
package foo
import (
"flag"
"time"
)
var rpcTimeoutMsec = flag.Duration("rpc_timeout", 100*time.Millisecond, "some flag") // MATCH /Msec.*\*time.Duration/
var timeoutSecs = 5 * time.Second // MATCH /Secs.*time.Duration/
|
lint/testdata/time.go/0
|
{
"file_path": "lint/testdata/time.go",
"repo_id": "lint",
"token_count": 99
}
| 589 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build android && (arm || 386 || amd64 || arm64)
// Package callfn provides an android entry point.
//
// It is a separate package from app because it contains Go assembly,
// which does not compile in a package using cgo.
package callfn
// CallFn calls a zero-argument function by its program counter.
// It is only intended for calling main.main. Using it for
// anything else will not end well.
func CallFn(fn uintptr)
|
mobile/app/internal/callfn/callfn.go/0
|
{
"file_path": "mobile/app/internal/callfn/callfn.go",
"repo_id": "mobile",
"token_count": 156
}
| 590 |
package bind
import (
"bytes"
"flag"
"go/ast"
"go/build"
"go/format"
"go/importer"
"go/parser"
"go/token"
"go/types"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"testing"
"golang.org/x/mobile/internal/importers"
"golang.org/x/mobile/internal/importers/java"
"golang.org/x/mobile/internal/importers/objc"
)
func init() {
log.SetFlags(log.Lshortfile)
}
var updateFlag = flag.Bool("update", false, "Update the golden files.")
var tests = []string{
"", // The universe package with the error type.
"testdata/basictypes.go",
"testdata/structs.go",
"testdata/interfaces.go",
"testdata/issue10788.go",
"testdata/issue12328.go",
"testdata/issue12403.go",
"testdata/issue29559.go",
"testdata/keywords.go",
"testdata/try.go",
"testdata/vars.go",
"testdata/ignore.go",
"testdata/doc.go",
"testdata/underscores.go",
}
var javaTests = []string{
"testdata/java.go",
"testdata/classes.go",
}
var objcTests = []string{
"testdata/objc.go",
"testdata/objcw.go",
}
var fset = token.NewFileSet()
func fileRefs(t *testing.T, filename string, pkgPrefix string) *importers.References {
f, err := parser.ParseFile(fset, filename, nil, parser.AllErrors)
if err != nil {
t.Fatalf("%s: %v", filename, err)
}
refs, err := importers.AnalyzeFile(f, pkgPrefix)
if err != nil {
t.Fatalf("%s: %v", filename, err)
}
fakePath := path.Dir(filename)
for i := range refs.Embedders {
refs.Embedders[i].PkgPath = fakePath
}
return refs
}
func typeCheck(t *testing.T, filename string, gopath string) (*types.Package, *ast.File) {
f, err := parser.ParseFile(fset, filename, nil, parser.AllErrors|parser.ParseComments)
if err != nil {
t.Fatalf("%s: %v", filename, err)
}
pkgName := filepath.Base(filename)
pkgName = strings.TrimSuffix(pkgName, ".go")
// typecheck and collect typechecker errors
var conf types.Config
conf.Error = func(err error) {
t.Error(err)
}
if gopath != "" {
conf.Importer = importer.Default()
oldDefault := build.Default
defer func() { build.Default = oldDefault }()
build.Default.GOPATH = gopath
}
pkg, err := conf.Check(pkgName, fset, []*ast.File{f}, nil)
if err != nil {
t.Fatal(err)
}
return pkg, f
}
// diff runs the command "diff a b" and returns its output
func diff(a, b string) string {
var buf bytes.Buffer
var cmd *exec.Cmd
switch runtime.GOOS {
case "plan9":
cmd = exec.Command("/bin/diff", "-c", a, b)
default:
cmd = exec.Command("/usr/bin/diff", "-u", a, b)
}
cmd.Stdout = &buf
cmd.Stderr = &buf
cmd.Run()
return buf.String()
}
func writeTempFile(t *testing.T, name string, contents []byte) string {
f, err := ioutil.TempFile("", name)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write(contents); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
return f.Name()
}
func TestGenObjc(t *testing.T) {
for _, filename := range tests {
var pkg *types.Package
var file *ast.File
if filename != "" {
pkg, file = typeCheck(t, filename, "")
}
var buf bytes.Buffer
g := &ObjcGen{
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte("\t")},
Fset: fset,
Files: []*ast.File{file},
Pkg: pkg,
},
}
if pkg != nil {
g.AllPkg = []*types.Package{pkg}
}
g.Init(nil)
testcases := []struct {
suffix string
gen func() error
}{
{
".objc.h.golden",
g.GenH,
},
{
".objc.m.golden",
g.GenM,
},
{
".objc.go.h.golden",
g.GenGoH,
},
}
for _, tc := range testcases {
buf.Reset()
if err := tc.gen(); err != nil {
t.Errorf("%s: %v", filename, err)
continue
}
out := writeTempFile(t, "generated"+tc.suffix, buf.Bytes())
defer os.Remove(out)
var golden string
if filename != "" {
golden = filename[:len(filename)-len(".go")]
} else {
golden = "testdata/universe"
}
golden += tc.suffix
if diffstr := diff(golden, out); diffstr != "" {
t.Errorf("%s: does not match Objective-C golden:\n%s", filename, diffstr)
if *updateFlag {
t.Logf("Updating %s...", golden)
err := exec.Command("/bin/cp", out, golden).Run()
if err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
}
}
func genObjcPackages(t *testing.T, dir string, cg *ObjcWrapper) {
pkgBase := filepath.Join(dir, "src", "ObjC")
if err := os.MkdirAll(pkgBase, 0700); err != nil {
t.Fatal(err)
}
for i, jpkg := range cg.Packages() {
pkgDir := filepath.Join(pkgBase, jpkg)
if err := os.MkdirAll(pkgDir, 0700); err != nil {
t.Fatal(err)
}
pkgFile := filepath.Join(pkgDir, "package.go")
cg.Buf.Reset()
cg.GenPackage(i)
if err := ioutil.WriteFile(pkgFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
}
cg.Buf.Reset()
cg.GenInterfaces()
clsFile := filepath.Join(pkgBase, "interfaces.go")
if err := ioutil.WriteFile(clsFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
gocmd := filepath.Join(runtime.GOROOT(), "bin", "go")
cmd := exec.Command(
gocmd,
"install",
"-pkgdir="+filepath.Join(dir, "pkg", build.Default.GOOS+"_"+build.Default.GOARCH),
"ObjC/...",
)
cmd.Env = append(os.Environ(), "GOPATH="+dir, "GO111MODULE=off")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("failed to go install the generated ObjC wrappers: %v: %s", err, string(out))
}
}
func genJavaPackages(t *testing.T, dir string, cg *ClassGen) {
buf := cg.Buf
cg.Buf = new(bytes.Buffer)
pkgBase := filepath.Join(dir, "src", "Java")
if err := os.MkdirAll(pkgBase, 0700); err != nil {
t.Fatal(err)
}
for i, jpkg := range cg.Packages() {
pkgDir := filepath.Join(pkgBase, jpkg)
if err := os.MkdirAll(pkgDir, 0700); err != nil {
t.Fatal(err)
}
pkgFile := filepath.Join(pkgDir, "package.go")
cg.Buf.Reset()
cg.GenPackage(i)
if err := ioutil.WriteFile(pkgFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
io.Copy(buf, cg.Buf)
}
cg.Buf.Reset()
cg.GenInterfaces()
clsFile := filepath.Join(pkgBase, "interfaces.go")
if err := ioutil.WriteFile(clsFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
io.Copy(buf, cg.Buf)
cg.Buf = buf
gocmd := filepath.Join(runtime.GOROOT(), "bin", "go")
cmd := exec.Command(
gocmd,
"install",
"-pkgdir="+filepath.Join(dir, "pkg", build.Default.GOOS+"_"+build.Default.GOARCH),
"Java/...",
)
cmd.Env = append(os.Environ(), "GOPATH="+dir, "GO111MODULE=off")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("failed to go install the generated Java wrappers: %v: %s", err, string(out))
}
}
func TestGenJava(t *testing.T) {
allTests := tests
if java.IsAvailable() {
allTests = append(append([]string{}, allTests...), javaTests...)
}
for _, filename := range allTests {
var pkg *types.Package
var file *ast.File
var buf bytes.Buffer
var cg *ClassGen
var classes []*java.Class
if filename != "" {
refs := fileRefs(t, filename, "Java/")
imp := &java.Importer{}
var err error
classes, err = imp.Import(refs)
if err != nil {
t.Fatal(err)
}
tmpGopath := ""
if len(classes) > 0 {
tmpGopath, err = ioutil.TempDir(os.TempDir(), "gomobile-bind-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpGopath)
cg = &ClassGen{
Printer: &Printer{
IndentEach: []byte("\t"),
Buf: new(bytes.Buffer),
},
}
cg.Init(classes, refs.Embedders)
genJavaPackages(t, tmpGopath, cg)
cg.Buf = &buf
}
pkg, file = typeCheck(t, filename, tmpGopath)
}
g := &JavaGen{
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte(" ")},
Fset: fset,
Files: []*ast.File{file},
Pkg: pkg,
},
}
if pkg != nil {
g.AllPkg = []*types.Package{pkg}
}
g.Init(classes)
testCases := []struct {
suffix string
gen func() error
}{
{
".java.golden",
func() error {
for i := range g.ClassNames() {
if err := g.GenClass(i); err != nil {
return err
}
}
return g.GenJava()
},
},
{
".java.c.golden",
func() error {
if cg != nil {
cg.GenC()
}
return g.GenC()
},
},
{
".java.h.golden",
func() error {
if cg != nil {
cg.GenH()
}
return g.GenH()
},
},
}
for _, tc := range testCases {
buf.Reset()
if err := tc.gen(); err != nil {
t.Errorf("%s: %v", filename, err)
continue
}
out := writeTempFile(t, "generated"+tc.suffix, buf.Bytes())
defer os.Remove(out)
var golden string
if filename != "" {
golden = filename[:len(filename)-len(".go")]
} else {
golden = "testdata/universe"
}
golden += tc.suffix
if diffstr := diff(golden, out); diffstr != "" {
t.Errorf("%s: does not match Java golden:\n%s", filename, diffstr)
if *updateFlag {
t.Logf("Updating %s...", golden)
if err := exec.Command("/bin/cp", out, golden).Run(); err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
}
}
func TestGenGo(t *testing.T) {
for _, filename := range tests {
var buf bytes.Buffer
var pkg *types.Package
if filename != "" {
pkg, _ = typeCheck(t, filename, "")
}
testGenGo(t, filename, &buf, pkg)
}
}
func TestGenGoJavaWrappers(t *testing.T) {
if !java.IsAvailable() {
t.Skipf("java is not available")
}
for _, filename := range javaTests {
var buf bytes.Buffer
refs := fileRefs(t, filename, "Java/")
imp := &java.Importer{}
classes, err := imp.Import(refs)
if err != nil {
t.Fatal(err)
}
tmpGopath, err := ioutil.TempDir(os.TempDir(), "gomobile-bind-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpGopath)
cg := &ClassGen{
Printer: &Printer{
IndentEach: []byte("\t"),
Buf: &buf,
},
}
cg.Init(classes, refs.Embedders)
genJavaPackages(t, tmpGopath, cg)
pkg, _ := typeCheck(t, filename, tmpGopath)
cg.GenGo()
testGenGo(t, filename, &buf, pkg)
}
}
func TestGenGoObjcWrappers(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skipf("can only generate objc wrappers on darwin")
}
for _, filename := range objcTests {
var buf bytes.Buffer
refs := fileRefs(t, filename, "ObjC/")
types, err := objc.Import(refs)
if err != nil {
t.Fatal(err)
}
tmpGopath, err := ioutil.TempDir(os.TempDir(), "gomobile-bind-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpGopath)
cg := &ObjcWrapper{
Printer: &Printer{
IndentEach: []byte("\t"),
Buf: &buf,
},
}
var genNames []string
for _, emb := range refs.Embedders {
genNames = append(genNames, emb.Name)
}
cg.Init(types, genNames)
genObjcPackages(t, tmpGopath, cg)
pkg, _ := typeCheck(t, filename, tmpGopath)
cg.GenGo()
testGenGo(t, filename, &buf, pkg)
}
}
func testGenGo(t *testing.T, filename string, buf *bytes.Buffer, pkg *types.Package) {
conf := &GeneratorConfig{
Writer: buf,
Fset: fset,
Pkg: pkg,
}
if pkg != nil {
conf.AllPkg = []*types.Package{pkg}
}
if err := GenGo(conf); err != nil {
t.Errorf("%s: %v", filename, err)
return
}
// TODO(hyangah): let GenGo format the generated go files.
out := writeTempFile(t, "go", gofmt(t, buf.Bytes()))
defer os.Remove(out)
golden := filename
if golden == "" {
golden = "testdata/universe"
}
golden += ".golden"
goldenContents, err := ioutil.ReadFile(golden)
if err != nil {
t.Fatalf("failed to read golden file: %v", err)
}
// format golden file using the current go version's formatting rule.
formattedGolden := writeTempFile(t, "go", gofmt(t, goldenContents))
defer os.Remove(formattedGolden)
if diffstr := diff(formattedGolden, out); diffstr != "" {
t.Errorf("%s: does not match Go golden:\n%s", filename, diffstr)
if *updateFlag {
t.Logf("Updating %s...", golden)
if err := exec.Command("/bin/cp", out, golden).Run(); err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
// gofmt formats the collection of Go source files auto-generated by gobind.
func gofmt(t *testing.T, src []byte) []byte {
t.Helper()
buf := &bytes.Buffer{}
mark := []byte(gobindPreamble)
for i, c := range bytes.Split(src, mark) {
if i == 0 {
buf.Write(c)
continue
}
tmp := append(mark, c...)
out, err := format.Source(tmp)
if err != nil {
t.Fatalf("failed to format Go file: error=%v\n----\n%s\n----", err, tmp)
}
if _, err := buf.Write(out); err != nil {
t.Fatalf("failed to write formatted file to buffer: %v", err)
}
}
return buf.Bytes()
}
func TestCustomPrefix(t *testing.T) {
const datafile = "testdata/customprefix.go"
pkg, file := typeCheck(t, datafile, "")
type testCase struct {
golden string
gen func(w io.Writer) error
}
var buf bytes.Buffer
jg := &JavaGen{
JavaPkg: "com.example",
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte(" ")},
Fset: fset,
AllPkg: []*types.Package{pkg},
Files: []*ast.File{file},
Pkg: pkg,
},
}
jg.Init(nil)
testCases := []testCase{
{
"testdata/customprefix.java.golden",
func(w io.Writer) error {
buf.Reset()
for i := range jg.ClassNames() {
if err := jg.GenClass(i); err != nil {
return err
}
}
if err := jg.GenJava(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix.java.h.golden",
func(w io.Writer) error {
buf.Reset()
if err := jg.GenH(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix.java.c.golden",
func(w io.Writer) error {
buf.Reset()
if err := jg.GenC(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
}
for _, pref := range []string{"EX", ""} {
og := &ObjcGen{
Prefix: pref,
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte(" ")},
Fset: fset,
AllPkg: []*types.Package{pkg},
Pkg: pkg,
},
}
og.Init(nil)
testCases = append(testCases, []testCase{
{
"testdata/customprefix" + pref + ".objc.go.h.golden",
func(w io.Writer) error {
buf.Reset()
if err := og.GenGoH(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix" + pref + ".objc.h.golden",
func(w io.Writer) error {
buf.Reset()
if err := og.GenH(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix" + pref + ".objc.m.golden",
func(w io.Writer) error {
buf.Reset()
if err := og.GenM(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
}...)
}
for _, tc := range testCases {
var buf bytes.Buffer
if err := tc.gen(&buf); err != nil {
t.Errorf("generating %s: %v", tc.golden, err)
continue
}
out := writeTempFile(t, "generated", buf.Bytes())
defer os.Remove(out)
if diffstr := diff(tc.golden, out); diffstr != "" {
t.Errorf("%s: generated file does not match:\b%s", tc.golden, diffstr)
if *updateFlag {
t.Logf("Updating %s...", tc.golden)
err := exec.Command("/bin/cp", out, tc.golden).Run()
if err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
}
func TestLowerFirst(t *testing.T) {
testCases := []struct {
in, want string
}{
{"", ""},
{"Hello", "hello"},
{"HelloGopher", "helloGopher"},
{"hello", "hello"},
{"ID", "id"},
{"IDOrName", "idOrName"},
{"ΓειαΣας", "γειαΣας"},
}
for _, tc := range testCases {
if got := lowerFirst(tc.in); got != tc.want {
t.Errorf("lowerFirst(%q) = %q; want %q", tc.in, got, tc.want)
}
}
}
// Test that typeName work for anonymous qualified fields.
func TestSelectorExprTypeName(t *testing.T) {
e, err := parser.ParseExprFrom(fset, "", "struct { bytes.Buffer }", 0)
if err != nil {
t.Fatal(err)
}
ft := e.(*ast.StructType).Fields.List[0].Type
if got, want := typeName(ft), "Buffer"; got != want {
t.Errorf("got: %q; want %q", got, want)
}
}
|
mobile/bind/bind_test.go/0
|
{
"file_path": "mobile/bind/bind_test.go",
"repo_id": "mobile",
"token_count": 7502
}
| 591 |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// C support functions for bindings. This file is copied into the
// generated gomobile_bind package and compiled along with the
// generated binding files.
#include <android/log.h>
#include <errno.h>
#include <jni.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "seq.h"
#include "_cgo_export.h"
#define NULL_REFNUM 41
// initClasses are only exported from Go if reverse bindings are used.
// If they're not, weakly define a no-op function.
__attribute__((weak)) void initClasses(void) { }
static JavaVM *jvm;
// jnienvs holds the per-thread JNIEnv* for Go threads where we called AttachCurrentThread.
// A pthread key destructor is supplied to call DetachCurrentThread on exit. This trick is
// documented in http://developer.android.com/training/articles/perf-jni.html under "Threads".
static pthread_key_t jnienvs;
static jclass seq_class;
static jmethodID seq_getRef;
static jmethodID seq_decRef;
static jmethodID seq_incRef;
static jmethodID seq_incGoObjectRef;
static jmethodID seq_incRefnum;
static jfieldID ref_objField;
static jclass throwable_class;
// env_destructor is registered as a thread data key destructor to
// clean up a Go thread that is attached to the JVM.
static void env_destructor(void *env) {
if ((*jvm)->DetachCurrentThread(jvm) != JNI_OK) {
LOG_INFO("failed to detach current thread");
}
}
static JNIEnv *go_seq_get_thread_env(void) {
JNIEnv *env;
jint ret = (*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_6);
if (ret != JNI_OK) {
if (ret != JNI_EDETACHED) {
LOG_FATAL("failed to get thread env");
}
if ((*jvm)->AttachCurrentThread(jvm, &env, NULL) != JNI_OK) {
LOG_FATAL("failed to attach current thread");
}
pthread_setspecific(jnienvs, env);
}
return env;
}
void go_seq_maybe_throw_exception(JNIEnv *env, jobject exc) {
if (exc != NULL) {
(*env)->Throw(env, exc);
}
}
jobject go_seq_get_exception(JNIEnv *env) {
jthrowable exc = (*env)->ExceptionOccurred(env);
if (!exc) {
return NULL;
}
(*env)->ExceptionClear(env);
return exc;
}
jbyteArray go_seq_to_java_bytearray(JNIEnv *env, nbyteslice s, int copy) {
if (s.ptr == NULL) {
return NULL;
}
jbyteArray res = (*env)->NewByteArray(env, s.len);
if (res == NULL) {
LOG_FATAL("NewByteArray failed");
}
(*env)->SetByteArrayRegion(env, res, 0, s.len, s.ptr);
if (copy) {
free(s.ptr);
}
return res;
}
#define surr1 0xd800
#define surr2 0xdc00
#define surr3 0xe000
// Unicode replacement character
#define replacementChar 0xFFFD
#define rune1Max ((1<<7) - 1)
#define rune2Max ((1<<11) - 1)
#define rune3Max ((1<<16) - 1)
// Maximum valid Unicode code point.
#define MaxRune 0x0010FFFF
#define surrogateMin 0xD800
#define surrogateMax 0xDFFF
// 0011 1111
#define maskx 0x3F
// 1000 0000
#define tx 0x80
// 1100 0000
#define t2 0xC0
// 1110 0000
#define t3 0xE0
// 1111 0000
#define t4 0xF0
// encode_rune writes into p (which must be large enough) the UTF-8 encoding
// of the rune. It returns the number of bytes written.
static int encode_rune(uint8_t *p, uint32_t r) {
if (r <= rune1Max) {
p[0] = (uint8_t)r;
return 1;
} else if (r <= rune2Max) {
p[0] = t2 | (uint8_t)(r>>6);
p[1] = tx | (((uint8_t)(r))&maskx);
return 2;
} else {
if (r > MaxRune || (surrogateMin <= r && r <= surrogateMax)) {
r = replacementChar;
}
if (r <= rune3Max) {
p[0] = t3 | (uint8_t)(r>>12);
p[1] = tx | (((uint8_t)(r>>6))&maskx);
p[2] = tx | (((uint8_t)(r))&maskx);
return 3;
} else {
p[0] = t4 | (uint8_t)(r>>18);
p[1] = tx | (((uint8_t)(r>>12))&maskx);
p[2] = tx | (((uint8_t)(r>>6))&maskx);
p[3] = tx | (((uint8_t)(r))&maskx);
return 4;
}
}
}
// utf16_decode decodes an array of UTF16 characters to a UTF-8 encoded
// nstring copy. The support functions and utf16_decode itself are heavily
// based on the unicode/utf8 and unicode/utf16 Go packages.
static nstring utf16_decode(jchar *chars, jsize len) {
jsize worstCaseLen = 4*len;
uint8_t *buf = malloc(worstCaseLen);
if (buf == NULL) {
LOG_FATAL("utf16Decode: malloc failed");
}
jsize nsrc = 0;
jsize ndst = 0;
while (nsrc < len) {
uint32_t r = chars[nsrc];
nsrc++;
if (surr1 <= r && r < surr2 && nsrc < len) {
uint32_t r2 = chars[nsrc];
if (surr2 <= r2 && r2 < surr3) {
nsrc++;
r = (((r-surr1)<<10) | (r2 - surr2)) + 0x10000;
}
}
if (ndst + 4 > worstCaseLen) {
LOG_FATAL("utf16Decode: buffer overflow");
}
ndst += encode_rune(buf + ndst, r);
}
struct nstring res = {.chars = buf, .len = ndst};
return res;
}
nstring go_seq_from_java_string(JNIEnv *env, jstring str) {
struct nstring res = {NULL, 0};
if (str == NULL) {
return res;
}
jsize nchars = (*env)->GetStringLength(env, str);
if (nchars == 0) {
return res;
}
jchar *chars = (jchar *)(*env)->GetStringChars(env, str, NULL);
if (chars == NULL) {
LOG_FATAL("GetStringChars failed");
}
nstring nstr = utf16_decode(chars, nchars);
(*env)->ReleaseStringChars(env, str, chars);
return nstr;
}
nbyteslice go_seq_from_java_bytearray(JNIEnv *env, jbyteArray arr, int copy) {
struct nbyteslice res = {NULL, 0};
if (arr == NULL) {
return res;
}
jsize len = (*env)->GetArrayLength(env, arr);
if (len == 0) {
return res;
}
jbyte *ptr = (*env)->GetByteArrayElements(env, arr, NULL);
if (ptr == NULL) {
LOG_FATAL("GetByteArrayElements failed");
}
if (copy) {
void *ptr_copy = (void *)malloc(len);
if (ptr_copy == NULL) {
LOG_FATAL("malloc failed");
}
memcpy(ptr_copy, ptr, len);
(*env)->ReleaseByteArrayElements(env, arr, ptr, JNI_ABORT);
ptr = (jbyte *)ptr_copy;
}
res.ptr = ptr;
res.len = len;
return res;
}
int32_t go_seq_to_refnum_go(JNIEnv *env, jobject o) {
if (o == NULL) {
return NULL_REFNUM;
}
return (int32_t)(*env)->CallStaticIntMethod(env, seq_class, seq_incGoObjectRef, o);
}
int32_t go_seq_to_refnum(JNIEnv *env, jobject o) {
if (o == NULL) {
return NULL_REFNUM;
}
return (int32_t)(*env)->CallStaticIntMethod(env, seq_class, seq_incRef, o);
}
int32_t go_seq_unwrap(jint refnum) {
JNIEnv *env = go_seq_push_local_frame(0);
jobject jobj = go_seq_from_refnum(env, refnum, NULL, NULL);
int32_t goref = go_seq_to_refnum_go(env, jobj);
go_seq_pop_local_frame(env);
return goref;
}
jobject go_seq_from_refnum(JNIEnv *env, int32_t refnum, jclass proxy_class, jmethodID proxy_cons) {
if (refnum == NULL_REFNUM) {
return NULL;
}
if (refnum < 0) { // Go object
// return new <Proxy>(refnum)
return (*env)->NewObject(env, proxy_class, proxy_cons, refnum);
}
// Seq.Ref ref = Seq.getRef(refnum)
jobject ref = (*env)->CallStaticObjectMethod(env, seq_class, seq_getRef, (jint)refnum);
if (ref == NULL) {
LOG_FATAL("Unknown reference: %d", refnum);
}
// Go incremented the reference count just before passing the refnum. Decrement it here.
(*env)->CallStaticVoidMethod(env, seq_class, seq_decRef, (jint)refnum);
// return ref.obj
return (*env)->GetObjectField(env, ref, ref_objField);
}
// go_seq_to_java_string converts a nstring to a jstring.
jstring go_seq_to_java_string(JNIEnv *env, nstring str) {
jstring s = (*env)->NewString(env, str.chars, str.len/2);
if (str.chars != NULL) {
free(str.chars);
}
return s;
}
// go_seq_push_local_frame retrieves or creates the JNIEnv* for the current thread
// and pushes a JNI reference frame. Must be matched with call to go_seq_pop_local_frame.
JNIEnv *go_seq_push_local_frame(jint nargs) {
JNIEnv *env = go_seq_get_thread_env();
// Given the number of function arguments, compute a conservative bound for the minimal frame size.
// Assume two slots for each per parameter (Seq.Ref and Seq.Object) and add extra
// extra space for the receiver, the return value, and exception (if any).
jint frameSize = 2*nargs + 10;
if ((*env)->PushLocalFrame(env, frameSize) < 0) {
LOG_FATAL("PushLocalFrame failed");
}
return env;
}
// Pop the current local frame, freeing all JNI local references in it
void go_seq_pop_local_frame(JNIEnv *env) {
(*env)->PopLocalFrame(env, NULL);
}
void go_seq_inc_ref(int32_t ref) {
JNIEnv *env = go_seq_get_thread_env();
(*env)->CallStaticVoidMethod(env, seq_class, seq_incRefnum, (jint)ref);
}
void go_seq_dec_ref(int32_t ref) {
JNIEnv *env = go_seq_get_thread_env();
(*env)->CallStaticVoidMethod(env, seq_class, seq_decRef, (jint)ref);
}
JNIEXPORT void JNICALL
Java_go_Seq_init(JNIEnv *env, jclass clazz) {
if ((*env)->GetJavaVM(env, &jvm) != 0) {
LOG_FATAL("failed to get JVM");
}
if (pthread_key_create(&jnienvs, env_destructor) != 0) {
LOG_FATAL("failed to initialize jnienvs thread local storage");
}
seq_class = (*env)->NewGlobalRef(env, clazz);
seq_getRef = (*env)->GetStaticMethodID(env, seq_class, "getRef", "(I)Lgo/Seq$Ref;");
if (seq_getRef == NULL) {
LOG_FATAL("failed to find method Seq.getRef");
}
seq_decRef = (*env)->GetStaticMethodID(env, seq_class, "decRef", "(I)V");
if (seq_decRef == NULL) {
LOG_FATAL("failed to find method Seq.decRef");
}
seq_incRefnum = (*env)->GetStaticMethodID(env, seq_class, "incRefnum", "(I)V");
if (seq_incRefnum == NULL) {
LOG_FATAL("failed to find method Seq.incRefnum");
}
seq_incRef = (*env)->GetStaticMethodID(env, seq_class, "incRef", "(Ljava/lang/Object;)I");
if (seq_incRef == NULL) {
LOG_FATAL("failed to find method Seq.incRef");
}
seq_incGoObjectRef = (*env)->GetStaticMethodID(env, seq_class, "incGoObjectRef", "(Lgo/Seq$GoObject;)I");
if (seq_incGoObjectRef == NULL) {
LOG_FATAL("failed to find method Seq.incGoObjectRef");
}
jclass ref_class = (*env)->FindClass(env, "go/Seq$Ref");
if (ref_class == NULL) {
LOG_FATAL("failed to find the Seq.Ref class");
}
ref_objField = (*env)->GetFieldID(env, ref_class, "obj", "Ljava/lang/Object;");
if (ref_objField == NULL) {
LOG_FATAL("failed to find the Seq.Ref.obj field");
}
initClasses();
}
JNIEXPORT void JNICALL
Java_go_Seq_destroyRef(JNIEnv *env, jclass clazz, jint refnum) {
DestroyRef(refnum);
}
JNIEXPORT void JNICALL
Java_go_Seq_incGoRef(JNIEnv *env, jclass clazz, jint refnum, jobject ref) {
IncGoRef(refnum);
}
jclass go_seq_find_class(const char *name) {
JNIEnv *env = go_seq_push_local_frame(0);
jclass clazz = (*env)->FindClass(env, name);
if (clazz == NULL) {
(*env)->ExceptionClear(env);
} else {
clazz = (*env)->NewGlobalRef(env, clazz);
}
go_seq_pop_local_frame(env);
return clazz;
}
jmethodID go_seq_get_static_method_id(jclass clazz, const char *name, const char *sig) {
JNIEnv *env = go_seq_push_local_frame(0);
jmethodID m = (*env)->GetStaticMethodID(env, clazz, name, sig);
if (m == NULL) {
(*env)->ExceptionClear(env);
}
go_seq_pop_local_frame(env);
return m;
}
jmethodID go_seq_get_method_id(jclass clazz, const char *name, const char *sig) {
JNIEnv *env = go_seq_push_local_frame(0);
jmethodID m = (*env)->GetMethodID(env, clazz, name, sig);
if (m == NULL) {
(*env)->ExceptionClear(env);
}
go_seq_pop_local_frame(env);
return m;
}
void go_seq_release_byte_array(JNIEnv *env, jbyteArray arr, jbyte* ptr) {
if (ptr != NULL) {
(*env)->ReleaseByteArrayElements(env, arr, ptr, 0);
}
}
int go_seq_isinstanceof(jint refnum, jclass clazz) {
JNIEnv *env = go_seq_push_local_frame(0);
jobject obj = go_seq_from_refnum(env, refnum, NULL, NULL);
jboolean isinst = (*env)->IsInstanceOf(env, obj, clazz);
go_seq_pop_local_frame(env);
return isinst;
}
|
mobile/bind/java/seq_android.c.support/0
|
{
"file_path": "mobile/bind/java/seq_android.c.support",
"repo_id": "mobile",
"token_count": 4790
}
| 592 |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package seq
//#cgo LDFLAGS: -llog
//#include <android/log.h>
//#include <string.h>
//import "C"
import (
"fmt"
"runtime"
"sync"
)
type countedObj struct {
obj interface{}
cnt int32
}
// also known to bind/java/Seq.java and bind/objc/seq_darwin.m
const NullRefNum = 41
// refs stores Go objects that have been passed to another language.
var refs struct {
sync.Mutex
next int32 // next reference number to use for Go object, always negative
refs map[interface{}]int32
objs map[int32]countedObj
}
func init() {
refs.Lock()
refs.next = -24 // Go objects get negative reference numbers. Arbitrary starting point.
refs.refs = make(map[interface{}]int32)
refs.objs = make(map[int32]countedObj)
refs.Unlock()
}
// A Ref represents a Java or Go object passed across the language
// boundary.
type Ref struct {
Bind_Num int32
}
type proxy interface {
// Use a strange name and hope that user code does not implement it
Bind_proxy_refnum__() int32
}
// ToRefNum increments the reference count for an object and
// returns its refnum.
func ToRefNum(obj interface{}) int32 {
// We don't track foreign objects, so if obj is a proxy
// return its refnum.
if r, ok := obj.(proxy); ok {
refnum := r.Bind_proxy_refnum__()
if refnum <= 0 {
panic(fmt.Errorf("seq: proxy contained invalid Go refnum: %d", refnum))
}
return refnum
}
refs.Lock()
num := refs.refs[obj]
if num != 0 {
s := refs.objs[num]
refs.objs[num] = countedObj{s.obj, s.cnt + 1}
} else {
num = refs.next
refs.next--
if refs.next > 0 {
panic("refs.next underflow")
}
refs.refs[obj] = num
refs.objs[num] = countedObj{obj, 1}
}
refs.Unlock()
return num
}
// FromRefNum returns the Ref for a refnum. If the refnum specifies a
// foreign object, a finalizer is set to track its lifetime.
func FromRefNum(num int32) *Ref {
if num == NullRefNum {
return nil
}
ref := &Ref{num}
if num > 0 {
// This is a foreign object reference.
// Track its lifetime with a finalizer.
runtime.SetFinalizer(ref, FinalizeRef)
}
return ref
}
// Bind_IncNum increments the foreign reference count and
// return the refnum.
func (r *Ref) Bind_IncNum() int32 {
refnum := r.Bind_Num
IncForeignRef(refnum)
// Make sure this reference is not finalized before
// the foreign reference count is incremented.
runtime.KeepAlive(r)
return refnum
}
// Get returns the underlying object.
func (r *Ref) Get() interface{} {
refnum := r.Bind_Num
refs.Lock()
o, ok := refs.objs[refnum]
refs.Unlock()
if !ok {
panic(fmt.Sprintf("unknown ref %d", refnum))
}
// This is a Go reference and its refnum was incremented
// before crossing the language barrier.
Delete(refnum)
return o.obj
}
// Inc increments the reference count for a refnum. Called from Bind_proxy_refnum
// functions.
func Inc(num int32) {
refs.Lock()
o, ok := refs.objs[num]
if !ok {
panic(fmt.Sprintf("seq.Inc: unknown refnum: %d", num))
}
refs.objs[num] = countedObj{o.obj, o.cnt + 1}
refs.Unlock()
}
// Delete decrements the reference count and removes the pinned object
// from the object map when the reference count becomes zero.
func Delete(num int32) {
refs.Lock()
defer refs.Unlock()
o, ok := refs.objs[num]
if !ok {
panic(fmt.Sprintf("seq.Delete unknown refnum: %d", num))
}
if o.cnt <= 1 {
delete(refs.objs, num)
delete(refs.refs, o.obj)
} else {
refs.objs[num] = countedObj{o.obj, o.cnt - 1}
}
}
|
mobile/bind/seq/ref.go/0
|
{
"file_path": "mobile/bind/seq/ref.go",
"repo_id": "mobile",
"token_count": 1328
}
| 593 |
// Code generated by gobind. DO NOT EDIT.
#include <jni.h>
#include "seq.h"
#include "classes.h"
static jclass class_java_lang_Runnable;
static jmethodID m_java_lang_Runnable_run;
static jclass class_java_io_InputStream;
static jmethodID m_java_io_InputStream_read__;
static jmethodID m_java_io_InputStream_read___3B;
static jmethodID m_java_io_InputStream_read___3BII;
static jmethodID m_java_io_InputStream_toString;
static jclass class_java_util_concurrent_Future;
static jmethodID m_java_util_concurrent_Future_get__;
static jmethodID m_java_util_concurrent_Future_get__JLjava_util_concurrent_TimeUnit_2;
static jclass class_java_lang_Object;
static jmethodID m_java_lang_Object_toString;
static jclass class_java_util_concurrent_TimeUnit;
static jmethodID m_java_util_concurrent_TimeUnit_toString;
static jclass class_java_util_Spliterators;
static jmethodID m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_2;
static jmethodID m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfInt_2;
static jmethodID m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfLong_2;
static jmethodID m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfDouble_2;
static jmethodID m_java_util_Spliterators_toString;
ret_jint cproxy_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_2(jint a0) {
JNIEnv *env = go_seq_push_local_frame(1);
jobject _a0 = go_seq_from_refnum(env, a0, NULL, NULL);
jobject res = (*env)->CallStaticObjectMethod(env, class_java_util_Spliterators, m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_2, _a0);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfInt_2(jint a0) {
JNIEnv *env = go_seq_push_local_frame(1);
jobject _a0 = go_seq_from_refnum(env, a0, NULL, NULL);
jobject res = (*env)->CallStaticObjectMethod(env, class_java_util_Spliterators, m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfInt_2, _a0);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfLong_2(jint a0) {
JNIEnv *env = go_seq_push_local_frame(1);
jobject _a0 = go_seq_from_refnum(env, a0, NULL, NULL);
jobject res = (*env)->CallStaticObjectMethod(env, class_java_util_Spliterators, m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfLong_2, _a0);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfDouble_2(jint a0) {
JNIEnv *env = go_seq_push_local_frame(1);
jobject _a0 = go_seq_from_refnum(env, a0, NULL, NULL);
jobject res = (*env)->CallStaticObjectMethod(env, class_java_util_Spliterators, m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfDouble_2, _a0);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
static jclass class_java_lang_System;
static jmethodID m_s_java_lang_System_console;
static jmethodID m_java_lang_System_toString;
ret_jint cproxy_s_java_lang_System_console() {
JNIEnv *env = go_seq_push_local_frame(0);
jobject res = (*env)->CallStaticObjectMethod(env, class_java_lang_System, m_s_java_lang_System_console);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
static jclass class_java_Future;
static jclass sclass_java_Future;
static jmethodID m_java_Future_get__;
static jmethodID sm_java_Future_get__;
static jmethodID m_java_Future_get__JLjava_util_concurrent_TimeUnit_2;
static jmethodID sm_java_Future_get__JLjava_util_concurrent_TimeUnit_2;
static jclass class_java_InputStream;
static jclass sclass_java_InputStream;
static jmethodID m_java_InputStream_read__;
static jmethodID sm_java_InputStream_read__;
static jmethodID m_java_InputStream_read___3B;
static jmethodID sm_java_InputStream_read___3B;
static jmethodID m_java_InputStream_read___3BII;
static jmethodID sm_java_InputStream_read___3BII;
static jmethodID m_java_InputStream_toString;
static jmethodID sm_java_InputStream_toString;
static jclass class_java_Object;
static jclass sclass_java_Object;
static jmethodID m_java_Object_toString;
static jmethodID sm_java_Object_toString;
static jclass class_java_Runnable;
static jclass sclass_java_Runnable;
static jmethodID m_java_Runnable_run;
static jmethodID sm_java_Runnable_run;
static jclass class_java_util_Iterator;
static jclass class_java_util_Spliterator;
static jclass class_java_util_PrimitiveIterator_OfInt;
static jclass class_java_util_Spliterator_OfInt;
static jclass class_java_util_PrimitiveIterator_OfLong;
static jclass class_java_util_Spliterator_OfLong;
static jclass class_java_util_PrimitiveIterator_OfDouble;
static jclass class_java_util_Spliterator_OfDouble;
static jclass class_java_io_Console;
static jmethodID m_java_io_Console_flush;
static jmethodID m_java_io_Console_toString;
void init_proxies() {
JNIEnv *env = go_seq_push_local_frame(20);
jclass clazz;
clazz = go_seq_find_class("java/lang/Runnable");
if (clazz != NULL) {
class_java_lang_Runnable = (*env)->NewGlobalRef(env, clazz);
m_java_lang_Runnable_run = go_seq_get_method_id(clazz, "run", "()V");
}
clazz = go_seq_find_class("java/io/InputStream");
if (clazz != NULL) {
class_java_io_InputStream = (*env)->NewGlobalRef(env, clazz);
m_java_io_InputStream_read__ = go_seq_get_method_id(clazz, "read", "()I");
m_java_io_InputStream_read___3B = go_seq_get_method_id(clazz, "read", "([B)I");
m_java_io_InputStream_read___3BII = go_seq_get_method_id(clazz, "read", "([BII)I");
m_java_io_InputStream_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
}
clazz = go_seq_find_class("java/util/concurrent/Future");
if (clazz != NULL) {
class_java_util_concurrent_Future = (*env)->NewGlobalRef(env, clazz);
m_java_util_concurrent_Future_get__ = go_seq_get_method_id(clazz, "get", "()Ljava/lang/Object;");
m_java_util_concurrent_Future_get__JLjava_util_concurrent_TimeUnit_2 = go_seq_get_method_id(clazz, "get", "(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;");
}
clazz = go_seq_find_class("java/lang/Object");
if (clazz != NULL) {
class_java_lang_Object = (*env)->NewGlobalRef(env, clazz);
m_java_lang_Object_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
}
clazz = go_seq_find_class("java/util/concurrent/TimeUnit");
if (clazz != NULL) {
class_java_util_concurrent_TimeUnit = (*env)->NewGlobalRef(env, clazz);
m_java_util_concurrent_TimeUnit_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
}
clazz = go_seq_find_class("java/util/Spliterators");
if (clazz != NULL) {
class_java_util_Spliterators = (*env)->NewGlobalRef(env, clazz);
m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_2 = go_seq_get_static_method_id(clazz, "iterator", "(Ljava/util/Spliterator;)Ljava/util/Iterator;");
m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfInt_2 = go_seq_get_static_method_id(clazz, "iterator", "(Ljava/util/Spliterator$OfInt;)Ljava/util/PrimitiveIterator$OfInt;");
m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfLong_2 = go_seq_get_static_method_id(clazz, "iterator", "(Ljava/util/Spliterator$OfLong;)Ljava/util/PrimitiveIterator$OfLong;");
m_s_java_util_Spliterators_iterator__Ljava_util_Spliterator_00024OfDouble_2 = go_seq_get_static_method_id(clazz, "iterator", "(Ljava/util/Spliterator$OfDouble;)Ljava/util/PrimitiveIterator$OfDouble;");
m_java_util_Spliterators_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
}
clazz = go_seq_find_class("java/lang/System");
if (clazz != NULL) {
class_java_lang_System = (*env)->NewGlobalRef(env, clazz);
m_s_java_lang_System_console = go_seq_get_static_method_id(clazz, "console", "()Ljava/io/Console;");
m_java_lang_System_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
}
clazz = go_seq_find_class("java/Future");
if (clazz != NULL) {
class_java_Future = (*env)->NewGlobalRef(env, clazz);
sclass_java_Future = (*env)->GetSuperclass(env, clazz);
sclass_java_Future = (*env)->NewGlobalRef(env, sclass_java_Future);
m_java_Future_get__ = go_seq_get_method_id(clazz, "get", "()Ljava/lang/Object;");
sm_java_Future_get__ = go_seq_get_method_id(sclass_java_Future, "get", "()Ljava/lang/Object;");
m_java_Future_get__JLjava_util_concurrent_TimeUnit_2 = go_seq_get_method_id(clazz, "get", "(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;");
sm_java_Future_get__JLjava_util_concurrent_TimeUnit_2 = go_seq_get_method_id(sclass_java_Future, "get", "(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;");
}
clazz = go_seq_find_class("java/InputStream");
if (clazz != NULL) {
class_java_InputStream = (*env)->NewGlobalRef(env, clazz);
sclass_java_InputStream = (*env)->GetSuperclass(env, clazz);
sclass_java_InputStream = (*env)->NewGlobalRef(env, sclass_java_InputStream);
m_java_InputStream_read__ = go_seq_get_method_id(clazz, "read", "()I");
sm_java_InputStream_read__ = go_seq_get_method_id(sclass_java_InputStream, "read", "()I");
m_java_InputStream_read___3B = go_seq_get_method_id(clazz, "read", "([B)I");
sm_java_InputStream_read___3B = go_seq_get_method_id(sclass_java_InputStream, "read", "([B)I");
m_java_InputStream_read___3BII = go_seq_get_method_id(clazz, "read", "([BII)I");
sm_java_InputStream_read___3BII = go_seq_get_method_id(sclass_java_InputStream, "read", "([BII)I");
m_java_InputStream_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
sm_java_InputStream_toString = go_seq_get_method_id(sclass_java_InputStream, "toString", "()Ljava/lang/String;");
}
clazz = go_seq_find_class("java/Object");
if (clazz != NULL) {
class_java_Object = (*env)->NewGlobalRef(env, clazz);
sclass_java_Object = (*env)->GetSuperclass(env, clazz);
sclass_java_Object = (*env)->NewGlobalRef(env, sclass_java_Object);
m_java_Object_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
sm_java_Object_toString = go_seq_get_method_id(sclass_java_Object, "toString", "()Ljava/lang/String;");
}
clazz = go_seq_find_class("java/Runnable");
if (clazz != NULL) {
class_java_Runnable = (*env)->NewGlobalRef(env, clazz);
sclass_java_Runnable = (*env)->GetSuperclass(env, clazz);
sclass_java_Runnable = (*env)->NewGlobalRef(env, sclass_java_Runnable);
m_java_Runnable_run = go_seq_get_method_id(clazz, "run", "()V");
sm_java_Runnable_run = go_seq_get_method_id(sclass_java_Runnable, "run", "()V");
}
clazz = go_seq_find_class("java/util/Iterator");
if (clazz != NULL) {
class_java_util_Iterator = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/util/Spliterator");
if (clazz != NULL) {
class_java_util_Spliterator = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/util/PrimitiveIterator$OfInt");
if (clazz != NULL) {
class_java_util_PrimitiveIterator_OfInt = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/util/Spliterator$OfInt");
if (clazz != NULL) {
class_java_util_Spliterator_OfInt = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/util/PrimitiveIterator$OfLong");
if (clazz != NULL) {
class_java_util_PrimitiveIterator_OfLong = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/util/Spliterator$OfLong");
if (clazz != NULL) {
class_java_util_Spliterator_OfLong = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/util/PrimitiveIterator$OfDouble");
if (clazz != NULL) {
class_java_util_PrimitiveIterator_OfDouble = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/util/Spliterator$OfDouble");
if (clazz != NULL) {
class_java_util_Spliterator_OfDouble = (*env)->NewGlobalRef(env, clazz);
}
clazz = go_seq_find_class("java/io/Console");
if (clazz != NULL) {
class_java_io_Console = (*env)->NewGlobalRef(env, clazz);
m_java_io_Console_flush = go_seq_get_method_id(clazz, "flush", "()V");
m_java_io_Console_toString = go_seq_get_method_id(clazz, "toString", "()Ljava/lang/String;");
}
go_seq_pop_local_frame(env);
}
jint cproxy_java_lang_Runnable_run(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
(*env)->CallVoidMethod(env, _this, m_java_lang_Runnable_run);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
go_seq_pop_local_frame(env);
return _exc_ref;
}
ret_jint cproxy_java_io_InputStream_read__(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jint res = (*env)->CallIntMethod(env, _this, m_java_io_InputStream_read__);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_io_InputStream_read___3B(jint this, nbyteslice a0) {
JNIEnv *env = go_seq_push_local_frame(2);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jbyteArray _a0 = go_seq_to_java_bytearray(env, a0, 0);
jint res = (*env)->CallIntMethod(env, _this, m_java_io_InputStream_read___3B, _a0);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_io_InputStream_read___3BII(jint this, nbyteslice a0, jint a1, jint a2) {
JNIEnv *env = go_seq_push_local_frame(4);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jbyteArray _a0 = go_seq_to_java_bytearray(env, a0, 0);
jint _a1 = a1;
jint _a2 = a2;
jint res = (*env)->CallIntMethod(env, _this, m_java_io_InputStream_read___3BII, _a0, _a1, _a2);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_nstring cproxy_java_io_InputStream_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_io_InputStream_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_util_concurrent_Future_get__(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jobject res = (*env)->CallObjectMethod(env, _this, m_java_util_concurrent_Future_get__);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_util_concurrent_Future_get__JLjava_util_concurrent_TimeUnit_2(jint this, jlong a0, jint a1) {
JNIEnv *env = go_seq_push_local_frame(3);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jlong _a0 = a0;
jobject _a1 = go_seq_from_refnum(env, a1, NULL, NULL);
jobject res = (*env)->CallObjectMethod(env, _this, m_java_util_concurrent_Future_get__JLjava_util_concurrent_TimeUnit_2, _a0, _a1);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_nstring cproxy_java_lang_Object_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_lang_Object_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_nstring cproxy_java_util_concurrent_TimeUnit_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_util_concurrent_TimeUnit_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_nstring cproxy_java_util_Spliterators_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_util_Spliterators_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_nstring cproxy_java_lang_System_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_lang_System_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_Future_get__(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jobject res = (*env)->CallObjectMethod(env, _this, m_java_Future_get__);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint csuper_java_Future_get__(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jobject res = (*env)->CallNonvirtualObjectMethod(env, _this, sclass_java_Future, sm_java_Future_get__);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_Future_get__JLjava_util_concurrent_TimeUnit_2(jint this, jlong a0, jint a1) {
JNIEnv *env = go_seq_push_local_frame(3);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jlong _a0 = a0;
jobject _a1 = go_seq_from_refnum(env, a1, NULL, NULL);
jobject res = (*env)->CallObjectMethod(env, _this, m_java_Future_get__JLjava_util_concurrent_TimeUnit_2, _a0, _a1);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint csuper_java_Future_get__JLjava_util_concurrent_TimeUnit_2(jint this, jlong a0, jint a1) {
JNIEnv *env = go_seq_push_local_frame(3);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jlong _a0 = a0;
jobject _a1 = go_seq_from_refnum(env, a1, NULL, NULL);
jobject res = (*env)->CallNonvirtualObjectMethod(env, _this, sclass_java_Future, sm_java_Future_get__JLjava_util_concurrent_TimeUnit_2, _a0, _a1);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
jint _res = go_seq_to_refnum(env, res);
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_InputStream_read__(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jint res = (*env)->CallIntMethod(env, _this, m_java_InputStream_read__);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint csuper_java_InputStream_read__(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jint res = (*env)->CallNonvirtualIntMethod(env, _this, sclass_java_InputStream, sm_java_InputStream_read__);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_InputStream_read___3B(jint this, nbyteslice a0) {
JNIEnv *env = go_seq_push_local_frame(2);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jbyteArray _a0 = go_seq_to_java_bytearray(env, a0, 0);
jint res = (*env)->CallIntMethod(env, _this, m_java_InputStream_read___3B, _a0);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint csuper_java_InputStream_read___3B(jint this, nbyteslice a0) {
JNIEnv *env = go_seq_push_local_frame(2);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jbyteArray _a0 = go_seq_to_java_bytearray(env, a0, 0);
jint res = (*env)->CallNonvirtualIntMethod(env, _this, sclass_java_InputStream, sm_java_InputStream_read___3B, _a0);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint cproxy_java_InputStream_read___3BII(jint this, nbyteslice a0, jint a1, jint a2) {
JNIEnv *env = go_seq_push_local_frame(4);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jbyteArray _a0 = go_seq_to_java_bytearray(env, a0, 0);
jint _a1 = a1;
jint _a2 = a2;
jint res = (*env)->CallIntMethod(env, _this, m_java_InputStream_read___3BII, _a0, _a1, _a2);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_jint csuper_java_InputStream_read___3BII(jint this, nbyteslice a0, jint a1, jint a2) {
JNIEnv *env = go_seq_push_local_frame(4);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jbyteArray _a0 = go_seq_to_java_bytearray(env, a0, 0);
jint _a1 = a1;
jint _a2 = a2;
jint res = (*env)->CallNonvirtualIntMethod(env, _this, sclass_java_InputStream, sm_java_InputStream_read___3BII, _a0, _a1, _a2);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = 0;
}
jint _res = res;
go_seq_pop_local_frame(env);
ret_jint __res = {_res, _exc_ref};
return __res;
}
ret_nstring cproxy_java_InputStream_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_InputStream_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_nstring csuper_java_InputStream_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallNonvirtualObjectMethod(env, _this, sclass_java_InputStream, sm_java_InputStream_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_nstring cproxy_java_Object_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_Object_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
ret_nstring csuper_java_Object_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallNonvirtualObjectMethod(env, _this, sclass_java_Object, sm_java_Object_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
jint cproxy_java_Runnable_run(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
(*env)->CallVoidMethod(env, _this, m_java_Runnable_run);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
go_seq_pop_local_frame(env);
return _exc_ref;
}
jint csuper_java_Runnable_run(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
(*env)->CallNonvirtualVoidMethod(env, _this, sclass_java_Runnable, sm_java_Runnable_run);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
go_seq_pop_local_frame(env);
return _exc_ref;
}
jint cproxy_java_io_Console_flush(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
(*env)->CallVoidMethod(env, _this, m_java_io_Console_flush);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
go_seq_pop_local_frame(env);
return _exc_ref;
}
ret_nstring cproxy_java_io_Console_toString(jint this) {
JNIEnv *env = go_seq_push_local_frame(1);
// Must be a Java object
jobject _this = go_seq_from_refnum(env, this, NULL, NULL);
jstring res = (*env)->CallObjectMethod(env, _this, m_java_io_Console_toString);
jobject _exc = go_seq_get_exception(env);
int32_t _exc_ref = go_seq_to_refnum(env, _exc);
if (_exc != NULL) {
res = NULL;
}
nstring _res = go_seq_from_java_string(env, res);
go_seq_pop_local_frame(env);
ret_nstring __res = {_res, _exc_ref};
return __res;
}
// Code generated by gobind. DO NOT EDIT.
// JNI functions for the Go <=> Java bridge.
//
// autogenerated by gobind -lang=java classes
#include <android/log.h>
#include <stdint.h>
#include "seq.h"
#include "_cgo_export.h"
#include "java.h"
jclass proxy_class_java_Future;
jmethodID proxy_class_java_Future_cons;
jclass proxy_class_java_InputStream;
jmethodID proxy_class_java_InputStream_cons;
jclass proxy_class_java_Object;
jmethodID proxy_class_java_Object_cons;
jclass proxy_class_java_Runnable;
jmethodID proxy_class_java_Runnable_cons;
JNIEXPORT void JNICALL
Java_java_Java__1init(JNIEnv *env, jclass _unused) {
jclass clazz;
clazz = (*env)->FindClass(env, "java/Future");
proxy_class_java_Future = (*env)->NewGlobalRef(env, clazz);
proxy_class_java_Future_cons = (*env)->GetMethodID(env, clazz, "<init>", "(I)V");
clazz = (*env)->FindClass(env, "java/Object");
proxy_class_java_Object = (*env)->NewGlobalRef(env, clazz);
proxy_class_java_Object_cons = (*env)->GetMethodID(env, clazz, "<init>", "(I)V");
clazz = (*env)->FindClass(env, "java/Runnable");
proxy_class_java_Runnable = (*env)->NewGlobalRef(env, clazz);
proxy_class_java_Runnable_cons = (*env)->GetMethodID(env, clazz, "<init>", "(I)V");
}
JNIEXPORT jobject JNICALL
Java_java_Java_newInputStream(JNIEnv* env, jclass _clazz) {
int32_t r0 = proxyjava__NewInputStream();
jobject _r0 = go_seq_from_refnum(env, r0, proxy_class_java_InputStream, proxy_class_java_InputStream_cons);
return _r0;
}
JNIEXPORT jint JNICALL
Java_java_Future__1_1New(JNIEnv *env, jclass clazz) {
return new_java_Future();
}
JNIEXPORT jobject JNICALL
Java_java_Future_get__(JNIEnv* env, jobject __this__) {
int32_t o = go_seq_to_refnum_go(env, __this__);
struct proxyjava_Future_Get_return res = proxyjava_Future_Get(o);
jobject _r0 = go_seq_from_refnum(env, res.r0, NULL, NULL);
jobject _r1 = go_seq_from_refnum(env, res.r1, proxy_class__error, proxy_class__error_cons);
go_seq_maybe_throw_exception(env, _r1);
return _r0;
}
JNIEXPORT jobject JNICALL
Java_java_Future_get__JLjava_util_concurrent_TimeUnit_2(JNIEnv* env, jobject __this__, jlong p0, jobject p1) {
int32_t o = go_seq_to_refnum_go(env, __this__);
int64_t _p0 = (int64_t)p0;
int32_t _p1 = go_seq_to_refnum(env, p1);
struct proxyjava_Future_Get__return res = proxyjava_Future_Get_(o, _p0, _p1);
jobject _r0 = go_seq_from_refnum(env, res.r0, NULL, NULL);
jobject _r1 = go_seq_from_refnum(env, res.r1, proxy_class__error, proxy_class__error_cons);
go_seq_maybe_throw_exception(env, _r1);
return _r0;
}
JNIEXPORT void JNICALL
Java_java_Future_setFuture(JNIEnv *env, jobject this, jobject v) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t _v = go_seq_to_refnum(env, v);
proxyjava_Future_Future_Set(o, _v);
}
JNIEXPORT jobject JNICALL
Java_java_Future_getFuture(JNIEnv *env, jobject this) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t r0 = proxyjava_Future_Future_Get(o);
jobject _r0 = go_seq_from_refnum(env, r0, NULL, NULL);
return _r0;
}
JNIEXPORT jint JNICALL
Java_java_InputStream__1_1NewInputStream(JNIEnv *env, jclass clazz) {
int32_t refnum = proxyjava__NewInputStream();
return refnum;
}
JNIEXPORT jint JNICALL
Java_java_InputStream_read__(JNIEnv* env, jobject __this__) {
int32_t o = go_seq_to_refnum_go(env, __this__);
struct proxyjava_InputStream_Read_return res = proxyjava_InputStream_Read(o);
jint _r0 = (jint)res.r0;
jobject _r1 = go_seq_from_refnum(env, res.r1, proxy_class__error, proxy_class__error_cons);
go_seq_maybe_throw_exception(env, _r1);
return _r0;
}
JNIEXPORT void JNICALL
Java_java_InputStream_setInputStream(JNIEnv *env, jobject this, jobject v) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t _v = go_seq_to_refnum(env, v);
proxyjava_InputStream_InputStream_Set(o, _v);
}
JNIEXPORT jobject JNICALL
Java_java_InputStream_getInputStream(JNIEnv *env, jobject this) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t r0 = proxyjava_InputStream_InputStream_Get(o);
jobject _r0 = go_seq_from_refnum(env, r0, NULL, NULL);
return _r0;
}
JNIEXPORT jint JNICALL
Java_java_Object__1_1New(JNIEnv *env, jclass clazz) {
return new_java_Object();
}
JNIEXPORT void JNICALL
Java_java_Object_setObject(JNIEnv *env, jobject this, jobject v) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t _v = go_seq_to_refnum(env, v);
proxyjava_Object_Object_Set(o, _v);
}
JNIEXPORT jobject JNICALL
Java_java_Object_getObject(JNIEnv *env, jobject this) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t r0 = proxyjava_Object_Object_Get(o);
jobject _r0 = go_seq_from_refnum(env, r0, NULL, NULL);
return _r0;
}
JNIEXPORT jint JNICALL
Java_java_Runnable__1_1New(JNIEnv *env, jclass clazz) {
return new_java_Runnable();
}
JNIEXPORT void JNICALL
Java_java_Runnable_run(JNIEnv* env, jobject __this__) {
int32_t o = go_seq_to_refnum_go(env, __this__);
int32_t _this_ = go_seq_to_refnum(env, __this__);
proxyjava_Runnable_Run(o, _this_);
}
JNIEXPORT void JNICALL
Java_java_Runnable_setRunnable(JNIEnv *env, jobject this, jobject v) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t _v = go_seq_to_refnum(env, v);
proxyjava_Runnable_Runnable_Set(o, _v);
}
JNIEXPORT jobject JNICALL
Java_java_Runnable_getRunnable(JNIEnv *env, jobject this) {
int32_t o = go_seq_to_refnum_go(env, this);
int32_t r0 = proxyjava_Runnable_Runnable_Get(o);
jobject _r0 = go_seq_from_refnum(env, r0, NULL, NULL);
return _r0;
}
|
mobile/bind/testdata/classes.java.c.golden/0
|
{
"file_path": "mobile/bind/testdata/classes.java.c.golden",
"repo_id": "mobile",
"token_count": 14798
}
| 594 |
// Code generated by gobind. DO NOT EDIT.
// Java class doc.NoDoc is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java doc
package doc;
import go.Seq;
/**
* A generic comment with <HTML>.
*/
public final class NoDoc implements Seq.Proxy {
static { Doc.touch(); }
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
NoDoc(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public NoDoc() { this.refnum = __New(); Seq.trackGoRef(refnum, this); }
private static native int __New();
@Override public boolean equals(Object o) {
if (o == null || !(o instanceof NoDoc)) {
return false;
}
NoDoc that = (NoDoc)o;
return true;
}
@Override public int hashCode() {
return java.util.Arrays.hashCode(new Object[] {});
}
@Override public String toString() {
StringBuilder b = new StringBuilder();
b.append("NoDoc").append("{");
return b.append("}").toString();
}
}
// Code generated by gobind. DO NOT EDIT.
// Java class doc.S is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java doc
package doc;
import go.Seq;
/**
* S is a struct.
*/
public final class S implements Seq.Proxy {
static { Doc.touch(); }
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
/**
* NewS is a constructor.
*/
public S() {
this.refnum = __NewS();
Seq.trackGoRef(refnum, this);
}
private static native int __NewS();
S(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
/**
* SF is a field.
*/
public final native String getSF();
/**
* SF is a field.
*/
public final native void setSF(String v);
/**
* Anonymous field.
*/
public final native S2 getS2();
/**
* Anonymous field.
*/
public final native void setS2(S2 v);
/**
* Multiple fields.
*/
public final native String getF1();
/**
* Multiple fields.
*/
public final native void setF1(String v);
/**
* Multiple fields.
*/
public final native String getF2();
/**
* Multiple fields.
*/
public final native void setF2(String v);
/**
* After is another method.
*/
public native void after();
public native void before();
@Override public boolean equals(Object o) {
if (o == null || !(o instanceof S)) {
return false;
}
S that = (S)o;
String thisSF = getSF();
String thatSF = that.getSF();
if (thisSF == null) {
if (thatSF != null) {
return false;
}
} else if (!thisSF.equals(thatSF)) {
return false;
}
S2 thisS2 = getS2();
S2 thatS2 = that.getS2();
if (thisS2 == null) {
if (thatS2 != null) {
return false;
}
} else if (!thisS2.equals(thatS2)) {
return false;
}
String thisF1 = getF1();
String thatF1 = that.getF1();
if (thisF1 == null) {
if (thatF1 != null) {
return false;
}
} else if (!thisF1.equals(thatF1)) {
return false;
}
String thisF2 = getF2();
String thatF2 = that.getF2();
if (thisF2 == null) {
if (thatF2 != null) {
return false;
}
} else if (!thisF2.equals(thatF2)) {
return false;
}
return true;
}
@Override public int hashCode() {
return java.util.Arrays.hashCode(new Object[] {getSF(), getS2(), getF1(), getF2()});
}
@Override public String toString() {
StringBuilder b = new StringBuilder();
b.append("S").append("{");
b.append("SF:").append(getSF()).append(",");
b.append("S2:").append(getS2()).append(",");
b.append("F1:").append(getF1()).append(",");
b.append("F2:").append(getF2()).append(",");
return b.append("}").toString();
}
}
// Code generated by gobind. DO NOT EDIT.
// Java class doc.S2 is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java doc
package doc;
import go.Seq;
/**
* S2 is a struct.
*/
public final class S2 implements Seq.Proxy {
static { Doc.touch(); }
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
S2(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public S2() { this.refnum = __New(); Seq.trackGoRef(refnum, this); }
private static native int __New();
@Override public boolean equals(Object o) {
if (o == null || !(o instanceof S2)) {
return false;
}
S2 that = (S2)o;
return true;
}
@Override public int hashCode() {
return java.util.Arrays.hashCode(new Object[] {});
}
@Override public String toString() {
StringBuilder b = new StringBuilder();
b.append("S2").append("{");
return b.append("}").toString();
}
}
// Code generated by gobind. DO NOT EDIT.
// Java class doc.I is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java doc
package doc;
import go.Seq;
/**
* I is an interface.
*/
public interface I {
/**
* IM is a method.
*/
public void im();
}
// Code generated by gobind. DO NOT EDIT.
// Java class doc.Doc is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java doc
package doc;
import go.Seq;
public abstract class Doc {
static {
Seq.touch(); // for loading the native library
_init();
}
private Doc() {} // uninstantiable
// touch is called from other bound packages to initialize this package
public static void touch() {}
private static native void _init();
private static final class proxyI implements Seq.Proxy, I {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyI(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native void im();
}
/**
* C is a constant.
*/
public static final boolean C = true;
/**
* A group of vars.
*/
public static native void setNoDocVar(double v);
/**
* A group of vars.
*/
public static native double getNoDocVar();
/**
* A specific var.
*/
public static native void setSpecific(String v);
/**
* A specific var.
*/
public static native String getSpecific();
/**
* V is a var.
*/
public static native void setV(String v);
/**
* V is a var.
*/
public static native String getV();
/**
* F is a function.
*/
public static native void f();
/**
* NewS is a constructor.
*/
public static native S newS();
}
|
mobile/bind/testdata/doc.java.golden/0
|
{
"file_path": "mobile/bind/testdata/doc.java.golden",
"repo_id": "mobile",
"token_count": 3376
}
| 595 |
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.Error is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
public interface Error {
public void err() throws Exception;
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.I is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
public interface I {
public int rand();
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.I1 is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
/**
* not implementable
*/
public interface I1 {
public void j();
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.I2 is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
/**
* not implementable
*/
public interface I2 {
public void g();
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.I3 is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
/**
* implementable
(the implementor has to find a source of I1s)
*/
public interface I3 {
public I1 f();
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.Interfaces_ is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
/**
* Interfaces is an interface with the same name as its package.
*/
public interface Interfaces_ {
public void someMethod();
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.LargerI is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
public interface LargerI extends I, SameI {
public void anotherFunc();
public int rand();
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.SameI is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
public interface SameI {
public int rand();
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.WithParam is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
public interface WithParam {
public void hasParam(boolean p0);
}
// Code generated by gobind. DO NOT EDIT.
// Java class interfaces.Interfaces is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java interfaces
package interfaces;
import go.Seq;
public abstract class Interfaces {
static {
Seq.touch(); // for loading the native library
_init();
}
private Interfaces() {} // uninstantiable
// touch is called from other bound packages to initialize this package
public static void touch() {}
private static native void _init();
private static final class proxyError implements Seq.Proxy, Error {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyError(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native void err() throws Exception;
}
private static final class proxyI implements Seq.Proxy, I {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyI(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native int rand();
}
private static final class proxyI1 implements Seq.Proxy, I1 {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyI1(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native void j();
}
private static final class proxyI2 implements Seq.Proxy, I2 {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyI2(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native void g();
}
private static final class proxyI3 implements Seq.Proxy, I3 {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyI3(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native I1 f();
}
private static final class proxyInterfaces implements Seq.Proxy, Interfaces_ {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyInterfaces(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native void someMethod();
}
private static final class proxyLargerI implements Seq.Proxy, LargerI {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyLargerI(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native void anotherFunc();
public native int rand();
}
private static final class proxySameI implements Seq.Proxy, SameI {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxySameI(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native int rand();
}
private static final class proxyWithParam implements Seq.Proxy, WithParam {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyWithParam(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native void hasParam(boolean p0);
}
public static native int add3(I r);
public static native void callErr(Error e) throws Exception;
public static native I seven();
}
|
mobile/bind/testdata/interfaces.java.golden/0
|
{
"file_path": "mobile/bind/testdata/interfaces.java.golden",
"repo_id": "mobile",
"token_count": 2793
}
| 596 |
// Code generated by gobind. DO NOT EDIT.
// Java class issue12328.T is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java issue12328
package issue12328;
import go.Seq;
public final class T implements Seq.Proxy {
static { Issue12328.touch(); }
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
T(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public T() { this.refnum = __New(); Seq.trackGoRef(refnum, this); }
private static native int __New();
public final native java.lang.Exception getErr();
public final native void setErr(java.lang.Exception v);
@Override public boolean equals(Object o) {
if (o == null || !(o instanceof T)) {
return false;
}
T that = (T)o;
java.lang.Exception thisErr = getErr();
java.lang.Exception thatErr = that.getErr();
if (thisErr == null) {
if (thatErr != null) {
return false;
}
} else if (!thisErr.equals(thatErr)) {
return false;
}
return true;
}
@Override public int hashCode() {
return java.util.Arrays.hashCode(new Object[] {getErr()});
}
@Override public String toString() {
StringBuilder b = new StringBuilder();
b.append("T").append("{");
b.append("Err:").append(getErr()).append(",");
return b.append("}").toString();
}
}
// Code generated by gobind. DO NOT EDIT.
// Java class issue12328.Issue12328 is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java issue12328
package issue12328;
import go.Seq;
public abstract class Issue12328 {
static {
Seq.touch(); // for loading the native library
_init();
}
private Issue12328() {} // uninstantiable
// touch is called from other bound packages to initialize this package
public static void touch() {}
private static native void _init();
}
|
mobile/bind/testdata/issue12328.java.golden/0
|
{
"file_path": "mobile/bind/testdata/issue12328.java.golden",
"repo_id": "mobile",
"token_count": 908
}
| 597 |
// Code generated by gobind. DO NOT EDIT.
// Java class issue29559.Issue29559 is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java issue29559
package issue29559;
import go.Seq;
public abstract class Issue29559 {
static {
Seq.touch(); // for loading the native library
_init();
}
private Issue29559() {} // uninstantiable
// touch is called from other bound packages to initialize this package
public static void touch() {}
private static native void _init();
public static native void takesAString(String s);
}
|
mobile/bind/testdata/issue29559.java.golden/0
|
{
"file_path": "mobile/bind/testdata/issue29559.java.golden",
"repo_id": "mobile",
"token_count": 217
}
| 598 |
// Objective-C API for talking to keywords Go package.
// gobind -lang=objc keywords
//
// File is generated by gobind. Do not edit.
#ifndef __Keywords_H__
#define __Keywords_H__
@import Foundation;
#include "ref.h"
#include "Universe.objc.h"
@protocol KeywordsKeywordCaller;
@class KeywordsKeywordCaller;
@protocol KeywordsKeywordCaller <NSObject>
- (void)abstract;
- (void)assert;
- (void)bool_;
- (void)boolean;
- (void)break;
- (void)byte;
- (void)case;
- (void)catch;
- (void)char_;
- (void)class;
- (void)const_;
- (void)continue;
- (void)default;
- (void)do;
- (void)double_;
- (void)else;
- (void)enum;
- (void)extends;
- (void)false;
- (void)final;
- (void)finally;
- (void)float_;
- (void)for;
- (void)goto;
- (void)if;
- (void)implements;
- (void)import;
- (void)instanceof;
- (void)int_;
- (void)interface;
- (void)long_;
- (void)native;
- (void)new;
- (void)nil_;
- (void)null;
- (void)package;
- (void)private;
- (void)protected;
- (void)public;
- (void)return;
- (void)short_;
- (void)static;
- (void)strictfp;
- (void)super_;
- (void)switch;
- (void)synchronized;
- (void)this;
- (void)throw;
- (void)throws;
- (void)transient;
- (void)true;
- (void)try;
- (void)void_;
- (void)volatile_;
- (void)while;
@end
FOUNDATION_EXPORT void KeywordsConst(NSString* _Nullable id_);
FOUNDATION_EXPORT void KeywordsStatic(NSString* _Nullable strictfp);
@class KeywordsKeywordCaller;
@interface KeywordsKeywordCaller : NSObject <goSeqRefInterface, KeywordsKeywordCaller> {
}
@property(strong, readonly) _Nonnull id _ref;
- (nonnull instancetype)initWithRef:(_Nonnull id)ref;
- (void)abstract;
- (void)assert;
- (void)bool_;
- (void)boolean;
- (void)break;
- (void)byte;
- (void)case;
- (void)catch;
- (void)char_;
- (void)class;
- (void)const_;
- (void)continue;
- (void)default;
- (void)do;
- (void)double_;
- (void)else;
- (void)enum;
- (void)extends;
- (void)false;
- (void)final;
- (void)finally;
- (void)float_;
- (void)for;
- (void)goto;
- (void)if;
- (void)implements;
- (void)import;
- (void)instanceof;
- (void)int_;
- (void)interface;
- (void)long_;
- (void)native;
- (void)new;
- (void)nil_;
- (void)null;
- (void)package;
- (void)private;
- (void)protected;
- (void)public;
- (void)return;
- (void)short_;
- (void)static;
- (void)strictfp;
- (void)super_;
- (void)switch;
- (void)synchronized;
- (void)this;
- (void)throw;
- (void)throws;
- (void)transient;
- (void)true;
- (void)try;
- (void)void_;
- (void)volatile_;
- (void)while;
@end
#endif
|
mobile/bind/testdata/keywords.objc.h.golden/0
|
{
"file_path": "mobile/bind/testdata/keywords.objc.h.golden",
"repo_id": "mobile",
"token_count": 1081
}
| 599 |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package javapkg
import (
"Java/java/lang/Float"
"Java/java/lang/Integer"
"Java/java/lang/System"
"Java/java/util/Collections"
"Java/java/util/jar/JarFile"
"fmt"
)
func SystemCurrentTimeMillis() int64 {
return System.CurrentTimeMillis()
}
func FloatMin() float32 {
return Float.MIN_VALUE
}
func ManifestName() string {
return JarFile.MANIFEST_NAME
}
func IntegerBytes() int {
return Integer.SIZE
}
func IntegerValueOf(v int32) int32 {
i, _ := Integer.ValueOf(v)
return i.IntValue()
}
func IntegerDecode(v string) (int32, error) {
i, err := Integer.Decode(v)
if err != nil {
return 0, fmt.Errorf("wrapped error: %v", err)
}
// Call methods from super class
i.HashCode()
return i.IntValue(), nil
}
func IntegerParseInt(v string, radix int32) (int32, error) {
return Integer.ParseInt(v, radix)
}
func ProvokeRuntimeException() (err error) {
defer func() {
err = recover().(error)
}()
Collections.Copy(nil, nil)
return
}
|
mobile/bind/testdata/testpkg/javapkg/java.go/0
|
{
"file_path": "mobile/bind/testdata/testpkg/javapkg/java.go",
"repo_id": "mobile",
"token_count": 410
}
| 600 |
// Code generated by gobind. DO NOT EDIT.
// Package main is an autogenerated binder stub for package vars.
//
// autogenerated by gobind -lang=go vars
package main
/*
#include <stdlib.h>
#include <stdint.h>
#include "seq.h"
#include "vars.h"
*/
import "C"
import (
_seq "golang.org/x/mobile/bind/seq"
"vars"
)
// suppress the error if seq ends up unused
var _ = _seq.FromRefNum
//export new_vars_S
func new_vars_S() C.int32_t {
return C.int32_t(_seq.ToRefNum(new(vars.S)))
}
type proxyvars_I _seq.Ref
func (p *proxyvars_I) Bind_proxy_refnum__() int32 {
return (*_seq.Ref)(p).Bind_IncNum()
}
//export var_setvars_ABool
func var_setvars_ABool(v C.char) {
_v := v != 0
vars.ABool = _v
}
//export var_getvars_ABool
func var_getvars_ABool() C.char {
v := vars.ABool
var _v C.char = 0
if v {
_v = 1
}
return _v
}
//export var_setvars_AFloat
func var_setvars_AFloat(v C.double) {
_v := float64(v)
vars.AFloat = _v
}
//export var_getvars_AFloat
func var_getvars_AFloat() C.double {
v := vars.AFloat
_v := C.double(v)
return _v
}
//export var_setvars_AFloat32
func var_setvars_AFloat32(v C.float) {
_v := float32(v)
vars.AFloat32 = _v
}
//export var_getvars_AFloat32
func var_getvars_AFloat32() C.float {
v := vars.AFloat32
_v := C.float(v)
return _v
}
//export var_setvars_AFloat64
func var_setvars_AFloat64(v C.double) {
_v := float64(v)
vars.AFloat64 = _v
}
//export var_getvars_AFloat64
func var_getvars_AFloat64() C.double {
v := vars.AFloat64
_v := C.double(v)
return _v
}
//export var_setvars_AString
func var_setvars_AString(v C.nstring) {
_v := decodeString(v)
vars.AString = _v
}
//export var_getvars_AString
func var_getvars_AString() C.nstring {
v := vars.AString
_v := encodeString(v)
return _v
}
//export var_setvars_AStructPtr
func var_setvars_AStructPtr(v C.int32_t) {
// Must be a Go object
var _v *vars.S
if _v_ref := _seq.FromRefNum(int32(v)); _v_ref != nil {
_v = _v_ref.Get().(*vars.S)
}
vars.AStructPtr = _v
}
//export var_getvars_AStructPtr
func var_getvars_AStructPtr() C.int32_t {
v := vars.AStructPtr
var _v C.int32_t = _seq.NullRefNum
if v != nil {
_v = C.int32_t(_seq.ToRefNum(v))
}
return _v
}
//export var_setvars_AnInt
func var_setvars_AnInt(v C.nint) {
_v := int(v)
vars.AnInt = _v
}
//export var_getvars_AnInt
func var_getvars_AnInt() C.nint {
v := vars.AnInt
_v := C.nint(v)
return _v
}
//export var_setvars_AnInt16
func var_setvars_AnInt16(v C.int16_t) {
_v := int16(v)
vars.AnInt16 = _v
}
//export var_getvars_AnInt16
func var_getvars_AnInt16() C.int16_t {
v := vars.AnInt16
_v := C.int16_t(v)
return _v
}
//export var_setvars_AnInt32
func var_setvars_AnInt32(v C.int32_t) {
_v := int32(v)
vars.AnInt32 = _v
}
//export var_getvars_AnInt32
func var_getvars_AnInt32() C.int32_t {
v := vars.AnInt32
_v := C.int32_t(v)
return _v
}
//export var_setvars_AnInt64
func var_setvars_AnInt64(v C.int64_t) {
_v := int64(v)
vars.AnInt64 = _v
}
//export var_getvars_AnInt64
func var_getvars_AnInt64() C.int64_t {
v := vars.AnInt64
_v := C.int64_t(v)
return _v
}
//export var_setvars_AnInt8
func var_setvars_AnInt8(v C.int8_t) {
_v := int8(v)
vars.AnInt8 = _v
}
//export var_getvars_AnInt8
func var_getvars_AnInt8() C.int8_t {
v := vars.AnInt8
_v := C.int8_t(v)
return _v
}
//export var_setvars_AnInterface
func var_setvars_AnInterface(v C.int32_t) {
var _v vars.I
_v_ref := _seq.FromRefNum(int32(v))
if _v_ref != nil {
if v < 0 { // go object
_v = _v_ref.Get().(vars.I)
} else { // foreign object
_v = (*proxyvars_I)(_v_ref)
}
}
vars.AnInterface = _v
}
//export var_getvars_AnInterface
func var_getvars_AnInterface() C.int32_t {
v := vars.AnInterface
var _v C.int32_t = _seq.NullRefNum
if v != nil {
_v = C.int32_t(_seq.ToRefNum(v))
}
return _v
}
|
mobile/bind/testdata/vars.go.golden/0
|
{
"file_path": "mobile/bind/testdata/vars.go.golden",
"repo_id": "mobile",
"token_count": 1865
}
| 601 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"text/template"
"golang.org/x/mobile/internal/sdkpath"
)
func TestBindAndroid(t *testing.T) {
platform, err := sdkpath.AndroidAPIPath(minAndroidAPI)
if err != nil {
t.Skip("No compatible Android API platform found, skipping bind")
}
// platform is a path like "/path/to/Android/sdk/platforms/android-32"
components := strings.Split(platform, string(filepath.Separator))
if len(components) < 2 {
t.Fatalf("API path is too short: %s", platform)
}
components = components[len(components)-2:]
platformRel := filepath.Join("$ANDROID_HOME", components[0], components[1])
defer func() {
xout = os.Stderr
buildN = false
buildX = false
buildO = ""
buildTarget = ""
bindJavaPkg = ""
}()
buildN = true
buildX = true
buildO = "asset.aar"
buildTarget = "android/arm"
tests := []struct {
javaPkg string
}{
{
// Empty javaPkg
},
{
javaPkg: "com.example.foo",
},
}
for _, tc := range tests {
bindJavaPkg = tc.javaPkg
buf := new(bytes.Buffer)
xout = buf
gopath = filepath.SplitList(goEnv("GOPATH"))[0]
if goos == "windows" {
os.Setenv("HOMEDRIVE", "C:")
}
cmdBind.flag.Parse([]string{"golang.org/x/mobile/asset"})
err := runBind(cmdBind)
if err != nil {
t.Log(buf.String())
t.Fatal(err)
}
got := filepath.ToSlash(buf.String())
output, err := defaultOutputData("")
if err != nil {
t.Fatal(err)
}
data := struct {
outputData
AndroidPlatform string
JavaPkg string
}{
outputData: output,
AndroidPlatform: platformRel,
JavaPkg: tc.javaPkg,
}
wantBuf := new(bytes.Buffer)
if err := bindAndroidTmpl.Execute(wantBuf, data); err != nil {
t.Errorf("%+v: computing diff failed: %v", tc, err)
continue
}
diff, err := diff(got, wantBuf.String())
if err != nil {
t.Errorf("%+v: computing diff failed: %v", tc, err)
continue
}
if diff != "" {
t.Errorf("%+v: unexpected output:\n%s", tc, diff)
}
}
}
func TestBindApple(t *testing.T) {
if !xcodeAvailable() {
t.Skip("Xcode is missing")
}
defer func() {
xout = os.Stderr
buildN = false
buildX = false
buildO = ""
buildTarget = ""
bindPrefix = ""
}()
buildN = true
buildX = true
buildO = "Asset.xcframework"
buildTarget = "ios/arm64"
tests := []struct {
prefix string
out string
}{
{
// empty prefix
},
{
prefix: "Foo",
},
{
out: "Abcde.xcframework",
},
}
for _, tc := range tests {
bindPrefix = tc.prefix
if tc.out != "" {
buildO = tc.out
}
buf := new(bytes.Buffer)
xout = buf
gopath = filepath.SplitList(goEnv("GOPATH"))[0]
if goos == "windows" {
os.Setenv("HOMEDRIVE", "C:")
}
cmdBind.flag.Parse([]string{"golang.org/x/mobile/asset"})
if err := runBind(cmdBind); err != nil {
t.Log(buf.String())
t.Fatal(err)
}
got := filepath.ToSlash(buf.String())
output, err := defaultOutputData("")
if err != nil {
t.Fatal(err)
}
data := struct {
outputData
Output string
Prefix string
}{
outputData: output,
Output: buildO[:len(buildO)-len(".xcframework")],
Prefix: tc.prefix,
}
wantBuf := new(bytes.Buffer)
if err := bindAppleTmpl.Execute(wantBuf, data); err != nil {
t.Errorf("%+v: computing diff failed: %v", tc, err)
continue
}
diff, err := diff(got, wantBuf.String())
if err != nil {
t.Errorf("%+v: computing diff failed: %v", tc, err)
continue
}
if diff != "" {
t.Errorf("%+v: unexpected output:\n%s", tc, diff)
}
}
}
var bindAndroidTmpl = template.Must(template.New("output").Parse(`GOMOBILE={{.GOPATH}}/pkg/gomobile
WORK=$WORK
GOOS=android CGO_ENABLED=1 gobind -lang=go,java -outdir=$WORK{{if .JavaPkg}} -javapkg={{.JavaPkg}}{{end}} golang.org/x/mobile/asset
mkdir -p $WORK/src-android-arm
PWD=$WORK/src-android-arm GOMODCACHE=$GOPATH/pkg/mod GOOS=android GOARCH=arm CC=$NDK_PATH/toolchains/llvm/prebuilt/{{.NDKARCH}}/bin/armv7a-linux-androideabi16-clang CXX=$NDK_PATH/toolchains/llvm/prebuilt/{{.NDKARCH}}/bin/armv7a-linux-androideabi16-clang++ CGO_ENABLED=1 GOARM=7 GOPATH=$WORK:$GOPATH go mod tidy
PWD=$WORK/src-android-arm GOMODCACHE=$GOPATH/pkg/mod GOOS=android GOARCH=arm CC=$NDK_PATH/toolchains/llvm/prebuilt/{{.NDKARCH}}/bin/armv7a-linux-androideabi16-clang CXX=$NDK_PATH/toolchains/llvm/prebuilt/{{.NDKARCH}}/bin/armv7a-linux-androideabi16-clang++ CGO_ENABLED=1 GOARM=7 GOPATH=$WORK:$GOPATH go build -x -buildmode=c-shared -o=$WORK/android/src/main/jniLibs/armeabi-v7a/libgojni.so ./gobind
PWD=$WORK/java javac -d $WORK/javac-output -source 1.8 -target 1.8 -bootclasspath {{.AndroidPlatform}}/android.jar *.java
jar c -C $WORK/javac-output .
`))
var bindAppleTmpl = template.Must(template.New("output").Parse(`GOMOBILE={{.GOPATH}}/pkg/gomobile
WORK=$WORK
rm -r -f "{{.Output}}.xcframework"
GOOS=ios CGO_ENABLED=1 gobind -lang=go,objc -outdir=$WORK/ios -tags=ios{{if .Prefix}} -prefix={{.Prefix}}{{end}} golang.org/x/mobile/asset
mkdir -p $WORK/ios/src-arm64
PWD=$WORK/ios/src-arm64 GOMODCACHE=$GOPATH/pkg/mod GOOS=ios GOARCH=arm64 GOFLAGS=-tags=ios CC=iphoneos-clang CXX=iphoneos-clang++ CGO_CFLAGS=-isysroot iphoneos -miphoneos-version-min=13.0 -fembed-bitcode -arch arm64 CGO_CXXFLAGS=-isysroot iphoneos -miphoneos-version-min=13.0 -fembed-bitcode -arch arm64 CGO_LDFLAGS=-isysroot iphoneos -miphoneos-version-min=13.0 -fembed-bitcode -arch arm64 CGO_ENABLED=1 DARWIN_SDK=iphoneos GOPATH=$WORK/ios:$GOPATH go mod tidy
PWD=$WORK/ios/src-arm64 GOMODCACHE=$GOPATH/pkg/mod GOOS=ios GOARCH=arm64 GOFLAGS=-tags=ios CC=iphoneos-clang CXX=iphoneos-clang++ CGO_CFLAGS=-isysroot iphoneos -miphoneos-version-min=13.0 -fembed-bitcode -arch arm64 CGO_CXXFLAGS=-isysroot iphoneos -miphoneos-version-min=13.0 -fembed-bitcode -arch arm64 CGO_LDFLAGS=-isysroot iphoneos -miphoneos-version-min=13.0 -fembed-bitcode -arch arm64 CGO_ENABLED=1 DARWIN_SDK=iphoneos GOPATH=$WORK/ios:$GOPATH go build -x -buildmode=c-archive -o $WORK/{{.Output}}-ios-arm64.a ./gobind
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers
ln -s A $WORK/ios/iphoneos/{{.Output}}.framework/Versions/Current
ln -s Versions/Current/Headers $WORK/ios/iphoneos/{{.Output}}.framework/Headers
ln -s Versions/Current/{{.Output}} $WORK/ios/iphoneos/{{.Output}}.framework/{{.Output}}
xcrun lipo $WORK/{{.Output}}-ios-arm64.a -create -o $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/{{.Output}}
cp $WORK/ios/src/gobind/{{.Prefix}}Asset.objc.h $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers/{{.Prefix}}Asset.objc.h
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers
cp $WORK/ios/src/gobind/Universe.objc.h $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers/Universe.objc.h
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers
cp $WORK/ios/src/gobind/ref.h $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers/ref.h
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Headers
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Resources
ln -s Versions/Current/Resources $WORK/ios/iphoneos/{{.Output}}.framework/Resources
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Resources
mkdir -p $WORK/ios/iphoneos/{{.Output}}.framework/Versions/A/Modules
ln -s Versions/Current/Modules $WORK/ios/iphoneos/{{.Output}}.framework/Modules
xcodebuild -create-xcframework -framework $WORK/ios/iphoneos/{{.Output}}.framework -output {{.Output}}.xcframework
`))
func TestBindAppleAll(t *testing.T) {
if !xcodeAvailable() {
t.Skip("Xcode is missing")
}
defer func() {
xout = os.Stderr
buildN = false
buildX = false
buildO = ""
buildTarget = ""
bindPrefix = ""
}()
buildN = true
buildX = true
buildO = "Asset.xcframework"
buildTarget = "ios"
buf := new(bytes.Buffer)
xout = buf
gopath = filepath.SplitList(goEnv("GOPATH"))[0]
if goos == "windows" {
os.Setenv("HOMEDRIVE", "C:")
}
cmdBind.flag.Parse([]string{"golang.org/x/mobile/asset"})
if err := runBind(cmdBind); err != nil {
t.Log(buf.String())
t.Fatal(err)
}
}
const ambiguousPathsGoMod = `module ambiguouspaths
go 1.18
require golang.org/x/mobile v0.0.0-20230905140555-fbe1c053b6a9
require (
golang.org/x/exp/shiny v0.0.0-20230817173708-d852ddb80c63 // indirect
golang.org/x/image v0.11.0 // indirect
golang.org/x/sys v0.11.0 // indirect
)
`
const ambiguousPathsGoSum = `github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp/shiny v0.0.0-20230817173708-d852ddb80c63 h1:3AGKexOYqL+ztdWdkB1bDwXgPBuTS/S8A4WzuTvJ8Cg=
golang.org/x/exp/shiny v0.0.0-20230817173708-d852ddb80c63/go.mod h1:UH99kUObWAZkDnWqppdQe5ZhPYESUw8I0zVV1uWBR+0=
golang.org/x/image v0.11.0 h1:ds2RoQvBvYTiJkwpSFDwCcDFNX7DqjL2WsUgTNk0Ooo=
golang.org/x/image v0.11.0/go.mod h1:bglhjqbqVuEb9e9+eNR45Jfu7D+T4Qan+NhQk8Ck2P8=
golang.org/x/mobile v0.0.0-20230905140555-fbe1c053b6a9 h1:LaLfQUz4L1tfuOlrtEouZLZ0qHDwKn87E1NKoiudP/o=
golang.org/x/mobile v0.0.0-20230905140555-fbe1c053b6a9/go.mod h1:2jxcxt/JNJik+N+QcB8q308+SyrE3bu43+sGZDmJ02M=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/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-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
`
const ambiguousPathsGo = `package ambiguouspaths
import (
_ "golang.org/x/mobile/app"
)
func Dummy() {}
`
func TestBindWithGoModules(t *testing.T) {
if runtime.GOOS == "android" || runtime.GOOS == "ios" {
t.Skipf("gomobile and gobind are not available on %s", runtime.GOOS)
}
dir := t.TempDir()
if out, err := exec.Command("go", "build", "-o="+dir, "golang.org/x/mobile/cmd/gobind").CombinedOutput(); err != nil {
t.Fatalf("%v: %s", err, string(out))
}
if out, err := exec.Command("go", "build", "-o="+dir, "golang.org/x/mobile/cmd/gomobile").CombinedOutput(); err != nil {
t.Fatalf("%v: %s", err, string(out))
}
path := dir
if p := os.Getenv("PATH"); p != "" {
path += string(filepath.ListSeparator) + p
}
// Create a source package dynamically to avoid go.mod files in this repository. See golang/go#34352 for more details.
if err := os.Mkdir(filepath.Join(dir, "ambiguouspaths"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "ambiguouspaths", "go.mod"), []byte(ambiguousPathsGoMod), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "ambiguouspaths", "go.sum"), []byte(ambiguousPathsGoSum), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "ambiguouspaths", "ambiguouspaths.go"), []byte(ambiguousPathsGo), 0644); err != nil {
t.Fatal(err)
}
for _, target := range []string{"android", "ios"} {
target := target
t.Run(target, func(t *testing.T) {
switch target {
case "android":
if _, err := sdkpath.AndroidAPIPath(minAndroidAPI); err != nil {
t.Skip("No compatible Android API platform found, skipping bind")
}
case "ios":
if !xcodeAvailable() {
t.Skip("Xcode is missing")
}
}
var out string
switch target {
case "android":
out = filepath.Join(dir, "cgopkg.aar")
case "ios":
out = filepath.Join(dir, "Cgopkg.xcframework")
}
tests := []struct {
Name string
Path string
Dir string
}{
{
Name: "Absolute Path",
Path: "golang.org/x/mobile/bind/testdata/cgopkg",
},
{
Name: "Relative Path",
Path: "./bind/testdata/cgopkg",
Dir: filepath.Join("..", ".."),
},
{
Name: "Ambiguous Paths",
Path: ".",
Dir: filepath.Join(dir, "ambiguouspaths"),
},
}
for _, tc := range tests {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
cmd := exec.Command(filepath.Join(dir, "gomobile"), "bind", "-target="+target, "-o="+out, tc.Path)
cmd.Env = append(os.Environ(), "PATH="+path, "GO111MODULE=on")
cmd.Dir = tc.Dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Errorf("gomobile bind failed: %v\n%s", err, string(out))
}
})
}
})
}
}
|
mobile/cmd/gomobile/bind_test.go/0
|
{
"file_path": "mobile/cmd/gomobile/bind_test.go",
"repo_id": "mobile",
"token_count": 7468
}
| 602 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"os"
"os/exec"
"path"
"strings"
)
var cmdInstall = &command{
run: runInstall,
Name: "install",
Usage: "[-target android] [build flags] [package]",
Short: "compile android APK and install on device",
Long: `
Install compiles and installs the app named by the import path on the
attached mobile device.
Only -target android is supported. The 'adb' tool must be on the PATH.
The build flags -a, -i, -n, -x, -gcflags, -ldflags, -tags, -trimpath, and -work are
shared with the build command.
For documentation, see 'go help build'.
`,
}
func runInstall(cmd *command) error {
if !strings.HasPrefix(buildTarget, "android") {
return fmt.Errorf("install is not supported for -target=%s", buildTarget)
}
pkg, err := runBuildImpl(cmd)
if err != nil {
return err
}
// Don't use runCmd as adb does not return a useful exit code.
c := exec.Command(
`adb`,
`install`,
`-r`,
androidPkgName(path.Base(pkg.PkgPath))+`.apk`,
)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if buildX || buildN {
printcmd("%s", strings.Join(c.Args, " "))
}
if buildN {
return nil
}
return c.Run()
}
|
mobile/cmd/gomobile/install.go/0
|
{
"file_path": "mobile/cmd/gomobile/install.go",
"repo_id": "mobile",
"token_count": 478
}
| 603 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.