text
stringlengths
2
1.1M
id
stringlengths
11
117
metadata
dict
__index_level_0__
int64
0
885
// run //go:build !nacl && !js // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Test that buffered channels are garbage collected properly. // An interesting case because they have finalizers and used to // have self loops that kept them from being collected. // (Cyclic data with finalizers is never finalized, nor collected.) package main import ( "fmt" "os" "runtime" ) func main() { const N = 10000 st := new(runtime.MemStats) memstats := new(runtime.MemStats) runtime.ReadMemStats(st) for i := 0; i < N; i++ { c := make(chan int, 10) _ = c if i%100 == 0 { for j := 0; j < 4; j++ { runtime.GC() runtime.Gosched() runtime.GC() runtime.Gosched() } } } runtime.ReadMemStats(memstats) obj := int64(memstats.HeapObjects - st.HeapObjects) if obj > N/5 { fmt.Println("too many objects left:", obj) os.Exit(1) } }
go/test/gc2.go/0
{ "file_path": "go/test/gc2.go", "repo_id": "go", "token_count": 365 }
549
// 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. // Verify that various kinds of "imported and not used" // errors are caught by the compiler. // Does not compile. package main // standard import "fmt" // ERROR "imported and not used.*fmt|\x22fmt\x22 imported and not used" // renamed import X "math" // ERROR "imported and not used.*math|\x22math\x22 imported as X and not used" // import dot import . "bufio" // ERROR "imported and not used.*bufio|imported and not used" // again, package without anything in it import "./empty" // ERROR "imported and not used.*empty|imported and not used" import Z "./empty" // ERROR "imported and not used.*empty|imported as Z and not used" import . "./empty" // ERROR "imported and not used.*empty|imported and not used"
go/test/import4.dir/import4.go/0
{ "file_path": "go/test/import4.dir/import4.go", "repo_id": "go", "token_count": 263 }
550
// 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. // Verify that initialization loops are caught // and that the errors print correctly. package main var ( x int = a a int = b // ERROR "a refers to\n.*b refers to\n.*c refers to\n.*a|initialization loop" b int = c c int = a )
go/test/initloop.go/0
{ "file_path": "go/test/initloop.go", "repo_id": "go", "token_count": 124 }
551
// 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 composite literals. package main type M map[int]int type S struct{ a,b,c int }; type SS struct{ aa,bb,cc S }; type SA struct{ a,b,c [3]int }; type SC struct{ a,b,c []int }; type SM struct{ a,b,c M }; func main() { test("s.a", s.a); test("s.b", s.b); test("s.c", s.c); test("ss.aa.a", ss.aa.a); test("ss.aa.b", ss.aa.b); test("ss.aa.c", ss.aa.c); test("ss.bb.a", ss.bb.a); test("ss.bb.b", ss.bb.b); test("ss.bb.c", ss.bb.c); test("ss.cc.a", ss.cc.a); test("ss.cc.b", ss.cc.b); test("ss.cc.c", ss.cc.c); for i:=0; i<3; i++ { test("a[i]", a[i]); test("c[i]", c[i]); test("m[i]", m[i]); test("as[i].a", as[i].a); test("as[i].b", as[i].b); test("as[i].c", as[i].c); test("cs[i].a", cs[i].a); test("cs[i].b", cs[i].b); test("cs[i].c", cs[i].c); test("ms[i].a", ms[i].a); test("ms[i].b", ms[i].b); test("ms[i].c", ms[i].c); test("sa.a[i]", sa.a[i]); test("sa.b[i]", sa.b[i]); test("sa.c[i]", sa.c[i]); test("sc.a[i]", sc.a[i]); test("sc.b[i]", sc.b[i]); test("sc.c[i]", sc.c[i]); test("sm.a[i]", sm.a[i]); test("sm.b[i]", sm.b[i]); test("sm.c[i]", sm.c[i]); for j:=0; j<3; j++ { test("aa[i][j]", aa[i][j]); test("ac[i][j]", ac[i][j]); test("am[i][j]", am[i][j]); test("ca[i][j]", ca[i][j]); test("cc[i][j]", cc[i][j]); test("cm[i][j]", cm[i][j]); test("ma[i][j]", ma[i][j]); test("mc[i][j]", mc[i][j]); test("mm[i][j]", mm[i][j]); } } } var ref = 0; func test(xs string, x int) { if ref >= len(answers) { println(xs, x); return; } if x != answers[ref] { println(xs, "is", x, "should be", answers[ref]) } ref++; } var a = [3]int{1001, 1002, 1003} var s = S{1101, 1102, 1103} var c = []int{1201, 1202, 1203} var m = M{0:1301, 1:1302, 2:1303} var aa = [3][3]int{[3]int{2001,2002,2003}, [3]int{2004,2005,2006}, [3]int{2007,2008,2009}} var as = [3]S{S{2101,2102,2103},S{2104,2105,2106},S{2107,2108,2109}} var ac = [3][]int{[]int{2201,2202,2203}, []int{2204,2205,2206}, []int{2207,2208,2209}} var am = [3]M{M{0:2301,1:2302,2:2303}, M{0:2304,1:2305,2:2306}, M{0:2307,1:2308,2:2309}} var sa = SA{[3]int{3001,3002,3003},[3]int{3004,3005,3006},[3]int{3007,3008,3009}} var ss = SS{S{3101,3102,3103},S{3104,3105,3106},S{3107,3108,3109}} var sc = SC{[]int{3201,3202,3203},[]int{3204,3205,3206},[]int{3207,3208,3209}} var sm = SM{M{0:3301,1:3302,2:3303}, M{0:3304,1:3305,2:3306}, M{0:3307,1:3308,2:3309}} var ca = [][3]int{[3]int{4001,4002,4003}, [3]int{4004,4005,4006}, [3]int{4007,4008,4009}} var cs = []S{S{4101,4102,4103},S{4104,4105,4106},S{4107,4108,4109}} var cc = [][]int{[]int{4201,4202,4203}, []int{4204,4205,4206}, []int{4207,4208,4209}} var cm = []M{M{0:4301,1:4302,2:4303}, M{0:4304,1:4305,2:4306}, M{0:4307,1:4308,2:4309}} var ma = map[int][3]int{0:[3]int{5001,5002,5003}, 1:[3]int{5004,5005,5006}, 2:[3]int{5007,5008,5009}} var ms = map[int]S{0:S{5101,5102,5103},1:S{5104,5105,5106},2:S{5107,5108,5109}} var mc = map[int][]int{0:[]int{5201,5202,5203}, 1:[]int{5204,5205,5206}, 2:[]int{5207,5208,5209}} var mm = map[int]M{0:M{0:5301,1:5302,2:5303}, 1:M{0:5304,1:5305,2:5306}, 2:M{0:5307,1:5308,2:5309}} var answers = [...]int { // s 1101, 1102, 1103, // ss 3101, 3102, 3103, 3104, 3105, 3106, 3107, 3108, 3109, // [0] 1001, 1201, 1301, 2101, 2102, 2103, 4101, 4102, 4103, 5101, 5102, 5103, 3001, 3004, 3007, 3201, 3204, 3207, 3301, 3304, 3307, // [0][j] 2001, 2201, 2301, 4001, 4201, 4301, 5001, 5201, 5301, 2002, 2202, 2302, 4002, 4202, 4302, 5002, 5202, 5302, 2003, 2203, 2303, 4003, 4203, 4303, 5003, 5203, 5303, // [1] 1002, 1202, 1302, 2104, 2105, 2106, 4104, 4105, 4106, 5104, 5105, 5106, 3002, 3005, 3008, 3202, 3205, 3208, 3302, 3305, 3308, // [1][j] 2004, 2204, 2304, 4004, 4204, 4304, 5004, 5204, 5304, 2005, 2205, 2305, 4005, 4205, 4305, 5005, 5205, 5305, 2006, 2206, 2306, 4006, 4206, 4306, 5006, 5206, 5306, // [2] 1003, 1203, 1303, 2107, 2108, 2109, 4107, 4108, 4109, 5107, 5108, 5109, 3003, 3006, 3009, 3203, 3206, 3209, 3303, 3306, 3309, // [2][j] 2007, 2207, 2307, 4007, 4207, 4307, 5007, 5207, 5307, 2008, 2208, 2308, 4008, 4208, 4308, 5008, 5208, 5308, 2009, 2209, 2309, 4009, 4209, 4309, 5009, 5209, 5309, }
go/test/ken/complit.go/0
{ "file_path": "go/test/ken/complit.go", "repo_id": "go", "token_count": 2492 }
552
// 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 goto and labels. package main func main() { i := 0 if false { goto gogoloop } if false { goto gogoloop } if false { goto gogoloop } goto gogoloop // backward declared loop: i = i + 1 if i < 100 { goto loop } return gogoloop: goto loop }
go/test/ken/label.go/0
{ "file_path": "go/test/ken/label.go", "repo_id": "go", "token_count": 174 }
553
// 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 simple switch. package main func main() { r := "" a := 3 for i := 0; i < 10; i = i + 1 { switch i { case 5: r += "five" case a, 7: r += "a" default: r += string(i + '0') } r += "out" + string(i+'0') } if r != "0out01out12out2aout34out4fiveout56out6aout78out89out9" { panic(r) } }
go/test/ken/simpswitch.go/0
{ "file_path": "go/test/ken/simpswitch.go", "repo_id": "go", "token_count": 211 }
554
// errorcheck // 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. // Ensure that typed non-integer, negative and too large // values are not accepted as size argument in make for // maps. package main type T map[int]int var sink T func main() { sink = make(T, -1) // ERROR "negative size argument in make.*|must not be negative" sink = make(T, uint64(1<<63)) // ERROR "size argument too large in make.*|overflows int" // Test that errors are emitted at call sites, not const declarations const x = -1 sink = make(T, x) // ERROR "negative size argument in make.*|must not be negative" const y = uint64(1 << 63) sink = make(T, y) // ERROR "size argument too large in make.*|overflows int" sink = make(T, 0.5) // ERROR "constant 0.5 truncated to integer|truncated to int" sink = make(T, 1.0) sink = make(T, float32(1.0)) // ERROR "non-integer size argument in make.*|must be integer" sink = make(T, float64(1.0)) // ERROR "non-integer size argument in make.*|must be integer" sink = make(T, 1+0i) sink = make(T, complex64(1+0i)) // ERROR "non-integer size argument in make.*|must be integer" sink = make(T, complex128(1+0i)) // ERROR "non-integer size argument in make.*|must be integer" }
go/test/makemap.go/0
{ "file_path": "go/test/makemap.go", "repo_id": "go", "token_count": 446 }
555
// 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 the 'for range' construct. package main // test range over channels func gen(c chan int, lo, hi int) { for i := lo; i <= hi; i++ { c <- i } close(c) } func seq(lo, hi int) chan int { c := make(chan int) go gen(c, lo, hi) return c } const alphabet = "abcdefghijklmnopqrstuvwxyz" func testblankvars() { n := 0 for range alphabet { n++ } if n != 26 { println("for range: wrong count", n, "want 26") panic("fail") } n = 0 for _ = range alphabet { n++ } if n != 26 { println("for _ = range: wrong count", n, "want 26") panic("fail") } n = 0 for _, _ = range alphabet { n++ } if n != 26 { println("for _, _ = range: wrong count", n, "want 26") panic("fail") } s := 0 for i, _ := range alphabet { s += i } if s != 325 { println("for i, _ := range: wrong sum", s, "want 325") panic("fail") } r := rune(0) for _, v := range alphabet { r += v } if r != 2847 { println("for _, v := range: wrong sum", r, "want 2847") panic("fail") } } func testchan() { s := "" for i := range seq('a', 'z') { s += string(i) } if s != alphabet { println("Wanted lowercase alphabet; got", s) panic("fail") } n := 0 for range seq('a', 'z') { n++ } if n != 26 { println("testchan wrong count", n, "want 26") panic("fail") } } // test that range over slice only evaluates // the expression after "range" once. var nmake = 0 func makeslice() []int { nmake++ return []int{1, 2, 3, 4, 5} } func testslice() { s := 0 nmake = 0 for _, v := range makeslice() { s += v } if nmake != 1 { println("range called makeslice", nmake, "times") panic("fail") } if s != 15 { println("wrong sum ranging over makeslice", s) panic("fail") } x := []int{10, 20} y := []int{99} i := 1 for i, x[i] = range y { break } if i != 0 || x[0] != 10 || x[1] != 99 { println("wrong parallel assignment", i, x[0], x[1]) panic("fail") } } func testslice1() { s := 0 nmake = 0 for i := range makeslice() { s += i } if nmake != 1 { println("range called makeslice", nmake, "times") panic("fail") } if s != 10 { println("wrong sum ranging over makeslice", s) panic("fail") } } func testslice2() { n := 0 nmake = 0 for range makeslice() { n++ } if nmake != 1 { println("range called makeslice", nmake, "times") panic("fail") } if n != 5 { println("wrong count ranging over makeslice", n) panic("fail") } } // test that range over []byte(string) only evaluates // the expression after "range" once. func makenumstring() string { nmake++ return "\x01\x02\x03\x04\x05" } func testslice3() { s := byte(0) nmake = 0 for _, v := range []byte(makenumstring()) { s += v } if nmake != 1 { println("range called makenumstring", nmake, "times") panic("fail") } if s != 15 { println("wrong sum ranging over []byte(makenumstring)", s) panic("fail") } } // test that range over array only evaluates // the expression after "range" once. func makearray() [5]int { nmake++ return [5]int{1, 2, 3, 4, 5} } func testarray() { s := 0 nmake = 0 for _, v := range makearray() { s += v } if nmake != 1 { println("range called makearray", nmake, "times") panic("fail") } if s != 15 { println("wrong sum ranging over makearray", s) panic("fail") } } func testarray1() { s := 0 nmake = 0 for i := range makearray() { s += i } if nmake != 1 { println("range called makearray", nmake, "times") panic("fail") } if s != 10 { println("wrong sum ranging over makearray", s) panic("fail") } } func testarray2() { n := 0 nmake = 0 for range makearray() { n++ } if nmake != 1 { println("range called makearray", nmake, "times") panic("fail") } if n != 5 { println("wrong count ranging over makearray", n) panic("fail") } } func makearrayptr() *[5]int { nmake++ return &[5]int{1, 2, 3, 4, 5} } func testarrayptr() { nmake = 0 x := len(makearrayptr()) if x != 5 || nmake != 1 { println("len called makearrayptr", nmake, "times and got len", x) panic("fail") } nmake = 0 x = cap(makearrayptr()) if x != 5 || nmake != 1 { println("cap called makearrayptr", nmake, "times and got len", x) panic("fail") } s := 0 nmake = 0 for _, v := range makearrayptr() { s += v } if nmake != 1 { println("range called makearrayptr", nmake, "times") panic("fail") } if s != 15 { println("wrong sum ranging over makearrayptr", s) panic("fail") } } func testarrayptr1() { s := 0 nmake = 0 for i := range makearrayptr() { s += i } if nmake != 1 { println("range called makearrayptr", nmake, "times") panic("fail") } if s != 10 { println("wrong sum ranging over makearrayptr", s) panic("fail") } } func testarrayptr2() { n := 0 nmake = 0 for range makearrayptr() { n++ } if nmake != 1 { println("range called makearrayptr", nmake, "times") panic("fail") } if n != 5 { println("wrong count ranging over makearrayptr", n) panic("fail") } } // test that range over string only evaluates // the expression after "range" once. func makestring() string { nmake++ return "abcd☺" } func teststring() { var s rune nmake = 0 for _, v := range makestring() { s += v } if nmake != 1 { println("range called makestring", nmake, "times") panic("fail") } if s != 'a'+'b'+'c'+'d'+'☺' { println("wrong sum ranging over makestring", s) panic("fail") } x := []rune{'a', 'b'} i := 1 for i, x[i] = range "c" { break } if i != 0 || x[0] != 'a' || x[1] != 'c' { println("wrong parallel assignment", i, x[0], x[1]) panic("fail") } y := []int{1, 2, 3} r := rune(1) for y[r], r = range "\x02" { break } if r != 2 || y[0] != 1 || y[1] != 0 || y[2] != 3 { println("wrong parallel assignment", r, y[0], y[1], y[2]) panic("fail") } } func teststring1() { s := 0 nmake = 0 for i := range makestring() { s += i } if nmake != 1 { println("range called makestring", nmake, "times") panic("fail") } if s != 10 { println("wrong sum ranging over makestring", s) panic("fail") } } func teststring2() { n := 0 nmake = 0 for range makestring() { n++ } if nmake != 1 { println("range called makestring", nmake, "times") panic("fail") } if n != 5 { println("wrong count ranging over makestring", n) panic("fail") } } // test that range over map only evaluates // the expression after "range" once. func makemap() map[int]int { nmake++ return map[int]int{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: '☺'} } func testmap() { s := 0 nmake = 0 for _, v := range makemap() { s += v } if nmake != 1 { println("range called makemap", nmake, "times") panic("fail") } if s != 'a'+'b'+'c'+'d'+'☺' { println("wrong sum ranging over makemap", s) panic("fail") } } func testmap1() { s := 0 nmake = 0 for i := range makemap() { s += i } if nmake != 1 { println("range called makemap", nmake, "times") panic("fail") } if s != 10 { println("wrong sum ranging over makemap", s) panic("fail") } } func testmap2() { n := 0 nmake = 0 for range makemap() { n++ } if nmake != 1 { println("range called makemap", nmake, "times") panic("fail") } if n != 5 { println("wrong count ranging over makemap", n) panic("fail") } } // test that range evaluates the index and value expressions // exactly once per iteration. var ncalls = 0 func getvar(p *int) *int { ncalls++ return p } func testcalls() { var i, v int si := 0 sv := 0 for *getvar(&i), *getvar(&v) = range [2]int{1, 2} { si += i sv += v } if ncalls != 4 { println("wrong number of calls:", ncalls, "!= 4") panic("fail") } if si != 1 || sv != 3 { println("wrong sum in testcalls", si, sv) panic("fail") } ncalls = 0 for *getvar(&i), *getvar(&v) = range [0]int{} { println("loop ran on empty array") panic("fail") } if ncalls != 0 { println("wrong number of calls:", ncalls, "!= 0") panic("fail") } } func main() { testblankvars() testchan() testarray() testarray1() testarray2() testarrayptr() testarrayptr1() testarrayptr2() testslice() testslice1() testslice2() testslice3() teststring() teststring1() teststring2() testmap() testmap1() testmap2() testcalls() }
go/test/range.go/0
{ "file_path": "go/test/range.go", "repo_id": "go", "token_count": 3544 }
556
// 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. // Similar to reflectmethod5.go, but for reflect.Type.MethodByName. package main import "reflect" var called bool type foo struct{} func (foo) X() { called = true } var h = reflect.Type.MethodByName func main() { v := reflect.ValueOf(foo{}) m, ok := h(v.Type(), "X") if !ok { panic("FAIL") } f := m.Func.Interface().(func(foo)) f(foo{}) if !called { panic("FAIL") } }
go/test/reflectmethod6.go/0
{ "file_path": "go/test/reflectmethod6.go", "repo_id": "go", "token_count": 204 }
557
// compile // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Test rune constants, expressions and types. // Compiles but does not run. package rune var ( r0 = 'a' r1 = 'a'+1 r2 = 1+'a' r3 = 'a'*2 r4 = 'a'/2 r5 = 'a'<<1 r6 = 'b'<<2 r7 int32 r = []rune{r0, r1, r2, r3, r4, r5, r6, r7} ) var ( f0 = 1.2 f1 = 1.2/'a' f = []float64{f0, f1} ) var ( i0 = 1 i1 = 1<<'\x01' i = []int{i0, i1} ) const ( maxRune = '\U0010FFFF' ) var ( b0 = maxRune < r0 b = []bool{b0} )
go/test/rune.go/0
{ "file_path": "go/test/rune.go", "repo_id": "go", "token_count": 305 }
558
// build // 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 general operation by solving a peg solitaire game. // A version of this is in the Go playground. // Don't run it - produces too much output. // This program solves the (English) peg solitaire board game. // See also: http://en.wikipedia.org/wiki/Peg_solitaire package main const N = 11 + 1 // length of a board row (+1 for newline) // The board must be surrounded by 2 illegal fields in each direction // so that move() doesn't need to check the board boundaries. Periods // represent illegal fields, ● are pegs, and ○ are holes. var board = []rune( `........... ........... ....●●●.... ....●●●.... ..●●●●●●●.. ..●●●○●●●.. ..●●●●●●●.. ....●●●.... ....●●●.... ........... ........... `) // center is the position of the center hole if there is a single one; // otherwise it is -1. var center int func init() { n := 0 for pos, field := range board { if field == '○' { center = pos n++ } } if n != 1 { center = -1 // no single hole } } var moves int // number of times move is called // move tests if there is a peg at position pos that can jump over another peg // in direction dir. If the move is valid, it is executed and move returns true. // Otherwise, move returns false. func move(pos, dir int) bool { moves++ if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' { board[pos] = '○' board[pos+dir] = '○' board[pos+2*dir] = '●' return true } return false } // unmove reverts a previously executed valid move. func unmove(pos, dir int) { board[pos] = '●' board[pos+dir] = '●' board[pos+2*dir] = '○' } // solve tries to find a sequence of moves such that there is only one peg left // at the end; if center is >= 0, that last peg must be in the center position. // If a solution is found, solve prints the board after each move in a backward // fashion (i.e., the last board position is printed first, all the way back to // the starting board position). func solve() bool { var last, n int for pos, field := range board { // try each board position if field == '●' { // found a peg for _, dir := range [...]int{-1, -N, +1, +N} { // try each direction if move(pos, dir) { // a valid move was found and executed, // see if this new board has a solution if solve() { unmove(pos, dir) println(string(board)) return true } unmove(pos, dir) } } last = pos n++ } } // tried each possible move if n == 1 && (center < 0 || last == center) { // there's only one peg left println(string(board)) return true } // no solution found for this board return false } func main() { if !solve() { println("no solution found") } println(moves, "moves tried") }
go/test/solitaire.go/0
{ "file_path": "go/test/solitaire.go", "repo_id": "go", "token_count": 1023 }
559
// errorcheck // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Verify that erroneous switch statements are detected by the compiler. // Does not compile. package main type I interface { M() } func bad() { i5 := 5 switch i5 { case 5: fallthrough // ERROR "cannot fallthrough final case in switch" } } func good() { var i interface{} var s string switch i { case s: } switch s { case i: } }
go/test/switch4.go/0
{ "file_path": "go/test/switch4.go", "repo_id": "go", "token_count": 172 }
560
// 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. // Make sure we handle instantiated empty interfaces. package main type E[T any] interface { } //go:noinline func f[T any](x E[T]) interface{} { return x } //go:noinline func g[T any](x interface{}) E[T] { return x } type I[T any] interface { foo() } type myint int func (x myint) foo() {} //go:noinline func h[T any](x I[T]) interface{ foo() } { return x } //go:noinline func i[T any](x interface{ foo() }) I[T] { return x } func main() { if f[int](1) != 1 { println("test 1 failed") } if f[int](2) != (interface{})(2) { println("test 2 failed") } if g[int](3) != 3 { println("test 3 failed") } if g[int](4) != (E[int])(4) { println("test 4 failed") } if h[int](myint(5)) != myint(5) { println("test 5 failed") } if h[int](myint(6)) != interface{ foo() }(myint(6)) { println("test 6 failed") } if i[int](myint(7)) != myint(7) { println("test 7 failed") } if i[int](myint(8)) != I[int](myint(8)) { println("test 8 failed") } }
go/test/typeparam/eface.go/0
{ "file_path": "go/test/typeparam/eface.go", "repo_id": "go", "token_count": 476 }
561
// 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. // Test that we can convert type parameters to both empty // and nonempty interfaces, and named and nonnamed versions // thereof. package main import "fmt" type E interface{} func f[T any](x T) interface{} { var i interface{} = x return i } func fs[T any](x T) interface{} { y := []T{x} var i interface{} = y return i } func g[T any](x T) E { var i E = x return i } type C interface { foo() int } type myInt int func (x myInt) foo() int { return int(x + 1) } func h[T C](x T) interface{ foo() int } { var i interface{ foo() int } = x return i } func i[T C](x T) C { var i C = x // conversion in assignment return i } func j[T C](t T) C { return C(t) // explicit conversion } func js[T any](x T) interface{} { y := []T{x} return interface{}(y) } func main() { if got, want := f[int](7), 7; got != want { panic(fmt.Sprintf("got %d want %d", got, want)) } if got, want := fs[int](7), []int{7}; got.([]int)[0] != want[0] { panic(fmt.Sprintf("got %d want %d", got, want)) } if got, want := g[int](7), 7; got != want { panic(fmt.Sprintf("got %d want %d", got, want)) } if got, want := h[myInt](7).foo(), 8; got != want { panic(fmt.Sprintf("got %d want %d", got, want)) } if got, want := i[myInt](7).foo(), 8; got != want { panic(fmt.Sprintf("got %d want %d", got, want)) } if got, want := j[myInt](7).foo(), 8; got != want { panic(fmt.Sprintf("got %d want %d", got, want)) } if got, want := js[int](7), []int{7}; got.([]int)[0] != want[0] { panic(fmt.Sprintf("got %d want %d", got, want)) } }
go/test/typeparam/ifaceconv.go/0
{ "file_path": "go/test/typeparam/ifaceconv.go", "repo_id": "go", "token_count": 703 }
562
// 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 type Src1[T any] func() Src1[T] func (s *Src1[T]) Next() { *s = (*s)() } type Src2[T any] []func() Src2[T] func (s Src2[T]) Next() { _ = s[0]() } type Src3[T comparable] map[T]func() Src3[T] func (s Src3[T]) Next() { var a T _ = s[a]() } type Src4[T any] chan func() T func (s Src4[T]) Next() { _ = (<-s)() } type Src5[T any] func() Src5[T] func (s Src5[T]) Next() { var x interface{} = s _ = (x.(Src5[T]))() } func main() { var src1 Src1[int] src1.Next() var src2 Src2[int] src2.Next() var src3 Src3[string] src3.Next() var src4 Src4[int] src4.Next() var src5 Src5[int] src5.Next() }
go/test/typeparam/issue47878.go/0
{ "file_path": "go/test/typeparam/issue47878.go", "repo_id": "go", "token_count": 384 }
563
// 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 Pair[L, R any] struct { L L R R } func Two[L, R any](l L, r R) Pair[L, R] { return Pair[L, R]{L: l, R: r} } type Map[K, V any] interface { Put(K, V) Len() int Iterate(func(Pair[K, V]) bool) } type HashMap[K comparable, V any] struct { m map[K]V } func NewHashMap[K comparable, V any](capacity int) HashMap[K, V] { var m map[K]V if capacity >= 1 { m = make(map[K]V, capacity) } else { m = map[K]V{} } return HashMap[K, V]{m: m} } func (m HashMap[K, V]) Put(k K, v V) { m.m[k] = v } func (m HashMap[K, V]) Len() int { return len(m.m) } func (m HashMap[K, V]) Iterate(cb func(Pair[K, V]) bool) { for k, v := range m.m { if !cb(Two(k, v)) { return } } }
go/test/typeparam/issue48716.dir/a.go/0
{ "file_path": "go/test/typeparam/issue48716.dir/a.go", "repo_id": "go", "token_count": 396 }
564
// 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 R[T any] struct{ v T } func (r R[T]) Self() R[T] { return R[T]{} } type Fn[T any] func() R[T] func X() (r R[int]) { return r.Self() } func Y[T any](a Fn[T]) Fn[int] { return func() (r R[int]) { // No crash: return R[int]{} return r.Self() } }
go/test/typeparam/issue49246.dir/a.go/0
{ "file_path": "go/test/typeparam/issue49246.dir/a.go", "repo_id": "go", "token_count": 170 }
565
// 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 Complex interface { ~complex64 | ~complex128 } func zero[T Complex]() T { return T(0) } func pi[T Complex]() T { return T(3.14) } func sqrtN1[T Complex]() T { return T(-1i) } func main() { fmt.Println(zero[complex128]()) fmt.Println(pi[complex128]()) fmt.Println(sqrtN1[complex128]()) fmt.Println(zero[complex64]()) fmt.Println(pi[complex64]()) fmt.Println(sqrtN1[complex64]()) }
go/test/typeparam/issue50193.go/0
{ "file_path": "go/test/typeparam/issue50193.go", "repo_id": "go", "token_count": 239 }
566
xe [1] ye [2 3] x [[1]] SetEq [1] [2 3]
go/test/typeparam/issue51303.out/0
{ "file_path": "go/test/typeparam/issue51303.out", "repo_id": "go", "token_count": 27 }
567
// 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 type T1 struct{} type T2 struct{} type Both struct { T1 T2 } func (T1) m() { panic("FAIL") } func (T2) m() { panic("FAIL") } func (Both) m() {} func f[T interface{ m() }](c T) { c.m() } func main() { var b Both b.m() f(b) }
go/test/typeparam/issue53419.go/0
{ "file_path": "go/test/typeparam/issue53419.go", "repo_id": "go", "token_count": 170 }
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 list provides a doubly linked list of some element type // (generic form of the "container/list" package). package main import ( "fmt" "strconv" ) // _Element is an element of a linked list. type _Element[T any] struct { // Next and previous pointers in the doubly-linked list of elements. // To simplify the implementation, internally a list l is implemented // as a ring, such that &l.root is both the next element of the last // list element (l.Back()) and the previous element of the first list // element (l.Front()). next, prev *_Element[T] // The list to which this element belongs. list *_List[T] // The value stored with this element. Value T } // Next returns the next list element or nil. func (e *_Element[T]) Next() *_Element[T] { if p := e.next; e.list != nil && p != &e.list.root { return p } return nil } // Prev returns the previous list element or nil. func (e *_Element[T]) Prev() *_Element[T] { if p := e.prev; e.list != nil && p != &e.list.root { return p } return nil } // _List represents a doubly linked list. // The zero value for _List is an empty list ready to use. type _List[T any] struct { root _Element[T] // sentinel list element, only &root, root.prev, and root.next are used len int // current list length excluding (this) sentinel element } // Init initializes or clears list l. func (l *_List[T]) Init() *_List[T] { l.root.next = &l.root l.root.prev = &l.root l.len = 0 return l } // New returns an initialized list. func _New[T any]() *_List[T] { return new(_List[T]).Init() } // Len returns the number of elements of list l. // The complexity is O(1). func (l *_List[_]) Len() int { return l.len } // Front returns the first element of list l or nil if the list is empty. func (l *_List[T]) Front() *_Element[T] { if l.len == 0 { return nil } return l.root.next } // Back returns the last element of list l or nil if the list is empty. func (l *_List[T]) Back() *_Element[T] { if l.len == 0 { return nil } return l.root.prev } // lazyInit lazily initializes a zero _List value. func (l *_List[_]) lazyInit() { if l.root.next == nil { l.Init() } } // insert inserts e after at, increments l.len, and returns e. func (l *_List[T]) insert(e, at *_Element[T]) *_Element[T] { e.prev = at e.next = at.next e.prev.next = e e.next.prev = e e.list = l l.len++ return e } // insertValue is a convenience wrapper for insert(&_Element[T]{Value: v}, at). func (l *_List[T]) insertValue(v T, at *_Element[T]) *_Element[T] { return l.insert(&_Element[T]{Value: v}, at) } // remove removes e from its list, decrements l.len, and returns e. func (l *_List[T]) remove(e *_Element[T]) *_Element[T] { e.prev.next = e.next e.next.prev = e.prev e.next = nil // avoid memory leaks e.prev = nil // avoid memory leaks e.list = nil l.len-- return e } // move moves e to next to at and returns e. func (l *_List[T]) move(e, at *_Element[T]) *_Element[T] { if e == at { return e } e.prev.next = e.next e.next.prev = e.prev e.prev = at e.next = at.next e.prev.next = e e.next.prev = e return e } // Remove removes e from l if e is an element of list l. // It returns the element value e.Value. // The element must not be nil. func (l *_List[T]) Remove(e *_Element[T]) T { if e.list == l { // if e.list == l, l must have been initialized when e was inserted // in l or l == nil (e is a zero _Element) and l.remove will crash l.remove(e) } return e.Value } // PushFront inserts a new element e with value v at the front of list l and returns e. func (l *_List[T]) PushFront(v T) *_Element[T] { l.lazyInit() return l.insertValue(v, &l.root) } // PushBack inserts a new element e with value v at the back of list l and returns e. func (l *_List[T]) PushBack(v T) *_Element[T] { l.lazyInit() return l.insertValue(v, l.root.prev) } // InsertBefore inserts a new element e with value v immediately before mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. func (l *_List[T]) InsertBefore(v T, mark *_Element[T]) *_Element[T] { if mark.list != l { return nil } // see comment in _List.Remove about initialization of l return l.insertValue(v, mark.prev) } // InsertAfter inserts a new element e with value v immediately after mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. func (l *_List[T]) InsertAfter(v T, mark *_Element[T]) *_Element[T] { if mark.list != l { return nil } // see comment in _List.Remove about initialization of l return l.insertValue(v, mark) } // MoveToFront moves element e to the front of list l. // If e is not an element of l, the list is not modified. // The element must not be nil. func (l *_List[T]) MoveToFront(e *_Element[T]) { if e.list != l || l.root.next == e { return } // see comment in _List.Remove about initialization of l l.move(e, &l.root) } // MoveToBack moves element e to the back of list l. // If e is not an element of l, the list is not modified. // The element must not be nil. func (l *_List[T]) MoveToBack(e *_Element[T]) { if e.list != l || l.root.prev == e { return } // see comment in _List.Remove about initialization of l l.move(e, l.root.prev) } // MoveBefore moves element e to its new position before mark. // If e or mark is not an element of l, or e == mark, the list is not modified. // The element and mark must not be nil. func (l *_List[T]) MoveBefore(e, mark *_Element[T]) { if e.list != l || e == mark || mark.list != l { return } l.move(e, mark.prev) } // MoveAfter moves element e to its new position after mark. // If e or mark is not an element of l, or e == mark, the list is not modified. // The element and mark must not be nil. func (l *_List[T]) MoveAfter(e, mark *_Element[T]) { if e.list != l || e == mark || mark.list != l { return } l.move(e, mark) } // PushBackList inserts a copy of an other list at the back of list l. // The lists l and other may be the same. They must not be nil. func (l *_List[T]) PushBackList(other *_List[T]) { l.lazyInit() for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() { l.insertValue(e.Value, l.root.prev) } } // PushFrontList inserts a copy of an other list at the front of list l. // The lists l and other may be the same. They must not be nil. func (l *_List[T]) PushFrontList(other *_List[T]) { l.lazyInit() for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() { l.insertValue(e.Value, &l.root) } } // Transform runs a transform function on a list returning a new list. func _Transform[TElem1, TElem2 any](lst *_List[TElem1], f func(TElem1) TElem2) *_List[TElem2] { ret := _New[TElem2]() for p := lst.Front(); p != nil; p = p.Next() { ret.PushBack(f(p.Value)) } return ret } func checkListLen[T any](l *_List[T], len int) bool { if n := l.Len(); n != len { panic(fmt.Sprintf("l.Len() = %d, want %d", n, len)) return false } return true } func checkListPointers[T any](l *_List[T], es []*_Element[T]) { root := &l.root if !checkListLen(l, len(es)) { return } // zero length lists must be the zero value or properly initialized (sentinel circle) if len(es) == 0 { if l.root.next != nil && l.root.next != root || l.root.prev != nil && l.root.prev != root { panic(fmt.Sprintf("l.root.next = %p, l.root.prev = %p; both should both be nil or %p", l.root.next, l.root.prev, root)) } return } // len(es) > 0 // check internal and external prev/next connections for i, e := range es { prev := root Prev := (*_Element[T])(nil) if i > 0 { prev = es[i-1] Prev = prev } if p := e.prev; p != prev { panic(fmt.Sprintf("elt[%d](%p).prev = %p, want %p", i, e, p, prev)) } if p := e.Prev(); p != Prev { panic(fmt.Sprintf("elt[%d](%p).Prev() = %p, want %p", i, e, p, Prev)) } next := root Next := (*_Element[T])(nil) if i < len(es)-1 { next = es[i+1] Next = next } if n := e.next; n != next { panic(fmt.Sprintf("elt[%d](%p).next = %p, want %p", i, e, n, next)) } if n := e.Next(); n != Next { panic(fmt.Sprintf("elt[%d](%p).Next() = %p, want %p", i, e, n, Next)) } } } func TestList() { l := _New[string]() checkListPointers(l, []*(_Element[string]){}) // Single element list e := l.PushFront("a") checkListPointers(l, []*(_Element[string]){e}) l.MoveToFront(e) checkListPointers(l, []*(_Element[string]){e}) l.MoveToBack(e) checkListPointers(l, []*(_Element[string]){e}) l.Remove(e) checkListPointers(l, []*(_Element[string]){}) // Bigger list l2 := _New[int]() e2 := l2.PushFront(2) e1 := l2.PushFront(1) e3 := l2.PushBack(3) e4 := l2.PushBack(600) checkListPointers(l2, []*(_Element[int]){e1, e2, e3, e4}) l2.Remove(e2) checkListPointers(l2, []*(_Element[int]){e1, e3, e4}) l2.MoveToFront(e3) // move from middle checkListPointers(l2, []*(_Element[int]){e3, e1, e4}) l2.MoveToFront(e1) l2.MoveToBack(e3) // move from middle checkListPointers(l2, []*(_Element[int]){e1, e4, e3}) l2.MoveToFront(e3) // move from back checkListPointers(l2, []*(_Element[int]){e3, e1, e4}) l2.MoveToFront(e3) // should be no-op checkListPointers(l2, []*(_Element[int]){e3, e1, e4}) l2.MoveToBack(e3) // move from front checkListPointers(l2, []*(_Element[int]){e1, e4, e3}) l2.MoveToBack(e3) // should be no-op checkListPointers(l2, []*(_Element[int]){e1, e4, e3}) e2 = l2.InsertBefore(2, e1) // insert before front checkListPointers(l2, []*(_Element[int]){e2, e1, e4, e3}) l2.Remove(e2) e2 = l2.InsertBefore(2, e4) // insert before middle checkListPointers(l2, []*(_Element[int]){e1, e2, e4, e3}) l2.Remove(e2) e2 = l2.InsertBefore(2, e3) // insert before back checkListPointers(l2, []*(_Element[int]){e1, e4, e2, e3}) l2.Remove(e2) e2 = l2.InsertAfter(2, e1) // insert after front checkListPointers(l2, []*(_Element[int]){e1, e2, e4, e3}) l2.Remove(e2) e2 = l2.InsertAfter(2, e4) // insert after middle checkListPointers(l2, []*(_Element[int]){e1, e4, e2, e3}) l2.Remove(e2) e2 = l2.InsertAfter(2, e3) // insert after back checkListPointers(l2, []*(_Element[int]){e1, e4, e3, e2}) l2.Remove(e2) // Check standard iteration. sum := 0 for e := l2.Front(); e != nil; e = e.Next() { sum += e.Value } if sum != 604 { panic(fmt.Sprintf("sum over l = %d, want 604", sum)) } // Clear all elements by iterating var next *_Element[int] for e := l2.Front(); e != nil; e = next { next = e.Next() l2.Remove(e) } checkListPointers(l2, []*(_Element[int]){}) } func checkList[T comparable](l *_List[T], es []interface{}) { if !checkListLen(l, len(es)) { return } i := 0 for e := l.Front(); e != nil; e = e.Next() { le := e.Value // Comparison between a generically-typed variable le and an interface. if le != es[i] { panic(fmt.Sprintf("elt[%d].Value = %v, want %v", i, le, es[i])) } i++ } } func TestExtending() { l1 := _New[int]() l2 := _New[int]() l1.PushBack(1) l1.PushBack(2) l1.PushBack(3) l2.PushBack(4) l2.PushBack(5) l3 := _New[int]() l3.PushBackList(l1) checkList(l3, []interface{}{1, 2, 3}) l3.PushBackList(l2) checkList(l3, []interface{}{1, 2, 3, 4, 5}) l3 = _New[int]() l3.PushFrontList(l2) checkList(l3, []interface{}{4, 5}) l3.PushFrontList(l1) checkList(l3, []interface{}{1, 2, 3, 4, 5}) checkList(l1, []interface{}{1, 2, 3}) checkList(l2, []interface{}{4, 5}) l3 = _New[int]() l3.PushBackList(l1) checkList(l3, []interface{}{1, 2, 3}) l3.PushBackList(l3) checkList(l3, []interface{}{1, 2, 3, 1, 2, 3}) l3 = _New[int]() l3.PushFrontList(l1) checkList(l3, []interface{}{1, 2, 3}) l3.PushFrontList(l3) checkList(l3, []interface{}{1, 2, 3, 1, 2, 3}) l3 = _New[int]() l1.PushBackList(l3) checkList(l1, []interface{}{1, 2, 3}) l1.PushFrontList(l3) checkList(l1, []interface{}{1, 2, 3}) } func TestRemove() { l := _New[int]() e1 := l.PushBack(1) e2 := l.PushBack(2) checkListPointers(l, []*(_Element[int]){e1, e2}) e := l.Front() l.Remove(e) checkListPointers(l, []*(_Element[int]){e2}) l.Remove(e) checkListPointers(l, []*(_Element[int]){e2}) } func TestIssue4103() { l1 := _New[int]() l1.PushBack(1) l1.PushBack(2) l2 := _New[int]() l2.PushBack(3) l2.PushBack(4) e := l1.Front() l2.Remove(e) // l2 should not change because e is not an element of l2 if n := l2.Len(); n != 2 { panic(fmt.Sprintf("l2.Len() = %d, want 2", n)) } l1.InsertBefore(8, e) if n := l1.Len(); n != 3 { panic(fmt.Sprintf("l1.Len() = %d, want 3", n)) } } func TestIssue6349() { l := _New[int]() l.PushBack(1) l.PushBack(2) e := l.Front() l.Remove(e) if e.Value != 1 { panic(fmt.Sprintf("e.value = %d, want 1", e.Value)) } if e.Next() != nil { panic(fmt.Sprintf("e.Next() != nil")) } if e.Prev() != nil { panic(fmt.Sprintf("e.Prev() != nil")) } } func TestMove() { l := _New[int]() e1 := l.PushBack(1) e2 := l.PushBack(2) e3 := l.PushBack(3) e4 := l.PushBack(4) l.MoveAfter(e3, e3) checkListPointers(l, []*(_Element[int]){e1, e2, e3, e4}) l.MoveBefore(e2, e2) checkListPointers(l, []*(_Element[int]){e1, e2, e3, e4}) l.MoveAfter(e3, e2) checkListPointers(l, []*(_Element[int]){e1, e2, e3, e4}) l.MoveBefore(e2, e3) checkListPointers(l, []*(_Element[int]){e1, e2, e3, e4}) l.MoveBefore(e2, e4) checkListPointers(l, []*(_Element[int]){e1, e3, e2, e4}) e2, e3 = e3, e2 l.MoveBefore(e4, e1) checkListPointers(l, []*(_Element[int]){e4, e1, e2, e3}) e1, e2, e3, e4 = e4, e1, e2, e3 l.MoveAfter(e4, e1) checkListPointers(l, []*(_Element[int]){e1, e4, e2, e3}) e2, e3, e4 = e4, e2, e3 l.MoveAfter(e2, e3) checkListPointers(l, []*(_Element[int]){e1, e3, e2, e4}) e2, e3 = e3, e2 } // Test PushFront, PushBack, PushFrontList, PushBackList with uninitialized _List func TestZeroList() { var l1 = new(_List[int]) l1.PushFront(1) checkList(l1, []interface{}{1}) var l2 = new(_List[int]) l2.PushBack(1) checkList(l2, []interface{}{1}) var l3 = new(_List[int]) l3.PushFrontList(l1) checkList(l3, []interface{}{1}) var l4 = new(_List[int]) l4.PushBackList(l2) checkList(l4, []interface{}{1}) } // Test that a list l is not modified when calling InsertBefore with a mark that is not an element of l. func TestInsertBeforeUnknownMark() { var l _List[int] l.PushBack(1) l.PushBack(2) l.PushBack(3) l.InsertBefore(1, new(_Element[int])) checkList(&l, []interface{}{1, 2, 3}) } // Test that a list l is not modified when calling InsertAfter with a mark that is not an element of l. func TestInsertAfterUnknownMark() { var l _List[int] l.PushBack(1) l.PushBack(2) l.PushBack(3) l.InsertAfter(1, new(_Element[int])) checkList(&l, []interface{}{1, 2, 3}) } // Test that a list l is not modified when calling MoveAfter or MoveBefore with a mark that is not an element of l. func TestMoveUnknownMark() { var l1 _List[int] e1 := l1.PushBack(1) var l2 _List[int] e2 := l2.PushBack(2) l1.MoveAfter(e1, e2) checkList(&l1, []interface{}{1}) checkList(&l2, []interface{}{2}) l1.MoveBefore(e1, e2) checkList(&l1, []interface{}{1}) checkList(&l2, []interface{}{2}) } // Test the Transform function. func TestTransform() { l1 := _New[int]() l1.PushBack(1) l1.PushBack(2) l2 := _Transform(l1, strconv.Itoa) checkList(l2, []interface{}{"1", "2"}) } func main() { TestList() TestExtending() TestRemove() TestIssue4103() TestIssue6349() TestMove() TestZeroList() TestInsertBeforeUnknownMark() TestInsertAfterUnknownMark() TestTransform() }
go/test/typeparam/list2.go/0
{ "file_path": "go/test/typeparam/list2.go", "repo_id": "go", "token_count": 6563 }
569
// 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 type parameter methods are handled correctly, even when // the instantiating type argument has additional methods. package main func main() { F(X(0)) } type I interface{ B() } func F[T I](t T) { CallMethod(t) MethodExpr[T]()(t) MethodVal(t)() } func CallMethod[T I](t T) { t.B() } func MethodExpr[T I]() func(T) { return T.B } func MethodVal[T I](t T) func() { return t.B } type X int func (X) A() { panic("FAIL") } func (X) B() {} func (X) C() { panic("FAIL") }
go/test/typeparam/mdempsky/19.go/0
{ "file_path": "go/test/typeparam/mdempsky/19.go", "repo_id": "go", "token_count": 245 }
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 import ( "fmt" "math" "sort" ) type Ordered interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string } type orderedSlice[Elem Ordered] []Elem func (s orderedSlice[Elem]) Len() int { return len(s) } func (s orderedSlice[Elem]) Less(i, j int) bool { if s[i] < s[j] { return true } isNaN := func(f Elem) bool { return f != f } if isNaN(s[i]) && !isNaN(s[j]) { return true } return false } func (s orderedSlice[Elem]) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func _OrderedSlice[Elem Ordered](s []Elem) { sort.Sort(orderedSlice[Elem](s)) } var ints = []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586} var float64s = []float64{74.3, 59.0, math.Inf(1), 238.2, -784.0, 2.3, math.NaN(), math.NaN(), math.Inf(-1), 9845.768, -959.7485, 905, 7.8, 7.8} var strings = []string{"", "Hello", "foo", "bar", "foo", "f00", "%*&^*&^&", "***"} func TestSortOrderedInts() bool { return testOrdered("ints", ints, sort.Ints) } func TestSortOrderedFloat64s() bool { return testOrdered("float64s", float64s, sort.Float64s) } func TestSortOrderedStrings() bool { return testOrdered("strings", strings, sort.Strings) } func testOrdered[Elem Ordered](name string, s []Elem, sorter func([]Elem)) bool { s1 := make([]Elem, len(s)) copy(s1, s) s2 := make([]Elem, len(s)) copy(s2, s) _OrderedSlice(s1) sorter(s2) ok := true if !sliceEq(s1, s2) { fmt.Printf("%s: got %v, want %v", name, s1, s2) ok = false } for i := len(s1) - 1; i > 0; i-- { if s1[i] < s1[i-1] { fmt.Printf("%s: element %d (%v) < element %d (%v)", name, i, s1[i], i-1, s1[i-1]) ok = false } } return ok } func sliceEq[Elem Ordered](s1, s2 []Elem) bool { 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 } func main() { if !TestSortOrderedInts() || !TestSortOrderedFloat64s() || !TestSortOrderedStrings() { panic("failure") } }
go/test/typeparam/ordered.go/0
{ "file_path": "go/test/typeparam/ordered.go", "repo_id": "go", "token_count": 1036 }
571
// 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 Stringer interface { String() string } func Stringify[T Stringer](s []T) (ret []string) { for _, v := range s { ret = append(ret, v.String()) } return ret }
go/test/typeparam/stringerimp.dir/a.go/0
{ "file_path": "go/test/typeparam/stringerimp.dir/a.go", "repo_id": "go", "token_count": 110 }
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 interface{ foo() int } type J interface { I bar() } type myint int func (x myint) foo() int { return int(x) } type myfloat float64 func (x myfloat) foo() int { return int(x) } type myint32 int32 func (x myint32) foo() int { return int(x) } func (x myint32) bar() {} func f[T I](i I) { switch x := i.(type) { case T: println("T", x.foo()) case myint: println("myint", x.foo()) default: println("other", x.foo()) } } func main() { f[myfloat](myint(6)) f[myfloat](myfloat(7)) f[myfloat](myint32(8)) f[myint32](myint32(8)) f[myint32](myfloat(7)) f[myint](myint32(9)) f[I](myint(10)) f[J](myint(11)) f[J](myint32(12)) }
go/test/typeparam/typeswitch3.go/0
{ "file_path": "go/test/typeparam/typeswitch3.go", "repo_id": "go", "token_count": 357 }
573
// 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. // Verify that various erroneous type switches are caught by the compiler. // Does not compile. package main import "io" func whatis(x interface{}) string { switch x.(type) { case int: return "int" case int: // ERROR "duplicate" return "int8" case io.Reader: return "Reader1" case io.Reader: // ERROR "duplicate" return "Reader2" case interface { r() w() }: return "rw" case interface { // ERROR "duplicate" w() r() }: return "wr" } return "" }
go/test/typeswitch2.go/0
{ "file_path": "go/test/typeswitch2.go", "repo_id": "go", "token_count": 232 }
574
// errorcheck // 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. // Verify that a couple of illegal variable declarations are caught by the compiler. // Does not compile. package main func main() { _ = asdf // ERROR "undefined.*asdf" new = 1 // ERROR "use of builtin new not in function call|invalid left hand side|must be called" }
go/test/varerr.go/0
{ "file_path": "go/test/varerr.go", "repo_id": "go", "token_count": 125 }
575
/* 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 lru import ( "fmt" "testing" ) type simpleStruct struct { int string } type complexStruct struct { int simpleStruct } var getTests = []struct { name string keyToAdd interface{} keyToGet interface{} expectedOk bool }{ {"string_hit", "myKey", "myKey", true}, {"string_miss", "myKey", "nonsense", false}, {"simple_struct_hit", simpleStruct{1, "two"}, simpleStruct{1, "two"}, true}, {"simple_struct_miss", simpleStruct{1, "two"}, simpleStruct{0, "noway"}, false}, {"complex_struct_hit", complexStruct{1, simpleStruct{2, "three"}}, complexStruct{1, simpleStruct{2, "three"}}, true}, } func TestGet(t *testing.T) { for _, tt := range getTests { lru := New(0) lru.Add(tt.keyToAdd, 1234) val, ok := lru.Get(tt.keyToGet) if ok != tt.expectedOk { t.Fatalf("%s: cache hit = %v; want %v", tt.name, ok, !ok) } else if ok && val != 1234 { t.Fatalf("%s expected get to return 1234 but got %v", tt.name, val) } } } func TestRemove(t *testing.T) { lru := New(0) lru.Add("myKey", 1234) if val, ok := lru.Get("myKey"); !ok { t.Fatal("TestRemove returned no match") } else if val != 1234 { t.Fatalf("TestRemove failed. Expected %d, got %v", 1234, val) } lru.Remove("myKey") if _, ok := lru.Get("myKey"); ok { t.Fatal("TestRemove returned a removed entry") } } func TestEvict(t *testing.T) { evictedKeys := make([]Key, 0) onEvictedFun := func(key Key, value interface{}) { evictedKeys = append(evictedKeys, key) } lru := New(20) lru.OnEvicted = onEvictedFun for i := 0; i < 22; i++ { lru.Add(fmt.Sprintf("myKey%d", i), 1234) } if len(evictedKeys) != 2 { t.Fatalf("got %d evicted keys; want 2", len(evictedKeys)) } if evictedKeys[0] != Key("myKey0") { t.Fatalf("got %v in first evicted key; want %s", evictedKeys[0], "myKey0") } if evictedKeys[1] != Key("myKey1") { t.Fatalf("got %v in second evicted key; want %s", evictedKeys[1], "myKey1") } }
groupcache/lru/lru_test.go/0
{ "file_path": "groupcache/lru/lru_test.go", "repo_id": "groupcache", "token_count": 967 }
576
// This file ends in _test.go, so we should not warn about doc comments. // OK package pkg import "testing" type H int func TestSomething(t *testing.T) { } func TestSomething_suffix(t *testing.T) { } func ExampleBuffer_reader() { }
lint/testdata/5_test.go/0
{ "file_path": "lint/testdata/5_test.go", "repo_id": "lint", "token_count": 83 }
577
// Test for use of x++ and x--. // Package pkg ... package pkg func addOne(x int) int { x += 1 // MATCH /x\+\+/ return x } func subOneInLoop(y int) { for ; y > 0; y -= 1 { // MATCH /y--/ } }
lint/testdata/inc.go/0
{ "file_path": "lint/testdata/inc.go", "repo_id": "lint", "token_count": 91 }
578
// 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 bind import ( "bytes" "fmt" "go/types" "strings" ) type goGen struct { *Generator // imports is the list of imports, in the form // "the/package/path" // // or // // name "the/package/path" // // in case of duplicates. imports []string // The set of taken import names. importNames map[string]struct{} // importMap is a map from packages to their names. The name of a package is the last // segment of its path, with duplicates resolved by appending a underscore and a unique // number. importMap map[*types.Package]string } const ( goPreamble = gobindPreamble + `// Package main is an autogenerated binder stub for package %[1]s. // // autogenerated by gobind -lang=go %[2]s package main /* #include <stdlib.h> #include <stdint.h> #include "seq.h" #include "%[1]s.h" */ import "C" ` ) func (g *goGen) genFuncBody(o *types.Func, selectorLHS string) { sig := o.Type().(*types.Signature) params := sig.Params() for i := 0; i < params.Len(); i++ { p := params.At(i) pn := "param_" + g.paramName(params, i) g.genRead("_"+pn, pn, p.Type(), modeTransient) } res := sig.Results() if res.Len() > 2 || res.Len() == 2 && !isErrorType(res.At(1).Type()) { g.errorf("functions and methods must return either zero or one values, and optionally an error") return } if res.Len() > 0 { for i := 0; i < res.Len(); i++ { if i > 0 { g.Printf(", ") } g.Printf("res_%d", i) } g.Printf(" := ") } g.Printf("%s%s(", selectorLHS, o.Name()) for i := 0; i < params.Len(); i++ { if i > 0 { g.Printf(", ") } g.Printf("_param_%s", g.paramName(params, i)) } g.Printf(")\n") for i := 0; i < res.Len(); i++ { pn := fmt.Sprintf("res_%d", i) g.genWrite("_"+pn, pn, res.At(i).Type(), modeRetained) } if res.Len() > 0 { g.Printf("return ") for i := 0; i < res.Len(); i++ { if i > 0 { g.Printf(", ") } g.Printf("_res_%d", i) } g.Printf("\n") } } func (g *goGen) genWrite(toVar, fromVar string, t types.Type, mode varMode) { switch t := t.(type) { case *types.Basic: switch t.Kind() { case types.String: g.Printf("%s := encodeString(%s)\n", toVar, fromVar) case types.Bool: g.Printf("var %s C.%s = 0\n", toVar, g.cgoType(t)) g.Printf("if %s { %s = 1 }\n", fromVar, toVar) default: g.Printf("%s := C.%s(%s)\n", toVar, g.cgoType(t), fromVar) } case *types.Slice: switch e := t.Elem().(type) { case *types.Basic: switch e.Kind() { case types.Uint8: // Byte. g.Printf("%s := fromSlice(%s, %v)\n", toVar, fromVar, mode == modeRetained) default: g.errorf("unsupported type: %s", t) } default: g.errorf("unsupported type: %s", t) } case *types.Pointer: // TODO(crawshaw): test *int // TODO(crawshaw): test **Generator switch t := t.Elem().(type) { case *types.Named: g.genToRefNum(toVar, fromVar) default: g.errorf("unsupported type %s", t) } case *types.Named: switch u := t.Underlying().(type) { case *types.Interface, *types.Pointer: g.genToRefNum(toVar, fromVar) default: g.errorf("unsupported, direct named type %s: %s", t, u) } default: g.errorf("unsupported type %s", t) } } // genToRefNum generates Go code for converting a variable to its refnum. // Note that the nil-check cannot be lifted into seq.ToRefNum, because a nil // struct pointer does not convert to a nil interface. func (g *goGen) genToRefNum(toVar, fromVar string) { g.Printf("var %s C.int32_t = _seq.NullRefNum\n", toVar) g.Printf("if %s != nil {\n", fromVar) g.Printf(" %s = C.int32_t(_seq.ToRefNum(%s))\n", toVar, fromVar) g.Printf("}\n") } func (g *goGen) genFuncSignature(o *types.Func, objName string) { g.Printf("//export proxy%s_%s_%s\n", g.pkgPrefix, objName, o.Name()) g.Printf("func proxy%s_%s_%s(", g.pkgPrefix, objName, o.Name()) if objName != "" { g.Printf("refnum C.int32_t") } sig := o.Type().(*types.Signature) params := sig.Params() for i := 0; i < params.Len(); i++ { if objName != "" || i > 0 { g.Printf(", ") } p := params.At(i) g.Printf("param_%s C.%s", g.paramName(params, i), g.cgoType(p.Type())) } g.Printf(") ") res := sig.Results() if res.Len() > 0 { g.Printf("(") for i := 0; i < res.Len(); i++ { if i > 0 { g.Printf(", ") } g.Printf("C.%s", g.cgoType(res.At(i).Type())) } g.Printf(") ") } g.Printf("{\n") } func (g *goGen) paramName(params *types.Tuple, pos int) string { return basicParamName(params, pos) } func (g *goGen) genFunc(o *types.Func) { if !g.isSigSupported(o.Type()) { g.Printf("// skipped function %s with unsupported parameter or result types\n", o.Name()) return } g.genFuncSignature(o, "") g.Indent() g.genFuncBody(o, g.pkgName(g.Pkg)) g.Outdent() g.Printf("}\n\n") } func (g *goGen) genStruct(obj *types.TypeName, T *types.Struct) { fields := exportedFields(T) methods := exportedMethodSet(types.NewPointer(obj.Type())) for _, f := range fields { if t := f.Type(); !g.isSupported(t) { g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", obj.Name(), f.Name(), t) continue } g.Printf("//export proxy%s_%s_%s_Set\n", g.pkgPrefix, obj.Name(), f.Name()) g.Printf("func proxy%s_%s_%s_Set(refnum C.int32_t, v C.%s) {\n", g.pkgPrefix, obj.Name(), f.Name(), g.cgoType(f.Type())) g.Indent() g.Printf("ref := _seq.FromRefNum(int32(refnum))\n") g.genRead("_v", "v", f.Type(), modeRetained) g.Printf("ref.Get().(*%s%s).%s = _v\n", g.pkgName(g.Pkg), obj.Name(), f.Name()) g.Outdent() g.Printf("}\n\n") g.Printf("//export proxy%s_%s_%s_Get\n", g.pkgPrefix, obj.Name(), f.Name()) g.Printf("func proxy%s_%s_%s_Get(refnum C.int32_t) C.%s {\n", g.pkgPrefix, obj.Name(), f.Name(), g.cgoType(f.Type())) g.Indent() g.Printf("ref := _seq.FromRefNum(int32(refnum))\n") g.Printf("v := ref.Get().(*%s%s).%s\n", g.pkgName(g.Pkg), obj.Name(), f.Name()) g.genWrite("_v", "v", f.Type(), modeRetained) g.Printf("return _v\n") g.Outdent() g.Printf("}\n\n") } for _, m := range methods { if !g.isSigSupported(m.Type()) { g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name()) continue } g.genFuncSignature(m, obj.Name()) g.Indent() g.Printf("ref := _seq.FromRefNum(int32(refnum))\n") g.Printf("v := ref.Get().(*%s%s)\n", g.pkgName(g.Pkg), obj.Name()) g.genFuncBody(m, "v.") g.Outdent() g.Printf("}\n\n") } // Export constructor for ObjC and Java default no-arg constructors g.Printf("//export new_%s_%s\n", g.Pkg.Name(), obj.Name()) g.Printf("func new_%s_%s() C.int32_t {\n", g.Pkg.Name(), obj.Name()) g.Indent() g.Printf("return C.int32_t(_seq.ToRefNum(new(%s%s)))\n", g.pkgName(g.Pkg), obj.Name()) g.Outdent() g.Printf("}\n") } func (g *goGen) genVar(o *types.Var) { if t := o.Type(); !g.isSupported(t) { g.Printf("// skipped variable %s with unsupported type %s\n\n", o.Name(), t) return } // TODO(hyangah): non-struct pointer types (*int), struct type. v := fmt.Sprintf("%s%s", g.pkgName(g.Pkg), o.Name()) // var I int // // func var_setI(v int) g.Printf("//export var_set%s_%s\n", g.pkgPrefix, o.Name()) g.Printf("func var_set%s_%s(v C.%s) {\n", g.pkgPrefix, o.Name(), g.cgoType(o.Type())) g.Indent() g.genRead("_v", "v", o.Type(), modeRetained) g.Printf("%s = _v\n", v) g.Outdent() g.Printf("}\n") // func var_getI() int g.Printf("//export var_get%s_%s\n", g.pkgPrefix, o.Name()) g.Printf("func var_get%s_%s() C.%s {\n", g.pkgPrefix, o.Name(), g.cgoType(o.Type())) g.Indent() g.Printf("v := %s\n", v) g.genWrite("_v", "v", o.Type(), modeRetained) g.Printf("return _v\n") g.Outdent() g.Printf("}\n") } func (g *goGen) genInterface(obj *types.TypeName) { iface := obj.Type().(*types.Named).Underlying().(*types.Interface) summary := makeIfaceSummary(iface) // Define the entry points. for _, m := range summary.callable { if !g.isSigSupported(m.Type()) { g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name()) continue } g.genFuncSignature(m, obj.Name()) g.Indent() g.Printf("ref := _seq.FromRefNum(int32(refnum))\n") g.Printf("v := ref.Get().(%s%s)\n", g.pkgName(g.Pkg), obj.Name()) g.genFuncBody(m, "v.") g.Outdent() g.Printf("}\n\n") } // Define a proxy interface. if !summary.implementable { // The interface defines an unexported method or a method that // uses an unexported type. We cannot generate a proxy object // for such a type. return } g.Printf("type proxy%s_%s _seq.Ref\n\n", g.pkgPrefix, obj.Name()) g.Printf("func (p *proxy%s_%s) Bind_proxy_refnum__() int32 {\n", g.pkgPrefix, obj.Name()) g.Indent() g.Printf("return (*_seq.Ref)(p).Bind_IncNum()\n") g.Outdent() g.Printf("}\n\n") for _, m := range summary.callable { if !g.isSigSupported(m.Type()) { g.Printf("// skipped method %s.%s with unsupported parameter or result types\n", obj.Name(), m.Name()) continue } sig := m.Type().(*types.Signature) params := sig.Params() res := sig.Results() if res.Len() > 2 || (res.Len() == 2 && !isErrorType(res.At(1).Type())) { g.errorf("functions and methods must return either zero or one value, and optionally an error: %s.%s", obj.Name(), m.Name()) continue } g.Printf("func (p *proxy%s_%s) %s(", g.pkgPrefix, obj.Name(), m.Name()) for i := 0; i < params.Len(); i++ { if i > 0 { g.Printf(", ") } g.Printf("param_%s %s", g.paramName(params, i), g.typeString(params.At(i).Type())) } g.Printf(") ") if res.Len() == 1 { g.Printf(g.typeString(res.At(0).Type())) } else if res.Len() == 2 { g.Printf("(%s, error)", g.typeString(res.At(0).Type())) } g.Printf(" {\n") g.Indent() for i := 0; i < params.Len(); i++ { pn := "param_" + g.paramName(params, i) g.genWrite("_"+pn, pn, params.At(i).Type(), modeTransient) } if res.Len() > 0 { g.Printf("res := ") } g.Printf("C.cproxy%s_%s_%s(C.int32_t(p.Bind_proxy_refnum__())", g.pkgPrefix, obj.Name(), m.Name()) for i := 0; i < params.Len(); i++ { g.Printf(", _param_%s", g.paramName(params, i)) } g.Printf(")\n") var retName string if res.Len() > 0 { if res.Len() == 1 { T := res.At(0).Type() g.genRead("_res", "res", T, modeRetained) retName = "_res" } else { var rvs []string for i := 0; i < res.Len(); i++ { rv := fmt.Sprintf("res_%d", i) g.genRead(rv, fmt.Sprintf("res.r%d", i), res.At(i).Type(), modeRetained) rvs = append(rvs, rv) } retName = strings.Join(rvs, ", ") } g.Printf("return %s\n", retName) } g.Outdent() g.Printf("}\n\n") } } func (g *goGen) genRead(toVar, fromVar string, typ types.Type, mode varMode) { switch t := typ.(type) { case *types.Basic: switch t.Kind() { case types.String: g.Printf("%s := decodeString(%s)\n", toVar, fromVar) case types.Bool: g.Printf("%s := %s != 0\n", toVar, fromVar) default: g.Printf("%s := %s(%s)\n", toVar, t.Underlying().String(), fromVar) } case *types.Slice: switch e := t.Elem().(type) { case *types.Basic: switch e.Kind() { case types.Uint8: // Byte. g.Printf("%s := toSlice(%s, %v)\n", toVar, fromVar, mode == modeRetained) default: g.errorf("unsupported type: %s", t) } default: g.errorf("unsupported type: %s", t) } case *types.Pointer: switch u := t.Elem().(type) { case *types.Named: o := u.Obj() oPkg := o.Pkg() if !g.validPkg(oPkg) { g.errorf("type %s is defined in %s, which is not bound", u, oPkg) return } g.Printf("// Must be a Go object\n") g.Printf("var %s *%s%s\n", toVar, g.pkgName(oPkg), o.Name()) g.Printf("if %s_ref := _seq.FromRefNum(int32(%s)); %s_ref != nil {\n", toVar, fromVar, toVar) g.Printf(" %s = %s_ref.Get().(*%s%s)\n", toVar, toVar, g.pkgName(oPkg), o.Name()) g.Printf("}\n") default: g.errorf("unsupported pointer type %s", t) } case *types.Named: switch t.Underlying().(type) { case *types.Interface, *types.Pointer: hasProxy := true if iface, ok := t.Underlying().(*types.Interface); ok { hasProxy = makeIfaceSummary(iface).implementable } pkgFirst := typePkgFirstElem(t) isWrapper := pkgFirst == "Java" || pkgFirst == "ObjC" o := t.Obj() oPkg := o.Pkg() if !isErrorType(t) && !g.validPkg(oPkg) && !isWrapper { g.errorf("type %s is defined in %s, which is not bound", t, oPkg) return } g.Printf("var %s %s\n", toVar, g.typeString(t)) g.Printf("%s_ref := _seq.FromRefNum(int32(%s))\n", toVar, fromVar) g.Printf("if %s_ref != nil {\n", toVar) g.Printf(" if %s < 0 { // go object \n", fromVar) g.Printf(" %s = %s_ref.Get().(%s%s)\n", toVar, toVar, g.pkgName(oPkg), o.Name()) if hasProxy { g.Printf(" } else { // foreign object \n") if isWrapper { var clsName string switch pkgFirst { case "Java": clsName = flattenName(classNameFor(t)) case "ObjC": clsName = t.Obj().Name() } g.Printf(" %s = (*proxy_class_%s)(%s_ref)\n", toVar, clsName, toVar) } else { g.Printf(" %s = (*proxy%s_%s)(%s_ref)\n", toVar, pkgPrefix(oPkg), o.Name(), toVar) } } g.Printf(" }\n") g.Printf("}\n") default: g.errorf("unsupported named type %s", t) } default: g.errorf("unsupported type: %s", typ) } } func (g *goGen) typeString(typ types.Type) string { pkg := g.Pkg switch t := typ.(type) { case *types.Named: obj := t.Obj() if obj.Pkg() == nil { // e.g. error type is *types.Named. return types.TypeString(typ, types.RelativeTo(pkg)) } oPkg := obj.Pkg() if !g.validPkg(oPkg) && !isWrapperType(t) { g.errorf("type %s is defined in %s, which is not bound", t, oPkg) return "TODO" } switch t.Underlying().(type) { case *types.Interface, *types.Struct: return fmt.Sprintf("%s%s", g.pkgName(oPkg), types.TypeString(typ, types.RelativeTo(oPkg))) default: g.errorf("unsupported named type %s / %T", t, t) } case *types.Pointer: switch t := t.Elem().(type) { case *types.Named: return fmt.Sprintf("*%s", g.typeString(t)) default: g.errorf("not yet supported, pointer type %s / %T", t, t) } default: return types.TypeString(typ, types.RelativeTo(pkg)) } return "" } // genPreamble generates the preamble. It is generated after everything // else, where we know which bound packages to import. func (g *goGen) genPreamble() { pkgName := "" pkgPath := "" if g.Pkg != nil { pkgName = g.Pkg.Name() pkgPath = g.Pkg.Path() } else { pkgName = "universe" } g.Printf(goPreamble, pkgName, pkgPath) g.Printf("import (\n") g.Indent() g.Printf("_seq \"golang.org/x/mobile/bind/seq\"\n") for _, imp := range g.imports { g.Printf("%s\n", imp) } g.Outdent() g.Printf(")\n\n") } func (g *goGen) gen() error { g.importNames = make(map[string]struct{}) g.importMap = make(map[*types.Package]string) // Switch to a temporary buffer so the preamble can be // written last. oldBuf := g.Printer.Buf newBuf := new(bytes.Buffer) g.Printer.Buf = newBuf g.Printf("// suppress the error if seq ends up unused\n") g.Printf("var _ = _seq.FromRefNum\n") for _, s := range g.structs { g.genStruct(s.obj, s.t) } for _, intf := range g.interfaces { g.genInterface(intf.obj) } for _, v := range g.vars { g.genVar(v) } for _, f := range g.funcs { g.genFunc(f) } // Switch to the original buffer, write the preamble // and append the rest of the file. g.Printer.Buf = oldBuf g.genPreamble() g.Printer.Buf.Write(newBuf.Bytes()) if len(g.err) > 0 { return g.err } return nil } // pkgName returns the package name and adds the package to the list of // imports. func (g *goGen) pkgName(pkg *types.Package) string { // The error type has no package if pkg == nil { return "" } if name, exists := g.importMap[pkg]; exists { return name + "." } i := 0 pname := pkg.Name() name := pkg.Name() for { if _, exists := g.importNames[name]; !exists { g.importNames[name] = struct{}{} g.importMap[pkg] = name var imp string if pname != name { imp = fmt.Sprintf("%s %q", name, pkg.Path()) } else { imp = fmt.Sprintf("%q", pkg.Path()) } g.imports = append(g.imports, imp) break } i++ name = fmt.Sprintf("%s_%d", pname, i) } g.importMap[pkg] = name return name + "." }
mobile/bind/gengo.go/0
{ "file_path": "mobile/bind/gengo.go", "repo_id": "mobile", "token_count": 7570 }
579
// 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 java import ( "fmt" "io" "io/ioutil" "log" "os" "os/exec" "path/filepath" "runtime" "strings" "testing" "golang.org/x/mobile/internal/importers/java" "golang.org/x/mobile/internal/sdkpath" ) var gomobileBin string func TestMain(m *testing.M) { os.Exit(testMain(m)) } func testMain(m *testing.M) int { // Build gomobile and gobind and put them into PATH. binDir, err := ioutil.TempDir("", "bind-java-test-") if err != nil { log.Fatal(err) } defer os.RemoveAll(binDir) exe := "" if runtime.GOOS == "windows" { exe = ".exe" } if runtime.GOOS != "android" { gocmd := filepath.Join(runtime.GOROOT(), "bin", "go") gomobileBin = filepath.Join(binDir, "gomobile"+exe) gobindBin := filepath.Join(binDir, "gobind"+exe) if out, err := exec.Command(gocmd, "build", "-o", gomobileBin, "golang.org/x/mobile/cmd/gomobile").CombinedOutput(); err != nil { log.Fatalf("gomobile build failed: %v: %s", err, out) } if out, err := exec.Command(gocmd, "build", "-o", gobindBin, "golang.org/x/mobile/cmd/gobind").CombinedOutput(); err != nil { log.Fatalf("gobind build failed: %v: %s", err, out) } path := binDir if oldPath := os.Getenv("PATH"); oldPath != "" { path += string(filepath.ListSeparator) + oldPath } os.Setenv("PATH", path) } return m.Run() } func TestClasses(t *testing.T) { if !java.IsAvailable() { t.Skipf("java importer is not available") } runTest(t, []string{ "golang.org/x/mobile/bind/testdata/testpkg/javapkg", }, "", "ClassesTest") } func TestCustomPkg(t *testing.T) { runTest(t, []string{ "golang.org/x/mobile/bind/testdata/testpkg", }, "org.golang.custompkg", "CustomPkgTest") } func TestJavaSeqTest(t *testing.T) { runTest(t, []string{ "golang.org/x/mobile/bind/testdata/testpkg", "golang.org/x/mobile/bind/testdata/testpkg/secondpkg", "golang.org/x/mobile/bind/testdata/testpkg/simplepkg", }, "", "SeqTest") } // TestJavaSeqBench runs java test SeqBench.java, with the same // environment requirements as TestJavaSeqTest. // // The benchmarks runs on the phone, so the benchmarkpkg implements // rudimentary timing logic and outputs benchcmp compatible runtimes // to logcat. Use // // adb logcat -v raw GoLog:* *:S // // while running the benchmark to see the results. func TestJavaSeqBench(t *testing.T) { if testing.Short() { t.Skip("skipping benchmark in short mode.") } runTest(t, []string{"golang.org/x/mobile/bind/testdata/benchmark"}, "", "SeqBench") } // runTest runs the Android java test class specified with javaCls. If javaPkg is // set, it is passed with the -javapkg flag to gomobile. The pkgNames lists the Go // packages to bind for the test. // This requires the gradle command to be in PATH and the Android SDK to be // installed. func runTest(t *testing.T, pkgNames []string, javaPkg, javaCls string) { if gomobileBin == "" { t.Skipf("no gomobile on %s", runtime.GOOS) } gradle, err := exec.LookPath("gradle") if err != nil { t.Skip("command gradle not found, skipping") } if _, err := sdkpath.AndroidHome(); err != nil { t.Skip("Android SDK not found, skipping") } cwd, err := os.Getwd() if err != nil { t.Fatalf("failed pwd: %v", err) } tmpdir, err := ioutil.TempDir("", "bind-java-seq-test-") if err != nil { t.Fatalf("failed to prepare temp dir: %v", err) } defer os.RemoveAll(tmpdir) t.Logf("tmpdir = %s", tmpdir) if err := os.Chdir(tmpdir); err != nil { t.Fatalf("failed chdir: %v", err) } defer os.Chdir(cwd) for _, d := range []string{"src/main", "src/androidTest/java/go", "libs", "src/main/res/values"} { err = os.MkdirAll(filepath.Join(tmpdir, d), 0700) if err != nil { t.Fatal(err) } } args := []string{"bind", "-tags", "aaa bbb", "-o", "pkg.aar"} if javaPkg != "" { args = append(args, "-javapkg", javaPkg) } args = append(args, pkgNames...) cmd := exec.Command(gomobileBin, args...) // Reverse binding doesn't work with Go module since imports starting with Java or ObjC are not valid FQDNs. // Disable Go module explicitly until this problem is solved. See golang/go#27234. cmd.Env = append(os.Environ(), "GO111MODULE=off") buf, err := cmd.CombinedOutput() if err != nil { t.Logf("%s", buf) t.Fatalf("failed to run gomobile bind: %v", err) } fname := filepath.Join(tmpdir, "libs", "pkg.aar") err = cp(fname, filepath.Join(tmpdir, "pkg.aar")) if err != nil { t.Fatalf("failed to copy pkg.aar: %v", err) } fname = filepath.Join(tmpdir, "src/androidTest/java/go/"+javaCls+".java") err = cp(fname, filepath.Join(cwd, javaCls+".java")) if err != nil { t.Fatalf("failed to copy SeqTest.java: %v", err) } fname = filepath.Join(tmpdir, "src/main/AndroidManifest.xml") err = ioutil.WriteFile(fname, []byte(androidmanifest), 0700) if err != nil { t.Fatalf("failed to write android manifest file: %v", err) } // Add a dummy string resource to avoid errors from the Android build system. fname = filepath.Join(tmpdir, "src/main/res/values/strings.xml") err = ioutil.WriteFile(fname, []byte(stringsxml), 0700) if err != nil { t.Fatalf("failed to write strings.xml file: %v", err) } fname = filepath.Join(tmpdir, "build.gradle") err = ioutil.WriteFile(fname, []byte(buildgradle), 0700) if err != nil { t.Fatalf("failed to write build.gradle file: %v", err) } if buf, err := run(gradle + " connectedAndroidTest"); err != nil { t.Logf("%s", buf) t.Errorf("failed to run gradle test: %v", err) } } func run(cmd string) ([]byte, error) { c := strings.Split(cmd, " ") return exec.Command(c[0], c[1:]...).CombinedOutput() } func cp(dst, src string) error { r, err := os.Open(src) if err != nil { return fmt.Errorf("failed to read source: %v", err) } defer r.Close() w, err := os.Create(dst) if err != nil { return fmt.Errorf("failed to open destination: %v", err) } _, err = io.Copy(w, r) cerr := w.Close() if err != nil { return err } return cerr } const androidmanifest = `<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.BindTest" android:versionCode="1" android:versionName="1.0"> </manifest>` const buildgradle = `buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.0' } } allprojects { repositories { google() jcenter() } } apply plugin: 'com.android.library' android { compileSdkVersion 'android-19' defaultConfig { minSdkVersion 16 } } repositories { flatDir { dirs 'libs' } } dependencies { implementation(name: "pkg", ext: "aar") } ` const stringsxml = `<?xml version="1.0" encoding="utf-8"?> <resources> <string name="dummy">dummy</string> </resources>`
mobile/bind/java/seq_test.go/0
{ "file_path": "mobile/bind/java/seq_test.go", "repo_id": "mobile", "token_count": 2763 }
580
// 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 import ( "testing" "unicode/utf16" ) var strData = []string{ "abcxyz09{}", "Hello, 世界", string([]rune{0xffff, 0x10000, 0x10001, 0x12345, 0x10ffff}), } func TestString(t *testing.T) { for _, test := range strData { chars := make([]uint16, 4*len(test)) nchars := UTF16Encode(test, chars) chars = chars[:nchars] got := string(utf16.Decode(chars)) if got != test { t.Errorf("UTF16: got %q, want %q", got, test) } } }
mobile/bind/seq/string_test.go/0
{ "file_path": "mobile/bind/seq/string_test.go", "repo_id": "mobile", "token_count": 256 }
581
// 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. // Data for -pkgpath and -prefix options. package customprefix func F() { }
mobile/bind/testdata/customprefix.go/0
{ "file_path": "mobile/bind/testdata/customprefix.go", "repo_id": "mobile", "token_count": 67 }
582
// Objective-C API for talking to doc Go package. // gobind -lang=objc doc // // File is generated by gobind. Do not edit. #ifndef __Doc_H__ #define __Doc_H__ @import Foundation; #include "ref.h" #include "Universe.objc.h" @class DocNoDoc; @class DocS; @class DocS2; @protocol DocI; @class DocI; @protocol DocI <NSObject> /** * IM is a method. */ - (void)im; @end /** * A generic comment with <HTML>. */ @interface DocNoDoc : NSObject <goSeqRefInterface> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (nonnull instancetype)init; @end /** * S is a struct. */ @interface DocS : NSObject <goSeqRefInterface> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; /** * NewS is a constructor. */ - (nullable instancetype)init; /** * SF is a field. */ @property (nonatomic) NSString* _Nonnull sf; /** * Anonymous field. */ @property (nonatomic) DocS2* _Nullable s2; /** * Multiple fields. */ @property (nonatomic) NSString* _Nonnull f1; /** * Multiple fields. */ @property (nonatomic) NSString* _Nonnull f2; /** * After is another method. */ - (void)after; - (void)before; @end /** * S2 is a struct. */ @interface DocS2 : NSObject <goSeqRefInterface> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (nonnull instancetype)init; @end /** * C is a constant. */ FOUNDATION_EXPORT const BOOL DocC; @interface Doc : NSObject /** * A group of vars. */ + (double) noDocVar; + (void) setNoDocVar:(double)v; /** * A specific var. */ + (NSString* _Nonnull) specific; + (void) setSpecific:(NSString* _Nonnull)v; /** * V is a var. */ + (NSString* _Nonnull) v; + (void) setV:(NSString* _Nonnull)v; @end /** * F is a function. */ FOUNDATION_EXPORT void DocF(void); /** * NewS is a constructor. */ FOUNDATION_EXPORT DocS* _Nullable DocNewS(void); @class DocI; /** * I is an interface. */ @interface DocI : NSObject <goSeqRefInterface, DocI> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; /** * IM is a method. */ - (void)im; @end #endif
mobile/bind/testdata/doc.objc.h.golden/0
{ "file_path": "mobile/bind/testdata/doc.objc.h.golden", "repo_id": "mobile", "token_count": 858 }
583
// Objective-C API for talking to interfaces Go package. // gobind -lang=objc interfaces // // File is generated by gobind. Do not edit. #ifndef __Interfaces_H__ #define __Interfaces_H__ @import Foundation; #include "ref.h" #include "Universe.objc.h" @protocol InterfacesError; @class InterfacesError; @protocol InterfacesI; @class InterfacesI; @protocol InterfacesI1; @protocol InterfacesI2; @protocol InterfacesI3; @class InterfacesI3; @protocol InterfacesInterfaces; @class InterfacesInterfaces; @protocol InterfacesLargerI; @class InterfacesLargerI; @protocol InterfacesSameI; @class InterfacesSameI; @protocol InterfacesWithParam; @class InterfacesWithParam; @protocol InterfacesError <NSObject> - (BOOL)err:(NSError* _Nullable* _Nullable)error; @end @protocol InterfacesI <NSObject> - (int32_t)rand; @end /** * not implementable */ @interface InterfacesI1 : NSObject <goSeqRefInterface> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (void)j; @end /** * not implementable */ @interface InterfacesI2 : NSObject <goSeqRefInterface> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (void)g; @end @protocol InterfacesI3 <NSObject> - (InterfacesI1* _Nullable)f; @end @protocol InterfacesInterfaces <NSObject> - (void)someMethod; @end @protocol InterfacesLargerI <NSObject> - (void)anotherFunc; - (int32_t)rand; @end @protocol InterfacesSameI <NSObject> - (int32_t)rand; @end @protocol InterfacesWithParam <NSObject> - (void)hasParam:(BOOL)p0; @end FOUNDATION_EXPORT int32_t InterfacesAdd3(id<InterfacesI> _Nullable r); FOUNDATION_EXPORT BOOL InterfacesCallErr(id<InterfacesError> _Nullable e, NSError* _Nullable* _Nullable error); FOUNDATION_EXPORT id<InterfacesI> _Nullable InterfacesSeven(void); @class InterfacesError; @class InterfacesI; @class InterfacesI3; @class InterfacesInterfaces; @class InterfacesLargerI; @class InterfacesSameI; @class InterfacesWithParam; @interface InterfacesError : NSObject <goSeqRefInterface, InterfacesError> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (BOOL)err:(NSError* _Nullable* _Nullable)error; @end @interface InterfacesI : NSObject <goSeqRefInterface, InterfacesI> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (int32_t)rand; @end /** * implementable (the implementor has to find a source of I1s) */ @interface InterfacesI3 : NSObject <goSeqRefInterface, InterfacesI3> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (InterfacesI1* _Nullable)f; @end /** * Interfaces is an interface with the same name as its package. */ @interface InterfacesInterfaces : NSObject <goSeqRefInterface, InterfacesInterfaces> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (void)someMethod; @end @interface InterfacesLargerI : NSObject <goSeqRefInterface, InterfacesLargerI> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (void)anotherFunc; - (int32_t)rand; @end @interface InterfacesSameI : NSObject <goSeqRefInterface, InterfacesSameI> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (int32_t)rand; @end @interface InterfacesWithParam : NSObject <goSeqRefInterface, InterfacesWithParam> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (void)hasParam:(BOOL)p0; @end #endif
mobile/bind/testdata/interfaces.objc.h.golden/0
{ "file_path": "mobile/bind/testdata/interfaces.objc.h.golden", "repo_id": "mobile", "token_count": 1353 }
584
// Objective-C API for talking to issue12328 Go package. // gobind -lang=objc issue12328 // // File is generated by gobind. Do not edit. #ifndef __Issue12328_H__ #define __Issue12328_H__ @import Foundation; #include "ref.h" #include "Universe.objc.h" @class Issue12328T; @interface Issue12328T : NSObject <goSeqRefInterface> { } @property(strong, readonly) _Nonnull id _ref; - (nonnull instancetype)initWithRef:(_Nonnull id)ref; - (nonnull instancetype)init; @property (nonatomic) NSError* _Nullable err; @end #endif
mobile/bind/testdata/issue12328.objc.h.golden/0
{ "file_path": "mobile/bind/testdata/issue12328.objc.h.golden", "repo_id": "mobile", "token_count": 197 }
585
// Objective-C API for talking to issue29559 Go package. // gobind -lang=objc issue29559 // // File is generated by gobind. Do not edit. #ifndef __Issue29559_H__ #define __Issue29559_H__ @import Foundation; #include "ref.h" #include "Universe.objc.h" FOUNDATION_EXPORT void Issue29559TakesAString(NSString* _Nullable s); #endif
mobile/bind/testdata/issue29559.objc.h.golden/0
{ "file_path": "mobile/bind/testdata/issue29559.objc.h.golden", "repo_id": "mobile", "token_count": 122 }
586
// Code generated by gobind. DO NOT EDIT. package ObjC // Used to silence this package not used errors const Dummy = 0 type Foundation_NSString interface { } type Foundation_NSDate interface { } type Foundation_NSObjectC interface { } // Code generated by gobind. DO NOT EDIT. package main // #include "interfaces.h" import "C" import "ObjC" import _seq "golang.org/x/mobile/bind/seq" type proxy interface{ Bind_proxy_refnum__() int32 } // Suppress unused package error var _ = _seq.FromRefNum const _ = ObjC.Dummy func init() { } type proxy_class_NSString _seq.Ref func (p *proxy_class_NSString) Bind_proxy_refnum__() int32 { return (*_seq.Ref)(p).Bind_IncNum() } func init() { } type proxy_class_NSDate _seq.Ref func (p *proxy_class_NSDate) Bind_proxy_refnum__() int32 { return (*_seq.Ref)(p).Bind_IncNum() } func init() { } type proxy_class_NSObjectC _seq.Ref func (p *proxy_class_NSObjectC) Bind_proxy_refnum__() int32 { return (*_seq.Ref)(p).Bind_IncNum() } // Code generated by gobind. DO NOT EDIT. // Package main is an autogenerated binder stub for package objc. // // autogenerated by gobind -lang=go objc package main /* #include <stdlib.h> #include <stdint.h> #include "seq.h" #include "objc.h" */ import "C" import ( _seq "golang.org/x/mobile/bind/seq" ) // suppress the error if seq ends up unused var _ = _seq.FromRefNum type proxyobjc_D _seq.Ref func (p *proxyobjc_D) Bind_proxy_refnum__() int32 { return (*_seq.Ref)(p).Bind_IncNum() } type proxyobjc_O _seq.Ref func (p *proxyobjc_O) Bind_proxy_refnum__() int32 { return (*_seq.Ref)(p).Bind_IncNum() } type proxyobjc_S _seq.Ref func (p *proxyobjc_S) Bind_proxy_refnum__() int32 { return (*_seq.Ref)(p).Bind_IncNum() }
mobile/bind/testdata/objc.go.golden/0
{ "file_path": "mobile/bind/testdata/objc.go.golden", "repo_id": "mobile", "token_count": 658 }
587
// 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 secondpkg is imported by bind tests that verify // that a bound package can reference another bound package. package secondpkg type ( Ser interface { S(_ *S) } IF interface { F() } I interface { F(i int) int } S struct{} ) func (_ *S) F(i int) int { return i } const HelloString = "secondpkg string" func Hello() string { return HelloString } type Secondpkg struct { V string } func (_ *Secondpkg) M() { } func NewSecondpkg() *Secondpkg { return new(Secondpkg) }
mobile/bind/testdata/testpkg/secondpkg/secondpkg.go/0
{ "file_path": "mobile/bind/testdata/testpkg/secondpkg/secondpkg.go", "repo_id": "mobile", "token_count": 219 }
588
// Code generated by gobind. DO NOT EDIT. // Java class underscore_pkg.Underscore_struct is a proxy for talking to a Go program. // // autogenerated by gobind -lang=java underscores package underscore_pkg; import go.Seq; public final class Underscore_struct implements Seq.Proxy { static { Underscore_pkg.touch(); } private final int refnum; @Override public final int incRefnum() { Seq.incGoRef(refnum, this); return refnum; } Underscore_struct(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); } public Underscore_struct() { this.refnum = __New(); Seq.trackGoRef(refnum, this); } private static native int __New(); public final native String getUnderscore_field(); public final native void setUnderscore_field(String v); @Override public boolean equals(Object o) { if (o == null || !(o instanceof Underscore_struct)) { return false; } Underscore_struct that = (Underscore_struct)o; String thisUnderscore_field = getUnderscore_field(); String thatUnderscore_field = that.getUnderscore_field(); if (thisUnderscore_field == null) { if (thatUnderscore_field != null) { return false; } } else if (!thisUnderscore_field.equals(thatUnderscore_field)) { return false; } return true; } @Override public int hashCode() { return java.util.Arrays.hashCode(new Object[] {getUnderscore_field()}); } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("Underscore_struct").append("{"); b.append("Underscore_field:").append(getUnderscore_field()).append(","); return b.append("}").toString(); } } // Code generated by gobind. DO NOT EDIT. // Java class underscore_pkg.Underscore_pkg is a proxy for talking to a Go program. // // autogenerated by gobind -lang=java underscores package underscore_pkg; import go.Seq; public abstract class Underscore_pkg { static { Seq.touch(); // for loading the native library _init(); } private Underscore_pkg() {} // 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 setUnderscore_var(long v); public static native long getUnderscore_var(); public static native void underscore_func(); }
mobile/bind/testdata/underscores.java.golden/0
{ "file_path": "mobile/bind/testdata/underscores.java.golden", "repo_id": "mobile", "token_count": 1017 }
589
// Code generated by gobind. DO NOT EDIT. // JNI function headers for the Go <=> Java bridge. // // autogenerated by gobind -lang=java vars #ifndef __Vars_H__ #define __Vars_H__ #include <jni.h> extern jclass proxy_class_vars_I; extern jmethodID proxy_class_vars_I_cons; extern jclass proxy_class_vars_S; extern jmethodID proxy_class_vars_S_cons; #endif
mobile/bind/testdata/vars.java.h.golden/0
{ "file_path": "mobile/bind/testdata/vars.java.h.golden", "repo_id": "mobile", "token_count": 144 }
590
// 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" "crypto/x509" "encoding/pem" "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "text/template" "golang.org/x/tools/go/packages" ) func goAppleBuild(pkg *packages.Package, bundleID string, targets []targetInfo) (map[string]bool, error) { src := pkg.PkgPath if buildO != "" && !strings.HasSuffix(buildO, ".app") { return nil, fmt.Errorf("-o must have an .app for -target=ios") } productName := rfc1034Label(path.Base(pkg.PkgPath)) if productName == "" { productName = "ProductName" // like xcode. } infoplist := new(bytes.Buffer) if err := infoplistTmpl.Execute(infoplist, infoplistTmplData{ BundleID: bundleID + "." + productName, Name: strings.Title(path.Base(pkg.PkgPath)), }); err != nil { return nil, err } // Detect the team ID teamID, err := detectTeamID() if err != nil { return nil, err } projPbxproj := new(bytes.Buffer) if err := projPbxprojTmpl.Execute(projPbxproj, projPbxprojTmplData{ TeamID: teamID, }); err != nil { return nil, err } files := []struct { name string contents []byte }{ {tmpdir + "/main.xcodeproj/project.pbxproj", projPbxproj.Bytes()}, {tmpdir + "/main/Info.plist", infoplist.Bytes()}, {tmpdir + "/main/Images.xcassets/AppIcon.appiconset/Contents.json", []byte(contentsJSON)}, } for _, file := range files { if err := mkdir(filepath.Dir(file.name)); err != nil { return nil, err } if buildX { printcmd("echo \"%s\" > %s", file.contents, file.name) } if !buildN { if err := ioutil.WriteFile(file.name, file.contents, 0644); err != nil { return nil, err } } } // We are using lipo tool to build multiarchitecture binaries. cmd := exec.Command( "xcrun", "lipo", "-o", filepath.Join(tmpdir, "main/main"), "-create", ) var nmpkgs map[string]bool builtArch := map[string]bool{} for _, t := range targets { // Only one binary per arch allowed // e.g. ios/arm64 + iossimulator/amd64 if builtArch[t.arch] { continue } builtArch[t.arch] = true path := filepath.Join(tmpdir, t.platform, t.arch) // Disable DWARF; see golang.org/issues/25148. if err := goBuild(src, appleEnv[t.String()], "-ldflags=-w", "-o="+path); err != nil { return nil, err } if nmpkgs == nil { var err error nmpkgs, err = extractPkgs(appleNM, path) if err != nil { return nil, err } } cmd.Args = append(cmd.Args, path) } if err := runCmd(cmd); err != nil { return nil, err } // TODO(jbd): Set the launcher icon. if err := appleCopyAssets(pkg, tmpdir); err != nil { return nil, err } // Build and move the release build to the output directory. cmdStrings := []string{ "xcodebuild", "-configuration", "Release", "-project", tmpdir + "/main.xcodeproj", "-allowProvisioningUpdates", "DEVELOPMENT_TEAM=" + teamID, } cmd = exec.Command("xcrun", cmdStrings...) if err := runCmd(cmd); err != nil { return nil, err } // TODO(jbd): Fallback to copying if renaming fails. if buildO == "" { n := pkg.PkgPath if n == "." { // use cwd name cwd, err := os.Getwd() if err != nil { return nil, fmt.Errorf("cannot create .app; cannot get the current working dir: %v", err) } n = cwd } n = path.Base(n) buildO = n + ".app" } if buildX { printcmd("mv %s %s", tmpdir+"/build/Release-iphoneos/main.app", buildO) } if !buildN { // if output already exists, remove. if err := os.RemoveAll(buildO); err != nil { return nil, err } if err := os.Rename(tmpdir+"/build/Release-iphoneos/main.app", buildO); err != nil { return nil, err } } return nmpkgs, nil } func detectTeamID() (string, error) { // Grabs the first certificate for "Apple Development"; will not work if there // are multiple certificates and the first is not desired. cmd := exec.Command( "security", "find-certificate", "-c", "Apple Development", "-p", ) pemString, err := cmd.Output() if err != nil { err = fmt.Errorf("failed to pull the signing certificate to determine your team ID: %v", err) return "", err } block, _ := pem.Decode(pemString) if block == nil { err = fmt.Errorf("failed to decode the PEM to determine your team ID: %s", pemString) return "", err } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { err = fmt.Errorf("failed to parse your signing certificate to determine your team ID: %v", err) return "", err } if len(cert.Subject.OrganizationalUnit) == 0 { err = fmt.Errorf("the signing certificate has no organizational unit (team ID)") return "", err } return cert.Subject.OrganizationalUnit[0], nil } func appleCopyAssets(pkg *packages.Package, xcodeProjDir string) error { dstAssets := xcodeProjDir + "/main/assets" if err := mkdir(dstAssets); err != nil { return err } // TODO(hajimehoshi): This works only with Go tools that assume all source files are in one directory. // Fix this to work with other Go tools. srcAssets := filepath.Join(filepath.Dir(pkg.GoFiles[0]), "assets") fi, err := os.Stat(srcAssets) if err != nil { if os.IsNotExist(err) { // skip walking through the directory to deep copy. return nil } return err } if !fi.IsDir() { // skip walking through to deep copy. return nil } // if assets is a symlink, follow the symlink. srcAssets, err = filepath.EvalSymlinks(srcAssets) if err != nil { return err } return filepath.Walk(srcAssets, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if name := filepath.Base(path); strings.HasPrefix(name, ".") { // Do not include the hidden files. return nil } if info.IsDir() { return nil } dst := dstAssets + "/" + path[len(srcAssets)+1:] return copyFile(dst, path) }) } type infoplistTmplData struct { BundleID string Name string } var infoplistTmpl = template.Must(template.New("infoplist").Parse(`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>main</string> <key>CFBundleIdentifier</key> <string>{{.BundleID}}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>{{.Name}}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist> `)) type projPbxprojTmplData struct { TeamID string } var projPbxprojTmpl = template.Must(template.New("projPbxproj").Parse(`// !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 254BB84F1B1FD08900C56DE9 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 254BB84E1B1FD08900C56DE9 /* Images.xcassets */; }; 254BB8681B1FD16500C56DE9 /* main in Resources */ = {isa = PBXBuildFile; fileRef = 254BB8671B1FD16500C56DE9 /* main */; }; 25FB30331B30FDEE0005924C /* assets in Resources */ = {isa = PBXBuildFile; fileRef = 25FB30321B30FDEE0005924C /* assets */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 254BB83E1B1FD08900C56DE9 /* main.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = main.app; sourceTree = BUILT_PRODUCTS_DIR; }; 254BB8421B1FD08900C56DE9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 254BB84E1B1FD08900C56DE9 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = "<group>"; }; 254BB8671B1FD16500C56DE9 /* main */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.executable"; path = main; sourceTree = "<group>"; }; 25FB30321B30FDEE0005924C /* assets */ = {isa = PBXFileReference; lastKnownFileType = folder; name = assets; path = main/assets; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXGroup section */ 254BB8351B1FD08900C56DE9 = { isa = PBXGroup; children = ( 25FB30321B30FDEE0005924C /* assets */, 254BB8401B1FD08900C56DE9 /* main */, 254BB83F1B1FD08900C56DE9 /* Products */, ); sourceTree = "<group>"; usesTabs = 0; }; 254BB83F1B1FD08900C56DE9 /* Products */ = { isa = PBXGroup; children = ( 254BB83E1B1FD08900C56DE9 /* main.app */, ); name = Products; sourceTree = "<group>"; }; 254BB8401B1FD08900C56DE9 /* main */ = { isa = PBXGroup; children = ( 254BB8671B1FD16500C56DE9 /* main */, 254BB84E1B1FD08900C56DE9 /* Images.xcassets */, 254BB8411B1FD08900C56DE9 /* Supporting Files */, ); path = main; sourceTree = "<group>"; }; 254BB8411B1FD08900C56DE9 /* Supporting Files */ = { isa = PBXGroup; children = ( 254BB8421B1FD08900C56DE9 /* Info.plist */, ); name = "Supporting Files"; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 254BB83D1B1FD08900C56DE9 /* main */ = { isa = PBXNativeTarget; buildConfigurationList = 254BB8611B1FD08900C56DE9 /* Build configuration list for PBXNativeTarget "main" */; buildPhases = ( 254BB83C1B1FD08900C56DE9 /* Resources */, ); buildRules = ( ); dependencies = ( ); name = main; productName = main; productReference = 254BB83E1B1FD08900C56DE9 /* main.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 254BB8361B1FD08900C56DE9 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0630; ORGANIZATIONNAME = Developer; TargetAttributes = { 254BB83D1B1FD08900C56DE9 = { CreatedOnToolsVersion = 6.3.1; DevelopmentTeam = {{.TeamID}}; }; }; }; buildConfigurationList = 254BB8391B1FD08900C56DE9 /* Build configuration list for PBXProject "main" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 254BB8351B1FD08900C56DE9; productRefGroup = 254BB83F1B1FD08900C56DE9 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 254BB83D1B1FD08900C56DE9 /* main */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 254BB83C1B1FD08900C56DE9 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 25FB30331B30FDEE0005924C /* assets in Resources */, 254BB8681B1FD16500C56DE9 /* main in Resources */, 254BB84F1B1FD08900C56DE9 /* Images.xcassets in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 254BB8601B1FD08900C56DE9 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Development"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; ENABLE_BITCODE = YES; }; name = Release; }; 254BB8631B1FD08900C56DE9 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = main/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 254BB8391B1FD08900C56DE9 /* Build configuration list for PBXProject "main" */ = { isa = XCConfigurationList; buildConfigurations = ( 254BB8601B1FD08900C56DE9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 254BB8611B1FD08900C56DE9 /* Build configuration list for PBXNativeTarget "main" */ = { isa = XCConfigurationList; buildConfigurations = ( 254BB8631B1FD08900C56DE9 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 254BB8361B1FD08900C56DE9 /* Project object */; } `)) const contentsJSON = `{ "images" : [ { "idiom" : "iphone", "size" : "29x29", "scale" : "2x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "3x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "2x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "3x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "3x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "1x" }, { "idiom" : "ipad", "size" : "29x29", "scale" : "2x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "1x" }, { "idiom" : "ipad", "size" : "40x40", "scale" : "2x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "1x" }, { "idiom" : "ipad", "size" : "76x76", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } } ` // rfc1034Label sanitizes the name to be usable in a uniform type identifier. // The sanitization is similar to xcode's rfc1034identifier macro that // replaces illegal characters (not conforming the rfc1034 label rule) with '-'. func rfc1034Label(name string) string { // * Uniform type identifier: // // According to // https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html // // A uniform type identifier is a Unicode string that usually contains characters // in the ASCII character set. However, only a subset of the ASCII characters are // permitted. You may use the Roman alphabet in upper and lower case (A–Z, a–z), // the digits 0 through 9, the dot (“.”), and the hyphen (“-”). This restriction // is based on DNS name restrictions, set forth in RFC 1035. // // Uniform type identifiers may also contain any of the Unicode characters greater // than U+007F. // // Note: the actual implementation of xcode does not allow some unicode characters // greater than U+007f. In this implementation, we just replace everything non // alphanumeric with "-" like the rfc1034identifier macro. // // * RFC1034 Label // // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> // <let-dig-hyp> ::= <let-dig> | "-" // <let-dig> ::= <letter> | <digit> const surrSelf = 0x10000 begin := false var res []rune for i, r := range name { if r == '.' && !begin { continue } begin = true switch { case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z': res = append(res, r) case '0' <= r && r <= '9': if i == 0 { res = append(res, '-') } else { res = append(res, r) } default: if r < surrSelf { res = append(res, '-') } else { res = append(res, '-', '-') } } } return string(res) }
mobile/cmd/gomobile/build_apple.go/0
{ "file_path": "mobile/cmd/gomobile/build_apple.go", "repo_id": "mobile", "token_count": 7641 }
591
// 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" type stringsFlag []string func (v *stringsFlag) Set(s string) error { var err error *v, err = splitQuotedFields(s) if *v == nil { *v = []string{} } return err } func isSpaceByte(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' } func splitQuotedFields(s string) ([]string, error) { // Split fields allowing '' or "" around elements. // Quotes further inside the string do not count. var f []string for len(s) > 0 { for len(s) > 0 && isSpaceByte(s[0]) { s = s[1:] } if len(s) == 0 { break } // Accepted quoted string. No unescaping inside. if s[0] == '"' || s[0] == '\'' { quote := s[0] s = s[1:] i := 0 for i < len(s) && s[i] != quote { i++ } if i >= len(s) { return nil, fmt.Errorf("unterminated %c string", quote) } f = append(f, s[:i]) s = s[i+1:] continue } i := 0 for i < len(s) && !isSpaceByte(s[i]) { i++ } f = append(f, s[:i]) s = s[i:] } return f, nil } func (v *stringsFlag) String() string { return "<stringsFlag>" }
mobile/cmd/gomobile/strings_flag.go/0
{ "file_path": "mobile/cmd/gomobile/strings_flag.go", "repo_id": "mobile", "token_count": 540 }
592
Go bind android app example Run $ gomobile bind -o app/hello.aar golang.org/x/mobile/example/bind/hello and import this project in Android Studio. If you prefer the command line, use gradle to build directly. Note that you need to run gomobile bind again every time you make a change to Go code.
mobile/example/bind/android/README/0
{ "file_path": "mobile/example/bind/android/README", "repo_id": "mobile", "token_count": 87 }
593
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:id="@+id/layout" android:background="@color/body"> <ScrollView android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical" android:fillViewport="false" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_above="@+id/layout_bottom" android:padding="@dimen/abc_control_padding_material"> <WebView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/webView" android:gravity="left|bottom" android:textIsSelectable="true" android:clickable="false" android:background="@color/body" /> </ScrollView> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:id="@+id/layout_bottom" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentBottom="true"> <EditText android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/editText" android:gravity="top|left|start" android:textStyle="normal" android:inputType="textVisiblePassword" android:hint="@string/editTextHelp"/> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageButton" android:background="@drawable/circle_shape" android:src="@drawable/ic_done_white_24dp" android:contentDescription="@string/ok" android:onClick="onClick" android:clickable="true" android:padding="@dimen/abc_control_padding_material" android:layout_margin="@dimen/abc_control_padding_material" /> </LinearLayout> </RelativeLayout>
mobile/example/ivy/android/app/src/main/res/layout/activity_main.xml/0
{ "file_path": "mobile/example/ivy/android/app/src/main/res/layout/activity_main.xml", "repo_id": "mobile", "token_count": 1120 }
594
// 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. // This is an empty package. // We have this package to convince this is buildable and go mod tidy can work. package dummy
mobile/example/ivy/doc.go/0
{ "file_path": "mobile/example/ivy/doc.go", "repo_id": "mobile", "token_count": 72 }
595
// 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 f32 import "fmt" // A Mat4 is a 4x4 matrix of float32 values. // Elements are indexed first by row then column, i.e. m[row][column]. type Mat4 [4]Vec4 func (m Mat4) String() string { return fmt.Sprintf(`Mat4[% 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f, % 0.3f]`, m[0][0], m[0][1], m[0][2], m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3], m[3][0], m[3][1], m[3][2], m[3][3]) } func (m *Mat4) Identity() { *m = Mat4{ {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, } } func (m *Mat4) Eq(n *Mat4, epsilon float32) bool { for i := range m { for j := range m[i] { diff := m[i][j] - n[i][j] if diff < -epsilon || +epsilon < diff { return false } } } return true } // Mul stores a × b in m. func (m *Mat4) Mul(a, b *Mat4) { // Store the result in local variables, in case m == a || m == b. m00 := a[0][0]*b[0][0] + a[0][1]*b[1][0] + a[0][2]*b[2][0] + a[0][3]*b[3][0] m01 := a[0][0]*b[0][1] + a[0][1]*b[1][1] + a[0][2]*b[2][1] + a[0][3]*b[3][1] m02 := a[0][0]*b[0][2] + a[0][1]*b[1][2] + a[0][2]*b[2][2] + a[0][3]*b[3][2] m03 := a[0][0]*b[0][3] + a[0][1]*b[1][3] + a[0][2]*b[2][3] + a[0][3]*b[3][3] m10 := a[1][0]*b[0][0] + a[1][1]*b[1][0] + a[1][2]*b[2][0] + a[1][3]*b[3][0] m11 := a[1][0]*b[0][1] + a[1][1]*b[1][1] + a[1][2]*b[2][1] + a[1][3]*b[3][1] m12 := a[1][0]*b[0][2] + a[1][1]*b[1][2] + a[1][2]*b[2][2] + a[1][3]*b[3][2] m13 := a[1][0]*b[0][3] + a[1][1]*b[1][3] + a[1][2]*b[2][3] + a[1][3]*b[3][3] m20 := a[2][0]*b[0][0] + a[2][1]*b[1][0] + a[2][2]*b[2][0] + a[2][3]*b[3][0] m21 := a[2][0]*b[0][1] + a[2][1]*b[1][1] + a[2][2]*b[2][1] + a[2][3]*b[3][1] m22 := a[2][0]*b[0][2] + a[2][1]*b[1][2] + a[2][2]*b[2][2] + a[2][3]*b[3][2] m23 := a[2][0]*b[0][3] + a[2][1]*b[1][3] + a[2][2]*b[2][3] + a[2][3]*b[3][3] m30 := a[3][0]*b[0][0] + a[3][1]*b[1][0] + a[3][2]*b[2][0] + a[3][3]*b[3][0] m31 := a[3][0]*b[0][1] + a[3][1]*b[1][1] + a[3][2]*b[2][1] + a[3][3]*b[3][1] m32 := a[3][0]*b[0][2] + a[3][1]*b[1][2] + a[3][2]*b[2][2] + a[3][3]*b[3][2] m33 := a[3][0]*b[0][3] + a[3][1]*b[1][3] + a[3][2]*b[2][3] + a[3][3]*b[3][3] m[0][0] = m00 m[0][1] = m01 m[0][2] = m02 m[0][3] = m03 m[1][0] = m10 m[1][1] = m11 m[1][2] = m12 m[1][3] = m13 m[2][0] = m20 m[2][1] = m21 m[2][2] = m22 m[2][3] = m23 m[3][0] = m30 m[3][1] = m31 m[3][2] = m32 m[3][3] = m33 } // Perspective sets m to be the GL perspective matrix. func (m *Mat4) Perspective(fov Radian, aspect, near, far float32) { t := Tan(float32(fov) / 2) m[0][0] = 1 / (aspect * t) m[1][1] = 1 / t m[2][2] = -(far + near) / (far - near) m[2][3] = -1 m[3][2] = -2 * far * near / (far - near) } // Scale sets m to be a scale followed by p. // It is equivalent to // // m.Mul(p, &Mat4{ // {x, 0, 0, 0}, // {0, y, 0, 0}, // {0, 0, z, 0}, // {0, 0, 0, 1}, // }). func (m *Mat4) Scale(p *Mat4, x, y, z float32) { m[0][0] = p[0][0] * x m[0][1] = p[0][1] * y m[0][2] = p[0][2] * z m[0][3] = p[0][3] m[1][0] = p[1][0] * x m[1][1] = p[1][1] * y m[1][2] = p[1][2] * z m[1][3] = p[1][3] m[2][0] = p[2][0] * x m[2][1] = p[2][1] * y m[2][2] = p[2][2] * z m[2][3] = p[2][3] m[3][0] = p[3][0] * x m[3][1] = p[3][1] * y m[3][2] = p[3][2] * z m[3][3] = p[3][3] } // Translate sets m to be a translation followed by p. // It is equivalent to // // m.Mul(p, &Mat4{ // {1, 0, 0, x}, // {0, 1, 0, y}, // {0, 0, 1, z}, // {0, 0, 0, 1}, // }). func (m *Mat4) Translate(p *Mat4, x, y, z float32) { m[0][0] = p[0][0] m[0][1] = p[0][1] m[0][2] = p[0][2] m[0][3] = p[0][0]*x + p[0][1]*y + p[0][2]*z + p[0][3] m[1][0] = p[1][0] m[1][1] = p[1][1] m[1][2] = p[1][2] m[1][3] = p[1][0]*x + p[1][1]*y + p[1][2]*z + p[1][3] m[2][0] = p[2][0] m[2][1] = p[2][1] m[2][2] = p[2][2] m[2][3] = p[2][0]*x + p[2][1]*y + p[2][2]*z + p[2][3] m[3][0] = p[3][0] m[3][1] = p[3][1] m[3][2] = p[3][2] m[3][3] = p[3][0]*x + p[3][1]*y + p[3][2]*z + p[3][3] } // Rotate sets m to a rotation in radians around a specified axis, followed by p. // It is equivalent to m.Mul(p, affineRotation). func (m *Mat4) Rotate(p *Mat4, angle Radian, axis *Vec3) { a := *axis a.Normalize() c, s := Cos(float32(angle)), Sin(float32(angle)) d := 1 - c m.Mul(p, &Mat4{{ c + d*a[0]*a[1], 0 + d*a[0]*a[1] + s*a[2], 0 + d*a[0]*a[1] - s*a[1], 0, }, { 0 + d*a[1]*a[0] - s*a[2], c + d*a[1]*a[1], 0 + d*a[1]*a[2] + s*a[0], 0, }, { 0 + d*a[2]*a[0] + s*a[1], 0 + d*a[2]*a[1] - s*a[0], c + d*a[2]*a[2], 0, }, { 0, 0, 0, 1, }}) } func (m *Mat4) LookAt(eye, center, up *Vec3) { f, s, u := new(Vec3), new(Vec3), new(Vec3) *f = *center f.Sub(f, eye) f.Normalize() s.Cross(f, up) s.Normalize() u.Cross(s, f) *m = Mat4{ {s[0], u[0], -f[0], 0}, {s[1], u[1], -f[1], 0}, {s[2], u[2], -f[2], 0}, {-s.Dot(eye), -u.Dot(eye), +f.Dot(eye), 1}, } }
mobile/exp/f32/mat4.go/0
{ "file_path": "mobile/exp/f32/mat4.go", "repo_id": "mobile", "token_count": 3252 }
596
// 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 // +build android #include <stdlib.h> #include <jni.h> #include <android/sensor.h> #define GO_ANDROID_SENSOR_LOOPER_ID 100 #define GO_ANDROID_READ_TIMEOUT_MS 1000 ASensorEventQueue* queue = NULL; ALooper* looper = NULL; static ASensorManager* getSensorManager() { #pragma clang diagnostic push // Builders convert C warnings to errors, so suppress the // error from ASensorManager_getInstance being deprecated // in Android 26. #pragma clang diagnostic ignored "-Wdeprecated-declarations" return ASensorManager_getInstance(); #pragma clang diagnostic pop } void GoAndroid_createManager() { ASensorManager* manager = getSensorManager(); looper = ALooper_forThread(); if (looper == NULL) { looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); } queue = ASensorManager_createEventQueue(manager, looper, GO_ANDROID_SENSOR_LOOPER_ID, NULL, NULL); } int GoAndroid_enableSensor(int s, int32_t usec) { ASensorManager* manager = getSensorManager(); const ASensor* sensor = ASensorManager_getDefaultSensor(manager, s); if (sensor == NULL) { return 1; } ASensorEventQueue_enableSensor(queue, sensor); ASensorEventQueue_setEventRate(queue, sensor, usec); return 0; } void GoAndroid_disableSensor(int s) { ASensorManager* manager = getSensorManager(); const ASensor* sensor = ASensorManager_getDefaultSensor(manager, s); ASensorEventQueue_disableSensor(queue, sensor); } int GoAndroid_readQueue(int n, int32_t* types, int64_t* timestamps, float* vectors) { int id; int events; ASensorEvent event; int i = 0; // Try n times read from the event queue. // If anytime timeout occurs, don't retry to read and immediately return. // Consume the event queue entirely between polls. while (i < n && (id = ALooper_pollOnce(GO_ANDROID_READ_TIMEOUT_MS, NULL, &events, NULL)) >= 0) { if (id != GO_ANDROID_SENSOR_LOOPER_ID) { continue; } while (i < n && ASensorEventQueue_getEvents(queue, &event, 1)) { types[i] = event.type; timestamps[i] = event.timestamp; vectors[i*3] = event.vector.x; vectors[i*3+1] = event.vector.y; vectors[i*3+2] = event.vector.z; i++; } } return i; } void GoAndroid_destroyManager() { ASensorManager* manager = getSensorManager(); ASensorManager_destroyEventQueue(manager, queue); queue = NULL; looper = NULL; }
mobile/exp/sensor/android.c/0
{ "file_path": "mobile/exp/sensor/android.c", "repo_id": "mobile", "token_count": 898 }
597
// 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 gl implements Go bindings for OpenGL ES 2.0 and ES 3.0. The GL functions are defined on a Context object that is responsible for tracking a GL context. Typically a windowing system package (such as golang.org/x/exp/shiny/screen) will call NewContext and provide a gl.Context for a user application. If the gl package is compiled on a platform capable of supporting ES 3.0, the gl.Context object also implements gl.Context3. The bindings are deliberately minimal, staying as close the C API as possible. The semantics of each function maps onto functions described in the Khronos documentation: https://www.khronos.org/opengles/sdk/docs/man/ One notable departure from the C API is the introduction of types to represent common uses of GLint: Texture, Surface, Buffer, etc. # Debug Logging A tracing version of the OpenGL bindings is behind the `gldebug` build tag. It acts as a simplified version of apitrace. Build your Go binary with -tags gldebug and each call to a GL function will log its input, output, and any error messages. For example, I/GoLog (27668): gl.GenBuffers(1) [Buffer(70001)] I/GoLog (27668): gl.BindBuffer(ARRAY_BUFFER, Buffer(70001)) I/GoLog (27668): gl.BufferData(ARRAY_BUFFER, 36, len(36), STATIC_DRAW) I/GoLog (27668): gl.BindBuffer(ARRAY_BUFFER, Buffer(70001)) I/GoLog (27668): gl.VertexAttribPointer(Attrib(0), 6, FLOAT, false, 0, 0) error: [INVALID_VALUE] The gldebug tracing has very high overhead, so make sure to remove the build tag before deploying any binaries. */ package gl // import "golang.org/x/mobile/gl" /* Implementation details. All GL function calls fill out a C.struct_fnargs and drop it on the work queue. The Start function drains the work queue and hands over a batch of calls to C.process which runs them. This allows multiple GL calls to be executed in a single cgo call. A GL call is marked as blocking if it returns a value, or if it takes a Go pointer. In this case the call will not return until C.process sends a value on the retvalue channel. This implementation ensures any goroutine can make GL calls, but it does not make the GL interface safe for simultaneous use by multiple goroutines. For the purpose of analyzing this code for race conditions, picture two separate goroutines: one blocked on gl.Start, and another making calls to the gl package exported functions. */ //go:generate go run gendebug.go -o gldebug.go
mobile/gl/doc.go/0
{ "file_path": "mobile/gl/doc.go", "repo_id": "mobile", "token_count": 750 }
598
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.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ= golang.org/x/image v0.18.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E= golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
mobile/go.sum/0
{ "file_path": "mobile/go.sum", "repo_id": "mobile", "token_count": 715 }
599
package importers import ( "go/parser" "go/token" "reflect" "testing" ) func TestAnalyzer(t *testing.T) { file := `package ast_test import "Prefix/some/pkg/Name" import "Prefix/some/pkg/Name2" const c = Name.Constant type T struct { Name.Type unexported Name.Type2 } func f() { Name2.Func().Func().Func() } ` fset := token.NewFileSet() f, err := parser.ParseFile(fset, "ast_test.go", file, parser.AllErrors) if err != nil { t.Fatal(err) } refs, err := AnalyzeFile(f, "Prefix/") if err != nil { t.Fatal(err) } exps := []PkgRef{ {Pkg: "some/pkg/Name", Name: "Constant"}, {Pkg: "some/pkg/Name", Name: "Type"}, {Pkg: "some/pkg/Name2", Name: "Func"}, {Pkg: "some/pkg/Name", Name: "Type2"}, } if len(refs.Refs) != len(exps) { t.Fatalf("expected %d references; got %d", len(exps), len(refs.Refs)) } for i, exp := range exps { if got := refs.Refs[i]; exp != got { t.Errorf("expected ref %v; got %v", exp, got) } } if _, exists := refs.Names["Constant"]; !exists { t.Errorf("expected \"Constant\" in the names set") } if len(refs.Embedders) != 1 { t.Fatalf("expected 1 struct; got %d", len(refs.Embedders)) } s := refs.Embedders[0] exp := Struct{ Name: "T", Pkg: "ast_test", Refs: []PkgRef{{Pkg: "some/pkg/Name", Name: "Type"}}, } if !reflect.DeepEqual(exp, s) { t.Errorf("expected struct %v; got %v", exp, s) } }
mobile/internal/importers/ast_test.go/0
{ "file_path": "mobile/internal/importers/ast_test.go", "repo_id": "mobile", "token_count": 633 }
600
# This is the official list of GoMock authors for copyright purposes. # This file is distinct from the CONTRIBUTORS files. # See the latter for an explanation. # Names should be added to this file as # Name or Organization <email address> # The email address is not required for organizations. # Please keep the list sorted. Alex Reece <awreece@gmail.com> Google Inc.
mock/AUTHORS/0
{ "file_path": "mock/AUTHORS", "repo_id": "mock", "token_count": 98 }
601
package gomock_test //go:generate mockgen -destination mock_test.go -package gomock_test -source example_test.go import ( "fmt" "testing" "time" "github.com/golang/mock/gomock" ) type Foo interface { Bar(string) string } func ExampleCall_DoAndReturn_latency() { t := &testing.T{} // provided by test ctrl := gomock.NewController(t) mockIndex := NewMockFoo(ctrl) mockIndex.EXPECT().Bar(gomock.Any()).DoAndReturn( func(arg string) string { time.Sleep(1 * time.Millisecond) return "I'm sleepy" }, ) r := mockIndex.Bar("foo") fmt.Println(r) // Output: I'm sleepy } func ExampleCall_DoAndReturn_captureArguments() { t := &testing.T{} // provided by test ctrl := gomock.NewController(t) mockIndex := NewMockFoo(ctrl) var s string mockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn( func(arg string) interface{} { s = arg return "I'm sleepy" }, ) r := mockIndex.Bar("foo") fmt.Printf("%s %s", r, s) // Output: I'm sleepy foo }
mock/gomock/example_test.go/0
{ "file_path": "mock/gomock/example_test.go", "repo_id": "mock", "token_count": 406 }
602
package bugreport import ( "github.com/golang/mock/gomock" "testing" ) func TestExample_Method(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockExample(ctrl) m.EXPECT().Method(1, 2, 3, 4) m.Method(1, 2, 3, 4) ctrl.Finish() } func TestExample_VarargMethod(t *testing.T) { ctrl := gomock.NewController(t) m := NewMockExample(ctrl) m.EXPECT().VarargMethod(1, 2, 3, 4, 6, 7) m.VarargMethod(1, 2, 3, 4, 6, 7) ctrl.Finish() }
mock/mockgen/internal/tests/generated_identifier_conflict/bugreport_test.go/0
{ "file_path": "mock/mockgen/internal/tests/generated_identifier_conflict/bugreport_test.go", "repo_id": "mock", "token_count": 202 }
603
// Code generated by MockGen. DO NOT EDIT. // Source: net.go // Package bugreport is a generated GoMock package. package bugreport import ( http "net/http" reflect "reflect" gomock "github.com/golang/mock/gomock" ) // MockNet is a mock of Net interface. type MockNet struct { ctrl *gomock.Controller recorder *MockNetMockRecorder } // MockNetMockRecorder is the mock recorder for MockNet. type MockNetMockRecorder struct { mock *MockNet } // NewMockNet creates a new mock instance. func NewMockNet(ctrl *gomock.Controller) *MockNet { mock := &MockNet{ctrl: ctrl} mock.recorder = &MockNetMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockNet) EXPECT() *MockNetMockRecorder { return m.recorder } // Header mocks base method. func (m *MockNet) Header() http.Header { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Header") ret0, _ := ret[0].(http.Header) return ret0 } // Header indicates an expected call of Header. func (mr *MockNetMockRecorder) Header() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Header", reflect.TypeOf((*MockNet)(nil).Header)) } // Write mocks base method. func (m *MockNet) Write(arg0 []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Write", arg0) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Write indicates an expected call of Write. func (mr *MockNetMockRecorder) Write(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockNet)(nil).Write), arg0) } // WriteHeader mocks base method. func (m *MockNet) WriteHeader(statusCode int) { m.ctrl.T.Helper() m.ctrl.Call(m, "WriteHeader", statusCode) } // WriteHeader indicates an expected call of WriteHeader. func (mr *MockNetMockRecorder) WriteHeader(statusCode interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteHeader", reflect.TypeOf((*MockNet)(nil).WriteHeader), statusCode) }
mock/mockgen/internal/tests/import_embedded_interface/net_mock.go/0
{ "file_path": "mock/mockgen/internal/tests/import_embedded_interface/net_mock.go", "repo_id": "mock", "token_count": 781 }
604
package users //go:generate mockgen --source=user.go --destination=mock_test.go --package=users_test type User struct { Name string } type Finder interface { FindUser(name string) User Add(u User) }
mock/mockgen/internal/tests/mock_in_test_package/user.go/0
{ "file_path": "mock/mockgen/internal/tests/mock_in_test_package/user.go", "repo_id": "mock", "token_count": 70 }
605
package users_test //go:generate mockgen --source=user_test.go --destination=mock_test.go --package=users_test type User struct { Name string } type Finder interface { FindUser(name string) User Add(u User) }
mock/mockgen/internal/tests/test_package/user_test.go/0
{ "file_path": "mock/mockgen/internal/tests/test_package/user_test.go", "repo_id": "mock", "token_count": 74 }
606
package model import ( "fmt" "testing" ) func TestImpPath(t *testing.T) { nonVendor := "github.com/foo/bar" if nonVendor != impPath(nonVendor) { t.Errorf("") } testCases := []struct { input string want string }{ {"foo/bar", "foo/bar"}, {"vendor/foo/bar", "foo/bar"}, {"vendor/foo/vendor/bar", "bar"}, {"/vendor/foo/bar", "foo/bar"}, {"qux/vendor/foo/bar", "foo/bar"}, {"qux/vendor/foo/vendor/bar", "bar"}, {"govendor/foo", "govendor/foo"}, {"foo/govendor/bar", "foo/govendor/bar"}, {"vendors/foo", "vendors/foo"}, {"foo/vendors/bar", "foo/vendors/bar"}, } for _, tc := range testCases { t.Run(fmt.Sprintf("input %s", tc.input), func(t *testing.T) { if got := impPath(tc.input); got != tc.want { t.Errorf("got %s; want %s", got, tc.want) } }) } }
mock/mockgen/model/model_test.go/0
{ "file_path": "mock/mockgen/model/model_test.go", "repo_id": "mock", "token_count": 376 }
607
# Go Networking [![Go Reference](https://pkg.go.dev/badge/golang.org/x/net.svg)](https://pkg.go.dev/golang.org/x/net) This repository holds supplementary Go networking libraries. ## Download/Install The easiest way to install is to run `go get -u golang.org/x/net`. You can also manually git clone the repository to `$GOPATH/src/golang.org/x/net`. ## Report Issues / Send Patches This repository uses Gerrit for code changes. To learn how to submit changes to this repository, see https://golang.org/doc/contribute.html. The main issue tracker for the net repository is located at https://github.com/golang/go/issues. Prefix your issue with "x/net:" in the subject line, so it is easy to find.
net/README.md/0
{ "file_path": "net/README.md", "repo_id": "net", "token_count": 220 }
608
// 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 bpf_test import ( "testing" "golang.org/x/net/bpf" ) func TestVMRetA(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 1, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 9, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMRetALargerThanInput(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.LoadAbsolute{ Off: 8, Size: 2, }, bpf.RetA{}, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 255, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMRetConstant(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.RetConstant{ Val: 9, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 1, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } } func TestVMRetConstantLargerThanInput(t *testing.T) { vm, done, err := testVM(t, []bpf.Instruction{ bpf.RetConstant{ Val: 16, }, }) if err != nil { t.Fatalf("failed to load BPF program: %v", err) } defer done() out, err := vm.Run([]byte{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 1, }) if err != nil { t.Fatalf("unexpected error while running program: %v", err) } if want, got := 2, out; want != got { t.Fatalf("unexpected number of output bytes:\n- want: %d\n- got: %d", want, got) } }
net/bpf/vm_ret_test.go/0
{ "file_path": "net/bpf/vm_ret_test.go", "repo_id": "net", "token_count": 1070 }
609
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package html import ( "golang.org/x/net/html/atom" ) // A NodeType is the type of a Node. type NodeType uint32 const ( ErrorNode NodeType = iota TextNode DocumentNode ElementNode CommentNode DoctypeNode // RawNode nodes are not returned by the parser, but can be part of the // Node tree passed to func Render to insert raw HTML (without escaping). // If so, this package makes no guarantee that the rendered HTML is secure // (from e.g. Cross Site Scripting attacks) or well-formed. RawNode scopeMarkerNode ) // Section 12.2.4.3 says "The markers are inserted when entering applet, // object, marquee, template, td, th, and caption elements, and are used // to prevent formatting from "leaking" into applet, object, marquee, // template, td, th, and caption elements". var scopeMarker = Node{Type: scopeMarkerNode} // A Node consists of a NodeType and some Data (tag name for element nodes, // content for text) and are part of a tree of Nodes. Element nodes may also // have a Namespace and contain a slice of Attributes. Data is unescaped, so // that it looks like "a<b" rather than "a&lt;b". For element nodes, DataAtom // is the atom for Data, or zero if Data is not a known tag name. // // An empty Namespace implies a "http://www.w3.org/1999/xhtml" namespace. // Similarly, "math" is short for "http://www.w3.org/1998/Math/MathML", and // "svg" is short for "http://www.w3.org/2000/svg". type Node struct { Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node Type NodeType DataAtom atom.Atom Data string Namespace string Attr []Attribute } // InsertBefore inserts newChild as a child of n, immediately before oldChild // in the sequence of n's children. oldChild may be nil, in which case newChild // is appended to the end of n's children. // // It will panic if newChild already has a parent or siblings. func (n *Node) InsertBefore(newChild, oldChild *Node) { if newChild.Parent != nil || newChild.PrevSibling != nil || newChild.NextSibling != nil { panic("html: InsertBefore called for an attached child Node") } var prev, next *Node if oldChild != nil { prev, next = oldChild.PrevSibling, oldChild } else { prev = n.LastChild } if prev != nil { prev.NextSibling = newChild } else { n.FirstChild = newChild } if next != nil { next.PrevSibling = newChild } else { n.LastChild = newChild } newChild.Parent = n newChild.PrevSibling = prev newChild.NextSibling = next } // AppendChild adds a node c as a child of n. // // It will panic if c already has a parent or siblings. func (n *Node) AppendChild(c *Node) { if c.Parent != nil || c.PrevSibling != nil || c.NextSibling != nil { panic("html: AppendChild called for an attached child Node") } last := n.LastChild if last != nil { last.NextSibling = c } else { n.FirstChild = c } n.LastChild = c c.Parent = n c.PrevSibling = last } // RemoveChild removes a node c that is a child of n. Afterwards, c will have // no parent and no siblings. // // It will panic if c's parent is not n. func (n *Node) RemoveChild(c *Node) { if c.Parent != n { panic("html: RemoveChild called for a non-child Node") } if n.FirstChild == c { n.FirstChild = c.NextSibling } if c.NextSibling != nil { c.NextSibling.PrevSibling = c.PrevSibling } if n.LastChild == c { n.LastChild = c.PrevSibling } if c.PrevSibling != nil { c.PrevSibling.NextSibling = c.NextSibling } c.Parent = nil c.PrevSibling = nil c.NextSibling = nil } // reparentChildren reparents all of src's child nodes to dst. func reparentChildren(dst, src *Node) { for { child := src.FirstChild if child == nil { break } src.RemoveChild(child) dst.AppendChild(child) } } // clone returns a new node with the same type, data and attributes. // The clone has no parent, no siblings and no children. func (n *Node) clone() *Node { m := &Node{ Type: n.Type, DataAtom: n.DataAtom, Data: n.Data, Attr: make([]Attribute, len(n.Attr)), } copy(m.Attr, n.Attr) return m } // nodeStack is a stack of nodes. type nodeStack []*Node // pop pops the stack. It will panic if s is empty. func (s *nodeStack) pop() *Node { i := len(*s) n := (*s)[i-1] *s = (*s)[:i-1] return n } // top returns the most recently pushed node, or nil if s is empty. func (s *nodeStack) top() *Node { if i := len(*s); i > 0 { return (*s)[i-1] } return nil } // index returns the index of the top-most occurrence of n in the stack, or -1 // if n is not present. func (s *nodeStack) index(n *Node) int { for i := len(*s) - 1; i >= 0; i-- { if (*s)[i] == n { return i } } return -1 } // contains returns whether a is within s. func (s *nodeStack) contains(a atom.Atom) bool { for _, n := range *s { if n.DataAtom == a && n.Namespace == "" { return true } } return false } // insert inserts a node at the given index. func (s *nodeStack) insert(i int, n *Node) { (*s) = append(*s, nil) copy((*s)[i+1:], (*s)[i:]) (*s)[i] = n } // remove removes a node from the stack. It is a no-op if n is not present. func (s *nodeStack) remove(n *Node) { i := s.index(n) if i == -1 { return } copy((*s)[i:], (*s)[i+1:]) j := len(*s) - 1 (*s)[j] = nil *s = (*s)[:j] } type insertionModeStack []insertionMode func (s *insertionModeStack) pop() (im insertionMode) { i := len(*s) im = (*s)[i-1] *s = (*s)[:i-1] return im } func (s *insertionModeStack) top() insertionMode { if i := len(*s); i > 0 { return (*s)[i-1] } return nil }
net/html/node.go/0
{ "file_path": "net/html/node.go", "repo_id": "net", "token_count": 2073 }
610
#data FOO<!-- BAR -->BAZ #errors (1,3): expected-doctype-but-got-chars #document | <html> | <head> | <body> | "FOO" | <!-- BAR --> | "BAZ" #data FOO<!-- BAR --!>BAZ #errors (1,3): expected-doctype-but-got-chars (1,15): unexpected-bang-after-double-dash-in-comment #new-errors (1:16) incorrectly-closed-comment #document | <html> | <head> | <body> | "FOO" | <!-- BAR --> | "BAZ" #data FOO<!-- BAR --! >BAZ #errors (1,3): expected-doctype-but-got-chars #new-errors (1:20) eof-in-comment #document | <html> | <head> | <body> | "FOO" | <!-- BAR --! >BAZ --> #data FOO<!-- BAR --! >BAZ #errors (1,3): expected-doctype-but-got-chars #new-errors (1:20) eof-in-comment #document | <html> | <head> | <body> | "FOO" | <!-- BAR --! >BAZ --> #data FOO<!-- BAR -- >BAZ #errors (1,3): expected-doctype-but-got-chars (1,15): unexpected-char-in-comment (1,21): eof-in-comment #new-errors (1:22) eof-in-comment #document | <html> | <head> | <body> | "FOO" | <!-- BAR -- >BAZ --> #data FOO<!-- BAR -- <QUX> -- MUX -->BAZ #errors (1,3): expected-doctype-but-got-chars (1,15): unexpected-char-in-comment (1,24): unexpected-char-in-comment #document | <html> | <head> | <body> | "FOO" | <!-- BAR -- <QUX> -- MUX --> | "BAZ" #data FOO<!-- BAR -- <QUX> -- MUX --!>BAZ #errors (1,3): expected-doctype-but-got-chars (1,15): unexpected-char-in-comment (1,24): unexpected-char-in-comment (1,31): unexpected-bang-after-double-dash-in-comment #new-errors (1:32) incorrectly-closed-comment #document | <html> | <head> | <body> | "FOO" | <!-- BAR -- <QUX> -- MUX --> | "BAZ" #data FOO<!-- BAR -- <QUX> -- MUX -- >BAZ #errors (1,3): expected-doctype-but-got-chars (1,15): unexpected-char-in-comment (1,24): unexpected-char-in-comment (1,31): unexpected-char-in-comment (1,35): eof-in-comment #new-errors (1:36) eof-in-comment #document | <html> | <head> | <body> | "FOO" | <!-- BAR -- <QUX> -- MUX -- >BAZ --> #data FOO<!---->BAZ #errors (1,3): expected-doctype-but-got-chars #document | <html> | <head> | <body> | "FOO" | <!-- --> | "BAZ" #data FOO<!--->BAZ #errors (1,3): expected-doctype-but-got-chars (1,9): incorrect-comment #new-errors (1:9) abrupt-closing-of-empty-comment #document | <html> | <head> | <body> | "FOO" | <!-- --> | "BAZ" #data FOO<!-->BAZ #errors (1,3): expected-doctype-but-got-chars (1,8): incorrect-comment #new-errors (1:8) abrupt-closing-of-empty-comment #document | <html> | <head> | <body> | "FOO" | <!-- --> | "BAZ" #data <?xml version="1.0">Hi #errors (1,1): expected-tag-name-but-got-question-mark (1,22): expected-doctype-but-got-chars #new-errors (1:2) unexpected-question-mark-instead-of-tag-name #document | <!-- ?xml version="1.0" --> | <html> | <head> | <body> | "Hi" #data <?xml version="1.0"> #errors (1,1): expected-tag-name-but-got-question-mark (1,20): expected-doctype-but-got-eof #new-errors (1:2) unexpected-question-mark-instead-of-tag-name #document | <!-- ?xml version="1.0" --> | <html> | <head> | <body> #data <?xml version #errors (1,1): expected-tag-name-but-got-question-mark (1,13): expected-doctype-but-got-eof #new-errors (1:2) unexpected-question-mark-instead-of-tag-name #document | <!-- ?xml version --> | <html> | <head> | <body> #data FOO<!----->BAZ #errors (1,3): expected-doctype-but-got-chars (1,10): unexpected-dash-after-double-dash-in-comment #document | <html> | <head> | <body> | "FOO" | <!-- - --> | "BAZ" #data <html><!-- comment --><title>Comment before head</title> #errors (1,6): expected-doctype-but-got-start-tag #document | <html> | <!-- comment --> | <head> | <title> | "Comment before head" | <body>
net/html/testdata/webkit/comments01.dat/0
{ "file_path": "net/html/testdata/webkit/comments01.dat", "repo_id": "net", "token_count": 1844 }
611
#data FOO&#x000D;ZOO #errors (1,3): expected-doctype-but-got-chars (1,11): illegal-codepoint-for-numeric-entity #new-errors (1:12) control-character-reference #document | <html> | <head> | <body> | "FOO ZOO" #data <html><frameset></frameset> #errors (1,6): expected-doctype-but-got-start-tag (1,7): invalid-codepoint (1,7): invalid-codepoint-in-body (1,17): unexpected-start-tag #new-errors (1:7) unexpected-null-character #document | <html> | <head> | <frameset> #data <html> <frameset></frameset> #errors (1,6): expected-doctype-but-got-start-tag (1,8): invalid-codepoint (1,8): invalid-codepoint-in-body (1,19): unexpected-start-tag #new-errors (1:8) unexpected-null-character #document | <html> | <head> | <frameset> #data <html>aa<frameset></frameset> #errors (1,6): expected-doctype-but-got-start-tag (1,8): invalid-codepoint (1,8): invalid-codepoint-in-body (1,19): unexpected-start-tag (1,30): unexpected-end-tag #new-errors (1:8) unexpected-null-character #document | <html> | <head> | <body> | "aa" #data <html><frameset></frameset> #errors (1,6): expected-doctype-but-got-start-tag (1,7): invalid-codepoint (1,7): invalid-codepoint-in-body (1,8): invalid-codepoint (1,8): invalid-codepoint-in-body (1,18): unexpected-start-tag #new-errors (1:7) unexpected-null-character (1:8) unexpected-null-character #document | <html> | <head> | <frameset> #data <html> <frameset></frameset> #errors (1,6): expected-doctype-but-got-start-tag (1,7): invalid-codepoint (1,7): invalid-codepoint-in-body (2,11): unexpected-start-tag #new-errors (1:7) unexpected-null-character #document | <html> | <head> | <frameset> #data <html><select> #errors (1,6): expected-doctype-but-got-start-tag (1,15): invalid-codepoint (1,15): invalid-codepoint-in-select (1,15): eof-in-select #new-errors (1:15) unexpected-null-character #document | <html> | <head> | <body> | <select> #data #errors (1,1): invalid-codepoint (1,1): expected-doctype-but-got-chars (1,1): invalid-codepoint-in-body #new-errors (1:1) unexpected-null-character #document | <html> | <head> | <body> #data <body> #errors (1,6): expected-doctype-but-got-start-tag (1,7): invalid-codepoint (1,7): invalid-codepoint-in-body #new-errors (1:7) unexpected-null-character #document | <html> | <head> | <body> #data <plaintext>fillertext #errors (1,11): expected-doctype-but-got-start-tag (1,12): invalid-codepoint (1,19): invalid-codepoint (1,24): invalid-codepoint (1,24): expected-closing-tag-but-got-eof #new-errors (1:12) unexpected-null-character (1:19) unexpected-null-character (1:24) unexpected-null-character #document | <html> | <head> | <body> | <plaintext> | "�filler�text�" #data <svg><![CDATA[fillertext]]> #errors (1,5): expected-doctype-but-got-start-tag (1,30): invalid-codepoint (1,30): invalid-codepoint (1,30): invalid-codepoint (1,30): expected-closing-tag-but-got-eof #document | <html> | <head> | <body> | <svg svg> | "�filler�text�" #data <body><!> #errors (1,6): expected-doctype-but-got-start-tag (1,8): expected-dashes-or-doctype #new-errors (1:9) incorrectly-opened-comment (1:9) unexpected-null-character #document | <html> | <head> | <body> | <!-- � --> #data <body><!fillertext> #errors (1,6): expected-doctype-but-got-start-tag (1,8): expected-dashes-or-doctype #new-errors (1:9) incorrectly-opened-comment (1:9) unexpected-null-character (1:16) unexpected-null-character #document | <html> | <head> | <body> | <!-- �filler�text --> #data <body><svg><foreignObject>fillertext #errors (1,6): expected-doctype-but-got-start-tag (1,27): invalid-codepoint (1,27): invalid-codepoint-in-body (1,34): invalid-codepoint (1,34): invalid-codepoint-in-body (1,38): expected-closing-tag-but-got-eof #new-errors (1:27) unexpected-null-character (1:34) unexpected-null-character #document | <html> | <head> | <body> | <svg svg> | <svg foreignObject> | "fillertext" #data <svg>fillertext #errors (1,5): expected-doctype-but-got-start-tag (1,6): invalid-codepoint (1,6): invalid-codepoint-in-foreign-content (1,13): invalid-codepoint (1,13): invalid-codepoint-in-foreign-content (1,17): expected-closing-tag-but-got-eof #new-errors (1:6) unexpected-null-character (1:13) unexpected-null-character #document | <html> | <head> | <body> | <svg svg> | "�filler�text" #data <svg><frameset> #errors (1,5): expected-doctype-but-got-start-tag (1,6): invalid-codepoint (1,6): invalid-codepoint-in-foreign-content (1,16): expected-closing-tag-but-got-eof #new-errors (1:6) unexpected-null-character #document | <html> | <head> | <body> | <svg svg> | "�" | <svg frameset> #data <svg> <frameset> #errors (1,5): expected-doctype-but-got-start-tag (1,6): invalid-codepoint (1,6): invalid-codepoint-in-foreign-content (1,17): expected-closing-tag-but-got-eof #new-errors (1:6) unexpected-null-character #document | <html> | <head> | <body> | <svg svg> | "� " | <svg frameset> #data <svg>a<frameset> #errors (1,5): expected-doctype-but-got-start-tag (1,6): invalid-codepoint (1,6): invalid-codepoint-in-foreign-content (1,17): expected-closing-tag-but-got-eof #new-errors (1:6) unexpected-null-character #document | <html> | <head> | <body> | <svg svg> | "�a" | <svg frameset> #data <svg></svg><frameset> #errors (1,5): expected-doctype-but-got-start-tag (1,6): invalid-codepoint (1,6): invalid-codepoint-in-foreign-content (1,22): unexpected-start-tag (1,22): eof-in-frameset #new-errors (1:6) unexpected-null-character #document | <html> | <head> | <frameset> #data <svg> </svg><frameset> #errors (1,5): expected-doctype-but-got-start-tag (1,6): invalid-codepoint (1,6): invalid-codepoint-in-foreign-content (1,23): unexpected-start-tag (1,23): eof-in-frameset #new-errors (1:6) unexpected-null-character #document | <html> | <head> | <frameset> #data <svg>a</svg><frameset> #errors (1,5): expected-doctype-but-got-start-tag (1,6): invalid-codepoint (1,6): invalid-codepoint-in-foreign-content (1,23): unexpected-start-tag #new-errors (1:6) unexpected-null-character #document | <html> | <head> | <body> | <svg svg> | "�a" #data <svg><path></path></svg><frameset> #errors (1,5): expected-doctype-but-got-start-tag (1,34): unexpected-start-tag (1,34): eof-in-frameset #document | <html> | <head> | <frameset> #data <svg><p><frameset> #errors (1, 5) expected-doctype-but-got-start-tag (1, 8) unexpected-html-element-in-foreign-content (1, 18) unexpected-start-tag (1, 18) eof-in-frameset #document | <html> | <head> | <frameset> #data <!DOCTYPE html><pre> A</pre> #errors #document | <!DOCTYPE html> | <html> | <head> | <body> | <pre> | " A" #data <!DOCTYPE html><pre> A</pre> #errors #document | <!DOCTYPE html> | <html> | <head> | <body> | <pre> | " A" #data <!DOCTYPE html><pre> A</pre> #errors #document | <!DOCTYPE html> | <html> | <head> | <body> | <pre> | "A" #data <!DOCTYPE html><table><tr><td><math><mtext>a #errors (1,44): invalid-codepoint (1,44): invalid-codepoint-in-body (1,45): expected-closing-tag-but-got-eof #new-errors (1:44) unexpected-null-character #document | <!DOCTYPE html> | <html> | <head> | <body> | <table> | <tbody> | <tr> | <td> | <math math> | <math mtext> | "a" #data <!DOCTYPE html><table><tr><td><svg><foreignObject>a #errors (1,51): invalid-codepoint (1,51): invalid-codepoint-in-body (1,52): expected-closing-tag-but-got-eof #new-errors (1:51) unexpected-null-character #document | <!DOCTYPE html> | <html> | <head> | <body> | <table> | <tbody> | <tr> | <td> | <svg svg> | <svg foreignObject> | "a" #data <!DOCTYPE html><math><mi>ab #errors (1,27): invalid-codepoint (1,27): invalid-codepoint-in-body (1,28): expected-closing-tag-but-got-eof #new-errors (1:27) unexpected-null-character #document | <!DOCTYPE html> | <html> | <head> | <body> | <math math> | <math mi> | "ab" #data <!DOCTYPE html><math><mo>ab #errors (1,27): invalid-codepoint (1,27): invalid-codepoint-in-body (1,28): expected-closing-tag-but-got-eof #new-errors (1:27) unexpected-null-character #document | <!DOCTYPE html> | <html> | <head> | <body> | <math math> | <math mo> | "ab" #data <!DOCTYPE html><math><mn>ab #errors (1,27): invalid-codepoint (1,27): invalid-codepoint-in-body (1,28): expected-closing-tag-but-got-eof #new-errors (1:27) unexpected-null-character #document | <!DOCTYPE html> | <html> | <head> | <body> | <math math> | <math mn> | "ab" #data <!DOCTYPE html><math><ms>ab #errors (1,27): invalid-codepoint (1,27): invalid-codepoint-in-body (1,28): expected-closing-tag-but-got-eof #new-errors (1:27) unexpected-null-character #document | <!DOCTYPE html> | <html> | <head> | <body> | <math math> | <math ms> | "ab" #data <!DOCTYPE html><math><mtext>ab #errors (1,30): invalid-codepoint (1,30): invalid-codepoint-in-body (1,31): expected-closing-tag-but-got-eof #new-errors (1:30) unexpected-null-character #document | <!DOCTYPE html> | <html> | <head> | <body> | <math math> | <math mtext> | "ab"
net/html/testdata/webkit/plain-text-unsafe.dat/0
{ "file_path": "net/html/testdata/webkit/plain-text-unsafe.dat", "repo_id": "net", "token_count": 4500 }
612
#data <!doctype html><table><tbody><select><tr> #errors (1,37): unexpected-start-tag-implies-table-voodoo (1,41): unexpected-table-element-start-tag-in-select-in-table (1,41): eof-in-table #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> | <table> | <tbody> | <tr> #data <!doctype html><table><tr><select><td> #errors (1,34): unexpected-start-tag-implies-table-voodoo (1,38): unexpected-table-element-start-tag-in-select-in-table (1,38): expected-closing-tag-but-got-eof #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> | <table> | <tbody> | <tr> | <td> #data <!doctype html><table><tr><td><select><td> #errors (1,42): unexpected-table-element-start-tag-in-select-in-table (1,42): expected-closing-tag-but-got-eof #document | <!DOCTYPE html> | <html> | <head> | <body> | <table> | <tbody> | <tr> | <td> | <select> | <td> #data <!doctype html><table><tr><th><select><td> #errors (1,42): unexpected-table-element-start-tag-in-select-in-table (1,42): expected-closing-tag-but-got-eof #document | <!DOCTYPE html> | <html> | <head> | <body> | <table> | <tbody> | <tr> | <th> | <select> | <td> #data <!doctype html><table><caption><select><tr> #errors (1,43): unexpected-table-element-start-tag-in-select-in-table (1,43): eof-in-table #document | <!DOCTYPE html> | <html> | <head> | <body> | <table> | <caption> | <select> | <tbody> | <tr> #data <!doctype html><select><tr> #errors (1,27): unexpected-start-tag-in-select (1,27): eof-in-select #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> #data <!doctype html><select><td> #errors (1,27): unexpected-start-tag-in-select (1,27): eof-in-select #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> #data <!doctype html><select><th> #errors (1,27): unexpected-start-tag-in-select (1,27): eof-in-select #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> #data <!doctype html><select><tbody> #errors (1,30): unexpected-start-tag-in-select (1,30): eof-in-select #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> #data <!doctype html><select><thead> #errors (1,30): unexpected-start-tag-in-select (1,30): eof-in-select #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> #data <!doctype html><select><tfoot> #errors (1,30): unexpected-start-tag-in-select (1,30): eof-in-select #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> #data <!doctype html><select><caption> #errors (1,32): unexpected-start-tag-in-select (1,32): eof-in-select #document | <!DOCTYPE html> | <html> | <head> | <body> | <select> #data <!doctype html><table><tr></table>a #errors #document | <!DOCTYPE html> | <html> | <head> | <body> | <table> | <tbody> | <tr> | "a"
net/html/testdata/webkit/tests17.dat/0
{ "file_path": "net/html/testdata/webkit/tests17.dat", "repo_id": "net", "token_count": 1546 }
613
#data <div> <div></div> </span>x #errors (1,5): expected-doctype-but-got-start-tag (3,7): unexpected-end-tag (3,8): expected-closing-tag-but-got-eof #document | <html> | <head> | <body> | <div> | " " | <div> | " x" #data <div>x<div></div> </span>x #errors (1,5): expected-doctype-but-got-start-tag (2,7): unexpected-end-tag (2,8): expected-closing-tag-but-got-eof #document | <html> | <head> | <body> | <div> | "x" | <div> | " x" #data <div>x<div></div>x</span>x #errors (1,5): expected-doctype-but-got-start-tag (1,25): unexpected-end-tag (1,26): expected-closing-tag-but-got-eof #document | <html> | <head> | <body> | <div> | "x" | <div> | "xx" #data <div>x<div></div>y</span>z #errors (1,5): expected-doctype-but-got-start-tag (1,25): unexpected-end-tag (1,26): expected-closing-tag-but-got-eof #document | <html> | <head> | <body> | <div> | "x" | <div> | "yz" #data <table><div>x<div></div>x</span>x #errors (1,7): expected-doctype-but-got-start-tag (1,12): foster-parenting-start-tag (1,13): foster-parenting-character (1,18): foster-parenting-start-tag (1,24): foster-parenting-end-tag (1,25): foster-parenting-start-tag (1,32): foster-parenting-end-tag (1,32): unexpected-end-tag (1,33): foster-parenting-character (1,33): eof-in-table #document | <html> | <head> | <body> | <div> | "x" | <div> | "xx" | <table> #data <table><li><li></table> #errors #document | <html> | <head> | <body> | <li> | <li> | <table> #data x<table>x #errors (1,1): expected-doctype-but-got-chars (1,9): foster-parenting-character (1,9): eof-in-table #document | <html> | <head> | <body> | "xx" | <table> #data x<table><table>x #errors (1,1): expected-doctype-but-got-chars (1,15): unexpected-start-tag-implies-end-tag (1,16): foster-parenting-character (1,16): eof-in-table #document | <html> | <head> | <body> | "x" | <table> | "x" | <table> #data <b>a<div></div><div></b>y #errors (1,3): expected-doctype-but-got-start-tag (1,24): adoption-agency-1.3 (1,25): expected-closing-tag-but-got-eof #document | <html> | <head> | <body> | <b> | "a" | <div> | <div> | <b> | "y" #data <a><div><p></a> #errors (1,3): expected-doctype-but-got-start-tag (1,15): adoption-agency-1.3 (1,15): adoption-agency-1.3 (1,15): expected-closing-tag-but-got-eof #document | <html> | <head> | <body> | <a> | <div> | <a> | <p> | <a>
net/html/testdata/webkit/tests8.dat/0
{ "file_path": "net/html/testdata/webkit/tests8.dat", "repo_id": "net", "token_count": 1381 }
614
// 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 http2 import "strings" // The HTTP protocols are defined in terms of ASCII, not Unicode. This file // contains helper functions which may use Unicode-aware functions which would // otherwise be unsafe and could introduce vulnerabilities if used improperly. // asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t // are equal, ASCII-case-insensitively. func asciiEqualFold(s, t string) bool { if len(s) != len(t) { return false } for i := 0; i < len(s); i++ { if lower(s[i]) != lower(t[i]) { return false } } return true } // lower returns the ASCII lowercase version of b. func lower(b byte) byte { if 'A' <= b && b <= 'Z' { return b + ('a' - 'A') } return b } // isASCIIPrint returns whether s is ASCII and printable according to // https://tools.ietf.org/html/rfc20#section-4.2. func isASCIIPrint(s string) bool { for i := 0; i < len(s); i++ { if s[i] < ' ' || s[i] > '~' { return false } } return true } // asciiToLower returns the lowercase version of s if s is ASCII and printable, // and whether or not it was. func asciiToLower(s string) (lower string, ok bool) { if !isASCIIPrint(s) { return "", false } return strings.ToLower(s), true }
net/http2/ascii.go/0
{ "file_path": "net/http2/ascii.go", "repo_id": "net", "token_count": 480 }
615
// 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. // Defensive debug-only utility to track that functions run on the // goroutine that they're supposed to. package http2 import ( "bytes" "errors" "fmt" "os" "runtime" "strconv" "sync" ) var DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1" type goroutineLock uint64 func newGoroutineLock() goroutineLock { if !DebugGoroutines { return 0 } return goroutineLock(curGoroutineID()) } func (g goroutineLock) check() { if !DebugGoroutines { return } if curGoroutineID() != uint64(g) { panic("running on the wrong goroutine") } } func (g goroutineLock) checkNotOn() { if !DebugGoroutines { return } if curGoroutineID() == uint64(g) { panic("running on the wrong goroutine") } } var goroutineSpace = []byte("goroutine ") func curGoroutineID() uint64 { bp := littleBuf.Get().(*[]byte) defer littleBuf.Put(bp) b := *bp b = b[:runtime.Stack(b, false)] // Parse the 4707 out of "goroutine 4707 [" b = bytes.TrimPrefix(b, goroutineSpace) i := bytes.IndexByte(b, ' ') if i < 0 { panic(fmt.Sprintf("No space found in %q", b)) } b = b[:i] n, err := parseUintBytes(b, 10, 64) if err != nil { panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) } return n } var littleBuf = sync.Pool{ New: func() interface{} { buf := make([]byte, 64) return &buf }, } // parseUintBytes is like strconv.ParseUint, but using a []byte. func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { var cutoff, maxVal uint64 if bitSize == 0 { bitSize = int(strconv.IntSize) } s0 := s switch { case len(s) < 1: err = strconv.ErrSyntax goto Error case 2 <= base && base <= 36: // valid base; nothing to do case base == 0: // Look for octal, hex prefix. switch { case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): base = 16 s = s[2:] if len(s) < 1 { err = strconv.ErrSyntax goto Error } case s[0] == '0': base = 8 default: base = 10 } default: err = errors.New("invalid base " + strconv.Itoa(base)) goto Error } n = 0 cutoff = cutoff64(base) maxVal = 1<<uint(bitSize) - 1 for i := 0; i < len(s); i++ { var v byte d := s[i] switch { case '0' <= d && d <= '9': v = d - '0' case 'a' <= d && d <= 'z': v = d - 'a' + 10 case 'A' <= d && d <= 'Z': v = d - 'A' + 10 default: n = 0 err = strconv.ErrSyntax goto Error } if int(v) >= base { n = 0 err = strconv.ErrSyntax goto Error } if n >= cutoff { // n*base overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n *= uint64(base) n1 := n + uint64(v) if n1 < n || n1 > maxVal { // n+v overflows n = 1<<64 - 1 err = strconv.ErrRange goto Error } n = n1 } return n, nil Error: return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} } // Return the first number n such that n*base >= 1<<64. func cutoff64(base int) uint64 { if base < 2 { return 0 } return (1<<64-1)/uint64(base) + 1 }
net/http2/gotrack.go/0
{ "file_path": "net/http2/gotrack.go", "repo_id": "net", "token_count": 1397 }
616
// 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 http2 implements the HTTP/2 protocol. // // This package is low-level and intended to be used directly by very // few people. Most users will use it indirectly through the automatic // use by the net/http package (from Go 1.6 and later). // For use in earlier Go versions see ConfigureServer. (Transport support // requires Go 1.6 or later) // // See https://http2.github.io/ for more information on HTTP/2. // // See https://http2.golang.org/ for a test server running this code. package http2 // import "golang.org/x/net/http2" import ( "bufio" "context" "crypto/tls" "fmt" "io" "net/http" "os" "sort" "strconv" "strings" "sync" "time" "golang.org/x/net/http/httpguts" ) var ( VerboseLogs bool logFrameWrites bool logFrameReads bool inTests bool ) func init() { e := os.Getenv("GODEBUG") if strings.Contains(e, "http2debug=1") { VerboseLogs = true } if strings.Contains(e, "http2debug=2") { VerboseLogs = true logFrameWrites = true logFrameReads = true } } const ( // ClientPreface is the string that must be sent by new // connections from clients. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" // SETTINGS_MAX_FRAME_SIZE default // https://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2 initialMaxFrameSize = 16384 // NextProtoTLS is the NPN/ALPN protocol negotiated during // HTTP/2's TLS setup. NextProtoTLS = "h2" // https://httpwg.org/specs/rfc7540.html#SettingValues initialHeaderTableSize = 4096 initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size defaultMaxReadFrameSize = 1 << 20 ) var ( clientPreface = []byte(ClientPreface) ) type streamState int // HTTP/2 stream states. // // See http://tools.ietf.org/html/rfc7540#section-5.1. // // For simplicity, the server code merges "reserved (local)" into // "half-closed (remote)". This is one less state transition to track. // The only downside is that we send PUSH_PROMISEs slightly less // liberally than allowable. More discussion here: // https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html // // "reserved (remote)" is omitted since the client code does not // support server push. const ( stateIdle streamState = iota stateOpen stateHalfClosedLocal stateHalfClosedRemote stateClosed ) var stateName = [...]string{ stateIdle: "Idle", stateOpen: "Open", stateHalfClosedLocal: "HalfClosedLocal", stateHalfClosedRemote: "HalfClosedRemote", stateClosed: "Closed", } func (st streamState) String() string { return stateName[st] } // Setting is a setting parameter: which setting it is, and its value. type Setting struct { // ID is which setting is being set. // See https://httpwg.org/specs/rfc7540.html#SettingFormat ID SettingID // Val is the value. Val uint32 } func (s Setting) String() string { return fmt.Sprintf("[%v = %d]", s.ID, s.Val) } // Valid reports whether the setting is valid. func (s Setting) Valid() error { // Limits and error codes from 6.5.2 Defined SETTINGS Parameters switch s.ID { case SettingEnablePush: if s.Val != 1 && s.Val != 0 { return ConnectionError(ErrCodeProtocol) } case SettingInitialWindowSize: if s.Val > 1<<31-1 { return ConnectionError(ErrCodeFlowControl) } case SettingMaxFrameSize: if s.Val < 16384 || s.Val > 1<<24-1 { return ConnectionError(ErrCodeProtocol) } } return nil } // A SettingID is an HTTP/2 setting as defined in // https://httpwg.org/specs/rfc7540.html#iana-settings type SettingID uint16 const ( SettingHeaderTableSize SettingID = 0x1 SettingEnablePush SettingID = 0x2 SettingMaxConcurrentStreams SettingID = 0x3 SettingInitialWindowSize SettingID = 0x4 SettingMaxFrameSize SettingID = 0x5 SettingMaxHeaderListSize SettingID = 0x6 ) var settingName = map[SettingID]string{ SettingHeaderTableSize: "HEADER_TABLE_SIZE", SettingEnablePush: "ENABLE_PUSH", SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS", SettingInitialWindowSize: "INITIAL_WINDOW_SIZE", SettingMaxFrameSize: "MAX_FRAME_SIZE", SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE", } func (s SettingID) String() string { if v, ok := settingName[s]; ok { return v } return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s)) } // validWireHeaderFieldName reports whether v is a valid header field // name (key). See httpguts.ValidHeaderName for the base rules. // // Further, http2 says: // // "Just as in HTTP/1.x, header field names are strings of ASCII // characters that are compared in a case-insensitive // fashion. However, header field names MUST be converted to // lowercase prior to their encoding in HTTP/2. " func validWireHeaderFieldName(v string) bool { if len(v) == 0 { return false } for _, r := range v { if !httpguts.IsTokenRune(r) { return false } if 'A' <= r && r <= 'Z' { return false } } return true } func httpCodeString(code int) string { switch code { case 200: return "200" case 404: return "404" } return strconv.Itoa(code) } // from pkg io type stringWriter interface { WriteString(s string) (n int, err error) } // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed). type closeWaiter chan struct{} // Init makes a closeWaiter usable. // It exists because so a closeWaiter value can be placed inside a // larger struct and have the Mutex and Cond's memory in the same // allocation. func (cw *closeWaiter) Init() { *cw = make(chan struct{}) } // Close marks the closeWaiter as closed and unblocks any waiters. func (cw closeWaiter) Close() { close(cw) } // Wait waits for the closeWaiter to become closed. func (cw closeWaiter) Wait() { <-cw } // bufferedWriter is a buffered writer that writes to w. // Its buffered writer is lazily allocated as needed, to minimize // idle memory usage with many connections. type bufferedWriter struct { _ incomparable w io.Writer // immutable bw *bufio.Writer // non-nil when data is buffered } func newBufferedWriter(w io.Writer) *bufferedWriter { return &bufferedWriter{w: w} } // bufWriterPoolBufferSize is the size of bufio.Writer's // buffers created using bufWriterPool. // // TODO: pick a less arbitrary value? this is a bit under // (3 x typical 1500 byte MTU) at least. Other than that, // not much thought went into it. const bufWriterPoolBufferSize = 4 << 10 var bufWriterPool = sync.Pool{ New: func() interface{} { return bufio.NewWriterSize(nil, bufWriterPoolBufferSize) }, } func (w *bufferedWriter) Available() int { if w.bw == nil { return bufWriterPoolBufferSize } return w.bw.Available() } func (w *bufferedWriter) Write(p []byte) (n int, err error) { if w.bw == nil { bw := bufWriterPool.Get().(*bufio.Writer) bw.Reset(w.w) w.bw = bw } return w.bw.Write(p) } func (w *bufferedWriter) Flush() error { bw := w.bw if bw == nil { return nil } err := bw.Flush() bw.Reset(nil) bufWriterPool.Put(bw) w.bw = nil return err } func mustUint31(v int32) uint32 { if v < 0 || v > 2147483647 { panic("out of range") } return uint32(v) } // bodyAllowedForStatus reports whether a given response status code // permits a body. See RFC 7230, section 3.3. func bodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: return false case status == 204: return false case status == 304: return false } return true } type httpError struct { _ incomparable msg string timeout bool } func (e *httpError) Error() string { return e.msg } func (e *httpError) Timeout() bool { return e.timeout } func (e *httpError) Temporary() bool { return true } var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true} type connectionStater interface { ConnectionState() tls.ConnectionState } var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }} type sorter struct { v []string // owned by sorter } func (s *sorter) Len() int { return len(s.v) } func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] } func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] } // Keys returns the sorted keys of h. // // The returned slice is only valid until s used again or returned to // its pool. func (s *sorter) Keys(h http.Header) []string { keys := s.v[:0] for k := range h { keys = append(keys, k) } s.v = keys sort.Sort(s) return keys } func (s *sorter) SortStrings(ss []string) { // Our sorter works on s.v, which sorter owns, so // stash it away while we sort the user's buffer. save := s.v s.v = ss sort.Sort(s) s.v = save } // validPseudoPath reports whether v is a valid :path pseudo-header // value. It must be either: // // - a non-empty string starting with '/' // - the string '*', for OPTIONS requests. // // For now this is only used a quick check for deciding when to clean // up Opaque URLs before sending requests from the Transport. // See golang.org/issue/16847 // // We used to enforce that the path also didn't start with "//", but // Google's GFE accepts such paths and Chrome sends them, so ignore // that part of the spec. See golang.org/issue/19103. func validPseudoPath(v string) bool { return (len(v) > 0 && v[0] == '/') || v == "*" } // incomparable is a zero-width, non-comparable type. Adding it to a struct // makes that struct also non-comparable, and generally doesn't add // any size (as long as it's first). type incomparable [0]func() // synctestGroupInterface is the methods of synctestGroup used by Server and Transport. // It's defined as an interface here to let us keep synctestGroup entirely test-only // and not a part of non-test builds. type synctestGroupInterface interface { Join() Now() time.Time NewTimer(d time.Duration) timer AfterFunc(d time.Duration, f func()) timer ContextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) }
net/http2/http2.go/0
{ "file_path": "net/http2/http2.go", "repo_id": "net", "token_count": 3611 }
617
// 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 http2 import "math" // NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2 // priorities. Control frames like SETTINGS and PING are written before DATA // frames, but if no control frames are queued and multiple streams have queued // HEADERS or DATA frames, Pop selects a ready stream arbitrarily. func NewRandomWriteScheduler() WriteScheduler { return &randomWriteScheduler{sq: make(map[uint32]*writeQueue)} } type randomWriteScheduler struct { // zero are frames not associated with a specific stream. zero writeQueue // sq contains the stream-specific queues, keyed by stream ID. // When a stream is idle, closed, or emptied, it's deleted // from the map. sq map[uint32]*writeQueue // pool of empty queues for reuse. queuePool writeQueuePool } func (ws *randomWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { // no-op: idle streams are not tracked } func (ws *randomWriteScheduler) CloseStream(streamID uint32) { q, ok := ws.sq[streamID] if !ok { return } delete(ws.sq, streamID) ws.queuePool.put(q) } func (ws *randomWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { // no-op: priorities are ignored } func (ws *randomWriteScheduler) Push(wr FrameWriteRequest) { if wr.isControl() { ws.zero.push(wr) return } id := wr.StreamID() q, ok := ws.sq[id] if !ok { q = ws.queuePool.get() ws.sq[id] = q } q.push(wr) } func (ws *randomWriteScheduler) Pop() (FrameWriteRequest, bool) { // Control and RST_STREAM frames first. if !ws.zero.empty() { return ws.zero.shift(), true } // Iterate over all non-idle streams until finding one that can be consumed. for streamID, q := range ws.sq { if wr, ok := q.consume(math.MaxInt32); ok { if q.empty() { delete(ws.sq, streamID) ws.queuePool.put(q) } return wr, true } } return FrameWriteRequest{}, false }
net/http2/writesched_random.go/0
{ "file_path": "net/http2/writesched_random.go", "repo_id": "net", "token_count": 705 }
618
// 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 icmp import ( "net" "golang.org/x/net/internal/iana" ) const ipv6PseudoHeaderLen = 2*net.IPv6len + 8 // IPv6PseudoHeader returns an IPv6 pseudo header for checksum // calculation. func IPv6PseudoHeader(src, dst net.IP) []byte { b := make([]byte, ipv6PseudoHeaderLen) copy(b, src.To16()) copy(b[net.IPv6len:], dst.To16()) b[len(b)-1] = byte(iana.ProtocolIPv6ICMP) return b }
net/icmp/ipv6.go/0
{ "file_path": "net/icmp/ipv6.go", "repo_id": "net", "token_count": 213 }
619
// 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. //go:build ignore //go:generate go run gen.go // This program generates internet protocol constants and tables by // reading IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "net/http" "os" "strconv" "strings" ) var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "https://www.iana.org/assignments/dscp-registry/dscp-registry.xml", parseDSCPRegistry, }, { "https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml", parseProtocolNumbers, }, { "https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xml", parseAddrFamilyNumbers, }, } func main() { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// Code generated by the command above; DO NOT EDIT.\n\n") fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n") fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"`+"\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url) os.Exit(1) } if err := r.parse(&bb, resp.Body); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := os.WriteFile("const.go", b, 0644); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func parseDSCPRegistry(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var dr dscpRegistry if err := dec.Decode(&dr); err != nil { return err } fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated) fmt.Fprintf(w, "const (\n") for _, dr := range dr.escapeDSCP() { fmt.Fprintf(w, "DiffServ%s = %#02x", dr.Name, dr.Value) fmt.Fprintf(w, "// %s\n", dr.OrigName) } for _, er := range dr.escapeECN() { fmt.Fprintf(w, "%s = %#02x", er.Descr, er.Value) fmt.Fprintf(w, "// %s\n", er.OrigDescr) } fmt.Fprintf(w, ")\n") return nil } type dscpRegistry struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Note string `xml:"note"` Registries []struct { Title string `xml:"title"` Registries []struct { Title string `xml:"title"` Records []struct { Name string `xml:"name"` Space string `xml:"space"` } `xml:"record"` } `xml:"registry"` Records []struct { Value string `xml:"value"` Descr string `xml:"description"` } `xml:"record"` } `xml:"registry"` } type canonDSCPRecord struct { OrigName string Name string Value int } func (drr *dscpRegistry) escapeDSCP() []canonDSCPRecord { var drs []canonDSCPRecord for _, preg := range drr.Registries { if !strings.Contains(preg.Title, "Differentiated Services Field Codepoints") { continue } for _, reg := range preg.Registries { if !strings.Contains(reg.Title, "Pool 1 Codepoints") { continue } drs = make([]canonDSCPRecord, len(reg.Records)) sr := strings.NewReplacer( "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, dr := range reg.Records { s := strings.TrimSpace(dr.Name) drs[i].OrigName = s drs[i].Name = sr.Replace(s) n, err := strconv.ParseUint(dr.Space, 2, 8) if err != nil { continue } drs[i].Value = int(n) << 2 } } } return drs } type canonECNRecord struct { OrigDescr string Descr string Value int } func (drr *dscpRegistry) escapeECN() []canonECNRecord { var ers []canonECNRecord for _, reg := range drr.Registries { if !strings.Contains(reg.Title, "ECN Field") { continue } ers = make([]canonECNRecord, len(reg.Records)) sr := strings.NewReplacer( "Capable", "", "Not-ECT", "", "ECT(1)", "", "ECT(0)", "", "CE", "", "(", "", ")", "", "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, er := range reg.Records { s := strings.TrimSpace(er.Descr) ers[i].OrigDescr = s ss := strings.Split(s, " ") if len(ss) > 1 { ers[i].Descr = strings.Join(ss[1:], " ") } else { ers[i].Descr = ss[0] } ers[i].Descr = sr.Replace(er.Descr) n, err := strconv.ParseUint(er.Value, 2, 8) if err != nil { continue } ers[i].Value = int(n) } } return ers } func parseProtocolNumbers(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var pn protocolNumbers if err := dec.Decode(&pn); err != nil { return err } prs := pn.escape() prs = append([]canonProtocolRecord{{ Name: "IP", Descr: "IPv4 encapsulation, pseudo protocol number", Value: 0, }}, prs...) fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value) s := pr.Descr if s == "" { s = pr.OrigName } fmt.Fprintf(w, "// %s\n", s) } fmt.Fprintf(w, ")\n") return nil } type protocolNumbers struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` RegTitle string `xml:"registry>title"` Note string `xml:"registry>note"` Records []struct { Value string `xml:"value"` Name string `xml:"name"` Descr string `xml:"description"` } `xml:"registry>record"` } type canonProtocolRecord struct { OrigName string Name string Descr string Value int } func (pn *protocolNumbers) escape() []canonProtocolRecord { prs := make([]canonProtocolRecord, len(pn.Records)) sr := strings.NewReplacer( "-in-", "in", "-within-", "within", "-over-", "over", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range pn.Records { if strings.Contains(pr.Name, "Deprecated") || strings.Contains(pr.Name, "deprecated") { continue } prs[i].OrigName = pr.Name s := strings.TrimSpace(pr.Name) switch pr.Name { case "ISIS over IPv4": prs[i].Name = "ISIS" case "manet": prs[i].Name = "MANET" default: prs[i].Name = sr.Replace(s) } ss := strings.Split(pr.Descr, "\n") for i := range ss { ss[i] = strings.TrimSpace(ss[i]) } if len(ss) > 1 { prs[i].Descr = strings.Join(ss, " ") } else { prs[i].Descr = ss[0] } prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs } func parseAddrFamilyNumbers(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var afn addrFamilylNumbers if err := dec.Decode(&afn); err != nil { return err } afrs := afn.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", afn.Title, afn.Updated) fmt.Fprintf(w, "const (\n") for _, afr := range afrs { if afr.Name == "" { continue } fmt.Fprintf(w, "AddrFamily%s = %d", afr.Name, afr.Value) fmt.Fprintf(w, "// %s\n", afr.Descr) } fmt.Fprintf(w, ")\n") return nil } type addrFamilylNumbers struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` RegTitle string `xml:"registry>title"` Note string `xml:"registry>note"` Records []struct { Value string `xml:"value"` Descr string `xml:"description"` } `xml:"registry>record"` } type canonAddrFamilyRecord struct { Name string Descr string Value int } func (afn *addrFamilylNumbers) escape() []canonAddrFamilyRecord { afrs := make([]canonAddrFamilyRecord, len(afn.Records)) sr := strings.NewReplacer( "IP version 4", "IPv4", "IP version 6", "IPv6", "Identifier", "ID", "-", "", "-", "", "/", "", ".", "", " ", "", ) for i, afr := range afn.Records { if strings.Contains(afr.Descr, "Unassigned") || strings.Contains(afr.Descr, "Reserved") { continue } afrs[i].Descr = afr.Descr s := strings.TrimSpace(afr.Descr) switch s { case "IP (IP version 4)": afrs[i].Name = "IPv4" case "IP6 (IP version 6)": afrs[i].Name = "IPv6" case "AFI for L2VPN information": afrs[i].Name = "L2VPN" case "E.164 with NSAP format subaddress": afrs[i].Name = "E164withSubaddress" case "MT IP: Multi-Topology IP version 4": afrs[i].Name = "MTIPv4" case "MAC/24": afrs[i].Name = "MACFinal24bits" case "MAC/40": afrs[i].Name = "MACFinal40bits" case "IPv6/64": afrs[i].Name = "IPv6Initial64bits" default: n := strings.Index(s, "(") if n > 0 { s = s[:n] } n = strings.Index(s, ":") if n > 0 { s = s[:n] } afrs[i].Name = sr.Replace(s) } afrs[i].Value, _ = strconv.Atoi(afr.Value) } return afrs }
net/internal/iana/gen.go/0
{ "file_path": "net/internal/iana/gen.go", "repo_id": "net", "token_count": 4074 }
620
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build aix || linux || netbsd package socket import ( "net" "os" "sync" "syscall" ) type mmsghdrs []mmsghdr func (hs mmsghdrs) unpack(ms []Message, parseFn func([]byte, string) (net.Addr, error), hint string) error { for i := range hs { ms[i].N = int(hs[i].Len) ms[i].NN = hs[i].Hdr.controllen() ms[i].Flags = hs[i].Hdr.flags() if parseFn != nil { var err error ms[i].Addr, err = parseFn(hs[i].Hdr.name(), hint) if err != nil { return err } } } return nil } // mmsghdrsPacker packs Message-slices into mmsghdrs (re-)using pre-allocated buffers. type mmsghdrsPacker struct { // hs are the pre-allocated mmsghdrs. hs mmsghdrs // sockaddrs is the pre-allocated buffer for the Hdr.Name buffers. // We use one large buffer for all messages and slice it up. sockaddrs []byte // vs are the pre-allocated iovecs. // We allocate one large buffer for all messages and slice it up. This allows to reuse the buffer // if the number of buffers per message is distributed differently between calls. vs []iovec } func (p *mmsghdrsPacker) prepare(ms []Message) { n := len(ms) if n <= cap(p.hs) { p.hs = p.hs[:n] } else { p.hs = make(mmsghdrs, n) } if n*sizeofSockaddrInet6 <= cap(p.sockaddrs) { p.sockaddrs = p.sockaddrs[:n*sizeofSockaddrInet6] } else { p.sockaddrs = make([]byte, n*sizeofSockaddrInet6) } nb := 0 for _, m := range ms { nb += len(m.Buffers) } if nb <= cap(p.vs) { p.vs = p.vs[:nb] } else { p.vs = make([]iovec, nb) } } func (p *mmsghdrsPacker) pack(ms []Message, parseFn func([]byte, string) (net.Addr, error), marshalFn func(net.Addr, []byte) int) mmsghdrs { p.prepare(ms) hs := p.hs vsRest := p.vs saRest := p.sockaddrs for i := range hs { nvs := len(ms[i].Buffers) vs := vsRest[:nvs] vsRest = vsRest[nvs:] var sa []byte if parseFn != nil { sa = saRest[:sizeofSockaddrInet6] saRest = saRest[sizeofSockaddrInet6:] } else if marshalFn != nil { n := marshalFn(ms[i].Addr, saRest) if n > 0 { sa = saRest[:n] saRest = saRest[n:] } } hs[i].Hdr.pack(vs, ms[i].Buffers, ms[i].OOB, sa) } return hs } // syscaller is a helper to invoke recvmmsg and sendmmsg via the RawConn.Read/Write interface. // It is reusable, to amortize the overhead of allocating a closure for the function passed to // RawConn.Read/Write. type syscaller struct { n int operr error hs mmsghdrs flags int boundRecvmmsgF func(uintptr) bool boundSendmmsgF func(uintptr) bool } func (r *syscaller) init() { r.boundRecvmmsgF = r.recvmmsgF r.boundSendmmsgF = r.sendmmsgF } func (r *syscaller) recvmmsg(c syscall.RawConn, hs mmsghdrs, flags int) (int, error) { r.n = 0 r.operr = nil r.hs = hs r.flags = flags if err := c.Read(r.boundRecvmmsgF); err != nil { return r.n, err } if r.operr != nil { return r.n, os.NewSyscallError("recvmmsg", r.operr) } return r.n, nil } func (r *syscaller) recvmmsgF(s uintptr) bool { r.n, r.operr = recvmmsg(s, r.hs, r.flags) return ioComplete(r.flags, r.operr) } func (r *syscaller) sendmmsg(c syscall.RawConn, hs mmsghdrs, flags int) (int, error) { r.n = 0 r.operr = nil r.hs = hs r.flags = flags if err := c.Write(r.boundSendmmsgF); err != nil { return r.n, err } if r.operr != nil { return r.n, os.NewSyscallError("sendmmsg", r.operr) } return r.n, nil } func (r *syscaller) sendmmsgF(s uintptr) bool { r.n, r.operr = sendmmsg(s, r.hs, r.flags) return ioComplete(r.flags, r.operr) } // mmsgTmps holds reusable temporary helpers for recvmmsg and sendmmsg. type mmsgTmps struct { packer mmsghdrsPacker syscaller syscaller } var defaultMmsgTmpsPool = mmsgTmpsPool{ p: sync.Pool{ New: func() interface{} { tmps := new(mmsgTmps) tmps.syscaller.init() return tmps }, }, } type mmsgTmpsPool struct { p sync.Pool } func (p *mmsgTmpsPool) Get() *mmsgTmps { m := p.p.Get().(*mmsgTmps) // Clear fields up to the len (not the cap) of the slice, // assuming that the previous caller only used that many elements. for i := range m.packer.sockaddrs { m.packer.sockaddrs[i] = 0 } m.packer.sockaddrs = m.packer.sockaddrs[:0] for i := range m.packer.vs { m.packer.vs[i] = iovec{} } m.packer.vs = m.packer.vs[:0] for i := range m.packer.hs { m.packer.hs[i].Len = 0 m.packer.hs[i].Hdr = msghdr{} } m.packer.hs = m.packer.hs[:0] return m } func (p *mmsgTmpsPool) Put(tmps *mmsgTmps) { p.p.Put(tmps) }
net/internal/socket/mmsghdr_unix.go/0
{ "file_path": "net/internal/socket/mmsghdr_unix.go", "repo_id": "net", "token_count": 2075 }
621
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !windows && !zos package socket func (c *Conn) recvMsg(m *Message, flags int) error { return errNotImplemented } func (c *Conn) sendMsg(m *Message, flags int) error { return errNotImplemented }
net/internal/socket/rawconn_nomsg.go/0
{ "file_path": "net/internal/socket/rawconn_nomsg.go", "repo_id": "net", "token_count": 151 }
622
// 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. package ipv4_test import ( "net" "runtime" "testing" "golang.org/x/net/ipv4" "golang.org/x/net/nettest" ) var udpMultipleGroupListenerTests = []net.Addr{ &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}, // see RFC 4727 &net.UDPAddr{IP: net.IPv4(224, 0, 0, 250)}, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 254)}, } func TestUDPSinglePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "fuchsia", "hurd", "js", "nacl", "plan9", "wasip1", "windows", "zos": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } for _, gaddr := range udpMultipleGroupListenerTests { c, err := net.ListenPacket("udp4", "0.0.0.0:0") // wildcard address with no reusable port if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, err := nettest.MulticastSource("ip4", &ifi); err != nil { continue } if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "fuchsia", "hurd", "js", "nacl", "plan9", "wasip1", "windows", "zos": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } for _, gaddr := range udpMultipleGroupListenerTests { c1, err := net.ListenPacket("udp4", "224.0.0.0:0") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c1.Close() _, port, err := net.SplitHostPort(c1.LocalAddr().String()) if err != nil { t.Fatal(err) } c2, err := net.ListenPacket("udp4", net.JoinHostPort("224.0.0.0", port)) // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c2.Close() var ps [2]*ipv4.PacketConn ps[0] = ipv4.NewPacketConn(c1) ps[1] = ipv4.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, err := nettest.MulticastSource("ip4", &ifi); err != nil { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } } func TestUDPPerInterfaceSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "fuchsia", "hurd", "js", "nacl", "plan9", "wasip1", "windows", "zos": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 type ml struct { c *ipv4.PacketConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } port := "0" for i, ifi := range ift { ip, err := nettest.MulticastSource("ip4", &ifi) if err != nil { continue } c, err := net.ListenPacket("udp4", net.JoinHostPort(ip.String(), port)) // unicast address with non-reusable port if err != nil { // The listen may fail when the service is // already in use, but it's fine because the // purpose of this is not to test the // bookkeeping of IP control block inside the // kernel. t.Log(err) continue } defer c.Close() if port == "0" { _, port, err = net.SplitHostPort(c.LocalAddr().String()) if err != nil { t.Fatal(err) } } p := ipv4.NewPacketConn(c) if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{p, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPSingleRawConnWithSingleGroupListener(t *testing.T) { if testing.Short() { t.Skip("to avoid external network") } if !nettest.SupportsRawSocket() { t.Skipf("not supported on %s/%s", runtime.GOOS, runtime.GOARCH) } c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") // wildcard address if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, err := nettest.MulticastSource("ip4", &ifi); err != nil { continue } if err := r.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := r.LeaveGroup(ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPPerInterfaceSingleRawConnWithSingleGroupListener(t *testing.T) { if testing.Short() { t.Skip("to avoid external network") } if !nettest.SupportsRawSocket() { t.Skipf("not supported on %s/%s", runtime.GOOS, runtime.GOARCH) } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 type ml struct { c *ipv4.RawConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { ip, err := nettest.MulticastSource("ip4", &ifi) if err != nil { continue } c, err := net.ListenPacket("ip4:253", ip.String()) // unicast address if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } if err := r.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{r, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } }
net/ipv4/multicastlistener_test.go/0
{ "file_path": "net/ipv4/multicastlistener_test.go", "repo_id": "net", "token_count": 2733 }
623
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs defs_dragonfly.go package ipv4 const ( sizeofIPMreq = 0x8 ) type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ }
net/ipv4/zsys_dragonfly.go/0
{ "file_path": "net/ipv4/zsys_dragonfly.go", "repo_id": "net", "token_count": 91 }
624
// 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 ipv6 import "golang.org/x/net/internal/socket" func setControlMessage(c *socket.Conn, opt *rawOpt, cf ControlFlags, on bool) error { // TODO(mikio): implement this return errNotImplemented }
net/ipv6/control_windows.go/0
{ "file_path": "net/ipv6/control_windows.go", "repo_id": "net", "token_count": 113 }
625
// 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. //go:build ignore //go:generate go run gen.go // This program generates system adaptation constants and types, // internet protocol constants and tables by reading template files // and IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "net/http" "os" "os/exec" "runtime" "strconv" "strings" ) func main() { if err := genzsys(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := geniana(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func genzsys() error { defs := "defs_" + runtime.GOOS + ".go" f, err := os.Open(defs) if err != nil { if os.IsNotExist(err) { return nil } return err } f.Close() cmd := exec.Command("go", "tool", "cgo", "-godefs", defs) b, err := cmd.Output() if err != nil { return err } b, err = format.Source(b) if err != nil { return err } zsys := "zsys_" + runtime.GOOS + ".go" switch runtime.GOOS { case "freebsd", "linux": zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go" } if err := os.WriteFile(zsys, b, 0644); err != nil { return err } return nil } var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "https://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xml", parseICMPv6Parameters, }, } func geniana() error { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// Code generated by the command above; DO NOT EDIT.\n\n") fmt.Fprintf(&bb, "package ipv6\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url) } if err := r.parse(&bb, resp.Body); err != nil { return err } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { return err } if err := os.WriteFile("iana.go", b, 0644); err != nil { return err } return nil } func parseICMPv6Parameters(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var icp icmpv6Parameters if err := dec.Decode(&icp); err != nil { return err } prs := icp.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Name, pr.Value) fmt.Fprintf(w, "// %s\n", pr.OrigName) } fmt.Fprintf(w, ")\n\n") fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigName)) } fmt.Fprintf(w, "}\n") return nil } type icmpv6Parameters struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Registries []struct { Title string `xml:"title"` Records []struct { Value string `xml:"value"` Name string `xml:"name"` } `xml:"record"` } `xml:"registry"` } type canonICMPv6ParamRecord struct { OrigName string Name string Value int } func (icp *icmpv6Parameters) escape() []canonICMPv6ParamRecord { id := -1 for i, r := range icp.Registries { if strings.Contains(r.Title, "Type") || strings.Contains(r.Title, "type") { id = i break } } if id < 0 { return nil } prs := make([]canonICMPv6ParamRecord, len(icp.Registries[id].Records)) sr := strings.NewReplacer( "Messages", "", "Message", "", "ICMP", "", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range icp.Registries[id].Records { if strings.Contains(pr.Name, "Reserved") || strings.Contains(pr.Name, "Unassigned") || strings.Contains(pr.Name, "Deprecated") || strings.Contains(pr.Name, "Experiment") || strings.Contains(pr.Name, "experiment") { continue } ss := strings.Split(pr.Name, "\n") if len(ss) > 1 { prs[i].Name = strings.Join(ss, " ") } else { prs[i].Name = ss[0] } s := strings.TrimSpace(prs[i].Name) prs[i].OrigName = s prs[i].Name = sr.Replace(s) prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs }
net/ipv6/gen.go/0
{ "file_path": "net/ipv6/gen.go", "repo_id": "net", "token_count": 1939 }
626
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs defs_darwin.go package ipv6 const ( sizeofSockaddrStorage = 0x80 sizeofSockaddrInet6 = 0x1c sizeofInet6Pktinfo = 0x14 sizeofIPv6Mtuinfo = 0x20 sizeofIPv6Mreq = 0x14 sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPv6Filter = 0x20 ) type sockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type ipv6Mtuinfo struct { Addr sockaddrInet6 Mtu uint32 } type ipv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type icmpv6Filter struct { Filt [8]uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [128]byte } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [128]byte Pad_cgo_1 [128]byte }
net/ipv6/zsys_darwin.go/0
{ "file_path": "net/ipv6/zsys_darwin.go", "repo_id": "net", "token_count": 493 }
627
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package proxy import ( "context" "errors" "net" "reflect" "testing" ) type recordingProxy struct { addrs []string } func (r *recordingProxy) Dial(network, addr string) (net.Conn, error) { r.addrs = append(r.addrs, addr) return nil, errors.New("recordingProxy") } func TestPerHost(t *testing.T) { expectedDef := []string{ "example.com:123", "1.2.3.4:123", "[1001::]:123", } expectedBypass := []string{ "localhost:123", "zone:123", "foo.zone:123", "127.0.0.1:123", "10.1.2.3:123", "[1000::]:123", } t.Run("Dial", func(t *testing.T) { var def, bypass recordingProxy perHost := NewPerHost(&def, &bypass) perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16") for _, addr := range expectedDef { perHost.Dial("tcp", addr) } for _, addr := range expectedBypass { perHost.Dial("tcp", addr) } if !reflect.DeepEqual(expectedDef, def.addrs) { t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef) } if !reflect.DeepEqual(expectedBypass, bypass.addrs) { t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass) } }) t.Run("DialContext", func(t *testing.T) { var def, bypass recordingProxy perHost := NewPerHost(&def, &bypass) perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16") for _, addr := range expectedDef { perHost.DialContext(context.Background(), "tcp", addr) } for _, addr := range expectedBypass { perHost.DialContext(context.Background(), "tcp", addr) } if !reflect.DeepEqual(expectedDef, def.addrs) { t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef) } if !reflect.DeepEqual(expectedBypass, bypass.addrs) { t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass) } }) }
net/proxy/per_host_test.go/0
{ "file_path": "net/proxy/per_host_test.go", "repo_id": "net", "token_count": 830 }
628
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build go1.21 package quic import ( "slices" "testing" "time" ) func TestAcksDisallowDuplicate(t *testing.T) { // Don't process a packet that we've seen before. acks := ackState{} now := time.Now() receive := []packetNumber{0, 1, 2, 4, 7, 6, 9} seen := map[packetNumber]bool{} for i, pnum := range receive { acks.receive(now, appDataSpace, pnum, true) seen[pnum] = true for ppnum := packetNumber(0); ppnum < 11; ppnum++ { if got, want := acks.shouldProcess(ppnum), !seen[ppnum]; got != want { t.Fatalf("after receiving %v: acks.shouldProcess(%v) = %v, want %v", receive[:i+1], ppnum, got, want) } } } } func TestAcksDisallowDiscardedAckRanges(t *testing.T) { // Don't process a packet with a number in a discarded range. acks := ackState{} now := time.Now() for pnum := packetNumber(0); ; pnum += 2 { acks.receive(now, appDataSpace, pnum, true) send, _ := acks.acksToSend(now) for ppnum := packetNumber(0); ppnum < packetNumber(send.min()); ppnum++ { if acks.shouldProcess(ppnum) { t.Fatalf("after limiting ack ranges to %v: acks.shouldProcess(%v) (in discarded range) = true, want false", send, ppnum) } } if send.min() > 10 { break } } } func TestAcksSent(t *testing.T) { type packet struct { pnum packetNumber ackEliciting bool } for _, test := range []struct { name string space numberSpace // ackedPackets and packets are packets that we receive. // After receiving all packets in ackedPackets, we send an ack. // Then we receive the subsequent packets in packets. ackedPackets []packet packets []packet wantDelay time.Duration wantAcks rangeset[packetNumber] }{{ name: "no packets to ack", space: initialSpace, }, { name: "non-ack-eliciting packets are not acked", space: initialSpace, packets: []packet{{ pnum: 0, ackEliciting: false, }}, }, { name: "ack-eliciting Initial packets are acked immediately", space: initialSpace, packets: []packet{{ pnum: 0, ackEliciting: true, }}, wantAcks: rangeset[packetNumber]{{0, 1}}, wantDelay: 0, }, { name: "ack-eliciting Handshake packets are acked immediately", space: handshakeSpace, packets: []packet{{ pnum: 0, ackEliciting: true, }}, wantAcks: rangeset[packetNumber]{{0, 1}}, wantDelay: 0, }, { name: "ack-eliciting AppData packets are acked after max_ack_delay", space: appDataSpace, packets: []packet{{ pnum: 0, ackEliciting: true, }}, wantAcks: rangeset[packetNumber]{{0, 1}}, wantDelay: maxAckDelay - timerGranularity, }, { name: "reordered ack-eliciting packets are acked immediately", space: appDataSpace, ackedPackets: []packet{{ pnum: 1, ackEliciting: true, }}, packets: []packet{{ pnum: 0, ackEliciting: true, }}, wantAcks: rangeset[packetNumber]{{0, 2}}, wantDelay: 0, }, { name: "gaps in ack-eliciting packets are acked immediately", space: appDataSpace, packets: []packet{{ pnum: 1, ackEliciting: true, }}, wantAcks: rangeset[packetNumber]{{1, 2}}, wantDelay: 0, }, { name: "reordered non-ack-eliciting packets are not acked immediately", space: appDataSpace, ackedPackets: []packet{{ pnum: 1, ackEliciting: true, }}, packets: []packet{{ pnum: 2, ackEliciting: true, }, { pnum: 0, ackEliciting: false, }, { pnum: 4, ackEliciting: false, }}, wantAcks: rangeset[packetNumber]{{0, 3}, {4, 5}}, wantDelay: maxAckDelay - timerGranularity, }, { name: "immediate ack after two ack-eliciting packets are received", space: appDataSpace, packets: []packet{{ pnum: 0, ackEliciting: true, }, { pnum: 1, ackEliciting: true, }}, wantAcks: rangeset[packetNumber]{{0, 2}}, wantDelay: 0, }} { t.Run(test.name, func(t *testing.T) { acks := ackState{} start := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) for _, p := range test.ackedPackets { t.Logf("receive %v.%v, ack-eliciting=%v", test.space, p.pnum, p.ackEliciting) acks.receive(start, test.space, p.pnum, p.ackEliciting) } t.Logf("send an ACK frame") acks.sentAck() for _, p := range test.packets { t.Logf("receive %v.%v, ack-eliciting=%v", test.space, p.pnum, p.ackEliciting) acks.receive(start, test.space, p.pnum, p.ackEliciting) } switch { case len(test.wantAcks) == 0: // No ACK should be sent, even well after max_ack_delay. if acks.shouldSendAck(start.Add(10 * maxAckDelay)) { t.Errorf("acks.shouldSendAck(T+10*max_ack_delay) = true, want false") } case test.wantDelay > 0: // No ACK should be sent before a delay. if acks.shouldSendAck(start.Add(test.wantDelay - 1)) { t.Errorf("acks.shouldSendAck(T+%v-1ns) = true, want false", test.wantDelay) } fallthrough default: // ACK should be sent after a delay. if !acks.shouldSendAck(start.Add(test.wantDelay)) { t.Errorf("acks.shouldSendAck(T+%v) = false, want true", test.wantDelay) } } // acksToSend always reports the available packets that can be acked, // and the amount of time that has passed since the most recent acked // packet was received. for _, delay := range []time.Duration{ 0, test.wantDelay, test.wantDelay + 1, } { gotNums, gotDelay := acks.acksToSend(start.Add(delay)) wantDelay := delay if len(gotNums) == 0 { wantDelay = 0 } if !slices.Equal(gotNums, test.wantAcks) || gotDelay != wantDelay { t.Errorf("acks.acksToSend(T+%v) = %v, %v; want %v, %v", delay, gotNums, gotDelay, test.wantAcks, wantDelay) } } }) } } func TestAcksDiscardAfterAck(t *testing.T) { acks := ackState{} now := time.Now() acks.receive(now, appDataSpace, 0, true) acks.receive(now, appDataSpace, 2, true) acks.receive(now, appDataSpace, 4, true) acks.receive(now, appDataSpace, 5, true) acks.receive(now, appDataSpace, 6, true) acks.handleAck(6) // discards all ranges prior to the one containing packet 6 acks.receive(now, appDataSpace, 7, true) got, _ := acks.acksToSend(now) if len(got) != 1 { t.Errorf("acks.acksToSend contains ranges prior to last acknowledged ack; got %v, want 1 range", got) } } func TestAcksLargestSeen(t *testing.T) { acks := ackState{} now := time.Now() acks.receive(now, appDataSpace, 0, true) acks.receive(now, appDataSpace, 4, true) acks.receive(now, appDataSpace, 1, true) if got, want := acks.largestSeen(), packetNumber(4); got != want { t.Errorf("acks.largestSeen() = %v, want %v", got, want) } }
net/quic/acks_test.go/0
{ "file_path": "net/quic/acks_test.go", "repo_id": "net", "token_count": 3002 }
629
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build go1.21 package quic import ( "context" "crypto/tls" "fmt" "testing" ) // Frames may be retransmitted either when the packet containing the frame is lost, or on PTO. // lostFrameTest runs a test in both configurations. func lostFrameTest(t *testing.T, f func(t *testing.T, pto bool)) { t.Run("lost", func(t *testing.T) { f(t, false) }) t.Run("pto", func(t *testing.T) { f(t, true) }) } // triggerLossOrPTO causes the conn to declare the last sent packet lost, // or advances to the PTO timer. func (tc *testConn) triggerLossOrPTO(ptype packetType, pto bool) { tc.t.Helper() if pto { if !tc.conn.loss.ptoTimerArmed { tc.t.Fatalf("PTO timer not armed, expected it to be") } if *testVV { tc.t.Logf("advancing to PTO timer") } tc.advanceTo(tc.conn.loss.timer) return } if *testVV { *testVV = false defer func() { tc.t.Logf("cause conn to declare last packet lost") *testVV = true }() } defer func(ignoreFrames map[byte]bool) { tc.ignoreFrames = ignoreFrames }(tc.ignoreFrames) tc.ignoreFrames = map[byte]bool{ frameTypeAck: true, frameTypePadding: true, } // Send three packets containing PINGs, and then respond with an ACK for the // last one. This puts the last packet before the PINGs outside the packet // reordering threshold, and it will be declared lost. const lossThreshold = 3 var num packetNumber for i := 0; i < lossThreshold; i++ { tc.conn.ping(spaceForPacketType(ptype)) d := tc.readDatagram() if d == nil { tc.t.Fatalf("conn is idle; want PING frame") } if d.packets[0].ptype != ptype { tc.t.Fatalf("conn sent %v packet; want %v", d.packets[0].ptype, ptype) } num = d.packets[0].num } tc.writeFrames(ptype, debugFrameAck{ ranges: []i64range[packetNumber]{ {num, num + 1}, }, }) } func TestLostResetStreamFrame(t *testing.T) { // "Cancellation of stream transmission, as carried in a RESET_STREAM frame, // is sent until acknowledged or until all stream data is acknowledged by the peer [...]" // https://www.rfc-editor.org/rfc/rfc9000.html#section-13.3-3.4 lostFrameTest(t, func(t *testing.T, pto bool) { tc, s := newTestConnAndLocalStream(t, serverSide, uniStream, permissiveTransportParameters) tc.ignoreFrame(frameTypeAck) s.Reset(1) tc.wantFrame("reset stream", packetType1RTT, debugFrameResetStream{ id: s.id, code: 1, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resent RESET_STREAM frame", packetType1RTT, debugFrameResetStream{ id: s.id, code: 1, }) }) } func TestLostStopSendingFrame(t *testing.T) { // "[...] a request to cancel stream transmission, as encoded in a STOP_SENDING frame, // is sent until the receiving part of the stream enters either a "Data Recvd" or // "Reset Recvd" state [...]" // https://www.rfc-editor.org/rfc/rfc9000.html#section-13.3-3.5 // // Technically, we can stop sending a STOP_SENDING frame if the peer sends // us all the data for the stream or resets it. We don't bother tracking this, // however, so we'll keep sending the frame until it is acked. This is harmless. lostFrameTest(t, func(t *testing.T, pto bool) { tc, s := newTestConnAndRemoteStream(t, serverSide, uniStream, permissiveTransportParameters) tc.ignoreFrame(frameTypeAck) s.CloseRead() tc.wantFrame("stream is read-closed", packetType1RTT, debugFrameStopSending{ id: s.id, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resent STOP_SENDING frame", packetType1RTT, debugFrameStopSending{ id: s.id, }) }) } func TestLostCryptoFrame(t *testing.T) { // "Data sent in CRYPTO frames is retransmitted [...] until all data has been acknowledged." // https://www.rfc-editor.org/rfc/rfc9000.html#section-13.3-3.1 lostFrameTest(t, func(t *testing.T, pto bool) { tc := newTestConn(t, clientSide) tc.ignoreFrame(frameTypeAck) tc.wantFrame("client sends Initial CRYPTO frame", packetTypeInitial, debugFrameCrypto{ data: tc.cryptoDataOut[tls.QUICEncryptionLevelInitial], }) tc.triggerLossOrPTO(packetTypeInitial, pto) tc.wantFrame("client resends Initial CRYPTO frame", packetTypeInitial, debugFrameCrypto{ data: tc.cryptoDataOut[tls.QUICEncryptionLevelInitial], }) tc.writeFrames(packetTypeInitial, debugFrameCrypto{ data: tc.cryptoDataIn[tls.QUICEncryptionLevelInitial], }) tc.writeFrames(packetTypeHandshake, debugFrameCrypto{ data: tc.cryptoDataIn[tls.QUICEncryptionLevelHandshake], }) tc.wantFrame("client sends Handshake CRYPTO frame", packetTypeHandshake, debugFrameCrypto{ data: tc.cryptoDataOut[tls.QUICEncryptionLevelHandshake], }) tc.wantFrame("client provides server with an additional connection ID", packetType1RTT, debugFrameNewConnectionID{ seq: 1, connID: testLocalConnID(1), token: testLocalStatelessResetToken(1), }) tc.triggerLossOrPTO(packetTypeHandshake, pto) tc.wantFrame("client resends Handshake CRYPTO frame", packetTypeHandshake, debugFrameCrypto{ data: tc.cryptoDataOut[tls.QUICEncryptionLevelHandshake], }) }) } func TestLostStreamFrameEmpty(t *testing.T) { // A STREAM frame opening a stream, but containing no stream data, should // be retransmitted if lost. lostFrameTest(t, func(t *testing.T, pto bool) { ctx := canceledContext() tc := newTestConn(t, clientSide, permissiveTransportParameters) tc.handshake() tc.ignoreFrame(frameTypeAck) c, err := tc.conn.NewStream(ctx) if err != nil { t.Fatalf("NewStream: %v", err) } c.Flush() // open the stream tc.wantFrame("created bidirectional stream 0", packetType1RTT, debugFrameStream{ id: newStreamID(clientSide, bidiStream, 0), data: []byte{}, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resent stream frame", packetType1RTT, debugFrameStream{ id: newStreamID(clientSide, bidiStream, 0), data: []byte{}, }) }) } func TestLostStreamWithData(t *testing.T) { // "Application data sent in STREAM frames is retransmitted in new STREAM // frames unless the endpoint has sent a RESET_STREAM for that stream." // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.2 // // TODO: Lost stream frame after RESET_STREAM lostFrameTest(t, func(t *testing.T, pto bool) { data := []byte{0, 1, 2, 3, 4, 5, 6, 7} tc, s := newTestConnAndLocalStream(t, serverSide, uniStream, func(p *transportParameters) { p.initialMaxStreamsUni = 1 p.initialMaxData = 1 << 20 p.initialMaxStreamDataUni = 1 << 20 }) s.Write(data[:4]) s.Flush() tc.wantFrame("send [0,4)", packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: data[:4], }) s.Write(data[4:8]) s.Flush() tc.wantFrame("send [4,8)", packetType1RTT, debugFrameStream{ id: s.id, off: 4, data: data[4:8], }) s.CloseWrite() tc.wantFrame("send FIN", packetType1RTT, debugFrameStream{ id: s.id, off: 8, fin: true, data: []byte{}, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resend data", packetType1RTT, debugFrameStream{ id: s.id, off: 0, fin: true, data: data[:8], }) }) } func TestLostStreamPartialLoss(t *testing.T) { // Conn sends four STREAM packets. // ACKs are received for the packets containing bytes 0 and 2. // The remaining packets are declared lost. // The Conn resends only the lost data. // // This test doesn't have a PTO mode, because the ACK for the packet containing byte 2 // starts the loss timer for the packet containing byte 1, and the PTO timer is not // armed when the loss timer is. data := []byte{0, 1, 2, 3} tc, s := newTestConnAndLocalStream(t, serverSide, uniStream, func(p *transportParameters) { p.initialMaxStreamsUni = 1 p.initialMaxData = 1 << 20 p.initialMaxStreamDataUni = 1 << 20 }) for i := range data { s.Write(data[i : i+1]) s.Flush() tc.wantFrame(fmt.Sprintf("send STREAM frame with byte %v", i), packetType1RTT, debugFrameStream{ id: s.id, off: int64(i), data: data[i : i+1], }) if i%2 == 0 { tc.writeAckForLatest() } } const pto = false tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resend byte 1", packetType1RTT, debugFrameStream{ id: s.id, off: 1, data: data[1:2], }) tc.wantFrame("resend byte 3", packetType1RTT, debugFrameStream{ id: s.id, off: 3, data: data[3:4], }) tc.wantIdle("no more frames sent after packet loss") } func TestLostMaxDataFrame(t *testing.T) { // "An updated value is sent in a MAX_DATA frame if the packet // containing the most recently sent MAX_DATA frame is declared lost [...]" // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.7 lostFrameTest(t, func(t *testing.T, pto bool) { const maxWindowSize = 32 buf := make([]byte, maxWindowSize) tc, s := newTestConnAndRemoteStream(t, serverSide, uniStream, func(c *Config) { c.MaxConnReadBufferSize = 32 }) // We send MAX_DATA = 63. tc.writeFrames(packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: make([]byte, maxWindowSize-1), }) if n, err := s.Read(buf[:maxWindowSize]); err != nil || n != maxWindowSize-1 { t.Fatalf("Read() = %v, %v; want %v, nil", n, err, maxWindowSize-1) } tc.wantFrame("conn window is extended after reading data", packetType1RTT, debugFrameMaxData{ max: (maxWindowSize * 2) - 1, }) // MAX_DATA = 64, which is only one more byte, so we don't send the frame. tc.writeFrames(packetType1RTT, debugFrameStream{ id: s.id, off: maxWindowSize - 1, data: make([]byte, 1), }) if n, err := s.Read(buf[:1]); err != nil || n != 1 { t.Fatalf("Read() = %v, %v; want %v, nil", n, err, 1) } tc.wantIdle("read doesn't extend window enough to send another MAX_DATA") // The MAX_DATA = 63 packet was lost, so we send 64. tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resent MAX_DATA includes most current value", packetType1RTT, debugFrameMaxData{ max: maxWindowSize * 2, }) }) } func TestLostMaxStreamDataFrame(t *testing.T) { // "[...] an updated value is sent when the packet containing // the most recent MAX_STREAM_DATA frame for a stream is lost" // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.8 lostFrameTest(t, func(t *testing.T, pto bool) { const maxWindowSize = 32 buf := make([]byte, maxWindowSize) tc, s := newTestConnAndRemoteStream(t, serverSide, uniStream, func(c *Config) { c.MaxStreamReadBufferSize = maxWindowSize }) // We send MAX_STREAM_DATA = 63. tc.writeFrames(packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: make([]byte, maxWindowSize-1), }) if n, err := s.Read(buf[:maxWindowSize]); err != nil || n != maxWindowSize-1 { t.Fatalf("Read() = %v, %v; want %v, nil", n, err, maxWindowSize-1) } tc.wantFrame("stream window is extended after reading data", packetType1RTT, debugFrameMaxStreamData{ id: s.id, max: (maxWindowSize * 2) - 1, }) // MAX_STREAM_DATA = 64, which is only one more byte, so we don't send the frame. tc.writeFrames(packetType1RTT, debugFrameStream{ id: s.id, off: maxWindowSize - 1, data: make([]byte, 1), }) if n, err := s.Read(buf); err != nil || n != 1 { t.Fatalf("Read() = %v, %v; want %v, nil", n, err, 1) } tc.wantIdle("read doesn't extend window enough to send another MAX_STREAM_DATA") // The MAX_STREAM_DATA = 63 packet was lost, so we send 64. tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resent MAX_STREAM_DATA includes most current value", packetType1RTT, debugFrameMaxStreamData{ id: s.id, max: maxWindowSize * 2, }) }) } func TestLostMaxStreamDataFrameAfterStreamFinReceived(t *testing.T) { // "An endpoint SHOULD stop sending MAX_STREAM_DATA frames when // the receiving part of the stream enters a "Size Known" or "Reset Recvd" state." // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.8 lostFrameTest(t, func(t *testing.T, pto bool) { const maxWindowSize = 10 buf := make([]byte, maxWindowSize) tc, s := newTestConnAndRemoteStream(t, serverSide, uniStream, func(c *Config) { c.MaxStreamReadBufferSize = maxWindowSize }) tc.writeFrames(packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: make([]byte, maxWindowSize), }) if n, err := s.Read(buf); err != nil || n != maxWindowSize { t.Fatalf("Read() = %v, %v; want %v, nil", n, err, maxWindowSize) } tc.wantFrame("stream window is extended after reading data", packetType1RTT, debugFrameMaxStreamData{ id: s.id, max: 2 * maxWindowSize, }) tc.writeFrames(packetType1RTT, debugFrameStream{ id: s.id, off: maxWindowSize, fin: true, }) tc.ignoreFrame(frameTypePing) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantIdle("lost MAX_STREAM_DATA not resent for stream in 'size known'") }) } func TestLostMaxStreamsFrameMostRecent(t *testing.T) { // "[...] an updated value is sent when a packet containing the // most recent MAX_STREAMS for a stream type frame is declared lost [...]" // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.9 testStreamTypes(t, "", func(t *testing.T, styp streamType) { lostFrameTest(t, func(t *testing.T, pto bool) { ctx := canceledContext() tc := newTestConn(t, serverSide, func(c *Config) { c.MaxUniRemoteStreams = 1 c.MaxBidiRemoteStreams = 1 }) tc.handshake() tc.ignoreFrame(frameTypeAck) tc.writeFrames(packetType1RTT, debugFrameStream{ id: newStreamID(clientSide, styp, 0), fin: true, }) s, err := tc.conn.AcceptStream(ctx) if err != nil { t.Fatalf("AcceptStream() = %v", err) } s.SetWriteContext(ctx) s.Close() if styp == bidiStream { tc.wantFrame("stream is closed", packetType1RTT, debugFrameStream{ id: s.id, data: []byte{}, fin: true, }) tc.writeAckForAll() } tc.wantFrame("closing stream updates peer's MAX_STREAMS", packetType1RTT, debugFrameMaxStreams{ streamType: styp, max: 2, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("lost MAX_STREAMS is resent", packetType1RTT, debugFrameMaxStreams{ streamType: styp, max: 2, }) }) }) } func TestLostMaxStreamsFrameNotMostRecent(t *testing.T) { // Send two MAX_STREAMS frames, lose the first one. // // No PTO mode for this test: The ack that causes the first frame // to be lost arms the loss timer for the second, so the PTO timer is not armed. const pto = false ctx := canceledContext() tc := newTestConn(t, serverSide, func(c *Config) { c.MaxUniRemoteStreams = 2 }) tc.handshake() tc.ignoreFrame(frameTypeAck) for i := int64(0); i < 2; i++ { tc.writeFrames(packetType1RTT, debugFrameStream{ id: newStreamID(clientSide, uniStream, i), fin: true, }) s, err := tc.conn.AcceptStream(ctx) if err != nil { t.Fatalf("AcceptStream() = %v", err) } if err := s.Close(); err != nil { t.Fatalf("stream.Close() = %v", err) } tc.wantFrame("closing stream updates peer's MAX_STREAMS", packetType1RTT, debugFrameMaxStreams{ streamType: uniStream, max: 3 + i, }) } // The second MAX_STREAMS frame is acked. tc.writeAckForLatest() // The first MAX_STREAMS frame is lost. tc.conn.ping(appDataSpace) tc.wantFrame("connection should send a PING frame", packetType1RTT, debugFramePing{}) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantIdle("superseded MAX_DATA is not resent on loss") } func TestLostStreamDataBlockedFrame(t *testing.T) { // "A new [STREAM_DATA_BLOCKED] frame is sent if a packet containing // the most recent frame for a scope is lost [...]" // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.10 lostFrameTest(t, func(t *testing.T, pto bool) { tc, s := newTestConnAndLocalStream(t, serverSide, uniStream, func(p *transportParameters) { p.initialMaxStreamsUni = 1 p.initialMaxData = 1 << 20 }) w := runAsync(tc, func(ctx context.Context) (int, error) { return s.Write([]byte{0, 1, 2, 3}) }) defer w.cancel() tc.wantFrame("write is blocked by flow control", packetType1RTT, debugFrameStreamDataBlocked{ id: s.id, max: 0, }) tc.writeFrames(packetType1RTT, debugFrameMaxStreamData{ id: s.id, max: 1, }) tc.wantFrame("write makes some progress, but is still blocked by flow control", packetType1RTT, debugFrameStreamDataBlocked{ id: s.id, max: 1, }) tc.wantFrame("write consuming available window", packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: []byte{0}, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("STREAM_DATA_BLOCKED is resent", packetType1RTT, debugFrameStreamDataBlocked{ id: s.id, max: 1, }) tc.wantFrame("STREAM is resent as well", packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: []byte{0}, }) }) } func TestLostStreamDataBlockedFrameAfterStreamUnblocked(t *testing.T) { // "A new [STREAM_DATA_BLOCKED] frame is sent [...] only while // the endpoint is blocked on the corresponding limit." // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.10 lostFrameTest(t, func(t *testing.T, pto bool) { tc, s := newTestConnAndLocalStream(t, serverSide, uniStream, func(p *transportParameters) { p.initialMaxStreamsUni = 1 p.initialMaxData = 1 << 20 }) data := []byte{0, 1, 2, 3} w := runAsync(tc, func(ctx context.Context) (int, error) { return s.Write(data) }) defer w.cancel() tc.wantFrame("write is blocked by flow control", packetType1RTT, debugFrameStreamDataBlocked{ id: s.id, max: 0, }) tc.writeFrames(packetType1RTT, debugFrameMaxStreamData{ id: s.id, max: 10, }) tc.wantFrame("write completes after flow control available", packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: data, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("STREAM data is resent", packetType1RTT, debugFrameStream{ id: s.id, off: 0, data: data, }) tc.wantIdle("STREAM_DATA_BLOCKED is not resent, since the stream is not blocked") }) } func TestLostNewConnectionIDFrame(t *testing.T) { // "New connection IDs are [...] retransmitted if the packet containing them is lost." // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.13 lostFrameTest(t, func(t *testing.T, pto bool) { tc := newTestConn(t, serverSide) tc.handshake() tc.ignoreFrame(frameTypeAck) tc.writeFrames(packetType1RTT, debugFrameRetireConnectionID{ seq: 1, }) tc.wantFrame("provide a new connection ID after peer retires old one", packetType1RTT, debugFrameNewConnectionID{ seq: 2, connID: testLocalConnID(2), token: testLocalStatelessResetToken(2), }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resend new connection ID", packetType1RTT, debugFrameNewConnectionID{ seq: 2, connID: testLocalConnID(2), token: testLocalStatelessResetToken(2), }) }) } func TestLostRetireConnectionIDFrame(t *testing.T) { // "[...] retired connection IDs are [...] retransmitted // if the packet containing them is lost." // https://www.rfc-editor.org/rfc/rfc9000#section-13.3-3.13 lostFrameTest(t, func(t *testing.T, pto bool) { tc := newTestConn(t, clientSide) tc.handshake() tc.ignoreFrame(frameTypeAck) tc.writeFrames(packetType1RTT, debugFrameNewConnectionID{ seq: 2, retirePriorTo: 1, connID: testPeerConnID(2), }) tc.wantFrame("peer requested connection id be retired", packetType1RTT, debugFrameRetireConnectionID{ seq: 0, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("resend RETIRE_CONNECTION_ID", packetType1RTT, debugFrameRetireConnectionID{ seq: 0, }) }) } func TestLostPathResponseFrame(t *testing.T) { // "Responses to path validation using PATH_RESPONSE frames are sent just once." // https://www.rfc-editor.org/rfc/rfc9000.html#section-13.3-3.12 lostFrameTest(t, func(t *testing.T, pto bool) { tc := newTestConn(t, clientSide) tc.handshake() tc.ignoreFrame(frameTypeAck) tc.ignoreFrame(frameTypePing) data := pathChallengeData{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef} tc.writeFrames(packetType1RTT, debugFramePathChallenge{ data: data, }) tc.wantFrame("response to PATH_CHALLENGE", packetType1RTT, debugFramePathResponse{ data: data, }) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantIdle("lost PATH_RESPONSE frame is not retransmitted") }) } func TestLostHandshakeDoneFrame(t *testing.T) { // "The HANDSHAKE_DONE frame MUST be retransmitted until it is acknowledged." // https://www.rfc-editor.org/rfc/rfc9000.html#section-13.3-3.16 lostFrameTest(t, func(t *testing.T, pto bool) { tc := newTestConn(t, serverSide) tc.ignoreFrame(frameTypeAck) tc.writeFrames(packetTypeInitial, debugFrameCrypto{ data: tc.cryptoDataIn[tls.QUICEncryptionLevelInitial], }) tc.wantFrame("server sends Initial CRYPTO frame", packetTypeInitial, debugFrameCrypto{ data: tc.cryptoDataOut[tls.QUICEncryptionLevelInitial], }) tc.wantFrame("server sends Handshake CRYPTO frame", packetTypeHandshake, debugFrameCrypto{ data: tc.cryptoDataOut[tls.QUICEncryptionLevelHandshake], }) tc.wantFrame("server provides an additional connection ID", packetType1RTT, debugFrameNewConnectionID{ seq: 1, connID: testLocalConnID(1), token: testLocalStatelessResetToken(1), }) tc.writeFrames(packetTypeHandshake, debugFrameCrypto{ data: tc.cryptoDataIn[tls.QUICEncryptionLevelHandshake], }) tc.wantFrame("server sends HANDSHAKE_DONE after handshake completes", packetType1RTT, debugFrameHandshakeDone{}) tc.triggerLossOrPTO(packetType1RTT, pto) tc.wantFrame("server resends HANDSHAKE_DONE", packetType1RTT, debugFrameHandshakeDone{}) }) }
net/quic/conn_loss_test.go/0
{ "file_path": "net/quic/conn_loss_test.go", "repo_id": "net", "token_count": 9125 }
630
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build go1.21 package quic import ( "bytes" "encoding/binary" "testing" ) func TestDecodePacketNumber(t *testing.T) { for _, test := range []struct { largest packetNumber truncated packetNumber want packetNumber size int }{{ largest: 0, truncated: 1, size: 4, want: 1, }, { largest: 0, truncated: 0, size: 1, want: 0, }, { largest: 0x00, truncated: 0x01, size: 1, want: 0x01, }, { largest: 0x00, truncated: 0xff, size: 1, want: 0xff, }, { largest: 0xff, truncated: 0x01, size: 1, want: 0x101, }, { largest: 0x1000, truncated: 0xff, size: 1, want: 0xfff, }, { largest: 0xa82f30ea, truncated: 0x9b32, size: 2, want: 0xa82f9b32, }} { got := decodePacketNumber(test.largest, test.truncated, test.size) if got != test.want { t.Errorf("decodePacketNumber(largest=0x%x, truncated=0x%x, size=%v) = 0x%x, want 0x%x", test.largest, test.truncated, test.size, got, test.want) } } } func TestEncodePacketNumber(t *testing.T) { for _, test := range []struct { largestAcked packetNumber pnum packetNumber wantSize int }{{ largestAcked: -1, pnum: 0, wantSize: 1, }, { largestAcked: 1000, pnum: 1000 + 0x7f, wantSize: 1, }, { largestAcked: 1000, pnum: 1000 + 0x80, // 0x468 wantSize: 2, }, { largestAcked: 0x12345678, pnum: 0x12345678 + 0x7fff, // 0x305452663 wantSize: 2, }, { largestAcked: 0x12345678, pnum: 0x12345678 + 0x8000, wantSize: 3, }, { largestAcked: 0, pnum: 0x7fffff, wantSize: 3, }, { largestAcked: 0, pnum: 0x800000, wantSize: 4, }, { largestAcked: 0xabe8bc, pnum: 0xac5c02, wantSize: 2, }, { largestAcked: 0xabe8bc, pnum: 0xace8fe, wantSize: 3, }} { size := packetNumberLength(test.pnum, test.largestAcked) if got, want := size, test.wantSize; got != want { t.Errorf("packetNumberLength(num=%x, maxAck=%x) = %v, want %v", test.pnum, test.largestAcked, got, want) } var enc packetNumber switch size { case 1: enc = test.pnum & 0xff case 2: enc = test.pnum & 0xffff case 3: enc = test.pnum & 0xffffff case 4: enc = test.pnum & 0xffffffff } wantBytes := binary.BigEndian.AppendUint32(nil, uint32(enc))[4-size:] gotBytes := appendPacketNumber(nil, test.pnum, test.largestAcked) if !bytes.Equal(gotBytes, wantBytes) { t.Errorf("appendPacketNumber(num=%v, maxAck=%x) = {%x}, want {%x}", test.pnum, test.largestAcked, gotBytes, wantBytes) } gotNum := decodePacketNumber(test.largestAcked, enc, size) if got, want := gotNum, test.pnum; got != want { t.Errorf("packetNumberLength(num=%x, maxAck=%x) = %v, but decoded number=%x", test.pnum, test.largestAcked, size, got) } } } func FuzzPacketNumber(f *testing.F) { truncatedNumber := func(in []byte) packetNumber { var truncated packetNumber for _, b := range in { truncated = (truncated << 8) | packetNumber(b) } return truncated } f.Fuzz(func(t *testing.T, in []byte, largestAckedInt64 int64) { largestAcked := packetNumber(largestAckedInt64) if len(in) < 1 || len(in) > 4 || largestAcked < 0 || largestAcked > maxPacketNumber { return } truncatedIn := truncatedNumber(in) decoded := decodePacketNumber(largestAcked, truncatedIn, len(in)) // Check that the decoded packet number's least significant bits match the input. var mask packetNumber for i := 0; i < len(in); i++ { mask = (mask << 8) | 0xff } if truncatedIn != decoded&mask { t.Fatalf("decoding mismatch: input=%x largestAcked=%v decoded=0x%x", in, largestAcked, decoded) } // We don't support encoding packet numbers less than largestAcked (since packet numbers // never decrease), so skip the encoder tests if this would make us go backwards. if decoded < largestAcked { return } // We might encode this number using a different length than we received, // but the common portions should match. encoded := appendPacketNumber(nil, decoded, largestAcked) a, b := in, encoded if len(b) < len(a) { a, b = b, a } for len(a) < len(b) { b = b[1:] } if len(a) == 0 || !bytes.Equal(a, b) { t.Fatalf("encoding mismatch: input=%x largestAcked=%v decoded=%v reencoded=%x", in, largestAcked, decoded, encoded) } if g := decodePacketNumber(largestAcked, truncatedNumber(encoded), len(encoded)); g != decoded { t.Fatalf("packet encode/decode mismatch: pnum=%v largestAcked=%v encoded=%x got=%v", decoded, largestAcked, encoded, g) } if l := packetNumberLength(decoded, largestAcked); l != len(encoded) { t.Fatalf("packet number length mismatch: pnum=%v largestAcked=%v encoded=%x len=%v", decoded, largestAcked, encoded, l) } }) }
net/quic/packet_number_test.go/0
{ "file_path": "net/quic/packet_number_test.go", "repo_id": "net", "token_count": 2315 }
631
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build go1.21 // Package qlog serializes qlog events. package qlog import ( "bytes" "context" "errors" "io" "log/slog" "os" "path/filepath" "sync" "time" ) // Vantage is the vantage point of a trace. type Vantage string const ( // VantageEndpoint traces contain events not specific to a single connection. VantageEndpoint = Vantage("endpoint") // VantageClient traces follow a connection from the client's perspective. VantageClient = Vantage("client") // VantageServer traces follow a connection from the server's perspective. VantageServer = Vantage("server") ) // TraceInfo contains information about a trace. type TraceInfo struct { // Vantage is the vantage point of the trace. Vantage Vantage // GroupID identifies the logical group the trace belongs to. // For a connection trace, the group will be the same for // both the client and server vantage points. GroupID string } // HandlerOptions are options for a JSONHandler. type HandlerOptions struct { // Level reports the minimum record level that will be logged. // If Level is nil, the handler assumes QLogLevelEndpoint. Level slog.Leveler // Dir is the directory in which to create trace files. // The handler will create one file per connection. // If NewTrace is non-nil or Dir is "", the handler will not create files. Dir string // NewTrace is called to create a new trace. // If NewTrace is nil and Dir is set, // the handler will create a new file in Dir for each trace. NewTrace func(TraceInfo) (io.WriteCloser, error) } type endpointHandler struct { opts HandlerOptions traceOnce sync.Once trace *jsonTraceHandler } // NewJSONHandler returns a handler which serializes qlog events to JSON. // // The handler will write an endpoint-wide trace, // and a separate trace for each connection. // The HandlerOptions control the location traces are written. // // It uses the streamable JSON Text Sequences mapping (JSON-SEQ) // defined in draft-ietf-quic-qlog-main-schema-04, Section 6.2. // // A JSONHandler may be used as the handler for a quic.Config.QLogLogger. // It is not a general-purpose slog handler, // and may not properly handle events from other sources. func NewJSONHandler(opts HandlerOptions) slog.Handler { if opts.Dir == "" && opts.NewTrace == nil { return slogDiscard{} } return &endpointHandler{ opts: opts, } } func (h *endpointHandler) Enabled(ctx context.Context, level slog.Level) bool { return enabled(h.opts.Level, level) } func (h *endpointHandler) Handle(ctx context.Context, r slog.Record) error { h.traceOnce.Do(func() { h.trace, _ = newJSONTraceHandler(h.opts, nil) }) if h.trace != nil { h.trace.Handle(ctx, r) } return nil } func (h *endpointHandler) WithAttrs(attrs []slog.Attr) slog.Handler { // Create a new trace output file for each top-level WithAttrs. tr, err := newJSONTraceHandler(h.opts, attrs) if err != nil { return withAttrs(h, attrs) } return tr } func (h *endpointHandler) WithGroup(name string) slog.Handler { return withGroup(h, name) } type jsonTraceHandler struct { level slog.Leveler w jsonWriter start time.Time buf bytes.Buffer } func newJSONTraceHandler(opts HandlerOptions, attrs []slog.Attr) (*jsonTraceHandler, error) { w, err := newTraceWriter(opts, traceInfoFromAttrs(attrs)) if err != nil { return nil, err } // For testing, it might be nice to set the start time used for relative timestamps // to the time of the first event. // // At the expense of some additional complexity here, we could defer writing // the reference_time header field until the first event is processed. // // Just use the current time for now. start := time.Now() h := &jsonTraceHandler{ w: jsonWriter{w: w}, level: opts.Level, start: start, } h.writeHeader(attrs) return h, nil } func traceInfoFromAttrs(attrs []slog.Attr) TraceInfo { info := TraceInfo{ Vantage: VantageEndpoint, // default if not specified } for _, a := range attrs { if a.Key == "group_id" && a.Value.Kind() == slog.KindString { info.GroupID = a.Value.String() } if a.Key == "vantage_point" && a.Value.Kind() == slog.KindGroup { for _, aa := range a.Value.Group() { if aa.Key == "type" && aa.Value.Kind() == slog.KindString { info.Vantage = Vantage(aa.Value.String()) } } } } return info } func newTraceWriter(opts HandlerOptions, info TraceInfo) (io.WriteCloser, error) { var w io.WriteCloser var err error if opts.NewTrace != nil { w, err = opts.NewTrace(info) } else if opts.Dir != "" { var filename string if info.GroupID != "" { filename = info.GroupID + "_" } filename += string(info.Vantage) + ".sqlog" if !filepath.IsLocal(filename) { return nil, errors.New("invalid trace filename") } w, err = os.OpenFile(filepath.Join(opts.Dir, filename), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0666) } else { err = errors.New("no log destination") } return w, err } func (h *jsonTraceHandler) writeHeader(attrs []slog.Attr) { h.w.writeRecordStart() defer h.w.writeRecordEnd() // At the time of writing this comment the most recent version is 0.4, // but qvis only supports up to 0.3. h.w.writeStringField("qlog_version", "0.3") h.w.writeStringField("qlog_format", "JSON-SEQ") // The attrs flatten both common trace event fields and Trace fields. // This identifies the fields that belong to the Trace. isTraceSeqField := func(s string) bool { switch s { case "title", "description", "configuration", "vantage_point": return true } return false } h.w.writeObjectField("trace", func() { h.w.writeObjectField("common_fields", func() { h.w.writeRawField("protocol_type", `["QUIC"]`) h.w.writeStringField("time_format", "relative") h.w.writeTimeField("reference_time", h.start) for _, a := range attrs { if !isTraceSeqField(a.Key) { h.w.writeAttr(a) } } }) for _, a := range attrs { if isTraceSeqField(a.Key) { h.w.writeAttr(a) } } }) } func (h *jsonTraceHandler) Enabled(ctx context.Context, level slog.Level) bool { return enabled(h.level, level) } func (h *jsonTraceHandler) Handle(ctx context.Context, r slog.Record) error { h.w.writeRecordStart() defer h.w.writeRecordEnd() h.w.writeDurationField("time", r.Time.Sub(h.start)) h.w.writeStringField("name", r.Message) h.w.writeObjectField("data", func() { r.Attrs(func(a slog.Attr) bool { h.w.writeAttr(a) return true }) }) return nil } func (h *jsonTraceHandler) WithAttrs(attrs []slog.Attr) slog.Handler { return withAttrs(h, attrs) } func (h *jsonTraceHandler) WithGroup(name string) slog.Handler { return withGroup(h, name) } func enabled(leveler slog.Leveler, level slog.Level) bool { var minLevel slog.Level if leveler != nil { minLevel = leveler.Level() } return level >= minLevel } type slogDiscard struct{} func (slogDiscard) Enabled(context.Context, slog.Level) bool { return false } func (slogDiscard) Handle(ctx context.Context, r slog.Record) error { return nil } func (slogDiscard) WithAttrs(attrs []slog.Attr) slog.Handler { return slogDiscard{} } func (slogDiscard) WithGroup(name string) slog.Handler { return slogDiscard{} }
net/quic/qlog/qlog.go/0
{ "file_path": "net/quic/qlog/qlog.go", "repo_id": "net", "token_count": 2619 }
632
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build go1.21 package quic import "testing" func TestSentPacket(t *testing.T) { frames := []any{ byte(frameTypePing), byte(frameTypeStreamBase), uint64(1), i64range[int64]{1 << 20, 1<<20 + 1024}, } // Record sent frames. sent := newSentPacket() for _, f := range frames { switch f := f.(type) { case byte: sent.appendAckElicitingFrame(f) case uint64: sent.appendInt(f) case i64range[int64]: sent.appendOffAndSize(f.start, int(f.size())) } } // Read the record. for i, want := range frames { if done := sent.done(); done { t.Fatalf("before consuming contents, sent.done() = true, want false") } switch want := want.(type) { case byte: if got := sent.next(); got != want { t.Fatalf("%v: sent.next() = %v, want %v", i, got, want) } case uint64: if got := sent.nextInt(); got != want { t.Fatalf("%v: sent.nextInt() = %v, want %v", i, got, want) } case i64range[int64]: if start, end := sent.nextRange(); start != want.start || end != want.end { t.Fatalf("%v: sent.nextRange() = [%v,%v), want %v", i, start, end, want) } } } if done := sent.done(); !done { t.Fatalf("after consuming contents, sent.done() = false, want true") } }
net/quic/sent_packet_test.go/0
{ "file_path": "net/quic/sent_packet_test.go", "repo_id": "net", "token_count": 562 }
633
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build go1.21 && linux package quic import ( "golang.org/x/sys/unix" ) // See udp.go. const ( udpECNSupport = true udpInvalidLocalAddrIsError = false ) // The IP_TOS socket option is a single byte containing the IP TOS field. // The low two bits are the ECN field. func parseIPTOS(b []byte) (ecnBits, bool) { if len(b) != 1 { return 0, false } return ecnBits(b[0] & ecnMask), true } func appendCmsgECNv4(b []byte, ecn ecnBits) []byte { b, data := appendCmsg(b, unix.IPPROTO_IP, unix.IP_TOS, 1) data[0] = byte(ecn) return b }
net/quic/udp_linux.go/0
{ "file_path": "net/quic/udp_linux.go", "repo_id": "net", "token_count": 296 }
634
// 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 trace // This file implements histogramming for RPC statistics collection. import ( "bytes" "fmt" "html/template" "log" "math" "sync" "golang.org/x/net/internal/timeseries" ) const ( bucketCount = 38 ) // histogram keeps counts of values in buckets that are spaced // out in powers of 2: 0-1, 2-3, 4-7... // histogram implements timeseries.Observable type histogram struct { sum int64 // running total of measurements sumOfSquares float64 // square of running total buckets []int64 // bucketed values for histogram value int // holds a single value as an optimization valueCount int64 // number of values recorded for single value } // addMeasurement records a value measurement observation to the histogram. func (h *histogram) addMeasurement(value int64) { // TODO: assert invariant h.sum += value h.sumOfSquares += float64(value) * float64(value) bucketIndex := getBucket(value) if h.valueCount == 0 || (h.valueCount > 0 && h.value == bucketIndex) { h.value = bucketIndex h.valueCount++ } else { h.allocateBuckets() h.buckets[bucketIndex]++ } } func (h *histogram) allocateBuckets() { if h.buckets == nil { h.buckets = make([]int64, bucketCount) h.buckets[h.value] = h.valueCount h.value = 0 h.valueCount = -1 } } func log2(i int64) int { n := 0 for ; i >= 0x100; i >>= 8 { n += 8 } for ; i > 0; i >>= 1 { n += 1 } return n } func getBucket(i int64) (index int) { index = log2(i) - 1 if index < 0 { index = 0 } if index >= bucketCount { index = bucketCount - 1 } return } // Total returns the number of recorded observations. func (h *histogram) total() (total int64) { if h.valueCount >= 0 { total = h.valueCount } for _, val := range h.buckets { total += int64(val) } return } // Average returns the average value of recorded observations. func (h *histogram) average() float64 { t := h.total() if t == 0 { return 0 } return float64(h.sum) / float64(t) } // Variance returns the variance of recorded observations. func (h *histogram) variance() float64 { t := float64(h.total()) if t == 0 { return 0 } s := float64(h.sum) / t return h.sumOfSquares/t - s*s } // StandardDeviation returns the standard deviation of recorded observations. func (h *histogram) standardDeviation() float64 { return math.Sqrt(h.variance()) } // PercentileBoundary estimates the value that the given fraction of recorded // observations are less than. func (h *histogram) percentileBoundary(percentile float64) int64 { total := h.total() // Corner cases (make sure result is strictly less than Total()) if total == 0 { return 0 } else if total == 1 { return int64(h.average()) } percentOfTotal := round(float64(total) * percentile) var runningTotal int64 for i := range h.buckets { value := h.buckets[i] runningTotal += value if runningTotal == percentOfTotal { // We hit an exact bucket boundary. If the next bucket has data, it is a // good estimate of the value. If the bucket is empty, we interpolate the // midpoint between the next bucket's boundary and the next non-zero // bucket. If the remaining buckets are all empty, then we use the // boundary for the next bucket as the estimate. j := uint8(i + 1) min := bucketBoundary(j) if runningTotal < total { for h.buckets[j] == 0 { j++ } } max := bucketBoundary(j) return min + round(float64(max-min)/2) } else if runningTotal > percentOfTotal { // The value is in this bucket. Interpolate the value. delta := runningTotal - percentOfTotal percentBucket := float64(value-delta) / float64(value) bucketMin := bucketBoundary(uint8(i)) nextBucketMin := bucketBoundary(uint8(i + 1)) bucketSize := nextBucketMin - bucketMin return bucketMin + round(percentBucket*float64(bucketSize)) } } return bucketBoundary(bucketCount - 1) } // Median returns the estimated median of the observed values. func (h *histogram) median() int64 { return h.percentileBoundary(0.5) } // Add adds other to h. func (h *histogram) Add(other timeseries.Observable) { o := other.(*histogram) if o.valueCount == 0 { // Other histogram is empty } else if h.valueCount >= 0 && o.valueCount > 0 && h.value == o.value { // Both have a single bucketed value, aggregate them h.valueCount += o.valueCount } else { // Two different values necessitate buckets in this histogram h.allocateBuckets() if o.valueCount >= 0 { h.buckets[o.value] += o.valueCount } else { for i := range h.buckets { h.buckets[i] += o.buckets[i] } } } h.sumOfSquares += o.sumOfSquares h.sum += o.sum } // Clear resets the histogram to an empty state, removing all observed values. func (h *histogram) Clear() { h.buckets = nil h.value = 0 h.valueCount = 0 h.sum = 0 h.sumOfSquares = 0 } // CopyFrom copies from other, which must be a *histogram, into h. func (h *histogram) CopyFrom(other timeseries.Observable) { o := other.(*histogram) if o.valueCount == -1 { h.allocateBuckets() copy(h.buckets, o.buckets) } h.sum = o.sum h.sumOfSquares = o.sumOfSquares h.value = o.value h.valueCount = o.valueCount } // Multiply scales the histogram by the specified ratio. func (h *histogram) Multiply(ratio float64) { if h.valueCount == -1 { for i := range h.buckets { h.buckets[i] = int64(float64(h.buckets[i]) * ratio) } } else { h.valueCount = int64(float64(h.valueCount) * ratio) } h.sum = int64(float64(h.sum) * ratio) h.sumOfSquares = h.sumOfSquares * ratio } // New creates a new histogram. func (h *histogram) New() timeseries.Observable { r := new(histogram) r.Clear() return r } func (h *histogram) String() string { return fmt.Sprintf("%d, %f, %d, %d, %v", h.sum, h.sumOfSquares, h.value, h.valueCount, h.buckets) } // round returns the closest int64 to the argument func round(in float64) int64 { return int64(math.Floor(in + 0.5)) } // bucketBoundary returns the first value in the bucket. func bucketBoundary(bucket uint8) int64 { if bucket == 0 { return 0 } return 1 << bucket } // bucketData holds data about a specific bucket for use in distTmpl. type bucketData struct { Lower, Upper int64 N int64 Pct, CumulativePct float64 GraphWidth int } // data holds data about a Distribution for use in distTmpl. type data struct { Buckets []*bucketData Count, Median int64 Mean, StandardDeviation float64 } // maxHTMLBarWidth is the maximum width of the HTML bar for visualizing buckets. const maxHTMLBarWidth = 350.0 // newData returns data representing h for use in distTmpl. func (h *histogram) newData() *data { // Force the allocation of buckets to simplify the rendering implementation h.allocateBuckets() // We scale the bars on the right so that the largest bar is // maxHTMLBarWidth pixels in width. maxBucket := int64(0) for _, n := range h.buckets { if n > maxBucket { maxBucket = n } } total := h.total() barsizeMult := maxHTMLBarWidth / float64(maxBucket) var pctMult float64 if total == 0 { pctMult = 1.0 } else { pctMult = 100.0 / float64(total) } buckets := make([]*bucketData, len(h.buckets)) runningTotal := int64(0) for i, n := range h.buckets { if n == 0 { continue } runningTotal += n var upperBound int64 if i < bucketCount-1 { upperBound = bucketBoundary(uint8(i + 1)) } else { upperBound = math.MaxInt64 } buckets[i] = &bucketData{ Lower: bucketBoundary(uint8(i)), Upper: upperBound, N: n, Pct: float64(n) * pctMult, CumulativePct: float64(runningTotal) * pctMult, GraphWidth: int(float64(n) * barsizeMult), } } return &data{ Buckets: buckets, Count: total, Median: h.median(), Mean: h.average(), StandardDeviation: h.standardDeviation(), } } func (h *histogram) html() template.HTML { buf := new(bytes.Buffer) if err := distTmpl().Execute(buf, h.newData()); err != nil { buf.Reset() log.Printf("net/trace: couldn't execute template: %v", err) } return template.HTML(buf.String()) } var distTmplCache *template.Template var distTmplOnce sync.Once func distTmpl() *template.Template { distTmplOnce.Do(func() { // Input: data distTmplCache = template.Must(template.New("distTmpl").Parse(` <table> <tr> <td style="padding:0.25em">Count: {{.Count}}</td> <td style="padding:0.25em">Mean: {{printf "%.0f" .Mean}}</td> <td style="padding:0.25em">StdDev: {{printf "%.0f" .StandardDeviation}}</td> <td style="padding:0.25em">Median: {{.Median}}</td> </tr> </table> <hr> <table> {{range $b := .Buckets}} {{if $b}} <tr> <td style="padding:0 0 0 0.25em">[</td> <td style="text-align:right;padding:0 0.25em">{{.Lower}},</td> <td style="text-align:right;padding:0 0.25em">{{.Upper}})</td> <td style="text-align:right;padding:0 0.25em">{{.N}}</td> <td style="text-align:right;padding:0 0.25em">{{printf "%#.3f" .Pct}}%</td> <td style="text-align:right;padding:0 0.25em">{{printf "%#.3f" .CumulativePct}}%</td> <td><div style="background-color: blue; height: 1em; width: {{.GraphWidth}};"></div></td> </tr> {{end}} {{end}} </table> `)) }) return distTmplCache }
net/trace/histogram.go/0
{ "file_path": "net/trace/histogram.go", "repo_id": "net", "token_count": 3683 }
635
// 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. // Package xml implements a simple XML 1.0 parser that // understands XML name spaces. package xml // References: // Annotated XML spec: http://www.xml.com/axml/testaxml.htm // XML name spaces: http://www.w3.org/TR/REC-xml-names/ // TODO(rsc): // Test error handling. import ( "bufio" "bytes" "errors" "fmt" "io" "strconv" "strings" "unicode" "unicode/utf8" ) // A SyntaxError represents a syntax error in the XML input stream. type SyntaxError struct { Msg string Line int } func (e *SyntaxError) Error() string { return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg } // A Name represents an XML name (Local) annotated with a name space // identifier (Space). In tokens returned by Decoder.Token, the Space // identifier is given as a canonical URL, not the short prefix used in // the document being parsed. // // As a special case, XML namespace declarations will use the literal // string "xmlns" for the Space field instead of the fully resolved URL. // See Encoder.EncodeToken for more information on namespace encoding // behaviour. type Name struct { Space, Local string } // isNamespace reports whether the name is a namespace-defining name. func (name Name) isNamespace() bool { return name.Local == "xmlns" || name.Space == "xmlns" } // An Attr represents an attribute in an XML element (Name=Value). type Attr struct { Name Name Value string } // A Token is an interface holding one of the token types: // StartElement, EndElement, CharData, Comment, ProcInst, or Directive. type Token interface{} // A StartElement represents an XML start element. type StartElement struct { Name Name Attr []Attr } func (e StartElement) Copy() StartElement { attrs := make([]Attr, len(e.Attr)) copy(attrs, e.Attr) e.Attr = attrs return e } // End returns the corresponding XML end element. func (e StartElement) End() EndElement { return EndElement{e.Name} } // setDefaultNamespace sets the namespace of the element // as the default for all elements contained within it. func (e *StartElement) setDefaultNamespace() { if e.Name.Space == "" { // If there's no namespace on the element, don't // set the default. Strictly speaking this might be wrong, as // we can't tell if the element had no namespace set // or was just using the default namespace. return } // Don't add a default name space if there's already one set. for _, attr := range e.Attr { if attr.Name.Space == "" && attr.Name.Local == "xmlns" { return } } e.Attr = append(e.Attr, Attr{ Name: Name{ Local: "xmlns", }, Value: e.Name.Space, }) } // An EndElement represents an XML end element. type EndElement struct { Name Name } // A CharData represents XML character data (raw text), // in which XML escape sequences have been replaced by // the characters they represent. type CharData []byte func makeCopy(b []byte) []byte { b1 := make([]byte, len(b)) copy(b1, b) return b1 } func (c CharData) Copy() CharData { return CharData(makeCopy(c)) } // A Comment represents an XML comment of the form <!--comment-->. // The bytes do not include the <!-- and --> comment markers. type Comment []byte func (c Comment) Copy() Comment { return Comment(makeCopy(c)) } // A ProcInst represents an XML processing instruction of the form <?target inst?> type ProcInst struct { Target string Inst []byte } func (p ProcInst) Copy() ProcInst { p.Inst = makeCopy(p.Inst) return p } // A Directive represents an XML directive of the form <!text>. // The bytes do not include the <! and > markers. type Directive []byte func (d Directive) Copy() Directive { return Directive(makeCopy(d)) } // CopyToken returns a copy of a Token. func CopyToken(t Token) Token { switch v := t.(type) { case CharData: return v.Copy() case Comment: return v.Copy() case Directive: return v.Copy() case ProcInst: return v.Copy() case StartElement: return v.Copy() } return t } // A Decoder represents an XML parser reading a particular input stream. // The parser assumes that its input is encoded in UTF-8. type Decoder struct { // Strict defaults to true, enforcing the requirements // of the XML specification. // If set to false, the parser allows input containing common // mistakes: // * If an element is missing an end tag, the parser invents // end tags as necessary to keep the return values from Token // properly balanced. // * In attribute values and character data, unknown or malformed // character entities (sequences beginning with &) are left alone. // // Setting: // // d.Strict = false; // d.AutoClose = HTMLAutoClose; // d.Entity = HTMLEntity // // creates a parser that can handle typical HTML. // // Strict mode does not enforce the requirements of the XML name spaces TR. // In particular it does not reject name space tags using undefined prefixes. // Such tags are recorded with the unknown prefix as the name space URL. Strict bool // When Strict == false, AutoClose indicates a set of elements to // consider closed immediately after they are opened, regardless // of whether an end element is present. AutoClose []string // Entity can be used to map non-standard entity names to string replacements. // The parser behaves as if these standard mappings are present in the map, // regardless of the actual map content: // // "lt": "<", // "gt": ">", // "amp": "&", // "apos": "'", // "quot": `"`, Entity map[string]string // CharsetReader, if non-nil, defines a function to generate // charset-conversion readers, converting from the provided // non-UTF-8 charset into UTF-8. If CharsetReader is nil or // returns an error, parsing stops with an error. One of the // the CharsetReader's result values must be non-nil. CharsetReader func(charset string, input io.Reader) (io.Reader, error) // DefaultSpace sets the default name space used for unadorned tags, // as if the entire XML stream were wrapped in an element containing // the attribute xmlns="DefaultSpace". DefaultSpace string r io.ByteReader buf bytes.Buffer saved *bytes.Buffer stk *stack free *stack needClose bool toClose Name nextToken Token nextByte int ns map[string]string err error line int offset int64 unmarshalDepth int } // NewDecoder creates a new XML parser reading from r. // If r does not implement io.ByteReader, NewDecoder will // do its own buffering. func NewDecoder(r io.Reader) *Decoder { d := &Decoder{ ns: make(map[string]string), nextByte: -1, line: 1, Strict: true, } d.switchToReader(r) return d } // Token returns the next XML token in the input stream. // At the end of the input stream, Token returns nil, io.EOF. // // Slices of bytes in the returned token data refer to the // parser's internal buffer and remain valid only until the next // call to Token. To acquire a copy of the bytes, call CopyToken // or the token's Copy method. // // Token expands self-closing elements such as <br/> // into separate start and end elements returned by successive calls. // // Token guarantees that the StartElement and EndElement // tokens it returns are properly nested and matched: // if Token encounters an unexpected end element, // it will return an error. // // Token implements XML name spaces as described by // http://www.w3.org/TR/REC-xml-names/. Each of the // Name structures contained in the Token has the Space // set to the URL identifying its name space when known. // If Token encounters an unrecognized name space prefix, // it uses the prefix as the Space rather than report an error. func (d *Decoder) Token() (t Token, err error) { if d.stk != nil && d.stk.kind == stkEOF { err = io.EOF return } if d.nextToken != nil { t = d.nextToken d.nextToken = nil } else if t, err = d.rawToken(); err != nil { return } if !d.Strict { if t1, ok := d.autoClose(t); ok { d.nextToken = t t = t1 } } switch t1 := t.(type) { case StartElement: // In XML name spaces, the translations listed in the // attributes apply to the element name and // to the other attribute names, so process // the translations first. for _, a := range t1.Attr { if a.Name.Space == "xmlns" { v, ok := d.ns[a.Name.Local] d.pushNs(a.Name.Local, v, ok) d.ns[a.Name.Local] = a.Value } if a.Name.Space == "" && a.Name.Local == "xmlns" { // Default space for untagged names v, ok := d.ns[""] d.pushNs("", v, ok) d.ns[""] = a.Value } } d.translate(&t1.Name, true) for i := range t1.Attr { d.translate(&t1.Attr[i].Name, false) } d.pushElement(t1.Name) t = t1 case EndElement: d.translate(&t1.Name, true) if !d.popElement(&t1) { return nil, d.err } t = t1 } return } const xmlURL = "http://www.w3.org/XML/1998/namespace" // Apply name space translation to name n. // The default name space (for Space=="") // applies only to element names, not to attribute names. func (d *Decoder) translate(n *Name, isElementName bool) { switch { case n.Space == "xmlns": return case n.Space == "" && !isElementName: return case n.Space == "xml": n.Space = xmlURL case n.Space == "" && n.Local == "xmlns": return } if v, ok := d.ns[n.Space]; ok { n.Space = v } else if n.Space == "" { n.Space = d.DefaultSpace } } func (d *Decoder) switchToReader(r io.Reader) { // Get efficient byte at a time reader. // Assume that if reader has its own // ReadByte, it's efficient enough. // Otherwise, use bufio. if rb, ok := r.(io.ByteReader); ok { d.r = rb } else { d.r = bufio.NewReader(r) } } // Parsing state - stack holds old name space translations // and the current set of open elements. The translations to pop when // ending a given tag are *below* it on the stack, which is // more work but forced on us by XML. type stack struct { next *stack kind int name Name ok bool } const ( stkStart = iota stkNs stkEOF ) func (d *Decoder) push(kind int) *stack { s := d.free if s != nil { d.free = s.next } else { s = new(stack) } s.next = d.stk s.kind = kind d.stk = s return s } func (d *Decoder) pop() *stack { s := d.stk if s != nil { d.stk = s.next s.next = d.free d.free = s } return s } // Record that after the current element is finished // (that element is already pushed on the stack) // Token should return EOF until popEOF is called. func (d *Decoder) pushEOF() { // Walk down stack to find Start. // It might not be the top, because there might be stkNs // entries above it. start := d.stk for start.kind != stkStart { start = start.next } // The stkNs entries below a start are associated with that // element too; skip over them. for start.next != nil && start.next.kind == stkNs { start = start.next } s := d.free if s != nil { d.free = s.next } else { s = new(stack) } s.kind = stkEOF s.next = start.next start.next = s } // Undo a pushEOF. // The element must have been finished, so the EOF should be at the top of the stack. func (d *Decoder) popEOF() bool { if d.stk == nil || d.stk.kind != stkEOF { return false } d.pop() return true } // Record that we are starting an element with the given name. func (d *Decoder) pushElement(name Name) { s := d.push(stkStart) s.name = name } // Record that we are changing the value of ns[local]. // The old value is url, ok. func (d *Decoder) pushNs(local string, url string, ok bool) { s := d.push(stkNs) s.name.Local = local s.name.Space = url s.ok = ok } // Creates a SyntaxError with the current line number. func (d *Decoder) syntaxError(msg string) error { return &SyntaxError{Msg: msg, Line: d.line} } // Record that we are ending an element with the given name. // The name must match the record at the top of the stack, // which must be a pushElement record. // After popping the element, apply any undo records from // the stack to restore the name translations that existed // before we saw this element. func (d *Decoder) popElement(t *EndElement) bool { s := d.pop() name := t.Name switch { case s == nil || s.kind != stkStart: d.err = d.syntaxError("unexpected end element </" + name.Local + ">") return false case s.name.Local != name.Local: if !d.Strict { d.needClose = true d.toClose = t.Name t.Name = s.name return true } d.err = d.syntaxError("element <" + s.name.Local + "> closed by </" + name.Local + ">") return false case s.name.Space != name.Space: d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space + "closed by </" + name.Local + "> in space " + name.Space) return false } // Pop stack until a Start or EOF is on the top, undoing the // translations that were associated with the element we just closed. for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF { s := d.pop() if s.ok { d.ns[s.name.Local] = s.name.Space } else { delete(d.ns, s.name.Local) } } return true } // If the top element on the stack is autoclosing and // t is not the end tag, invent the end tag. func (d *Decoder) autoClose(t Token) (Token, bool) { if d.stk == nil || d.stk.kind != stkStart { return nil, false } name := strings.ToLower(d.stk.name.Local) for _, s := range d.AutoClose { if strings.ToLower(s) == name { // This one should be auto closed if t doesn't close it. et, ok := t.(EndElement) if !ok || et.Name.Local != name { return EndElement{d.stk.name}, true } break } } return nil, false } var errRawToken = errors.New("xml: cannot use RawToken from UnmarshalXML method") // RawToken is like Token but does not verify that // start and end elements match and does not translate // name space prefixes to their corresponding URLs. func (d *Decoder) RawToken() (Token, error) { if d.unmarshalDepth > 0 { return nil, errRawToken } return d.rawToken() } func (d *Decoder) rawToken() (Token, error) { if d.err != nil { return nil, d.err } if d.needClose { // The last element we read was self-closing and // we returned just the StartElement half. // Return the EndElement half now. d.needClose = false return EndElement{d.toClose}, nil } b, ok := d.getc() if !ok { return nil, d.err } if b != '<' { // Text section. d.ungetc(b) data := d.text(-1, false) if data == nil { return nil, d.err } return CharData(data), nil } if b, ok = d.mustgetc(); !ok { return nil, d.err } switch b { case '/': // </: End element var name Name if name, ok = d.nsname(); !ok { if d.err == nil { d.err = d.syntaxError("expected element name after </") } return nil, d.err } d.space() if b, ok = d.mustgetc(); !ok { return nil, d.err } if b != '>' { d.err = d.syntaxError("invalid characters between </" + name.Local + " and >") return nil, d.err } return EndElement{name}, nil case '?': // <?: Processing instruction. var target string if target, ok = d.name(); !ok { if d.err == nil { d.err = d.syntaxError("expected target name after <?") } return nil, d.err } d.space() d.buf.Reset() var b0 byte for { if b, ok = d.mustgetc(); !ok { return nil, d.err } d.buf.WriteByte(b) if b0 == '?' && b == '>' { break } b0 = b } data := d.buf.Bytes() data = data[0 : len(data)-2] // chop ?> if target == "xml" { content := string(data) ver := procInst("version", content) if ver != "" && ver != "1.0" { d.err = fmt.Errorf("xml: unsupported version %q; only version 1.0 is supported", ver) return nil, d.err } enc := procInst("encoding", content) if enc != "" && enc != "utf-8" && enc != "UTF-8" { if d.CharsetReader == nil { d.err = fmt.Errorf("xml: encoding %q declared but Decoder.CharsetReader is nil", enc) return nil, d.err } newr, err := d.CharsetReader(enc, d.r.(io.Reader)) if err != nil { d.err = fmt.Errorf("xml: opening charset %q: %v", enc, err) return nil, d.err } if newr == nil { panic("CharsetReader returned a nil Reader for charset " + enc) } d.switchToReader(newr) } } return ProcInst{target, data}, nil case '!': // <!: Maybe comment, maybe CDATA. if b, ok = d.mustgetc(); !ok { return nil, d.err } switch b { case '-': // <!- // Probably <!-- for a comment. if b, ok = d.mustgetc(); !ok { return nil, d.err } if b != '-' { d.err = d.syntaxError("invalid sequence <!- not part of <!--") return nil, d.err } // Look for terminator. d.buf.Reset() var b0, b1 byte for { if b, ok = d.mustgetc(); !ok { return nil, d.err } d.buf.WriteByte(b) if b0 == '-' && b1 == '-' && b == '>' { break } b0, b1 = b1, b } data := d.buf.Bytes() data = data[0 : len(data)-3] // chop --> return Comment(data), nil case '[': // <![ // Probably <![CDATA[. for i := 0; i < 6; i++ { if b, ok = d.mustgetc(); !ok { return nil, d.err } if b != "CDATA["[i] { d.err = d.syntaxError("invalid <![ sequence") return nil, d.err } } // Have <![CDATA[. Read text until ]]>. data := d.text(-1, true) if data == nil { return nil, d.err } return CharData(data), nil } // Probably a directive: <!DOCTYPE ...>, <!ENTITY ...>, etc. // We don't care, but accumulate for caller. Quoted angle // brackets do not count for nesting. d.buf.Reset() d.buf.WriteByte(b) inquote := uint8(0) depth := 0 for { if b, ok = d.mustgetc(); !ok { return nil, d.err } if inquote == 0 && b == '>' && depth == 0 { break } HandleB: d.buf.WriteByte(b) switch { case b == inquote: inquote = 0 case inquote != 0: // in quotes, no special action case b == '\'' || b == '"': inquote = b case b == '>' && inquote == 0: depth-- case b == '<' && inquote == 0: // Look for <!-- to begin comment. s := "!--" for i := 0; i < len(s); i++ { if b, ok = d.mustgetc(); !ok { return nil, d.err } if b != s[i] { for j := 0; j < i; j++ { d.buf.WriteByte(s[j]) } depth++ goto HandleB } } // Remove < that was written above. d.buf.Truncate(d.buf.Len() - 1) // Look for terminator. var b0, b1 byte for { if b, ok = d.mustgetc(); !ok { return nil, d.err } if b0 == '-' && b1 == '-' && b == '>' { break } b0, b1 = b1, b } } } return Directive(d.buf.Bytes()), nil } // Must be an open element like <a href="foo"> d.ungetc(b) var ( name Name empty bool attr []Attr ) if name, ok = d.nsname(); !ok { if d.err == nil { d.err = d.syntaxError("expected element name after <") } return nil, d.err } attr = []Attr{} for { d.space() if b, ok = d.mustgetc(); !ok { return nil, d.err } if b == '/' { empty = true if b, ok = d.mustgetc(); !ok { return nil, d.err } if b != '>' { d.err = d.syntaxError("expected /> in element") return nil, d.err } break } if b == '>' { break } d.ungetc(b) n := len(attr) if n >= cap(attr) { nCap := 2 * cap(attr) if nCap == 0 { nCap = 4 } nattr := make([]Attr, n, nCap) copy(nattr, attr) attr = nattr } attr = attr[0 : n+1] a := &attr[n] if a.Name, ok = d.nsname(); !ok { if d.err == nil { d.err = d.syntaxError("expected attribute name in element") } return nil, d.err } d.space() if b, ok = d.mustgetc(); !ok { return nil, d.err } if b != '=' { if d.Strict { d.err = d.syntaxError("attribute name without = in element") return nil, d.err } else { d.ungetc(b) a.Value = a.Name.Local } } else { d.space() data := d.attrval() if data == nil { return nil, d.err } a.Value = string(data) } } if empty { d.needClose = true d.toClose = name } return StartElement{name, attr}, nil } func (d *Decoder) attrval() []byte { b, ok := d.mustgetc() if !ok { return nil } // Handle quoted attribute values if b == '"' || b == '\'' { return d.text(int(b), false) } // Handle unquoted attribute values for strict parsers if d.Strict { d.err = d.syntaxError("unquoted or missing attribute value in element") return nil } // Handle unquoted attribute values for unstrict parsers d.ungetc(b) d.buf.Reset() for { b, ok = d.mustgetc() if !ok { return nil } // http://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.2 if 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' || '0' <= b && b <= '9' || b == '_' || b == ':' || b == '-' { d.buf.WriteByte(b) } else { d.ungetc(b) break } } return d.buf.Bytes() } // Skip spaces if any func (d *Decoder) space() { for { b, ok := d.getc() if !ok { return } switch b { case ' ', '\r', '\n', '\t': default: d.ungetc(b) return } } } // Read a single byte. // If there is no byte to read, return ok==false // and leave the error in d.err. // Maintain line number. func (d *Decoder) getc() (b byte, ok bool) { if d.err != nil { return 0, false } if d.nextByte >= 0 { b = byte(d.nextByte) d.nextByte = -1 } else { b, d.err = d.r.ReadByte() if d.err != nil { return 0, false } if d.saved != nil { d.saved.WriteByte(b) } } if b == '\n' { d.line++ } d.offset++ return b, true } // InputOffset returns the input stream byte offset of the current decoder position. // The offset gives the location of the end of the most recently returned token // and the beginning of the next token. func (d *Decoder) InputOffset() int64 { return d.offset } // Return saved offset. // If we did ungetc (nextByte >= 0), have to back up one. func (d *Decoder) savedOffset() int { n := d.saved.Len() if d.nextByte >= 0 { n-- } return n } // Must read a single byte. // If there is no byte to read, // set d.err to SyntaxError("unexpected EOF") // and return ok==false func (d *Decoder) mustgetc() (b byte, ok bool) { if b, ok = d.getc(); !ok { if d.err == io.EOF { d.err = d.syntaxError("unexpected EOF") } } return } // Unread a single byte. func (d *Decoder) ungetc(b byte) { if b == '\n' { d.line-- } d.nextByte = int(b) d.offset-- } var entity = map[string]rune{ "lt": '<', "gt": '>', "amp": '&', "apos": '\'', "quot": '"', } // Read plain text section (XML calls it character data). // If quote >= 0, we are in a quoted string and need to find the matching quote. // If cdata == true, we are in a <![CDATA[ section and need to find ]]>. // On failure return nil and leave the error in d.err. func (d *Decoder) text(quote int, cdata bool) []byte { var b0, b1 byte var trunc int d.buf.Reset() Input: for { b, ok := d.getc() if !ok { if cdata { if d.err == io.EOF { d.err = d.syntaxError("unexpected EOF in CDATA section") } return nil } break Input } // <![CDATA[ section ends with ]]>. // It is an error for ]]> to appear in ordinary text. if b0 == ']' && b1 == ']' && b == '>' { if cdata { trunc = 2 break Input } d.err = d.syntaxError("unescaped ]]> not in CDATA section") return nil } // Stop reading text if we see a <. if b == '<' && !cdata { if quote >= 0 { d.err = d.syntaxError("unescaped < inside quoted string") return nil } d.ungetc('<') break Input } if quote >= 0 && b == byte(quote) { break Input } if b == '&' && !cdata { // Read escaped character expression up to semicolon. // XML in all its glory allows a document to define and use // its own character names with <!ENTITY ...> directives. // Parsers are required to recognize lt, gt, amp, apos, and quot // even if they have not been declared. before := d.buf.Len() d.buf.WriteByte('&') var ok bool var text string var haveText bool if b, ok = d.mustgetc(); !ok { return nil } if b == '#' { d.buf.WriteByte(b) if b, ok = d.mustgetc(); !ok { return nil } base := 10 if b == 'x' { base = 16 d.buf.WriteByte(b) if b, ok = d.mustgetc(); !ok { return nil } } start := d.buf.Len() for '0' <= b && b <= '9' || base == 16 && 'a' <= b && b <= 'f' || base == 16 && 'A' <= b && b <= 'F' { d.buf.WriteByte(b) if b, ok = d.mustgetc(); !ok { return nil } } if b != ';' { d.ungetc(b) } else { s := string(d.buf.Bytes()[start:]) d.buf.WriteByte(';') n, err := strconv.ParseUint(s, base, 64) if err == nil && n <= unicode.MaxRune { text = string(rune(n)) haveText = true } } } else { d.ungetc(b) if !d.readName() { if d.err != nil { return nil } ok = false } if b, ok = d.mustgetc(); !ok { return nil } if b != ';' { d.ungetc(b) } else { name := d.buf.Bytes()[before+1:] d.buf.WriteByte(';') if isName(name) { s := string(name) if r, ok := entity[s]; ok { text = string(r) haveText = true } else if d.Entity != nil { text, haveText = d.Entity[s] } } } } if haveText { d.buf.Truncate(before) d.buf.Write([]byte(text)) b0, b1 = 0, 0 continue Input } if !d.Strict { b0, b1 = 0, 0 continue Input } ent := string(d.buf.Bytes()[before:]) if ent[len(ent)-1] != ';' { ent += " (no semicolon)" } d.err = d.syntaxError("invalid character entity " + ent) return nil } // We must rewrite unescaped \r and \r\n into \n. if b == '\r' { d.buf.WriteByte('\n') } else if b1 == '\r' && b == '\n' { // Skip \r\n--we already wrote \n. } else { d.buf.WriteByte(b) } b0, b1 = b1, b } data := d.buf.Bytes() data = data[0 : len(data)-trunc] // Inspect each rune for being a disallowed character. buf := data for len(buf) > 0 { r, size := utf8.DecodeRune(buf) if r == utf8.RuneError && size == 1 { d.err = d.syntaxError("invalid UTF-8") return nil } buf = buf[size:] if !isInCharacterRange(r) { d.err = d.syntaxError(fmt.Sprintf("illegal character code %U", r)) return nil } } return data } // Decide whether the given rune is in the XML Character Range, per // the Char production of http://www.xml.com/axml/testaxml.htm, // Section 2.2 Characters. func isInCharacterRange(r rune) (inrange bool) { return r == 0x09 || r == 0x0A || r == 0x0D || r >= 0x20 && r <= 0xDF77 || r >= 0xE000 && r <= 0xFFFD || r >= 0x10000 && r <= 0x10FFFF } // Get name space name: name with a : stuck in the middle. // The part before the : is the name space identifier. func (d *Decoder) nsname() (name Name, ok bool) { s, ok := d.name() if !ok { return } i := strings.Index(s, ":") if i < 0 { name.Local = s } else { name.Space = s[0:i] name.Local = s[i+1:] } return name, true } // Get name: /first(first|second)*/ // Do not set d.err if the name is missing (unless unexpected EOF is received): // let the caller provide better context. func (d *Decoder) name() (s string, ok bool) { d.buf.Reset() if !d.readName() { return "", false } // Now we check the characters. b := d.buf.Bytes() if !isName(b) { d.err = d.syntaxError("invalid XML name: " + string(b)) return "", false } return string(b), true } // Read a name and append its bytes to d.buf. // The name is delimited by any single-byte character not valid in names. // All multi-byte characters are accepted; the caller must check their validity. func (d *Decoder) readName() (ok bool) { var b byte if b, ok = d.mustgetc(); !ok { return } if b < utf8.RuneSelf && !isNameByte(b) { d.ungetc(b) return false } d.buf.WriteByte(b) for { if b, ok = d.mustgetc(); !ok { return } if b < utf8.RuneSelf && !isNameByte(b) { d.ungetc(b) break } d.buf.WriteByte(b) } return true } func isNameByte(c byte) bool { return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c == ':' || c == '.' || c == '-' } func isName(s []byte) bool { if len(s) == 0 { return false } c, n := utf8.DecodeRune(s) if c == utf8.RuneError && n == 1 { return false } if !unicode.Is(first, c) { return false } for n < len(s) { s = s[n:] c, n = utf8.DecodeRune(s) if c == utf8.RuneError && n == 1 { return false } if !unicode.Is(first, c) && !unicode.Is(second, c) { return false } } return true } func isNameString(s string) bool { if len(s) == 0 { return false } c, n := utf8.DecodeRuneInString(s) if c == utf8.RuneError && n == 1 { return false } if !unicode.Is(first, c) { return false } for n < len(s) { s = s[n:] c, n = utf8.DecodeRuneInString(s) if c == utf8.RuneError && n == 1 { return false } if !unicode.Is(first, c) && !unicode.Is(second, c) { return false } } return true } // These tables were generated by cut and paste from Appendix B of // the XML spec at http://www.xml.com/axml/testaxml.htm // and then reformatting. First corresponds to (Letter | '_' | ':') // and second corresponds to NameChar. var first = &unicode.RangeTable{ R16: []unicode.Range16{ {0x003A, 0x003A, 1}, {0x0041, 0x005A, 1}, {0x005F, 0x005F, 1}, {0x0061, 0x007A, 1}, {0x00C0, 0x00D6, 1}, {0x00D8, 0x00F6, 1}, {0x00F8, 0x00FF, 1}, {0x0100, 0x0131, 1}, {0x0134, 0x013E, 1}, {0x0141, 0x0148, 1}, {0x014A, 0x017E, 1}, {0x0180, 0x01C3, 1}, {0x01CD, 0x01F0, 1}, {0x01F4, 0x01F5, 1}, {0x01FA, 0x0217, 1}, {0x0250, 0x02A8, 1}, {0x02BB, 0x02C1, 1}, {0x0386, 0x0386, 1}, {0x0388, 0x038A, 1}, {0x038C, 0x038C, 1}, {0x038E, 0x03A1, 1}, {0x03A3, 0x03CE, 1}, {0x03D0, 0x03D6, 1}, {0x03DA, 0x03E0, 2}, {0x03E2, 0x03F3, 1}, {0x0401, 0x040C, 1}, {0x040E, 0x044F, 1}, {0x0451, 0x045C, 1}, {0x045E, 0x0481, 1}, {0x0490, 0x04C4, 1}, {0x04C7, 0x04C8, 1}, {0x04CB, 0x04CC, 1}, {0x04D0, 0x04EB, 1}, {0x04EE, 0x04F5, 1}, {0x04F8, 0x04F9, 1}, {0x0531, 0x0556, 1}, {0x0559, 0x0559, 1}, {0x0561, 0x0586, 1}, {0x05D0, 0x05EA, 1}, {0x05F0, 0x05F2, 1}, {0x0621, 0x063A, 1}, {0x0641, 0x064A, 1}, {0x0671, 0x06B7, 1}, {0x06BA, 0x06BE, 1}, {0x06C0, 0x06CE, 1}, {0x06D0, 0x06D3, 1}, {0x06D5, 0x06D5, 1}, {0x06E5, 0x06E6, 1}, {0x0905, 0x0939, 1}, {0x093D, 0x093D, 1}, {0x0958, 0x0961, 1}, {0x0985, 0x098C, 1}, {0x098F, 0x0990, 1}, {0x0993, 0x09A8, 1}, {0x09AA, 0x09B0, 1}, {0x09B2, 0x09B2, 1}, {0x09B6, 0x09B9, 1}, {0x09DC, 0x09DD, 1}, {0x09DF, 0x09E1, 1}, {0x09F0, 0x09F1, 1}, {0x0A05, 0x0A0A, 1}, {0x0A0F, 0x0A10, 1}, {0x0A13, 0x0A28, 1}, {0x0A2A, 0x0A30, 1}, {0x0A32, 0x0A33, 1}, {0x0A35, 0x0A36, 1}, {0x0A38, 0x0A39, 1}, {0x0A59, 0x0A5C, 1}, {0x0A5E, 0x0A5E, 1}, {0x0A72, 0x0A74, 1}, {0x0A85, 0x0A8B, 1}, {0x0A8D, 0x0A8D, 1}, {0x0A8F, 0x0A91, 1}, {0x0A93, 0x0AA8, 1}, {0x0AAA, 0x0AB0, 1}, {0x0AB2, 0x0AB3, 1}, {0x0AB5, 0x0AB9, 1}, {0x0ABD, 0x0AE0, 0x23}, {0x0B05, 0x0B0C, 1}, {0x0B0F, 0x0B10, 1}, {0x0B13, 0x0B28, 1}, {0x0B2A, 0x0B30, 1}, {0x0B32, 0x0B33, 1}, {0x0B36, 0x0B39, 1}, {0x0B3D, 0x0B3D, 1}, {0x0B5C, 0x0B5D, 1}, {0x0B5F, 0x0B61, 1}, {0x0B85, 0x0B8A, 1}, {0x0B8E, 0x0B90, 1}, {0x0B92, 0x0B95, 1}, {0x0B99, 0x0B9A, 1}, {0x0B9C, 0x0B9C, 1}, {0x0B9E, 0x0B9F, 1}, {0x0BA3, 0x0BA4, 1}, {0x0BA8, 0x0BAA, 1}, {0x0BAE, 0x0BB5, 1}, {0x0BB7, 0x0BB9, 1}, {0x0C05, 0x0C0C, 1}, {0x0C0E, 0x0C10, 1}, {0x0C12, 0x0C28, 1}, {0x0C2A, 0x0C33, 1}, {0x0C35, 0x0C39, 1}, {0x0C60, 0x0C61, 1}, {0x0C85, 0x0C8C, 1}, {0x0C8E, 0x0C90, 1}, {0x0C92, 0x0CA8, 1}, {0x0CAA, 0x0CB3, 1}, {0x0CB5, 0x0CB9, 1}, {0x0CDE, 0x0CDE, 1}, {0x0CE0, 0x0CE1, 1}, {0x0D05, 0x0D0C, 1}, {0x0D0E, 0x0D10, 1}, {0x0D12, 0x0D28, 1}, {0x0D2A, 0x0D39, 1}, {0x0D60, 0x0D61, 1}, {0x0E01, 0x0E2E, 1}, {0x0E30, 0x0E30, 1}, {0x0E32, 0x0E33, 1}, {0x0E40, 0x0E45, 1}, {0x0E81, 0x0E82, 1}, {0x0E84, 0x0E84, 1}, {0x0E87, 0x0E88, 1}, {0x0E8A, 0x0E8D, 3}, {0x0E94, 0x0E97, 1}, {0x0E99, 0x0E9F, 1}, {0x0EA1, 0x0EA3, 1}, {0x0EA5, 0x0EA7, 2}, {0x0EAA, 0x0EAB, 1}, {0x0EAD, 0x0EAE, 1}, {0x0EB0, 0x0EB0, 1}, {0x0EB2, 0x0EB3, 1}, {0x0EBD, 0x0EBD, 1}, {0x0EC0, 0x0EC4, 1}, {0x0F40, 0x0F47, 1}, {0x0F49, 0x0F69, 1}, {0x10A0, 0x10C5, 1}, {0x10D0, 0x10F6, 1}, {0x1100, 0x1100, 1}, {0x1102, 0x1103, 1}, {0x1105, 0x1107, 1}, {0x1109, 0x1109, 1}, {0x110B, 0x110C, 1}, {0x110E, 0x1112, 1}, {0x113C, 0x1140, 2}, {0x114C, 0x1150, 2}, {0x1154, 0x1155, 1}, {0x1159, 0x1159, 1}, {0x115F, 0x1161, 1}, {0x1163, 0x1169, 2}, {0x116D, 0x116E, 1}, {0x1172, 0x1173, 1}, {0x1175, 0x119E, 0x119E - 0x1175}, {0x11A8, 0x11AB, 0x11AB - 0x11A8}, {0x11AE, 0x11AF, 1}, {0x11B7, 0x11B8, 1}, {0x11BA, 0x11BA, 1}, {0x11BC, 0x11C2, 1}, {0x11EB, 0x11F0, 0x11F0 - 0x11EB}, {0x11F9, 0x11F9, 1}, {0x1E00, 0x1E9B, 1}, {0x1EA0, 0x1EF9, 1}, {0x1F00, 0x1F15, 1}, {0x1F18, 0x1F1D, 1}, {0x1F20, 0x1F45, 1}, {0x1F48, 0x1F4D, 1}, {0x1F50, 0x1F57, 1}, {0x1F59, 0x1F5B, 0x1F5B - 0x1F59}, {0x1F5D, 0x1F5D, 1}, {0x1F5F, 0x1F7D, 1}, {0x1F80, 0x1FB4, 1}, {0x1FB6, 0x1FBC, 1}, {0x1FBE, 0x1FBE, 1}, {0x1FC2, 0x1FC4, 1}, {0x1FC6, 0x1FCC, 1}, {0x1FD0, 0x1FD3, 1}, {0x1FD6, 0x1FDB, 1}, {0x1FE0, 0x1FEC, 1}, {0x1FF2, 0x1FF4, 1}, {0x1FF6, 0x1FFC, 1}, {0x2126, 0x2126, 1}, {0x212A, 0x212B, 1}, {0x212E, 0x212E, 1}, {0x2180, 0x2182, 1}, {0x3007, 0x3007, 1}, {0x3021, 0x3029, 1}, {0x3041, 0x3094, 1}, {0x30A1, 0x30FA, 1}, {0x3105, 0x312C, 1}, {0x4E00, 0x9FA5, 1}, {0xAC00, 0xD7A3, 1}, }, } var second = &unicode.RangeTable{ R16: []unicode.Range16{ {0x002D, 0x002E, 1}, {0x0030, 0x0039, 1}, {0x00B7, 0x00B7, 1}, {0x02D0, 0x02D1, 1}, {0x0300, 0x0345, 1}, {0x0360, 0x0361, 1}, {0x0387, 0x0387, 1}, {0x0483, 0x0486, 1}, {0x0591, 0x05A1, 1}, {0x05A3, 0x05B9, 1}, {0x05BB, 0x05BD, 1}, {0x05BF, 0x05BF, 1}, {0x05C1, 0x05C2, 1}, {0x05C4, 0x0640, 0x0640 - 0x05C4}, {0x064B, 0x0652, 1}, {0x0660, 0x0669, 1}, {0x0670, 0x0670, 1}, {0x06D6, 0x06DC, 1}, {0x06DD, 0x06DF, 1}, {0x06E0, 0x06E4, 1}, {0x06E7, 0x06E8, 1}, {0x06EA, 0x06ED, 1}, {0x06F0, 0x06F9, 1}, {0x0901, 0x0903, 1}, {0x093C, 0x093C, 1}, {0x093E, 0x094C, 1}, {0x094D, 0x094D, 1}, {0x0951, 0x0954, 1}, {0x0962, 0x0963, 1}, {0x0966, 0x096F, 1}, {0x0981, 0x0983, 1}, {0x09BC, 0x09BC, 1}, {0x09BE, 0x09BF, 1}, {0x09C0, 0x09C4, 1}, {0x09C7, 0x09C8, 1}, {0x09CB, 0x09CD, 1}, {0x09D7, 0x09D7, 1}, {0x09E2, 0x09E3, 1}, {0x09E6, 0x09EF, 1}, {0x0A02, 0x0A3C, 0x3A}, {0x0A3E, 0x0A3F, 1}, {0x0A40, 0x0A42, 1}, {0x0A47, 0x0A48, 1}, {0x0A4B, 0x0A4D, 1}, {0x0A66, 0x0A6F, 1}, {0x0A70, 0x0A71, 1}, {0x0A81, 0x0A83, 1}, {0x0ABC, 0x0ABC, 1}, {0x0ABE, 0x0AC5, 1}, {0x0AC7, 0x0AC9, 1}, {0x0ACB, 0x0ACD, 1}, {0x0AE6, 0x0AEF, 1}, {0x0B01, 0x0B03, 1}, {0x0B3C, 0x0B3C, 1}, {0x0B3E, 0x0B43, 1}, {0x0B47, 0x0B48, 1}, {0x0B4B, 0x0B4D, 1}, {0x0B56, 0x0B57, 1}, {0x0B66, 0x0B6F, 1}, {0x0B82, 0x0B83, 1}, {0x0BBE, 0x0BC2, 1}, {0x0BC6, 0x0BC8, 1}, {0x0BCA, 0x0BCD, 1}, {0x0BD7, 0x0BD7, 1}, {0x0BE7, 0x0BEF, 1}, {0x0C01, 0x0C03, 1}, {0x0C3E, 0x0C44, 1}, {0x0C46, 0x0C48, 1}, {0x0C4A, 0x0C4D, 1}, {0x0C55, 0x0C56, 1}, {0x0C66, 0x0C6F, 1}, {0x0C82, 0x0C83, 1}, {0x0CBE, 0x0CC4, 1}, {0x0CC6, 0x0CC8, 1}, {0x0CCA, 0x0CCD, 1}, {0x0CD5, 0x0CD6, 1}, {0x0CE6, 0x0CEF, 1}, {0x0D02, 0x0D03, 1}, {0x0D3E, 0x0D43, 1}, {0x0D46, 0x0D48, 1}, {0x0D4A, 0x0D4D, 1}, {0x0D57, 0x0D57, 1}, {0x0D66, 0x0D6F, 1}, {0x0E31, 0x0E31, 1}, {0x0E34, 0x0E3A, 1}, {0x0E46, 0x0E46, 1}, {0x0E47, 0x0E4E, 1}, {0x0E50, 0x0E59, 1}, {0x0EB1, 0x0EB1, 1}, {0x0EB4, 0x0EB9, 1}, {0x0EBB, 0x0EBC, 1}, {0x0EC6, 0x0EC6, 1}, {0x0EC8, 0x0ECD, 1}, {0x0ED0, 0x0ED9, 1}, {0x0F18, 0x0F19, 1}, {0x0F20, 0x0F29, 1}, {0x0F35, 0x0F39, 2}, {0x0F3E, 0x0F3F, 1}, {0x0F71, 0x0F84, 1}, {0x0F86, 0x0F8B, 1}, {0x0F90, 0x0F95, 1}, {0x0F97, 0x0F97, 1}, {0x0F99, 0x0FAD, 1}, {0x0FB1, 0x0FB7, 1}, {0x0FB9, 0x0FB9, 1}, {0x20D0, 0x20DC, 1}, {0x20E1, 0x3005, 0x3005 - 0x20E1}, {0x302A, 0x302F, 1}, {0x3031, 0x3035, 1}, {0x3099, 0x309A, 1}, {0x309D, 0x309E, 1}, {0x30FC, 0x30FE, 1}, }, } // HTMLEntity is an entity map containing translations for the // standard HTML entity characters. var HTMLEntity = htmlEntity var htmlEntity = map[string]string{ /* hget http://www.w3.org/TR/html4/sgml/entities.html | ssam ' ,y /\&gt;/ x/\&lt;(.|\n)+/ s/\n/ /g ,x v/^\&lt;!ENTITY/d ,s/\&lt;!ENTITY ([^ ]+) .*U\+([0-9A-F][0-9A-F][0-9A-F][0-9A-F]) .+/ "\1": "\\u\2",/g ' */ "nbsp": "\u00A0", "iexcl": "\u00A1", "cent": "\u00A2", "pound": "\u00A3", "curren": "\u00A4", "yen": "\u00A5", "brvbar": "\u00A6", "sect": "\u00A7", "uml": "\u00A8", "copy": "\u00A9", "ordf": "\u00AA", "laquo": "\u00AB", "not": "\u00AC", "shy": "\u00AD", "reg": "\u00AE", "macr": "\u00AF", "deg": "\u00B0", "plusmn": "\u00B1", "sup2": "\u00B2", "sup3": "\u00B3", "acute": "\u00B4", "micro": "\u00B5", "para": "\u00B6", "middot": "\u00B7", "cedil": "\u00B8", "sup1": "\u00B9", "ordm": "\u00BA", "raquo": "\u00BB", "frac14": "\u00BC", "frac12": "\u00BD", "frac34": "\u00BE", "iquest": "\u00BF", "Agrave": "\u00C0", "Aacute": "\u00C1", "Acirc": "\u00C2", "Atilde": "\u00C3", "Auml": "\u00C4", "Aring": "\u00C5", "AElig": "\u00C6", "Ccedil": "\u00C7", "Egrave": "\u00C8", "Eacute": "\u00C9", "Ecirc": "\u00CA", "Euml": "\u00CB", "Igrave": "\u00CC", "Iacute": "\u00CD", "Icirc": "\u00CE", "Iuml": "\u00CF", "ETH": "\u00D0", "Ntilde": "\u00D1", "Ograve": "\u00D2", "Oacute": "\u00D3", "Ocirc": "\u00D4", "Otilde": "\u00D5", "Ouml": "\u00D6", "times": "\u00D7", "Oslash": "\u00D8", "Ugrave": "\u00D9", "Uacute": "\u00DA", "Ucirc": "\u00DB", "Uuml": "\u00DC", "Yacute": "\u00DD", "THORN": "\u00DE", "szlig": "\u00DF", "agrave": "\u00E0", "aacute": "\u00E1", "acirc": "\u00E2", "atilde": "\u00E3", "auml": "\u00E4", "aring": "\u00E5", "aelig": "\u00E6", "ccedil": "\u00E7", "egrave": "\u00E8", "eacute": "\u00E9", "ecirc": "\u00EA", "euml": "\u00EB", "igrave": "\u00EC", "iacute": "\u00ED", "icirc": "\u00EE", "iuml": "\u00EF", "eth": "\u00F0", "ntilde": "\u00F1", "ograve": "\u00F2", "oacute": "\u00F3", "ocirc": "\u00F4", "otilde": "\u00F5", "ouml": "\u00F6", "divide": "\u00F7", "oslash": "\u00F8", "ugrave": "\u00F9", "uacute": "\u00FA", "ucirc": "\u00FB", "uuml": "\u00FC", "yacute": "\u00FD", "thorn": "\u00FE", "yuml": "\u00FF", "fnof": "\u0192", "Alpha": "\u0391", "Beta": "\u0392", "Gamma": "\u0393", "Delta": "\u0394", "Epsilon": "\u0395", "Zeta": "\u0396", "Eta": "\u0397", "Theta": "\u0398", "Iota": "\u0399", "Kappa": "\u039A", "Lambda": "\u039B", "Mu": "\u039C", "Nu": "\u039D", "Xi": "\u039E", "Omicron": "\u039F", "Pi": "\u03A0", "Rho": "\u03A1", "Sigma": "\u03A3", "Tau": "\u03A4", "Upsilon": "\u03A5", "Phi": "\u03A6", "Chi": "\u03A7", "Psi": "\u03A8", "Omega": "\u03A9", "alpha": "\u03B1", "beta": "\u03B2", "gamma": "\u03B3", "delta": "\u03B4", "epsilon": "\u03B5", "zeta": "\u03B6", "eta": "\u03B7", "theta": "\u03B8", "iota": "\u03B9", "kappa": "\u03BA", "lambda": "\u03BB", "mu": "\u03BC", "nu": "\u03BD", "xi": "\u03BE", "omicron": "\u03BF", "pi": "\u03C0", "rho": "\u03C1", "sigmaf": "\u03C2", "sigma": "\u03C3", "tau": "\u03C4", "upsilon": "\u03C5", "phi": "\u03C6", "chi": "\u03C7", "psi": "\u03C8", "omega": "\u03C9", "thetasym": "\u03D1", "upsih": "\u03D2", "piv": "\u03D6", "bull": "\u2022", "hellip": "\u2026", "prime": "\u2032", "Prime": "\u2033", "oline": "\u203E", "frasl": "\u2044", "weierp": "\u2118", "image": "\u2111", "real": "\u211C", "trade": "\u2122", "alefsym": "\u2135", "larr": "\u2190", "uarr": "\u2191", "rarr": "\u2192", "darr": "\u2193", "harr": "\u2194", "crarr": "\u21B5", "lArr": "\u21D0", "uArr": "\u21D1", "rArr": "\u21D2", "dArr": "\u21D3", "hArr": "\u21D4", "forall": "\u2200", "part": "\u2202", "exist": "\u2203", "empty": "\u2205", "nabla": "\u2207", "isin": "\u2208", "notin": "\u2209", "ni": "\u220B", "prod": "\u220F", "sum": "\u2211", "minus": "\u2212", "lowast": "\u2217", "radic": "\u221A", "prop": "\u221D", "infin": "\u221E", "ang": "\u2220", "and": "\u2227", "or": "\u2228", "cap": "\u2229", "cup": "\u222A", "int": "\u222B", "there4": "\u2234", "sim": "\u223C", "cong": "\u2245", "asymp": "\u2248", "ne": "\u2260", "equiv": "\u2261", "le": "\u2264", "ge": "\u2265", "sub": "\u2282", "sup": "\u2283", "nsub": "\u2284", "sube": "\u2286", "supe": "\u2287", "oplus": "\u2295", "otimes": "\u2297", "perp": "\u22A5", "sdot": "\u22C5", "lceil": "\u2308", "rceil": "\u2309", "lfloor": "\u230A", "rfloor": "\u230B", "lang": "\u2329", "rang": "\u232A", "loz": "\u25CA", "spades": "\u2660", "clubs": "\u2663", "hearts": "\u2665", "diams": "\u2666", "quot": "\u0022", "amp": "\u0026", "lt": "\u003C", "gt": "\u003E", "OElig": "\u0152", "oelig": "\u0153", "Scaron": "\u0160", "scaron": "\u0161", "Yuml": "\u0178", "circ": "\u02C6", "tilde": "\u02DC", "ensp": "\u2002", "emsp": "\u2003", "thinsp": "\u2009", "zwnj": "\u200C", "zwj": "\u200D", "lrm": "\u200E", "rlm": "\u200F", "ndash": "\u2013", "mdash": "\u2014", "lsquo": "\u2018", "rsquo": "\u2019", "sbquo": "\u201A", "ldquo": "\u201C", "rdquo": "\u201D", "bdquo": "\u201E", "dagger": "\u2020", "Dagger": "\u2021", "permil": "\u2030", "lsaquo": "\u2039", "rsaquo": "\u203A", "euro": "\u20AC", } // HTMLAutoClose is the set of HTML elements that // should be considered to close automatically. var HTMLAutoClose = htmlAutoClose var htmlAutoClose = []string{ /* hget http://www.w3.org/TR/html4/loose.dtd | 9 sed -n 's/<!ELEMENT ([^ ]*) +- O EMPTY.+/ "\1",/p' | tr A-Z a-z */ "basefont", "br", "area", "link", "img", "param", "hr", "input", "col", "frame", "isindex", "base", "meta", } var ( esc_quot = []byte("&#34;") // shorter than "&quot;" esc_apos = []byte("&#39;") // shorter than "&apos;" esc_amp = []byte("&amp;") esc_lt = []byte("&lt;") esc_gt = []byte("&gt;") esc_tab = []byte("&#x9;") esc_nl = []byte("&#xA;") esc_cr = []byte("&#xD;") esc_fffd = []byte("\uFFFD") // Unicode replacement character ) // EscapeText writes to w the properly escaped XML equivalent // of the plain text data s. func EscapeText(w io.Writer, s []byte) error { return escapeText(w, s, true) } // escapeText writes to w the properly escaped XML equivalent // of the plain text data s. If escapeNewline is true, newline // characters will be escaped. func escapeText(w io.Writer, s []byte, escapeNewline bool) error { var esc []byte last := 0 for i := 0; i < len(s); { r, width := utf8.DecodeRune(s[i:]) i += width switch r { case '"': esc = esc_quot case '\'': esc = esc_apos case '&': esc = esc_amp case '<': esc = esc_lt case '>': esc = esc_gt case '\t': esc = esc_tab case '\n': if !escapeNewline { continue } esc = esc_nl case '\r': esc = esc_cr default: if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { esc = esc_fffd break } continue } if _, err := w.Write(s[last : i-width]); err != nil { return err } if _, err := w.Write(esc); err != nil { return err } last = i } if _, err := w.Write(s[last:]); err != nil { return err } return nil } // EscapeString writes to p the properly escaped XML equivalent // of the plain text data s. func (p *printer) EscapeString(s string) { var esc []byte last := 0 for i := 0; i < len(s); { r, width := utf8.DecodeRuneInString(s[i:]) i += width switch r { case '"': esc = esc_quot case '\'': esc = esc_apos case '&': esc = esc_amp case '<': esc = esc_lt case '>': esc = esc_gt case '\t': esc = esc_tab case '\n': esc = esc_nl case '\r': esc = esc_cr default: if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { esc = esc_fffd break } continue } p.WriteString(s[last : i-width]) p.Write(esc) last = i } p.WriteString(s[last:]) } // Escape is like EscapeText but omits the error return value. // It is provided for backwards compatibility with Go 1.0. // Code targeting Go 1.1 or later should use EscapeText. func Escape(w io.Writer, s []byte) { EscapeText(w, s) } // procInst parses the `param="..."` or `param='...'` // value out of the provided string, returning "" if not found. func procInst(param, s string) string { // TODO: this parsing is somewhat lame and not exact. // It works for all actual cases, though. param = param + "=" idx := strings.Index(s, param) if idx == -1 { return "" } v := s[idx+len(param):] if v == "" { return "" } if v[0] != '\'' && v[0] != '"' { return "" } idx = strings.IndexRune(v[1:], rune(v[0])) if idx == -1 { return "" } return v[1 : idx+1] }
net/webdav/internal/xml/xml.go/0
{ "file_path": "net/webdav/internal/xml/xml.go", "repo_id": "net", "token_count": 22939 }
636
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket // This file implements a protocol of hybi draft. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 import ( "bufio" "bytes" "crypto/rand" "crypto/sha1" "encoding/base64" "encoding/binary" "fmt" "io" "net/http" "net/url" "strings" ) const ( websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" closeStatusNormal = 1000 closeStatusGoingAway = 1001 closeStatusProtocolError = 1002 closeStatusUnsupportedData = 1003 closeStatusFrameTooLarge = 1004 closeStatusNoStatusRcvd = 1005 closeStatusAbnormalClosure = 1006 closeStatusBadMessageData = 1007 closeStatusPolicyViolation = 1008 closeStatusTooBigData = 1009 closeStatusExtensionMismatch = 1010 maxControlFramePayloadLength = 125 ) var ( ErrBadMaskingKey = &ProtocolError{"bad masking key"} ErrBadPongMessage = &ProtocolError{"bad pong message"} ErrBadClosingStatus = &ProtocolError{"bad closing status"} ErrUnsupportedExtensions = &ProtocolError{"unsupported extensions"} ErrNotImplemented = &ProtocolError{"not implemented"} handshakeHeader = map[string]bool{ "Host": true, "Upgrade": true, "Connection": true, "Sec-Websocket-Key": true, "Sec-Websocket-Origin": true, "Sec-Websocket-Version": true, "Sec-Websocket-Protocol": true, "Sec-Websocket-Accept": true, } ) // A hybiFrameHeader is a frame header as defined in hybi draft. type hybiFrameHeader struct { Fin bool Rsv [3]bool OpCode byte Length int64 MaskingKey []byte data *bytes.Buffer } // A hybiFrameReader is a reader for hybi frame. type hybiFrameReader struct { reader io.Reader header hybiFrameHeader pos int64 length int } func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) { n, err = frame.reader.Read(msg) if frame.header.MaskingKey != nil { for i := 0; i < n; i++ { msg[i] = msg[i] ^ frame.header.MaskingKey[frame.pos%4] frame.pos++ } } return n, err } func (frame *hybiFrameReader) PayloadType() byte { return frame.header.OpCode } func (frame *hybiFrameReader) HeaderReader() io.Reader { if frame.header.data == nil { return nil } if frame.header.data.Len() == 0 { return nil } return frame.header.data } func (frame *hybiFrameReader) TrailerReader() io.Reader { return nil } func (frame *hybiFrameReader) Len() (n int) { return frame.length } // A hybiFrameReaderFactory creates new frame reader based on its frame type. type hybiFrameReaderFactory struct { *bufio.Reader } // NewFrameReader reads a frame header from the connection, and creates new reader for the frame. // See Section 5.2 Base Framing protocol for detail. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2 func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) { hybiFrame := new(hybiFrameReader) frame = hybiFrame var header []byte var b byte // First byte. FIN/RSV1/RSV2/RSV3/OpCode(4bits) b, err = buf.ReadByte() if err != nil { return } header = append(header, b) hybiFrame.header.Fin = ((header[0] >> 7) & 1) != 0 for i := 0; i < 3; i++ { j := uint(6 - i) hybiFrame.header.Rsv[i] = ((header[0] >> j) & 1) != 0 } hybiFrame.header.OpCode = header[0] & 0x0f // Second byte. Mask/Payload len(7bits) b, err = buf.ReadByte() if err != nil { return } header = append(header, b) mask := (b & 0x80) != 0 b &= 0x7f lengthFields := 0 switch { case b <= 125: // Payload length 7bits. hybiFrame.header.Length = int64(b) case b == 126: // Payload length 7+16bits lengthFields = 2 case b == 127: // Payload length 7+64bits lengthFields = 8 } for i := 0; i < lengthFields; i++ { b, err = buf.ReadByte() if err != nil { return } if lengthFields == 8 && i == 0 { // MSB must be zero when 7+64 bits b &= 0x7f } header = append(header, b) hybiFrame.header.Length = hybiFrame.header.Length*256 + int64(b) } if mask { // Masking key. 4 bytes. for i := 0; i < 4; i++ { b, err = buf.ReadByte() if err != nil { return } header = append(header, b) hybiFrame.header.MaskingKey = append(hybiFrame.header.MaskingKey, b) } } hybiFrame.reader = io.LimitReader(buf.Reader, hybiFrame.header.Length) hybiFrame.header.data = bytes.NewBuffer(header) hybiFrame.length = len(header) + int(hybiFrame.header.Length) return } // A HybiFrameWriter is a writer for hybi frame. type hybiFrameWriter struct { writer *bufio.Writer header *hybiFrameHeader } func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) { var header []byte var b byte if frame.header.Fin { b |= 0x80 } for i := 0; i < 3; i++ { if frame.header.Rsv[i] { j := uint(6 - i) b |= 1 << j } } b |= frame.header.OpCode header = append(header, b) if frame.header.MaskingKey != nil { b = 0x80 } else { b = 0 } lengthFields := 0 length := len(msg) switch { case length <= 125: b |= byte(length) case length < 65536: b |= 126 lengthFields = 2 default: b |= 127 lengthFields = 8 } header = append(header, b) for i := 0; i < lengthFields; i++ { j := uint((lengthFields - i - 1) * 8) b = byte((length >> j) & 0xff) header = append(header, b) } if frame.header.MaskingKey != nil { if len(frame.header.MaskingKey) != 4 { return 0, ErrBadMaskingKey } header = append(header, frame.header.MaskingKey...) frame.writer.Write(header) data := make([]byte, length) for i := range data { data[i] = msg[i] ^ frame.header.MaskingKey[i%4] } frame.writer.Write(data) err = frame.writer.Flush() return length, err } frame.writer.Write(header) frame.writer.Write(msg) err = frame.writer.Flush() return length, err } func (frame *hybiFrameWriter) Close() error { return nil } type hybiFrameWriterFactory struct { *bufio.Writer needMaskingKey bool } func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType} if buf.needMaskingKey { frameHeader.MaskingKey, err = generateMaskingKey() if err != nil { return nil, err } } return &hybiFrameWriter{writer: buf.Writer, header: frameHeader}, nil } type hybiFrameHandler struct { conn *Conn payloadType byte } func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, error) { if handler.conn.IsServerConn() { // The client MUST mask all frames sent to the server. if frame.(*hybiFrameReader).header.MaskingKey == nil { handler.WriteClose(closeStatusProtocolError) return nil, io.EOF } } else { // The server MUST NOT mask all frames. if frame.(*hybiFrameReader).header.MaskingKey != nil { handler.WriteClose(closeStatusProtocolError) return nil, io.EOF } } if header := frame.HeaderReader(); header != nil { io.Copy(io.Discard, header) } switch frame.PayloadType() { case ContinuationFrame: frame.(*hybiFrameReader).header.OpCode = handler.payloadType case TextFrame, BinaryFrame: handler.payloadType = frame.PayloadType() case CloseFrame: return nil, io.EOF case PingFrame, PongFrame: b := make([]byte, maxControlFramePayloadLength) n, err := io.ReadFull(frame, b) if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { return nil, err } io.Copy(io.Discard, frame) if frame.PayloadType() == PingFrame { if _, err := handler.WritePong(b[:n]); err != nil { return nil, err } } return nil, nil } return frame, nil } func (handler *hybiFrameHandler) WriteClose(status int) (err error) { handler.conn.wio.Lock() defer handler.conn.wio.Unlock() w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame) if err != nil { return err } msg := make([]byte, 2) binary.BigEndian.PutUint16(msg, uint16(status)) _, err = w.Write(msg) w.Close() return err } func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) { handler.conn.wio.Lock() defer handler.conn.wio.Unlock() w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame) if err != nil { return 0, err } n, err = w.Write(msg) w.Close() return n, err } // newHybiConn creates a new WebSocket connection speaking hybi draft protocol. func newHybiConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { if buf == nil { br := bufio.NewReader(rwc) bw := bufio.NewWriter(rwc) buf = bufio.NewReadWriter(br, bw) } ws := &Conn{config: config, request: request, buf: buf, rwc: rwc, frameReaderFactory: hybiFrameReaderFactory{buf.Reader}, frameWriterFactory: hybiFrameWriterFactory{ buf.Writer, request == nil}, PayloadType: TextFrame, defaultCloseStatus: closeStatusNormal} ws.frameHandler = &hybiFrameHandler{conn: ws} return ws } // generateMaskingKey generates a masking key for a frame. func generateMaskingKey() (maskingKey []byte, err error) { maskingKey = make([]byte, 4) if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil { return } return } // generateNonce generates a nonce consisting of a randomly selected 16-byte // value that has been base64-encoded. func generateNonce() (nonce []byte) { key := make([]byte, 16) if _, err := io.ReadFull(rand.Reader, key); err != nil { panic(err) } nonce = make([]byte, 24) base64.StdEncoding.Encode(nonce, key) return } // removeZone removes IPv6 zone identifier from host. // E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080" func removeZone(host string) string { if !strings.HasPrefix(host, "[") { return host } i := strings.LastIndex(host, "]") if i < 0 { return host } j := strings.LastIndex(host[:i], "%") if j < 0 { return host } return host[:j] + host[i:] } // getNonceAccept computes the base64-encoded SHA-1 of the concatenation of // the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string. func getNonceAccept(nonce []byte) (expected []byte, err error) { h := sha1.New() if _, err = h.Write(nonce); err != nil { return } if _, err = h.Write([]byte(websocketGUID)); err != nil { return } expected = make([]byte, 28) base64.StdEncoding.Encode(expected, h.Sum(nil)) return } // Client handshake described in draft-ietf-hybi-thewebsocket-protocol-17 func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) { bw.WriteString("GET " + config.Location.RequestURI() + " HTTP/1.1\r\n") // According to RFC 6874, an HTTP client, proxy, or other // intermediary must remove any IPv6 zone identifier attached // to an outgoing URI. bw.WriteString("Host: " + removeZone(config.Location.Host) + "\r\n") bw.WriteString("Upgrade: websocket\r\n") bw.WriteString("Connection: Upgrade\r\n") nonce := generateNonce() if config.handshakeData != nil { nonce = []byte(config.handshakeData["key"]) } bw.WriteString("Sec-WebSocket-Key: " + string(nonce) + "\r\n") bw.WriteString("Origin: " + strings.ToLower(config.Origin.String()) + "\r\n") if config.Version != ProtocolVersionHybi13 { return ErrBadProtocolVersion } bw.WriteString("Sec-WebSocket-Version: " + fmt.Sprintf("%d", config.Version) + "\r\n") if len(config.Protocol) > 0 { bw.WriteString("Sec-WebSocket-Protocol: " + strings.Join(config.Protocol, ", ") + "\r\n") } // TODO(ukai): send Sec-WebSocket-Extensions. err = config.Header.WriteSubset(bw, handshakeHeader) if err != nil { return err } bw.WriteString("\r\n") if err = bw.Flush(); err != nil { return err } resp, err := http.ReadResponse(br, &http.Request{Method: "GET"}) if err != nil { return err } if resp.StatusCode != 101 { return ErrBadStatus } if strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" || strings.ToLower(resp.Header.Get("Connection")) != "upgrade" { return ErrBadUpgrade } expectedAccept, err := getNonceAccept(nonce) if err != nil { return err } if resp.Header.Get("Sec-WebSocket-Accept") != string(expectedAccept) { return ErrChallengeResponse } if resp.Header.Get("Sec-WebSocket-Extensions") != "" { return ErrUnsupportedExtensions } offeredProtocol := resp.Header.Get("Sec-WebSocket-Protocol") if offeredProtocol != "" { protocolMatched := false for i := 0; i < len(config.Protocol); i++ { if config.Protocol[i] == offeredProtocol { protocolMatched = true break } } if !protocolMatched { return ErrBadWebSocketProtocol } config.Protocol = []string{offeredProtocol} } return nil } // newHybiClientConn creates a client WebSocket connection after handshake. func newHybiClientConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser) *Conn { return newHybiConn(config, buf, rwc, nil) } // A HybiServerHandshaker performs a server handshake using hybi draft protocol. type hybiServerHandshaker struct { *Config accept []byte } func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) { c.Version = ProtocolVersionHybi13 if req.Method != "GET" { return http.StatusMethodNotAllowed, ErrBadRequestMethod } // HTTP version can be safely ignored. if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" || !strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") { return http.StatusBadRequest, ErrNotWebSocket } key := req.Header.Get("Sec-Websocket-Key") if key == "" { return http.StatusBadRequest, ErrChallengeResponse } version := req.Header.Get("Sec-Websocket-Version") switch version { case "13": c.Version = ProtocolVersionHybi13 default: return http.StatusBadRequest, ErrBadWebSocketVersion } var scheme string if req.TLS != nil { scheme = "wss" } else { scheme = "ws" } c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI()) if err != nil { return http.StatusBadRequest, err } protocol := strings.TrimSpace(req.Header.Get("Sec-Websocket-Protocol")) if protocol != "" { protocols := strings.Split(protocol, ",") for i := 0; i < len(protocols); i++ { c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i])) } } c.accept, err = getNonceAccept([]byte(key)) if err != nil { return http.StatusInternalServerError, err } return http.StatusSwitchingProtocols, nil } // Origin parses the Origin header in req. // If the Origin header is not set, it returns nil and nil. func Origin(config *Config, req *http.Request) (*url.URL, error) { var origin string switch config.Version { case ProtocolVersionHybi13: origin = req.Header.Get("Origin") } if origin == "" { return nil, nil } return url.ParseRequestURI(origin) } func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) { if len(c.Protocol) > 0 { if len(c.Protocol) != 1 { // You need choose a Protocol in Handshake func in Server. return ErrBadWebSocketProtocol } } buf.WriteString("HTTP/1.1 101 Switching Protocols\r\n") buf.WriteString("Upgrade: websocket\r\n") buf.WriteString("Connection: Upgrade\r\n") buf.WriteString("Sec-WebSocket-Accept: " + string(c.accept) + "\r\n") if len(c.Protocol) > 0 { buf.WriteString("Sec-WebSocket-Protocol: " + c.Protocol[0] + "\r\n") } // TODO(ukai): send Sec-WebSocket-Extensions. if c.Header != nil { err := c.Header.WriteSubset(buf, handshakeHeader) if err != nil { return err } } buf.WriteString("\r\n") return buf.Flush() } func (c *hybiServerHandshaker) NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { return newHybiServerConn(c.Config, buf, rwc, request) } // newHybiServerConn returns a new WebSocket connection speaking hybi draft protocol. func newHybiServerConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { return newHybiConn(config, buf, rwc, request) }
net/websocket/hybi.go/0
{ "file_path": "net/websocket/hybi.go", "repo_id": "net", "token_count": 6115 }
637
// 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 endpoints import ( "testing" "golang.org/x/oauth2" ) func TestAWSCognitoEndpoint(t *testing.T) { var endpointTests = []struct { in string out oauth2.Endpoint }{ { in: "https://testing.auth.us-east-1.amazoncognito.com", out: oauth2.Endpoint{ AuthURL: "https://testing.auth.us-east-1.amazoncognito.com/oauth2/authorize", TokenURL: "https://testing.auth.us-east-1.amazoncognito.com/oauth2/token", }, }, { in: "https://testing.auth.us-east-1.amazoncognito.com/", out: oauth2.Endpoint{ AuthURL: "https://testing.auth.us-east-1.amazoncognito.com/oauth2/authorize", TokenURL: "https://testing.auth.us-east-1.amazoncognito.com/oauth2/token", }, }, } for _, tt := range endpointTests { t.Run(tt.in, func(t *testing.T) { endpoint := AWSCognito(tt.in) if endpoint != tt.out { t.Errorf("got %q, want %q", endpoint, tt.out) } }) } }
oauth2/endpoints/endpoints_test.go/0
{ "file_path": "oauth2/endpoints/endpoints_test.go", "repo_id": "oauth2", "token_count": 466 }
638
// 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 google import ( "errors" "golang.org/x/oauth2" ) // AuthenticationError indicates there was an error in the authentication flow. // // Use (*AuthenticationError).Temporary to check if the error can be retried. type AuthenticationError struct { err *oauth2.RetrieveError } func newAuthenticationError(err error) error { re := &oauth2.RetrieveError{} if !errors.As(err, &re) { return err } return &AuthenticationError{ err: re, } } // Temporary indicates that the network error has one of the following status codes and may be retried: 500, 503, 408, or 429. func (e *AuthenticationError) Temporary() bool { if e.err.Response == nil { return false } sc := e.err.Response.StatusCode return sc == 500 || sc == 503 || sc == 408 || sc == 429 } func (e *AuthenticationError) Error() string { return e.err.Error() } func (e *AuthenticationError) Unwrap() error { return e.err } type errWrappingTokenSource struct { src oauth2.TokenSource } func newErrWrappingTokenSource(ts oauth2.TokenSource) oauth2.TokenSource { return &errWrappingTokenSource{src: ts} } // Token returns the current token if it's still valid, else will // refresh the current token (using r.Context for HTTP client // information) and return the new one. func (s *errWrappingTokenSource) Token() (*oauth2.Token, error) { t, err := s.src.Token() if err != nil { return nil, newAuthenticationError(err) } return t, nil }
oauth2/google/error.go/0
{ "file_path": "oauth2/google/error.go", "repo_id": "oauth2", "token_count": 507 }
639
{ "data": [ { "credential": { "_class": "OAuth2Credentials", "_module": "oauth2client.client", "access_token": "foo_access_token", "client_id": "foo_client_id", "client_secret": "foo_client_secret", "id_token": { "at_hash": "foo_at_hash", "aud": "foo_aud", "azp": "foo_azp", "cid": "foo_cid", "email": "foo@example.com", "email_verified": true, "exp": 1420573614, "iat": 1420569714, "id": "1337", "iss": "accounts.google.com", "sub": "1337", "token_hash": "foo_token_hash", "verified_email": true }, "invalid": false, "refresh_token": "foo_refresh_token", "revoke_uri": "https://oauth2.googleapis.com/revoke", "token_expiry": "2015-01-09T00:51:51Z", "token_response": { "access_token": "foo_access_token", "expires_in": 3600, "id_token": "foo_id_token", "token_type": "Bearer" }, "token_uri": "https://oauth2.googleapis.com/token", "user_agent": "Cloud SDK Command Line Tool" }, "key": { "account": "foo@example.com", "clientId": "foo_client_id", "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "type": "google-cloud-sdk" } }, { "credential": { "_class": "OAuth2Credentials", "_module": "oauth2client.client", "access_token": "bar_access_token", "client_id": "bar_client_id", "client_secret": "bar_client_secret", "id_token": { "at_hash": "bar_at_hash", "aud": "bar_aud", "azp": "bar_azp", "cid": "bar_cid", "email": "bar@example.com", "email_verified": true, "exp": 1420573614, "iat": 1420569714, "id": "1337", "iss": "accounts.google.com", "sub": "1337", "token_hash": "bar_token_hash", "verified_email": true }, "invalid": false, "refresh_token": "bar_refresh_token", "revoke_uri": "https://oauth2.googleapis.com/revoke", "token_expiry": "2015-01-09T00:51:51Z", "token_response": { "access_token": "bar_access_token", "expires_in": 3600, "id_token": "bar_id_token", "token_type": "Bearer" }, "token_uri": "https://oauth2.googleapis.com/token", "user_agent": "Cloud SDK Command Line Tool" }, "key": { "account": "bar@example.com", "clientId": "bar_client_id", "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "type": "google-cloud-sdk" } }, { "credential": { "_class": "ServiceAccountCredentials", "_kwargs": {}, "_module": "oauth2client.client", "_private_key_id": "00000000000000000000000000000000", "_private_key_pkcs8_text": "-----BEGIN RSA PRIVATE KEY-----\nMIICWwIBAAKBgQCt3fpiynPSaUhWSIKMGV331zudwJ6GkGmvQtwsoK2S2LbvnSwU\nNxgj4fp08kIDR5p26wF4+t/HrKydMwzftXBfZ9UmLVJgRdSswmS5SmChCrfDS5OE\nvFFcN5+6w1w8/Nu657PF/dse8T0bV95YrqyoR0Osy8WHrUOMSIIbC3hRuwIDAQAB\nAoGAJrGE/KFjn0sQ7yrZ6sXmdLawrM3mObo/2uI9T60+k7SpGbBX0/Pi6nFrJMWZ\nTVONG7P3Mu5aCPzzuVRYJB0j8aldSfzABTY3HKoWCczqw1OztJiEseXGiYz4QOyr\nYU3qDyEpdhS6q6wcoLKGH+hqRmz6pcSEsc8XzOOu7s4xW8kCQQDkc75HjhbarCnd\nJJGMe3U76+6UGmdK67ltZj6k6xoB5WbTNChY9TAyI2JC+ppYV89zv3ssj4L+02u3\nHIHFGxsHAkEAwtU1qYb1tScpchPobnYUFiVKJ7KA8EZaHVaJJODW/cghTCV7BxcJ\nbgVvlmk4lFKn3lPKAgWw7PdQsBTVBUcCrQJATPwoIirizrv3u5soJUQxZIkENAqV\nxmybZx9uetrzP7JTrVbFRf0SScMcyN90hdLJiQL8+i4+gaszgFht7sNMnwJAAbfj\nq0UXcauQwALQ7/h2oONfTg5S+MuGC/AxcXPSMZbMRGGoPh3D5YaCv27aIuS/ukQ+\n6dmm/9AGlCb64fsIWQJAPaokbjIifo+LwC5gyK73Mc4t8nAOSZDenzd/2f6TCq76\nS1dcnKiPxaED7W/y6LJiuBT2rbZiQ2L93NJpFZD/UA==\n-----END RSA PRIVATE KEY-----\n", "_revoke_uri": "https://oauth2.googleapis.com/revoke", "_scopes": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "_service_account_email": "baz@serviceaccount.example.com", "_service_account_id": "baz.serviceaccount.example.com", "_token_uri": "https://oauth2.googleapis.com/token", "_user_agent": "Cloud SDK Command Line Tool", "access_token": null, "assertion_type": null, "client_id": null, "client_secret": null, "id_token": null, "invalid": false, "refresh_token": null, "revoke_uri": "https://oauth2.googleapis.com/revoke", "service_account_name": "baz@serviceaccount.example.com", "token_expiry": null, "token_response": null, "user_agent": "Cloud SDK Command Line Tool" }, "key": { "account": "baz@serviceaccount.example.com", "clientId": "baz_client_id", "scope": "https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/prediction https://www.googleapis.com/auth/projecthosting", "type": "google-cloud-sdk" } } ], "file_version": 1 }
oauth2/google/testdata/gcloud/credentials/0
{ "file_path": "oauth2/google/testdata/gcloud/credentials", "repo_id": "oauth2", "token_count": 3334 }
640
// 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 jwt import ( "context" "encoding/base64" "encoding/json" "fmt" "net/http" "net/http/httptest" "reflect" "strings" "testing" "golang.org/x/oauth2" "golang.org/x/oauth2/jws" ) var dummyPrivateKey = []byte(`-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK 1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9 /E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt 3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn 2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3 nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK 6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf 5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1 M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y 1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw 5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84 OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ 5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg== -----END RSA PRIVATE KEY-----`) func TestJWTFetch_JSONResponse(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{ "access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 3600 }`)) })) defer ts.Close() conf := &Config{ Email: "aaa@xxx.com", PrivateKey: dummyPrivateKey, TokenURL: ts.URL, } tok, err := conf.TokenSource(context.Background()).Token() if err != nil { t.Fatal(err) } if !tok.Valid() { t.Errorf("got invalid token: %v", tok) } if got, want := tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c"; got != want { t.Errorf("access token = %q; want %q", got, want) } if got, want := tok.TokenType, "bearer"; got != want { t.Errorf("token type = %q; want %q", got, want) } if got := tok.Expiry.IsZero(); got { t.Errorf("token expiry = %v, want none", got) } scope := tok.Extra("scope") if got, want := scope, "user"; got != want { t.Errorf("scope = %q; want %q", got, want) } } func TestJWTFetch_BadResponse(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) })) defer ts.Close() conf := &Config{ Email: "aaa@xxx.com", PrivateKey: dummyPrivateKey, TokenURL: ts.URL, } tok, err := conf.TokenSource(context.Background()).Token() if err != nil { t.Fatal(err) } if tok == nil { t.Fatalf("got nil token; want token") } if tok.Valid() { t.Errorf("got invalid token: %v", tok) } if got, want := tok.AccessToken, ""; got != want { t.Errorf("access token = %q; want %q", got, want) } if got, want := tok.TokenType, "bearer"; got != want { t.Errorf("token type = %q; want %q", got, want) } scope := tok.Extra("scope") if got, want := scope, "user"; got != want { t.Errorf("token scope = %q; want %q", got, want) } } func TestJWTFetch_BadResponseType(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) })) defer ts.Close() conf := &Config{ Email: "aaa@xxx.com", PrivateKey: dummyPrivateKey, TokenURL: ts.URL, } tok, err := conf.TokenSource(context.Background()).Token() if err == nil { t.Error("got a token; expected error") if got, want := tok.AccessToken, ""; got != want { t.Errorf("access token = %q; want %q", got, want) } } } func TestJWTFetch_Assertion(t *testing.T) { var assertion string ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.ParseForm() assertion = r.Form.Get("assertion") w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{ "access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 3600 }`)) })) defer ts.Close() conf := &Config{ Email: "aaa@xxx.com", PrivateKey: dummyPrivateKey, PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", TokenURL: ts.URL, } _, err := conf.TokenSource(context.Background()).Token() if err != nil { t.Fatalf("Failed to fetch token: %v", err) } parts := strings.Split(assertion, ".") if len(parts) != 3 { t.Fatalf("assertion = %q; want 3 parts", assertion) } gotjson, err := base64.RawURLEncoding.DecodeString(parts[0]) if err != nil { t.Fatalf("invalid token header; err = %v", err) } got := jws.Header{} if err := json.Unmarshal(gotjson, &got); err != nil { t.Errorf("failed to unmarshal json token header = %q; err = %v", gotjson, err) } want := jws.Header{ Algorithm: "RS256", Typ: "JWT", KeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", } if got != want { t.Errorf("access token header = %q; want %q", got, want) } } func TestJWTFetch_AssertionPayload(t *testing.T) { var assertion string ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.ParseForm() assertion = r.Form.Get("assertion") w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{ "access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 3600 }`)) })) defer ts.Close() for _, conf := range []*Config{ { Email: "aaa1@xxx.com", PrivateKey: dummyPrivateKey, PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", TokenURL: ts.URL, }, { Email: "aaa2@xxx.com", PrivateKey: dummyPrivateKey, PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", TokenURL: ts.URL, Audience: "https://example.com", }, { Email: "aaa2@xxx.com", PrivateKey: dummyPrivateKey, PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", TokenURL: ts.URL, PrivateClaims: map[string]interface{}{ "private0": "claim0", "private1": "claim1", }, }, } { t.Run(conf.Email, func(t *testing.T) { _, err := conf.TokenSource(context.Background()).Token() if err != nil { t.Fatalf("Failed to fetch token: %v", err) } parts := strings.Split(assertion, ".") if len(parts) != 3 { t.Fatalf("assertion = %q; want 3 parts", assertion) } gotjson, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil { t.Fatalf("invalid token payload; err = %v", err) } claimSet := jws.ClaimSet{} if err := json.Unmarshal(gotjson, &claimSet); err != nil { t.Errorf("failed to unmarshal json token payload = %q; err = %v", gotjson, err) } if got, want := claimSet.Iss, conf.Email; got != want { t.Errorf("payload email = %q; want %q", got, want) } if got, want := claimSet.Scope, strings.Join(conf.Scopes, " "); got != want { t.Errorf("payload scope = %q; want %q", got, want) } aud := conf.TokenURL if conf.Audience != "" { aud = conf.Audience } if got, want := claimSet.Aud, aud; got != want { t.Errorf("payload audience = %q; want %q", got, want) } if got, want := claimSet.Sub, conf.Subject; got != want { t.Errorf("payload subject = %q; want %q", got, want) } if got, want := claimSet.Prn, conf.Subject; got != want { t.Errorf("payload prn = %q; want %q", got, want) } if len(conf.PrivateClaims) > 0 { var got interface{} if err := json.Unmarshal(gotjson, &got); err != nil { t.Errorf("failed to parse payload; err = %q", err) } m := got.(map[string]interface{}) for v, k := range conf.PrivateClaims { if !reflect.DeepEqual(m[v], k) { t.Errorf("payload private claims key = %q: got %#v; want %#v", v, m[v], k) } } } }) } } func TestTokenRetrieveError(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-type", "application/json") w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error": "invalid_grant"}`)) })) defer ts.Close() conf := &Config{ Email: "aaa@xxx.com", PrivateKey: dummyPrivateKey, TokenURL: ts.URL, } _, err := conf.TokenSource(context.Background()).Token() if err == nil { t.Fatalf("got no error, expected one") } _, ok := err.(*oauth2.RetrieveError) if !ok { t.Fatalf("got %T error, expected *RetrieveError", err) } // Test error string for backwards compatibility expected := fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", "400 Bad Request", `{"error": "invalid_grant"}`) if errStr := err.Error(); errStr != expected { t.Fatalf("got %#v, expected %#v", errStr, expected) } }
oauth2/jwt/jwt_test.go/0
{ "file_path": "oauth2/jwt/jwt_test.go", "repo_id": "oauth2", "token_count": 4791 }
641
// 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 oauth2 import ( "context" "fmt" "net/http" "net/url" "strconv" "strings" "time" "golang.org/x/oauth2/internal" ) // defaultExpiryDelta determines how earlier a token should be considered // expired than its actual expiration time. It is used to avoid late // expirations due to client-server time mismatches. const defaultExpiryDelta = 10 * time.Second // Token represents the credentials used to authorize // the requests to access protected resources on the OAuth 2.0 // provider's backend. // // Most users of this package should not access fields of Token // directly. They're exported mostly for use by related packages // implementing derivative OAuth2 flows. type Token struct { // AccessToken is the token that authorizes and authenticates // the requests. AccessToken string `json:"access_token"` // TokenType is the type of token. // The Type method returns either this or "Bearer", the default. TokenType string `json:"token_type,omitempty"` // RefreshToken is a token that's used by the application // (as opposed to the user) to refresh the access token // if it expires. RefreshToken string `json:"refresh_token,omitempty"` // Expiry is the optional expiration time of the access token. // // If zero, TokenSource implementations will reuse the same // token forever and RefreshToken or equivalent // mechanisms for that TokenSource will not be used. Expiry time.Time `json:"expiry,omitempty"` // raw optionally contains extra metadata from the server // when updating a token. raw interface{} // expiryDelta is used to calculate when a token is considered // expired, by subtracting from Expiry. If zero, defaultExpiryDelta // is used. expiryDelta time.Duration } // Type returns t.TokenType if non-empty, else "Bearer". func (t *Token) Type() string { if strings.EqualFold(t.TokenType, "bearer") { return "Bearer" } if strings.EqualFold(t.TokenType, "mac") { return "MAC" } if strings.EqualFold(t.TokenType, "basic") { return "Basic" } if t.TokenType != "" { return t.TokenType } return "Bearer" } // SetAuthHeader sets the Authorization header to r using the access // token in t. // // This method is unnecessary when using Transport or an HTTP Client // returned by this package. func (t *Token) SetAuthHeader(r *http.Request) { r.Header.Set("Authorization", t.Type()+" "+t.AccessToken) } // WithExtra returns a new Token that's a clone of t, but using the // provided raw extra map. This is only intended for use by packages // implementing derivative OAuth2 flows. func (t *Token) WithExtra(extra interface{}) *Token { t2 := new(Token) *t2 = *t t2.raw = extra return t2 } // Extra returns an extra field. // Extra fields are key-value pairs returned by the server as a // part of the token retrieval response. func (t *Token) Extra(key string) interface{} { if raw, ok := t.raw.(map[string]interface{}); ok { return raw[key] } vals, ok := t.raw.(url.Values) if !ok { return nil } v := vals.Get(key) switch s := strings.TrimSpace(v); strings.Count(s, ".") { case 0: // Contains no "."; try to parse as int if i, err := strconv.ParseInt(s, 10, 64); err == nil { return i } case 1: // Contains a single "."; try to parse as float if f, err := strconv.ParseFloat(s, 64); err == nil { return f } } return v } // timeNow is time.Now but pulled out as a variable for tests. var timeNow = time.Now // expired reports whether the token is expired. // t must be non-nil. func (t *Token) expired() bool { if t.Expiry.IsZero() { return false } expiryDelta := defaultExpiryDelta if t.expiryDelta != 0 { expiryDelta = t.expiryDelta } return t.Expiry.Round(0).Add(-expiryDelta).Before(timeNow()) } // Valid reports whether t is non-nil, has an AccessToken, and is not expired. func (t *Token) Valid() bool { return t != nil && t.AccessToken != "" && !t.expired() } // tokenFromInternal maps an *internal.Token struct into // a *Token struct. func tokenFromInternal(t *internal.Token) *Token { if t == nil { return nil } return &Token{ AccessToken: t.AccessToken, TokenType: t.TokenType, RefreshToken: t.RefreshToken, Expiry: t.Expiry, raw: t.Raw, } } // retrieveToken takes a *Config and uses that to retrieve an *internal.Token. // This token is then mapped from *internal.Token into an *oauth2.Token which is returned along // with an error.. func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) { tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v, internal.AuthStyle(c.Endpoint.AuthStyle), c.authStyleCache.Get()) if err != nil { if rErr, ok := err.(*internal.RetrieveError); ok { return nil, (*RetrieveError)(rErr) } return nil, err } return tokenFromInternal(tk), nil } // RetrieveError is the error returned when the token endpoint returns a // non-2XX HTTP status code or populates RFC 6749's 'error' parameter. // https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 type RetrieveError struct { Response *http.Response // Body is the body that was consumed by reading Response.Body. // It may be truncated. Body []byte // ErrorCode is RFC 6749's 'error' parameter. ErrorCode string // ErrorDescription is RFC 6749's 'error_description' parameter. ErrorDescription string // ErrorURI is RFC 6749's 'error_uri' parameter. ErrorURI string } func (r *RetrieveError) Error() string { if r.ErrorCode != "" { s := fmt.Sprintf("oauth2: %q", r.ErrorCode) if r.ErrorDescription != "" { s += fmt.Sprintf(" %q", r.ErrorDescription) } if r.ErrorURI != "" { s += fmt.Sprintf(" %q", r.ErrorURI) } return s } return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) }
oauth2/token.go/0
{ "file_path": "oauth2/token.go", "repo_id": "oauth2", "token_count": 1978 }
642
#!/bin/sh set -e for base in sparse dense sweep-flow mark-flow plan; do inkscape --export-png=$base.png $base.svg done
proposal/design/12800/convert/0
{ "file_path": "proposal/design/12800/convert", "repo_id": "proposal", "token_count": 49 }
643
# Proposal: Zip-based Go package archives Author: Russ Cox Last updated: February 2016 Discussion at https://golang.org/issue/14386. ## Abstract Go package archives (the `*.a` files manipulated by `go tool pack`) use the old Unix ar archive format. I propose to change both Go package archives and Go object files to use the more standard zip archive format. In contrast to ar archives, zip archives admit efficient random access to individual files within the archive and also allow decisions about compression on a per-file basis. The result for Go will be cleaner access to the parts of a package archive and the ability later to add compression of individual parts as appropriate. ## Background ### Go object files and package archives The Go toolchain stores compiled packages in archives written in the Unix ar format used by traditional C toolchains. Before continuing, two notes on terminology: - An archive (a `*.a` file), such as an ar or zip file, is a file that contains other files. To avoid confusion, this design document uses the term _archive_ for the archive file itself and reserves the term _file_ exclusively for other kinds of files, including the files inside the archive. - An _object file_ (a `*.o` file) holds machine code corresponding to a source file; the linker merges multiple object files into a final executable. Examples of object files include the ELF, Mach-O, and PE object files used by Linux, OS X, and Windows systems, respectively. We refer to these as _system object files_. Go uses its own object file format, which we refer to as _Go object files_; that format is unchanged by this proposal. In a traditional C toolchain, an archive contains a file named `__.SYMDEF` and then one or more object files (`.o` files) containing compiled code; each object file corresponds to a different C or assembly source file. The `__.SYMDEF` file is a symbol index a mapping from symbol name (such as `printf`) to the specific object file containing that symbol (such as `print.o`). A traditional C linker reads the symbol index to learn which of the object files it needs to read from the archive; it can completely ignore the others. Go has diverged over time from the C toolchain way of using ar archives. A Go package archive contains package metadata in a file named `__.PKGDEF`, one or more Go object files, and zero or more system object files. The Go object files are generated by the compiler (one for all the Go source code in the package) and by the assembler (one for each assembly source file). The system object files are generated by the system C compiler (one for each `*.c` file in the package directory, plus a few for C source files generated by cgo), or (less commonly) are direct copies of `*.syso` files in the package source directory. Because the Go linker does dead code elimination at a symbol level rather than at the object file level, a traditional C symbol index is not useful and not included in the Go package archive. Long before Go 1, the Go compiler read a single Go source file and wrote a single Go object file, much like a C compiler. Each object file contained a fragment of package metadata contributed by that file. After running the compiler separately on each Go source file in a package, the build system (`make`) invoked the archiver (`6ar`, even on non-amd64 systems) to create an archive containing all the object files. As part of creating the archive, the archiver copied and merged the metadata fragments from the many Go object files into the single `__.PKGDEF` file. This had the effect of storing the package metdata in the archive twice, although the different copies ended up being read by different tools. The copy in `__.PKGDEF` was read by later compilations importing the package, and the fragmented copy spread across the Go object files was read by the linker (which needed to read the object files anyway) and used to detect version skew (a common problem due to the use of per-directory makefiles). By the time of Go 1, the Go compiler read all the Go source files for a package together and wrote a single Go object file. As before, that object file contained (now complete) package metadata, and the archiver (now `go tool pack`) extracted that metadata into the `__.PKGDEF` file. The package still contained two copies of the package metadata. Equally embarassing, most package archives (those for Go packages with no assembly or C) contained only a single `*.o` file, making the archiving step a mostly unnecessary, trivial copy of the data through the file system. Go 1.3 added a new `-pack` option to the Go compiler, directing it to write a Go package archive containing `__.PKGDEF` and a `_go_.o` _without_ package metadata. The go command used this option to create the initial package archive. If the package had no assembly or C sources, there was no need for any more work on the archive. If the package did have assembly or C sources, those additional objects needed to be appended to the archive, which could be done without copying or rewriting the existing data. Adopting `-pack` eliminated the duplicate copy of the package metadata, and it also removed from the linker the job of detecting version skew, since the package metadata was no longer in the object files the linker read. The package metadata itself contains multiple sections used by different programs: a unique build ID, needed by the go command; the package name, needed by the compiler during import, but also needed by the linker; detailed information about exported API, needed by the compiler during import; and directives related to cgo, needed by the linker. The entire metadata format is textual, with sections separated by `$$` lines. Today, the situation is not much different from that of Go 1.3. There are two main problems. First, the individual package metadata sections are difficult to access independently, because of the use of ad-hoc framing inside the standard ar-format framing. The inner framing is necessary in the current system in part because metadata is still sometimes (when not using `-pack`) stored in Go object files, and those object files have no outer framing. The line-oriented nature of the inner framing is a hurdle for converting to a more compact binary format for the export data. In a cleaner design, the different metadata sections would be stored in different files in the Go package archive, eliminating the inner framing. Cleaner separation would allow different tools to access only the data they needed without needing to process unrelated data. The go command, the compiler, and the linker all read `__.PKGDEF`, but only the compiler needs all of it. Distributed build systems can also benefit from splitting a package archive into two halves, one used by the compiler to satisfy imports and one used by the linker to generate the final executable. The build system can then ship just the compiler-relevant data to machines running the compiler and just the linker-relevant data to machines running the linker. In particular, the compiler does not need the Go object files, and the linker does not need the Go export data; both savings can be large. Second, there is no simple way to enable compression for certain files in the Go package archive. It could be worthwhile to compress the Go export data and Go object files, to save disk space as well as I/O time (not just disk I/O but potentially also network I/O, when using network file systems or distributed build systems). ### Archive file formats The ar archive format is simplistic: it begins with a distinguishing 8-byte header (`!<arch>\n`) and then contains a sequence of files. Each file has its own 60-byte header giving the file name (up to 16 bytes), modification time, user and group IDs, permission bits, and size. That header is followed by size bytes of data. If size is odd, the data is followed by a single padding byte so that file headers are always 16-bit aligned within the archive. There is no table of contents: to find the names of all files in the archive, one must read the entire archive (perhaps seeking past file content). There is no compression. Additional file entries can simply be appended to the end of an existing archive. The zip archive format is much more capable, but only a little more complex. A zip archive consists of a sequence of files followed by a table of contents. Each file is stored as a header giving metadata such as the file name and data encoding, followed by encoded file data, followed by a file trailer. The two standard encodings are “store” (raw, uncompressed) and “deflate” (compressed using the same algorithm as zlib and gzip). The table of contents at the end of the zip archive is a contiguous list of file headers including offsets to the actual file data, making it efficient to access a particular file in the archive. As mentioned above, the zip format supports but does not require compression. Appending to a zip archive is simple, although not as trivial as appending to an ar archive. The table of contents must be saved, then new file entries are written starting where the table of contents used to be, and then a new, expanded table of contents is written. Importantly, the existing files are left in place during this process, making it about as efficient as adding to an ar format archive. ## Proposal To address the problems described above, I propose to change Go package archives to use the zip format instead of the current ar format, at the same time separating the current `__.PKGDEF` metadata file into multiple files according to what tools use process the data. To avoid the need to preserve the current custom framing in Go object files, I propose to stop writing Go object files at all, except inside Go package archives. The toolchain would still generate `*.o` files at the times it does today, but the bytes inside those files would be identical to those inside a Go package archive. Although the bytes stored in the `*.a` and `*.o` files would be changing, there would be no visible changes in the rest of the toolchain. In particular, the file names would stay the same, as would the commands used to manipulate and inspect archives. The only differences would be in the encoding used within the file. A Go package archive would be a zip-format archive containing the following files: _go_/header _go_/export _go_/cgo _go_/*.obj _go_/*.sysobj The `_go_/header` file is required, must be first in the archive, must be uncompressed, and is of bounded size. The header content is a sequence of at most four textual metadata lines. For example: go object darwin amd64 devel +8b5a9bd Tue Feb 2 22:46:19 2016 -0500 X:none build id "4fe8e8c8bc1ea2d7c03bd08cf3025e302ff33742" main safe The `go object` line must be first and identifies the operating system, architecture, and toolchain version (including enabled experiments) of the package archive. This line is today the first line of `__.PKGDEF`, and its uses remain the same: the compiler and linker both refuse to use package archives with an unexpected `go object` line. The remaining lines are optional, but whichever ones are present must appear in the order given here. The `build id` line specifies the build ID, an opaque hash used by the build system (typically the go command) as a version identifier, to help detect when a package must be rebuilt. This line is today the second line of `__.PKGDEF`, when present. The `main` line is present if the package archive is `package main`, making it a valid top-level input for the linker. The command `go tool link x.a` will refuse to build a binary from `x.a` if that package's header does not have a `main` line. The `safe` line is present if the code was compiled with `-u`, indicating that it has been checked for safety. When the linker is invoked with `-u`, it refuses to use any unsafe package archives during the link. This mode is experimental and carried forward from earlier versions of Go. The `main` and `safe` lines are today derived from the first line of the export data, which echoes the package statement from the Go source code, followed by the word `safe` for safe packages. The new header omits the name of non-main packages entirely in order to ensure that the header size is bounded no matter how long a package name appears in the package's source code. More header lines may be added to the end of this list in the future, always being careful to keep the overall header size bounded. The `_go_/export` file is usually required (details below), must be second in the archive, and holds a description of the package's exported API for use by a later compilation importing the package. The format of the export data is not specified here, but as mentioned above part of the motivation for this design is to make it possible to use a binary export data format and to apply compression to it. The export data corresponds to the top of the `__.PKGDEF` file, excluding the initial `go object` and `build id` lines and stopping at the first `$$` line. The `_go_/cgo` file is optional and holds cgo-related directives for the linker. The format of these directives is not specified here. This data corresponds to the end of the Go object file metadata, specifically the lines between the third `$$` line and the terminating `!` line. Each of the `_go_/*.obj` files is a traditional Go object file, holding machine code, data, and relocations processed by the linker. Each of the `_go_/*.sysobj` files is a system object file, either generated during the build by the system C compiler or copied verbatim from a `*.syso` file in the package source directory (see the [go command documentation](https://golang.org/cmd/go/#hdr-File_types) for more about `*.syso` files). It is valid today and remains valid in this proposal for multiple files within an archive to have the same name. This simplifies the generation and combination of package files. ## Rationale ### Zip format As discussed in the background section, the most fundamental problem with the current archive format as used by Go is that all package metadata is combined into the single `__.PKGDEF` file. This is done for many reasons, all addressed by the use of zip files. One reason for the single `__.PKGDEF` file is that there is no efficient random access to files inside ar archives. The first file in the archive is the only one that can be accessed with a fixed number of disk I/O operations, and so it is often given a distinguished role. The zip format has a contiguous table of contents, making it possible to access any file in the archive in a fixed number of disk I/O operations. This reduces the pressure to keep all important data in the first file. It is still possible, however, to read a zip file from the beginning of the file, without first consulting the table of contents. The requirements that `_go_/header` be first, be uncompressed, and be bounded in size exist precisely to make it possible to read the package archive header by reading nothing but a prefix of the file (say, the first kilobyte). The requirement that `_go_/export` be second also makes it possible for a compiler to read the header and export data without using any disk I/O to read the table of contents. As mentioned above, another reason for the single `__.PKGDEF` file is that the metadata is stored not just in Go package archives but also in Go object files, as written by `go tool compile` (without `-pack`) or `go tool asm`, and those object files have no archive framing available. Changing `*.o` files to reuse the Go package archive format eliminates the need for a separate framing solution for metadata in `*.o` files. Zip also makes it possible to make different compression decisions for different files within an archive. This is important primarily because we would like the option of compressing the export data and Go object files but likely cannot compress the system object files, because reading them requires having random access to the data. It is also useful to be able to arrange that the header can be read without the overhead of decompression. We could take the current archive format and add a table of contents and support for per-file compression methods, but why reinvent the wheel? Zip is a standard format, and the Go standard library already supports it well. The only other standard archive format in the Go standard library is the Unix tar format. Tar is a marvel: it adds significant complexity to the ar format without addressing any of the architectural problems that make ar unsuitable for our purposes. In some circles, zip has a bad reputation. I speculate that this is due to zip's historically strong association with MS-DOS and historically weak support on Unix systems. Reputation aside, the zip format is clearly documented, is well designed, and avoids the architectural problems of ar and tar. It is perhaps worth noting that Java .jar files also use the zip format internally, and that seems to be working well for them. ### File names The names of files within the package archives all begin with `_go_/`. This is done so that Go packages are easier to distinguish from other zip files and also so that an accidental `unzip x.a` is easier to clean up. Distinguishing Go object files from system object files by name is new in this proposal. Today, tools assume that `__.PKGDEF` is the only non-object file in the package archive, and each file must be inspected to find out what kind of object file it is (Go object or system object). The suffixes make it possible to know both that a particular file is an object file and what kind it is, without reading the file data. The suffixes also isolate tools from each other, making it easier to extend the archive with new data in new files. For example, if some other part of the toolchain needs to add a new file to the archive, the linker will automatically ignore it (assuming the file name does not end in `.obj` or `.sysobj`). ### Compression Go export data and Go object files can both be quite large. I ran experiment on a large program at Google, built with Go 1.5. I gathered all the package archives linked into that program corresponding to Go source code generated from protocol buffer definitions (which can be quite large), and I ran the standard `gzip -1` (fastest, least compression) on those files. That resulted in a 7.5x space savings for the packages. Clearly there are significant space improvements available with only modest attempts at compression. I ran another experiment on the main repo toward the end of the Go 1.6 cycle. I changed the existing package archive format to force compression of `__.PKGDEF` and all Go object files, using Go's compress/gzip at compression level 1, when writing them to the package archive, and I changed all readers to know to decompress them when reading them back out of the archive. This resulted in a 4X space savings for packages on disk: the $GOROOT/pkg tree after make.bash shrunk from about 64 MB to about 16 MB. The cost was an approximately 10% slowdown in make.bash time: the roughly two minutes make.bash normally took on my laptop was extended by about 10 seconds. My experiment was not as efficient in its use of compression as it could be. For example, the linker went to the trouble to open and decompress the beginning of `__.PKGDEF` just to read the few bits it actually needed. Independently, Klaus Post has been working on improving the speed of Go's compress/flate package (used by archive/zip, compress/gzip, and compress/zlib) at all compression levels, as well as the efficiency of the decompressor. He has also replaced compression level 1 by a port of the logic from Google's Snappy (formerly Zippy) algorithm, which was designed specifically for compression speed. Unlike Snappy, though, his port produces DEFLATE-compatible output, so it can be used by a compressor without requiring a non-standard decompressor on the other side. From the combination of a more careful separation of data within the package archive and Klaus's work on compression speed, I expect the slowdown in make.bash due to compression can be reduced to under 5% (for a 4X space savings!). Of course, if the cost of compression is determined to be not paid for by the space savings it brings, it is possible to use zip with no compression at all. The other benefits of the zip format still make this a worthwhile cleanup. ## Compatibility The toolchain is not subject to the [compatibility guidelines](https://golang.org/doc/go1compat). Even so, this change is intended to be invisible to any use case that does not actually open a package archive or object files and read the raw bytes contained within. ## Implementation The implementation proceeds in these steps: 1. Implementation of a new package `cmd/internal/pkg` for manipulating zip-format package archives. 2. Replacement of the ar-format archives with zip-format archives, but still containing the old files (`__.PKGDEF` followed by any number of object files of unspecified type). 3. Implementation of the new file structure within the archives: the separate metadata files and the forced suffixes for Go object files and system object files. 4. Addition of compression. Steps 1, 2, and 3 should have no performance impact on build times. We will measure the speed of make.bash to confirm this. These steps depend on some extensions to the archive/zip package suggested by Roger Peppe. He has implemented these and intends to send them early in the Go 1.7 cycle. Step 4 will have a performance impact on build times. It must be measured to make a proper engineering decision about whether and how much to compress. This step depends on the compress/flate performance improvements by Klaus Post described above. He has implemented these and intends to send them early in the Go 1.7 cycle. I will do this work early in the Go 1.7 cycle, immediately following Roger's and Klaus's work. I have a rough but working prototype of steps 1, 2, and 3 already. Enabling compression in the zip writer is a few lines of code beyond that. Part of the motivation for doing this early in Go 1.7 is to make it possible for Robert Griesemer to gather performance data for his new binary export data format and enable that for Go 1.7 as well. The binary export code is currently bottlenecked by the need to escape and unescape the data to avoid generating a terminating `\n$$` sequence.
proposal/design/14386-zip-package-archives.md/0
{ "file_path": "proposal/design/14386-zip-package-archives.md", "repo_id": "proposal", "token_count": 5434 }
644
# Generalized Types In Go This is a proposal for adding generics to Go, written by Ian Lance Taylor in October, 2013. This proposal will not be adopted. It is being presented as an example for what a complete generics proposal must cover. ## Introduction This document describes a possible implementation of generalized types in Go. We introduce a new keyword, `gen`, that declares one or more type parameters: types that are not known at compile time. These type parameters may then be used in other declarations, producing generalized types and functions. Some goals, borrowed from [Garcia et al](https://web.archive.org/web/20170812055356/http://www.crest.iu.edu/publications/prints/2003/comparing_generic_programming03.pdf): * Do not require an explicit relationship between a definition of a generalized function and its use. The function should be callable with any suitable type. * Permit interfaces to express relationships between types of methods, as in a comparison function that takes two parameters of the same unknown type. * Given a generalized type, make it possible to use related types, such as a slice of that type. * Do not require explicit instantiation of generalized functions. * Permit type aliasing of generalized types. ## Background My earlier proposal for generalized types had some flaws. People expect functions that operate on generalized types to be fast. They do not want a reflection based interface in all cases. The question is how to support that without excessively slowing down the compiler. People want to be able to write simple generalized functions like `Sum(v []T) T`, a function that sums the values in the slice `v`. They are prepared to assume that `T` is a numeric type. They don’t want to have to write a set of methods simply to implement `Sum` or the many other similar functions for every numeric type, including their own named numeric types. People want to be able to write the same function to work on both `[]byte` and `string`, without requiring a copy. People want to write functions on generalized types that support simple operations like comparison. That is, they want to write a function that uses a generalized type and compares a value of that type to another value of the same type. That was awkward in my earlier proposal: it required using a form of the curiously recurring template pattern. Go’s use of structural typing means that you can use any type to meet an interface without an explicit declaration. Generalized types should work the same way. ## Proposal We permit package-level type and func declarations to use generalized types. There are no restrictions on how these types may be used within their scope. At compile time each actual use of a generalized type or function is instantiated by replacing the generalized type with some concrete type. This may happen multiple times with different concrete types. A concrete type is only permitted if all the operations used with the generalized types are permitted for the concrete type. How to implement this efficiently is discussed below. ## Syntax Any package-scope type or func declaration may be preceded with the new keyword `gen` followed by a list of type parameter names in square brackets: ``` gen [T] type Vector []T ``` This defines `T` as a type parameter for the generalized type `Vector`. The scope of `Vector` is the same as it would be if `gen` did not appear. A use of a generalized type must provide specific types to use for the type parameters. This is normally done using square brackets following the generalized type. ``` type VectorInt Vector[int] var v1 Vector[int] var v2 Vector[float32] gen [T1, T2] type Pair struct { first T1; second T2 } var v3 Pair[int, string] ``` Type parameters may also be used with functions. ``` gen [T] func SetHead(v Vector[T], e T) T { v[0] = e return e } ``` We permit a modified version of the factoring syntax used with `var`, `type`, and `const` to permit a series of declarations to share the same type parameters. ``` gen [T1, T2] ( type Pair struct { first T1; second T2 } func MakePair(first T1, second T2) Pair { return &Pair{first, second} } ) // Ends gen. ``` References to other names declared within the same `gen` block do not have to specify the type parameters. When the type parameters are omitted, they are implied to simply be the parameters declared for the block. In the above example, `Pair` when used as the result type of `MakePair` is equivalent to `Pair[T1, T2]`. When this syntax is used we require that the entire contents of the block be valid for a given concrete type. The block is instantiated as a whole, not in individual pieces. As with generalized types, we must specify the types when we refer to a generalized function (but see the section on type deduction, below). ``` var MakeIntPair = MakePair[int, int] var IntPairZero = MakeIntPair(0, 0) ``` A generalized type can have methods. ``` gen [T] func (v *Vector[T]) SetHead(e T) T { v[0] = e return e } ``` Of course a method of a generalized type may itself be a generalized function. ``` gen [T, T2] func (v *Vector[T]) Transform(f func(T) T2) Vector[T2] ``` The `gen` keyword may only be used with a type or function. It may only appear in package scope, not within a function. A non-generalized type may not have a generalized method. A `gen` keyword may appear within the scope of another `gen` keyword. In that case, any use of the generalized type or function must specify all the type parameters, starting with the outermost ones. A different way of writing the last example would be: ``` gen [T] ( type Vector []T gen [T2] func (v *Vector[T]) Transform(f func(T) T2) Vector[T2] ) var v Vector[int] var v2 = v.Transform[int, string](strconv.Itoa) ``` Type deduction, described below, would permit omitting the `[int, string]` in the last line, based on the types of `v` and `strconv.Itoa`. Inner type parameters shadow outer ones with the same name, as in other scopes in Go (although it’s hard to see a use for this shadowing). ### A note on syntax While the use of the `gen` keyword fits reasonably well into the existing Go language, the use of square brackets to denote the specific types is new to Go. We have considered a number of different approaches: * Use angle brackets, as in `Pair<int, string>`. This has the advantage of being familiar to C++ and Java programmers. Unfortunately, it means that `f<T>(true)` can be parsed as either a call to function `f<T>` or a comparison of `f<T` (an expression that tests whether `f` is less than `T`) with `(true)`. While it may be possible to construct complex resolution rules, the Go syntax avoids that sort of ambiguity for good reason. * Overload the dot operator again, as in `Vector.int` or `Pair.(int, string)`. This becomes confusing when we see `Vector.(int)`, which could be a type assertion. * We considered using dot but putting the type first, as in `int.Vector` or `(int, string).Pair`. It might be possible to make that work without ambiguity, but putting the types first seems to make the code harder to read. * An earlier version of this proposal used parentheses for names after types, as in `Vector(int)`. However, that proposal was flawed because there was no way to specify types for generalized functions, and extending the parentheses syntax led to `MakePair(int, string)(1, "")` which seems less than ideal. * We considered various different characters, such as backslash, dollar sign, at-sign or sharp. The square brackets grouped the parameters nicely and provide an acceptable visual appearance. The use of square brackets to pick specific versions of generalized types and functions seems appropriate. However, the top-level declarations could work differently. * We could omit the square brackets in a `gen` declaration without ambiguity. * `gen T type Vector []T` * `gen T1, T2 type Pair struct { f1 T1; f2 T2 }` * We could keep the square brackets, but use the existing `type` keyword rather than introducing a new keyword. * `type [T] type Vector []T` I have a mild preference for the syntax described above but I’m OK with other choices as well. ## Type Deduction When calling a function, as opposed to referring to it without calling it, the type parameters may be omitted in some cases. A function call may omit the type parameters when every type parameter is used for a regular parameter, or, in other words, there are no type parameters that are used only for results. In that case the compiler will compare the actual type of the argument `A` with the type of the generalized parameter `P`, examining the arguments from left to right. `A` and `P` must be identical. The first time we see a type parameter in `P`, it will be set to the appropriate portion of `A`. If the type parameter appears again, it must be identical to the actual type at that point. Note that at compile time the argument type may itself be a generalized type, when one generalized function calls another. The type deduction algorithm is the same. A type parameter of `P` may match a type parameter of `A`. Once this match is made, then every subsequent instance of the `P` type parameter must match the same `A` type parameter. When doing type deduction with an untyped constant, the constant does not determine anything about the generalized type. The deduction proceeds with the remaining arguments. If at the end of the deduction the type has not been determined, the untyped constants are re-examined in sequence, and given the type `int`, `rune`, `float64`, or `complex1281 as usual. Type deduction does not support passing an untyped `nil` constant; `nil` may only be used with an explicit type conversion (or, of course, the type parameters may be written explicitly). Type deduction also applies to composite literals, in which the type parameters for a generalized struct type are deduced from the types of the literals. For example, these three variables will have the same type and value. ``` var v1 = MakePair[int, int](0, 0) var v2 = MakePair(0, 0) // [int, int] deduced. var v3 = Pair{0, 0} // [int, int] deduced. ``` To explain the untyped constant rules: ``` gen [T] func Max(a, b T) T { if a < b { return b } return a } var i int var m1 = Max(i, 0) // i causes T to be deduced as int, 0 is // passed as int. var m2 = Max(0, i) // 0 ignored on first pass, i causes // T to be deduced as int, 0 is passed as // int. var m3 = Max(1, 2.5) // 1 and 2.5 ignored on first pass. // On second pass 1 causes T to be deduced // as int. Passing 2.5 is an error. var m4 = Max(2.5, 1) // 2.5 and 1 ignored on first pass. // On second pass 2.5 causes T to be // deduced as float64. 1 converted to // float64. ``` ## Examples A hash table. ``` package hashmap gen [Keytype, Valtype] ( type bucket struct { next *bucket key Keytype val Valtype } type Hashfn func(Keytype) uint type Eqfn func(Keytype, Keytype) bool type Hashmap struct { hashfn Hashfn eqfn Eqfn buckets []bucket entries int } // This function must be called with explicit type parameters, as // there is no way to deduce the value type. For example, // h := hashmap.New[int, string](hashfn, eqfn) func New(hashfn Hashfn, eqfn Eqfn) *Hashmap { return &Hashmap{hashfn, eqfn, make([]buckets, 16), 0} } func (p *Hashmap) Lookup(key Keytype) (val Valtype, found bool) { h := p.hashfn(key) % len(p.buckets) for b := p.buckets[h]; b != nil; b = b.next { if p.eqfn(key, b.key) { return b.val, true } } return } func (p *Hashmap) Insert(key Keytype, val Valtype) (inserted bool) { // Implementation omitted. } ) // Ends gen. ``` Using the hash table. ``` package sample import ( "fmt" "hashmap" "os" ) func hashint(i int) uint { return uint(i) } func eqint(i, j int) bool { return i == j } var v = hashmap.New[int, string](hashint, eqint) func Add(id int, name string) { if !v.Insert(id, name) { fmt.Println(“duplicate id”, id) os.Exit(1) } } func Find(id int) string { val, found := v.Lookup(id) if !found { fmt.Println(“missing id”, id) os.Exit(1) } return val } ``` Sorting a slice given a comparison function. ``` gen [T] ( func SortSlice(s []T, less func(T, T) bool) { sort.Sort(&sorter{s, less}) } type sorter struct { s []T less func(T, T) bool } func (s *sorter) Len() int { return len(s.s) } func (s *sorter) Less(i, j int) bool { return s.less(s[i], s[j]) } func (s *sorter) Swap(i, j int) { s.s[i], s.s[j] = s.s[j], s.s[i] } ) // End gen ``` Sorting a numeric slice (also works for string). ``` // This can be successfully instantiated for any type T that can be // used with <. gen [T] func SortNumericSlice(s []T) { SortSlice(s, func(a, b T) bool { return a < b }) } ``` Merging two channels into one. ``` gen [T] func Merge(a, b <-chan T) <-chan T { c := make(chan T) go func(a, b chan T) { for a != nil && b != nil { select { case v, ok := <-a: if ok { c <- v } else { a = nil } case v, ok := <-b: if ok { c <- v } else { b = nil } } } close(c) }(a, b) return c } ``` Summing a slice. ``` // Works with any type that supports +. gen [T] func Sum(a []T) T { var s T for _, v := range a { s += v } return s } ``` A generic interface. ``` gen [T] type Equaler interface { Equal(T) bool } // Return the index in s of v1. gen [T] func Find(s []T, v1 T) int { eq, eqok := v1.(Equaler[T]) for i, v2 := range s { if eqok { if eq.Equal(v2) { return i } } else if reflect.DeepEqual(v1, v2) { return i } } return -1 } type S []int // Slice equality that treats nil and S{} as equal. func (s1 S) Equal(s2 S) bool { if len(s1) != len(s2) { return false } for i, v1 := range s1 { if v1 != s2[i] { return false } } return true } var i = Find([]S{S{1, 2}}, S{1, 2}) ``` Joining sequences; works for any `T` that supports `len`, `copy` to `[]byte`, and conversion from `[]byte`; in other words, works for `[]byte` and `string`. ``` gen [T] func Join(a []T, sep T) T { if len(a) == 0 { return T([]byte{}) } if len(a) == 1 { return a[0] } n := len(sep) * (len(a) - 1) for _, v := range a { n += len(v) } b := make([]byte, n) bp := copy(b, a[0]) for _, v := range a[1:] { bp += copy(b[bp:], sep) bp += copy(b[bp:], v) } return T(b) } ``` Require generalized types to implement an interface. ``` // A vector of any type that supports the io.Reader interface. gen [T] ( type ReaderVector []T // This function is not used. // It can only be compiled if T is an io.Reader, so instantiating // this block with any other T will fail. func _(t T) { var _ io.Reader = t } ) // Ends gen. ``` ## Implementation When the compiler sees a gen declaration, it must examine the associated types and functions and build a set of constraints on the generalized type. For example, if the type is used with binary `+` as in the `Sum` example, then the type must be a numeric or string type. If the type is used as `a + 1` then it must be numeric. If a type method is called, then the type must support a method with that name that can accept the given argument types. If the type is passed to a function, then it must have a type acceptable to that function. The compiler can do minimal type checking on the generalized types: if the set of constraints on the generalized type can not be satisfied, the program is in error. For example, if we see both `a + 1` and `a + "b"`, where `a` is a variable of the same generalized type, the compiler should issue an error at that point. When the compiler needs to instantiate a generalized type or function, it compares the concrete type with the constraints. If some constraint fails, the instantiation is invalid. The compiler can give an appropriate error (`"cannot use complex64 with SortNumericSlice because complex64 does not support <"`). The ability to give good clear errors for such a case is important, to avoid the C++ cascading error problem. These constraints are used to build a set of methods required for the generalized type. When compiling a generalized function, each local variable of the generalized type (or any type derived from the generalized type) is changed to an interface type. Each use of the generalized type is changed to call a method on the generalized type. Each constraint becomes a method. Calling a generalized function then means passing in an interface type whose methods are built from the constraints. For example, start with the Sum function. ``` gen [T] func Sum(a []T) T { var s T for _, v := range a { s += v } return s } ``` This get rewritten along the lines of ``` type T interface { plus(T) T } type S interface { len() int index(int) T } func GenSum(a S) T { var s T for i := 0; i < a.len(); i++ { v := a.index(i) s = s.plus(v) } return s } ``` This code is compiled as usual. In addition, the compiler generates instantiation templates. These could perhaps be plain text that can be included in the export data. ``` type realT <instantiation of T> func (p realT) plus(a T) T { return p + a.(realT) // return converts realT to T } type realS []realT func (s realS) len() int { return len(s) } func (s realS) index(i int) T { return s[i] // return converts realT to T } ``` When instantiating `Sum` for a new type, the compiler builds and compiles this code for the new type and calls the compiled version of `Sum` with the interface value for the generated interface. As shown above, the methods automatically use type assertions and interface conversion as needed. The actual call to `Sum(s)` will be rewritten as `GenSum(s).(realT)`. The type assertions and interface conversions are checked at compile time and will always succeed. Note that another way to say whether a concrete type may be used to instantiate a generalized function is to ask whether the instantiation templates may be instantiated and compiled without error. More complex cases may of course involve multiple generalized types in a single expression such as a function call. The compiler can arbitrarily pick one value to carry the methods, and the method implementation will use type assertions to implement the call. This works because all the concrete types are known at instantiation time. For cases like `make` where the compiler has no value on which to invoke a method, there are two cases. For a generalized function, the compiler can write the function as a closure. The actual instantiation will pass a special object in the closure value. See the use of make in the next example. ``` gen [T1, T2, T3] func Combine(a []T1, b []T2, f func(T1, T2) T3) []T3 { r := make([]T3, len(a)) for i, v := range a { r[i] = f(v, b[i]) } return r } ``` This will be rewritten as ``` type S1 interface { len() int index(int) T1 } type S2 interface { index(int) T2 } type S3 interface { set(int, T3) } type F interface { call(T1, T2) T3 } type T1 interface{} type T2 interface{} type T3 interface{} type Maker interface { make(int) S3 } func GenCombine(a S1, b S2, f F) S3 { // The maker var has type Maker and is accessed via the // function’s closure. r = maker.make(a.len()) for i := 0; i < a.len(); i++ { v := a.index(i) r.set(i, f.call(v, b.index(i)) } return r } ``` The associated instantiation templates will be ``` type realT1 <instantiation of T1> type realT2 <instantiation of T2> type realT3 <instantiation of T3> type realS1 []realT1 type realS2 []realT2 type realS3 []realT3 type realF func(realT1, realT2) realT3 type realMaker struct{} func (s1 realS1) len() int { return len(s1) } func (s1 realS1) index(i int) T1 { return s1[i] } func (s2 realS2) index(i int) T2 { return s2[i] } func (s3 realS3) set(i int, t3 T3) { s3[i] = t3.(realT3) } func (f realF) call(t1 T1, t2 T2) T3 { return f(t1.(realT1), t2.(realT2)) } func (m realMaker) make(l int) S3 { return make(realT3, l) } ``` A reference to `Combine` will then be built into a closure value with `GenCombine` as the function and a value of the `Maker` interface in the closure. The dynamic type of the `Maker` value will be `realMaker`. (If a function like `make` is invoked in a method on a generalized type, we can’t use a closure, so we instead add an appropriate hidden method on the generalized type.) With this implementation approach we are taking interface types in a different direction. The interface type in Go lets the programmer define methods and then implement them for different types. With generalized types the programmer describes how the interface is used, and the compiler uses that description to define the methods and their implementation. Another example. When a generalized type has methods, those methods need to be instantiated as calls to the generalized methods with appropriate type assertions and conversions. ``` gen [T] ( type Vector []T func (v Vector) Len() int { return len(v) } func (v Vector) Index(i int) T { return v[i] } ) // Ends gen. type Readers interface { Len() int Index(i int) io.Reader } type VectorReader Vector[io.Reader] var _ = make(VectorReader, 0).(Readers) ``` The last statement asserts that `VectorReader[io.Reader]` supports the Readers interface, as of course it should. The `Vector` type implementation will look like this. ``` type T interface{} type S interface { len() int index(i int) T } type V struct { S } func (v V) Len() int { return v.S.len() } func (v V) Index(i int) T { return v.S.index(i) } ``` The instantiation templates will be ``` type realT <instantiation of T> type realS []realT func (s realS) len() { return len(s) } func (s realS) index(i int) T { return s[i] } ``` When this is instantiated with `io.Reader`, the compiler will generate additional methods. ``` func (s realS) Len() int { return V{s}.Len() } func (s realS) Index(i int) io.Reader { return V{s}.Index(i).(io.Reader) } ``` With an example this simple this seems like a pointless runaround. In general, though, the idea is that the bulk of the method implementation will be in the `V` methods, which are compiled once. The `realS` `len` and `index` methods support those `V` methods. The `realS` `Len` and `Index` methods simply call the `V` methods with appropriate type conversions. That ensures that the `Index` method returns `io.Reader` rather than `T` aka `interface{}`, so that `realS` satisfies the `Readers` interface in the original code. Now an example with a variadic method. ``` gen [T] func F(v T) { v.M(1) v.M(“a”, “b”) } ``` This looks odd, but it’s valid for a type with a method `M(...interface{})`. This is rewritten as ``` type T interface { m(...interface{}) // Not the same as T’s method M. } func GF(v T) { v.m(1) v.m(“a”, “b”) } ``` The instantiation templates will be ``` type realT <instantiation of T> func (t realT) m(a ...interface{}) { t.M(a...) } ``` The basic rule is that if the same method is called with different numbers of arguments, it must be instantiated with a variadic method. If it is called with the same number of arguments with different types, it must be instantiated with interface{} arguments. In the general case the instantiation template may need to convert the argument types to the types that the real type’s method accepts. Because generalized types are implemented by interface types, there is no way to write generalized code that detects whether it was instantiated with an interface type. If the code can assume that a generalized function was instantiated by a non-interface type, then it can detect that type using a type switch or type assertion. If it is important to be able to detect whether a generalized function was instantiated with an interface type, some new mechanism will be required. In the above examples I’ve always described a rewritten implementation and instantiation templates. There is of course another implementation method that will be appropriate for simple generalized functions: inline the function. That would most likely be the implementation method of choice for something like a generalized `Max` function. I think this could be handled as a minor variant on traditional function inlinining. In some cases the compiler can determine that only a specific number of concrete types are permitted. For example, the `Sum` function can only be used with types that support that binary `+` operator, which means a numeric or string type. In that case the compiler could choose to instantiate and compile the function for each possible type. Uses of the generalized function would then call the appropriate instantiation. This would be more work when compiling the generalized function, but not much more work. It would mean no extra work for uses of the generalized function. ## Spec changes I don’t think many spec changes are needed other than a new section on generalized types. The syntax of generalized types would have to be described. The implementation details do not need to be in the spec. A generalized function instantiated with concrete types is valid if rewriting the function with the concrete types would produce valid Go code. There is a minor exception to that approach: we would want to permit type assertions and type switches for generalized types as well as for interface types, even if the concrete type is not an interface type. ## Compatibility This approach introduces a new keyword, `gen`. However, this keyword is only permitted in top-level declarations. That means that we could treat it as a new syntactic category, a top-level keyword that is only recognized as such when parsing a `TopLevelDecl`. That would mean that any code that currently compiles with Go 1 would continue to compile with this new proposal, as any existing use of gen at top-level is invalid. We could also maintain Go 1 compatibility by using the existing `type` keyword instead of `gen`. The square brackets used around the generalized type names would make this unambiguous. However, syntactic compatibility is only part of the story. If this proposal is adopted there will be a push toward rewriting certain parts of the standard library to use generalized types. For example, people will want to change the `container` and `sort` packages. A farther reaching change will be changing `io.Writer` to take a generalized type that is either `[]byte` or `string`, and work to push that through the `net` and `os` packages down to the `syscall` package. I do not know whether this work could be done while maintaining Go 1 compatibility. I do not even know if this work should be done, although I’m sure that people will want it. ## Comparison to other languages ### C Generalized types in C are implemented via preprocessor macros. The system described here can be seen as a macro system. However, unlike in C, each generalized function must be complete and compilable by itself. The result is in some ways less powerful than C preprocessor macros, but does not suffer from problems of namespace conflict and does not require a completely separate language (the preprocessor language) for implementation. ### C++ The system described here can be seen as a subset of C++ templates. Go’s very simple name lookup rules mean that there is none of the confusion of dependent vs. non-dependent names. Go’s lack of function overloading removes any concern over just which instance of a name is being used. Together these permit the explicit determination of constraints when compiling a generalized function, whereas in C++ where it’s nearly impossible to determine whether a type may be used to instantiate a template without effectively compiling the instantiated template and looking for errors (or using concepts, proposed for later addition to the language). C++ template metaprogramming uses template specialization, non-type template parameters, variadic templates, and SFINAE to implement a Turing complete language accessible at compile time. This is very powerful but at the same time has serious drawbacks: the template metaprogramming language has a baroque syntax, no variables or non-recursive loops, and is in general completely different from C++ itself. The system described here does not support anything similar to template metaprogramming for Go. I believe this is a feature. I think the right way to implement such features in Go would be to add support in the go tool for writing Go code to generate Go code, most likely using the go/ast package and friends, which is in turn compiled into the final program. This would mean that the metaprogramming language in Go is itself Go. ### Java I believe this system is slightly more powerful than Java generics, in that it permits direct operations on basic types without requiring explicit methods. This system also does not use type erasure. Although the implementation described above does insert type assertions in various places, all the types are fully checked at compile time and those type assertions will always succeed. ## Summary This proposal will not be adopted. It has significant flaws. The factored `gen` syntax is convenient but looks awkward on the page. You wind up with a trailing close parenthesis after a set of function definitions. Indenting all the function definitions looks silly. The description of constraints in the implementation section is imprecise. It's hard to know how well it would work in practice. Can the proposed implementation really handle the possible cases? A type switch that uses cases with generalized types may wind up with identical types in multiple different cases. We need to clearly explain which case is chosen.
proposal/design/15292/2013-10-gen.md/0
{ "file_path": "proposal/design/15292/2013-10-gen.md", "repo_id": "proposal", "token_count": 8707 }
645
# Proposal: emit DWARF inlining info in the Go compiler Author(s): Than McIntosh Last updated: 2017-10-23 Discussion at: https://golang.org/issue/22080 # Abstract In Go 1.9, the inliner was enhanced to support mid-stack inlining, including tracking of inlines in the PC-value table to enable accurate tracebacks (see [proposal](https://golang.org/issue/19348)). The mid-stack inlining proposal included plans to enhance DWARF generation to emit inlining records, however the DWARF support has yet to be implemented. This document outlines a proposal for completing this work. # Background This section discusses previous work done on the compiler related to inlining and related to debug info generation, and outlines the what we want to see in terms of generated DWARF. ### Source position tracking As part of the mid-stack inlining work, the Go compiler's source position tracking was enhanced, giving it the ability to capture the inlined call stack for an instruction created during an inlining operation. This additional source position information is then used to create an inline-aware PC-value table (readable by the runtime) to provide accurate tracebacks, but is not yet being used to emit DWARF inlining records. ### Lexical scopes The Go compiler also incorporates support for emitting DWARF lexical scope records, so as to provide information to the debugger on which instance of a given variable name is in scope at a given program point. This feature is currently only operational when the user is compiling with "-l -N" passed via -gcflags; these options disable inlining and turn off most optimizations. The scoping implementation currently relies on disabling the inliner; to enable scope generation in combination with inlining would require a separate effort. ### Enhanced variable location tracking There is also work being done to enable more accurate DWARF location lists for function parameters and local variables. This better value tracking is currently checked in but not enabled by default, however the hope is to make this the default behavior for all compilations. ### Compressed source positions, updates during inlining The compiler currently uses a compressed representation for source position information. AST nodes and SSA names incorporate a compact [`src.XPos`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/internal/src/xpos.go#L11) object of the form ``` type XPos struct { index int32 // index into table of PosBase objects lico } ``` where [`src.PosBase`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/internal/src/pos.go#L130) contains source file info and a line base: ``` type PosBase struct { pos Pos filename string // file name used to open source file, for error messages absFilename string // absolute file name, for PC-Line tables symFilename string // cached symbol file name line uint // relative line number at pos inl int // inlining index (see cmd/internal/obj/inl.go) } ``` In the struct above, `inl` is an index into the global inlining tree (maintained as a global slice of [`obj.InlinedCall`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/internal/obj/inl.go#L46) objects): ``` // InlinedCall is a node in an InlTree. type InlinedCall struct { Parent int // index of parent in InlTree or -1 if outermost call Pos src.XPos // position of the inlined call Func *LSym // function that was inlined } ``` When the inliner replaces a call with the body of an inlinable procedure, it creates a new `inl.InlinedCall` object based on the call, then a new `src.PosBase` referring to the InlinedCall's index in the global tree. It then rewrites/updates the src.XPos objects in the inlined blob to refer to the new `src.PosBase` (this process is described in more detail in the [mid-stack inlining design document](https://golang.org/design/19348-midstack-inlining)). ### Overall existing framework for debug generation DWARF generation is split between the Go compiler and Go linker; the top-level driver routine for debug generation is [`obj.populateDWARF`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/internal/obj/objfile.go#L485). This routine makes a call back into [`gc.debuginfo`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/compile/internal/gc/pgen.go#L304) (via context pointer), which collects information on variables and scopes for a function, then invokes [`dwarf.PutFunc`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/internal/dwarf/dwarf.go#L687) to create what amounts to an abstract version of the DWARF DIE chain for the function itself and its children (formals, variables, scopes). The linker starts with the skeleton DIE tree emitted by the compiler, then uses it as a guide to emit the actual DWARF .debug_info section. Other DWARF sections (`.debug_line`, `.debug_frame`) are emitted as well based on non-DWARF-specific data structures (for example, the PCLN table). ### Mechanisms provided by the DWARF standard for representing inlining info The DWARF specification provides details on how compilers can capture and encapsulate information about inlining. See section 3.3.8 of the DWARF V4 standard for a start. If a routine X winds up being inlined, the information that would ordinarily get placed into the subprogram DIE is divided into two partitions: the abstract attributes such as name, type (which will be the same regardless of whether we're talking about an inlined function body or an out-of-line function body), and concrete attributes such as the location for a variable, hi/lo PC or PC ranges for a function body. The abstract items are placed into an "abstract" subprogram instance, then each actual instance of a function body is given a "concrete" instance, which refers back to its parent abstract instance. This can be seen in more detail in the "how the generated DWARF should look" section below. # Example ``` package s func Leaf(lx, ly int) int { return (lx << 7) ^ (ly >> uint32(lx&7)) } func Mid(mx, my int) int { var mv [10]int mv[mx&3] += 2 return mv[my&3] + Leaf(mx+my, my-mx) } func Top(tq int) int { var tv [10]int tr := Leaf(tq-13, tq+13) tv[tq&3] = Mid(tq, tq*tq) return tr + tq + tv[tr&3] } ``` If the code above is compiled with the existing compiler and the resulting DWARF inspected, there is a single DW_TAG_subprogram DIE for `Top`, with variable DIEs reflecting params and (selected) locals for that routine. Two of the stack-allocated locals from the inlined routines (Mid and Leaf) survive in the DWARF, but other inlined variables do not: ``` DW_TAG_subprogram { DW_AT_name: s.Top ... DW_TAG_variable { DW_AT_name: tv ... } DW_TAG_variable { DW_AT_name: mv ... } DW_TAG_formal_parameter { DW_AT_name: tq ... } DW_TAG_formal_parameter { DW_AT_name: ~r1 ... } ``` There are also subprogram DIE's for the out-of-line copies of `Leaf` and `Mid`, which look similar (variable DIEs for locals and params with stack locations). When enhanced DWARF location tracking is turned on, in addition to more accurate variable location expressions within `Top`, there are additional DW_TAG_variable entries for variable such as "lx" and "ly" corresponding those values within the inlined body of `Leaf`. Since these vars are directly parented by `Top` there is no way to disambiguate the various instances of a var such as "lx". # How the generated DWARF should look As mentioned above, emitting DWARF records that capture inlining decisions involves splitting the subprogram DIE for a given function into two pieces, a single "abstract instance" (containing location-independent info) and then a set of "concrete instances", one for each instantiation of the function. Here is a representation of how the generated DWARF should look for the example above. First, the abstract subprogram instance for `Leaf`. No high/lo PC, no locations, for variables etc (these are provided in concrete instances): ``` DW_TAG_subprogram { // offset: D1 DW_AT_name: s.Leaf DW_AT_inline : DW_INL_inlined (not declared as inline but inlined) ... DW_TAG_formal_parameter { // offset: D2 DW_AT_name: lx DW_AT_type: ... } DW_TAG_formal_parameter { // offset: D3 DW_AT_name: ly DW_AT_type: ... } ... } ``` Next we would expect to see a concrete subprogram instance for `s.Leaf`, corresponding to the out-of-line copy of the function (which may wind up being eliminated by the linker if all calls are inlined). This DIE refers back to its abstract parent via the DW_AT_abstract_origin attribute, then fills in location details (such as hi/lo PC, variable locations, etc): ``` DW_TAG_subprogram { DW_AT_abstract_origin: // reference to D1 above DW_AT_low_pc : ... DW_AT_high_pc : ... ... DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D2 above DW_AT_location: ... } DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D3 above DW_AT_location: ... } ... } ``` Similarly for `Mid`, there would be an abstract subprogram instance: ``` DW_TAG_subprogram { // offset: D4 DW_AT_name: s.Mid DW_AT_inline : DW_INL_inlined (not declared as inline but inlined) ... DW_TAG_formal_parameter { // offset: D5 DW_AT_name: mx DW_AT_type: ... } DW_TAG_formal_parameter { // offset: D6 DW_AT_name: my DW_AT_type: ... } DW_TAG_variable { // offset: D7 DW_AT_name: mv DW_AT_type: ... } } ``` Then a concrete subprogram instance for out-of-line copy of `Mid`. Note that incorporated into the concrete instance for `Mid` we also see an inlined instance for `Leaf`. This DIE (with tag DW_TAG_inlined_subroutine) contains a reference to the abstract subprogram DIE for `Leaf`, also attributes for the file and line of the callsite that was inlined: ``` DW_TAG_subprogram { DW_AT_abstract_origin: // reference to D4 above DW_AT_low_pc : ... DW_AT_high_pc : ... DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D5 above DW_AT_location: ... } DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D6 above DW_AT_location: ... } DW_TAG_variable { DW_AT_abstract_origin: // reference to D7 above DW_AT_location: ... } // inlined body of 'Leaf' DW_TAG_inlined_subroutine { DW_AT_abstract_origin: // reference to D1 above DW_AT_call_file: 1 DW_AT_call_line: 10 DW_AT_ranges : ... DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D2 above DW_AT_location: ... } DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D3 above DW_AT_location: ... } ... } } ``` Finally we would expect to see a subprogram instance for `s.Top`. Note that since `s.Top` is not inlined, we would have a single subprogram DIE (as opposed to an abstract instance DIE and a concrete instance DIE): ``` DW_TAG_subprogram { DW_AT_name: s.Top DW_TAG_formal_parameter { DW_AT_name: tq DW_AT_type: ... } ... // inlined body of 'Leaf' DW_TAG_inlined_subroutine { DW_AT_abstract_origin: // reference to D1 above DW_AT_call_file: 1 DW_AT_call_line: 15 DW_AT_ranges : ... DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D2 above DW_AT_location: ... } DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D3 above DW_AT_location: ... } ... } DW_TAG_variable { DW_AT_name: tr DW_AT_type: ... } DW_TAG_variable { DW_AT_name: tv DW_AT_type: ... } // inlined body of 'Mid' DW_TAG_inlined_subroutine { DW_AT_abstract_origin: // reference to D4 above DW_AT_call_file: 1 DW_AT_call_line: 16 DW_AT_low_pc : ... DW_AT_high_pc : ... DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D5 above DW_AT_location: ... } DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D6 above DW_AT_location: ... } DW_TAG_variable { DW_AT_abstract_origin: // reference to D7 above DW_AT_location: ... } // inlined body of 'Leaf' DW_TAG_inlined_subroutine { DW_AT_abstract_origin: // reference to D1 above DW_AT_call_file: 1 DW_AT_call_line: 10 DW_AT_ranges : ... DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D2 above DW_AT_location: ... } DW_TAG_formal_parameter { DW_AT_abstract_origin: // reference to D3 above DW_AT_location: ... } ... } } } ``` # Outline of proposed changes ### Changes to the inliner The inliner manufactures new temporaries for each of the inlined functions formal parameters; it then creates code to assign the correct "actual" expression to each temp, and finally walks the inlined body to replace formal references with temp references. For proper DWARF generation, we need to have a way to associate each of these temps with the formal from which it was derived. It should be possible to create such an association by making sure the temp has the correct src pos (which refers to the callsite) and by giving the temp the same name as the formal. ### Changes to debug generation For the abbreviation table ([`dwarf.dwAbbrev`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/internal/dwarf/dwarf.go#L245) array), we will need to add abstract and concrete versions of the DW_TAG_subprogram abbrev entry used for functions to the abbrev list. top For a given function, [`dwarf.PutFunc`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/internal/dwarf/dwarf.go#L687) will need to emit either an ordinary subprogram DIE (if the function was never inlined) or an abstract subprogram instance followed by a concrete subprogram instance, corresponding to the out-of-line version of the function. It probably makes sense to define a new `dwarf.InlinedCall` type; this will be a struct holding information on the result of an inlined call in a function: ``` type InlinedCall struct { Children []*InlinedCall InlIndex int // index into ctx.InlTree } ``` Code can be added (presumably in `gc.debuginfo`) that collects a tree of `dwarf.InlinedCall` objects corresponding to the functions inlined into the current function being emitted. This tree can then be used to drive creation of concrete inline instances as children of the subprogram DIE of the function being emitted. There will need to be code written that assigns variables and instructions (progs/PCs) to specific concrete inlined routine instances, similar to what is being done currently with scopes in [`gc.assembleScopes`](https://github.com/golang/go/blob/release-branch.go1.9/src/cmd/compile/internal/gc/scope.go#L29). One wrinkle in that the existing machinery for creating intra-DWARF references (attributes with form DW_FORM_ref_addr) assumes that the target of the reference is a top-level DIE with an associated symbol (type, function, etc). This assumption no longer holds for DW_AT_abstract_origin references to formal parameters (where the param is a sub-attribute of a top-level DIE). Some new mechanism will need to be invented to capture this flavor of reference. ### Changes to the linker There will probably need to be a few changes to the linker to accommodate abstract origin references, but for the most part I think the bulk of the work will be done in the compiler. # Compatibility The DWARF constructs proposed here require DWARF version 4, however the compiler is already emitting DWARF V4 as of 1.9. # Implementation Plan is for thanm@ to implement this in go 1.10 timeframe. # Prerequisite Changes N/A # Preliminary Results No data available yet. Expectation is that this will increase the load module size due to the additional DWARF records, but not clear to what degree. # Open issues Once lexical scope tracking is enhanced to work for regular (not '-l -N') compilation, we'll want to integrate inlined instance records with scopes (e.g. if the topmost callsite in question is nested within a scope, then the top-level inlined instance DIE should be parented by the appropriate scope DIE).
proposal/design/22080-dwarf-inlining.md/0
{ "file_path": "proposal/design/22080-dwarf-inlining.md", "repo_id": "proposal", "token_count": 6491 }
646
# Proposal: Simplify mark termination and eliminate mark 2 Author(s): Austin Clements Last updated: 2018-08-09 Discussion at https://golang.org/issue/26903. ## Abstract Go's garbage collector has evolved substantially over time, and as with any software with a history, there are places where the vestigial remnants of this evolution show. This document proposes several related simplifications to the design of Go's mark termination and related parts of concurrent marking that were made possible by shifts in other parts of the garbage collector. The keystone of these simplifications is a new mark completion algorithm. The current algorithm is racy and, as a result, mark termination must cope with the possibility that there may still be marking work to do. We propose a new algorithm based on distributed termination detection that both eliminates this race and replaces the existing "mark 2" sub-phase, yielding simplifications throughout concurrent mark and mark termination. This new mark completion algorithm combined with a few smaller changes can simplify or completely eliminate several other parts of the garbage collector. Hence, we propose to also: 1. Unify stop-the-world GC and checkmark mode with concurrent marking; 2. Flush mcaches after mark termination; 3. And allow safe-points without preemption in dedicated workers. Taken together, these fairly small changes will allow us to eliminate mark 2, "blacken promptly" mode, the second root marking pass, blocking drain mode, `getfull` and its troublesome spin loop, work queue draining during mark termination, `gchelper`, and idle worker tracking. This will eliminate a good deal of subtle code from the garbage collector, making it simpler and more maintainable. As an added bonus, it's likely to perform a little better, too. ## Background Prior to Go 1.5, Go's garbage collector was a stop-the-world garbage collector, and Go continues to support STW garbage collection as a debugging mode. Go 1.5 introduced a concurrent collector, but, in order to minimize a massively invasive change, it kept much of the existing GC mechanism as a STW "mark termination" phase, while adding a concurrent mark phase before the STW phase. This concurrent mark phase did as much as it could, but ultimately fell back to the STW algorithm to clean up any work it left behind. Until Go 1.8, concurrent marking always left behind at least some work, since any stacks that had been modified during the concurrent mark phase had to be re-scanned during mark termination. Go 1.8 introduced [a new write barrier](17503-eliminate-rescan.md) that eliminated the need to re-scan stacks. This significantly reduced the amount of work that had to be done in mark termination. However, since it had never really mattered before, we were sloppy about entering mark termination: the algorithm that decided when it was time to enter mark termination *usually* waited until all work was done by concurrent mark, but sometimes [work would slip through](17503-eliminate-rescan.md#appendix-mark-completion-race), leaving mark termination to clean up the mess. Furthermore, in order to minimize (though not eliminate) the chance of entering mark termination prematurely, Go 1.5 divided concurrent marking into two phases creatively named "mark 1" and "mark 2". During mark 1, when it ran out of global marking work, it would flush and disable all local work caches (enabling "blacken promptly" mode) and enter mark 2. During mark 2, when it ran out of global marking work again, it would enter mark termination. Unfortunately, blacken promptly mode has performance implications (there was a reason for those local caches), and this algorithm can enter mark 2 very early in the GC cycle since it merely detects a work bottleneck. And while disabling all local caches was intended to prevent premature mark termination, this doesn't always work. ## Proposal There are several steps to this proposal, and it's not necessary to implement all of them. However, the crux of the proposal is a new termination detection algorithm. ### Replace mark 2 with a race-free algorithm We propose replacing mark 2 with a race-free algorithm based on ideas from distributed termination detection [Matocha '97]. The GC maintains several work queues of grey objects to be blackened. It maintains two global queues, one for root marking work and one for heap objects, but we can think of these as a single logical queue. It also maintains a queue of locally cached work on each *P* (that is, each GC worker). A P can move work from the global queue to its local queue or vice-versa. Scanning removes work from the local queue and may add work back to the local queue. This algorithm does not change the structure of the GC's work queues from the current implementation. A P *cannot* observe or remove work from another P's local queue. A P also *cannot* create work from nothing: it must consume a marking job in order to create more marking jobs. This is critical to termination detection because it means termination is a stable condition. Furthermore, all of these actions must be *GC-atomic*; that is, there are no safe-points within each of these actions. Again, all of this is true of the current implementation. The proposed algorithm is as follows: First, each P, maintains a local *flushed* flag that it sets whenever the P flushes any local GC work to the global queue. The P may cache an arbitrary amount of GC work locally without setting this flag; the flag indicates that it may have shared work with another P. This flag is only accessed synchronously, so it need not be atomic. When a P's local queue is empty and the global queue is empty it runs the termination detection algorithm: 1. Acquire a global termination detection lock (only one P may run this algorithm at a time). 2. Check the global queue. If it is non-empty, we have not reached termination, so abort the algorithm. 3. Execute a ragged barrier. On each P, when it reaches a safe-point, 1. Flush the local write barrier buffer. This may mark objects and add pointers to the local work queue. 2. Flush the local work queue. This may set the P's flushed flag. 3. Check and clear the P's flushed flag. 4. If any P's flushed flag was set, we have not reached termination, so abort the algorithm. If no P's flushed flag was set, enter mark termination. Like most wave-based distributed termination algorithms, it may be necessary to run this algorithm multiple times during a cycle. However, this isn't necessarily a disadvantage: flushing the local work queues also serves to balance work between Ps, and makes it okay to keep work cached on a P that isn't actively doing GC work. There are a few subtleties to this algorithm that are worth noting. First, unlike many distributed termination algorithms, it *does not* detect that no work was done since the previous barrier. It detects that no work was *communicated*, and that all queues were empty at some point. As a result, while many similar algorithms require at least two waves to detect termination [Hudson '97], this algorithm can detect termination in a single wave. For example, on small heaps it's possible for all Ps to work entirely out of their local queues, in which case mark can complete after just a single wave. Second, while the only way to add work to the local work queue is by consuming work, this is not true of the local write barrier buffer. Since this buffer simply records pointer writes, and the recorded objects may already be black, it can continue to grow after termination has been detected. However, once termination is detected, we know that all pointers in the write barrier buffer must be to black objects, so this buffer can simply be discarded. #### Variations on the basic algorithm There are several small variations on the basic algorithm that may be desirable for implementation and efficiency reasons. When flushing the local work queues during the ragged barrier, it may be valuable to break up the work buffers that are put on the global queue. For efficiency, work is tracked in batches and the queues track these batches, rather than individual marking jobs. The ragged barrier is an excellent opportunity to break up these batches to better balance work. The ragged barrier places no constraints on the order in which Ps flush, nor does it need to run on all Ps if some P has its local flushed flag set. One obvious optimization this allows is for the P that triggers termination detection to flush its own queues and check its own flushed flag before trying to interrupt other Ps. If its own flushed flag is set, it can simply clear it and abort (or retry) termination detection. #### Consequences This new termination detection algorithm replaces mark 2, which means we no longer need blacken-promptly mode. Hence, we can delete all code related to blacken-promptly mode. It also eliminates the mark termination race, so, in concurrent mode, mark termination no longer needs to detect this race and behave differently. However, we should probably continue to detect the race and panic, as detecting the race is cheap and this is an excellent self-check. ### Unify STW GC and checkmark mode with concurrent marking The next step in this proposal is to unify stop-the-world GC and checkmark mode with concurrent marking. Because of the GC's heritage from a STW collector, there are several code paths that are specific to STW collection, even though STW is only a debugging option at this point. In fact, as we've made the collector more concurrent, more code paths have become vestigial, existing only to support STW mode. This adds complexity to the garbage collector and makes this debugging mode less reliable (and less useful) as these code paths are poorly tested. We propose instead implementing STW collection by reusing the existing concurrent collector, but simply telling the scheduler that all Ps must run "dedicated GC workers". Hence, while the world won't technically be stopped during marking, it will effectively be stopped. #### Consequences Unifying STW into concurrent marking directly eliminates several code paths specific to STW mode. Most notably, concurrent marking currently has two root marking phases and STW mode has a single root marking pass. All three of these passes must behave differently. Unifying STW and concurrent marking collapses all three passes into one. In conjunction with the new termination detection algorithm, this eliminates the need for mark work draining during mark termination. As a result, the write barrier does not need to be on during mark termination, and we can eliminate blocking drain mode entirely. Currently, blocking drain mode is only used if the mark termination race happens or if we're in STW mode. This in turn eliminates the troublesome spin loop in `getfull` that implements blocking drain mode. Specifically, this eliminates `work.helperDrainBlock`, `gcDrainBlock` mode, `gcWork.get`, and `getfull`. At this point, the `gcMark` function should be renamed, since it will no longer have anything to do with marking. Unfortunately, this isn't enough to eliminate work draining entirely from mark termination, since the draining mechanism is also used to flush mcaches during mark termination. ### Flush mcaches after mark termination The third step in this proposal is to delay the flushing of mcaches until after mark termination. Each P has an mcache that tracks spans being actively allocated from by that P. Sweeping happens when a P brings a span into its mcache, or can happen asynchronously as part of background sweeping. Hence, the spans in mcaches must be flushed out in order to trigger sweeping of those spans and to prevent a race between allocating from an unswept span and the background sweeper sweeping that span. While it's important for the mcaches to be flushed between enabling the sweeper and allocating, it does not have to happen during mark termination. Hence, we propose to flush each P's mcache when that P returns from the mark termination STW. This is early enough to ensure no allocation can happen on that P, parallelizes this flushing, and doesn't block other Ps during flushing. Combined with the first two steps, this eliminates the only remaining use of work draining during mark termination, so we can eliminate mark termination draining entirely, including `gchelper` and related mechanisms (`mhelpgc`, `m.helpgc`, `helpgc`, `gcprocs`, `needaddgcproc`, etc). ### Allow safe-points without preemption in dedicated workers The final step of this proposal is to allow safe-points in dedicated GC workers. Currently, dedicated GC workers only reach a safe-point when there is no more local or global work. However, this interferes with the ragged barrier in the termination detection algorithm (which can only run at a safe-point on each P). As a result, it's only fruitful to run the termination detection algorithm if there are no dedicated workers running, which in turn requires tracking the number of running and idle workers, and may delay work balancing. By allowing more frequent safe-points in dedicated GC workers, termination detection can run more eagerly. Furthermore, worker tracking was based on the mechanism used by STW GC to implement the `getfull` barrier. Once that has also been eliminated, we no longer need any worker tracking. ## Proof of termination detection algorithm The proposed termination detection algorithm is remarkably simple to implement, but subtle in its reasoning. Here we prove it correct and endeavor to provide some insight into why it works. **Theorem.** The termination detection algorithm succeeds only if all mark work queues are empty when the algorithm terminates. **Proof.** Assume the termination detection algorithm succeeds. In order to show that all mark work queues must be empty once the algorithm succeeds, we use induction to show that all possible actions must maintain three conditions: 1) the global queue is empty, 2) all flushed flags are clear, and 3) after a P has been visited by the ragged barrier, its local queue is empty. First, we show that these conditions were true at the instant it observed the global queue was empty. This point in time trivially satisfies condition 1. Since the algorithm succeeded, each P's flushed flag must have been clear when the ragged barrier observed that P. Because termination detection is the only operation that clears the flushed flags, each flag must have been clear for all time between the start of termination detection and when the ragged barrier observed the flag. In particular, all flags must have been clear at the instant it observed that the global queue was empty, so condition 2 is satisfied. Condition 3 is trivially satisfied at this point because no Ps have been visited by the ragged barrier. This establishes the base case for induction. Next, we consider all possible actions that could affect the state of the queue or the flags after this initial state. There are four such actions: 1. The ragged barrier can visit a P. This may modify the global queue, but if it does so it will set the flushed flag and the algorithm will not succeed, contradicting the assumption. Thus it could not have modified the global queue, maintaining condition 1. For the same reason, we know it did not set the flushed flag, maintaining condition 2. Finally, the ragged barrier adds the P to the set of visited P, but flushes the P's local queue, thus maintaining condition 3. 2. If the global queue is non-empty, a P can move work from the global queue to its local queue. By assumption, the global queue is empty, so this action can't happen. 3. If its local queue is non-empty, a P can consume local work and potentially produce local work. This action does not modify the global queue or flushed flag, so it maintains conditions 1 and 2. If the P has not been visited by the ragged barrier, then condition 3 is trivially maintained. If it has been visited, then by assumption the P's local queue is empty, so this action can't happen. 4. If the local queue is non-empty, the P can move work from the local queue to the global queue. There are two sub-cases. If the P has not been visited by the ragged barrier, then this action would set the P's flushed flag, causing termination detection to fail, which contradicts the assumption. If the P has been visited by the ragged barrier, then its local queue is empty, so this action can't happen. Therefore, by induction, all three conditions must be true when termination detection succeeds. Notably, we've shown that once the ragged barrier is complete, none of the per-P actions (2, 3, and 4) can happen. Thus, if termination detection succeeds, then by conditions 1 and 3, all mark work queues must be empty. **Corollary.** Once the termination detection algorithm succeeds, there will be no work to do in mark termination. Go's GC never turns a black object grey because it uses black mutator techniques (once a stack is black it remains black) and a forward-progress barrier. Since the mark work queues contain pointers to grey objects, it follows that once the mark work queues are empty, they will remain empty, including when the garbage collector transitions in to mark termination. ## Compatibility This proposal does not affect any user-visible APIs, so it is Go 1 compatible. ## Implementation This proposal can be implemented incrementally, and each step opens up new simplifications. The first step will be to implement the new termination detection algorithm, since all other simplifications build on that, but the other steps can be implemented as convenient. Austin Clements plans to implement all or most of this proposal for Go 1.12. The actual implementation effort for each step is likely to be fairly small (the mark termination algorithm was implemented and debugged in under an hour). ## References [Hudson '97] R. L. Hudson, R. Morrison, J. E. B. Moss, and D. S. Munro. Garbage collecting the world: One car at a time. In *ACM SIGPLAN Notices* 32(10):162–175, October 1997. [Matocha '98] Jeff Matocha and Tracy Camp. "A taxonomy of distributed termination detection algorithms." In *Journal of Systems and Software* 43(3):207–221, November 1998.
proposal/design/26903-simplify-mark-termination.md/0
{ "file_path": "proposal/design/26903-simplify-mark-termination.md", "repo_id": "proposal", "token_count": 4381 }
647
# Proposal: Lazy Module Loading Author: Bryan C. Mills (with substantial input from Russ Cox, Jay Conrod, and Michael Matloob) Last updated: 2020-02-20 Discussion at https://golang.org/issue/36460. ## Abstract We propose to change `cmd/go` to avoid loading transitive module dependencies that have no observable effect on the packages to be built. The key insights that lead to this approach are: 1. If _no_ package in a given dependency module is ever (even transitively) imported by any package loaded by an invocation of the `go` command, then an incompatibility between any package in that dependency and any other package has no observable effect in the resulting program(s). Therefore, we can safely ignore the (transitive) requirements of any module that does not contribute any package to the build. 2. We can use the explicit requirements of the main module as a coarse filter on the set of modules relevant to the main module and to previous invocations of the `go` command. Based on those insights, we propose to change the `go` command to retain more transitive dependencies in `go.mod` files and to avoid loading `go.mod` files for “irrelevant” modules, while still maintaining high reproducibility for build and test operations. ## Background In the initial implementation of modules, we attempted to make `go mod tidy` prune out of the `go.mod` file any module that did not provide a transitive import of the main module. However, that did not always preserve the remaining build list: a module that provided no packages might still raise the minimum requirement on some _other_ module that _did_ provide a package. We addressed that problem in [CL 121304] by explicitly retaining requirements on all modules that provide _directly-imported_ packages, _as well as_ a minimal set of module requirement roots needed to retain the selected versions of transitively-imported packages. In [#29773] and [#31248], we realized that, due to the fact that the `go.mod` file is pruned to remove indirect dependencies already implied by other requirements, we must load the `go.mod` file for all versions of dependencies, even if we know that they will not be selected — even including the main module itself! In [#30831] and [#34016], we learned that following deep history makes problematic dependencies very difficult to completely eliminate. If the repository containing a module is no longer available and the module is not cached in a module mirror, then we will encounter an error when loading any module — even a very old, irrelevant one! — that required it. In [#26904], [#32058], [#33370], and [#34417], we found that the need to consider every version of a module separately, rather than only the selected version, makes the `replace` directive difficult to understand, difficult to use correctly, and generally more complex than we would like it to be. In addition, users have repeatedly expressed the desire to avoid the cognitive overhead of seeing “irrelevant” transitive dependencies ([#26955], [#27900], [#32380]), reasoning about older-than-selected transitive dependencies ([#36369]), and fetching large numbers of `go.mod` files ([#33669], [#29935]). ### Properties In this proposal, we aim to achieve a property that we call <dfn>lazy loading</dfn>: * In the steady state, an invocation of the `go` command should not load any `go.mod` file or source code for a module (other than the main module) that provides no _packages_ loaded by that invocation. * In particular, if the selected version of a module is not changed by a `go` command, the `go` command should not load a `go.mod` file or source code for any _other_ version of that module. We also want to preserve <dfn>reproducibility</dfn> of `go` command invocations: * An invocation of the `go` command should either load the same version of each package as every other invocation since the last edit to the `go.mod` file, or should edit the `go.mod` file in a way that causes the next invocation on any subset of the same packages to use the same versions. ## Proposal ### Invariants We propose that, when the main module's `go.mod` file specifies `go 1.15` or higher, every invocation of the `go` command should update the `go.mod` file to maintain three invariants. 1. (The <dfn>import invariant</dfn>.) The main module's `go.mod` file explicitly requires the selected version of every module that contains one or more packages that were transitively imported by any package in the main module. 2. (The <dfn>argument invariant<dfn>.) The main module's `go.mod` file explicitly requires the selected version of every module that contains one or more packages that matched an explicit [package pattern] argument. 3. (The <dfn>completeness invariant</dfn>.) The version of every module that contributed any package to the build is recorded in the `go.mod` file of either the main module itself or one of modules it requires explicitly. The _completeness invariant_ alone is sufficient to ensure _reproducibility_ and _lazy loading_. However, it is under-constrained: there are potentially many _minimal_ sets of requirements that satisfy the completeness invariant, and even more _valid_ solutions. The _import_ and _argument_ invariants guide us toward a _specific_ solution that is simple and intuitive to explain in terms of the `go` commands invoked by the user. If the main module satisfies the _import_ and _argument_ invariants, and all explicit module dependencies also satisfy the import invariant, then the _completeness_ invariant is also trivially satisfied. Given those, the completeness invariant exists only in order to tolerate _incomplete_ dependencies. If the import invariant or argument invariant holds at the start of a `go` invocation, we can trivially preserve that invariant (without loading any additional packages or modules) at the end of the invocation by updating the `go.mod` file with explicit versions for all module paths that were already present, in addition to any new main-module imports or package arguments found during the invocation. ### Module loading procedure At the start of each operation, we load all of the explicit requirements from the main module's `go.mod` file. If we encounter an import from any module that is not already _explicitly_ required by the main module, we perform a <dfn>deepening scan</dfn>. To perform a deepening scan, we read the `go.mod` file for each module explicitly required by the main module, and add its requirements to the build list. If any explicitly-required module uses `go 1.14` or earlier, we also read the `go.mod` files for all of that module's (transitive) module dependencies. (The deepening scan allows us to detect changes to the import graph without loading the whole graph explicitly: if we encounter a new import from within a previously-irrelevant package, the deepening scan will re-read the requirements of the module containing that package, and will ensure that the selected version of that import is compatible with all other relevant packages.) As we load each imported package, we also read the `go.mod` file for the module containing that package and add its requirements to the build list — even if that version of the module was already explicitly required by the main module. (This step is theoretically redundant: the requirements of the main module will already reflect any relevant dependencies, and the _deepening scan_ will catch any previously-irrelevant dependencies that subsequently _become_ relevant. However, reading the `go.mod` file for each imported package makes the `go` command much more robust to inconsistencies in the `go.mod` file — including manual edits, erroneous version-control merge resolutions, incomplete dependencies, and changes in `replace` directives and replacement directory contents.) If, after the _deepening scan,_ the package to be imported is still not found in any module in the build list, we resolve the `latest` version of a module containing that package and add it to the build list (following the same search procedure as in Go 1.14), then perform another deepening scan (this time including the newly added-module) to ensure consistency. ### The `all` pattern and `mod` subcommands #### In Go 1.11–1.14 In module mode in Go 1.11–1.14, the `all` package pattern matches each package reachable by following imports _and tests of imported packages_ recursively, starting from the packages in the main module. (It is equivalent to the set of packages obtained by iterating `go list -deps -test ./...` over its own output until it reaches a fixed point.) `go mod tidy` adjusts the `go.mod` and `go.sum` files so that the main module transitively requires a set of modules that provide every package matching the `all` package pattern, independent of build tags. After `go mod tidy`, every package matching the `all` _package_ pattern is provided by some module matching the `all` _module_ pattern. `go mod tidy` also updates a set of `// indirect` comments indicating versions added or upgraded beyond what is implied by transitive dependencies. `go mod download` downloads all modules matching the `all` _module_ pattern, which normally includes a module providing every package in the `all` _package_ pattern. In contrast, `go mod vendor` copies in only the subset of packages transitively _imported by_ the packages and tests _in the main module_: it does not scan the imports of tests outside of the main module, even if those tests are for imported packages. (That is: `go mod vendor` only covers the packages directly reported by `go list -deps -test ./...`.) As a result, when using `-mod=vendor` the `all` and `...` patterns may match substantially fewer packages than when using `-mod=mod` (the default) or `-mod=readonly`. <!-- Note: the behavior of `go mod vendor` was changed to its current form during the `vgo` prototype, in https://golang.org/cl/122256. --> #### The `all` package pattern and `go mod tidy` We would like to preserve the property that, after `go mod tidy`, invocations of the `go` command — including `go test` — are _reproducible_ (without changing the `go.mod` file) for every package matching the `all` package pattern. The _completeness invariant_ is what ensures reproducibility, so `go mod tidy` must ensure that it holds. Unfortunately, even if the _import invariant_ holds for all of the dependencies of the main module, the current definition of the `all` pattern includes _dependencies of tests of dependencies_, recursively. In order to establish the _completeness invariant_ for distant test-of-test dependencies, `go mod tidy` would sometimes need to record a substantial number of dependencies of tests found outside of the main module in the main module's `go.mod` file. Fortunately, we can omit those distant dependencies a different way: by changing the definition of the `all` pattern itself, so that test-of-test dependencies are no longer included. Feedback from users (in [#29935], [#26955], [#32380], [#32419], [#33669], and perhaps others) has consistently favored omitting those dependencies, and narrowing the `all` pattern would also establish a nice _new_ property: after running `go mod vendor`, the `all` package pattern with `-mod=vendor` would now match the `all` pattern with `-mod=mod`. Taking those considerations into account, we propose that the `all` package pattern in module mode should match only the packages transitively _imported by_ packages and tests in the main module: that is, exactly the set of packages preserved by `go mod vendor`. Since the `all` pattern is based on package imports (more-or-less independent of module dependencies), this change should be independent of the `go` version specified in the `go.mod` file. The behavior of `go mod tidy` should change depending on the `go` version. In a module that specifies `go 1.15` or later, `go mod tidy` should scan the packages matching the new definition of `all`, ignoring build tags. In a module that specifies `go 1.14` or earlier, it should continue to scan the packages matching the _old_ definition (still ignoring build tags). (Note that both of those sets are supersets of the new `all` pattern.) #### The `all` and `...` module patterns and `go mod download` In Go 1.11–1.14, the `all` module pattern matches each module reachable by following module requirements recursively, starting with the main module and visiting every version of every module encountered. The module pattern `...` has the same behavior. The `all` module pattern is important primarily because it is the default set of modules downloaded by the `go mod download` subcommand, which sets up the local cache for offline use. However, it (along with `...`) is also currently used by a few other tools (such as `go doc`) to locate “modules of interest” for other purposes. Unfortunately, these patterns as defined in Go 1.11–1.14 are _not compatible with lazy loading:_ they examine transitive `go.mod` files without loading any packages. Therefore, in order to achieve lazy loading we must change their behavior. Since we want to compute the list of modules without loading any packages or irrelevant `go.mod` files, we propose that when the main module's `go.mod` file specifies `go 1.15` or higher, the `all` and wildcard module patterns should match only those modules found in a _deepening scan_ of the main module's dependencies. That definition includes every module whose version is reproducible due to the _completeness invariant,_ including modules needed by tests of transitive imports. With this redefinition of the `all` module pattern, and the above redefinition of the `all` package pattern, we again have the property that, after `go mod tidy && go mod download all`, invoking `go test` on any package within `all` does not need to download any new dependencies. Since the `all` pattern includes every module encountered in the deepening scan, rather than only those that provide imported packages, `go mod download` may continue to download more source code than is strictly necessary to build the packages in `all`. However, as is the case today, users may download only that narrower set as a side effect of invoking `go list all`. ### Effect on `go.mod` size Under this approach, the set of modules recorded in the `go.mod` file would in most cases increase beyond the set recorded in Go 1.14. However, the set of modules recorded in the `go.sum` file would decrease: irrelevant modules would no longer be included. - The modules recorded in `go.mod` under this proposal would be a strict subset of the set of modules recorded in `go.sum` in Go 1.14. - The set of recorded modules would more closely resemble a “lock” file as used in other dependency-management systems. (However, the `go` command would still not require a separate “manifest” file, and unlike a lock file, the `go.mod` file would still be updated automatically to reflect new requirements discovered during package loading.) - For modules with _few_ test-of-test dependencies, the `go.mod` file after running `go mod tidy` will typically be larger than in Go 1.14. For modules with _many_ test-of-test dependencies, it may be substantially smaller. - For modules that are _tidy:_ - The module versions recorded in the `go.mod` file would be exactly those listed in `vendor/modules.txt`, if present. - The module versions recorded in `vendor/modules.txt` would be the same as under Go 1.14, although the `## explicit` annotations could perhaps be removed (because _all_ relevant dependencies would be recorded explicitly). - The module versions recorded in the `go.sum` file would be exactly those listed in the `go.mod` file. ## Compatibility The `go.mod` file syntax and semantics proposed here are backward compatible with previous Go releases: all `go.mod` files for existing `go` versions would retain their current meaning. Under this proposal, a `go.mod` file that specifies `go 1.15` or higher will cause the `go` command to lazily load the `go.mod` files for its requirements. When reading a `go 1.15` file, previous versions of the `go` command (which do not prune irrelevant dependencies) may select _higher_ versions than those selected under this proposal, by following otherwise-irrelevant dependency edges. However, because the `require` directive continues to specify a minimum version for the required dependency, a previous version of the `go` command will never select a _lower_ version of any dependency. Moreover, any strategy that prunes out a dependency as interpreted by a previous `go` version will continue to prune out that dependency as interpreted under this proposal: module maintainers will not be forced to break users on new `go` versions in order to support users on older versions (or vice-versa). Versions of the `go` command before 1.14 do not preserve the proposed invariants for the main module: if `go` command from before 1.14 is run in a `go 1.15` module, it may automatically remove requirements that are now needed. However, as a result of [CL 204878], `go` version 1.14 does preserve those invariants in all subcommands except for `go mod tidy`: Go 1.14 users will be able to work (in a limited fashion) within a Go 1.15 main module without disrupting its invariants. ## Implementation `bcmills` is working on a prototype of this design for `cmd/go` in Go 1.15. At this time, we do not believe that any other tooling changes will be needed. ## Open issues Because `go mod tidy` will now preserve seemingly-redundant requirements, we may find that we want to expand or update the `// indirect` comments that it currently manages. For example, we may want to indicate “indirect dependencies at implied versions” separately from “upgraded or potentially-unused indirect dependencies”, and we may want to indicate “direct or indirect dependencies of tests” separately from “direct or indirect dependencies of non-tests”. Since these comments do not have a semantic effect, we can fine-tune them after implementation (based on user feedback) without breaking existing modules. ## Examples The following examples illustrate the proposed behavior using the `cmd/go` [script test] format. For local testing and exploration, the test files can be extracted using the [`txtar`] tool. ### Importing a new package from an existing module dependency ```txtar cp go.mod go.mod.old go mod tidy cmp go.mod go.mod.old # Before adding a new import, the go.mod file should # enumerate modules for all packages already imported. go list all cmp go.mod go.mod.old # When a new import is found, we should perform a deepening scan of the existing # dependencies and add a requirement on the version required by those # dependencies — not re-resolve 'latest'. cp lazy.go.new lazy.go go list all cmp go.mod go.mod.new -- go.mod -- module example.com/lazy go 1.15 require ( example.com/a v0.1.0 example.com/b v0.1.0 // indirect ) replace ( example.com/a v0.1.0 => ./a example.com/b v0.1.0 => ./b example.com/c v0.1.0 => ./c1 example.com/c v0.2.0 => ./c2 ) -- lazy.go -- package lazy import ( _ "example.com/a/x" ) -- lazy.go.new -- package lazy import ( _ "example.com/a/x" _ "example.com/a/y" ) -- go.mod.new -- module example.com/lazy go 1.15 require ( example.com/a v0.1.0 example.com/b v0.1.0 // indirect example.com/c v0.1.0 // indirect ) replace ( example.com/a v0.1.0 => ./a example.com/b v0.1.0 => ./b example.com/c v0.1.0 => ./c1 example.com/c v0.2.0 => ./c2 ) -- a/go.mod -- module example.com/a go 1.15 require ( example.com/b v0.1.0 example.com/c v0.1.0 ) -- a/x/x.go -- package x import _ "example.com/b" -- a/y/y.go -- package y import _ "example.com/c" -- b/go.mod -- module example.com/b go 1.15 -- b/b.go -- package b -- c1/go.mod -- module example.com/c go 1.15 -- c1/c.go -- package c -- c2/go.mod -- module example.com/c go 1.15 -- c2/c.go -- package c ``` ### Testing an imported package found in another module ```txtar cp go.mod go.mod.old go mod tidy cmp go.mod go.mod.old # 'go list -m all' should include modules that cover the test dependencies of # the packages imported by the main module, found via a deepening scan. go list -m all stdout 'example.com/b v0.1.0' ! stdout example.com/c cmp go.mod go.mod.old # 'go test' of any package in 'all' should use its existing dependencies without # updating the go.mod file. go list all stdout example.com/a/x go test example.com/a/x cmp go.mod go.mod.old -- go.mod -- module example.com/lazy go 1.15 require example.com/a v0.1.0 replace ( example.com/a v0.1.0 => ./a example.com/b v0.1.0 => ./b1 example.com/b v0.2.0 => ./b2 example.com/c v0.1.0 => ./c ) -- lazy.go -- package lazy import ( _ "example.com/a/x" ) -- a/go.mod -- module example.com/a go 1.15 require example.com/b v0.1.0 -- a/x/x.go -- package x -- a/x/x_test.go -- package x import ( "testing" _ "example.com/b" ) func TestUsingB(t *testing.T) { // … } -- b1/go.mod -- module example.com/b go 1.15 require example.com/c v0.1.0 -- b1/b.go -- package b -- b1/b_test.go -- package b import _ "example.com/c" -- b2/go.mod -- module example.com/b go 1.15 require example.com/c v0.1.0 -- b2/b.go -- package b -- b2/b_test.go -- package b import _ "example.com/c" -- c/go.mod -- module example.com/c go 1.15 -- c/c.go -- package c ``` ### Testing an unimported package found in an existing module dependency ```txtar cp go.mod go.mod.old go mod tidy cmp go.mod go.mod.old # 'go list -m all' should include modules that cover the test dependencies of # the packages imported by the main module, found via a deepening scan. go list -m all stdout 'example.com/b v0.1.0' cmp go.mod go.mod.old # 'go test all' should use those existing dependencies without updating the # go.mod file. go test all cmp go.mod go.mod.old -- go.mod -- module example.com/lazy go 1.15 require ( example.com/a v0.1.0 ) replace ( example.com/a v0.1.0 => ./a example.com/b v0.1.0 => ./b1 example.com/b v0.2.0 => ./b2 example.com/c v0.1.0 => ./c ) -- lazy.go -- package lazy import ( _ "example.com/a/x" ) -- a/go.mod -- module example.com/a go 1.15 require ( example.com/b v0.1.0 ) -- a/x/x.go -- package x -- a/x/x_test.go -- package x import _ "example.com/b" func TestUsingB(t *testing.T) { // … } -- b1/go.mod -- module example.com/b go 1.15 -- b1/b.go -- package b -- b1/b_test.go -- package b import _ "example.com/c" -- b2/go.mod -- module example.com/b go 1.15 require ( example.com/c v0.1.0 ) -- b2/b.go -- package b -- b2/b_test.go -- package b import _ "example.com/c" -- c/go.mod -- module example.com/c go 1.15 -- c/c.go -- package c ``` ### Testing a package imported from a `go 1.14` dependency ```txtar cp go.mod go.mod.old go mod tidy cmp go.mod go.mod.old # 'go list -m all' should include modules that cover the test dependencies of # the packages imported by the main module, found via a deepening scan. go list -m all stdout 'example.com/b v0.1.0' stdout 'example.com/c v0.1.0' cmp go.mod go.mod.old # 'go test' of any package in 'all' should use its existing dependencies without # updating the go.mod file. # # In order to satisfy reproducibility for the loaded packages, the deepening # scan must follow the transitive module dependencies of 'go 1.14' modules. go list all stdout example.com/a/x go test example.com/a/x cmp go.mod go.mod.old -- go.mod -- module example.com/lazy go 1.15 require example.com/a v0.1.0 replace ( example.com/a v0.1.0 => ./a example.com/b v0.1.0 => ./b example.com/c v0.1.0 => ./c1 example.com/c v0.2.0 => ./c2 ) -- lazy.go -- package lazy import ( _ "example.com/a/x" ) -- a/go.mod -- module example.com/a go 1.14 require example.com/b v0.1.0 -- a/x/x.go -- package x -- a/x/x_test.go -- package x import ( "testing" _ "example.com/b" ) func TestUsingB(t *testing.T) { // … } -- b/go.mod -- module example.com/b go 1.14 require example.com/c v0.1.0 -- b/b.go -- package b import _ "example.com/c" -- c1/go.mod -- module example.com/c go 1.14 -- c1/c.go -- package c -- c2/go.mod -- module example.com/c go 1.14 -- c2/c.go -- package c ``` <!-- References --> [package pattern]: https://tip.golang.org/cmd/go/#hdr-Package_lists_and_patterns "go — Package lists and patterns" [script test]: https://go.googlesource.com/go/+/refs/heads/master/src/cmd/go/testdata/script/README "src/cmd/go/testdata/script/README" [`txtar`]: https://pkg.go.dev/golang.org/x/exp/cmd/txtar "golang.org/x/exp/cmd/txtar" [CL 121304]: https://golang.org/cl/121304 "cmd/go/internal/vgo: track directly-used vs indirectly-used modules" [CL 122256]: https://golang.org/cl/122256 "cmd/go/internal/modcmd: drop test sources and data from mod -vendor" [CL 204878]: https://golang.org/cl/204878 "cmd/go: make commands other than 'tidy' prune go.mod less aggressively" [#26904]: https://golang.org/issue/26904 "cmd/go: allow replacement modules to alias other active modules" [#27900]: https://golang.org/issue/27900 "cmd/go: 'go mod why' should have an answer for every module in 'go list -m all'" [#29773]: https://golang.org/issue/29773 "cmd/go: 'go list -m' fails to follow dependencies through older versions of the main module" [#29935]: https://golang.org/issue/29935 "x/build: reconsider the large number of third-party dependencies" [#26955]: https://golang.org/issue/26955 "cmd/go: provide straightforward way to see non-test dependencies" [#30831]: https://golang.org/issue/30831 "cmd/go: 'get -u' stumbles over repos imported via non-canonical paths" [#31248]: https://golang.org/issue/31248 "cmd/go: mod tidy removes lines that build seems to need" [#32058]: https://golang.org/issue/32058 "cmd/go: replace directives are not thoroughly documented" [#32380]: https://golang.org/issue/32380 "cmd/go: don't add dependencies of external tests" [#32419]: https://golang.org/issue/32419 "proposal: cmd/go: conditional/optional dependency for go mod" [#33370]: https://golang.org/issue/33370 "cmd/go: treat pseudo-version 'vX.0.0-00010101000000-000000000000' as equivalent to an empty commit" [#33669]: https://golang.org/issue/33669 "cmd/go: fetching dependencies can be very aggressive when going via an HTTP proxy" [#34016]: https://golang.org/issue/34016 "cmd/go: 'go list -m all' hangs for git.apache.org" [#34417]: https://golang.org/issue/34417 "cmd/go: do not allow the main module to replace (to or from) itself" [#34822]: https://golang.org/issue/34822 "cmd/go: do not update 'go.mod' automatically if the changes are only cosmetic" [#36369]: https://golang.org/issue/36369 "cmd/go: dependencies in go.mod of older versions of modules in require cycles affect the current version's build"
proposal/design/36460-lazy-module-loading.md/0
{ "file_path": "proposal/design/36460-lazy-module-loading.md", "repo_id": "proposal", "token_count": 8232 }
648